@coldsmirk/abacus-core 0.4.0 → 0.4.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/dist/index.cjs CHANGED
@@ -1,2 +1,1040 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=class extends Error{expression;constructor(e,t,n){super(e,{cause:n}),this.name=`ExpressionError`,this.expression=t}},t=class extends e{constructor(e=`Expression engine is not initialized. Await loadEngine() or render under <ExpressionEngineProvider>.`){super(e),this.name=`ExpressionNotReadyError`}};function n(e){return e===void 0}function r(e){return typeof e==`string`}function i(e){return Array.isArray(e)}function a(e){return e==null}function o(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}let s=null,c=null,l=null,u,d=null;function f(t,n){try{return n()}catch(n){throw new e(`Failed to evaluate expression: ${t}`,t,n)}}function p(){let e=`Failed to load the ZEN expression engine`;return typeof window>`u`?`${e}. In a non-browser or non-DOM host (Node, SSR, Web Worker) the wasm cannot be auto-resolved; call configureEngine({ wasmInput }) with the wasm bytes or URL before loading.`:e}function m(t){if(s||c)throw new e(`configureEngine() must be called before the engine loads.`);u=t.wasmInput}function h(){return s||(l=null,s=(async()=>{let e=await import(`@gorules/zen-engine-wasm`);await e.default(n(u)?void 0:{module_or_path:u});let t=t=>e.VariableType.fromJson(t),r=e=>{if(d&&d.variables===e)return d;let n=d;d=null,n?.handle.free();let r=t(e);try{d={variables:e,handle:r,rootKind:r.toJson()}}catch(e){throw r.free(),e}return d},i=Object.freeze({evaluate:(t,n={})=>f(t,()=>e.evaluateExpression(t,n)),evaluateUnary:(t,n={})=>f(t,()=>e.evaluateUnaryExpression(t,n)),validate:t=>e.validateExpression(t),validateUnary:t=>e.validateUnaryExpression(t),getCompletions:()=>e.getCompletions(),analyze:(e,t,n)=>{let i=r(e),a=n?i.handle.typeCheckUnary(t):i.handle.typeCheck(t);return{rootKind:i.rootKind,spans:Array.isArray(a)?a:[]}},satisfies:(e,n)=>{let r=t(e);try{let e=t(n);try{return r.satisfies(e)}finally{e.free()}}finally{r.free()}},isReady:()=>e.isReady()});return c=i,i})().catch(t=>{throw s=null,l=new e(p(),void 0,t),l}),s)}function g(){return c?.isReady()??!1}function _(){return l}function v(){if(!c)throw new t;return c}function ee(){d?.handle.free(),d=null,s=null,c=null,l=null,u=void 0}const y=te();function te(){return typeof process>`u`?!1:process.env?process.env.NODE_ENV!==`production`:!1}const ne=/^[A-Z_$][\w$]*(?:\.[A-Z_$][\w$]*|\[\d+\])*$/i,re=new Set([`and`,`or`,`not`,`in`,`true`,`false`,`null`]);function b(e){return ne.test(e)&&(e.match(/[A-Z_$][\w$]*/gi)??[]).every(e=>!re.has(e))}function x(t){if(a(t))return`null`;if(typeof t==`number`){if(!Number.isFinite(t))throw new e(`Number ${String(t)} has no ZEN literal representation`);return String(t)}if(typeof t==`boolean`||typeof t==`bigint`)return String(t);if(r(t))return ie(t);if(i(t))return`[${t.map(e=>x(e)).join(`, `)}]`;throw new e(`Value of type "${typeof t}" has no ZEN literal representation`)}function ie(t){let n=t.includes(`'`),r=t.includes(`"`);if(n&&r)throw new e(`String contains both single and double quotes and has no ZEN literal representation`);return n?`"${t}"`:`'${t}'`}function S(e){return i(e)?x(e):`[${x(e)}]`}function C(e){return`(${e} == null or (type(${e}) == 'string' and len(trim(${e})) == 0) or (type(${e}) == 'array' and len(${e}) == 0))`}function ae(t,n,r){switch(n){case`eq`:return`${t} == ${x(r)}`;case`ne`:return`${t} != ${x(r)}`;case`gt`:return`${t} > ${x(r)}`;case`gte`:return`${t} >= ${x(r)}`;case`lt`:return`${t} < ${x(r)}`;case`lte`:return`${t} <= ${x(r)}`;case`contains`:return`contains(${t}, ${x(r)})`;case`not_contains`:return`not contains(${t}, ${x(r)})`;case`starts_with`:return`startsWith(${t}, ${x(r)})`;case`ends_with`:return`endsWith(${t}, ${x(r)})`;case`in`:return`${t} in ${S(r)}`;case`not_in`:return`not (${t} in ${S(r)})`;case`is_empty`:return C(t);case`is_not_empty`:return`not ${C(t)}`;default:throw new e(`Unsupported operator: ${String(n)}`)}}function w(e){if(e.kind===`expression`){let t=e.expression.trim();return t===``?null:`(${t})`}let t=e.subject.trim();if(!b(t))return null;try{return ae(t,e.operator,e.value)}catch{return null}}function T(e){let t=e.conditions.map(e=>w(e)).filter(e=>e!==null);return t.length===0?null:t.join(` and `)}function E(e){let t=(e.conditionGroups??[]).map(e=>T(e)).filter(e=>e!==null);return t.length===0?null:t.map(e=>`(${e})`).join(` or `)}function D(e,t,n){let r=e.toSorted((e,t)=>e.priority-t.priority);for(let e of r){if(e.isDefault)continue;let r=E(e);if(r===null){y&&console.warn(`[expression] branch "${e.id}" has no compilable condition and can never match`);continue}if(oe(n,r,t))return{branchId:e.id,matched:!0}}return{branchId:r.find(e=>e.isDefault)?.id??null,matched:!1}}function oe(e,t,n){try{return e.evaluate(t,n)===!0}catch(n){return y&&se(e,t,n),!1}}function se(e,t,n){let r;try{r=e.validate(t)}catch{return}a(r)||console.warn(`[expression] compiled branch expression failed to parse: ${t}`,r,n)}async function ce(e,t){return D(e,t,await h())}const O=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`not_contains`,`starts_with`,`ends_with`,`in`,`not_in`,`is_empty`,`is_not_empty`],le={eq:`scalar`,ne:`scalar`,gt:`scalar`,gte:`scalar`,lt:`scalar`,lte:`scalar`,contains:`scalar`,not_contains:`scalar`,starts_with:`scalar`,ends_with:`scalar`,in:`array`,not_in:`array`,is_empty:`none`,is_not_empty:`none`};function k(e){return le[e]}function ue(e){let t=A(e);return t===null?``:j(t,!0)}function A(e){if(e.kind===`rule`)return M(e)===null?null:e;let t=e.items.map(e=>A(e)).filter(e=>e!==null);return t.length===0?null:t.length===1?t[0]:{kind:`group`,op:e.op,items:t}}function j(e,t){if(e.kind===`rule`)return M(e);let n=e.items.map(e=>j(e,!1)).join(e.op===`and`?` and `:` or `);return t?n:`(${n})`}function M(e){return de(e)?w({kind:`field`,subject:e.left,operator:e.operator,value:e.right}):null}function de(e){switch(k(e.operator)){case`scalar`:return N(e.right);case`array`:return fe(e.right);case`none`:return e.right===void 0}}function N(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function fe(e){return i(e)&&e.every(e=>N(e))}const pe=new Set([`==`,`!=`,`<=`,`>=`]),me=new Set([`(`,`)`,`[`,`]`,`,`,`.`,`<`,`>`,`-`]),he=/[a-z_$]/i,ge=/[\w$]/,_e=/\d/,ve=/^\d+(?:\.\d+)?(?:e[+-]?\d+)?/i,ye=/^\d+$/,be={"==":`eq`,"!=":`ne`,">":`gt`,">=":`gte`,"<":`lt`,"<=":`lte`},xe={contains:`contains`,startsWith:`starts_with`,endsWith:`ends_with`};function Se(e){let t=L(e);if(t===null||t.length===0)return null;let n=0;function r(e=0){return t[n+e]}function i(e){let t=r();return t!==void 0&&t.kind===`punct`&&t.value===e?(n+=1,!0):!1}function a(e){let t=r();return t!==void 0&&t.kind===`ident`&&t.value===e?(n+=1,!0):!1}function o(e,n){for(let[r,i]of n.entries()){let n=t[e+r],a=i;if(n===void 0||n.kind!==a.kind||n.value!==a.value)return!1}return!0}function s(){let e=P(t,n);return e===null?null:(n=e.next,e.path)}function c(){let e=r();if(e===void 0)return null;if(e.kind===`string`)return n+=1,e.value;if(e.kind===`number`)return n+=1,Number(e.value);if(e.kind===`ident`)return e.value===`true`?(n+=1,!0):e.value===`false`?(n+=1,!1):null;if(e.kind===`punct`&&e.value===`-`){let e=r(1);return e===void 0||e.kind!==`number`?null:(n+=2,-Number(e.value))}return null}function l(){if(!i(`[`))return null;if(I(r(),`]`))return n+=1,[];let e=c();if(e===null)return null;let t=[e];for(;I(r(),`,`);){n+=1;let e=c();if(e===null)return null;t.push(e)}return i(`]`)?t:null}function u(e){if(!i(`(`))return null;let t=s();if(t===null||!i(`,`))return null;let n=c();return n===null||!i(`)`)?null:{kind:`rule`,left:t,operator:e,right:n}}function d(){let e=s();if(e===null||!a(`in`))return null;let t=l();return t===null||!i(`)`)?null:{kind:`rule`,left:e,operator:`not_in`,right:t}}function f(){let e=r();if(e===void 0)return null;let i,a;if(e.kind===`ident`&&e.value===`not`&&I(r(1),`(`))i=`is_not_empty`,a=n+2;else if(e.kind===`punct`&&e.value===`(`)i=`is_empty`,a=n+1;else return null;let s=P(t,a);if(s===null)return null;let c=w({kind:`field`,subject:s.path,operator:i,value:void 0});if(c===null)return null;let l=L(c);return l===null||!o(n,l)?null:(n+=l.length,{kind:`rule`,left:s.path,operator:i})}function p(){let e=r();if(e===void 0||e.kind!==`ident`)return null;if(e.value===`not`){let e=r(1);return e===void 0?null:e.kind===`ident`&&e.value===`contains`&&I(r(2),`(`)?(n+=2,u(`not_contains`)):e.kind===`punct`&&e.value===`(`?(n+=2,d()):null}if(I(r(1),`(`)){let t=xe[e.value];return t===void 0?null:(n+=1,u(t))}let t=s();if(t===null)return null;let i=r();if(i===void 0)return null;if(i.kind===`ident`&&i.value===`in`){n+=1;let e=l();return e===null?null:{kind:`rule`,left:t,operator:`in`,right:e}}if(i.kind===`punct`){let e=be[i.value];if(e===void 0)return null;n+=1;let r=c();return r===null?null:{kind:`rule`,left:t,operator:e,right:r}}return null}function m(e){let t=f();if(t!==null)return t;if(I(r(),`(`)){if(e>=64)return null;n+=1;let t=g(e+1);return t===null||!i(`)`)?null:F(t)}return p()}function h(){let e=r();return e!==void 0&&e.kind===`ident`&&(e.value===`and`||e.value===`or`)?e.value:null}function g(e){let t=m(e);if(t===null)return null;let r=[t],i=null,a=h();for(;a!==null;){if(i===null)i=a;else if(i!==a)return null;n+=1;let t=m(e);if(t===null)return null;r.push(t),a=h()}return r.length===1?r[0]:{kind:`group`,op:i??`and`,items:r}}let _=g(0);return _===null||n!==t.length?null:F(_)}function P(e,t){let n=e[t];if(n===void 0||n.kind!==`ident`)return null;let r=n.value,i=t+1,a=e[i];for(;a!==void 0&&a.kind===`punct`&&(a.value===`.`||a.value===`[`);){if(a.value===`.`){let t=e[i+1];if(t===void 0||t.kind!==`ident`)return null;r+=`.${t.value}`,i+=2}else{let t=e[i+1];if(t===void 0||t.kind!==`number`||!ye.test(t.value))return null;let n=e[i+2];if(n===void 0||n.kind!==`punct`||n.value!==`]`)return null;r+=`[${t.value}]`,i+=3}a=e[i]}return b(r)?{path:r,next:i}:null}function F(e){return e.kind===`group`?e:{kind:`group`,op:`and`,items:[e]}}function I(e,t){return e!==void 0&&e.kind===`punct`&&e.value===t}function L(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r===` `||r===` `||r===`
2
- `||r===`\r`){n+=1;continue}if(r===`'`||r===`"`){let i=e.indexOf(r,n+1);if(i===-1)return null;t.push({kind:`string`,value:e.slice(n+1,i)}),n=i+1;continue}let i=e.slice(n,n+2);if(pe.has(i)){t.push({kind:`punct`,value:i}),n+=2;continue}if(me.has(r)){t.push({kind:`punct`,value:r}),n+=1;continue}if(_e.test(r)){let r=ve.exec(e.slice(n));if(r===null)return null;t.push({kind:`number`,value:r[0]}),n+=r[0].length;continue}if(he.test(r)){let r=n+1;for(;r<e.length&&ge.test(e[r]);)r+=1;t.push({kind:`ident`,value:e.slice(n,r)}),n=r;continue}return null}return t}const Ce=O;async function we(e,t){return await h(),R(e,t)}async function Te(e,t){return await h(),z(e,t)}function R(e,t){return v().evaluate(e,t)}function z(e,t){return v().evaluateUnary(e,t)}const Ee={"Returns the length of variable":`返回变量的长度`,"Checks if variable contains a needle":`检查变量是否包含指定元素`,"Flattens an array":`将数组扁平化`,"Merges multiple objects into one.":`将多个对象合并为一个。`,"Deeply merges multiple objects into one.":`将多个对象深度合并为一个。`,"Converts all characters in a string to uppercase":`将字符串中所有字符转换为大写`,"Converts all characters in a string to lowercase":`将字符串中所有字符转换为小写`,"Returns the string with leading and trailing whitespace removed":`返回去除首尾空白后的字符串`,"Returns true if the string starts with the specified prefix":`若字符串以指定前缀开头则返回 true`,"Returns true if the string ends with the specified suffix":`若字符串以指定后缀结尾则返回 true`,"Returns true if the string matches the specified pattern":`若字符串匹配指定模式则返回 true`,"Extracts matching substrings according to a pattern":`按模式提取匹配的子串`,"Performs a fuzzy search of the needle in the haystack, and returns the match score(s).":`在目标中对关键字进行模糊搜索,并返回匹配得分。`,"Splits a string into an array of substrings using the specified delimiter.":`使用指定分隔符将字符串拆分为子串数组。`,"Returns the absolute value of a number":`返回数字的绝对值`,"Returns the sum of all elements in the input array.":`返回输入数组中所有元素之和。`,"Calculates the average of all elements in the input array.":`计算输入数组中所有元素的平均值。`,"Returns the smallest of the elements in the input array.":`返回输入数组中的最小元素。`,"Returns the largest of the elements in the input array.":`返回输入数组中的最大元素。`,"Generates a random number between 0 (inclusive) and max (inclusive).":`生成 0 到 max(均包含)之间的随机数。`,"Calculates the median value of all elements in the input array.":`计算输入数组中所有元素的中位数。`,"Finds the mode(s) of the input array, which are the most frequent element(s).":`求输入数组的众数,即出现最频繁的元素。`,"Rounds a number down to the nearest integer.":`向下取整到最接近的整数。`,"Rounds a number up to the nearest integer.":`向上取整到最接近的整数。`,"Rounds a number to a specified number of decimal places.":`将数字四舍五入到指定的小数位数。`,"Truncates a number to a specified number of decimal places.":`将数字截断到指定的小数位数。`,"Checks if the given value is of a numeric type.":`检查给定值是否为数值类型。`,"Converts the given value to a string.":`将给定值转换为字符串。`,"Converts the given value to a number.":`将给定值转换为数字。`,"Converts the given value to a boolean.":`将给定值转换为布尔值。`,"Returns a string representing the data type of the value.":`返回表示该值数据类型的字符串。`,"Returns an array of a given object's own enumerable property names.":`返回由给定对象自身可枚举属性名组成的数组。`,"Returns an array of a given object's own enumerable property values.":`返回由给定对象自身可枚举属性值组成的数组。`,"Returns a new date time instance.":`返回一个新的日期时间实例。`,"Converts a numeric timestamp to a unix timestamp.":`将数值时间戳转换为 Unix 时间戳。`,"Extracts the time from a numeric timestamp and returns it as a seconds from beginning of day.":`从数值时间戳中提取时间,以当天起始的秒数返回。`,"e.g. 1h30min":`例如 1h30min`,"Extracts the year from a given timestamp.":`从给定时间戳中提取年份。`,"Gets the day of the week from a given timestamp, where Sunday might be 0.":`获取给定时间戳的星期几(周日可能为 0)。`,"Extracts the day of the month from a given timestamp.":`从给定时间戳中提取当月的日期。`,"Gets the day of the year from a given timestamp.":`获取给定时间戳在一年中的第几天。`,"Calculates the week of the year from a given timestamp.":`计算给定时间戳在一年中的第几周。`,"Extracts the month from a given timestamp, typically with January as 1.":`从给定时间戳中提取月份(通常 1 月为 1)。`,"Converts the month from a given timestamp into its string representation (e.g., 'Jan').":`将给定时间戳的月份转换为字符串表示(例如 'Jan')。`,"Converts a timestamp to a human-readable date string.":`将时间戳转换为人类可读的日期字符串。`,"Converts the day of the week from a given timestamp into its string representation (e.g., 'Mon').":`将给定时间戳的星期几转换为字符串表示(例如 'Mon')。`,"Returns the timestamp representing the start of a specified unit (e.g., day, month, year) based on a given timestamp.":`返回给定时间戳在指定单位(如日、月、年)起始处的时间戳。`,"Returns the timestamp representing the end of a specified unit (e.g., day, month, year) based on a given timestamp.":`返回给定时间戳在指定单位(如日、月、年)结束处的时间戳。`,"Checks if all elements in the array satisfy the condition defined in the callback.":`检查数组中所有元素是否都满足回调中定义的条件。`,"Checks if no elements in the array satisfy the condition defined in the callback.":`检查数组中是否没有任何元素满足回调中定义的条件。`,"Checks if at least one element in the array satisfies the condition defined in the callback.":`检查数组中是否至少有一个元素满足回调中定义的条件。`,"Checks if exactly one element in the array satisfies the condition defined in the callback.":`检查数组中是否恰好有一个元素满足回调中定义的条件。`,"Creates a new array with all elements that satisfy the condition defined in the callback.":`创建一个仅包含满足回调中定义条件的元素的新数组。`,"Creates a new array populated with the results of calling the provided function on every element in the calling array.":`创建一个新数组,其元素为对原数组每个元素调用所提供函数的结果。`,"First maps each element using a mapping function, then flattens the result into a new array.":`先用映射函数处理每个元素,再将结果扁平化为新数组。`,"Counts the number of elements in the array that satisfy the condition defined in the callback.":`统计数组中满足回调中定义条件的元素个数。`,"Adds time to a date":`为日期增加时间`,"Subtracts time from a date":`从日期中减去时间`,"Sets a specific unit of time on a date":`设置日期的某个时间单位`,"Formats a date into a string representation":`将日期格式化为字符串`,"Returns the start of a specified time unit for a date":`返回日期在指定时间单位上的起始`,"Returns the end of a specified time unit for a date":`返回日期在指定时间单位上的结束`,"Calculates the difference between two dates":`计算两个日期之间的差值`,"Converts a date to a different timezone":`将日期转换到不同的时区`,"Checks if two dates are the same":`检查两个日期是否相同`,"Checks if a date is before another date":`检查日期是否早于另一个日期`,"Checks if a date is after another date":`检查日期是否晚于另一个日期`,"Checks if a date is the same as or before another date":`检查日期是否等于或早于另一个日期`,"Checks if a date is the same as or after another date":`检查日期是否等于或晚于另一个日期`,"Gets the seconds of a date":`获取日期的秒`,"Gets the minutes of a date":`获取日期的分钟`,"Gets the hours of a date":`获取日期的小时`,"Gets the day of the month for a date":`获取日期在当月的第几天`,"Gets the day of the year for a date":`获取日期在当年的第几天`,"Gets the week of the year for a date":`获取日期在当年的第几周`,"Gets the day of the week for a date":`获取日期的星期几`,"Gets the month for a date":`获取日期的月份`,"Gets the quarter for a date":`获取日期所在的季度`,"Gets the year for a date":`获取日期的年份`,"Gets the Unix timestamp for a date":`获取日期的 Unix 时间戳`,"Gets the timezone offset name for a date":`获取日期的时区偏移名称`,"Checks if a date is valid":`检查日期是否有效`,"Checks if a date is yesterday":`检查日期是否为昨天`,"Checks if a date is today":`检查日期是否为今天`,"Checks if a date is tomorrow":`检查日期是否为明天`,"Checks if the year of a date is a leap year":`检查日期所在年份是否为闰年`},De={lexerError:`Lexer error`,parserError:`Parser error`,compilerError:`Compiler error`,vmError:`VM error`},Oe={lexerError:`词法错误`,parserError:`语法错误`,compilerError:`编译错误`,vmError:`运行时错误`};function B(e,t,n){return(n===void 0?void 0:e[n])??t}const V={sourceLabel:e=>B(De,`Error`,e),completionInfo:e=>e,typeCheckSource:`Type check`,expectedBoolean:e=>`Expected a boolean test expression, received \`${e}\`.`,expectedType:(e,t)=>`Expected \`${e}\`, received \`${t}\`.`},H={sourceLabel:e=>B(Oe,`错误`,e),completionInfo:e=>e===``?``:Ee[e]??e,typeCheckSource:`类型检查`,expectedBoolean:e=>`期望布尔测试表达式,实际类型为 \`${e}\`。`,expectedType:(e,t)=>`期望 \`${e}\`,实际为 \`${t}\`。`},U=new Map([[`en-US`,V],[`zh-CN`,H]]);let W=V;function ke(e,t){U.set(e,t)}function Ae({locale:e,messages:t}){let n=e===void 0?W:U.get(e)??W;W=t===void 0?n:{...n,...t}}function G(){return W}function K(e){let t=e?.trim();return t?Number(t):NaN}function je(e){let t=e.split(` at `),n=t.length<=1?void 0:t.at(-1);if(n===void 0)return null;let[r,i]=n.replace(`(`,``).replace(`)`,``).split(`, `),a=K(r);if(Number.isNaN(a))return null;let o=K(i);return[a,Number.isNaN(o)?a:o]}function Me(e,t){if(e==null)return null;let n=o(e)&&typeof e.type==`string`?e.type:void 0,r=o(e)&&typeof e.source==`string`?e.source:String(e),[i,a]=je(r)??[0,t.length];return{from:i,to:a,message:r,source:G().sourceLabel(n)}}function Ne(e){if(!Array.isArray(e))return[];let t=G();return e.flatMap(e=>!o(e)||typeof e.label!=`string`||e.label===``?[]:[{type:e.type===`method`||e.type===`variable`?e.type:`function`,label:e.label,detail:typeof e.detail==`string`?e.detail.replaceAll("`",``):``,info:t.completionInfo(typeof e.info==`string`?e.info:``),boost:typeof e.boost==`number`?e.boost:null,methodFor:typeof e.methodFor==`string`?e.methodFor:null}])}async function Pe(e,t){return await h(),q(e,t)}function q(e,t){let n=v();return Me(t===`unary`?n.validateUnary(e):n.validate(e),e)}async function Fe(){return await h(),J()}function J(){return Ne(v().getCompletions())}async function Ie(e,t,n){return await h(),Y(e,t,n)}function Y(e,t,n){return v().analyze(e,t,n===`unary`)}async function Le(e,t){return await h(),X(e,t)}function X(e,t){return v().satisfies(e,t)}const Z=/\{\{(?<expression>[^{}]*)\}\}/g;function Q(e){let t=[];Z.lastIndex=0;for(let n=Z.exec(e);n!==null;n=Z.exec(e)){let e=n.groups?.expression??``,r=n.index+2;t.push({from:r,to:r+e.length,expression:e})}return t}function Re(e,t){return Q(e).find(e=>t>=e.from&&t<=e.to)??null}function ze(e){return e.expression.trim().length>0}function Be(e,n){if(!g())throw new t;let r=[];for(let t of Q(n))if(ze(t))try{for(let n of Y(e,t.expression,`standard`).spans)r.push({...n,span:[n.span[0]+t.from,n.span[1]+t.from]})}catch{}return{rootKind:e,spans:r}}async function Ve(e,t){return await h(),Be(e,t)}function $(e){if(!g())throw new t;let n=[];for(let t of Q(e)){if(!ze(t))continue;let e=q(t.expression,`standard`);e&&n.push({...e,from:e.from+t.from,to:e.to+t.from})}return n}async function He(e){return await h(),$(e)}exports.CONDITION_OPERATORS=O,exports.CONDITION_TREE_OPERATORS=Ce,exports.ExpressionError=e,exports.ExpressionNotReadyError=t,exports.analyzeTemplate=Ve,exports.analyzeTemplateSync=Be,exports.analyzeTypes=Ie,exports.analyzeTypesSync=Y,exports.compileBranch=E,exports.compileCondition=w,exports.compileConditionTree=ue,exports.compileGroup=T,exports.conditionOperatorArity=k,exports.configureEngine=m,exports.configureExpressionMessages=Ae,exports.enMessages=V,exports.evaluate=we,exports.evaluateSync=R,exports.evaluateUnary=Te,exports.evaluateUnarySync=z,exports.getCompletionItems=Fe,exports.getCompletionItemsSync=J,exports.getDiagnostics=Pe,exports.getDiagnosticsSync=q,exports.getEngineError=_,exports.getEngineSync=v,exports.getExpressionMessages=G,exports.getTemplateDiagnostics=He,exports.getTemplateDiagnosticsSync=$,exports.isEngineReady=g,exports.liftConditionTree=Se,exports.loadEngine=h,exports.parseTemplateHoles=Q,exports.registerExpressionLocale=ke,exports.resetEngine=ee,exports.satisfiesType=Le,exports.satisfiesTypeSync=X,exports.selectBranch=ce,exports.selectBranchWith=D,exports.templateHoleAt=Re,exports.toZenLiteral=x,exports.zhCNMessages=H;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/engine/errors.ts
3
+ var ExpressionError = class extends Error {
4
+ expression;
5
+ constructor(message, expression, cause) {
6
+ super(message, { cause });
7
+ this.name = "ExpressionError";
8
+ this.expression = expression;
9
+ }
10
+ };
11
+ var ExpressionNotReadyError = class extends ExpressionError {
12
+ constructor(message = "Expression engine is not initialized. Await loadEngine() or render under <ExpressionEngineProvider>.") {
13
+ super(message);
14
+ this.name = "ExpressionNotReadyError";
15
+ }
16
+ };
17
+ //#endregion
18
+ //#region src/internal/predicates.ts
19
+ function isUndefined(value) {
20
+ return value === void 0;
21
+ }
22
+ function isString(value) {
23
+ return typeof value === "string";
24
+ }
25
+ function isArray(value) {
26
+ return Array.isArray(value);
27
+ }
28
+ function isNullish(value) {
29
+ return value === null || value === void 0;
30
+ }
31
+ function isRecord(value) {
32
+ return typeof value === "object" && value !== null && !Array.isArray(value);
33
+ }
34
+ //#endregion
35
+ //#region src/engine/loader.ts
36
+ let enginePromise = null;
37
+ let engineSync = null;
38
+ let engineError = null;
39
+ let configuredInput;
40
+ let typeContextCache = null;
41
+ function evaluateSafely(expression, run) {
42
+ try {
43
+ return run();
44
+ } catch (error) {
45
+ throw new ExpressionError(`Failed to evaluate expression: ${expression}`, expression, error);
46
+ }
47
+ }
48
+ function loadFailureMessage() {
49
+ const base = "Failed to load the ZEN expression engine";
50
+ if (typeof window === "undefined") return `${base}. In a non-browser or non-DOM host (Node, SSR, Web Worker) the wasm cannot be auto-resolved; call configureEngine({ wasmInput }) with the wasm bytes or URL before loading.`;
51
+ return base;
52
+ }
53
+ function configureEngine(options) {
54
+ if (enginePromise || engineSync) throw new ExpressionError("configureEngine() must be called before the engine loads.");
55
+ configuredInput = options.wasmInput;
56
+ }
57
+ function loadEngine() {
58
+ if (enginePromise) return enginePromise;
59
+ engineError = null;
60
+ enginePromise = (async () => {
61
+ const zen = await import("@gorules/zen-engine-wasm");
62
+ await zen.default(isUndefined(configuredInput) ? void 0 : { module_or_path: configuredInput });
63
+ const toVariableType = (type) => zen.VariableType.fromJson(type);
64
+ const ensureTypeContext = (variables) => {
65
+ if (typeContextCache && typeContextCache.variables === variables) return typeContextCache;
66
+ const stale = typeContextCache;
67
+ typeContextCache = null;
68
+ stale?.handle.free();
69
+ const handle = toVariableType(variables);
70
+ try {
71
+ typeContextCache = {
72
+ variables,
73
+ handle,
74
+ rootKind: handle.toJson()
75
+ };
76
+ } catch (error) {
77
+ handle.free();
78
+ throw error;
79
+ }
80
+ return typeContextCache;
81
+ };
82
+ const engine = Object.freeze({
83
+ evaluate: (expression, context = {}) => evaluateSafely(expression, () => zen.evaluateExpression(expression, context)),
84
+ evaluateUnary: (expression, context = {}) => evaluateSafely(expression, () => zen.evaluateUnaryExpression(expression, context)),
85
+ validate: (expression) => zen.validateExpression(expression),
86
+ validateUnary: (expression) => zen.validateUnaryExpression(expression),
87
+ getCompletions: () => zen.getCompletions(),
88
+ analyze: (variables, source, unary) => {
89
+ const context = ensureTypeContext(variables);
90
+ const rawSpans = unary ? context.handle.typeCheckUnary(source) : context.handle.typeCheck(source);
91
+ return {
92
+ rootKind: context.rootKind,
93
+ spans: Array.isArray(rawSpans) ? rawSpans : []
94
+ };
95
+ },
96
+ satisfies: (actual, expected) => {
97
+ const actualType = toVariableType(actual);
98
+ try {
99
+ const expectedType = toVariableType(expected);
100
+ try {
101
+ return actualType.satisfies(expectedType);
102
+ } finally {
103
+ expectedType.free();
104
+ }
105
+ } finally {
106
+ actualType.free();
107
+ }
108
+ },
109
+ isReady: () => zen.isReady()
110
+ });
111
+ engineSync = engine;
112
+ return engine;
113
+ })().catch((error) => {
114
+ enginePromise = null;
115
+ engineError = new ExpressionError(loadFailureMessage(), void 0, error);
116
+ throw engineError;
117
+ });
118
+ return enginePromise;
119
+ }
120
+ function isEngineReady() {
121
+ return engineSync?.isReady() ?? false;
122
+ }
123
+ function getEngineError() {
124
+ return engineError;
125
+ }
126
+ function getEngineSync() {
127
+ if (!engineSync) throw new ExpressionNotReadyError();
128
+ return engineSync;
129
+ }
130
+ function resetEngine() {
131
+ typeContextCache?.handle.free();
132
+ typeContextCache = null;
133
+ enginePromise = null;
134
+ engineSync = null;
135
+ engineError = null;
136
+ configuredInput = void 0;
137
+ }
138
+ //#endregion
139
+ //#region src/internal/env.ts
140
+ const isDev = detectDev();
141
+ function detectDev() {
142
+ if (typeof process === "undefined") return false;
143
+ return process.env ? process.env.NODE_ENV !== "production" : false;
144
+ }
145
+ //#endregion
146
+ //#region src/condition/subject.ts
147
+ const SUBJECT_PATTERN = /^[A-Z_$][\w$]*(?:\.[A-Z_$][\w$]*|\[\d+\])*$/i;
148
+ const ZEN_RESERVED_WORDS = new Set([
149
+ "and",
150
+ "or",
151
+ "not",
152
+ "in",
153
+ "true",
154
+ "false",
155
+ "null"
156
+ ]);
157
+ function isIdentifierPath(subject) {
158
+ return SUBJECT_PATTERN.test(subject) && (subject.match(/[A-Z_$][\w$]*/gi) ?? []).every((segment) => !ZEN_RESERVED_WORDS.has(segment));
159
+ }
160
+ //#endregion
161
+ //#region src/condition/compile.ts
162
+ function toZenLiteral(value) {
163
+ if (isNullish(value)) return "null";
164
+ if (typeof value === "number") {
165
+ if (!Number.isFinite(value)) throw new ExpressionError(`Number ${String(value)} has no ZEN literal representation`);
166
+ return String(value);
167
+ }
168
+ if (typeof value === "boolean" || typeof value === "bigint") return String(value);
169
+ if (isString(value)) return encodeZenString(value);
170
+ if (isArray(value)) return `[${value.map((item) => toZenLiteral(item)).join(", ")}]`;
171
+ throw new ExpressionError(`Value of type "${typeof value}" has no ZEN literal representation`);
172
+ }
173
+ function encodeZenString(value) {
174
+ const hasSingle = value.includes("'");
175
+ const hasDouble = value.includes("\"");
176
+ if (hasSingle && hasDouble) throw new ExpressionError("String contains both single and double quotes and has no ZEN literal representation");
177
+ return hasSingle ? `"${value}"` : `'${value}'`;
178
+ }
179
+ function toArrayLiteral(value) {
180
+ return isArray(value) ? toZenLiteral(value) : `[${toZenLiteral(value)}]`;
181
+ }
182
+ function zenIsEmpty(subject) {
183
+ return `(${subject} == null or (type(${subject}) == 'string' and len(trim(${subject})) == 0) or (type(${subject}) == 'array' and len(${subject}) == 0))`;
184
+ }
185
+ function compileFieldCondition(subject, operator, value) {
186
+ switch (operator) {
187
+ case "eq": return `${subject} == ${toZenLiteral(value)}`;
188
+ case "ne": return `${subject} != ${toZenLiteral(value)}`;
189
+ case "gt": return `${subject} > ${toZenLiteral(value)}`;
190
+ case "gte": return `${subject} >= ${toZenLiteral(value)}`;
191
+ case "lt": return `${subject} < ${toZenLiteral(value)}`;
192
+ case "lte": return `${subject} <= ${toZenLiteral(value)}`;
193
+ case "contains": return `contains(${subject}, ${toZenLiteral(value)})`;
194
+ case "not_contains": return `not contains(${subject}, ${toZenLiteral(value)})`;
195
+ case "starts_with": return `startsWith(${subject}, ${toZenLiteral(value)})`;
196
+ case "ends_with": return `endsWith(${subject}, ${toZenLiteral(value)})`;
197
+ case "in": return `${subject} in ${toArrayLiteral(value)}`;
198
+ case "not_in": return `not (${subject} in ${toArrayLiteral(value)})`;
199
+ case "is_empty": return zenIsEmpty(subject);
200
+ case "is_not_empty": return `not ${zenIsEmpty(subject)}`;
201
+ default: throw new ExpressionError(`Unsupported operator: ${String(operator)}`);
202
+ }
203
+ }
204
+ function compileCondition(condition) {
205
+ if (condition.kind === "expression") {
206
+ const expression = condition.expression.trim();
207
+ return expression === "" ? null : `(${expression})`;
208
+ }
209
+ const subject = condition.subject.trim();
210
+ if (!isIdentifierPath(subject)) return null;
211
+ try {
212
+ return compileFieldCondition(subject, condition.operator, condition.value);
213
+ } catch {
214
+ return null;
215
+ }
216
+ }
217
+ function compileGroup(group) {
218
+ const parts = group.conditions.map((condition) => compileCondition(condition)).filter((part) => part !== null);
219
+ return parts.length === 0 ? null : parts.join(" and ");
220
+ }
221
+ function compileBranch(branch) {
222
+ const groups = (branch.conditionGroups ?? []).map((group) => compileGroup(group)).filter((group) => group !== null);
223
+ return groups.length === 0 ? null : groups.map((group) => `(${group})`).join(" or ");
224
+ }
225
+ function selectBranchWith(branches, context, engine) {
226
+ const ordered = branches.toSorted((a, b) => a.priority - b.priority);
227
+ for (const branch of ordered) {
228
+ if (branch.isDefault) continue;
229
+ const expression = compileBranch(branch);
230
+ if (expression === null) {
231
+ if (isDev) console.warn(`[expression] branch "${branch.id}" has no compilable condition and can never match`);
232
+ continue;
233
+ }
234
+ if (evaluatesTrue(engine, expression, context)) return {
235
+ branchId: branch.id,
236
+ matched: true
237
+ };
238
+ }
239
+ return {
240
+ branchId: ordered.find((branch) => branch.isDefault)?.id ?? null,
241
+ matched: false
242
+ };
243
+ }
244
+ function evaluatesTrue(engine, expression, context) {
245
+ try {
246
+ return engine.evaluate(expression, context) === true;
247
+ } catch (error) {
248
+ if (isDev) reportEvaluationFailure(engine, expression, error);
249
+ return false;
250
+ }
251
+ }
252
+ function reportEvaluationFailure(engine, expression, error) {
253
+ let diagnostic;
254
+ try {
255
+ diagnostic = engine.validate(expression);
256
+ } catch {
257
+ return;
258
+ }
259
+ if (!isNullish(diagnostic)) console.warn(`[expression] compiled branch expression failed to parse: ${expression}`, diagnostic, error);
260
+ }
261
+ async function selectBranch(branches, context) {
262
+ return selectBranchWith(branches, context, await loadEngine());
263
+ }
264
+ //#endregion
265
+ //#region src/condition/types.ts
266
+ const CONDITION_OPERATORS = [
267
+ "eq",
268
+ "ne",
269
+ "gt",
270
+ "gte",
271
+ "lt",
272
+ "lte",
273
+ "contains",
274
+ "not_contains",
275
+ "starts_with",
276
+ "ends_with",
277
+ "in",
278
+ "not_in",
279
+ "is_empty",
280
+ "is_not_empty"
281
+ ];
282
+ const CONDITION_OPERATOR_ARITIES = {
283
+ eq: "scalar",
284
+ ne: "scalar",
285
+ gt: "scalar",
286
+ gte: "scalar",
287
+ lt: "scalar",
288
+ lte: "scalar",
289
+ contains: "scalar",
290
+ not_contains: "scalar",
291
+ starts_with: "scalar",
292
+ ends_with: "scalar",
293
+ in: "array",
294
+ not_in: "array",
295
+ is_empty: "none",
296
+ is_not_empty: "none"
297
+ };
298
+ function conditionOperatorArity(operator) {
299
+ return CONDITION_OPERATOR_ARITIES[operator];
300
+ }
301
+ //#endregion
302
+ //#region src/condition/compile-tree.ts
303
+ function compileConditionTree(tree) {
304
+ const normalized = normalizeNode(tree);
305
+ return normalized === null ? "" : emitNode(normalized, true);
306
+ }
307
+ function normalizeNode(node) {
308
+ if (node.kind === "rule") return compileRule(node) === null ? null : node;
309
+ const items = node.items.map((item) => normalizeNode(item)).filter((item) => item !== null);
310
+ if (items.length === 0) return null;
311
+ if (items.length === 1) return items[0];
312
+ return {
313
+ kind: "group",
314
+ op: node.op,
315
+ items
316
+ };
317
+ }
318
+ function emitNode(node, topLevel) {
319
+ if (node.kind === "rule") return compileRule(node);
320
+ const joined = node.items.map((item) => emitNode(item, false)).join(node.op === "and" ? " and " : " or ");
321
+ return topLevel ? joined : `(${joined})`;
322
+ }
323
+ function compileRule(rule) {
324
+ if (!matchesOperatorArity(rule)) return null;
325
+ return compileCondition({
326
+ kind: "field",
327
+ subject: rule.left,
328
+ operator: rule.operator,
329
+ value: rule.right
330
+ });
331
+ }
332
+ function matchesOperatorArity(rule) {
333
+ switch (conditionOperatorArity(rule.operator)) {
334
+ case "scalar": return isConditionScalar(rule.right);
335
+ case "array": return isScalarArray(rule.right);
336
+ case "none": return rule.right === void 0;
337
+ }
338
+ }
339
+ function isConditionScalar(value) {
340
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
341
+ }
342
+ function isScalarArray(value) {
343
+ return isArray(value) && value.every((item) => isConditionScalar(item));
344
+ }
345
+ //#endregion
346
+ //#region src/condition/lift-tree.ts
347
+ const TWO_CHAR_PUNCTUATION = new Set([
348
+ "==",
349
+ "!=",
350
+ "<=",
351
+ ">="
352
+ ]);
353
+ const ONE_CHAR_PUNCTUATION = new Set([
354
+ "(",
355
+ ")",
356
+ "[",
357
+ "]",
358
+ ",",
359
+ ".",
360
+ "<",
361
+ ">",
362
+ "-"
363
+ ]);
364
+ const IDENT_START = /[a-z_$]/i;
365
+ const IDENT_PART = /[\w$]/;
366
+ const DIGIT = /\d/;
367
+ const NUMBER_PATTERN = /^\d+(?:\.\d+)?(?:e[+-]?\d+)?/i;
368
+ const INTEGER_PATTERN = /^\d+$/;
369
+ const COMPARISON_OPERATORS = {
370
+ "==": "eq",
371
+ "!=": "ne",
372
+ ">": "gt",
373
+ ">=": "gte",
374
+ "<": "lt",
375
+ "<=": "lte"
376
+ };
377
+ const CALL_OPERATORS = {
378
+ contains: "contains",
379
+ startsWith: "starts_with",
380
+ endsWith: "ends_with"
381
+ };
382
+ const MAX_GROUP_DEPTH = 64;
383
+ function liftConditionTree(expression) {
384
+ const tokens = tokenize(expression);
385
+ if (tokens === null || tokens.length === 0) return null;
386
+ let pos = 0;
387
+ function peek(offset = 0) {
388
+ return tokens[pos + offset];
389
+ }
390
+ function consumePunct(value) {
391
+ const token = peek();
392
+ if (token !== void 0 && token.kind === "punct" && token.value === value) {
393
+ pos += 1;
394
+ return true;
395
+ }
396
+ return false;
397
+ }
398
+ function consumeIdent(value) {
399
+ const token = peek();
400
+ if (token !== void 0 && token.kind === "ident" && token.value === value) {
401
+ pos += 1;
402
+ return true;
403
+ }
404
+ return false;
405
+ }
406
+ function tokensMatchAt(from, expected) {
407
+ for (const [index, element] of expected.entries()) {
408
+ const actual = tokens[from + index];
409
+ const want = element;
410
+ if (actual === void 0 || actual.kind !== want.kind || actual.value !== want.value) return false;
411
+ }
412
+ return true;
413
+ }
414
+ function parsePath() {
415
+ const read = readPath(tokens, pos);
416
+ if (read === null) return null;
417
+ pos = read.next;
418
+ return read.path;
419
+ }
420
+ function parseLiteral() {
421
+ const token = peek();
422
+ if (token === void 0) return null;
423
+ if (token.kind === "string") {
424
+ pos += 1;
425
+ return token.value;
426
+ }
427
+ if (token.kind === "number") {
428
+ pos += 1;
429
+ return Number(token.value);
430
+ }
431
+ if (token.kind === "ident") {
432
+ if (token.value === "true") {
433
+ pos += 1;
434
+ return true;
435
+ }
436
+ if (token.value === "false") {
437
+ pos += 1;
438
+ return false;
439
+ }
440
+ return null;
441
+ }
442
+ if (token.kind === "punct" && token.value === "-") {
443
+ const digits = peek(1);
444
+ if (digits === void 0 || digits.kind !== "number") return null;
445
+ pos += 2;
446
+ return -Number(digits.value);
447
+ }
448
+ return null;
449
+ }
450
+ function parseArray() {
451
+ if (!consumePunct("[")) return null;
452
+ if (isPunct(peek(), "]")) {
453
+ pos += 1;
454
+ return [];
455
+ }
456
+ const first = parseLiteral();
457
+ if (first === null) return null;
458
+ const items = [first];
459
+ while (isPunct(peek(), ",")) {
460
+ pos += 1;
461
+ const next = parseLiteral();
462
+ if (next === null) return null;
463
+ items.push(next);
464
+ }
465
+ return consumePunct("]") ? items : null;
466
+ }
467
+ function parseCall(operator) {
468
+ if (!consumePunct("(")) return null;
469
+ const left = parsePath();
470
+ if (left === null || !consumePunct(",")) return null;
471
+ const right = parseLiteral();
472
+ if (right === null || !consumePunct(")")) return null;
473
+ return {
474
+ kind: "rule",
475
+ left,
476
+ operator,
477
+ right
478
+ };
479
+ }
480
+ function parseNotIn() {
481
+ const left = parsePath();
482
+ if (left === null || !consumeIdent("in")) return null;
483
+ const right = parseArray();
484
+ if (right === null || !consumePunct(")")) return null;
485
+ return {
486
+ kind: "rule",
487
+ left,
488
+ operator: "not_in",
489
+ right
490
+ };
491
+ }
492
+ function tryEmptiness() {
493
+ const first = peek();
494
+ if (first === void 0) return null;
495
+ let operator;
496
+ let pathIndex;
497
+ if (first.kind === "ident" && first.value === "not" && isPunct(peek(1), "(")) {
498
+ operator = "is_not_empty";
499
+ pathIndex = pos + 2;
500
+ } else if (first.kind === "punct" && first.value === "(") {
501
+ operator = "is_empty";
502
+ pathIndex = pos + 1;
503
+ } else return null;
504
+ const read = readPath(tokens, pathIndex);
505
+ if (read === null) return null;
506
+ const canonical = compileCondition({
507
+ kind: "field",
508
+ subject: read.path,
509
+ operator,
510
+ value: void 0
511
+ });
512
+ if (canonical === null) return null;
513
+ const expected = tokenize(canonical);
514
+ if (expected === null || !tokensMatchAt(pos, expected)) return null;
515
+ pos += expected.length;
516
+ return {
517
+ kind: "rule",
518
+ left: read.path,
519
+ operator
520
+ };
521
+ }
522
+ function parseRule() {
523
+ const token = peek();
524
+ if (token === void 0 || token.kind !== "ident") return null;
525
+ if (token.value === "not") {
526
+ const next = peek(1);
527
+ if (next === void 0) return null;
528
+ if (next.kind === "ident" && next.value === "contains" && isPunct(peek(2), "(")) {
529
+ pos += 2;
530
+ return parseCall("not_contains");
531
+ }
532
+ if (next.kind === "punct" && next.value === "(") {
533
+ pos += 2;
534
+ return parseNotIn();
535
+ }
536
+ return null;
537
+ }
538
+ if (isPunct(peek(1), "(")) {
539
+ const operator = CALL_OPERATORS[token.value];
540
+ if (operator === void 0) return null;
541
+ pos += 1;
542
+ return parseCall(operator);
543
+ }
544
+ const left = parsePath();
545
+ if (left === null) return null;
546
+ const operatorToken = peek();
547
+ if (operatorToken === void 0) return null;
548
+ if (operatorToken.kind === "ident" && operatorToken.value === "in") {
549
+ pos += 1;
550
+ const right = parseArray();
551
+ return right === null ? null : {
552
+ kind: "rule",
553
+ left,
554
+ operator: "in",
555
+ right
556
+ };
557
+ }
558
+ if (operatorToken.kind === "punct") {
559
+ const operator = COMPARISON_OPERATORS[operatorToken.value];
560
+ if (operator === void 0) return null;
561
+ pos += 1;
562
+ const right = parseLiteral();
563
+ return right === null ? null : {
564
+ kind: "rule",
565
+ left,
566
+ operator,
567
+ right
568
+ };
569
+ }
570
+ return null;
571
+ }
572
+ function parseItem(depth) {
573
+ const emptiness = tryEmptiness();
574
+ if (emptiness !== null) return emptiness;
575
+ if (isPunct(peek(), "(")) {
576
+ if (depth >= MAX_GROUP_DEPTH) return null;
577
+ pos += 1;
578
+ const inner = parseGroup(depth + 1);
579
+ if (inner === null || !consumePunct(")")) return null;
580
+ return asGroup(inner);
581
+ }
582
+ return parseRule();
583
+ }
584
+ function peekJoin() {
585
+ const token = peek();
586
+ if (token !== void 0 && token.kind === "ident" && (token.value === "and" || token.value === "or")) return token.value;
587
+ return null;
588
+ }
589
+ function parseGroup(depth) {
590
+ const first = parseItem(depth);
591
+ if (first === null) return null;
592
+ const items = [first];
593
+ let op = null;
594
+ let join = peekJoin();
595
+ while (join !== null) {
596
+ if (op === null) op = join;
597
+ else if (op !== join) return null;
598
+ pos += 1;
599
+ const next = parseItem(depth);
600
+ if (next === null) return null;
601
+ items.push(next);
602
+ join = peekJoin();
603
+ }
604
+ return items.length === 1 ? items[0] : {
605
+ kind: "group",
606
+ op: op ?? "and",
607
+ items
608
+ };
609
+ }
610
+ const parsed = parseGroup(0);
611
+ if (parsed === null || pos !== tokens.length) return null;
612
+ return asGroup(parsed);
613
+ }
614
+ function readPath(tokens, from) {
615
+ const head = tokens[from];
616
+ if (head === void 0 || head.kind !== "ident") return null;
617
+ let path = head.value;
618
+ let index = from + 1;
619
+ let segment = tokens[index];
620
+ while (segment !== void 0 && segment.kind === "punct" && (segment.value === "." || segment.value === "[")) {
621
+ if (segment.value === ".") {
622
+ const name = tokens[index + 1];
623
+ if (name === void 0 || name.kind !== "ident") return null;
624
+ path += `.${name.value}`;
625
+ index += 2;
626
+ } else {
627
+ const inner = tokens[index + 1];
628
+ if (inner === void 0 || inner.kind !== "number" || !INTEGER_PATTERN.test(inner.value)) return null;
629
+ const close = tokens[index + 2];
630
+ if (close === void 0 || close.kind !== "punct" || close.value !== "]") return null;
631
+ path += `[${inner.value}]`;
632
+ index += 3;
633
+ }
634
+ segment = tokens[index];
635
+ }
636
+ return isIdentifierPath(path) ? {
637
+ path,
638
+ next: index
639
+ } : null;
640
+ }
641
+ function asGroup(node) {
642
+ return node.kind === "group" ? node : {
643
+ kind: "group",
644
+ op: "and",
645
+ items: [node]
646
+ };
647
+ }
648
+ function isPunct(token, value) {
649
+ return token !== void 0 && token.kind === "punct" && token.value === value;
650
+ }
651
+ function tokenize(input) {
652
+ const tokens = [];
653
+ let index = 0;
654
+ while (index < input.length) {
655
+ const char = input[index];
656
+ if (char === " " || char === " " || char === "\n" || char === "\r") {
657
+ index += 1;
658
+ continue;
659
+ }
660
+ if (char === "'" || char === "\"") {
661
+ const end = input.indexOf(char, index + 1);
662
+ if (end === -1) return null;
663
+ tokens.push({
664
+ kind: "string",
665
+ value: input.slice(index + 1, end)
666
+ });
667
+ index = end + 1;
668
+ continue;
669
+ }
670
+ const pair = input.slice(index, index + 2);
671
+ if (TWO_CHAR_PUNCTUATION.has(pair)) {
672
+ tokens.push({
673
+ kind: "punct",
674
+ value: pair
675
+ });
676
+ index += 2;
677
+ continue;
678
+ }
679
+ if (ONE_CHAR_PUNCTUATION.has(char)) {
680
+ tokens.push({
681
+ kind: "punct",
682
+ value: char
683
+ });
684
+ index += 1;
685
+ continue;
686
+ }
687
+ if (DIGIT.test(char)) {
688
+ const match = NUMBER_PATTERN.exec(input.slice(index));
689
+ if (match === null) return null;
690
+ tokens.push({
691
+ kind: "number",
692
+ value: match[0]
693
+ });
694
+ index += match[0].length;
695
+ continue;
696
+ }
697
+ if (IDENT_START.test(char)) {
698
+ let end = index + 1;
699
+ while (end < input.length && IDENT_PART.test(input[end])) end += 1;
700
+ tokens.push({
701
+ kind: "ident",
702
+ value: input.slice(index, end)
703
+ });
704
+ index = end;
705
+ continue;
706
+ }
707
+ return null;
708
+ }
709
+ return tokens;
710
+ }
711
+ //#endregion
712
+ //#region src/condition/tree-types.ts
713
+ const CONDITION_TREE_OPERATORS = CONDITION_OPERATORS;
714
+ //#endregion
715
+ //#region src/engine/evaluate.ts
716
+ async function evaluate(expression, context) {
717
+ await loadEngine();
718
+ return evaluateSync(expression, context);
719
+ }
720
+ async function evaluateUnary(expression, context) {
721
+ await loadEngine();
722
+ return evaluateUnarySync(expression, context);
723
+ }
724
+ function evaluateSync(expression, context) {
725
+ return getEngineSync().evaluate(expression, context);
726
+ }
727
+ function evaluateUnarySync(expression, context) {
728
+ return getEngineSync().evaluateUnary(expression, context);
729
+ }
730
+ //#endregion
731
+ //#region src/engine/messages.ts
732
+ const COMPLETION_INFO_ZH = {
733
+ "Returns the length of variable": "返回变量的长度",
734
+ "Checks if variable contains a needle": "检查变量是否包含指定元素",
735
+ "Flattens an array": "将数组扁平化",
736
+ "Merges multiple objects into one.": "将多个对象合并为一个。",
737
+ "Deeply merges multiple objects into one.": "将多个对象深度合并为一个。",
738
+ "Converts all characters in a string to uppercase": "将字符串中所有字符转换为大写",
739
+ "Converts all characters in a string to lowercase": "将字符串中所有字符转换为小写",
740
+ "Returns the string with leading and trailing whitespace removed": "返回去除首尾空白后的字符串",
741
+ "Returns true if the string starts with the specified prefix": "若字符串以指定前缀开头则返回 true",
742
+ "Returns true if the string ends with the specified suffix": "若字符串以指定后缀结尾则返回 true",
743
+ "Returns true if the string matches the specified pattern": "若字符串匹配指定模式则返回 true",
744
+ "Extracts matching substrings according to a pattern": "按模式提取匹配的子串",
745
+ "Performs a fuzzy search of the needle in the haystack, and returns the match score(s).": "在目标中对关键字进行模糊搜索,并返回匹配得分。",
746
+ "Splits a string into an array of substrings using the specified delimiter.": "使用指定分隔符将字符串拆分为子串数组。",
747
+ "Returns the absolute value of a number": "返回数字的绝对值",
748
+ "Returns the sum of all elements in the input array.": "返回输入数组中所有元素之和。",
749
+ "Calculates the average of all elements in the input array.": "计算输入数组中所有元素的平均值。",
750
+ "Returns the smallest of the elements in the input array.": "返回输入数组中的最小元素。",
751
+ "Returns the largest of the elements in the input array.": "返回输入数组中的最大元素。",
752
+ "Generates a random number between 0 (inclusive) and max (inclusive).": "生成 0 到 max(均包含)之间的随机数。",
753
+ "Calculates the median value of all elements in the input array.": "计算输入数组中所有元素的中位数。",
754
+ "Finds the mode(s) of the input array, which are the most frequent element(s).": "求输入数组的众数,即出现最频繁的元素。",
755
+ "Rounds a number down to the nearest integer.": "向下取整到最接近的整数。",
756
+ "Rounds a number up to the nearest integer.": "向上取整到最接近的整数。",
757
+ "Rounds a number to a specified number of decimal places.": "将数字四舍五入到指定的小数位数。",
758
+ "Truncates a number to a specified number of decimal places.": "将数字截断到指定的小数位数。",
759
+ "Checks if the given value is of a numeric type.": "检查给定值是否为数值类型。",
760
+ "Converts the given value to a string.": "将给定值转换为字符串。",
761
+ "Converts the given value to a number.": "将给定值转换为数字。",
762
+ "Converts the given value to a boolean.": "将给定值转换为布尔值。",
763
+ "Returns a string representing the data type of the value.": "返回表示该值数据类型的字符串。",
764
+ "Returns an array of a given object's own enumerable property names.": "返回由给定对象自身可枚举属性名组成的数组。",
765
+ "Returns an array of a given object's own enumerable property values.": "返回由给定对象自身可枚举属性值组成的数组。",
766
+ "Returns a new date time instance.": "返回一个新的日期时间实例。",
767
+ "Converts a numeric timestamp to a unix timestamp.": "将数值时间戳转换为 Unix 时间戳。",
768
+ "Extracts the time from a numeric timestamp and returns it as a seconds from beginning of day.": "从数值时间戳中提取时间,以当天起始的秒数返回。",
769
+ "e.g. 1h30min": "例如 1h30min",
770
+ "Extracts the year from a given timestamp.": "从给定时间戳中提取年份。",
771
+ "Gets the day of the week from a given timestamp, where Sunday might be 0.": "获取给定时间戳的星期几(周日可能为 0)。",
772
+ "Extracts the day of the month from a given timestamp.": "从给定时间戳中提取当月的日期。",
773
+ "Gets the day of the year from a given timestamp.": "获取给定时间戳在一年中的第几天。",
774
+ "Calculates the week of the year from a given timestamp.": "计算给定时间戳在一年中的第几周。",
775
+ "Extracts the month from a given timestamp, typically with January as 1.": "从给定时间戳中提取月份(通常 1 月为 1)。",
776
+ "Converts the month from a given timestamp into its string representation (e.g., 'Jan').": "将给定时间戳的月份转换为字符串表示(例如 'Jan')。",
777
+ "Converts a timestamp to a human-readable date string.": "将时间戳转换为人类可读的日期字符串。",
778
+ "Converts the day of the week from a given timestamp into its string representation (e.g., 'Mon').": "将给定时间戳的星期几转换为字符串表示(例如 'Mon')。",
779
+ "Returns the timestamp representing the start of a specified unit (e.g., day, month, year) based on a given timestamp.": "返回给定时间戳在指定单位(如日、月、年)起始处的时间戳。",
780
+ "Returns the timestamp representing the end of a specified unit (e.g., day, month, year) based on a given timestamp.": "返回给定时间戳在指定单位(如日、月、年)结束处的时间戳。",
781
+ "Checks if all elements in the array satisfy the condition defined in the callback.": "检查数组中所有元素是否都满足回调中定义的条件。",
782
+ "Checks if no elements in the array satisfy the condition defined in the callback.": "检查数组中是否没有任何元素满足回调中定义的条件。",
783
+ "Checks if at least one element in the array satisfies the condition defined in the callback.": "检查数组中是否至少有一个元素满足回调中定义的条件。",
784
+ "Checks if exactly one element in the array satisfies the condition defined in the callback.": "检查数组中是否恰好有一个元素满足回调中定义的条件。",
785
+ "Creates a new array with all elements that satisfy the condition defined in the callback.": "创建一个仅包含满足回调中定义条件的元素的新数组。",
786
+ "Creates a new array populated with the results of calling the provided function on every element in the calling array.": "创建一个新数组,其元素为对原数组每个元素调用所提供函数的结果。",
787
+ "First maps each element using a mapping function, then flattens the result into a new array.": "先用映射函数处理每个元素,再将结果扁平化为新数组。",
788
+ "Counts the number of elements in the array that satisfy the condition defined in the callback.": "统计数组中满足回调中定义条件的元素个数。",
789
+ "Adds time to a date": "为日期增加时间",
790
+ "Subtracts time from a date": "从日期中减去时间",
791
+ "Sets a specific unit of time on a date": "设置日期的某个时间单位",
792
+ "Formats a date into a string representation": "将日期格式化为字符串",
793
+ "Returns the start of a specified time unit for a date": "返回日期在指定时间单位上的起始",
794
+ "Returns the end of a specified time unit for a date": "返回日期在指定时间单位上的结束",
795
+ "Calculates the difference between two dates": "计算两个日期之间的差值",
796
+ "Converts a date to a different timezone": "将日期转换到不同的时区",
797
+ "Checks if two dates are the same": "检查两个日期是否相同",
798
+ "Checks if a date is before another date": "检查日期是否早于另一个日期",
799
+ "Checks if a date is after another date": "检查日期是否晚于另一个日期",
800
+ "Checks if a date is the same as or before another date": "检查日期是否等于或早于另一个日期",
801
+ "Checks if a date is the same as or after another date": "检查日期是否等于或晚于另一个日期",
802
+ "Gets the seconds of a date": "获取日期的秒",
803
+ "Gets the minutes of a date": "获取日期的分钟",
804
+ "Gets the hours of a date": "获取日期的小时",
805
+ "Gets the day of the month for a date": "获取日期在当月的第几天",
806
+ "Gets the day of the year for a date": "获取日期在当年的第几天",
807
+ "Gets the week of the year for a date": "获取日期在当年的第几周",
808
+ "Gets the day of the week for a date": "获取日期的星期几",
809
+ "Gets the month for a date": "获取日期的月份",
810
+ "Gets the quarter for a date": "获取日期所在的季度",
811
+ "Gets the year for a date": "获取日期的年份",
812
+ "Gets the Unix timestamp for a date": "获取日期的 Unix 时间戳",
813
+ "Gets the timezone offset name for a date": "获取日期的时区偏移名称",
814
+ "Checks if a date is valid": "检查日期是否有效",
815
+ "Checks if a date is yesterday": "检查日期是否为昨天",
816
+ "Checks if a date is today": "检查日期是否为今天",
817
+ "Checks if a date is tomorrow": "检查日期是否为明天",
818
+ "Checks if the year of a date is a leap year": "检查日期所在年份是否为闰年"
819
+ };
820
+ const EN_SOURCE_LABELS = {
821
+ lexerError: "Lexer error",
822
+ parserError: "Parser error",
823
+ compilerError: "Compiler error",
824
+ vmError: "VM error"
825
+ };
826
+ const ZH_SOURCE_LABELS = {
827
+ lexerError: "词法错误",
828
+ parserError: "语法错误",
829
+ compilerError: "编译错误",
830
+ vmError: "运行时错误"
831
+ };
832
+ function sourceLabelFrom(table, fallback, type) {
833
+ return (type === void 0 ? void 0 : table[type]) ?? fallback;
834
+ }
835
+ const enMessages = {
836
+ sourceLabel: (type) => sourceLabelFrom(EN_SOURCE_LABELS, "Error", type),
837
+ completionInfo: (info) => info,
838
+ typeCheckSource: "Type check",
839
+ expectedBoolean: (actualType) => `Expected a boolean test expression, received \`${actualType}\`.`,
840
+ expectedType: (expectedType, actualType) => `Expected \`${expectedType}\`, received \`${actualType}\`.`
841
+ };
842
+ const zhCNMessages = {
843
+ sourceLabel: (type) => sourceLabelFrom(ZH_SOURCE_LABELS, "错误", type),
844
+ completionInfo: (info) => info === "" ? "" : COMPLETION_INFO_ZH[info] ?? info,
845
+ typeCheckSource: "类型检查",
846
+ expectedBoolean: (actualType) => `期望布尔测试表达式,实际类型为 \`${actualType}\`。`,
847
+ expectedType: (expectedType, actualType) => `期望 \`${expectedType}\`,实际为 \`${actualType}\`。`
848
+ };
849
+ const localeRegistry = new Map([["en-US", enMessages], ["zh-CN", zhCNMessages]]);
850
+ let activeMessages = enMessages;
851
+ function registerExpressionLocale(locale, messages) {
852
+ localeRegistry.set(locale, messages);
853
+ }
854
+ function configureExpressionMessages({ locale, messages }) {
855
+ const base = locale === void 0 ? activeMessages : localeRegistry.get(locale) ?? activeMessages;
856
+ activeMessages = messages === void 0 ? base : {
857
+ ...base,
858
+ ...messages
859
+ };
860
+ }
861
+ function getExpressionMessages() {
862
+ return activeMessages;
863
+ }
864
+ //#endregion
865
+ //#region src/engine/intellisense.ts
866
+ function parseOffset(text) {
867
+ const trimmed = text?.trim();
868
+ return trimmed ? Number(trimmed) : NaN;
869
+ }
870
+ function extractPosition(message) {
871
+ const segments = message.split(" at ");
872
+ const last = segments.length <= 1 ? void 0 : segments.at(-1);
873
+ if (last === void 0) return null;
874
+ const [left, right] = last.replace("(", "").replace(")", "").split(", ");
875
+ const from = parseOffset(left);
876
+ if (Number.isNaN(from)) return null;
877
+ const to = parseOffset(right);
878
+ return [from, Number.isNaN(to) ? from : to];
879
+ }
880
+ function normalizeDiagnostic(raw, source) {
881
+ if (raw === null || raw === void 0) return null;
882
+ const errorType = isRecord(raw) && typeof raw.type === "string" ? raw.type : void 0;
883
+ const message = isRecord(raw) && typeof raw.source === "string" ? raw.source : String(raw);
884
+ const [from, to] = extractPosition(message) ?? [0, source.length];
885
+ return {
886
+ from,
887
+ to,
888
+ message,
889
+ source: getExpressionMessages().sourceLabel(errorType)
890
+ };
891
+ }
892
+ function normalizeCompletions(raw) {
893
+ if (!Array.isArray(raw)) return [];
894
+ const messages = getExpressionMessages();
895
+ return raw.flatMap((entry) => {
896
+ if (!isRecord(entry) || typeof entry.label !== "string" || entry.label === "") return [];
897
+ return [{
898
+ type: entry.type === "method" || entry.type === "variable" ? entry.type : "function",
899
+ label: entry.label,
900
+ detail: typeof entry.detail === "string" ? entry.detail.replaceAll("`", "") : "",
901
+ info: messages.completionInfo(typeof entry.info === "string" ? entry.info : ""),
902
+ boost: typeof entry.boost === "number" ? entry.boost : null,
903
+ methodFor: typeof entry.methodFor === "string" ? entry.methodFor : null
904
+ }];
905
+ });
906
+ }
907
+ async function getDiagnostics(expression, mode) {
908
+ await loadEngine();
909
+ return getDiagnosticsSync(expression, mode);
910
+ }
911
+ function getDiagnosticsSync(expression, mode) {
912
+ const engine = getEngineSync();
913
+ return normalizeDiagnostic(mode === "unary" ? engine.validateUnary(expression) : engine.validate(expression), expression);
914
+ }
915
+ async function getCompletionItems() {
916
+ await loadEngine();
917
+ return getCompletionItemsSync();
918
+ }
919
+ function getCompletionItemsSync() {
920
+ return normalizeCompletions(getEngineSync().getCompletions());
921
+ }
922
+ async function analyzeTypes(variables, source, mode) {
923
+ await loadEngine();
924
+ return analyzeTypesSync(variables, source, mode);
925
+ }
926
+ function analyzeTypesSync(variables, source, mode) {
927
+ return getEngineSync().analyze(variables, source, mode === "unary");
928
+ }
929
+ async function satisfiesType(actual, expected) {
930
+ await loadEngine();
931
+ return satisfiesTypeSync(actual, expected);
932
+ }
933
+ function satisfiesTypeSync(actual, expected) {
934
+ return getEngineSync().satisfies(actual, expected);
935
+ }
936
+ //#endregion
937
+ //#region src/engine/template.ts
938
+ const HOLE_PATTERN = /\{\{(?<expression>[^{}]*)\}\}/g;
939
+ function parseTemplateHoles(source) {
940
+ const holes = [];
941
+ HOLE_PATTERN.lastIndex = 0;
942
+ for (let match = HOLE_PATTERN.exec(source); match !== null; match = HOLE_PATTERN.exec(source)) {
943
+ const inner = match.groups?.expression ?? "";
944
+ const from = match.index + 2;
945
+ holes.push({
946
+ from,
947
+ to: from + inner.length,
948
+ expression: inner
949
+ });
950
+ }
951
+ return holes;
952
+ }
953
+ function templateHoleAt(source, pos) {
954
+ return parseTemplateHoles(source).find((hole) => pos >= hole.from && pos <= hole.to) ?? null;
955
+ }
956
+ function hasExpression(hole) {
957
+ return hole.expression.trim().length > 0;
958
+ }
959
+ function analyzeTemplateSync(variables, source) {
960
+ if (!isEngineReady()) throw new ExpressionNotReadyError();
961
+ const spans = [];
962
+ for (const hole of parseTemplateHoles(source)) {
963
+ if (!hasExpression(hole)) continue;
964
+ try {
965
+ for (const span of analyzeTypesSync(variables, hole.expression, "standard").spans) spans.push({
966
+ ...span,
967
+ span: [span.span[0] + hole.from, span.span[1] + hole.from]
968
+ });
969
+ } catch {}
970
+ }
971
+ return {
972
+ rootKind: variables,
973
+ spans
974
+ };
975
+ }
976
+ async function analyzeTemplate(variables, source) {
977
+ await loadEngine();
978
+ return analyzeTemplateSync(variables, source);
979
+ }
980
+ function getTemplateDiagnosticsSync(source) {
981
+ if (!isEngineReady()) throw new ExpressionNotReadyError();
982
+ const diagnostics = [];
983
+ for (const hole of parseTemplateHoles(source)) {
984
+ if (!hasExpression(hole)) continue;
985
+ const diagnostic = getDiagnosticsSync(hole.expression, "standard");
986
+ if (diagnostic) diagnostics.push({
987
+ ...diagnostic,
988
+ from: diagnostic.from + hole.from,
989
+ to: diagnostic.to + hole.from
990
+ });
991
+ }
992
+ return diagnostics;
993
+ }
994
+ async function getTemplateDiagnostics(source) {
995
+ await loadEngine();
996
+ return getTemplateDiagnosticsSync(source);
997
+ }
998
+ //#endregion
999
+ exports.CONDITION_OPERATORS = CONDITION_OPERATORS;
1000
+ exports.CONDITION_TREE_OPERATORS = CONDITION_TREE_OPERATORS;
1001
+ exports.ExpressionError = ExpressionError;
1002
+ exports.ExpressionNotReadyError = ExpressionNotReadyError;
1003
+ exports.analyzeTemplate = analyzeTemplate;
1004
+ exports.analyzeTemplateSync = analyzeTemplateSync;
1005
+ exports.analyzeTypes = analyzeTypes;
1006
+ exports.analyzeTypesSync = analyzeTypesSync;
1007
+ exports.compileBranch = compileBranch;
1008
+ exports.compileCondition = compileCondition;
1009
+ exports.compileConditionTree = compileConditionTree;
1010
+ exports.compileGroup = compileGroup;
1011
+ exports.conditionOperatorArity = conditionOperatorArity;
1012
+ exports.configureEngine = configureEngine;
1013
+ exports.configureExpressionMessages = configureExpressionMessages;
1014
+ exports.enMessages = enMessages;
1015
+ exports.evaluate = evaluate;
1016
+ exports.evaluateSync = evaluateSync;
1017
+ exports.evaluateUnary = evaluateUnary;
1018
+ exports.evaluateUnarySync = evaluateUnarySync;
1019
+ exports.getCompletionItems = getCompletionItems;
1020
+ exports.getCompletionItemsSync = getCompletionItemsSync;
1021
+ exports.getDiagnostics = getDiagnostics;
1022
+ exports.getDiagnosticsSync = getDiagnosticsSync;
1023
+ exports.getEngineError = getEngineError;
1024
+ exports.getEngineSync = getEngineSync;
1025
+ exports.getExpressionMessages = getExpressionMessages;
1026
+ exports.getTemplateDiagnostics = getTemplateDiagnostics;
1027
+ exports.getTemplateDiagnosticsSync = getTemplateDiagnosticsSync;
1028
+ exports.isEngineReady = isEngineReady;
1029
+ exports.liftConditionTree = liftConditionTree;
1030
+ exports.loadEngine = loadEngine;
1031
+ exports.parseTemplateHoles = parseTemplateHoles;
1032
+ exports.registerExpressionLocale = registerExpressionLocale;
1033
+ exports.resetEngine = resetEngine;
1034
+ exports.satisfiesType = satisfiesType;
1035
+ exports.satisfiesTypeSync = satisfiesTypeSync;
1036
+ exports.selectBranch = selectBranch;
1037
+ exports.selectBranchWith = selectBranchWith;
1038
+ exports.templateHoleAt = templateHoleAt;
1039
+ exports.toZenLiteral = toZenLiteral;
1040
+ exports.zhCNMessages = zhCNMessages;