@jmespath-community/jmespath
Version:
Typescript implementation of the JMESPath Community specification
2 lines • 33.7 kB
JavaScript
var nt=Object.defineProperty;var it=(i,t,e)=>t in i?nt(i,t,{enumerable:true,configurable:true,writable:true,value:e}):i[t]=e;var a=(i,t,e)=>it(i,typeof t!="symbol"?t+"":t,e);var L=i=>i!==null&&Object.prototype.toString.call(i)==="[object Object]",O=(i,t)=>{if(i===t)return true;if(typeof i!=typeof t)return false;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return false;for(let e=0;e<i.length;e+=1)if(!O(i[e],t[e]))return false;return true}if(L(i)&&L(t)){let e=Object.entries(i),r=new Set(Object.keys(t));if(e.length!==r.size)return false;for(let[n,s]of e){if(!O(s,t[n]))return false;r.delete(n);}return r.size===0}return false},E=i=>i==null||i===false?true:typeof i=="string"?i==="":typeof i=="object"?Array.isArray(i)?i.length===0:i===null?true:Object.keys(i).length===0:false,S=i=>i>="a"&&i<="z"||i>="A"&&i<="Z"||i==="_",R=i=>i>="0"&&i<="9"||i==="-",J=i=>i>="a"&&i<="z"||i>="A"&&i<="Z"||i>="0"&&i<="9"||i==="_",f=i=>{if(typeof i!="number"||Math.floor(i)!==i)throw new Error("invalid-value: expecting an integer.");return i},d=i=>{if(typeof i!="number"||i<0||Math.floor(i)!==i)throw new Error("invalid-value: expecting a non-negative integer.");return i},_=(...i)=>{for(let t=0;t<i.length;t++){if(i[t]===null||i[t]===void 0)throw new Error("not-a-number: undefined");if(typeof i[t]!="number")throw new Error("not-a-number")}},B=i=>{if(i=+i,!i)throw new Error("not-a-number: divide by zero");return i},w=(i,t)=>(_(i,t),i+t),M=(i,t)=>(_(i,t),i-t),U=(i,t)=>(_(i,t),i*t),k=(i,t)=>(_(i,t),i/B(t)),C=(i,t)=>(_(i,t),Math.floor(i/B(t))),V=(i,t)=>(_(i,t),i%t);var G=(i,t,e,r)=>{if(!i||!t)return null;e=Math.max(f(e=e||0),0),r=Math.min(f(r=r||i.length),i.length);let n=i.slice(e,r).indexOf(t);return n===-1?null:n+e},D=(i,t,e,r)=>{if(!i||!t)return null;e=Math.max(f(e=e||0),0),r=Math.min(f(r=r||i.length),i.length);let n=i.slice(e,r).lastIndexOf(t);return n===-1?null:n+e},j=i=>i.toLowerCase(),$=(i,t,e)=>{if(e=e||" ",e.length>1)throw new Error(`invalid value, ${i} expects its 'pad' parameter to be a valid string with a single codepoint`);return d(t),e},Q=(i,t,e)=>(e=$("pad_left",t,e),i&&i.padStart(t,e)||""),H=(i,t,e)=>(e=$("pad_right",t,e),i&&i.padEnd(t,e)||""),N=(i,t,e,r)=>r===0?i:r?(d(r),[...Array(r).keys()].map(()=>i=i.replace(t,e)),i):i.split(t).join(e),X=(i,t,e)=>{if(i.length==0&&t.length===0)return [];if(e==null)return i.split(t);if(d(e),e===0)return [i];let r=i.split(t);return [...r.slice(0,e),r.slice(e).join(t)]},z=(i,t)=>I(x(i,t),t),I=(i,t)=>q(i,e=>new RegExp(`^[${e}]*(.*?)`),t),x=(i,t)=>q(i,e=>new RegExp(`(.*?)[${e}]*$`),t),q=(i,t,e)=>{let r=e?e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"):"\\s\x85";return i.replace(t(r),"$1")},W=i=>i.toUpperCase();var Z={"(":"Lparen",")":"Rparen","*":"Star",",":"Comma",".":"Dot",":":"Colon","@":"Current","]":"Rbracket","{":"Lbrace","}":"Rbrace","+":"Plus","%":"Modulo","?":"Question","\u2212":"Minus","\xD7":"Multiply","\xF7":"Divide"},st={"!":true,"<":true,"=":true,">":true,"&":true,"|":true,"/":true},ut={" ":true,"\n":true,"\r":true," ":true},P=class{constructor(){a(this,"_current",0);a(this,"_enable_legacy_literals",false);}tokenize(t,e){let r=[];this._current=0,this._enable_legacy_literals=e?.enable_legacy_literals||false;let n,s,u;for(;this._current<t.length;)if(S(t[this._current]))n=this._current,s=this.consumeUnquotedIdentifier(t),r.push({start:n,type:"UnquotedIdentifier",value:s});else if(Z[t[this._current]]!==void 0)r.push({start:this._current,type:Z[t[this._current]],value:t[this._current]}),this._current+=1;else if(t[this._current]==="$")n=this._current,this._current+1<t.length&&S(t[this._current+1])?(this._current+=1,s=this.consumeUnquotedIdentifier(t),r.push({start:n,type:"Variable",value:s})):(r.push({start:n,type:"Root",value:t[this._current]}),this._current+=1);else if(t[this._current]==="-")if(this._current+1<t.length&&R(t[this._current+1])){let o=this.consumeNumber(t);o&&r.push(o);}else {let o={start:this._current,type:"Minus",value:"-"};r.push(o),this._current+=1;}else if(R(t[this._current]))u=this.consumeNumber(t),r.push(u);else if(t[this._current]==="[")u=this.consumeLBracket(t),r.push(u);else if(t[this._current]==='"')n=this._current,s=this.consumeQuotedIdentifier(t),r.push({start:n,type:"QuotedIdentifier",value:s});else if(t[this._current]==="'")n=this._current,s=this.consumeRawStringLiteral(t),r.push({start:n,type:"Literal",value:s});else if(t[this._current]==="`"){n=this._current;let o=this.consumeLiteral(t);r.push({start:n,type:"Literal",value:o});}else if(st[t[this._current]]!==void 0)u=this.consumeOperator(t),u&&r.push(u);else if(ut[t[this._current]]!==void 0)this._current+=1;else {let o=new Error(`Syntax error: unknown character: ${t[this._current]}`);throw o.name="LexerError",o}return r}consumeUnquotedIdentifier(t){let e=this._current;for(this._current+=1;this._current<t.length&&J(t[this._current]);)this._current+=1;return t.slice(e,this._current)}consumeQuotedIdentifier(t){let e=this._current;this._current+=1;let r=t.length;for(;t[this._current]!=='"'&&this._current<r;){let u=this._current;t[u]==="\\"&&(t[u+1]==="\\"||t[u+1]==='"')?u+=2:u+=1,this._current=u;}this._current+=1;let[n,s]=this.parseJSON(t.slice(e,this._current));if(!s){let u=new Error("syntax: unexpected end of JSON input");throw u.name="LexerError",u}return n}consumeRawStringLiteral(t){let e=this._current;this._current+=1;let r=t.length;for(;t[this._current]!=="'"&&this._current<r;){let s=this._current;t[s]==="\\"&&(t[s+1]==="\\"||t[s+1]==="'")?s+=2:s+=1,this._current=s;}this._current+=1;let n=t.slice(e+1,this._current-1);return N(N(n,"\\\\","\\"),"\\'","'")}consumeNumber(t){let e=this._current;this._current+=1;let r=t.length;for(;R(t[this._current])&&this._current<r;)this._current+=1;let n=parseInt(t.slice(e,this._current),10);return {start:e,value:n,type:"Number"}}consumeLBracket(t){let e=this._current;return this._current+=1,t[this._current]==="?"?(this._current+=1,{start:e,type:"Filter",value:"[?"}):t[this._current]==="]"?(this._current+=1,{start:e,type:"Flatten",value:"[]"}):{start:e,type:"Lbracket",value:"["}}consumeOrElse(t,e,r,n){let s=this._current;return this._current+=1,this._current<t.length&&t[this._current]===e?(this._current+=1,{start:s,type:n,value:t.slice(s,this._current)}):{start:s,type:r,value:t[s]}}consumeOperator(t){let e=this._current;switch(t[e]){case "!":return this.consumeOrElse(t,"=","Not","NE");case "<":return this.consumeOrElse(t,"=","LT","LTE");case ">":return this.consumeOrElse(t,"=","GT","GTE");case "=":return this.consumeOrElse(t,"=","Assign","EQ");case "&":return this.consumeOrElse(t,"&","Expref","And");case "|":return this.consumeOrElse(t,"|","Pipe","Or");case "/":return this.consumeOrElse(t,"/","Divide","Div")}}consumeLiteral(t){this._current+=1;let e=this._current,r=t.length;for(;t[this._current]!=="`"&&this._current<r;){let o=this._current;t[o]==="\\"&&(t[o+1]==="\\"||t[o+1]==="`")?o+=2:o+=1,this._current=o;}let n=t.slice(e,this._current).trimStart();n=n.replace("\\`","`");let s=null,u=false;if(this.looksLikeJSON(n)&&([s,u]=this.parseJSON(n)),!u&&this._enable_legacy_literals&&([s,u]=this.parseJSON(`"${n}"`)),!u){let o=new Error(`Syntax error: unexpected end of JSON input or invalid format for a JSON literal: ${t[this._current]}`);throw o.name="LexerError",o}return this._current+=1,s}looksLikeJSON(t){let e='[{"',r=["true","false","null"],n="-0123456789";if(t==="")return false;if(e.includes(t[0])||r.includes(t))return true;if(n.includes(t[0])){let[s,u]=this.parseJSON(t);return u}return false}parseJSON(t){try{return [JSON.parse(t),!0]}catch{return [null,false]}}},ot=new P,y=ot;var p={EOF:0,Variable:0,UnquotedIdentifier:0,QuotedIdentifier:0,Rbracket:0,Rparen:0,Comma:0,Rbrace:0,Number:0,Current:0,Expref:0,Root:0,Assign:1,Pipe:1,Question:2,Or:3,And:4,EQ:5,GT:5,LT:5,GTE:5,LTE:5,NE:5,Minus:6,Plus:6,Div:7,Divide:7,Modulo:7,Multiply:7,Flatten:9,Star:20,Filter:21,Dot:40,Not:45,Lbrace:50,Lbracket:55,Lparen:60},b=class i{constructor(){a(this,"index",0);a(this,"tokens",[]);}parse(t,e){this.loadTokens(t,e||{enable_legacy_literals:false}),this.index=0;let r=this.expression(0);if(this.lookahead(0)!=="EOF"){let n=this.lookaheadToken(0);this.errorToken(n,`Syntax error: unexpected token type: ${n.type}, value: ${n.value}`);}return r}loadTokens(t,e){this.tokens=y.tokenize(t,e),this.tokens.push({type:"EOF",value:"",start:t.length});}expression(t){let e=this.lookaheadToken(0);this.advance();let r=this.nud(e),n=this.lookahead(0);for(;t<p[n];)this.advance(),r=this.led(n,r),n=this.lookahead(0);return r}lookahead(t){return this.tokens[this.index+t].type}lookaheadToken(t){return this.tokens[this.index+t]}advance(){this.index+=1;}nud(t){switch(t.type){case "Variable":return {type:"Variable",name:t.value};case "Literal":return {type:"Literal",value:t.value};case "UnquotedIdentifier":return i.isKeyword(t,"let")&&this.lookahead(0)==="Variable"?this.parseLetExpression():{type:"Field",name:t.value};case "QuotedIdentifier":if(this.lookahead(0)==="Lparen")throw new Error("Syntax error: quoted identifier not allowed for function names.");return {type:"Field",name:t.value};case "Not":return {type:"NotExpression",child:this.expression(p.Not)};case "Minus":{let e=this.expression(p.Minus);return {type:"Unary",operator:t.type,operand:e}}case "Plus":{let e=this.expression(p.Plus);return {type:"Unary",operator:t.type,operand:e}}case "Star":return {type:"ValueProjection",left:{type:"Identity"},right:this.parseProjectionRHS(p.Star)};case "Filter":return this.led(t.type,{type:"Identity"});case "Lbrace":return this.parseMultiselectHash();case "Flatten":{let e={type:"Flatten",child:{type:"Identity"}},r=this.parseProjectionRHS(p.Flatten);return {type:"Projection",left:e,right:r}}case "Lbracket":{if(this.lookahead(0)==="Number"||this.lookahead(0)==="Colon"){let e=this.parseIndexExpression();return this.projectIfSlice({type:"Identity"},e)}if(this.lookahead(0)==="Star"&&this.lookahead(1)==="Rbracket"){this.advance(),this.advance();let e=this.parseProjectionRHS(p.Star);return {left:{type:"Identity"},right:e,type:"Projection"}}return this.parseMultiselectList()}case "Current":return {type:"Current"};case "Root":return {type:"Root"};case "Expref":return {type:"ExpressionReference",child:this.expression(p.Expref)};case "Lparen":{let e=this.expression(0);return this.match("Rparen"),e}default:this.errorToken(t);}}led(t,e){switch(t){case "Question":{let r=this.expression(0);this.match("Colon");let n=this.expression(0);return {type:"Ternary",condition:e,trueExpr:r,falseExpr:n}}case "Dot":{let r=p.Dot;if(this.lookahead(0)!=="Star"){let s=this.parseDotRHS(r);return {type:"Subexpression",left:e,right:s}}this.advance();let n=this.parseProjectionRHS(r);return {type:"ValueProjection",left:e,right:n}}case "Pipe":{let r=this.expression(p.Pipe);return {type:"Pipe",left:e,right:r}}case "Or":{let r=this.expression(p.Or);return {type:"OrExpression",left:e,right:r}}case "And":{let r=this.expression(p.And);return {type:"AndExpression",left:e,right:r}}case "Lparen":{if(e.type!=="Field")throw new Error("Syntax error: expected a Field node");let r=e.name,n=this.parseCommaSeparatedExpressionsUntilToken("Rparen");return {name:r,type:"Function",children:n}}case "Filter":{let r=this.expression(0);this.match("Rbracket");let n=this.lookahead(0)==="Flatten"?{type:"Identity"}:this.parseProjectionRHS(p.Filter);return {type:"FilterProjection",left:e,right:n,condition:r}}case "Flatten":{let r={type:"Flatten",child:e},n=this.parseProjectionRHS(p.Flatten);return {type:"Projection",left:r,right:n}}case "Assign":{let r=e,n=this.expression(0);return {type:"Binding",variable:r.name,reference:n}}case "EQ":case "NE":case "GT":case "GTE":case "LT":case "LTE":return this.parseComparator(e,t);case "Plus":case "Minus":case "Multiply":case "Star":case "Divide":case "Modulo":case "Div":return this.parseArithmetic(e,t);case "Lbracket":{let r=this.lookaheadToken(0);if(r.type==="Number"||r.type==="Colon"){let s=this.parseIndexExpression();return this.projectIfSlice(e,s)}this.match("Star"),this.match("Rbracket");let n=this.parseProjectionRHS(p.Star);return {type:"Projection",left:e,right:n}}default:return this.errorToken(this.lookaheadToken(0))}}static isKeyword(t,e){return t.type==="UnquotedIdentifier"&&t.value===e}match(t){if(this.lookahead(0)===t){this.advance();return}else {let e=this.lookaheadToken(0);this.errorToken(e,`Syntax error: expected ${t}, got: ${e.type}`);}}errorToken(t,e=""){let r=new Error(e||`Syntax error: invalid token (${t.type}): "${t.value}"`);throw r.name="ParserError",r}parseIndexExpression(){if(this.lookahead(0)==="Colon"||this.lookahead(1)==="Colon")return this.parseSliceExpression();let t=Number(this.lookaheadToken(0).value);return this.advance(),this.match("Rbracket"),{type:"Index",value:t}}projectIfSlice(t,e){let r={type:"IndexExpression",left:t,right:e};return e.type==="Slice"?{left:r,right:this.parseProjectionRHS(p.Star),type:"Projection"}:r}parseSliceExpression(){let t=[null,null,null],e=0,r=this.lookaheadToken(0);for(;r.type!="Rbracket"&&e<3;){if(r.type==="Colon")e++,e===3&&this.errorToken(this.lookaheadToken(0),"Syntax error, too many colons in slice expression"),this.advance();else if(r.type==="Number"){let o=this.lookaheadToken(0).value;t[e]=o,this.advance();}else {let o=this.lookaheadToken(0);this.errorToken(o,`Syntax error, unexpected token: ${o.value}(${o.type})`);}r=this.lookaheadToken(0);}this.match("Rbracket");let[n,s,u]=t;return {type:"Slice",start:n,stop:s,step:u}}parseLetExpression(){let t=this.parseCommaSeparatedExpressionsUntilKeyword("in"),e=this.expression(0);return {type:"LetExpression",bindings:t.map(n=>n),expression:e}}parseCommaSeparatedExpressionsUntilKeyword(t){return this.parseCommaSeparatedExpressionsUntil(()=>i.isKeyword(this.lookaheadToken(0),t),()=>{this.advance();})}parseCommaSeparatedExpressionsUntilToken(t){return this.parseCommaSeparatedExpressionsUntil(()=>this.lookahead(0)===t,()=>this.match(t))}parseCommaSeparatedExpressionsUntil(t,e){let r=[],n;for(;!t();)n=this.expression(0),this.lookahead(0)==="Comma"&&this.match("Comma"),r.push(n);return e(),r}parseComparator(t,e){let r=this.expression(p[e]);return {type:"Comparator",name:e,left:t,right:r}}parseArithmetic(t,e){let r=this.expression(p[e]);return {type:"Arithmetic",operator:e,left:t,right:r}}parseDotRHS(t){let e=this.lookahead(0);if(["UnquotedIdentifier","QuotedIdentifier","Star"].includes(e))return this.expression(t);if(e==="Lbracket")return this.match("Lbracket"),this.parseMultiselectList();if(e==="Lbrace")return this.match("Lbrace"),this.parseMultiselectHash();let n=this.lookaheadToken(0);this.errorToken(n,`Syntax error, unexpected token: ${n.value}(${n.type})`);}parseProjectionRHS(t){if(p[this.lookahead(0)]<10)return {type:"Identity"};if(this.lookahead(0)==="Lbracket")return this.expression(t);if(this.lookahead(0)==="Filter")return this.expression(t);if(this.lookahead(0)==="Dot")return this.match("Dot"),this.parseDotRHS(t);let e=this.lookaheadToken(0);this.errorToken(e,`Syntax error, unexpected token: ${e.value}(${e.type})`);}parseMultiselectList(){let t=[];for(;this.lookahead(0)!=="Rbracket";){let e=this.expression(0);if(t.push(e),this.lookahead(0)==="Comma"&&(this.match("Comma"),this.lookahead(0)==="Rbracket"))throw new Error("Syntax error: unexpected token Rbracket")}return this.match("Rbracket"),{type:"MultiSelectList",children:t}}parseMultiselectHash(){let t=[],e=["UnquotedIdentifier","QuotedIdentifier"],r,n,s;for(;;){if(r=this.lookaheadToken(0),!e.includes(r.type))throw new Error(`Syntax error: expecting an identifier token, got: ${r.type}`);if(n=r.value,this.advance(),this.match("Colon"),s=this.expression(0),t.push({value:s,type:"KeyValuePair",name:n}),this.lookahead(0)==="Comma")this.match("Comma");else if(this.lookahead(0)==="Rbrace"){this.match("Rbrace");break}}return {type:"MultiSelectHash",children:t}}},at=new b,Y=at;var g=class i{constructor(t){a(this,"_text");this._text=t;}get string(){return this._text}get length(){return this.codePoints.length}compareTo(t){return i.compare(this,new i(t))}static get comparer(){return (e,r)=>new i(e).compareTo(r)}static compare(t,e){let r=t.codePoints,n=e.codePoints;for(let s=0;s<Math.min(r.length,n.length);s++)if(r[s]!==n[s])return r[s]-n[s]>0?1:-1;return r.length-n.length>0?1:-1}reverse(){return String.fromCodePoint(...this.codePoints.reverse())}get codePoints(){return [...this._text].map(e=>e.codePointAt(0))}};var K=i=>([t])=>i(t),et=i=>([t])=>i(t),rt=i=>([t])=>i(t),A=class{constructor(t){a(this,"_interpreter");a(this,"_functionTable");a(this,"_customFunctions",new Set);a(this,"TYPE_NAME_TABLE",Object.freeze({0:"number",1:"any",2:"string",3:"array",4:"object",5:"boolean",6:"expression",7:"null",8:"Array<number>",10:"Array<object>",9:"Array<string>",11:"Array<Array<any>>"}));a(this,"functionAvg",([t])=>{if(!t||t.length==0)return null;let e=0;for(let r=0;r<t.length;r+=1)e+=t[r];return e/t.length});a(this,"functionContains",([t,e])=>{if(Array.isArray(t))return t.includes(e);if(typeof t=="string"){let r=t;if(typeof e=="string")return r.includes(e)}return null});a(this,"functionEndsWith",t=>{let[e,r]=t;return e.includes(r,e.length-r.length)});a(this,"functionFindFirst",this.createFindFunction(G));a(this,"functionFindLast",this.createFindFunction(D));a(this,"functionFromItems",([t])=>(t.map(e=>{if(e.length!=2||typeof e[0]!="string")throw new Error("invalid value, each array must contain two elements, a pair of string and value")}),Object.fromEntries(t)));a(this,"functionGroupBy",([t,e])=>{let r=this.createKeyFunction(e,[2]);return t.reduce((n,s)=>{let u=r(s??{});return (n[u]=n[u]||[]).push(s),n},{})});a(this,"functionItems",([t])=>Object.entries(t));a(this,"functionJoin",t=>{let[e,r]=t;return r.join(e)});a(this,"functionLength",([t])=>typeof t=="string"?new g(t).length:Array.isArray(t)?t.length:Object.keys(t).length);a(this,"functionMap",([t,e])=>{if(!this._interpreter)return [];let r=[],n=this._interpreter;for(let s=0;s<e.length;s+=1)r.push(n.visit(t,e[s]));return r});a(this,"functionMax",([t])=>{if(!t.length)return null;if(this.getTypeName(t[0])===0)return Math.max(...t);let r=t,n=r[0];for(let s=1;s<r.length;s+=1)n.localeCompare(r[s])<0&&(n=r[s]);return n});a(this,"functionMaxBy",t=>{let e=t[1],r=t[0],n=this.createKeyFunction(e,[0,2]),s=-1/0,u,o;for(let c=0;c<r.length;c+=1)o=n&&n(r[c]),o!==void 0&&o>s&&(s=o,u=r[c]);return u||null});a(this,"functionMerge",t=>{let e={};for(let r=0;r<t.length;r+=1){let n=t[r];e=Object.assign(e,n);}return e});a(this,"functionMin",([t])=>{if(!t.length)return null;if(this.getTypeName(t[0])===0)return Math.min(...t);let r=t,n=r[0];for(let s=1;s<r.length;s+=1)r[s].localeCompare(n)<0&&(n=r[s]);return n});a(this,"functionMinBy",t=>{let e=t[1],r=t[0],n=this.createKeyFunction(e,[0,2]),s=1/0,u,o;for(let c=0;c<r.length;c+=1)o=n&&n(r[c]),o!==void 0&&o<s&&(s=o,u=r[c]);return u||null});a(this,"functionNotNull",t=>{for(let e=0;e<t.length;e+=1)if(this.getTypeName(t[e])!==7)return t[e];return null});a(this,"functionPadLeft",this.createPadFunction(Q));a(this,"functionPadRight",this.createPadFunction(H));a(this,"functionReplace",t=>{let e=t[0],r=t[1],n=t[2];return N(e,r,n,t.length>3?t[3]:void 0)});a(this,"functionSplit",t=>{let e=t[0],r=t[1];return X(e,r,t.length>2?t[2]:void 0)});a(this,"functionReverse",([t])=>{if(this.getTypeName(t)===2)return new g(t).reverse();let r=t.slice(0);return r.reverse(),r});a(this,"functionSort",([t])=>t.length==0?t:typeof t[0]=="string"?[...t].sort(g.comparer):[...t].sort());a(this,"functionSortBy",t=>{let e=t[0].slice(0);if(e.length===0)return e;let r=this._interpreter,n=t[1],s=this.getTypeName(r.visit(n,e[0]));if(s!==void 0&&![0,2].includes(s))throw new Error(`Invalid type: unexpected type (${this.TYPE_NAME_TABLE[s]})`);function u(o,c){throw new Error(`Invalid type: expected (${o.TYPE_NAME_TABLE[s]}), received ${o.TYPE_NAME_TABLE[o.getTypeName(c)]}`)}return e.sort((o,c)=>{let l=r.visit(n,o),h=r.visit(n,c);return this.getTypeName(l)!==s?u(this,l):this.getTypeName(h)!==s&&u(this,h),s===2?g.comparer(l,h):l-h})});a(this,"functionStartsWith",([t,e])=>t.startsWith(e));a(this,"functionSum",([t])=>t.reduce((e,r)=>e+r,0));a(this,"functionToArray",([t])=>this.getTypeName(t)===3?t:[t]);a(this,"functionToNumber",([t])=>{let e=this.getTypeName(t),r;return e===0?t:e===2&&(r=+t,!isNaN(r))?r:null});a(this,"functionToString",([t])=>this.getTypeName(t)===2?t:JSON.stringify(t));a(this,"functionTrim",this.createTrimFunction(z));a(this,"functionTrimLeft",this.createTrimFunction(I));a(this,"functionTrimRight",this.createTrimFunction(x));a(this,"functionType",([t])=>{switch(this.getTypeName(t)){case 0:return "number";case 2:return "string";case 3:return "array";case 4:return "object";case 5:return "boolean";case 7:return "null";default:throw new Error("invalid-type")}});a(this,"functionZip",t=>{let e=Math.min(...t.map(n=>n.length));return Array(e).fill(null).map((n,s)=>t.map(u=>u[s]))});this._interpreter=t,this._functionTable=this.buildFunctionTable();}buildFunctionTable(){return {abs:{_func:K(Math.abs),_signature:[{types:[0]}]},ceil:{_func:K(Math.ceil),_signature:[{types:[0]}]},floor:{_func:K(Math.floor),_signature:[{types:[0]}]},lower:{_func:et(j),_signature:[{types:[2]}]},upper:{_func:et(W),_signature:[{types:[2]}]},keys:{_func:rt(Object.keys),_signature:[{types:[4]}]},values:{_func:rt(Object.values),_signature:[{types:[4]}]},avg:{_func:this.functionAvg,_signature:[{types:[8]}]},contains:{_func:this.functionContains,_signature:[{types:[2,3]},{types:[1]}]},ends_with:{_func:this.functionEndsWith,_signature:[{types:[2]},{types:[2]}]},find_first:{_func:this.functionFindFirst,_signature:[{types:[2]},{types:[2]},{types:[0],optional:true},{types:[0],optional:true}]},find_last:{_func:this.functionFindLast,_signature:[{types:[2]},{types:[2]},{types:[0],optional:true},{types:[0],optional:true}]},from_items:{_func:this.functionFromItems,_signature:[{types:[11]}]},group_by:{_func:this.functionGroupBy,_signature:[{types:[3]},{types:[6]}]},items:{_func:this.functionItems,_signature:[{types:[4]}]},join:{_func:this.functionJoin,_signature:[{types:[2]},{types:[9]}]},length:{_func:this.functionLength,_signature:[{types:[2,3,4]}]},map:{_func:this.functionMap,_signature:[{types:[6]},{types:[3]}]},max:{_func:this.functionMax,_signature:[{types:[8,9]}]},max_by:{_func:this.functionMaxBy,_signature:[{types:[3]},{types:[6]}]},merge:{_func:this.functionMerge,_signature:[{types:[4],variadic:true}]},min:{_func:this.functionMin,_signature:[{types:[8,9]}]},min_by:{_func:this.functionMinBy,_signature:[{types:[3]},{types:[6]}]},not_null:{_func:this.functionNotNull,_signature:[{types:[1],variadic:true}]},pad_left:{_func:this.functionPadLeft,_signature:[{types:[2]},{types:[0]},{types:[2],optional:true}]},pad_right:{_func:this.functionPadRight,_signature:[{types:[2]},{types:[0]},{types:[2],optional:true}]},replace:{_func:this.functionReplace,_signature:[{types:[2]},{types:[2]},{types:[2]},{types:[0],optional:true}]},reverse:{_func:this.functionReverse,_signature:[{types:[2,3]}]},sort:{_func:this.functionSort,_signature:[{types:[9,8]}]},sort_by:{_func:this.functionSortBy,_signature:[{types:[3]},{types:[6]}]},split:{_func:this.functionSplit,_signature:[{types:[2]},{types:[2]},{types:[0],optional:true}]},starts_with:{_func:this.functionStartsWith,_signature:[{types:[2]},{types:[2]}]},sum:{_func:this.functionSum,_signature:[{types:[8]}]},to_array:{_func:this.functionToArray,_signature:[{types:[1]}]},to_number:{_func:this.functionToNumber,_signature:[{types:[1]}]},to_string:{_func:this.functionToString,_signature:[{types:[1]}]},trim:{_func:this.functionTrim,_signature:[{types:[2]},{types:[2],optional:true}]},trim_left:{_func:this.functionTrimLeft,_signature:[{types:[2]},{types:[2],optional:true}]},trim_right:{_func:this.functionTrimRight,_signature:[{types:[2]},{types:[2],optional:true}]},type:{_func:this.functionType,_signature:[{types:[1]}]},zip:{_func:this.functionZip,_signature:[{types:[3],variadic:true}]}}}registerFunction(t,e,r,n){let s=this._registerInternal(t,e,r,n);if(!s.success)throw new Error(s.message)}_registerInternal(t,e,r,n={}){if(!t||typeof t!="string"||t.trim()==="")return {success:false,reason:"invalid-name",message:"Function name must be a non-empty string"};try{this.validateInputSignatures(t,r);}catch(l){return {success:false,reason:"invalid-signature",message:l instanceof Error?l.message:"Invalid function signature"}}let{override:s=false,warn:u=false}=n,o=t in this._functionTable;return o&&!s?{success:false,reason:"already-exists",message:`Function already defined: ${t}(). Use { override: true } to replace it.`}:(o&&s&&u&&console.warn(`Warning: Overriding existing function: ${t}()`),this._functionTable[t]={_func:e.bind(this),_signature:r},this._customFunctions.add(t),{success:true,message:o?`Function ${t}() overridden successfully`:`Function ${t}() registered successfully`})}register(t,e,r,n={}){return this._registerInternal(t,e,r,n)}unregister(t){return this._customFunctions.has(t)?(delete this._functionTable[t],this._customFunctions.delete(t),true):false}isRegistered(t){return t in this._functionTable}getRegistered(){return Object.keys(this._functionTable)}getCustomFunctions(){return Array.from(this._customFunctions)}clearCustomFunctions(){for(let t of this._customFunctions)delete this._functionTable[t];this._customFunctions.clear();}callFunction(t,e){let r=this._functionTable[t];if(r===void 0)throw new Error(`Unknown function: ${t}()`);return this.validateArgs(t,e,r._signature),r._func.call(this,e)}validateInputSignatures(t,e){for(let r=0;r<e.length;r+=1)if("variadic"in e[r]&&r!==e.length-1)throw new Error(`Invalid arity: ${t}() 'variadic' argument ${r+1} must occur last`)}validateArgs(t,e,r){this.validateInputSignatures(t,r),this.validateArity(t,e,r),this.validateTypes(t,e,r);}validateArity(t,e,r){let n=r.filter(c=>!(c.optional??false)).length,s=r[r.length-1]?.variadic??false,u=e.length<n,o=e.length>r.length;if(s&&u||!s&&(u||o)){let c=u&&(!s&&n>1||s)?"at least ":"",l=r.length>1;throw new Error(`Invalid arity: ${t}() takes ${c}${n} argument${l&&"s"||""} but received ${e.length}`)}}validateTypes(t,e,r){for(let n=0;n<r.length;n+=1){let s=r[n].types,u=this.getTypeName(e[n]);if(u===void 0)continue;if(!s.some(c=>this.typeMatches(u,c,e[n]))){let c=s.map(l=>this.TYPE_NAME_TABLE[l]).join(" | ");throw new Error(`Invalid type: ${t}() expected argument ${n+1} to be type (${c}) but received type ${this.TYPE_NAME_TABLE[u]} instead.`)}}}typeMatches(t,e,r){if(e===1)return true;if(e===9||e===8||e===10||e===11||e===3){if(e===3)return t===3;if(t===3){let n;e===8?n=0:e===10?n=4:e===9?n=2:e===11&&(n=3);let s=r;for(let u=0;u<s.length;u+=1){let o=this.getTypeName(s[u]);if(o!==void 0&&n!==void 0&&!this.typeMatches(o,n,s[u]))return false}return true}}else return t===e;return false}getTypeName(t){if(t===null)return 7;if(typeof t=="string")return 2;if(typeof t=="number")return 0;if(typeof t=="boolean")return 5;if(Array.isArray(t))return 3;if(typeof t=="object")return t.expref?6:4}createKeyFunction(t,e){let r=this._interpreter;return s=>{let u=r.visit(t,s);if(!e.includes(this.getTypeName(u))){let o=`Invalid type: expected one of (${e.map(c=>this.TYPE_NAME_TABLE[c]).join(" | ")}), received ${this.TYPE_NAME_TABLE[this.getTypeName(u)]}`;throw new Error(o)}return u}}createFindFunction(t){return e=>{let r=e[0],n=e[1],s=e.length>2?e[2]:void 0,u=e.length>3?e[3]:void 0;return t(r,n,s,u)}}createPadFunction(t){return e=>{let r=e[0],n=e[1],s=e.length>2?e[2]:void 0;return t(r,n,s)}}createTrimFunction(t){return e=>{let r=e[0],n=e.length>1?e[1]:void 0;return t(r,n)}}};var m=class i{constructor(){a(this,"inner");a(this,"data",{});}get currentScopeData(){return this.data}withScope(t){let e=new i;return e.inner=this,e.data=t,e}getValue(t){return Object.prototype.hasOwnProperty.call(this.data,t)?this.data[t]:this.inner?this.inner.getValue(t):null}};var ct=new m,v=class i{constructor(){a(this,"runtime");a(this,"_rootValue",null);a(this,"_scope");this.runtime=new A(this),this._scope=new m;}withScope(t){let e=new i;return e.runtime._functionTable=this.runtime._functionTable,e._rootValue=this._rootValue,e._scope=this._scope.withScope(t),e}search(t,e){return this._rootValue=e,this._scope=ct,this.visit(t,e)}visit(t,e){switch(t.type){case "Ternary":{let n=this.visit(t.condition,e);return E(n)?this.visit(t.falseExpr,e):this.visit(t.trueExpr,e)}case "Field":let r=t.name;return e===null||typeof e!="object"||Array.isArray(e)?null:e[r]??null;case "LetExpression":{let{bindings:n,expression:s}=t,u={};return n.forEach(o=>{let c=this.visit(o,e);u={...u,...c};}),this.withScope(u).visit(s,e)}case "Binding":{let{variable:n,reference:s}=t,u=this.visit(s,e);return {[n]:u}}case "Variable":{let n=t.name;if(!this._scope.getValue(n)&&!Object.prototype.hasOwnProperty.call(this._scope.currentScopeData,n))throw new Error(`Error referencing undefined variable ${n}`);return this._scope.getValue(n)}case "IndexExpression":return this.visit(t.right,this.visit(t.left,e));case "Subexpression":{let n=this.visit(t.left,e);return n!=null?this.visit(t.right,n)??null:null}case "Index":{if(!Array.isArray(e))return null;let n=t.value<0?e.length+t.value:t.value;return e[n]??null}case "Slice":{if(!Array.isArray(e)&&typeof e!="string")return null;let{start:n,stop:s,step:u}=this.computeSliceParams(e.length,t);if(typeof e=="string"){let o=[...e];return this.slice(o,n,s,u).join("")}else return this.slice(e,n,s,u)}case "Projection":{let{left:n,right:s}=t,u=false;n.type==="IndexExpression"&&n.right.type==="Slice"&&(u=true);let o=this.visit(n,e);if(u&&typeof o=="string")return this.visit(s,o);if(!Array.isArray(o))return null;let c=[];for(let l of o){let h=this.visit(s,l);h!==null&&c.push(h);}return c}case "ValueProjection":{let{left:n,right:s}=t,u=this.visit(n,e);if(u===null||typeof u!="object"||Array.isArray(u))return null;let o=[],c=Object.values(u);for(let l of c){let h=this.visit(s,l);h!==null&&o.push(h);}return o}case "FilterProjection":{let{left:n,right:s,condition:u}=t,o=this.visit(n,e);if(!Array.isArray(o))return null;let c=[];for(let l of o){let h=this.visit(u,l);if(E(h))continue;let F=this.visit(s,l);F!==null&&c.push(F);}return c}case "Arithmetic":{let n=this.visit(t.left,e),s=this.visit(t.right,e);switch(t.operator){case "Plus":return w(n,s);case "Minus":return M(n,s);case "Multiply":case "Star":return U(n,s);case "Divide":return k(n,s);case "Modulo":return V(n,s);case "Div":return C(n,s);default:throw new Error(`Syntax error: unknown arithmetic operator: ${t.operator}`)}}case "Unary":{let n=this.visit(t.operand,e);switch(t.operator){case "Plus":return _(n),n;case "Minus":return _(n),-n;default:throw new Error(`Syntax error: unknown arithmetic operator: ${t.operator}`)}}case "Comparator":{let n=this.visit(t.left,e),s=this.visit(t.right,e);switch(t.name){case "EQ":return O(n,s);case "NE":return !O(n,s)}if(typeof n!="number"||typeof s!="number")return null;switch(t.name){case "GT":return n>s;case "GTE":return n>=s;case "LT":return n<s;case "LTE":return n<=s}}case "Flatten":{let n=this.visit(t.child,e);return Array.isArray(n)?n.flat():null}case "Root":return this._rootValue;case "MultiSelectList":{let n=[];for(let s of t.children)n.push(this.visit(s,e));return n}case "MultiSelectHash":{let n={};for(let s of t.children)n[s.name]=this.visit(s.value,e);return n}case "OrExpression":{let n=this.visit(t.left,e);return E(n)?this.visit(t.right,e):n}case "AndExpression":{let n=this.visit(t.left,e);return E(n)?n:this.visit(t.right,e)}case "NotExpression":return E(this.visit(t.child,e));case "Literal":return t.value;case "Pipe":return this.visit(t.right,this.visit(t.left,e));case "Function":{let n=[];for(let s of t.children)n.push(this.visit(s,e));return this.runtime.callFunction(t.name,n)}case "ExpressionReference":return {expref:true,...t.child};case "Current":case "Identity":return e}}computeSliceParams(t,e){let{start:r,stop:n,step:s}=e;if(s===null)s=1;else if(s===0){let u=new Error("Invalid value: slice step cannot be 0");throw u.name="RuntimeError",u}return r=r===null?s<0?t-1:0:this.capSliceRange(t,r,s),n=n===null?s<0?-1:t:this.capSliceRange(t,n,s),{start:r,stop:n,step:s}}capSliceRange(t,e,r){let n=e;return n<0?(n+=t,n<0&&(n=r<0?-1:0)):n>=t&&(n=r<0?t-1:t),n}slice(t,e,r,n){let s=[];if(n>0)for(let u=e;u<r;u+=n)s.push(t[u]);else for(let u=e;u>r;u+=n)s.push(t[u]);return s}},pt=new v,T=pt;var lt=1,ht=3,Ne=11,Tt=8,Re=10,_t=9,gt=5,mt=6,Et=7,Ot=0,ft=4,Nt=2;function Rt(i,t){return Y.parse(i,t)}function dt(i,t){return y.tokenize(i,t)}var yt=(i,t,e,r)=>{T.runtime.registerFunction(i,t,e,r);},At=(i,t,e,r)=>T.runtime.register(i,t,e,r),St=i=>T.runtime.unregister(i),It=i=>T.runtime.isRegistered(i),xt=()=>T.runtime.getRegistered(),Pt=()=>T.runtime.getCustomFunctions(),bt=()=>{T.runtime.clearCustomFunctions();};function Yt(i,t,e){let r=Y.parse(t,e);return T.search(r,i)}function de(){return new m}var Kt=T,ye={compile:Rt,registerFunction:yt,register:At,unregisterFunction:St,isRegistered:It,getRegisteredFunctions:xt,getCustomFunctions:Pt,clearCustomFunctions:bt,search:Yt,tokenize:dt,TreeInterpreter:Kt,TYPE_ANY:lt,TYPE_ARRAY_NUMBER:Tt,TYPE_ARRAY_STRING:_t,TYPE_ARRAY:ht,TYPE_BOOLEAN:gt,TYPE_EXPREF:mt,TYPE_NULL:Et,TYPE_NUMBER:Ot,TYPE_OBJECT:ft,TYPE_STRING:Nt};export{de as Scope,lt as TYPE_ANY,ht as TYPE_ARRAY,Ne as TYPE_ARRAY_ARRAY,Tt as TYPE_ARRAY_NUMBER,Re as TYPE_ARRAY_OBJECT,_t as TYPE_ARRAY_STRING,gt as TYPE_BOOLEAN,mt as TYPE_EXPREF,Et as TYPE_NULL,Ot as TYPE_NUMBER,ft as TYPE_OBJECT,Nt as TYPE_STRING,Kt as TreeInterpreter,bt as clearCustomFunctions,Rt as compile,ye as default,Pt as getCustomFunctions,xt as getRegisteredFunctions,It as isRegistered,ye as jmespath,At as register,yt as registerFunction,Yt as search,dt as tokenize,St as unregisterFunction};//# sourceMappingURL=index.esm.min.js.map
//# sourceMappingURL=index.esm.min.js.map