solve-engine 2.32.0 → 2.34.0
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/{EngineError-CqGtaT_v.d.cts → EngineError-Bm4OYmw8.d.cts} +6 -0
- package/dist/{EngineError-CqGtaT_v.d.ts → EngineError-Bm4OYmw8.d.ts} +6 -0
- package/dist/{Lexer-CqFjYoRA.d.ts → Lexer-DPn5dfCH.d.ts} +1 -13
- package/dist/{Lexer-sCI05tqO.d.cts → Lexer-DaWkCu84.d.cts} +1 -13
- package/dist/{PackageCompatibility-phvSFP4f.d.ts → PackageCompatibility-CkzZfoJ3.d.ts} +1 -1
- package/dist/{PackageCompatibility-Bn-T_xKW.d.cts → PackageCompatibility-E_5GtcQW.d.cts} +1 -1
- package/dist/{PackageRegistry-C78jVkI9.d.ts → PackageRegistry-DSqic8kz.d.ts} +132 -23
- package/dist/{PackageRegistry-B-C1duZw.d.cts → PackageRegistry-js47hr28.d.cts} +132 -23
- package/dist/{Parselet-Dgymjxzd.d.ts → Parselet-CQjcHOKw.d.ts} +13 -6
- package/dist/{Parselet-DF3864la.d.cts → Parselet-s1sRRn8H.d.cts} +13 -6
- package/dist/{TokenNormalizer-Pe3_390t.d.cts → TokenNormalizer-D382VSYh.d.cts} +4 -1
- package/dist/{TokenNormalizer-IF7nPRMp.d.ts → TokenNormalizer-DAzPp-j1.d.ts} +4 -1
- package/dist/{VMBuiltins-BkKzhj6C.d.cts → VMBuiltins-JCavlQUj.d.cts} +53 -18
- package/dist/{VMBuiltins-Du9y8sEo.d.ts → VMBuiltins-qgzA6qGi.d.ts} +53 -18
- package/dist/{VMCheckpoints-WdUQrdc9.d.cts → VMCheckpoints-BxPzmdu0.d.cts} +2 -2
- package/dist/{VMCheckpoints-gvy_yxYh.d.ts → VMCheckpoints-DjjE92mf.d.ts} +2 -2
- package/dist/{Value-BYHw-x7q.d.cts → Value-2TIKi-YL.d.cts} +19 -0
- package/dist/{Value-BYHw-x7q.d.ts → Value-2TIKi-YL.d.ts} +19 -0
- package/dist/{WorkerError-DTrl3Jag.d.ts → WorkerError-BaN8_eok.d.ts} +1 -1
- package/dist/{WorkerError-CRoM8Ju1.d.cts → WorkerError-CexHHmbb.d.cts} +1 -1
- package/dist/{chunk-IJE4AEDX.js → chunk-24OW3AAU.js} +3 -3
- package/dist/{chunk-IJE4AEDX.js.map → chunk-24OW3AAU.js.map} +1 -1
- package/dist/{chunk-CAJTDZ5B.cjs → chunk-2XOLAHW6.cjs} +2 -2
- package/dist/{chunk-CAJTDZ5B.cjs.map → chunk-2XOLAHW6.cjs.map} +1 -1
- package/dist/{chunk-AGCNMEP2.cjs → chunk-3MG7VIPL.cjs} +2 -2
- package/dist/{chunk-AGCNMEP2.cjs.map → chunk-3MG7VIPL.cjs.map} +1 -1
- package/dist/chunk-4ASM522I.js +2 -0
- package/dist/chunk-4ASM522I.js.map +1 -0
- package/dist/{chunk-KH4QXKLT.js → chunk-4MD5L23F.js} +2 -2
- package/dist/{chunk-KH4QXKLT.js.map → chunk-4MD5L23F.js.map} +1 -1
- package/dist/{chunk-IQVSCL2R.js → chunk-4XWZXP6I.js} +3 -3
- package/dist/{chunk-IQVSCL2R.js.map → chunk-4XWZXP6I.js.map} +1 -1
- package/dist/{chunk-RELMEWY6.js → chunk-6G2NES2I.js} +2 -2
- package/dist/chunk-6G2NES2I.js.map +1 -0
- package/dist/{chunk-CDE2ZUGG.js → chunk-6NL7RBAG.js} +2 -2
- package/dist/{chunk-CDE2ZUGG.js.map → chunk-6NL7RBAG.js.map} +1 -1
- package/dist/{chunk-SUAGBRQ7.cjs → chunk-6SYU4MH7.cjs} +2 -2
- package/dist/chunk-6SYU4MH7.cjs.map +1 -0
- package/dist/chunk-72J5V7SN.cjs +2 -0
- package/dist/chunk-72J5V7SN.cjs.map +1 -0
- package/dist/{chunk-TSJ4RQLZ.js → chunk-AENL3Z66.js} +2 -2
- package/dist/{chunk-TSJ4RQLZ.js.map → chunk-AENL3Z66.js.map} +1 -1
- package/dist/chunk-APYRNAU2.js +2 -0
- package/dist/chunk-APYRNAU2.js.map +1 -0
- package/dist/{chunk-AXTYQFIV.cjs → chunk-D7URPV5Z.cjs} +3 -3
- package/dist/{chunk-AXTYQFIV.cjs.map → chunk-D7URPV5Z.cjs.map} +1 -1
- package/dist/chunk-DB5ISONG.js +2 -0
- package/dist/chunk-DB5ISONG.js.map +1 -0
- package/dist/chunk-DGDVY6XI.js +3 -0
- package/dist/chunk-DGDVY6XI.js.map +1 -0
- package/dist/chunk-EOKHRS2T.js +2 -0
- package/dist/chunk-EOKHRS2T.js.map +1 -0
- package/dist/{chunk-NQFCXLEF.js → chunk-EOO6M65F.js} +2 -2
- package/dist/{chunk-NQFCXLEF.js.map → chunk-EOO6M65F.js.map} +1 -1
- package/dist/{chunk-A764BY7L.cjs → chunk-EQNKDTMX.cjs} +2 -2
- package/dist/{chunk-A764BY7L.cjs.map → chunk-EQNKDTMX.cjs.map} +1 -1
- package/dist/chunk-FESR6PZI.cjs +2 -0
- package/dist/chunk-FESR6PZI.cjs.map +1 -0
- package/dist/chunk-G2LCDR52.cjs +3 -0
- package/dist/chunk-G2LCDR52.cjs.map +1 -0
- package/dist/chunk-G5TZ6TDA.js +2 -0
- package/dist/chunk-G5TZ6TDA.js.map +1 -0
- package/dist/chunk-GDLYXRMA.cjs +2 -0
- package/dist/chunk-GDLYXRMA.cjs.map +1 -0
- package/dist/{chunk-7DJYS5PO.cjs → chunk-HSTGWWU2.cjs} +2 -2
- package/dist/{chunk-7DJYS5PO.cjs.map → chunk-HSTGWWU2.cjs.map} +1 -1
- package/dist/{chunk-OE2DBN4K.js → chunk-INMJ7ZXL.js} +2 -2
- package/dist/chunk-INMJ7ZXL.js.map +1 -0
- package/dist/chunk-ITH2RLRG.js +5 -0
- package/dist/chunk-ITH2RLRG.js.map +1 -0
- package/dist/{chunk-5AKT36UK.cjs → chunk-K3PZ66XR.cjs} +2 -2
- package/dist/{chunk-5AKT36UK.cjs.map → chunk-K3PZ66XR.cjs.map} +1 -1
- package/dist/chunk-LI6LYJDA.cjs +2 -0
- package/dist/chunk-LI6LYJDA.cjs.map +1 -0
- package/dist/{chunk-WQGHJAW2.cjs → chunk-M4UC2PB6.cjs} +2 -2
- package/dist/{chunk-WQGHJAW2.cjs.map → chunk-M4UC2PB6.cjs.map} +1 -1
- package/dist/chunk-O7HF345B.js +2 -0
- package/dist/chunk-O7HF345B.js.map +1 -0
- package/dist/{chunk-CM2WM5CM.cjs → chunk-OBZJKZ2F.cjs} +2 -2
- package/dist/{chunk-CM2WM5CM.cjs.map → chunk-OBZJKZ2F.cjs.map} +1 -1
- package/dist/{chunk-Q7TBBV62.cjs → chunk-P5YWBIIU.cjs} +2 -2
- package/dist/chunk-P5YWBIIU.cjs.map +1 -0
- package/dist/chunk-PICFFFJV.js +3 -0
- package/dist/chunk-PICFFFJV.js.map +1 -0
- package/dist/{chunk-P43SV4NJ.cjs → chunk-QOOTRUY7.cjs} +3 -3
- package/dist/{chunk-P43SV4NJ.cjs.map → chunk-QOOTRUY7.cjs.map} +1 -1
- package/dist/chunk-R3W53ZMP.cjs +2 -0
- package/dist/chunk-R3W53ZMP.cjs.map +1 -0
- package/dist/chunk-RMDCGYZM.js +2 -0
- package/dist/chunk-RMDCGYZM.js.map +1 -0
- package/dist/{chunk-CB3EXUM2.js → chunk-RU3KGJRA.js} +2 -2
- package/dist/chunk-RU3KGJRA.js.map +1 -0
- package/dist/chunk-S3SPDK6N.cjs +2 -0
- package/dist/chunk-S3SPDK6N.cjs.map +1 -0
- package/dist/chunk-SF5QVUEI.cjs +3 -0
- package/dist/chunk-SF5QVUEI.cjs.map +1 -0
- package/dist/{chunk-FXB5GCBT.js → chunk-TJKN466F.js} +2 -2
- package/dist/{chunk-FXB5GCBT.js.map → chunk-TJKN466F.js.map} +1 -1
- package/dist/{chunk-VLX7ZVK4.js → chunk-U5MESNRT.js} +2 -2
- package/dist/{chunk-VLX7ZVK4.js.map → chunk-U5MESNRT.js.map} +1 -1
- package/dist/chunk-WCVPXBCW.cjs +5 -0
- package/dist/chunk-WCVPXBCW.cjs.map +1 -0
- package/dist/{chunk-YWF6C2IO.cjs → chunk-WFT3XUSH.cjs} +2 -2
- package/dist/{chunk-YWF6C2IO.cjs.map → chunk-WFT3XUSH.cjs.map} +1 -1
- package/dist/{chunk-3ZGFAE3Q.js → chunk-X2GQAKL2.js} +2 -2
- package/dist/{chunk-3ZGFAE3Q.js.map → chunk-X2GQAKL2.js.map} +1 -1
- package/dist/{chunk-G3POUURF.js → chunk-YID47OPR.js} +2 -2
- package/dist/{chunk-G3POUURF.js.map → chunk-YID47OPR.js.map} +1 -1
- package/dist/chunk-YV4GDW5A.cjs +2 -0
- package/dist/chunk-YV4GDW5A.cjs.map +1 -0
- package/dist/chunk-ZSXQP7PD.cjs +2 -0
- package/dist/chunk-ZSXQP7PD.cjs.map +1 -0
- package/dist/constants.cjs +1 -1
- package/dist/constants.js +1 -1
- package/dist/engine.cjs +1 -1
- package/dist/engine.d.cts +10 -10
- package/dist/engine.d.ts +10 -10
- package/dist/engine.js +1 -1
- package/dist/engine.worker.cjs +1 -1
- package/dist/engine.worker.cjs.map +1 -1
- package/dist/engine.worker.js +1 -1
- package/dist/engine.worker.js.map +1 -1
- package/dist/errors.cjs +1 -1
- package/dist/errors.d.cts +3 -3
- package/dist/errors.d.ts +3 -3
- package/dist/errors.js +1 -1
- package/dist/format.cjs +1 -1
- package/dist/format.d.cts +1 -1
- package/dist/format.d.ts +1 -1
- package/dist/format.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -10
- package/dist/index.d.ts +10 -10
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/language.d.cts +9 -9
- package/dist/language.d.ts +9 -9
- package/dist/lexer.cjs +1 -1
- package/dist/lexer.d.cts +3 -3
- package/dist/lexer.d.ts +3 -3
- package/dist/lexer.js +1 -1
- package/dist/normalizer.cjs +1 -1
- package/dist/normalizer.d.cts +2 -2
- package/dist/normalizer.d.ts +2 -2
- package/dist/normalizer.js +1 -1
- package/dist/packages.cjs +1 -1
- package/dist/packages.d.cts +8 -8
- package/dist/packages.d.ts +8 -8
- package/dist/packages.js +1 -1
- package/dist/parser.cjs +1 -1
- package/dist/parser.d.cts +3 -3
- package/dist/parser.d.ts +3 -3
- package/dist/parser.js +1 -1
- package/dist/{pipeline-BYkKNpql.d.cts → pipeline-Bum6y1B9.d.cts} +1 -1
- package/dist/{pipeline-Cl7KW8CB.d.ts → pipeline-DOo3KHaq.d.ts} +1 -1
- package/dist/resolvers.cjs +1 -1
- package/dist/resolvers.d.cts +69 -3
- package/dist/resolvers.d.ts +69 -3
- package/dist/resolvers.js +1 -1
- package/dist/temporal.cjs +1 -1
- package/dist/temporal.js +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +9 -9
- package/dist/testing.d.ts +9 -9
- package/dist/testing.js +1 -1
- package/dist/testing.js.map +1 -1
- package/dist/uom.cjs +1 -1
- package/dist/uom.d.cts +35 -2
- package/dist/uom.d.ts +35 -2
- package/dist/uom.js +1 -1
- package/dist/vm.cjs +1 -1
- package/dist/vm.d.cts +6 -6
- package/dist/vm.d.ts +6 -6
- package/dist/vm.js +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +9 -9
- package/dist/worker.d.ts +9 -9
- package/dist/worker.js +1 -1
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-4DR5RBHQ.cjs +0 -2
- package/dist/chunk-4DR5RBHQ.cjs.map +0 -1
- package/dist/chunk-4IC5OARK.js +0 -3
- package/dist/chunk-4IC5OARK.js.map +0 -1
- package/dist/chunk-7ODHPWQC.js +0 -5
- package/dist/chunk-7ODHPWQC.js.map +0 -1
- package/dist/chunk-A755LVPT.cjs +0 -2
- package/dist/chunk-A755LVPT.cjs.map +0 -1
- package/dist/chunk-AF6NDOIE.js +0 -2
- package/dist/chunk-AF6NDOIE.js.map +0 -1
- package/dist/chunk-B2NL65FI.js +0 -2
- package/dist/chunk-B2NL65FI.js.map +0 -1
- package/dist/chunk-CB3EXUM2.js.map +0 -1
- package/dist/chunk-DUFEONVN.cjs +0 -3
- package/dist/chunk-DUFEONVN.cjs.map +0 -1
- package/dist/chunk-IJHL3LMH.js +0 -2
- package/dist/chunk-IJHL3LMH.js.map +0 -1
- package/dist/chunk-LCYQQFUH.cjs +0 -2
- package/dist/chunk-LCYQQFUH.cjs.map +0 -1
- package/dist/chunk-LP3JYC3A.js +0 -2
- package/dist/chunk-LP3JYC3A.js.map +0 -1
- package/dist/chunk-OE2DBN4K.js.map +0 -1
- package/dist/chunk-OKKGPINQ.cjs +0 -5
- package/dist/chunk-OKKGPINQ.cjs.map +0 -1
- package/dist/chunk-OM7NOHJF.cjs +0 -2
- package/dist/chunk-OM7NOHJF.cjs.map +0 -1
- package/dist/chunk-PTXUWGRR.js +0 -3
- package/dist/chunk-PTXUWGRR.js.map +0 -1
- package/dist/chunk-Q7TBBV62.cjs.map +0 -1
- package/dist/chunk-RELMEWY6.js.map +0 -1
- package/dist/chunk-SFM4XFGJ.js +0 -2
- package/dist/chunk-SFM4XFGJ.js.map +0 -1
- package/dist/chunk-SRAU3BLV.cjs +0 -3
- package/dist/chunk-SRAU3BLV.cjs.map +0 -1
- package/dist/chunk-SUAGBRQ7.cjs.map +0 -1
- package/dist/chunk-UNKZ5XRC.cjs +0 -2
- package/dist/chunk-UNKZ5XRC.cjs.map +0 -1
- package/dist/chunk-WU7SBKVU.cjs +0 -2
- package/dist/chunk-WU7SBKVU.cjs.map +0 -1
- package/dist/chunk-X5K72MBV.js +0 -2
- package/dist/chunk-X5K72MBV.js.map +0 -1
- package/dist/chunk-ZVPZQ66D.cjs +0 -2
- package/dist/chunk-ZVPZQ66D.cjs.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a,c}from'./chunk-FAO6DQ74.js';import {a as a$1}from'./chunk-LHLW7JLS.js';import {c as c$1}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a,c}from'./chunk-FAO6DQ74.js';import {a as a$1}from'./chunk-LHLW7JLS.js';import {c as c$1}from'./chunk-6G2NES2I.js';var o={Lowest:0,Assignment:10,LogicalOr:12,LogicalAnd:14,Conjunction:16,BitwiseOr:18,BitwiseXor:20,BitwiseAnd:22,Conditional:24,Shift:27,Sum:30,Product:40,Uncertainty:45,Exponent:50,Prefix:60,Postfix:70,Call:80};var f={[a.PLUS]:o.Sum,[a.MINUS]:o.Sum,[a.STAR]:o.Product,[a.SLASH]:o.Product,[a.MOD]:o.Product,[a.CARET]:o.Exponent,[a.BIT_OR]:o.BitwiseOr,[a.BIT_XOR]:o.BitwiseXor,[a.BIT_AND]:o.BitwiseAnd,[a.LSHIFT]:o.Shift,[a.RSHIFT]:o.Shift,[a.URSHIFT]:o.Shift,[a.PERCENT]:o.Postfix,[a.OF]:o.Product},h=null;function F(){if(h)return h;let i=0;for(let n of Object.keys(f)){let t=c(n);t>i&&(i=t);}for(let n of Object.values(a)){let t=c(n);t>i&&(i=t);}let e=new Uint8Array(i+1);for(let[n,t]of Object.entries(f)){let u=c(n);e[u]=t;}return h=e,e}function P(){h=null;}var r=255,A="-0";function m(i,e){if(!Number.isInteger(i)||i<0||i>255)throw c$1.parsing("BYTECODE_OPERAND_OUT_OF_RANGE",`A bytecode ${e} must be an integer from 0 to 255, but ${i} was emitted; the opcode stream stores one byte per operand.`,{value:i,what:e});return i}var O=Object.freeze([]),B=new Float64Array(0),b=class{constructor(e){this.pluginFunctionIndex=e;this.opcodes=[];this.numbers=[];this.strings=[];this.stringIndex=new Map;this.numberIndex=new Map;this._hasAsync=false;this.userFunctionBodies=[];this.anonymousBodies=[];}get pluginIndexMap(){return this.pluginFunctionIndex}emitPluginCall(e,n){let t=this.pluginFunctionIndex?.get(e);if(t===void 0)throw c$1.execution("UNKNOWN_PLUGIN_FUNCTION",`No registered plugin function named "${e}". A package must declare it in its pluginFunctions record and be registered before an expression using it is parsed.`,{functionName:e});if(t>65535)throw c$1.parsing("PLUGIN_FUNCTION_INDEX_TOO_LARGE",`Plugin-function index ${t} exceeds the two-byte bytecode limit (65535).`,{index:t});t<=255?(this.emitOpcode(50),this.emitIndex(t)):(this.emitOpcode(161),this.emitIndex(t&255),this.emitIndex(t>>8&255)),this.emitIndex(n);}emitOpcode(e){this.opcodes.push(e),(e===50||e===161)&&(this._hasAsync=true);}emitNumber(e){let n=Object.is(e,-0)?A:e,t=this.numberIndex.get(n);if(t===void 0){if(t=this.numbers.length,t>r)throw c$1.parsing("TOO_MANY_NUMERIC_CONSTANTS",`Expression has more than ${r+1} distinct numeric literals, exceeding the bytecode constant pool's limit.`,{limit:r+1});this.numbers.push(e),this.numberIndex.set(n,t);}this.opcodes.push(t);}emitString(e){let n=this.stringIndex.get(e);if(n===void 0){if(n=this.strings.length,n>r)throw c$1.parsing("TOO_MANY_STRING_CONSTANTS",`Expression has more than ${r+1} distinct string literals, exceeding the bytecode constant pool's limit.`,{limit:r+1});this.strings.push(e),this.stringIndex.set(e,n);}this.opcodes.push(n);}emitIndex(e){this.opcodes.push(m(e,"index"));}emitByte(e){this.opcodes.push(m(e,"byte"));}get currentLength(){return this.opcodes.length}emitUserFunctionBody(e,n,t){let u=this.userFunctionBodies.length;if(u>r)throw c$1.parsing("TOO_MANY_FUNCTION_DEFINITIONS",`More than ${r+1} function definitions on one line, exceeding the bytecode constant pool's limit.`,{limit:r+1});return this.userFunctionBodies.push({name:e,params:n,program:t}),u}emitAnonymousBody(e,n){let t=this.anonymousBodies.length;if(t>r)throw c$1.parsing("TOO_MANY_ANONYMOUS_BODIES",`More than ${r+1} map/reduce transform expressions on one line, exceeding the bytecode constant pool's limit.`,{limit:r+1});return this.anonymousBodies.push({params:e,program:n}),t}patchJump(e,n){if(e<0||e>=this.opcodes.length)throw c$1.parsing("BYTECODE_OPERAND_OUT_OF_RANGE",`patchJump was asked to write at position ${e}, outside the ${this.opcodes.length} bytes emitted so far.`,{position:e,length:this.opcodes.length});this.opcodes[e]=m(n,"jump target");}build(){return {opcodes:new Uint8Array(this.opcodes),numbers:this.numbers.length>0?new Float64Array(this.numbers):B,strings:this.strings.length>0?[...this.strings]:O,hasAsync:this._hasAsync,userFunctionBodies:this.userFunctionBodies.length>0?[...this.userFunctionBodies]:void 0,anonymousBodies:this.anonymousBodies.length>0?[...this.anonymousBodies]:void 0}}buildInto(e){let n=this.opcodes.length,t=this.numbers.length,u=e&&e.opcodes.length>=n,I=e&&e.numbers.length>=t,g=u?new Uint8Array(e.opcodes.buffer,e.opcodes.byteOffset,n):new Uint8Array(n),p=I?new Float64Array(e.numbers.buffer,e.numbers.byteOffset,t):new Float64Array(t);for(let c=0;c<n;c++)g[c]=this.opcodes[c];for(let c=0;c<t;c++)p[c]=this.numbers[c];return {opcodes:g,numbers:p,strings:[...this.strings],hasAsync:this._hasAsync,userFunctionBodies:this.userFunctionBodies.length>0?[...this.userFunctionBodies]:void 0,anonymousBodies:this.anonymousBodies.length>0?[...this.anonymousBodies]:void 0}}reset(){this.opcodes.length=0,this.numbers.length>0&&(this.numbers.length=0,this.numberIndex.clear()),this.strings.length>0&&(this.strings.length=0,this.stringIndex.clear()),this._hasAsync=false,this.userFunctionBodies.length>0&&(this.userFunctionBodies.length=0),this.anonymousBodies.length>0&&(this.anonymousBodies.length=0);}};var _=/^\d{1,3}(\.\d{3}){2,}$/,y=/^\d+$/;function R(i,e){let n=i.endsWith("n")?i.slice(0,-1):i;if(y.test(n))return n;let t=_.test(n)?n.split(".").join(""):x(n,e);if(!y.test(t)){let u=n.includes(".")?".":n.includes(",")?",":n;throw c$1.parsing("INVALID_NUMBER_LITERAL",`"${i}" is not a whole number: "${u}" separates decimals in the ${e} locale, and a whole number cannot have a fractional part.`,{raw:i,localeCode:e,separator:u})}return t}function x(i,e){let n=a$1(e).display.thousandsSeparator;return n?i.split(n).join(""):i}export{o as a,F as b,P as c,b as d,R as e};//# sourceMappingURL=chunk-U5MESNRT.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-U5MESNRT.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/parser/BindingPower.ts","../src/parser/BytecodeBuilder.ts","../src/parser/BigIntLiteral.ts"],"names":["BindingPower","BUILTIN_INFIX_BP","TokenTypes","_bpTable","buildBindingPowerTable","maxId","name","id","tokenTypeId","table","bp","invalidateBindingPowerTable","MAX_CONSTANT_POOL_INDEX","NEGATIVE_ZERO_KEY","checkedOperand","value","what","ErrorFactory","EMPTY_STRINGS","EMPTY_NUMBERS","BytecodeBuilder","pluginFunctionIndex","argCount","index","op","n","key","idx","s","b","params","program","position","target","buf","opLen","numLen","reuseOpcodes","reuseNumbers","opcodes","numbers","i","CHAINED_DOT_THOUSANDS_GROUPS","DIGITS_ONLY","bigIntLiteralDigits","raw","localeCode","withoutSuffix","digits","stripLocaleGrouping","separator","text","thousandsSeparator","getLocale"],"mappings":"4HAWO,IAAMA,CAAAA,CAAe,CAC1B,MAAA,CAAQ,CAAA,CACR,UAAA,CAAY,EAAA,CACZ,SAAA,CAAW,EAAA,CACX,UAAA,CAAY,EAAA,CAaZ,WAAA,CAAa,EAAA,CAab,SAAA,CAAW,EAAA,CACX,UAAA,CAAY,EAAA,CACZ,UAAA,CAAY,EAAA,CACZ,WAAA,CAAa,EAAA,CACb,KAAA,CAAO,EAAA,CACP,GAAA,CAAK,EAAA,CACL,OAAA,CAAS,EAAA,CAMT,WAAA,CAAa,EAAA,CAIb,QAAA,CAAU,GACV,MAAA,CAAQ,EAAA,CACR,OAAA,CAAS,EAAA,CACT,IAAA,CAAM,EACR,EAiDO,IAAMC,CAAAA,CAA2C,CAEtD,CAACC,CAAAA,CAAW,IAAI,EAAOF,CAAAA,CAAa,GAAA,CACpC,CAACE,CAAAA,CAAW,KAAK,EAAMF,CAAAA,CAAa,GAAA,CACpC,CAACE,C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,CAAI,GAAA,CAAMA,CAAAA,CAAc,QAAA,CAAS,GAAG,CAAA,CAAI,GAAA,CAAMA,CAAAA,CAC1F,MAAM9B,GAAAA,CAAa,OAAA,CAClB,wBAAA,CACA,CAAA,CAAA,EAAI4B,CAAG,CAAA,0BAAA,EAA6BK,CAAS,CAAA,4BAAA,EAA+BJ,CAAU,CAAA,0DAAA,CAAA,CACtF,CAAE,GAAA,CAAAD,CAAAA,CAAK,UAAA,CAAAC,CAAAA,CAAY,SAAA,CAAAI,CAAU,CAC9B,CACD,CACA,OAAOF,CACR,CASA,SAASC,CAAAA,CAAoBE,CAAAA,CAAcL,CAAAA,CAA4B,CACtE,IAAMM,CAAAA,CAAqBC,GAAAA,CAAUP,CAAU,CAAA,CAAE,OAAA,CAAQ,kBAAA,CACzD,OAAOM,CAAAA,CAAqBD,CAAAA,CAAK,KAAA,CAAMC,CAAkB,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA,CAAID,CACvE","file":"chunk-VLX7ZVK4.js","sourcesContent":["/**\n * Named precedence levels for the Pratt parser, from loosest (`Lowest`) to\n * tightest (`Call`) binding. A custom infix parselet compares its own\n * binding power against the current expression's to decide whether to\n * consume the next operator (higher power binds tighter, e.g. `*` over `+`).\n *\n * Package authors reference these when declaring an infix parselet in a\n * package's `infixParselets`. See the built-in packages for examples of\n * picking an appropriate level (e.g. arithmetic `+`/`-` use `Sum`, `*`/`/`\n * use `Product`).\n */\nexport const BindingPower = {\n Lowest: 0,\n Assignment: 10,\n LogicalOr: 12, // `or`, `||` — loosest of the boolean-logic operators\n LogicalAnd: 14, // `&&` — binds tighter than `or` (\"a or b and c\" = \"a or (b and c)\")\n // The word \"and\" (`AND_CONJ`), which is both arithmetic addition (\"5 and 3\"\n // is 8) and boolean conjunction (\"true and false\"). A phrase parselet\n // collecting a list (\"average of X, Y and Z\") parses each argument at this\n // level, and an argument stops at any operator whose power is <= the level it\n // was parsed at, so putting \"and\" here is what makes it end an argument\n // rather than be consumed as the addition it also is. Everything an argument\n // should keep binds tighter, including a genuine \"+\" (`Sum`).\n //\n // It sits BELOW `Conditional` because the boolean reading needs comparisons\n // to be its operands: at 28, \"5 > 3 and 2 > 1\" parsed as \"5 > (3 and 2) > 1\"\n // and answered false. Above `LogicalAnd` so that \"and\" is still the tighter\n // of the two conjunctions, and two steps off each neighbour to leave room.\n Conjunction: 16,\n // The bitwise trio and the shifts, ordered exactly as C and JavaScript order\n // them, which is the order every language that borrowed these operators from\n // C uses: `|` looser than `xor`, `xor` looser than `&`, all three looser than\n // comparison, and the shifts tighter than comparison but looser than `+`.\n // They used to share one level (35) between `Sum` and `Product`, so\n // \"1 + 2 << 3\" answered 17 where JavaScript answers 24 and \"4 & 3 + 1\"\n // answered 1 where JavaScript answers 4. Each has its own level now because\n // a shared level makes \"4 | 6 & 3\" group left instead of letting `&` win.\n //\n // They stay TIGHTER than `Conjunction` so that a phrase argument parsed at\n // that level (\"average of 5 | 3, 2 and 4\") keeps its bitwise operators\n // instead of stopping at the first one.\n BitwiseOr: 18, // `|`\n BitwiseXor: 20, // the `xor` keyword (`BIT_XOR`), not the `^` exponent token\n BitwiseAnd: 22, // `&`\n Conditional: 24, // comparisons (`==`, `<`, `>=`, ...), tighter than the bitwise trio, looser than the shifts\n Shift: 27, // `<<`, `>>`, `>>>`\n Sum: 30,\n Product: 40,\n // `±` (the uncertainty operator), tighter than `+ - * /` and looser than `^`,\n // so the tolerance attaches to its adjacent values: `12.3 ± 0.5 * 4` reads as\n // `(12.3 ± 0.5) * 4` (the parenthesised headline case), and `2 + 3 ± 0.5` as\n // `2 + (3 ± 0.5)`. A Tier-2 parselet (packages/uncertainty/), so this level is\n // read off the parselet rather than the Tier-1 BUILTIN_INFIX_BP table below.\n Uncertainty: 45,\n // `^`, RIGHT-associative: \"2 ^ 3 ^ 2\" is 2^(3^2) = 512, as in mathematics,\n // Python, Ruby and JavaScript's `**`. See PrecedenceParser.parseExpression\n // and BinaryOpParselet for the two places that associativity is implemented.\n Exponent: 50,\n Prefix: 60,\n Postfix: 70,\n Call: 80,\n} as const;\n\n/**\n * Set the binding power of a named operator.\n *\n * Binding power is what decides precedence in the Pratt parser: a higher number\n * binds tighter, so `*` outranks `+`. Changing one changes how every existing\n * expression using that operator parses, which is why packages should allocate\n * a new name rather than adjust a built-in.\n *\n * @param name - Operator name.\n * @param power - Higher binds tighter.\n */\nexport function setBindingPower(name: string, power: number): void {\n (BindingPower as Record<string, number>)[name] = power;\n}\n\n/**\n * Read the binding power of a named operator.\n *\n * @param name - Operator name.\n * @returns Its binding power, or 0 when the name is unknown, which makes an\n * unregistered operator terminate an expression rather than swallow the rest\n * of it.\n */\nexport function getBindingPower(name: string): number {\n return (BindingPower as Record<string, number>)[name] ?? 0;\n}\n\n// ── Built-in Infix Operator Binding Power Table ──────────────────────────────\n// Pre-computed Uint8Array lookup indexed by token typeId.\n// value > 0 → built-in infix operator with that binding power\n// value = 0 → not a built-in infix, fall through to Tier 2 parselet registry\n//\n// Built at module load via buildBindingPowerTable(). The table is sparse\n// most entries are 0 since only ~15 of 80+ token types are infix operators.\n//\n// Performance: Uint8Array[typeId] is a single typed array load, no Map.get()\n// no string hashing, no property chain. V8 eliminates bounds checks when typeId\n// is known to be within array length.\n\nimport { TokenTypes } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\n\n/**\n * Mapping of token type names → binding powers for built-in infix operators.\n * Only operators listed here get the Tier 1 fast path in PrecedenceParser.\n * All other infix tokens use the Tier 2 parselet registry fallback.\n */\nexport const BUILTIN_INFIX_BP: Record<string, number> = {\n // Arithmetic (infix, left-associative)\n [TokenTypes.PLUS]: BindingPower.Sum,\n [TokenTypes.MINUS]: BindingPower.Sum,\n [TokenTypes.STAR]: BindingPower.Product,\n [TokenTypes.SLASH]: BindingPower.Product,\n [TokenTypes.MOD]: BindingPower.Product,\n\n // Arithmetic (infix, RIGHT-associative, PrecedenceParser handles this specially)\n [TokenTypes.CARET]: BindingPower.Exponent,\n\n // Bitwise and shift (infix, left-associative), one level each, ordered as C\n // and JavaScript order them. `>>>` used to be missing from this table\n // entirely, which left it running at its Tier 2 parselet level while `>>`\n // ran at the Tier 1 one, so \"16 >> 3 & 1\" and \"16 >>> 3 & 1\" grouped\n // differently and answered 0 and 8.\n [TokenTypes.BIT_OR]: BindingPower.BitwiseOr,\n [TokenTypes.BIT_XOR]: BindingPower.BitwiseXor,\n [TokenTypes.BIT_AND]: BindingPower.BitwiseAnd,\n [TokenTypes.LSHIFT]: BindingPower.Shift,\n [TokenTypes.RSHIFT]: BindingPower.Shift,\n [TokenTypes.URSHIFT]: BindingPower.Shift,\n\n // Postfix (no right operand, PrecedenceParser handles this specially)\n [TokenTypes.PERCENT]: BindingPower.Postfix,\n\n // Percentage keyword (infix, left-associative: \"50% of 200\" → MUL)\n [TokenTypes.OF]: BindingPower.Product,\n};\n\n// Note: These token types are intentionally NOT in the BP_TABLE, they stay in\n// the Tier 2 parselet registry because they require complex handling:\n// IN, TO → UoM conversion parselets (peek at target unit token, complex logic)\n// DOT → Property access (chained OBJ_GET, needs left-token tracking)\n// EQUALS → Assignment (VariableParselet handles :var = expr pattern)\n// EQUALITY, NEQ, GTE, LTE → Comparison ops (need dedicated VM opcodes, task 2.15a)\n// COMMA → Argument separator (function calls, array/object literals)\n\n/** Cached BP_TABLE, built once at module load, immutable thereafter. */\nlet _bpTable: Uint8Array | null = null;\n\n/**\n * Build the Uint8Array binding power table indexed by token typeId.\n * Idempotent, returns cached table on subsequent calls.\n *\n * Must be called after all token types are registered (via registerAllTokenTypes())\n * and after plugin providers have registered their token types.\n */\nexport function buildBindingPowerTable(): Uint8Array {\n if (_bpTable) return _bpTable;\n\n // Size to the largest registered typeId + 1\n let maxId = 0;\n for (const name of Object.keys(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n // Also scan all TokenTypes to ensure table covers all registered IDs\n for (const name of Object.values(TokenTypes)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n\n const table = new Uint8Array(maxId + 1);\n for (const [name, bp] of Object.entries(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n table[id] = bp;\n }\n\n _bpTable = table;\n return table;\n}\n\n/**\n * Drop the cached table, so the next {@link buildBindingPowerTable} call builds\n * a fresh one sized to the token types registered by then.\n *\n * It does NOT add a plugin's operator to the Tier 1 fast path, which is what\n * this comment used to promise. The values in the table come from\n * `BUILTIN_INFIX_BP`, which is module-private and has no registration path, so\n * a rebuilt table holds the same binding powers and a plugin token still reads\n * 0. `PrecedenceParser.BP_TABLE` is a static initialized once at class\n * definition time and never re-read, so it would not see a rebuild anyway.\n *\n * A plugin's infix operator takes the Tier 2 parselet-registry route instead,\n * which is where an operator whose binding power the engine does not already\n * know is meant to live.\n */\nexport function invalidateBindingPowerTable(): void {\n _bpTable = null;\n}\n","import { OpCode } from \"@solve-js/parser/OpCode\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * `BytecodeProgram.opcodes` is a `Uint8Array`, every operand written into\n * it (including constant-pool indices from {@link BytecodeBuilder.emitNumber}/\n * {@link BytecodeBuilder.emitString}) is truncated to a single byte on\n * `build()`. Exceeding this silently wraps the index (e.g. entry 300 reads\n * back as entry 44), producing a wrong result with no error. See\n * {@link BytecodeBuilder.emitNumber} for the guard that turns this into a\n * thrown error instead.\n */\nconst MAX_CONSTANT_POOL_INDEX = 255;\n\n/** The `numberIndex` key for negative zero, which `Map` would otherwise fold into positive zero. */\nconst NEGATIVE_ZERO_KEY = \"-0\";\n\n/**\n * An operand that fits the byte the opcode stream stores it in, or a\n * structured refusal. `build()` copies the stream into a `Uint8Array`, which\n * keeps the low eight bits of whatever it is given: an operand of 300 used to\n * become 44 with no error, and the program then read a different constant,\n * plugin function or argument count from the one the parselet emitted. Every\n * raw operand goes through here, so a package author's mistake is reported at\n * compile time as a fault in the package rather than answered with a wrong\n * number.\n */\nfunction checkedOperand(value: number, what: string): number {\n\tif (!Number.isInteger(value) || value < 0 || value > 255) {\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"BYTECODE_OPERAND_OUT_OF_RANGE\",\n\t\t\t`A bytecode ${what} must be an integer from 0 to 255, but ${value} was emitted; the opcode stream stores one byte per operand.`,\n\t\t\t{ value, what }\n\t\t);\n\t}\n\treturn value;\n}\n\n/**\n * Compiled bytecode program produced by {@link BytecodeBuilder}.\n * Ready for consumption by {@link executeBytecode} without further processing.\n */\nexport interface BytecodeProgram {\n\topcodes: Uint8Array;\n\tnumbers: Float64Array;\n\tstrings: string[];\n\t/**\n\t * Numeric constants by opcode position, restored from a snapshot.\n\t *\n\t * Nothing in the compile path writes this: numbers are emitted inline into\n\t * {@link numbers} instead. `build()` used to attach an empty Map to every\n\t * program anyway, which was one allocation per compiled expression, around a\n\t * tenth of parse-and-compile time, for a collection that was never read.\n\t * It is left off now, and only {@link EngineSnapshot} sets it when restoring\n\t * a program that carried one; every reader already guards on its absence.\n\t */\n\tconstants?: Map<number, number>;\n\t/**\n\t * Whether the program contains any async opcodes (CALL_PLUGIN, etc.).\n\t * Set during compilation by the BytecodeBuilder. Allows the engine\n\t * to skip the O(n) resolver preflight check in O(1) for purely\n\t * synchronous expressions like `2 + 2`.\n\t */\n\thasAsync: boolean;\n\t/**\n\t * User-defined-function bodies compiled alongside this program (one\n\t * entry per `name(params) = body` definition on this line). See\n\t * {@link BytecodeBuilder.emitUserFunctionBody}. `OpCode.DEFINE_USER_FUNCTION`'s\n\t * operand is an index into this array, resolved at VM-execution time\n\t * (not parse time) so a diagnostic/lookahead parse that never actually\n\t * executes the definition line has no side effect on `vm.userFunctions`.\n\t */\n\tuserFunctionBodies?: UserFunctionDef[];\n\t/**\n\t * Anonymous function bodies compiled alongside this program, one entry\n\t * per `map`/`reduce` inline transform expression (e.g. the `10*x` in\n\t * `map(10*x, [0,1,500])`). See {@link BytecodeBuilder.emitAnonymousBody}.\n\t * Deliberately a SEPARATE side-table from `userFunctionBodies`, not\n\t * routed through `vm.userFunctions` at all: an inline body has no name\n\t * and must never leak into the persistent name-keyed registry the way\n\t * a real `f(x) = ...` definition does.\n\t */\n\tanonymousBodies?: AnonymousBodyDef[];\n}\n\n/**\n * An anonymous transform body for `map`/`reduce`'s inline-expression form\n * (e.g. `10*x` in `map(10*x, [0,1,500])`, or `acc+x` in `reduce(acc+x,\n * [1,2,3])`). Structurally identical to {@link UserFunctionDef} minus the\n * `name`. See `OpCode.MAP_INVOKE`/`REDUCE_INVOKE` and\n * `vm/VM.ts`'s handlers, which build a call frame from `params`/`args`\n * exactly like `CALL_USER_FUNCTION` does, just without ever registering\n * the body in `vm.userFunctions`.\n */\nexport interface AnonymousBodyDef {\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * A user-defined, parameterized, reusable function's compiled form\n * (`f(x) = 2*x + 1`). See `OpCode.DEFINE_USER_FUNCTION`/`CALL_USER_FUNCTION`\n * and `vm/VM.ts`'s `VM.defineUserFunction`/`getUserFunction`.\n *\n * `program` is the body compiled to its OWN independent `BytecodeProgram`,\n * not a fragment of the definition line's own bytecode. Parameter names\n * inside the body compile to ORDINARY `LOAD_VAR <name>` opcodes, no\n * parse-time rewriting, because parameter resolution happens dynamically\n * at the VM level: `CALL_USER_FUNCTION` pushes a name-keyed call frame\n * (`Map<string, Value>`) before re-executing `program`, and `VM.getVar()`\n * checks the innermost call frame before falling back to the flat\n * document-variable store. This is why a `UNIT`-collision parameter name\n * (e.g. `h` in `area(w, h) = w * h`, which lexes as the \"hour\" unit) needs\n * no special handling anywhere, it's just another `LOAD_VAR \"h\"`, resolved\n * the same way as any other name.\n */\nexport interface UserFunctionDef {\n\tname: string;\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * Shared empty collections for programs that emit none.\n *\n * `build()` runs once per compiled expression, so an empty array allocated\n * there is an allocation per line of every document. Most programs emit no\n * strings at all (only the unit and datetime parselets do), and one that emits\n * no numbers is common too, so both were routinely allocating an empty\n * container that nothing would ever read.\n *\n * Sharing them is safe because a built program is read-only downstream: the VM\n * and the snapshot writer only index and iterate these, and nothing in the\n * engine pushes to `program.strings` or `program.numbers`. They are frozen so\n * that a future writer fails loudly here rather than silently corrupting every\n * other program that shares the instance.\n */\nconst EMPTY_STRINGS: readonly string[] = Object.freeze([]);\nconst EMPTY_NUMBERS = new Float64Array(0);\n\n/**\n * Direct-to-bytecode compiler for the Pratt parser.\n *\n * Accumulates opcodes, numeric constants, and string references during parsing,\n * then produces a {@link BytecodeProgram} for VM execution. Supports:\n * - Standard build via {@link build}\n * - Zero-copy build into pre-allocated buffers via {@link buildInto}\n * - In-place reset for reuse without reallocation\n */\nexport class BytecodeBuilder {\n\tprivate opcodes: number[] = [];\n\tprivate numbers: number[] = [];\n\tprivate strings: string[] = [];\n\tprivate stringIndex = new Map<string, number>();\n\t/** Value (or {@link NEGATIVE_ZERO_KEY}) to its slot in `numbers`, so a repeated literal is emitted once. */\n\tprivate numberIndex = new Map<number | string, number>();\n\tprivate _hasAsync = false;\n\tprivate userFunctionBodies: UserFunctionDef[] = [];\n\tprivate anonymousBodies: AnonymousBodyDef[] = [];\n\n\t/**\n\t * The per-engine `plugin function name -> registry index` map, wired in by\n\t * the engine so {@link emitPluginCall} can resolve a name at emit time. The\n\t * same object reference is shared with every builder in an engine (the pool\n\t * and each ad-hoc nested-body builder), and the engine populates it as\n\t * packages register, so a parselet never sees the numeric index.\n\t */\n\tconstructor(private readonly pluginFunctionIndex?: ReadonlyMap<string, number>) {}\n\n\t/** The name->index map, so a nested-body builder inherits the same resolution. */\n\tget pluginIndexMap(): ReadonlyMap<string, number> | undefined {\n\t\treturn this.pluginFunctionIndex;\n\t}\n\n\t/**\n\t * Emit a plugin-function call by NAME. The engine assigns each registered\n\t * `pluginFunctions` entry an index at registration; this resolves the name to\n\t * that index and emits `CALL_PLUGIN` + index + argCount. Package authors emit\n\t * through this rather than a hand-allocated index.\n\t */\n\temitPluginCall(name: string, argCount: number): void {\n\t\tconst index = this.pluginFunctionIndex?.get(name);\n\t\tif (index === undefined) {\n\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\"UNKNOWN_PLUGIN_FUNCTION\",\n\t\t\t\t`No registered plugin function named \"${name}\". A package must declare it in its pluginFunctions record and be registered before an expression using it is parsed.`,\n\t\t\t\t{ functionName: name },\n\t\t\t);\n\t\t}\n\t\t// One byte covers the first 256 plugin functions; beyond that, the\n\t\t// wide opcode carries a two-byte little-endian index. Emitting the\n\t\t// narrow form whenever it fits keeps existing bytecode and snapshots\n\t\t// byte-for-byte unchanged. The index cannot exceed 65535 because the\n\t\t// allocator (allocatePluginFunctionIndex) caps it, but guard anyway so\n\t\t// a stray index is a clear error rather than a silently truncated byte.\n\t\tif (index > 0xffff) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"PLUGIN_FUNCTION_INDEX_TOO_LARGE\",\n\t\t\t\t`Plugin-function index ${index} exceeds the two-byte bytecode limit (65535).`,\n\t\t\t\t{ index },\n\t\t\t);\n\t\t}\n\t\tif (index <= 0xff) {\n\t\t\tthis.emitOpcode(OpCode.CALL_PLUGIN);\n\t\t\tthis.emitIndex(index);\n\t\t} else {\n\t\t\tthis.emitOpcode(OpCode.CALL_PLUGIN_WIDE);\n\t\t\tthis.emitIndex(index & 0xff); // low byte\n\t\t\tthis.emitIndex((index >> 8) & 0xff); // high byte\n\t\t}\n\t\tthis.emitIndex(argCount);\n\t}\n\n\t/** Emit an {@link OpCode} instruction. */\n\temitOpcode(op: OpCode): void {\n\t\tthis.opcodes.push(op);\n\t\tif (op === OpCode.CALL_PLUGIN || op === OpCode.CALL_PLUGIN_WIDE) {\n\t\t\tthis._hasAsync = true;\n\t\t}\n\t}\n\n\t/**\n\t * Emit a numeric literal: interns `n` into the program's constant pool\n\t * (deduplicated, like {@link emitString}) and writes its index into the\n\t * opcode stream (read back by the VM as e.g. `PUSH_NUMBER <idx>`).\n\t *\n\t * Deduplicated so that the 256-entry pool counts distinct values rather\n\t * than occurrences: a long line of repeated literals used to exhaust it\n\t * long before it held 256 different numbers. Negative zero keeps its own\n\t * slot, because `1 / -0` is not `1 / 0`; NaN shares one, since every NaN\n\t * reads the same.\n\t *\n\t * @throws If the pool would exceed 256 distinct entries.\n\t */\n\temitNumber(n: number): void {\n\t\tconst key = Object.is(n, -0) ? NEGATIVE_ZERO_KEY : n;\n\t\tlet idx = this.numberIndex.get(key);\n\t\tif (idx === undefined) {\n\t\t\tidx = this.numbers.length;\n\t\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\t\"TOO_MANY_NUMERIC_CONSTANTS\",\n\t\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} distinct numeric literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.numbers.push(n);\n\t\t\tthis.numberIndex.set(key, idx);\n\t\t}\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a string literal: interns `s` into the program's string pool\n\t * (deduplicated via `stringIndex`) and writes its index into the opcode\n\t * stream. Subject to the same constant-pool bound as {@link emitNumber},\n\t * but since strings ARE deduplicated, only distinct string values count\n\t * against the limit.\n\t *\n\t * @throws If the string pool would exceed 256 distinct entries.\n\t */\n\temitString(s: string): void {\n\t\tlet idx = this.stringIndex.get(s);\n\t\tif (idx === undefined) {\n\t\t\tidx = this.strings.length;\n\t\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\t\"TOO_MANY_STRING_CONSTANTS\",\n\t\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} distinct string literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.strings.push(s);\n\t\t\tthis.stringIndex.set(s, idx);\n\t\t}\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a raw numeric operand (0-255) following an opcode, e.g. a\n\t * plugin-function index for `CALL_PLUGIN`, or an argument count. Unlike\n\t * {@link emitOpcode}, this does not go through the `OpCode` enum, so\n\t * package authors use this (not an unsafe cast to `OpCode`) to push\n\t * operands their own opcode handler expects to read positionally.\n\t */\n\temitIndex(idx: number): void {\n\t\tthis.opcodes.push(checkedOperand(idx, \"index\"));\n\t}\n\n\t/** Emit a raw byte (0-255), used for fixed small operands like argument counts. */\n\temitByte(b: number): void {\n\t\tthis.opcodes.push(checkedOperand(b, \"byte\"));\n\t}\n\n\t/** Number of opcodes/operands emitted so far, used to compute jump targets before {@link patchJump}. */\n\tget currentLength(): number {\n\t\treturn this.opcodes.length;\n\t}\n\n\t/**\n\t * Register a compiled user-defined-function body, returning its index\n\t * into this program's `userFunctionBodies` side-table, the caller emits\n\t * that index as `DEFINE_USER_FUNCTION`'s operand via {@link emitIndex}.\n\t * Subject to the same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitNumber}/{@link emitString} (the index itself is a single\n\t * opcode-stream byte), in practice a single line defines at most a\n\t * handful of functions, so this limit is never realistically reached.\n\t *\n\t * @throws If more than 256 function bodies are registered on one program.\n\t */\n\temitUserFunctionBody(name: string, params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.userFunctionBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_FUNCTION_DEFINITIONS\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} function definitions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.userFunctionBodies.push({ name, params, program });\n\t\treturn idx;\n\t}\n\n\t/**\n\t * Register a compiled `map`/`reduce` anonymous transform body, returning\n\t * its index into this program's `anonymousBodies` side-table, the\n\t * caller emits that index as `MAP_INVOKE`/`REDUCE_INVOKE`'s operand via\n\t * {@link emitIndex}. Same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitUserFunctionBody}.\n\t *\n\t * @throws If more than 256 anonymous bodies are registered on one program.\n\t */\n\temitAnonymousBody(params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.anonymousBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_ANONYMOUS_BODIES\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} map/reduce transform expressions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.anonymousBodies.push({ params, program });\n\t\treturn idx;\n\t}\n\n\t/** Overwrite a previously-emitted placeholder operand at `position` with the real jump `target`, once known. */\n\tpatchJump(position: number, target: number): void {\n\t\tif (position < 0 || position >= this.opcodes.length) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"BYTECODE_OPERAND_OUT_OF_RANGE\",\n\t\t\t\t`patchJump was asked to write at position ${position}, outside the ${this.opcodes.length} bytes emitted so far.`,\n\t\t\t\t{ position, length: this.opcodes.length }\n\t\t\t);\n\t\t}\n\t\tthis.opcodes[position] = checkedOperand(target, \"jump target\");\n\t}\n\n\t/**\n\t * Build the accumulated opcodes/numbers/strings into a BytecodeProgram.\n\t * Creates new TypedArrays, the builder can be reused after this call.\n\t */\n\tbuild(): BytecodeProgram {\n\t\treturn {\n\t\t\topcodes: new Uint8Array(this.opcodes),\n\t\t\tnumbers: this.numbers.length > 0 ? new Float64Array(this.numbers) : EMPTY_NUMBERS,\n\t\t\t// Defensive copy when there is anything to copy: reset()'s\n\t\t\t// `.length = 0` would otherwise clear a reference the program still\n\t\t\t// holds. An empty one needs no copy, so it shares the frozen\n\t\t\t// singleton instead of allocating per program.\n\t\t\tstrings: this.strings.length > 0 ? [...this.strings] : (EMPTY_STRINGS as string[]),\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Build directly into a pre-allocated buffer for zero-copy VM consumption.\n\t *\n\t * When `buf` is provided and large enough, writes into it and returns\n\t * subarray **views** (not copies), the returned TypedArrays share the\n\t * buffer's underlying ArrayBuffer. The caller MUST NOT mutate the buffer\n\t * until the returned BytecodeProgram is no longer needed.\n\t *\n\t * If the caller intends to cache the result, they must copy the TypedArrays\n\t * (e.g. `new Uint8Array(program.opcodes)`) before reusing the buffer pool.\n\t *\n\t * When `buf` is omitted or too small, allocates fresh TypedArrays.\n\t */\n\tbuildInto(buf?: { opcodes: Uint8Array; numbers: Float64Array }): BytecodeProgram {\n\t\tconst opLen = this.opcodes.length;\n\t\tconst numLen = this.numbers.length;\n\n\t\tconst reuseOpcodes = buf && buf.opcodes.length >= opLen;\n\t\tconst reuseNumbers = buf && buf.numbers.length >= numLen;\n\n\t\t// Subarray views that share the buffer's ArrayBuffer (zero-copy)\n\t\tconst opcodes = reuseOpcodes\n\t\t\t? new Uint8Array(buf!.opcodes.buffer, buf!.opcodes.byteOffset, opLen)\n\t\t\t: new Uint8Array(opLen);\n\t\tconst numbers = reuseNumbers\n\t\t\t? new Float64Array(buf!.numbers.buffer, buf!.numbers.byteOffset, numLen)\n\t\t\t: new Float64Array(numLen);\n\n\t\t// Write data into the views\n\t\tfor (let i = 0; i < opLen; i++) opcodes[i] = this.opcodes[i];\n\t\tfor (let i = 0; i < numLen; i++) numbers[i] = this.numbers[i];\n\n\t\treturn {\n\t\t\topcodes,\n\t\t\tnumbers,\n\t\t\tstrings: [...this.strings],\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\treset(): void {\n\t\t// Retain backing stores with .length = 0 to avoid reallocation on growth.\n\t\t// = [] discards the ArrayBuffer, forcing V8 to reallocate on every push()\n\t\t// threshold (4→8→16→32...). For a 50-opcode expression, that's 3-4 copies.\n\t\tthis.opcodes.length = 0;\n\t\tif (this.numbers.length > 0) {\n\t\t\tthis.numbers.length = 0;\n\t\t\tthis.numberIndex.clear();\n\t\t}\n\t\t// Guarded on being non-empty. reset() runs once per compiled expression\n\t\t// and a CPU profile put it at over a tenth of parse-and-compile, which\n\t\t// is a lot for clearing collections that are usually already empty:\n\t\t// most expressions emit no strings, and user function bodies are rarer\n\t\t// still. Emptying an empty Map is not free, and neither is the write\n\t\t// barrier on a length assignment.\n\t\tif (this.strings.length > 0) {\n\t\t\tthis.strings.length = 0;\n\t\t\tthis.stringIndex.clear();\n\t\t}\n\t\tthis._hasAsync = false;\n\t\tif (this.userFunctionBodies.length > 0) this.userFunctionBodies.length = 0;\n\t\tif (this.anonymousBodies.length > 0) this.anonymousBodies.length = 0;\n\t}\n}\n","/**\n * Turning a `123n` literal's source text into the digits `PUSH_BIGINT` stores.\n *\n * The lexer coalesces thousands groups into the number token it is building,\n * accepting both `,` and `.` as the separator regardless of locale (see\n * `lexer/ExpressionLexer.ts`'s \"Thousands separators\" block). For a NUMBER that\n * is fine, because the separators are stripped again when the text is turned\n * into a double. For a BIGINT nothing stripped them: both consumers took the\n * token text, removed the trailing `n`, and handed the rest straight to\n * `BigInt()`.\n *\n * So `1.000n` reached `BigInt(\"1.000\")`, which throws a raw `SyntaxError` that\n * arrived at the host as UNEXPECTED_ERROR/INTERNAL: the engine reporting its\n * own bug for six characters a user typed. `1.01n` and `1.1n` were fine, which\n * is the tell that the `n` suffix was never the problem, the three-digit\n * thousands group was: a dot followed by exactly three digits is what the lexer\n * swallows, and one followed by one or two digits it leaves alone.\n *\n * Written once here rather than inline at both call sites. There are two\n * (`parser/PrecedenceParser.ts`'s Tier-1 switch and\n * `packages/biginteger/parselets/BigIntNumberParselet.ts`), they already held\n * identical copies of the `n`-stripping, and the two tiers disagreeing about a\n * literal is a bug shape this codebase has had before.\n *\n * @module BigIntLiteral\n */\n\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Two or more dot-separated groups of three, e.g. `1.234.567`.\n *\n * Unambiguous in any locale, since no locale writes two decimal points, so this\n * is stripped without consulting one. Same regex and same reasoning as\n * `NumberParselet.ts`'s copy for the NUMBER path.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/** Digits and nothing else, which is what `BigInt()` can be handed safely. */\nconst DIGITS_ONLY = /^\\d+$/;\n\n/**\n * The digit string behind a bigint literal.\n *\n * A bigint literal has no fractional part by construction: the lexer only emits\n * BIGINT when it saw no decimal point of its own and no exponent, so any `.` or\n * `,` still in the text got there as a thousands group. Which of the two the\n * writer meant is a locale question, and answering it wrongly would silently\n * change the value by three orders of magnitude, so only the separator this\n * locale actually uses for grouping is removed. Anything left over is refused\n * rather than guessed at.\n *\n * @param raw - The token's text, with or without the trailing `n`.\n * @param localeCode - The engine's active locale.\n * @returns A string of digits, ready for `BigInt()`.\n * @throws An `INVALID_NUMBER_LITERAL` parsing error when what is left is not a\n * whole number, e.g. `1.000n` in a locale that writes decimals with a dot.\n */\nexport function bigIntLiteralDigits(raw: string, localeCode: string): string {\n\tconst withoutSuffix = raw.endsWith(\"n\") ? raw.slice(0, -1) : raw;\n\n\t// The common case first: nothing was grouped, so there is nothing to decide.\n\tif (DIGITS_ONLY.test(withoutSuffix)) return withoutSuffix;\n\n\tconst digits = CHAINED_DOT_THOUSANDS_GROUPS.test(withoutSuffix)\n\t\t? withoutSuffix.split(\".\").join(\"\")\n\t\t: stripLocaleGrouping(withoutSuffix, localeCode);\n\n\tif (!DIGITS_ONLY.test(digits)) {\n\t\tconst separator = withoutSuffix.includes(\".\") ? \".\" : withoutSuffix.includes(\",\") ? \",\" : withoutSuffix;\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"INVALID_NUMBER_LITERAL\",\n\t\t\t`\"${raw}\" is not a whole number: \"${separator}\" separates decimals in the ${localeCode} locale, and a whole number cannot have a fractional part.`,\n\t\t\t{ raw, localeCode, separator },\n\t\t);\n\t}\n\treturn digits;\n}\n\n/**\n * Removes the active locale's own thousands separator and nothing else.\n *\n * @param text - The literal without its `n`.\n * @param localeCode - The engine's active locale.\n * @returns The text with grouping removed, which the caller then re-checks.\n */\nfunction stripLocaleGrouping(text: string, localeCode: string): string {\n\tconst thousandsSeparator = getLocale(localeCode).display.thousandsSeparator;\n\treturn thousandsSeparator ? text.split(thousandsSeparator).join(\"\") : text;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/parser/BindingPower.ts","../src/parser/BytecodeBuilder.ts","../src/parser/BigIntLiteral.ts"],"names":["BindingPower","BUILTIN_INFIX_BP","TokenTypes","_bpTable","buildBindingPowerTable","maxId","name","id","tokenTypeId","table","bp","invalidateBindingPowerTable","MAX_CONSTANT_POOL_INDEX","NEGATIVE_ZERO_KEY","checkedOperand","value","what","ErrorFactory","EMPTY_STRINGS","EMPTY_NUMBERS","BytecodeBuilder","pluginFunctionIndex","argCount","index","op","n","key","idx","s","b","params","program","position","target","buf","opLen","numLen","reuseOpcodes","reuseNumbers","opcodes","numbers","i","CHAINED_DOT_THOUSANDS_GROUPS","DIGITS_ONLY","bigIntLiteralDigits","raw","localeCode","withoutSuffix","digits","stripLocaleGrouping","separator","text","thousandsSeparator","getLocale"],"mappings":"4HAWO,IAAMA,CAAAA,CAAe,CAC1B,MAAA,CAAQ,CAAA,CACR,UAAA,CAAY,EAAA,CACZ,SAAA,CAAW,EAAA,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AS,GAAG,CAAA,CAAIA,CAAAA,CAAI,KAAA,CAAM,CAAA,CAAG,EAAE,CAAA,CAAIA,CAAAA,CAG7D,GAAIF,CAAAA,CAAY,IAAA,CAAKI,CAAa,CAAA,CAAG,OAAOA,CAAAA,CAE5C,IAAMC,CAAAA,CAASN,CAAAA,CAA6B,IAAA,CAAKK,CAAa,CAAA,CAC3DA,CAAAA,CAAc,KAAA,CAAM,GAAG,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA,CAChCE,CAAAA,CAAoBF,CAAAA,CAAeD,CAAU,CAAA,CAEhD,GAAI,CAACH,CAAAA,CAAY,IAAA,CAAKK,CAAM,CAAA,CAAG,CAC9B,IAAME,CAAAA,CAAYH,CAAAA,CAAc,QAAA,CAAS,GAAG,CAAA,CAAI,GAAA,CAAMA,CAAAA,CAAc,QAAA,CAAS,GAAG,CAAA,CAAI,GAAA,CAAMA,CAAAA,CAC1F,MAAM9B,GAAAA,CAAa,OAAA,CAClB,wBAAA,CACA,CAAA,CAAA,EAAI4B,CAAG,CAAA,0BAAA,EAA6BK,CAAS,CAAA,4BAAA,EAA+BJ,CAAU,CAAA,0DAAA,CAAA,CACtF,CAAE,GAAA,CAAAD,CAAAA,CAAK,UAAA,CAAAC,CAAAA,CAAY,SAAA,CAAAI,CAAU,CAC9B,CACD,CACA,OAAOF,CACR,CASA,SAASC,CAAAA,CAAoBE,CAAAA,CAAcL,CAAAA,CAA4B,CACtE,IAAMM,CAAAA,CAAqBC,GAAAA,CAAUP,CAAU,CAAA,CAAE,OAAA,CAAQ,kBAAA,CACzD,OAAOM,CAAAA,CAAqBD,CAAAA,CAAK,KAAA,CAAMC,CAAkB,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA,CAAID,CACvE","file":"chunk-U5MESNRT.js","sourcesContent":["/**\n * Named precedence levels for the Pratt parser, from loosest (`Lowest`) to\n * tightest (`Call`) binding. A custom infix parselet compares its own\n * binding power against the current expression's to decide whether to\n * consume the next operator (higher power binds tighter, e.g. `*` over `+`).\n *\n * Package authors reference these when declaring an infix parselet in a\n * package's `infixParselets`. See the built-in packages for examples of\n * picking an appropriate level (e.g. arithmetic `+`/`-` use `Sum`, `*`/`/`\n * use `Product`).\n */\nexport const BindingPower = {\n Lowest: 0,\n Assignment: 10,\n LogicalOr: 12, // `or`, `||` — loosest of the boolean-logic operators\n LogicalAnd: 14, // `&&` — binds tighter than `or` (\"a or b and c\" = \"a or (b and c)\")\n // The word \"and\" (`AND_CONJ`), which is both arithmetic addition (\"5 and 3\"\n // is 8) and boolean conjunction (\"true and false\"). A phrase parselet\n // collecting a list (\"average of X, Y and Z\") parses each argument at this\n // level, and an argument stops at any operator whose power is <= the level it\n // was parsed at, so putting \"and\" here is what makes it end an argument\n // rather than be consumed as the addition it also is. Everything an argument\n // should keep binds tighter, including a genuine \"+\" (`Sum`).\n //\n // It sits BELOW `Conditional` because the boolean reading needs comparisons\n // to be its operands: at 28, \"5 > 3 and 2 > 1\" parsed as \"5 > (3 and 2) > 1\"\n // and answered false. Above `LogicalAnd` so that \"and\" is still the tighter\n // of the two conjunctions, and two steps off each neighbour to leave room.\n Conjunction: 16,\n // The bitwise trio and the shifts, ordered exactly as C and JavaScript order\n // them, which is the order every language that borrowed these operators from\n // C uses: `|` looser than `xor`, `xor` looser than `&`, all three looser than\n // comparison, and the shifts tighter than comparison but looser than `+`.\n // They used to share one level (35) between `Sum` and `Product`, so\n // \"1 + 2 << 3\" answered 17 where JavaScript answers 24 and \"4 & 3 + 1\"\n // answered 1 where JavaScript answers 4. Each has its own level now because\n // a shared level makes \"4 | 6 & 3\" group left instead of letting `&` win.\n //\n // They stay TIGHTER than `Conjunction` so that a phrase argument parsed at\n // that level (\"average of 5 | 3, 2 and 4\") keeps its bitwise operators\n // instead of stopping at the first one.\n BitwiseOr: 18, // `|`\n BitwiseXor: 20, // the `xor` keyword (`BIT_XOR`), not the `^` exponent token\n BitwiseAnd: 22, // `&`\n Conditional: 24, // comparisons (`==`, `<`, `>=`, ...), tighter than the bitwise trio, looser than the shifts\n Shift: 27, // `<<`, `>>`, `>>>`\n Sum: 30,\n Product: 40,\n // `±` (the uncertainty operator), tighter than `+ - * /` and looser than `^`,\n // so the tolerance attaches to its adjacent values: `12.3 ± 0.5 * 4` reads as\n // `(12.3 ± 0.5) * 4` (the parenthesised headline case), and `2 + 3 ± 0.5` as\n // `2 + (3 ± 0.5)`. A Tier-2 parselet (packages/uncertainty/), so this level is\n // read off the parselet rather than the Tier-1 BUILTIN_INFIX_BP table below.\n Uncertainty: 45,\n // `^`, RIGHT-associative: \"2 ^ 3 ^ 2\" is 2^(3^2) = 512, as in mathematics,\n // Python, Ruby and JavaScript's `**`. See PrecedenceParser.parseExpression\n // and BinaryOpParselet for the two places that associativity is implemented.\n Exponent: 50,\n Prefix: 60,\n Postfix: 70,\n Call: 80,\n} as const;\n\n/**\n * Set the binding power of a named operator.\n *\n * Binding power is what decides precedence in the Pratt parser: a higher number\n * binds tighter, so `*` outranks `+`. Changing one changes how every existing\n * expression using that operator parses, which is why packages should allocate\n * a new name rather than adjust a built-in.\n *\n * @param name - Operator name.\n * @param power - Higher binds tighter.\n */\nexport function setBindingPower(name: string, power: number): void {\n (BindingPower as Record<string, number>)[name] = power;\n}\n\n/**\n * Read the binding power of a named operator.\n *\n * @param name - Operator name.\n * @returns Its binding power, or 0 when the name is unknown, which makes an\n * unregistered operator terminate an expression rather than swallow the rest\n * of it.\n */\nexport function getBindingPower(name: string): number {\n return (BindingPower as Record<string, number>)[name] ?? 0;\n}\n\n// ── Built-in Infix Operator Binding Power Table ──────────────────────────────\n// Pre-computed Uint8Array lookup indexed by token typeId.\n// value > 0 → built-in infix operator with that binding power\n// value = 0 → not a built-in infix, fall through to Tier 2 parselet registry\n//\n// Built at module load via buildBindingPowerTable(). The table is sparse\n// most entries are 0 since only ~15 of 80+ token types are infix operators.\n//\n// Performance: Uint8Array[typeId] is a single typed array load, no Map.get()\n// no string hashing, no property chain. V8 eliminates bounds checks when typeId\n// is known to be within array length.\n\nimport { TokenTypes } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\n\n/**\n * Mapping of token type names → binding powers for built-in infix operators.\n * Only operators listed here get the Tier 1 fast path in PrecedenceParser.\n * All other infix tokens use the Tier 2 parselet registry fallback.\n */\nexport const BUILTIN_INFIX_BP: Record<string, number> = {\n // Arithmetic (infix, left-associative)\n [TokenTypes.PLUS]: BindingPower.Sum,\n [TokenTypes.MINUS]: BindingPower.Sum,\n [TokenTypes.STAR]: BindingPower.Product,\n [TokenTypes.SLASH]: BindingPower.Product,\n [TokenTypes.MOD]: BindingPower.Product,\n\n // Arithmetic (infix, RIGHT-associative, PrecedenceParser handles this specially)\n [TokenTypes.CARET]: BindingPower.Exponent,\n\n // Bitwise and shift (infix, left-associative), one level each, ordered as C\n // and JavaScript order them. `>>>` used to be missing from this table\n // entirely, which left it running at its Tier 2 parselet level while `>>`\n // ran at the Tier 1 one, so \"16 >> 3 & 1\" and \"16 >>> 3 & 1\" grouped\n // differently and answered 0 and 8.\n [TokenTypes.BIT_OR]: BindingPower.BitwiseOr,\n [TokenTypes.BIT_XOR]: BindingPower.BitwiseXor,\n [TokenTypes.BIT_AND]: BindingPower.BitwiseAnd,\n [TokenTypes.LSHIFT]: BindingPower.Shift,\n [TokenTypes.RSHIFT]: BindingPower.Shift,\n [TokenTypes.URSHIFT]: BindingPower.Shift,\n\n // Postfix (no right operand, PrecedenceParser handles this specially)\n [TokenTypes.PERCENT]: BindingPower.Postfix,\n\n // Percentage keyword (infix, left-associative: \"50% of 200\" → MUL)\n [TokenTypes.OF]: BindingPower.Product,\n};\n\n// Note: These token types are intentionally NOT in the BP_TABLE, they stay in\n// the Tier 2 parselet registry because they require complex handling:\n// IN, TO → UoM conversion parselets (peek at target unit token, complex logic)\n// DOT → Property access (chained OBJ_GET, needs left-token tracking)\n// EQUALS → Assignment (VariableParselet handles :var = expr pattern)\n// EQUALITY, NEQ, GTE, LTE → Comparison ops (need dedicated VM opcodes, task 2.15a)\n// COMMA → Argument separator (function calls, array/object literals)\n\n/** Cached BP_TABLE, built once at module load, immutable thereafter. */\nlet _bpTable: Uint8Array | null = null;\n\n/**\n * Build the Uint8Array binding power table indexed by token typeId.\n * Idempotent, returns cached table on subsequent calls.\n *\n * Must be called after all token types are registered (via registerAllTokenTypes())\n * and after plugin providers have registered their token types.\n */\nexport function buildBindingPowerTable(): Uint8Array {\n if (_bpTable) return _bpTable;\n\n // Size to the largest registered typeId + 1\n let maxId = 0;\n for (const name of Object.keys(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n // Also scan all TokenTypes to ensure table covers all registered IDs\n for (const name of Object.values(TokenTypes)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n\n const table = new Uint8Array(maxId + 1);\n for (const [name, bp] of Object.entries(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n table[id] = bp;\n }\n\n _bpTable = table;\n return table;\n}\n\n/**\n * Drop the cached table, so the next {@link buildBindingPowerTable} call builds\n * a fresh one sized to the token types registered by then.\n *\n * It does NOT add a plugin's operator to the Tier 1 fast path, which is what\n * this comment used to promise. The values in the table come from\n * `BUILTIN_INFIX_BP`, which is module-private and has no registration path, so\n * a rebuilt table holds the same binding powers and a plugin token still reads\n * 0. `PrecedenceParser.BP_TABLE` is a static initialized once at class\n * definition time and never re-read, so it would not see a rebuild anyway.\n *\n * A plugin's infix operator takes the Tier 2 parselet-registry route instead,\n * which is where an operator whose binding power the engine does not already\n * know is meant to live.\n */\nexport function invalidateBindingPowerTable(): void {\n _bpTable = null;\n}\n","import { OpCode } from \"@solve-js/parser/OpCode\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * `BytecodeProgram.opcodes` is a `Uint8Array`, every operand written into\n * it (including constant-pool indices from {@link BytecodeBuilder.emitNumber}/\n * {@link BytecodeBuilder.emitString}) is truncated to a single byte on\n * `build()`. Exceeding this silently wraps the index (e.g. entry 300 reads\n * back as entry 44), producing a wrong result with no error. See\n * {@link BytecodeBuilder.emitNumber} for the guard that turns this into a\n * thrown error instead.\n */\nconst MAX_CONSTANT_POOL_INDEX = 255;\n\n/** The `numberIndex` key for negative zero, which `Map` would otherwise fold into positive zero. */\nconst NEGATIVE_ZERO_KEY = \"-0\";\n\n/**\n * An operand that fits the byte the opcode stream stores it in, or a\n * structured refusal. `build()` copies the stream into a `Uint8Array`, which\n * keeps the low eight bits of whatever it is given: an operand of 300 used to\n * become 44 with no error, and the program then read a different constant,\n * plugin function or argument count from the one the parselet emitted. Every\n * raw operand goes through here, so a package author's mistake is reported at\n * compile time as a fault in the package rather than answered with a wrong\n * number.\n */\nfunction checkedOperand(value: number, what: string): number {\n\tif (!Number.isInteger(value) || value < 0 || value > 255) {\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"BYTECODE_OPERAND_OUT_OF_RANGE\",\n\t\t\t`A bytecode ${what} must be an integer from 0 to 255, but ${value} was emitted; the opcode stream stores one byte per operand.`,\n\t\t\t{ value, what }\n\t\t);\n\t}\n\treturn value;\n}\n\n/**\n * Compiled bytecode program produced by {@link BytecodeBuilder}.\n * Ready for consumption by {@link executeBytecode} without further processing.\n */\nexport interface BytecodeProgram {\n\topcodes: Uint8Array;\n\tnumbers: Float64Array;\n\tstrings: string[];\n\t/**\n\t * Numeric constants by opcode position, restored from a snapshot.\n\t *\n\t * Nothing in the compile path writes this: numbers are emitted inline into\n\t * {@link numbers} instead. `build()` used to attach an empty Map to every\n\t * program anyway, which was one allocation per compiled expression, around a\n\t * tenth of parse-and-compile time, for a collection that was never read.\n\t * It is left off now, and only {@link EngineSnapshot} sets it when restoring\n\t * a program that carried one; every reader already guards on its absence.\n\t */\n\tconstants?: Map<number, number>;\n\t/**\n\t * Whether the program contains any async opcodes (CALL_PLUGIN, etc.).\n\t * Set during compilation by the BytecodeBuilder. Allows the engine\n\t * to skip the O(n) resolver preflight check in O(1) for purely\n\t * synchronous expressions like `2 + 2`.\n\t */\n\thasAsync: boolean;\n\t/**\n\t * User-defined-function bodies compiled alongside this program (one\n\t * entry per `name(params) = body` definition on this line). See\n\t * {@link BytecodeBuilder.emitUserFunctionBody}. `OpCode.DEFINE_USER_FUNCTION`'s\n\t * operand is an index into this array, resolved at VM-execution time\n\t * (not parse time) so a diagnostic/lookahead parse that never actually\n\t * executes the definition line has no side effect on `vm.userFunctions`.\n\t */\n\tuserFunctionBodies?: UserFunctionDef[];\n\t/**\n\t * Anonymous function bodies compiled alongside this program, one entry\n\t * per `map`/`reduce` inline transform expression (e.g. the `10*x` in\n\t * `map(10*x, [0,1,500])`). See {@link BytecodeBuilder.emitAnonymousBody}.\n\t * Deliberately a SEPARATE side-table from `userFunctionBodies`, not\n\t * routed through `vm.userFunctions` at all: an inline body has no name\n\t * and must never leak into the persistent name-keyed registry the way\n\t * a real `f(x) = ...` definition does.\n\t */\n\tanonymousBodies?: AnonymousBodyDef[];\n}\n\n/**\n * An anonymous transform body for `map`/`reduce`'s inline-expression form\n * (e.g. `10*x` in `map(10*x, [0,1,500])`, or `acc+x` in `reduce(acc+x,\n * [1,2,3])`). Structurally identical to {@link UserFunctionDef} minus the\n * `name`. See `OpCode.MAP_INVOKE`/`REDUCE_INVOKE` and\n * `vm/VM.ts`'s handlers, which build a call frame from `params`/`args`\n * exactly like `CALL_USER_FUNCTION` does, just without ever registering\n * the body in `vm.userFunctions`.\n */\nexport interface AnonymousBodyDef {\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * A user-defined, parameterized, reusable function's compiled form\n * (`f(x) = 2*x + 1`). See `OpCode.DEFINE_USER_FUNCTION`/`CALL_USER_FUNCTION`\n * and `vm/VM.ts`'s `VM.defineUserFunction`/`getUserFunction`.\n *\n * `program` is the body compiled to its OWN independent `BytecodeProgram`,\n * not a fragment of the definition line's own bytecode. Parameter names\n * inside the body compile to ORDINARY `LOAD_VAR <name>` opcodes, no\n * parse-time rewriting, because parameter resolution happens dynamically\n * at the VM level: `CALL_USER_FUNCTION` pushes a name-keyed call frame\n * (`Map<string, Value>`) before re-executing `program`, and `VM.getVar()`\n * checks the innermost call frame before falling back to the flat\n * document-variable store. This is why a `UNIT`-collision parameter name\n * (e.g. `h` in `area(w, h) = w * h`, which lexes as the \"hour\" unit) needs\n * no special handling anywhere, it's just another `LOAD_VAR \"h\"`, resolved\n * the same way as any other name.\n */\nexport interface UserFunctionDef {\n\tname: string;\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * Shared empty collections for programs that emit none.\n *\n * `build()` runs once per compiled expression, so an empty array allocated\n * there is an allocation per line of every document. Most programs emit no\n * strings at all (only the unit and datetime parselets do), and one that emits\n * no numbers is common too, so both were routinely allocating an empty\n * container that nothing would ever read.\n *\n * Sharing them is safe because a built program is read-only downstream: the VM\n * and the snapshot writer only index and iterate these, and nothing in the\n * engine pushes to `program.strings` or `program.numbers`. They are frozen so\n * that a future writer fails loudly here rather than silently corrupting every\n * other program that shares the instance.\n */\nconst EMPTY_STRINGS: readonly string[] = Object.freeze([]);\nconst EMPTY_NUMBERS = new Float64Array(0);\n\n/**\n * Direct-to-bytecode compiler for the Pratt parser.\n *\n * Accumulates opcodes, numeric constants, and string references during parsing,\n * then produces a {@link BytecodeProgram} for VM execution. Supports:\n * - Standard build via {@link build}\n * - Zero-copy build into pre-allocated buffers via {@link buildInto}\n * - In-place reset for reuse without reallocation\n */\nexport class BytecodeBuilder {\n\tprivate opcodes: number[] = [];\n\tprivate numbers: number[] = [];\n\tprivate strings: string[] = [];\n\tprivate stringIndex = new Map<string, number>();\n\t/** Value (or {@link NEGATIVE_ZERO_KEY}) to its slot in `numbers`, so a repeated literal is emitted once. */\n\tprivate numberIndex = new Map<number | string, number>();\n\tprivate _hasAsync = false;\n\tprivate userFunctionBodies: UserFunctionDef[] = [];\n\tprivate anonymousBodies: AnonymousBodyDef[] = [];\n\n\t/**\n\t * The per-engine `plugin function name -> registry index` map, wired in by\n\t * the engine so {@link emitPluginCall} can resolve a name at emit time. The\n\t * same object reference is shared with every builder in an engine (the pool\n\t * and each ad-hoc nested-body builder), and the engine populates it as\n\t * packages register, so a parselet never sees the numeric index.\n\t */\n\tconstructor(private readonly pluginFunctionIndex?: ReadonlyMap<string, number>) {}\n\n\t/** The name->index map, so a nested-body builder inherits the same resolution. */\n\tget pluginIndexMap(): ReadonlyMap<string, number> | undefined {\n\t\treturn this.pluginFunctionIndex;\n\t}\n\n\t/**\n\t * Emit a plugin-function call by NAME. The engine assigns each registered\n\t * `pluginFunctions` entry an index at registration; this resolves the name to\n\t * that index and emits `CALL_PLUGIN` + index + argCount. Package authors emit\n\t * through this rather than a hand-allocated index.\n\t */\n\temitPluginCall(name: string, argCount: number): void {\n\t\tconst index = this.pluginFunctionIndex?.get(name);\n\t\tif (index === undefined) {\n\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\"UNKNOWN_PLUGIN_FUNCTION\",\n\t\t\t\t`No registered plugin function named \"${name}\". A package must declare it in its pluginFunctions record and be registered before an expression using it is parsed.`,\n\t\t\t\t{ functionName: name },\n\t\t\t);\n\t\t}\n\t\t// One byte covers the first 256 plugin functions; beyond that, the\n\t\t// wide opcode carries a two-byte little-endian index. Emitting the\n\t\t// narrow form whenever it fits keeps existing bytecode and snapshots\n\t\t// byte-for-byte unchanged. The index cannot exceed 65535 because the\n\t\t// allocator (allocatePluginFunctionIndex) caps it, but guard anyway so\n\t\t// a stray index is a clear error rather than a silently truncated byte.\n\t\tif (index > 0xffff) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"PLUGIN_FUNCTION_INDEX_TOO_LARGE\",\n\t\t\t\t`Plugin-function index ${index} exceeds the two-byte bytecode limit (65535).`,\n\t\t\t\t{ index },\n\t\t\t);\n\t\t}\n\t\tif (index <= 0xff) {\n\t\t\tthis.emitOpcode(OpCode.CALL_PLUGIN);\n\t\t\tthis.emitIndex(index);\n\t\t} else {\n\t\t\tthis.emitOpcode(OpCode.CALL_PLUGIN_WIDE);\n\t\t\tthis.emitIndex(index & 0xff); // low byte\n\t\t\tthis.emitIndex((index >> 8) & 0xff); // high byte\n\t\t}\n\t\tthis.emitIndex(argCount);\n\t}\n\n\t/** Emit an {@link OpCode} instruction. */\n\temitOpcode(op: OpCode): void {\n\t\tthis.opcodes.push(op);\n\t\tif (op === OpCode.CALL_PLUGIN || op === OpCode.CALL_PLUGIN_WIDE) {\n\t\t\tthis._hasAsync = true;\n\t\t}\n\t}\n\n\t/**\n\t * Emit a numeric literal: interns `n` into the program's constant pool\n\t * (deduplicated, like {@link emitString}) and writes its index into the\n\t * opcode stream (read back by the VM as e.g. `PUSH_NUMBER <idx>`).\n\t *\n\t * Deduplicated so that the 256-entry pool counts distinct values rather\n\t * than occurrences: a long line of repeated literals used to exhaust it\n\t * long before it held 256 different numbers. Negative zero keeps its own\n\t * slot, because `1 / -0` is not `1 / 0`; NaN shares one, since every NaN\n\t * reads the same.\n\t *\n\t * @throws If the pool would exceed 256 distinct entries.\n\t */\n\temitNumber(n: number): void {\n\t\tconst key = Object.is(n, -0) ? NEGATIVE_ZERO_KEY : n;\n\t\tlet idx = this.numberIndex.get(key);\n\t\tif (idx === undefined) {\n\t\t\tidx = this.numbers.length;\n\t\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\t\"TOO_MANY_NUMERIC_CONSTANTS\",\n\t\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} distinct numeric literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.numbers.push(n);\n\t\t\tthis.numberIndex.set(key, idx);\n\t\t}\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a string literal: interns `s` into the program's string pool\n\t * (deduplicated via `stringIndex`) and writes its index into the opcode\n\t * stream. Subject to the same constant-pool bound as {@link emitNumber},\n\t * but since strings ARE deduplicated, only distinct string values count\n\t * against the limit.\n\t *\n\t * @throws If the string pool would exceed 256 distinct entries.\n\t */\n\temitString(s: string): void {\n\t\tlet idx = this.stringIndex.get(s);\n\t\tif (idx === undefined) {\n\t\t\tidx = this.strings.length;\n\t\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\t\"TOO_MANY_STRING_CONSTANTS\",\n\t\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} distinct string literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.strings.push(s);\n\t\t\tthis.stringIndex.set(s, idx);\n\t\t}\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a raw numeric operand (0-255) following an opcode, e.g. a\n\t * plugin-function index for `CALL_PLUGIN`, or an argument count. Unlike\n\t * {@link emitOpcode}, this does not go through the `OpCode` enum, so\n\t * package authors use this (not an unsafe cast to `OpCode`) to push\n\t * operands their own opcode handler expects to read positionally.\n\t */\n\temitIndex(idx: number): void {\n\t\tthis.opcodes.push(checkedOperand(idx, \"index\"));\n\t}\n\n\t/** Emit a raw byte (0-255), used for fixed small operands like argument counts. */\n\temitByte(b: number): void {\n\t\tthis.opcodes.push(checkedOperand(b, \"byte\"));\n\t}\n\n\t/** Number of opcodes/operands emitted so far, used to compute jump targets before {@link patchJump}. */\n\tget currentLength(): number {\n\t\treturn this.opcodes.length;\n\t}\n\n\t/**\n\t * Register a compiled user-defined-function body, returning its index\n\t * into this program's `userFunctionBodies` side-table, the caller emits\n\t * that index as `DEFINE_USER_FUNCTION`'s operand via {@link emitIndex}.\n\t * Subject to the same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitNumber}/{@link emitString} (the index itself is a single\n\t * opcode-stream byte), in practice a single line defines at most a\n\t * handful of functions, so this limit is never realistically reached.\n\t *\n\t * @throws If more than 256 function bodies are registered on one program.\n\t */\n\temitUserFunctionBody(name: string, params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.userFunctionBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_FUNCTION_DEFINITIONS\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} function definitions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.userFunctionBodies.push({ name, params, program });\n\t\treturn idx;\n\t}\n\n\t/**\n\t * Register a compiled `map`/`reduce` anonymous transform body, returning\n\t * its index into this program's `anonymousBodies` side-table, the\n\t * caller emits that index as `MAP_INVOKE`/`REDUCE_INVOKE`'s operand via\n\t * {@link emitIndex}. Same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitUserFunctionBody}.\n\t *\n\t * @throws If more than 256 anonymous bodies are registered on one program.\n\t */\n\temitAnonymousBody(params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.anonymousBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_ANONYMOUS_BODIES\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} map/reduce transform expressions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.anonymousBodies.push({ params, program });\n\t\treturn idx;\n\t}\n\n\t/** Overwrite a previously-emitted placeholder operand at `position` with the real jump `target`, once known. */\n\tpatchJump(position: number, target: number): void {\n\t\tif (position < 0 || position >= this.opcodes.length) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"BYTECODE_OPERAND_OUT_OF_RANGE\",\n\t\t\t\t`patchJump was asked to write at position ${position}, outside the ${this.opcodes.length} bytes emitted so far.`,\n\t\t\t\t{ position, length: this.opcodes.length }\n\t\t\t);\n\t\t}\n\t\tthis.opcodes[position] = checkedOperand(target, \"jump target\");\n\t}\n\n\t/**\n\t * Build the accumulated opcodes/numbers/strings into a BytecodeProgram.\n\t * Creates new TypedArrays, the builder can be reused after this call.\n\t */\n\tbuild(): BytecodeProgram {\n\t\treturn {\n\t\t\topcodes: new Uint8Array(this.opcodes),\n\t\t\tnumbers: this.numbers.length > 0 ? new Float64Array(this.numbers) : EMPTY_NUMBERS,\n\t\t\t// Defensive copy when there is anything to copy: reset()'s\n\t\t\t// `.length = 0` would otherwise clear a reference the program still\n\t\t\t// holds. An empty one needs no copy, so it shares the frozen\n\t\t\t// singleton instead of allocating per program.\n\t\t\tstrings: this.strings.length > 0 ? [...this.strings] : (EMPTY_STRINGS as string[]),\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Build directly into a pre-allocated buffer for zero-copy VM consumption.\n\t *\n\t * When `buf` is provided and large enough, writes into it and returns\n\t * subarray **views** (not copies), the returned TypedArrays share the\n\t * buffer's underlying ArrayBuffer. The caller MUST NOT mutate the buffer\n\t * until the returned BytecodeProgram is no longer needed.\n\t *\n\t * If the caller intends to cache the result, they must copy the TypedArrays\n\t * (e.g. `new Uint8Array(program.opcodes)`) before reusing the buffer pool.\n\t *\n\t * When `buf` is omitted or too small, allocates fresh TypedArrays.\n\t */\n\tbuildInto(buf?: { opcodes: Uint8Array; numbers: Float64Array }): BytecodeProgram {\n\t\tconst opLen = this.opcodes.length;\n\t\tconst numLen = this.numbers.length;\n\n\t\tconst reuseOpcodes = buf && buf.opcodes.length >= opLen;\n\t\tconst reuseNumbers = buf && buf.numbers.length >= numLen;\n\n\t\t// Subarray views that share the buffer's ArrayBuffer (zero-copy)\n\t\tconst opcodes = reuseOpcodes\n\t\t\t? new Uint8Array(buf!.opcodes.buffer, buf!.opcodes.byteOffset, opLen)\n\t\t\t: new Uint8Array(opLen);\n\t\tconst numbers = reuseNumbers\n\t\t\t? new Float64Array(buf!.numbers.buffer, buf!.numbers.byteOffset, numLen)\n\t\t\t: new Float64Array(numLen);\n\n\t\t// Write data into the views\n\t\tfor (let i = 0; i < opLen; i++) opcodes[i] = this.opcodes[i];\n\t\tfor (let i = 0; i < numLen; i++) numbers[i] = this.numbers[i];\n\n\t\treturn {\n\t\t\topcodes,\n\t\t\tnumbers,\n\t\t\tstrings: [...this.strings],\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\treset(): void {\n\t\t// Retain backing stores with .length = 0 to avoid reallocation on growth.\n\t\t// = [] discards the ArrayBuffer, forcing V8 to reallocate on every push()\n\t\t// threshold (4→8→16→32...). For a 50-opcode expression, that's 3-4 copies.\n\t\tthis.opcodes.length = 0;\n\t\tif (this.numbers.length > 0) {\n\t\t\tthis.numbers.length = 0;\n\t\t\tthis.numberIndex.clear();\n\t\t}\n\t\t// Guarded on being non-empty. reset() runs once per compiled expression\n\t\t// and a CPU profile put it at over a tenth of parse-and-compile, which\n\t\t// is a lot for clearing collections that are usually already empty:\n\t\t// most expressions emit no strings, and user function bodies are rarer\n\t\t// still. Emptying an empty Map is not free, and neither is the write\n\t\t// barrier on a length assignment.\n\t\tif (this.strings.length > 0) {\n\t\t\tthis.strings.length = 0;\n\t\t\tthis.stringIndex.clear();\n\t\t}\n\t\tthis._hasAsync = false;\n\t\tif (this.userFunctionBodies.length > 0) this.userFunctionBodies.length = 0;\n\t\tif (this.anonymousBodies.length > 0) this.anonymousBodies.length = 0;\n\t}\n}\n","/**\n * Turning a `123n` literal's source text into the digits `PUSH_BIGINT` stores.\n *\n * The lexer coalesces thousands groups into the number token it is building,\n * accepting both `,` and `.` as the separator regardless of locale (see\n * `lexer/ExpressionLexer.ts`'s \"Thousands separators\" block). For a NUMBER that\n * is fine, because the separators are stripped again when the text is turned\n * into a double. For a BIGINT nothing stripped them: both consumers took the\n * token text, removed the trailing `n`, and handed the rest straight to\n * `BigInt()`.\n *\n * So `1.000n` reached `BigInt(\"1.000\")`, which throws a raw `SyntaxError` that\n * arrived at the host as UNEXPECTED_ERROR/INTERNAL: the engine reporting its\n * own bug for six characters a user typed. `1.01n` and `1.1n` were fine, which\n * is the tell that the `n` suffix was never the problem, the three-digit\n * thousands group was: a dot followed by exactly three digits is what the lexer\n * swallows, and one followed by one or two digits it leaves alone.\n *\n * Written once here rather than inline at both call sites. There are two\n * (`parser/PrecedenceParser.ts`'s Tier-1 switch and\n * `packages/biginteger/parselets/BigIntNumberParselet.ts`), they already held\n * identical copies of the `n`-stripping, and the two tiers disagreeing about a\n * literal is a bug shape this codebase has had before.\n *\n * @module BigIntLiteral\n */\n\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Two or more dot-separated groups of three, e.g. `1.234.567`.\n *\n * Unambiguous in any locale, since no locale writes two decimal points, so this\n * is stripped without consulting one. Same regex and same reasoning as\n * `NumberParselet.ts`'s copy for the NUMBER path.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/** Digits and nothing else, which is what `BigInt()` can be handed safely. */\nconst DIGITS_ONLY = /^\\d+$/;\n\n/**\n * The digit string behind a bigint literal.\n *\n * A bigint literal has no fractional part by construction: the lexer only emits\n * BIGINT when it saw no decimal point of its own and no exponent, so any `.` or\n * `,` still in the text got there as a thousands group. Which of the two the\n * writer meant is a locale question, and answering it wrongly would silently\n * change the value by three orders of magnitude, so only the separator this\n * locale actually uses for grouping is removed. Anything left over is refused\n * rather than guessed at.\n *\n * @param raw - The token's text, with or without the trailing `n`.\n * @param localeCode - The engine's active locale.\n * @returns A string of digits, ready for `BigInt()`.\n * @throws An `INVALID_NUMBER_LITERAL` parsing error when what is left is not a\n * whole number, e.g. `1.000n` in a locale that writes decimals with a dot.\n */\nexport function bigIntLiteralDigits(raw: string, localeCode: string): string {\n\tconst withoutSuffix = raw.endsWith(\"n\") ? raw.slice(0, -1) : raw;\n\n\t// The common case first: nothing was grouped, so there is nothing to decide.\n\tif (DIGITS_ONLY.test(withoutSuffix)) return withoutSuffix;\n\n\tconst digits = CHAINED_DOT_THOUSANDS_GROUPS.test(withoutSuffix)\n\t\t? withoutSuffix.split(\".\").join(\"\")\n\t\t: stripLocaleGrouping(withoutSuffix, localeCode);\n\n\tif (!DIGITS_ONLY.test(digits)) {\n\t\tconst separator = withoutSuffix.includes(\".\") ? \".\" : withoutSuffix.includes(\",\") ? \",\" : withoutSuffix;\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"INVALID_NUMBER_LITERAL\",\n\t\t\t`\"${raw}\" is not a whole number: \"${separator}\" separates decimals in the ${localeCode} locale, and a whole number cannot have a fractional part.`,\n\t\t\t{ raw, localeCode, separator },\n\t\t);\n\t}\n\treturn digits;\n}\n\n/**\n * Removes the active locale's own thousands separator and nothing else.\n *\n * @param text - The literal without its `n`.\n * @param localeCode - The engine's active locale.\n * @returns The text with grouping removed, which the caller then re-checks.\n */\nfunction stripLocaleGrouping(text: string, localeCode: string): string {\n\tconst thousandsSeparator = getLocale(localeCode).display.thousandsSeparator;\n\treturn thousandsSeparator ? text.split(thousandsSeparator).join(\"\") : text;\n}\n"]}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
'use strict';var chunkP5YWBIIU_cjs=require('./chunk-P5YWBIIU.cjs'),chunkR3W53ZMP_cjs=require('./chunk-R3W53ZMP.cjs'),chunkTTFO4YDP_cjs=require('./chunk-TTFO4YDP.cjs'),chunkLI6LYJDA_cjs=require('./chunk-LI6LYJDA.cjs'),chunkHG4NPDN5_cjs=require('./chunk-HG4NPDN5.cjs'),chunkQOOTRUY7_cjs=require('./chunk-QOOTRUY7.cjs'),chunkM4UC2PB6_cjs=require('./chunk-M4UC2PB6.cjs'),chunkK3PZ66XR_cjs=require('./chunk-K3PZ66XR.cjs'),chunkYV4GDW5A_cjs=require('./chunk-YV4GDW5A.cjs'),chunkUURM7P3P_cjs=require('./chunk-UURM7P3P.cjs'),chunkZLRJ7TDP_cjs=require('./chunk-ZLRJ7TDP.cjs'),chunkFESR6PZI_cjs=require('./chunk-FESR6PZI.cjs'),chunkWFT3XUSH_cjs=require('./chunk-WFT3XUSH.cjs'),chunkEQNKDTMX_cjs=require('./chunk-EQNKDTMX.cjs'),chunkS3SPDK6N_cjs=require('./chunk-S3SPDK6N.cjs'),chunk2XOLAHW6_cjs=require('./chunk-2XOLAHW6.cjs'),chunk3MG7VIPL_cjs=require('./chunk-3MG7VIPL.cjs'),chunkY7O4D3BJ_cjs=require('./chunk-Y7O4D3BJ.cjs'),chunk72J5V7SN_cjs=require('./chunk-72J5V7SN.cjs'),chunkYBQOQTVL_cjs=require('./chunk-YBQOQTVL.cjs'),chunkS3DFU33X_cjs=require('./chunk-S3DFU33X.cjs'),chunk6SYU4MH7_cjs=require('./chunk-6SYU4MH7.cjs');function jt(n,e,t,r,i){let s=t[e],o=r[e];if(!s||!o)return;let l=new Set(Object.keys(s));for(let a of Object.keys(o))l.has(a)&&i.push({kind:n,severity:"warning",detail:`Both "${t.name}" and "${r.name}" register a ${e==="prefixParselets"?"prefix":"infix"} parselet for token type "${a}" \u2014 the later-registered one silently wins.`,packages:[t.name,r.name]});}function Wt(n,e){let t=[];if(jt("prefixParseletTokenType","prefixParselets",n,e,t),jt("infixParseletTokenType","infixParselets",n,e,t),n.phrases&&e.phrases)for(let[s,o]of Object.entries(e.phrases)){let l=n.phrases[s];l!==void 0&&l!==o&&t.push({kind:"phrase",severity:"warning",detail:`Both "${n.name}" (-> "${l}") and "${e.name}" (-> "${o}") fuse the phrase "${s}" to DIFFERENT token types \u2014 PhraseTrie has no collision detection of its own, so the later-registered mapping silently wins with no other signal.`,packages:[n.name,e.name]});}if(n.asConverters&&e.asConverters)for(let s of Object.keys(e.asConverters)){let o=s.toLowerCase();Object.keys(n.asConverters).some(l=>l.toLowerCase()===o)&&t.push({kind:"converterName",severity:"warning",detail:`Both "${n.name}" and "${e.name}" register an "as ${s}" converter \u2014 the later-registered handler silently wins.`,packages:[n.name,e.name]});}if(n.pluginFunctions&&e.pluginFunctions){let s=new Set(Object.keys(n.pluginFunctions));for(let o of Object.keys(e.pluginFunctions))s.has(o)&&t.push({kind:"pluginFunctionName",severity:"warning",detail:`Both "${n.name}" and "${e.name}" register a plugin function named "${o}" \u2014 the later registration wins in the engine's name-to-index map. Give each package's functions package-unique names.`,packages:[n.name,e.name]});}if(n.normalizerRules&&e.normalizerRules){let s=new Set(n.normalizerRules.map(o=>o.name));for(let o of e.normalizerRules)s.has(o.name)&&t.push({kind:"normalizerRuleName",severity:"warning",detail:`Both "${n.name}" and "${e.name}" register a normalizer rule named "${o.name}" \u2014 the normalizer unregisters rules by name, so removing either package would drop both rules. Give each package's rules a package-unique name.`,packages:[n.name,e.name]});}let r=n.lexerVocabulary,i=e.lexerVocabulary;if(r?.keywords&&i?.keywords)for(let[s,o]of Object.entries(i.keywords)){let l=r.keywords[s];l!==void 0&&l!==o&&t.push({kind:"lexerKeyword",severity:"error",detail:`Both "${n.name}" (-> "${l}") and "${e.name}" (-> "${o}") register the lexer keyword "${s}" for DIFFERENT token types \u2014 whichever package registers second wins, and the loser's grammar becomes silently unreachable for that word.`,packages:[n.name,e.name]});}if(r?.operators&&i?.operators)for(let[s,o]of Object.entries(i.operators)){let l=r.operators[s];l!==void 0&&l!==o&&t.push({kind:"lexerOperator",severity:"error",detail:`Both "${n.name}" (-> "${l}") and "${e.name}" (-> "${o}") register the lexer operator "${s}" for DIFFERENT token types.`,packages:[n.name,e.name]});}if(n.asyncResolvers&&e.asyncResolvers){let s=new Set(n.asyncResolvers.map(o=>o.namespace));for(let o of e.asyncResolvers)s.has(o.namespace)&&t.push({kind:"asyncResolverNamespace",severity:"error",detail:`Both "${n.name}" and "${e.name}" register an async resolver under the namespace "${o.namespace}" \u2014 ResolverRegistry is keyed by namespace, so one resolver's cache/preflight state will silently clobber the other's.`,packages:[n.name,e.name]});}if(n.tokenCategories&&e.tokenCategories)for(let[s,o]of Object.entries(e.tokenCategories)){let l=n.tokenCategories[s];l!==void 0&&l!==o&&t.push({kind:"tokenCategory",severity:"info",detail:`Both "${n.name}" (-> "${l}") and "${e.name}" (-> "${o}") declare a highlight category for token type "${s}" \u2014 cosmetic only, but the later registration wins.`,packages:[n.name,e.name]});}return t}function Zn(n,e){let t=[];for(let r of e)r===n||r.name===n.name||t.push(...Wt(r,n));return {compatible:!t.some(r=>r.severity==="error"),conflicts:t}}var ve=class{constructor(){this.prefixOwners=new Map;this.infixOwners=new Map;this.phraseOwners=new Map;this.converterOwners=new Map;this.pluginFnOwners=new Map;this.ruleOwners=new Map;this.keywordOwners=new Map;this.operatorOwners=new Map;this.resolverOwners=new Map;this.categoryOwners=new Map;}check(e){let t=new Set,r=(s,o)=>{let l=s.get(o);l&&l!==e&&l.name!==e.name&&t.add(l);};if(e.prefixParselets)for(let s of Object.keys(e.prefixParselets))r(this.prefixOwners,s);if(e.infixParselets)for(let s of Object.keys(e.infixParselets))r(this.infixOwners,s);if(e.phrases)for(let s of Object.keys(e.phrases))r(this.phraseOwners,s);if(e.asConverters)for(let s of Object.keys(e.asConverters))r(this.converterOwners,s.toLowerCase());if(e.pluginFunctions)for(let s of Object.keys(e.pluginFunctions))r(this.pluginFnOwners,s);if(e.normalizerRules)for(let s of e.normalizerRules)r(this.ruleOwners,s.name);if(e.lexerVocabulary?.keywords)for(let s of Object.keys(e.lexerVocabulary.keywords))r(this.keywordOwners,s);if(e.lexerVocabulary?.operators)for(let s of Object.keys(e.lexerVocabulary.operators))r(this.operatorOwners,s);if(e.asyncResolvers)for(let s of e.asyncResolvers)r(this.resolverOwners,s.namespace);if(e.tokenCategories)for(let s of Object.keys(e.tokenCategories))r(this.categoryOwners,s);let i=[];for(let s of t)i.push(...Wt(s,e));return i}add(e){let t=(r,i)=>{r.has(i)||r.set(i,e);};if(e.prefixParselets)for(let r of Object.keys(e.prefixParselets))t(this.prefixOwners,r);if(e.infixParselets)for(let r of Object.keys(e.infixParselets))t(this.infixOwners,r);if(e.phrases)for(let r of Object.keys(e.phrases))t(this.phraseOwners,r);if(e.asConverters)for(let r of Object.keys(e.asConverters))t(this.converterOwners,r.toLowerCase());if(e.pluginFunctions)for(let r of Object.keys(e.pluginFunctions))t(this.pluginFnOwners,r);if(e.normalizerRules)for(let r of e.normalizerRules)t(this.ruleOwners,r.name);if(e.lexerVocabulary?.keywords)for(let r of Object.keys(e.lexerVocabulary.keywords))t(this.keywordOwners,r);if(e.lexerVocabulary?.operators)for(let r of Object.keys(e.lexerVocabulary.operators))t(this.operatorOwners,r);if(e.asyncResolvers)for(let r of e.asyncResolvers)t(this.resolverOwners,r.namespace);if(e.tokenCategories)for(let r of Object.keys(e.tokenCategories))t(this.categoryOwners,r);}rebuild(e){for(let t of [this.prefixOwners,this.infixOwners,this.phraseOwners,this.converterOwners,this.pluginFnOwners,this.ruleOwners,this.keywordOwners,this.operatorOwners,this.resolverOwners,this.categoryOwners])t.clear();for(let t of e)this.add(t);}};var Tn=/(\d+)\.(\d+)\.(\d+)/,Rn=/^\d+$/;function Ht(n){let e=Tn.exec(n.trim());return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function Nn(n,e){return n[0]-e[0]||n[1]-e[1]||n[2]-e[2]}function De(n){let e=n.split(".");if(e.length===0||e.length>3)return null;let t=[0,0,0];for(let r=0;r<e.length;r++){if(!Rn.test(e[r]))return null;t[r]=Number(e[r]);}return [t[0],t[1],t[2]]}function wn([n,e,t]){let r=n>0?[n+1,0,0]:e>0?[0,e+1,0]:[0,0,t+1];return [{op:">=",v:[n,e,t]},{op:"<",v:r}]}function An([n,e,t]){return [{op:">=",v:[n,e,t]},{op:"<",v:[n,e+1,0]}]}function Pn(n){if(n===""||n==="*"||n==="x"||n==="X")return [];if(n[0]==="^"){let i=De(n.slice(1));return i&&wn(i)}if(n[0]==="~"){let i=De(n.slice(1));return i&&An(i)}let e=/^(>=|<=|>|<|=)/.exec(n),t=e?e[1]:"=",r=De(e?n.slice(e[1].length):n);return r&&[{op:t,v:r}]}function Kt(n){let e=[];for(let t of n.split("||")){let r=t.trim().split(/\s+/).filter(s=>s!==""),i=[];for(let s of r){let o=Pn(s);if(o===null)return null;i.push(...o);}e.push(i);}return e}function Gt(n){return Kt(n.trim())!==null}function On(n,e){let t=Nn(n,e.v);switch(e.op){case "<":return t<0;case "<=":return t<=0;case ">":return t>0;case ">=":return t>=0;case "=":return t===0}}function qt(n,e){let t=Kt(e.trim());return t===null?false:t.some(r=>r.every(i=>On(n,i)))}function Ln(n,e=chunk2XOLAHW6_cjs.a){if(!n.engineVersion)return {compatible:true};if(!Gt(n.engineVersion))return {compatible:false,reason:"invalid-range",declaredRange:n.engineVersion,engineVersion:e};let t=Ht(e);return t===null||!qt(t,n.engineVersion)?{compatible:false,reason:"range-not-satisfied",declaredRange:n.engineVersion,engineVersion:e}:{compatible:true}}function Qt(n,e=chunk2XOLAHW6_cjs.a){let t=Ln(n,e);if(!t.compatible)throw t.reason==="invalid-range"?chunk6SYU4MH7_cjs.c.config({code:"PACKAGE_ENGINE_VERSION_INVALID_RANGE",message:`Package "${n.name}" declares an invalid engineVersion range: "${t.declaredRange}" is not a valid semver range.`,expected:'a valid semver range string (e.g. "^0.1.0", ">=0.2.0 <1.0.0")',found:`"${t.declaredRange}"`,suggestion:`This is a range-syntax typo in "${n.name}"'s own descriptor, not a version mismatch with the running engine \u2014 check for a stray character.`,context:{packageName:n.name,declaredRange:t.declaredRange}}):chunk6SYU4MH7_cjs.c.config({code:"PACKAGE_ENGINE_VERSION_MISMATCH",message:`Package "${n.name}" declares engineVersion "${t.declaredRange}", which is not satisfied by the running engine version "${t.engineVersion}".`,expected:`an engine version satisfying "${t.declaredRange}"`,found:`engine version "${t.engineVersion}"`,suggestion:`Update "${n.name}" to a version built against solve-engine ${t.engineVersion}, or pin solve-engine to a version satisfying "${t.declaredRange}".`,context:{packageName:n.name,declaredRange:t.declaredRange,engineVersion:t.engineVersion}})}var ee="solve-engine/snapshot",Q=1;function $(n){return Number.isFinite(n)?n:Number.isNaN(n)?"NaN":n>0?"Infinity":"-Infinity"}function U(n){if(typeof n=="number")return n;if(n==="NaN")return NaN;if(n==="Infinity")return 1/0;if(n==="-Infinity")return -1/0;throw chunk6SYU4MH7_cjs.c.validation({code:M.SNAPSHOT_MALFORMED,message:`Snapshot holds an unrecognised number sentinel: ${JSON.stringify(n)}`,expected:'a JSON number, or one of "NaN", "Infinity", "-Infinity"',found:JSON.stringify(n)})}var M={SNAPSHOT_VERSION_MISMATCH:"SNAPSHOT_VERSION_MISMATCH",SNAPSHOT_MALFORMED:"SNAPSHOT_MALFORMED",SNAPSHOT_UNSUPPORTED_VALUE:"SNAPSHOT_UNSUPPORTED_VALUE"};function Yt(n){return {coef:n.coef.toString(),scale:n.scale}}function Xt(n){return {coef:BigInt(n.coef),scale:n.scale}}function In(n){return {n:n.n.toString(),d:n.d.toString()}}function Dn(n){return {n:BigInt(n.n),d:BigInt(n.d)}}function Jt(n){return chunkS3SPDK6N_cjs.g[n]??String(n)}function Me(n,e){throw chunk6SYU4MH7_cjs.c.validation({code:M.SNAPSHOT_UNSUPPORTED_VALUE,message:`A ${Jt(n)} value (${e}) cannot be included in a snapshot yet.`,expected:"a concrete number, string, boolean, unit, range, matrix, bigint, or money value",found:`${Jt(n)} value`,suggestion:"Symbolic (algebra) values are deferred to a follow-up. Evaluate the document without the symbolic line, or re-derive it after restoring.",context:{valueType:n,location:e}})}function Ve(n,e){switch(n.type){case 0:{let t={t:0,v:$(n.value)};return n.exact!==void 0&&(t.exact=Yt(n.exact)),n.rational!==void 0&&(t.rational=In(n.rational)),t}case 1:{let t=n.value;return typeof t=="bigint"?{t:1,v:t.toString(),big:true,base:n.unit}:{t:1,v:$(t),base:n.unit}}case 2:return {t:2,v:n.value.toString()};case 3:return {t:3,v:n.value};case 4:{let t={t:4,v:$(n.value)};return n.grain!==void 0&&(t.g=n.grain),n.zone!==void 0&&(t.z=n.zone),t}case 5:return {t:5,v:$(n.value)};case 6:{let t={t:6,v:$(n.value),unit:n.unit??""};return n.exact!==void 0&&(t.exact=Yt(n.exact)),t}case 7:{let t=n.value;t.hasSymbolic&&Me(9,`${e} (symbolic matrix cell)`);let r=t.data.map(i=>Mn(i,e));return {t:7,rows:t.rows,cols:t.cols,data:r}}case 8:{let t=n.value;return {t:8,min:$(t.min),max:$(t.max)}}case 10:return {t:10,v:n.value};case 13:return {t:13,code:n.value,message:n.unit??""};default:return Me(n.type,e)}}function Mn(n,e){return typeof n=="boolean"?n:typeof n=="number"?$(n):Me(9,`${e} (symbolic matrix cell)`)}function Be(n){switch(n.t){case 0:{let e=new chunkS3SPDK6N_cjs.m(0,U(n.v));return n.exact!==void 0&&(e.exact=Xt(n.exact)),n.rational!==void 0&&(e.rational=Dn(n.rational)),e}case 1:{let e=n.big?BigInt(n.v):U(n.v);return new chunkS3SPDK6N_cjs.m(1,e,n.base)}case 2:return new chunkS3SPDK6N_cjs.m(2,BigInt(n.v));case 3:return new chunkS3SPDK6N_cjs.m(3,n.v);case 4:{let e=new chunkS3SPDK6N_cjs.m(4,U(n.v));return n.g!==void 0&&(e.grain=n.g),n.z!==void 0&&(e.zone=n.z),e}case 5:return new chunkS3SPDK6N_cjs.m(5,U(n.v));case 6:{let e=new chunkS3SPDK6N_cjs.m(6,U(n.v),n.unit);return n.exact!==void 0&&(e.exact=Xt(n.exact)),e}case 7:{let e=n.data.map(r=>typeof r=="boolean"?r:U(r)),t={rows:n.rows,cols:n.cols,data:e,hasSymbolic:false};return new chunkS3SPDK6N_cjs.m(7,t)}case 8:return new chunkS3SPDK6N_cjs.m(8,{min:U(n.min),max:U(n.max)});case 10:return new chunkS3SPDK6N_cjs.m(10,n.v);case 13:return new chunkS3SPDK6N_cjs.m(13,n.code,n.message);default:throw chunk6SYU4MH7_cjs.c.validation({code:M.SNAPSHOT_MALFORMED,message:`Snapshot holds a value with an unknown type tag: ${JSON.stringify(n.t)}`,expected:"a known SerializedValue type tag",found:JSON.stringify(n.t)})}}function ue(n){let e={opcodes:Array.from(n.opcodes),numbers:Array.from(n.numbers,$),strings:n.strings.slice(),hasAsync:n.hasAsync};return n.constants&&(e.constants=Array.from(n.constants.entries())),n.userFunctionBodies&&(e.userFunctionBodies=n.userFunctionBodies.map(ze)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:ue(t.program)}))),e}function pe(n){let e={opcodes:Uint8Array.from(n.opcodes),numbers:Float64Array.from(n.numbers,U),strings:n.strings.slice(),hasAsync:n.hasAsync};return n.constants&&(e.constants=new Map(n.constants)),n.userFunctionBodies&&(e.userFunctionBodies=n.userFunctionBodies.map(Fe)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:pe(t.program)}))),e}function ze(n){return {name:n.name,params:n.params.slice(),program:ue(n.program)}}function Fe(n){return {name:n.name,params:n.params.slice(),program:pe(n.program)}}function nn(n){if(typeof n!="object"||n===null)throw chunk6SYU4MH7_cjs.c.validation({code:M.SNAPSHOT_VERSION_MISMATCH,message:"fromJSON was given something that is not a snapshot object.",expected:`an object produced by ExpressionEngine.toJSON() with format "${ee}"`,found:n===null?"null":typeof n});let e=n;if(e.format!==ee)throw chunk6SYU4MH7_cjs.c.validation({code:M.SNAPSHOT_VERSION_MISMATCH,message:`This object is not a solve-engine snapshot (its "format" is ${JSON.stringify(e.format)}).`,expected:`format "${ee}"`,found:JSON.stringify(e.format)});if(e.version!==Q)throw chunk6SYU4MH7_cjs.c.validation({code:M.SNAPSHOT_VERSION_MISMATCH,message:`This snapshot was written for format version ${e.version}, but this engine restores version ${Q}.`,expected:`snapshot version ${Q}`,found:`version ${e.version}`,suggestion:"Regenerate the snapshot with a matching engine version, or re-evaluate the document from source.",context:{snapshotVersion:e.version,readerVersion:Q,engineVersion:e.engineVersion}});zn(n);}var Zt=32;function Vn(n){return n===null?"null":Array.isArray(n)?`an array of ${n.length}`:typeof n=="object"?"an object":`${typeof n} ${JSON.stringify(n)}`.slice(0,80)}function g(n,e,t){throw chunk6SYU4MH7_cjs.c.validation({code:M.SNAPSHOT_MALFORMED,message:`Snapshot is malformed at ${n}: expected ${e}.`,expected:e,found:Vn(t),suggestion:"Regenerate the snapshot with ExpressionEngine.toJSON(), or re-evaluate the document from source.",context:{location:n}})}function j(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function _(n){return typeof n=="number"||n==="NaN"||n==="Infinity"||n==="-Infinity"}function ce(n){return typeof n=="string"&&/^-?\d+$/.test(n)}function be(n,e){(!Array.isArray(n)||!n.every(t=>typeof t=="string"))&&g(e,"an array of strings",n);}function en(n,e){(!j(n)||!ce(n.coef)||typeof n.scale!="number")&&g(e,"a decimal as { coef: digits, scale: number }",n);}function Bn(n,e){(!j(n)||!ce(n.n)||!ce(n.d))&&g(e,"a rational as { n: digits, d: digits }",n);}function tn(n,e){switch(j(n)||g(e,"a serialised value object",n),n.t){case 0:_(n.v)||g(`${e}.v`,"a number",n.v),n.exact!==void 0&&en(n.exact,`${e}.exact`),n.rational!==void 0&&Bn(n.rational,`${e}.rational`);return;case 1:(n.big?!ce(n.v):!_(n.v))&&g(`${e}.v`,n.big?"an integer string":"a number",n.v),n.base!==void 0&&typeof n.base!="string"&&g(`${e}.base`,"a base name",n.base);return;case 2:ce(n.v)||g(`${e}.v`,"an integer string",n.v);return;case 3:typeof n.v!="string"&&g(`${e}.v`,"a string",n.v);return;case 4:_(n.v)||g(`${e}.v`,"a number",n.v),n.g!==void 0&&n.g!=="date"&&n.g!=="datetime"&&n.g!=="instant"&&g(`${e}.g`,'one of "date", "datetime" or "instant"',n.g),n.z!==void 0&&typeof n.z!="string"&&g(`${e}.z`,"a zone reference",n.z);return;case 5:_(n.v)||g(`${e}.v`,"a number",n.v);return;case 6:_(n.v)||g(`${e}.v`,"a number",n.v),typeof n.unit!="string"&&g(`${e}.unit`,"a unit name",n.unit),n.exact!==void 0&&en(n.exact,`${e}.exact`);return;case 7:{let{rows:t,cols:r,data:i}=n;(!Number.isInteger(t)||t<0)&&g(`${e}.rows`,"a non-negative integer",t),(!Number.isInteger(r)||r<0)&&g(`${e}.cols`,"a non-negative integer",r),(!Array.isArray(i)||i.length!==t*r)&&g(`${e}.data`,`an array of ${t} \xD7 ${r} cells`,i),i.every(s=>typeof s=="boolean"||_(s))||g(`${e}.data`,"numeric or boolean cells",i);return}case 8:(!_(n.min)||!_(n.max))&&g(e,"a range with numeric min and max",n);return;case 10:typeof n.v!="boolean"&&g(`${e}.v`,"a boolean",n.v);return;case 13:(typeof n.code!="string"||typeof n.message!="string")&&g(e,"an error with a string code and message",n);return;default:return}}function Ee(n,e,t){if(t>Zt&&g(e,`function bodies nested at most ${Zt} deep`,"deeper nesting"),j(n)||g(e,"a serialised program object",n),(!Array.isArray(n.opcodes)||!n.opcodes.every(r=>Number.isInteger(r)&&r>=0&&r<=255))&&g(`${e}.opcodes`,"an array of bytes (integers 0 to 255)",n.opcodes),(!Array.isArray(n.numbers)||!n.numbers.every(_))&&g(`${e}.numbers`,"an array of numbers",n.numbers),be(n.strings,`${e}.strings`),typeof n.hasAsync!="boolean"&&g(`${e}.hasAsync`,"a boolean",n.hasAsync),n.constants!==void 0){let r=i=>Array.isArray(i)&&i.length===2&&typeof i[0]=="number"&&typeof i[1]=="number";(!Array.isArray(n.constants)||!n.constants.every(r))&&g(`${e}.constants`,"an array of [number, number] pairs",n.constants);}n.userFunctionBodies!==void 0&&(Array.isArray(n.userFunctionBodies)||g(`${e}.userFunctionBodies`,"an array of functions",n.userFunctionBodies),n.userFunctionBodies.forEach((r,i)=>rn(r,`${e}.userFunctionBodies[${i}]`,t+1))),n.anonymousBodies!==void 0&&(Array.isArray(n.anonymousBodies)||g(`${e}.anonymousBodies`,"an array of bodies",n.anonymousBodies),n.anonymousBodies.forEach((r,i)=>{let s=`${e}.anonymousBodies[${i}]`;j(r)||g(s,"a body object",r),be(r.params,`${s}.params`),Ee(r.program,`${s}.program`,t+1);}));}function rn(n,e,t){j(n)||g(e,"a function object",n),typeof n.name!="string"&&g(`${e}.name`,"a function name",n.name),be(n.params,`${e}.params`),Ee(n.program,`${e}.program`,t);}function zn(n){n.locale!==void 0&&typeof n.locale!="string"&&g("locale","a locale code",n.locale),j(n.variables)||g("variables","an object of values by name",n.variables);for(let[e,t]of Object.entries(n.variables))tn(t,`variables.${e}`);Array.isArray(n.userFunctions)||g("userFunctions","an array of functions",n.userFunctions),n.userFunctions.forEach((e,t)=>rn(e,`userFunctions[${t}]`,1)),Array.isArray(n.lineCache)||g("lineCache","an array of cached lines",n.lineCache),n.lineCache.forEach((e,t)=>{let r=`lineCache[${t}]`;j(e)||g(r,"a cached line",e),Number.isInteger(e.line)||g(`${r}.line`,"a line number",e.line),typeof e.expression!="string"&&g(`${r}.expression`,"the line's expression text",e.expression),tn(e.result,`${r}.result`),Ee(e.bytecode,`${r}.bytecode`,1),be(e.reads,`${r}.reads`),e.writeVar!==null&&typeof e.writeVar!="string"&&g(`${r}.writeVar`,"a variable name or null",e.writeVar);}),Array.isArray(n.bytecodeCache)||g("bytecodeCache","an array of compiled expressions",n.bytecodeCache),n.bytecodeCache.forEach((e,t)=>{let r=`bytecodeCache[${t}]`;(!j(e)||typeof e.expression!="string")&&g(r,"an { expression, program } pair",e),Ee(e.program,`${r}.program`,1);});}var sn=null;function cr(n){sn=n;}function Ue(){return sn}var on=3e4,an=50,xe=class{constructor(e){this.workers=[];this.nextWorker=0;this.nextId=1;this.pendingBatches=new Map;this.terminated=false;this._available=null;this.poolSize=Math.min(e??this.defaultPoolSize(),4);}defaultPoolSize(){return typeof navigator<"u"&&navigator.hardwareConcurrency?Math.min(navigator.hardwareConcurrency,4):2}isAvailable(){if(this.terminated)return false;if(this._available!==null)return this._available;if(typeof Worker>"u")return this._available=false,false;try{let e=Ue();return e===null?(this._available=!1,!1):(e().terminate(),this._available=!0,!0)}catch{return this._available=false,false}}executeBatch(e,t){if(!this.isAvailable())return;if(e.length===0)return Promise.resolve([]);this.ensureWorkers();let r=[];for(let a of e){let c=t.get(a);if(!c||c.bytecode.opcodes.length===0)continue;let u=c.bytecode.opcodes,p=c.bytecode.numbers,h=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength),y=p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength);r.push({lineNumber:a,opcodesBuffer:h,numbersBuffer:y,opcodesLength:u.length,numbersLength:p.length,strings:[...c.bytecode.strings]});}if(r.length===0)return Promise.resolve([]);let i=[];for(let a of r)a.opcodesBuffer.byteLength>0&&i.push(a.opcodesBuffer),a.numbersBuffer.byteLength>0&&i.push(a.numbersBuffer);let s=this.nextId++,o=this.nextWorkerIndex(),l=this.workers[o];return new Promise(a=>{let c=setTimeout(()=>{this.pendingBatches.has(s)&&this.failWorker(o,"WORKER_TIMEOUT",`Evaluation did not finish within ${on/1e3} seconds; the worker was replaced`);},on);this.pendingBatches.set(s,{id:s,lineNumbers:r.map(u=>u.lineNumber),workerIndex:o,resolve:u=>{clearTimeout(c),a(u);}}),l.postMessage({type:"EXECUTE_BATCH",id:s,items:r},i);})}clear(){for(let[,e]of this.pendingBatches)e.resolve([]);this.pendingBatches.clear();for(let e of this.workers)e.terminate();this.workers=[],this.nextWorker=0;}destroy(){this.terminated=true,this.clear();}ensureWorkers(){if(!(this.workers.length>0))for(let e=0;e<this.poolSize;e++)this.spawnWorker(e);}spawnWorker(e){let t=Ue();if(t===null)return;let r=t();r.onmessage=i=>{this.handleWorkerMessage(i.data);},r.onerror=i=>{console.error(`[ExecutionPool] Worker ${e} error:`,i.message),this.failWorker(e,"WORKER_EXECUTION_ERROR",`Worker failed: ${i.message}`);},this.workers[e]=r;}failWorker(e,t,r){if(this.workers.length!==0){this.workers[e]?.terminate(),this.terminated||this.spawnWorker(e);for(let[i,s]of this.pendingBatches)s.workerIndex===e&&(this.pendingBatches.delete(i),s.resolve(Fn(s.lineNumbers,t,r)));}}nextWorkerIndex(){let e=this.nextWorker;return this.nextWorker=(this.nextWorker+1)%this.workers.length,e}handleWorkerMessage(e){if(e.type!=="EXECUTE_RESULT")return;let t=this.pendingBatches.get(e.id);t&&(this.pendingBatches.delete(e.id),t.resolve(e.results));}};function Fn(n,e,t){return n.map(r=>({lineNumber:r,valueType:13,value:0,unit:t,isPending:false,errorCode:e}))}function ln(n){switch(n.valueType){case 0:return chunkS3SPDK6N_cjs.n(n.value);case 1:return chunkS3SPDK6N_cjs.r(n.value);case 2:return chunkS3SPDK6N_cjs.s(BigInt(n.value));case 3:return chunkS3SPDK6N_cjs.t(String(n.value));case 4:return chunkS3SPDK6N_cjs.M(n.value);case 5:return chunkS3SPDK6N_cjs.N(n.value);case 6:return chunkS3SPDK6N_cjs.u(n.value,n.unit??"");case 7:return chunkS3SPDK6N_cjs.n(n.value);case 10:return chunkS3SPDK6N_cjs.L(n.value!==0);case 12:return chunkS3SPDK6N_cjs.O(n.queryKey??"");case 13:return chunkS3SPDK6N_cjs.P(n.errorCode??"WORKER_EXECUTION_ERROR",n.unit??"Unknown worker error");default:return chunkS3SPDK6N_cjs.n(n.value)}}var ke=class ke{constructor(e,t,r,i=ke.DEFAULT_HIGH_WATER_MARK){this.pending=new Map;this.collapsed=0;this.scheduled=false;this.cleared=false;this.executionPool=null;this.workerOffloadDispatchCount=0;this._streamController=null;this._testCaptures=null;this.onLineResult=null;this.warnedAboutMissingHook=false;this.dag=e,this.lineCache=t,this.vm=r,this.highWaterMark=i,this._eventStream=this.createEventStream();}warnIfUnwired(){this.onLineResult||this.listenerCount>0||this.warnedAboutMissingHook||(this.warnedAboutMissingHook=true,console.warn("[solve-engine] An async result resolved, but nothing is listening for it: no reader is attached to engine.getEventStream() and AsyncResolutionBatcher.onLineResult is not set. The value is in the cache; without one of those the line keeps showing as pending. Read the event stream and re-evaluate the lines it names (see the async guide), or set onLineResult to mirror resolved values into your own state. This warning appears once per batcher."));}createEventStream(){return new ReadableStream({start:e=>{this._streamController=e;},cancel:()=>{this._streamController=null;}},new CountQueuingStrategy({highWaterMark:this.highWaterMark}))}add(e){this.cleared=false;let t=`${e.packageId}:${e.queryKey}`;if(this.pending.has(t)){this.collapsed++;return}this.pending.set(t,e),this.scheduled||(this.scheduled=true,queueMicrotask(()=>{try{this.flush();}catch(r){let i=chunk6SYU4MH7_cjs.d(r);console.error(`[AsyncResolutionBatcher] flush() failed unexpectedly \u2014 this should never happen; please report: ${i.format()}`);}}));}getEventStream(){return this._eventStream}get pendingCount(){return this.pending.size}get dedupCount(){return this.collapsed}get listenerCount(){return this._eventStream.locked?1:0}get workerOffloadCount(){return this.workerOffloadDispatchCount}clearAll(){this.pending=new Map,this.collapsed=0,this.scheduled=false,this.cleared=true,this._testCaptures=null,this.onLineResult=null;try{this._streamController?.close();}catch{}this._streamController=null,this._eventStream=this.createEventStream(),this.executionPool&&(this.executionPool.clear(),this.executionPool=null),this.workerOffloadDispatchCount=0;}flush(){if(this.scheduled=false,this.cleared||this.pending.size===0)return;let e=this.pending;this.pending=new Map,this.collapsed=0;let t=[],r=[];for(let a of e.values())a.isError?t.push(a):r.push(a);for(let a of t)a.signal.aborted||this.notifyListeners({type:"error",queryKey:a.queryKey,packageId:a.packageId,error:a.error??new Error("Unknown async resolution error")});let i=new Set,s=[],o=[...r,...t];for(let a of o){if(a.signal.aborted)continue;s.push(a.queryKey);let c=this.dag.getAffectedLinesByDataSource(a.packageId,[a.queryKey]);for(let u of c)i.add(u);}if(i.size===0){this.notifyListeners({type:"lines-updated",lineNumbers:[],affectedQueryKeys:s});return}let l=this.topologicalSort(Array.from(i));if(l.length>an){let a=new Map;for(let c of l)a.set(c,this.lineCache.getEntryForLine(c));this.reExecuteViaWorkerPool(l,a,s).catch(c=>{let u=chunk6SYU4MH7_cjs.d(c);console.error(`[AsyncResolutionBatcher] reExecuteViaWorkerPool() failed unexpectedly: ${u.format()}`);});return}this.reExecuteMainThread(l,s);}topologicalSort(e){if(e.length<=1)return e;let t=new Map,r=new Map,i=new Map;for(let l of e)t.set(l,0),r.set(l,[]);for(let l of e){let a=this.dag.getWrites(l);for(let c of a)i.set(c,l);}for(let l of e){let a=this.dag.getDependencies(l);for(let c of a){let u=i.get(c);u!==void 0&&u!==l&&(r.get(u).push(l),t.set(l,(t.get(l)??0)+1));}}let s=[];for(let[l,a]of t)a===0&&s.push(l);if(s.length===0&&e.length>0)return [...e].sort((l,a)=>l-a);let o=[];for(let l=0;l<s.length;l++){let a=s[l];o.push(a);for(let c of r.get(a)??[]){let u=(t.get(c)??1)-1;t.set(c,u),u===0&&s.push(c);}}if(o.length<e.length){let l=new Set(o),a=e.filter(c=>!l.has(c)).sort((c,u)=>c-u);o.push(...a);}return o}async reExecuteViaWorkerPool(e,t,r){this.executionPool||(this.executionPool=new xe);let i=this.executionPool.executeBatch(e,t);if(!i){this.reExecuteMainThread(e,r,t);return}this.workerOffloadDispatchCount++;let s=await i;if(this.cleared)return;let o=[];for(let l of s){let a=t.get(l.lineNumber);if(!a||l.isPending)continue;let c=ln(l);a.result=c,this.warnIfUnwired(),this.onLineResult?.(l.lineNumber,c),o.push(l.lineNumber);}this.cleared||(o.length>0||r.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:o,affectedQueryKeys:r});}reExecuteMainThread(e,t,r){let i=[];for(let s of e){let o=r?r.get(s):this.lineCache.getEntryForLine(s);if(!o||o.bytecode.opcodes.length===0)continue;let l=this.vm.getStack().length;try{let a=chunkLI6LYJDA_cjs.d(o.bytecode,this.vm,void 0,void 0,{lineIndex:s,networkEnabled:this.vm.context.networkEnabled,calendar:this.vm.context.calendar});for(;this.vm.getStack().length>l;)this.vm.pop();if(a.type==="value")o.result=a.value,this.warnIfUnwired(),this.onLineResult?.(s,a.value),i.push(s);else if(a.type==="error"){let c=chunkS3SPDK6N_cjs.P(a.error.code,a.error.message);o.result=c,this.warnIfUnwired(),this.warnIfUnwired(),this.onLineResult?.(s,c),i.push(s);}}catch(a){for(;this.vm.getStack().length>l;)this.vm.pop();let c=chunk6SYU4MH7_cjs.d(a),u=chunkS3SPDK6N_cjs.P(c.code,c.message);o.result=u,this.warnIfUnwired(),this.onLineResult?.(s,u),i.push(s);}}return (i.length>0||t.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:i,affectedQueryKeys:t}),i}notifyListeners(e){if(this._testCaptures&&this._testCaptures.push(e),this._streamController)try{this._streamController.enqueue(e);}catch{}}};ke.DEFAULT_HIGH_WATER_MARK=64;var Se=ke;function _e(n,e){if(n.length>e.maxExpressionLength){let t=chunk6SYU4MH7_cjs.c.validation("EXPRESSION_TOO_LONG",`Expression exceeds max length of ${e.maxExpressionLength} characters (got ${n.length})`,{expressionLength:n.length,maxLength:e.maxExpressionLength});return {passed:false,error:{value:chunkS3SPDK6N_cjs.n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:t.message,engineError:t}}}return {passed:true}}function $e(n,e){let t=0,r=0,i=0;for(let o of n)o.type==="FUNC"&&t++,(o.value==="("||o.type==="LPAREN")&&(r++,i=Math.max(i,r)),(o.value===")"||o.type==="RPAREN")&&r--;let s=n.length+t*5+i*10;if(s>e.maxComplexity){let o=chunk6SYU4MH7_cjs.c.validation("EXPRESSION_TOO_COMPLEX",`Expression complexity score ${s} exceeds maximum of ${e.maxComplexity}`,{complexity:s,maxComplexity:e.maxComplexity});return {passed:false,complexityScore:s,errorMessage:o.message,engineError:o}}return {passed:true,complexityScore:s}}function de(n){return n.type==="IDENT"||n.type==="UNIT"}function Un(n){return n.type==="NUMBER"||n.type==="TO"||n.type==="IN"||n.type==="RPAREN"}function cn(n,e){let t=0;for(let r=e;r<n.length;r++)if(n[r].type==="LPAREN")t++;else if(n[r].type==="RPAREN"&&(t--,t===0))return r;return null}function _n(n){let e=new Set;for(let t=0;t<n.length;t++){if(!de(n[t])||t>0&&n[t-1].type==="COLON"||n[t+1]?.type!=="LPAREN")continue;let r=cn(n,t+1);if(r!==null&&n[r+1]?.type==="EQUALS")for(let i=t+2;i<r;i++)de(n[i])&&e.add(n[i].value);}return e}function Ce(n){let e=[],t=[],r=_n(n);for(let i=0;i<n.length;i++){let s=n[i];if(s.type==="GLOBAL"){if(i+2<n.length&&n[i+1].type==="COLON"&&de(n[i+2])){let o=chunkFESR6PZI_cjs.K(n[i+2].value);e.push(o),i+3<n.length&&n[i+3].type==="EQUALS"&&t.push(o);}continue}if(s.type==="COLON"){if(i>0&&n[i-1].type==="GLOBAL")continue;if(i+1<n.length&&de(n[i+1])){let o=n[i+1].value;e.push(o),i+2<n.length&&n[i+2].type==="EQUALS"&&t.push(o);}}if(de(s)){if(i>0&&n[i-1].type==="COLON"||s.type==="UNIT"&&i>0&&Un(n[i-1])||r.has(s.value))continue;if(n[i+1]?.type==="LPAREN"){let l=cn(n,i+1);if(l!==null&&n[l+1]?.type==="EQUALS"){e.push(s.value),t.push(s.value);continue}}e.push(s.value);let o=n[i+1]?.type;(o==="EQUALS"||o==="PLUS_EQUALS"||o==="MINUS_EQUALS")&&t.push(s.value);}}return {reads:e,writes:t}}function Cr(n){return chunk3MG7VIPL_cjs.c.classifyLine(n).skip}function Tr(n,e){return chunk3MG7VIPL_cjs.c.findInlineSolves(n).map(r=>({start:r.start,end:r.end,expression:r.expression,lineNumber:e,columnNumber:r.columnNumber}))}var K=class{constructor(e,t,r,i){this.result=e;this.bytecode=t;this.readVariables=r;this.writeVariable=i;}},Te=class n{constructor(){this.byLine=new Map;this.count=0;}static exprKey(e){return e??""}static displayKey(e,t){return t===""?`${e}`:`${e}:${t}`}get(e,t){return this.byLine.get(e)?.get(n.exprKey(t))}getEntryForLine(e){let t=this.byLine.get(e);if(t)for(let r of t.values())return r}set(e,t,r){let i=this.byLine.get(e);i||(i=new Map,this.byLine.set(e,i));let s=n.exprKey(r);i.size>0&&!i.has(s)&&(this.count-=i.size,i.clear()),i.has(s)||this.count++,i.set(s,t);}has(e,t){return this.byLine.get(e)?.has(n.exprKey(t))??false}remove(e,t){let r=this.byLine.get(e);r&&r.delete(n.exprKey(t))&&(this.count--,r.size===0&&this.byLine.delete(e));}removeAllForLine(e){let t=this.byLine.get(e);t&&(this.count-=t.size,this.byLine.delete(e));}clearLine(e){this.removeAllForLine(e);}get size(){return this.count}clear(){this.byLine.clear(),this.count=0;}forEach(e){for(let[t,r]of this.byLine)for(let[i,s]of r)e(n.displayKey(t,i),s);}snapshotEntries(){let e=[];for(let[t,r]of this.byLine)for(let[i,s]of r)e.push({line:t,expression:i,entry:s});return e}keys(){let e=[];for(let[t,r]of this.byLine)for(let i of r.keys())e.push(n.displayKey(t,i));return e}};function je(n,e){let t=e.fields(n),r=String(t.month0+1).padStart(2,"0"),i=String(t.day).padStart(2,"0");return `${t.year}-${r}-${i}`}function $n(n,e){if(n instanceof Date)return je(n.getTime(),e);if(typeof n=="number")return Number.isFinite(n)?je(n,e):null;let t=/^(\d{4})-(\d{2})-(\d{2})/.exec(n.trim());return t?`${t[1]}-${t[2]}-${t[3]}`:null}function un(n,e){if(n===void 0)return;if(typeof n=="function")return r=>n(new Date(r));let t=new Set;for(let r of n){let i=$n(r,e);i!==null&&t.add(i);}return r=>t.has(je(r,e))}function jn(n,e){if(!n||n.type!==e.type||n.value!==e.value)return true;let t=n.unit,r=e.unit;return t!==r}var Re=class n{constructor(e,t){this.dag=e;this.enqueue=t;this.entries=new Map;}get size(){return this.entries.size}static idOf(e,t){return JSON.stringify([e,t])}register(e){if(!(e.intervalMs>0))return;let t=n.idOf(e.packageId,e.queryKey);if(this.entries.has(t))return;let r=setInterval(()=>{this.tick(t);},e.intervalMs);r.unref?.(),this.entries.set(t,{...e,timer:r,lastValue:null,inFlight:false});}async tick(e){let t=this.entries.get(e);if(t&&!t.inFlight){if(this.isDead(t)){this.stop(e);return}t.inFlight=true;try{let r=await t.refetch(),i=this.entries.get(e);if(!i)return;r&&jn(i.lastValue,r)&&(i.lastValue=r,this.enqueue(i.packageId,i.queryKey));}catch{}finally{let r=this.entries.get(e);r&&(r.inFlight=false);}}}isDead(e){return this.dag.getAffectedLinesByDataSource(e.packageId,[e.queryKey]).size===0}reconcile(){for(let[e,t]of this.entries)this.isDead(t)&&this.stop(e);}stop(e){let t=this.entries.get(e);t&&(clearInterval(t.timer),this.entries.delete(e));}clearAll(){for(let e of this.entries.values())clearInterval(e.timer);this.entries.clear();}};var z=class{static enable(){this.enabled=true;}static disable(){this.enabled=false;}static isEnabled(){return this.enabled}static track(e,t,r){if(!this.enabled)return {result:t(),alloc:null};let i=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,s=typeof process<"u"&&process.hrtime?process.hrtime():performance.now(),o=t(),l=typeof process<"u"&&process.hrtime?process.hrtime(s):void 0,a=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,c=l?l[0]*1e9+l[1]:(performance.now()-s)*1e6,u=i&&a?a.heapUsed-i.heapUsed:0,p={stage:e,allocCount:0,allocBytes:u,objectCounts:{},wallTimeNs:c,...r};return {result:o,alloc:p}}static generateReport(e,t){let r=[];r.push(t?`## ${t}`:"## Pipeline Allocation Report"),r.push(""),r.push(`**Runs:** ${e.length} | **Generated:** ${new Date().toISOString()}`),r.push("");let i=this.aggregate(e);if(i.length===0)return r.push("_No telemetry data._"),r.join(`
|
|
2
|
+
`);r.push("### Per-Stage Breakdown"),r.push(""),r.push("| Stage | Count | Mean Wall (\xB5s) | Mean Alloc (bytes) | Min (\xB5s) | Max (\xB5s) | p50 (\xB5s) | p95 (\xB5s) | p99 (\xB5s) |"),r.push("|-------|:-----:|:--------------:|:------------------:|:--------:|:--------:|:--------:|:--------:|:--------:|");for(let a of i)r.push(`| ${a.stage} | ${a.count} | ${(a.meanWallTimeNs/1e3).toFixed(2)} | ${a.meanAllocBytes.toFixed(0)} | ${(a.minWallTimeNs/1e3).toFixed(2)} | ${(a.maxWallTimeNs/1e3).toFixed(2)} | ${(a.p50WallTimeNs/1e3).toFixed(2)} | ${(a.p95WallTimeNs/1e3).toFixed(2)} | ${(a.p99WallTimeNs/1e3).toFixed(2)} |`);let s=e.reduce((a,c)=>a+c.totalAllocBytes,0),o=e.reduce((a,c)=>a+c.totalWallTimeNs,0),l=e.filter(a=>a.fastPath).length;return r.push(""),r.push("### Totals"),r.push(""),r.push(`- **Total wall time:** ${(o/1e6).toFixed(2)} ms (${e.length} runs)`),r.push(`- **Total heap allocated:** ${s.toLocaleString()} bytes`),r.push(`- **Fast-path runs:** ${l}/${e.length} (${(l/e.length*100).toFixed(0)}%)`),r.push(`- **Mean per-run:** ${(o/e.length/1e3).toFixed(2)} \xB5s, ${(s/e.length).toFixed(0)} bytes`),r.join(`
|
|
3
|
+
`)}static aggregate(e){let t=new Map;for(let i of e)for(let s of i.stages)t.has(s.stage)||t.set(s.stage,[]),t.get(s.stage).push(s);let r=[];for(let[i,s]of t){let o=s.map(c=>c.wallTimeNs).sort((c,u)=>c-u),l=s.map(c=>c.allocBytes),a=s.length;r.push({stage:i,count:a,meanAllocBytes:l.reduce((c,u)=>c+u,0)/a,meanWallTimeNs:o.reduce((c,u)=>c+u,0)/a,minWallTimeNs:o[0],maxWallTimeNs:o[o.length-1],p50WallTimeNs:We(o,50),p95WallTimeNs:We(o,95),p99WallTimeNs:We(o,99)});}return r.sort((i,s)=>i.stage.localeCompare(s.stage)),r}static createTelemetry(e,t,r=false){let i=t.reduce((o,l)=>o+l.allocBytes,0),s=t.reduce((o,l)=>o+l.wallTimeNs,0);return {expression:e,stages:t,totalAllocBytes:i,totalWallTimeNs:s,fastPath:r}}};z.enabled=false;function We(n,e){if(n.length===0)return 0;if(n.length===1)return n[0];let t=e/100*(n.length-1),r=Math.floor(t),i=Math.ceil(t);if(r===i)return n[r];let s=t-r;return n[r]*(1-s)+n[i]*s}function pn(n){let e=n[n.length-1],t=e.length>1&&e.endsWith("s")?e.slice(0,-1):e;return [...n.slice(0,-1),t].join(" ")}var Ne=class{constructor(){this.byKey=new Map;this.longestName=0;}get isEmpty(){return this.byKey.size===0}get maxWordCount(){return this.longestName}define(e,t,r){let i=pn(e);this.byKey.set(i,{displayName:e.join(" "),ratioText:t,baseUnit:r}),e.length>this.longestName&&(this.longestName=e.length);}match(e){let t=Math.min(e.length,this.longestName);for(let r=t;r>=1;r--){let i=this.byKey.get(pn(e.slice(0,r)));if(i!==void 0)return {definition:i,wordCount:r}}return null}clear(){this.byKey.clear(),this.longestName=0;}};function dn(n,e=82){return {name:"uom:user-unit",priority:e,shape:[{types:["NUMBER","RPAREN"]},{types:["IDENT"]}],match(t,r){if(n.isEmpty)return null;let i=t[r];if(i.type!=="NUMBER"&&i.type!=="RPAREN")return null;let s=[],o=n.maxWordCount;for(let d=r+1;d<t.length&&s.length<o&&t[d].type==="IDENT";d++)s.push(t[d].value);if(s.length===0)return null;let l=n.match(s);if(l===null||t[r+1+l.wordCount]?.type==="EQUALS")return null;let{ratioText:c,baseUnit:u}=l.definition,p=new chunk72J5V7SN_cjs.a("STAR",chunkYBQOQTVL_cjs.c("STAR"),"*","*",i.offset,0,i.line,i.col),h=new chunk72J5V7SN_cjs.a("NUMBER",chunkYBQOQTVL_cjs.c("NUMBER"),c,c,i.offset,0,i.line,i.col),y=new chunk72J5V7SN_cjs.a("UNIT",chunkYBQOQTVL_cjs.c("UNIT"),u,u,i.offset,0,i.line,i.col);return {consumed:1+l.wordCount,replacement:[i,p,h,y],ruleName:"uom:user-unit"}}}}var fn="engine:call-fusion";function gn(n,e=80){return {name:fn,priority:e,shape:[{types:["IDENT"]},{types:["LPAREN"]}],match(t,r){let i=t[r];if(!i||i.type!=="IDENT"||t[r+1]?.type!=="LPAREN"||t[r-1]?.type==="COLON")return null;let s=(i.value??"").toLowerCase(),o=n.get(s);return o===void 0?null:{consumed:1,replacement:[new chunk72J5V7SN_cjs.a(o,chunkYBQOQTVL_cjs.c(o),s,i.value,i.offset,0,i.line,i.col)],ruleName:fn}}}}var Wn={january:1,jan:1,february:2,feb:2,march:3,mar:3,april:4,apr:4,may:5,june:6,jun:6,july:7,jul:7,august:8,aug:8,september:9,sep:9,sept:9,october:10,oct:10,november:11,nov:11,december:12,dec:12};function hn(n){return n===void 0||n.type!=="IDENT"&&n.type!=="UNIT"?0:Wn[(n.text??n.value??"").toLowerCase()]??0}var fe=/^\d+$/;function we(n){return n.length===4}function te(n,e,t,r,i,s){let o="datetime:month-name-date",l=chunkM4UC2PB6_cjs.q(n,e,t,r,o,i);return l!==null?l:s==="arithmetic"||e<1||e>12||n<1||n>31?null:chunkM4UC2PB6_cjs.s(chunkM4UC2PB6_cjs.g.DATE_NOT_A_CALENDAR_DAY,`"${chunkM4UC2PB6_cjs.r(r)}" is not a real date: ${chunkM4UC2PB6_cjs.j(n,e,t)}.`,r,`${o}:unreadable`)}function mn(n){return n.fields(n.now()).year}function yn(n=64,e=()=>chunkEQNKDTMX_cjs.b,t=()=>"refuse"){return {name:"datetime:month-name-date",priority:n,startTokenTypes:["NUMBER","IDENT","UNIT"],match(r,i){let s=e(),o=t(),l=r[i];if(l?.type==="NUMBER"&&fe.test(l.text??"")){let y=hn(r[i+1]);if(y===0)return null;let d=Number(l.text);if(d<1||d>31)return null;let T=r[i+2];return T?.type==="NUMBER"&&fe.test(T.text??"")&&we(T.text??"")?te(d,y,Number(T.text),r.slice(i,i+3),s,o):te(d,y,mn(s),r.slice(i,i+2),s,o)}let a=hn(l);if(a===0)return null;let c=r[i+1];if(c?.type!=="NUMBER"||!fe.test(c.text??""))return null;if(we(c.text??""))return te(1,a,Number(c.text),r.slice(i,i+2),s,o);let u=Number(c.text),p=r[i+2],h=r[i+3];return p?.type==="COMMA"&&h?.type==="NUMBER"&&fe.test(h.text??"")&&we(h.text??"")?te(u,a,Number(h.text),r.slice(i,i+4),s,o):p?.type==="NUMBER"&&fe.test(p.text??"")&&we(p.text??"")?te(u,a,Number(p.text),r.slice(i,i+3),s,o):te(u,a,mn(s),r.slice(i,i+2),s,o)}}}var Hn=30,Kn=40,Gn=50,qn=24;function Qn(n){switch(n){case chunkYBQOQTVL_cjs.a.PLUS:case chunkYBQOQTVL_cjs.a.MINUS:return Hn;case chunkYBQOQTVL_cjs.a.STAR:case chunkYBQOQTVL_cjs.a.SLASH:case chunkYBQOQTVL_cjs.a.MOD:case chunkYBQOQTVL_cjs.a.OF:return Kn;case chunkYBQOQTVL_cjs.a.CARET:return Gn;case chunkYBQOQTVL_cjs.a.PCT_ON:case chunkYBQOQTVL_cjs.a.PCT_OFF:return qn;default:return 0}}function Yn(n){switch(n){case chunkYBQOQTVL_cjs.a.PLUS:return "plus";case chunkYBQOQTVL_cjs.a.MINUS:return "minus";case chunkYBQOQTVL_cjs.a.STAR:return "times";case chunkYBQOQTVL_cjs.a.SLASH:return "divided by";case chunkYBQOQTVL_cjs.a.MOD:return "mod";case chunkYBQOQTVL_cjs.a.CARET:return "to the power of";case chunkYBQOQTVL_cjs.a.OF:return "of";case chunkYBQOQTVL_cjs.a.PCT_ON:return "plus";case chunkYBQOQTVL_cjs.a.PCT_OFF:return "less";default:return n.toLowerCase()}}function vn(n){return n.sourceEnd??n.offset+n.value.length}var Xn=new Set([chunkYBQOQTVL_cjs.a.NUMBER,chunkYBQOQTVL_cjs.a.BIGINT,chunkYBQOQTVL_cjs.a.IDENT,chunkYBQOQTVL_cjs.a.UNIT,chunkYBQOQTVL_cjs.a.PERCENT,chunkYBQOQTVL_cjs.a.PI,chunkYBQOQTVL_cjs.a.E,chunkYBQOQTVL_cjs.a.TRUE,chunkYBQOQTVL_cjs.a.FALSE,chunkYBQOQTVL_cjs.a.DOLLAR,chunkYBQOQTVL_cjs.a.POUND,chunkYBQOQTVL_cjs.a.EURO,chunkYBQOQTVL_cjs.a.YEN,chunkYBQOQTVL_cjs.a.RUBLE,chunkYBQOQTVL_cjs.a.WON,chunkYBQOQTVL_cjs.a.CURRENCY_SYMBOL]);function Jn(n){return !Xn.has(n)}var He=class{constructor(e){this.tokens=e;this.pos=0;}peek(){return this.tokens[this.pos]}next(){return this.tokens[this.pos++]}parseAll(){let e=this.parseExpression(0);if(this.pos!==this.tokens.length)throw new Error("explain: unconsumed tokens");return e}parseExpression(e){let t=this.parseOperand();for(;;){let r=this.peek();if(!r)break;let i=Qn(r.type);if(i===0||i<=e)break;this.next();let s=r.type===chunkYBQOQTVL_cjs.a.CARET?i-1:i,o=this.parseExpression(s);t={kind:"binary",op:r.type,left:t,right:o,start:t.start,end:o.end};}return t}parseOperand(){let e=this.peek();if(!e)throw new Error("explain: expected an operand");if(e.type===chunkYBQOQTVL_cjs.a.LPAREN)return this.parseGroup();let t=e.offset,r=false;for(;this.peek()&&(this.peek().type===chunkYBQOQTVL_cjs.a.PLUS||this.peek().type===chunkYBQOQTVL_cjs.a.MINUS);)this.next(),r=true;if(r&&this.peek()&&this.peek().type===chunkYBQOQTVL_cjs.a.LPAREN){let s=this.parseGroup();return {kind:"wrap",child:s,start:t,end:s.end}}let i=-1;for(;this.peek()&&!Jn(this.peek().type);)i=vn(this.next());if(i===-1)throw new Error("explain: expected an operand");return {kind:"leaf",start:t,end:i}}parseGroup(){let e=this.next(),t=this.parseExpression(0),r=this.peek();if(!r||r.type!==chunkYBQOQTVL_cjs.a.RPAREN)throw new Error("explain: unbalanced parentheses");return this.next(),{kind:"wrap",child:t,start:e.offset,end:vn(r)}}},Ke=class{constructor(e,t,r){this.source=e;this.evaluate=t;this.steps=[];this.cache=new Map;this.resultPrefix=chunkS3DFU33X_cjs.a(r).display.resultPrefix;}build(e){return this.emit(e),{steps:this.steps,result:this.valueOf(e)}}emit(e){if(e.kind!=="leaf"){if(e.kind==="wrap"){this.emit(e.child);return}this.emit(e.left),this.emit(e.right),this.steps.push({description:this.describe(e),value:this.valueOf(e)});}}describe(e){let t=Yn(e.op);return e.op===chunkYBQOQTVL_cjs.a.PCT_ON||e.op===chunkYBQOQTVL_cjs.a.PCT_OFF?`${this.operand(e.right)} ${t} ${this.operand(e.left)}`:`${this.operand(e.left)} ${t} ${this.operand(e.right)}`}operand(e){return e.kind==="leaf"?this.source.slice(e.start,e.end).trim():this.render(this.valueOf(e))}valueOf(e){let t=this.cache.get(e);if(t)return t;let r=this.evaluate(this.source.slice(e.start,e.end));return this.cache.set(e,r),r}render(e){let t=chunkQOOTRUY7_cjs.c(e,chunkQOOTRUY7_cjs.a);return t.startsWith(this.resultPrefix)?t.slice(this.resultPrefix.length):t}};function Ge(n){let{expression:e,tokens:t,evaluate:r,locale:i,readings:s=[]}=n,o=c=>s.filter(u=>u.needsNote).map(u=>({description:u.note,value:c})),l=()=>{let c=r(e);return {expression:e,steps:o(c),result:c}},a;try{a=new He(t).parseAll();}catch{return l()}try{let{steps:c,result:u}=new Ke(e,r,i).build(a);return {expression:e,steps:[...o(u),...c],result:u}}catch{return l()}}var Y=class Y{constructor(e={}){this.dag=new chunkLI6LYJDA_cjs.a;this.lineCache=new Te;this.accumulatorNames=new Set;this.scopeManager=new chunkLI6LYJDA_cjs.b;this.resolverRegistry=new chunkR3W53ZMP_cjs.a;this.packageContributions=new Map;this.registeredPackages=new Map;this.callFusions=new Map;this.callFusionOwners=new Map;this.compatIndex=new ve;this.documentModel=null;this.goalSeekDepth=0;this.batchScanResults=null;this.batchParsedLines=null;this.lineContext=null;this.lineContextDoc=null;this.lineContextScan=null;this.lineContextParsed=null;this.packageCompletionItems=new Map;this.keystrokeSignal=null;this.backgroundRefreshSignal=new AbortController().signal;this.inertSignal=new AbortController().signal;this.userUnits=new Ne;this.bytecodeCache=new Map;this.compiledFrontHalf=new Map;this.failedParses=new Map;this.pluginFunctionIndexByName=new Map;this.builderPool=[new chunkK3PZ66XR_cjs.d(this.pluginFunctionIndexByName),new chunkK3PZ66XR_cjs.d(this.pluginFunctionIndexByName),new chunkK3PZ66XR_cjs.d(this.pluginFunctionIndexByName),new chunkK3PZ66XR_cjs.d(this.pluginFunctionIndexByName)];this.builderPoolIndex=0;this.lastTelemetry=null;let{locale:t="en",diagnostics:r=false,config:i,packages:s,calendar:o}=e;this.localeCode=t,this.config=chunk2XOLAHW6_cjs.c(chunk2XOLAHW6_cjs.b,i??{}),this.dateReading=chunkM4UC2PB6_cjs.h(this.config.date),this.lexer=new chunk3MG7VIPL_cjs.b(t),this.registry=new chunkP5YWBIIU_cjs.b,this.context=chunkFESR6PZI_cjs.x({networkEnabled:this.config.network.enabled,calendar:o}),r?(this.diagnosticPipeline=new chunkHG4NPDN5_cjs.a,this.timelineCollector=new chunkHG4NPDN5_cjs.b,this.diagnosticPipeline.register(this.timelineCollector)):this.diagnosticPipeline=new chunkHG4NPDN5_cjs.a,this.normalizer=new chunkYV4GDW5A_cjs.c;for(let[a,c]of Object.entries(chunk72J5V7SN_cjs.c))this.normalizer.addPhrase(a,c);this.normalizer.register(chunkYV4GDW5A_cjs.d(50,a=>this.normalizer.canStartPhrase(a))),this.normalizer.register(dn(this.userUnits)),this.normalizer.register(gn(this.callFusions));let l=s??[];for(let a of l)try{this.registerPackage(a);}catch(c){let u=chunk6SYU4MH7_cjs.d(c);console.error(`[ExpressionEngine] Failed to register package "${a.name}" \u2014 skipping it and continuing construction with the remaining packages: ${u.format()}`);}if(this.registry.hasPrefix("DATETIME_LITERAL")&&this.registry.hasPrefix("DATETIME_LITERAL_UNREADABLE")){let a=()=>this.context.calendar;this.normalizer.register(chunkM4UC2PB6_cjs.t(()=>this.dateReading.order,a,()=>this.config.date.onAmbiguous)),this.normalizer.register(yn(void 0,a,()=>this.config.date.onAmbiguous));}this.parser=new chunkP5YWBIIU_cjs.a(this.registry,this.config.validation.maxNestingDepth,t,this.pluginFunctionIndexByName,this.context.calendar),this.vm=chunkLI6LYJDA_cjs.c(this.context.opRegistry,this.config.vm.maxStackDepth,this.config.vm.maxInstructions,void 0,this.config.vm.maxCollectionSize,this.config.vm.maxAllocatedElements,this.config.vm.maxFunctionCalls,this.config.date.maxOffsetYears,this.config.date.minOffsetYears,this.context,un(this.config.date.holidays,this.context.calendar)),this.queryClient=chunkZLRJ7TDP_cjs.c(),this.batcher=new Se(this.dag,this.lineCache,this.vm),this.backgroundRefresh=this.config.backgroundRefresh.enabled?new Re(this.dag,(a,c)=>this.batcher.add({queryKey:c,packageId:a,signal:this.backgroundRefreshSignal,isError:false})):null,e.warmup===true&&this.warmUp();}setDocumentModel(e){this.documentModel=e;}getDocumentModel(){return this.documentModel}warmUp(){let e=new chunkK3PZ66XR_cjs.d(this.pluginFunctionIndexByName);for(let t of Y.WARMUP_EXPRESSIONS)try{this.lexer.resetExpression(t);let r=[];for(let o of this.lexer)o.type!=="COMMENT"&&r.push(o);let i=this.normalizer.normalize(r);e.reset(),this.parser.load(i),this.parser.parseExpression(0,e);let s=e.build();this.vm.reset(),chunkLI6LYJDA_cjs.d(s,this.vm);}catch{}this.vm.reset();}makeLineContext(e){let t=this.documentModel,r=t?null:this.batchScanResults,i=t?null:this.batchParsedLines,s=this.lineContext;return (s===null||this.lineContextDoc!==t||this.lineContextScan!==r||this.lineContextParsed!==i)&&(s=this.buildLineContext(t,r,i,e),this.lineContext=s,this.lineContextDoc=t,this.lineContextScan=r,this.lineContextParsed=i),s.lineIndex=e,s}buildLineContext(e,t,r,i){return {lineIndex:i,getLineResult:e?s=>e.getLineAt(s)?.result??void 0:r?s=>r[s-1]?.result??void 0:void 0,isLineBoundary:e?s=>{let o=e.getLineAt(s);return o?o.isEmpty||/^\s*#/.test(o.text):true}:t?s=>{let o=t[s-1];return o?o.classification.skip||/^\s*#/.test(o.text):true}:void 0,getLineReads:e?s=>{let o=e.getLineAt(s);if(!(!o||o.bytecodes.length===0))return o.reads}:void 0,evaluateLineWithBinding:e?(s,o,l,a)=>this.evaluateLineWithBinding(s,o,l,a):void 0,goalSeekMaxIterations:this.config.vm.maxGoalSeekIterations,networkEnabled:this.config.network.enabled,calendar:this.context.calendar,getLineText:e?s=>e.getLineAt(s)?.text:t?s=>t[s-1]?.text:void 0}}evaluateLineWithBinding(e,t,r,i){let s=this.documentModel;if(!s)return chunkS3SPDK6N_cjs.P("GOAL_SEEK_NO_DOCUMENT","Goal seek needs a document to solve against, which the single-expression entry point does not have.");if(this.goalSeekDepth>=Y.GOAL_SEEK_MAX_NESTING_DEPTH)return chunkS3SPDK6N_cjs.P("GOAL_SEEK_NESTED","A goal-seek line cannot target another goal-seek line, since each already re-runs its target many times.");let o=s.getLineAt(e);if(!o||o.bytecodes.length===0)return chunkS3SPDK6N_cjs.P("GOAL_SEEK_LINE_NOT_READY",`Line ${e} has no evaluated expression to solve (forward reference, out of range, or not an expression).`);if(o.isVariableDef)return chunkS3SPDK6N_cjs.P("GOAL_SEEK_TARGET_IS_DEFINITION",`Line ${e} defines a variable, so re-running it would overwrite that variable. Target the line that uses ${t}, not the one that sets a value.`);let l=o.bytecodes[0];this.goalSeekDepth++;try{let a=new Map([[t,r]]),c=this.vm.getStack().length;this.vm.pushCallFrame(a);try{let u=chunkLI6LYJDA_cjs.d(l,this.vm,void 0,void 0,this.buildLineContext(s,null,null,e),i);return u.type==="pending"?chunkS3SPDK6N_cjs.P("GOAL_SEEK_ASYNC_UNSUPPORTED",`Line ${e} depends on an async value (weather, stocks, currency, ...), which goal seek cannot re-run.`):u.type==="error"?chunkS3SPDK6N_cjs.P(u.error.code??"GOAL_SEEK_TARGET_ERROR",u.error.message):u.value}finally{for(this.vm.popCallFrame();this.vm.getStack().length>c;)this.vm.pop();}}catch(a){return chunkS3SPDK6N_cjs.P("GOAL_SEEK_TARGET_ERROR",chunk6SYU4MH7_cjs.d(a).message)}finally{this.goalSeekDepth--;}}frontHalfCached(e){return this.compiledFrontHalf.has(e)&&this.bytecodeCache.has(e)||this.failedParses.has(e)}clearCompiledCache(){this.bytecodeCache.clear(),this.compiledFrontHalf.clear(),this.failedParses.clear();}cacheBytecode(e,t,r){let i=this.config.performance.defaultCacheSize;if(this.bytecodeCache.size>=i){let s=this.bytecodeCache.keys().next().value;s!==void 0&&(this.bytecodeCache.delete(s),this.compiledFrontHalf.delete(s));}this.bytecodeCache.set(e,t),this.compiledFrontHalf.set(e,r);}touchCompiled(e,t){this.bytecodeCache.size<this.config.performance.defaultCacheSize||(this.bytecodeCache.delete(e),this.bytecodeCache.set(e,t));}rememberFailedParse(e,t){if(this.failedParses.size>=this.config.performance.defaultCacheSize){let r=this.failedParses.keys().next().value;r!==void 0&&this.failedParses.delete(r);}this.failedParses.set(e,t);}touchFailedParse(e,t){this.failedParses.size<this.config.performance.defaultCacheSize||(this.failedParses.delete(e),this.failedParses.set(e,t));}getEventStream(){return this.batcher.getEventStream()}getBatcher(){return this.batcher}registerPackage(e){Qt(e),this.packageContributions.has(e.name)&&(console.warn(`[ExpressionEngine] Package "${e.name}" is already registered. Unregistering the previous registration before re-registering.`),this.unregisterPackage(e.name));let t=this.compatIndex.check(e);for(let i of t)(i.severity==="error"?console.error:console.warn)(`[ExpressionEngine] Package compatibility ${i.severity} (${i.kind}): ${i.detail}`);let r={pluginFunctionIndices:[],pluginFunctionNames:[],resolverNamespaces:[],tokenCategories:[],lexerVocabulary:e.lexerVocabulary,asConverterNames:[],normalizerRuleNames:[],callFusionNames:[]};if(e.lexerVocabulary&&this.lexer.registerVocabulary(e.lexerVocabulary),e.prefixParselets)for(let[i,s]of Object.entries(e.prefixParselets))this.registry.registerPrefix(i,s);if(e.infixParselets)for(let[i,s]of Object.entries(e.infixParselets))this.registry.registerInfix(i,s);if(e.pluginFunctions)for(let[i,s]of Object.entries(e.pluginFunctions)){let o=chunkFESR6PZI_cjs.F(`${e.name}:${i}`);this.context.pluginFunctions[o]=s,this.context.pluginFunctionOwners[o]=e.name,this.pluginFunctionIndexByName.set(i,o),r.pluginFunctionIndices.push(o),r.pluginFunctionNames.push(i);}if(e.asyncResolvers)for(let i of e.asyncResolvers)this.resolverRegistry.register(i),r.resolverNamespaces.push(i.namespace);if(e.phrases)for(let[i,s]of Object.entries(e.phrases))this.normalizer.addPhrase(i,s);if(e.normalizerRules)for(let i of e.normalizerRules)this.normalizer.register(i),r.normalizerRuleNames.push(i.name);if(e.callFusions)for(let[i,s]of Object.entries(e.callFusions)){let o=i.toLowerCase(),l=this.callFusionOwners.get(o);l?l.push({pkg:e.name,tokenType:s}):this.callFusionOwners.set(o,[{pkg:e.name,tokenType:s}]),this.callFusions.set(o,s),r.callFusionNames.push(o);}if(e.tokenCategories)for(let[i,s]of Object.entries(e.tokenCategories))chunkY7O4D3BJ_cjs.b(i,s),r.tokenCategories.push(i);if(e.completionItems&&this.packageCompletionItems.set(e.name,e.completionItems),e.asConverters)for(let[i,s]of Object.entries(e.asConverters))chunkFESR6PZI_cjs.H(i,s),r.asConverterNames.push(i);this.packageContributions.set(e.name,r),this.registeredPackages.set(e.name,e),this.compatIndex.add(e),this.clearCompiledCache();}unregisterPackage(e){let t=this.packageContributions.get(e);if(!t)return false;for(let r of t.pluginFunctionIndices)delete this.context.pluginFunctions[r],delete this.context.pluginFunctionOwners[r];for(let r of t.pluginFunctionNames)this.pluginFunctionIndexByName.delete(r);for(let r of t.resolverNamespaces)this.resolverRegistry.unregister(r);for(let r of t.tokenCategories)chunkY7O4D3BJ_cjs.c(r);t.lexerVocabulary&&this.lexer.unregisterVocabulary(t.lexerVocabulary);for(let r of t.asConverterNames)chunkFESR6PZI_cjs.I(r);for(let r of t.normalizerRuleNames)this.normalizer.unregister(r);for(let r of t.callFusionNames){let i=(this.callFusionOwners.get(r)??[]).filter(s=>s.pkg!==e);i.length===0?(this.callFusionOwners.delete(r),this.callFusions.delete(r)):(this.callFusionOwners.set(r,i),this.callFusions.set(r,i[i.length-1].tokenType));}return this.packageCompletionItems.delete(e),this.packageContributions.delete(e),this.registeredPackages.delete(e),this.compatIndex.rebuild(this.registeredPackages.values()),this.clearCompiledCache(),true}getConfig(){return {...this.config}}getDateReading(){return this.dateReading}readDates(e){let{tokens:t}=this.lexToTokens(e,void 0,false),r=this.normalizer.normalize(t.filter(s=>s.type!=="COMMENT")),i=[];for(let s of r){let o=s.type===chunkM4UC2PB6_cjs.p;if(!o&&s.type!==chunkM4UC2PB6_cjs.o)continue;let l=s.offset,a=s.sourceEnd??s.offset+s.text.length;i.push(this.describeDateLiteral(e.slice(l,a),l,a,s,o));}return i}describeDateLiteral(e,t,r,i,s){let o=chunkM4UC2PB6_cjs.n(e);if(o!==null){let c=chunkM4UC2PB6_cjs.l(o,this.dateReading.order,this.config.date.onAmbiguous,this.context.calendar),u=chunkM4UC2PB6_cjs.i(o.groups[0],o.groups[1],o.groups[2],o.separator)==="iso",p=this.dateReading.order==="auto"?o.separator==="hyphen"?"MDY":"DMY":this.dateReading.order,h=u?{order:"ISO",orderSource:"iso",locale:void 0}:{order:p,orderSource:this.dateReading.orderSource,locale:this.dateReading.locale};return c.kind==="date"?chunkM4UC2PB6_cjs.m({text:e,start:t,end:r,iso:chunkM4UC2PB6_cjs.k(c.day,c.month,c.year),...h,contested:c.alternative!==void 0,shortYear:c.shortYear,alternative:c.alternative},o.separator):chunkM4UC2PB6_cjs.m({text:e,start:t,end:r,iso:null,...h,contested:false,shortYear:false,problem:c.kind==="refuse"?c.code:void 0},o.separator,c.kind==="refuse"?c.message:void 0)}if(s){let c=i.fault??{code:"DATE_NOT_A_CALENDAR_DAY",message:`"${i.value}" is not a date this engine can read.`};return chunkM4UC2PB6_cjs.m({text:e,start:t,end:r,iso:null,order:null,orderSource:"spelled",contested:false,shortYear:false,problem:c.code},"slash",c.message)}let l=this.context.calendar.fields(Number(i.value)),a=/^\d{4}-/.test(e)?"iso":"spelled";return chunkM4UC2PB6_cjs.m({text:e,start:t,end:r,iso:chunkM4UC2PB6_cjs.k(l.day,l.month0+1,l.year),order:a==="iso"?"ISO":"spelled",orderSource:a,contested:false,shortYear:false},"slash")}getDiagnosticPipeline(){return this.diagnosticPipeline}storeLineResult(e,t,r,i,s,o){this.lineCache.set(e,new K(t,r,i,s.length>0?s[0]:null),o);}mayResolve(e){return e.hasAsync||this.resolverRegistry.mayIntercept(e)}armCancellation(e,t){if(!this.mayResolve(e))return this.vm.activeSignal=this.inertSignal,this.vm.abortCurrent=void 0,null;let r=new AbortController,i=()=>r.abort(),s=this.keystrokeSignal;s?.addEventListener("abort",i,{once:true}),chunkTTFO4YDP_cjs.a.localControllerCreated(t),s&&chunkTTFO4YDP_cjs.a.signalLinked(t);let o=()=>s?.removeEventListener("abort",i);return this.vm.activeSignal=r.signal,this.vm.abortCurrent=()=>{chunkTTFO4YDP_cjs.a.signalUnlinked(t),o(),r.abort();},o}executeAndStore(e,t,r,i,s,o,l,a){let c=this.vm.getStack().length,u=this.armCancellation(e,"executeAndStore");chunkZLRJ7TDP_cjs.a(this.queryClient);let p=chunkLI6LYJDA_cjs.d(e,this.vm,l,a,this.makeLineContext(t));for(;this.vm.getStack().length>c;)this.vm.pop();if(p.type==="pending"){this.resolveAsync(p),this.dag.registerLineDataSourceDependency(t,p.packageId||o,[p.queryKey]);let h=chunkS3SPDK6N_cjs.O(p.queryKey);return this.storeLineResult(t,h,e,i,s,r),h}if(p.type==="error")throw u?.(),p.error;return u?.(),this.dag.registerLine(t,i,s),this.storeLineResult(t,p.value,e,i,s,r),p.value}executeRaw(e,t=-1){let r=this.vm.getStack().length,i=this.armCancellation(e,"executeRaw");chunkZLRJ7TDP_cjs.a(this.queryClient);let s=chunkLI6LYJDA_cjs.d(e,this.vm,void 0,void 0,this.makeLineContext(t));for(;this.vm.getStack().length>r;)this.vm.pop();return s.type!=="pending"&&i?.(),s}async resolveAsync(e){let{queryKey:t,resolver:r,packageId:i,signal:s}=e,o=i||"_engine";try{if(await r,s.aborted){chunkTTFO4YDP_cjs.a.staleDataDiscarded(t,"signal aborted after resolve");return}this.batcher.add({queryKey:t,packageId:o,signal:s,isError:!1});}catch(l){if(s.aborted){chunkTTFO4YDP_cjs.a.staleDataDiscarded(t,"signal aborted after error");return}let a=l instanceof Error?l:new Error(String(l));this.batcher.add({queryKey:t,packageId:o,signal:s,isError:true,error:a});}}registerBackgroundRefresh(e){this.backgroundRefresh&&(e.refetchIntervalMs===void 0||!e.refetch||this.backgroundRefresh.register({packageId:e.packageId||"_engine",queryKey:e.queryKey,intervalMs:e.refetchIntervalMs,refetch:e.refetch}));}getBackgroundRefreshCount(){return this.backgroundRefresh?.size??0}parseDocument(e,t={inputType:"markdown"}){let r=this.config.performance.maxDocumentLines;if(chunkUURM7P3P_cjs.b(e,r)>r)throw chunk6SYU4MH7_cjs.c.execution("DOCUMENT_TOO_LARGE",`This document has more than ${r.toLocaleString("en-US")} lines, which is the most the engine will process in one pass`,{maxLines:r});this.userUnits.isEmpty||this.clearCompiledCache(),this.userUnits.clear(),this.resetAccumulators();let i=this.lexer.scanDocument(e),s=this.processScanResults(i),o={lines:s,totalLines:s.length,errors:[]};for(let a of s){a.error&&o.errors.push(`Line ${a.lineNumber}: ${a.error}`);for(let c of a.inlineSolves)c.error&&o.errors.push(`Line ${a.lineNumber}: ${c.error}`);}if(t.includeDiagnostics??false){let a=this.diagnosticPipeline.collectReports();a.length>0&&(o.diagnostics=a[0].toJSON());}return o}evaluateLines(e){this.userUnits.isEmpty||this.clearCompiledCache(),this.userUnits.clear(),this.resetAccumulators();let t=e.join(`
|
|
4
|
+
`),r=this.lexer.scanDocument(t);return this.processScanResults(r)}processScanResults(e){let t=[],r=this.batchScanResults,i=this.batchParsedLines;this.batchScanResults=e,this.batchParsedLines=t;try{for(let s of e){let o=s.text,l=s.lineNumber,a=s.startOffset,c=s.endOffset,u=s.classification.skip,p=s.inlineSolves.map(d=>({start:d.start,end:d.end,expression:d.expression,lineNumber:l,columnNumber:d.columnNumber})),h=p.length>0,y={lineNumber:l,text:o,startPosition:a,endPosition:c,isEmpty:u,hasInlineSolves:h,inlineSolves:p,expression:null,result:null,error:null};if(s.error)y.error=s.error.message;else if(!u){let d=o.trim().startsWith(":");if(h&&!d)for(let T of p)try{T.result=this.evaluateLine(l,T.expression);}catch(b){let w=b instanceof Error?b.message:String(b);T.error=w;}else {let T=s.classification.contentOffset,w=(T===void 0?o:o.slice(T-a)).trim();if(w)try{let O=this.evaluateLineWithPreTokenized(l,w,s.tokens);y.expression=w,y.result=O[0];}catch(O){let G=O instanceof Error?O.message:String(O);y.error=G;}}}t.push(y);}}finally{this.batchScanResults=r,this.batchParsedLines=i,this.lineContext=null;}return t}evaluateLineWithPreTokenized(e,t,r){let i=[],s=false;for(let o of r)(o.type==="LPAREN"||o.type==="RPAREN")&&(s=true),i.push(o);return [this.evaluateWithTokens(e,t,i,s)]}parseExpression(e,t,r,i=true){this.parser.setBuilder(e),this.parser.load(t,this.config.validation.autoBalanceParens?r:false),this.parser.parseExpression(0);let s=this.parser.peek();if(s){if(s.type==="EQUALS"&&!this.parser.peekAt(1))return;for(let o=i?t.length-1:0;o>=1;o--){if(t[o].type!=="COLON"||o+1>=t.length)continue;let l=true;for(let a=0;a<o;a++){let c=t[a].type;if(c!=="NUMBER"&&c!=="COLON"){l=false;break}}if(l){let a=t.slice(0,o+2).map(c=>c.value).join("");throw chunk6SYU4MH7_cjs.c.parsing("INVALID_TIME_LITERAL",`"${a}" is not a valid time`,{tokenType:t[o].type,tokenValue:a})}e.reset();try{this.parseExpression(e,t.slice(o+1),r,!1);return}catch{}}throw chunk6SYU4MH7_cjs.c.parsing({code:"UNEXPECTED_TRAILING_TOKEN",message:`Unexpected token after expression: "${s.value}"`,context:{tokenType:s.type,tokenValue:s.value},span:{start:s.offset,end:s.sourceEnd??s.offset+s.text.length,line:s.line,col:s.col}})}}compileAdHoc(e){let t=new chunkK3PZ66XR_cjs.d(this.pluginFunctionIndexByName);return this.parseExpression(t,e),t.build()}executeSymbolicTolerant(e,t=-1){let r=chunkLI6LYJDA_cjs.d(e,this.vm,void 0,void 0,this.makeLineContext(t),true);if(r.type==="error")throw r.error;if(r.type==="pending")throw chunk6SYU4MH7_cjs.c.execution("THEREFORE_ASYNC_UNSUPPORTED",`"=>" doesn't support expressions that call an async operation (weather/stocks/currency).`);return r.value}simplifySymbolically(e,t=-1){return this.executeSymbolicTolerant(this.compileAdHoc(e),t)}parseFactorChain(e){if(e.length===0||e.length%2===0)return null;let t=[];for(let r=0;r<e.length;r++)if(r%2===0){if(e[r].type!=="IDENT"&&e[r].type!=="UNIT")return null;t.push(e[r].value);}else if(e[r].type!=="STAR")return null;return t}solveEquation(e,t=-1){let r=[];for(let l of e.factorNames){let a=this.vm.getVar(l);if(a===void 0)return chunkS3SPDK6N_cjs.P("EQUATION_FACTOR_UNDEFINED",`Cannot solve for "${e.variable}": "${l}" is not yet defined.`);if(a.type!==7)return chunkS3SPDK6N_cjs.P("EQUATION_FACTOR_NOT_MATRIX",`Cannot solve for "${e.variable}": "${l}" must be a Matrix (got a different value type).`);r.push(a);}let i=r[0].value;for(let l=1;l<r.length;l++){let a=chunkWFT3XUSH_cjs._(i,r[l].value);if(a.type===13)return a;i=a.value;}let s=chunkWFT3XUSH_cjs.da(i);if(s.type===13)return s;let o=this.executeSymbolicTolerant(e.rhsProgram,t);return o.type!==7?chunkS3SPDK6N_cjs.P("EQUATION_RHS_NOT_MATRIX",`Cannot solve for "${e.variable}": the right-hand side must be a Matrix.`):chunkWFT3XUSH_cjs._(s.value,o.value)}tryDefineUserUnit(e){if(e.length<5||e[0].type!=="NUMBER"||Number(e[0].value)!==1)return null;let t=1;e[t].type==="STAR"&&t++;let r=[];for(;t<e.length&&e[t].type==="IDENT";)r.push(e[t].value),t++;if(r.length===0||e[t]?.type!=="EQUALS"||(t++,e[t]?.type!=="NUMBER"))return null;let i=e[t];if(t++,e[t]?.type!=="UNIT")return null;let s=e[t];return t++,t!==e.length?null:(this.userUnits.define(r,i.value,s.value),this.clearCompiledCache(),chunkS3SPDK6N_cjs.t(`${r.join(" ")} defined`))}tryCompoundAssignment(e,t=-1){if(e.length<2)return null;let r=e[0],i=e[1],s=r.type==="IDENT"||r.type==="UNIT",o=i.type==="PLUS_EQUALS"||i.type==="MINUS_EQUALS";if(!s||!o)return null;let l=e.slice(2);if(l.length===0)throw chunk6SYU4MH7_cjs.c.parsing("COMPOUND_ASSIGN_REQUIRES_EXPRESSION",`"${r.value} ${i.value}" needs an expression on the right, e.g. "${r.value} ${i.value} 10".`);let a=r.value;this.accumulatorNames.add(a),this.vm.getVar(a)===void 0&&this.vm.setVar(a,chunkS3SPDK6N_cjs.n(0));let c=i.type==="PLUS_EQUALS"?{type:"PLUS",text:"+"}:{type:"MINUS",text:"-"},u=[chunkYV4GDW5A_cjs.b("IDENT",a,[r]),chunkYV4GDW5A_cjs.b(c.type,c.text,[i]),chunkYV4GDW5A_cjs.b("LPAREN","(",[i]),...l,chunkYV4GDW5A_cjs.b("RPAREN",")",[i])],p=chunkLI6LYJDA_cjs.d(this.compileAdHoc(u),this.vm,void 0,void 0,this.makeLineContext(t),false);if(p.type==="error")throw p.error;if(p.type==="pending")throw chunk6SYU4MH7_cjs.c.execution("COMPOUND_ASSIGN_ASYNC_UNSUPPORTED","A running total (+= / -=) cannot use an async operation (weather/stocks/currency) on its right-hand side.");return this.vm.setVar(a,p.value),p.value}resetAccumulators(){for(let e of this.accumulatorNames)this.vm.deleteVar(e);return this.accumulatorNames}trySymbolicGrammar(e,t=-1){if(e.length===0)return null;if(e[e.length-1].type==="THEREFORE"){let c=e.slice(0,-1);if(c.length===0)throw chunk6SYU4MH7_cjs.c.parsing("THEREFORE_REQUIRES_EXPRESSION",'"=>" needs an expression or variable name before it.');if(c.length===1&&(c[0].type==="IDENT"||c[0].type==="UNIT")){let u=c[0].value,p=this.vm.getEquation(u),h=this.vm.getScalarEquation(u);if(p){let y=this.solveEquation(p,t);if(!(y.type===13&&y.value==="EQUATION_FACTOR_NOT_MATRIX")||!h)return y}if(h)return this.solveScalarEquation(h,t)}return this.simplifySymbolically(c,t)}if(chunkM4UC2PB6_cjs.b(e))return this.simplifySymbolically(e,t);if(e[0].type==="COLON"||e[0].type==="GLOBAL"||e[0].type==="GOAL_SEEK")return null;let i=e.findIndex(c=>c.type==="EQUALS");if(i===-1)return null;let s=this.parseFactorChain(e.slice(0,i));if(s===null)return this.tryStoreScalarEquation(e,i);let o=e.slice(i+1);if(s.length===1){let c=this.simplifySymbolically(o,t);return this.vm.setVar(s[0],c),c}let l=s[s.length-1],a=s.slice(0,-1);return this.vm.defineEquation(l,a,this.compileAdHoc(o)),this.vm.defineScalarEquation(l,this.compileAdHoc(e.slice(0,i)),this.compileAdHoc(o)),chunkS3SPDK6N_cjs.t(`${l} stored as an equation \u2014 solve with "${l} =>"`)}tryStoreScalarEquation(e,t){if(e[1]?.type==="LPAREN"||t===0||t===e.length-1)return null;let r=e.slice(0,t),i=e.slice(t+1);if(i.some(l=>l.type==="EQUALS"))return null;let s=this.equationUnknowns(r,i);if(s.length!==1)return null;let o=s[0];return this.vm.defineScalarEquation(o,this.compileAdHoc(r),this.compileAdHoc(i)),chunkS3SPDK6N_cjs.t(`${o} stored as an equation \u2014 solve with "${o} =>"`)}equationUnknowns(e,t){let r=[];for(let i of [...e,...t])i.type!=="IDENT"&&i.type!=="UNIT"||this.vm.getVar(i.value)===void 0&&(this.vm.hasUserFunction(i.value)||r.includes(i.value)||r.push(i.value));return r}solveScalarEquation(e,t=-1){let r=this.executeSymbolicTolerant(e.lhsProgram,t),i=this.executeSymbolicTolerant(e.rhsProgram,t);return chunkFESR6PZI_cjs.i(r,i,e.variable)}lexToTokens(e,t,r=true){let i=[],s=false;if(r&&!t&&this.frontHalfCached(e))return {tokens:i,hasParens:s,compiled:true};this.lexer.resetExpression(e);for(let o of this.lexer)o.type!=="COMMENT"&&((o.type==="LPAREN"||o.type==="RPAREN")&&(s=true),i.push(o),t?.(o));return {tokens:i,hasParens:s,compiled:false}}prepareExpression(e,t,r,i,s=-1){let o=this.bytecodeCache.get(e);if(o&&!i){let b=this.compiledFrontHalf.get(e);if(b)return this.touchCompiled(e,o),{kind:"ready",normalizedTokens:b.normalizedTokens,reads:b.reads,writes:b.writes,program:o,cached:true}}let l=i?void 0:this.failedParses.get(e),a;if(l)this.touchFailedParse(e,l),a=l.normalizedTokens;else {let b=_e(e,this.config.validation);if(!b.passed)return {kind:"error",stage:"length",error:b.error.engineError};let w=t.filter(G=>G.type!=="COMMENT");if(w.length===0)return {kind:"empty"};a=this.normalizer.normalize(w,i);let O=$e(a,this.config.validation);if(!O.passed)return {kind:"error",stage:"complexity",error:O.engineError,normalizedTokens:a}}let c,u=null;try{if(c=this.tryDefineUserUnit(a),c===null){let b=this.tryCompoundAssignment(a,s);b!==null&&(c=b,u=Ce(a));}c===null&&(c=this.trySymbolicGrammar(a,s));}catch(b){let{reads:w,writes:O}=Ce(a);return {kind:"error",stage:"parse",error:chunk6SYU4MH7_cjs.d(b),reads:w,writes:O,normalizedTokens:a}}if(c!==null)return {kind:"symbolic-solve",normalizedTokens:a,value:c,reads:u?.reads,writes:u?.writes};if(l)return {kind:"error",stage:"parse",error:l.error,reads:l.reads,writes:l.writes,normalizedTokens:a};let{reads:p,writes:h}=Ce(a);if(o)return this.compiledFrontHalf.set(e,{normalizedTokens:a,reads:p,writes:h}),this.touchCompiled(e,o),{kind:"ready",normalizedTokens:a,reads:p,writes:h,program:o,cached:true};let y=this.builderPool[this.builderPoolIndex++%this.builderPool.length];y.reset();let d,T=null;try{let b=z.track("parser",()=>(this.parseExpression(y,a,r),y.build()));d=b.result,T=b.alloc;}catch(b){let w=chunk6SYU4MH7_cjs.d(b);return this.rememberFailedParse(e,{error:w,normalizedTokens:a,reads:p,writes:h}),{kind:"error",stage:"parse",error:w,reads:p,writes:h,normalizedTokens:a}}return this.cacheBytecode(e,d,{normalizedTokens:a,reads:p,writes:h}),{kind:"ready",normalizedTokens:a,reads:p,writes:h,program:d,cached:false,parserAlloc:T}}preflightAsync(e,t,r,i,s,o){if(!this.mayResolve(t))return {kind:"proceed"};let l=new AbortController,a=()=>l.abort();this.keystrokeSignal?.addEventListener("abort",a,{once:true}),chunkTTFO4YDP_cjs.a.localControllerCreated("preflightAsync"),this.keystrokeSignal&&chunkTTFO4YDP_cjs.a.signalLinked("preflightAsync");let c=l.signal,u=this.resolverRegistry.preflightAll(e,t,"_engine",c,this.queryClient,this.config.network.enabled);if(u){this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.dag.registerLineDataSourceDependency(r,u.packageId||"_engine",[u.queryKey]),this.registerBackgroundRefresh(u);let p=chunkS3SPDK6N_cjs.O(u.queryKey);return this.storeLineResult(r,p,t,s,o,i),{kind:"pending",value:p}}return this.keystrokeSignal?.removeEventListener("abort",a),{kind:"proceed"}}evaluateWithTokens(e,t,r,i){let s=this.prepareExpression(t,r,i,void 0,e);if(s.kind==="empty"){let p=chunkS3SPDK6N_cjs.n(0);return this.lineCache.set(e,new K(p,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),t),p}if(s.kind==="error")throw s.error;if(s.kind==="symbolic-solve")return this.storeLineResult(e,s.value,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},s.reads??[],s.writes??[],t),s.value;let{normalizedTokens:o,reads:l,writes:a,program:c}=s,u=this.preflightAsync(o,c,e,t,l,a);return u.kind==="pending"?u.value:this.executeAndStore(c,e,t,l,a,"_engine")}evaluateLine(e,t){let r=this.evaluateLineWithDebug(e,t);if(r.error)throw r.engineError?r.engineError:chunk6SYU4MH7_cjs.c.execution("EVALUATION_ERROR",r.error,{lineNumber:e});return chunkS3SPDK6N_cjs.l(r.value)}evaluateLineWithDebug(e,t,r="expression"){let i=t.match(/^s`([^`]*)`$/);if(i){let s=i[1];return {...this.evaluateExpressionWithDiagnostic(s,e,r),inlineSolve:{start:0,end:t.length,expression:s,lineNumber:e,columnNumber:1}}}return this.evaluateExpressionWithDiagnostic(t,e,r)}addDiagnosticStage(e,t,r,i,s,o,l,a,c){e.push({stage:t,label:r,icon:i,colorClass:s,stepNumber:o,elapsedNs:l,skipped:a,output:c});}evaluateExpressionWithDiagnostic(e,t,r="expression"){let i=this.diagnosticPipeline,s=i.hasCollectors,o=this.timelineCollector?.parseletMatchCount??0,l=z.isEnabled(),a=[],c=[],u=0,p=_e(e,this.config.validation);if(!p.passed)return s&&this.addDiagnosticStage(c,"safety_length","Safety: Length","\u{1F6E1}\uFE0F","validate",2,u,false,{type:"safety_length",passed:false,expressionLength:e.length,maxLength:this.config.validation.maxExpressionLength,errorMessage:p.error.error}),{...p.error,debug:void 0,diagnostic:void 0};s&&(i.firePipelineStart({type:chunkHG4NPDN5_cjs.c.PipelineStart,elapsedNs:0,expression:e,inputType:r}),this.addDiagnosticStage(c,"pipeline_start","Pipeline Start","\u25B6","pipeline",1,u,false,{type:"pipeline_start",expression:e,inputType:r}),this.addDiagnosticStage(c,"safety_length","Safety: Length","\u{1F6E1}\uFE0F","validate",2,u,false,{type:"safety_length",passed:true,expressionLength:e.length,maxLength:this.config.validation.maxExpressionLength}));let h=s?m=>{i.fireTokenEmitted({type:chunkHG4NPDN5_cjs.c.TokenEmitted,elapsedNs:0,expression:e,token:{type:m.type,value:m.value,offset:m.offset||0,line:m.line||t,col:m.col||0}});}:void 0,y=z.track("lexer",()=>this.lexToTokens(e,h)),d=y.result.tokens,T=y.result.hasParens,b=y.result.compiled;if(l&&y.alloc&&a.push(y.alloc),s){let m={};for(let P of d)m[P.type]=(m[P.type]||0)+1;this.addDiagnosticStage(c,"lexer","Lexer","\u{1F524}","lexer",3,u,false,{type:"lexer",tokenCount:d.length,tokenTypes:m,hasParens:T,locale:this.localeCode,tokens:[...d]});let A=[];for(let P=0;P<d.length;P++){let se=d[P];if(se.type==="INLINE_SOLVE_START"){let V=-1;for(let W=P+1;W<d.length;W++)if(d[W].type==="BACKTICK_OPEN"){V=W;break}if(V>P){let kn=d.slice(P+1,V).map(Cn=>Cn.value).join("");A.push({startTokenIndex:P,endTokenIndex:V,expression:kn,columnNumber:se.col||1}),P=V;}}}this.addDiagnosticStage(c,"line_classification","Line Classification","\u{1F4CB}","classify",3.5,u,false,{type:"line_classification",classification:"expression",skip:false,hasInlineSolve:A.length>0,inlineSolveSpans:A});}if(!b&&d.length===0){let m=chunkS3SPDK6N_cjs.n(0);return this.lineCache.set(t,new K(m,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:0,totalOpcodes:0}),{value:m,tokens:d,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}let w=0,O=[],G=new Map,En=s?m=>{w++,O.push(m),G.set(m.rule,(G.get(m.rule)||0)+1),i.fireTokenFused({type:chunkHG4NPDN5_cjs.c.TokenFused,elapsedNs:0,expression:e,ruleName:m.rule,sourceTokenCount:m.sourceTokens.length,fusedTokenType:m.fusedToken.type,fusedTokenValue:m.fusedToken.value});}:void 0;s&&this.normalizer.ruleCount>0&&i.fireNormalizerStart({type:chunkHG4NPDN5_cjs.c.NormalizerStart,elapsedNs:0,expression:e,inputTokenCount:d.length});let D=this.bytecodeCache.get(e);s&&!D&&this.parser.setDiagnosticPipeline(i,e);let v=this.prepareExpression(e,d,T,En,t);b&&v.kind==="ready"&&(d=v.normalizedTokens),l&&v.kind==="ready"&&v.parserAlloc&&a.push(v.parserAlloc),s&&!D&&this.parser.setDiagnosticPipeline(void 0,"");let S=v.kind==="empty"?d:v.normalizedTokens??d;if(s&&(this.normalizer.ruleCount>0?(i.fireNormalizerEnd({type:chunkHG4NPDN5_cjs.c.NormalizerEnd,elapsedNs:0,expression:e,outputTokenCount:S.length,fusionsCount:w}),this.addDiagnosticStage(c,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,false,{type:"normalizer",inputTokenCount:d.length,outputTokenCount:S.length,fusions:O,rulesApplied:[...G.entries()].map(([m,A])=>({rule:m,count:A})),tokens:[...S],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(S)})):this.addDiagnosticStage(c,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,true,{type:"normalizer",inputTokenCount:d.length,outputTokenCount:d.length,fusions:[],rulesApplied:[],tokens:[...d],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(d)})),v.kind==="empty"||v.kind==="error"&&v.stage==="length"){if(s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:v.kind==="empty",totalTokens:d.length,totalOpcodes:0}),v.kind==="empty"){let m=chunkS3SPDK6N_cjs.n(0);return this.lineCache.set(t,new K(m,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),{value:m,tokens:d,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}return {value:chunkS3SPDK6N_cjs.n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:v.error.message,engineError:v.error,debug:void 0,diagnostic:void 0}}let ne=$e(S,this.config.validation);if(v.kind==="error"&&v.stage==="complexity")return s&&(this.addDiagnosticStage(c,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:false,complexityScore:ne.complexityScore??0,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:S.length,functionCalls:0,nestingDepth:0},errorMessage:ne.errorMessage}),i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d.length,totalOpcodes:0})),{value:chunkS3SPDK6N_cjs.n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:ne.errorMessage,engineError:ne.engineError,debug:void 0,diagnostic:void 0};if(s&&this.addDiagnosticStage(c,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:true,complexityScore:ne.complexityScore??S.length,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:S.length,functionCalls:0,nestingDepth:0}}),v.kind==="symbolic-solve"){s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d.length,totalOpcodes:0});let m={opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false};return this.storeLineResult(t,v.value,m,v.reads??[],v.writes??[],e),{value:v.value,tokens:S,program:m,debug:void 0,diagnostic:void 0}}let ge=v.reads??[],re=v.writes??[];if(s&&(this.addDiagnosticStage(c,"readwrite","Read/Write","\u{1F4CB}","readwrite",6,u,false,{type:"readwrite",reads:ge,writes:re,isAssignment:re.length>0}),this.addDiagnosticStage(c,"cache_check","Cache Check","\u{1F4BE}","cache",7,u,false,{type:"cache_check",hit:!!D,cacheSize:this.bytecodeCache.size,cacheKey:e}),D?i.fireCacheHit({type:chunkHG4NPDN5_cjs.c.CacheHit,elapsedNs:0,expression:e,cache:"bytecode",key:e}):i.fireCacheMiss({type:chunkHG4NPDN5_cjs.c.CacheMiss,elapsedNs:0,expression:e,cache:"bytecode",key:e})),v.kind==="error"&&v.stage==="parse")return s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d.length,totalOpcodes:0}),{value:chunkS3SPDK6N_cjs.n(0),tokens:S,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:v.error.message,engineError:v.error,debug:void 0,diagnostic:void 0};if(v.kind!=="ready")throw chunk6SYU4MH7_cjs.c.internal({code:"UNEXPECTED_ERROR",message:"Internal error: prepareExpression() returned an unexpected variant after all other cases were handled"});let x=v.program;s&&(this.addDiagnosticStage(c,"parser","Parser","\u{1F333}","parser",8,u,!!D,{type:"parser",parselets:[],uniqueParseletTypes:[],astDepth:0}),this.addDiagnosticStage(c,"compiler","Compiler","\u2699\uFE0F","compiler",9,u,!!D,{type:"compiler",opcodeCount:x.opcodes.length,numberConstants:x.numbers.length,stringConstants:x.strings.length,hasAsync:x.hasAsync,cached:!!D}),i.fireBytecodeBuilt({type:chunkHG4NPDN5_cjs.c.BytecodeBuilt,elapsedNs:0,expression:e,opcodesLength:x.opcodes.length,numbersLength:x.numbers.length,stringsLength:x.strings.length,isCached:!!D}));let xn=this.mayResolve(x),ie=this.preflightAsync(S,x,t,e,ge,re);if(s&&(ie.kind==="pending"?this.addDiagnosticStage(c,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"pending",pendingQueryKey:ie.value.value,resolverCount:this.resolverRegistry.size,skippedGuard:true}):xn?this.addDiagnosticStage(c,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"sync",resolverCount:this.resolverRegistry.size,skippedGuard:false}):this.addDiagnosticStage(c,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,true,{type:"async_preflight",path:"sync",resolverCount:this.resolverRegistry.size,skippedGuard:true})),ie.kind==="pending")return s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d.length,totalOpcodes:x.opcodes.length}),{value:ie.value,tokens:S,program:x,debug:void 0,diagnostic:s?this.buildDiagnosticResult(c,ie.value,S,x,null):void 0};let Sn=s&&this.config.diagnostic.vmTraceEnabled===true,R;try{let m=z.track("vm",()=>this.executeAndStore(x,t,e,ge,re,"_engine",Sn?i:void 0,e),{cacheHit:!!D});R=m.result,l&&m.alloc&&a.push(m.alloc);}catch(m){let A=chunk6SYU4MH7_cjs.d(m);return s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d.length,totalOpcodes:x.opcodes.length}),{value:chunkS3SPDK6N_cjs.n(0),tokens:S,program:x,error:A.message,engineError:A,debug:void 0,diagnostic:void 0}}let he=R.type===12;if(s){let m=he?"pending":String(R.value??""),A=he?"Pending":R.unit?"Uom":"Number";this.addDiagnosticStage(c,"vm_execute","VM Execute","\u26A1","vm",11,u,false,{type:"vm_execute",totalInstructions:x.opcodes.length,stackDepth:this.vm.getStack().length,resultType:A,resultValue:m,isPending:he});}if(he)return s&&i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d.length,totalOpcodes:x.opcodes.length}),{value:R,tokens:S,program:x,debug:void 0,diagnostic:s?this.buildDiagnosticResult(c,R,S,x,null):void 0};if(l&&a.length>0&&(this.lastTelemetry=z.createTelemetry(e,a,!!D)),s&&(this.addDiagnosticStage(c,"dag_registration","DAG Registration","\u{1F517}","dag",12,u,false,{type:"dag_registration",readsRegistered:ge,writesRegistered:re,dataSourcesRegistered:[]}),this.addDiagnosticStage(c,"linecache","Line Cache","\u{1F4E6}","cache",13,u,false,{type:"linecache",lineNumber:t,expression:e,stored:true}),this.addDiagnosticStage(c,"result","Result","\u2713","result",14,u,false,{type:"result",rawValue:String(R.value),formattedValue:String(R.value),valueType:R.type===0?"Number":"Value",unit:R.unit}),i.fireVmHalt({type:chunkHG4NPDN5_cjs.c.VmHalt,elapsedNs:0,expression:e,result:R?{type:R.type,value:R.value,unit:R.unit}:void 0}),this.addDiagnosticStage(c,"pipeline_end","Pipeline End","\u23F9","pipeline",15,u,false,{type:"pipeline_end",success:true,totalTokens:d.length,totalOpcodes:x.opcodes.length,cacheHit:!!D}),i.firePipelineEnd({type:chunkHG4NPDN5_cjs.c.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d.length,totalOpcodes:x.opcodes.length})),s){let A=i.collectReports()[0]?.toJSON(),P=A;if(A){let se=A.parselets.slice(o),V={};for(let W of se)V[W.parseletCategory]=(V[W.parseletCategory]??0)+1;P={...A,parselets:se,summary:{...A.summary,totalParselets:Object.keys(V).length,parseCategories:V}};}return {value:R,tokens:S,program:x,debug:P,diagnostic:this.buildDiagnosticResult(c,R,S,x,null)}}return {value:R,tokens:S,program:x}}buildDiagnosticResult(e,t,r,i,s){return {stages:e,value:t,tokens:r,program:i,error:s,dagSnapshot:this.dag.getSnapshot(),cacheSnapshot:this.getCacheSnapshot(),batcherMetrics:this.getBatcherMetrics(),checkpoints:this.getCheckpoints()}}reEvaluateLine(e,t){let r=this.lineCache.get(e,t);if(!r)return;let i=this.bytecodeCache.get(t);if(!i)return;if(this.touchCompiled(t,i),this.mayResolve(r.bytecode)){let l=new AbortController,a=()=>l.abort();this.keystrokeSignal?.addEventListener("abort",a,{once:true}),chunkTTFO4YDP_cjs.a.localControllerCreated("reEvaluateLine preflight"),this.keystrokeSignal&&chunkTTFO4YDP_cjs.a.signalLinked("reEvaluateLine preflight");let c=l.signal,u=this.resolverRegistry.preflightAll([],r.bytecode,"_engine",c,this.queryClient,this.config.network.enabled);if(u)return this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.registerBackgroundRefresh(u),chunkS3SPDK6N_cjs.O(u.queryKey);this.keystrokeSignal?.removeEventListener("abort",a);}let s=this.executeRaw(i,e);if(s.type==="pending")return this.resolveAsync(s),chunkS3SPDK6N_cjs.O(s.queryKey);if(s.type==="error")throw s.error;let o=s.value;return r.result=o,o}getDag(){return this.dag}getLineCache(){return this.lineCache}getBytecodeCache(){return this.bytecodeCache}getVM(){return this.vm}getContext(){return this.context}getScopeManager(){return this.scopeManager}getLexer(){return this.lexer}getNormalizer(){return this.normalizer}getPackageCompletionItems(){let e=[];for(let t of this.packageCompletionItems.values())e.push(...t);return e}getParseletRegistry(){return {prefix:this.registry.getAllPrefix(),infix:this.registry.getAllInfix()}}tokenizeForClassification(e){this.lexer.resetExpression(e);let r=Array.from(this.lexer).filter(i=>i.type!=="COMMENT");return r.length===0?[]:this.normalizer.normalize(r)}getParser(){return this.parser}isDiagnosticMode(){return this.diagnosticPipeline.hasCollectors}setKeystrokeSignal(e){e?chunkTTFO4YDP_cjs.a.keystrokeSignalSet(e.aborted):chunkTTFO4YDP_cjs.a.keystrokeSignalCleared(),this.keystrokeSignal=e;}getCacheSnapshot(){let e=[];for(let[o,l]of this.bytecodeCache)e.push({expression:o,opcodesLength:l.opcodes.length,numbersLength:l.numbers.length,stringsLength:l.strings.length,hasAsync:l.hasAsync});let t=[];for(let o of this.lineCache.keys()){let l=o.indexOf(":"),a=l>0?parseInt(o.slice(0,l),10)||0:parseInt(o,10)||0,c=l>0?o.slice(l+1):void 0,u=c!==void 0?this.lineCache.get(a,c):this.lineCache.getEntryForLine(a);u&&t.push({key:o,lineNumber:a,resultType:String(u.result?.type??""),resultValue:String(u.result?.value??""),reads:u.readVariables??[],writeVar:u.writeVariable??null});}let s=this.queryClient.getQueryCache().getAll().map(o=>{let l=o.state.status==="success"?"resolved":o.state.status==="error"?"error":"in_flight";return {packageId:o.queryKey[0]??"unknown",resolvedCount:o.state.status==="success"?1:0,inFlightCount:o.state.status!=="success"&&o.state.status!=="error"?1:0,errorCount:o.state.status==="error"?1:0,entries:[{key:o.queryKey.join(":"),status:l}]}});return {bytecode:e,lineCache:t,asyncCache:s}}getBatcherMetrics(){return {pendingCount:this.batcher.pendingCount,dedupCount:this.batcher.dedupCount,workerOffloadCount:this.batcher.workerOffloadCount,listenerCount:this.batcher.listenerCount}}getCheckpoints(){let t=this.vm.checkpointer;return t?t.getAllCheckpoints().map(i=>({lineNumber:i.lineNumber,variables:Object.keys(i.variables),variableCount:Object.keys(i.variables).length})):[]}getLastTelemetry(){return this.lastTelemetry}evaluateExpression(e){return this.evaluateLine(-1,e)}explainLine(e){let{tokens:t}=this.lexToTokens(e,void 0,false),r=t.filter(s=>s.type!=="COMMENT"),i=this.normalizer.normalize(r);return Ge({expression:e,tokens:i,evaluate:s=>this.evaluateIsolated(s),locale:this.localeCode,readings:this.readDates(e)})}evaluateIsolated(e){let{tokens:t,hasParens:r}=this.lexToTokens(e),i=this.prepareExpression(e,t,r,void 0,-1);if(i.kind==="empty")return chunkS3SPDK6N_cjs.n(0);if(i.kind==="error")throw i.error;if(i.kind==="symbolic-solve")return i.value;let s=this.executeRaw(i.program,-1);if(s.type==="error")throw s.error;if(s.type==="pending")throw chunk6SYU4MH7_cjs.c.execution("EXPLAIN_ASYNC_UNSUPPORTED",`A derivation cannot be built for a line that resolves data asynchronously: "${e}"`,{expression:e});return s.value}compileExpression(e){let t=this.lexToTokens(e),{hasParens:r}=t,i=this.prepareExpression(e,t.tokens,r),s=t.compiled&&i.kind==="ready"?i.normalizedTokens:t.tokens;if(i.kind==="empty")return {program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:[],reads:[],writes:[]};if(i.kind==="error")throw i.stage==="parse"&&(i.reads?.length||i.writes?.length)?new chunk6SYU4MH7_cjs.b(i.error.category,{code:i.error.code,message:i.error.message,expected:i.error.expected,found:i.error.found,suggestion:i.error.suggestion,recoverable:i.error.recoverable,span:i.error.span,cause:i.error.cause,context:{...i.error.context,reads:i.reads??[],writes:i.writes??[]}}):i.error;return i.kind==="symbolic-solve"?{program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:i.normalizedTokens,reads:i.reads??[],writes:i.writes??[]}:{program:i.program,tokens:s,reads:i.reads,writes:i.writes}}tryCompileExpression(e){try{return this.tryCompileExpressionUnguarded(e)}catch{return false}}tryCompileExpressionUnguarded(e){let{tokens:t,hasParens:r}=this.lexToTokens(e);return this.prepareExpression(e,t,r).kind!=="error"}executeCached(e,t=-1){if(e.opcodes.length===0)return chunkS3SPDK6N_cjs.n(0);let r=this.executeRaw(e,t);if(r.type==="pending")return this.resolveAsync(r),chunkS3SPDK6N_cjs.O(r.queryKey);if(r.type==="error")throw r.error;return r.value}evaluateNumber(e){let t=e.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&this.vm.getVar(t)===void 0)return NaN;try{let r=this.evaluateLine(-1,e);return r.isFault()?NaN:r.toNumber()}catch{return NaN}}clear(){this.batcher.clearAll(),this.backgroundRefresh?.clearAll(),this.queryClient.clear(),chunkZLRJ7TDP_cjs.b()===this.queryClient&&chunkZLRJ7TDP_cjs.a(null),this.dag.clear(),this.lineCache.clear(),this.scopeManager.clear(),this.clearCompiledCache(),this.vm.reset(),this.userUnits.clear(),this.accumulatorNames.clear(),this.lastTelemetry=null,this.lineContext=null;}toJSON(){let e=this.dag.getSnapshot(),t=new Set;for(let c of Object.keys(e.dataSourceDeps)){let u=Number(c);Number.isNaN(u)||t.add(u);}let r=this.lineCache.snapshotEntries(),i=new Map;for(let{line:c,entry:u}of r){let p=t.has(c)||u.bytecode.hasAsync;p&&t.add(c);let h=u.writeVariable;if(h){let y=i.get(h);(!y||c>=y.line)&&i.set(h,{line:c,async:p});}}let s={};for(let[c,u]of this.vm.getVariableEntries())if(u.type!==12&&!i.get(c)?.async)try{s[c]=Ve(u,`variable "${c}"`);}catch(p){if(p instanceof chunk6SYU4MH7_cjs.b&&p.code===M.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw p}let o=this.vm.getUserFunctionDefs().map(ze),l=[];for(let{line:c,expression:u,entry:p}of r){if(t.has(c)||p.result.type===12)continue;let h;try{h=Ve(p.result,`line ${c}`);}catch(y){if(y instanceof chunk6SYU4MH7_cjs.b&&y.code===M.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw y}l.push({line:c,expression:u,result:h,bytecode:ue(p.bytecode),reads:p.readVariables.slice(),writeVar:p.writeVariable});}let a=Array.from(this.bytecodeCache.entries()).map(([c,u])=>({expression:c,program:ue(u)}));return {format:ee,version:Q,engineVersion:chunk2XOLAHW6_cjs.a,locale:this.localeCode,variables:s,userFunctions:o,lineCache:l,bytecodeCache:a}}static fromJSON(e,t={}){nn(e);let r=t.locale??e.locale??"en",i=new Y({locale:r,diagnostics:t.diagnostics??false,config:t.config,packages:t.packages,calendar:t.calendar});return i.restoreSnapshot(e),i}restoreSnapshot(e){for(let[t,r]of Object.entries(e.variables))this.vm.setVar(t,Be(r));for(let t of e.userFunctions){let r=Fe(t);this.vm.defineUserFunction(r.name,r.params,r.program);}for(let t of e.lineCache){let r=new K(Be(t.result),pe(t.bytecode),t.reads.slice(),t.writeVar);this.lineCache.set(t.line,r,t.expression),this.dag.registerLine(t.line,t.reads,t.writeVar?[t.writeVar]:[]);}for(let{expression:t,program:r}of e.bytecodeCache)this.bytecodeCache.set(t,pe(r));}evaluateIncremental(e,t){let r=this.dag.getAffectedLinesInOrder(e);this.vm.setVar(e,chunkS3SPDK6N_cjs.n(t));let i=new Map;for(let s of r){let o=this.lineCache.getEntryForLine(s);if(!o||o.bytecode.opcodes.length===0)continue;let l=this.executeRaw(o.bytecode,s);if(l.type==="pending"){this.resolveAsync(l);continue}if(l.type==="error"){let c=chunkS3SPDK6N_cjs.P(l.error.code,l.error.message);i.set(s,c),o.result=c;continue}let a=l.value;i.set(s,a),o.result=a;}return i}};Y.GOAL_SEEK_MAX_NESTING_DEPTH=1,Y.WARMUP_EXPRESSIONS=["1 + 2 * 3","10.5 / 2 - 0.25","50% of 200","3 kg + 400 g","sqrt(144) + max(1, 2)","1 < 2 && 3 >= 3","half of 250",'"text" + "joined"'];var bn=Y;exports.a=Zn;exports.b=Ln;exports.c=Qt;exports.d=ee;exports.e=Q;exports.f=M;exports.g=cr;exports.h=Ue;exports.i=Se;exports.j=_e;exports.k=$e;exports.l=Ce;exports.m=Cr;exports.n=Tr;exports.o=bn;//# sourceMappingURL=chunk-WCVPXBCW.cjs.map
|
|
5
|
+
//# sourceMappingURL=chunk-WCVPXBCW.cjs.map
|