fig-tree-evaluator 3.0.0-preview.2 → 3.0.0-preview.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.js CHANGED
@@ -1 +1 @@
1
- import{f as e,g as t,h as r,r as a,i as n,D as o,E as i,b as s,c as l,j as c,k as u,d,l as p,S as m,n as f,a as h,p as v,s as y,e as g,m as b,o as w,t as k,q as $,R as x,F as j,u as P,v as O,w as A,x as D,W as N,y as S,z as C,G as q,A as T}from"./chunks/shared.js";const E=[!1,null,0,""],z=e=>-1===E.indexOf(e),M=(e,t)=>"number"==typeof e&&"number"==typeof t?e<t?-1:e>t?1:0:L(String(e),String(t)),L=(e,t)=>{const r=Array.from(e),a=Array.from(t),n=Math.min(r.length,a.length);for(let e=0;e<n;e++){const t=r[e].codePointAt(0),n=a[e].codePointAt(0);if(t!==n)return t<n?-1:1}return r.length===a.length?0:r.length<a.length?-1:1},R="<array>",F="<object>",I=e=>null===e?"":"string"==typeof e?e:"number"==typeof e?String(e):"boolean"==typeof e?e?"true":"false":Array.isArray(e)?R:F,V=e=>e.trim(),Q=/\s+$/,J=/^\s+/,U=e=>e.replace(Q,""),B=e=>e.replace(J,""),G=e=>Array.from(e),W=(e,t)=>{const[r,a]=String(e).split("e"),n=void 0!==a?Number(a)+t:t;return Number(`${r}e${n}`)},K=Object.prototype.hasOwnProperty,H=(e,t)=>{for(const r of e.keys())if(_(r,t))return r},_=(e,t)=>{let r,a,n;if(e===t)return!0;if(e&&t&&(r=e.constructor)===t.constructor){if(r===Date)return e.getTime()===t.getTime();if(r===RegExp)return e.toString()===t.toString();if(r===Array){if((a=e.length)===t.length)for(;a--&&_(e[a],t[a]););return-1===a}if(r===Set){if(e.size!==t.size)return!1;for(a of e){if(n=a,n&&"object"==typeof n&&(n=H(t,n),!n))return!1;if(!t.has(n))return!1}return!0}if(r===Map){if(e.size!==t.size)return!1;for(a of e){if(n=a[0],n&&"object"==typeof n&&(n=H(t,n),!n))return!1;if(!_(a[1],t.get(n)))return!1}return!0}if(r===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(r===DataView){if((a=e.byteLength)===t.byteLength)for(;a--&&e.getInt8(a)===t.getInt8(a););return-1===a}if(ArrayBuffer.isView(e)){if((a=e.byteLength)===t.byteLength)for(;a--&&e[a]===t[a];);return-1===a}if(!r||"object"==typeof e){for(r in a=0,e){if(K.call(e,r)&&++a&&!K.call(t,r))return!1;if(!(r in t)||!_(e[r],t[r]))return!1}return Object.keys(t).length===a}}return e!=e&&t!=t},X="3.0.0-preview.2",Y={ok:!0},Z=e=>null===e?"null":Array.isArray(e)?"array":typeof e,ee=(e,t)=>({ok:!1,expected:e,actual:Z(t)}),te=(t,r)=>{switch(r){case"any":return!0;case"string":return"string"==typeof t;case"number":return"number"==typeof t;case"integer":return"number"==typeof t&&Number.isInteger(t);case"boolean":return"boolean"==typeof t;case"array":return Array.isArray(t);case"object":return e(t);case"null":return null===t;default:return!1}},re=e=>"null"===e||"any"===e||!!Array.isArray(e)&&(e.includes("null")||e.includes("any")),ae=/*#__PURE__*/new Set(["any","string","number","boolean","array","object","null","integer"]),ne=t=>{if("string"==typeof t)return ae.has(t);if(Array.isArray(t))return t.length>0&&t.every(e=>"string"==typeof e&&ae.has(e));if(e(t)&&"literal"in t){const e=t.literal;return Array.isArray(e)&&e.length>0&&e.every(e=>["string","number","boolean"].includes(typeof e))}return!1},oe=(e,r)=>{if(t(r)){if(-1!==r.literal.indexOf(e))return Y;const t=r.literal.map(e=>JSON.stringify(e)).join(", ");return ee(`one of ${t}`,e)}return"string"==typeof r?te(e,r)?Y:ee(r,e):r.some(t=>te(e,t))?Y:ee(r.join(" | "),e)},ie=(e,t)=>{if(void 0!==t.length){if(!Array.isArray(e))return ee("array",e);if(e.length!==t.length)return{ok:!1,expected:`array of length ${t.length}`,actual:`array of length ${e.length}`}}if(t.homogeneous){if(!Array.isArray(e))return ee("array",e);const r=t.homogeneous;if(e.length>0){if(void 0===r.find(t=>e.every(e=>te(e,t))))return{ok:!1,expected:`homogeneous array of ${r.join(" | ")}`,actual:se(e)}}}if(t.elementShape){if(!Array.isArray(e))return ee("array",e);for(let r=0;r<e.length;r++){const a=ue(e[r],t.elementShape);if(!a.ok)return a}}return Y},se=e=>{const t=Z(e[0]),r=e.find(e=>Z(e)!==t);return void 0===r?`array of ${t}`:`${Z(r)} beside ${t}`},le=["length","homogeneous","elementShape"],ce=t=>{if(!e(t))return ee("a constraints object",t);for(const e of Object.keys(t))if(!le.includes(e))return{ok:!1,expected:`one of ${le.join(", ")}`,actual:e};const{length:r,homogeneous:a,elementShape:n}=t;if(void 0!==r&&(!Number.isInteger(r)||r<0))return ee("a non-negative integer length",r);if(!(void 0===a||Array.isArray(a)&&ne(a)))return ee("a non-empty array of basic types",a);if(void 0!==n){if(!e(n))return ee("an object of declarations",n);for(const[t,r]of Object.entries(n)){if(!e(r))return ee(`a declaration for "${t}"`,r);if(void 0!==r.type&&!ne(r.type))return ee(`a vocabulary type for "${t}"`,r.type);if(void 0!==r.required&&"boolean"!=typeof r.required)return ee(`a boolean "required" for "${t}"`,r.required);if(void 0!==r.constraints){const e=ce(r.constraints);if(!e.ok)return e}}}return Y},ue=(t,r)=>{if(!e(t))return ee("object",t);const a=Object.keys(r);for(let e=0;e<a.length;e++){const n=a[e],o=r[n],i=Object.prototype.hasOwnProperty.call(t,n),s=!1!==o.required;if(i){if(void 0!==o.type){const e=oe(t[n],o.type);if(!e.ok)return e}if(void 0!==o.constraints){const e=ie(t[n],o.constraints);if(!e.ok)return e}}else if(s)return{ok:!1,expected:`property "${n}"`,actual:"missing"}}return Y},de=(e,t,r)=>{if(!r||!Array.isArray(e))return ie(e,t);const{length:a,...n}=t;if(void 0!==a){const t=ie(e,{length:a});if(!t.ok)return t}return ie(e.filter(e=>null!==e),n)},pe=["logic","comparison","math","string","array","data","io","other"],me=Symbol("fig-tree:EvaluationData"),fe=Symbol("fig-tree:validated-operator"),he=e=>"object"==typeof e&&null!==e&&!0===e[fe],ve=e=>!e.includes("{")&&!e.includes("}")&&(e.startsWith("$")?e.length>1:r(e).ok),ye=e=>{const t=[];let r="";const a=()=>{""!==r&&(t.push({kind:"text",text:r}),r="")};let n=0;for(;n<e.length;){const o=e[n];if("%"===o){let i=n+1;for(;i<e.length&&e[i]>="0"&&e[i]<="9";)i++;if(i>n+1){const r=e.slice(n,i);a(),t.push({kind:"positional",raw:r,index:Number(r.slice(1))}),n=i;continue}r+=o,n++;continue}if("{"===o&&"{"===e[n+1]){const o=e.indexOf("}}",n+2);if(-1!==o){const r=e.slice(n+2,o);if(ve(r)){a(),t.push({kind:"named",raw:e.slice(n,o+2),body:r}),n=o+2;continue}}r+="{{",n+=2;continue}r+=o,n++}return a(),t},ge=(e,t)=>{const r={registry:t,maxDepth:0};return{constant:be(r,e,0),depth:r.maxDepth}},be=(e,t,r)=>{if(r>o)return!1;if(r>e.maxDepth&&(e.maxDepth=r),void 0===t)return!1;if("string"==typeof t){const e=a(t).kind;return"plain"===e||"unrecognized"===e}if(Array.isArray(t)){for(let a=0;a<t.length;a++)if(!be(e,t[a],r+1))return!1;return!0}if(n(t)){for(const r in t){if("operator"===r||"fragment"===r||"vars"===r||"//"===r)return!1;if(r.startsWith("$")&&we(e.registry,r.slice(1)))return!1}for(const a in t)if(!be(e,t[a],r+1))return!1;return!0}return!0},we=(e,t)=>"literal"===t||void 0!==mr(e,t)||e.fragments.has(t),ke=(e,t)=>({parent:e,key:t}),$e=e=>{const t=[];for(let r=e;null!==r;r=r.parent)t.push(r.key);return t.reverse()},xe=e=>{e.sort((e,t)=>e.order-t.order)},je=e=>e.some(({issue:e})=>"error"===e.severity),Pe=e=>{const t=e.entry.definition.parameters.as;if("structural"!==t?.evaluation)return null;const r=e.params.as;return"constant"===r?.kind&&"string"==typeof r.value?r.value:null},Oe=(e,t,r)=>void 0===r?null===e:("element"===t?e:`${e??""}Index`)===r,Ae=(e,t,r)=>{const a=new Set;let n=e;return t.forEach((e,t)=>{n=De(n,e.at,r[t],a)}),n},De=(e,t,r,a)=>{const n=Ne(e,a),[o,...i]=t;return n[o]=0===i.length?r:De(n[o],i,r,a),n},Ne=(e,t)=>{if(t.has(e))return e;const r=Array.isArray(e)?[...e]:{...e};return t.add(r),r},Se=/*#__PURE__*/new Set(["data","vars","params","element","index","d","v","p","e","i"]),Ce=(e,t,r={})=>{const a={registry:t,recognizes:e=>we(t,e),issues:[],order:0,nodeCount:0,maxDepth:0,dataPaths:new Map,dynamic:!1,operators:new Set,fragmentNames:new Set,fragmentCalls:[],dataReads:[],identityOnly:!1,renamedBindings:[],asNames:new Set,unrecognized:[]},n=(r.basePath??[]).reduce(ke,null),o=ze(a,e,n,0);Te(a);const i=kt(a,o);xe(a.issues);const s=je(a.issues),l={nodeCount:a.nodeCount,maxDepth:a.maxDepth,dependencies:{dataPaths:a.dataPaths,dynamic:a.dynamic,operators:[...a.operators],fragments:[...a.fragmentNames]},identityOnly:a.identityOnly};return{root:o,holes:i,issues:a.issues,hasErrors:s,timeoutShielded:i.every(e=>void 0!==e.timeoutFallback),own:l,...qe(l,a.fragmentCalls,t.fragments),fragmentCalls:a.fragmentCalls,dataReads:a.dataReads}},qe=(e,t,r)=>{if(0===t.length)return e;const a=new Map(e.dependencies.dataPaths),n=new Set(e.dependencies.operators),o=new Set(e.dependencies.fragments);let{nodeCount:i,maxDepth:s,identityOnly:l}=e,c=e.dependencies.dynamic;for(const e of t){const t=r.get(e.name);if(void 0!==t){i+=t.nodeCount,s=Math.max(s,e.depth+t.maxDepth),l||=t.identityOnly,c||=t.dependencies.dynamic;for(const[e,r]of t.dependencies.dataPaths)a.set(e,r);for(const e of t.dependencies.operators)n.add(e);for(const e of t.dependencies.fragments)o.add(e)}}return{nodeCount:i,maxDepth:s,identityOnly:l,dependencies:{dataPaths:a,dynamic:c,operators:[...n],fragments:[...o]}}},Te=e=>{if(0!==e.asNames.size)for(const{token:t,issue:r,raw:a}of e.unrecognized)e.asNames.has(t)&&(r.issue={...r.issue,severity:"error",code:i.unresolvedBinding,message:`'${a}' names an iterator binding, but no enclosing iterator binds it here`})},Ee=(e,t,r,a,n,o,i={})=>{const s={severity:t,code:r,message:a,path:$e(n)};void 0!==i.operator&&(s.operator=i.operator),void 0!==i.parameter&&(s.parameter=i.parameter),void 0!==i.suggestion&&(s.suggestion=i.suggestion);const l={issue:s,order:o};return e.issues.push(l),l},ze=(e,t,r,a)=>{const n=e.order++;if(a>e.maxDepth&&(e.maxDepth=a),a>o)return Ee(e,"error",i.depthCeiling,`the expression nests deeper than the engine's ceiling of ${o} levels — descent stopped here`,r,n),e.nodeCount++,Re(t,r,n);const s=Me(e,t,r,a,n);return"operator"!==s.kind&&"fragmentCall"!==s.kind&&"reference"!==s.kind&&"invalid"!==s.kind||e.nodeCount++,s},Me=(e,t,r,a,o)=>null==t?Le(t??null,r,o):"number"==typeof t||"boolean"==typeof t?Le(t,r,o):"string"==typeof t?Fe(e,t,r,o):Array.isArray(t)?Ve(e,t,r,a,o):n(t)?Qe(e,t,r,a,o):(e.identityOnly=!0,Le(t,r,o)),Le=(e,t,r)=>({kind:"constant",value:e,path:t,order:r}),Re=(e,t,r)=>({kind:"invalid",raw:e,path:t,order:r}),Fe=(e,t,r,n)=>{const o=a(t);switch(o.kind){case"plain":return Le(t,r,n);case"unrecognized":{const a=Ie(e,t,r,n);if(null!==a)return a;const o=Ee(e,"warning",i.unrecognizedIdentifier,`'${t}' matches no reference namespace and will pass through as data`,r,n),l=s(t);return null!==l&&e.unrecognized.push({token:l.token,issue:o,raw:t}),Le(t,r,n)}case"invalid":return Ee(e,"error",o.code??i.invalidReference,`'${t}': ${o.reason}`,r,n),Re(t,r,n);case"reference":{const{namespace:a,segments:i,drill:s}=o;return"data"===a&&(0===i.length?e.dynamic=!0:Xe(e,i,s.startsWith(".")?s.slice(1):void 0,r)),{kind:"reference",namespace:a,segments:i,raw:t,path:r,order:n}}}},Ie=(e,t,r,a)=>{const n=s(t);if(null===n)return null;const{token:o,rest:l}=n;for(let n=e.renamedBindings.length-1;n>=0;n--){const s=e.renamedBindings[n];if(o===s.element)try{return{kind:"reference",namespace:"element",segments:p(l),raw:t,binding:o,path:r,order:a}}catch(n){return Ee(e,"error",i.invalidReference,`'${t}': ${n.message}`,r,a),Re(t,r,a)}if(o===s.index)return""!==l?(Ee(e,"error",i.invalidReference,`'${t}': the index binding is bare-only — it cannot be drilled`,r,a),Re(t,r,a)):{kind:"reference",namespace:"index",segments:[],raw:t,binding:o,path:r,order:a}}return null},Ve=(e,t,r,a,n)=>{const o=t.map((t,n)=>({key:n,rawChild:void 0===t?null:t,node:ze(e,void 0===t?null:t,ke(r,n),a+1)})),i=t.some(e=>void 0===e);return wt(e,t,o,!0,i,void 0,r,n)},Qe=(e,t,r,a,n)=>{const o=l(t,e.recognizes);switch(o.kind){case"malformed":return Ee(e,"error",i.malformedNode,o.message,r,n),Re(t,r,n);case"operator":return Je(e,t,r,a,n);case"fragment":return mt(e,t,r,a,n);case"shorthand":return it(e,t,o.key,r,a,n);case"plain":return gt(e,t,r,a,n)}},Je=(e,t,r,a,n)=>{const o=t.operator;if("string"!=typeof o)return Ee(e,"error",i.malformedNode,"the 'operator' value must be a literal string",r,n),Re(t,r,n);if("literal"===o)return pt(e,t,t.value,"value"in t,r,n);const s=mr(e.registry,o);if(void 0===s){const a=f(o,jt(e));return Ee(e,"error",i.unknownOperator,`'${o}' names no registered operator${a?` — did you mean '${a}'?`:""}`,r,n,{suggestion:a}),Re(t,r,n)}const l=Ue(e,s,r,n),c=[];for(const o in t){const s=t[o];"operator"!==o&&"//"!==o&&void 0!==s&&(Be(e,l,o,s,r,a,n)||("parameters"!==o?Ge(e,l,c,o,s,ke(r,o),n):Ee(e,"error",i.malformedNode,"'parameters' is reserved and unused on operator nodes",ke(r,o),n,{operator:l.name})))}return We(e,l,c,a,n),l},Ue=(e,t,r,a)=>(e.operators.add(t.definition.name),{kind:"operator",name:t.definition.name,entry:t,params:{},path:r,order:a}),Be=(e,t,r,a,n,o,s)=>"fallback"===r?(t.fallback=ze(e,a,ke(n,"fallback"),o+1),!0):"useCache"===r?("boolean"==typeof a?t.useCache=a:Ee(e,"error",i.malformedNode,"'useCache' must be a literal boolean — the cache lookup happens before evaluation",ke(n,"useCache"),s,{operator:t.name}),!0):"vars"===r&&(t.vars=yt(e,a,n,o,s),!0),Ge=(e,t,r,a,n,o,s)=>{if(void 0===t.entry.definition.parameters[a]){const r=f(a,Object.keys(t.entry.definition.parameters));return void Ee(e,"error",i.unknownNodeKey,`'${a}' is not a parameter of '${t.name}'${r?` — did you mean '${r}'?`:""}`,o,s,{operator:t.name,parameter:a,suggestion:r})}r.push({name:a,kind:"value",value:n,path:o})},We=(e,t,r,a,n)=>{const o=t.entry.definition,i=o.resolution.perElement.length>0;let s;if(i){const a=r.find(e=>"as"===e.name&&"structural"===o.parameters.as?.evaluation&&"value"===e.kind);void 0!==a&&"value"===a.kind&&(s=ot(e,t,a.value,a.path,n))}for(const n of r){const r=o.parameters[n.name]?.evaluation;"perElement"!==r&&(t.params[n.name]=Ze(e,n,r,a))}if(i){void 0!==s&&e.renamedBindings.push(s);for(const n of r){const r=o.parameters[n.name]?.evaluation;"perElement"===r&&(t.params[n.name]=Ze(e,n,r,a))}void 0!==s&&e.renamedBindings.pop()}Ye(e,t),Ke(e,t)},Ke=(e,t)=>{if("buildString"!==t.name)return;const r=t.params.template;if("constant"!==r?.kind||"string"!=typeof r.value)return;const a=ye(r.value).filter(e=>"text"!==e.kind);if(0===a.length)return;const o=t.params.substitutions,i=(e=>{if(void 0===e)return{mode:"absent"};if("constant"===e.kind)return Array.isArray(e.value)?{mode:"array",length:e.value.length}:n(e.value)?{mode:"object",keys:new Set(Object.keys(e.value))}:{mode:"dynamic"};if("skeleton"===e.kind){const{skeleton:t,holes:r}=e;if(Array.isArray(t))return{mode:"array",length:t.length};if(n(t)){const e=new Set(Object.keys(t));for(const t of r)e.add(String(t.at[0]));return{mode:"object",keys:e}}}return{mode:"dynamic"}})(o);if(_e(e,t,r,a,i),"absent"!==i.mode&&"object"!==i.mode)return;const s=[],l=new Set;for(const t of a){if("named"!==t.kind||!t.body.startsWith("$"))continue;if(l.has(t.body))continue;const a=Fe(e,t.body,r.path,e.order++);"reference"===a.kind&&(e.nodeCount++,l.add(t.body),s.push({path:r.path,at:[t.body],node:a}))}0!==s.length&&(t.params.substitutions=He(e,t,o,s))},He=(e,t,r,a)=>{const n="skeleton"===r?.kind?{...r,skeleton:{...r.skeleton},holes:[...r.holes]}:{kind:"skeleton",skeleton:"constant"===r?.kind?{...r.value}:{},holes:[],path:r?.path??ke(t.path,"substitutions"),order:r?.order??e.order++};return n.holes.push(...a),n},_e=(e,t,r,a,n)=>{const o=(a,n,o="warning")=>Ee(e,o,a,n,r.path,r.order,{operator:t.name});if("array"!==n.mode&&"dynamic"!==n.mode||a.some(e=>"named"===e.kind&&e.body.startsWith("$"))&&o(i.inertReferenceToken,`a reference token needs the named face — beside ${"array"===n.mode?"positional substitutions":"a dynamically supplied map"} it is not recognized and renders as its own text`),"array"===n.mode){const e=new Set;let t=!1;for(const r of a)"positional"===r.kind&&(r.index>=1&&r.index<=n.length?e.add(r.index):(t=!0,o(i.unboundToken,`'${r.raw}' binds to nothing and renders as its own text`)));const r=[];for(let t=1;t<=n.length;t++)e.has(t)||r.push(t);for(const e of r)o(i.unusedSubstitution,`substitution ${e} is never named by the template`);return void(r.length>0&&t&&o(i.tokenRenumber,`the tokens skip a number — renumber them to ${[...Array(n.length).keys()].map(e=>`%${e+1}`).join(", ")}`,"hint"))}if("object"===n.mode){const e=new Set;for(const t of a)"named"===t.kind&&(n.keys.has(t.body)?e.add(t.body):t.body.startsWith("$")||o(i.unboundToken,`'${t.raw}' binds to nothing and renders as its own text`));for(const t of n.keys)e.has(t)||o(i.unusedSubstitution,`substitution '${t}' is never named by the template`)}},Xe=(e,t,r,a)=>{let n,o;void 0!==r&&c(r)?(n=r,o=t):(o=u(t),n=d(o)),e.dataPaths.set(n,o),e.dataReads.push({kind:"path",key:n,segments:o,path:a})},Ye=(e,t)=>{if("get"!==t.name||void 0!==t.params.from)return;const r=t.params.path;if(void 0!==r)if("constant"===r.kind)try{const a="string"==typeof r.value?g(r.value):r.value;if(!Array.isArray(a)||!a.every(b))return void(e.dynamic=!0);if(0===a.length)return void(e.dynamic=!0);Xe(e,a,"string"==typeof r.value?r.value:void 0,t.path)}catch{e.dynamic=!0}else e.dynamic=!0},Ze=(e,t,r,a)=>{if("lazyElements"===r||"race"===r){const r=at(e,t,a);if(null!==r)return r}if("lazyEntries"===r){const r=nt(e,t,a);if(null!==r)return r}return"value"===t.kind?ze(e,t.value,t.path,a+1):et(e,t,a)},et=(e,t,r)=>{const{order:a,containerDepth:n}=tt(e,r),o=rt(e,t.elements,t.basePath,t.offset,n),i=t.elements.some(e=>void 0===e);return wt(e,t.elements,o,!0,i,void 0,t.basePath,a)},tt=(e,t)=>{const r=e.order++,a=t+1;return a>e.maxDepth&&(e.maxDepth=a),{order:r,containerDepth:a}},rt=(e,t,r,a,n)=>t.map((t,o)=>({key:o,rawChild:void 0===t?null:t,node:ze(e,void 0===t?null:t,ke(r,a+o),n+1)})),at=(e,t,r)=>{const a="slice"===t.kind?t.elements:t.value;if(!Array.isArray(a))return null;const n="slice"===t.kind?t.basePath:t.path,o="slice"===t.kind?t.offset:0,{order:i,containerDepth:s}=tt(e,r),l=rt(e,a,n,o,s);if(l.every(e=>"constant"===e.node.kind)){const t=a.some(e=>void 0===e);return wt(e,a,l,!0,t,void 0,n,i)}return{kind:"elements",nodes:l.map(e=>e.node),path:n,order:i}},nt=(e,t,r)=>{if("value"!==t.kind)return null;const a=t.value;if(!n(a)||h(a,e.recognizes))return null;const{order:o,containerDepth:i}=tt(e,r),{entries:s,vars:l,changed:c}=bt(e,a,t.path,i,o);if(s.every(e=>"constant"===e.node.kind))return wt(e,a,s,!1,c,l,t.path,o);const u={};for(const{key:e,node:t}of s)u[String(e)]=t;const d={kind:"entries",entries:u,path:t.path,order:o};return void 0!==l&&(d.vars=l),d},ot=(e,t,n,o,s)=>{const l=r=>{Ee(e,"error",i.invalidAs,r,o,s,{operator:t.name})};if("string"!=typeof n||"plain"!==a(n).kind)return l("'as' must be a literal name — a dynamic value cannot be statically resolved");const c=r(n);if(!c.ok)return l(`'${n}' is not a legal binding name — ${c.reason}`);const u=[n,`${n}Index`];for(const t of u){if(Se.has(t))return l(`'${n}' collides with the reserved namespace word '${t}'`);for(const r of e.renamedBindings)if(t===r.element||t===r.index)return l(`'${n}' collides with an enclosing 'as' binding ('${t}')`)}for(const t of u)e.asNames.add(t);return{element:n,index:`${n}Index`}},it=(e,t,r,a,n,o)=>{const s=r.slice(1),l="literal"===s,c=!l&&e.registry.fragments.has(s);for(const n in t){if(n===r)continue;if(!(m.has(n)&&!(c&&"useCache"===n)))return Ee(e,"error",i.malformedNode,`'${n}' may not sit beside the shorthand key '${r}' — reserved modifiers only`,ke(a,n),o),Re(t,a,o)}const u=t[r],d=ke(a,r);if(l){for(const r of["fallback","vars","useCache"])r in t&&Ee(e,"warning",i.uselessModifier,`'${r}' on 'literal' is dead — contents are never evaluated`,ke(a,r),o);return pt(e,t,u,!0,a,o)}if(c)return ft(e,t,s,u,a,n,o);const p=mr(e.registry,s),f=Ue(e,p,a,o);for(const i in t){const s=t[i];i!==r&&"//"!==i&&void 0!==s&&Be(e,f,i,s,a,n,o)}const h=[];return st(e,f,h,u,d,o),We(e,f,h,n,o),f},st=(e,t,r,a,o,i)=>{if(Array.isArray(a))ct(e,t,r,a,o,i);else if(!n(a)||h(a,e.recognizes))lt(e,t,r,a,o,i);else for(const n in a){const s=a[n];"//"!==n&&void 0!==s&&Ge(e,t,r,n,s,ke(o,n),i)}},lt=(e,t,r,a,n,o)=>{const i=y(t.entry.definition);null!==i?r.push({name:i,kind:"value",value:a,path:n}):ut(e,t,n,o)},ct=(e,t,r,a,n,o)=>{const i=t.entry.definition,s=v(i,a.length);if(null===s)return void dt(e,t,a,n,o);const l=i.positionalParams;for(let e=0;e<s.bound;e++)r.push({name:l[e],kind:"value",value:a[e],path:ke(n,e)});const{restAt:c}=s;null!==c&&r.push({name:i.restParam,kind:"slice",elements:0===c?a:a.slice(c),basePath:n,offset:c})},ut=(e,t,r,a)=>Ee(e,"error",i.positionalArity,`'${t.name}' takes no positional arguments — use the named form`,r,a,{operator:t.name}),dt=(e,t,r,a,n)=>{const o=t.entry.definition.positionalParams;if(void 0===o)return void ut(e,t,a,n);const s=o.length;Ee(e,"error",i.positionalArity,`'${t.name}' takes at most ${s} positional argument${1===s?"":"s"} (${o.join(", ")}), got ${r.length}`,a,n,{operator:t.name})},pt=(e,t,r,a,n,o)=>{if("operator"in t){for(const r in t)"operator"!==r&&"value"!==r&&"//"!==r&&("fallback"!==r&&"vars"!==r&&"useCache"!==r?Ee(e,"error",i.unknownNodeKey,`'${r}' is not a key of 'literal' — content goes in 'value'`,ke(n,r),o,{operator:"literal"}):Ee(e,"warning",i.uselessModifier,`'${r}' on 'literal' is dead — contents are never evaluated`,ke(n,r),o));if(!a)return Ee(e,"error",i.malformedNode,"'literal' requires its content in 'value'",n,o,{operator:"literal"}),Re(t,n,o)}return Le(r,n,o)},mt=(e,t,r,a,n)=>{const o=t.fragment;if("string"!=typeof o)return Ee(e,"error",i.malformedNode,"the 'fragment' value must be a literal string",r,n),Re(t,r,n);const s={kind:"fragmentCall",name:o,argumentsMode:"static",path:r,order:n};ht(e,s,a);for(const o in t){const l=t[o];"fragment"!==o&&"//"!==o&&void 0!==l&&("parameters"!==o?"fallback"!==o?"vars"!==o?"useCache"!==o?Ee(e,"error",i.unknownNodeKey,`'${o}' is not a key of a fragment call — arguments live only in 'parameters'`,ke(r,o),n):Ee(e,"error",i.malformedNode,"'useCache' is not available on fragment calls — caching stays operator-level",ke(r,"useCache"),n):s.vars=yt(e,l,r,a,n):s.fallback=ze(e,l,ke(r,"fallback"),a+1):vt(e,s,l,ke(r,"parameters"),a,n))}return s},ft=(e,t,r,a,o,s,l)=>{const c={kind:"fragmentCall",name:r,argumentsMode:"static",path:o,order:l};ht(e,c,s);for(const a in t){const n=t[a];a!==`$${r}`&&"//"!==a&&void 0!==n&&("fallback"===a&&(c.fallback=ze(e,n,ke(o,"fallback"),s+1)),"vars"===a&&(c.vars=yt(e,n,o,s,l)))}return n(a)?vt(e,c,a,ke(o,`$${r}`),s,l):Ee(e,"error",i.malformedNode,`fragments have no single-value or positional form — '$${r}' takes a named-arguments object`,ke(o,`$${r}`),l),c},ht=(e,t,r)=>{const{name:a,path:n,order:o}=t;e.fragmentNames.add(a);const s=e.registry.fragments.get(a);if(void 0===s){const t=f(a,e.registry.fragments.keys());return void Ee(e,"error",i.unknownFragment,`'${a}' names no registered fragment${t?` — did you mean '${t}'?`:""}`,n,o,{suggestion:t})}t.entry=s,e.fragmentCalls.push({name:a,depth:r}),e.dataReads.push({kind:"call",fragment:s,path:n})},vt=(e,t,r,o,s,l)=>{if(void 0!==r){if(h(r,e.recognizes)||"string"==typeof r&&"reference"===a(r).kind)return t.argumentsMode="dynamic",t.parameters=ze(e,r,o,s+1),void(e.dynamic=!0);if(n(r)){const a={};for(const t in r){const n=r[t];"//"!==t&&void 0!==n&&(a[t]=ze(e,n,ke(o,t),s+1))}return void(t.parameters=a)}Ee(e,"error",i.malformedNode,"a fragment's 'parameters' must be a named-arguments object or a node computing one",o,l)}},yt=(e,t,a,o,s)=>{const l=ke(a,"vars");if(!n(t))return void Ee(e,"error",i.invalidVars,"a 'vars' block must be an object of name → expression entries",l,s);const c={};for(const a in t){const n=t[a];if("//"===a||void 0===n)continue;const u=ke(l,a),d=r(a);d.ok?c[a]=ze(e,n,u,o+1):Ee(e,"error",i.invalidName,`'${a}' is not a legal var name — ${d.reason}`,u,s)}return c},gt=(e,t,r,a,n)=>{const{entries:o,vars:i,changed:s}=bt(e,t,r,a,n);return wt(e,t,o,!1,s,i,r,n)},bt=(e,t,r,a,n)=>{let o,s=!1;const l=[];for(const c in t){const u=t[c];if("//"!==c)if("vars"!==c)if(void 0!==u){if(c.startsWith("$")){const t=f(c.slice(1),jt(e));Ee(e,"warning",i.unrecognizedIdentifier,`'${c}' is not a registered operator or fragment and will pass through as data${t?` — did you mean '$${t}'?`:""}`,ke(r,c),n,{suggestion:void 0===t?void 0:`$${t}`})}l.push({key:c,rawChild:u,node:ze(e,u,ke(r,c),a+1)})}else s=!0;else o=yt(e,u,r,a,n),s=!0;else s=!0}return{entries:l,vars:o,changed:s}},wt=(e,t,r,a,n,o,s,l)=>{const c=[],u=a?new Array(r.length):{};let d=n;for(const{key:e,rawChild:t,node:a}of r)"constant"!==a.kind?(d=!0,"skeleton"!==a.kind||void 0!==a.vars?c.push({path:a.path,at:[e],node:a}):(u[e]=a.skeleton,c.push(...a.holes.map(t=>({...t,at:[e,...t.at]}))))):(u[e]=a.value,a.value!==t&&(d=!0));if(0===c.length)return void 0!==o&&Object.keys(o).length>0&&Ee(e,"warning",i.unreferencedVar,"this vars block declares names nothing in its scope references",ke(s,"vars"),l),Le(d||void 0!==o?u:t,s,l);const p={kind:"skeleton",skeleton:u,holes:c,path:s,order:l};return void 0!==o&&(p.vars=o),p},kt=(e,t)=>"constant"===t.kind?[]:"skeleton"===t.kind?t.holes.map(t=>({path:$e(t.path),node:t.node,...$t(e,t.node)})):[{path:$e(t.path),node:t,...$t(e,t)}],$t=(e,t)=>{const r=xt(e,t);return void 0===r?{}:{timeoutFallback:r}},xt=(e,t)=>{if("operator"===t.kind||"fragmentCall"===t.kind){if(void 0!==t.fallback)return"constant"===t.fallback.kind?{value:t.fallback.value}:void 0;if("operator"===t.kind){const r=t.entry.instanceDefaults;return void 0!==r&&"fallback"in r&&ge(r.fallback,e.registry).constant?{value:r.fallback}:void 0}return t.entry?.timeoutFallback}},jt=e=>[...e.registry.operators.keys(),...e.registry.aliases.keys(),...e.registry.fragments.keys()],Pt=e=>{switch(e.kind){case"operator":return e.entry.definition.returns;case"fragmentCall":return e.entry?.returns??"any";case"skeleton":return Array.isArray(e.skeleton)?"array":"object";case"constant":return Ot(e.value);default:return"any"}},Ot=t=>{if(null===t)return"null";if(Array.isArray(t))return"array";if(e(t))return"object";switch(typeof t){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"any"}},At=/*#__PURE__*/Object.freeze({parsePath:g,resolvePath:w,checkType:oe,checkConstraints:ie,describeType:Z,renderText:I,isTruthy:z}),Dt=(e,t={})=>{St({artifact:e,context:t,varsFrames:[],iteratorFrames:[]},e.root),xe(e.issues),e.hasErrors=je(e.issues)},Nt=(e,t,r,a,n,o,i={})=>{const s={severity:t,code:r,message:a,path:$e(n)};void 0!==i.operator&&(s.operator=i.operator),void 0!==i.fragment&&(s.fragment=i.fragment),void 0!==i.parameter&&(s.parameter=i.parameter),void 0!==i.suggestion&&(s.suggestion=i.suggestion),e.artifact.issues.push({issue:s,order:o})},St=(e,t)=>{switch(t.kind){case"constant":case"invalid":return;case"reference":return void Rt(e,t);case"skeleton":{const r=Qt(e,t.vars,t.path);for(const r of t.holes)St(e,r.node);return void Jt(e,r)}case"fragmentCall":return void Mt(e,t);case"elements":for(const r of t.nodes)St(e,r);return;case"entries":{const r=Qt(e,t.vars,t.path);for(const r in t.entries)St(e,t.entries[r]);return void Jt(e,r)}case"operator":return void qt(e,t)}return t},Ct=e=>"kind"in e&&"string"==typeof e.kind,qt=(e,t)=>{const r=Qt(e,t.vars,t.path);void 0!==t.fallback&&St(e,t.fallback);const a=t.entry.definition,n=zt(t);for(const[r,o]of a.resolution.entries){const a=t.params[r];void 0!==a?"constant"===a.kind&&null===a.value&&Tt(t,r)||Et(e,n,r,o,a):o.required&&Nt(e,"error",i.missingRequired,`'${t.name}' requires '${r}'`,t.path,t.order,{operator:t.name,parameter:r})}Lt(e,t);const o=[];for(const r in t.params){const n=t.params[r];"perElement"===a.parameters[r]?.evaluation?o.push([r,n]):St(e,n)}if(o.length>0){const r={as:Pe(t),referenced:!1};e.iteratorFrames.push(r);for(const[,t]of o)St(e,t);e.iteratorFrames.pop(),r.referenced||Nt(e,"warning",i.deadBinding,`'${t.name}' binds ${null===r.as?"$element / $index":`$${r.as}`} but its 'each' references neither`,t.path,t.order,{operator:t.name})}Jt(e,r)},Tt=(e,t)=>{const{definition:r,instanceDefaults:a}=e.entry;for(const[n,o]of r.resolution.entries){if(!o.replacesNullAt?.includes(t))continue;const r=e.params[n];if(void 0===r){if(void 0!==a&&Object.hasOwn(a,n)&&null!==a[n])return!0}else if("constant"!==r.kind||null!==r.value)return!0}return!1},Et=(e,t,r,a,n)=>{if("constant"===n.kind){if(null===n.value&&!a.required&&!re(a.type))return;const o=oe(n.value,a.type);if(!o.ok)return void Nt(e,"error",i.typeCheck,`'${t.label}.${r}': expected ${o.expected}, received ${o.actual}`,n.path,n.order,{...t.extra,parameter:r});if(void 0!==a.constraints){const o=de(n.value,a.constraints,void 0!==a.elementNullPolicy);o.ok||Nt(e,"error",i.typeCheck,`'${t.label}.${r}': expected ${o.expected}, received ${o.actual}`,n.path,n.order,{...t.extra,parameter:r})}return}if("elements"===n.kind){const o=a.constraints?.length;return void(void 0!==o&&n.nodes.length!==o&&Nt(e,"error",i.typeCheck,`'${t.label}.${r}': expected ${o} element${1===o?"":"s"}, received ${n.nodes.length}`,n.path,n.order,{...t.extra,parameter:r}))}if("structural"!==a.evaluation||"as"===r){if("operator"===n.kind||"fragmentCall"===n.kind&&void 0!==n.entry){const o=Pt(n);if(!k(o,a.type)){const a="operator"===n.kind?`'${n.name}'`:`fragment '${n.name}'`;Nt(e,"error",i.returnsMismatch,`${a} returns ${JSON.stringify(o)} — it can never satisfy '${t.label}.${r}'`,n.path,n.order,{...t.extra,parameter:r})}return}if("skeleton"===n.kind){const o=oe(Array.isArray(n.skeleton)?[]:{},a.type);o.ok||Nt(e,"error",i.typeCheck,`'${t.label}.${r}': expected ${o.expected}, received ${o.actual}`,n.path,n.order,{...t.extra,parameter:r})}}else Nt(e,"error",i.typeCheck,`'${t.label}.${r}' is structural — it requires a literal value`,n.path,n.order,{...t.extra,parameter:r})},zt=e=>({label:e.name,extra:{operator:e.name}}),Mt=(e,t)=>{const r=Qt(e,t.vars,t.path);void 0!==t.fallback&&St(e,t.fallback);const a=t.entry?.parameters,n=void 0===t.parameters||Ct(t.parameters)?void 0:t.parameters;if(void 0!==a&&"static"===t.argumentsMode){const r={label:t.name,extra:{fragment:t.name}};for(const o in a){const s=a[o],l=n?.[o];void 0!==l?Et(e,r,o,s,l):s.required&&Nt(e,"error",i.missingRequired,`fragment '${t.name}' – requires '${o}'`,t.path,t.order,{fragment:t.name,parameter:o})}if(void 0!==n)for(const r in n){const o=n[r];if(void 0===a[r]){const n=f(r,Object.keys(a));Nt(e,"error",i.unknownNodeKey,`fragment '${t.name}' declares no parameter '${r}'${n?` — did you mean '${n}'?`:""}`,o.path,o.order,{parameter:r,suggestion:n})}}}if(void 0!==t.parameters)if(Ct(t.parameters))St(e,t.parameters);else for(const r in t.parameters)St(e,t.parameters[r]);Jt(e,r)},Lt=(e,t)=>{const r=t.entry.definition.validate;if(void 0===r)return;const a={};for(const e in t.params){const r=t.params[e];"constant"===r.kind&&(a[e]=r.value)}let n;try{n=r(a,At)}catch(r){return void Nt(e,"error",i.operatorValidate,`'${t.name}' validate hook threw: ${r.message}`,t.path,t.order,{operator:t.name})}for(const r of n){const a=void 0!==r.parameter?t.params[r.parameter]:void 0;Nt(e,r.severity,i.operatorValidate,r.message,a?.path??t.path,t.order,{operator:t.name,...void 0!==r.parameter?{parameter:r.parameter}:{}})}},Rt=(e,t)=>{switch(t.namespace){case"data":return;case"vars":return void Ft(e,t);case"params":return void It(e,t);case"element":case"index":return void Vt(e,t,t.namespace)}},Ft=(e,t)=>{const r=t.segments[0],a="string"==typeof r?r:void 0;if(void 0!==a)for(let t=e.varsFrames.length-1;t>=0;t--){const r=e.varsFrames[t],n=r.names.get(a);if(void 0!==n){if(n.referenced=!0,null!==r.currentVar){const e=r.edges.get(r.currentVar)??new Set;e.add(a),r.edges.set(r.currentVar,e)}return}}Nt(e,"error",i.unresolvedVar,`'${t.raw}': no var '${a??""}' is declared in scope`,t.path,t.order)},It=(e,t)=>{const r=e.context.fragmentParams;if(void 0===r)return void Nt(e,"error",i.unresolvedParam,`'${t.raw}': $params is only available inside a fragment body`,t.path,t.order);if(0===t.segments.length)return;const a=t.segments[0];"string"==typeof a&&r.has(a)||Nt(e,"error",i.unresolvedParam,`'${t.raw}': the fragment declares no parameter '${String(a)}'`,t.path,t.order)},Vt=(e,t,r)=>{for(let a=e.iteratorFrames.length-1;a>=0;a--){const n=e.iteratorFrames[a];if(Oe(n.as,r,t.binding))return void(n.referenced=!0)}Nt(e,"error",i.unresolvedBinding,`'${t.raw}' resolves against no enclosing iterator here`,t.path,t.order)},Qt=(e,t,r)=>{if(void 0===t)return null;const a={names:new Map,currentVar:null,edges:new Map},n=ke(r,"vars");for(const r in t){const o=t[r],s=ke(n,r);for(const t of e.varsFrames)if(t.names.has(r)){Nt(e,"warning",i.shadowedVar,`'${r}' shadows a var of the same name from an enclosing scope`,s,o.order);break}a.names.set(r,{node:o,declaredAt:s,order:o.order,referenced:!1})}e.varsFrames.push(a);for(const[t,r]of a.names)a.currentVar=t,St(e,r.node),a.currentVar=null;return a},Jt=(e,t)=>{if(null!==t){e.varsFrames.pop();for(const[r,a]of t.names)a.referenced||Nt(e,"warning",i.unreferencedVar,`'${r}' is declared but never referenced in its scope`,a.declaredAt,a.order);Ut(e,t)}},Ut=(e,t)=>{const r=new Set,a=new Set,n=new Set,o=e=>{if(a.has(e))return!1;if(r.has(e))return!0;r.add(e);for(const n of t.edges.get(e)??[])if(o(n))return r.delete(e),a.add(e),!0;return r.delete(e),a.add(e),!1};for(const r of t.names.keys())if(!a.has(r)&&!n.has(r)&&o(r)){const a=t.names.get(r);Nt(e,"error",i.varCycle,`'${r}' participates in a vars cycle — a var may not depend on itself`,a.declaredAt,a.order),n.add(r)}};class Bt{max;entries=new Map;constructor(e){this.max=e,Gt(e)}get size(){return this.entries.size}get(e){if(!this.entries.has(e))return;const t=this.entries.get(e);return this.entries.delete(e),this.entries.set(e,t),t}set(e,t){this.entries.delete(e),this.entries.set(e,t),this.entries.size>this.max&&this.evictOldest()}delete(e){this.entries.delete(e)}clear(){this.entries.clear()}resize(e){for(Gt(e),this.max=e;this.entries.size>this.max;)this.evictOldest()}evictOldest(){const e=this.entries.keys().next();!0!==e.done&&this.entries.delete(e.value)}}const Gt=e=>{if(!Number.isInteger(e)||e<1)throw new RangeError("LRU bound must be a positive integer")},Wt="~",Kt=(e,t)=>{if(t>o)return"refused";switch(typeof e){case"boolean":return"json";case"string":return e.length>4096?"serializer":"json";case"number":return Number.isFinite(e)&&!Object.is(e,-0)?"json":"serializer";case"undefined":return"serializer";case"object":break;default:return"refused"}if(null===e)return"json";if(Array.isArray(e)){for(let r=0;r<e.length;r++){const a=Kt(e[r],t+1);if("json"!==a)return a}return"json"}if(!n(e))return"refused";for(const r in e){if(r.length>4096)return"serializer";const a=Kt(e[r],t+1);if("json"!==a)return a}return"json"},Ht=e=>_t(e,[]),_t=(e,t)=>Xt(e,0,t)?t.join(""):void 0,Xt=(e,t,r)=>{if(t>o)return!1;if(null===e)return Zt(r,"n");if(void 0===e)return Zt(r,"u");switch(typeof e){case"boolean":return Zt(r,e?"t":"f");case"number":return Yt(e,r);case"string":return Zt(r,`s${e.length}:${e}`);case"object":break;default:return!1}if(Array.isArray(e)){r.push("[");for(const a of e)if(!Xt(a,t+1,r))return!1;return Zt(r,"]")}if(!n(e))return!1;r.push("{");for(const a in e)if(r.push(`s${a.length}:${a}`),!Xt(e[a],t+1,r))return!1;return Zt(r,"}")},Yt=(e,t)=>Number.isNaN(e)?Zt(t,"N"):e===1/0?Zt(t,"I"):e===-1/0?Zt(t,"J"):Object.is(e,-0)?Zt(t,"#-0"):Zt(t,`#${String(e)}`),Zt=(e,t)=>(e.push(t),!0);class er{deps;identity=new WeakMap;content=new Bt(200);constructor(e){this.deps=e}resolve(e){const t="object"==typeof e&&null!==e?e:void 0;if(void 0!==t){const e=this.identity.get(t);if(void 0!==e)return e}const r=this.deps.probe(e);if(r.constant){const e={kind:"inert",depth:r.depth};return void 0!==t&&this.identity.set(t,e),e}const a=void 0===t?void 0:(e=>{const t=Kt(e,0);return"json"===t?JSON.stringify(e):"serializer"===t?_t(e,[Wt]):void 0})(e),n=void 0===a?void 0:this.content.get(a),o=n??this.deps.compile(e),i={kind:"artifact",artifact:o};return void 0!==t&&this.identity.set(t,i),void 0!==a&&void 0===n&&!o.identityOnly&&o.holes.length>0&&this.content.set(a,o),i}}const tr=/*#__PURE__*/new Set(["type","required","default","description","metadata","constraints"]),rr=/*#__PURE__*/new Set(["expression","parameters","description","metadata"]),ar=(t,a,n)=>{const o=(...e)=>["fragments",t,...e],s=r(t);if(!s.ok)return void n(i.invalidName,`'${t}' is not a legal fragment name: ${s.reason}`,o());if($.has(t))return void n(i.reservedName,`'${t}' is a reserved name and may not name a fragment`,o());if(!e(a))return void n(i.invalidDefinition,`fragment '${t}' must be a wrapper object: { expression, parameters?, description?, metadata? }`,o());if(!("expression"in a))return void n(i.invalidDefinition,`fragment '${t}' has no 'expression'`,o());for(const e of Object.keys(a))rr.has(e)||n(i.invalidDefinition,`'${e}' is not a key of a fragment definition`,o(e));const l={name:t,parameters:{},body:{kind:"constant",value:null,path:null,order:0},returns:"any",warnings:[],nodeCount:0,maxDepth:0,dependencies:{dataPaths:new Map,dynamic:!1,operators:[],fragments:[]},identityOnly:!1};if(void 0!==a.description&&("string"!=typeof a.description?n(i.invalidDefinition,"'description' must be a string",o("description")):l.description=a.description),void 0!==a.metadata&&(e(a.metadata)?l.metadata=a.metadata:n(i.invalidDefinition,"'metadata' must be a plain object",o("metadata"))),void 0!==a.parameters)if(e(a.parameters))for(const[e,t]of Object.entries(a.parameters)){const r=nr(e,t,o,n);void 0!==r&&(l.parameters[e]=r)}else n(i.invalidDefinition,"'parameters' must be a plain object",o("parameters"));return l},nr=(t,a,n,o)=>{const s=n("parameters",t),l=r(t);if(!l.ok)return void o(i.invalidName,`'${t}' is not a legal parameter name: ${l.reason}`,s);if(x.has(t))return void o(i.reservedName,`'${t}' is a reserved node key and may not name a parameter`,s);if(!e(a))return void o(i.invalidDefinition,`the declaration of '${t}' must be an object`,s);for(const e of Object.keys(a))tr.has(e)||o(i.invalidDefinition,`'${e}' is not a key of a parameter declaration`,[...s,e]);const c=a.type??"any";if(!ne(c))return void o(i.invalidDefinition,`'${t}' declares an unknown type`,[...s,"type"]);if(void 0!==a.required&&"boolean"!=typeof a.required)return void o(i.invalidDefinition,"'required' must be a boolean",[...s,"required"]);let u;if(void 0!==a.constraints){const e=ce(a.constraints);if(!e.ok)return void o(i.invalidDefinition,`'${t}' declares invalid constraints: expected ${e.expected}, got ${e.actual}`,[...s,"constraints"]);u=a.constraints}const d="default"in a;if(d&&!0===a.required)return void o(i.invalidDefinition,`'${t}' is declared required and also declares a default — the default could never apply`,[...s,"default"]);if(d){const e=oe(a.default,c);if(!e.ok)return void o(i.typeCheck,`the default for '${t}' does not satisfy its declared type: expected ${e.expected}, got ${e.actual}`,[...s,"default"]);if(void 0!==u){const e=ie(a.default,u);if(!e.ok)return void o(i.typeCheck,`the default for '${t}' violates its declared constraints: expected ${e.expected}, got ${e.actual}`,[...s,"default"])}}const p={type:c,required:a.required??!d};return d&&(p.default=a.default),"string"==typeof a.description&&(p.description=a.description),e(a.metadata)&&(p.metadata=a.metadata),void 0!==u&&(p.constraints=u),p},or=e=>{const t=new Set,r=new Set,a=e=>{if(r.has(e.name)||t.has(e.name))return;t.add(e.name);const n=e.body;"fragmentCall"===n.kind&&void 0!==n.entry&&a(n.entry),e.returns=Pt(n),t.delete(e.name),r.add(e.name)};for(const t of e.fragments.values())a(t)},ir=(e,t)=>{const r=[],a=new Set,n=new Set,o=s=>{const l=r.indexOf(s);if(-1!==l){const e=[...r.slice(l),s],a=[...e].sort().join("\0");return n.has(a)||t(i.fragmentCycle,`fragment '${s}' reaches itself: ${e.join(" → ")} — recursion is not supported`,["fragments",s]),void n.add(a)}if(!a.has(s)){r.push(s);for(const t of e.get(s)?.fragmentCalls??[])o(t.name);r.pop(),a.add(s)}};for(const t of e.keys())o(t);return 0===n.size},sr=(e,t)=>{const r=new Set,a=n=>{if(r.has(n))return;r.add(n);const o=e.fragments.get(n),i=t.get(n);if(void 0===o||void 0===i)return;for(const e of i.fragmentCalls)a(e.name);const s=qe(i.own,i.fragmentCalls,e.fragments);o.nodeCount=s.nodeCount,o.maxDepth=s.maxDepth,o.dependencies=s.dependencies,o.identityOnly=s.identityOnly,o.timeoutFallback=lr(i,e.fragments)};for(const e of t.keys())a(e)},lr=(e,t)=>{const{root:r,holes:a}=e;if(0===a.length)return;const n=[];for(const e of a){const r=cr(e,t);if(void 0===r)return;n.push(r.value)}return"skeleton"===r.kind?{value:Ae(r.skeleton,r.holes,n)}:{value:n[0]}},cr=(e,t)=>{if(void 0!==e.timeoutFallback)return e.timeoutFallback;const{node:r}=e;return"fragmentCall"===r.kind&&void 0===r.fallback?t.get(r.name)?.timeoutFallback:void 0},ur=["fallback","useCache"],dr=t=>{const r=[],a=(e,t,a,n)=>{r.push({severity:"error",code:e,message:t,path:a,...void 0!==n?{operator:n}:{}})},n={operators:new Map,aliases:new Map,fragments:new Map},{operators:o,aliases:s}=n,l=new Map,c=(e,t,r)=>{const n=l.get(e);return void 0!==n?(a(i.duplicateOperator,`'${e}' is already registered (by '${n}') — one namespace, no silent precedence`,t,r),!1):(l.set(e,r),!0)},u=(e,t)=>{if("function"==typeof e)return void a(i.invalidOptions,`operators[${t[1]}]${t.length>2?`[${t[2]}]`:""} is a function — factories must be called: httpOperators(client)`,t);if(!he(e))return void a(i.invalidOptions,"every operators entry must be built with defineOperator() — a plain definition object is not accepted",t);const{name:r,alias:n}=e,l=c(r,t,r),u=void 0===n||c(n,t,r);l&&u&&(o.set(r,{definition:e}),void 0!==n&&s.set(n,r))};return Array.isArray(t.operators)?t.operators.forEach((e,t)=>{Array.isArray(e)?e.forEach((e,r)=>{Array.isArray(e)?a(i.invalidOptions,"'operators' is flattened one level only — arrays may not nest deeper",["operators",t,r]):u(e,["operators",t,r])}):u(e,["operators",t])}):a(i.invalidOptions,"'operators' must be an array",["operators"]),void 0!==t.operatorDefaults&&pr(t.operatorDefaults,o,s,a),((t,r,a,n)=>{if(void 0===t)return;if(!e(t))return void n(i.invalidOptions,"'fragments' must be a plain object",["fragments"]);for(const[e,o]of Object.entries(t)){const t=ar(e,o,n);void 0!==t&&a(e,["fragments",e])&&r.fragments.set(e,t)}const o=new Map;for(const[e,a]of r.fragments){const n=t[e],i=Ce(n.expression,r,{basePath:["expression"]});a.body=i.root,o.set(e,i)}or(r);for(const[e,t]of r.fragments){const r=o.get(e);Dt(r,{fragmentParams:new Set(Object.keys(t.parameters))});for(const{issue:a}of r.issues)if("error"===a.severity)n(a.code,`fragment '${e}': ${a.message}`,["fragments",e,...a.path]);else{const e={...a,path:[...a.path]};Object.freeze(e.path),t.warnings.push(Object.freeze(e))}}ir(o,n)&&sr(r,o)})(t.fragments,n,(e,t)=>c(e,t,e),a),r.length>0&&(e=>{const[t]=e,r=e.length-1,a=r>0?`${t.message} (+ ${r} more issue${1===r?"":"s"})`:t.message;throw new j({code:i.invalidOptions,message:a,path:t.path,...void 0!==t.operator?{operator:t.operator}:{},issues:e})})(r),n},pr=(t,r,a,n)=>{if(e(t))for(const[o,s]of Object.entries(t)){const t=["operatorDefaults",o],l=r.get(o);if(void 0===l){const e=a.get(o);void 0!==e?n(i.invalidOptions,`'operatorDefaults' keys are canonical names — use '${e}', not its alias '${o}'`,t,e):n(i.unknownOperator,`'${o}' names no registered operator`,t);continue}if(!e(s)){n(i.invalidOptions,`the defaults for '${o}' must be a plain object`,t,o);continue}let c=!0;for(const[e,r]of Object.entries(s)){const a=[...t,e];if(ur.includes(e)){"useCache"===e&&"boolean"!=typeof r&&(n(i.invalidOptions,"the 'useCache' modifier default must be a boolean",a,o),c=!1);continue}const s=l.definition.parameters[e];if(void 0===s){n(i.invalidOptions,`'${e}' names no declared parameter of '${o}' (nor 'fallback'/'useCache')`,a,o),c=!1;continue}if(s.required){n(i.invalidOptions,`'${e}' is a required parameter of '${o}' — operatorDefaults may only target optional parameters`,a,o),c=!1;continue}const u=oe(r,s.type);if(u.ok){if(void 0!==s.constraints){const t=ie(r,s.constraints);t.ok||(n(i.typeCheck,`the default for '${o}.${e}' violates its declared constraints: expected ${t.expected}, got ${t.actual}`,a,o),c=!1)}}else n(i.typeCheck,`the default for '${o}.${e}' does not satisfy its declared type: expected ${u.expected}, got ${u.actual}`,a,o),c=!1}c&&(l.instanceDefaults=Object.freeze({...s}))}else n(i.invalidOptions,"'operatorDefaults' must be a plain object",["operatorDefaults"])},mr=(e,t)=>{const r=e.operators.get(t);if(void 0!==r)return r;const a=e.aliases.get(t);return void 0!==a?e.operators.get(a):void 0},fr="fig-tree:scope-settled",hr="fig-tree:request-expired",vr="fig-tree:evaluation-timeout";class yr{parent;controller;upstream;forward;settled=!1;verified=-1;clock;constructor(e){this.parent=e,this.clock=void 0===e?{epoch:0}:e.clock}get aborted(){return void 0!==this.controller?this.controller.signal.aborted:!!this.settled||this.verified!==this.clock.epoch&&(!(void 0===this.parent||!this.parent.aborted)||(this.verified=this.clock.epoch,!1))}get reason(){return void 0!==this.controller?this.controller.signal.reason:this.settled?fr:this.parent?.reason}get signal(){if(void 0===this.controller){const e=new AbortController;if(this.controller=e,this.settled)e.abort(fr);else if(void 0!==this.parent){const t=this.parent.signal;t.aborted?e.abort(t.reason):(this.upstream=t,this.forward=()=>e.abort(t.reason),t.addEventListener("abort",this.forward,{once:!0}))}}return this.controller.signal}settle(){this.settled||(this.settled=!0,this.clock.epoch+=1,void 0!==this.controller&&(void 0!==this.upstream&&void 0!==this.forward&&this.upstream.removeEventListener("abort",this.forward),this.controller.abort(fr)))}}const gr=(e,t)=>({get aborted(){return e.aborted},get reason(){return e.reason},signal:e,clock:t.clock,settle:P}),br=(e,t,r)=>{const a=void 0===e?(()=>{const e=new AbortController;return{signal:e.signal,abort:t=>e.abort(t),settle:()=>e.abort(fr)}})():(e=>{const t=new AbortController;e.aborted&&t.abort(e.reason);const r=()=>t.abort(e.reason);return e.addEventListener("abort",r,{once:!0}),{signal:t.signal,abort:e=>t.abort(e),settle:()=>{e.removeEventListener("abort",r),t.abort(fr)}}})(e),{signal:n}=a;let o;const i=new Promise((e,t)=>{o=t});i.catch(P);const s=()=>o(n.reason);n.aborted?s():n.addEventListener("abort",s,{once:!0});const l=void 0===t?void 0:setTimeout(()=>a.abort(r),Math.min(t,2147483647));return{signal:n,expiry:i,settle:()=>{void 0!==l&&clearTimeout(l),n.removeEventListener("abort",s),a.settle()}}},wr=(e,t)=>br(e,t,hr),kr=async(e,t,r,a)=>{const n=e.generation,o=await e.lookup(t);if(a?.({type:"cache",hit:o.hit}),o.hit)return o.value;const i=await r();return await e.write(t,i,n),i},$r=/*#__PURE__*/Object.freeze({});class xr{options;cache;trace;#e;constructor(e,t,r,a){this.options=t,this.cache=r,this.trace=a,this.#e=e}get signal(){return this.#e.signal}}const jr={memo:(e,t)=>t()},Pr={note:P},Or=Symbol("fig-tree:internal-error"),Ar=e=>Mr(`[fig-tree internal] ${e}`,Or),Dr=e=>Rr(e,Or),Nr=Symbol("fig-tree:cancelled"),Sr=()=>Mr("[fig-tree] evaluation cancelled",Nr),Cr=e=>Rr(e,Nr),qr=(e,t,r)=>e.rootScope.aborted?Tr(e.rootScope.reason,t,r):e.abortScope.aborted?Sr():void 0,Tr=(e,t,r)=>e===fr?Sr():Er(e,$e(t),{operator:r}),Er=(e,t,r={})=>{const{operator:a,ms:n}=r,o=e===vr,s=void 0===n?"":`${n}ms `;return new j({code:o?i.timeout:i.aborted,message:o?`evaluation exceeded its ${s}timeout`:"evaluation was aborted by the caller",path:t,...void 0!==a?{operator:a}:{}})},zr=e=>O(e)&&(e.code===i.aborted||e.code===i.timeout),Mr=(e,t)=>{const r=new Error(e);return Lr(r,t),r},Lr=(e,t)=>{e[t]=!0},Rr=(e,t)=>e instanceof Error&&!0===e[t],Fr=()=>performance.now(),Ir=e=>{const t=new Map,r=new WeakMap;let a;const n=(e,r,a)=>{const n=t.get(e);if(void 0===n)return;t.delete(e),"fallback"!==e.status&&(e.status=r),void 0!==a.error&&void 0===e.error&&(e.error=a.error),"failed"!==r&&"cancelled"!==r&&(e.value=a.value),void 0!==a.elapsed&&(e.elapsed=a.elapsed);const o=[...n.children,...Vr(n)];o.length>0&&(e.children=o.sort((e,t)=>e.order-t.order||e.index-t.index).map(e=>e.entry))},o=(e,t)=>{(e.events??=[]).push(t)};return{enter:(e,n,o,i)=>{const s=Wr(e),l=Kr(e),c={path:$e(e.path),kind:Gr(e),status:"value",...void 0!==o?{source:{fragment:o.fragment}}:{},...void 0!==s?{operator:s}:{},...void 0!==l?{ref:l}:{},...void 0!==i?.var?{var:i.var}:{}};return t.set(c,{node:e,children:[],seen:new Set}),r.set(e,c),((e,r,n)=>{if(void 0===e)return void(a=r.entry);const o=t.get(e);void 0!==o&&(o.children.push(r),o.seen.add(n))})(n,{entry:c,order:e.order,index:i?.index??0},e),c},settle:n,markFallback:(e,t)=>{e.status="fallback",e.error=t},note:o,noteOn:(e,t)=>{const a=r.get(e);void 0!==a&&o(a,t)},finish:()=>{for(const e of[...t.keys()].reverse())n(e,"cancelled",{});return void 0!==a&&e.length>0&&(a.warnings=e),a}}},Vr=e=>Qr(e.node).filter(t=>!e.seen.has(t)).map(e=>({entry:{path:$e(e.path),kind:Gr(e),status:"skipped"},order:e.order,index:0})),Qr=e=>{switch(e.kind){case"operator":return[...Object.values(e.params).flatMap(Jr),...void 0!==e.fallback?[e.fallback]:[],...Object.values(e.vars??{})];case"fragmentCall":return[...Ur(e.parameters),...void 0!==e.fallback?[e.fallback]:[],...Object.values(e.vars??{}),...void 0!==e.entry?[e.entry.body]:[]];case"skeleton":return[...e.holes.map(e=>e.node),...Object.values(e.vars??{})];case"elements":return e.nodes;case"entries":return Object.values(e.entries);default:return[]}},Jr=e=>"elements"===e.kind||"entries"===e.kind?Qr(e):[e],Ur=e=>void 0===e?[]:Br(e)?[e]:Object.values(e),Br=e=>"string"==typeof e.kind,Gr=e=>{switch(e.kind){case"operator":return"operator";case"fragmentCall":return"fragment";case"reference":return"reference";case"skeleton":return"skeleton";default:return"literal"}},Wr=e=>"operator"===e.kind||"fragmentCall"===e.kind?e.name:void 0,Kr=e=>"reference"===e.kind?e.raw:void 0,Hr=(e,t)=>{if(void 0===t)return e;const r={parent:e.scope,vars:new Map},a={...e,scope:r};for(const[e,n]of Object.entries(t))r.vars.set(e,A(()=>Ra(n,a,{var:e})));return a},_r=async(e,t,r,a,n)=>{const o={...r,params:"dynamic"===e.argumentsMode?await Yr(e,t,a):Xr(e,t,a),frame:n};delete o.scope,delete o.bindings;const i=await Ra(t.body,o);return void 0===i?null:i},Xr=(e,t,r)=>{const a=e.parameters??{},n=new Map;for(const[o,i]of Object.entries(t.parameters)){const t=a[o],s=A(async()=>{if(void 0===t)return Zr(e,o,i,r);let a;try{a=await Ra(t,r)}catch(e){throw na(e,r.frame)}return ea(e,o,i,a,t.path,r)});n.set(o,()=>{const e=s();return e.catch(P),e})}return n},Yr=async(t,r,a)=>{const n=t.parameters;let o;try{o=await Ra(n,a)}catch(e){throw na(e,a.frame)}if(!e(o))throw na(ta(t,i.typeCheck,`'parameters' must evaluate to an object, received ${ra(o)}`,n.path),a.frame);const s=new Map;for(const[e,i]of Object.entries(r.parameters)){const r=Object.hasOwn(o,e)?ea(t,e,i,o[e],n.path,a):Zr(t,e,i,a,n.path);s.set(e,()=>Promise.resolve(r))}return s},Zr=(e,t,r,a,n=e.path)=>{if(!r.required)return r.default??null;throw na(ta(e,i.missingRequired,`requires '${t}'`,n),a.frame)},ea=(e,t,r,a,n,o)=>{const s=void 0===a?null:a;if(null===s&&!r.required&&!re(r.type))return r.default??null;if(!o.runtimeTypeCheck)return s;const l=oe(s,r.type);if(!l.ok)throw na(ta(e,i.typeCheck,`parameter '${t}': expected ${l.expected}, received ${l.actual}`,n),o.frame);if(void 0!==r.constraints){const a=ie(s,r.constraints);if(!a.ok)throw na(ta(e,i.typeCheck,`parameter '${t}': expected ${a.expected}, received ${a.actual}`,n),o.frame)}return s},ta=(e,t,r,a)=>new j({code:t,message:`fragment '${e.name}' – ${r}`,path:$e(a)}),ra=e=>null===e?"null":Array.isArray(e)?"array":typeof e,aa=Symbol("fig-tree:anchored"),na=(e,t)=>!O(e)||Rr(e,aa)?e:(Lr(e,aa),void 0===t||(e.fragment=t.fragment,e.fragmentPath=e.path,e.path=$e(t.callPath)),e);class oa extends Error{code;errorData;constructor(e,t={}){super(e),this.name="OperatorFailure",void 0!==t.code&&(this.code=t.code),void 0!==t.errorData&&(this.errorData=t.errorData)}}const ia=e=>e instanceof oa,sa=Symbol("fig-tree:lazy-handle"),la=(e,t,r)=>ua(Array.from({length:e},(e,a)=>ca(a,()=>t(a),r)),e),ca=async(e,t,r)=>{try{return{index:e,ok:!0,value:r(await t())}}catch(t){return{index:e,ok:!1,error:t}}},ua=(e,t)=>{const r=new Map(e.map((e,t)=>[t,e]));return{[sa]:!0,length:t,async*[Symbol.asyncIterator](){for(;r.size>0;){const e=await Promise.race(r.values());r.delete(e.index),yield e}}}},da=e=>({[sa]:!0,evaluate:A(e)}),pa=e=>({[sa]:!0,evaluate:()=>Promise.resolve(e)}),ma=(e,t,r,a,n)=>da(async()=>fa(await Ra(e,n),t,r,a,n)),fa=(e,t,r,a,n)=>{if(n.runtimeTypeCheck){const n=oe(e,a.type);if(!n.ok)throw ba(t,r,n);if(null!==e&&void 0!==a.constraints){const n=de(e,a.constraints,void 0!==a.elementNullPolicy);if(!n.ok)throw ba(t,r,n)}}return a.truthiness?xa(e,a.type):e},ha=(e,t,r,a,n,o)=>{const i=Array.isArray(t)?t:[],s=Pe(r),l=new Map,c=t=>{const c=l.get(t);if(void 0!==c)return c;const u=(async()=>fa(await Ra(e,((e,t,r,a)=>({...e,bindings:{parent:e.bindings,as:t,element:r,index:a}}))(o,s,i[t],t),{index:t}),r,a,n,o))();return u.catch(P),l.set(t,u),u};return{[sa]:!0,evaluate:c,settle:()=>la(i.length,c,e=>e)}},va=(e,t)=>t.truthiness?z(e):e,ya=(e,t,r)=>{if("lazyElements"===t.evaluation&&"elements"===e.kind)return e.nodes.map((e,a)=>da(async()=>va(await Ra(e,r,{index:a}),t)));if("race"===t.evaluation&&"elements"===e.kind)return((e,t,r)=>la(e.length,r=>Ra(e[r],t,{index:r}),r))(e.nodes,r,e=>va(e,t));if("lazyEntries"===t.evaluation&&"entries"===e.kind){const a=Hr(r,e.vars),n={};for(const[r,o]of Object.entries(e.entries))n[r]=da(async()=>va(await Ra(o,a),t));return n}},ga=(e,t)=>{switch(t.evaluation){case"lazyElements":return e.map(e=>pa(va(e,t)));case"race":return((e,t)=>la(e.length,t=>Promise.resolve(e[t]),t))(e,e=>va(e,t));case"lazyEntries":{const r={};for(const[a,n]of Object.entries(e))r[a]=pa(va(n,t));return r}case"lazy":return pa(e);default:return e}},ba=(e,t,r)=>new j({code:i.typeCheck,message:`${e.name} – parameter '${t}': expected ${r.expected}, received ${r.actual}`,path:$e(e.path),operator:e.name}),wa=(e,t,r)=>{if("string"==typeof t.nullPolicy)return t.nullPolicy;const a=t.nullPolicy,n=e.entry.definition.parameters[a.selector],o=r[a.selector],i=oe(o,n.type);if(!i.ok)throw ba(e,a.selector,i);const s=a.table.find(e=>e.value===o);if(void 0===s)throw Ar(`no null-policy row for ${e.name}.${a.selector}`);return s.policy},ka=async(t,r,a)=>{if(void 0!==r.elementNullPolicy){if(Array.isArray(t)&&t.includes(null)){const e=await a();return t.map(t=>null===t?e:t)}if(e(t)&&Object.values(t).includes(null)){const e=await a(),r={};for(const[a,n]of Object.entries(t))r[a]=null===n?e:n;return r}return t}return null===t?a():t},$a=t=>Array.isArray(t)?t.includes(null):!!e(t)&&Object.values(t).includes(null),xa=(t,r)=>{if((e=>!("object"==typeof e&&!Array.isArray(e))&&(Array.isArray(e)?e:[e]).every(e=>"array"===e||"object"===e))(r)){if(Array.isArray(t))return t.map(z);if(e(t)){const e={};for(const[r,a]of Object.entries(t))e[r]=z(a);return e}}return z(t)},ja=async(e,t)=>{const{params:r,propagate:a}=await(async(e,t)=>{const{definition:r,instanceDefaults:a}=e.entry,{entries:n,whole:o,perElement:i}=r.resolution,s=[],l=[],c={};let u;const d={};for(const[r,o]of n){const n=e.params[r];switch(o.evaluation){case"eager":void 0!==n&&(s.push(r),l.push(Ra(n,t)));break;case"structural":"constant"===n?.kind&&(c[r]=n.value);break;case"lazy":if(void 0!==o.replacesNullAt){const e=void 0!==n?A(()=>Ra(n,t)):void 0!==a&&Object.hasOwn(a,r)?A(()=>a[r]):void 0;if(void 0!==e)for(const t of o.replacesNullAt)(u??={})[t]=e;break}void 0!==n&&(d[r]=ma(n,e,r,o,t));break;case"lazyElements":case"lazyEntries":case"race":{if(void 0===n)break;const e=ya(n,o,t);if(void 0!==e){d[r]=e;break}s.push(r),l.push(Ra(n,t));break}case"perElement":break;default:o.evaluation}}if(l.length>0)if(1===l.length){const e=l[0];c[s[0]]=D(e)?await e:e}else{const e=await Promise.all(l);s.forEach((t,r)=>{c[t]=e[r]})}for(const[e,r]of o){if(Object.hasOwn(d,e))continue;const n=c[e];(void 0===n||null===n&&!r.required&&!re(r.type))&&(void 0!==a&&Object.hasOwn(a,e)?c[e]=a[e]:"default"in r?c[e]=r.default===me?t.data:r.default:delete c[e])}for(const[r,a]of o){if(Object.hasOwn(d,r))continue;let n=c[r];if(void 0===n)continue;const o=u?.[r];void 0!==o&&(n=await ka(n,a,o));const i="eager"!==a.evaluation&&"structural"!==a.evaluation;if(null===n&&re(a.type)&&!i&&"propagate"===wa(e,a,c))return{params:d,propagate:!0};if("propagate"===a.elementNullPolicy&&$a(n))return{params:d,propagate:!0};n=fa(n,e,r,a,t),d[r]=ga(n,a)}for(const[r,a]of i){if(void 0===a.over)throw Ar(`parameter '${r}' of '${e.name}' declares perElement without 'over'`);const n=e.params[r];void 0!==n&&(d[r]=ha(n,d[a.over],e,r,a,t))}return{params:d,propagate:!1}})(e,t);if(a)return null;const{definition:n}=e.entry,o=Da(e,t.options),i=Oa(n,r),s=void 0===i?void 0:wr(t.abortScope.signal,i),l=void 0===s?t:{...t,abortScope:gr(s.signal,t.abortScope)},c=(e=>{const{trace:t,traceParent:r}=e;if(void 0!==t&&void 0!==r)return e=>{t.note(r,e)}})(t),u=((e,t,r,a)=>{return new xr(e.abortScope,e.options,r?{memo:(n={operator:t.name,fingerprint:t.fingerprint,note:a},o=e.cache,(e,t)=>{const r=Ht(["M",n.operator,n.fingerprint,e]);return void 0===r?t():kr(o,r,t,n.note)})}:jr,void 0===a?Pr:{note:a});var n,o})(l,n,o,c);try{if(!o||"auto"!==n.cache)return await Pa(e,t,r,u,s);const a=((e,t)=>{const{definition:r}=e.entry;if(!r.deliversLazily)return Ht(["A",r.name,r.fingerprint,t])})(e,r),i=()=>Pa(e,t,r,u,s);return await(void 0===a?i():kr(t.cache,a,i,c))}catch(r){throw Aa(r,e,t,s,i)}finally{s?.settle()}},Pa=async(e,t,r,a,n)=>{const o=qr(t,e.path,e.name);if(void 0!==o)throw o;const i=Promise.resolve(e.entry.definition.evaluate(r,a));return void 0===n?Sa(await i,e):(i.catch(P),Sa(await Promise.race([i,n.expiry]),e))},Oa=(e,t)=>{const r=e.timeoutParam;if(null===r)return;const a=t[r];return"number"==typeof a&&a>0?a:void 0},Aa=(e,t,r,a,n)=>{if(Dr(e)||Cr(e))return e;const o=qr(r,t.path,t.name);return void 0!==o?o:a?.signal.reason===hr?new oa(`request exceeded its ${String(n)}ms timeout`,{code:i.requestTimeout}):e},Da=(e,t)=>e.useCache??e.entry.instanceDefaults?.useCache??t.useCache??e.entry.definition.useCache,Na=(e,t)=>{const r=e.fallback;if(void 0!==r)return()=>Ra(r,t);const a=e.entry.instanceDefaults;return void 0!==a&&Object.hasOwn(a,"fallback")?()=>a.fallback:void 0},Sa=(e,t)=>{if(void 0===e)return null;if("number"==typeof e&&!Number.isFinite(e))throw new j({code:i.nonFiniteResult,message:`${t.name} – produced a non-finite number (${String(e)})`,path:$e(t.path),operator:t.name});if("object"==typeof(r=e)&&null!==r&&!0===r[sa])throw new j({code:i.escapedHandle,message:`${t.name} – returned a lazy handle instead of evaluating it`,path:$e(t.path),operator:t.name});var r;return e},Ca=(e,t)=>{if(O(e))return e;if(ia(e))return new j({code:e.code??i.operatorFailure,message:`${t.name} – ${e.message}`,path:$e(t.path),operator:t.name,...void 0!==e.errorData?{errorData:e.errorData}:{}});const r=e instanceof Error?e.message:String(e);return new j({code:i.operatorFailure,message:`${t.name} – ${r}`,path:$e(t.path),operator:t.name})},qa=(e,t)=>0===e.segments.length?t.data:Ma(t.data,e.segments,e,t,"is absent from the evaluation data"),Ta=async(e,t)=>{const[r,...a]=e.segments,n="string"==typeof r?((e,t)=>{for(let r=e;void 0!==r;r=r.parent){const e=r.vars.get(t);if(void 0!==e)return e}})(t.scope,r):void 0;if("string"!=typeof r||void 0===n)throw Ar(`'${e.raw}': no var named '${String(r)}' is in scope — the static gate should have refused it`);const o=await n();return 0===a.length?La(o):Ma(o,a,e,t,`is absent from the value of '$vars.${r}'`)},Ea=async(e,t)=>{const r=t.params;if(void 0===r)throw Ar(`'${e.raw}': $params outside a fragment body — the static gate should have refused it`);const[a,...n]=e.segments;if(void 0===a){const e={};return await Promise.all([...r].map(async([t,r])=>{e[t]=La(await r())})),e}const o="string"==typeof a?r.get(a):void 0;if(void 0===o)throw Ar(`'${e.raw}': the fragment declares no parameter '${String(a)}' — the static gate should have refused it`);const i=await o();return 0===n.length?La(i):Ma(i,n,e,t,`is absent from the value of '$params.${String(a)}'`)},za=(e,t)=>{const r=e.namespace,a=((e,t,r)=>{for(let a=e;void 0!==a;a=a.parent)if(Oe(a.as,t,r))return a})(t.bindings,r,e.binding);if(void 0===a)throw Ar(`'${e.raw}': no enclosing iterator binds it — the static gate should have refused it`);return"index"===r?a.index:0===e.segments.length?La(a.element):Ma(a.element,e.segments,e,t,`is absent from '${e.raw.split(".")[0]}'`)},Ma=(e,t,r,a,n)=>{const o=w(e,t);if(o.found)return La(o.value);if(!a.strictDataPaths)return null;throw new j({code:i.missingDataPath,message:`'${r.raw}' ${n} (strictDataPaths)`,path:$e(r.path)})},La=e=>void 0===e?null:e,Ra=(e,t,r)=>void 0!==t.trace?Fa(e,t,t.trace,r):t.abortScope.aborted?Promise.reject(qr(t,e.path)):Ia(e,t),Fa=async(e,t,r,a)=>{const n=r.enter(e,t.traceParent,t.frame,a),o=Fr();try{if(t.abortScope.aborted)throw qr(t,e.path);const a=await Ia(e,{...t,traceParent:n});return r.settle(n,"value",{value:a,elapsed:Fr()-o}),a}catch(e){throw r.settle(n,Cr(e)?"cancelled":"failed",{...O(e)?{error:e}:{},elapsed:Fr()-o}),e}},Ia=(e,t)=>{try{switch(e.kind){case"constant":return e.value;case"reference":return((e,t)=>{switch(e.namespace){case"data":return qa(e,t);case"vars":return Ta(e,t);case"params":return Ea(e,t);case"element":case"index":return za(e,t)}})(e,t);case"skeleton":return Va(e,t);case"operator":return(async(e,t)=>{const r=Hr(t,e.vars),a=e.entry.definition.deliversLazily?new yr(r.abortScope):void 0,n=void 0===a?r:{...r,abortScope:a};try{try{return await ja(e,n)}finally{a?.settle()}}catch(a){if(Dr(a)||Cr(a)||zr(a))throw a;const n=Ca(a,e),o=Na(e,r);if(void 0===o)throw n;try{const e=await o();return void 0!==t.trace&&void 0!==t.traceParent&&t.trace.markFallback(t.traceParent,n),e}catch(t){if(Dr(t)||Cr(t)||zr(t))throw t;const r=Ca(t,e);throw void 0===r.cause&&(r.cause=n),r}}})(e,t);case"fragmentCall":return(async(e,t)=>{const{entry:r}=e;if(void 0===r)throw Ar(`fragment call '${e.name}' resolved to nothing — the static gate should have refused it`);const a=Hr(t,e.vars),n=new yr(a.abortScope),o={fragment:e.name,callPath:t.frame?.callPath??e.path},i={...a,abortScope:n};try{try{return await _r(e,r,i,a,o)}finally{n.settle()}}catch(r){if(Dr(r)||Cr(r)||zr(r))throw r;const n=na(r,o),{fallback:i}=e;if(void 0===i)throw n;try{return await Ra(i,a)}catch(e){if(Dr(e)||Cr(e)||zr(e))throw e;const r=na(e,t.frame);throw O(r)&&void 0===r.cause&&(r.cause=n),r}}})(e,t);case"elements":case"entries":throw Ar(`a '${e.kind}' parameter value reached the node dispatch — parameter resolution consumes these, and nothing else may hold one`);case"invalid":throw Ar("an invalid node reached evaluation — the static gate should have refused it")}}catch(e){return Promise.reject(e)}},Va=async(e,t)=>{const r=t.rootBoundary,a=void 0===r?t:{...t,rootBoundary:void 0},n=Hr(a,e.vars),o=e.holes.map(e=>void 0===r?Ra(e.node,n):r(()=>Ra(e.node,n),e.node)),i=o.some(D)?await Promise.all(o):o;return Ae(e.skeleton,e.holes,i)},Qa=Number.MAX_SAFE_INTEGER,Ja=(e,t)=>{if(O(e))return e;const r=e instanceof Error?e.message:String(e);return new j({code:i.operatorFailure,message:r,path:t.path})},Ua=(e,t)=>{if(void 0===e.holePath)return e.holePath=t,e;const r=new j({...e,message:e.message,holePath:t});return r.stack=e.stack,r},Ba=async(e,t,r)=>{const{timeout:a,signal:n}=t,o="report"===t.mode,s=e.holes.length>0,l=void 0!==a||void 0!==n?br(n,a,vr):void 0,c=void 0!==l?((e,t)=>{const r={epoch:0};return e.addEventListener("abort",()=>{r.epoch+=1},{once:!0}),{get aborted(){return e.aborted},get reason(){return e.reason},signal:e,clock:r,settle:t}})(l.signal,l.settle):new yr(void 0),u=void 0!==l&&void 0!==a&&e.timeoutShielded&&s,d=o?(()=>{const e=[];return{record:(t,r)=>{e.push({error:Ua(Ja(t,r),r.path),order:r.node.order})},add:t=>{e.push({error:t,order:Qa})},emit:()=>[...e].sort((e,t)=>e.order-t.order).map(e=>e.error)}})():void 0,p=!0===t.trace?Ir(e.issues.map(e=>e.issue).filter(e=>"error"!==e.severity)):void 0,m=((e,t,r,a)=>({options:e,data:e.data??$r,abortScope:r,rootScope:r,cache:t,strictDataPaths:e.strictDataPaths??!1,runtimeTypeCheck:e.runtimeTypeCheck??!0,...void 0!==a?{trace:a}:{}}))(t,r,c,p),f=s&&(void 0!==d||u)?Ha(e,d,u?l.expiry:void 0,p):void 0,h=void 0!==f&&"skeleton"!==e.root.kind,v=void 0===f||h?m:{...m,rootBoundary:f};try{if(c.aborted)throw Er(c.reason,[]);const t=()=>h&&void 0!==f?f(()=>Ra(e.root,v),e.root):Ra(e.root,v),r=await(u||void 0===l?t():Ka(t,l,a));return void 0!==d&&u&&Wa(l)&&d.add(Er(vr,[],{ms:a})),Ga(r,d,p)}catch(e){if(void 0!==d&&O(e)&&e.code===i.timeout)return d.add(e),Ga(null,d,p);throw void 0!==p&&O(e)&&void 0===e.trace&&(e.trace=p.finish()),e}finally{c.settle()}},Ga=(e,t,r)=>({result:e,errors:t?.emit()??[],...void 0!==r?{trace:r.finish()}:{}}),Wa=e=>e.signal.aborted&&e.signal.reason===vr,Ka=(e,t,r)=>Promise.race([e(),t.expiry.catch(e=>{throw Er(e,[],{ms:r})})]),Ha=(e,t,r,a)=>{const n=new Map(e.holes.map(e=>[e.node,e]));return(e,o)=>{const i=n.get(o);if(void 0===i)throw Ar(`the hole boundary was handed the node at ${JSON.stringify($e(o.path))}, which is not one of the artifact's holes`);const s=void 0===t?Promise.resolve(e()):_a(e,i,t);if(void 0===r)return s;let l=!1;const c=s.then(e=>(l=!0,e));return Promise.race([c,r.catch(e=>{if(e!==vr)throw Er(e,[]);if(!l)return a?.noteOn(i.node,{type:"shielded-fallback"}),Xa(i)})])}},_a=async(e,t,r)=>{try{return await e()}catch(e){if(Dr(e)||Cr(e)||zr(e))throw e;return r.record(e,t),null}},Xa=e=>{if(void 0===e.timeoutFallback)throw Ar("a shielded artifact has a hole with no static fallback");return e.timeoutFallback.value},Ya={hit:!1},Za=e=>{if(void 0===e)return{maxSize:50,maxTime:1800};if(!n(e))throw tn("'cache' must be an object");const{store:t,maxSize:r,maxTime:a}=e;if(void 0!==t&&!en(t))throw tn("'cache.store' must provide get, set, delete and clear methods");if(void 0!==r&&(!Number.isInteger(r)||r<1))throw tn("'cache.maxSize' must be a positive integer");if(void 0!==a&&("number"!=typeof a||a<=0||Number.isNaN(a)))throw tn("'cache.maxTime' must be a positive number of seconds, or Infinity");return{...void 0!==t?{store:t}:{},maxSize:r??50,maxTime:a??1800}},en=e=>"object"==typeof e&&null!==e&&["get","set","delete","clear"].every(t=>"function"==typeof e[t]),tn=e=>new j({code:i.invalidOptions,message:e,path:[]});class rn{store;own;maxTime;current=0;constructor(e){void 0===e.store?(this.own=new Bt(e.maxSize),this.store=this.own):this.store=e.store,this.maxTime=e.maxTime}get generation(){return this.current}async lookup(e){let t;try{t=await this.store.get(e)}catch{return Ya}return n(r=t)&&"ft3"===r.fig&&"number"==typeof r.generation?t.generation<this.current||an(t)?(this.drop(e),Ya):{hit:!0,value:t.value}:Ya;var r}async write(e,t,r){if(r!==this.current)return;const a={fig:"ft3",value:t,generation:r,...Number.isFinite(this.maxTime)?{expiresAt:Date.now()+1e3*this.maxTime}:{}};try{await this.store.set(e,a)}catch{}}clear(){this.current+=1;try{Promise.resolve(this.store.clear()).catch(P)}catch{}}configure(e){void 0!==e.store&&e.store!==this.store&&(this.store=e.store,this.own=void 0),this.maxTime=e.maxTime,this.own?.resize(e.maxSize)}drop(e){try{Promise.resolve(this.store.delete(e)).catch(P)}catch{}}}const an=e=>void 0!==e.expiresAt&&e.expiresAt<=Date.now(),nn=e=>e===N?0:"number"==typeof e?1:2,on=e=>({data:{paths:[...e.dataPaths].sort(([,e],[,t])=>((e,t)=>{const r=Math.min(e.length,t.length);for(let a=0;a<r;a++){const r=e[a],n=t[a];if(r===n)continue;const o=nn(r)-nn(n);return 0!==o?o:"number"==typeof r&&"number"==typeof n?r-n:r<n?-1:1}return e.length-t.length})(e,t)).map(([e])=>e),dynamic:e.dynamic},operators:[...e.operators],fragments:[...e.fragments]}),sn=(e,t)=>{const r={};for(const[a,n]of Object.entries(e)){const e={...n};void 0!==t&&Object.hasOwn(t,a)&&(e.instanceDefault=t[a]),r[a]=e}return r},ln=(e,t)=>{const r=[];return void 0!==t.maxDepth&&e.maxDepth>t.maxDepth&&r.push(cn(e.maxDepth,t.maxDepth)),void 0!==t.maxNodes&&e.nodeCount>t.maxNodes&&r.push({severity:"error",code:i.maxNodesExceeded,message:`the expression holds ${e.nodeCount} evaluable nodes — maxNodes is ${t.maxNodes}`,path:[]}),r},cn=(e,t)=>({severity:"error",code:i.maxDepthExceeded,message:`the expression nests ${e} levels deep — maxDepth is ${t}`,path:[]}),un=(e,t,r)=>{const a=[...ln(e,t),...e.issues.map(r)];return void 0!==t.data&&a.push(...dn(e.dataReads,t.data)),a},dn=(e,t)=>{const r=new Map,a=new Map,n=[],o=(e,o,s,l)=>{let c=r.get(e);if(void 0===c&&(c=w(t,o).found,r.set(e,c)),c)return;let u=a.get(s.path);if(void 0===u&&a.set(s.path,u=new Set),u.has(e))return;u.add(e);const d=void 0===l?"":` (read by fragment '${l}')`;n.push({severity:"warning",code:i.missingDataPath,message:`'${S(o)}' is absent from the supplied sample data${d}`,path:$e(s.path)})};for(const t of e)if("path"===t.kind)o(t.key,t.segments,t,void 0);else for(const[e,r]of t.fragment.dependencies.dataPaths)o(e,r,t,t.fragment.name);return n},pn="...",mn=/*#__PURE__*/new Set(["propagate","value"]),fn=e=>{const t={};for(const[r,a]of Object.entries(e.parameters))t[r]=a.type??"any";const r=hn(e.parameters,t,(t,r,a)=>{throw new j({code:t,message:r,path:a,operator:e.name})});return vn(e,r)},hn=(e,r,a)=>{const n=Object.entries(r).filter(([,e])=>t(e)).map(([e])=>e),o=new Map;for(const[s,l]of Object.entries(e)){if("function"!=typeof l.nullPolicy)continue;const e=["parameters",s,"nullPolicy"];if(1!==n.length){a(i.invalidNullPolicy,`a conditional 'nullPolicy' requires exactly one literal-union parameter in the definition — found ${n.length}`,e,s);continue}const c=n[0],u=r[c];if(!t(u))continue;const d=[];let p=!0;for(const t of u.literal){let r;try{r=l.nullPolicy(t)}catch(r){a(i.invalidNullPolicy,`the conditional 'nullPolicy' threw during compilation for member ${JSON.stringify(t)}: ${String(r)}`,e,s),p=!1;break}if("string"!=typeof r||!mn.has(r)){a(i.invalidNullPolicy,`the conditional 'nullPolicy' must return 'propagate' or 'value' for every member — got ${JSON.stringify(r)} for ${JSON.stringify(t)}`,e,s),p=!1;break}d.push({value:t,policy:r})}p&&o.set(s,{selector:c,table:d})}return o},vn=(e,t)=>{const r={};for(const[a,n]of Object.entries(e.parameters)){const e=t.get(a),o="string"==typeof n.nullPolicy?n.nullPolicy:void 0,i=n.type??"any",s=!0===n.truthiness&&re(i)?"value":"propagate",l={type:gn(i),required:n.required??!("default"in n),evaluation:n.evaluation??"eager",truthiness:n.truthiness??!1,nullPolicy:e??o??s};"default"in n&&(l.default=n.default),void 0!==n.description&&(l.description=n.description),void 0!==n.metadata&&(l.metadata=n.metadata),void 0!==n.elementNullPolicy&&(l.elementNullPolicy=n.elementNullPolicy),void 0!==n.constraints&&(l.constraints=bn(n.constraints)),void 0!==n.over&&(l.over=n.over),void 0!==n.replacesNullAt&&(l.replacesNullAt=[...n.replacesNullAt]),r[a]=l}const a=e.positionalParams?.at(-1),n=a?.startsWith(pn)?a.slice(3):null,o={[fe]:!0,name:e.name,category:e.category,description:e.description,parameters:r,resolution:wn(r),restParam:n,deliversLazily:Object.values(r).some(e=>"eager"!==e.evaluation&&"structural"!==e.evaluation),timeoutParam:e.timeoutParam??null,useCache:e.useCache??!1,cache:e.cache??"auto",fingerprint:"",evaluate:e.evaluate,returns:void 0!==e.returns?gn(e.returns):"any"};return void 0!==e.alias&&(o.alias=e.alias),void 0!==e.metadata&&(o.metadata=e.metadata),void 0!==e.positionalParams&&(o.positionalParams=[...e.positionalParams]),void 0!==e.validate&&(o.validate=e.validate),o.fingerprint=yn(o),kn(o)},yn=e=>C(JSON.stringify([e.name,e.parameters,e.positionalParams,e.restParam,e.returns,e.useCache,e.cache,e.timeoutParam,e.evaluate,e.validate],(e,t)=>"function"==typeof t||"symbol"==typeof t||t instanceof RegExp?String(t):t)),gn=e=>"string"==typeof e?e:t(e)?{literal:[...e.literal]}:[...e],bn=t=>{if(Array.isArray(t))return t.map(bn);if(e(t)){const e={};for(const[r,a]of Object.entries(t))e[r]=bn(a);return e}return t},wn=e=>{const t=Object.entries(e);return{entries:t,whole:t.filter(([,e])=>void 0===e.replacesNullAt&&"perElement"!==e.evaluation),perElement:t.filter(([,e])=>"perElement"===e.evaluation)}},kn=e=>{for(const t of Object.values(e.parameters))"string"!=typeof t.type&&Object.freeze(t.type),"object"==typeof t.type&&"literal"in t.type&&Object.freeze(t.type.literal),"object"==typeof t.nullPolicy&&(t.nullPolicy.table.forEach(e=>Object.freeze(e)),Object.freeze(t.nullPolicy.table),Object.freeze(t.nullPolicy)),void 0!==t.constraints&&$n(t.constraints),void 0!==t.replacesNullAt&&Object.freeze(t.replacesNullAt),Object.freeze(t);Object.freeze(e.parameters);for(const t of Object.values(e.resolution))t.forEach(e=>Object.freeze(e)),Object.freeze(t);return Object.freeze(e.resolution),"string"!=typeof e.returns&&Object.freeze(e.returns),void 0!==e.positionalParams&&Object.freeze(e.positionalParams),Object.freeze(e)},$n=t=>{Array.isArray(t)?(t.forEach($n),Object.freeze(t)):e(t)&&(Object.values(t).forEach($n),Object.freeze(t))},xn=e=>{if(Array.isArray(e))return e;try{return g(e)}catch(e){throw new oa(e.message)}},jn=(e,t)=>{if("string"!=typeof e)return[];try{return g(e),[]}catch(e){return[{severity:"error",parameter:t,message:e.message}]}},Pn=e=>Array.isArray(e.values)&&0===e.values.length?[{severity:"error",parameter:"values",message:"an empty values array has no result — supply at least one value"}]:[],On=e=>t=>{const r=t[e];return Array.isArray(r)&&0===r.length?[{severity:"warning",parameter:e,message:`an empty ${e} array is a dead expression — the result is always the identity`}]:[]},An=/*#__PURE__*/On("values"),Dn=/*#__PURE__*/On("input"),Nn=/*#__PURE__*/On("entries"),Sn=e=>Array.isArray(e.values)&&e.values.length<2?[{severity:"warning",parameter:"values",message:"fewer than two values is a dead comparison — the result never varies"}]:[],Cn=(e,t)=>new oa(`${e} of nothing — the values array is empty${void 0!==t?`; ${t}`:""}`,{code:i.emptyAggregate}),qn=e=>new oa(e,{code:i.typeCheck}),Tn=async(e,t)=>{const r=[];for await(const a of e){if(a.ok&&a.value===t)return t;a.ok||r.push(a)}if(r.length>0)throw r.sort((e,t)=>e.index-t.index),En(r);return!t},En=e=>{const[t,...r]=e,a=r.map(e=>e.error).filter(O);return a.length>0&&O(t.error)&&void 0===t.error.related&&(t.error.related=a),t.error},zn=async e=>{const t=new Array(e.length);let r=0;for await(const a of e){t[a.index]=a;for(let e=t[r];void 0!==e;e=t[r]){if(!e.ok)throw e.error;r+=1}}return t.map(e=>e?.value)},Mn=(e,t)=>{const r=e=>t&&"string"==typeof e?e.toLowerCase():e;if(e.length<2)return!0;const a=r(e[0]);return e.every(e=>_(r(e),a))},Ln={values:{type:"array",elementNullPolicy:"value",description:"The values compared; null is comparable (null equals null)"},caseInsensitive:{type:"boolean",default:!1,description:"Fold string operands to one case before comparing (shallow)"}},Rn={name:"equal",alias:"=",category:"comparison",description:"Are all the values equal? Deep, structural, key-order-insensitive; a cross-type comparison is false",parameters:Ln,positionalParams:["...values"],returns:"boolean",validate:Sn,evaluate:({values:e,caseInsensitive:t})=>Mn(e,t)},Fn={name:"notEqual",alias:"!=",category:"comparison",description:'Are the values NOT all equal? The exact negation of equal (never "all distinct")',parameters:Ln,positionalParams:["...values"],returns:"boolean",validate:Sn,evaluate:({values:e,caseInsensitive:t})=>!Mn(e,t)},In=(e,t,r,a)=>({name:e,alias:t,category:"comparison",description:r,parameters:{values:{type:"array",elementNullPolicy:"propagate",constraints:{length:2,homogeneous:["number","string"]},description:"Exactly two operands: both numbers, or both strings (codepoint order)"},nullValueDefault:{type:["number","string"],required:!1,evaluation:"lazy",replacesNullAt:["values"],description:"Replaces a null operand before comparing"}},positionalParams:["...values"],returns:"boolean",evaluate:({values:e})=>{const[t,r]=e;return a(M(t,r))}}),Vn=/*#__PURE__*/In("greaterThan",">","Is the first value strictly greater than the second?",e=>e>0),Qn=/*#__PURE__*/In("greaterThanOrEqual",">=","Is the first value greater than or equal to the second?",e=>e>=0),Jn=/*#__PURE__*/In("lessThan","<","Is the first value strictly less than the second?",e=>e<0),Un=/*#__PURE__*/In("lessThanOrEqual","<=","Is the first value less than or equal to the second?",e=>e<=0),Bn={number:()=>0,string:()=>"",array:()=>[],object:()=>({})},Gn=t=>"number"==typeof t?"number":"string"==typeof t?"string":Array.isArray(t)?"array":e(t)?"object":void 0,Wn={name:"plus",alias:"+",category:"math",description:"Add numbers, concatenate strings or arrays, or shallow-merge objects — all operands must share one type",parameters:{values:{type:"array",elementNullPolicy:"propagate",constraints:{homogeneous:["number","string","array","object"]},description:"The operands; homogeneous: all numbers, strings, arrays or objects"},expect:{type:{literal:["number","string","array","object"]},required:!1,description:"Pin the mode: every operand must be this type, and an empty input yields its identity"},nullValueDefault:{type:["number","string","array","object"],required:!1,evaluation:"lazy",replacesNullAt:["values"],description:"Replaces any null operand before the addition"}},positionalParams:["...values"],returns:["number","string","array","object"],validate:({values:e,expect:t})=>void 0!==t?An({values:e}):Pn({values:e}),evaluate:({values:e,expect:t})=>{if(0===e.length){if(void 0===t)throw Cn("the sum","pin the mode with 'expect' to get its identity");return Bn[t]()}const r=t??Gn(e[0]);if(void 0===r)throw qn(`operands must be numbers, strings, arrays or objects — received ${Z(e[0])}`);const a=e.find(e=>Gn(e)!==r);if(void 0!==a)throw qn(`all operands must be ${r}s — received ${Z(a)}${void 0===t?" beside "+r+"s":""}`);switch(r){case"number":return e.reduce((e,t)=>e+t,0);case"string":return e.join("");case"array":return e.flat(1);case"object":return Object.assign({},...e)}}},Kn={name:"subtract",alias:"-",category:"math",description:"Subtract one number from another",parameters:{value:{type:["number","null"],description:"The main operand"},minus:{type:["number","null"],description:"The amount subtracted from value"}},positionalParams:["value","minus"],returns:"number",evaluate:({value:e,minus:t})=>e-t},Hn={name:"divide",alias:"/",category:"math",description:"Divide one number by another — true division; zero divisors fail",parameters:{value:{type:["number","null"],description:"The main operand"},by:{type:["number","null"],description:"The divisor"}},positionalParams:["value","by"],returns:"number",evaluate:({value:e,by:t})=>e/t},_n={name:"modulo",category:"math",description:"The floored remainder: the result takes the sign of mod, so modulo(-7, 3) is 2",parameters:{value:{type:["number","null"],description:"The main operand"},mod:{type:["number","null"],description:"The modulus"}},positionalParams:["value","mod"],returns:"number",evaluate:({value:e,mod:t})=>(e%t+t)%t},Xn={name:"multiply",alias:"*",category:"math",description:"Multiply numbers together — an empty input is 1, the empty product",parameters:{values:{type:"array",elementNullPolicy:"propagate",constraints:{homogeneous:["number"]},description:"The factors"},nullValueDefault:{type:"number",required:!1,evaluation:"lazy",replacesNullAt:["values"],description:"Replaces any null factor before multiplying"}},positionalParams:["...values"],returns:"number",validate:An,evaluate:({values:e})=>e.reduce((e,t)=>e*t,1)},Yn={name:"power",alias:"^",category:"math",description:"Raise a base to an exponent — overflow and complex results fail",parameters:{base:{type:["number","null"],description:"The number to raise"},exponent:{type:["number","null"],description:"The power to raise it to"}},positionalParams:["base","exponent"],returns:"number",evaluate:({base:e,exponent:t})=>e**t},Zn={name:"round",category:"math",description:"Round to a number of decimal places — ties go half away from zero; negative decimals round to tens, hundreds, …",parameters:{value:{type:["number","null"],description:"The number to round"},decimals:{type:"integer",default:0,description:"Decimal places to keep; negative values round to powers of ten"}},positionalParams:["value","decimals"],returns:"number",evaluate:({value:e,decimals:t})=>((e,t=0)=>{if(!Number.isFinite(e))return e;const r=e<0?-1:1,a=Math.round(W(Math.abs(e),t));return r*W(a,-t)})(e,t)},eo=(e,t,r,a)=>({name:e,category:"math",description:t,parameters:{value:{type:["number","null"],description:r}},positionalParams:["value"],returns:"number",evaluate:({value:e})=>a(e)}),to=/*#__PURE__*/eo("floor","Round down toward negative infinity","The number to round down",Math.floor),ro=/*#__PURE__*/eo("ceil","Round up toward positive infinity","The number to round up",Math.ceil),ao=/*#__PURE__*/eo("abs","The absolute value","The number",Math.abs),no=(e,t,r,a)=>({name:e,category:"math",description:r,parameters:{values:{type:"array",elementNullPolicy:"propagate",constraints:{homogeneous:["number","string"]},description:"The candidates: all numbers, or all strings (codepoint order)"},nullValueDefault:{type:["number","string"],required:!1,evaluation:"lazy",replacesNullAt:["values"],description:"Replaces any null candidate before comparing"}},positionalParams:["...values"],returns:["number","string"],validate:Pn,evaluate:({values:e})=>{const r=e;if(0===r.length)throw Cn(t);return r.reduce((e,t)=>a(M(t,e))?t:e)}}),oo=(e,t,r,a)=>({name:e,category:"string",description:t,parameters:{value:{type:["string","null"],description:r}},positionalParams:["value"],returns:"string",evaluate:({value:e})=>a(e)}),io={name:"split",category:"string",description:"Divide a string on a delimiter into an array of pieces — empty pieces are kept; an empty delimiter splits into code points",parameters:{value:{type:["string","null"],description:"The string to divide"},delimiter:{type:"string",default:" ",description:'Split on each occurrence; "" splits into code points'},trim:{type:"boolean",default:!0,description:"Trim whitespace from each piece"}},positionalParams:["value","delimiter"],returns:"array",evaluate:({value:e,delimiter:t,trim:r})=>{const a=""===t?G(e):e.split(t);return r?a.map(V):a}},so=e=>null!==e&&"object"==typeof e,lo=e=>Array.isArray(e.values)&&e.values.some(so)?[{severity:"error",parameter:"values",message:"a composite element renders as a placeholder, never as text — drill in, or join it explicitly"}]:[],co={name:"join",category:"string",description:"Render array elements to text and concatenate them with a delimiter",parameters:{values:{type:"array",elementNullPolicy:"value",description:'Elements of any type, rendered by the stringification table; a null renders "" and still occupies its slot'},delimiter:{type:"string",default:" ",description:"Placed between each adjacent pair — shares its contract with split"},nullValueDefault:{type:["string","number","boolean"],required:!1,evaluation:"lazy",replacesNullAt:["values"],description:'Rendered in place of a null element, instead of ""'}},positionalParams:["...values"],returns:"string",validate:e=>[...An(e),...lo(e)],evaluate:({values:e,delimiter:t},r)=>e.map((e,t)=>{const a=`[${t}]`;return null===e?r.trace.note({type:"render",token:a,rendered:"empty"}):so(e)&&r.trace.note({type:"render",token:a,rendered:"placeholder"}),I(e)}).join(t)},uo=e=>{const t=new Set,r=[];for(const a of e)if("imsu".includes(a)){if(t.has(a))return`duplicate regex flag '${a}'`;t.add(a)}else r.includes(a)||r.push(a);if(0===r.length)return;const a=r.includes("g")||r.includes("y")?" — all matches is mode: 'match'":"";return`unknown regex flag${1===r.length?"":"s"}: ${r.join(", ")}${a}`},po={type:"array",description:"The collection iterated over; a null input is a type error"},mo={type:"string",required:!1,evaluation:"structural",description:"Rename the bindings: as: 'row' binds $row and $rowIndex"},fo={type:"array",required:!1,evaluation:"lazy",replacesNullAt:["input"],description:"Used as the collection when input evaluates to null — typically []"},ho={type:"any",evaluation:"perElement",over:"input",description:"The predicate, per element — a truthiness position, so null is falsy",truthiness:!0},vo={name:"get",category:"data",description:"Read a path out of the evaluation data, or out of a supplied object — the dynamic face of a $data reference",parameters:{path:{type:["string","array","null"],description:"Dot and bracket segments, quoted keys and the [*] projection — or an array of segments, taken verbatim"},from:{type:"any",nullPolicy:"value",default:me,description:"The object searched instead of the evaluation data — replace, never merge; a null source is one where every path is missing"},default:{type:"any",required:!1,evaluation:"lazy",description:"The answer when the path is missing — a stored null passes through unchanged (firstOf replaces one); supplying it also opts out of strictDataPaths"}},positionalParams:q,returns:"any",validate:({path:e})=>jn(e,"path"),evaluate:({path:e,from:t,default:r},a)=>{const n=w(t,xn(e));if(n.found)return void 0===n.value?null:n.value;if(void 0!==r)return r.evaluate();if(a.options.strictDataPaths)throw new oa(`'${yo(e)}' is missing (strictDataPaths)`,{code:i.missingDataPath});return null}},yo=e=>"string"==typeof e?e:e.map(e=>String(e)).join("."),go={name:"buildObject",category:"data",description:"Assemble an object from computed key/value entries — for keys known only at runtime",parameters:{entries:{type:"array",constraints:{elementShape:{key:{type:["string","number","boolean"]},value:{type:"any"}}},description:'Objects with a "key" and a "value"; a null value keeps its key'}},positionalParams:["...entries"],returns:"object",validate:e=>[...Nn(e),...bo(e)],evaluate:({entries:e},t)=>{const r={};for(const a of e){const e=I(a.key);Object.hasOwn(r,e)&&t.trace.note({type:"key-overwrite",key:e}),r[e]=a.value}return r}},bo=e=>{const t=e.entries;if(!Array.isArray(t))return[];const r=new Set,a=new Set,n=[];for(const e of t){const t=e?.key;if("string"!=typeof t&&"number"!=typeof t&&"boolean"!=typeof t)continue;const o=I(t);r.has(o)&&!a.has(o)&&(a.add(o),n.push({severity:"warning",parameter:"entries",message:`duplicate key '${o}' — the last entry wins and the earlier one is dead`})),r.add(o)}return n},wo=(e,t)=>new oa(`cannot convert ${Z(e)} to ${t}`),ko=/*#__PURE__*/[{name:"and",category:"logic",description:"True when every value is truthy — operands run in parallel",parameters:{values:{type:"array",truthiness:!0,evaluation:"race",description:"Operands, judged by FigTree truthiness; null is falsy"}},positionalParams:["...values"],returns:"boolean",validate:An,evaluate:({values:e})=>Tn(e,!1)},{name:"or",category:"logic",description:"True when any value is truthy — operands run in parallel",parameters:{values:{type:"array",truthiness:!0,evaluation:"race",description:"Operands, judged by FigTree truthiness; null is falsy"}},positionalParams:["...values"],returns:"boolean",validate:An,evaluate:({values:e})=>Tn(e,!0)},{name:"not",alias:"!",category:"logic",description:"Negate the truthiness of a value",parameters:{value:{type:"any",truthiness:!0,description:"Judged by FigTree truthiness; null is falsy, so not(null) is true"}},positionalParams:["value"],returns:"boolean",evaluate:({value:e})=>!e},{name:"if",alias:"?",category:"logic",description:"Choose between two branches — only the chosen branch evaluates",parameters:{condition:{type:"any",truthiness:!0,description:"Judged by FigTree truthiness; null is falsy"},then:{type:"any",evaluation:"lazy",description:"The value when the condition holds"},else:{type:"any",evaluation:"lazy",default:null,description:"The value when it does not; omitted means null"}},positionalParams:["condition","then","else"],evaluate:({condition:e,then:t,else:r})=>e?t.evaluate():r.evaluate()},{name:"match",category:"logic",description:"Dispatch on a value — only the matching branch evaluates",parameters:{value:{type:["string","number","boolean","null"],nullPolicy:"value",description:"Matched against branch keys by its canonical string form"},branches:{type:"object",evaluation:"lazyEntries",description:"A literal map of branches, or an expression computing one"},default:{type:"any",required:!1,evaluation:"lazy",description:"The branch taken when none matches; absent means failure"}},positionalParams:["value","branches","default"],evaluate:({value:e,branches:t,default:r})=>{const a=null===e?null:I(e);if(null!==a&&Object.hasOwn(t,a))return t[a].evaluate();if(void 0!==r)return r.evaluate();throw new oa(`no branch matches ${null===a?"null":`'${a}'`}, and no default was supplied`)}},{name:"firstOf",category:"logic",description:"The first candidate that is not null (SQL COALESCE) — later candidates never evaluate",parameters:{values:{type:"array",evaluation:"lazyElements",description:"Candidates, tried in order; only null is skipped"}},positionalParams:["...values"],validate:An,evaluate:async({values:e})=>{for(const t of e){const e=await t.evaluate();if(null!==e)return e}return null}},Rn,Fn,Vn,Qn,Jn,Un,Wn,Kn,Xn,Hn,_n,Yn,Zn,to,ro,ao,/*#__PURE__*/no("min","the minimum","The smallest of the values — numbers numerically, strings in codepoint order",e=>e<0),/*#__PURE__*/no("max","the maximum","The largest of the values — numbers numerically, strings in codepoint order",e=>e>0),{name:"buildString",category:"string",description:"Render a template, filling its tokens — the result is always a string",parameters:{template:{type:["string","null"],description:"The text, with %N or {{name}} tokens; in a literal template, {{$data.x}} is that reference"},substitutions:{type:["array","object"],default:[],elementNullPolicy:"value",description:"An array pairs with %N tokens, an object with {{name}} tokens; the mode dispatches on which arrives"},trim:{type:"boolean",default:!1,description:"Trim whitespace from each rendered value, never from the template text"},closeGaps:{type:"boolean",default:!1,description:"A value that renders empty also takes one run of adjacent template whitespace"},nullValueDefault:{type:["string","number","boolean"],required:!1,evaluation:"lazy",replacesNullAt:["substitutions"],description:'Rendered in place of a null value, instead of ""'}},positionalParams:["template","...substitutions"],returns:"string",evaluate:({template:e,substitutions:t,trim:r,closeGaps:a},n)=>{const o=Array.isArray(t)?t:void 0,i=void 0===o?t:void 0,s=[];for(const t of ye(e)){if("text"===t.kind){s.push({text:t.text,site:!1});continue}if(!("positional"===t.kind?void 0!==o&&t.index>=1&&t.index<=o.length:void 0!==i&&Object.hasOwn(i,t.body))){n.trace.note({type:"render",token:t.raw,rendered:"literal"}),s.push({text:t.raw,site:!1});continue}const e="positional"===t.kind?o[t.index-1]:i[t.body],a=I(e);so(e)&&n.trace.note({type:"render",token:t.raw,rendered:"placeholder"});const l=r?V(a):a;""===l&&n.trace.note({type:"render",token:t.raw,rendered:"empty"}),s.push({text:l,site:!0,token:t.raw})}if(a)for(const e of(e=>{const t=[];for(let r=0;r<e.length;r++){const a=e[r];if(!a.site||""!==a.text)continue;const n=e[r-1];if(void 0!==n&&!n.site){const e=U(n.text);if(e!==n.text){n.text=e,t.push(a.token);continue}}const o=e[r+1];if(void 0!==o&&!o.site){const e=B(o.text);e!==o.text&&t.push(a.token),o.text=e}}return t})(s))n.trace.note({type:"render",token:e,rendered:"gap-closed"});return s.map(e=>e.text).join("")}},io,co,/*#__PURE__*/oo("lower","Lowercase a string — Unicode default case mapping, locale-independent","The string to lowercase",e=>e.toLowerCase()),/*#__PURE__*/oo("upper","Uppercase a string — Unicode default case mapping, locale-independent","The string to uppercase",e=>e.toUpperCase()),/*#__PURE__*/oo("trim","Strip whitespace (the JS trim set) from both ends of a string","The string to trim",V),{name:"regex",category:"string",description:"Test, extract or match a string against a regular expression",parameters:{value:{type:["string","null"],description:"The subject string"},pattern:{type:["string","null"],description:"The regular expression source"},flags:{type:"string",default:"",description:"The admitted subset: i, m, s, u"},mode:{type:{literal:["test","extract","match"]},default:"test",description:"test gives a boolean, extract the first matching substring, match every one of them"},noMatchDefault:{type:"any",required:!1,default:null,nullPolicy:"value",evaluation:"lazy",description:"The extract answer when nothing matches — a matched empty string still passes through"}},positionalParams:["value","pattern"],returns:["boolean","string","array","null"],validate:({pattern:e,flags:t})=>{const r=[],a="string"==typeof t?uo(t):void 0;if(void 0!==a&&r.push({severity:"error",parameter:"flags",message:a}),"string"==typeof e)try{new RegExp(e,"string"==typeof t&&void 0===a?t:"")}catch(e){r.push({severity:"error",parameter:"pattern",message:`pattern does not compile: ${e.message}`})}return r},evaluate:({value:e,pattern:t,flags:r,mode:a,noMatchDefault:n})=>{const o=uo(r);if(void 0!==o)throw new oa(o);const i=e=>{try{return new RegExp(t,r+e)}catch(e){throw new oa(`pattern does not compile: ${e.message}`)}};switch(a){case"test":return i("").test(e);case"extract":{const t=i("").exec(e);return null===t?n.evaluate():t[0]}case"match":return[...e.matchAll(i("g"))].map(e=>e[0])}}},{name:"length",category:"array",description:"An array's element count, or a string's Unicode code-point count",parameters:{value:{type:["string","array","null"],description:"The array or string measured"}},positionalParams:["...value"],returns:"integer",evaluate:({value:e})=>"string"==typeof e?G(e).length:e.length},{name:"map",category:"array",description:"Transform every element of an array",parameters:{input:po,as:mo,nullInputDefault:fo,each:{type:"any",evaluation:"perElement",over:"input",description:"Evaluated per element, with $element and $index bound"}},positionalParams:["input","each"],returns:"array",validate:Dn,evaluate:({each:e})=>zn(e.settle())},{name:"filter",category:"array",description:"Keep the elements of an array whose predicate is truthy",parameters:{input:po,as:mo,nullInputDefault:fo,each:ho},positionalParams:["input","each"],returns:"array",validate:Dn,evaluate:async({input:e,each:t})=>{const r=await zn(t.settle());return e.filter((e,t)=>r[t])}},{name:"find",category:"array",description:"The first element of an array whose predicate is truthy",parameters:{input:po,as:mo,nullInputDefault:fo,each:ho,noMatchDefault:{type:"any",required:!1,default:null,evaluation:"lazy",description:"The answer when nothing matches; a found null passes through unchanged"}},positionalParams:["input","each"],validate:Dn,evaluate:async({input:e,each:t,noMatchDefault:r})=>{const a=new Array(e.length);let n=0;for await(const r of t.settle()){a[r.index]=r;for(let t=a[n];void 0!==t;t=a[n]){if(!t.ok)throw t.error;if(!0===t.value)return e[n];n+=1}}return r.evaluate()}},{name:"some",category:"array",description:"True when any element satisfies the predicate",parameters:{input:po,as:mo,nullInputDefault:fo,each:ho},positionalParams:["input","each"],returns:"boolean",validate:Dn,evaluate:({each:e})=>Tn(e.settle(),!0)},{name:"every",category:"array",description:"True when every element satisfies the predicate",parameters:{input:po,as:mo,nullInputDefault:fo,each:ho},positionalParams:["input","each"],returns:"boolean",validate:Dn,evaluate:({each:e})=>Tn(e.settle(),!1)},vo,go,{name:"convert",category:"other",description:"Convert a value to a number, string, boolean or array — strict: a failed conversion is an error, never a guess",parameters:{value:{type:"any",nullPolicy:e=>"boolean"===e?"value":"propagate",description:"The value to convert; null propagates except for boolean, where it is false"},to:{type:{literal:["number","string","boolean","array"]},description:"The target type"}},positionalParams:["value","to"],returns:["number","string","boolean","array"],evaluate:({value:t,to:r})=>{switch(r){case"number":if("number"==typeof t)return t;if("boolean"==typeof t)return t?1:0;if("string"==typeof t){const e=t.trim(),r=""===e?NaN:Number(e);if(Number.isNaN(r))throw new oa(`'${t}' is not a numeric string — use regex to extract a number from text`);return r}throw wo(t,"number");case"string":if(Array.isArray(t)||e(t))throw new oa(`cannot convert ${Z(t)} to string — a cast is not a render; use buildString or join`);if("object"==typeof t)throw wo(t,"string");return I(t);case"boolean":if("string"==typeof t){const e=t.trim().toLowerCase();if("true"===e)return!0;if("false"===e)return!1}return z(t);case"array":return Array.isArray(t)?t:[t]}}}].map(fn),$o=(e,t)=>{const r=((e,t)=>{const r={...e};for(const[e,a]of Object.entries(t)){if(void 0===a)continue;if("data"===e||!n(a)){r[e]=a;continue}const t=r[e],o=n(t)?{...t}:{};for(const[e,t]of Object.entries(a))void 0!==t&&(o[e]=t);r[e]=o}return r})(null===e?{}:e.options,t);Eo(r);const a=xo(r);if(null!==e&&!(e=>void 0!==e.operators||void 0!==e.fragments||void 0!==e.operatorDefaults)(t))return{options:r,evaluation:a,registry:e.registry,compileCache:e.compileCache};const o=dr({operators:r.operators??[ko],...void 0!==r.operatorDefaults?{operatorDefaults:r.operatorDefaults}:{},...void 0!==r.fragments?{fragments:r.fragments}:{}});return{options:r,evaluation:a,registry:o,compileCache:new er({compile:e=>jo(e,o),probe:e=>ge(e,o)})}},xo=e=>{const t={...e};return delete t.operators,delete t.fragments,t},jo=(e,t)=>{const r=Ce(e,t);return Dt(r),r};class Po{state;results;version=X;constructor(e={}){this.state=$o(null,e),this.results=new rn(Za(e.cache))}updateOptions(e={}){const t=$o(this.state,e),r=Za(t.options.cache);this.state=t,this.results.configure(r)}clearCache(){this.results.clear()}getOptions(){return(e=>{const t={};for(const[r,a]of Object.entries(e))t[r]=n(a)?{...a}:a;return t})(this.state.evaluation)}getOperators(){return[...this.state.registry.operators.values()].map(e=>{const{definition:t,instanceDefaults:r}=e,a={name:t.name,category:t.category,description:t.description,parameters:sn(t.parameters,r),restParam:t.restParam,timeoutParam:t.timeoutParam,useCache:t.useCache,cache:t.cache,returns:t.returns,hasValidate:void 0!==t.validate};return void 0!==t.alias&&(a.alias=t.alias),void 0!==t.metadata&&(a.metadata=t.metadata),void 0!==t.positionalParams&&(a.positionalParams=t.positionalParams),void 0!==r&&(Object.hasOwn(r,"useCache")&&(a.instanceUseCache=r.useCache),Object.hasOwn(r,"fallback")&&(a.instanceFallback=r.fallback)),a})}getFragments(){return[...this.state.registry.fragments.values()].map(e=>{const t={name:e.name,parameters:Object.fromEntries(Object.entries(e.parameters).map(([e,t])=>[e,{...t}])),returns:e.returns,warnings:[...e.warnings],dependencies:on(e.dependencies)};return void 0!==e.description&&(t.description=e.description),void 0!==e.metadata&&(t.metadata=e.metadata),t})}validate(e,t){const r=void 0===t?this.state.evaluation:qo(this.state.evaluation,t),a=jo(e,this.state.registry),n=un(a,r,e=>e.issue);return{valid:!n.some(e=>"error"===e.severity),issues:n,timeoutShielded:a.timeoutShielded}}getDependencies(e){return on(Ce(e,this.state.registry).dependencies)}isEvaluable(e){const t=Ce(e,this.state.registry);return t.holes.length>0||t.hasErrors}evaluate(e,t){const{state:r}=this;return Oo(r.evaluation,this.results,e,t,()=>r.compileCache.resolve(e),()=>jo(e,r.registry))}compile(e){const{state:t}=this;return No(e,t.compileCache.resolve(e),t.evaluation,t.registry,this.results)}}const Oo=async(e,t,r,a,n,o)=>{const i=void 0===a?e:qo(e,a),s="report"===i.mode,l=s||!0===i.trace,c=n(),u="inert"===c.kind&&!0===i.trace?{kind:"artifact",artifact:o()}:c;if("inert"===u.kind){if(void 0!==i.maxDepth&&u.depth>i.maxDepth){const e=cn(u.depth,i.maxDepth);if(!s)throw Mo(e,[e]);return So(null,[Mo(e)])}return l?So(r,[]):r}const{artifact:d}=u;if(d.hasErrors||void 0!==i.maxDepth||void 0!==i.maxNodes){const e=[...ln(d,i),...d.issues.map(e=>e.issue)],t=e.filter(e=>"error"===e.severity);if(t.length>0){if(!s)throw Mo(t[0],e);return So(null,t.map(e=>Mo(e)))}}const p=await Ba(d,i,t);return l?p:p.result};let Ao;class Do{#t;#r;#a;#n;#o;#i;#s;constructor(e,t,r,a,n){this.#t=e,this.#r=t,this.#a=r,this.#n=a,this.#o=n,Ao??=(e,t)=>{if("object"!=typeof e||null===e||!(#r in e))return;const r=void 0===t?e.#a:qo(e.#a,t);return{expression:e.#t,artifact:e.#l(),options:r}}}get expression(){return this.#t}get issues(){return this.#s??=this.#l().issues.map(e=>e.issue)}get hasErrors(){return this.#l().hasErrors}evaluate(e){return Oo(this.#a,this.#o,this.#t,e,()=>this.#r,()=>this.#l())}getDependencies(){return on(this.#l().dependencies)}#l(){return"artifact"===this.#r.kind?this.#r.artifact:this.#i??=jo(this.#t,this.#n)}}const No=(e,t,r,a,n)=>new Do(e,t,r,a,n),So=(e,t)=>({result:e,errors:t}),Co=/*#__PURE__*/new Set(Object.keys({data:0,signal:0,timeout:0,mode:0,trace:0})),qo=(e,t)=>{let r;for(const a in t){const n=t[a];if(void 0!==n){if(!Co.has(a))throw To(a);r??={...e},r[a]=n}}return void 0===r?e:(Eo(t),r)},To=e=>new j({code:i.invalidOptions,message:`'${e}' is not a per-call option — a call may supply data, signal, timeout, mode and trace; configure the rest at construction or via updateOptions()`,path:[]}),Eo=e=>{const{timeout:t,signal:r}=e;if(void 0!==t&&("number"!=typeof t||!Number.isFinite(t)||t<=0))throw new j({code:i.invalidOptions,message:"'timeout' must be a positive number of milliseconds",path:[]});if(void 0!==r&&!zo(r))throw new j({code:i.invalidOptions,message:"'signal' must be an AbortSignal",path:[]})},zo=e=>"object"==typeof e&&null!==e&&"boolean"==typeof e.aborted&&"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,Mo=(e,t)=>new j({code:e.code,message:e.message,path:e.path,...void 0!==e.operator?{operator:e.operator}:{},...void 0!==t?{issues:t}:{}}),Lo=/[a-z]Default$/,Ro=/*#__PURE__*/new Set(["eager","race","lazy","lazyElements","lazyEntries","perElement","structural"]),Fo=/*#__PURE__*/new Set(pe),Io=e=>"array"===e||"any"===e||!!Array.isArray(e)&&(e.includes("array")||e.includes("any")),Vo=e=>"array"===e||"object"===e||"any"===e||!!Array.isArray(e)&&(e.includes("array")||e.includes("object")||e.includes("any")),Qo=(e,t)=>{const[r]=e,a=e.length-1,n=a>0?`${r.message} (+ ${a} more issue${1===a?"":"s"})`:r.message;throw new j({code:i.invalidDefinition,message:n,path:r.path,...void 0!==t?{operator:t}:{},issues:e})};function Jo(t){if(he(t))return t;const a=[],n=e(t)?t.name:void 0,o="string"==typeof n?n:void 0,s=(e,t,r,n)=>{a.push({severity:"error",code:e,message:t,path:r,...void 0!==o?{operator:o}:{},...void 0!==n?{parameter:n}:{}})};e(t)||(s(i.invalidDefinition,"a definition must be a plain object",[]),Qo(a));const l=t;"string"!=typeof l.name&&s(i.invalidDefinition,"'name' is required and must be a string",["name"]),"string"==typeof l.description&&""!==l.description||s(i.invalidDefinition,"'description' is required and must be non-empty",["description"]),e(l.parameters)||s(i.invalidDefinition,"'parameters' is required and must be an object of declarations (may be {})",["parameters"]),"function"!=typeof l.evaluate&&s(i.invalidDefinition,"'evaluate' is required and must be a function",["evaluate"]),a.length>0&&Qo(a,o),"string"!=typeof l.category?s(i.invalidDefinition,`'category' is required and must be one of ${[...Fo].join(", ")}`,["category"]):Fo.has(l.category)||s(i.invalidDefinition,`'${l.category}' is not a category — expected one of ${[...Fo].join(", ")}`,["category"]),void 0!==l.alias&&"string"!=typeof l.alias&&s(i.invalidDefinition,"'alias' must be a string",["alias"]),void 0!==l.useCache&&"boolean"!=typeof l.useCache&&s(i.invalidDefinition,"'useCache' must be a boolean",["useCache"]),void 0!==l.cache&&"auto"!==l.cache&&"manual"!==l.cache&&s(i.invalidDefinition,"'cache' must be 'auto' or 'manual'",["cache"]),void 0===l.metadata||e(l.metadata)||s(i.invalidDefinition,"'metadata' must be a plain object",["metadata"]),void 0===l.positionalParams||Array.isArray(l.positionalParams)&&!l.positionalParams.some(e=>"string"!=typeof e)||s(i.invalidDefinition,"'positionalParams' must be an array of parameter names",["positionalParams"]),void 0!==l.timeoutParam&&"string"!=typeof l.timeoutParam&&s(i.invalidDefinition,"'timeoutParam' must be a parameter name",["timeoutParam"]),void 0!==l.validate&&"function"!=typeof l.validate&&s(i.invalidDefinition,"'validate' must be a function",["validate"]),void 0===l.returns||ne(l.returns)||s(i.invalidDefinition,"'returns' must be a metadata-vocabulary type",["returns"]);const c=(e,t,r)=>{e===me?s(i.invalidDefinition,"the EvaluationData sentinel is legal only as a parameter 'default'",t,r):Array.isArray(e)&&e.forEach((e,a)=>{e===me&&c(e,[...t,a],r)})};for(const[e,t]of Object.entries(l))"parameters"!==e&&"metadata"!==e&&c(t,[e]);const u=(e,t)=>{const a=r(e);a.ok?$.has(e)&&s(i.reservedName,`'${e}' is a reserved name`,t):s(i.invalidName,`'${e}': ${a.reason}`,t)};"string"==typeof l.name&&u(l.name,["name"]),"string"==typeof l.alias&&u(l.alias,["alias"]);const d=l.parameters,p={};for(const[t,a]of Object.entries(d)){const n=["parameters",t],o=r(t);o.ok?x.has(t)&&s(i.reservedName,`'${t}' is a reserved node key and cannot name a parameter`,n,t):s(i.invalidName,`'${t}': ${o.reason}`,n,t),e(a)?p[t]=a:s(i.invalidDefinition,`the declaration for '${t}' must be a plain object`,n,t)}const m={};for(const[t,r]of Object.entries(p)){const a=["parameters",t],n=e=>[...a,e],o=r;for(const[e,r]of Object.entries(o))"default"!==e&&"metadata"!==e&&c(r,n(e),t);let l=!0;void 0===o.type||ne(o.type)||(s(i.invalidDefinition,"'type' must be a metadata-vocabulary type",n("type"),t),l=!1),l&&(m[t]=o.type??"any");let u=!1;if(void 0!==o.constraints){const e=ce(o.constraints);e.ok?u=!0:s(i.invalidDefinition,`'constraints' is malformed: expected ${e.expected}, got ${e.actual}`,n("constraints"),t)}void 0!==o.required&&"boolean"!=typeof o.required&&s(i.invalidDefinition,"'required' must be a boolean",n("required"),t),void 0!==o.description&&"string"!=typeof o.description&&s(i.invalidDefinition,"'description' must be a string",n("description"),t),void 0===o.metadata||e(o.metadata)||s(i.invalidDefinition,"'metadata' must be a plain object",n("metadata"),t);const d="default"in o;if(d&&!0===o.required&&s(i.invalidDefinition,"a 'default' contradicts 'required: true' — a default implies the parameter is optional",n("default"),t),d&&o.default!==me){const e=m[t];if(void 0!==e){const r=oe(o.default,e);if(r.ok){if(u&&void 0!==o.constraints){const e=ie(o.default,o.constraints);e.ok||s(i.typeCheck,`'default' violates the declared constraints: expected ${e.expected}, got ${e.actual}`,n("default"),t)}}else s(i.typeCheck,`'default' does not satisfy the declared type: expected ${r.expected}, got ${r.actual}`,n("default"),t)}}if(void 0===o.evaluation||Ro.has(o.evaluation)||s(i.invalidDefinition,`'evaluation' must be one of ${[...Ro].join(", ")}`,n("evaluation"),t),void 0!==o.truthiness&&"boolean"!=typeof o.truthiness&&s(i.invalidDefinition,"'truthiness' must be a boolean",n("truthiness"),t),void 0!==o.over&&"string"!=typeof o.over&&s(i.invalidDefinition,"'over' must be a parameter name",n("over"),t),void 0===o.replacesNullAt||Array.isArray(o.replacesNullAt)&&!o.replacesNullAt.some(e=>"string"!=typeof e)||s(i.invalidDefinition,"'replacesNullAt' must be an array of sibling parameter names",n("replacesNullAt"),t),void 0!==o.nullPolicy){const e=o.nullPolicy;"function"==typeof e||mn.has(e)||s(i.invalidNullPolicy,"'nullPolicy' must be 'propagate', 'value' or a conditional function",n("nullPolicy"),t);const r=m[t];void 0===r||re(r)||s(i.invalidNullPolicy,"'nullPolicy' is legal only where the declared type names 'null' — a type without 'null' is the reject declaration",n("nullPolicy"),t),!0===o.truthiness&&"propagate"===e&&s(i.invalidNullPolicy,"'truthiness' implies null policy 'value' (null is falsy) — declaring 'propagate' is a conflict",n("nullPolicy"),t)}if(void 0!==o.elementNullPolicy){mn.has(o.elementNullPolicy)||s(i.invalidNullPolicy,"'elementNullPolicy' must be 'propagate' or 'value' — the conditional form is not admitted here",n("elementNullPolicy"),t);const e=m[t];void 0===e||Vo(e)||s(i.invalidNullPolicy,"'elementNullPolicy' applies to container parameters only",n("elementNullPolicy"),t)}}if(Array.isArray(l.positionalParams)&&l.positionalParams.every(e=>"string"==typeof e)){const e=new Set,t=l.positionalParams;t.forEach((r,a)=>{const n=r.startsWith(pn),o=n?r.slice(3):r;n&&a!==t.length-1&&s(i.invalidDefinition,`the rest entry '${r}' must be the last positional entry`,["positionalParams",a]),o in p||s(i.invalidDefinition,`positional entry '${r}' names no declared parameter`,["positionalParams",a]),e.has(o)&&s(i.invalidDefinition,`duplicate positional entry '${r}'`,["positionalParams",a]),e.add(o)})}for(const[e,t]of Object.entries(p)){const r=["parameters",e],a="perElement"===t.evaluation;if(void 0!==t.over&&"string"==typeof t.over)if(a){const a=t.over;if(a in p&&a!==e){const t=m[a];void 0===t||Io(t)||s(i.invalidDefinition,`the 'over' target '${a}' must admit an array`,[...r,"over"],e)}else s(i.invalidDefinition,`'over' names no sibling parameter ('${a}')`,[...r,"over"],e)}else s(i.invalidDefinition,"'over' is legal only with evaluation: 'perElement'",[...r,"over"],e);else a&&s(i.invalidDefinition,"evaluation: 'perElement' requires 'over' to name the iterated sibling",[...r,"evaluation"],e)}for(const[e,t]of Object.entries(p)){if(void 0===t.replacesNullAt)continue;if(!Array.isArray(t.replacesNullAt)||t.replacesNullAt.some(e=>"string"!=typeof e))continue;const r=["parameters",e,"replacesNullAt"];"lazy"!==t.evaluation&&s(i.invalidDefinition,"a 'replacesNullAt' holder must declare evaluation: 'lazy'",r,e);(t.required??!("default"in t))&&s(i.invalidDefinition,"a 'replacesNullAt' holder must be optional",r,e),"default"in t&&s(i.invalidDefinition,"a 'replacesNullAt' holder may not carry a 'default' — it is presence-sensitive by construction",r,e),t.replacesNullAt.forEach((t,a)=>{t===e?s(i.invalidDefinition,"'replacesNullAt' may not target the holder itself",[...r,a],e):t in p||s(i.invalidDefinition,`'replacesNullAt' target '${t}' names no sibling parameter`,[...r,a],e)})}for(const[e,t]of Object.entries(p))Lo.test(e)&&"lazy"!==t.evaluation&&s(i.invalidDefinition,`'${e}' is named for the '…Default' family, so it must declare evaluation: 'lazy' — add 'replacesNullAt', read it as a LazyValue in the body, or rename it`,["parameters",e,"evaluation"],e);const f=hn(p,m,s);if("string"==typeof l.timeoutParam){void 0===p[l.timeoutParam]?s(i.invalidDefinition,`'timeoutParam' names no declared parameter ('${l.timeoutParam}')`,["timeoutParam"]):"integer"!==m[l.timeoutParam]&&s(i.invalidDefinition,"the 'timeoutParam' target must be 'integer'-typed",["timeoutParam"])}return a.length>0&&Qo(a,o),vn(l,f)}const Uo=e=>new oa(`request failed (${e.status}): ${e.url}`,{errorData:{status:e.status,statusText:e.statusText,url:e.url,response:e.payload}}),Bo=(e,t)=>{const r=t instanceof Error?t.message:String(t),a=t??{},n={driver:e};for(const e of["code","table","column","constraint"])"string"==typeof a[e]&&(n[e]=a[e]);return new oa(`${e}: ${r}`,{errorData:n})},Go=(e,t=500)=>e.length<=t?e:`${e.slice(0,t)}… (${e.length} characters)`;class Wo{supplied;constructor(e){if(void 0===e&&"function"!=typeof globalThis.fetch)throw new oa("FetchClient(): this runtime has no global fetch — pass one, new FetchClient(myFetch), or use another client such as new AxiosClient(axios)");this.supplied=e}request=async e=>{const t=this.supplied??globalThis.fetch,r=await t.call(globalThis,e.url,{method:e.method.toUpperCase(),headers:e.headers,...void 0!==e.body?{body:JSON.stringify(e.body)}:{},signal:e.signal}),a=await r.text();if(!r.ok)throw Uo({status:r.status,statusText:r.statusText,url:r.url||e.url,payload:_o(a)});return Ho(a,r.url||e.url,r.status)}}class Ko{axios;constructor(e){if(this.axios=e,"function"!=typeof e||"function"!=typeof e.isAxiosError)throw new oa("AxiosClient(axios): pass the axios import itself — new AxiosClient(axios)")}request=async e=>{try{const t=await this.axios({url:e.url,method:e.method,headers:e.headers,...void 0!==e.body?{data:e.body}:{},signal:e.signal});return""===t.data||void 0===t.data?null:t.data}catch(t){if(this.axios.isAxiosError(t)&&t.response)throw Uo({status:t.response.status,statusText:t.response.statusText,url:t.config?.url??e.url,payload:t.response.data});throw t}}}const Ho=(e,t,r)=>{if(""===e.trim())return null;try{return JSON.parse(e)}catch{throw new oa(`response was not JSON (${r}): ${t}`,{errorData:{status:r,url:t,response:Go(e)}})}},_o=e=>{if(""===e.trim())return null;try{return JSON.parse(e)}catch{return Go(e)}},Xo=/^https?:\/\//i,Yo=(e,t,r)=>{const a=Xo.test(e)?e:Zo(r,e),n=ei(t),o=""===n?a:`${a}${a.includes("?")?"&":"?"}${n}`;try{new URL(o)}catch{throw new oa(`'${o}' is not a valid URL`,{code:i.typeCheck})}return o},Zo=(e,t)=>{if(void 0===e||""===e)throw new oa(`'${t}' is a relative URL and no http.baseEndpoint is configured`,{code:i.typeCheck});return""===t?e:`${e.replace(/\/$/,"")}/${t.replace(/^\//,"")}`},ei=e=>{if(void 0===e)return"";const t=new URLSearchParams;for(const[r,a]of Object.entries(e))null!=a&&t.append(r,ai(a,`query['${r}']`,"query"));return t.toString()},ti=(...e)=>{const t={};for(const r of e)if(void 0!==r)for(const[e,a]of Object.entries(r))null!=a?t[e]=ai(a,`headers['${e}']`,"header"):delete t[e];return t},ri=e=>({Accept:"application/json",...e?{"Content-Type":"application/json"}:{}}),ai=(e,t,r)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return I(e);throw new oa(`${t} is ${Z(e)} — a ${r} value must be a string, number or boolean; render it explicitly (join) or supply a fully-formed URL`,{code:i.typeCheck})},ni=e=>({method:e.method,url:e.url,headers:Object.fromEntries(Object.entries(e.headers).sort(([e],[t])=>e<t?-1:e>t?1:0)),...void 0!==e.body?{body:e.body}:{}}),oi=t=>Array.isArray(t)?t.length>0:e(t)?Object.keys(t).length>0:null!=t,ii=(e,t)=>{if(void 0===t)return e;const r=w(e,xn(t));return r.found?void 0===r.value?null:r.value:null},si=(t,r)=>{if(!e(t))throw new oa("a row was not an object");const a=Object.values(t);if(1!==a.length)throw new oa(`shape: '${r}' needs a single-column result — this row has ${a.length} columns; name the one column you want in the SQL`,{code:i.typeCheck});return a[0]},li={type:"integer",required:!1,description:"Per-request deadline in ms; expiry is an ordinary failure this node’s fallback catches"},ci={type:["string","array"],required:!1,description:"Dot/bracket path or segments array applied to the response; a miss is null"},ui=e=>({name:"http",category:"io",description:"One HTTP request — GET or POST — returning the parsed JSON response",parameters:{url:{type:"string",description:"A full http(s) URL is used verbatim; anything else — including an empty string — joins http.baseEndpoint"},method:{type:{literal:["get","post"]},default:"get",description:"Lowercase; the mutating verbs are deliberately absent — an expression is a read"},query:{type:"object",required:!1,elementNullPolicy:"value",description:"Query-string pairs; a null value omits its pair, a composite one is an error"},body:{type:["string","number","boolean","array","object"],required:!1,description:"The JSON payload; a whole-null body means NO body, while nulls inside one are JSON nulls"},headers:{type:"object",required:!1,elementNullPolicy:"value",description:"Merged over the http.headers option per key; a null value removes an inherited pair"},returnPath:ci,timeout:li},positionalParams:["url"],timeoutParam:"timeout",useCache:!0,cache:"manual",returns:"any",validate:({returnPath:e,method:t,body:r})=>[...jn(e,"returnPath"),...mi(t,r)],evaluate:async({url:t,method:r,query:a,body:n,headers:o,returnPath:s},l)=>{if("get"===r&&void 0!==n)throw new oa("a GET carries no body — did you mean method: 'post'?",{code:i.typeCheck});const c={method:r,url:Yo(t,a,l.options.http?.baseEndpoint),headers:ti(ri(void 0!==n),l.options.http?.headers,o),...void 0!==n?{body:n}:{}},u=await l.cache.memo(ni(c),()=>(vi(l,c),e.request({...c,signal:l.signal})));return ii(u,s)}}),di=t=>({name:"graphQL",category:"io",description:"One GraphQL query — a POST of { query, variables } — returning the data field",parameters:{query:{type:"string",description:"The GraphQL document — the protocol’s own word, as sql.query is"},variables:{type:"object",required:!1,elementNullPolicy:"value",description:"Query variables; a null value is CARRIED as JSON null, a nullable argument being meaningful GraphQL"},url:{type:"string",required:!1,description:"Per-node endpoint override; unset means the graphQL.endpoint option"},headers:{type:"object",required:!1,elementNullPolicy:"value",description:"Merged over http.headers then graphQL.headers; a null value removes a pair"},returnPath:ci,timeout:li},positionalParams:["query","variables"],timeoutParam:"timeout",useCache:!0,cache:"manual",returns:"any",validate:({returnPath:e})=>jn(e,"returnPath"),evaluate:async({query:r,variables:a,url:n,headers:o,returnPath:i},s)=>{const l=n??s.options.graphQL?.endpoint;if(void 0===l)throw new oa("no endpoint — supply url, or set the graphQL.endpoint option");const c={method:"post",url:Yo(l,void 0,s.options.http?.baseEndpoint),headers:ti(ri(!0),s.options.http?.headers,s.options.graphQL?.headers,o),body:{query:r,...oi(a)?{variables:a}:{}}},u=await s.cache.memo(ni(c),async()=>(vi(s,c),(t=>{if(!e(t))throw new oa("the GraphQL response was not an object");const r=t.errors;if(Array.isArray(r)&&r.length>0){const e=r[0]?.message;throw new oa(`the GraphQL response carried ${r.length} error${1===r.length?"":"s"}`+("string"==typeof e?`: ${e}`:""),{errorData:{errors:r}})}if(!("data"in t))throw new oa("the GraphQL response carried neither data nor errors");return t.data??null})(await t.request({...c,signal:s.signal}))));return ii(u,i)}}),pi=e=>({name:"sql",category:"io",description:"One SQL query against the registered connection. Expressions are READS — give the connection a read-only role and run mutations host-side",parameters:{query:{type:"string",description:"SQL text with the driver’s own placeholders — FigTree never parses SQL"},values:{type:["array","object"],required:!1,elementNullPolicy:"value",description:"Bind values — positional as an array, named as an object; a null binds SQL NULL"},shape:{type:{literal:["rows","firstRow","column","firstValue"]},default:"rows",description:"rows: every row object; firstRow: the first; column: one column’s values; firstValue: one scalar"},noRowDefault:{type:"any",required:!1,default:null,nullPolicy:"value",evaluation:"lazy",description:"The answer when firstRow / firstValue find no row — never for rows / column, never on failure"},timeout:li},positionalParams:["query","...values"],timeoutParam:"timeout",useCache:!0,cache:"manual",returns:"any",evaluate:async({query:t,values:r,shape:a,noRowDefault:n},o)=>{const i={text:t,...oi(r)?{values:r}:{}};return(async(e,t,r)=>{switch(t){case"rows":return e;case"firstRow":return 0===e.length?r.evaluate():e[0];case"column":return e.map(e=>si(e,"column"));case"firstValue":return 0===e.length?r.evaluate():si(e[0],"firstValue")}})(await o.cache.memo(i,()=>(o.trace.note({type:"query",text:i.text}),e.query({...i,signal:o.signal}))),a,n)}}),mi=(e,t)=>void 0!==t&&"get"===e?[{severity:"error",parameter:"body",message:"a GET carries no body — add method: 'post', or drop the body"}]:[],fi=(e=new Wo)=>[fn(ui(e)),fn(di(e))],hi=e=>[fn(pi(e))],vi=(e,t)=>{e.trace.note({type:"request",method:t.method,url:t.url,headers:Object.keys(t.headers)})};class yi{client;constructor(e){if(this.client=e,"function"!=typeof e?.query)throw new oa("PostgresConnection(client): pass a connected node-postgres Client or Pool")}query=async e=>{if(void 0!==e.values&&!Array.isArray(e.values))throw new oa("postgres takes positional binds ($1, $2, …) — an object of named binds needs a driver that supports them");try{const t=await this.client.query({text:e.text,...void 0!==e.values?{values:e.values}:{}});return t?.rows??[]}catch(e){throw Bo("postgres",e)}}}class gi{db;constructor(e){if(this.db=e,"function"!=typeof e?.all)throw new oa("SQLiteConnection(db): pass an open sqlite Database")}query=async e=>{try{return await this.db.all(e.text,e.values)??[]}catch(e){throw Bo("sqlite",e)}}}const bi=e=>wi(e,0,new Set),wi=(e,t,r)=>{if(null===e||"boolean"==typeof e||"string"==typeof e)return e;if("number"==typeof e&&Number.isFinite(e)&&!Object.is(e,-0))return e;if("object"!=typeof e)return ki(e);if(!Array.isArray(e)&&!n(e))return $i(e);if(r.has(e))return"[circular]";if(t>=o)return"[too deep]";r.add(e);const a=Array.isArray(e)?Array.from(e,e=>wi(e,t+1,r)):Object.fromEntries(Object.entries(e).map(([e,a])=>[e,wi(a,t+1,r)]));return r.delete(e),a},ki=e=>{switch(typeof e){case"function":return""===e.name?"[function]":`[function ${e.name}]`;case"symbol":return`[${String(e)}]`;case"bigint":return`[bigint ${e}]`;case"number":return Object.is(e,-0)?"[-0]":`[${e}]`;default:return"[undefined]"}},$i=e=>{const t=xi(e);try{const r=e.toJSON;if("function"==typeof r){const a=r.call(e);if("string"==typeof a)return`[${t} ${a}]`}}catch{}return`[${t}]`},xi=e=>{try{const t=e.constructor?.name;return"string"==typeof t&&""!==t?t:"Object"}catch{return"Object"}},ji=e=>{const t=new Map;for(const r of e.holes)void 0!==r.timeoutFallback&&t.set(r.node,r.timeoutFallback);const r=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,n(t)])),a=e=>{const r=t.get(e);return void 0===r?{}:{timeoutFallback:bi(r.value)}},n=e=>{const t={order:e.order,kind:e.kind,path:$e(e.path)},o="vars"in e&&void 0!==e.vars?{vars:r(e.vars)}:{};switch(e.kind){case"constant":return{...t,kind:e.kind,value:bi(e.value)};case"reference":return{...t,kind:e.kind,reference:T(e.binding??e.namespace,e.segments),authored:e.raw,...void 0===e.binding?{}:{binding:e.binding}};case"operator":return{...t,kind:e.kind,...o,operator:e.name,params:r(e.params),...void 0===e.fallback?{}:{fallback:n(e.fallback)},...a(e),...void 0===e.useCache?{}:{useCache:e.useCache},...void 0===e.entry.instanceDefaults?{}:{instanceDefaults:Object.keys(e.entry.instanceDefaults)}};case"fragmentCall":return{...t,kind:e.kind,...o,fragment:e.name,resolved:void 0!==e.entry,argumentsMode:e.argumentsMode,...void 0===e.parameters?{}:{parameters:"dynamic"===e.argumentsMode?n(e.parameters):r(e.parameters)},...void 0===e.fallback?{}:{fallback:n(e.fallback)},...a(e)};case"skeleton":{const r=Ae(e.skeleton,e.holes,e.holes.map(()=>"<hole>"));return{...t,kind:e.kind,...o,shape:bi(r),holes:e.holes.map(e=>({at:[...e.at],node:n(e.node)}))}}case"elements":return{...t,kind:e.kind,elements:e.nodes.map(n)};case"entries":return{...t,kind:e.kind,...o,entries:r(e.entries)};case"invalid":return{...t,kind:e.kind,raw:bi(e.raw)}}};return n(e.root)},Pi=(e,t)=>{const r=(a=e,n=t,Ao?.(a,n));var a,n;if(void 0===r)throw new TypeError("inspect() takes a CompiledExpression — the handle fig.compile() returns");const{expression:o,artifact:i,options:s}=r;return{version:X,expression:bi(o),options:Ai(s),canonicalForm:ji(i),issues:un(i,s,({issue:e,order:t})=>({order:t,...e,path:[...e.path]})),timeoutShielded:i.timeoutShielded,nodeCount:i.nodeCount,maxDepth:i.maxDepth,dependencies:Si(i.dependencies),own:{nodeCount:i.own.nodeCount,maxDepth:i.own.maxDepth,dependencies:Si(i.own.dependencies)}}},Oi="[supplied]",Ai=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[e,Di(e,t)])),Di=(e,t)=>{switch(e){case"data":{const e="object"==typeof t&&null!==t?Object.keys(t).length:0;return`[supplied: ${e} top-level key${1===e?"":"s"}]`}case"signal":return Oi;case"http":case"graphQL":return Ni(t,"headers",e=>"object"==typeof e&&null!==e?Object.fromEntries(Object.keys(e).map(e=>[e,"[redacted]"])):bi(e));case"cache":return Ni(t,"store",()=>Oi);default:return bi(t)}},Ni=(e,t,r)=>"object"==typeof e&&null!==e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).map(([e,a])=>[e,e===t?r(a):bi(a)])):bi(e),Si=e=>({dataPaths:[...e.dataPaths.keys()],dynamic:e.dynamic,operators:[...e.operators],fragments:[...e.fragments]});export{R as ARRAY,Ko as AxiosClient,i as ErrorCodes,me as EvaluationData,Wo as FetchClient,Po as FigTree,j as FigTreeError,F as OBJECT,pe as OPERATOR_CATEGORIES,oa as OperatorFailure,yi as PostgresConnection,gi as SQLiteConnection,N as WILDCARD,M as compareValues,ko as coreOperators,_ as deepEqual,Jo as defineOperator,fi as httpOperators,Pi as inspect,O as isFigTreeError,ia as isOperatorFailure,z as isTruthy,g as parsePath,I as renderText,w as resolvePath,hi as sqlOperators,X as version};
1
+ import{f as e,g as t,h as r,r as a,i as n,D as o,E as i,b as s,c as l,j as c,k as u,d,S as p,n as m,a as f,p as h,s as v,l as y,e as g,m as b,o as w,q as k,t as $,u as x,R as j,F as P,v as O,w as A,x as D,y as N,W as C,z as S,A as q,G as T,B as E}from"./chunks/shared.js";const z=[!1,null,0,""],M=e=>-1===z.indexOf(e),F=(e,t)=>"number"==typeof e&&"number"==typeof t?e<t?-1:e>t?1:0:L(String(e),String(t)),L=(e,t)=>{const r=Array.from(e),a=Array.from(t),n=Math.min(r.length,a.length);for(let e=0;e<n;e++){const t=r[e].codePointAt(0),n=a[e].codePointAt(0);if(t!==n)return t<n?-1:1}return r.length===a.length?0:r.length<a.length?-1:1},R="<array>",V="<object>",I=e=>null===e?"":"string"==typeof e?e:"number"==typeof e?String(e):"boolean"==typeof e?e?"true":"false":Array.isArray(e)?R:V,Q=e=>e.trim(),J=/\s+$/,U=/^\s+/,G=e=>e.replace(J,""),W=e=>e.replace(U,""),B=e=>Array.from(e),K=(e,t)=>{const[r,a]=String(e).split("e"),n=void 0!==a?Number(a)+t:t;return Number(`${r}e${n}`)},H=Object.prototype.hasOwnProperty,_=(e,t)=>{for(const r of e.keys())if(X(r,t))return r},X=(e,t)=>{let r,a,n;if(e===t)return!0;if(e&&t&&(r=e.constructor)===t.constructor){if(r===Date)return e.getTime()===t.getTime();if(r===RegExp)return e.toString()===t.toString();if(r===Array){if((a=e.length)===t.length)for(;a--&&X(e[a],t[a]););return-1===a}if(r===Set){if(e.size!==t.size)return!1;for(a of e){if(n=a,n&&"object"==typeof n&&(n=_(t,n),!n))return!1;if(!t.has(n))return!1}return!0}if(r===Map){if(e.size!==t.size)return!1;for(a of e){if(n=a[0],n&&"object"==typeof n&&(n=_(t,n),!n))return!1;if(!X(a[1],t.get(n)))return!1}return!0}if(r===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(r===DataView){if((a=e.byteLength)===t.byteLength)for(;a--&&e.getInt8(a)===t.getInt8(a););return-1===a}if(ArrayBuffer.isView(e)){if((a=e.byteLength)===t.byteLength)for(;a--&&e[a]===t[a];);return-1===a}if(!r||"object"==typeof e){for(r in a=0,e){if(H.call(e,r)&&++a&&!H.call(t,r))return!1;if(!(r in t)||!X(e[r],t[r]))return!1}return Object.keys(t).length===a}}return e!=e&&t!=t},Y="3.0.0-preview.4",Z={ok:!0},ee=e=>null===e?"null":Array.isArray(e)?"array":typeof e,te=(e,t)=>({ok:!1,expected:e,actual:ee(t)}),re=(t,r)=>{switch(r){case"any":return!0;case"string":return"string"==typeof t;case"number":return"number"==typeof t;case"integer":return"number"==typeof t&&Number.isInteger(t);case"boolean":return"boolean"==typeof t;case"array":return Array.isArray(t);case"object":return e(t);case"null":return null===t;default:return!1}},ae=e=>"null"===e||"any"===e||!!Array.isArray(e)&&(e.includes("null")||e.includes("any")),ne=/*#__PURE__*/new Set(["any","string","number","boolean","array","object","null","integer"]),oe=t=>{if("string"==typeof t)return ne.has(t);if(Array.isArray(t))return t.length>0&&t.every(e=>"string"==typeof e&&ne.has(e));if(e(t)&&"literal"in t){const e=t.literal;return Array.isArray(e)&&e.length>0&&e.every(e=>["string","number","boolean"].includes(typeof e))}return!1},ie=(e,r)=>{if(t(r)){if(-1!==r.literal.indexOf(e))return Z;const t=r.literal.map(e=>JSON.stringify(e)).join(", ");return te(`one of ${t}`,e)}return"string"==typeof r?re(e,r)?Z:te(r,e):r.some(t=>re(e,t))?Z:te(r.join(" | "),e)},se=(e,t)=>{if(void 0!==t.length){if(!Array.isArray(e))return te("array",e);if(e.length!==t.length)return{ok:!1,expected:`array of length ${t.length}`,actual:`array of length ${e.length}`}}if(t.homogeneous){if(!Array.isArray(e))return te("array",e);const r=t.homogeneous;if(e.length>0){if(void 0===r.find(t=>e.every(e=>re(e,t))))return{ok:!1,expected:`homogeneous array of ${r.join(" | ")}`,actual:le(e)}}}if(t.elementShape){if(!Array.isArray(e))return te("array",e);for(let r=0;r<e.length;r++){const a=de(e[r],t.elementShape);if(!a.ok)return a}}return Z},le=e=>{const t=ee(e[0]),r=e.find(e=>ee(e)!==t);return void 0===r?`array of ${t}`:`${ee(r)} beside ${t}`},ce=["length","homogeneous","elementShape"],ue=t=>{if(!e(t))return te("a constraints object",t);for(const e of Object.keys(t))if(!ce.includes(e))return{ok:!1,expected:`one of ${ce.join(", ")}`,actual:e};const{length:r,homogeneous:a,elementShape:n}=t;if(void 0!==r&&(!Number.isInteger(r)||r<0))return te("a non-negative integer length",r);if(!(void 0===a||Array.isArray(a)&&oe(a)))return te("a non-empty array of basic types",a);if(void 0!==n){if(!e(n))return te("an object of declarations",n);for(const[t,r]of Object.entries(n)){if(!e(r))return te(`a declaration for "${t}"`,r);if(void 0!==r.type&&!oe(r.type))return te(`a vocabulary type for "${t}"`,r.type);if(void 0!==r.required&&"boolean"!=typeof r.required)return te(`a boolean "required" for "${t}"`,r.required);if(void 0!==r.constraints){const e=ue(r.constraints);if(!e.ok)return e}}}return Z},de=(t,r)=>{if(!e(t))return te("object",t);const a=Object.keys(r);for(let e=0;e<a.length;e++){const n=a[e],o=r[n],i=Object.prototype.hasOwnProperty.call(t,n),s=!1!==o.required;if(i){if(void 0!==o.type){const e=ie(t[n],o.type);if(!e.ok)return e}if(void 0!==o.constraints){const e=se(t[n],o.constraints);if(!e.ok)return e}}else if(s)return{ok:!1,expected:`property "${n}"`,actual:"missing"}}return Z},pe=(e,t,r)=>{if(!r||!Array.isArray(e))return se(e,t);const{length:a,...n}=t;if(void 0!==a){const t=se(e,{length:a});if(!t.ok)return t}return se(e.filter(e=>null!==e),n)},me=["logic","comparison","math","string","array","data","io","other"],fe=Symbol("fig-tree:EvaluationData"),he=Symbol("fig-tree:validated-operator"),ve=e=>"object"==typeof e&&null!==e&&!0===e[he],ye=e=>!e.includes("{")&&!e.includes("}")&&(e.startsWith("$")?e.length>1:r(e).ok),ge=e=>{const t=[];let r="";const a=()=>{""!==r&&(t.push({kind:"text",text:r}),r="")};let n=0;for(;n<e.length;){const o=e[n];if("%"===o){let i=n+1;for(;i<e.length&&e[i]>="0"&&e[i]<="9";)i++;if(i>n+1){const r=e.slice(n,i);a(),t.push({kind:"positional",raw:r,index:Number(r.slice(1))}),n=i;continue}r+=o,n++;continue}if("{"===o&&"{"===e[n+1]){const o=e.indexOf("}}",n+2);if(-1!==o){const r=e.slice(n+2,o);if(ye(r)){a(),t.push({kind:"named",raw:e.slice(n,o+2),body:r}),n=o+2;continue}}r+="{{",n+=2;continue}r+=o,n++}return a(),t},be=(e,t)=>{const r={registry:t,maxDepth:0};return{constant:we(r,e,0),depth:r.maxDepth}},we=(e,t,r)=>{if(r>o)return!1;if(r>e.maxDepth&&(e.maxDepth=r),void 0===t)return!1;if("string"==typeof t){const e=a(t).kind;return"plain"===e||"unrecognized"===e}if(Array.isArray(t)){for(let a=0;a<t.length;a++)if(!we(e,t[a],r+1))return!1;return!0}if(n(t)){for(const r in t){if("operator"===r||"fragment"===r||"vars"===r||"//"===r)return!1;if(r.startsWith("$")&&ke(e.registry,r.slice(1)))return!1}for(const a in t)if(!we(e,t[a],r+1))return!1;return!0}return!0},ke=(e,t)=>"literal"===t||void 0!==jr(e,t)||e.fragments.has(t),$e=(e,t)=>({parent:e,key:t}),xe=e=>{const t=[];for(let r=e;null!==r;r=r.parent)t.push(r.key);return t.reverse()},je=e=>{e.sort((e,t)=>e.order-t.order)},Pe=e=>e.some(({issue:e})=>"error"===e.severity),Oe=e=>{const t=e.entry.definition.parameters.as;if("structural"!==t?.evaluation)return null;const r=e.params.as;return"constant"===r?.kind&&"string"==typeof r.value?r.value:null},Ae=(e,t,r)=>void 0===r?null===e:("element"===t?e:`${e??""}Index`)===r,De=(e,t,r)=>{const a=new Set;let n=e;return t.forEach((e,t)=>{n=Ne(n,e.at,r[t],a)}),n},Ne=(e,t,r,a)=>{const n=Ce(e,a),[o,...i]=t;return n[o]=0===i.length?r:Ne(n[o],i,r,a),n},Ce=(e,t)=>{if(t.has(e))return e;const r=Array.isArray(e)?[...e]:{...e};return t.add(r),r},Se=/*#__PURE__*/new Set(["data","vars","params","element","index","d","v","p","e","i"]),qe=(e,t,r={})=>{const a={registry:t,recognizes:e=>ke(t,e),issues:[],order:0,nodeCount:0,maxDepth:0,dataPaths:new Map,dynamic:!1,operators:new Set,fragmentNames:new Set,fragmentCalls:[],dataReads:[],identityOnly:!1,scope:{bindings:[]},asNames:new Set,unrecognized:[],hasNoCache:!1},n=(r.basePath??[]).reduce($e,null),o=Me(a,e,n,0);Ee(a);const i=$t(a,o);je(a.issues);const s=Pe(a.issues),l={nodeCount:a.nodeCount,maxDepth:a.maxDepth,dependencies:{dataPaths:a.dataPaths,dynamic:a.dynamic,operators:[...a.operators],fragments:[...a.fragmentNames]},identityOnly:a.identityOnly};return{root:o,holes:i,issues:a.issues,hasErrors:s,timeoutShielded:i.every(e=>void 0!==e.timeoutFallback),own:l,...Te(l,a.fragmentCalls,t.fragments),fragmentCalls:a.fragmentCalls,dataReads:a.dataReads,hasNoCache:a.hasNoCache}},Te=(e,t,r)=>{if(0===t.length)return e;const a=new Map(e.dependencies.dataPaths),n=new Set(e.dependencies.operators),o=new Set(e.dependencies.fragments);let{nodeCount:i,maxDepth:s,identityOnly:l}=e,c=e.dependencies.dynamic;for(const e of t){const t=r.get(e.name);if(void 0!==t){i+=t.nodeCount,s=Math.max(s,e.depth+t.maxDepth),l||=t.identityOnly,c||=t.dependencies.dynamic;for(const[e,r]of t.dependencies.dataPaths)a.set(e,r);for(const e of t.dependencies.operators)n.add(e);for(const e of t.dependencies.fragments)o.add(e)}}return{nodeCount:i,maxDepth:s,identityOnly:l,dependencies:{dataPaths:a,dynamic:c,operators:[...n],fragments:[...o]}}},Ee=e=>{if(0!==e.asNames.size)for(const{token:t,issue:r,raw:a}of e.unrecognized)e.asNames.has(t)&&(r.issue={...r.issue,severity:"error",code:i.unresolvedBinding,message:`'${a}' names an iterator binding, but no enclosing iterator binds it here`})},ze=(e,t,r,a,n,o,i={})=>{const s={severity:t,code:r,message:a,path:xe(n)};void 0!==i.operator&&(s.operator=i.operator),void 0!==i.parameter&&(s.parameter=i.parameter),void 0!==i.suggestion&&(s.suggestion=i.suggestion);const l={issue:s,order:o};return e.issues.push(l),l},Me=(e,t,r,a)=>{const n=e.order++;if(a>e.maxDepth&&(e.maxDepth=a),a>o)return ze(e,"error",i.depthCeiling,`the expression nests deeper than the engine's ceiling of ${o} levels — descent stopped here`,r,n),e.nodeCount++,Re(t,r,n);const s=Fe(e,t,r,a,n);return"operator"!==s.kind&&"fragmentCall"!==s.kind&&"reference"!==s.kind&&"invalid"!==s.kind||e.nodeCount++,s},Fe=(e,t,r,a,o)=>null==t?Le(t??null,r,o):"number"==typeof t||"boolean"==typeof t?Le(t,r,o):"string"==typeof t?Ve(e,t,r,o):Array.isArray(t)?Ie(e,t,r,a,o):n(t)?Qe(e,t,r,a,o):(e.identityOnly=!0,Le(t,r,o)),Le=(e,t,r)=>({kind:"constant",value:e,path:t,order:r}),Re=(e,t,r)=>({kind:"invalid",raw:e,path:t,order:r}),Ve=(e,t,r,n)=>{const o=a(t,e.scope);switch(o.kind){case"plain":return Le(t,r,n);case"unrecognized":{const a=ze(e,"warning",i.unrecognizedIdentifier,`'${t}' matches no reference namespace and will pass through as data`,r,n),o=s(t);return null!==o&&e.unrecognized.push({token:o.token,issue:a,raw:t}),Le(t,r,n)}case"invalid":return ze(e,"error",o.code??i.invalidReference,`'${t}': ${o.reason}`,r,n),Re(t,r,n);case"reference":{const{namespace:a,segments:i,drill:s,binding:l}=o;return void 0!==l?{kind:"reference",namespace:a,segments:i,raw:t,binding:l,path:r,order:n}:("data"===a&&(0===i.length?e.dynamic=!0:Ye(e,i,s.startsWith(".")?s.slice(1):void 0,r)),{kind:"reference",namespace:a,segments:i,raw:t,path:r,order:n})}}},Ie=(e,t,r,a,n)=>{const o=t.map((t,n)=>({key:n,rawChild:void 0===t?null:t,node:Me(e,void 0===t?null:t,$e(r,n),a+1)})),i=t.some(e=>void 0===e);return kt(e,t,o,!0,i,void 0,r,n)},Qe=(e,t,r,a,n)=>{const o=l(t,e.recognizes);switch(o.kind){case"malformed":return ze(e,"error",i.malformedNode,o.message,r,n),Re(t,r,n);case"operator":return Je(e,t,r,a,n);case"fragment":return ft(e,t,r,a,n);case"shorthand":return st(e,t,o.key,r,a,n);case"plain":return bt(e,t,r,a,n)}},Je=(e,t,r,a,n)=>{const o=t.operator;if("string"!=typeof o)return ze(e,"error",i.malformedNode,"the 'operator' value must be a literal string",r,n),Re(t,r,n);if("literal"===o)return mt(e,t,t.value,"value"in t,r,n);const s=jr(e.registry,o);if(void 0===s){const a=m(o,Pt(e));return ze(e,"error",i.unknownOperator,`'${o}' names no registered operator${a?` — did you mean '${a}'?`:""}`,r,n,{suggestion:a}),Re(t,r,n)}const l=Ue(e,s,r,n),c=[];for(const o in t){const s=t[o];"operator"!==o&&"//"!==o&&void 0!==s&&(Ge(e,l,o,s,r,a,n)||("parameters"!==o?Be(e,l,c,o,s,$e(r,o),n):ze(e,"error",i.malformedNode,"'parameters' is reserved and unused on operator nodes",$e(r,o),n,{operator:l.name})))}return Ke(e,l,c,a,n),l},Ue=(e,t,r,a)=>(e.operators.add(t.definition.name),{kind:"operator",name:t.definition.name,entry:t,params:{},path:r,order:a}),Ge=(e,t,r,a,n,o,i)=>"fallback"===r?(t.fallback=Me(e,a,$e(n,"fallback"),o+1),!0):"noCache"===r?(We(e,t,a,n,i),!0):"vars"===r&&(t.vars=gt(e,a,n,o,i),!0),We=(e,t,r,a,n)=>{!0===r?(t.noCache=!0,e.hasNoCache=!0):ze(e,"error",i.malformedNode,"'noCache' takes only the literal true — it is settled before the subtree runs",$e(a,"noCache"),n,"operator"===t.kind?{operator:t.name}:{})},Be=(e,t,r,a,n,o,s)=>{if(void 0===t.entry.definition.parameters[a]){const r=m(a,Object.keys(t.entry.definition.parameters));return void ze(e,"error",i.unknownNodeKey,`'${a}' is not a parameter of '${t.name}'${r?` — did you mean '${r}'?`:""}`,o,s,{operator:t.name,parameter:a,suggestion:r})}r.push({name:a,kind:"value",value:n,path:o})},Ke=(e,t,r,a,n)=>{const o=t.entry.definition,i=o.resolution.perElement.length>0;let s;if(i){const a=r.find(e=>"as"===e.name&&"structural"===o.parameters.as?.evaluation&&"value"===e.kind);void 0!==a&&"value"===a.kind&&(s=it(e,t,a.value,a.path,n))}for(const n of r){const r=o.parameters[n.name]?.evaluation;"perElement"!==r&&(t.params[n.name]=et(e,n,r,a))}if(i){void 0!==s&&e.scope.bindings.push(s);for(const n of r){const r=o.parameters[n.name]?.evaluation;"perElement"===r&&(t.params[n.name]=et(e,n,r,a))}void 0!==s&&e.scope.bindings.pop()}Ze(e,t),He(e,t)},He=(e,t)=>{if("buildString"!==t.name)return;const r=t.params.template;if("constant"!==r?.kind||"string"!=typeof r.value)return;const a=ge(r.value).filter(e=>"text"!==e.kind);if(0===a.length)return;const o=t.params.substitutions,i=(e=>{if(void 0===e)return{mode:"absent"};if("constant"===e.kind)return Array.isArray(e.value)?{mode:"array",length:e.value.length}:n(e.value)?{mode:"object",keys:new Set(Object.keys(e.value))}:{mode:"dynamic"};if("skeleton"===e.kind){const{skeleton:t,holes:r}=e;if(Array.isArray(t))return{mode:"array",length:t.length};if(n(t)){const e=new Set(Object.keys(t));for(const t of r)e.add(String(t.at[0]));return{mode:"object",keys:e}}}return{mode:"dynamic"}})(o);if(Xe(e,t,r,a,i),"absent"!==i.mode&&"object"!==i.mode)return;const s=[],l=new Set;for(const t of a){if("named"!==t.kind||!t.body.startsWith("$"))continue;if(l.has(t.body))continue;const a=Ve(e,t.body,r.path,e.order++);"reference"===a.kind&&(e.nodeCount++,l.add(t.body),s.push({path:r.path,at:[t.body],node:a}))}0!==s.length&&(t.params.substitutions=_e(e,t,o,s))},_e=(e,t,r,a)=>{const n="skeleton"===r?.kind?{...r,skeleton:{...r.skeleton},holes:[...r.holes]}:{kind:"skeleton",skeleton:"constant"===r?.kind?{...r.value}:{},holes:[],path:r?.path??$e(t.path,"substitutions"),order:r?.order??e.order++};return n.holes.push(...a),n},Xe=(e,t,r,a,n)=>{const o=(a,n,o="warning")=>ze(e,o,a,n,r.path,r.order,{operator:t.name});if("array"!==n.mode&&"dynamic"!==n.mode||a.some(e=>"named"===e.kind&&e.body.startsWith("$"))&&o(i.inertReferenceToken,`a reference token needs the named face — beside ${"array"===n.mode?"positional substitutions":"a dynamically supplied map"} it is not recognized and renders as its own text`),"array"===n.mode){const e=new Set;let t=!1;for(const r of a)"positional"===r.kind&&(r.index>=1&&r.index<=n.length?e.add(r.index):(t=!0,o(i.unboundToken,`'${r.raw}' binds to nothing and renders as its own text`)));const r=[];for(let t=1;t<=n.length;t++)e.has(t)||r.push(t);for(const e of r)o(i.unusedSubstitution,`substitution ${e} is never named by the template`);return void(r.length>0&&t&&o(i.tokenRenumber,`the tokens skip a number — renumber them to ${[...Array(n.length).keys()].map(e=>`%${e+1}`).join(", ")}`,"hint"))}if("object"===n.mode){const e=new Set;for(const t of a)"named"===t.kind&&(n.keys.has(t.body)?e.add(t.body):t.body.startsWith("$")||o(i.unboundToken,`'${t.raw}' binds to nothing and renders as its own text`));for(const t of n.keys)e.has(t)||o(i.unusedSubstitution,`substitution '${t}' is never named by the template`)}},Ye=(e,t,r,a)=>{let n,o;void 0!==r&&c(r)?(n=r,o=t):(o=u(t),n=d(o)),e.dataPaths.set(n,o),e.dataReads.push({kind:"path",key:n,segments:o,path:a})},Ze=(e,t)=>{if("get"!==t.name||void 0!==t.params.from)return;const r=t.params.path;if(void 0!==r)if("constant"===r.kind)try{const a="string"==typeof r.value?g(r.value):r.value;if(!Array.isArray(a)||!a.every(b))return void(e.dynamic=!0);if(0===a.length)return void(e.dynamic=!0);Ye(e,a,"string"==typeof r.value?r.value:void 0,t.path)}catch{e.dynamic=!0}else e.dynamic=!0},et=(e,t,r,a)=>{if("lazyElements"===r||"race"===r){const r=nt(e,t,a);if(null!==r)return r}if("lazyEntries"===r){const r=ot(e,t,a);if(null!==r)return r}return"value"===t.kind?Me(e,t.value,t.path,a+1):tt(e,t,a)},tt=(e,t,r)=>{const{order:a,containerDepth:n}=rt(e,r),o=at(e,t.elements,t.basePath,t.offset,n),i=t.elements.some(e=>void 0===e);return kt(e,t.elements,o,!0,i,void 0,t.basePath,a)},rt=(e,t)=>{const r=e.order++,a=t+1;return a>e.maxDepth&&(e.maxDepth=a),{order:r,containerDepth:a}},at=(e,t,r,a,n)=>t.map((t,o)=>({key:o,rawChild:void 0===t?null:t,node:Me(e,void 0===t?null:t,$e(r,a+o),n+1)})),nt=(e,t,r)=>{const a="slice"===t.kind?t.elements:t.value;if(!Array.isArray(a))return null;const n="slice"===t.kind?t.basePath:t.path,o="slice"===t.kind?t.offset:0,{order:i,containerDepth:s}=rt(e,r),l=at(e,a,n,o,s);if(l.every(e=>"constant"===e.node.kind)){const t=a.some(e=>void 0===e);return kt(e,a,l,!0,t,void 0,n,i)}return{kind:"elements",nodes:l.map(e=>e.node),path:n,order:i}},ot=(e,t,r)=>{if("value"!==t.kind)return null;const a=t.value;if(!n(a)||f(a,e.recognizes))return null;const{order:o,containerDepth:i}=rt(e,r),{entries:s,vars:l,changed:c}=wt(e,a,t.path,i,o);if(s.every(e=>"constant"===e.node.kind))return kt(e,a,s,!1,c,l,t.path,o);const u={};for(const{key:e,node:t}of s)u[String(e)]=t;const d={kind:"entries",entries:u,path:t.path,order:o};return void 0!==l&&(d.vars=l),d},it=(e,t,n,o,s)=>{const l=r=>{ze(e,"error",i.invalidAs,r,o,s,{operator:t.name})};if("string"!=typeof n||"plain"!==a(n).kind)return l("'as' must be a literal name — a dynamic value cannot be statically resolved");const c=r(n);if(!c.ok)return l(`'${n}' is not a legal binding name — ${c.reason}`);const u=[n,w(n)];for(const t of u){if(Se.has(t))return l(`'${n}' collides with the reserved namespace word '${t}'`);if(null!==y(t,e.scope.bindings))return l(`'${n}' collides with an enclosing 'as' binding ('${t}')`)}for(const t of u)e.asNames.add(t);return n},st=(e,t,r,a,n,o)=>{const s=r.slice(1),l="literal"===s,c=!l&&e.registry.fragments.has(s);for(const n in t)if(n!==r&&!p.has(n))return ze(e,"error",i.malformedNode,`'${n}' may not sit beside the shorthand key '${r}' — reserved modifiers only`,$e(a,n),o),Re(t,a,o);const u=t[r],d=$e(a,r);if(l){for(const r of["fallback","vars","noCache"])r in t&&ze(e,"warning",i.uselessModifier,`'${r}' on 'literal' is dead — contents are never evaluated`,$e(a,r),o);return mt(e,t,u,!0,a,o)}if(c)return ht(e,t,s,u,a,n,o);const m=jr(e.registry,s),f=Ue(e,m,a,o);for(const i in t){const s=t[i];i!==r&&"//"!==i&&void 0!==s&&Ge(e,f,i,s,a,n,o)}const h=[];return lt(e,f,h,u,d,o),Ke(e,f,h,n,o),f},lt=(e,t,r,a,o,i)=>{if(Array.isArray(a))ut(e,t,r,a,o,i);else if(!n(a)||f(a,e.recognizes))ct(e,t,r,a,o,i);else for(const n in a){const s=a[n];"//"!==n&&void 0!==s&&Be(e,t,r,n,s,$e(o,n),i)}},ct=(e,t,r,a,n,o)=>{const i=v(t.entry.definition);null!==i?r.push({name:i,kind:"value",value:a,path:n}):dt(e,t,n,o)},ut=(e,t,r,a,n,o)=>{const i=t.entry.definition,s=h(i,a.length);if(null===s)return void pt(e,t,a,n,o);const l=i.positionalParams;for(let e=0;e<s.bound;e++)r.push({name:l[e],kind:"value",value:a[e],path:$e(n,e)});const{restAt:c}=s;null!==c&&r.push({name:i.restParam,kind:"slice",elements:0===c?a:a.slice(c),basePath:n,offset:c})},dt=(e,t,r,a)=>ze(e,"error",i.positionalArity,`'${t.name}' takes no positional arguments — use the named form`,r,a,{operator:t.name}),pt=(e,t,r,a,n)=>{const o=t.entry.definition.positionalParams;if(void 0===o)return void dt(e,t,a,n);const s=o.length;ze(e,"error",i.positionalArity,`'${t.name}' takes at most ${s} positional argument${1===s?"":"s"} (${o.join(", ")}), got ${r.length}`,a,n,{operator:t.name})},mt=(e,t,r,a,n,o)=>{if("operator"in t){for(const r in t)"operator"!==r&&"value"!==r&&"//"!==r&&("fallback"!==r&&"vars"!==r&&"noCache"!==r?ze(e,"error",i.unknownNodeKey,`'${r}' is not a key of 'literal' — content goes in 'value'`,$e(n,r),o,{operator:"literal"}):ze(e,"warning",i.uselessModifier,`'${r}' on 'literal' is dead — contents are never evaluated`,$e(n,r),o));if(!a)return ze(e,"error",i.malformedNode,"'literal' requires its content in 'value'",n,o,{operator:"literal"}),Re(t,n,o)}return Le(r,n,o)},ft=(e,t,r,a,n)=>{const o=t.fragment;if("string"!=typeof o)return ze(e,"error",i.malformedNode,"the 'fragment' value must be a literal string",r,n),Re(t,r,n);const s={kind:"fragmentCall",name:o,argumentsMode:"static",path:r,order:n};vt(e,s,a);for(const o in t){const l=t[o];"fragment"!==o&&"//"!==o&&void 0!==l&&("parameters"!==o?"fallback"!==o?"vars"!==o?"noCache"!==o?ze(e,"error",i.unknownNodeKey,`'${o}' is not a key of a fragment call — arguments live only in 'parameters'`,$e(r,o),n):We(e,s,l,r,n):s.vars=gt(e,l,r,a,n):s.fallback=Me(e,l,$e(r,"fallback"),a+1):yt(e,s,l,$e(r,"parameters"),a,n))}return s},ht=(e,t,r,a,o,s,l)=>{const c={kind:"fragmentCall",name:r,argumentsMode:"static",path:o,order:l};vt(e,c,s);for(const a in t){const n=t[a];a!==`$${r}`&&"//"!==a&&void 0!==n&&("fallback"===a&&(c.fallback=Me(e,n,$e(o,"fallback"),s+1)),"noCache"===a&&We(e,c,n,o,l),"vars"===a&&(c.vars=gt(e,n,o,s,l)))}return n(a)?yt(e,c,a,$e(o,`$${r}`),s,l):ze(e,"error",i.malformedNode,`fragments have no single-value or positional form — '$${r}' takes a named-arguments object`,$e(o,`$${r}`),l),c},vt=(e,t,r)=>{const{name:a,path:n,order:o}=t;e.fragmentNames.add(a);const s=e.registry.fragments.get(a);if(void 0===s){const t=m(a,e.registry.fragments.keys());return void ze(e,"error",i.unknownFragment,`'${a}' names no registered fragment${t?` — did you mean '${t}'?`:""}`,n,o,{suggestion:t})}t.entry=s,e.fragmentCalls.push({name:a,depth:r}),e.dataReads.push({kind:"call",fragment:s,path:n})},yt=(e,t,r,o,s,l)=>{if(void 0!==r){if(f(r,e.recognizes)||"string"==typeof r&&"reference"===a(r).kind)return t.argumentsMode="dynamic",t.parameters=Me(e,r,o,s+1),void(e.dynamic=!0);if(n(r)){const a={};for(const t in r){const n=r[t];"//"!==t&&void 0!==n&&(a[t]=Me(e,n,$e(o,t),s+1))}return void(t.parameters=a)}ze(e,"error",i.malformedNode,"a fragment's 'parameters' must be a named-arguments object or a node computing one",o,l)}},gt=(e,t,a,o,s)=>{const l=$e(a,"vars");if(!n(t))return void ze(e,"error",i.invalidVars,"a 'vars' block must be an object of name → expression entries",l,s);const c={};for(const a in t){const n=t[a];if("//"===a||void 0===n)continue;const u=$e(l,a),d=r(a);d.ok?c[a]=Me(e,n,u,o+1):ze(e,"error",i.invalidName,`'${a}' is not a legal var name — ${d.reason}`,u,s)}return c},bt=(e,t,r,a,n)=>{const{entries:o,vars:i,changed:s}=wt(e,t,r,a,n);return kt(e,t,o,!1,s,i,r,n)},wt=(e,t,r,a,n)=>{let o,s=!1;const l=[];for(const c in t){const u=t[c];if("//"!==c)if("vars"!==c)if(void 0!==u){if(c.startsWith("$")){const t=m(c.slice(1),Pt(e));ze(e,"warning",i.unrecognizedIdentifier,`'${c}' is not a registered operator or fragment and will pass through as data${t?` — did you mean '$${t}'?`:""}`,$e(r,c),n,{suggestion:void 0===t?void 0:`$${t}`})}l.push({key:c,rawChild:u,node:Me(e,u,$e(r,c),a+1)})}else s=!0;else o=gt(e,u,r,a,n),s=!0;else s=!0}return{entries:l,vars:o,changed:s}},kt=(e,t,r,a,n,o,s,l)=>{const c=[],u=a?new Array(r.length):{};let d=n;for(const{key:e,rawChild:t,node:a}of r)"constant"!==a.kind?(d=!0,"skeleton"!==a.kind||void 0!==a.vars?c.push({path:a.path,at:[e],node:a}):(u[e]=a.skeleton,c.push(...a.holes.map(t=>({...t,at:[e,...t.at]}))))):(u[e]=a.value,a.value!==t&&(d=!0));if(0===c.length)return void 0!==o&&Object.keys(o).length>0&&ze(e,"warning",i.unreferencedVar,"this vars block declares names nothing in its scope references",$e(s,"vars"),l),Le(d||void 0!==o?u:t,s,l);const p={kind:"skeleton",skeleton:u,holes:c,path:s,order:l};return void 0!==o&&(p.vars=o),p},$t=(e,t)=>"constant"===t.kind?[]:"skeleton"===t.kind?t.holes.map(t=>({path:xe(t.path),node:t.node,...xt(e,t.node)})):[{path:xe(t.path),node:t,...xt(e,t)}],xt=(e,t)=>{const r=jt(e,t);return void 0===r?{}:{timeoutFallback:r}},jt=(e,t)=>{if("operator"===t.kind||"fragmentCall"===t.kind){if(void 0!==t.fallback)return"constant"===t.fallback.kind?{value:t.fallback.value}:void 0;if("operator"===t.kind){const r=t.entry.instanceDefaults;return void 0!==r&&"fallback"in r&&be(r.fallback,e.registry).constant?{value:r.fallback}:void 0}return t.entry?.timeoutFallback}},Pt=e=>[...e.registry.operators.keys(),...e.registry.aliases.keys(),...e.registry.fragments.keys()],Ot=e=>{switch(e.kind){case"operator":return e.entry.definition.returns;case"fragmentCall":return e.entry?.returns??"any";case"skeleton":return Array.isArray(e.skeleton)?"array":"object";case"constant":return At(e.value);default:return"any"}},At=t=>{if(null===t)return"null";if(Array.isArray(t))return"array";if(e(t))return"object";switch(typeof t){case"string":return"string";case"number":return"number";case"boolean":return"boolean";default:return"any"}},Dt=/*#__PURE__*/Object.freeze({parsePath:g,resolvePath:k,checkType:ie,checkConstraints:se,describeType:ee,renderText:I,isTruthy:M}),Nt=(e,t={})=>{St({artifact:e,context:t,varsFrames:[],iteratorFrames:[]},e.root),je(e.issues),e.hasErrors=Pe(e.issues)},Ct=(e,t,r,a,n,o,i={})=>{const s={severity:t,code:r,message:a,path:xe(n)};void 0!==i.operator&&(s.operator=i.operator),void 0!==i.fragment&&(s.fragment=i.fragment),void 0!==i.parameter&&(s.parameter=i.parameter),void 0!==i.suggestion&&(s.suggestion=i.suggestion),e.artifact.issues.push({issue:s,order:o})},St=(e,t)=>{switch(t.kind){case"constant":case"invalid":return;case"reference":return void Rt(e,t);case"skeleton":{const r=Jt(e,t.vars,t.path);for(const r of t.holes)St(e,r.node);return void Ut(e,r)}case"fragmentCall":return void Ft(e,t);case"elements":for(const r of t.nodes)St(e,r);return;case"entries":{const r=Jt(e,t.vars,t.path);for(const r in t.entries)St(e,t.entries[r]);return void Ut(e,r)}case"operator":return void Tt(e,t)}return t},qt=e=>"kind"in e&&"string"==typeof e.kind,Tt=(e,t)=>{const r=Jt(e,t.vars,t.path);void 0!==t.fallback&&St(e,t.fallback);const a=t.entry.definition,n=Mt(t);for(const[r,o]of a.resolution.entries){const a=t.params[r];void 0!==a?"constant"===a.kind&&null===a.value&&Et(t,r)||zt(e,n,r,o,a):o.required&&Ct(e,"error",i.missingRequired,`'${t.name}' requires '${r}'`,t.path,t.order,{operator:t.name,parameter:r})}Lt(e,t);const o=[];for(const r in t.params){const n=t.params[r];"perElement"===a.parameters[r]?.evaluation?o.push([r,n]):St(e,n)}if(o.length>0){const r={as:Oe(t),referenced:!1};e.iteratorFrames.push(r);for(const[,t]of o)St(e,t);e.iteratorFrames.pop(),r.referenced||Ct(e,"warning",i.deadBinding,`'${t.name}' binds ${null===r.as?"$element / $index":`$${r.as}`} but its 'each' references neither`,t.path,t.order,{operator:t.name})}Ut(e,r)},Et=(e,t)=>{const{definition:r,instanceDefaults:a}=e.entry;for(const[n,o]of r.resolution.entries){if(!o.replacesNullAt?.includes(t))continue;const r=e.params[n];if(void 0===r){if(void 0!==a&&Object.hasOwn(a,n)&&null!==a[n])return!0}else if("constant"!==r.kind||null!==r.value)return!0}return!1},zt=(e,t,r,a,n)=>{if("constant"===n.kind){if(null===n.value&&!a.required&&!ae(a.type))return;const o=ie(n.value,a.type);if(!o.ok)return void Ct(e,"error",i.typeCheck,`'${t.label}.${r}': expected ${o.expected}, received ${o.actual}`,n.path,n.order,{...t.extra,parameter:r});if(void 0!==a.constraints){const o=pe(n.value,a.constraints,void 0!==a.elementNullPolicy);o.ok||Ct(e,"error",i.typeCheck,`'${t.label}.${r}': expected ${o.expected}, received ${o.actual}`,n.path,n.order,{...t.extra,parameter:r})}return}if("elements"===n.kind){const o=a.constraints?.length;return void(void 0!==o&&n.nodes.length!==o&&Ct(e,"error",i.typeCheck,`'${t.label}.${r}': expected ${o} element${1===o?"":"s"}, received ${n.nodes.length}`,n.path,n.order,{...t.extra,parameter:r}))}if("structural"!==a.evaluation||"as"===r){if("operator"===n.kind||"fragmentCall"===n.kind&&void 0!==n.entry){const o=Ot(n);if(!$(o,a.type)){const a="operator"===n.kind?`'${n.name}'`:`fragment '${n.name}'`;Ct(e,"error",i.returnsMismatch,`${a} returns ${JSON.stringify(o)} — it can never satisfy '${t.label}.${r}'`,n.path,n.order,{...t.extra,parameter:r})}return}if("skeleton"===n.kind){const o=ie(Array.isArray(n.skeleton)?[]:{},a.type);o.ok||Ct(e,"error",i.typeCheck,`'${t.label}.${r}': expected ${o.expected}, received ${o.actual}`,n.path,n.order,{...t.extra,parameter:r})}}else Ct(e,"error",i.typeCheck,`'${t.label}.${r}' is structural — it requires a literal value`,n.path,n.order,{...t.extra,parameter:r})},Mt=e=>({label:e.name,extra:{operator:e.name}}),Ft=(e,t)=>{const r=Jt(e,t.vars,t.path);void 0!==t.fallback&&St(e,t.fallback);const a=t.entry?.parameters,n=void 0===t.parameters||qt(t.parameters)?void 0:t.parameters;if(void 0!==a&&"static"===t.argumentsMode){const r={label:t.name,extra:{fragment:t.name}};for(const o in a){const s=a[o],l=n?.[o];void 0!==l?zt(e,r,o,s,l):s.required&&Ct(e,"error",i.missingRequired,`fragment '${t.name}' – requires '${o}'`,t.path,t.order,{fragment:t.name,parameter:o})}if(void 0!==n)for(const r in n){const o=n[r];if(void 0===a[r]){const n=m(r,Object.keys(a));Ct(e,"error",i.unknownNodeKey,`fragment '${t.name}' declares no parameter '${r}'${n?` — did you mean '${n}'?`:""}`,o.path,o.order,{parameter:r,suggestion:n})}}}if(void 0!==t.parameters)if(qt(t.parameters))St(e,t.parameters);else for(const r in t.parameters)St(e,t.parameters[r]);Ut(e,r)},Lt=(e,t)=>{const r=t.entry.definition.validate;if(void 0===r)return;const a={};for(const e in t.params){const r=t.params[e];"constant"===r.kind&&(a[e]=r.value)}let n;try{n=r(a,Dt)}catch(r){return void Ct(e,"error",i.operatorValidate,`'${t.name}' validate hook threw: ${r.message}`,t.path,t.order,{operator:t.name})}for(const r of n){const a=void 0!==r.parameter?t.params[r.parameter]:void 0;Ct(e,r.severity,i.operatorValidate,r.message,a?.path??t.path,t.order,{operator:t.name,...void 0!==r.parameter?{parameter:r.parameter}:{}})}},Rt=(e,t)=>{switch(t.namespace){case"data":return;case"vars":return void Vt(e,t);case"params":return void It(e,t);case"element":case"index":return void Qt(e,t,t.namespace)}},Vt=(e,t)=>{const r=t.segments[0],a="string"==typeof r?r:void 0;if(void 0!==a)for(let t=e.varsFrames.length-1;t>=0;t--){const r=e.varsFrames[t],n=r.names.get(a);if(void 0!==n){if(n.referenced=!0,null!==r.currentVar){const e=r.edges.get(r.currentVar)??new Set;e.add(a),r.edges.set(r.currentVar,e)}return}}Ct(e,"error",i.unresolvedVar,`'${t.raw}': no var '${a??""}' is declared in scope`,t.path,t.order)},It=(e,t)=>{const r=e.context.fragmentParams;if(void 0===r)return void Ct(e,"error",i.unresolvedParam,`'${t.raw}': $params is only available inside a fragment body`,t.path,t.order);if(0===t.segments.length)return;const a=t.segments[0];"string"==typeof a&&r.has(a)||Ct(e,"error",i.unresolvedParam,`'${t.raw}': the fragment declares no parameter '${String(a)}'`,t.path,t.order)},Qt=(e,t,r)=>{for(let a=e.iteratorFrames.length-1;a>=0;a--){const n=e.iteratorFrames[a];if(Ae(n.as,r,t.binding))return void(n.referenced=!0)}Ct(e,"error",i.unresolvedBinding,`'${t.raw}' resolves against no enclosing iterator here`,t.path,t.order)},Jt=(e,t,r)=>{if(void 0===t)return null;const a={names:new Map,currentVar:null,edges:new Map},n=$e(r,"vars");for(const r in t){const o=t[r],s=$e(n,r);for(const t of e.varsFrames)if(t.names.has(r)){Ct(e,"warning",i.shadowedVar,`'${r}' shadows a var of the same name from an enclosing scope`,s,o.order);break}a.names.set(r,{node:o,declaredAt:s,order:o.order,referenced:!1})}e.varsFrames.push(a);for(const[t,r]of a.names)a.currentVar=t,St(e,r.node),a.currentVar=null;return a},Ut=(e,t)=>{if(null!==t){e.varsFrames.pop();for(const[r,a]of t.names)a.referenced||Ct(e,"warning",i.unreferencedVar,`'${r}' is declared but never referenced in its scope`,a.declaredAt,a.order);Gt(e,t)}},Gt=(e,t)=>{const r=new Set,a=new Set,n=new Set,o=e=>{if(a.has(e))return!1;if(r.has(e))return!0;r.add(e);for(const n of t.edges.get(e)??[])if(o(n))return r.delete(e),a.add(e),!0;return r.delete(e),a.add(e),!1};for(const r of t.names.keys())if(!a.has(r)&&!n.has(r)&&o(r)){const a=t.names.get(r);Ct(e,"error",i.varCycle,`'${r}' participates in a vars cycle — a var may not depend on itself`,a.declaredAt,a.order),n.add(r)}},Wt={capable:!1,effective:!1},Bt={capable:!0,effective:!0},Kt=e=>{const{effective:t}=Ht(e,e.root,!1);return je(e.issues),t},Ht=(e,t,r)=>{switch(t.kind){case"constant":case"reference":return Wt;case"invalid":return Bt;case"skeleton":return Yt(e,[...t.holes.map(e=>e.node),...Zt(t.vars)],r);case"elements":return Yt(e,t.nodes,r);case"entries":return Yt(e,[...Object.values(t.entries),...Zt(t.vars)],r);case"operator":return _t(e,t,wr(t.entry),r);case"fragmentCall":return _t(e,t,t.entry?.caches??!0,r)}return t},_t=(e,t,r,a)=>{const n=!0===t.noCache,o=Yt(e,Xt(t),a||n),i=r||o.capable;return n&&a?er(e,t,"'noCache' is redundant — an enclosing node already sets it"):n&&!i&&er(e,t,"'noCache' is dead — nothing beneath this node caches"),{capable:i,effective:!n&&(r||o.effective)}},Xt=e=>{const t=[];return"operator"===e.kind?t.push(...Object.values(e.params)):void 0!==e.parameters&&("dynamic"===e.argumentsMode?t.push(e.parameters):t.push(...Object.values(e.parameters))),void 0!==e.fallback&&t.push(e.fallback),t.push(...Zt(e.vars)),t},Yt=(e,t,r)=>{const a={capable:!1,effective:!1};for(const n of t){const{capable:t,effective:o}=Ht(e,n,r);a.capable||=t,a.effective||=o}return a},Zt=e=>void 0===e?[]:Object.values(e),er=(e,t,r)=>{const a={severity:"warning",code:i.uselessModifier,message:r,path:xe($e(t.path,"noCache"))};"operator"===t.kind?a.operator=t.name:a.fragment=t.name,e.issues.push({issue:a,order:t.order})};class tr{max;entries=new Map;constructor(e){this.max=e,rr(e)}get size(){return this.entries.size}get(e){if(!this.entries.has(e))return;const t=this.entries.get(e);return this.entries.delete(e),this.entries.set(e,t),t}set(e,t){this.entries.delete(e),this.entries.set(e,t),this.entries.size>this.max&&this.evictOldest()}delete(e){this.entries.delete(e)}clear(){this.entries.clear()}resize(e){for(rr(e),this.max=e;this.entries.size>this.max;)this.evictOldest()}evictOldest(){const e=this.entries.keys().next();!0!==e.done&&this.entries.delete(e.value)}}const rr=e=>{if(!Number.isInteger(e)||e<1)throw new RangeError("LRU bound must be a positive integer")},ar=Symbol("fig-tree:lazy-handle"),nr="~",or=(e,t)=>{if(t>o)return"refused";switch(typeof e){case"boolean":return"json";case"string":return e.length>4096?"serializer":"json";case"number":return Number.isFinite(e)&&!Object.is(e,-0)?"json":"serializer";case"undefined":return"serializer";case"object":break;default:return"refused"}if(null===e)return"json";if(Array.isArray(e)){for(let r=0;r<e.length;r++){const a=or(e[r],t+1);if("json"!==a)return a}return"json"}if(!n(e))return"refused";for(const r in e){if(r.length>4096)return"serializer";const a=or(e[r],t+1);if("json"!==a)return a}return"json"},ir=(e,t)=>sr(e,0,t)?t.join(""):void 0,sr=(e,t,r)=>{if(t>o)return!1;if(null===e)return cr(r,"n");if(void 0===e)return cr(r,"u");switch(typeof e){case"boolean":return cr(r,e?"t":"f");case"number":return lr(e,r);case"string":return cr(r,`s${e.length}:${e}`);case"object":break;default:return!1}if(Array.isArray(e)){r.push("[");for(const a of e)if(!sr(a,t+1,r))return!1;return cr(r,"]")}if(!n(e)||ar in e)return!1;r.push("{");for(const a in e)if(r.push(`s${a.length}:${a}`),!sr(e[a],t+1,r))return!1;return cr(r,"}")},lr=(e,t)=>Number.isNaN(e)?cr(t,"N"):e===1/0?cr(t,"I"):e===-1/0?cr(t,"J"):Object.is(e,-0)?cr(t,"#-0"):cr(t,`#${String(e)}`),cr=(e,t)=>(e.push(t),!0);class ur{deps;identity=new WeakMap;content=new tr(200);constructor(e){this.deps=e}resolve(e){const t="object"==typeof e&&null!==e?e:void 0;if(void 0!==t){const e=this.identity.get(t);if(void 0!==e)return e}const r=this.deps.probe(e);if(r.constant){const e={kind:"inert",depth:r.depth};return void 0!==t&&this.identity.set(t,e),e}const a=void 0===t?void 0:(e=>{const t=or(e,0);return"json"===t?JSON.stringify(e):"serializer"===t?ir(e,[nr]):void 0})(e),n=void 0===a?void 0:this.content.get(a),o=n??this.deps.compile(e),i={kind:"artifact",artifact:o};return void 0!==t&&this.identity.set(t,i),void 0!==a&&void 0===n&&!o.identityOnly&&o.holes.length>0&&this.content.set(a,o),i}}const dr=/*#__PURE__*/new Set(["type","required","default","description","metadata","constraints"]),pr=/*#__PURE__*/new Set(["expression","parameters","description","metadata"]),mr=(t,a,n)=>{const o=(...e)=>["fragments",t,...e],s=r(t);if(!s.ok)return void n(i.invalidName,`'${t}' is not a legal fragment name: ${s.reason}`,o());if(x.has(t))return void n(i.reservedName,`'${t}' is a reserved name and may not name a fragment`,o());if(!e(a))return void n(i.invalidDefinition,`fragment '${t}' must be a wrapper object: { expression, parameters?, description?, metadata? }`,o());if(!("expression"in a))return void n(i.invalidDefinition,`fragment '${t}' has no 'expression'`,o());for(const e of Object.keys(a))pr.has(e)||n(i.invalidDefinition,`'${e}' is not a key of a fragment definition`,o(e));const l={name:t,parameters:{},body:{kind:"constant",value:null,path:null,order:0},returns:"any",warnings:[],nodeCount:0,maxDepth:0,dependencies:{dataPaths:new Map,dynamic:!1,operators:[],fragments:[]},identityOnly:!1,caches:!1};if(void 0!==a.description&&("string"!=typeof a.description?n(i.invalidDefinition,"'description' must be a string",o("description")):l.description=a.description),void 0!==a.metadata&&(e(a.metadata)?l.metadata=a.metadata:n(i.invalidDefinition,"'metadata' must be a plain object",o("metadata"))),void 0!==a.parameters)if(e(a.parameters))for(const[e,t]of Object.entries(a.parameters)){const r=fr(e,t,o,n);void 0!==r&&(l.parameters[e]=r)}else n(i.invalidDefinition,"'parameters' must be a plain object",o("parameters"));return l},fr=(t,a,n,o)=>{const s=n("parameters",t),l=r(t);if(!l.ok)return void o(i.invalidName,`'${t}' is not a legal parameter name: ${l.reason}`,s);if(j.has(t))return void o(i.reservedName,`'${t}' is a reserved node key and may not name a parameter`,s);if(!e(a))return void o(i.invalidDefinition,`the declaration of '${t}' must be an object`,s);for(const e of Object.keys(a))dr.has(e)||o(i.invalidDefinition,`'${e}' is not a key of a parameter declaration`,[...s,e]);const c=a.type??"any";if(!oe(c))return void o(i.invalidDefinition,`'${t}' declares an unknown type`,[...s,"type"]);if(void 0!==a.required&&"boolean"!=typeof a.required)return void o(i.invalidDefinition,"'required' must be a boolean",[...s,"required"]);let u;if(void 0!==a.constraints){const e=ue(a.constraints);if(!e.ok)return void o(i.invalidDefinition,`'${t}' declares invalid constraints: expected ${e.expected}, got ${e.actual}`,[...s,"constraints"]);u=a.constraints}const d="default"in a;if(d&&!0===a.required)return void o(i.invalidDefinition,`'${t}' is declared required and also declares a default — the default could never apply`,[...s,"default"]);if(d){const e=ie(a.default,c);if(!e.ok)return void o(i.typeCheck,`the default for '${t}' does not satisfy its declared type: expected ${e.expected}, got ${e.actual}`,[...s,"default"]);if(void 0!==u){const e=se(a.default,u);if(!e.ok)return void o(i.typeCheck,`the default for '${t}' violates its declared constraints: expected ${e.expected}, got ${e.actual}`,[...s,"default"])}}const p={type:c,required:a.required??!d};return d&&(p.default=a.default),"string"==typeof a.description&&(p.description=a.description),e(a.metadata)&&(p.metadata=a.metadata),void 0!==u&&(p.constraints=u),p},hr=e=>{const t=new Set,r=new Set,a=e=>{if(r.has(e.name)||t.has(e.name))return;t.add(e.name);const n=e.body;"fragmentCall"===n.kind&&void 0!==n.entry&&a(n.entry),e.returns=Ot(n),t.delete(e.name),r.add(e.name)};for(const t of e.fragments.values())a(t)},vr=(e,t)=>{const r=[],a=new Set,n=new Set,o=s=>{const l=r.indexOf(s);if(-1!==l){const e=[...r.slice(l),s],a=[...e].sort().join("\0");return n.has(a)||t(i.fragmentCycle,`fragment '${s}' reaches itself: ${e.join(" → ")} — recursion is not supported`,["fragments",s]),void n.add(a)}if(!a.has(s)){r.push(s);for(const t of e.get(s)?.fragmentCalls??[])o(t.name);r.pop(),a.add(s)}};for(const t of e.keys())o(t);return 0===n.size},yr=(e,t)=>{const r=new Set,a=n=>{if(r.has(n))return;r.add(n);const o=e.fragments.get(n),i=t.get(n);if(void 0===o||void 0===i)return;for(const e of i.fragmentCalls)a(e.name);const s=Te(i.own,i.fragmentCalls,e.fragments);o.nodeCount=s.nodeCount,o.maxDepth=s.maxDepth,o.dependencies=s.dependencies,o.identityOnly=s.identityOnly,o.caches=Kt(i),o.timeoutFallback=gr(i,e.fragments)};for(const e of t.keys())a(e)},gr=(e,t)=>{const{root:r,holes:a}=e;if(0===a.length)return;const n=[];for(const e of a){const r=br(e,t);if(void 0===r)return;n.push(r.value)}return"skeleton"===r.kind?{value:De(r.skeleton,r.holes,n)}:{value:n[0]}},br=(e,t)=>{if(void 0!==e.timeoutFallback)return e.timeoutFallback;const{node:r}=e;return"fragmentCall"===r.kind&&void 0===r.fallback?t.get(r.name)?.timeoutFallback:void 0},wr=e=>e.definition.cache&&!0!==e.instanceDefaults?.noCache,kr=["fallback","noCache"],$r=t=>{const r=[],a=(e,t,a,n)=>{r.push({severity:"error",code:e,message:t,path:a,...void 0!==n?{operator:n}:{}})},n={operators:new Map,aliases:new Map,fragments:new Map},{operators:o,aliases:s}=n,l=new Map,c=(e,t,r)=>{const n=l.get(e);return void 0!==n?(a(i.duplicateOperator,`'${e}' is already registered (by '${n}') — one namespace, no silent precedence`,t,r),!1):(l.set(e,r),!0)},u=(e,t)=>{if("function"==typeof e)return void a(i.invalidOptions,`operators[${t[1]}]${t.length>2?`[${t[2]}]`:""} is a function — factories must be called: httpOperators(client)`,t);if(!ve(e))return void a(i.invalidOptions,"every operators entry must be built with defineOperator() — a plain definition object is not accepted",t);const{name:r,alias:n}=e,l=c(r,t,r),u=void 0===n||c(n,t,r);l&&u&&(o.set(r,{definition:e}),void 0!==n&&s.set(n,r))};return Array.isArray(t.operators)?t.operators.forEach((e,t)=>{Array.isArray(e)?e.forEach((e,r)=>{Array.isArray(e)?a(i.invalidOptions,"'operators' is flattened one level only — arrays may not nest deeper",["operators",t,r]):u(e,["operators",t,r])}):u(e,["operators",t])}):a(i.invalidOptions,"'operators' must be an array",["operators"]),void 0!==t.operatorDefaults&&xr(t.operatorDefaults,o,s,a),((t,r,a,n)=>{if(void 0===t)return;if(!e(t))return void n(i.invalidOptions,"'fragments' must be a plain object",["fragments"]);for(const[e,o]of Object.entries(t)){const t=mr(e,o,n);void 0!==t&&a(e,["fragments",e])&&r.fragments.set(e,t)}const o=new Map;for(const[e,a]of r.fragments){const n=t[e],i=qe(n.expression,r,{basePath:["expression"]});a.body=i.root,o.set(e,i)}hr(r);for(const[e,t]of r.fragments){const r=o.get(e);Nt(r,{fragmentParams:new Set(Object.keys(t.parameters))});for(const{issue:t}of r.issues)"error"===t.severity&&n(t.code,`fragment '${e}': ${t.message}`,["fragments",e,...t.path])}vr(o,n)&&yr(r,o);for(const[e,t]of r.fragments)for(const{issue:r}of o.get(e).issues)if("error"!==r.severity){const e={...r,path:[...r.path]};Object.freeze(e.path),t.warnings.push(Object.freeze(e))}})(t.fragments,n,(e,t)=>c(e,t,e),a),r.length>0&&(e=>{const[t]=e,r=e.length-1,a=r>0?`${t.message} (+ ${r} more issue${1===r?"":"s"})`:t.message;throw new P({code:i.invalidOptions,message:a,path:t.path,...void 0!==t.operator?{operator:t.operator}:{},issues:e})})(r),n},xr=(t,r,a,n)=>{if(e(t))for(const[o,s]of Object.entries(t)){const t=["operatorDefaults",o],l=r.get(o);if(void 0===l){const e=a.get(o);void 0!==e?n(i.invalidOptions,`'operatorDefaults' keys are canonical names — use '${e}', not its alias '${o}'`,t,e):n(i.unknownOperator,`'${o}' names no registered operator`,t);continue}if(!e(s)){n(i.invalidOptions,`the defaults for '${o}' must be a plain object`,t,o);continue}let c=!0;for(const[e,r]of Object.entries(s)){const a=[...t,e];if(kr.includes(e)){"noCache"===e&&(!0!==r?(n(i.invalidOptions,"the 'noCache' modifier takes only the literal true",a,o),c=!1):l.definition.cache||(n(i.invalidOptions,`'noCache' on '${o}', which never caches — its definition does not declare 'cache: true'`,a,o),c=!1));continue}const s=l.definition.parameters[e];if(void 0===s){n(i.invalidOptions,`'${e}' names no declared parameter of '${o}' (nor 'fallback'/'noCache')`,a,o),c=!1;continue}if(s.required){n(i.invalidOptions,`'${e}' is a required parameter of '${o}' — operatorDefaults may only target optional parameters`,a,o),c=!1;continue}const u=ie(r,s.type);if(u.ok){if(void 0!==s.constraints){const t=se(r,s.constraints);t.ok||(n(i.typeCheck,`the default for '${o}.${e}' violates its declared constraints: expected ${t.expected}, got ${t.actual}`,a,o),c=!1)}}else n(i.typeCheck,`the default for '${o}.${e}' does not satisfy its declared type: expected ${u.expected}, got ${u.actual}`,a,o),c=!1}c&&(l.instanceDefaults=Object.freeze({...s}))}else n(i.invalidOptions,"'operatorDefaults' must be a plain object",["operatorDefaults"])},jr=(e,t)=>{const r=e.operators.get(t);if(void 0!==r)return r;const a=e.aliases.get(t);return void 0!==a?e.operators.get(a):void 0},Pr="fig-tree:scope-settled",Or="fig-tree:request-expired",Ar="fig-tree:evaluation-timeout";class Dr{parent;controller;upstream;forward;settled=!1;verified=-1;clock;constructor(e){this.parent=e,this.clock=void 0===e?{epoch:0}:e.clock}get aborted(){return void 0!==this.controller?this.controller.signal.aborted:!!this.settled||this.verified!==this.clock.epoch&&(!(void 0===this.parent||!this.parent.aborted)||(this.verified=this.clock.epoch,!1))}get reason(){return void 0!==this.controller?this.controller.signal.reason:this.settled?Pr:this.parent?.reason}get signal(){if(void 0===this.controller){const e=new AbortController;if(this.controller=e,this.settled)e.abort(Pr);else if(void 0!==this.parent){const t=this.parent.signal;t.aborted?e.abort(t.reason):(this.upstream=t,this.forward=()=>e.abort(t.reason),t.addEventListener("abort",this.forward,{once:!0}))}}return this.controller.signal}settle(){this.settled||(this.settled=!0,this.clock.epoch+=1,void 0!==this.controller&&(void 0!==this.upstream&&void 0!==this.forward&&this.upstream.removeEventListener("abort",this.forward),this.controller.abort(Pr)))}}const Nr=(e,t)=>({get aborted(){return e.aborted},get reason(){return e.reason},signal:e,clock:t.clock,settle:O}),Cr=(e,t,r)=>{const a=void 0===e?(()=>{const e=new AbortController;return{signal:e.signal,abort:t=>e.abort(t),settle:()=>e.abort(Pr)}})():(e=>{const t=new AbortController;e.aborted&&t.abort(e.reason);const r=()=>t.abort(e.reason);return e.addEventListener("abort",r,{once:!0}),{signal:t.signal,abort:e=>t.abort(e),settle:()=>{e.removeEventListener("abort",r),t.abort(Pr)}}})(e),{signal:n}=a;let o;const i=new Promise((e,t)=>{o=t});i.catch(O);const s=()=>o(n.reason);n.aborted?s():n.addEventListener("abort",s,{once:!0});const l=void 0===t?void 0:setTimeout(()=>a.abort(r),Math.min(t,2147483647));return{signal:n,expiry:i,settle:()=>{void 0!==l&&clearTimeout(l),n.removeEventListener("abort",s),a.settle()}}},Sr=(e,t)=>Cr(e,t,Or),qr=(e,t)=>(r,a)=>{const n=(o=[e.operator,e.fingerprint,r],ir(o,[]));var o;return void 0===n?a():(async(e,t,r,a)=>{const n=e.generation,o=await e.lookup(t);if(a?.({type:"cache",hit:o.hit}),o.hit)return o.value;const i=await r();return await e.write(t,i,n),i})(t,n,a,e.note)},Tr=/*#__PURE__*/Object.freeze({}),Er=(e,t)=>!0!==t||!0===e.noCache?e:{...e,noCache:t};class zr{options;cache;trace;#e;constructor(e,t,r,a){this.options=t,this.cache=r,this.trace=a,this.#e=e}get signal(){return this.#e.signal}}const Mr={memo:(e,t)=>t()},Fr={note:O},Lr=Symbol("fig-tree:internal-error"),Rr=e=>Kr(`[fig-tree internal] ${e}`,Lr),Vr=e=>_r(e,Lr),Ir=Symbol("fig-tree:cancelled"),Qr=()=>Kr("[fig-tree] evaluation cancelled",Ir),Jr=e=>_r(e,Ir),Ur=(e,t,r)=>e.rootScope.aborted?Gr(e.rootScope.reason,t,r):e.abortScope.aborted?Qr():void 0,Gr=(e,t,r)=>e===Pr?Qr():Wr(e,xe(t),{operator:r}),Wr=(e,t,r={})=>{const{operator:a,ms:n}=r,o=e===Ar,s=void 0===n?"":`${n}ms `;return new P({code:o?i.timeout:i.aborted,message:o?`evaluation exceeded its ${s}timeout`:"evaluation was aborted by the caller",path:t,...void 0!==a?{operator:a}:{}})},Br=e=>A(e)&&(e.code===i.aborted||e.code===i.timeout),Kr=(e,t)=>{const r=new Error(e);return Hr(r,t),r},Hr=(e,t)=>{e[t]=!0},_r=(e,t)=>e instanceof Error&&!0===e[t],Xr=()=>performance.now(),Yr=e=>{const t=new Map,r=new WeakMap;let a;const n=(e,r,a)=>{const n=t.get(e);if(void 0===n)return;t.delete(e),"fallback"!==e.status&&(e.status=r),void 0!==a.error&&void 0===e.error&&(e.error=a.error),"failed"!==r&&"cancelled"!==r&&(e.value=a.value),void 0!==a.elapsed&&(e.elapsed=a.elapsed);const o=[...n.children,...Zr(n)];o.length>0&&(e.children=o.sort((e,t)=>e.order-t.order||e.index-t.index).map(e=>e.entry))},o=(e,t)=>{(e.events??=[]).push(t)};return{enter:(e,n,o,i)=>{const s=oa(e),l=ia(e),c={path:xe(e.path),kind:na(e),status:"value",...void 0!==o?{source:{fragment:o.fragment}}:{},...void 0!==s?{operator:s}:{},...void 0!==l?{ref:l}:{},...void 0!==i?.var?{var:i.var}:{}};return t.set(c,{node:e,children:[],seen:new Set}),r.set(e,c),((e,r,n)=>{if(void 0===e)return void(a=r.entry);const o=t.get(e);void 0!==o&&(o.children.push(r),o.seen.add(n))})(n,{entry:c,order:e.order,index:i?.index??0},e),c},settle:n,markFallback:(e,t)=>{e.status="fallback",e.error=t},note:o,noteOn:(e,t)=>{const a=r.get(e);void 0!==a&&o(a,t)},finish:()=>{for(const e of[...t.keys()].reverse())n(e,"cancelled",{});return void 0!==a&&e.length>0&&(a.warnings=e),a}}},Zr=e=>ea(e.node).filter(t=>!e.seen.has(t)).map(e=>({entry:{path:xe(e.path),kind:na(e),status:"skipped"},order:e.order,index:0})),ea=e=>{switch(e.kind){case"operator":return[...Object.values(e.params).flatMap(ta),...void 0!==e.fallback?[e.fallback]:[],...Object.values(e.vars??{})];case"fragmentCall":return[...ra(e.parameters),...void 0!==e.fallback?[e.fallback]:[],...Object.values(e.vars??{}),...void 0!==e.entry?[e.entry.body]:[]];case"skeleton":return[...e.holes.map(e=>e.node),...Object.values(e.vars??{})];case"elements":return e.nodes;case"entries":return Object.values(e.entries);default:return[]}},ta=e=>"elements"===e.kind||"entries"===e.kind?ea(e):[e],ra=e=>void 0===e?[]:aa(e)?[e]:Object.values(e),aa=e=>"string"==typeof e.kind,na=e=>{switch(e.kind){case"operator":return"operator";case"fragmentCall":return"fragment";case"reference":return"reference";case"skeleton":return"skeleton";default:return"literal"}},oa=e=>"operator"===e.kind||"fragmentCall"===e.kind?e.name:void 0,ia=e=>"reference"===e.kind?e.raw:void 0,sa=(e,t)=>{if(void 0===t)return e;const r={parent:e.scope,vars:new Map},a={...e,scope:r};for(const[e,n]of Object.entries(t))r.vars.set(e,D(()=>Ka(n,a,{var:e})));return a},la=async(e,t,r,a,n)=>{const o={...r,params:"dynamic"===e.argumentsMode?await ua(e,t,a):ca(e,t,a),frame:n};delete o.scope,delete o.bindings;const i=await Ka(t.body,o);return void 0===i?null:i},ca=(e,t,r)=>{const a=e.parameters??{},n=new Map;for(const[o,i]of Object.entries(t.parameters)){const t=a[o],s=D(async()=>{if(void 0===t)return da(e,o,i,r);let a;try{a=await Ka(t,r)}catch(e){throw va(e,r.frame)}return pa(e,o,i,a,t.path,r)});n.set(o,()=>{const e=s();return e.catch(O),e})}return n},ua=async(t,r,a)=>{const n=t.parameters;let o;try{o=await Ka(n,a)}catch(e){throw va(e,a.frame)}if(!e(o))throw va(ma(t,i.typeCheck,`'parameters' must evaluate to an object, received ${fa(o)}`,n.path),a.frame);const s=new Map;for(const[e,i]of Object.entries(r.parameters)){const r=Object.hasOwn(o,e)?pa(t,e,i,o[e],n.path,a):da(t,e,i,a,n.path);s.set(e,()=>Promise.resolve(r))}return s},da=(e,t,r,a,n=e.path)=>{if(!r.required)return r.default??null;throw va(ma(e,i.missingRequired,`requires '${t}'`,n),a.frame)},pa=(e,t,r,a,n,o)=>{const s=void 0===a?null:a;if(null===s&&!r.required&&!ae(r.type))return r.default??null;if(!o.runtimeTypeCheck)return s;const l=ie(s,r.type);if(!l.ok)throw va(ma(e,i.typeCheck,`parameter '${t}': expected ${l.expected}, received ${l.actual}`,n),o.frame);if(void 0!==r.constraints){const a=se(s,r.constraints);if(!a.ok)throw va(ma(e,i.typeCheck,`parameter '${t}': expected ${a.expected}, received ${a.actual}`,n),o.frame)}return s},ma=(e,t,r,a)=>new P({code:t,message:`fragment '${e.name}' – ${r}`,path:xe(a)}),fa=e=>null===e?"null":Array.isArray(e)?"array":typeof e,ha=Symbol("fig-tree:anchored"),va=(e,t)=>!A(e)||_r(e,ha)?e:(Hr(e,ha),void 0===t||(e.fragment=t.fragment,e.fragmentPath=e.path,e.path=xe(t.callPath)),e);class ya extends Error{code;errorData;constructor(e,t={}){super(e),this.name="OperatorFailure",void 0!==t.code&&(this.code=t.code),void 0!==t.errorData&&(this.errorData=t.errorData)}}const ga=e=>e instanceof ya,ba=(e,t,r)=>ka(Array.from({length:e},(e,a)=>wa(a,()=>t(a),r)),e),wa=async(e,t,r)=>{try{return{index:e,ok:!0,value:r(await t())}}catch(t){return{index:e,ok:!1,error:t}}},ka=(e,t)=>{const r=new Map(e.map((e,t)=>[t,e]));return{[ar]:!0,length:t,async*[Symbol.asyncIterator](){for(;r.size>0;){const e=await Promise.race(r.values());r.delete(e.index),yield e}}}},$a=e=>({[ar]:!0,evaluate:D(e)}),xa=e=>({[ar]:!0,evaluate:()=>Promise.resolve(e)}),ja=(e,t,r,a,n)=>$a(async()=>Pa(await Ka(e,n),t,r,a,n)),Pa=(e,t,r,a,n)=>{if(n.runtimeTypeCheck){const n=ie(e,a.type);if(!n.ok)throw Ca(t,r,n);if(null!==e&&void 0!==a.constraints){const n=pe(e,a.constraints,void 0!==a.elementNullPolicy);if(!n.ok)throw Ca(t,r,n)}}return a.truthiness?Ea(e,a.type):e},Oa=(e,t,r,a,n,o)=>{const i=Array.isArray(t)?t:[],s=Oe(r),l=new Map,c=t=>{const c=l.get(t);if(void 0!==c)return c;const u=(async()=>Pa(await Ka(e,((e,t,r,a)=>({...e,bindings:{parent:e.bindings,as:t,element:r,index:a}}))(o,s,i[t],t),{index:t}),r,a,n,o))();return u.catch(O),l.set(t,u),u};return{[ar]:!0,evaluate:c,settle:()=>ba(i.length,c,e=>e)}},Aa=(e,t)=>t.truthiness?M(e):e,Da=(e,t,r)=>{if("lazyElements"===t.evaluation&&"elements"===e.kind)return e.nodes.map((e,a)=>$a(async()=>Aa(await Ka(e,r,{index:a}),t)));if("race"===t.evaluation&&"elements"===e.kind)return((e,t,r)=>ba(e.length,r=>Ka(e[r],t,{index:r}),r))(e.nodes,r,e=>Aa(e,t));if("lazyEntries"===t.evaluation&&"entries"===e.kind){const a=sa(r,e.vars),n={};for(const[r,o]of Object.entries(e.entries))n[r]=$a(async()=>Aa(await Ka(o,a),t));return n}},Na=(e,t)=>{switch(t.evaluation){case"lazyElements":return e.map(e=>xa(Aa(e,t)));case"race":return((e,t)=>ba(e.length,t=>Promise.resolve(e[t]),t))(e,e=>Aa(e,t));case"lazyEntries":{const r={};for(const[a,n]of Object.entries(e))r[a]=xa(Aa(n,t));return r}case"lazy":return xa(e);default:return e}},Ca=(e,t,r)=>new P({code:i.typeCheck,message:`${e.name} – parameter '${t}': expected ${r.expected}, received ${r.actual}`,path:xe(e.path),operator:e.name}),Sa=(e,t,r)=>{if("string"==typeof t.nullPolicy)return t.nullPolicy;const a=t.nullPolicy,n=e.entry.definition.parameters[a.selector],o=r[a.selector],i=ie(o,n.type);if(!i.ok)throw Ca(e,a.selector,i);const s=a.table.find(e=>e.value===o);if(void 0===s)throw Rr(`no null-policy row for ${e.name}.${a.selector}`);return s.policy},qa=async(t,r,a)=>{if(void 0!==r.elementNullPolicy){if(Array.isArray(t)&&t.includes(null)){const e=await a();return t.map(t=>null===t?e:t)}if(e(t)&&Object.values(t).includes(null)){const e=await a(),r={};for(const[a,n]of Object.entries(t))r[a]=null===n?e:n;return r}return t}return null===t?a():t},Ta=t=>Array.isArray(t)?t.includes(null):!!e(t)&&Object.values(t).includes(null),Ea=(t,r)=>{if((e=>!("object"==typeof e&&!Array.isArray(e))&&(Array.isArray(e)?e:[e]).every(e=>"array"===e||"object"===e))(r)){if(Array.isArray(t))return t.map(M);if(e(t)){const e={};for(const[r,a]of Object.entries(t))e[r]=M(a);return e}}return M(t)},za=async(e,t)=>{const{params:r,propagate:a}=await(async(e,t)=>{const{definition:r,instanceDefaults:a}=e.entry,{entries:n,whole:o,perElement:i}=r.resolution,s=[],l=[],c={};let u;const d={};for(const[r,o]of n){const n=e.params[r];switch(o.evaluation){case"eager":void 0!==n&&(s.push(r),l.push(Ka(n,t)));break;case"structural":"constant"===n?.kind&&(c[r]=n.value);break;case"lazy":if(void 0!==o.replacesNullAt){const e=void 0!==n?D(()=>Ka(n,t)):void 0!==a&&Object.hasOwn(a,r)?D(()=>a[r]):void 0;if(void 0!==e)for(const t of o.replacesNullAt)(u??={})[t]=e;break}void 0!==n&&(d[r]=ja(n,e,r,o,t));break;case"lazyElements":case"lazyEntries":case"race":{if(void 0===n)break;const e=Da(n,o,t);if(void 0!==e){d[r]=e;break}s.push(r),l.push(Ka(n,t));break}case"perElement":break;default:o.evaluation}}if(l.length>0)if(1===l.length){const e=l[0];c[s[0]]=N(e)?await e:e}else{const e=await Promise.all(l);s.forEach((t,r)=>{c[t]=e[r]})}for(const[e,r]of o){if(Object.hasOwn(d,e))continue;const n=c[e];(void 0===n||null===n&&!r.required&&!ae(r.type))&&(void 0!==a&&Object.hasOwn(a,e)?c[e]=a[e]:"default"in r?c[e]=r.default===fe?t.data:r.default:delete c[e])}for(const[r,a]of o){if(Object.hasOwn(d,r))continue;let n=c[r];if(void 0===n)continue;const o=u?.[r];void 0!==o&&(n=await qa(n,a,o));const i="eager"!==a.evaluation&&"structural"!==a.evaluation;if(null===n&&ae(a.type)&&!i&&"propagate"===Sa(e,a,c))return{params:d,propagate:!0};if("propagate"===a.elementNullPolicy&&Ta(n))return{params:d,propagate:!0};n=Pa(n,e,r,a,t),d[r]=Na(n,a)}for(const[r,a]of i){if(void 0===a.over)throw Rr(`parameter '${r}' of '${e.name}' declares perElement without 'over'`);const n=e.params[r];void 0!==n&&(d[r]=Oa(n,d[a.over],e,r,a,t))}return{params:d,propagate:!1}})(e,t);if(a)return null;const{definition:n}=e.entry,o=!0!==t.noCache&&wr(e.entry),i=Fa(n,r),s=void 0===i?void 0:Sr(t.abortScope.signal,i),l=void 0===s?t:{...t,abortScope:Nr(s.signal,t.abortScope)},c=(e=>{const{trace:t,traceParent:r}=e;if(void 0!==t&&void 0!==r)return e=>{t.note(r,e)}})(t),u=((e,t,r,a)=>new zr(e.abortScope,e.options,r?{memo:qr({operator:t.name,fingerprint:t.fingerprint,note:a},e.cache)}:Mr,void 0===a?Fr:{note:a}))(l,n,o,c);try{return await Ma(e,t,r,u,s)}catch(r){throw La(r,e,t,s,i)}finally{s?.settle()}},Ma=async(e,t,r,a,n)=>{const o=Ur(t,e.path,e.name);if(void 0!==o)throw o;const i=Promise.resolve(e.entry.definition.evaluate(r,a));return void 0===n?Va(await i,e):(i.catch(O),Va(await Promise.race([i,n.expiry]),e))},Fa=(e,t)=>{const r=e.timeoutParam;if(null===r)return;const a=t[r];return"number"==typeof a&&a>0?a:void 0},La=(e,t,r,a,n)=>{if(Vr(e)||Jr(e))return e;const o=Ur(r,t.path,t.name);return void 0!==o?o:a?.signal.reason===Or?new ya(`request exceeded its ${String(n)}ms timeout`,{code:i.requestTimeout}):e},Ra=(e,t)=>{const r=e.fallback;if(void 0!==r)return()=>Ka(r,t);const a=e.entry.instanceDefaults;return void 0!==a&&Object.hasOwn(a,"fallback")?()=>a.fallback:void 0},Va=(e,t)=>{if(void 0===e)return null;if("number"==typeof e&&!Number.isFinite(e))throw new P({code:i.nonFiniteResult,message:`${t.name} – produced a non-finite number (${String(e)})`,path:xe(t.path),operator:t.name});if("object"==typeof(r=e)&&null!==r&&!0===r[ar])throw new P({code:i.escapedHandle,message:`${t.name} – returned a lazy handle instead of evaluating it`,path:xe(t.path),operator:t.name});var r;return e},Ia=(e,t)=>{if(A(e))return e;if(ga(e))return new P({code:e.code??i.operatorFailure,message:`${t.name} – ${e.message}`,path:xe(t.path),operator:t.name,...void 0!==e.errorData?{errorData:e.errorData}:{}});const r=e instanceof Error?e.message:String(e);return new P({code:i.operatorFailure,message:`${t.name} – ${r}`,path:xe(t.path),operator:t.name})},Qa=(e,t)=>0===e.segments.length?t.data:Wa(t.data,e.segments,e,t,"is absent from the evaluation data"),Ja=async(e,t)=>{const[r,...a]=e.segments,n="string"==typeof r?((e,t)=>{for(let r=e;void 0!==r;r=r.parent){const e=r.vars.get(t);if(void 0!==e)return e}})(t.scope,r):void 0;if("string"!=typeof r||void 0===n)throw Rr(`'${e.raw}': no var named '${String(r)}' is in scope — the static gate should have refused it`);const o=await n();return 0===a.length?Ba(o):Wa(o,a,e,t,`is absent from the value of '$vars.${r}'`)},Ua=async(e,t)=>{const r=t.params;if(void 0===r)throw Rr(`'${e.raw}': $params outside a fragment body — the static gate should have refused it`);const[a,...n]=e.segments;if(void 0===a){const e={};return await Promise.all([...r].map(async([t,r])=>{e[t]=Ba(await r())})),e}const o="string"==typeof a?r.get(a):void 0;if(void 0===o)throw Rr(`'${e.raw}': the fragment declares no parameter '${String(a)}' — the static gate should have refused it`);const i=await o();return 0===n.length?Ba(i):Wa(i,n,e,t,`is absent from the value of '$params.${String(a)}'`)},Ga=(e,t)=>{const r=e.namespace,a=((e,t,r)=>{for(let a=e;void 0!==a;a=a.parent)if(Ae(a.as,t,r))return a})(t.bindings,r,e.binding);if(void 0===a)throw Rr(`'${e.raw}': no enclosing iterator binds it — the static gate should have refused it`);return"index"===r?a.index:0===e.segments.length?Ba(a.element):Wa(a.element,e.segments,e,t,`is absent from '${e.raw.split(".")[0]}'`)},Wa=(e,t,r,a,n)=>{const o=k(e,t);if(o.found)return Ba(o.value);if(!a.strictDataPaths)return null;throw new P({code:i.missingDataPath,message:`'${r.raw}' ${n} (strictDataPaths)`,path:xe(r.path)})},Ba=e=>void 0===e?null:e,Ka=(e,t,r)=>void 0!==t.trace?Ha(e,t,t.trace,r):t.abortScope.aborted?Promise.reject(Ur(t,e.path)):_a(e,t),Ha=async(e,t,r,a)=>{const n=r.enter(e,t.traceParent,t.frame,a),o=Xr();try{if(t.abortScope.aborted)throw Ur(t,e.path);const a=await _a(e,{...t,traceParent:n});return r.settle(n,"value",{value:a,elapsed:Xr()-o}),a}catch(e){throw r.settle(n,Jr(e)?"cancelled":"failed",{...A(e)?{error:e}:{},elapsed:Xr()-o}),e}},_a=(e,t)=>{try{switch(e.kind){case"constant":return e.value;case"reference":return((e,t)=>{switch(e.namespace){case"data":return Qa(e,t);case"vars":return Ja(e,t);case"params":return Ua(e,t);case"element":case"index":return Ga(e,t)}})(e,t);case"skeleton":return Xa(e,t);case"operator":return(async(e,t)=>{const r=sa(Er(t,e.noCache),e.vars),a=e.entry.definition.deliversLazily?new Dr(r.abortScope):void 0,n=void 0===a?r:{...r,abortScope:a};try{try{return await za(e,n)}finally{a?.settle()}}catch(a){if(Vr(a)||Jr(a)||Br(a))throw a;const n=Ia(a,e),o=Ra(e,r);if(void 0===o)throw n;try{const e=await o();return void 0!==t.trace&&void 0!==t.traceParent&&t.trace.markFallback(t.traceParent,n),e}catch(t){if(Vr(t)||Jr(t)||Br(t))throw t;const r=Ia(t,e);throw void 0===r.cause&&(r.cause=n),r}}})(e,t);case"fragmentCall":return(async(e,t)=>{const{entry:r}=e;if(void 0===r)throw Rr(`fragment call '${e.name}' resolved to nothing — the static gate should have refused it`);const a=sa(Er(t,e.noCache),e.vars),n=new Dr(a.abortScope),o={fragment:e.name,callPath:t.frame?.callPath??e.path},i={...a,abortScope:n};try{try{return await la(e,r,i,a,o)}finally{n.settle()}}catch(r){if(Vr(r)||Jr(r)||Br(r))throw r;const n=va(r,o),{fallback:i}=e;if(void 0===i)throw n;try{return await Ka(i,a)}catch(e){if(Vr(e)||Jr(e)||Br(e))throw e;const r=va(e,t.frame);throw A(r)&&void 0===r.cause&&(r.cause=n),r}}})(e,t);case"elements":case"entries":throw Rr(`a '${e.kind}' parameter value reached the node dispatch — parameter resolution consumes these, and nothing else may hold one`);case"invalid":throw Rr("an invalid node reached evaluation — the static gate should have refused it")}}catch(e){return Promise.reject(e)}},Xa=async(e,t)=>{const r=t.rootBoundary,a=void 0===r?t:{...t,rootBoundary:void 0},n=sa(a,e.vars),o=e.holes.map(e=>void 0===r?Ka(e.node,n):r(()=>Ka(e.node,n),e.node)),i=o.some(N)?await Promise.all(o):o;return De(e.skeleton,e.holes,i)},Ya=Number.MAX_SAFE_INTEGER,Za=(e,t)=>{if(A(e))return e;const r=e instanceof Error?e.message:String(e);return new P({code:i.operatorFailure,message:r,path:t.path})},en=(e,t)=>{if(void 0===e.holePath)return e.holePath=t,e;const r=new P({...e,message:e.message,holePath:t});return r.stack=e.stack,r},tn=async(e,t,r)=>{const{timeout:a,signal:n}=t,o="report"===t.mode,s=e.holes.length>0,l=void 0!==a||void 0!==n?Cr(n,a,Ar):void 0,c=void 0!==l?((e,t)=>{const r={epoch:0};return e.addEventListener("abort",()=>{r.epoch+=1},{once:!0}),{get aborted(){return e.aborted},get reason(){return e.reason},signal:e,clock:r,settle:t}})(l.signal,l.settle):new Dr(void 0),u=void 0!==l&&void 0!==a&&e.timeoutShielded&&s,d=o?(()=>{const e=[];return{record:(t,r)=>{e.push({error:en(Za(t,r),r.path),order:r.node.order})},add:t=>{e.push({error:t,order:Ya})},emit:()=>[...e].sort((e,t)=>e.order-t.order).map(e=>e.error)}})():void 0,p=!0===t.trace?Yr(e.issues.map(e=>e.issue).filter(e=>"error"!==e.severity)):void 0,m=((e,t,r,a)=>({options:e,data:e.data??Tr,abortScope:r,rootScope:r,cache:t,strictDataPaths:e.strictDataPaths??!1,runtimeTypeCheck:e.runtimeTypeCheck??!0,...void 0!==a?{trace:a}:{}}))(t,r,c,p),f=s&&(void 0!==d||u)?on(e,d,u?l.expiry:void 0,p):void 0,h=void 0!==f&&"skeleton"!==e.root.kind,v=void 0===f||h?m:{...m,rootBoundary:f};try{if(c.aborted)throw Wr(c.reason,[]);const t=()=>h&&void 0!==f?f(()=>Ka(e.root,v),e.root):Ka(e.root,v),r=await(u||void 0===l?t():nn(t,l,a));return void 0!==d&&u&&an(l)&&d.add(Wr(Ar,[],{ms:a})),rn(r,d,p)}catch(e){if(void 0!==d&&A(e)&&e.code===i.timeout)return d.add(e),rn(null,d,p);throw void 0!==p&&A(e)&&void 0===e.trace&&(e.trace=p.finish()),e}finally{c.settle()}},rn=(e,t,r)=>({result:e,errors:t?.emit()??[],...void 0!==r?{trace:r.finish()}:{}}),an=e=>e.signal.aborted&&e.signal.reason===Ar,nn=(e,t,r)=>Promise.race([e(),t.expiry.catch(e=>{throw Wr(e,[],{ms:r})})]),on=(e,t,r,a)=>{const n=new Map(e.holes.map(e=>[e.node,e]));return(e,o)=>{const i=n.get(o);if(void 0===i)throw Rr(`the hole boundary was handed the node at ${JSON.stringify(xe(o.path))}, which is not one of the artifact's holes`);const s=void 0===t?Promise.resolve(e()):sn(e,i,t);if(void 0===r)return s;let l=!1;const c=s.then(e=>(l=!0,e));return Promise.race([c,r.catch(e=>{if(e!==Ar)throw Wr(e,[]);if(!l)return a?.noteOn(i.node,{type:"shielded-fallback"}),ln(i)})])}},sn=async(e,t,r)=>{try{return await e()}catch(e){if(Vr(e)||Jr(e)||Br(e))throw e;return r.record(e,t),null}},ln=e=>{if(void 0===e.timeoutFallback)throw Rr("a shielded artifact has a hole with no static fallback");return e.timeoutFallback.value},cn={hit:!1},un=e=>{if(void 0===e)return{maxSize:50,maxTime:1800};if(!n(e))throw pn("'cache' must be an object");const{store:t,maxSize:r,maxTime:a}=e;if(void 0!==t&&!dn(t))throw pn("'cache.store' must provide get, set, delete and clear methods");if(void 0!==r&&(!Number.isInteger(r)||r<1))throw pn("'cache.maxSize' must be a positive integer");if(void 0!==a&&("number"!=typeof a||a<=0||Number.isNaN(a)))throw pn("'cache.maxTime' must be a positive number of seconds, or Infinity");return{...void 0!==t?{store:t}:{},maxSize:r??50,maxTime:a??1800}},dn=e=>"object"==typeof e&&null!==e&&["get","set","delete","clear"].every(t=>"function"==typeof e[t]),pn=e=>new P({code:i.invalidOptions,message:e,path:[]});class mn{store;own;maxTime;current=0;constructor(e){void 0===e.store?(this.own=new tr(e.maxSize),this.store=this.own):this.store=e.store,this.maxTime=e.maxTime}get generation(){return this.current}async lookup(e){let t;try{t=await this.store.get(e)}catch{return cn}return n(r=t)&&"ft3"===r.fig&&"number"==typeof r.generation?t.generation<this.current||fn(t)?(this.drop(e),cn):{hit:!0,value:t.value}:cn;var r}async write(e,t,r){if(r!==this.current)return;const a={fig:"ft3",value:t,generation:r,...Number.isFinite(this.maxTime)?{expiresAt:Date.now()+1e3*this.maxTime}:{}};try{await this.store.set(e,a)}catch{}}clear(){this.current+=1;try{Promise.resolve(this.store.clear()).catch(O)}catch{}}configure(e){void 0!==e.store&&e.store!==this.store&&(this.store=e.store,this.own=void 0),this.maxTime=e.maxTime,this.own?.resize(e.maxSize)}drop(e){try{Promise.resolve(this.store.delete(e)).catch(O)}catch{}}}const fn=e=>void 0!==e.expiresAt&&e.expiresAt<=Date.now(),hn=e=>e===C?0:"number"==typeof e?1:2,vn=e=>({data:{paths:[...e.dataPaths].sort(([,e],[,t])=>((e,t)=>{const r=Math.min(e.length,t.length);for(let a=0;a<r;a++){const r=e[a],n=t[a];if(r===n)continue;const o=hn(r)-hn(n);return 0!==o?o:"number"==typeof r&&"number"==typeof n?r-n:r<n?-1:1}return e.length-t.length})(e,t)).map(([e])=>e),dynamic:e.dynamic},operators:[...e.operators],fragments:[...e.fragments]}),yn=(e,t)=>{const r={};for(const[a,n]of Object.entries(e)){const e={...n};void 0!==t&&Object.hasOwn(t,a)&&(e.instanceDefault=t[a]),r[a]=e}return r},gn=(e,t)=>{const r=[];return void 0!==t.maxDepth&&e.maxDepth>t.maxDepth&&r.push(bn(e.maxDepth,t.maxDepth)),void 0!==t.maxNodes&&e.nodeCount>t.maxNodes&&r.push({severity:"error",code:i.maxNodesExceeded,message:`the expression holds ${e.nodeCount} evaluable nodes — maxNodes is ${t.maxNodes}`,path:[]}),r},bn=(e,t)=>({severity:"error",code:i.maxDepthExceeded,message:`the expression nests ${e} levels deep — maxDepth is ${t}`,path:[]}),wn=(e,t,r)=>{const a=[...gn(e,t),...e.issues.map(r)];return void 0!==t.data&&a.push(...kn(e.dataReads,t.data)),a},kn=(e,t)=>{const r=new Map,a=new Map,n=[],o=(e,o,s,l)=>{let c=r.get(e);if(void 0===c&&(c=k(t,o).found,r.set(e,c)),c)return;let u=a.get(s.path);if(void 0===u&&a.set(s.path,u=new Set),u.has(e))return;u.add(e);const d=void 0===l?"":` (read by fragment '${l}')`;n.push({severity:"warning",code:i.missingDataPath,message:`'${S(o)}' is absent from the supplied sample data${d}`,path:xe(s.path)})};for(const t of e)if("path"===t.kind)o(t.key,t.segments,t,void 0);else for(const[e,r]of t.fragment.dependencies.dataPaths)o(e,r,t,t.fragment.name);return n},$n="...",xn=/*#__PURE__*/new Set(["propagate","value"]),jn=e=>{const t={};for(const[r,a]of Object.entries(e.parameters))t[r]=a.type??"any";const r=Pn(e.parameters,t,(t,r,a)=>{throw new P({code:t,message:r,path:a,operator:e.name})});return On(e,r)},Pn=(e,r,a)=>{const n=Object.entries(r).filter(([,e])=>t(e)).map(([e])=>e),o=new Map;for(const[s,l]of Object.entries(e)){if("function"!=typeof l.nullPolicy)continue;const e=["parameters",s,"nullPolicy"];if(1!==n.length){a(i.invalidNullPolicy,`a conditional 'nullPolicy' requires exactly one literal-union parameter in the definition — found ${n.length}`,e,s);continue}const c=n[0],u=r[c];if(!t(u))continue;const d=[];let p=!0;for(const t of u.literal){let r;try{r=l.nullPolicy(t)}catch(r){a(i.invalidNullPolicy,`the conditional 'nullPolicy' threw during compilation for member ${JSON.stringify(t)}: ${String(r)}`,e,s),p=!1;break}if("string"!=typeof r||!xn.has(r)){a(i.invalidNullPolicy,`the conditional 'nullPolicy' must return 'propagate' or 'value' for every member — got ${JSON.stringify(r)} for ${JSON.stringify(t)}`,e,s),p=!1;break}d.push({value:t,policy:r})}p&&o.set(s,{selector:c,table:d})}return o},On=(e,t)=>{const r={};for(const[a,n]of Object.entries(e.parameters)){const e=t.get(a),o="string"==typeof n.nullPolicy?n.nullPolicy:void 0,i=n.type??"any",s=!0===n.truthiness&&ae(i)?"value":"propagate",l={type:Dn(i),required:n.required??!("default"in n),evaluation:n.evaluation??"eager",truthiness:n.truthiness??!1,nullPolicy:e??o??s};"default"in n&&(l.default=n.default),void 0!==n.description&&(l.description=n.description),void 0!==n.metadata&&(l.metadata=n.metadata),void 0!==n.elementNullPolicy&&(l.elementNullPolicy=n.elementNullPolicy),void 0!==n.constraints&&(l.constraints=Nn(n.constraints)),void 0!==n.over&&(l.over=n.over),void 0!==n.replacesNullAt&&(l.replacesNullAt=[...n.replacesNullAt]),r[a]=l}const a=e.positionalParams?.at(-1),n=a?.startsWith($n)?a.slice(3):null,o={[he]:!0,name:e.name,category:e.category,description:e.description,parameters:r,resolution:Cn(r),restParam:n,deliversLazily:Object.values(r).some(e=>"eager"!==e.evaluation&&"structural"!==e.evaluation),timeoutParam:e.timeoutParam??null,cache:!0===e.cache,fingerprint:"",evaluate:e.evaluate,returns:void 0!==e.returns?Dn(e.returns):"any"};return void 0!==e.alias&&(o.alias=e.alias),void 0!==e.metadata&&(o.metadata=e.metadata),void 0!==e.positionalParams&&(o.positionalParams=[...e.positionalParams]),void 0!==e.validate&&(o.validate=e.validate),o.fingerprint=An(o),Sn(o)},An=e=>q(JSON.stringify([e.name,e.parameters,e.positionalParams,e.restParam,e.returns,e.cache,e.timeoutParam,e.evaluate,e.validate],(e,t)=>"function"==typeof t||"symbol"==typeof t||t instanceof RegExp?String(t):t)),Dn=e=>"string"==typeof e?e:t(e)?{literal:[...e.literal]}:[...e],Nn=t=>{if(Array.isArray(t))return t.map(Nn);if(e(t)){const e={};for(const[r,a]of Object.entries(t))e[r]=Nn(a);return e}return t},Cn=e=>{const t=Object.entries(e);return{entries:t,whole:t.filter(([,e])=>void 0===e.replacesNullAt&&"perElement"!==e.evaluation),perElement:t.filter(([,e])=>"perElement"===e.evaluation)}},Sn=e=>{for(const t of Object.values(e.parameters))"string"!=typeof t.type&&Object.freeze(t.type),"object"==typeof t.type&&"literal"in t.type&&Object.freeze(t.type.literal),"object"==typeof t.nullPolicy&&(t.nullPolicy.table.forEach(e=>Object.freeze(e)),Object.freeze(t.nullPolicy.table),Object.freeze(t.nullPolicy)),void 0!==t.constraints&&qn(t.constraints),void 0!==t.replacesNullAt&&Object.freeze(t.replacesNullAt),Object.freeze(t);Object.freeze(e.parameters);for(const t of Object.values(e.resolution))t.forEach(e=>Object.freeze(e)),Object.freeze(t);return Object.freeze(e.resolution),"string"!=typeof e.returns&&Object.freeze(e.returns),void 0!==e.positionalParams&&Object.freeze(e.positionalParams),Object.freeze(e)},qn=t=>{Array.isArray(t)?(t.forEach(qn),Object.freeze(t)):e(t)&&(Object.values(t).forEach(qn),Object.freeze(t))},Tn=e=>{if(Array.isArray(e))return e;try{return g(e)}catch(e){throw new ya(e.message)}},En=(e,t)=>{if("string"!=typeof e)return[];try{return g(e),[]}catch(e){return[{severity:"error",parameter:t,message:e.message}]}},zn=e=>Array.isArray(e.values)&&0===e.values.length?[{severity:"error",parameter:"values",message:"an empty values array has no result — supply at least one value"}]:[],Mn=e=>t=>{const r=t[e];return Array.isArray(r)&&0===r.length?[{severity:"warning",parameter:e,message:`an empty ${e} array is a dead expression — the result is always the identity`}]:[]},Fn=/*#__PURE__*/Mn("values"),Ln=/*#__PURE__*/Mn("input"),Rn=/*#__PURE__*/Mn("entries"),Vn=e=>Array.isArray(e.values)&&e.values.length<2?[{severity:"warning",parameter:"values",message:"fewer than two values is a dead comparison — the result never varies"}]:[],In=(e,t)=>new ya(`${e} of nothing — the values array is empty${void 0!==t?`; ${t}`:""}`,{code:i.emptyAggregate}),Qn=e=>new ya(e,{code:i.typeCheck}),Jn=async(e,t)=>{const r=[];for await(const a of e){if(a.ok&&a.value===t)return t;a.ok||r.push(a)}if(r.length>0)throw r.sort((e,t)=>e.index-t.index),Un(r);return!t},Un=e=>{const[t,...r]=e,a=r.map(e=>e.error).filter(A);return a.length>0&&A(t.error)&&void 0===t.error.related&&(t.error.related=a),t.error},Gn=async e=>{const t=new Array(e.length);let r=0;for await(const a of e){t[a.index]=a;for(let e=t[r];void 0!==e;e=t[r]){if(!e.ok)throw e.error;r+=1}}return t.map(e=>e?.value)},Wn=(e,t)=>{const r=e=>t&&"string"==typeof e?e.toLowerCase():e;if(e.length<2)return!0;const a=r(e[0]);return e.every(e=>X(r(e),a))},Bn={values:{type:"array",elementNullPolicy:"value",description:"The values compared; null is comparable (null equals null)"},caseInsensitive:{type:"boolean",default:!1,description:"Fold string operands to one case before comparing (shallow)"}},Kn={name:"equal",alias:"=",category:"comparison",description:"Are all the values equal? Deep, structural, key-order-insensitive; a cross-type comparison is false",parameters:Bn,positionalParams:["...values"],returns:"boolean",validate:Vn,evaluate:({values:e,caseInsensitive:t})=>Wn(e,t)},Hn={name:"notEqual",alias:"!=",category:"comparison",description:'Are the values NOT all equal? The exact negation of equal (never "all distinct")',parameters:Bn,positionalParams:["...values"],returns:"boolean",validate:Vn,evaluate:({values:e,caseInsensitive:t})=>!Wn(e,t)},_n=(e,t,r,a)=>({name:e,alias:t,category:"comparison",description:r,parameters:{values:{type:"array",elementNullPolicy:"propagate",constraints:{length:2,homogeneous:["number","string"]},description:"Exactly two operands: both numbers, or both strings (codepoint order)"},nullValueDefault:{type:["number","string"],required:!1,evaluation:"lazy",replacesNullAt:["values"],description:"Replaces a null operand before comparing"}},positionalParams:["...values"],returns:"boolean",evaluate:({values:e})=>{const[t,r]=e;return a(F(t,r))}}),Xn=/*#__PURE__*/_n("greaterThan",">","Is the first value strictly greater than the second?",e=>e>0),Yn=/*#__PURE__*/_n("greaterThanOrEqual",">=","Is the first value greater than or equal to the second?",e=>e>=0),Zn=/*#__PURE__*/_n("lessThan","<","Is the first value strictly less than the second?",e=>e<0),eo=/*#__PURE__*/_n("lessThanOrEqual","<=","Is the first value less than or equal to the second?",e=>e<=0),to={number:()=>0,string:()=>"",array:()=>[],object:()=>({})},ro=t=>"number"==typeof t?"number":"string"==typeof t?"string":Array.isArray(t)?"array":e(t)?"object":void 0,ao={name:"plus",alias:"+",category:"math",description:"Add numbers, concatenate strings or arrays, or shallow-merge objects — all operands must share one type",parameters:{values:{type:"array",elementNullPolicy:"propagate",constraints:{homogeneous:["number","string","array","object"]},description:"The operands; homogeneous: all numbers, strings, arrays or objects"},expect:{type:{literal:["number","string","array","object"]},required:!1,description:"Pin the mode: every operand must be this type, and an empty input yields its identity"},nullValueDefault:{type:["number","string","array","object"],required:!1,evaluation:"lazy",replacesNullAt:["values"],description:"Replaces any null operand before the addition"}},positionalParams:["...values"],returns:["number","string","array","object"],validate:({values:e,expect:t})=>void 0!==t?Fn({values:e}):zn({values:e}),evaluate:({values:e,expect:t})=>{if(0===e.length){if(void 0===t)throw In("the sum","pin the mode with 'expect' to get its identity");return to[t]()}const r=t??ro(e[0]);if(void 0===r)throw Qn(`operands must be numbers, strings, arrays or objects — received ${ee(e[0])}`);const a=e.find(e=>ro(e)!==r);if(void 0!==a)throw Qn(`all operands must be ${r}s — received ${ee(a)}${void 0===t?" beside "+r+"s":""}`);switch(r){case"number":return e.reduce((e,t)=>e+t,0);case"string":return e.join("");case"array":return e.flat(1);case"object":return Object.assign({},...e)}}},no={name:"subtract",alias:"-",category:"math",description:"Subtract one number from another",parameters:{value:{type:["number","null"],description:"The main operand"},minus:{type:["number","null"],description:"The amount subtracted from value"}},positionalParams:["value","minus"],returns:"number",evaluate:({value:e,minus:t})=>e-t},oo={name:"divide",alias:"/",category:"math",description:"Divide one number by another — true division; zero divisors fail",parameters:{value:{type:["number","null"],description:"The main operand"},by:{type:["number","null"],description:"The divisor"}},positionalParams:["value","by"],returns:"number",evaluate:({value:e,by:t})=>e/t},io={name:"modulo",category:"math",description:"The floored remainder: the result takes the sign of mod, so modulo(-7, 3) is 2",parameters:{value:{type:["number","null"],description:"The main operand"},mod:{type:["number","null"],description:"The modulus"}},positionalParams:["value","mod"],returns:"number",evaluate:({value:e,mod:t})=>(e%t+t)%t},so={name:"multiply",alias:"*",category:"math",description:"Multiply numbers together — an empty input is 1, the empty product",parameters:{values:{type:"array",elementNullPolicy:"propagate",constraints:{homogeneous:["number"]},description:"The factors"},nullValueDefault:{type:"number",required:!1,evaluation:"lazy",replacesNullAt:["values"],description:"Replaces any null factor before multiplying"}},positionalParams:["...values"],returns:"number",validate:Fn,evaluate:({values:e})=>e.reduce((e,t)=>e*t,1)},lo={name:"power",alias:"^",category:"math",description:"Raise a base to an exponent — overflow and complex results fail",parameters:{base:{type:["number","null"],description:"The number to raise"},exponent:{type:["number","null"],description:"The power to raise it to"}},positionalParams:["base","exponent"],returns:"number",evaluate:({base:e,exponent:t})=>e**t},co={name:"round",category:"math",description:"Round to a number of decimal places — ties go half away from zero; negative decimals round to tens, hundreds, …",parameters:{value:{type:["number","null"],description:"The number to round"},decimals:{type:"integer",default:0,description:"Decimal places to keep; negative values round to powers of ten"}},positionalParams:["value","decimals"],returns:"number",evaluate:({value:e,decimals:t})=>((e,t=0)=>{if(!Number.isFinite(e))return e;const r=e<0?-1:1,a=Math.round(K(Math.abs(e),t));return r*K(a,-t)})(e,t)},uo=(e,t,r,a)=>({name:e,category:"math",description:t,parameters:{value:{type:["number","null"],description:r}},positionalParams:["value"],returns:"number",evaluate:({value:e})=>a(e)}),po=/*#__PURE__*/uo("floor","Round down toward negative infinity","The number to round down",Math.floor),mo=/*#__PURE__*/uo("ceil","Round up toward positive infinity","The number to round up",Math.ceil),fo=/*#__PURE__*/uo("abs","The absolute value","The number",Math.abs),ho=(e,t,r,a)=>({name:e,category:"math",description:r,parameters:{values:{type:"array",elementNullPolicy:"propagate",constraints:{homogeneous:["number","string"]},description:"The candidates: all numbers, or all strings (codepoint order)"},nullValueDefault:{type:["number","string"],required:!1,evaluation:"lazy",replacesNullAt:["values"],description:"Replaces any null candidate before comparing"}},positionalParams:["...values"],returns:["number","string"],validate:zn,evaluate:({values:e})=>{const r=e;if(0===r.length)throw In(t);return r.reduce((e,t)=>a(F(t,e))?t:e)}}),vo=(e,t,r,a)=>({name:e,category:"string",description:t,parameters:{value:{type:["string","null"],description:r}},positionalParams:["value"],returns:"string",evaluate:({value:e})=>a(e)}),yo={name:"split",category:"string",description:"Divide a string on a delimiter into an array of pieces — empty pieces are kept; an empty delimiter splits into code points",parameters:{value:{type:["string","null"],description:"The string to divide"},delimiter:{type:"string",default:" ",description:'Split on each occurrence; "" splits into code points'},trim:{type:"boolean",default:!0,description:"Trim whitespace from each piece"}},positionalParams:["value","delimiter"],returns:"array",evaluate:({value:e,delimiter:t,trim:r})=>{const a=""===t?B(e):e.split(t);return r?a.map(Q):a}},go=e=>null!==e&&"object"==typeof e,bo=e=>Array.isArray(e.values)&&e.values.some(go)?[{severity:"error",parameter:"values",message:"a composite element renders as a placeholder, never as text — drill in, or join it explicitly"}]:[],wo={name:"join",category:"string",description:"Render array elements to text and concatenate them with a delimiter",parameters:{values:{type:"array",elementNullPolicy:"value",description:'Elements of any type, rendered by the stringification table; a null renders "" and still occupies its slot'},delimiter:{type:"string",default:" ",description:"Placed between each adjacent pair — shares its contract with split"},nullValueDefault:{type:["string","number","boolean"],required:!1,evaluation:"lazy",replacesNullAt:["values"],description:'Rendered in place of a null element, instead of ""'}},positionalParams:["...values"],returns:"string",validate:e=>[...Fn(e),...bo(e)],evaluate:({values:e,delimiter:t},r)=>e.map((e,t)=>{const a=`[${t}]`;return null===e?r.trace.note({type:"render",token:a,rendered:"empty"}):go(e)&&r.trace.note({type:"render",token:a,rendered:"placeholder"}),I(e)}).join(t)},ko=e=>{const t=new Set,r=[];for(const a of e)if("imsu".includes(a)){if(t.has(a))return`duplicate regex flag '${a}'`;t.add(a)}else r.includes(a)||r.push(a);if(0===r.length)return;const a=r.includes("g")||r.includes("y")?" — all matches is mode: 'match'":"";return`unknown regex flag${1===r.length?"":"s"}: ${r.join(", ")}${a}`},$o={type:"array",description:"The collection iterated over; a null input is a type error"},xo={type:"string",required:!1,evaluation:"structural",description:"Rename the bindings: as: 'row' binds $row and $rowIndex"},jo={type:"array",required:!1,evaluation:"lazy",replacesNullAt:["input"],description:"Used as the collection when input evaluates to null — typically []"},Po={type:"any",evaluation:"perElement",over:"input",description:"The predicate, per element — a truthiness position, so null is falsy",truthiness:!0},Oo={name:"get",category:"data",description:"Read a path out of the evaluation data, or out of a supplied object — the dynamic face of a $data reference",parameters:{path:{type:["string","array","null"],description:"Dot and bracket segments, quoted keys and the [*] projection — or an array of segments, taken verbatim"},from:{type:"any",nullPolicy:"value",default:fe,description:"The object searched instead of the evaluation data — replace, never merge; a null source is one where every path is missing"},default:{type:"any",required:!1,evaluation:"lazy",description:"The answer when the path is missing — a stored null passes through unchanged (firstOf replaces one); supplying it also opts out of strictDataPaths"}},positionalParams:T,returns:"any",validate:({path:e})=>En(e,"path"),evaluate:({path:e,from:t,default:r},a)=>{const n=k(t,Tn(e));if(n.found)return void 0===n.value?null:n.value;if(void 0!==r)return r.evaluate();if(a.options.strictDataPaths)throw new ya(`'${Ao(e)}' is missing (strictDataPaths)`,{code:i.missingDataPath});return null}},Ao=e=>"string"==typeof e?e:e.map(e=>String(e)).join("."),Do={name:"buildObject",category:"data",description:"Assemble an object from computed key/value entries — for keys known only at runtime",parameters:{entries:{type:"array",constraints:{elementShape:{key:{type:["string","number","boolean"]},value:{type:"any"}}},description:'Objects with a "key" and a "value"; a null value keeps its key'}},positionalParams:["...entries"],returns:"object",validate:e=>[...Rn(e),...No(e)],evaluate:({entries:e},t)=>{const r={};for(const a of e){const e=I(a.key);Object.hasOwn(r,e)&&t.trace.note({type:"key-overwrite",key:e}),r[e]=a.value}return r}},No=e=>{const t=e.entries;if(!Array.isArray(t))return[];const r=new Set,a=new Set,n=[];for(const e of t){const t=e?.key;if("string"!=typeof t&&"number"!=typeof t&&"boolean"!=typeof t)continue;const o=I(t);r.has(o)&&!a.has(o)&&(a.add(o),n.push({severity:"warning",parameter:"entries",message:`duplicate key '${o}' — the last entry wins and the earlier one is dead`})),r.add(o)}return n},Co=(e,t)=>new ya(`cannot convert ${ee(e)} to ${t}`),So=/*#__PURE__*/[{name:"and",category:"logic",description:"True when every value is truthy — operands run in parallel",parameters:{values:{type:"array",truthiness:!0,evaluation:"race",description:"Operands, judged by FigTree truthiness; null is falsy"}},positionalParams:["...values"],returns:"boolean",validate:Fn,evaluate:({values:e})=>Jn(e,!1)},{name:"or",category:"logic",description:"True when any value is truthy — operands run in parallel",parameters:{values:{type:"array",truthiness:!0,evaluation:"race",description:"Operands, judged by FigTree truthiness; null is falsy"}},positionalParams:["...values"],returns:"boolean",validate:Fn,evaluate:({values:e})=>Jn(e,!0)},{name:"not",alias:"!",category:"logic",description:"Negate the truthiness of a value",parameters:{value:{type:"any",truthiness:!0,description:"Judged by FigTree truthiness; null is falsy, so not(null) is true"}},positionalParams:["value"],returns:"boolean",evaluate:({value:e})=>!e},{name:"if",alias:"?",category:"logic",description:"Choose between two branches — only the chosen branch evaluates",parameters:{condition:{type:"any",truthiness:!0,description:"Judged by FigTree truthiness; null is falsy"},then:{type:"any",evaluation:"lazy",description:"The value when the condition holds"},else:{type:"any",evaluation:"lazy",default:null,description:"The value when it does not; omitted means null"}},positionalParams:["condition","then","else"],evaluate:({condition:e,then:t,else:r})=>e?t.evaluate():r.evaluate()},{name:"match",category:"logic",description:"Dispatch on a value — only the matching branch evaluates",parameters:{value:{type:["string","number","boolean","null"],nullPolicy:"value",description:"Matched against branch keys by its canonical string form"},branches:{type:"object",evaluation:"lazyEntries",description:"A literal map of branches, or an expression computing one"},default:{type:"any",required:!1,evaluation:"lazy",description:"The branch taken when none matches; absent means failure"}},positionalParams:["value","branches","default"],evaluate:({value:e,branches:t,default:r})=>{const a=null===e?null:I(e);if(null!==a&&Object.hasOwn(t,a))return t[a].evaluate();if(void 0!==r)return r.evaluate();throw new ya(`no branch matches ${null===a?"null":`'${a}'`}, and no default was supplied`)}},{name:"firstOf",category:"logic",description:"The first candidate that is not null (SQL COALESCE) — later candidates never evaluate",parameters:{values:{type:"array",evaluation:"lazyElements",description:"Candidates, tried in order; only null is skipped"}},positionalParams:["...values"],validate:Fn,evaluate:async({values:e})=>{for(const t of e){const e=await t.evaluate();if(null!==e)return e}return null}},Kn,Hn,Xn,Yn,Zn,eo,ao,no,so,oo,io,lo,co,po,mo,fo,/*#__PURE__*/ho("min","the minimum","The smallest of the values — numbers numerically, strings in codepoint order",e=>e<0),/*#__PURE__*/ho("max","the maximum","The largest of the values — numbers numerically, strings in codepoint order",e=>e>0),{name:"buildString",category:"string",description:"Render a template, filling its tokens — the result is always a string",parameters:{template:{type:["string","null"],description:"The text, with %N or {{name}} tokens; in a literal template, {{$data.x}} is that reference"},substitutions:{type:["array","object"],default:[],elementNullPolicy:"value",description:"An array pairs with %N tokens, an object with {{name}} tokens; the mode dispatches on which arrives"},trim:{type:"boolean",default:!1,description:"Trim whitespace from each rendered value, never from the template text"},closeGaps:{type:"boolean",default:!1,description:"A value that renders empty also takes one run of adjacent template whitespace"},nullValueDefault:{type:["string","number","boolean"],required:!1,evaluation:"lazy",replacesNullAt:["substitutions"],description:'Rendered in place of a null value, instead of ""'}},positionalParams:["template","...substitutions"],returns:"string",evaluate:({template:e,substitutions:t,trim:r,closeGaps:a},n)=>{const o=Array.isArray(t)?t:void 0,i=void 0===o?t:void 0,s=[];for(const t of ge(e)){if("text"===t.kind){s.push({text:t.text,site:!1});continue}if(!("positional"===t.kind?void 0!==o&&t.index>=1&&t.index<=o.length:void 0!==i&&Object.hasOwn(i,t.body))){n.trace.note({type:"render",token:t.raw,rendered:"literal"}),s.push({text:t.raw,site:!1});continue}const e="positional"===t.kind?o[t.index-1]:i[t.body],a=I(e);go(e)&&n.trace.note({type:"render",token:t.raw,rendered:"placeholder"});const l=r?Q(a):a;""===l&&n.trace.note({type:"render",token:t.raw,rendered:"empty"}),s.push({text:l,site:!0,token:t.raw})}if(a)for(const e of(e=>{const t=[];for(let r=0;r<e.length;r++){const a=e[r];if(!a.site||""!==a.text)continue;const n=e[r-1];if(void 0!==n&&!n.site){const e=G(n.text);if(e!==n.text){n.text=e,t.push(a.token);continue}}const o=e[r+1];if(void 0!==o&&!o.site){const e=W(o.text);e!==o.text&&t.push(a.token),o.text=e}}return t})(s))n.trace.note({type:"render",token:e,rendered:"gap-closed"});return s.map(e=>e.text).join("")}},yo,wo,/*#__PURE__*/vo("lower","Lowercase a string — Unicode default case mapping, locale-independent","The string to lowercase",e=>e.toLowerCase()),/*#__PURE__*/vo("upper","Uppercase a string — Unicode default case mapping, locale-independent","The string to uppercase",e=>e.toUpperCase()),/*#__PURE__*/vo("trim","Strip whitespace (the JS trim set) from both ends of a string","The string to trim",Q),{name:"regex",category:"string",description:"Test, extract or match a string against a regular expression",parameters:{value:{type:["string","null"],description:"The subject string"},pattern:{type:["string","null"],description:"The regular expression source"},flags:{type:"string",default:"",description:"The admitted subset: i, m, s, u"},mode:{type:{literal:["test","extract","match"]},default:"test",description:"test gives a boolean, extract the first matching substring, match every one of them"},noMatchDefault:{type:"any",required:!1,default:null,nullPolicy:"value",evaluation:"lazy",description:"The extract answer when nothing matches — a matched empty string still passes through"}},positionalParams:["value","pattern"],returns:["boolean","string","array","null"],validate:({pattern:e,flags:t})=>{const r=[],a="string"==typeof t?ko(t):void 0;if(void 0!==a&&r.push({severity:"error",parameter:"flags",message:a}),"string"==typeof e)try{new RegExp(e,"string"==typeof t&&void 0===a?t:"")}catch(e){r.push({severity:"error",parameter:"pattern",message:`pattern does not compile: ${e.message}`})}return r},evaluate:({value:e,pattern:t,flags:r,mode:a,noMatchDefault:n})=>{const o=ko(r);if(void 0!==o)throw new ya(o);const i=e=>{try{return new RegExp(t,r+e)}catch(e){throw new ya(`pattern does not compile: ${e.message}`)}};switch(a){case"test":return i("").test(e);case"extract":{const t=i("").exec(e);return null===t?n.evaluate():t[0]}case"match":return[...e.matchAll(i("g"))].map(e=>e[0])}}},{name:"length",category:"array",description:"An array's element count, or a string's Unicode code-point count",parameters:{value:{type:["string","array","null"],description:"The array or string measured"}},positionalParams:["...value"],returns:"integer",evaluate:({value:e})=>"string"==typeof e?B(e).length:e.length},{name:"map",category:"array",description:"Transform every element of an array",parameters:{input:$o,as:xo,nullInputDefault:jo,each:{type:"any",evaluation:"perElement",over:"input",description:"Evaluated per element, with $element and $index bound"}},positionalParams:["input","each"],returns:"array",validate:Ln,evaluate:({each:e})=>Gn(e.settle())},{name:"filter",category:"array",description:"Keep the elements of an array whose predicate is truthy",parameters:{input:$o,as:xo,nullInputDefault:jo,each:Po},positionalParams:["input","each"],returns:"array",validate:Ln,evaluate:async({input:e,each:t})=>{const r=await Gn(t.settle());return e.filter((e,t)=>r[t])}},{name:"find",category:"array",description:"The first element of an array whose predicate is truthy",parameters:{input:$o,as:xo,nullInputDefault:jo,each:Po,noMatchDefault:{type:"any",required:!1,default:null,evaluation:"lazy",description:"The answer when nothing matches; a found null passes through unchanged"}},positionalParams:["input","each"],validate:Ln,evaluate:async({input:e,each:t,noMatchDefault:r})=>{const a=new Array(e.length);let n=0;for await(const r of t.settle()){a[r.index]=r;for(let t=a[n];void 0!==t;t=a[n]){if(!t.ok)throw t.error;if(!0===t.value)return e[n];n+=1}}return r.evaluate()}},{name:"some",category:"array",description:"True when any element satisfies the predicate",parameters:{input:$o,as:xo,nullInputDefault:jo,each:Po},positionalParams:["input","each"],returns:"boolean",validate:Ln,evaluate:({each:e})=>Jn(e.settle(),!0)},{name:"every",category:"array",description:"True when every element satisfies the predicate",parameters:{input:$o,as:xo,nullInputDefault:jo,each:Po},positionalParams:["input","each"],returns:"boolean",validate:Ln,evaluate:({each:e})=>Jn(e.settle(),!1)},Oo,Do,{name:"convert",category:"other",description:"Convert a value to a number, string, boolean or array — strict: a failed conversion is an error, never a guess",parameters:{value:{type:"any",nullPolicy:e=>"boolean"===e?"value":"propagate",description:"The value to convert; null propagates except for boolean, where it is false"},to:{type:{literal:["number","string","boolean","array"]},description:"The target type"}},positionalParams:["value","to"],returns:["number","string","boolean","array"],evaluate:({value:t,to:r})=>{switch(r){case"number":if("number"==typeof t)return t;if("boolean"==typeof t)return t?1:0;if("string"==typeof t){const e=t.trim(),r=""===e?NaN:Number(e);if(Number.isNaN(r))throw new ya(`'${t}' is not a numeric string — use regex to extract a number from text`);return r}throw Co(t,"number");case"string":if(Array.isArray(t)||e(t))throw new ya(`cannot convert ${ee(t)} to string — a cast is not a render; use buildString or join`);if("object"==typeof t)throw Co(t,"string");return I(t);case"boolean":if("string"==typeof t){const e=t.trim().toLowerCase();if("true"===e)return!0;if("false"===e)return!1}return M(t);case"array":return Array.isArray(t)?t:[t]}}}].map(jn),qo=(e,t)=>{const r=((e,t)=>{const r={...e};for(const[e,a]of Object.entries(t)){if(void 0===a)continue;if("data"===e||!n(a)){r[e]=a;continue}const t=r[e],o=n(t)?{...t}:{};for(const[e,t]of Object.entries(a))void 0!==t&&(o[e]=t);r[e]=o}return r})(null===e?{}:e.options,t);Uo(r);const a=To(r);if(null!==e&&!(e=>void 0!==e.operators||void 0!==e.fragments||void 0!==e.operatorDefaults)(t))return{options:r,evaluation:a,registry:e.registry,compileCache:e.compileCache};const o=$r({operators:r.operators??[So],...void 0!==r.operatorDefaults?{operatorDefaults:r.operatorDefaults}:{},...void 0!==r.fragments?{fragments:r.fragments}:{}});return{options:r,evaluation:a,registry:o,compileCache:new ur({compile:e=>Eo(e,o),probe:e=>be(e,o)})}},To=e=>{const t={...e};return delete t.operators,delete t.fragments,t},Eo=(e,t)=>{const r=qe(e,t);return Nt(r),r.hasNoCache&&Kt(r),r};class zo{state;results;version=Y;constructor(e={}){this.state=qo(null,e),this.results=new mn(un(e.cache))}updateOptions(e={}){const t=qo(this.state,e),r=un(t.options.cache);this.state=t,this.results.configure(r)}clearCache(){this.results.clear()}getOptions(){return(e=>{const t={};for(const[r,a]of Object.entries(e))t[r]=n(a)?{...a}:a;return t})(this.state.evaluation)}getOperators(){return[...this.state.registry.operators.values()].map(e=>{const{definition:t,instanceDefaults:r}=e,a={name:t.name,category:t.category,description:t.description,parameters:yn(t.parameters,r),restParam:t.restParam,timeoutParam:t.timeoutParam,cache:t.cache,returns:t.returns,hasValidate:void 0!==t.validate};return void 0!==t.alias&&(a.alias=t.alias),void 0!==t.metadata&&(a.metadata=t.metadata),void 0!==t.positionalParams&&(a.positionalParams=t.positionalParams),void 0!==r&&(!0===r.noCache&&(a.instanceNoCache=!0),Object.hasOwn(r,"fallback")&&(a.instanceFallback=r.fallback)),a})}getFragments(){return[...this.state.registry.fragments.values()].map(e=>{const t={name:e.name,parameters:Object.fromEntries(Object.entries(e.parameters).map(([e,t])=>[e,{...t}])),returns:e.returns,warnings:[...e.warnings],dependencies:vn(e.dependencies),caches:e.caches};return void 0!==e.description&&(t.description=e.description),void 0!==e.metadata&&(t.metadata=e.metadata),t})}validate(e,t){const r=void 0===t?this.state.evaluation:Qo(this.state.evaluation,t),a=Eo(e,this.state.registry),n=wn(a,r,e=>e.issue);return{valid:!n.some(e=>"error"===e.severity),issues:n,timeoutShielded:a.timeoutShielded}}getDependencies(e){return vn(qe(e,this.state.registry).dependencies)}isEvaluable(e){const t=qe(e,this.state.registry);return t.holes.length>0||t.hasErrors}evaluate(e,t){const{state:r}=this;return Mo(r.evaluation,this.results,e,t,()=>r.compileCache.resolve(e),()=>Eo(e,r.registry))}compile(e){const{state:t}=this;return Ro(e,t.compileCache.resolve(e),t.evaluation,t.registry,this.results)}}const Mo=async(e,t,r,a,n,o)=>{const i=void 0===a?e:Qo(e,a),s="report"===i.mode,l=s||!0===i.trace,c=n(),u="inert"===c.kind&&!0===i.trace?{kind:"artifact",artifact:o()}:c;if("inert"===u.kind){if(void 0!==i.maxDepth&&u.depth>i.maxDepth){const e=bn(u.depth,i.maxDepth);if(!s)throw Wo(e,[e]);return Vo(null,[Wo(e)])}return l?Vo(r,[]):r}const{artifact:d}=u;if(d.hasErrors||void 0!==i.maxDepth||void 0!==i.maxNodes){const e=[...gn(d,i),...d.issues.map(e=>e.issue)],t=e.filter(e=>"error"===e.severity);if(t.length>0){if(!s)throw Wo(t[0],e);return Vo(null,t.map(e=>Wo(e)))}}const p=await tn(d,i,t);return l?p:p.result};let Fo;class Lo{#t;#r;#a;#n;#o;#i;#s;constructor(e,t,r,a,n){this.#t=e,this.#r=t,this.#a=r,this.#n=a,this.#o=n,Fo??=(e,t)=>{if("object"!=typeof e||null===e||!(#r in e))return;const r=void 0===t?e.#a:Qo(e.#a,t);return{expression:e.#t,artifact:e.#l(),options:r}}}get expression(){return this.#t}get issues(){return this.#s??=this.#l().issues.map(e=>e.issue)}get hasErrors(){return this.#l().hasErrors}evaluate(e){return Mo(this.#a,this.#o,this.#t,e,()=>this.#r,()=>this.#l())}getDependencies(){return vn(this.#l().dependencies)}#l(){return"artifact"===this.#r.kind?this.#r.artifact:this.#i??=Eo(this.#t,this.#n)}}const Ro=(e,t,r,a,n)=>new Lo(e,t,r,a,n),Vo=(e,t)=>({result:e,errors:t}),Io=/*#__PURE__*/new Set(Object.keys({data:0,signal:0,timeout:0,mode:0,trace:0})),Qo=(e,t)=>{let r;for(const a in t){const n=t[a];if(void 0!==n){if(!Io.has(a))throw Jo(a);r??={...e},r[a]=n}}return void 0===r?e:(Uo(t),r)},Jo=e=>new P({code:i.invalidOptions,message:`'${e}' is not a per-call option — a call may supply data, signal, timeout, mode and trace; configure the rest at construction or via updateOptions()`,path:[]}),Uo=e=>{const{timeout:t,signal:r}=e;if(void 0!==t&&("number"!=typeof t||!Number.isFinite(t)||t<=0))throw new P({code:i.invalidOptions,message:"'timeout' must be a positive number of milliseconds",path:[]});if(void 0!==r&&!Go(r))throw new P({code:i.invalidOptions,message:"'signal' must be an AbortSignal",path:[]})},Go=e=>"object"==typeof e&&null!==e&&"boolean"==typeof e.aborted&&"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,Wo=(e,t)=>new P({code:e.code,message:e.message,path:e.path,...void 0!==e.operator?{operator:e.operator}:{},...void 0!==t?{issues:t}:{}}),Bo=/[a-z]Default$/,Ko=/*#__PURE__*/new Set(["eager","race","lazy","lazyElements","lazyEntries","perElement","structural"]),Ho=/*#__PURE__*/new Set(me),_o=e=>"array"===e||"any"===e||!!Array.isArray(e)&&(e.includes("array")||e.includes("any")),Xo=e=>"array"===e||"object"===e||"any"===e||!!Array.isArray(e)&&(e.includes("array")||e.includes("object")||e.includes("any")),Yo=(e,t)=>{const[r]=e,a=e.length-1,n=a>0?`${r.message} (+ ${a} more issue${1===a?"":"s"})`:r.message;throw new P({code:i.invalidDefinition,message:n,path:r.path,...void 0!==t?{operator:t}:{},issues:e})};function Zo(t){if(ve(t))return t;const a=[],n=e(t)?t.name:void 0,o="string"==typeof n?n:void 0,s=(e,t,r,n)=>{a.push({severity:"error",code:e,message:t,path:r,...void 0!==o?{operator:o}:{},...void 0!==n?{parameter:n}:{}})};e(t)||(s(i.invalidDefinition,"a definition must be a plain object",[]),Yo(a));const l=t;"string"!=typeof l.name&&s(i.invalidDefinition,"'name' is required and must be a string",["name"]),"string"==typeof l.description&&""!==l.description||s(i.invalidDefinition,"'description' is required and must be non-empty",["description"]),e(l.parameters)||s(i.invalidDefinition,"'parameters' is required and must be an object of declarations (may be {})",["parameters"]),"function"!=typeof l.evaluate&&s(i.invalidDefinition,"'evaluate' is required and must be a function",["evaluate"]),a.length>0&&Yo(a,o),"string"!=typeof l.category?s(i.invalidDefinition,`'category' is required and must be one of ${[...Ho].join(", ")}`,["category"]):Ho.has(l.category)||s(i.invalidDefinition,`'${l.category}' is not a category — expected one of ${[...Ho].join(", ")}`,["category"]),void 0!==l.alias&&"string"!=typeof l.alias&&s(i.invalidDefinition,"'alias' must be a string",["alias"]),void 0!==l.cache&&!0!==l.cache&&s(i.invalidDefinition,"'cache' must be the literal true",["cache"]),void 0===l.metadata||e(l.metadata)||s(i.invalidDefinition,"'metadata' must be a plain object",["metadata"]),void 0===l.positionalParams||Array.isArray(l.positionalParams)&&!l.positionalParams.some(e=>"string"!=typeof e)||s(i.invalidDefinition,"'positionalParams' must be an array of parameter names",["positionalParams"]),void 0!==l.timeoutParam&&"string"!=typeof l.timeoutParam&&s(i.invalidDefinition,"'timeoutParam' must be a parameter name",["timeoutParam"]),void 0!==l.validate&&"function"!=typeof l.validate&&s(i.invalidDefinition,"'validate' must be a function",["validate"]),void 0===l.returns||oe(l.returns)||s(i.invalidDefinition,"'returns' must be a metadata-vocabulary type",["returns"]);const c=(e,t,r)=>{e===fe?s(i.invalidDefinition,"the EvaluationData sentinel is legal only as a parameter 'default'",t,r):Array.isArray(e)&&e.forEach((e,a)=>{e===fe&&c(e,[...t,a],r)})};for(const[e,t]of Object.entries(l))"parameters"!==e&&"metadata"!==e&&c(t,[e]);const u=(e,t)=>{const a=r(e);a.ok?x.has(e)&&s(i.reservedName,`'${e}' is a reserved name`,t):s(i.invalidName,`'${e}': ${a.reason}`,t)};"string"==typeof l.name&&u(l.name,["name"]),"string"==typeof l.alias&&u(l.alias,["alias"]);const d=l.parameters,p={};for(const[t,a]of Object.entries(d)){const n=["parameters",t],o=r(t);o.ok?j.has(t)&&s(i.reservedName,`'${t}' is a reserved node key and cannot name a parameter`,n,t):s(i.invalidName,`'${t}': ${o.reason}`,n,t),e(a)?p[t]=a:s(i.invalidDefinition,`the declaration for '${t}' must be a plain object`,n,t)}const m={};for(const[t,r]of Object.entries(p)){const a=["parameters",t],n=e=>[...a,e],o=r;for(const[e,r]of Object.entries(o))"default"!==e&&"metadata"!==e&&c(r,n(e),t);let l=!0;void 0===o.type||oe(o.type)||(s(i.invalidDefinition,"'type' must be a metadata-vocabulary type",n("type"),t),l=!1),l&&(m[t]=o.type??"any");let u=!1;if(void 0!==o.constraints){const e=ue(o.constraints);e.ok?u=!0:s(i.invalidDefinition,`'constraints' is malformed: expected ${e.expected}, got ${e.actual}`,n("constraints"),t)}void 0!==o.required&&"boolean"!=typeof o.required&&s(i.invalidDefinition,"'required' must be a boolean",n("required"),t),void 0!==o.description&&"string"!=typeof o.description&&s(i.invalidDefinition,"'description' must be a string",n("description"),t),void 0===o.metadata||e(o.metadata)||s(i.invalidDefinition,"'metadata' must be a plain object",n("metadata"),t);const d="default"in o;if(d&&!0===o.required&&s(i.invalidDefinition,"a 'default' contradicts 'required: true' — a default implies the parameter is optional",n("default"),t),d&&o.default!==fe){const e=m[t];if(void 0!==e){const r=ie(o.default,e);if(r.ok){if(u&&void 0!==o.constraints){const e=se(o.default,o.constraints);e.ok||s(i.typeCheck,`'default' violates the declared constraints: expected ${e.expected}, got ${e.actual}`,n("default"),t)}}else s(i.typeCheck,`'default' does not satisfy the declared type: expected ${r.expected}, got ${r.actual}`,n("default"),t)}}if(void 0===o.evaluation||Ko.has(o.evaluation)||s(i.invalidDefinition,`'evaluation' must be one of ${[...Ko].join(", ")}`,n("evaluation"),t),void 0!==o.truthiness&&"boolean"!=typeof o.truthiness&&s(i.invalidDefinition,"'truthiness' must be a boolean",n("truthiness"),t),void 0!==o.over&&"string"!=typeof o.over&&s(i.invalidDefinition,"'over' must be a parameter name",n("over"),t),void 0===o.replacesNullAt||Array.isArray(o.replacesNullAt)&&!o.replacesNullAt.some(e=>"string"!=typeof e)||s(i.invalidDefinition,"'replacesNullAt' must be an array of sibling parameter names",n("replacesNullAt"),t),void 0!==o.nullPolicy){const e=o.nullPolicy;"function"==typeof e||xn.has(e)||s(i.invalidNullPolicy,"'nullPolicy' must be 'propagate', 'value' or a conditional function",n("nullPolicy"),t);const r=m[t];void 0===r||ae(r)||s(i.invalidNullPolicy,"'nullPolicy' is legal only where the declared type names 'null' — a type without 'null' is the reject declaration",n("nullPolicy"),t),!0===o.truthiness&&"propagate"===e&&s(i.invalidNullPolicy,"'truthiness' implies null policy 'value' (null is falsy) — declaring 'propagate' is a conflict",n("nullPolicy"),t)}if(void 0!==o.elementNullPolicy){xn.has(o.elementNullPolicy)||s(i.invalidNullPolicy,"'elementNullPolicy' must be 'propagate' or 'value' — the conditional form is not admitted here",n("elementNullPolicy"),t);const e=m[t];void 0===e||Xo(e)||s(i.invalidNullPolicy,"'elementNullPolicy' applies to container parameters only",n("elementNullPolicy"),t)}}if(Array.isArray(l.positionalParams)&&l.positionalParams.every(e=>"string"==typeof e)){const e=new Set,t=l.positionalParams;t.forEach((r,a)=>{const n=r.startsWith($n),o=n?r.slice(3):r;n&&a!==t.length-1&&s(i.invalidDefinition,`the rest entry '${r}' must be the last positional entry`,["positionalParams",a]),o in p||s(i.invalidDefinition,`positional entry '${r}' names no declared parameter`,["positionalParams",a]),e.has(o)&&s(i.invalidDefinition,`duplicate positional entry '${r}'`,["positionalParams",a]),e.add(o)})}for(const[e,t]of Object.entries(p)){const r=["parameters",e],a="perElement"===t.evaluation;if(void 0!==t.over&&"string"==typeof t.over)if(a){const a=t.over;if(a in p&&a!==e){const t=m[a];void 0===t||_o(t)||s(i.invalidDefinition,`the 'over' target '${a}' must admit an array`,[...r,"over"],e)}else s(i.invalidDefinition,`'over' names no sibling parameter ('${a}')`,[...r,"over"],e)}else s(i.invalidDefinition,"'over' is legal only with evaluation: 'perElement'",[...r,"over"],e);else a&&s(i.invalidDefinition,"evaluation: 'perElement' requires 'over' to name the iterated sibling",[...r,"evaluation"],e)}for(const[e,t]of Object.entries(p)){if(void 0===t.replacesNullAt)continue;if(!Array.isArray(t.replacesNullAt)||t.replacesNullAt.some(e=>"string"!=typeof e))continue;const r=["parameters",e,"replacesNullAt"];"lazy"!==t.evaluation&&s(i.invalidDefinition,"a 'replacesNullAt' holder must declare evaluation: 'lazy'",r,e);(t.required??!("default"in t))&&s(i.invalidDefinition,"a 'replacesNullAt' holder must be optional",r,e),"default"in t&&s(i.invalidDefinition,"a 'replacesNullAt' holder may not carry a 'default' — it is presence-sensitive by construction",r,e),t.replacesNullAt.forEach((t,a)=>{t===e?s(i.invalidDefinition,"'replacesNullAt' may not target the holder itself",[...r,a],e):t in p||s(i.invalidDefinition,`'replacesNullAt' target '${t}' names no sibling parameter`,[...r,a],e)})}for(const[e,t]of Object.entries(p))Bo.test(e)&&"lazy"!==t.evaluation&&s(i.invalidDefinition,`'${e}' is named for the '…Default' family, so it must declare evaluation: 'lazy' — add 'replacesNullAt', read it as a LazyValue in the body, or rename it`,["parameters",e,"evaluation"],e);const f=Pn(p,m,s);if("string"==typeof l.timeoutParam){void 0===p[l.timeoutParam]?s(i.invalidDefinition,`'timeoutParam' names no declared parameter ('${l.timeoutParam}')`,["timeoutParam"]):"integer"!==m[l.timeoutParam]&&s(i.invalidDefinition,"the 'timeoutParam' target must be 'integer'-typed",["timeoutParam"])}return a.length>0&&Yo(a,o),On(l,f)}const ei=e=>new ya(`request failed (${e.status}): ${e.url}`,{errorData:{status:e.status,statusText:e.statusText,url:e.url,response:e.payload}}),ti=(e,t)=>{const r=t instanceof Error?t.message:String(t),a=t??{},n={driver:e};for(const e of["code","table","column","constraint"])"string"==typeof a[e]&&(n[e]=a[e]);return new ya(`${e}: ${r}`,{errorData:n})},ri=(e,t=500)=>e.length<=t?e:`${e.slice(0,t)}… (${e.length} characters)`;class ai{supplied;constructor(e){if(void 0===e&&"function"!=typeof globalThis.fetch)throw new ya("FetchClient(): this runtime has no global fetch — pass one, new FetchClient(myFetch), or use another client such as new AxiosClient(axios)");this.supplied=e}request=async e=>{const t=this.supplied??globalThis.fetch,r=await t.call(globalThis,e.url,{method:e.method.toUpperCase(),headers:e.headers,...void 0!==e.body?{body:JSON.stringify(e.body)}:{},signal:e.signal}),a=await r.text();if(!r.ok)throw ei({status:r.status,statusText:r.statusText,url:r.url||e.url,payload:ii(a)});return oi(a,r.url||e.url,r.status)}}class ni{axios;constructor(e){if(this.axios=e,"function"!=typeof e||"function"!=typeof e.isAxiosError)throw new ya("AxiosClient(axios): pass the axios import itself — new AxiosClient(axios)")}request=async e=>{try{const t=await this.axios({url:e.url,method:e.method,headers:e.headers,...void 0!==e.body?{data:e.body}:{},signal:e.signal});return""===t.data||void 0===t.data?null:t.data}catch(t){if(this.axios.isAxiosError(t)&&t.response)throw ei({status:t.response.status,statusText:t.response.statusText,url:t.config?.url??e.url,payload:t.response.data});throw t}}}const oi=(e,t,r)=>{if(""===e.trim())return null;try{return JSON.parse(e)}catch{throw new ya(`response was not JSON (${r}): ${t}`,{errorData:{status:r,url:t,response:ri(e)}})}},ii=e=>{if(""===e.trim())return null;try{return JSON.parse(e)}catch{return ri(e)}},si=/^https?:\/\//i,li=(e,t,r)=>{const a=si.test(e)?e:ci(r,e),n=ui(t),o=""===n?a:`${a}${a.includes("?")?"&":"?"}${n}`;try{new URL(o)}catch{throw new ya(`'${o}' is not a valid URL`,{code:i.typeCheck})}return o},ci=(e,t)=>{if(void 0===e||""===e)throw new ya(`'${t}' is a relative URL and no http.baseEndpoint is configured`,{code:i.typeCheck});return""===t?e:`${e.replace(/\/$/,"")}/${t.replace(/^\//,"")}`},ui=e=>{if(void 0===e)return"";const t=new URLSearchParams;for(const[r,a]of Object.entries(e))null!=a&&t.append(r,mi(a,`query['${r}']`,"query"));return t.toString()},di=(...e)=>{const t={};for(const r of e)if(void 0!==r)for(const[e,a]of Object.entries(r))null!=a?t[e]=mi(a,`headers['${e}']`,"header"):delete t[e];return t},pi=e=>({Accept:"application/json",...e?{"Content-Type":"application/json"}:{}}),mi=(e,t,r)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return I(e);throw new ya(`${t} is ${ee(e)} — a ${r} value must be a string, number or boolean; render it explicitly (join) or supply a fully-formed URL`,{code:i.typeCheck})},fi=e=>({method:e.method,url:e.url,headers:Object.fromEntries(Object.entries(e.headers).sort(([e],[t])=>e<t?-1:e>t?1:0)),...void 0!==e.body?{body:e.body}:{}}),hi=t=>Array.isArray(t)?t.length>0:e(t)?Object.keys(t).length>0:null!=t,vi=(e,t)=>{if(void 0===t)return e;const r=k(e,Tn(t));return r.found?void 0===r.value?null:r.value:null},yi=(t,r)=>{if(!e(t))throw new ya("a row was not an object");const a=Object.values(t);if(1!==a.length)throw new ya(`shape: '${r}' needs a single-column result — this row has ${a.length} columns; name the one column you want in the SQL`,{code:i.typeCheck});return a[0]},gi={type:"integer",required:!1,description:"Per-request deadline in ms; expiry is an ordinary failure this node’s fallback catches"},bi={type:["string","array"],required:!1,description:"Dot/bracket path or segments array applied to the response; a miss is null"},wi=e=>({name:"http",category:"io",description:"One HTTP request — GET or POST — returning the parsed JSON response",parameters:{url:{type:"string",description:"A full http(s) URL is used verbatim; anything else — including an empty string — joins http.baseEndpoint"},method:{type:{literal:["get","post"]},default:"get",description:"Lowercase; the mutating verbs are deliberately absent — an expression is a read"},query:{type:"object",required:!1,elementNullPolicy:"value",description:"Query-string pairs; a null value omits its pair, a composite one is an error"},body:{type:["string","number","boolean","array","object"],required:!1,description:"The JSON payload; a whole-null body means NO body, while nulls inside one are JSON nulls"},headers:{type:"object",required:!1,elementNullPolicy:"value",description:"Merged over the http.headers option per key; a null value removes an inherited pair"},returnPath:bi,timeout:gi},positionalParams:["url"],timeoutParam:"timeout",cache:!0,returns:"any",validate:({returnPath:e,method:t,body:r})=>[...En(e,"returnPath"),...xi(t,r)],evaluate:async({url:t,method:r,query:a,body:n,headers:o,returnPath:s},l)=>{if("get"===r&&void 0!==n)throw new ya("a GET carries no body — did you mean method: 'post'?",{code:i.typeCheck});const c={method:r,url:li(t,a,l.options.http?.baseEndpoint),headers:di(pi(void 0!==n),l.options.http?.headers,o),...void 0!==n?{body:n}:{}},u=await l.cache.memo(fi(c),()=>(Oi(l,c),e.request({...c,signal:l.signal})));return vi(u,s)}}),ki=t=>({name:"graphQL",category:"io",description:"One GraphQL query — a POST of { query, variables } — returning the data field",parameters:{query:{type:"string",description:"The GraphQL document — the protocol’s own word, as sql.query is"},variables:{type:"object",required:!1,elementNullPolicy:"value",description:"Query variables; a null value is CARRIED as JSON null, a nullable argument being meaningful GraphQL"},url:{type:"string",required:!1,description:"Per-node endpoint override; unset means the graphQL.endpoint option"},headers:{type:"object",required:!1,elementNullPolicy:"value",description:"Merged over http.headers then graphQL.headers; a null value removes a pair"},returnPath:bi,timeout:gi},positionalParams:["query","variables"],timeoutParam:"timeout",cache:!0,returns:"any",validate:({returnPath:e})=>En(e,"returnPath"),evaluate:async({query:r,variables:a,url:n,headers:o,returnPath:i},s)=>{const l=n??s.options.graphQL?.endpoint;if(void 0===l)throw new ya("no endpoint — supply url, or set the graphQL.endpoint option");const c={method:"post",url:li(l,void 0,s.options.http?.baseEndpoint),headers:di(pi(!0),s.options.http?.headers,s.options.graphQL?.headers,o),body:{query:r,...hi(a)?{variables:a}:{}}},u=await s.cache.memo(fi(c),async()=>(Oi(s,c),(t=>{if(!e(t))throw new ya("the GraphQL response was not an object");const r=t.errors;if(Array.isArray(r)&&r.length>0){const e=r[0]?.message;throw new ya(`the GraphQL response carried ${r.length} error${1===r.length?"":"s"}`+("string"==typeof e?`: ${e}`:""),{errorData:{errors:r}})}if(!("data"in t))throw new ya("the GraphQL response carried neither data nor errors");return t.data??null})(await t.request({...c,signal:s.signal}))));return vi(u,i)}}),$i=e=>({name:"sql",category:"io",description:"One SQL query against the registered connection. Expressions are READS — give the connection a read-only role and run mutations host-side",parameters:{query:{type:"string",description:"SQL text with the driver’s own placeholders — FigTree never parses SQL"},values:{type:["array","object"],required:!1,elementNullPolicy:"value",description:"Bind values — positional as an array, named as an object; a null binds SQL NULL"},shape:{type:{literal:["rows","firstRow","column","firstValue"]},default:"rows",description:"rows: every row object; firstRow: the first; column: one column’s values; firstValue: one scalar"},noRowDefault:{type:"any",required:!1,default:null,nullPolicy:"value",evaluation:"lazy",description:"The answer when firstRow / firstValue find no row — never for rows / column, never on failure"},timeout:gi},positionalParams:["query","...values"],timeoutParam:"timeout",cache:!0,returns:"any",evaluate:async({query:t,values:r,shape:a,noRowDefault:n},o)=>{const i={text:t,...hi(r)?{values:r}:{}};return(async(e,t,r)=>{switch(t){case"rows":return e;case"firstRow":return 0===e.length?r.evaluate():e[0];case"column":return e.map(e=>yi(e,"column"));case"firstValue":return 0===e.length?r.evaluate():yi(e[0],"firstValue")}})(await o.cache.memo(i,()=>(o.trace.note({type:"query",text:i.text}),e.query({...i,signal:o.signal}))),a,n)}}),xi=(e,t)=>void 0!==t&&"get"===e?[{severity:"error",parameter:"body",message:"a GET carries no body — add method: 'post', or drop the body"}]:[],ji=(e=new ai)=>[jn(wi(e)),jn(ki(e))],Pi=e=>[jn($i(e))],Oi=(e,t)=>{e.trace.note({type:"request",method:t.method,url:t.url,headers:Object.keys(t.headers)})};class Ai{client;constructor(e){if(this.client=e,"function"!=typeof e?.query)throw new ya("PostgresConnection(client): pass a connected node-postgres Client or Pool")}query=async e=>{if(void 0!==e.values&&!Array.isArray(e.values))throw new ya("postgres takes positional binds ($1, $2, …) — an object of named binds needs a driver that supports them");try{const t=await this.client.query({text:e.text,...void 0!==e.values?{values:e.values}:{}});return t?.rows??[]}catch(e){throw ti("postgres",e)}}}class Di{db;constructor(e){if(this.db=e,"function"!=typeof e?.all)throw new ya("SQLiteConnection(db): pass an open sqlite Database")}query=async e=>{try{return await this.db.all(e.text,e.values)??[]}catch(e){throw ti("sqlite",e)}}}const Ni=e=>Ci(e,0,new Set),Ci=(e,t,r)=>{if(null===e||"boolean"==typeof e||"string"==typeof e)return e;if("number"==typeof e&&Number.isFinite(e)&&!Object.is(e,-0))return e;if("object"!=typeof e)return Si(e);if(!Array.isArray(e)&&!n(e))return qi(e);if(r.has(e))return"[circular]";if(t>=o)return"[too deep]";r.add(e);const a=Array.isArray(e)?Array.from(e,e=>Ci(e,t+1,r)):Object.fromEntries(Object.entries(e).map(([e,a])=>[e,Ci(a,t+1,r)]));return r.delete(e),a},Si=e=>{switch(typeof e){case"function":return""===e.name?"[function]":`[function ${e.name}]`;case"symbol":return`[${String(e)}]`;case"bigint":return`[bigint ${e}]`;case"number":return Object.is(e,-0)?"[-0]":`[${e}]`;default:return"[undefined]"}},qi=e=>{const t=Ti(e);try{const r=e.toJSON;if("function"==typeof r){const a=r.call(e);if("string"==typeof a)return`[${t} ${a}]`}}catch{}return`[${t}]`},Ti=e=>{try{const t=e.constructor?.name;return"string"==typeof t&&""!==t?t:"Object"}catch{return"Object"}},Ei=e=>{const t=new Map;for(const r of e.holes)void 0!==r.timeoutFallback&&t.set(r.node,r.timeoutFallback);const r=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[e,n(t)])),a=e=>{const r=t.get(e);return void 0===r?{}:{timeoutFallback:Ni(r.value)}},n=e=>{const t={order:e.order,kind:e.kind,path:xe(e.path)},o="vars"in e&&void 0!==e.vars?{vars:r(e.vars)}:{};switch(e.kind){case"constant":return{...t,kind:e.kind,value:Ni(e.value)};case"reference":return{...t,kind:e.kind,reference:E(e.binding??e.namespace,e.segments),authored:e.raw,...void 0===e.binding?{}:{binding:e.binding}};case"operator":return{...t,kind:e.kind,...o,operator:e.name,params:r(e.params),...void 0===e.fallback?{}:{fallback:n(e.fallback)},...a(e),...void 0===e.noCache?{}:{noCache:e.noCache},...void 0===e.entry.instanceDefaults?{}:{instanceDefaults:Object.keys(e.entry.instanceDefaults)}};case"fragmentCall":return{...t,kind:e.kind,...o,fragment:e.name,resolved:void 0!==e.entry,argumentsMode:e.argumentsMode,...void 0===e.parameters?{}:{parameters:"dynamic"===e.argumentsMode?n(e.parameters):r(e.parameters)},...void 0===e.fallback?{}:{fallback:n(e.fallback)},...a(e),...void 0===e.noCache?{}:{noCache:e.noCache}};case"skeleton":{const r=De(e.skeleton,e.holes,e.holes.map(()=>"<hole>"));return{...t,kind:e.kind,...o,shape:Ni(r),holes:e.holes.map(e=>({at:[...e.at],node:n(e.node)}))}}case"elements":return{...t,kind:e.kind,elements:e.nodes.map(n)};case"entries":return{...t,kind:e.kind,...o,entries:r(e.entries)};case"invalid":return{...t,kind:e.kind,raw:Ni(e.raw)}}};return n(e.root)},zi=(e,t)=>{const r=(a=e,n=t,Fo?.(a,n));var a,n;if(void 0===r)throw new TypeError("inspect() takes a CompiledExpression — the handle fig.compile() returns");const{expression:o,artifact:i,options:s}=r;return{version:Y,expression:Ni(o),options:Fi(s),canonicalForm:Ei(i),issues:wn(i,s,({issue:e,order:t})=>({order:t,...e,path:[...e.path]})),timeoutShielded:i.timeoutShielded,nodeCount:i.nodeCount,maxDepth:i.maxDepth,dependencies:Vi(i.dependencies),own:{nodeCount:i.own.nodeCount,maxDepth:i.own.maxDepth,dependencies:Vi(i.own.dependencies)}}},Mi="[supplied]",Fi=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[e,Li(e,t)])),Li=(e,t)=>{switch(e){case"data":{const e="object"==typeof t&&null!==t?Object.keys(t).length:0;return`[supplied: ${e} top-level key${1===e?"":"s"}]`}case"signal":return Mi;case"http":case"graphQL":return Ri(t,"headers",e=>"object"==typeof e&&null!==e?Object.fromEntries(Object.keys(e).map(e=>[e,"[redacted]"])):Ni(e));case"cache":return Ri(t,"store",()=>Mi);default:return Ni(t)}},Ri=(e,t,r)=>"object"==typeof e&&null!==e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).map(([e,a])=>[e,e===t?r(a):Ni(a)])):Ni(e),Vi=e=>({dataPaths:[...e.dataPaths.keys()],dynamic:e.dynamic,operators:[...e.operators],fragments:[...e.fragments]});export{R as ARRAY,ni as AxiosClient,i as ErrorCodes,fe as EvaluationData,ai as FetchClient,zo as FigTree,P as FigTreeError,V as OBJECT,me as OPERATOR_CATEGORIES,ya as OperatorFailure,Ai as PostgresConnection,Di as SQLiteConnection,C as WILDCARD,F as compareValues,So as coreOperators,X as deepEqual,Zo as defineOperator,ji as httpOperators,zi as inspect,A as isFigTreeError,ga as isOperatorFailure,M as isTruthy,g as parsePath,I as renderText,k as resolvePath,Pi as sqlOperators,Y as version};