fig-tree-evaluator 2.23.2 → 3.0.0-preview.1

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 ADDED
@@ -0,0 +1 @@
1
+ import{f as e,g as t,r,i as a,D as n,E as o,b as i,c as s,h as l,j as c,d as u,k as d,S as p,n as m,a as f,p as h,s as v,e as y,l as g,m as b,o as w,R as k,F as $,q as x,t as j,u as P,v as O,W as A,w as D,x as N,G as S,y as C}from"./chunks/shared.js";const q=[!1,null,0,""],E=e=>-1===q.indexOf(e),T=(e,t)=>"number"==typeof e&&"number"==typeof t?e<t?-1:e>t?1:0:z(String(e),String(t)),z=(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},M="<array>",L="<object>",F=e=>null===e?"":"string"==typeof e?e:"number"==typeof e?String(e):"boolean"==typeof e?e?"true":"false":Array.isArray(e)?M:L,R=e=>e.trim(),I=/\s+$/,V=/^\s+/,Q=e=>e.replace(I,""),J=e=>e.replace(V,""),U=e=>Array.from(e),B=(e,t)=>{const[r,a]=String(e).split("e"),n=void 0!==a?Number(a)+t:t;return Number(`${r}e${n}`)},G=Object.prototype.hasOwnProperty,W=(e,t)=>{for(const r of e.keys())if(K(r,t))return r},K=(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--&&K(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=W(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=W(t,n),!n))return!1;if(!K(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(G.call(e,r)&&++a&&!G.call(t,r))return!1;if(!(r in t)||!K(e[r],t[r]))return!1}return Object.keys(t).length===a}}return e!=e&&t!=t},H="3.0.0-preview.1",_={ok:!0},X=e=>null===e?"null":Array.isArray(e)?"array":typeof e,Y=(e,t)=>({ok:!1,expected:e,actual:X(t)}),Z=(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}},ee=e=>"null"===e||"any"===e||!!Array.isArray(e)&&(e.includes("null")||e.includes("any")),te=e=>"object"==typeof e&&null!==e&&!Array.isArray(e)&&"literal"in e,re=/*#__PURE__*/new Set(["any","string","number","boolean","array","object","null","integer"]),ae=t=>{if("string"==typeof t)return re.has(t);if(Array.isArray(t))return t.length>0&&t.every(e=>"string"==typeof e&&re.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},ne=(e,t)=>{if(te(t)){if(-1!==t.literal.indexOf(e))return _;const r=t.literal.map(e=>JSON.stringify(e)).join(", ");return Y(`one of ${r}`,e)}return"string"==typeof t?Z(e,t)?_:Y(t,e):t.some(t=>Z(e,t))?_:Y(t.join(" | "),e)},oe=(e,t)=>{if(void 0!==t.length){if(!Array.isArray(e))return Y("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 Y("array",e);const r=t.homogeneous;if(e.length>0){if(void 0===r.find(t=>e.every(e=>Z(e,t))))return{ok:!1,expected:`homogeneous array of ${r.join(" | ")}`,actual:"mixed types"}}}if(t.elementShape){if(!Array.isArray(e))return Y("array",e);for(let r=0;r<e.length;r++){const a=le(e[r],t.elementShape);if(!a.ok)return a}}return _},ie=["length","homogeneous","elementShape"],se=t=>{if(!e(t))return Y("a constraints object",t);for(const e of Object.keys(t))if(!ie.includes(e))return{ok:!1,expected:`one of ${ie.join(", ")}`,actual:e};const{length:r,homogeneous:a,elementShape:n}=t;if(void 0!==r&&(!Number.isInteger(r)||r<0))return Y("a non-negative integer length",r);if(!(void 0===a||Array.isArray(a)&&ae(a)))return Y("a non-empty array of basic types",a);if(void 0!==n){if(!e(n))return Y("an object of declarations",n);for(const[t,r]of Object.entries(n)){if(!e(r))return Y(`a declaration for "${t}"`,r);if(void 0!==r.type&&!ae(r.type))return Y(`a vocabulary type for "${t}"`,r.type);if(void 0!==r.required&&"boolean"!=typeof r.required)return Y(`a boolean "required" for "${t}"`,r.required);if(void 0!==r.constraints){const e=se(r.constraints);if(!e.ok)return e}}}return _},le=(t,r)=>{if(!e(t))return Y("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=ne(t[n],o.type);if(!e.ok)return e}if(void 0!==o.constraints){const e=oe(t[n],o.constraints);if(!e.ok)return e}}else if(s)return{ok:!1,expected:`property "${n}"`,actual:"missing"}}return _},ce=e=>{if(te(e))return{any:!1,basics:[],literals:e.literal};const t="string"==typeof e?[e]:e;return{any:t.includes("any"),basics:t}},ue=(e,t)=>"string"==typeof e?t.includes("string"):"boolean"==typeof e?t.includes("boolean"):t.includes("number")||Number.isInteger(e)&&t.includes("integer"),de=(e,t,r)=>{if(!r||!Array.isArray(e))return oe(e,t);const{length:a,...n}=t;if(void 0!==a){const t=oe(e,{length:a});if(!t.ok)return t}return oe(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:t(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,o)=>{if(o>n)return!1;if(o>e.maxDepth&&(e.maxDepth=o),void 0===t)return!1;if("string"==typeof t){const e=r(t).kind;return"plain"===e||"unrecognized"===e}if(Array.isArray(t)){for(let r=0;r<t.length;r++)if(!be(e,t[r],o+1))return!1;return!0}if(a(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 r in t)if(!be(e,t[r],o+1))return!1;return!0}return!0},we=(e,t)=>"literal"===t||void 0!==ur(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:[],identityOnly:!1,renamedBindings:[],asNames:new Set,unrecognized:[]},n=(r.basePath??[]).reduce(ke,null),o=ze(a,e,n,0);Ee(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}},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]}}},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:o.unresolvedBinding,message:`'${a}' names an iterator binding, but no enclosing iterator binds it here`})},Te=(e,t,r,a,n,o,i)=>{const s={issue:{severity:t,code:r,message:a,path:$e(n),...void 0!==i?{operator:i}:{}},order:o};return e.issues.push(s),s},ze=(e,t,r,a)=>{const i=e.order++;if(a>e.maxDepth&&(e.maxDepth=a),a>n)return Te(e,"error",o.depthCeiling,`the expression nests deeper than the engine's ceiling of ${n} levels — descent stopped here`,r,i),e.nodeCount++,Fe(t,r,i);const s=Me(e,t,r,a,i);return"operator"!==s.kind&&"fragmentCall"!==s.kind&&"reference"!==s.kind&&"invalid"!==s.kind||e.nodeCount++,s},Me=(e,t,r,n,o)=>null==t?Le(t??null,r,o):"number"==typeof t||"boolean"==typeof t?Le(t,r,o):"string"==typeof t?Re(e,t,r,o):Array.isArray(t)?Ve(e,t,r,n,o):a(t)?Qe(e,t,r,n,o):(e.identityOnly=!0,Le(t,r,o)),Le=(e,t,r)=>({kind:"constant",value:e,path:t,order:r}),Fe=(e,t,r)=>({kind:"invalid",raw:e,path:t,order:r}),Re=(e,t,a,n)=>{const s=r(t);switch(s.kind){case"plain":return Le(t,a,n);case"unrecognized":{const r=Ie(e,t,a,n);if(null!==r)return r;const s=Te(e,"warning",o.unrecognizedIdentifier,`'${t}' matches no reference namespace and will pass through as data`,a,n),l=i(t);return null!==l&&e.unrecognized.push({token:l.token,issue:s,raw:t}),Le(t,a,n)}case"invalid":return Te(e,"error",s.code??o.invalidReference,`'${t}': ${s.reason}`,a,n),Fe(t,a,n);case"reference":{const{namespace:r,segments:o,drill:i}=s;return"data"===r&&(0===o.length?e.dynamic=!0:Xe(e,o,i.startsWith(".")?i.slice(1):void 0)),{kind:"reference",namespace:r,segments:o,raw:t,path:a,order:n}}}},Ie=(e,t,r,a)=>{const n=i(t);if(null===n)return null;const{token:s,rest:l}=n;for(let n=e.renamedBindings.length-1;n>=0;n--){const i=e.renamedBindings[n];if(s===i.element)try{return{kind:"reference",namespace:"element",segments:d(l),raw:t,binding:s,path:r,order:a}}catch(n){return Te(e,"error",o.invalidReference,`'${t}': ${n.message}`,r,a),Fe(t,r,a)}if(s===i.index)return""!==l?(Te(e,"error",o.invalidReference,`'${t}': the index binding is bare-only — it cannot be drilled`,r,a),Fe(t,r,a)):{kind:"reference",namespace:"index",segments:[],raw:t,binding:s,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 i=s(t,e.recognizes);switch(i.kind){case"malformed":return Te(e,"error",o.malformedNode,i.message,r,n),Fe(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,i.key,r,a,n);case"plain":return gt(e,t,r,a,n)}},Je=(e,t,r,a,n)=>{const i=t.operator;if("string"!=typeof i)return Te(e,"error",o.malformedNode,"the 'operator' value must be a literal string",r,n),Fe(t,r,n);if("literal"===i)return pt(e,t,t.value,"value"in t,r,n);const s=ur(e.registry,i);if(void 0===s){const a=m(i,jt(e));return Te(e,"error",o.unknownOperator,`'${i}' names no registered operator${a?` — did you mean '${a}'?`:""}`,r,n),Fe(t,r,n)}const l=Ue(e,s,r,n),c=[];for(const i in t){const s=t[i];"operator"!==i&&"//"!==i&&void 0!==s&&(Be(e,l,i,s,r,a,n)||("parameters"!==i?Ge(e,l,c,i,s,ke(r,i),n):Te(e,"error",o.malformedNode,"'parameters' is reserved and unused on operator nodes",ke(r,i),n,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,i,s)=>"fallback"===r?(t.fallback=ze(e,a,ke(n,"fallback"),i+1),!0):"useCache"===r?("boolean"==typeof a?t.useCache=a:Te(e,"error",o.malformedNode,"'useCache' must be a literal boolean — the cache lookup happens before evaluation",ke(n,"useCache"),s,t.name),!0):"vars"===r&&(t.vars=yt(e,a,n,i,s),!0),Ge=(e,t,r,a,n,i,s)=>{if(void 0===t.entry.definition.parameters[a]){const r=m(a,Object.keys(t.entry.definition.parameters));return void Te(e,"error",o.unknownNodeKey,`'${a}' is not a parameter of '${t.name}'${r?` — did you mean '${r}'?`:""}`,i,s,t.name)}r.push({name:a,kind:"value",value:n,path:i})},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 n=ye(r.value).filter(e=>"text"!==e.kind);if(0===n.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}:a(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(a(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,n,i),"absent"!==i.mode&&"object"!==i.mode)return;const s=[],l=new Set;for(const t of n){if("named"!==t.kind||!t.body.startsWith("$"))continue;if(l.has(t.body))continue;const a=Re(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 i=(a,n,o="warning")=>Te(e,o,a,n,r.path,r.order,t.name);if("array"!==n.mode&&"dynamic"!==n.mode||a.some(e=>"named"===e.kind&&e.body.startsWith("$"))&&i(o.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,i(o.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)i(o.unusedSubstitution,`substitution ${e} is never named by the template`);return void(r.length>0&&t&&i(o.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("$")||i(o.unboundToken,`'${t.raw}' binds to nothing and renders as its own text`));for(const t of n.keys)e.has(t)||i(o.unusedSubstitution,`substitution '${t}' is never named by the template`)}},Xe=(e,t,r)=>{if(void 0!==r&&l(r))return void e.dataPaths.set(r,t);const a=c(t);e.dataPaths.set(u(a),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 t="string"==typeof r.value?y(r.value):r.value;if(!Array.isArray(t)||!t.every(g))return void(e.dynamic=!0);if(0===t.length)return void(e.dynamic=!0);Xe(e,t,"string"==typeof r.value?r.value:void 0)}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 n=t.value;if(!a(n)||f(n,e.recognizes))return null;const{order:o,containerDepth:i}=tt(e,r),{entries:s,vars:l,changed:c}=bt(e,n,t.path,i,o);if(s.every(e=>"constant"===e.node.kind))return wt(e,n,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,a,n,i,s)=>{const l=t=>{Te(e,"error",o.invalidAs,t,i,s,a.name)};if("string"!=typeof n||"plain"!==r(n).kind)return l("'as' must be a literal name — a dynamic value cannot be statically resolved");const c=t(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,i)=>{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(!(p.has(n)&&!(c&&"useCache"===n)))return Te(e,"error",o.malformedNode,`'${n}' may not sit beside the shorthand key '${r}' — reserved modifiers only`,ke(a,n),i),Fe(t,a,i)}const u=t[r],d=ke(a,r);if(l){for(const r of["fallback","vars","useCache"])r in t&&Te(e,"warning",o.uselessModifier,`'${r}' on 'literal' is dead — contents are never evaluated`,ke(a,r),i);return pt(e,t,u,!0,a,i)}if(c)return ft(e,t,s,u,a,n,i);const m=ur(e.registry,s),f=Ue(e,m,a,i);for(const o in t){const s=t[o];o!==r&&"//"!==o&&void 0!==s&&Be(e,f,o,s,a,n,i)}const h=[];return st(e,f,h,u,d,i),We(e,f,h,n,i),f},st=(e,t,r,n,o,i)=>{if(Array.isArray(n))ct(e,t,r,n,o,i);else if(!a(n)||f(n,e.recognizes))lt(e,t,r,n,o,i);else for(const a in n){const s=n[a];"//"!==a&&void 0!==s&&Ge(e,t,r,a,s,ke(o,a),i)}},lt=(e,t,r,a,n,o)=>{const i=v(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=h(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)=>Te(e,"error",o.positionalArity,`'${t.name}' takes no positional arguments — use the named form`,r,a,t.name),dt=(e,t,r,a,n)=>{const i=t.entry.definition.positionalParams;if(void 0===i)return void ut(e,t,a,n);const s=i.length;Te(e,"error",o.positionalArity,`'${t.name}' takes at most ${s} positional argument${1===s?"":"s"} (${i.join(", ")}), got ${r.length}`,a,n,t.name)},pt=(e,t,r,a,n,i)=>{if("operator"in t){for(const r in t)"operator"!==r&&"value"!==r&&"//"!==r&&("fallback"!==r&&"vars"!==r&&"useCache"!==r?Te(e,"error",o.unknownNodeKey,`'${r}' is not a key of 'literal' — content goes in 'value'`,ke(n,r),i,"literal"):Te(e,"warning",o.uselessModifier,`'${r}' on 'literal' is dead — contents are never evaluated`,ke(n,r),i));if(!a)return Te(e,"error",o.malformedNode,"'literal' requires its content in 'value'",n,i,"literal"),Fe(t,n,i)}return Le(r,n,i)},mt=(e,t,r,a,n)=>{const i=t.fragment;if("string"!=typeof i)return Te(e,"error",o.malformedNode,"the 'fragment' value must be a literal string",r,n),Fe(t,r,n);const s={kind:"fragmentCall",name:i,argumentsMode:"static",path:r,order:n};ht(e,s,a);for(const i in t){const l=t[i];"fragment"!==i&&"//"!==i&&void 0!==l&&("parameters"!==i?"fallback"!==i?"vars"!==i?"useCache"!==i?Te(e,"error",o.unknownNodeKey,`'${i}' is not a key of a fragment call — arguments live only in 'parameters'`,ke(r,i),n):Te(e,"error",o.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,n,i,s,l)=>{const c={kind:"fragmentCall",name:r,argumentsMode:"static",path:i,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(i,"fallback"),s+1)),"vars"===a&&(c.vars=yt(e,n,i,s,l)))}return a(n)?vt(e,c,n,ke(i,`$${r}`),s,l):Te(e,"error",o.malformedNode,`fragments have no single-value or positional form — '$${r}' takes a named-arguments object`,ke(i,`$${r}`),l),c},ht=(e,t,r)=>{const{name:a,path:n,order:i}=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 Te(e,"error",o.unknownFragment,`'${a}' names no registered fragment${t?` — did you mean '${t}'?`:""}`,n,i)}t.entry=s,e.fragmentCalls.push({name:a,depth:r})},vt=(e,t,n,i,s,l)=>{if(void 0!==n){if(f(n,e.recognizes)||"string"==typeof n&&"reference"===r(n).kind)return t.argumentsMode="dynamic",t.parameters=ze(e,n,i,s+1),void(e.dynamic=!0);if(a(n)){const r={};for(const t in n){const a=n[t];"//"!==t&&void 0!==a&&(r[t]=ze(e,a,ke(i,t),s+1))}return void(t.parameters=r)}Te(e,"error",o.malformedNode,"a fragment's 'parameters' must be a named-arguments object or a node computing one",i,l)}},yt=(e,r,n,i,s)=>{const l=ke(n,"vars");if(!a(r))return void Te(e,"error",o.invalidVars,"a 'vars' block must be an object of name → expression entries",l,s);const c={};for(const a in r){const n=r[a];if("//"===a||void 0===n)continue;const u=ke(l,a),d=t(a);d.ok?c[a]=ze(e,n,u,i+1):Te(e,"error",o.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 i,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),jt(e));Te(e,"warning",o.unrecognizedIdentifier,`'${c}' is not a registered operator or fragment and will pass through as data${t?` — did you mean '$${t}'?`:""}`,r,n)}l.push({key:c,rawChild:u,node:ze(e,u,ke(r,c),a+1)})}else s=!0;else i=yt(e,u,r,a,n),s=!0;else s=!0}return{entries:l,vars:i,changed:s}},wt=(e,t,r,a,n,i,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!==i&&Object.keys(i).length>0&&Te(e,"warning",o.unreferencedVar,"this vars block declares names nothing in its scope references",ke(s,"vars"),l),Le(d||void 0!==i?u:t,s,l);const p={kind:"skeleton",skeleton:u,holes:c,path:s,order:l};return void 0!==i&&(p.vars=i),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=/*#__PURE__*/Object.freeze({parsePath:y,resolvePath:b,checkType:ne,checkConstraints:oe,describeType:X,renderText:F,isTruthy:E}),Ot=(e,t={})=>{Dt({artifact:e,context:t,varsFrames:[],iteratorFrames:[]},e.root),xe(e.issues),e.hasErrors=je(e.issues)},At=(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),e.artifact.issues.push({issue:s,order:o})},Dt=(e,t)=>{switch(t.kind){case"constant":case"invalid":return;case"reference":return void Mt(e,t);case"skeleton":{const r=It(e,t.vars,t.path);for(const r of t.holes)Dt(e,r.node);return void Vt(e,r)}case"fragmentCall":return void Tt(e,t);case"elements":for(const r of t.nodes)Dt(e,r);return;case"entries":{const r=It(e,t.vars,t.path);for(const r in t.entries)Dt(e,t.entries[r]);return void Vt(e,r)}case"operator":return void St(e,t)}return t},Nt=e=>"kind"in e&&"string"==typeof e.kind,St=(e,t)=>{const r=It(e,t.vars,t.path);void 0!==t.fallback&&Dt(e,t.fallback);const a=t.entry.definition,n=Et(t);for(const[r,i]of a.resolution.entries){const a=t.params[r];void 0!==a?"constant"===a.kind&&null===a.value&&Ct(t,r)||qt(e,n,r,i,a):i.required&&At(e,"error",o.missingRequired,`'${t.name}' requires '${r}'`,t.path,t.order,{operator:t.name,parameter:r})}zt(e,t);const i=[];for(const r in t.params){const n=t.params[r];"perElement"===a.parameters[r]?.evaluation?i.push([r,n]):Dt(e,n)}if(i.length>0){const r={as:Pe(t),referenced:!1};e.iteratorFrames.push(r);for(const[,t]of i)Dt(e,t);e.iteratorFrames.pop(),r.referenced||At(e,"warning",o.deadBinding,`'${t.name}' binds ${null===r.as?"$element / $index":`$${r.as}`} but its 'each' references neither`,t.path,t.order,{operator:t.name})}Vt(e,r)},Ct=(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},qt=(e,t,r,a,n)=>{if("constant"===n.kind){if(null===n.value&&!a.required&&!ee(a.type))return;const i=ne(n.value,a.type);if(!i.ok)return void At(e,"error",o.typeCheck,`'${t.label}.${r}': expected ${i.expected}, received ${i.actual}`,n.path,n.order,{...t.extra,parameter:r});if(void 0!==a.constraints){const i=de(n.value,a.constraints,void 0!==a.elementNullPolicy);i.ok||At(e,"error",o.typeCheck,`'${t.label}.${r}': expected ${i.expected}, received ${i.actual}`,n.path,n.order,{...t.extra,parameter:r})}return}if("elements"===n.kind){const i=a.constraints?.length;return void(void 0!==i&&n.nodes.length!==i&&At(e,"error",o.typeCheck,`'${t.label}.${r}': expected ${i} element${1===i?"":"s"}, received ${n.nodes.length}`,n.path,n.order,{...t.extra,parameter:r}))}if("structural"!==a.evaluation||"as"===r){if("operator"===n.kind){const i=n.entry.definition.returns;((e,t)=>{const r=ce(e),a=ce(t);return!(!r.any&&!a.any)||(void 0!==r.literals&&void 0!==a.literals?r.literals.some(e=>a.literals.includes(e)):void 0!==r.literals?r.literals.some(e=>ue(e,a.basics)):void 0!==a.literals?a.literals.some(e=>ue(e,r.basics)):r.basics.some(e=>a.basics.includes(e)||"integer"===e&&a.basics.includes("number")||"number"===e&&a.basics.includes("integer")))})(i,a.type)||At(e,"error",o.returnsMismatch,`'${n.name}' returns ${JSON.stringify(i)} — it can never satisfy '${t.label}.${r}'`,n.path,n.order,{...t.extra,parameter:r})}}else At(e,"error",o.typeCheck,`'${t.label}.${r}' is structural — it requires a literal value`,n.path,n.order,{...t.extra,parameter:r})},Et=e=>({label:e.name,extra:{operator:e.name}}),Tt=(e,t)=>{const r=It(e,t.vars,t.path);void 0!==t.fallback&&Dt(e,t.fallback);const a=t.entry?.parameters,n=void 0===t.parameters||Nt(t.parameters)?void 0:t.parameters;if(void 0!==a&&"static"===t.argumentsMode){const r={label:t.name,extra:{fragment:t.name}};for(const i in a){const s=a[i],l=n?.[i];void 0!==l?qt(e,r,i,s,l):s.required&&At(e,"error",o.missingRequired,`fragment '${t.name}' – requires '${i}'`,t.path,t.order,{fragment:t.name,parameter:i})}if(void 0!==n)for(const r in n){const i=n[r];if(void 0===a[r]){const n=m(r,Object.keys(a));At(e,"error",o.unknownNodeKey,`fragment '${t.name}' declares no parameter '${r}'${n?` — did you mean '${n}'?`:""}`,i.path,i.order,{parameter:r})}}}if(void 0!==t.parameters)if(Nt(t.parameters))Dt(e,t.parameters);else for(const r in t.parameters)Dt(e,t.parameters[r]);Vt(e,r)},zt=(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,Pt)}catch(r){return void At(e,"error",o.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;At(e,r.severity,o.operatorValidate,r.message,a?.path??t.path,t.order,{operator:t.name,...void 0!==r.parameter?{parameter:r.parameter}:{}})}},Mt=(e,t)=>{switch(t.namespace){case"data":return;case"vars":return void Lt(e,t);case"params":return void Ft(e,t);case"element":case"index":return void Rt(e,t,t.namespace)}},Lt=(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}}At(e,"error",o.unresolvedVar,`'${t.raw}': no var '${a??""}' is declared in scope`,t.path,t.order)},Ft=(e,t)=>{const r=e.context.fragmentParams;if(void 0===r)return void At(e,"error",o.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)||At(e,"error",o.unresolvedParam,`'${t.raw}': the fragment declares no parameter '${String(a)}'`,t.path,t.order)},Rt=(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)}At(e,"error",o.unresolvedBinding,`'${t.raw}' resolves against no enclosing iterator here`,t.path,t.order)},It=(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 i=t[r],s=ke(n,r);for(const t of e.varsFrames)if(t.names.has(r)){At(e,"warning",o.shadowedVar,`'${r}' shadows a var of the same name from an enclosing scope`,s,i.order);break}a.names.set(r,{node:i,declaredAt:s,order:i.order,referenced:!1})}e.varsFrames.push(a);for(const[t,r]of a.names)a.currentVar=t,Dt(e,r.node),a.currentVar=null;return a},Vt=(e,t)=>{if(null!==t){e.varsFrames.pop();for(const[r,a]of t.names)a.referenced||At(e,"warning",o.unreferencedVar,`'${r}' is declared but never referenced in its scope`,a.declaredAt,a.order);Qt(e,t)}},Qt=(e,t)=>{const r=new Set,a=new Set,n=new Set,i=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(i(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)&&i(r)){const a=t.names.get(r);At(e,"error",o.varCycle,`'${r}' participates in a vars cycle — a var may not depend on itself`,a.declaredAt,a.order),n.add(r)}};class Jt{max;entries=new Map;constructor(e){this.max=e,Ut(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(Ut(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 Ut=e=>{if(!Number.isInteger(e)||e<1)throw new RangeError("LRU bound must be a positive integer")},Bt="~",Gt=(e,t)=>{if(t>n)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=Gt(e[r],t+1);if("json"!==a)return a}return"json"}if(!a(e))return"refused";for(const r in e){if(r.length>4096)return"serializer";const a=Gt(e[r],t+1);if("json"!==a)return a}return"json"},Wt=e=>Kt(e,[]),Kt=(e,t)=>Ht(e,0,t)?t.join(""):void 0,Ht=(e,t,r)=>{if(t>n)return!1;if(null===e)return Xt(r,"n");if(void 0===e)return Xt(r,"u");switch(typeof e){case"boolean":return Xt(r,e?"t":"f");case"number":return _t(e,r);case"string":return Xt(r,`s${e.length}:${e}`);case"object":break;default:return!1}if(Array.isArray(e)){r.push("[");for(const a of e)if(!Ht(a,t+1,r))return!1;return Xt(r,"]")}if(!a(e))return!1;r.push("{");for(const a in e)if(r.push(`s${a.length}:${a}`),!Ht(e[a],t+1,r))return!1;return Xt(r,"}")},_t=(e,t)=>Number.isNaN(e)?Xt(t,"N"):e===1/0?Xt(t,"I"):e===-1/0?Xt(t,"J"):Object.is(e,-0)?Xt(t,"#-0"):Xt(t,`#${String(e)}`),Xt=(e,t)=>(e.push(t),!0);class Yt{deps;identity=new WeakMap;content=new Jt(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=Gt(e,0);return"json"===t?JSON.stringify(e):"serializer"===t?Kt(e,[Bt]):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 Zt=/*#__PURE__*/new Set(["type","required","default","description","metadata","constraints"]),er=/*#__PURE__*/new Set(["expression","parameters","description","metadata"]),tr=(r,a,n)=>{const i=(...e)=>["fragments",r,...e],s=t(r);if(!s.ok)return void n(o.invalidName,`'${r}' is not a legal fragment name: ${s.reason}`,i());if(w.has(r))return void n(o.reservedName,`'${r}' is a reserved name and may not name a fragment`,i());if(!e(a))return void n(o.invalidDefinition,`fragment '${r}' must be a wrapper object: { expression, parameters?, description?, metadata? }`,i());if(!("expression"in a))return void n(o.invalidDefinition,`fragment '${r}' has no 'expression'`,i());for(const e of Object.keys(a))er.has(e)||n(o.invalidDefinition,`'${e}' is not a key of a fragment definition`,i(e));const l={name:r,parameters:{},body:{kind:"constant",value:null,path:null,order:0},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(o.invalidDefinition,"'description' must be a string",i("description")):l.description=a.description),void 0!==a.metadata&&(e(a.metadata)?l.metadata=a.metadata:n(o.invalidDefinition,"'metadata' must be a plain object",i("metadata"))),void 0!==a.parameters)if(e(a.parameters))for(const[e,t]of Object.entries(a.parameters)){const r=rr(e,t,i,n);void 0!==r&&(l.parameters[e]=r)}else n(o.invalidDefinition,"'parameters' must be a plain object",i("parameters"));return l},rr=(r,a,n,i)=>{const s=n("parameters",r),l=t(r);if(!l.ok)return void i(o.invalidName,`'${r}' is not a legal parameter name: ${l.reason}`,s);if(k.has(r))return void i(o.reservedName,`'${r}' is a reserved node key and may not name a parameter`,s);if(!e(a))return void i(o.invalidDefinition,`the declaration of '${r}' must be an object`,s);for(const e of Object.keys(a))Zt.has(e)||i(o.invalidDefinition,`'${e}' is not a key of a parameter declaration`,[...s,e]);const c=a.type??"any";if(!ae(c))return void i(o.invalidDefinition,`'${r}' declares an unknown type`,[...s,"type"]);if(void 0!==a.required&&"boolean"!=typeof a.required)return void i(o.invalidDefinition,"'required' must be a boolean",[...s,"required"]);let u;if(void 0!==a.constraints){const e=se(a.constraints);if(!e.ok)return void i(o.invalidDefinition,`'${r}' 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 i(o.invalidDefinition,`'${r}' is declared required and also declares a default — the default could never apply`,[...s,"default"]);if(d){const e=ne(a.default,c);if(!e.ok)return void i(o.typeCheck,`the default for '${r}' does not satisfy its declared type: expected ${e.expected}, got ${e.actual}`,[...s,"default"]);if(void 0!==u){const e=oe(a.default,u);if(!e.ok)return void i(o.typeCheck,`the default for '${r}' 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},ar=(e,t)=>{const r=[],a=new Set,n=new Set,i=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(o.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??[])i(t.name);r.pop(),a.add(s)}};for(const t of e.keys())i(t);return 0===n.size},nr=(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=or(i,e.fragments)};for(const e of t.keys())a(e)},or=(e,t)=>{const{root:r,holes:a}=e;if(0===a.length)return;const n=[];for(const e of a){const r=ir(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]}},ir=(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},sr=["fallback","useCache"],lr=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:i,aliases:s}=n,l=new Map,c=(e,t,r)=>{const n=l.get(e);return void 0!==n?(a(o.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(o.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(o.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&&(i.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(o.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(o.invalidOptions,"'operators' must be an array",["operators"]),void 0!==t.operatorDefaults&&cr(t.operatorDefaults,i,s,a),((t,r,a,n)=>{if(void 0===t)return;if(!e(t))return void n(o.invalidOptions,"'fragments' must be a plain object",["fragments"]);for(const[e,o]of Object.entries(t)){const t=tr(e,o,n);void 0!==t&&a(e,["fragments",e])&&r.fragments.set(e,t)}const i=new Map;for(const[e,a]of r.fragments){const o=t[e],s=Ce(o.expression,r,{basePath:["expression"]});Ot(s,{fragmentParams:new Set(Object.keys(a.parameters))});for(const{issue:t}of s.issues)if("error"===t.severity)n(t.code,`fragment '${e}': ${t.message}`,["fragments",e,...t.path]);else{const e={...t,path:[...t.path]};Object.freeze(e.path),a.warnings.push(Object.freeze(e))}a.body=s.root,i.set(e,s)}ar(i,n)&&nr(r,i)})(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 $({code:o.invalidOptions,message:a,path:t.path,...void 0!==t.operator?{operator:t.operator}:{},issues:e})})(r),n},cr=(t,r,a,n)=>{if(e(t))for(const[i,s]of Object.entries(t)){const t=["operatorDefaults",i],l=r.get(i);if(void 0===l){const e=a.get(i);void 0!==e?n(o.invalidOptions,`'operatorDefaults' keys are canonical names — use '${e}', not its alias '${i}'`,t,e):n(o.unknownOperator,`'${i}' names no registered operator`,t);continue}if(!e(s)){n(o.invalidOptions,`the defaults for '${i}' must be a plain object`,t,i);continue}let c=!0;for(const[e,r]of Object.entries(s)){const a=[...t,e];if(sr.includes(e)){"useCache"===e&&"boolean"!=typeof r&&(n(o.invalidOptions,"the 'useCache' modifier default must be a boolean",a,i),c=!1);continue}const s=l.definition.parameters[e];if(void 0===s){n(o.invalidOptions,`'${e}' names no declared parameter of '${i}' (nor 'fallback'/'useCache')`,a,i),c=!1;continue}if(s.required){n(o.invalidOptions,`'${e}' is a required parameter of '${i}' — operatorDefaults may only target optional parameters`,a,i),c=!1;continue}const u=ne(r,s.type);if(u.ok){if(void 0!==s.constraints){const t=oe(r,s.constraints);t.ok||(n(o.typeCheck,`the default for '${i}.${e}' violates its declared constraints: expected ${t.expected}, got ${t.actual}`,a,i),c=!1)}}else n(o.typeCheck,`the default for '${i}.${e}' does not satisfy its declared type: expected ${u.expected}, got ${u.actual}`,a,i),c=!1}c&&(l.instanceDefaults=Object.freeze({...s}))}else n(o.invalidOptions,"'operatorDefaults' must be a plain object",["operatorDefaults"])},ur=(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},dr="fig-tree:scope-settled",pr="fig-tree:request-expired",mr="fig-tree:evaluation-timeout";class fr{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?dr:this.parent?.reason}get signal(){if(void 0===this.controller){const e=new AbortController;if(this.controller=e,this.settled)e.abort(dr);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(dr)))}}const hr=(e,t)=>({get aborted(){return e.aborted},get reason(){return e.reason},signal:e,clock:t.clock,settle:x}),vr=(e,t,r)=>{const a=void 0===e?(()=>{const e=new AbortController;return{signal:e.signal,abort:t=>e.abort(t),settle:()=>e.abort(dr)}})():(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(dr)}}})(e),{signal:n}=a;let o;const i=new Promise((e,t)=>{o=t});i.catch(x);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()}}},yr=(e,t)=>vr(e,t,pr),gr=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},br=/*#__PURE__*/Object.freeze({});class wr{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 kr={memo:(e,t)=>t()},$r={note:x},xr=Symbol("fig-tree:internal-error"),jr=e=>Er(`[fig-tree internal] ${e}`,xr),Pr=e=>zr(e,xr),Or=Symbol("fig-tree:cancelled"),Ar=()=>Er("[fig-tree] evaluation cancelled",Or),Dr=e=>zr(e,Or),Nr=(e,t,r)=>e.rootScope.aborted?Sr(e.rootScope.reason,t,r):e.abortScope.aborted?Ar():void 0,Sr=(e,t,r)=>e===dr?Ar():Cr(e,$e(t),{operator:r}),Cr=(e,t,r={})=>{const{operator:a,ms:n}=r,i=e===mr,s=void 0===n?"":`${n}ms `;return new $({code:i?o.timeout:o.aborted,message:i?`evaluation exceeded its ${s}timeout`:"evaluation was aborted by the caller",path:t,...void 0!==a?{operator:a}:{}})},qr=e=>j(e)&&(e.code===o.aborted||e.code===o.timeout),Er=(e,t)=>{const r=new Error(e);return Tr(r,t),r},Tr=(e,t)=>{e[t]=!0},zr=(e,t)=>e instanceof Error&&!0===e[t],Mr=()=>performance.now(),Lr=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,...Fr(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=Ur(e),l=Br(e),c={path:$e(e.path),kind:Jr(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}}},Fr=e=>Rr(e.node).filter(t=>!e.seen.has(t)).map(e=>({entry:{path:$e(e.path),kind:Jr(e),status:"skipped"},order:e.order,index:0})),Rr=e=>{switch(e.kind){case"operator":return[...Object.values(e.params).flatMap(Ir),...void 0!==e.fallback?[e.fallback]:[],...Object.values(e.vars??{})];case"fragmentCall":return[...Vr(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[]}},Ir=e=>"elements"===e.kind||"entries"===e.kind?Rr(e):[e],Vr=e=>void 0===e?[]:Qr(e)?[e]:Object.values(e),Qr=e=>"string"==typeof e.kind,Jr=e=>{switch(e.kind){case"operator":return"operator";case"fragmentCall":return"fragment";case"reference":return"reference";case"skeleton":return"skeleton";default:return"literal"}},Ur=e=>"operator"===e.kind||"fragmentCall"===e.kind?e.name:void 0,Br=e=>"reference"===e.kind?e.raw:void 0,Gr=(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,P(()=>za(n,a,{var:e})));return a},Wr=async(e,t,r,a,n)=>{const o={...r,params:"dynamic"===e.argumentsMode?await Hr(e,t,a):Kr(e,t,a),frame:n};delete o.scope,delete o.bindings;const i=await za(t.body,o);return void 0===i?null:i},Kr=(e,t,r)=>{const a=e.parameters??{},n=new Map;for(const[o,i]of Object.entries(t.parameters)){const t=a[o],s=P(async()=>{if(void 0===t)return _r(e,o,i,r);let a;try{a=await za(t,r)}catch(e){throw ta(e,r.frame)}return Xr(e,o,i,a,t.path,r)});n.set(o,()=>{const e=s();return e.catch(x),e})}return n},Hr=async(t,r,a)=>{const n=t.parameters;let i;try{i=await za(n,a)}catch(e){throw ta(e,a.frame)}if(!e(i))throw ta(Yr(t,o.typeCheck,`'parameters' must evaluate to an object, received ${Zr(i)}`,n.path),a.frame);const s=new Map;for(const[e,o]of Object.entries(r.parameters)){const r=Object.hasOwn(i,e)?Xr(t,e,o,i[e],n.path,a):_r(t,e,o,a,n.path);s.set(e,()=>Promise.resolve(r))}return s},_r=(e,t,r,a,n=e.path)=>{if(!r.required)return r.default??null;throw ta(Yr(e,o.missingRequired,`requires '${t}'`,n),a.frame)},Xr=(e,t,r,a,n,i)=>{const s=void 0===a?null:a;if(null===s&&!r.required&&!ee(r.type))return r.default??null;if(!i.runtimeTypeCheck)return s;const l=ne(s,r.type);if(!l.ok)throw ta(Yr(e,o.typeCheck,`parameter '${t}': expected ${l.expected}, received ${l.actual}`,n),i.frame);if(void 0!==r.constraints){const a=oe(s,r.constraints);if(!a.ok)throw ta(Yr(e,o.typeCheck,`parameter '${t}': expected ${a.expected}, received ${a.actual}`,n),i.frame)}return s},Yr=(e,t,r,a)=>new $({code:t,message:`fragment '${e.name}' – ${r}`,path:$e(a)}),Zr=e=>null===e?"null":Array.isArray(e)?"array":typeof e,ea=Symbol("fig-tree:anchored"),ta=(e,t)=>!j(e)||zr(e,ea)?e:(Tr(e,ea),void 0===t||(e.fragment=t.fragment,e.fragmentPath=e.path,e.path=$e(t.callPath)),e);class ra 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 aa=e=>e instanceof ra,na=Symbol("fig-tree:lazy-handle"),oa=(e,t,r)=>sa(Array.from({length:e},(e,a)=>ia(a,()=>t(a),r)),e),ia=async(e,t,r)=>{try{return{index:e,ok:!0,value:r(await t())}}catch(t){return{index:e,ok:!1,error:t}}},sa=(e,t)=>{const r=new Map(e.map((e,t)=>[t,e]));return{[na]:!0,length:t,async*[Symbol.asyncIterator](){for(;r.size>0;){const e=await Promise.race(r.values());r.delete(e.index),yield e}}}},la=e=>({[na]:!0,evaluate:P(e)}),ca=e=>({[na]:!0,evaluate:()=>Promise.resolve(e)}),ua=(e,t,r,a,n)=>la(async()=>da(await za(e,n),t,r,a,n)),da=(e,t,r,a,n)=>{if(n.runtimeTypeCheck){const n=ne(e,a.type);if(!n.ok)throw va(t,r,n);if(null!==e&&void 0!==a.constraints){const n=de(e,a.constraints,void 0!==a.elementNullPolicy);if(!n.ok)throw va(t,r,n)}}return a.truthiness?wa(e,a.type):e},pa=(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()=>da(await za(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(x),l.set(t,u),u};return{[na]:!0,evaluate:c,settle:()=>oa(i.length,c,e=>e)}},ma=(e,t)=>t.truthiness?E(e):e,fa=(e,t,r)=>{if("lazyElements"===t.evaluation&&"elements"===e.kind)return e.nodes.map((e,a)=>la(async()=>ma(await za(e,r,{index:a}),t)));if("race"===t.evaluation&&"elements"===e.kind)return((e,t,r)=>oa(e.length,r=>za(e[r],t,{index:r}),r))(e.nodes,r,e=>ma(e,t));if("lazyEntries"===t.evaluation&&"entries"===e.kind){const a=Gr(r,e.vars),n={};for(const[r,o]of Object.entries(e.entries))n[r]=la(async()=>ma(await za(o,a),t));return n}},ha=(e,t)=>{switch(t.evaluation){case"lazyElements":return e.map(e=>ca(ma(e,t)));case"race":return((e,t)=>oa(e.length,t=>Promise.resolve(e[t]),t))(e,e=>ma(e,t));case"lazyEntries":{const r={};for(const[a,n]of Object.entries(e))r[a]=ca(ma(n,t));return r}case"lazy":return ca(e);default:return e}},va=(e,t,r)=>new $({code:o.typeCheck,message:`${e.name} – parameter '${t}': expected ${r.expected}, received ${r.actual}`,path:$e(e.path),operator:e.name}),ya=(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=ne(o,n.type);if(!i.ok)throw va(e,a.selector,i);const s=a.table.find(e=>e.value===o);if(void 0===s)throw jr(`no null-policy row for ${e.name}.${a.selector}`);return s.policy},ga=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},ba=t=>Array.isArray(t)?t.includes(null):!!e(t)&&Object.values(t).includes(null),wa=(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(E);if(e(t)){const e={};for(const[r,a]of Object.entries(t))e[r]=E(a);return e}}return E(t)},ka=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(za(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?P(()=>za(n,t)):void 0!==a&&Object.hasOwn(a,r)?P(()=>a[r]):void 0;if(void 0!==e)for(const t of o.replacesNullAt)(u??={})[t]=e;break}void 0!==n&&(d[r]=ua(n,e,r,o,t));break;case"lazyElements":case"lazyEntries":case"race":{if(void 0===n)break;const e=fa(n,o,t);if(void 0!==e){d[r]=e;break}s.push(r),l.push(za(n,t));break}case"perElement":break;default:o.evaluation}}if(l.length>0)if(1===l.length){const e=l[0];c[s[0]]=O(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&&!ee(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 ga(n,a,o));const i="eager"!==a.evaluation&&"structural"!==a.evaluation;if(null===n&&ee(a.type)&&!i&&"propagate"===ya(e,a,c))return{params:d,propagate:!0};if("propagate"===a.elementNullPolicy&&ba(n))return{params:d,propagate:!0};n=da(n,e,r,a,t),d[r]=ha(n,a)}for(const[r,a]of i){if(void 0===a.over)throw jr(`parameter '${r}' of '${e.name}' declares perElement without 'over'`);const n=e.params[r];void 0!==n&&(d[r]=pa(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=Pa(e,t.options),i=xa(n,r),s=void 0===i?void 0:yr(t.abortScope.signal,i),l=void 0===s?t:{...t,abortScope:hr(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 wr(e.abortScope,e.options,r?{memo:(n={operator:t.name,fingerprint:t.fingerprint,note:a},o=e.cache,(e,t)=>{const r=Wt(["M",n.operator,n.fingerprint,e]);return void 0===r?t():gr(o,r,t,n.note)})}:kr,void 0===a?$r:{note:a});var n,o})(l,n,o,c);try{if(!o||"auto"!==n.cache)return await $a(e,t,r,u,s);const a=((e,t)=>{const{definition:r}=e.entry;if(!r.deliversLazily)return Wt(["A",r.name,r.fingerprint,t])})(e,r),i=()=>$a(e,t,r,u,s);return await(void 0===a?i():gr(t.cache,a,i,c))}catch(r){throw ja(r,e,t,s,i)}finally{s?.settle()}},$a=async(e,t,r,a,n)=>{const o=Nr(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?Aa(await i,e):(i.catch(x),Aa(await Promise.race([i,n.expiry]),e))},xa=(e,t)=>{const r=e.timeoutParam;if(null===r)return;const a=t[r];return"number"==typeof a&&a>0?a:void 0},ja=(e,t,r,a,n)=>{if(Pr(e)||Dr(e))return e;const i=Nr(r,t.path,t.name);return void 0!==i?i:a?.signal.reason===pr?new ra(`request exceeded its ${String(n)}ms timeout`,{code:o.requestTimeout}):e},Pa=(e,t)=>e.useCache??e.entry.instanceDefaults?.useCache??t.useCache??e.entry.definition.useCache,Oa=(e,t)=>{const r=e.fallback;if(void 0!==r)return()=>za(r,t);const a=e.entry.instanceDefaults;return void 0!==a&&Object.hasOwn(a,"fallback")?()=>a.fallback:void 0},Aa=(e,t)=>{if(void 0===e)return null;if("number"==typeof e&&!Number.isFinite(e))throw new $({code:o.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[na])throw new $({code:o.escapedHandle,message:`${t.name} – returned a lazy handle instead of evaluating it`,path:$e(t.path),operator:t.name});var r;return e},Da=(e,t)=>{if(j(e))return e;if(aa(e))return new $({code:e.code??o.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 $({code:o.operatorFailure,message:`${t.name} – ${r}`,path:$e(t.path),operator:t.name})},Na=(e,t)=>0===e.segments.length?t.data:Ea(t.data,e.segments,e,t,"is absent from the evaluation data"),Sa=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 jr(`'${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?Ta(o):Ea(o,a,e,t,`is absent from the value of '$vars.${r}'`)},Ca=async(e,t)=>{const r=t.params;if(void 0===r)throw jr(`'${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]=Ta(await r())})),e}const o="string"==typeof a?r.get(a):void 0;if(void 0===o)throw jr(`'${e.raw}': the fragment declares no parameter '${String(a)}' — the static gate should have refused it`);const i=await o();return 0===n.length?Ta(i):Ea(i,n,e,t,`is absent from the value of '$params.${String(a)}'`)},qa=(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 jr(`'${e.raw}': no enclosing iterator binds it — the static gate should have refused it`);return"index"===r?a.index:0===e.segments.length?Ta(a.element):Ea(a.element,e.segments,e,t,`is absent from '${e.raw.split(".")[0]}'`)},Ea=(e,t,r,a,n)=>{const i=b(e,t);if(i.found)return Ta(i.value);if(!a.strictDataPaths)return null;throw new $({code:o.missingDataPath,message:`'${r.raw}' ${n} (strictDataPaths)`,path:$e(r.path)})},Ta=e=>void 0===e?null:e,za=(e,t,r)=>void 0!==t.trace?Ma(e,t,t.trace,r):t.abortScope.aborted?Promise.reject(Nr(t,e.path)):La(e,t),Ma=async(e,t,r,a)=>{const n=r.enter(e,t.traceParent,t.frame,a),o=Mr();try{if(t.abortScope.aborted)throw Nr(t,e.path);const a=await La(e,{...t,traceParent:n});return r.settle(n,"value",{value:a,elapsed:Mr()-o}),a}catch(e){throw r.settle(n,Dr(e)?"cancelled":"failed",{...j(e)?{error:e}:{},elapsed:Mr()-o}),e}},La=(e,t)=>{try{switch(e.kind){case"constant":return e.value;case"reference":return((e,t)=>{switch(e.namespace){case"data":return Na(e,t);case"vars":return Sa(e,t);case"params":return Ca(e,t);case"element":case"index":return qa(e,t)}})(e,t);case"skeleton":return Fa(e,t);case"operator":return(async(e,t)=>{const r=Gr(t,e.vars),a=e.entry.definition.deliversLazily?new fr(r.abortScope):void 0,n=void 0===a?r:{...r,abortScope:a};try{try{return await ka(e,n)}finally{a?.settle()}}catch(a){if(Pr(a)||Dr(a)||qr(a))throw a;const n=Da(a,e),o=Oa(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(Pr(t)||Dr(t)||qr(t))throw t;const r=Da(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 jr(`fragment call '${e.name}' resolved to nothing — the static gate should have refused it`);const a=Gr(t,e.vars),n=new fr(a.abortScope),o={fragment:e.name,callPath:t.frame?.callPath??e.path},i={...a,abortScope:n};try{try{return await Wr(e,r,i,a,o)}finally{n.settle()}}catch(r){if(Pr(r)||Dr(r)||qr(r))throw r;const n=ta(r,o),{fallback:i}=e;if(void 0===i)throw n;try{return await za(i,a)}catch(e){if(Pr(e)||Dr(e)||qr(e))throw e;const r=ta(e,t.frame);throw j(r)&&void 0===r.cause&&(r.cause=n),r}}})(e,t);case"elements":case"entries":throw jr(`a '${e.kind}' parameter value reached the node dispatch — parameter resolution consumes these, and nothing else may hold one`);case"invalid":throw jr("an invalid node reached evaluation — the static gate should have refused it")}}catch(e){return Promise.reject(e)}},Fa=async(e,t)=>{const r=t.rootBoundary,a=void 0===r?t:{...t,rootBoundary:void 0},n=Gr(a,e.vars),o=e.holes.map(e=>void 0===r?za(e.node,n):r(()=>za(e.node,n),e.node)),i=o.some(O)?await Promise.all(o):o;return Ae(e.skeleton,e.holes,i)},Ra=Number.MAX_SAFE_INTEGER,Ia=(e,t)=>{if(j(e))return e;const r=e instanceof Error?e.message:String(e);return new $({code:o.operatorFailure,message:r,path:t.path})},Va=(e,t)=>{if(void 0===e.holePath)return e.holePath=t,e;const r=new $({...e,message:e.message,holePath:t});return r.stack=e.stack,r},Qa=async(e,t,r)=>{const{timeout:a,signal:n}=t,i="report"===t.mode,s=e.holes.length>0,l=void 0!==a||void 0!==n?vr(n,a,mr):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 fr(void 0),u=void 0!==l&&void 0!==a&&e.timeoutShielded&&s,d=i?(()=>{const e=[];return{record:(t,r)=>{e.push({error:Va(Ia(t,r),r.path),order:r.node.order})},add:t=>{e.push({error:t,order:Ra})},emit:()=>[...e].sort((e,t)=>e.order-t.order).map(e=>e.error)}})():void 0,p=!0===t.trace?Lr(e.issues.map(e=>e.issue).filter(e=>"error"!==e.severity)):void 0,m=((e,t,r,a)=>({options:e,data:e.data??br,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)?Ga(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 Cr(c.reason,[]);const t=()=>h&&void 0!==f?f(()=>za(e.root,v),e.root):za(e.root,v),r=await(u||void 0===l?t():Ba(t,l,a));return void 0!==d&&u&&Ua(l)&&d.add(Cr(mr,[],{ms:a})),Ja(r,d,p)}catch(e){if(void 0!==d&&j(e)&&e.code===o.timeout)return d.add(e),Ja(null,d,p);throw void 0!==p&&j(e)&&void 0===e.trace&&(e.trace=p.finish()),e}finally{c.settle()}},Ja=(e,t,r)=>({result:e,errors:t?.emit()??[],...void 0!==r?{trace:r.finish()}:{}}),Ua=e=>e.signal.aborted&&e.signal.reason===mr,Ba=(e,t,r)=>Promise.race([e(),t.expiry.catch(e=>{throw Cr(e,[],{ms:r})})]),Ga=(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 jr(`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()):Wa(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!==mr)throw Cr(e,[]);if(!l)return a?.noteOn(i.node,{type:"shielded-fallback"}),Ka(i)})])}},Wa=async(e,t,r)=>{try{return await e()}catch(e){if(Pr(e)||Dr(e)||qr(e))throw e;return r.record(e,t),null}},Ka=e=>{if(void 0===e.timeoutFallback)throw jr("a shielded artifact has a hole with no static fallback");return e.timeoutFallback.value},Ha={hit:!1},_a=e=>{if(void 0===e)return{maxSize:50,maxTime:1800};if(!a(e))throw Ya("'cache' must be an object");const{store:t,maxSize:r,maxTime:n}=e;if(void 0!==t&&!Xa(t))throw Ya("'cache.store' must provide get, set, delete and clear methods");if(void 0!==r&&(!Number.isInteger(r)||r<1))throw Ya("'cache.maxSize' must be a positive integer");if(void 0!==n&&("number"!=typeof n||n<=0||Number.isNaN(n)))throw Ya("'cache.maxTime' must be a positive number of seconds, or Infinity");return{...void 0!==t?{store:t}:{},maxSize:r??50,maxTime:n??1800}},Xa=e=>"object"==typeof e&&null!==e&&["get","set","delete","clear"].every(t=>"function"==typeof e[t]),Ya=e=>new $({code:o.invalidOptions,message:e,path:[]});class Za{store;own;maxTime;current=0;constructor(e){void 0===e.store?(this.own=new Jt(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 Ha}return a(r=t)&&"ft3"===r.fig&&"number"==typeof r.generation?t.generation<this.current||en(t)?(this.drop(e),Ha):{hit:!0,value:t.value}:Ha;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(x)}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(x)}catch{}}}const en=e=>void 0!==e.expiresAt&&e.expiresAt<=Date.now(),tn=e=>e===A?0:"number"==typeof e?1:2,rn=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=tn(r)-tn(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]}),an=(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},nn=(e,t)=>{const r=[];return void 0!==t.maxDepth&&e.maxDepth>t.maxDepth&&r.push(on(e.maxDepth,t.maxDepth)),void 0!==t.maxNodes&&e.nodeCount>t.maxNodes&&r.push({severity:"error",code:o.maxNodesExceeded,message:`the expression holds ${e.nodeCount} evaluable nodes — maxNodes is ${t.maxNodes}`,path:[]}),r},on=(e,t)=>({severity:"error",code:o.maxDepthExceeded,message:`the expression nests ${e} levels deep — maxDepth is ${t}`,path:[]}),sn=(e,t,r)=>{const a=[...nn(e,t),...e.issues.map(r)];if(void 0!==t.data)for(const r of e.dependencies.dataPaths.values())b(t.data,r).found||a.push({severity:"warning",code:o.missingDataPath,message:`'${D(r)}' is absent from the supplied sample data`,path:[]});return a},ln="...",cn=/*#__PURE__*/new Set(["propagate","value"]),un=e=>{const t={};for(const[r,a]of Object.entries(e.parameters))t[r]=a.type??"any";const r=dn(e.parameters,t,(t,r,a)=>{throw new $({code:t,message:r,path:a,operator:e.name})});return pn(e,r)},dn=(e,t,r)=>{const a=Object.entries(t).filter(([,e])=>te(e)).map(([e])=>e),n=new Map;for(const[i,s]of Object.entries(e)){if("function"!=typeof s.nullPolicy)continue;const e=["parameters",i,"nullPolicy"];if(1!==a.length){r(o.invalidNullPolicy,`a conditional 'nullPolicy' requires exactly one literal-union parameter in the definition — found ${a.length}`,e,i);continue}const l=a[0],c=t[l];if(!te(c))continue;const u=[];let d=!0;for(const t of c.literal){let a;try{a=s.nullPolicy(t)}catch(a){r(o.invalidNullPolicy,`the conditional 'nullPolicy' threw during compilation for member ${JSON.stringify(t)}: ${String(a)}`,e,i),d=!1;break}if("string"!=typeof a||!cn.has(a)){r(o.invalidNullPolicy,`the conditional 'nullPolicy' must return 'propagate' or 'value' for every member — got ${JSON.stringify(a)} for ${JSON.stringify(t)}`,e,i),d=!1;break}u.push({value:t,policy:a})}d&&n.set(i,{selector:l,table:u})}return n},pn=(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&&ee(i)?"value":"propagate",l={type:fn(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=hn(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(ln)?a.slice(3):null,o={[fe]:!0,name:e.name,category:e.category,description:e.description,parameters:r,resolution:vn(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?fn(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=mn(o),yn(o)},mn=e=>N(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)),fn=e=>"string"==typeof e?e:te(e)?{literal:[...e.literal]}:[...e],hn=t=>{if(Array.isArray(t))return t.map(hn);if(e(t)){const e={};for(const[r,a]of Object.entries(t))e[r]=hn(a);return e}return t},vn=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)}},yn=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&&gn(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)},gn=t=>{Array.isArray(t)?(t.forEach(gn),Object.freeze(t)):e(t)&&(Object.values(t).forEach(gn),Object.freeze(t))},bn=e=>{if(Array.isArray(e))return e;try{return y(e)}catch(e){throw new ra(e.message)}},wn=(e,t)=>{if("string"!=typeof e)return[];try{return y(e),[]}catch(e){return[{severity:"error",parameter:t,message:e.message}]}},kn=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"}]:[],$n=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`}]:[]},xn=/*#__PURE__*/$n("values"),jn=/*#__PURE__*/$n("input"),Pn=/*#__PURE__*/$n("entries"),On=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"}]:[],An=(e,t)=>new ra(`${e} of nothing — the values array is empty${void 0!==t?`; ${t}`:""}`,{code:o.emptyAggregate}),Dn=e=>new ra(e,{code:o.typeCheck}),Nn=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),Sn(r);return!t},Sn=e=>{const[t,...r]=e,a=r.map(e=>e.error).filter(j);return a.length>0&&j(t.error)&&void 0===t.error.related&&(t.error.related=a),t.error},Cn=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)},qn=(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=>K(r(e),a))},En={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)"}},Tn={name:"equal",alias:"=",category:"comparison",description:"Are all the values equal? Deep, structural, key-order-insensitive; a cross-type comparison is false",parameters:En,positionalParams:["...values"],returns:"boolean",validate:On,evaluate:({values:e,caseInsensitive:t})=>qn(e,t)},zn={name:"notEqual",alias:"!=",category:"comparison",description:'Are the values NOT all equal? The exact negation of equal (never "all distinct")',parameters:En,positionalParams:["...values"],returns:"boolean",validate:On,evaluate:({values:e,caseInsensitive:t})=>!qn(e,t)},Mn=(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(T(t,r))}}),Ln=/*#__PURE__*/Mn("greaterThan",">","Is the first value strictly greater than the second?",e=>e>0),Fn=/*#__PURE__*/Mn("greaterThanOrEqual",">=","Is the first value greater than or equal to the second?",e=>e>=0),Rn=/*#__PURE__*/Mn("lessThan","<","Is the first value strictly less than the second?",e=>e<0),In=/*#__PURE__*/Mn("lessThanOrEqual","<=","Is the first value less than or equal to the second?",e=>e<=0),Vn={number:()=>0,string:()=>"",array:()=>[],object:()=>({})},Qn=t=>"number"==typeof t?"number":"string"==typeof t?"string":Array.isArray(t)?"array":e(t)?"object":void 0,Jn={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",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?xn({values:e}):kn({values:e}),evaluate:({values:e,expect:t})=>{if(0===e.length){if(void 0===t)throw An("the sum","pin the mode with 'expect' to get its identity");return Vn[t]()}const r=t??Qn(e[0]);if(void 0===r)throw Dn(`operands must be numbers, strings, arrays or objects — received ${X(e[0])}`);const a=e.find(e=>Qn(e)!==r);if(void 0!==a)throw Dn(`all operands must be ${r}s — received ${X(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)}}},Un={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},Bn={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},Gn={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},Wn={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:xn,evaluate:({values:e})=>e.reduce((e,t)=>e*t,1)},Kn={name:"power",alias:"^",category:"math",description:"Raise a base to an exponent — overflow and complex results fail",parameters:{base:{type:["number","null"]},exponent:{type:["number","null"]}},positionalParams:["base","exponent"],returns:"number",evaluate:({base:e,exponent:t})=>e**t},Hn={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"]},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(B(Math.abs(e),t));return r*B(a,-t)})(e,t)},_n=(e,t,r)=>({name:e,category:"math",description:t,parameters:{value:{type:["number","null"]}},positionalParams:["value"],returns:"number",evaluate:({value:e})=>r(e)}),Xn=/*#__PURE__*/_n("floor","Round down toward negative infinity",Math.floor),Yn=/*#__PURE__*/_n("ceil","Round up toward positive infinity",Math.ceil),Zn=/*#__PURE__*/_n("abs","The absolute value",Math.abs),eo=(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:kn,evaluate:({values:e})=>{const r=e;if(0===r.length)throw An(t);return r.reduce((e,t)=>a(T(t,e))?t:e)}}),to=(e,t,r)=>({name:e,category:"string",description:t,parameters:{value:{type:["string","null"]}},positionalParams:["value"],returns:"string",evaluate:({value:e})=>r(e)}),ro={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?U(e):e.split(t);return r?a.map(R):a}},ao=e=>null!==e&&"object"==typeof e,no=e=>Array.isArray(e.values)&&e.values.some(ao)?[{severity:"error",parameter:"values",message:"a composite element renders as a placeholder, never as text — drill in, or join it explicitly"}]:[],oo={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=>[...xn(e),...no(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"}):ao(e)&&r.trace.note({type:"render",token:a,rendered:"placeholder"}),F(e)}).join(t)},io=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}`},so={type:"array",description:"The collection iterated over; a null input is a type error"},lo={type:"string",required:!1,evaluation:"structural",description:"Rename the bindings: as: 'row' binds $row and $rowIndex"},co={type:"array",required:!1,evaluation:"lazy",replacesNullAt:["input"],description:"Used as the collection when input evaluates to null — typically []"},uo={type:"any",evaluation:"perElement",over:"input",description:"The predicate, per element — a truthiness position, so null is falsy",truthiness:!0},po={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:S,returns:"any",validate:({path:e})=>wn(e,"path"),evaluate:({path:e,from:t,default:r},a)=>{const n=b(t,bn(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 ra(`'${mo(e)}' is missing (strictDataPaths)`,{code:o.missingDataPath});return null}},mo=e=>"string"==typeof e?e:e.map(e=>String(e)).join("."),fo={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=>[...Pn(e),...ho(e)],evaluate:({entries:e},t)=>{const r={};for(const a of e){const e=F(a.key);Object.hasOwn(r,e)&&t.trace.note({type:"key-overwrite",key:e}),r[e]=a.value}return r}},ho=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=F(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},vo=(e,t)=>new ra(`cannot convert ${X(e)} to ${t}`),yo=/*#__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:xn,evaluate:({values:e})=>Nn(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:xn,evaluate:({values:e})=>Nn(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:F(e);if(null!==a&&Object.hasOwn(t,a))return t[a].evaluate();if(void 0!==r)return r.evaluate();throw new ra(`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:xn,evaluate:async({values:e})=>{for(const t of e){const e=await t.evaluate();if(null!==e)return e}return null}},Tn,zn,Ln,Fn,Rn,In,Jn,Un,Wn,Bn,Gn,Kn,Hn,Xn,Yn,Zn,/*#__PURE__*/eo("min","the minimum","The smallest of the values — numbers numerically, strings in codepoint order",e=>e<0),/*#__PURE__*/eo("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=F(e);ao(e)&&n.trace.note({type:"render",token:t.raw,rendered:"placeholder"});const l=r?R(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=Q(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=J(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("")}},ro,oo,/*#__PURE__*/to("lower","Lowercase a string — Unicode default case mapping, locale-independent",e=>e.toLowerCase()),/*#__PURE__*/to("upper","Uppercase a string — Unicode default case mapping, locale-independent",e=>e.toUpperCase()),/*#__PURE__*/to("trim","Strip whitespace (the JS trim set) from both ends of a string",R),{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?io(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=io(r);if(void 0!==o)throw new ra(o);const i=e=>{try{return new RegExp(t,r+e)}catch(e){throw new ra(`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?U(e).length:e.length},{name:"map",category:"array",description:"Transform every element of an array",parameters:{input:so,as:lo,nullInputDefault:co,each:{type:"any",evaluation:"perElement",over:"input",description:"Evaluated per element, with $element and $index bound"}},positionalParams:["input","each"],returns:"array",validate:jn,evaluate:({each:e})=>Cn(e.settle())},{name:"filter",category:"array",description:"Keep the elements of an array whose predicate is truthy",parameters:{input:so,as:lo,nullInputDefault:co,each:uo},positionalParams:["input","each"],returns:"array",validate:jn,evaluate:async({input:e,each:t})=>{const r=await Cn(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:so,as:lo,nullInputDefault:co,each:uo,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:jn,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:so,as:lo,nullInputDefault:co,each:uo},positionalParams:["input","each"],returns:"boolean",validate:jn,evaluate:({each:e})=>Nn(e.settle(),!0)},{name:"every",category:"array",description:"True when every element satisfies the predicate",parameters:{input:so,as:lo,nullInputDefault:co,each:uo},positionalParams:["input","each"],returns:"boolean",validate:jn,evaluate:({each:e})=>Nn(e.settle(),!1)},po,fo,{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 ra(`'${t}' is not a numeric string — use regex to extract a number from text`);return r}throw vo(t,"number");case"string":if(Array.isArray(t)||e(t))throw new ra(`cannot convert ${X(t)} to string — a cast is not a render; use buildString or join`);if("object"==typeof t)throw vo(t,"string");return F(t);case"boolean":if("string"==typeof t){const e=t.trim().toLowerCase();if("true"===e)return!0;if("false"===e)return!1}return E(t);case"array":return Array.isArray(t)?t:[t]}}}].map(un),go=(e,t)=>{const r=((e,t)=>{const r={...e};for(const[e,n]of Object.entries(t)){if(void 0===n)continue;if("data"===e||!a(n)){r[e]=n;continue}const t=r[e],o=a(t)?{...t}:{};for(const[e,t]of Object.entries(n))void 0!==t&&(o[e]=t);r[e]=o}return r})(null===e?{}:e.options,t);So(r);const n=bo(r);if(null!==e&&!(e=>void 0!==e.operators||void 0!==e.fragments||void 0!==e.operatorDefaults)(t))return{options:r,evaluation:n,registry:e.registry,compileCache:e.compileCache};const o=lr({operators:r.operators??[yo],...void 0!==r.operatorDefaults?{operatorDefaults:r.operatorDefaults}:{},...void 0!==r.fragments?{fragments:r.fragments}:{}});return{options:r,evaluation:n,registry:o,compileCache:new Yt({compile:e=>wo(e,o),probe:e=>ge(e,o)})}},bo=e=>{const t={...e};return delete t.operators,delete t.fragments,t},wo=(e,t)=>{const r=Ce(e,t);return Ot(r),r};class ko{state;results;version=H;constructor(e={}){this.state=go(null,e),this.results=new Za(_a(e.cache))}updateOptions(e={}){const t=go(this.state,e),r=_a(t.options.cache);this.state=t,this.results.configure(r)}clearCache(){this.results.clear()}getOptions(){return(e=>{const t={};for(const[r,n]of Object.entries(e))t[r]=a(n)?{...n}:n;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:an(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}])),warnings:[...e.warnings],dependencies:rn(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:Do(this.state.evaluation,t),a=wo(e,this.state.registry),n=sn(a,r,e=>e.issue);return{valid:!n.some(e=>"error"===e.severity),issues:n,timeoutShielded:a.timeoutShielded}}getDependencies(e){return rn(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 $o(r.evaluation,this.results,e,t,()=>r.compileCache.resolve(e),()=>wo(e,r.registry))}compile(e){const{state:t}=this;return Po(e,t.compileCache.resolve(e),t.evaluation,t.registry,this.results)}}const $o=async(e,t,r,a,n,o)=>{const i=void 0===a?e:Do(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=on(u.depth,i.maxDepth);if(!s)throw qo(e,[e]);return Oo(null,[qo(e)])}return l?Oo(r,[]):r}const{artifact:d}=u;if(d.hasErrors||void 0!==i.maxDepth||void 0!==i.maxNodes){const e=[...nn(d,i),...d.issues.map(e=>e.issue)],t=e.filter(e=>"error"===e.severity);if(t.length>0){if(!s)throw qo(t[0],e);return Oo(null,t.map(e=>qo(e)))}}const p=await Qa(d,i,t);return l?p:p.result};let xo;class jo{#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,xo??=(e,t)=>{if("object"!=typeof e||null===e||!(#r in e))return;const r=void 0===t?e.#a:Do(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 $o(this.#a,this.#o,this.#t,e,()=>this.#r,()=>this.#l())}getDependencies(){return rn(this.#l().dependencies)}#l(){return"artifact"===this.#r.kind?this.#r.artifact:this.#i??=wo(this.#t,this.#n)}}const Po=(e,t,r,a,n)=>new jo(e,t,r,a,n),Oo=(e,t)=>({result:e,errors:t}),Ao=/*#__PURE__*/new Set(Object.keys({data:0,signal:0,timeout:0,mode:0,trace:0})),Do=(e,t)=>{let r;for(const a in t){const n=t[a];if(void 0!==n){if(!Ao.has(a))throw No(a);r??={...e},r[a]=n}}return void 0===r?e:(So(t),r)},No=e=>new $({code:o.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:[]}),So=e=>{const{timeout:t,signal:r}=e;if(void 0!==t&&("number"!=typeof t||!Number.isFinite(t)||t<=0))throw new $({code:o.invalidOptions,message:"'timeout' must be a positive number of milliseconds",path:[]});if(void 0!==r&&!Co(r))throw new $({code:o.invalidOptions,message:"'signal' must be an AbortSignal",path:[]})},Co=e=>"object"==typeof e&&null!==e&&"boolean"==typeof e.aborted&&"function"==typeof e.addEventListener&&"function"==typeof e.removeEventListener,qo=(e,t)=>new $({code:e.code,message:e.message,path:e.path,...void 0!==e.operator?{operator:e.operator}:{},...void 0!==t?{issues:t}:{}}),Eo=/[a-z]Default$/,To=/*#__PURE__*/new Set(["eager","race","lazy","lazyElements","lazyEntries","perElement","structural"]),zo=/*#__PURE__*/new Set(pe),Mo=e=>"array"===e||"any"===e||!!Array.isArray(e)&&(e.includes("array")||e.includes("any")),Lo=e=>"array"===e||"object"===e||"any"===e||!!Array.isArray(e)&&(e.includes("array")||e.includes("object")||e.includes("any")),Fo=(e,t)=>{const[r]=e,a=e.length-1,n=a>0?`${r.message} (+ ${a} more issue${1===a?"":"s"})`:r.message;throw new $({code:o.invalidDefinition,message:n,path:r.path,...void 0!==t?{operator:t}:{},issues:e})};function Ro(r){if(he(r))return r;const a=[],n=e(r)?r.name:void 0,i="string"==typeof n?n:void 0,s=(e,t,r,n)=>{a.push({severity:"error",code:e,message:t,path:r,...void 0!==i?{operator:i}:{},...void 0!==n?{parameter:n}:{}})};e(r)||(s(o.invalidDefinition,"a definition must be a plain object",[]),Fo(a));const l=r;"string"!=typeof l.name&&s(o.invalidDefinition,"'name' is required and must be a string",["name"]),"string"==typeof l.description&&""!==l.description||s(o.invalidDefinition,"'description' is required and must be non-empty",["description"]),e(l.parameters)||s(o.invalidDefinition,"'parameters' is required and must be an object of declarations (may be {})",["parameters"]),"function"!=typeof l.evaluate&&s(o.invalidDefinition,"'evaluate' is required and must be a function",["evaluate"]),a.length>0&&Fo(a,i),"string"!=typeof l.category?s(o.invalidDefinition,`'category' is required and must be one of ${[...zo].join(", ")}`,["category"]):zo.has(l.category)||s(o.invalidDefinition,`'${l.category}' is not a category — expected one of ${[...zo].join(", ")}`,["category"]),void 0!==l.alias&&"string"!=typeof l.alias&&s(o.invalidDefinition,"'alias' must be a string",["alias"]),void 0!==l.useCache&&"boolean"!=typeof l.useCache&&s(o.invalidDefinition,"'useCache' must be a boolean",["useCache"]),void 0!==l.cache&&"auto"!==l.cache&&"manual"!==l.cache&&s(o.invalidDefinition,"'cache' must be 'auto' or 'manual'",["cache"]),void 0===l.metadata||e(l.metadata)||s(o.invalidDefinition,"'metadata' must be a plain object",["metadata"]),void 0===l.positionalParams||Array.isArray(l.positionalParams)&&!l.positionalParams.some(e=>"string"!=typeof e)||s(o.invalidDefinition,"'positionalParams' must be an array of parameter names",["positionalParams"]),void 0!==l.timeoutParam&&"string"!=typeof l.timeoutParam&&s(o.invalidDefinition,"'timeoutParam' must be a parameter name",["timeoutParam"]),void 0!==l.validate&&"function"!=typeof l.validate&&s(o.invalidDefinition,"'validate' must be a function",["validate"]),void 0===l.returns||ae(l.returns)||s(o.invalidDefinition,"'returns' must be a metadata-vocabulary type",["returns"]);const c=(e,t,r)=>{e===me?s(o.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,r)=>{const a=t(e);a.ok?w.has(e)&&s(o.reservedName,`'${e}' is a reserved name`,r):s(o.invalidName,`'${e}': ${a.reason}`,r)};"string"==typeof l.name&&u(l.name,["name"]),"string"==typeof l.alias&&u(l.alias,["alias"]);const d=l.parameters,p={};for(const[r,a]of Object.entries(d)){const n=["parameters",r],i=t(r);i.ok?k.has(r)&&s(o.reservedName,`'${r}' is a reserved node key and cannot name a parameter`,n,r):s(o.invalidName,`'${r}': ${i.reason}`,n,r),e(a)?p[r]=a:s(o.invalidDefinition,`the declaration for '${r}' must be a plain object`,n,r)}const m={};for(const[t,r]of Object.entries(p)){const a=["parameters",t],n=e=>[...a,e],i=r;for(const[e,r]of Object.entries(i))"default"!==e&&"metadata"!==e&&c(r,n(e),t);let l=!0;void 0===i.type||ae(i.type)||(s(o.invalidDefinition,"'type' must be a metadata-vocabulary type",n("type"),t),l=!1),l&&(m[t]=i.type??"any");let u=!1;if(void 0!==i.constraints){const e=se(i.constraints);e.ok?u=!0:s(o.invalidDefinition,`'constraints' is malformed: expected ${e.expected}, got ${e.actual}`,n("constraints"),t)}void 0!==i.required&&"boolean"!=typeof i.required&&s(o.invalidDefinition,"'required' must be a boolean",n("required"),t),void 0!==i.description&&"string"!=typeof i.description&&s(o.invalidDefinition,"'description' must be a string",n("description"),t),void 0===i.metadata||e(i.metadata)||s(o.invalidDefinition,"'metadata' must be a plain object",n("metadata"),t);const d="default"in i;if(d&&!0===i.required&&s(o.invalidDefinition,"a 'default' contradicts 'required: true' — a default implies the parameter is optional",n("default"),t),d&&i.default!==me){const e=m[t];if(void 0!==e){const r=ne(i.default,e);if(r.ok){if(u&&void 0!==i.constraints){const e=oe(i.default,i.constraints);e.ok||s(o.typeCheck,`'default' violates the declared constraints: expected ${e.expected}, got ${e.actual}`,n("default"),t)}}else s(o.typeCheck,`'default' does not satisfy the declared type: expected ${r.expected}, got ${r.actual}`,n("default"),t)}}if(void 0===i.evaluation||To.has(i.evaluation)||s(o.invalidDefinition,`'evaluation' must be one of ${[...To].join(", ")}`,n("evaluation"),t),void 0!==i.truthiness&&"boolean"!=typeof i.truthiness&&s(o.invalidDefinition,"'truthiness' must be a boolean",n("truthiness"),t),void 0!==i.over&&"string"!=typeof i.over&&s(o.invalidDefinition,"'over' must be a parameter name",n("over"),t),void 0===i.replacesNullAt||Array.isArray(i.replacesNullAt)&&!i.replacesNullAt.some(e=>"string"!=typeof e)||s(o.invalidDefinition,"'replacesNullAt' must be an array of sibling parameter names",n("replacesNullAt"),t),void 0!==i.nullPolicy){const e=i.nullPolicy;"function"==typeof e||cn.has(e)||s(o.invalidNullPolicy,"'nullPolicy' must be 'propagate', 'value' or a conditional function",n("nullPolicy"),t);const r=m[t];void 0===r||ee(r)||s(o.invalidNullPolicy,"'nullPolicy' is legal only where the declared type names 'null' — a type without 'null' is the reject declaration",n("nullPolicy"),t),!0===i.truthiness&&"propagate"===e&&s(o.invalidNullPolicy,"'truthiness' implies null policy 'value' (null is falsy) — declaring 'propagate' is a conflict",n("nullPolicy"),t)}if(void 0!==i.elementNullPolicy){cn.has(i.elementNullPolicy)||s(o.invalidNullPolicy,"'elementNullPolicy' must be 'propagate' or 'value' — the conditional form is not admitted here",n("elementNullPolicy"),t);const e=m[t];void 0===e||Lo(e)||s(o.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(ln),i=n?r.slice(3):r;n&&a!==t.length-1&&s(o.invalidDefinition,`the rest entry '${r}' must be the last positional entry`,["positionalParams",a]),i in p||s(o.invalidDefinition,`positional entry '${r}' names no declared parameter`,["positionalParams",a]),e.has(i)&&s(o.invalidDefinition,`duplicate positional entry '${r}'`,["positionalParams",a]),e.add(i)})}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||Mo(t)||s(o.invalidDefinition,`the 'over' target '${a}' must admit an array`,[...r,"over"],e)}else s(o.invalidDefinition,`'over' names no sibling parameter ('${a}')`,[...r,"over"],e)}else s(o.invalidDefinition,"'over' is legal only with evaluation: 'perElement'",[...r,"over"],e);else a&&s(o.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(o.invalidDefinition,"a 'replacesNullAt' holder must declare evaluation: 'lazy'",r,e);(t.required??!("default"in t))&&s(o.invalidDefinition,"a 'replacesNullAt' holder must be optional",r,e),"default"in t&&s(o.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(o.invalidDefinition,"'replacesNullAt' may not target the holder itself",[...r,a],e):t in p||s(o.invalidDefinition,`'replacesNullAt' target '${t}' names no sibling parameter`,[...r,a],e)})}for(const[e,t]of Object.entries(p))Eo.test(e)&&"lazy"!==t.evaluation&&s(o.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=dn(p,m,s);if("string"==typeof l.timeoutParam){void 0===p[l.timeoutParam]?s(o.invalidDefinition,`'timeoutParam' names no declared parameter ('${l.timeoutParam}')`,["timeoutParam"]):"integer"!==m[l.timeoutParam]&&s(o.invalidDefinition,"the 'timeoutParam' target must be 'integer'-typed",["timeoutParam"])}return a.length>0&&Fo(a,i),pn(l,f)}const Io=e=>new ra(`request failed (${e.status}): ${e.url}`,{errorData:{status:e.status,statusText:e.statusText,url:e.url,response:e.payload}}),Vo=(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 ra(`${e}: ${r}`,{errorData:n})},Qo=(e,t=500)=>e.length<=t?e:`${e.slice(0,t)}… (${e.length} characters)`;class Jo{supplied;constructor(e){if(void 0===e&&"function"!=typeof globalThis.fetch)throw new ra("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 Io({status:r.status,statusText:r.statusText,url:r.url||e.url,payload:Go(a)});return Bo(a,r.url||e.url,r.status)}}class Uo{axios;constructor(e){if(this.axios=e,"function"!=typeof e||"function"!=typeof e.isAxiosError)throw new ra("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 Io({status:t.response.status,statusText:t.response.statusText,url:t.config?.url??e.url,payload:t.response.data});throw t}}}const Bo=(e,t,r)=>{if(""===e.trim())return null;try{return JSON.parse(e)}catch{throw new ra(`response was not JSON (${r}): ${t}`,{errorData:{status:r,url:t,response:Qo(e)}})}},Go=e=>{if(""===e.trim())return null;try{return JSON.parse(e)}catch{return Qo(e)}},Wo=/^https?:\/\//i,Ko=(e,t,r)=>{const a=Wo.test(e)?e:Ho(r,e),n=_o(t),i=""===n?a:`${a}${a.includes("?")?"&":"?"}${n}`;try{new URL(i)}catch{throw new ra(`'${i}' is not a valid URL`,{code:o.typeCheck})}return i},Ho=(e,t)=>{if(void 0===e||""===e)throw new ra(`'${t}' is a relative URL and no http.baseEndpoint is configured`,{code:o.typeCheck});return""===t?e:`${e.replace(/\/$/,"")}/${t.replace(/^\//,"")}`},_o=e=>{if(void 0===e)return"";const t=new URLSearchParams;for(const[r,a]of Object.entries(e))null!=a&&t.append(r,Zo(a,`query['${r}']`,"query"));return t.toString()},Xo=(...e)=>{const t={};for(const r of e)if(void 0!==r)for(const[e,a]of Object.entries(r))null!=a?t[e]=Zo(a,`headers['${e}']`,"header"):delete t[e];return t},Yo=e=>({Accept:"application/json",...e?{"Content-Type":"application/json"}:{}}),Zo=(e,t,r)=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return F(e);throw new ra(`${t} is ${X(e)} — a ${r} value must be a string, number or boolean; render it explicitly (join) or supply a fully-formed URL`,{code:o.typeCheck})},ei=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}:{}}),ti=t=>Array.isArray(t)?t.length>0:e(t)?Object.keys(t).length>0:null!=t,ri=(e,t)=>{if(void 0===t)return e;const r=b(e,bn(t));return r.found?void 0===r.value?null:r.value:null},ai=(t,r)=>{if(!e(t))throw new ra("a row was not an object");const a=Object.values(t);if(1!==a.length)throw new ra(`shape: '${r}' needs a single-column result — this row has ${a.length} columns; name the one column you want in the SQL`,{code:o.typeCheck});return a[0]},ni={type:"integer",required:!1,description:"Per-request deadline in ms; expiry is an ordinary failure this node’s fallback catches"},oi={type:["string","array"],required:!1,description:"Dot/bracket path or segments array applied to the response; a miss is null"},ii=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:oi,timeout:ni},positionalParams:["url"],timeoutParam:"timeout",useCache:!0,cache:"manual",returns:"any",validate:({returnPath:e,method:t,body:r})=>[...wn(e,"returnPath"),...ci(t,r)],evaluate:async({url:t,method:r,query:a,body:n,headers:i,returnPath:s},l)=>{if("get"===r&&void 0!==n)throw new ra("a GET carries no body — did you mean method: 'post'?",{code:o.typeCheck});const c={method:r,url:Ko(t,a,l.options.http?.baseEndpoint),headers:Xo(Yo(void 0!==n),l.options.http?.headers,i),...void 0!==n?{body:n}:{}},u=await l.cache.memo(ei(c),()=>(pi(l,c),e.request({...c,signal:l.signal})));return ri(u,s)}}),si=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:oi,timeout:ni},positionalParams:["query","variables"],timeoutParam:"timeout",useCache:!0,cache:"manual",returns:"any",validate:({returnPath:e})=>wn(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 ra("no endpoint — supply url, or set the graphQL.endpoint option");const c={method:"post",url:Ko(l,void 0,s.options.http?.baseEndpoint),headers:Xo(Yo(!0),s.options.http?.headers,s.options.graphQL?.headers,o),body:{query:r,...ti(a)?{variables:a}:{}}},u=await s.cache.memo(ei(c),async()=>(pi(s,c),(t=>{if(!e(t))throw new ra("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 ra(`the GraphQL response carried ${r.length} error${1===r.length?"":"s"}`+("string"==typeof e?`: ${e}`:""),{errorData:{errors:r}})}if(!("data"in t))throw new ra("the GraphQL response carried neither data nor errors");return t.data??null})(await t.request({...c,signal:s.signal}))));return ri(u,i)}}),li=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:ni},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,...ti(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=>ai(e,"column"));case"firstValue":return 0===e.length?r.evaluate():ai(e[0],"firstValue")}})(await o.cache.memo(i,()=>(o.trace.note({type:"query",text:i.text}),e.query({...i,signal:o.signal}))),a,n)}}),ci=(e,t)=>void 0!==t&&"get"===e?[{severity:"error",parameter:"body",message:"a GET carries no body — add method: 'post', or drop the body"}]:[],ui=(e=new Jo)=>[un(ii(e)),un(si(e))],di=e=>[un(li(e))],pi=(e,t)=>{e.trace.note({type:"request",method:t.method,url:t.url,headers:Object.keys(t.headers)})};class mi{client;constructor(e){if(this.client=e,"function"!=typeof e?.query)throw new ra("PostgresConnection(client): pass a connected node-postgres Client or Pool")}query=async e=>{if(void 0!==e.values&&!Array.isArray(e.values))throw new ra("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 Vo("postgres",e)}}}class fi{db;constructor(e){if(this.db=e,"function"!=typeof e?.all)throw new ra("SQLiteConnection(db): pass an open sqlite Database")}query=async e=>{try{return await this.db.all(e.text,e.values)??[]}catch(e){throw Vo("sqlite",e)}}}const hi=e=>vi(e,0,new Set),vi=(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 yi(e);if(!Array.isArray(e)&&!a(e))return gi(e);if(r.has(e))return"[circular]";if(t>=n)return"[too deep]";r.add(e);const o=Array.isArray(e)?Array.from(e,e=>vi(e,t+1,r)):Object.fromEntries(Object.entries(e).map(([e,a])=>[e,vi(a,t+1,r)]));return r.delete(e),o},yi=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]"}},gi=e=>{const t=bi(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}]`},bi=e=>{try{const t=e.constructor?.name;return"string"==typeof t&&""!==t?t:"Object"}catch{return"Object"}},wi=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:hi(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:hi(e.value)};case"reference":return{...t,kind:e.kind,reference:C(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:hi(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:hi(e.raw)}}};return n(e.root)},ki=(e,t)=>{const r=(a=e,n=t,xo?.(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:H,expression:hi(o),options:xi(s),canonicalForm:wi(i),issues:sn(i,s,({issue:e,order:t})=>({order:t,...e,path:[...e.path]})),timeoutShielded:i.timeoutShielded,nodeCount:i.nodeCount,maxDepth:i.maxDepth,dependencies:Oi(i.dependencies),own:{nodeCount:i.own.nodeCount,maxDepth:i.own.maxDepth,dependencies:Oi(i.own.dependencies)}}},$i="[supplied]",xi=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[e,ji(e,t)])),ji=(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 $i;case"http":case"graphQL":return Pi(t,"headers",e=>"object"==typeof e&&null!==e?Object.fromEntries(Object.keys(e).map(e=>[e,"[redacted]"])):hi(e));case"cache":return Pi(t,"store",()=>$i);default:return hi(t)}},Pi=(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):hi(a)])):hi(e),Oi=e=>({dataPaths:[...e.dataPaths.keys()],dynamic:e.dynamic,operators:[...e.operators],fragments:[...e.fragments]});export{M as ARRAY,Uo as AxiosClient,o as ErrorCodes,me as EvaluationData,Jo as FetchClient,ko as FigTree,$ as FigTreeError,L as OBJECT,pe as OPERATOR_CATEGORIES,ra as OperatorFailure,mi as PostgresConnection,fi as SQLiteConnection,A as WILDCARD,T as compareValues,yo as coreOperators,K as deepEqual,Ro as defineOperator,ui as httpOperators,ki as inspect,j as isFigTreeError,aa as isOperatorFailure,E as isTruthy,y as parsePath,F as renderText,b as resolvePath,di as sqlOperators,H as version};
@@ -0,0 +1,55 @@
1
+ type BasicType = 'any' | 'string' | 'number' | 'boolean' | 'array' | 'object' | 'null' | 'integer';
2
+ type LiteralType = {
3
+ literal: readonly (string | number | boolean)[];
4
+ };
5
+ type ExpectedType = BasicType | LiteralType | readonly BasicType[];
6
+ interface Constraints {
7
+ length?: number;
8
+ homogeneous?: readonly BasicType[];
9
+ elementShape?: Record<string, TypeDeclaration>;
10
+ }
11
+ interface TypeDeclaration {
12
+ type?: ExpectedType;
13
+ required?: boolean;
14
+ constraints?: Constraints;
15
+ }
16
+
17
+ interface FragmentParameterDeclaration extends TypeDeclaration {
18
+ default?: unknown;
19
+ description?: string;
20
+ metadata?: Record<string, unknown>;
21
+ }
22
+ interface FragmentDefinition {
23
+ expression: unknown;
24
+ parameters?: Record<string, FragmentParameterDeclaration>;
25
+ description?: string;
26
+ metadata?: Record<string, unknown>;
27
+ }
28
+
29
+ interface MigrationIssue {
30
+ code: 'split-trailing-empty' | 'remainder-sign' | 'template-numbering' | 'named-token-source' | 'response-collapse' | 'computed-delimiter' | 'computed-branches' | 'graphql-relative-url' | 'output-type' | 'missing-data-fallback' | 'unprefixed-parameter' | 'instance-case-insensitive' | 'values-cut' | 'fallback-converted' | 'malformed-entry' | 'unreachable-branches' | 'overridden-value' | 'discarded-expression' | 'fragment-shorthand-payload' | 'shadowed-argument' | 'unknown-argument' | 'fragment-use-cache' | 'name-renamed' | 'unknown-parameter-type' | 'default-outside-type' | 'unused-output-type' | 'deciding-value' | 'drilled-substitution-token' | 'number-mapping' | 'template-escape' | 'computed-dollar-template' | 'custom-function-call' | 'computed-function-name' | 'computed-arguments' | 'body-override' | 'computed-fragment-name' | 'replaced-output-type' | 'computed-children' | 'unknown-operator' | 'unconvertible-input';
31
+ tag: 'non-convertible' | 'intentional-semantic-change' | 'lossy-default';
32
+ path: (string | number)[];
33
+ message: string;
34
+ }
35
+ interface MigrationResult {
36
+ expression: unknown;
37
+ issues: MigrationIssue[];
38
+ }
39
+ interface FragmentMigrationResult {
40
+ fragments: Record<string, FragmentDefinition>;
41
+ issues: MigrationIssue[];
42
+ }
43
+ interface V2Options {
44
+ fragments?: Record<string, unknown>;
45
+ functions?: readonly string[] | Record<string, unknown>;
46
+ evaluateFullObject?: boolean;
47
+ noShorthand?: boolean;
48
+ caseInsensitive?: boolean;
49
+ useCache?: boolean;
50
+ }
51
+
52
+ declare const migrateV2Expression: (expression: unknown, options?: V2Options) => MigrationResult;
53
+ declare const migrateV2Fragments: (options: V2Options) => FragmentMigrationResult;
54
+
55
+ export { migrateV2Expression, migrateV2Fragments };
@@ -0,0 +1 @@
1
+ const e=(e,t)=>t.length<=e.length&&t.every((t,s)=>e[s]===t),t={"split-trailing-empty":{tag:"intentional-semantic-change",message:()=>"v2 dropped one trailing empty piece, so `'a,b,'` split to `['a', 'b']` and `''` to `[]`. v3 keeps it, giving `['a', 'b', '']` and `['']`. Where empty pieces must go, `filter` the result."},"computed-delimiter":{tag:"intentional-semantic-change",message:()=>"The delimiter is computed. v2 turned `\\n`, `\\t` and `\\r` typed as text in a delimiter into the characters they name, and v3 splits on the text as written. If the delimiter can hold such text, make it the real character."},"output-type":{tag:"intentional-semantic-change",message:({differences:e})=>`v3's \`convert\` is strict where v2 guessed: ${e}. Check that this node's result can never be one of them.`},"remainder-sign":{tag:"intentional-semantic-change",message:()=>"v2's remainder took the sign of the dividend (−7 remainder 3 was −1), and v3's `modulo` takes the sign of `mod` (2). They differ only when exactly one operand is negative. For v2's answer there, take the `modulo` of the `abs` values and give it the dividend's sign."},"template-numbering":{tag:"intentional-semantic-change",message:()=>"The template is computed, so its tokens cannot be renumbered. v2 matched tokens to substitutions by rank (`'%1 %3'` used the first two), and v3 matches by number. Check that the template's tokens have no gaps."},"named-token-source":{tag:"intentional-semantic-change",message:()=>"The template or `substitutions` is computed, so the converter cannot tell which `{{…}}` tokens read `data` in v2, which any name missing from `substitutions` did. In v3 such a token is written `{{$data.name}}`. Rewrite those tokens."},"response-collapse":{tag:"intentional-semantic-change",message:()=>"v2 reduced each single-key object in the response to its value, so a list of `{ name }` objects came back as a list of names. v3 returns the response as sent. To keep v2's result, project the field in `returnPath`, as in `'countries[*].name'`. The same `[*]` is needed wherever `returnPath` crosses an array, since v2 projected a key across one silently. Where the array holds the one element wanted, as a lookup by name often does, `[0]` reads that element instead: `'[0].flag'` rather than `'[*].flag'`, which gives a list of one."},"computed-branches":{tag:"intentional-semantic-change",message:()=>"`branches` is computed. v2 evaluated the branch it picked when that was an expression, and answered with a `fallback` key when nothing matched. v3 returns the branch as it is, and reads `fallback` as an ordinary key. Check that the object holds plain values, and give the no-match answer with `default`."},"graphql-relative-url":{tag:"intentional-semantic-change",message:()=>"v2 joined a relative `url` to its GraphQL endpoint option, and v3 joins it to `http.baseEndpoint`. Check the host's `http.baseEndpoint`, or write the full URL."},"missing-data-fallback":{tag:"intentional-semantic-change",message:()=>"In v2 a missing path failed, and this `fallback` answered. In v3 the read gives `null` and the node carries on. For data, set the host option `strictDataPaths: true` to fail as v2 did, or give the read its own default (`get`'s `default`, or `firstOf`). For a response's `returnPath`, which `strictDataPaths` does not reach, use `firstOf`, or read the path with a `get` and its `default`."},"unprefixed-parameter":{tag:"intentional-semantic-change",message:({name:e})=>`v2 read the declared name \`${e}\` as written, without a \`$\`, so the declaration never filled the body's \`$${e}\`: its default and type did nothing, and a call that left \`$${e}\` out got that text. v3 applies the declaration. Check the calls that leave it out.`},"instance-case-insensitive":{tag:"lossy-default",message:({operator:e})=>`v2's \`caseInsensitive\` option applied to this node. v3 compares case-sensitively until the host adds \`operatorDefaults: { ${e}: { caseInsensitive: true } }\`, or this node sets \`caseInsensitive: true\`.`},"values-cut":{tag:"lossy-default",message:({removed:e})=>`v2 used the first two values and ignored the rest. Removed: ${e}.`},"fallback-converted":{tag:"lossy-default",message:({type:e})=>`This \`fallback\` becomes \`default\`, which v3's \`convert\` then converts to ${e}, where v2 returned it as it was. Unless the default is already of that type, it fails or changes. Give a default of that type.`},"malformed-entry":{tag:"lossy-default",message:({odd:e})=>e?"An alternating list gives each key a value, and v2 failed on this key, which has none. v3 builds the object without it. Removed.":"v2 skipped an entry with no `key` or no `value`. Removed."},"overridden-value":{tag:"lossy-default",message:({key:e,winner:t})=>`v2 never read \`${e}\`: \`${t}\` gave the same parameter and won. Removed.`},"discarded-expression":{tag:"lossy-default",message:()=>"v2 evaluated this and then discarded it, so a failure in it failed the node, and any request, query or function call in it ran. v3 never evaluates it. Removed."},"unreachable-branches":{tag:"lossy-default",message:()=>"`branches` has a `fallback`, which v2 answered with before it read the node's own keys, so this branch was never reached. Removed."},"fragment-shorthand-payload":{tag:"lossy-default",message:()=>"A fragment shorthand takes an object of arguments. v2 spread this one into `parameters`, where it named nothing, so the call had no arguments. Removed."},"shadowed-argument":{tag:"lossy-default",message:({fragment:e,key:t})=>`The body of \`${e}\` sets its own \`${t}\`, which beat this argument in v2, so the argument never applied. Removed.`},"unknown-argument":{tag:"lossy-default",message:({fragment:e,name:t})=>`\`${e}\` has no parameter \`${t}\`. v2 ignored the argument, and v3 rejects it. Removed.`},"fragment-use-cache":{tag:"lossy-default",message:()=>"A v3 fragment call takes no `useCache`, since caching is set on the operators inside the body. v2 applied this one to the body's node, unless the body set its own. Removed. Set `useCache` in the definition if the body needs it."},"unused-output-type":{tag:"lossy-default",message:({key:e,reason:t})=>`v2 never applied this \`${e}\`: ${t}. Removed.`},"name-renamed":{tag:"lossy-default",message:({name:e,reason:t,renamed:s})=>`\`${e}\` cannot be registered in v3 (${t}), so it is renamed \`${s}\`, and calls follow. Update anything outside expressions that uses the old name.`},"unknown-parameter-type":{tag:"lossy-default",message:({type:e})=>`\`${e}\` is not a v3 type, so the parameter takes \`'any'\`.`},"default-outside-type":{tag:"lossy-default",message:({value:e,type:t})=>`The default \`${e}\` is not of the declared type \`${t}\`. v2 never checked it, and v3 would refuse to register the fragment, so the parameter takes \`'any'\`.`},"deciding-value":{tag:"non-convertible",message:({reason:e,wrote:t,key:s})=>`${e}, so the converter cannot tell what v2 did. It wrote ${t}, v2's default. Where \`${s}\` can be otherwise, rewrite the node by hand.`},"drilled-substitution-token":{tag:"non-convertible",message:({token:e,name:t})=>`\`${e}\` drills into the substitution \`${t}\`, and v3's substitution tokens do not drill. Pass the drilled value as a substitution of its own.`},"number-mapping":{tag:"non-convertible",message:({token:e})=>`v3 has no \`numberMapping\`, so ${e} renders the bare number. Choose the text in the substitution instead, with \`match\` or \`if\`.`},"template-escape":{tag:"non-convertible",message:()=>"v3 has no escapes, and reads `%N` and `{{…}}` in a template as tokens. To show such text literally, pass it in as a substitution."},"computed-dollar-template":{tag:"non-convertible",message:({what:e})=>`The template's \`$N\` tokens must become \`%N\` for v3, and a computed ${e} cannot be rewritten. Rewrite the template with v3's tokens.`},"custom-function-call":{tag:"non-convertible",message:({name:e,rename:t})=>`A call on the v2 custom function \`${e}\`. Register a v3 operator of that name, as "Custom functions" in the migration guide suggests, and check this call against its parameters.`+(void 0===t?"":` ${t}, so register it under another name and rename the call.`)},"computed-function-name":{tag:"non-convertible",message:()=>"The function name is computed, and v3 operator names are literal. The call is quoted unconverted. Rewrite it by hand, for example as a `match` over the functions it can name."},"computed-children":{tag:"non-convertible",message:({operator:e})=>`\`children\` is computed, and \`${e}\` sends its children to different parameters, which cannot be split before evaluation. The node is quoted unconverted. Rewrite it with named parameters.`},"computed-arguments":{tag:"non-convertible",message:()=>"The arguments are computed. v2's had `$` names and v3's do not, so as written they fill nothing. Make the computing expression produce names without the `$`."},"body-override":{tag:"non-convertible",message:({key:e})=>`In v2, \`${e}\` set the body's own \`${e}\`, through the call's spread over it. A v3 call passes only arguments. Removed. Make it a parameter of the fragment, or change the body.`},"replaced-output-type":{tag:"non-convertible",message:({fragment:e})=>`In v2 this \`outputType\` replaced the output type that the body of \`${e}\` sets with \`type\`. In v3 the body converts its result first, and this \`convert\` converts that, which gives v2's answer only where the first conversion loses nothing. Check the result, or take the output type off the body.`},"computed-fragment-name":{tag:"non-convertible",message:()=>"The fragment name is computed, and v3 fragment names are literal. The call is quoted unconverted. Rewrite it by hand, for example as a `match` over the fragments it can name."},"unknown-operator":{tag:"non-convertible",message:({name:e})=>`\`${e}\` is not a v2 operator. If it is one of your v2 custom functions, list it in the conversion's \`functions\` option and convert again, so the call converts to a call on a custom operator of that name. The node is quoted unconverted.`},"unconvertible-input":{tag:"non-convertible",message:()=>"The input nests too deeply to convert, or holds itself, which no JSON config does. It is quoted unconverted. Split it into fragments, or rewrite it by hand."}},s=(e,s,...[a])=>{const{tag:r,message:n}=t[e];return{code:e,tag:r,path:s,message:n(a)}},a={GET:{evaluatesContents:["parameters","headers"]},POST:{evaluatesContents:["parameters","headers"]},GRAPHQL:{evaluatesContents:["variables"]},BUILD_OBJECT:{evaluatesContents:["properties"]},MATCH:{evaluatesContents:["branches"]},STRING_SUBSTITUTION:{evaluatesContents:["substitutions"]},CUSTOM_FUNCTIONS:{evaluatesContents:["input"]}},r=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),n=/^\$(?:data|d|vars|v|params|p|element|e|index|i)(?:$|[.[])/,o=/^\$(?:data|d|vars|v|params|p|element|e)(?:$|[.[])/,i=/^\$(?:data|d)(?:$|[.[])/,u="v2 conversion: ",l=(e,t)=>({...void 0!==t&&{"//":t},operator:"literal",value:e}),c=e=>r(e)&&"literal"===e.operator,h=e=>c(e)?e.value:e,p=["//","fallback","useCache","vars"],d=e=>{if(!r(e))return!1;if(Object.hasOwn(e,"operator")||Object.hasOwn(e,"fragment"))return!0;const t=Object.keys(e).filter(e=>!p.includes(e));return 1===t.length&&t[0].startsWith("$")},m=e=>"string"==typeof e?n.test(e):d(e)&&(!c(e)||(e=>c(e)&&[e["//"]].flat().some(e=>"string"==typeof e&&e.startsWith(u)))(e)),f=e=>!!m(e)||(Array.isArray(e)?e.some(f):r(e)&&!c(e)&&Object.values(e).some(f)),v=e=>"string"==typeof e?n.test(e):Array.isArray(e)?e.some(v):!!r(e)&&Object.entries(e).some(([e,t])=>"operator"===e||"fragment"===e||e.startsWith("$")||"vars"===e||"//"===e||v(t)),y=e=>v(e)?l(e):e,g=e=>{const t=O(e),s="string"==typeof t?`'${t}'`:JSON.stringify(t)??String(t);return s.length>60?`${s.slice(0,57)}...`:s},b=e=>""===e?"$data":e.startsWith("[")?`$data${e}`:`$data.${e}`,O=e=>c(e)?e.value:Array.isArray(e)?e.map(O):r(e)?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,O(t)])):e,T=/*#__PURE__*/new Set(["operator","fragment","parameters","fallback","useCache","vars","//"]),w=/*#__PURE__*/new Set([...T,"data","params","element","index","d","v","p","e","i","literal"]),k=/*#__PURE__*/new Set(["any","string","number","boolean","array","object","null","integer"]),j=(e,t)=>{switch(t){case"any":return!0;case"integer":return Number.isInteger(e);case"array":return Array.isArray(e);case"object":return r(e);case"null":return null===e;default:return typeof e===t}},S=/^\$(?:data|d)[.[]/,A=(e,t)=>{const s=e=>A(e,t);if("string"==typeof e)return S.test(e);if(Array.isArray(e))return e.some(s);if(!r(e)||c(e))return!1;if(Object.hasOwn(e,"fragment")){return(Object.hasOwn(e,"fallback")?s(e.fallback):t(String(e.fragment)))||s(e.parameters)||s(e.vars)}if(d(e)&&Object.hasOwn(e,"fallback"))return s(e.fallback)||s(e.vars);const{operator:a}=e;return"get"===a&&!Object.hasOwn(e,"default")||(!("http"!==a&&"graphQL"!==a||!Object.hasOwn(e,"returnPath"))||Object.entries(e).some(([e,t])=>"//"!==e&&s(t)))},E=(e,t,s)=>(a,r)=>{const n={};e.forEach((e,t)=>{n[e]=void 0===a[t]&&"url"===e?"":r(t)});const o=a[e.length],i=e.length+1,u=Array.isArray(o)?o:[o];return n[t]=Object.fromEntries(u.map((e,t)=>[e,r(i+t)])),a.length-i>u.length&&(n[s]=r(a.length-1)),n},$={AND:{into:"values"},OR:{into:"values"},EQUAL:{into:"values"},NOT_EQUAL:{into:"values"},PLUS:{into:"values"},SUBTRACT:{into:"values"},MULTIPLY:{into:"values"},DIVIDE:{into:"values"},GREATER_THAN:{into:"values"},LESS_THAN:{into:"values"},COUNT:{into:"values"},CONDITIONAL:{positions:["condition","valueIfTrue","valueIfFalse"]},REGEX:{positions:["testString","pattern"]},SPLIT:{positions:["value","delimiter"],defaults:{delimiter:" "}},OBJECT_PROPERTIES:{positions:["property"],ifGiven:"fallback"},STRING_SUBSTITUTION:{positions:["string"],rest:"substitutions"},SQL:{positions:["query"],rest:"values"},CUSTOM_FUNCTIONS:{positions:["functionName"],rest:"args"},MATCH:(e,t)=>{const s={};for(let a=1;a+1<e.length;a+=2){const r=e[a];"string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r||(s[String(r)]=t(a+1))}return{matchExpression:t(0),branches:s}},BUILD_OBJECT:(e,t)=>{if(e.every(r))return{properties:e.map((e,s)=>t(s))};const s=[];for(let a=0;a<e.length;a+=2)s.push(a+1<e.length?{key:t(a),value:t(a+1)}:{key:t(a)});return{properties:s}},GET:E(["url"],"parameters","returnProperty"),POST:E(["url"],"parameters","returnProperty"),GRAPHQL:E(["query","url"],"variables","returnNode"),PASSTHRU:(e,t)=>({value:1===e.length?t(0):e.map((e,s)=>t(s))})},C={and:"AND","&":"AND","&&":"AND",or:"OR","|":"OR","||":"OR","=":"EQUAL",eq:"EQUAL",equal:"EQUAL",equals:"EQUAL","!=":"NOT_EQUAL",notEqual:"NOT_EQUAL","!":"NOT_EQUAL",ne:"NOT_EQUAL","+":"PLUS",plus:"PLUS",add:"PLUS",concat:"PLUS",join:"PLUS",merge:"PLUS","-":"SUBTRACT",subtract:"SUBTRACT",minus:"SUBTRACT",takeaway:"SUBTRACT","*":"MULTIPLY",x:"MULTIPLY",multiply:"MULTIPLY",times:"MULTIPLY","/":"DIVIDE",divide:"DIVIDE","÷":"DIVIDE",">":"GREATER_THAN",greaterThan:"GREATER_THAN",higher:"GREATER_THAN",larger:"GREATER_THAN","<":"LESS_THAN",lessThan:"LESS_THAN",lower:"LESS_THAN",smaller:"LESS_THAN","?":"CONDITIONAL",conditional:"CONDITIONAL",ifThen:"CONDITIONAL",regex:"REGEX",patternMatch:"REGEX",regexp:"REGEX",matchPattern:"REGEX",getData:"OBJECT_PROPERTIES",dataProperties:"OBJECT_PROPERTIES",data:"OBJECT_PROPERTIES",objectProperties:"OBJECT_PROPERTIES",objProps:"OBJECT_PROPERTIES",getProperty:"OBJECT_PROPERTIES",getObjProp:"OBJECT_PROPERTIES",stringSubstitution:"STRING_SUBSTITUTION",substitute:"STRING_SUBSTITUTION",stringSub:"STRING_SUBSTITUTION",replace:"STRING_SUBSTITUTION",split:"SPLIT",arraySplit:"SPLIT",count:"COUNT",length:"COUNT",GET:"GET",get:"GET",api:"GET",POST:"POST",post:"POST",sql:"SQL",pgSql:"SQL",postgres:"SQL",pg:"SQL",sqLite:"SQL",sqlite:"SQL",mySql:"SQL",graphQL:"GRAPHQL",graphQl:"GRAPHQL",graphql:"GRAPHQL",gql:"GRAPHQL",buildObject:"BUILD_OBJECT",build:"BUILD_OBJECT",object:"BUILD_OBJECT",match:"MATCH",switch:"MATCH",customFunctions:"CUSTOM_FUNCTIONS",customFunction:"CUSTOM_FUNCTIONS",objectFunctions:"CUSTOM_FUNCTIONS",function:"CUSTOM_FUNCTIONS",functions:"CUSTOM_FUNCTIONS",runFunction:"CUSTOM_FUNCTIONS",pass:"PASSTHRU",_:"PASSTHRU",passThru:"PASSTHRU",passthru:"PASSTHRU",ignore:"PASSTHRU",coerce:"PASSTHRU",convert:"PASSTHRU"},I={AND:[{name:"values",aliases:[]}],OR:[{name:"values",aliases:[]}],EQUAL:[{name:"values",aliases:[]},{name:"caseInsensitive",aliases:[]},{name:"nullEqualsUndefined",aliases:[]}],NOT_EQUAL:[{name:"values",aliases:[]},{name:"caseInsensitive",aliases:[]},{name:"nullEqualsUndefined",aliases:[]}],PLUS:[{name:"values",aliases:[]},{name:"type",aliases:[]}],SUBTRACT:[{name:"values",aliases:[]},{name:"from",aliases:["subtractFrom"]},{name:"subtract",aliases:[]}],MULTIPLY:[{name:"values",aliases:[]}],DIVIDE:[{name:"values",aliases:[]},{name:"dividend",aliases:["divide"]},{name:"divisor",aliases:["by","divideBy"]},{name:"output",aliases:[]}],GREATER_THAN:[{name:"values",aliases:[]},{name:"strict",aliases:[]}],LESS_THAN:[{name:"values",aliases:[]},{name:"strict",aliases:[]}],CONDITIONAL:[{name:"condition",aliases:[]},{name:"valueIfTrue",aliases:["ifTrue"]},{name:"valueIfFalse",aliases:["ifFalse","ifNot"]}],REGEX:[{name:"testString",aliases:["string","value"]},{name:"pattern",aliases:["regex","regexp","regExp","re"]}],OBJECT_PROPERTIES:[{name:"property",aliases:["path","propertyName"]},{name:"additionalData",aliases:["additional","objects","data","additionalObjects"]}],STRING_SUBSTITUTION:[{name:"string",aliases:[]},{name:"substitutions",aliases:["replacements","values"]},{name:"trimWhiteSpace",aliases:["trim","trimWhitespace"]},{name:"substitutionCharacter",aliases:["subCharacter","subChar"]},{name:"numberMapping",aliases:["numMap","numberMap","pluralisation","pluralization","plurals"]}],SPLIT:[{name:"value",aliases:["string"]},{name:"delimiter",aliases:["separator"]},{name:"trimWhiteSpace",aliases:["trim","trimWhitespace"]},{name:"excludeTrailing",aliases:["removeTrailing","excludeTrailingDelimiter"]}],COUNT:[{name:"values",aliases:[]}],GET:[{name:"url",aliases:["endpoint"]},{name:"returnProperty",aliases:["outputProperty"]},{name:"headers",aliases:[]},{name:"parameters",aliases:["queryParams","queryParameters","urlQueries"]},{name:"useCache",aliases:[]}],POST:[{name:"url",aliases:["endpoint"]},{name:"returnProperty",aliases:["outputProperty"]},{name:"headers",aliases:[]},{name:"parameters",aliases:["bodyJson","data"]},{name:"useCache",aliases:[]}],SQL:[{name:"query",aliases:["text"]},{name:"values",aliases:["replacements"]},{name:"single",aliases:["singleRecord"]},{name:"flatten",aliases:["flat","array"]},{name:"useCache",aliases:[]}],GRAPHQL:[{name:"query",aliases:[]},{name:"url",aliases:["endpoint"]},{name:"headers",aliases:[]},{name:"variables",aliases:[]},{name:"returnNode",aliases:["outputNode","returnProperty"]},{name:"useCache",aliases:[]}],BUILD_OBJECT:[{name:"properties",aliases:["values","keyValPairs","keyValuePairs"]}],MATCH:[{name:"matchExpression",aliases:["matchValue"]},{name:"branches",aliases:["arms","cases"]}],CUSTOM_FUNCTIONS:[{name:"functionName",aliases:["functionPath","funcName","function","path","name"]},{name:"args",aliases:["arguments","variables"]},{name:"input",aliases:["arg"]},{name:"useCache",aliases:[]}],PASSTHRU:[{name:"value",aliases:["_","data"]}]},N=e=>/^\$.+/.test(e),U=e=>Object.hasOwn(e,"operator")||Object.hasOwn(e,"fragment"),R=e=>{const t=(e=>(e=>e.replace(/[^A-Za-z\d _-]/g,"").split(/[-_ ]/).flatMap(e=>e.match(/[a-z]+|[A-Z]+[a-z]*/g)??e).filter(e=>""!==e).map((e,t)=>0===t?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(""))(e)||e)(e);return Object.hasOwn(C,t)?C[t]:void 0},P=["fallback","useCache","outputType"],L=["array","string","number"],x=["fallback","outputType","type","useCache","args","input"],_=Object.fromEntries(Object.entries(I).map(([e,t])=>[e,t.map(({name:e})=>e)])),q=Object.fromEntries(Object.entries(I).map(([e,t])=>[e,Object.fromEntries(t.flatMap(({name:e,aliases:t})=>t.map(t=>[t,e])))])),M=e=>"object"==typeof e?null!==e:"string"==typeof e&&N(e),B=(e,t)=>e.entries?.[t]??{path:[...e.path,t]},H=(t,s)=>(e(t,s)&&t.length>s.length?t.slice(s.length):t).map((e,t)=>"number"==typeof e?`[${e}]`:0===t?e:`.${e}`).join(""),G=e=>{const t=e.get("operator"),s=t?.source.path.at(-1);if("string"==typeof s&&N(s))return s.slice(1);const a=t?.value;return"string"==typeof a?a:JSON.stringify(a)??String(a)};class Q{index;constructor(e){this.index=e}}class D{source;issues;entries=new Map;constructor(e,t){this.source=e,this.issues=t}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}set(e,t,s=t.source.path){const a=this.entries.get(e);a&&this.overridden(a.source.path,s),this.entries.set(e,t)}drop(e,t){const s=this.entries.get(e);s&&this.overridden(s.source.path,t),this.entries.delete(e)}overridden(t,a){if(this.issues.some(({code:s,path:a})=>"overridden-value"===s&&e(t,a)))return;const r=this.source.path,n={key:H(t,r),winner:H(a,r)};this.issues.push(s("overridden-value",t,n))}}class F{sources=new Map;issues=[];fragments;functions;shorthand;fullObject;constructor(e){const{functions:t={}}=e;this.fragments=e.fragments??{},this.functions=new Set(Array.isArray(t)?t:Object.keys(t)),this.shorthand=!e.noShorthand,this.fullObject=!0===e.evaluateFullObject}value(e,t){if(Array.isArray(e)){const s=e.map((e,s)=>this.value(e,B(t,s)));return this.record(s,t)}if(!r(e))return e;const s=this.issues.length;if(Object.hasOwn(e,"fragment"))return this.fragmentCall(this.draft(e,t),e,s);if(Object.hasOwn(e,"operator"))return this.operatorNode(this.draft(e,t),e,s);const a=this.expandShorthand(e,t,this.issues);return void 0===a?this.plain(e,t):a.has("fragment")?this.fragmentCall(a,e,s):this.operatorNode(a,e,s)}draft(e,t){const s=new D(t,this.issues);for(const[a,r]of Object.entries(e))s.set(a,{value:r,source:B(t,a)});return s}plain(e,t){return this.fullObject?this.walk(e,t):t.entries?this.record(e,t):e}evaluates(e){if(Array.isArray(e))return e.some(e=>this.evaluates(e));if(!r(e))return!1;if(U(e))return!0;return!!Object.keys(e).some(e=>this.shorthand&&N(e)&&(void 0!==R(e.slice(1))||Object.hasOwn(this.fragments,e.slice(1))||this.functions.has(e.slice(1))))||this.fullObject&&Object.values(e).some(e=>this.evaluates(e))}walk(e,t,s=()=>!1){const a=Object.fromEntries(Object.entries(e).map(([e,a])=>[e,s(e)?a:this.value(a,B(t,e))]));return this.record(a,t)}record(e,t){const s=Object.fromEntries(Object.keys(e).map(s=>{const a=Array.isArray(e)?Number(s):s;return[s,B(t,a).path]}));return this.sources.set(e,{path:t.path,keys:s}),e}expandShorthand(e,t,s){if(!this.shorthand)return;const a=new D(t,s);let r=!1;for(const[s,n]of Object.entries(e))N(s)&&(r=this.expand(a,s,n,B(t,s))||r);for(const[s,r]of Object.entries(e))N(s)||a.set(s,{value:r,source:B(t,s)});return r?a:void 0}expand(e,t,a,n){const o=t.slice(1),i=e=>({value:[e],source:{path:n.path,entries:{0:n}}}),u=t=>{for(const[s,a]of Object.entries(t))e.set(s,{value:a,source:B(n,s)})},l=R(o);return void 0!==l?(Array.isArray(a)?(e.set("operator",{value:l,source:n}),e.set("children",{value:a,source:n})):r(a)&&!Object.keys(a).some(N)?(Object.hasOwn(a,"fragment")?e.overridden(n.path,[...n.path,"fragment"]):e.set("operator",{value:l,source:n}),u(a)):(e.set("operator",{value:l,source:n}),e.set("children",i(a))),!0):Object.hasOwn(this.fragments,o)?(e.set("fragment",{value:o,source:n}),r(a)||e.issues.push(s("fragment-shorthand-payload",n.path)),e.set("parameters",{value:r(a)?a:{},source:n}),!0):this.functions.has(o)?(e.set("operator",{value:o,source:n}),Array.isArray(a)?e.set("args",{value:a,source:n}):r(a)?Object.hasOwn(a,"input")||Object.hasOwn(a,"args")?u(a):e.set("input",{value:a,source:n}):e.set("args",i(a)),!0):(e.set(t,{value:a,source:n}),!1)}operatorNode(e,t,s){const{source:a}=e,r=e.get("operator")?.value;let n,o;if("string"==typeof r&&this.functions.has(r)?(({draft:e,ignored:n}=this.explicitCall(e)),o="CUSTOM_FUNCTIONS"):"string"==typeof r&&(o=R(r)),void 0===o)return this.asWritten(t,a,s,{code:"unknown-operator",at:e.get("operator")?.source.path??a.path,name:G(e)});const i=this.parameterNames(e,o),u=i.get("children");if(void 0!==u){i.entries.delete("children");const r=$[o];if(Array.isArray(u.value))this.mapChildren(i,o,u);else{if("function"==typeof r||!("into"in r))return this.asWritten(t,a,s,{code:"computed-children",at:u.source.path,name:G(e)});i.set(r.into,u)}}const l="CUSTOM_FUNCTIONS"===o?i.get("functionName"):void 0;return void 0!==l&&M(l.value)?this.asWritten(t,a,s,{code:"computed-function-name",at:l.source.path}):("MATCH"===o&&this.gatherBranches(i),this.writeNode(i,o,n))}asWritten(e,t,s,a){this.issues.length=s;const r=this.record({...e},t);return this.sources.get(r).quoted=a,r}explicitCall(e){const t=e.get("operator"),s=new D(e.source,e.issues);s.set("operator",{value:"CUSTOM_FUNCTIONS",source:t.source}),s.set("functionName",t);const a=[];for(const[t,r]of e.entries)"operator"!==t&&(x.includes(t)?s.set(t,r):a.push([t,r]));return 0===a.length?{draft:s}:s.has("input")?{draft:s,ignored:Object.fromEntries(a.map(([e,{value:t}])=>[e,t]))}:(s.set("input",{value:Object.fromEntries(a.map(([e,{value:t}])=>[e,t])),source:{path:e.source.path,entries:Object.fromEntries(a.map(([e,t])=>[e,t.source]))}}),{draft:s})}parameterNames(e,t){const s=q[t],a=new D(e.source,e.issues);for(const[t,r]of e.entries)a.set(Object.hasOwn(s,t)?s[t]:t,r);null==a.get("outputType")?.value&&a.entries.delete("outputType");const r=a.get("type"),n=a.get("outputType");return void 0===r||"PLUS"===t||"SQL"===t&&M(r.value)||(a.entries.delete("type"),"SQL"===t&&L.includes(r.value)?(a.set("flatten",{value:!0,source:r.source}),void 0===n&&a.set("outputType",r)):void 0!==n?a.overridden(r.source.path,n.source.path):a.set("outputType",r)),a}mapChildren(e,t,s){const a=s.value,n=t=>{if(t instanceof Q)return t.index<a.length?{value:a[t.index],source:B(s.source,t.index)}:{value:void 0,source:s.source};if(Array.isArray(t)||r(t)){const e=Object.entries(t).map(([e,t])=>[e,n(t)]),a=e.map(([e,{value:t}])=>[e,t]);return{value:Array.isArray(t)?a.map(([,e])=>e):Object.fromEntries(a),source:{path:s.source.path,entries:Object.fromEntries(e.map(([e,{source:t}])=>[e,t]))}}}return{value:t,source:e.source}},o=((e,t,s=e=>t[e])=>{const a=$[e];if("function"==typeof a)return a(t,s);if("into"in a)return{[a.into]:t.map((e,t)=>s(t))};const{positions:r,rest:n,defaults:o={},ifGiven:i}=a,u={};return r.forEach((e,a)=>{u[e]=void 0===t[a]&&Object.hasOwn(o,e)?o[e]:s(a)}),void 0!==n&&(u[n]=t.slice(r.length).map((e,t)=>s(r.length+t))),void 0!==i&&void 0!==t[r.length]&&(u[i]=s(r.length)),u})(t,a,e=>new Q(e));for(const[t,a]of Object.entries(o)){const r=n(a);void 0===r.value?e.drop(t,s.source.path):e.set(t,r,s.source.path)}}gatherBranches(e){const t=["operator",..._.MATCH,...P],a=[...e.entries].filter(([e])=>!t.includes(e)&&!N(e));if(0===a.length)return;const n=e.get("branches"),o=n?.value;if(Array.isArray(o)||r(o)&&!Object.hasOwn(o,"operator")){const t=n.source,r=Array.isArray(o)?o.filter((e,t)=>t%2==0).map(e=>String(e)):Object.keys(o),i=r.includes("fallback"),u=[];for(const[n,o]of a)e.entries.delete(n),i?e.issues.push(s("unreachable-branches",o.source.path)):r.includes(n)?e.overridden(o.source.path,[...t.path,n]):u.push([n,o]);if(0===u.length)return;if(Array.isArray(o)){const s={};o.forEach((e,a)=>s[a]=B(t,a)),u.forEach(([,e],t)=>{s[o.length+2*t]=e.source,s[o.length+2*t+1]=e.source});const a=u.flatMap(([e,{value:t}])=>[e,t]);e.entries.set("branches",{value:[...o,...a],source:{path:t.path,entries:s}})}else{const s=Object.fromEntries(Object.keys(o).map(e=>[e,B(t,e)]));for(const[e,t]of u)s[e]=t.source;e.entries.set("branches",{value:{...o,...Object.fromEntries(u.map(([e,t])=>[e,t.value]))},source:{path:t.path,entries:s}})}return}if(null==o){for(const[t]of a)e.entries.delete(t);e.entries.set("branches",{value:Object.fromEntries(a.map(([e,{value:t}])=>[e,t])),source:{path:e.source.path,entries:Object.fromEntries(a.map(([e,{source:t}])=>[e,t]))}})}}writeNode(e,t,s){const r=_[t],n=["operator",...r,...P],o=[...n.filter(t=>e.has(t)),...[...e.entries.keys()].filter(e=>!n.includes(e))],i=a[t]?.evaluatesContents??[],u={},l={};for(const s of o){const{value:a,source:n}=e.get(s);l[s]=n.path,"operator"===s?u[s]=t:"MATCH"===t&&"branches"===s?u[s]=this.matchBranches(a,n):r.includes(s)&&i.includes(s)?u[s]=this.contents(t,this.value(a,n),n):r.includes(s)||P.includes(s)||N(s)||"type"===s||"MATCH"===t?u[s]=this.value(a,n):u[s]=a}return this.sources.set(u,{path:e.source.path,keys:l,...s&&{ignored:s}}),u}contents(e,t,s){if(this.fullObject)return t;if("BUILD_OBJECT"===e){if(!Array.isArray(t)||!t.every(r))return t;const e=t.map((e,t)=>{if(U(e))return e;const a=B(s,t),r={...e};for(const t of["key","value"])Object.hasOwn(e,t)&&(r[t]=this.value(e[t],B(a,t)));return this.record(r,a)});return this.record(e,s)}return!r(t)||U(t)?t:"STRING_SUBSTITUTION"===e?this.walk(t,s,N):this.walk(t,s)}matchBranches(e,t){return Array.isArray(e)?this.value(e,t):r(e)?Object.hasOwn(e,"operator")?this.value(e,t):this.walk(e,t):e}fragmentCall(e,t,a){const{source:n}=e,o=e.get("fragment"),i="string"==typeof o.value&&Object.hasOwn(this.fragments,o.value);if(M(o.value)&&!i)return this.asWritten(t,n,a,{code:"computed-fragment-name",at:o.source.path});const u=e.get("parameters"),l=void 0===u||r(u.value)&&!U(u.value),c={fragment:o.value},h={fragment:o.source.path};if(l){const t=u?.source??n,a=new D(n,e.issues),r=this.bodyAliases(o.value),i=(t,a)=>e.issues.push(s("shadowed-argument",a,{fragment:String(o.value),key:t}));for(const[n,o]of Object.entries(u?.value??{})){const u={value:o,source:B(t,n)};this.fullObject&&r.has(n)?(i(n,u.source.path),this.evaluates(o)&&e.issues.push(s("discarded-expression",u.source.path))):a.set(n,u)}for(const[t,s]of e.entries){if(!N(t))continue;const e=a.get(t);void 0!==e?a.overridden(s.source.path,e.source.path):r.has(t)?i(t,s.source.path):a.set(t,s)}const l={},p={};for(const[e,{value:t,source:s}]of a.entries)l[e]=this.value(t,s),p[e]=s;c.parameters=this.record(l,{path:t.path,entries:p}),h.parameters=t.path}else c.parameters=this.value(u.value,u.source),h.parameters=u.source.path;for(const[t,{value:s,source:a}]of e.entries){if("fragment"===t||"parameters"===t||l&&N(t))continue;const e=P.includes(t)||N(t);c[t]=e?this.value(s,a):s,h[t]=a.path}return this.sources.set(c,{path:n.path,keys:h}),c}bodyAliases(e){if("string"!=typeof e||!Object.hasOwn(this.fragments,e))return new Set;const t=this.fragments[e];if(!r(t))return new Set;const s=U(t)?Object.keys(t):[...this.expandShorthand(t,{path:[]},[])?.entries.keys()??[]];return new Set(s.includes("operator")?s.filter(N):[])}}const W=(e,t={},s=[])=>{const a=new F(t);return{expression:a.value(e,{path:s}),sources:a.sources,issues:a.issues}},J={and:"and",or:"or",not:"not","!":"not",if:"if","?":"if",match:"match",firstOf:"firstOf",equal:"equal","=":"equal",notEqual:"notEqual","!=":"notEqual",greaterThan:"greaterThan",">":"greaterThan",greaterThanOrEqual:"greaterThanOrEqual",">=":"greaterThanOrEqual",lessThan:"lessThan","<":"lessThan",lessThanOrEqual:"lessThanOrEqual","<=":"lessThanOrEqual",plus:"plus","+":"plus",subtract:"subtract","-":"subtract",multiply:"multiply","*":"multiply",divide:"divide","/":"divide",modulo:"modulo",power:"power","^":"power",round:"round",floor:"floor",ceil:"ceil",abs:"abs",min:"min",max:"max",buildString:"buildString",split:"split",join:"join",lower:"lower",upper:"upper",trim:"trim",regex:"regex",length:"length",map:"map",filter:"filter",find:"find",some:"some",every:"every",get:"get",buildObject:"buildObject",convert:"convert",http:"http",graphQL:"graphQL",sql:"sql"},V=["name","type","required","default","description"],X=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Y=e=>e.replace(/^\$+/,"").replace(/[.[\]]/g,"_")||"_",z=(e,t)=>{let s=e;for(let a=2;t.has(s);a++)s=`${e}_${a}`;return t.add(s),s},Z=e=>{if(""===e)return"a v3 name cannot be empty";if(e.startsWith("$"))return"a v3 name cannot start with `$`";const t=/[.[\]]/.exec(e)?.[0];return void 0===t?void 0:`a v3 name cannot hold a \`${t}\``},K=e=>e.slice(1).map((e,t)=>"number"==typeof e?`[${e}]`:0===t?e:`.${e}`).join(""),ee=(e,t,a,n)=>{if(!r(t)||"string"!=typeof t.name)return;const o=t.name.startsWith("$"),i=o?t.name:`$${t.name}`;if(!N(i)||e.parameters.has(i))return;const u=[e.key,"metadata","parameters",a],l=o?void 0:((e,t)=>{if(void 0===e.operator||void 0===e.body)return;const s=I[e.operator].find(e=>e.name===t||e.aliases.includes(t));return void 0!==s?s.name:["fallback","useCache","outputType"].includes(t)?t:"type"===t?"outputType":void 0})(e,t.name);o||void 0!==l||e.issues.push(s("unprefixed-parameter",[...u,"name"],{name:t.name}));const{type:c,required:h,default:p,description:d}=t,m=Object.fromEntries(Object.entries(t).filter(([e])=>!V.includes(e))),f={key:i,name:i.slice(1),at:u,declared:!0,required:!0===h,exact:!1};if(void 0!==c){const t=(e=>{if("string"==typeof e)return k.has(e)?{type:e}:{type:"any",unknown:e};if(Array.isArray(e)){const t=e.filter(e=>"undefined"!==e);if(0===t.length)return{type:"any",unknown:"undefined"};const s=t.find(e=>"string"!=typeof e||!k.has(e));return void 0!==s?{type:"any",unknown:s}:{type:1===t.length?t[0]:t}}if(r(e)&&Array.isArray(e.literal)&&e.literal.length>0){const t=e=>["string","number","boolean"].includes(typeof e);if(e.literal.every(t))return{type:{literal:e.literal}}}return{type:"any",unknown:e}})(c);if(f.type=t.type,Object.hasOwn(t,"unknown")){const a="string"==typeof t.unknown?t.unknown:g(t.unknown);e.issues.push(s("unknown-parameter-type",[...u,"type"],{type:a}))}}if(void 0!==d&&(f.description=d),Object.keys(m).length>0&&(f.metadata=m),void 0!==p){const t=[...u,"default"],s=W(p,n,t);s.sources.forEach((t,s)=>e.sources.set(s,t)),e.issues.push(...s.issues),f.default={value:s.expression,path:t}}void 0!==l&&te(e,f,l),e.parameters.set(i,f)},te=(t,s,a)=>{const r=t.body,n=t.sources.get(r),o=n?.keys[a]??[t.key,a];Object.hasOwn(r,a)&&(void 0===s.default?s.default={value:r[a],path:o}:t.issues=t.issues.filter(t=>!e(t.path,o))),r[a]=s.key,void 0!==n&&(n.keys[a]=o)},se=(t,a,r,n)=>{for(const o of Object.keys(a).filter(N)){const i={value:a[o],path:r?.keys[o]??[t.key,o]},u=t.parameters.get(o);if(void 0===u)t.parameters.set(o,{key:o,name:o.slice(1),at:i.path,declared:!1,required:!1,type:"any",default:i,exact:!1});else if(void 0===u.default)u.default=i;else{const[a,r]=n.evaluateFullObject?[i,u.default]:[u.default,i],o={key:K(r.path),winner:K(a.path)};t.issues=t.issues.filter(({path:t})=>!e(t,r.path)),t.issues.push(s("overridden-value",r.path,o)),u.default=a}}},ae=e=>{const t=e=>Z(e)??(T.has(e)?"it is a reserved node key":void 0),a=[...e.parameters.values()],r=new Set(T);for(const e of a)void 0===t(e.name)&&r.add(e.name);for(const n of a.filter(({name:e})=>void 0!==t(e)).sort(X)){const a=t(n.name),o={name:n.name,reason:a,renamed:z(Y(n.name),r)};n.name=o.renamed,e.issues.push(s("name-renamed",n.at,o))}},re=([e,...t],s,a)=>e===s&&t.at(-1)===a&&(1===t.length||2===t.length&&"string"==typeof t[0]&&N(t[0])),ne=(e,t)=>{const a=r(e.fragments)?e.fragments:{},n=Object.entries(a).map(([t,s])=>((e,t,s)=>{const a={key:e,name:e,sources:new Map,convertsByType:!1,parameters:new Map,issues:[]};if(!r(t))return{...a,data:t};const{metadata:n,...o}=t,i=r(n)?n:void 0,u=W(i?o:t,s,[e]),l=u.expression;if(!r(l)||!Object.hasOwn(l,"operator")||Object.hasOwn(l,"fragment"))return{...a,data:t};a.body=l,u.sources.forEach((e,t)=>a.sources.set(t,e)),a.issues.push(...u.issues);const c=u.sources.get(l);if(void 0===c?.quoted&&(a.operator=l.operator),void 0!==i){const{description:e,parameters:t,...r}=i;"string"==typeof e?a.description=e:void 0!==e&&(r.description=e),Array.isArray(t)?t.forEach((e,t)=>ee(a,e,t,s)):void 0!==t&&(r.parameters=t),Object.keys(r).length>0&&(a.metadata=r)}void 0===c?.quoted&&se(a,l,c,s);const h=c?.keys.outputType?.at(-1);return Object.hasOwn(l,"outputType")?a.ownOutput="type"===h?"type":"outputType":Object.hasOwn(l,"type")&&(a.ownOutput="type"),a.convertsByType="type"===a.ownOutput&&("PLUS"===a.operator?["number","boolean","bool"].includes(l.type):Object.hasOwn(l,"outputType")),a})(t,s,e));((e,t)=>{const{functions:a={}}=t,r=new Set(Array.isArray(a)?a:Object.keys(a)),n=e=>Z(e)??(w.has(e)?"it is a reserved name":Object.hasOwn(J,e)?"it is already a v3 operator's name":r.has(e)?"it is a custom function's name, which becomes a v3 operator":void 0),o=new Set([...w,...Object.keys(J),...r]);for(const t of e)void 0===n(t.key)&&o.add(t.key);for(const t of e.filter(({key:e})=>void 0!==n(e)).sort(X)){t.name=z(Y(t.key),o);const e={name:t.key,reason:n(t.key),renamed:t.name};t.issues.unshift(s("name-renamed",[t.key],e))}})(n,e);const o={fragments:new Map(n.map(e=>[e.key,e])),bodyReads:()=>!1},i=new Map,u=new Map;for(let e=!0;e;){e=!1;for(const s of n){if(void 0===s.body)continue;const a=new Map,r=(e,t,s)=>a.set(e,[...a.get(e)??[],{path:t,throughCall:s}]);i.set(s.key,t(s,o,r)),u.set(s.key,a);for(const[t,[{path:r}]]of a)s.parameters.has(t)||(e=!0,s.parameters.set(t,{key:t,name:t.slice(1),at:r,declared:!1,required:!1,type:"any",exact:!1}))}}for(const e of n){for(const t of e.parameters.values()){const s=u.get(e.key)?.get(t.key)??[];t.exact=1===s.length&&!s[0].throughCall&&re(s[0].path,e.key,t.key.slice(1))}ae(e)}const l=new Map(n.map(e=>[e.name,e.key])),c=new Map;return o.bodyReads=e=>{const t=l.get(e);return!(void 0===t||!i.has(t))&&(c.has(t)||(c.set(t,!1),c.set(t,A(i.get(t),o.bodyReads))),c.get(t))},o},oe=(e,t,a)=>{const n=void 0!==t&&"computed"!==t?t:void 0;let{type:o}=e;if(void 0!==n&&void 0!==o&&!((e,t)=>Array.isArray(t)?t.some(t=>j(e,t)):r(t)&&Array.isArray(t.literal)?t.literal.includes(e):j(e,t))(n.constant,o)){const t={value:g(n.constant),type:g(o)};a.push(s("default-outside-type",e.default.path,t)),o="any"}const i=!e.declared&&void 0===t;return{...void 0!==o&&{type:o},...!(void 0!==n||i||e.required&&void 0===t)&&{required:!1},...void 0!==n&&{default:n.constant},...i&&{default:e.key},...void 0!==e.description&&{description:e.description},...void 0!==e.metadata&&{metadata:e.metadata}}},ie=(e,t,s,a)=>{const r=[...e.parameters.values()],n=[...r.filter(({declared:e})=>e),...r.filter(({declared:e})=>!e).sort((e,t)=>e.name<t.name?-1:1)],o=Object.fromEntries(n.map(e=>[e.name,oe(e,s.get(e.key),a)]));return{expression:t,...n.length>0&&{parameters:o},...void 0!==e.description&&{description:e.description},...void 0!==e.metadata&&{metadata:e.metadata}}},ue=e=>void 0!==e&&e>="0"&&e<="9",le={"%":/(?<!\\)%\d+/,$:/(?<!\\)\$\d+/},ce=/(?<!\\)({{(?:[A-Za-z0-9_.]|\[[0-9]+\])+}})/,he=/(?<!\\){{(.+)}}/,pe=e=>n.test(e)?l(e):e,de=(e,t=e.to)=>({operator:t,...e.params}),me=(e,t)=>m(t)?`\`${e}\` is computed`:`\`${g(t)}\` is not a value v2 accepted for \`${e}\``,fe=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e)),ve=(e,t)=>(!0!==t.options.caseInsensitive||Object.hasOwn(e.v2,"caseInsensitive")||t.issue("instance-case-insensitive",void 0,{operator:String(e.to)}),de(e)),ye=(e,t)=>(e.length>2&&(t.issue("values-cut","values",{removed:e.slice(2).map(g).join(", ")}),t.discard("values",2)),e.slice(0,2)),ge=e=>(t,s)=>{const{strict:a}=t.v2,r=!1===a?e:t.to;void 0!==a&&"boolean"!=typeof a&&s.issue("deciding-value","strict",{reason:me("strict",a),wrote:`\`${t.to}\``,key:"strict"}),s.discard("strict");const{values:n}=t.params;return Array.isArray(n)&&(t.params.values=ye(n,s)),de(t,r)},be=(e,t,s)=>(a,r)=>{const n=(e,t)=>fe({operator:a.to,value:e,[s]:t}),{values:i}=a.v2;if(void 0===i)return n(a.v2[e],a.v2[t]);const u=String(r.at("values").at(-1));for(const s of[e,t])Object.hasOwn(a.v2,s)&&(r.issue("overridden-value",s,{key:String(r.at(s).at(-1)),winner:u}),r.discard(s));if(Array.isArray(i)){const[e,t]=ye(i,r);return n(e,t)}if("string"==typeof i&&o.test(i))return n(`${i}[0]`,`${i}[1]`);const l=r.freshVar("values");return{...n(`$vars.${l}[0]`,`$vars.${l}[1]`),vars:{[l]:i}}},Oe=be("from","subtract","minus"),Te=be("dividend","divisor","by"),we={number:e=>"number"==typeof e,string:e=>"string"==typeof e,boolean:e=>"boolean"==typeof e,array:Array.isArray},ke=e=>{const t=h(e.url);if(m(e.url)||!r(t)||!c(e.url)&&f(e.url))return;const{url:s,headers:a}=t;if(e.url=y(s),void 0===a)return;const n=e.headers;e.headers=void 0===n?y(a):r(n)&&!d(n)&&r(a)&&!v(a)?{...a,...n}:{operator:"plus",values:[y(a),n]}},je=(e,t)=>{ke(e.params);const{url:s,method:a,query:r,body:n,headers:o,returnPath:i}=e.params;return t.issue("response-collapse",void 0),fe({operator:"http",url:s,method:a,query:r,body:"post"===a?n??{}:n,headers:o,returnPath:i})},Se={"00":"rows",10:"firstRow","01":"column",11:"firstValue"},Ae=e=>{const t=e.startsWith("$")?"$":/[.[\]]/.exec(e)?.[0];return"$"===t?`\`${e}\` starts with \`$\`, which a v3 name cannot`:void 0!==t?`\`${e}\` holds a \`${t}\`, which a v3 name cannot`:Object.hasOwn(J,e)?`\`${e}\` is already a v3 operator's name`:void 0},Ee={AND:{to:"and",params:{values:"values"}},OR:{to:"or",params:{values:"values"}},MULTIPLY:{to:"multiply",params:{values:"values"}},EQUAL:{to:"equal",params:{values:"values",caseInsensitive:"caseInsensitive",nullEqualsUndefined:"omitted"},build:ve},NOT_EQUAL:{to:"notEqual",params:{values:"values",caseInsensitive:"caseInsensitive",nullEqualsUndefined:"omitted"},build:ve},GREATER_THAN:{to:"greaterThan",params:{values:"values",strict:"consumed"},build:ge("greaterThanOrEqual")},LESS_THAN:{to:"lessThan",params:{values:"values",strict:"consumed"},build:ge("lessThanOrEqual")},CONDITIONAL:{to:"if",params:{condition:"condition",valueIfTrue:"then",valueIfFalse:"else"}},REGEX:{to:"regex",params:{testString:"value",pattern:"pattern"}},COUNT:{to:"length",params:{values:"value"}},SPLIT:{to:"split",params:{value:"value",delimiter:{to:"delimiter",value:(e,t)=>{if(m(e))t.issue("computed-delimiter","delimiter");else if("string"==typeof e)return e.replace(/\\n/g,"\n").replace(/\\t/g,"\t").replace(/\\r/g,"\r");return e}},trimWhiteSpace:"trim",excludeTrailing:"consumed"},build:(e,t)=>(!1!==e.v2.excludeTrailing&&t.issue("split-trailing-empty",void 0),t.discard("excludeTrailing"),de(e))},PLUS:{to:"plus",params:{values:"values",type:"consumed"},build:(e,t)=>{if(!Object.hasOwn(e.v2,"type"))return de(e);t.discard("type");const{type:s}=e.v2,{values:a}=e.params;switch(s){case"string":return{operator:"join",...e.params,delimiter:""};case"array":return Array.isArray(a)&&(e.params.values=a.map(e=>Array.isArray(h(e))||m(e)?e:[e])),{...de(e),expect:"array"};case"number":case"boolean":case"bool":return Object.hasOwn(e.modifiers,"outputType")||Object.assign(e.modifiers,{outputType:"number"===s?"number":"boolean",outputTypeAt:"type"}),de(e)}return t.issue("deciding-value","type",{reason:me("type",s),wrote:"`plus`",key:"type"}),de(e)}},SUBTRACT:{to:"subtract",params:{values:"consumed",from:"consumed",subtract:"consumed"},build:Oe},DIVIDE:{to:"divide",params:{values:"consumed",dividend:"consumed",divisor:"consumed",output:"consumed"},build:(e,t)=>{t.discard("output");const{vars:s,...a}=Te(e,t),{output:r}=e.v2,n=e=>({...e,...void 0!==s&&{vars:s}});switch(r){case void 0:case"decimal":return n(a);case"quotient":return n({operator:"floor",value:a});case"remainder":{t.issue("remainder-sign","output");const{value:e,by:s}=a;return n(fe({operator:"modulo",value:e,mod:s}))}}return t.issue("deciding-value","output",{reason:me("output",r),wrote:"`divide`",key:"output"}),n(a)}},OBJECT_PROPERTIES:{to:"get",params:{property:"path",additionalData:{to:"from",value:e=>({operator:"plus",values:["$data",e]})}},build:(e,t)=>{const{modifiers:s}=e;if(Object.hasOwn(s,"fallback")){const{fallback:a}=s;return delete s.fallback,Object.hasOwn(s,"outputType")&&((e,t,s)=>{const a="bool"===t?"boolean":t;!m(e)&&"string"==typeof a&&Object.hasOwn(we,a)&&we[a](h(e))||s.issue("fallback-converted","fallback",{type:m(a)?"the type `outputType` computes":`\`${String(h(a))}\``})})(a,s.outputType,t),{...de(e),default:a}}const{path:a}=e.params;return Object.hasOwn(e.params,"from")||"string"!=typeof a||m(a)||!(e=>/^(?:[^[]|\[(?:\d+|\*|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')\])*$/.test(e))(a)?de(e):b(a)}},STRING_SUBSTITUTION:{to:"buildString",params:{string:"template",substitutions:"substitutions",trimWhiteSpace:"consumed",substitutionCharacter:"consumed",numberMapping:"consumed"},build:(e,t)=>{const{substitutions:s}=e.params,{trimWhiteSpace:a,substitutionCharacter:n}=e.v2,o=e.params.template,i=h(o),u=m(n)?void 0:"$"===n?"$":"%",l="string"==typeof i&&!m(o),c=Array.isArray(s),p=null==s||r(s)&&!d(s),f=c||!p&&l&&((e,t)=>le[t].test(e))(i,u??"%")&&!ce.test(i)?"positional":"named";let v=o;"positional"===f?void 0===u?t.issue("computed-dollar-template","substitutionCharacter",{what:"`substitutionCharacter`"}):l?v=pe(((e,t,s)=>{const a=e.match(new RegExp(le[t],"g"))??[],r=[...new Set([...a].sort((e,t)=>Number(e.slice(1))-Number(t.slice(1))))],n=new Map(r.map((e,t)=>[e,`%${t+1}`]));let o="",i=!1;for(let s=0;s<e.length;){const a=e[s];if("\\"!==a||e[s+1]!==t){if(a===t&&ue(e[s+1])){let t=s+1;for(;ue(e[t]);)t++;o+=n.get(e.slice(s,t)),s=t;continue}"%"===a&&ue(e[s+1])&&(i=!0),o+=a,s++}else ue(e[s+2])?(i=!0,o+=`\\${t}`):o+=t,s+=2}return i&&s.issue("template-escape","string"),o})(i,u,t)):"$"===u?t.issue("computed-dollar-template","string",{what:"template"}):t.issue("template-numbering","string"):l&&p?v=pe(((e,t,s,a)=>{const{numberMapping:n}=s.v2,o=h(n);m(n)&&a.issue("number-mapping","numberMapping",{token:"each token it maps"});let i=!1;const u=e.split(ce).map((e,s)=>{if(s%2==0)return he.test(e)?e:e.replace(/\\{{/g,(t,s)=>{const a=e.indexOf("}}",s+3),r=-1!==a&&(n=e.slice(s+3,a),!/[{}]/.test(n)&&(n.startsWith("$")?n.length>1:""!==n&&!/[.[\]]/.test(n)));var n;return r&&(i=!0),r?t:"{{"});const n=e.slice(2,-2),u=`{{${n}}}`;r(o)&&Object.hasOwn(o,n)&&a.issue("number-mapping",["numberMapping",n],{token:`\`${u}\``});const[l]=n.split(/[.[]/);return void 0!==t&&Object.hasOwn(t,l)?(l!==n&&a.issue("drilled-substitution-token","string",{token:u,name:l}),e):`{{${b(n)}}}`});return i&&a.issue("template-escape","string"),u.join("")})(i,s??void 0,e,t)):t.issue("named-token-source","string");const y=void 0===a||(!1===a?void 0:a);return void 0===y&&t.discard("trimWhiteSpace"),t.discard("substitutionCharacter"),t.discard("numberMapping"),{operator:"buildString",...void 0!==o&&{template:v},...void 0!==s&&{substitutions:s},...void 0!==y&&{trim:y}}}},BUILD_OBJECT:{to:"buildObject",params:{properties:{to:"entries",value:(e,t)=>{if(!Array.isArray(e))return e;const s=[];if(!e.every(e=>m(e)||r(e)&&(!c(e)||r(e.value)))){for(let a=0;a<e.length;a+=2)a+1<e.length?s.push({key:e[a],value:e[a+1]}):(t.issue("malformed-entry",["properties",a],{odd:!0}),t.discard(["properties",a]));return s}return e.forEach((e,a)=>{m(e)||d(e)||Object.hasOwn(e,"key")&&Object.hasOwn(e,"value")?s.push(e):(t.issue("malformed-entry",["properties",a],{odd:!1}),t.discard(["properties",a]))}),s}}}},MATCH:{to:"match",params:{matchExpression:"value",branches:{to:"branches",value:e=>{if(!Array.isArray(e))return e;const t={};for(let s=0;s+1<e.length;s+=2){const a=e[s];"string"!=typeof a&&"number"!=typeof a&&"boolean"!=typeof a||(t[String(a)]=e[s+1])}return t}}},build:(e,t)=>{const{value:s,branches:a={}}=e.params;if(r(a)&&!d(a)){if(!Object.hasOwn(a,"fallback"))return{...de(e),branches:a};const{fallback:t,...s}=a;return{...de(e),branches:s,default:t}}if(t.issue("computed-branches","branches"),0===Object.keys(e.extra).length)return de(e);let n,o=s;if("string"!=typeof s&&f(s)){const e=t.freshVar("value");o=`$vars.${e}`,n={[e]:s}}return{...de(e),value:o,default:{operator:"match",value:o,branches:e.extra},...void 0!==n&&{vars:n}}}},PASSTHRU:{params:{value:"consumed"},build:({v2:e})=>Object.hasOwn(e,"value")?e.value:null},GET:{to:"http",params:{url:"url",parameters:"query",headers:"headers",returnProperty:"returnPath"},build:je},POST:{to:"http",add:{method:"post"},params:{url:"url",parameters:"body",headers:"headers",returnProperty:"returnPath"},build:je},GRAPHQL:{to:"graphQL",params:{query:"query",url:"url",headers:"headers",variables:"variables",returnNode:"returnPath"},build:(e,t)=>{ke(e.params);const{url:s}=e.params;return""===s||"string"==typeof s&&"graphqlendpoint"===s.toLowerCase()?delete e.params.url:"string"!=typeof s||m(s)||/^https?:\/\/.+/.test(s)||t.issue("graphql-relative-url","url"),t.issue("response-collapse",void 0),de(e)}},SQL:{to:"sql",params:{query:"query",values:"values",single:"consumed",flatten:"consumed"},build:(e,t)=>{const s=[],a=(e,t)=>void 0===t||"boolean"==typeof t?!0===t:(s.push([e,t]),!1),r=a("single",e.v2.single);let n=a("flatten",e.v2.flatten);!n&&Object.hasOwn(e.extra,"type")&&(n=a("type",e.extra.type));const o=Se[`${Number(r)}${Number(n)}`];for(const[e,a]of s)t.issue("deciding-value",e,{reason:me(e,a),wrote:`\`shape: '${o}'\``,key:e});for(const e of["single","flatten","type"])t.discard(e);return{...de(e),..."rows"!==o&&{shape:o}}}},CUSTOM_FUNCTIONS:{params:{functionName:"consumed",args:"consumed",input:"consumed"},build:(e,t)=>{const s=String(h(e.v2.functionName));t.issue("custom-function-call",void 0,{name:s,rename:Ae(s)});const{args:a,input:r}=e.v2;if(!Object.hasOwn(e.v2,"input"))return{[`$${s}`]:a??[]};const n=void 0===a||Array.isArray(a)||m(a)?a:[a];return fe({operator:s,input:r,args:n})}}},$e=["fallback","useCache","outputType"],Ce=["fragment","parameters","fallback","useCache","outputType","type","operator","//"],Ie=["array","string","number"],Ne={GET:!0,POST:!1,GRAPHQL:!0,SQL:!0,CUSTOM_FUNCTIONS:!1},Ue={number:"v2 took the first number in a text (`'abc4.5x'` was `4.5`), made a text with none `0`, and made `null` `0`, where v3 fails on a text that is not a number, and keeps `null`",string:"v2 wrote an array or object as text (`[1, 2]` was `'1,2'`) and `null` as `'null'`, where v3 fails on an array or object, which `join` or `buildString` render, and keeps `null`",boolean:"v2 made any text but `''` `true` (`'false'` was `true`), where v3 reads `'true'` and `'false'` as the booleans they name",array:"v2 wrapped `null` as `[null]`, where v3 keeps `null`"},Re=e=>{const t="bool"===e?"boolean":e;if("string"==typeof t&&Object.hasOwn(Ue,t))return Ue[t];return`the target type ${m(e)?"is computed":`\`${g(e)}\` is not one v2 had`}, and v2 guessed differently for each: ${Object.values(Ue).join("; ")}`},Pe=(e,{comment:t,fallback:s,useCache:a,vars:r})=>({...void 0!==t&&{"//":t},...e,...void 0!==s&&{fallback:s},...void 0!==a&&{useCache:a},...void 0!==r&&{vars:r}}),Le=e=>{const{"//":t,fallback:s,useCache:a,vars:r,...n}=e;return{body:n,carried:{comment:t,fallback:s,useCache:a,vars:r}}},xe=(e,t)=>void 0===e?t:void 0===t?e:[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]],_e=(e,t)=>void 0===e?t:void 0===t?e:{...e,...t},qe=(e,t)=>{const s=`$vars.${t}`;return"string"==typeof e?e===s||e.startsWith(`${s}.`)||e.startsWith(`${s}[`):Array.isArray(e)?e.some(e=>qe(e,t)):r(e)&&!c(e)&&Object.values(e).some(e=>qe(e,t))},Me=(e,t)=>{const s=new Set(t),a=new Map,r=e=>e.replace(/^\$+/,"").replace(/[.[\]]/g,"_")||"_";for(const t of e)r(t)!==t.slice(1)||s.has(t.slice(1))||a.set(t,t.slice(1));a.forEach(e=>s.add(e));for(const t of e.filter(e=>!a.has(e)).sort()){let e=r(t);for(let a=2;s.has(e);a++)e=`${r(t)}_${a}`;s.add(e),a.set(t,e)}return{names:a,taken:s}},Be=(e,t)=>!0===e?.parameters.get(`$${t}`)?.exact,He=(e,t)=>{if(Array.isArray(e)&&e.forEach(e=>He(e,t)),!r(e)||c(e))return t;for(const[s,a]of Object.entries(e))"vars"===s&&r(a)&&Object.keys(a).forEach(e=>t.add(e)),He(a,t);return t};class Ge{sources;options;fragments;onRead;issues=[];dropped=new Set;droppedPaths=[];raised=new WeakMap;constructor(e,t,s,a){this.sources=e,this.options=t,this.fragments=s,this.onRead=a}pathOf(e,t,s){return this.sources.get(e)?.keys[String(t)]??[...s,t]}pathIn(e,[t,...s],a){let r=this.pathOf(e,t,a),n=e[t];for(const e of s)"object"==typeof n&&null!==n?(r=this.pathOf(n,e,r),n=n[e]):r=[...r,e];return r}value(e,t,s){const a=this.issues.length,n=r(e)&&this.sources.get(e)?.path||t,o=this.convert(e,n,s);return"object"==typeof e&&null!==e&&this.raised.set(e,{from:a,to:this.issues.length}),o}convert(e,t,s){if(Array.isArray(e))return e.map((a,r)=>this.value(a,this.pathOf(e,r,t),s));if("string"==typeof e)return this.string(e,t,s);if(!r(e))return e;const a=this.sources.get(e)?.quoted;if(void 0!==a){const{code:t,at:s,name:r=""}=a;return"unknown-operator"===t?this.placeholder(e,t,s,{name:r}):"computed-children"===t?this.placeholder(e,t,s,{operator:r}):this.placeholder(e,t,s)}return Object.hasOwn(e,"fragment")?this.call(e,t,s):Object.hasOwn(e,"operator")?this.node(e,t,s):this.plain(e,t,s)}kept(t){const s=({path:t})=>this.droppedPaths.some(s=>e(t,s));return[...t.filter(e=>!s(e)),...this.issues.filter(e=>!this.dropped.has(e))]}drop(e){if("object"!=typeof e||null===e)return;const t=this.raised.get(e);if(void 0===t)for(const t of Object.values(e))this.drop(t);else for(let e=t.from;e<t.to;e++)this.dropped.add(this.issues[e])}asWritten(e){return void 0!==this.sources.get(e)?.quoted}evaluates(e){return Array.isArray(e)?e.some(e=>this.evaluates(e)):!!r(e)&&(!(!U(e)&&!this.asWritten(e))||!0===this.options.evaluateFullObject&&Object.values(e).some(e=>this.evaluates(e)))}settle({leftOut:t,start:a},r){for(const{input:n,path:o,evaluated:i}of t){if(this.drop(n),this.droppedPaths.push(o),!i||!this.evaluates(n))continue;this.issues.slice(a).some(t=>"non-convertible"===t.tag&&!this.dropped.has(t)&&t.path.length>r.length&&e(o,t.path))||this.issues.push(s("discarded-expression",o))}}string(e,t,s){if(N(e)){const a=s.refs.get(e);if(void 0!==a)return a===s.params?.get(e)&&this.onRead?.(e,t,!1),a;if(void 0!==this.onRead)return this.onRead(e,t,!1),`$params.${Y(e)}`}return n.test(e)?l(e):e}plain(e,t,s){return this.options.evaluateFullObject?this.walked(e,t,s):v(e)?l(e):e}walked(e,t,s){const{vars:a,inner:r}=this.declare(e,t,s,!1),n=Object.entries(e).filter(([e])=>!N(e)).map(([s,a])=>[s,this.value(a,this.pathOf(e,s,t),r)]);return n.some(([e])=>"vars"===e||"//"===e)?Pe({operator:"buildObject",entries:n.map(([e,t])=>({key:e,value:t}))},{vars:a}):{...Object.fromEntries(n),...void 0!==a&&{vars:a}}}declare(e,t,s,a=!0){const r=Object.keys(e).filter(N);if(0===r.length)return{inner:s};const{names:n,taken:o}=Me(r,s.names),i=Object.fromEntries(r.map(r=>{const o=e[r],i=a&&"string"==typeof o&&o!==r&&!s.refs.has(o)?n.get(o):void 0,u=void 0!==i?`$vars.${i}`:this.value(o,this.pathOf(e,r,t),s);return[n.get(r),u]})),u=new Map(s.refs);for(const[e,t]of n)u.set(e,`$vars.${t}`);return{vars:i,inner:{refs:u,names:o,params:s.params},sources:new Map(r.map(s=>[n.get(s),{input:e[s],path:this.pathOf(e,s,t)}]))}}node(e,t,s,a){const r=e.operator,n=I[r].map(({name:e})=>e).filter(e=>"useCache"!==e),{vars:o,inner:i,sources:u}=a??this.declare(e,t,s),l=[],c={};for(const s of n)Object.hasOwn(e,s)&&(c[s]=this.parameter(r,s,e,t,i));const h=s=>this.value(e[s],this.pathOf(e,s,t),i),p=Object.fromEntries(this.extraKeys(e,r,n).map(e=>[e,h(e)])),d={};Object.hasOwn(e,"fallback")&&(d.fallback=h("fallback")),Object.hasOwn(e,"outputType")&&Object.assign(d,{outputType:h("outputType"),outputTypeAt:"outputType"});const m=new Set([...i.names,...He([c,p,d],new Set)]),f=this.context(e,t,l,m,n,u),v=((e,t,s)=>{const a={};for(const[r,n]of Object.entries(e.params))if(Object.hasOwn(t.v2,r)&&"consumed"!==n)if("omitted"===n)s.discard(r);else if("string"==typeof n)a[n]=t.v2[r];else{const e=n.value(t.v2[r],s);void 0!==e?a[n.to]=e:s.discard(r)}Object.assign(a,e.add);const r={to:e.to,params:a,...t};return e.build?e.build(r,s):de(r)})(Ee[r],{v2:c,extra:p,modifiers:d},f),y=this.useCache(e,r,f),g=this.comment(e,[...n,...Object.keys(p)],l),b=this.attach(v,{comment:g,useCache:y,vars:o},d,f);return this.settle(f,t),b}parameter(e,t,s,n,o){const i=s[t],u=this.pathOf(s,t,n);if(!a[e]?.evaluatesContents?.includes(t))return this.value(i,u,o);if(Array.isArray(i)){if("MATCH"===e)return this.branchList(i,u,o);if("BUILD_OBJECT"===e)return this.entries(i,u,o)}if("BUILD_OBJECT"===e)return this.value(i,u,o);if(!r(i)||this.asWritten(i)||("MATCH"===e?Object.hasOwn(i,"operator"):U(i)))return this.value(i,u,o);const l=this.sources.get(i)?.path??u,c=(e=()=>!1)=>{const t={},s={};for(const[a,r]of Object.entries(i))e(a)?s[a]=r:t[a]=this.value(r,this.pathOf(i,a,l),o);return Object.keys(s).length>0?{"//":s,...t}:t};switch(e){case"MATCH":return c();case"STRING_SUBSTITUTION":return this.options.evaluateFullObject?this.walked(i,l,o):c(N);default:return this.walked(i,l,o)}}branchList(e,t,s){return e.map((a,r)=>r%2==0?a:this.value(a,this.pathOf(e,r,t),s))}entries(e,t,s){return this.options.evaluateFullObject||!e.every(r)?this.value(e,t,s):e.map((a,r)=>{const n=this.pathOf(e,r,t);if(U(a)||this.asWritten(a))return this.value(a,n,s);const o=this.sources.get(a)?.path??n,i={};for(const e of["key","value"])Object.hasOwn(a,e)&&(i[e]=this.value(a[e],this.pathOf(a,e,o),s));return i})}extraKeys(e,t,s){if("SQL"===t)return Object.hasOwn(e,"type")?["type"]:[];if("MATCH"!==t)return[];const a=["operator",...s,...$e,"//"];return Object.keys(e).filter(e=>!a.includes(e)&&!N(e))}context(e,t,a,r,n=[],o){const i=[];return{leftOut:i,start:this.issues.length,discard:(s,a)=>{const r="string"==typeof s?[s]:s;let o=e;for(const e of r){if("object"!=typeof o||null===o||!Object.hasOwn(o,e))return;o=o[e]}const u=this.pathIn(e,r,t),l=n.includes(String(r[0]));if(void 0===a)i.push({input:o,path:u,evaluated:l});else if(Array.isArray(o))for(let e=a;e<o.length;e++)i.push({input:o[e],path:this.pathOf(o,e,u),evaluated:l})},discardVars:e=>{for(const t of e){const e=o?.get(t);void 0!==e&&i.push({...e,evaluated:!0})}},options:this.options,path:t,at:s=>this.pathOf(e,s,t),issue:(r,n,...o)=>{const i=void 0===n?t:"string"==typeof n?this.pathOf(e,n,t):this.pathIn(e,n,t),l=s(r,i,...o);this.issues.push(l),"non-convertible"===l.tag&&a.push(`${u}${l.message}`)},freshVar:e=>{let t=e;for(let s=2;r.has(t);s++)t=`${e}_${s}`;return r.add(t),t}}}useCache(e,t,s){if("PASSTHRU"===t)return;if(!Object.hasOwn(e,"useCache"))return("POST"!==t||!0===this.options.useCache)&&void 0;const a=e.useCache;if("boolean"==typeof a)return a;const r=Ne[t];if(void 0===r)return;const n=this.options.useCache??r;return s.issue("deciding-value","useCache",{reason:me("useCache",a),wrote:`\`useCache: ${n}\``,key:"useCache"}),n}comment(e,t,s){const a=["operator",...t,...$e,"//"],r=Object.fromEntries(Object.entries(e).filter(([e])=>!a.includes(e)&&!N(e)));Object.assign(r,this.sources.get(e)?.ignored);const n=[...s,...Object.hasOwn(e,"//")?[e["//"]]:[],...Object.keys(r).length>0?[r]:[]];return 0===n.length?void 0:1===n.length?n[0]:n}attach(e,t,s,a){let{vars:r}=t;const{fallback:n}=s;if(({result:e,vars:r}=this.ownVar(e,r,n)),!Object.hasOwn(s,"outputType")||!s.outputType)return this.carry(e,{...t,fallback:n,vars:r},Object.hasOwn(s,"fallback"),a);const o=s.outputType;a.issue("output-type",s.outputTypeAt??"outputType",{differences:Re(o)});const i=d(e)&&!c(e),u=i?this.carry(e,{comment:t.comment,useCache:t.useCache},!1,a):e;return this.carry({operator:"convert",value:u,to:"bool"===o?"boolean":o},{comment:i?void 0:t.comment,fallback:n,vars:r},Object.hasOwn(s,"fallback"),a)}ownVar(e,t,s){const a={...t};let r="string"==typeof e?/^\$vars\.([^.[]+)$/.exec(e)?.[1]:void 0;for(;void 0!==r&&Object.hasOwn(a,r);){const{[r]:t,...n}=a;[e=t,s,...Object.values(n)].some(e=>qe(e,r))||delete a[r],r="string"==typeof e?/^\$vars\.([^.[]+)$/.exec(e)?.[1]:void 0}return{result:e,vars:Object.keys(a).length>0?a:void 0}}carry(e,t,s,a){const{comment:n,fallback:o,useCache:u,vars:l}=t;if(d(e)&&!c(e)){const{body:t,carried:r}=Le(e);let i=r.fallback;return s&&(void 0!==r.fallback?i=this.chain(r.fallback,o,a):(this.beneath(t,r.vars)&&a.issue("missing-data-fallback","fallback"),i=o)),Pe(t,{comment:xe(r.comment,n),fallback:i,useCache:r.useCache??u,vars:_e(l,r.vars)})}if("string"==typeof e&&i.test(e)){const t=e.replace(/^\$(?:data|d)\.?/,""),r=""!==t;if(s&&!r&&a.discard("fallback"),!(s&&r||void 0!==l))return e;const i={operator:"get",path:t,...s&&r&&{default:o}};return Pe(i,{comment:n,vars:l})}if(r(e)&&!c(e)&&f(e)){const{vars:t,...r}=e,i=_e(l,t);if(!s)return Pe(r,{comment:n,vars:i});const u={operator:"buildObject",entries:Object.entries(r).map(([e,t])=>({key:e,value:t}))};return this.uncaught(u)&&a.issue("missing-data-fallback","fallback"),Pe(u,{comment:n,fallback:o,vars:i})}if(Array.isArray(e)&&f(e)&&(s||void 0!==l)){const t={operator:"convert",value:e,to:"array"};return s&&this.uncaught(t)&&a.issue("missing-data-fallback","fallback"),Pe(t,{comment:n,fallback:s?o:void 0,vars:l})}if(s&&a.discard("fallback"),void 0!==l&&a.discardVars(Object.keys(l)),!c(e)||void 0===n)return e;const{body:h,carried:p}=Le(e);return Pe(h,{comment:xe(p.comment,n)})}chain(e,t,s){if(!d(e)||c(e))return s.discard("fallback"),e;const{body:a,carried:r}=Le(e);return void 0!==r.fallback?Pe(a,{...r,fallback:this.chain(r.fallback,t,s)}):(this.beneath(a)&&s.issue("missing-data-fallback","fallback"),Pe(a,{...r,fallback:t}))}uncaught(e){return A(e,this.fragments.bodyReads)}beneath(e,t){return Object.hasOwn(e,"fragment")?this.fragments.bodyReads(String(e.fragment)):this.uncaught(e)||this.uncaught(t)}call(e,t,s){const a=this.fragments.fragments.get(String(e.fragment)),r=[],n=this.sharedArguments(e,s,a),o={...s,names:n.taken},i=this.context(e,t,r,new Set(o.names)),u={fragment:a?.name??e.fragment},{parameters:l,vars:c}=this.callArguments(e,t,o,a,i,n.names);void 0!==l&&(u.parameters=l);const h={};Object.hasOwn(e,"fallback")&&(h.fallback=this.value(e.fallback,this.pathOf(e,"fallback",t),o)),this.callOutput(e,t,o,a,h,i),Object.hasOwn(e,"useCache")&&(i.issue("fragment-use-cache","useCache"),i.discard("useCache")),Object.hasOwn(e,"operator")&&(i.issue("overridden-value","operator",{key:"operator",winner:"fragment"}),i.discard("operator"));for(const t of Object.keys(e))Ce.includes(t)||N(t)||(i.issue("body-override",t,{key:t}),i.discard(t));const p=[...r,...Object.hasOwn(e,"//")?[e["//"]]:[]],d=0===p.length?void 0:1===p.length?p[0]:p,m=this.attach(u,{comment:d,vars:c},h,i);return this.settle(i,t),m}sharedArguments(e,t,s){const a=e.parameters;if(!r(a)||U(a))return Me([],t.names);const n=Object.keys(a).filter(e=>N(e)&&!(Object.hasOwn(a,e.slice(1))&&Be(s,e.slice(1)))),o=e=>{const s=a[e];return"string"==typeof s&&s!==e&&n.includes(s)&&!t.refs.has(s)?s:void 0},i=new Set,u=n.filter(e=>void 0===s||s.parameters.has(e));for(;u.length>0;){const e=o(u.pop());void 0===e||i.has(e)||(i.add(e),u.push(e))}return Me(n.filter(e=>i.has(e)),t.names)}callArguments(e,t,s,a,n,o){const i=e.parameters,u=this.pathOf(e,"parameters",t);if(null!=i&&(!r(i)||U(i))){n.issue("computed-arguments","parameters");const e=this.value(i,u,s);return m(e)?{parameters:e}:(n.leftOut.push({input:i,path:u,evaluated:!1}),{})}const l={},c={},h=new Set,p=r(i)?Object.entries(i):[],d=r(i)&&this.sources.get(i)?.path||u,f=(e,t,a)=>{const r="string"!=typeof t||t===e||s.refs.has(t)?void 0:o.get(t);return void 0!==r?`$vars.${r}`:this.value(t,a,s)};for(const[e,t]of p){const s=["parameters",e],r=this.pathOf(i,e,d),u=o.get(e);if(void 0!==u&&(c[u]=f(e,t,r)),!N(e)&&!Be(a,e)){n.issue("body-override",s,{key:e}),n.leftOut.push({input:t,path:r,evaluated:!1});continue}if(N(e)&&Object.hasOwn(i,e.slice(1))&&Be(a,e.slice(1))){n.issue("overridden-value",s,{key:e,winner:e.slice(1)}),n.leftOut.push({input:t,path:r,evaluated:!0});continue}const p=N(e)?e:`$${e}`,m=a?.parameters.get(p);if(void 0!==a&&void 0===m){if(void 0!==u)continue;n.issue("unknown-argument",s,{fragment:a.key,name:e}),n.leftOut.push({input:t,path:r,evaluated:!0});continue}l[m?.name??Y(p)]=void 0!==u?`$vars.${u}`:f(e,t,r),h.add(p)}return void 0!==a&&this.fill(a,h,l,t,s),{...Object.keys(l).length>0&&{parameters:l},...Object.keys(c).length>0&&{vars:c}}}fill(e,t,s,a,r){for(const n of e.parameters.values()){if(t.has(n.key)||void 0!==n.default)continue;let e=r.refs.get(n.key);if(void 0===e){if(void 0===this.onRead)continue;this.onRead(n.key,a,!0),e=`$params.${Y(n.key)}`}else e===r.params?.get(n.key)&&this.onRead?.(n.key,a,!0);s[n.name]=e}}callOutput(e,t,s,a,r,n){const o=["outputType","type"].find(t=>Object.hasOwn(e,t)&&("type"===t||null!=e[t]));if(void 0===o)return;if("outputType"===o&&Object.hasOwn(e,"type")&&(n.issue("overridden-value","type",{key:"type",winner:"outputType"}),n.discard("type")),void 0!==a){const t=e=>{n.issue("unused-output-type",o,{key:o,reason:`the body of \`${a.key}\` ${e}`}),n.discard(o)};if(void 0===a.body)return t("is not an operator node, which v2 returned as it was");if("outputType"===a.ownOutput||"type"===a.ownOutput&&"type"===o)return t("sets its own output type");const s=e.type,r="SQL"===a.operator&&("object"==typeof s&&null!==s||"string"==typeof s&&(N(s)||Ie.includes(s)));if("type"===o&&("PLUS"===a.operator||r))return n.issue("body-override","type",{key:o}),n.discard("type");"outputType"===o&&a.convertsByType&&n.issue("replaced-output-type","outputType",{fragment:a.key})}const i=this.value(e[o],this.pathOf(e,o,t),s);Object.assign(r,{outputType:i,outputTypeAt:o})}body(e){const t=new Map([...e.parameters.values()].map(({key:e,name:t})=>[e,`$params.${t}`])),s={refs:t,names:new Set,params:t},a=new Map(t),r=new Map,n={},o=new Map;for(const{key:t,name:i,default:u}of e.parameters.values()){if(void 0===u)continue;const e=this.value(u.value,u.path,s);f(e)?(r.set(t,"computed"),n[i]={operator:"firstOf",values:[`$params.${i}`,e]},o.set(i,{input:u.value,path:u.path}),a.set(t,`$vars.${i}`)):r.set(t,{constant:O(e)})}const i={refs:a,names:new Set(Object.keys(n)),params:a},u=i.names.size>0?n:void 0,l=e.body,c=this.sources.get(l)?.path??[e.key];return void 0!==this.sources.get(l)?.quoted?{expression:this.value(l,c,i),defaults:r}:{expression:this.node(l,c,i,{vars:u,inner:i,sources:o}),defaults:r}}placeholder(e,t,a,...r){const n=s(t,a,...r);return this.issues.push(n),l(e,`${u}${n.message}`)}}const Qe=e=>(t,s,a)=>new Ge(t.sources,e,s,a).body(t).expression,De=e=>{const t=r(e)?e:{},{fragments:s,functions:a,useCache:n}=t;return{fragments:r(s)?s:{},functions:Array.isArray(a)?a.filter(e=>"string"==typeof e):r(a)?Object.keys(a):[],evaluateFullObject:Boolean(t.evaluateFullObject),noShorthand:Boolean(t.noShorthand),caseInsensitive:Boolean(t.caseInsensitive),...null!=n&&{useCache:Boolean(n)}}},Fe=e=>{try{return JSON.stringify(e,function(e,t){const s=this[e],a=null===s||"string"==typeof s||"boolean"==typeof s||"number"==typeof s&&Number.isFinite(s)||"object"==typeof s&&(Array.isArray(s)||(e=>{const t=Object.getPrototypeOf(e);return"function"!=typeof e.toJSON&&(null===t||null===Object.getPrototypeOf(t))})(s));if(!a)throw new TypeError("not JSON");return t})}catch{return}};let We;const Je=(e,t,a)=>{if(!(e instanceof RangeError))throw e;const r=s("unconvertible-input",a);return{expression:l(t,`${u}${r.message}`),issue:r}},Ve=(e,t)=>{const s=De(t),a=W(e,s),r=new Ge(a.sources,s,(e=>{const t=Fe(e);if(void 0!==t&&t===We?.key)return We.catalogue;const s=ne(e,Qe(e));return void 0!==t&&(We={key:t,catalogue:s}),s})(s)),n={refs:new Map,names:new Set};return{expression:r.value(a.expression,[],n),issues:r.kept(a.issues)}},Xe=e=>{const t=De(e),s=ne(t,Qe(t)),a={},r=[];for(const e of s.fragments.values()){if(void 0===e.body){r.push(...e.issues),a[e.name]=ie(e,y(e.data),new Map,r);continue}const n=new Ge(e.sources,t,s),{expression:o,defaults:i}=n.body(e);r.push(...n.kept(e.issues)),a[e.name]=ie(e,o,i,r)}return{fragments:a,issues:r}},Ye=(e,t)=>((e,t)=>{try{return Ve(e,t)}catch(t){const s=Je(t,e,[]);return{expression:s.expression,issues:[s.issue]}}})(e,t),ze=e=>(e=>{try{return Xe(e)}catch(t){const s={},a=[],n=r(e?.fragments)?e.fragments:{};for(const[e,r]of Object.entries(n)){const n=Je(t,r,[e]);s[e]={expression:n.expression},a.push(n.issue)}return{fragments:s,issues:a}}})(e);export{Ye as migrateV2Expression,ze as migrateV2Fragments};