solve-engine 2.23.0 → 2.25.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/README.md +82 -32
- package/dist/{BytecodeBuilder-aqVa7Plx.d.cts → BytecodeBuilder-DSWKZi4f.d.cts} +11 -9
- package/dist/{BytecodeBuilder-aqVa7Plx.d.ts → BytecodeBuilder-DSWKZi4f.d.ts} +11 -9
- package/dist/{Configuration-BGQn-cJ8.d.cts → Configuration-DnzYPmoK.d.cts} +33 -0
- package/dist/{Configuration-BGQn-cJ8.d.ts → Configuration-DnzYPmoK.d.ts} +33 -0
- package/dist/{EngineError-DTk7I7hZ.d.cts → EngineError-fR1K1rvx.d.cts} +6 -0
- package/dist/{EngineError-DTk7I7hZ.d.ts → EngineError-fR1K1rvx.d.ts} +6 -0
- package/dist/{Lexer-CqagTewQ.d.ts → Lexer-Bmctxl0n.d.ts} +84 -35
- package/dist/{Lexer-CCHFDcgP.d.cts → Lexer-aB95pjoX.d.cts} +84 -35
- package/dist/{PackageCompatibility-BGXSFuL9.d.ts → PackageCompatibility-BludTs7v.d.ts} +1 -1
- package/dist/{PackageCompatibility-BZCqaTOO.d.cts → PackageCompatibility-CUVg8tmt.d.cts} +1 -1
- package/dist/{PackageRegistry-BRoVOYzg.d.ts → PackageRegistry-DT-x32OM.d.ts} +67 -14
- package/dist/{PackageRegistry-rMGnTh7W.d.cts → PackageRegistry-Dvn4i2QK.d.cts} +67 -14
- package/dist/{Parselet-Bkbp9CKD.d.cts → Parselet-BawfGuTF.d.cts} +8 -2
- package/dist/{Parselet-B-WyUtX4.d.ts → Parselet-DqTbbtWA.d.ts} +8 -2
- package/dist/{ScopeManager-gB9UengK.d.ts → ScopeManager-B636am7Y.d.ts} +39 -8
- package/dist/{ScopeManager-bCYewWVt.d.cts → ScopeManager-CdwX0VTw.d.cts} +39 -8
- package/dist/{TokenNormalizer-OTPS0Otq.d.ts → TokenNormalizer-CLBtiE8M.d.ts} +45 -26
- package/dist/{TokenNormalizer-MXaKLJ_m.d.cts → TokenNormalizer-CjTDmHgB.d.cts} +45 -26
- package/dist/{VMCheckpoints-DGar9Yg8.d.cts → VMCheckpoints-CYqeq8IV.d.cts} +3 -3
- package/dist/{VMCheckpoints-BDRY1Kx8.d.ts → VMCheckpoints-DDlxNssY.d.ts} +3 -3
- package/dist/{Value-DCTqTSeP.d.cts → Value-Ds3Gy07C.d.cts} +1 -1
- package/dist/{Value-DCTqTSeP.d.ts → Value-Ds3Gy07C.d.ts} +1 -1
- package/dist/{WorkerError-DGBNM3gA.d.cts → WorkerError-B1dF3VYT.d.cts} +1 -1
- package/dist/{WorkerError-DpZgKRks.d.ts → WorkerError-dneODN-u.d.ts} +1 -1
- package/dist/{chunk-YAONCEAW.cjs → chunk-4BAUQE6A.cjs} +3 -3
- package/dist/{chunk-YAONCEAW.cjs.map → chunk-4BAUQE6A.cjs.map} +1 -1
- package/dist/chunk-4BRTUFTH.js +2 -0
- package/dist/chunk-4BRTUFTH.js.map +1 -0
- package/dist/chunk-4NZXCHQL.cjs +2 -0
- package/dist/chunk-4NZXCHQL.cjs.map +1 -0
- package/dist/chunk-57PSJQQW.js +3 -0
- package/dist/chunk-57PSJQQW.js.map +1 -0
- package/dist/chunk-634ILVMP.cjs +2 -0
- package/dist/chunk-634ILVMP.cjs.map +1 -0
- package/dist/{chunk-HMC7FJO7.js → chunk-63ZOOUOL.js} +2 -2
- package/dist/{chunk-HMC7FJO7.js.map → chunk-63ZOOUOL.js.map} +1 -1
- package/dist/chunk-72PYPENZ.js +2 -0
- package/dist/chunk-72PYPENZ.js.map +1 -0
- package/dist/chunk-77KI7AKJ.cjs +2 -0
- package/dist/chunk-77KI7AKJ.cjs.map +1 -0
- package/dist/chunk-7DP57BA7.js +2 -0
- package/dist/chunk-7DP57BA7.js.map +1 -0
- package/dist/chunk-7N3IJSWF.js +5 -0
- package/dist/chunk-7N3IJSWF.js.map +1 -0
- package/dist/chunk-BMXYR5LI.cjs +2 -0
- package/dist/chunk-BMXYR5LI.cjs.map +1 -0
- package/dist/chunk-DUYTXLO2.js +2 -0
- package/dist/chunk-DUYTXLO2.js.map +1 -0
- package/dist/chunk-EL2XUOWX.js +2 -0
- package/dist/chunk-EL2XUOWX.js.map +1 -0
- package/dist/chunk-FYAMQFZZ.cjs +3 -0
- package/dist/chunk-FYAMQFZZ.cjs.map +1 -0
- package/dist/chunk-FYTB7SDP.cjs +2 -0
- package/dist/chunk-FYTB7SDP.cjs.map +1 -0
- package/dist/chunk-GBCN7FNV.cjs +2 -0
- package/dist/chunk-GBCN7FNV.cjs.map +1 -0
- package/dist/{chunk-7E7NXKQ5.js → chunk-IJHL3LMH.js} +2 -2
- package/dist/chunk-IJHL3LMH.js.map +1 -0
- package/dist/{chunk-4ETS224G.js → chunk-JFZ5SLF7.js} +2 -2
- package/dist/{chunk-4ETS224G.js.map → chunk-JFZ5SLF7.js.map} +1 -1
- package/dist/chunk-JSM3O7EM.cjs +2 -0
- package/dist/chunk-JSM3O7EM.cjs.map +1 -0
- package/dist/chunk-MZMA32NE.js +3 -0
- package/dist/chunk-MZMA32NE.js.map +1 -0
- package/dist/chunk-N4SSR7Q6.js +2 -0
- package/dist/chunk-N4SSR7Q6.js.map +1 -0
- package/dist/{chunk-TL545PXW.cjs → chunk-NEGZZB7F.cjs} +2 -2
- package/dist/{chunk-TL545PXW.cjs.map → chunk-NEGZZB7F.cjs.map} +1 -1
- package/dist/{chunk-3GR46UOX.js → chunk-NMU5E7W7.js} +2 -2
- package/dist/{chunk-3GR46UOX.js.map → chunk-NMU5E7W7.js.map} +1 -1
- package/dist/chunk-OB2VX4IL.js +2 -0
- package/dist/chunk-OB2VX4IL.js.map +1 -0
- package/dist/{chunk-MRRMIBHE.js → chunk-OONQ3V3I.js} +2 -2
- package/dist/{chunk-MRRMIBHE.js.map → chunk-OONQ3V3I.js.map} +1 -1
- package/dist/{chunk-N37PUZJR.cjs → chunk-RAPEZR5L.cjs} +2 -2
- package/dist/{chunk-N37PUZJR.cjs.map → chunk-RAPEZR5L.cjs.map} +1 -1
- package/dist/{chunk-KEA5HRL3.js → chunk-RDYXH7ML.js} +2 -2
- package/dist/{chunk-KEA5HRL3.js.map → chunk-RDYXH7ML.js.map} +1 -1
- package/dist/{chunk-3SSMOVWB.cjs → chunk-SAF3B3AX.cjs} +2 -2
- package/dist/{chunk-3SSMOVWB.cjs.map → chunk-SAF3B3AX.cjs.map} +1 -1
- package/dist/chunk-SPOVFRZO.cjs +5 -0
- package/dist/chunk-SPOVFRZO.cjs.map +1 -0
- package/dist/{chunk-75JLWK4L.cjs → chunk-SQHBOWES.cjs} +2 -2
- package/dist/{chunk-75JLWK4L.cjs.map → chunk-SQHBOWES.cjs.map} +1 -1
- package/dist/chunk-UF5XMZTT.js +2 -0
- package/dist/chunk-UF5XMZTT.js.map +1 -0
- package/dist/chunk-UV3EUIBT.cjs +3 -0
- package/dist/chunk-UV3EUIBT.cjs.map +1 -0
- package/dist/chunk-VMSCRVNX.cjs +2 -0
- package/dist/chunk-VMSCRVNX.cjs.map +1 -0
- package/dist/{chunk-J7ABVGZH.cjs → chunk-WGP4UUO5.cjs} +2 -2
- package/dist/{chunk-J7ABVGZH.cjs.map → chunk-WGP4UUO5.cjs.map} +1 -1
- package/dist/chunk-XBGK3TTU.cjs +3 -0
- package/dist/chunk-XBGK3TTU.cjs.map +1 -0
- package/dist/chunk-XHQYHXRE.js +3 -0
- package/dist/chunk-XHQYHXRE.js.map +1 -0
- package/dist/chunk-XX55RR4Q.js +3 -0
- package/dist/chunk-XX55RR4Q.js.map +1 -0
- package/dist/chunk-YBQPEWT7.cjs +3 -0
- package/dist/chunk-YBQPEWT7.cjs.map +1 -0
- package/dist/{chunk-CHSO3DCS.js → chunk-ZDCZ5IDD.js} +3 -3
- package/dist/{chunk-CHSO3DCS.js.map → chunk-ZDCZ5IDD.js.map} +1 -1
- package/dist/{chunk-LNZNJSRW.cjs → chunk-ZVPZQ66D.cjs} +2 -2
- package/dist/chunk-ZVPZQ66D.cjs.map +1 -0
- package/dist/constants.cjs +1 -1
- package/dist/constants.d.cts +1 -1
- package/dist/constants.d.ts +1 -1
- package/dist/constants.js +1 -1
- package/dist/engine.cjs +1 -1
- package/dist/engine.d.cts +12 -12
- package/dist/engine.d.ts +12 -12
- package/dist/engine.js +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 +14 -12
- package/dist/index.d.ts +14 -12
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/language.d.cts +11 -11
- package/dist/language.d.ts +11 -11
- package/dist/lexer.cjs +1 -1
- package/dist/lexer.cjs.map +1 -1
- package/dist/lexer.d.cts +8 -7
- package/dist/lexer.d.ts +8 -7
- package/dist/lexer.js +1 -1
- package/dist/lexer.js.map +1 -1
- package/dist/normalizer.cjs +1 -1
- package/dist/normalizer.d.cts +16 -10
- package/dist/normalizer.d.ts +16 -10
- package/dist/normalizer.js +1 -1
- package/dist/packages.cjs +1 -1
- package/dist/packages.d.cts +10 -10
- package/dist/packages.d.ts +10 -10
- package/dist/packages.js +1 -1
- package/dist/parser.cjs +1 -1
- package/dist/parser.d.cts +4 -4
- package/dist/parser.d.ts +4 -4
- package/dist/parser.js +1 -1
- package/dist/{pipeline-B4wf3M1h.d.cts → pipeline-69q2tsLE.d.cts} +1 -1
- package/dist/{pipeline-QIT4iD8f.d.ts → pipeline-DTqGLPsV.d.ts} +1 -1
- package/dist/resolvers.cjs +1 -1
- package/dist/resolvers.d.cts +19 -3
- package/dist/resolvers.d.ts +19 -3
- package/dist/resolvers.js +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.d.cts +11 -11
- package/dist/testing.d.ts +11 -11
- package/dist/testing.js +1 -1
- package/dist/uom.cjs +1 -1
- package/dist/uom.d.cts +2 -2
- package/dist/uom.d.ts +2 -2
- package/dist/uom.js +1 -1
- package/dist/vm.cjs +1 -1
- package/dist/vm.d.cts +8 -8
- package/dist/vm.d.ts +8 -8
- package/dist/vm.js +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +34 -25
- package/dist/worker.d.ts +34 -25
- package/dist/worker.js +1 -1
- package/dist/worker.js.map +1 -1
- package/package.json +5 -5
- package/dist/chunk-42JXN3BH.js +0 -5
- package/dist/chunk-42JXN3BH.js.map +0 -1
- package/dist/chunk-4DJJIUQF.js +0 -2
- package/dist/chunk-4DJJIUQF.js.map +0 -1
- package/dist/chunk-6YM67DWH.cjs +0 -3
- package/dist/chunk-6YM67DWH.cjs.map +0 -1
- package/dist/chunk-7E7NXKQ5.js.map +0 -1
- package/dist/chunk-7SZBEE5R.cjs +0 -2
- package/dist/chunk-7SZBEE5R.cjs.map +0 -1
- package/dist/chunk-A5M4QZIK.js +0 -2
- package/dist/chunk-A5M4QZIK.js.map +0 -1
- package/dist/chunk-AF7HQN6I.js +0 -2
- package/dist/chunk-AF7HQN6I.js.map +0 -1
- package/dist/chunk-ALY4ZMYO.js +0 -2
- package/dist/chunk-ALY4ZMYO.js.map +0 -1
- package/dist/chunk-BRJ4RT5U.js +0 -2
- package/dist/chunk-BRJ4RT5U.js.map +0 -1
- package/dist/chunk-CO2BI6WL.cjs +0 -3
- package/dist/chunk-CO2BI6WL.cjs.map +0 -1
- package/dist/chunk-EN3CDYOS.cjs +0 -2
- package/dist/chunk-EN3CDYOS.cjs.map +0 -1
- package/dist/chunk-EQDT42JG.js +0 -3
- package/dist/chunk-EQDT42JG.js.map +0 -1
- package/dist/chunk-FMMT5C5H.cjs +0 -3
- package/dist/chunk-FMMT5C5H.cjs.map +0 -1
- package/dist/chunk-FP6Z6PYR.js +0 -2
- package/dist/chunk-FP6Z6PYR.js.map +0 -1
- package/dist/chunk-H3JXNH7X.cjs +0 -3
- package/dist/chunk-H3JXNH7X.cjs.map +0 -1
- package/dist/chunk-HZOLIL5T.js +0 -3
- package/dist/chunk-HZOLIL5T.js.map +0 -1
- package/dist/chunk-JVMINMAB.js +0 -2
- package/dist/chunk-JVMINMAB.js.map +0 -1
- package/dist/chunk-JYLNQOPU.cjs +0 -2
- package/dist/chunk-JYLNQOPU.cjs.map +0 -1
- package/dist/chunk-KRXO3MOW.cjs +0 -2
- package/dist/chunk-KRXO3MOW.cjs.map +0 -1
- package/dist/chunk-KVLJDOZ7.cjs +0 -5
- package/dist/chunk-KVLJDOZ7.cjs.map +0 -1
- package/dist/chunk-LNZNJSRW.cjs.map +0 -1
- package/dist/chunk-O3BDXOQJ.js +0 -2
- package/dist/chunk-O3BDXOQJ.js.map +0 -1
- package/dist/chunk-PIZQIQVM.js +0 -3
- package/dist/chunk-PIZQIQVM.js.map +0 -1
- package/dist/chunk-QTSDIDAS.js +0 -3
- package/dist/chunk-QTSDIDAS.js.map +0 -1
- package/dist/chunk-SGIDBZ4T.cjs +0 -2
- package/dist/chunk-SGIDBZ4T.cjs.map +0 -1
- package/dist/chunk-UNKSCVIL.cjs +0 -2
- package/dist/chunk-UNKSCVIL.cjs.map +0 -1
- package/dist/chunk-USQ4KL6S.cjs +0 -2
- package/dist/chunk-USQ4KL6S.cjs.map +0 -1
- package/dist/chunk-XDXIPVZB.cjs +0 -2
- package/dist/chunk-XDXIPVZB.cjs.map +0 -1
package/dist/chunk-4DJJIUQF.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {a}from'./chunk-AF7HQN6I.js';import {c}from'./chunk-IJMNVBIS.js';import {c as c$1}from'./chunk-PIZQIQVM.js';var N=32,U=2;function x(a){return a.shape!==void 0?a.shape:a.startTokenTypes!==void 0?[{types:a.startTokenTypes}]:[]}var I=class{constructor(e){this.rules=e;let r=e.length,t=Math.max(1,Math.ceil(r/N));this.words=t,this.scratch=new Uint32Array(t);let s=e.map(x),n=0;for(let l of s)for(let c$1 of l)for(let f of c$1.types??[])n=Math.max(n,c(f));this.typeRows=n+1;let i=0;for(let l of s)i=Math.max(i,l.length);i=Math.min(i,U),this.allRules=new Uint32Array(t);for(let l=0;l<r;l++)this.allRules[l/N|0]|=1<<l%N;let u=[];for(let l=0;l<i;l++)u.push(this.buildPlane(s,l,t));this.planes=u;}buildPlane(e,r,t){let s={byType:new Uint32Array(this.typeRows*t),typeAny:new Uint32Array(t),atEnd:new Uint32Array(t),typeHasValues:new Uint8Array(this.typeRows),byValue:new Map,valueAny:new Uint32Array(t)};for(let n=0;n<e.length;n++){let i=e[n][r],u=n/N|0,l=1<<n%N,c$1=i?.types;if(c$1===void 0)s.typeAny[u]|=l,s.atEnd[u]|=l;else for(let p of c$1)s.byType[c(p)*t+u]|=l;let f=i?.values;if(f===void 0)s.valueAny[u]|=l;else {for(let p of f){let h=p.toLowerCase(),o=s.byValue.get(h);o===void 0&&(o=new Uint32Array(t),s.byValue.set(h,o)),o[u]|=l;}if(c$1===void 0)s.typeHasValues.fill(1);else for(let p of c$1){let h=c(p);h<this.typeRows&&(s.typeHasValues[h]=1);}}}return s}get size(){return this.rules.length}get depth(){return this.planes.length}candidates(e,r){let t=this.words,s=this.scratch,n=this.planes,i=e.length;if(n.length===0)return s.set(this.allRules),s;for(let u=0;u<n.length;u++){let l=n[u],c=r+u;if(c>=i){if(u===0)s.set(l.atEnd);else for(let o=0;o<t;o++)s[o]&=l.atEnd[o];continue}let f=e[c],p=f.typeId,h=p>=0&&p<this.typeRows?p*t:-1;if(u===0)if(h>=0)for(let o=0;o<t;o++)s[o]=l.byType[h+o]|l.typeAny[o];else s.set(l.typeAny);else if(h>=0)for(let o=0;o<t;o++)s[o]&=l.byType[h+o]|l.typeAny[o];else for(let o=0;o<t;o++)s[o]&=l.typeAny[o];if(h>=0&&l.typeHasValues[p]===1){let o=f.value,R=B(o)?o.toLowerCase():o,g=l.byValue.get(R);for(let T=0;T<t;T++)s[T]&=(g===void 0?0:g[T])|l.valueAny[T];}if(C(s))return s}return s}};function C(a){for(let e=0;e<a.length;e++)if(a[e]!==0)return false;return true}function B(a){for(let e=0;e<a.length;e++){let r=a.charCodeAt(e);if(r>=65&&r<=90)return true}return false}var O={maxPasses:100,maxTokens:1e4,onFusion:()=>{},ignoreRuleIndex:false};function S(a$1,e,r){let t=r[0],s=r[r.length-1],n=new a(a$1,c(a$1),e,e,t.offset,t.lineBreaks??0,t.line,t.col);return n.sourceEnd=s.sourceEnd??s.offset+s.text.length,n}function M(a,e){let r=e[e.length-1];r&&(a.sourceEnd=r.sourceEnd??r.offset+r.text.length);}var _=["NUMBER","HEX","BIGINT","FLOAT","LSHIFT","RSHIFT","BIT_AND","BIT_OR","BIT_XOR","LPAREN","RPAREN","LBRACKET","RBRACKET","COMMA","COLON","EQUALS","THEREFORE","PIPE","AMPERSAND","AT","SEMICOLON","QUESTION","EXCLAMATION","EOF","WS","NEWLINE"],P=(()=>{let a=_.map(t=>c(t)),e=Math.max(...a)+1,r=new Uint8Array(e);for(let t of a)r[t]=1;return r})(),z=new Set;function D(a){a.shape!==void 0&&a.shape.length>0||a.startTokenTypes===void 0&&a.unshapedReason===void 0&&(z.has(a.name)||(z.add(a.name),console.warn(`[TokenNormalizer] Rule "${a.name}" declares no \`shape\`, so it is tried at every token of every line and slows down documents that never use it. Declare the tokens it can start at, e.g. shape: [{ types: ["IDENT"], values: ["myword"] }, { types: ["LPAREN"] }]. If it genuinely cannot be described that way, set \`unshapedReason\` to say why and this warning will stop.`)));}var L=class{constructor(e={}){this.rules=[];this.sortedRulesCache=null;this.rulesByTokenType=new Map;this.ruleIndexCache=null;this.candidateBuffer=[];this.normalizeCalls=0;this.phraseTrie=new E;this.ruleShapesCache=null;this.options={...O,...e};}register(e){D(e),this.rules.push(e),this.sortedRulesCache=null,this.rulesByTokenType.clear(),this.ruleIndexCache=null,this.ruleShapesCache=null;}unregister(e){this.rules=this.rules.filter(r=>r.name!==e),this.sortedRulesCache=null,this.rulesByTokenType.clear(),this.ruleIndexCache=null,this.ruleShapesCache=null;}clear(){this.rules=[],this.sortedRulesCache=null,this.rulesByTokenType.clear(),this.ruleIndexCache=null,this.ruleShapesCache=null,this.phraseTrie=new E;}getSortedRules(){return this.sortedRulesCache===null&&(this.sortedRulesCache=[...this.rules].sort((e,r)=>r.priority-e.priority)),this.sortedRulesCache}getRuleIndex(){return this.ruleIndexCache===null&&(this.ruleIndexCache=new I(this.getSortedRules())),this.ruleIndexCache}rulesAt(e,r){let t=this.candidateBuffer;if(t.length=0,e===null){let n=this.rulesForTokenType(r);for(let i=0;i<n.length;i++)t.push(n[i]);return t}let s=this.getRuleIndex().rules;for(let n=0;n<e.length;n++){let i=e[n]>>>0,u=n*32;for(;i!==0;)(i&1)!==0&&t.push(s[u]),i>>>=1,u++;}return t}rulesForTokenType(e){let r=this.rulesByTokenType.get(e);return r===void 0&&(r=this.getSortedRules().filter(t=>t.startTokenTypes===void 0||t.startTokenTypes.includes(e)),this.rulesByTokenType.set(e,r)),r}get ruleCount(){return this.rules.length}getRuleShapes(){if(this.ruleShapesCache!==null)return this.ruleShapesCache;let e=this.getRuleIndex();return this.ruleShapesCache=this.getSortedRules().map(r=>{let t=x(r);return {name:r.name,priority:r.priority,shape:t,unshapedReason:r.unshapedReason,indexedSlots:Math.min(t.length,e.depth)}}),this.ruleShapesCache}getCandidateCounts(e){let r=this.getRuleIndex(),t=[];for(let s=0;s<e.length;s++){let n=r.candidates(e,s),i=0;for(let u=0;u<n.length;u++){let l=n[u]>>>0;for(;l!==0;)i+=l&1,l>>>=1;}t.push(i);}return t}addPhrase(e,r){this.phraseTrie.addPhrase(e,r);}getPhrases(){return this.phraseTrie.getAllPhrases()}canStartPhrase(e){return this.phraseTrie.canStart(e)}normalize(e,r){if(e.length===0)return e;let t=r??this.options.onFusion,s=this.options.maxPasses,n=this.options.maxTokens,i=this.normalizeCalls>0;i||(this.normalizeCalls=1);let u=i&&!this.options.ignoreRuleIndex,l=u?this.getRuleIndex():null,c=e,f=true,p=0;for(;f&&p<s;){f=false,p++;let h=null,o=0;for(;o<c.length;){let g=false,T=c[o].typeId;if(T>=P.length||P[T]===0){let m=this.phraseTrie.matchAt(c,o);if(m){let d=c.slice(o,o+m.consumed);h===null&&(h=c.slice(0,o));for(let A of m.replacement)h.push(A);m.consumed>1&&m.replacement.length===1&&(M(m.replacement[0],d),t({rule:m.ruleName??"phrase-trie",sourceTokens:d,fusedToken:m.replacement[0]})),o+=m.consumed,f=true;continue}}let b=u?l.candidates(c,o):null;if(b!==null&&C(b)){h!==null&&h.push(c[o]),o++;continue}for(let m of this.rulesAt(b,c[o].type)){let d=m.match(c,o);if(d){let A=c.slice(o,o+d.consumed);h===null&&(h=c.slice(0,o));for(let v of d.replacement)h.push(v);if(d.consumed>1&&d.replacement.length===1)M(d.replacement[0],A),t({rule:m.name,sourceTokens:A,fusedToken:d.replacement[0]});else if(d.consumed>1&&d.replacement.length<d.consumed)for(let v of d.replacement)t({rule:m.name,sourceTokens:A,fusedToken:v});o+=d.consumed,f=true,g=true;break}}g||(h!==null&&h.push(c[o]),o++);}if(h===null)break;let R=h;if(R.length>n)throw c$1.validation("NORMALIZED_TOKEN_LIMIT_EXCEEDED",`Normalized token count (${R.length}) exceeds safety limit (${n})`,{tokenCount:R.length,maxTokens:n});c=R;}return c}};var E=class{constructor(){this.startWords=new Set;this.root=new Map;}addPhrase(e,r){let t=e.toLowerCase().trim().split(/\s+/);if(t.length===0||t[0]==="")return;this.startWords.add(t[0]);let s=t[0],n;if(this.root.has(s)?n=this.root.get(s):(n={children:new Map,terminal:null},this.root.set(s,n)),t.length===1){n.terminal={tokenType:r,phrase:e,consumed:1};return}for(let i=1;i<t.length;i++){let u=t[i];n.children.has(u)||n.children.set(u,{children:new Map,terminal:null}),n=n.children.get(u);}n.terminal={tokenType:r,phrase:e,consumed:t.length};}matchAt(e,r){if(r>=e.length)return null;let t=e[r].type;if(t==="TAG"||t.startsWith("TAG_"))return null;let s=e[r].value.toLowerCase();if(!this.startWords.has(s))return null;let n=this.root.get(s);if(!n)return null;let i=null,u=1;if(n.terminal){let l=e.slice(r,r+1);i={consumed:1,replacement:[S(n.terminal.tokenType,n.terminal.phrase,l)],ruleName:n.terminal.phrase};}for(let l=r+1;l<e.length&&n?.children;l++){let c=e[l].type;if(c==="TAG"||c.startsWith("TAG_"))break;let f=e[l].value.toLowerCase();if(n=n.children.get(f),!n)break;if(u++,n.terminal){let p=e.slice(r,r+u);i={consumed:u,replacement:[S(n.terminal.tokenType,n.terminal.phrase,p)],ruleName:n.terminal.phrase};}}return i}get size(){return this.root.size}getAllPhrases(){let e={},r=(t,s)=>{t.terminal&&(e[s.join(" ")]=t.terminal.tokenType);for(let[n,i]of t.children)r(i,[...s,n]);};for(let[t,s]of this.root)r(s,[t]);return e}canStart(e){return this.startWords.has(e.toLowerCase())}};var F=new Set(["per","a","an","each","every"]),W=new Set(["to","power","increase","decrease","times","multiply","divide","by"]);function V(a$1=50,e){let r=e??(t=>W.has(t.toLowerCase()));return {name:"implicit:multiply",priority:a$1,shape:[{types:["NUMBER","RPAREN"]},{types:["IDENT","LPAREN","PI","E"]}],match(t,s){if(s+1>=t.length)return null;let n=t[s],i=t[s+1];if(!((n.type==="NUMBER"||n.type==="RPAREN")&&(i.type==="IDENT"||i.type==="LPAREN"||i.type==="PI"||i.type==="E")))return null;let l=i.value.toLowerCase();if(r(l)||F.has(l)&&t[s+2]?.type==="UNIT")return null;let c$1=new a("STAR",c("STAR"),"*","*",i.offset,0,i.line,i.col);return {consumed:1,replacement:[n,c$1]}}}}function te(a,e){let r=[];for(let t=0;t<e;t++){let s=a[t];if(s.type==="LBRACKET")r.push(true);else if(s.type==="LPAREN"){let n=a[t-1],i=!!n&&(n.type==="MAP"||n.type==="REDUCE"||n.type==="SUM_FN"||n.type==="PROD_FN"||n.type==="IDENT"&&(n.value.toLowerCase()==="map"||n.value.toLowerCase()==="reduce"||n.value.toLowerCase()==="sum"||n.value.toLowerCase()==="prod"));r.push(i);}else (s.type==="RBRACKET"||s.type==="RPAREN")&&r.pop();}return r.length>0&&r[r.length-1]}function ne(){return [V()]}var re={"to the power of":"CARET","power of":"CARET","increase by":"INCREASE_BY","decrease by":"DECREASE_BY","times by":"TIMES_BY","multiply by":"MULTIPLY_BY","divide by":"DIVIDE_BY","multiplied by":"MULTIPLY_BY","divided by":"DIVIDE_BY"};export{E as a,S as b,L as c,V as d,te as e,ne as f,re as g};//# sourceMappingURL=chunk-4DJJIUQF.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-4DJJIUQF.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/normalizer/RuleIndex.ts","../src/normalizer/TokenNormalizer.ts","../src/normalizer/PhraseTrie.ts","../src/normalizer/BuiltinNormalizerRules.ts"],"names":["WORD_BITS","MAX_PLANES","effectiveShape","rule","RuleIndex","sortedRules","n","w","shapes","maxTypeId","shape","slot","t","tokenTypeId","depth","i","planes","k","plane","word","bit","types","values","raw","value","mask","id","tokens","pos","scratch","len","at","token","typeId","base","lowered","hasUpper","named","isEmptyMask","c","DEFAULT_OPTIONS","createFusedToken","type","text","sourceTokens","first","last","LexerToken","recordSourceSpan","fused","NON_WORD_NAMES","NON_WORD_TABLE","ids","table","warnedUnshapedRules","warnIfUnshaped","TokenNormalizer","options","PhraseTrie","ruleName","a","b","buffer","list","rules","bits","index","counts","phrase","tokenType","onFusion","fusionHandler","maxPasses","maxTokens","warmedUp","useIndex","ruleIndex","current","changed","passCount","result","matched","tid","trieMatch","rt","candidates","match","passResult","ErrorFactory","words","firstWord","node","startType","best","contType","collect","path","child","RATE_DENOMINATOR_WORDS","PHRASE_START_WORDS","implicitMultiplyRule","priority","canStart","phraseGuard","next","nextValue","starToken","isInsideRangeContext","safeStack","prev","opensMapReduceCall","createBuiltinNormalizerRules","BUILTIN_PHRASES"],"mappings":"mHAiEA,IAAMA,CAAAA,CAAY,EAAA,CAeZC,CAAAA,C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G,CAAAA,CAAOlF,CAAAA,CAAOZ,CAAAA,CAAI,CAAC,CAAA,CACnB+F,CAAAA,CAAqB,CAAC,CAACD,IAC3BA,CAAAA,CAAK,IAAA,GAAS,KAAA,EAASA,CAAAA,CAAK,IAAA,GAAS,QAAA,EAAYA,CAAAA,CAAK,IAAA,GAAS,UAAYA,CAAAA,CAAK,IAAA,GAAS,SAAA,EACxFA,CAAAA,CAAK,IAAA,GAAS,OAAA,GAAYA,CAAAA,CAAK,KAAA,CAAM,aAAY,GAAM,KAAA,EAASA,CAAAA,CAAK,KAAA,CAAM,WAAA,EAAY,GAAM,QAAA,EAAYA,CAAAA,CAAK,KAAA,CAAM,WAAA,EAAY,GAAM,KAAA,EAASA,CAAAA,CAAK,KAAA,CAAM,WAAA,EAAY,GAAM,SAE/KD,CAAAA,CAAU,IAAA,CAAKE,CAAkB,EACnC,CAAA,KAAA,CAAWlG,CAAAA,CAAE,IAAA,GAAS,UAAA,EAAcA,EAAE,IAAA,GAAS,QAAA,GAC7CgG,CAAAA,CAAU,GAAA,GAEd,CACA,OAAOA,CAAAA,CAAU,OAAS,CAAA,EAAKA,CAAAA,CAAUA,CAAAA,CAAU,MAAA,CAAS,CAAC,CAC/D,CAoBO,SAASG,IAAiD,CAC/D,OAAO,CAELX,CAAAA,EACF,CACF,CASO,IAAMY,GAA0C,CACtD,iBAAA,CAAmB,OAAA,CACnB,UAAA,CAAY,OAAA,CACZ,aAAA,CAAe,aAAA,CACf,aAAA,CAAe,cACf,UAAA,CAAY,UAAA,CACZ,aAAA,CAAe,aAAA,CACf,WAAA,CAAa,WAAA,CAKb,eAAA,CAAiB,aAAA,CACjB,aAAc,WACf","file":"chunk-4DJJIUQF.js","sourcesContent":["//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * RuleIndex, a conjunctive bitmask prefilter over the normalizer's rules.\n *\n * ## Problem\n * The normalizer tries every rule eligible at a position, at every position.\n * The `startTokenTypes` hint buckets rules by the type of the token they start\n * at, which helps only where that type is selective. It is not: the thirteen\n * call-fusion rules all declare `[\"IDENT\"]`, the commonest token in prose, and\n * the rules firing on a bare `NUMBER` all share that one type too. Measured\n * against the built-in package set, the `IDENT` bucket held 53 of 57 rules and\n * the `NUMBER` bucket 45, because a rule declaring no hint has to be tried\n * everywhere.\n *\n * ## Solution\n * Rules discriminate on different things, so no single axis separates them.\n * A rule declares its leading {@link RuleSlot} shape, and this builds one\n * lookup plane per slot: a flat `Uint32Array` of rule bitmasks indexed by token\n * type id, so a lookup is an array load rather than a hash. A position ANDs the\n * planes together and iterates only the surviving bits, which for most\n * positions is none at all.\n *\n * Rejecting a position therefore costs a few loads and ANDs instead of\n * forty-odd closure calls, and one AND tests 32 rules at once. That the common\n * answer is \"no rule can fire here\" is the point.\n *\n * ## Why planes rather than a fingerprint\n * A superimposed code (OR the hashed types of a window into one word, AND\n * against a per-rule required fingerprint) looks like the cheaper way to reach\n * depth, but it is a per-RULE test with no way to invert it into a lookup, so\n * it stays O(rules) per position. These planes are the same conjunctive test\n * done exactly, at O(rules / 32) and with no false positives. Token types\n * number a couple of hundred, small enough to table, so there is nothing to\n * gain by approximating.\n *\n * ## Ordering\n * Bit `i` is the rule at index `i` of the priority-sorted rule list, so\n * iterating bits from low to high visits rules in exactly the order the\n * unindexed scan did. Ties keep registration order, because the sort is stable.\n * This is what makes the index a pure filter rather than a behaviour change,\n * and `NormalizerIndexFidelity.spec` pins it.\n *\n * ## Safety\n * The contract runs one way: a slot admitting MORE than the rule can match\n * costs a `match()` that returns null, which is what happens today; a slot\n * admitting LESS makes the rule unreachable, a silent bug. So indexing fewer\n * planes than were declared is always safe, which is why {@link MAX_PLANES}\n * can be tuned on evidence rather than being a correctness decision. Only\n * over-narrow declarations are dangerous, and those are what the fidelity spec\n * hunts for.\n *\n * @module RuleIndex\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { NormalizerRule, RuleSlot } from \"./NormalizerRule\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\n\n//#endregion\n//#region ─── Constants ────────────────────────────────────────────────────────\n\n/** Bits per word in the masks below. */\nconst WORD_BITS = 32;\n\n/**\n * How many leading slots are indexed, however many a rule declares.\n *\n * Each plane costs a load and an AND at every position, unconditionally, while\n * only positions surviving the earlier planes can benefit from a later one.\n * After two planes most positions have no candidates left, so a third would tax\n * every token to save a couple of `match()` calls on the few that reach it.\n *\n * Two is a measured default, not a limit of the design: raising it is a\n * one-line change, and lowering it can never break a rule (see this module's\n * Safety note). Rules may declare deeper shapes freely; the extra slots simply\n * go unindexed and are checked by `match()` as before.\n */\nconst MAX_PLANES = 2;\n\n//#endregion\n//#region ─── Shape normalisation ──────────────────────────────────────────────\n\n/**\n * A rule's effective shape, folding the older {@link NormalizerRule.startTokenTypes}\n * into the general form. `shape` wins when both are present.\n */\nexport function effectiveShape(rule: NormalizerRule): readonly RuleSlot[] {\n\tif (rule.shape !== undefined) return rule.shape;\n\tif (rule.startTokenTypes !== undefined) return [{ types: rule.startTokenTypes }];\n\treturn [];\n}\n\n//#endregion\n//#region ─── RuleIndex ────────────────────────────────────────────────────────\n\n/** One indexed slot position: the type plane, plus the value axis for it. */\ninterface Plane {\n\t/** `[typeId * words + w]`, rules whose slot admits `typeId`. */\n\treadonly byType: Uint32Array;\n\t/** Rules constraining no type here, admitted at a type with no row. */\n\treadonly typeAny: Uint32Array;\n\t/**\n\t * Rules constraining no type here, and so the only ones still admissible\n\t * when the stream ends before this slot.\n\t */\n\treadonly atEnd: Uint32Array;\n\t/** `[typeId]`, 1 when a value-constraining rule admits this type here. */\n\treadonly typeHasValues: Uint8Array;\n\t/** Lower-cased word to the rules naming it at this slot. */\n\treadonly byValue: Map<string, Uint32Array>;\n\t/** Rules constraining no value here. */\n\treadonly valueAny: Uint32Array;\n}\n\n/**\n * A conjunctive bitmask prefilter over a priority-sorted rule list.\n *\n * Built once per rule-set mutation (registration time), then read only. See\n * this module's overview for the shape and the ordering guarantee.\n */\nexport class RuleIndex {\n\t/** The priority-sorted rules. Bit `i` of every mask refers to `rules[i]`. */\n\treadonly rules: readonly NormalizerRule[];\n\n\t/** Words per mask, `ceil(rules.length / 32)`. */\n\treadonly words: number;\n\n\t/** Number of token type ids with their own row, exclusive upper bound. */\n\tprivate readonly typeRows: number;\n\n\t/** One per indexed slot, at most {@link MAX_PLANES}. */\n\tprivate readonly planes: readonly Plane[];\n\n\t/** Reused across positions so the hot path allocates nothing. */\n\tprivate readonly scratch: Uint32Array;\n\n\t/**\n\t * Every rule's bit set.\n\t *\n\t * Returned when there are no planes at all, which happens when no rule\n\t * declares a shape. Without it {@link candidates} would hand back an\n\t * unwritten scratch buffer, i.e. \"no rule can fire anywhere\", and every\n\t * rule would silently stop running. The all-admitted answer is the correct\n\t * one: a rule that constrains nothing can match anywhere.\n\t */\n\tprivate readonly allRules: Uint32Array;\n\n\tconstructor(sortedRules: readonly NormalizerRule[]) {\n\t\tthis.rules = sortedRules;\n\t\tconst n = sortedRules.length;\n\t\tconst w = Math.max(1, Math.ceil(n / WORD_BITS));\n\t\tthis.words = w;\n\t\tthis.scratch = new Uint32Array(w);\n\n\t\tconst shapes = sortedRules.map(effectiveShape);\n\n\t\t// Size the type-indexed rows to cover every type any rule names. A token\n\t\t// whose id lands past this (a plugin type minted after the index was\n\t\t// built, say) falls back to the \"constrains nothing\" masks, which is\n\t\t// correct rather than merely safe: a rule naming types cannot match a\n\t\t// type it did not name, and a rule naming none can match anywhere.\n\t\tlet maxTypeId = 0;\n\t\tfor (const shape of shapes) {\n\t\t\tfor (const slot of shape) {\n\t\t\t\tfor (const t of slot.types ?? []) maxTypeId = Math.max(maxTypeId, tokenTypeId(t));\n\t\t\t}\n\t\t}\n\t\tthis.typeRows = maxTypeId + 1;\n\n\t\tlet depth = 0;\n\t\tfor (const shape of shapes) depth = Math.max(depth, shape.length);\n\t\tdepth = Math.min(depth, MAX_PLANES);\n\n\t\tthis.allRules = new Uint32Array(w);\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\tthis.allRules[(i / WORD_BITS) | 0] |= 1 << (i % WORD_BITS);\n\t\t}\n\n\t\tconst planes: Plane[] = [];\n\t\tfor (let k = 0; k < depth; k++) {\n\t\t\tplanes.push(this.buildPlane(shapes, k, w));\n\t\t}\n\t\tthis.planes = planes;\n\t}\n\n\t/** Build the lookup plane for slot `k`. */\n\tprivate buildPlane(shapes: readonly (readonly RuleSlot[])[], k: number, w: number): Plane {\n\t\tconst plane: Plane = {\n\t\t\tbyType: new Uint32Array(this.typeRows * w),\n\t\t\ttypeAny: new Uint32Array(w),\n\t\t\tatEnd: new Uint32Array(w),\n\t\t\ttypeHasValues: new Uint8Array(this.typeRows),\n\t\t\tbyValue: new Map<string, Uint32Array>(),\n\t\t\tvalueAny: new Uint32Array(w),\n\t\t};\n\n\t\tfor (let i = 0; i < shapes.length; i++) {\n\t\t\tconst slot: RuleSlot | undefined = shapes[i][k];\n\t\t\tconst word = (i / WORD_BITS) | 0;\n\t\t\tconst bit = 1 << (i % WORD_BITS);\n\n\t\t\t// ── Types ──\n\t\t\tconst types = slot?.types;\n\t\t\tif (types === undefined) {\n\t\t\t\t// Constrains nothing here, so admitted at every type, at a type\n\t\t\t\t// with no row, and past the end of the stream.\n\t\t\t\t//\n\t\t\t\t// Deliberately NOT written into every row of `byType`. Doing that\n\t\t\t\t// made construction O(rules x tokenTypes), tens of thousands of\n\t\t\t\t// writes for a table most of which is the same bit, and the\n\t\t\t\t// engine builds an index per instance: a cold parse of a short\n\t\t\t\t// document paid for it without ever amortising it. The lookup\n\t\t\t\t// ORs `typeAny` in instead, which is one extra operation per word\n\t\t\t\t// on a path that already does several.\n\t\t\t\tplane.typeAny[word] |= bit;\n\t\t\t\tplane.atEnd[word] |= bit;\n\t\t\t} else {\n\t\t\t\tfor (const t of types) plane.byType[tokenTypeId(t) * w + word] |= bit;\n\t\t\t}\n\n\t\t\t// ── Values ──\n\t\t\tconst values = slot?.values;\n\t\t\tif (values === undefined) {\n\t\t\t\tplane.valueAny[word] |= bit;\n\t\t\t} else {\n\t\t\t\tfor (const raw of values) {\n\t\t\t\t\tconst value = raw.toLowerCase();\n\t\t\t\t\tlet mask = plane.byValue.get(value);\n\t\t\t\t\tif (mask === undefined) {\n\t\t\t\t\t\tmask = new Uint32Array(w);\n\t\t\t\t\t\tplane.byValue.set(value, mask);\n\t\t\t\t\t}\n\t\t\t\t\tmask[word] |= bit;\n\t\t\t\t}\n\t\t\t\t// The value axis is only worth a map lookup at a type some\n\t\t\t\t// value-constraining rule admits here.\n\t\t\t\tif (types === undefined) {\n\t\t\t\t\tplane.typeHasValues.fill(1);\n\t\t\t\t} else {\n\t\t\t\t\tfor (const t of types) {\n\t\t\t\t\t\tconst id = tokenTypeId(t);\n\t\t\t\t\t\tif (id < this.typeRows) plane.typeHasValues[id] = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn plane;\n\t}\n\n\t/** Number of indexed rules. */\n\tget size(): number { return this.rules.length; }\n\n\t/** How many slot positions are indexed. */\n\tget depth(): number { return this.planes.length; }\n\n\t/**\n\t * The candidate mask for a position, written into a reused scratch buffer\n\t * and returned. Bits are rule indices, ascending bit order being descending\n\t * priority. The buffer is overwritten by the next call, so read it before\n\t * calling again.\n\t *\n\t * @param tokens - The stream being walked\n\t * @param pos - The position to test\n\t */\n\tcandidates(tokens: readonly { typeId: number; value: string }[], pos: number): Uint32Array {\n\t\tconst w = this.words;\n\t\tconst scratch = this.scratch;\n\t\tconst planes = this.planes;\n\t\tconst len = tokens.length;\n\n\t\tif (planes.length === 0) {\n\t\t\tscratch.set(this.allRules);\n\t\t\treturn scratch;\n\t\t}\n\n\t\tfor (let k = 0; k < planes.length; k++) {\n\t\t\tconst plane = planes[k];\n\t\t\tconst at = pos + k;\n\n\t\t\tif (at >= len) {\n\t\t\t\t// The stream ends before this slot, so only rules that constrain\n\t\t\t\t// nothing here remain admissible.\n\t\t\t\tif (k === 0) { scratch.set(plane.atEnd); }\n\t\t\t\telse { for (let i = 0; i < w; i++) scratch[i] &= plane.atEnd[i]; }\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst token = tokens[at];\n\t\t\tconst typeId = token.typeId;\n\t\t\tconst base = typeId >= 0 && typeId < this.typeRows ? typeId * w : -1;\n\n\t\t\t// `typeAny` holds the rules that constrain no type at this slot, so\n\t\t\t// they are admitted whatever the token is; see the construction note.\n\t\t\tif (k === 0) {\n\t\t\t\tif (base >= 0) { for (let i = 0; i < w; i++) scratch[i] = plane.byType[base + i] | plane.typeAny[i]; }\n\t\t\t\telse { scratch.set(plane.typeAny); }\n\t\t\t} else {\n\t\t\t\tif (base >= 0) { for (let i = 0; i < w; i++) scratch[i] &= plane.byType[base + i] | plane.typeAny[i]; }\n\t\t\t\telse { for (let i = 0; i < w; i++) scratch[i] &= plane.typeAny[i]; }\n\t\t\t}\n\n\t\t\t// The value axis costs a map lookup and possibly a lower-casing, so\n\t\t\t// it is consulted only at a type some value-constraining rule names.\n\t\t\tif (base >= 0 && plane.typeHasValues[typeId] === 1) {\n\t\t\t\tconst value = token.value;\n\t\t\t\tconst lowered = hasUpper(value) ? value.toLowerCase() : value;\n\t\t\t\tconst named = plane.byValue.get(lowered);\n\t\t\t\tfor (let i = 0; i < w; i++) {\n\t\t\t\t\tscratch[i] &= (named === undefined ? 0 : named[i]) | plane.valueAny[i];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (isEmptyMask(scratch)) return scratch;\n\t\t}\n\n\t\treturn scratch;\n\t}\n}\n\n/** Whether every bit of a mask returned by {@link RuleIndex.candidates} is clear. */\nexport function isEmptyMask(mask: Uint32Array): boolean {\n\tfor (let i = 0; i < mask.length; i++) if (mask[i] !== 0) return false;\n\treturn true;\n}\n\n/**\n * Whether a string contains an ASCII upper-case letter.\n *\n * `toLowerCase()` allocates even when it changes nothing, and identifiers in\n * running prose are overwhelmingly already lower case, so this scan pays for\n * itself by skipping the allocation in the common case.\n */\nfunction hasUpper(value: string): boolean {\n\tfor (let i = 0; i < value.length; i++) {\n\t\tconst c = value.charCodeAt(i);\n\t\tif (c >= 65 && c <= 90) return true;\n\t}\n\treturn false;\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * TokenNormalizer, post-lexer token normalization pass.\n *\n * ## Purpose\n * Applies domain-specific {@link NormalizerRule | NormalizerRules} to the raw\n * token stream produced by the {@link ExpressionLexer}. This keeps the lexer\n * slim and focused on single-token production, while multi-token pattern\n * matching (phrases, implicit operators, domain merges) lives here.\n *\n * ## What rules can do\n * - **Phrase fusion**: Merge consecutive words into compound tokens\n * (e.g., `IDENT + ... + IDENT` → `CARET`)\n * - **Implicit operator insertion**: Insert missing operators between tokens\n * (e.g., `NUMBER IDENT` → `NUMBER STAR IDENT`)\n * - **Domain-specific transformations**: Coalesce item names, currency pairs,\n * percentage syntax, etc.\n *\n * ## Architecture\n * Providers register NormalizerRules alongside Parselets and OpCode handlers\n * via {@link IEnginePackage.normalizerRules}. The normalizer applies them\n * greedily left-to-right in multiple passes with safety limits.\n *\n * @module TokenNormalizer\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, RuleSlot, TokenFusion } from \"./NormalizerRule\";\nimport { PhraseTrie } from \"./PhraseTrie\";\nimport { RuleIndex, isEmptyMask, effectiveShape } from \"./RuleIndex\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n//#endregion\n//#region ─── NormalizerOptions, Configuration ────────────────────────────────\n\n/**\n * Configuration options for the normalization pass.\n *\n * These control safety limits and diagnostic callbacks. The defaults\n * are chosen to be generous enough for any realistic expression while\n * preventing runaway token expansion from recursive rules.\n */\nexport interface NormalizerOptions {\n /**\n * Maximum number of full passes over the token stream before bailing out.\n * Prevents infinite loops from recursive rule chains.\n * @default 100\n */\n maxPasses?: number;\n\n /**\n * Maximum number of tokens allowed after normalization.\n * If exceeded, an Error is thrown rather than passing a bloated stream\n * to the parser.\n * @default 10000\n */\n maxTokens?: number;\n\n /**\n * Callback invoked for each fusion event during normalization.\n * Used by diagnostic mode to populate {@link NormalizerOutput.fusions}.\n * When `undefined`, fusions are still tracked internally but no callbacks fire.\n */\n onFusion?: (fusion: TokenFusion) => void;\n\n /**\n * Try every registered rule at every position, ignoring the shape index.\n *\n * Diagnostic only, and much slower. It exists so the indexed walk can be\n * compared against the unindexed one over a corpus: the index is a pure\n * filter, so the two must agree token for token, and a rule whose declared\n * {@link NormalizerRule.shape} is too narrow shows up as a difference rather\n * than as a feature that quietly stopped working.\n * `NormalizerIndexFidelity.spec` is the consumer.\n *\n * @default false\n */\n ignoreRuleIndex?: boolean;\n}\n\n//#endregion\n//#region ─── Default Options ──────────────────────────────────────────────────\n\n/** Sensible defaults that catch infinite loops without limiting real expressions. */\nconst DEFAULT_OPTIONS: Required<NormalizerOptions> = {\n maxPasses: 100,\n maxTokens: 10000,\n onFusion: () => {},\n ignoreRuleIndex: false,\n};\n\n//#endregion\n//#region ─── createFusedToken, Token Factory ──────────────────────────────────\n\n/**\n * Creates a new normalized token from fused source tokens.\n *\n * The fused token inherits position information (offset, line, column)\n * from the first source token, which preserves source-map accuracy\n * for error messages and diagnostic highlighting.\n *\n * It also records where the source text ENDS, on `sourceEnd`. The start alone\n * is not enough to describe the span a fusion covers, because `text` is the\n * replacement rather than the original: `10 frames` fuses into a FRAME_COUNT\n * whose text is `10`, and a timecode fuses into a token whose text is a\n * comma-separated tuple that appears nowhere in the line. Anything painting the\n * line needs both ends, and only this function is in a position to know them.\n *\n * @param type - The new token type (e.g., \"CARET\", \"TIMES_BY\")\n * @param text - The combined text representation (e.g., \"to the power of\")\n * @param sourceTokens - The original tokens being fused (at least 2)\n * @returns A new {@link LexerToken} with the fused type and combined text\n */\nexport function createFusedToken(\n type: string,\n text: string,\n sourceTokens: Token[]\n): Token {\n const first = sourceTokens[0];\n const last = sourceTokens[sourceTokens.length - 1];\n const token = new LexerToken(\n type,\n tokenTypeId(type),\n text,\n text,\n first.offset,\n first.lineBreaks ?? 0,\n first.line,\n first.col,\n );\n // `text`, not `value`: this is where the SOURCE ended, and the two differ\n // for a string literal, whose value is the payload without its quotes.\n token.sourceEnd = last.sourceEnd ?? last.offset + last.text.length;\n return token;\n}\n\n/**\n * Record, on a token that replaced several, where its source text ended.\n *\n * Called centrally rather than left to each rule. A rule that builds its\n * replacement by hand rather than through {@link createFusedToken} is doing\n * nothing wrong, and several do: the date-literal rule needs a token whose\n * value is an epoch and whose text is the source, which that factory cannot\n * express. Stamping here means every fusion carries its span, including ones\n * written after this was.\n *\n * Reads `sourceEnd` off the last source token when it has one, so a fusion of\n * a fusion still describes the original text rather than the intermediate.\n *\n * @param fused - The single token the rule produced.\n * @param sourceTokens - The tokens it consumed.\n */\nfunction recordSourceSpan(fused: Token, sourceTokens: Token[]): void {\n const last = sourceTokens[sourceTokens.length - 1];\n if (!last) return;\n fused.sourceEnd = last.sourceEnd ?? last.offset + last.text.length;\n}\n\n//#endregion\n//#region ─── NON_WORD_TOKEN_TYPES, Type-guard skip set ────────────────────────\n\n/**\n * Token types that can NEVER start a multi-word phrase.\n *\n * Used by {@link normalize} to skip the PhraseTrie walk entirely at\n * positions where the token type makes phrase matching impossible.\n * This avoids even the O(1) {@link PhraseTrie.canStart} check.\n *\n * Types NOT in this set (IDENT, KEYWORD, FUNC, UNIT, and any custom\n * types registered by packages) still pass through to the trie for\n * a full match attempt.\n */\n// ── Non-word type ID lookup table (flat Uint8Array, true O(1) array index) ──\n//\n// Index = token typeId, value = 1 if non-word (skip trie), 0 otherwise.\n// Array indexing avoids ALL hashing: no Set.has(), no Map.get(), no string ops.\n//\n// Custom types from packages get IDs beyond the table length, so the bounds\n// check `tid < TABLE.length` safely passes them through to the trie.\n//\n// Arithmetic operators (PLUS, MINUS, STAR, SLASH, CARET, MOD, PERCENT) are\n// intentionally excluded: in keyword locales the lexer maps \"times\"→STAR,\n// \"divide\"→SLASH etc., and those tokens CAN start phrases like \"times by\".\n/**\n * Token type names that can NEVER start a multi-word phrase.\n *\n * Exported for testing only, consumers should use the type-guard behavior\n * of {@link TokenNormalizer.normalize} rather than this list directly.\n */\nexport const NON_WORD_NAMES = [\n\t\"NUMBER\", \"HEX\", \"BIGINT\", \"FLOAT\",\n\t\"LSHIFT\", \"RSHIFT\", \"BIT_AND\", \"BIT_OR\", \"BIT_XOR\",\n\t\"LPAREN\", \"RPAREN\", \"LBRACKET\", \"RBRACKET\",\n\t\"COMMA\", \"COLON\", \"EQUALS\", \"THEREFORE\", \"PIPE\", \"AMPERSAND\", \"AT\",\n\t\"SEMICOLON\", \"QUESTION\", \"EXCLAMATION\",\n\t\"EOF\", \"WS\", \"NEWLINE\",\n] as const;\n\n/**\n * Flat Uint8Array lookup table: index = token typeId, value = 1 if non-word.\n *\n * Exported for testing only, consumers should not depend on the internal\n * table layout, as the set of non-word types may change.\n */\nexport const NON_WORD_TABLE: Uint8Array = (() => {\n\t// Resolve all non-word type names to their numeric IDs\n\tconst ids = NON_WORD_NAMES.map(n => tokenTypeId(n));\n\t// Size the table to cover the largest ID + 1\n\tconst len = Math.max(...ids) + 1;\n\tconst table = new Uint8Array(len);\n\t// Mark non-word type positions\n\tfor (const id of ids) table[id] = 1;\n\treturn table;\n})();\n\n//#endregion\n//#region ─── TokenNormalizer Class ─────────────────────────────────────────────\n\n/**\n * Rule names already warned about, so a rule registered into many engines\n * says it once rather than once per engine.\n */\nconst warnedUnshapedRules = new Set<string>();\n\n/**\n * Warn when a rule declares neither a shape nor a reason for not having one.\n *\n * An unshaped rule is tried at every position of every line, so its cost is\n * paid by every document rather than only by the feature it implements. The\n * warning names the rule and points at the two ways out, and it fires once per\n * rule name per process: a warning a package author sees on every engine they\n * construct is one they learn to filter out, which would make it worse than\n * useless.\n *\n * Deliberately not an error. A rule without a shape is correct, only slower,\n * and refusing to register it would break every package written before the\n * field existed.\n */\nfunction warnIfUnshaped(rule: NormalizerRule): void {\n if (rule.shape !== undefined && rule.shape.length > 0) return;\n if (rule.startTokenTypes !== undefined) return;\n if (rule.unshapedReason !== undefined) return;\n if (warnedUnshapedRules.has(rule.name)) return;\n warnedUnshapedRules.add(rule.name);\n console.warn(\n `[TokenNormalizer] Rule \"${rule.name}\" declares no \\`shape\\`, so it is tried at every ` +\n `token of every line and slows down documents that never use it. Declare the tokens it ` +\n `can start at, e.g. shape: [{ types: [\"IDENT\"], values: [\"myword\"] }, { types: [\"LPAREN\"] }]. ` +\n `If it genuinely cannot be described that way, set \\`unshapedReason\\` to say why and this ` +\n `warning will stop.`,\n );\n}\n\n/**\n * Token normalizer: applies {@link NormalizerRule | NormalizerRules} to a token stream.\n *\n * ## Lifecycle\n * 1. **Registration**: Rules are added via {@link register} and sorted by priority\n * 2. **Normalization**: {@link normalize} applies rules greedily left-to-right\n * 3. **Cleanup**: {@link clear} or {@link unregister} removes rules\n *\n * ## Normalization algorithm\n * The normalizer uses a greedy left-to-right multi-pass algorithm:\n * - At each token position, rules are tried in priority order (highest first)\n * - When a rule matches, matched tokens are consumed and replaced\n * - Processing continues from the replacement position\n * - Multiple passes handle cascading matches (one rule's output triggers another)\n * - Safety limits ({@link NormalizerOptions.maxPasses}) prevent infinite loops\n *\n * @example\n * ```ts\n * const normalizer = new TokenNormalizer();\n * normalizer.register(phraseRule); // \"to the power of\" → CARET\n * normalizer.register(implicitMultRule); // \"2 x\" → \"2 * x\"\n * const normalized = normalizer.normalize(rawTokens);\n * ```\n */\nexport class TokenNormalizer {\n /** Registered rules, unsorted, the source of truth. */\n private rules: NormalizerRule[] = [];\n\n /**\n * Priority-sorted copy of {@link rules}, rebuilt lazily on the next\n * {@link normalize} call after a mutation. Rules are registered once at\n * engine/package-registration time and essentially never change during a\n * session, but normalize() runs on every keystroke-driven evaluation, an\n * earlier version re-sorted a fresh copy of `rules` on every single call,\n * which meant every keystroke paid for an allocation + sort of a list that\n * had usually not changed since the last one. `null` means \"stale, rebuild\n * on next use\"; {@link register}/{@link unregister}/{@link clear} all\n * invalidate it.\n */\n private sortedRulesCache: NormalizerRule[] | null = null;\n\n /**\n * Per-token-type view of the priority-sorted rules: for a token type, the\n * rules that could match a token of that type (those with no\n * {@link NormalizerRule.startTokenTypes} hint, plus those that list the type),\n * in the same priority order {@link getSortedRules} produces. Built lazily on\n * the first token of each type and cached, so a document of many number and\n * operator tokens never re-tries the many rules that only fire on an\n * identifier. Invalidated alongside {@link sortedRulesCache}.\n */\n private rulesByTokenType = new Map<string, NormalizerRule[]>();\n\n /**\n * Shape index over the priority-sorted rules, rebuilt alongside\n * {@link sortedRulesCache}. `null` means \"stale, rebuild on next use\".\n *\n * This is what turns the per-position scan from \"try every rule that could\n * fire on this token type\" into \"AND a few lookup planes and try what\n * survives\", which is usually nothing. See {@link RuleIndex}.\n */\n private ruleIndexCache: RuleIndex | null = null;\n\n /** Reused by {@link rulesAt} so a position's candidate list costs no allocation. */\n private candidateBuffer: NormalizerRule[] = [];\n\n /**\n * How many times {@link normalize} has run, capped once the index is in use.\n *\n * The index costs a few tens of microseconds to build and pays that back\n * within a line or two, but an engine that normalises exactly once, which is\n * what evaluating a single expression on a fresh engine does, would never\n * reach the payback. Skipping the build on the first call keeps that case at\n * the cost it had before the index existed, and a document reaches line two\n * immediately.\n */\n private normalizeCalls = 0;\n\n /**\n * Phrase trie for single-pass multi-word phrase fusion.\n * Tried at each token position BEFORE other rules, the trie walk\n * is O(depth) vs O(R × W) for separate rule matching.\n */\n private phraseTrie = new PhraseTrie();\n\n /** Merged options with defaults applied. */\n private options: Required<NormalizerOptions>;\n\n // ── Constructor ──────────────────────────────────────────────────────────\n\n /**\n * @param options - Configuration overrides for safety limits and diagnostic callbacks\n */\n constructor(options: NormalizerOptions = {}) {\n this.options = { ...DEFAULT_OPTIONS, ...options };\n }\n\n // ── Rule Management ──────────────────────────────────────────────────────\n\n /**\n * Register a normalization rule.\n *\n * Rules are sorted by priority (descending) on each {@link normalize} call.\n * Multiple rules can share the same priority, they are tried in registration\n * order when priorities are equal.\n *\n * @param rule - The rule to register\n */\n register(rule: NormalizerRule): void {\n warnIfUnshaped(rule);\n this.rules.push(rule);\n this.sortedRulesCache = null;\n this.rulesByTokenType.clear();\n this.ruleIndexCache = null;\n this.ruleShapesCache = null;\n }\n\n /**\n * Unregister a normalization rule by its {@link NormalizerRule.name | name}.\n *\n * If multiple rules share the same name, all are removed. This is safe to\n * call with a name that doesn't match any rule, it simply has no effect.\n *\n * @param ruleName - The name of the rule to remove\n */\n unregister(ruleName: string): void {\n this.rules = this.rules.filter(r => r.name !== ruleName);\n this.sortedRulesCache = null;\n this.rulesByTokenType.clear();\n this.ruleIndexCache = null;\n this.ruleShapesCache = null;\n }\n\n /**\n * Remove all registered rules, resetting the normalizer to its initial state.\n * Also clears the phrase trie.\n */\n clear(): void {\n this.rules = [];\n this.sortedRulesCache = null;\n this.rulesByTokenType.clear();\n this.ruleIndexCache = null;\n this.ruleShapesCache = null;\n this.phraseTrie = new PhraseTrie();\n }\n\n /**\n * Priority-sorted view of {@link rules} (descending priority; registration\n * order preserved for ties, since {@link Array.prototype.sort} is stable).\n * Cached until the next mutation. See {@link sortedRulesCache}.\n */\n private getSortedRules(): NormalizerRule[] {\n if (this.sortedRulesCache === null) {\n this.sortedRulesCache = [...this.rules].sort((a, b) => b.priority - a.priority);\n }\n return this.sortedRulesCache;\n }\n\n /**\n * The priority-sorted rules to try at a token of `type`: every rule with no\n * {@link NormalizerRule.startTokenTypes} hint, plus those that list this type.\n * A rule that declares a different trigger would have returned null here\n * anyway, so omitting it is behaviour-preserving. Built once per distinct type\n * and cached, which is what turns the per-position rule scan from \"try all R\n * rules\" into \"try only the ones that could fire on this token\".\n */\n private getRuleIndex(): RuleIndex {\n if (this.ruleIndexCache === null) {\n this.ruleIndexCache = new RuleIndex(this.getSortedRules());\n }\n return this.ruleIndexCache;\n }\n\n /**\n * The rules to try at a position, in priority order.\n *\n * With a candidate mask, walks its set bits low to high, which is descending\n * priority because bit `i` is the rule at index `i` of the priority-sorted\n * list.\n *\n * The walk shifts a bit at a time rather than jumping to the next set bit\n * with `Math.clz32(bits & -bits)`, which is the idiomatic form and was 36x\n * SLOWER here: 45us per line against 1.2us, measured over the built-in rule\n * set. `clz32` is specified on uint32 and the masks come out of a\n * `Uint32Array` as doubles above 2^31, so every call pays a conversion that\n * swamps the handful of iterations it saves. A de Bruijn table matched the\n * shift scan to within noise and needs a magic constant, so the plain shift\n * wins on both counts. Worst case is 32 iterations per word of pure integer\n * work.\n *\n * With `null` (the {@link NormalizerOptions.ignoreRuleIndex} path) it falls\n * back to the type-bucketed list, which is the behaviour this replaced.\n *\n * Returns a buffer reused across positions, so the caller must finish with it\n * before calling again. Copying the surviving rules out here rather than\n * yielding them lazily is deliberate twice over: it keeps the mask's own\n * scratch buffer from being read after the next position overwrites it, and\n * it avoids a generator on the hottest loop in the pass.\n */\n private rulesAt(mask: Uint32Array | null, type: string): NormalizerRule[] {\n const buffer = this.candidateBuffer;\n buffer.length = 0;\n\n if (mask === null) {\n const list = this.rulesForTokenType(type);\n for (let i = 0; i < list.length; i++) buffer.push(list[i]);\n return buffer;\n }\n\n const rules = this.getRuleIndex().rules;\n for (let w = 0; w < mask.length; w++) {\n let bits = mask[w] >>> 0;\n let index = w * 32;\n while (bits !== 0) {\n if ((bits & 1) !== 0) buffer.push(rules[index]);\n bits >>>= 1;\n index++;\n }\n }\n return buffer;\n }\n\n private rulesForTokenType(type: string): NormalizerRule[] {\n let list = this.rulesByTokenType.get(type);\n if (list === undefined) {\n list = this.getSortedRules().filter(\n (rule) => rule.startTokenTypes === undefined || rule.startTokenTypes.includes(type),\n );\n this.rulesByTokenType.set(type, list);\n }\n return list;\n }\n\n /**\n * Get the number of currently registered rules (excludes phrase trie entries).\n */\n get ruleCount(): number {\n return this.rules.length;\n }\n\n /**\n * Every registered rule with the shape it declared, for diagnostic display.\n *\n * Exposes what the index is actually working with: a rule that declares a\n * shape is only tried where that shape can match, and one that declares none\n * is tried at every position of every line. Which is which is invisible from\n * the outside otherwise, and it is the difference between a package that\n * costs the documents that use it and one that costs all of them, so the\n * playground draws it.\n *\n * Returned in priority order, highest first, which is the order the\n * normalizer tries them in.\n */\n private ruleShapesCache: Array<{\n name: string;\n priority: number;\n shape: readonly RuleSlot[];\n unshapedReason?: string;\n indexedSlots: number;\n }> | null = null;\n\n getRuleShapes(): Array<{\n name: string;\n priority: number;\n shape: readonly RuleSlot[];\n unshapedReason?: string;\n indexedSlots: number;\n }> {\n // Memoised: the answer depends only on the rule set, but the diagnostic\n // pipeline builds a stage per LINE, so recomputing it there made a\n // 25-line document walk every rule 25 times to produce 25 identical lists.\n if (this.ruleShapesCache !== null) return this.ruleShapesCache;\n const index = this.getRuleIndex();\n this.ruleShapesCache = this.getSortedRules().map((rule) => {\n const shape = effectiveShape(rule);\n return {\n name: rule.name,\n priority: rule.priority,\n shape,\n unshapedReason: rule.unshapedReason,\n indexedSlots: Math.min(shape.length, index.depth),\n };\n });\n return this.ruleShapesCache;\n }\n\n /**\n * How many rules could fire at each position of `tokens`, against the total.\n *\n * The point of the index is that most positions admit no rule at all, and\n * this is what makes that visible rather than asserted.\n */\n getCandidateCounts(tokens: Token[]): number[] {\n const index = this.getRuleIndex();\n const counts: number[] = [];\n for (let pos = 0; pos < tokens.length; pos++) {\n const mask = index.candidates(tokens, pos);\n let n = 0;\n for (let w = 0; w < mask.length; w++) {\n let bits = mask[w] >>> 0;\n while (bits !== 0) { n += bits & 1; bits >>>= 1; }\n }\n counts.push(n);\n }\n return counts;\n }\n\n // ── Phrase Registration ────────────────────────────────────────────────\n\n /**\n * Register a multi-word phrase for fusion into a single compound token.\n *\n * This is the preferred way to add phrase patterns. It inserts into the\n * internal {@link PhraseTrie}, which collapses all phrase rules into a\n * single O(depth) trie walk per position, no separate rule scanning.\n *\n * @param phrase - Multi-word phrase (e.g., \"to the power of\", \"abyssal whip\")\n * @param tokenType - Target token type after fusion (e.g., \"CARET\", \"ITEM\")\n */\n addPhrase(phrase: string, tokenType: string): void {\n this.phraseTrie.addPhrase(phrase, tokenType);\n }\n\n /**\n * Check whether a word can start any registered phrase.\n *\n * Used by {@link implicitMultiplyRule} to suppress `*` insertion\n * before phrase-starting identifiers (e.g., \"2 power of 3\" → `2 ^ 3`,\n * not `2 * power of 3`). Delegates to {@link PhraseTrie.canStart}.\n */\n /**\n * Get all registered phrases and their target token types.\n *\n * Exposes the full phrase trie structure for diagnostic rendering\n * in the playground's NormalizerTab. Returns ALL registered phrases,\n * not just the ones that matched in the last evaluation.\n */\n getPhrases(): Record<string, string> {\n return this.phraseTrie.getAllPhrases();\n }\n\n canStartPhrase(word: string): boolean {\n return this.phraseTrie.canStart(word);\n }\n\n // ── Normalization ────────────────────────────────────────────────────────\n\n /**\n * Normalize a token stream by applying all registered rules.\n *\n * ## Algorithm\n * Applies rules greedily left-to-right in multiple passes:\n * 1. Sort rules by priority (descending)\n * 2. Walk the token stream left to right\n * 3. At each position, try rules in priority order\n * 4. On match: consume matched tokens, insert replacements, restart from insert point\n * 5. On no match: pass token through unchanged\n * 6. Repeat until a full pass produces no changes, or maxPasses is reached\n *\n * ## Fusion tracking\n * When a rule consumes more tokens than it produces, the normalizer calls\n * `onFusion` with a {@link TokenFusion} record for diagnostic collection.\n * This populates {@link NormalizerOutput.fusions} in the playground pipeline view.\n *\n * ## Safety\n * If the normalized token count exceeds {@link NormalizerOptions.maxTokens},\n * an Error is thrown to prevent memory exhaustion from runaway rule expansion.\n *\n * @param tokens - Raw tokens from the lexer\n * @param onFusion - Optional fusion callback (overrides {@link NormalizerOptions.onFusion})\n * @returns Normalized tokens ready for parsing\n * @throws {Error} If the normalized token count exceeds maxTokens\n */\n normalize(tokens: Token[], onFusion?: (fusion: TokenFusion) => void): Token[] {\n // ── Early exit: nothing to normalize ──\n if (tokens.length === 0) return tokens;\n\n // Rules are consulted per token type via rulesForTokenType(), which builds\n // on the priority-sorted cache in getSortedRules().\n const fusionHandler = onFusion ?? this.options.onFusion;\n const maxPasses = this.options.maxPasses;\n const maxTokens = this.options.maxTokens;\n\n // Hoisted out of the pass loop: the rule set cannot change mid-normalize,\n // so the index is resolved once rather than per position.\n const warmedUp = this.normalizeCalls > 0;\n if (!warmedUp) this.normalizeCalls = 1;\n const useIndex = warmedUp && !this.options.ignoreRuleIndex;\n const ruleIndex = useIndex ? this.getRuleIndex() : null;\n\n let current = tokens;\n let changed = true;\n let passCount = 0;\n\n // Multi-pass loop: rules may trigger cascading matches across passes\n while (changed && passCount < maxPasses) {\n changed = false;\n passCount++;\n\n // Built lazily: a pass that changes nothing must not allocate an array\n // and copy every token into it only to throw the copy away. `null` means\n // \"nothing has changed yet, `current` is still the answer\"; the first\n // rule to fire calls ensureResult() to materialise it. A document whose\n // lines mostly normalise to themselves is the common case, and it now\n // costs no allocation at all.\n let result: Token[] | null = null;\n let pos = 0;\n\n // Single-pass left-to-right greedy walk\n while (pos < current.length) {\n let matched = false;\n\n // ── Fast path: phrase trie (O(depth) single walk vs O(R × W) per rule) ──\n // O(1) type-guard: skip trie entirely for tokens that can't start phrases.\n // Flat Uint8Array indexed by typeId, no hashing, no Set lookup, true O(1).\n const tid = current[pos].typeId;\n if (tid >= NON_WORD_TABLE.length || NON_WORD_TABLE[tid] === 0) {\n const trieMatch = this.phraseTrie.matchAt(current, pos);\n if (trieMatch) {\n const sourceTokens = current.slice(pos, pos + trieMatch.consumed);\n if (result === null) result = current.slice(0, pos);\n for (const rt of trieMatch.replacement) {\n result.push(rt);\n }\n if (trieMatch.consumed > 1 && trieMatch.replacement.length === 1) {\n recordSourceSpan(trieMatch.replacement[0], sourceTokens);\n fusionHandler({\n rule: trieMatch.ruleName ?? \"phrase-trie\",\n sourceTokens,\n fusedToken: trieMatch.replacement[0],\n });\n }\n pos += trieMatch.consumed;\n changed = true;\n continue; // trie matched — skip other rules at this position (no need to set matched)\n }\n }\n\n // Try, in priority order, only the rules whose declared shape admits\n // this position. The index is a pure filter: bit order is priority\n // order, and a rule it excludes would have returned null here anyway\n // (see RuleIndex). `ignoreRuleIndex` restores the exhaustive scan so\n // the two can be compared.\n const candidates = useIndex\n ? ruleIndex!.candidates(current, pos)\n : null;\n if (candidates !== null && isEmptyMask(candidates)) {\n // Nothing can fire here. This is the common case in running prose,\n // and reaching it costs a few array loads rather than one call per\n // registered rule.\n if (result !== null) result.push(current[pos]);\n pos++;\n continue;\n }\n for (const rule of this.rulesAt(candidates, current[pos].type)) {\n const match = rule.match(current, pos);\n if (match) {\n // Collect source tokens for fusion tracking\n const sourceTokens = current.slice(pos, pos + match.consumed);\n\n // Insert replacement tokens into result\n if (result === null) result = current.slice(0, pos);\n for (const rt of match.replacement) {\n result.push(rt);\n }\n\n // Track fusion events for diagnostics:\n // - Multiple tokens → single token: classic fusion\n // - Multiple tokens → fewer tokens: partial fusion\n if (match.consumed > 1 && match.replacement.length === 1) {\n recordSourceSpan(match.replacement[0], sourceTokens);\n fusionHandler({\n rule: rule.name,\n sourceTokens,\n fusedToken: match.replacement[0],\n });\n } else if (match.consumed > 1 && match.replacement.length < match.consumed) {\n for (const rt of match.replacement) {\n fusionHandler({\n rule: rule.name,\n sourceTokens,\n fusedToken: rt,\n });\n }\n }\n\n // Advance position past consumed tokens\n pos += match.consumed;\n changed = true;\n matched = true;\n break; // Rule matched — restart at new position with highest-priority rules\n }\n }\n\n if (!matched) {\n // No rule matched at this position, pass token through unchanged.\n // Only copied when an earlier position already forced the array.\n if (result !== null) result.push(current[pos]);\n pos++;\n }\n }\n\n // Nothing fired anywhere in this pass, so the stream is already its own\n // normal form and `changed` is false; the loop is about to end.\n if (result === null) break;\n const passResult: Token[] = result;\n\n // Safety: bail if token count explodes (runaway rule expansion)\n if (passResult.length > maxTokens) {\n // A raw Error here would bypass ThreeTierEvaluator's DAG-preservation\n // enrichment on compile failure (it specifically checks for\n // EngineError). Same reasoning as ExpressionEngineSafety.ts's\n // complexity/length checks, which this mirrors.\n throw ErrorFactory.validation(\n \"NORMALIZED_TOKEN_LIMIT_EXCEEDED\",\n `Normalized token count (${passResult.length}) exceeds safety limit (${maxTokens})`,\n { tokenCount: passResult.length, maxTokens }\n );\n }\n\n current = passResult;\n }\n\n return current;\n }\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * PhraseTrie, optimized word-level trie for multi-word phrase fusion.\n *\n * ## Problem\n * The normalizer previously applied N separate `phraseFusionRule` instances,\n * each scanning forward from the current token position. For R phrase rules\n * and W average phrase length, this cost O(N × R × W) per pass.\n *\n * ## Solution\n * A single trie walk per position collapses all phrase rules into O(D)\n * where D ≤ longest phrase depth (typically ≤ 5 words). The trie tracks\n * the deepest terminal node reached, implementing longest-match-wins\n * without priority sorting.\n *\n * ## Optimizations\n * 1. **Set<string> quick-reject**, the `startWords` set contains the first\n * word of every registered phrase. At each position, if the token's\n * lowercase value isn't in the set, we bail in O(1) without touching\n * the trie. ~80% of tokens (numbers, operators) hit this fast path.\n * 2. **Longest-match-wins**, the `matchAt()` walk continues past terminal\n * nodes, tracking the deepest one. Shorter overlapping phrases (e.g.,\n * \"power of\") don't need lower priority, the trie naturally prefers\n * the longer match.\n * 3. **Map-based children**, `Map<string, TrieNode>` gives O(1) amortized\n * child lookup per word, faster than array scanning for sparse branches.\n *\n * ## Package integration\n * Packages add phrases via {@link TokenNormalizer.addPhrase} (public API)\n * or the {@link IEnginePackage.phrases} declarative field. Each call to\n * `addPhrase()` inserts the phrase into this trie and updates `startWords`.\n *\n * @module PhraseTrie\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport type { NormalizerMatch } from \"./NormalizerRule\";\nimport { createFusedToken } from \"./TokenNormalizer\";\n\n//#endregion\n//#region ─── TrieNode ─────────────────────────────────────────────────────────\n\n/**\n * Internal trie node.\n *\n * Each node represents a matched word in a phrase. The path from root\n * to a node spells out a partial or complete phrase.\n */\ninterface TrieNode {\n\t/** Child nodes keyed by next word (all lowercase). */\n\tchildren: Map<string, TrieNode>;\n\t/**\n\t * If this node completes a phrase, the terminal metadata.\n\t * A node can be both terminal AND have children. This handles\n\t * overlapping phrases like \"power of\" and \"to the power of\".\n\t */\n\tterminal: TrieTerminal | null;\n}\n\n/** Metadata stored at terminal nodes for deferred token creation. */\ninterface TrieTerminal {\n\t/** The target token type after fusion (e.g., \"CARET\", \"TIMES_BY\"). */\n\ttokenType: string;\n\t/** The original phrase string (e.g., \"to the power of\"). */\n\tphrase: string;\n\t/** Number of tokens consumed by this phrase. */\n\tconsumed: number;\n}\n\n//#endregion\n//#region ─── PhraseTrie ─────────────────────────────────────────────────────\n\n/**\n * Word-level trie for single-pass multi-word phrase matching.\n *\n * @example\n * ```ts\n * const trie = new PhraseTrie();\n * trie.addPhrase(\"to the power of\", \"CARET\");\n * trie.addPhrase(\"power of\", \"CARET\");\n * trie.addPhrase(\"abyssal whip\", \"ITEM\");\n *\n * // At position 0 with tokens [\"to\",\"the\",\"power\",\"of\",\"3\"]\n * const match = trie.matchAt(tokens, 0);\n * // → { consumed: 4, replacement: [CARET(\"to the power of\")] }\n * ```\n */\nexport class PhraseTrie {\n\t/**\n\t * First words that can start any registered phrase (all lowercase).\n\t * O(1) quick-reject: if `tokens[pos].value.toLowerCase()` isn't here,\n\t * no phrase can match at this position.\n\t */\n\tprivate startWords = new Set<string>();\n\n\t/**\n\t * Root maps first word → child node.\n\t * Two-level root avoids an unnecessary intermediate TrieNode.\n\t */\n\tprivate root = new Map<string, TrieNode>();\n\n\t// ── Registration ──────────────────────────────────────────────────────\n\n\t/**\n\t * Register a phrase for fusion into a single compound token.\n\t *\n\t * @param phrase - Multi-word phrase (e.g., \"to the power of\")\n\t * @param tokenType - Target token type after fusion (e.g., \"CARET\")\n\t */\n\taddPhrase(phrase: string, tokenType: string): void {\n\t\tconst words = phrase.toLowerCase().trim().split(/\\s+/);\n\t\tif (words.length === 0 || words[0] === \"\") return;\n\n\t\tthis.startWords.add(words[0]);\n\n\t\tconst firstWord = words[0];\n\t\tlet node: TrieNode;\n\n\t\tif (this.root.has(firstWord)) {\n\t\t\tnode = this.root.get(firstWord)!;\n\t\t} else {\n\t\t\tnode = { children: new Map(), terminal: null };\n\t\t\tthis.root.set(firstWord, node);\n\t\t}\n\n\t\t// Single-word phrase: terminal at root's child\n\t\tif (words.length === 1) {\n\t\t\tnode.terminal = { tokenType, phrase, consumed: 1 };\n\t\t\treturn;\n\t\t}\n\n\t\t// Walk/insert remaining words\n\t\tfor (let i = 1; i < words.length; i++) {\n\t\t\tconst word = words[i];\n\t\t\tif (!node.children.has(word)) {\n\t\t\t\tnode.children.set(word, { children: new Map(), terminal: null });\n\t\t\t}\n\t\t\tnode = node.children.get(word)!;\n\t\t}\n\n\t\tnode.terminal = { tokenType, phrase, consumed: words.length };\n\t}\n\n\t// ── Matching ──────────────────────────────────────────────────────────\n\n\t/**\n\t * Attempt to match a phrase starting at `pos` in the token stream.\n\t *\n\t * Walks the trie one token at a time, tracking the deepest terminal\n\t * node reached. Returns the longest match found, or `null` if no\n\t * phrase starts at this position.\n\t *\n\t * @param tokens - The current token stream\n\t * @param pos - Position to attempt matching from\n\t * @returns The longest {@link NormalizerMatch}, or `null` on no match\n\t */\n\tmatchAt(tokens: Token[], pos: number): NormalizerMatch | null {\n\t\t// ── Bounds guard ──\n\t\tif (pos >= tokens.length) return null;\n\n\t\t// ── A tag token never takes part in phrase fusion (#197, #213) ──\n\t\t// A `#tag` is a typed token, not a bare word, so it must not start or\n\t\t// complete a phrase. The trie matches on written value alone, so without\n\t\t// this guard a tag whose name equals a phrase or a phrase-continuation\n\t\t// word (`1200 #assuming`, `total of #column`) is fused into that grammar\n\t\t// before the category-tag rules ever run, and the tag is lost.\n\t\t//\n\t\t// The guard also covers the fused aggregate tokens the tags package emits\n\t\t// (`TAG_SUM` / `TAG_COUNT` / `TAG_AVERAGE`), whose value is the tag NAME:\n\t\t// otherwise `total of #assuming` fuses correctly to TAG_SUM(\"assuming\"),\n\t\t// then the trie re-reads that value on the next pass and turns it back\n\t\t// into the finance ASSUMING keyword (#213). The whole `TAG` / `TAG_*`\n\t\t// namespace belongs to the tags package.\n\t\tconst startType = tokens[pos].type;\n\t\tif (startType === \"TAG\" || startType.startsWith(\"TAG_\")) return null;\n\n\t\t// ── O(1) quick-reject: first word not a phrase starter ──\n\t\tconst firstWord = tokens[pos].value.toLowerCase();\n\t\tif (!this.startWords.has(firstWord)) return null;\n\n\t\t// ── Walk trie, tracking deepest terminal ──\n\t\tlet node: TrieNode | undefined = this.root.get(firstWord);\n\t\tif (!node) return null;\n\n\t\tlet best: NormalizerMatch | null = null;\n\t\tlet depth = 1;\n\n\t\t// Check single-word phrase at first node\n\t\tif (node.terminal) {\n\t\t\tconst sourceTokens = tokens.slice(pos, pos + 1);\n\t\t\tbest = {\n\t\t\t\tconsumed: 1,\n\t\t\t\treplacement: [createFusedToken(node.terminal.tokenType, node.terminal.phrase, sourceTokens)],\n\t\t\t\truleName: node.terminal.phrase,\n\t\t\t};\n\t\t}\n\n\t\t// Walk deeper for multi-word phrases\n\t\tfor (let i = pos + 1; i < tokens.length && node?.children; i++) {\n\t\t\tconst contType = tokens[i].type;\n\t\t\tif (contType === \"TAG\" || contType.startsWith(\"TAG_\")) break; // a tag token can't continue a phrase (#197, #213)\n\t\t\tconst word = tokens[i].value.toLowerCase();\n\t\t\tnode = node.children.get(word);\n\t\t\tif (!node) break; // dead end\n\t\t\tdepth++;\n\n\t\t\tif (node.terminal) {\n\t\t\t\t// Deferred fused-token creation, only on deepest match found\n\t\t\t\tconst sourceTokens = tokens.slice(pos, pos + depth);\n\t\t\t\tbest = {\n\t\t\t\t\tconsumed: depth,\n\t\t\t\t\treplacement: [\n\t\t\t\t\t\tcreateFusedToken(node.terminal.tokenType, node.terminal.phrase, sourceTokens),\n\t\t\t\t\t],\n\t\t\t\t\truleName: node.terminal.phrase,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn best;\n\t}\n\n\t// ── Introspection ─────────────────────────────────────────────────────\n\n\t/** Number of unique first words (not total phrases). */\n\tget size(): number {\n\t\treturn this.root.size;\n\t}\n\n\t/**\n\t * Return all registered phrases and their target token types.\n\t *\n\t * Used by diagnostic mode to expose the complete trie structure to the\n\t * playground's NormalizerTab for rendering ALL registered phrases\n\t * (not just the ones that matched in this evaluation).\n\t */\n\tgetAllPhrases(): Record<string, string> {\n\t\tconst result: Record<string, string> = {};\n\n\t\tconst collect = (node: TrieNode, path: string[]): void => {\n\t\t\tif (node.terminal) {\n\t\t\t\tresult[path.join(' ')] = node.terminal.tokenType;\n\t\t\t}\n\t\t\tfor (const [word, child] of node.children) {\n\t\t\t\tcollect(child, [...path, word]);\n\t\t\t}\n\t\t};\n\n\t\tfor (const [firstWord, node] of this.root) {\n\t\t\tcollect(node, [firstWord]);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/** Check if any phrase starts with this word (case-insensitive). */\n\tcanStart(word: string): boolean {\n\t\treturn this.startWords.has(word.toLowerCase());\n\t}\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * Built-in normalization rules for the {@link TokenNormalizer}.\n *\n * These rules handle common expression patterns that span multiple tokens.\n * Phrase fusion (e.g., \"to the power of\" → CARET) is handled by the\n * internal {@link PhraseTrie}. See {@link TokenNormalizer.addPhrase}.\n * This module only exports non-phrase rules like {@link implicitMultiplyRule}.\n *\n * @module BuiltinNormalizerRules\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, NormalizerMatch } from \"./NormalizerRule\";\n\n//#endregion\n//#region ─── PHRASE_START_WORDS, Implicit Multiply Guard ─────────────────────\n\n/**\n * Words that can start multi-word phrases, hardcoded fallback.\n *\n * This is ONLY used as the default fallback in {@link implicitMultiplyRule}\n * when no `canStart` predicate is provided. In the recommended pattern,\n * the {@link PhraseTrie}'s live `canStart()` set is passed instead, keeping\n * the guard in sync with package-registered phrases.\n *\n * @see {@link TokenNormalizer.canStartPhrase}\n */\n/**\n * Words that introduce a rate denominator when a unit follows.\n *\n * Kept next to the implicit-multiplication rule because that is the only\n * thing they change here; the rate itself is built in the uom package.\n */\nconst RATE_DENOMINATOR_WORDS = new Set([\"per\", \"a\", \"an\", \"each\", \"every\"]);\n\nconst PHRASE_START_WORDS = new Set([\n \"to\", \"power\", \"increase\", \"decrease\", \"times\", \"multiply\", \"divide\", \"by\",\n]);\n\n//#endregion\n//#region ─── implicitMultiplyRule, Implicit Operator Insertion ────────────────\n\n/**\n * Creates a normalization rule that inserts an implicit multiplication operator\n * between adjacent tokens where multiplication is implied.\n *\n * ## When it fires\n * Inserts a STAR token between:\n * - `NUMBER IDENT` (e.g., \"2 x\" → \"2 * x\")\n * - `RPAREN IDENT` (e.g., \"(x+1)y\" → \"(x+1) * y\")\n * - `NUMBER LPAREN` (e.g., \"2(x+1)\" → \"2 * (x+1)\")\n * - `NUMBER PI` / `NUMBER E` (e.g., \"2π\" → \"2 * π\")\n *\n * ## When it doesn't fire\n * - When the following identifier starts a multi-word phrase\n * (checked against {@link PHRASE_START_WORDS})\n * - When the following token is not an identifier or parenthesized expression\n *\n * ## Priority\n * Default priority is 50, below phrase fusion so phrases match first.\n *\n * @param priority - Rule priority (default 50)\n * @returns A {@link NormalizerRule} that inserts implicit multiply operators\n */\nexport function implicitMultiplyRule(\n\tpriority: number = 50,\n\tcanStart?: (word: string) => boolean\n): NormalizerRule {\n\tconst phraseGuard = canStart ?? ((word: string) => PHRASE_START_WORDS.has(word.toLowerCase()));\n\n\treturn {\n name: \"implicit:multiply\",\n priority,\n // Both slots are exactly the `triggers` test below, which is the whole\n // condition: a value or closing bracket, then something a multiplication\n // could apply to.\n shape: [\n { types: [\"NUMBER\", \"RPAREN\"] },\n { types: [\"IDENT\", \"LPAREN\", \"PI\", \"E\"] },\n ],\n match(tokens: Token[], pos: number): NormalizerMatch | null {\n // ── Need at least one token after the current position ──\n if (pos + 1 >= tokens.length) return null;\n\n const t = tokens[pos];\n const next = tokens[pos + 1];\n\n // ── Check trigger conditions ──\n // Ordered FIRST deliberately. The two guards below only ever suppress a\n // match, so testing them after the trigger cannot change any result, and\n // the first of them allocates a lower-cased copy of the next token's\n // value. Running that ahead of a pair of type comparisons meant every\n // position in the document paid a string allocation and a set lookup to\n // reach a test that rejects nearly all of them.\n const triggers =\n (t.type === \"NUMBER\" || t.type === \"RPAREN\") &&\n (next.type === \"IDENT\" || next.type === \"LPAREN\" || next.type === \"PI\" || next.type === \"E\");\n\n if (!triggers) return null;\n\n // ── Guard: suppress if the next identifier starts a phrase ──\n // Uses the trie's canStart when available, falls back to hardcoded set.\n // This prevents \"2 power of 3\" from becoming \"2 * power of 3\".\n const nextValue = next.value.toLowerCase();\n if (phraseGuard(nextValue)) return null;\n\n // ── Guard: a rate denominator, not a multiplication ──\n // \"99 per week\" is ninety-nine a week, not ninety-nine times something\n // called per. The trie guard above cannot cover this, because these are\n // not registered phrases; they are recognised by the uom package's\n // bare-denominator rule, which runs after this one and then finds its\n // fused token stranded in operand position. The slash spelling never had\n // the problem, which is what made it hard to see.\n if (RATE_DENOMINATOR_WORDS.has(nextValue) && tokens[pos + 2]?.type === \"UNIT\") return null;\n\n // ── Insert a STAR token at the next token's position ──\n const starToken = new LexerToken(\n \"STAR\", tokenTypeId(\"STAR\"), \"*\", \"*\",\n next.offset, 0, next.line, next.col,\n );\n\n // consumed = 1: only the current token is replaced with [current, STAR]\n // The next token is NOT consumed, it stays for the next iteration\n return { consumed: 1, replacement: [t, starToken] };\n },\n };\n}\n\n//#endregion\n//#region ─── isInsideRangeContext, Bracket/Call-Paren Context Guard ───────────\n\n/**\n * Whether token `pos` sits inside a context where a bare `NUMBER:NUMBER`\n * sequence means a Range, not a clock-time/laptime/video-timecode literal:\n * a matrix literal/index/slice (`[1,2,3]`, `a[0:3]`), OR a `map`/`reduce`/\n * `sum`/`prod` call's own argument-list parens (`map(f, 0:3)`, these\n * accept a bare Range argument directly, per the Calca spec's own\n * example). Scans backward from `pos` over the CURRENT pass's token array,\n * tracking `[`/`(` nesting depth, the same \"positional guard via\n * backward scan\" idiom already used elsewhere in this normalizer layer\n * (e.g. `LineRefNormalizerRule`'s previous-token check), generalized to\n * depth-tracking. An `LBRACKET` is unconditionally a range-safe opener; an\n * `LPAREN` is range-safe ONLY when immediately preceded by MAP/REDUCE/\n * SUM_FN/PROD_FN, an ordinary grouping/function-call paren is NOT, so\n * `(9:00) + 5` still means a clock time, not a range.\n *\n * Needed because the clock-time/laptime/video-timecode rules each match a\n * bare `NUMBER COLON NUMBER...` shape with ZERO context-awareness, a real\n * collision discovered when adding Range support, since e.g. \"0:3\" is\n * valid input to BOTH features. These contexts have no legitimate use for\n * a clock-time/laptime/timecode literal, so the carve-out costs the time\n * features nothing.\n *\n * IMPORTANT cross-pass-timing gotcha (a real bug found and fixed here,\n * not a hypothetical): the `LPAREN`-opener check deliberately tests the\n * RAW word text (`prev.value.toLowerCase()`), not `prev.type ===\n * \"MAP\"/\"REDUCE\"/...`. The normalizer's multi-pass loop hands every rule\n * the SAME frozen `tokens` snapshot for an entire pass, a rule scanning\n * a LATER position in that pass cannot see a fusion `mapReduceCallNormalizerRule`\n * performs at an EARLIER position in that SAME pass (fusion results only\n * become visible to other rules starting the NEXT pass). Checking the\n * fused token type here would miss exactly the case that matters most\n * `map(f, 0:3)` on its very first normalization pass, silently letting\n * `0:3` fuse into a clock time before `map(`'s own fusion ever lands.\n * Testing the raw word is immune to this: it's true from the very first\n * pass, regardless of whether `mapReduceCallNormalizerRule` has run yet.\n * (`LBRACKET` above has no equivalent issue, it's a genuine lexer token\n * from the start, never itself the product of a fusion.)\n */\nexport function isInsideRangeContext(tokens: Token[], pos: number): boolean {\n const safeStack: boolean[] = [];\n for (let i = 0; i < pos; i++) {\n const t = tokens[i];\n if (t.type === \"LBRACKET\") {\n safeStack.push(true);\n } else if (t.type === \"LPAREN\") {\n const prev = tokens[i - 1];\n const opensMapReduceCall = !!prev && (\n prev.type === \"MAP\" || prev.type === \"REDUCE\" || prev.type === \"SUM_FN\" || prev.type === \"PROD_FN\" ||\n (prev.type === \"IDENT\" && (prev.value.toLowerCase() === \"map\" || prev.value.toLowerCase() === \"reduce\" || prev.value.toLowerCase() === \"sum\" || prev.value.toLowerCase() === \"prod\"))\n );\n safeStack.push(opensMapReduceCall);\n } else if (t.type === \"RBRACKET\" || t.type === \"RPAREN\") {\n safeStack.pop();\n }\n }\n return safeStack.length > 0 && safeStack[safeStack.length - 1];\n}\n\n//#endregion\n//#region ─── createBuiltinNormalizerRules, All Built-in Rules ─────────────────\n\n/**\n * Creates built-in non-phrase normalization rules.\n *\n * Returns implicit multiply insertion (priority 50).\n *\n * **Prefer** calling {@link implicitMultiplyRule} directly with a\n * `canStart` predicate wired to the normalizer's phrase trie:\n * ```ts\n * normalizer.register(implicitMultiplyRule(50, (w) => normalizer.canStartPhrase(w)));\n * ```\n * Without the predicate, this function falls back to a hardcoded\n * {@link PHRASE_START_WORDS} set that won't reflect package-registered phrases.\n *\n * @returns An array of {@link NormalizerRule} instances ready for registration\n */\nexport function createBuiltinNormalizerRules(): NormalizerRule[] {\n return [\n // ── Implicit operator insertion (priority 50) ──\n implicitMultiplyRule(),\n ];\n}\n\n/**\n * Built-in phrase → tokenType mappings.\n *\n * These are registered into the engine's {@link PhraseTrie} during\n * construction. Tests that create a standalone {@link TokenNormalizer}\n * should register these via {@link TokenNormalizer.addPhrase}.\n */\nexport const BUILTIN_PHRASES: Record<string, string> = {\n\t\"to the power of\": \"CARET\",\n\t\"power of\": \"CARET\",\n\t\"increase by\": \"INCREASE_BY\",\n\t\"decrease by\": \"DECREASE_BY\",\n\t\"times by\": \"TIMES_BY\",\n\t\"multiply by\": \"MULTIPLY_BY\",\n\t\"divide by\": \"DIVIDE_BY\",\n\t// The past-tense spellings, which is how the operation is usually written\n\t// out: \"3 multiplied by 4\". Same tokens, so no new parselets. Both this\n\t// branch and the parity branch added \"multiplied by\" independently; the\n\t// merge kept both copies and the locale table rejected the duplicate key.\n\t\"multiplied by\": \"MULTIPLY_BY\",\n\t\"divided by\": \"DIVIDE_BY\",\n};\n\n//#endregion\n"]}
|
package/dist/chunk-6YM67DWH.cjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkTLG7VZRX_cjs=require('./chunk-TLG7VZRX.cjs'),chunkCO2BI6WL_cjs=require('./chunk-CO2BI6WL.cjs');var T=new Set(["AED","AFN","ALL","AMD","ANG","AOA","ARS","AUD","AWG","AZN","BAM","BBD","BDT","BGN","BHD","BIF","BMD","BND","BOB","BOV","BRL","BSD","BTN","BWP","BYN","BZD","CAD","CDF","CHE","CHF","CHW","CLF","CLP","CNY","COP","COU","CRC","CUP","CVE","CZK","DJF","DKK","DOP","DZD","EGP","ERN","ETB","EUR","FJD","FKP","GBP","GEL","GHS","GIP","GMD","GNF","GTQ","GYD","HKD","HNL","HTG","HUF","IDR","ILS","INR","IQD","IRR","ISK","JMD","JOD","JPY","KES","KGS","KHR","KMF","KPW","KRW","KWD","KYD","KZT","LAK","LBP","LKR","LRD","LSL","LYD","MAD","MDL","MGA","MKD","MMK","MNT","MOP","MRU","MUR","MVR","MWK","MXN","MXV","MYR","MZN","NAD","NGN","NIO","NOK","NPR","NZD","OMR","PAB","PEN","PGK","PHP","PKR","PLN","PYG","QAR","RON","RSD","RUB","RWF","SAR","SBD","SCR","SDG","SEK","SGD","SHP","SLE","SOS","SRD","SSP","STN","SVC","SYP","SZL","THB","TJS","TMT","TND","TOP","TRY","TTD","TWD","TZS","UAH","UGX","USD","USN","UYI","UYU","UYW","UZS","VED","VES","VND","VUV","WST","XAF","XCD","XCG","XOF","XPF","YER","ZAR","ZMW","ZWG"]);function N(O){return T.has(O.toUpperCase())}var d={API_ERROR:"CURRENCY_API_ERROR",UNKNOWN_CODE:"UNKNOWN_CURRENCY_CODE",CRYPTO_API_ERROR:"CRYPTO_PRICE_API_ERROR"},o=class o{constructor(){this.baseTables=new Map;}isCryptoCode(t){return t.toUpperCase()in o.CRYPTO_IDS}async getRate(t,e,r){let n=t.toUpperCase(),s=e.toUpperCase();if(this.isCryptoCode(n)||this.isCryptoCode(s))return this.getCryptoRate(n,s,r);let{signal:C,cleanup:l}=chunkTLG7VZRX_cjs.a(r,o.FETCH_TIMEOUT_MS,"Currency API fetch");try{let a=await fetch(`https://api.frankfurter.dev/v2/rates?base=${n}`,{signal:C});if(!a.ok)throw chunkCO2BI6WL_cjs.c.external(d.API_ERROR,`Currency API returned ${a.status}`,{status:a.status});let i=await a.json(),c=Array.isArray(i)?Object.fromEntries(i.filter(R=>{if(typeof R!="object"||R===null)return !1;let u=R;return typeof u.quote=="string"&&typeof u.rate=="number"}).map(R=>[R.quote.toUpperCase(),R.rate])):i.rates??{};if(c[s]===void 0)throw chunkCO2BI6WL_cjs.c.validation(d.UNKNOWN_CODE,`Unknown currency: ${s}`,{code:s});return this.baseTables.set(n,{fetchedAt:Date.now(),rates:{...c,[n]:1}}),c[s]}finally{l();}}async getCryptoRate(t,e,r){let{signal:n,cleanup:s}=chunkTLG7VZRX_cjs.a(r,o.FETCH_TIMEOUT_MS,"Crypto price API fetch");try{let C=this.isCryptoCode(t),l=this.isCryptoCode(e),a;if(C&&l){let i=o.CRYPTO_IDS[t],c=o.CRYPTO_IDS[e],R=await this.fetchCoinGeckoPrices([i,c],"usd",n),u=R[i]?.usd,P=R[c]?.usd;if(typeof u!="number")throw chunkCO2BI6WL_cjs.c.validation(d.UNKNOWN_CODE,`Unknown currency: ${t}`,{code:t});if(typeof P!="number")throw chunkCO2BI6WL_cjs.c.validation(d.UNKNOWN_CODE,`Unknown currency: ${e}`,{code:e});a=u/P;}else if(C){let i=o.CRYPTO_IDS[t],c=e.toLowerCase(),u=(await this.fetchCoinGeckoPrices([i],c,n))[i]?.[c];if(typeof u!="number")throw chunkCO2BI6WL_cjs.c.validation(d.UNKNOWN_CODE,`Unknown currency: ${e}`,{code:e});a=u;}else {let i=o.CRYPTO_IDS[e],c=t.toLowerCase(),u=(await this.fetchCoinGeckoPrices([i],c,n))[i]?.[c];if(typeof u!="number")throw chunkCO2BI6WL_cjs.c.validation(d.UNKNOWN_CODE,`Unknown currency: ${t}`,{code:t});a=1/u;}return this.baseTables.set(t,{fetchedAt:Date.now(),rates:{[t]:1,[e]:a}}),a}finally{s();}}async fetchCoinGeckoPrices(t,e,r){let n=`https://api.coingecko.com/api/v3/simple/price?ids=${t.join(",")}&vs_currencies=${e}`,s=await fetch(n,{signal:r});if(!s.ok)throw chunkCO2BI6WL_cjs.c.external(d.CRYPTO_API_ERROR,`Crypto price API returned ${s.status}`,{status:s.status});return s.json()}primeRates(t,e){let r=t.toUpperCase();this.baseTables.set(r,{fetchedAt:Date.now(),rates:{...e,[r]:1}});}clearRates(){this.baseTables.clear();}getRateSync(t,e){let r=t.toUpperCase(),n=e.toUpperCase();if(r===n)return 1;let s=Date.now();for(let C of this.baseTables.values()){if(s-C.fetchedAt>o.RATE_FRESHNESS_MS)continue;let l=C.rates[r],a=C.rates[n];if(l&&a)return a/l}return null}async convert(t,e,r){let n=await this.getRate(e,r);return t*n}getAllRates(){let t=Date.now(),e={},r=false;for(let[n,s]of this.baseTables)if(!(t-s.fetchedAt>o.RATE_FRESHNESS_MS))for(let[C,l]of Object.entries(s.rates))e[`${n}:${C}`]=l,r=true;return r?e:null}hasRates(){return this.getAllRates()!==null}convertSync(t,e,r){let n=this.getRateSync(e,r);return n===null?null:t*n}isCurrency(t){return N(t)||this.isCryptoCode(t)}};o.RATE_FRESHNESS_MS=900*1e3,o.CRYPTO_IDS={BTC:"bitcoin",ETH:"ethereum",SOL:"solana",XRP:"ripple",ADA:"cardano",DOGE:"dogecoin",DOT:"polkadot"},o.FETCH_TIMEOUT_MS=1e4;var f=o,b=new f,h=b;
|
|
2
|
-
exports.a=f;exports.b=b;exports.c=h;//# sourceMappingURL=chunk-6YM67DWH.cjs.map
|
|
3
|
-
//# sourceMappingURL=chunk-6YM67DWH.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/uom/Iso4217.ts","../src/uom/CurrencyExchange.ts"],"names":["ISO_4217_CODES","isIso4217","code","CurrencyErrorCodes","_CurrencyExchangeService","from","to","signal","fromUpper","toUpper","fetchSignal","cleanup","createTimeoutSignal","response","ErrorFactory","data","rates","entry","candidate","fromIsCrypto","toIsCrypto","rate","fromId","toId","fromUsd","toUsd","vs","value","priceOfToInFrom","ids","vsCurrency","url","base","baseUpper","now","table","fromRate","toRate","snapshot","any","CurrencyExchangeService","currencyExchangeService","sharedCurrencyExchange"],"mappings":"qHAyBO,IAAMA,CAAAA,CAAsC,IAAI,GAAA,CAAI,CAC1D,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAC/D,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAC/D,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CACnC,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAC/D,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CACrB,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MACrB,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CACrB,KAAA,CAAO,KAAA,CACP,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MACjD,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CACrB,KAAA,CAAO,KAAA,CAAO,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AA,CAlDtC,IAAMoC,CAAAA,CAANpC,CAAAA,CAsTMqC,CAAAA,CAA0B,IAAID,CAAAA,CAI9BE,CAAAA,CAAyBD","file":"chunk-6YM67DWH.cjs","sourcesContent":["/**\n * Every active ISO 4217 currency code.\n *\n * This exists because `CurrencyExchange.isCurrency()` used to hold a\n * hand-written list of forty-six codes, and a code missing from it did not\n * error: `$100 in UAH` returned the original hundred dollars, unconverted, as\n * though the rate were 1. A wrong answer, not a missing feature.\n *\n * The list is the ISO 4217 active set, so \"is this a currency\" is answered by\n * the standard rather than by whichever codes happened to get added. Whether a\n * *rate* is available for one is a separate question, answered at resolution\n * time by whatever the exchange provider supports; conflating the two is what\n * produced the silent failure.\n *\n * Deliberately excluded:\n * - The historical/withdrawn codes (DEM, FRF, and the rest). They are not\n * active, no provider quotes them, and recognising them would only move the\n * failure later.\n * - The X-series non-currencies: XAU/XAG/XPT/XPD (metals), XDR (IMF special\n * drawing rights), XTS (reserved for testing) and XXX (explicitly \"no\n * currency\"). XXX in particular must never resolve.\n *\n * Cryptocurrencies are not here either. They are not ISO 4217 and are tracked\n * separately in `CurrencyExchangeService.CRYPTO_IDS`.\n */\nexport const ISO_4217_CODES: ReadonlySet<string> = new Set([\n\t\"AED\", \"AFN\", \"ALL\", \"AMD\", \"ANG\", \"AOA\", \"ARS\", \"AUD\", \"AWG\", \"AZN\",\n\t\"BAM\", \"BBD\", \"BDT\", \"BGN\", \"BHD\", \"BIF\", \"BMD\", \"BND\", \"BOB\", \"BOV\",\n\t\"BRL\", \"BSD\", \"BTN\", \"BWP\", \"BYN\", \"BZD\",\n\t\"CAD\", \"CDF\", \"CHE\", \"CHF\", \"CHW\", \"CLF\", \"CLP\", \"CNY\", \"COP\", \"COU\",\n\t\"CRC\", \"CUP\", \"CVE\", \"CZK\",\n\t\"DJF\", \"DKK\", \"DOP\", \"DZD\",\n\t\"EGP\", \"ERN\", \"ETB\", \"EUR\",\n\t\"FJD\", \"FKP\",\n\t\"GBP\", \"GEL\", \"GHS\", \"GIP\", \"GMD\", \"GNF\", \"GTQ\", \"GYD\",\n\t\"HKD\", \"HNL\", \"HTG\", \"HUF\",\n\t\"IDR\", \"ILS\", \"INR\", \"IQD\", \"IRR\", \"ISK\",\n\t\"JMD\", \"JOD\", \"JPY\",\n\t\"KES\", \"KGS\", \"KHR\", \"KMF\", \"KPW\", \"KRW\", \"KWD\", \"KYD\", \"KZT\",\n\t\"LAK\", \"LBP\", \"LKR\", \"LRD\", \"LSL\", \"LYD\",\n\t\"MAD\", \"MDL\", \"MGA\", \"MKD\", \"MMK\", \"MNT\", \"MOP\", \"MRU\", \"MUR\", \"MVR\",\n\t\"MWK\", \"MXN\", \"MXV\", \"MYR\", \"MZN\",\n\t\"NAD\", \"NGN\", \"NIO\", \"NOK\", \"NPR\", \"NZD\",\n\t\"OMR\",\n\t\"PAB\", \"PEN\", \"PGK\", \"PHP\", \"PKR\", \"PLN\", \"PYG\",\n\t\"QAR\",\n\t\"RON\", \"RSD\", \"RUB\", \"RWF\",\n\t\"SAR\", \"SBD\", \"SCR\", \"SDG\", \"SEK\", \"SGD\", \"SHP\", \"SLE\", \"SOS\", \"SRD\",\n\t\"SSP\", \"STN\", \"SVC\", \"SYP\", \"SZL\",\n\t\"THB\", \"TJS\", \"TMT\", \"TND\", \"TOP\", \"TRY\", \"TTD\", \"TWD\", \"TZS\",\n\t\"UAH\", \"UGX\", \"USD\", \"USN\", \"UYI\", \"UYU\", \"UYW\", \"UZS\",\n\t\"VED\", \"VES\", \"VND\", \"VUV\",\n\t\"WST\",\n\t\"XAF\", \"XCD\", \"XCG\", \"XOF\", \"XPF\",\n\t\"YER\",\n\t\"ZAR\", \"ZMW\", \"ZWG\",\n]);\n\n/**\n * Whether `code` is an active ISO 4217 currency code.\n *\n * @param code - A three-letter code, in any case.\n */\nexport function isIso4217(code: string): boolean {\n\treturn ISO_4217_CODES.has(code.toUpperCase());\n}\n","/**\n * Production-grade currency exchange service with scalable architecture\n * Integrates with DataQueryService for worker-based execution\n */\n\nimport { isIso4217 } from \"@solve-js/uom/Iso4217\";\nimport { createTimeoutSignal } from \"@solve-js/utilities/TimeoutSignal\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Error codes for this service. Co-located rather than unioned into\n * `errors/ErrorCode.ts`'s core catalog (that catalog is scoped to the\n * parser/VM/engine/errors/config/lexer layers, not yet the ~17 domain\n * packages. See that file's module doc for the intended per-package\n * pattern this follows).\n */\nexport const CurrencyErrorCodes = {\n /** Frankfurter's rates endpoint returned a non-OK HTTP status. */\n API_ERROR: \"CURRENCY_API_ERROR\",\n /** A requested currency/crypto code isn't in the fetched rate table, an unrecognized code, not an API failure. */\n UNKNOWN_CODE: \"UNKNOWN_CURRENCY_CODE\",\n /** CoinGecko's simple-price endpoint returned a non-OK HTTP status. */\n CRYPTO_API_ERROR: \"CRYPTO_PRICE_API_ERROR\",\n} as const;\n\n// ============================================================================\n// CURRENCY EXCHANGE SERVICE\n// ============================================================================\n\n/**\n * Caches exchange rates fetched from an external source.\n *\n * Rates are global market data rather than per-engine configuration, which is\n * why one instance is shared. Two engines with private copies would fetch the\n * same endpoint twice and could disagree about one pair at one moment. See\n * `engine/EngineContext.ts`.\n */\nexport class CurrencyExchangeService {\n /**\n * Live rate tables cached from successful getRate() fetches, keyed by\n * uppercase base currency. Each table holds every rate the API returned\n * for that base (plus the base itself at 1), so any pair whose two codes\n * appear in one fresh table can be served synchronously, including\n * cross pairs via triangulation (EUR→GBP through a USD-base table).\n * Stale tables are ignored, not evicted; the next successful fetch for\n * the same base overwrites them.\n */\n private baseTables: Map<string, { fetchedAt: number; rates: Record<string, number> }> = new Map();\n\n /**\n * How long a fetched rate may be served synchronously by getRateSync().\n * Beyond this window callers fall through to the async path (expression\n * shows Pending until the fetch lands).\n */\n private static readonly RATE_FRESHNESS_MS = 15 * 60 * 1000;\n\n /**\n * Ticker → CoinGecko coin id, for the cryptocurrencies `isCurrency()`\n * recognizes. Frankfurter (the fiat rate source below) is ECB reference\n * rates only and has no concept of BTC/ETH/etc, routing a crypto code\n * through it as `base=BTC` fails outright, which is why crypto pairs\n * previously never resolved (see CurrencyAsyncResolver/VM.ts's ADD\n * handling for the two bugs that let that failure pass silently instead\n * of surfacing as a real fetch).\n */\n private static readonly CRYPTO_IDS: Record<string, string> = {\n BTC: \"bitcoin\", ETH: \"ethereum\", SOL: \"solana\", XRP: \"ripple\",\n ADA: \"cardano\", DOGE: \"dogecoin\", DOT: \"polkadot\",\n };\n\n private isCryptoCode(code: string): boolean {\n return code.toUpperCase() in CurrencyExchangeService.CRYPTO_IDS;\n }\n\n constructor() {}\n\n // ------------------------------------------------------------------------\n // RATE FETCHING\n // ------------------------------------------------------------------------\n\n /**\n * Timeout (ms) for currency exchange rate fetches.\n *\n * If the frankfurter API doesn't respond within this window, the fetch\n * is aborted, preventing indefinite \"Pending\" states in the playground\n * and Obsidian plugin when the exchange rate API is unreachable.\n */\n private static readonly FETCH_TIMEOUT_MS = 10_000;\n\n /**\n * Fetch the live exchange rate for converting 1 unit of `from` into `to`.\n *\n * Routes cryptocurrency codes (see {@link CRYPTO_IDS}) to CoinGecko and\n * everything else to Frankfurter (ECB reference rates, fiat-only). On\n * success, caches the whole returned rate table for `from` so subsequent\n * lookups, including cross-pairs via triangulation, can be served\n * synchronously by {@link getRateSync} within the freshness window.\n *\n * @throws If the currency code is unrecognized or the fetch fails/times out.\n */\n async getRate(from: string, to: string, signal?: AbortSignal): Promise<number> {\n const fromUpper = from.toUpperCase();\n const toUpper = to.toUpperCase();\n\n if (this.isCryptoCode(fromUpper) || this.isCryptoCode(toUpper)) {\n return this.getCryptoRate(fromUpper, toUpper, signal);\n }\n\n // Combine the caller's optional abort signal with a hard timeout so a\n // hanging currency API never blocks re-evaluation indefinitely.\n const { signal: fetchSignal, cleanup } = createTimeoutSignal(\n signal,\n CurrencyExchangeService.FETCH_TIMEOUT_MS,\n \"Currency API fetch\",\n );\n\n try {\n const response = await fetch(`https://api.frankfurter.dev/v2/rates?base=${fromUpper}`, { signal: fetchSignal });\n if (!response.ok) throw ErrorFactory.external(CurrencyErrorCodes.API_ERROR, `Currency API returned ${response.status}`, { status: response.status });\n const data = await response.json();\n // The v2 endpoint returns a flat array of { date, base, quote, rate }\n // entries (one per target currency) rather than the classic v1 shape\n // { base, date, rates: { CODE: rate } }. Reading data.rates against\n // the real response is always undefined, so every conversion used to\n // throw \"Unknown currency\" no matter which currencies were requested.\n // Accept both shapes so a future API revision back to the object form\n // doesn't silently break this again.\n const rates: Record<string, number> = Array.isArray(data)\n ? Object.fromEntries(\n data\n .filter((entry: unknown): entry is { quote: string; rate: number } => {\n if (typeof entry !== \"object\" || entry === null) return false;\n const candidate = entry as { quote?: unknown; rate?: unknown };\n return typeof candidate.quote === \"string\" && typeof candidate.rate === \"number\";\n })\n .map((entry: { quote: string; rate: number }) => [entry.quote.toUpperCase(), entry.rate])\n )\n : (data.rates ?? {});\n if (rates[toUpper] === undefined) throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n\n // The API returns ALL rates for the base currency, cache the whole\n // table so subsequent conversions (including cross pairs via\n // triangulation) resolve synchronously within the freshness window\n // instead of going Pending again.\n this.baseTables.set(fromUpper, {\n fetchedAt: Date.now(),\n rates: { ...rates, [fromUpper]: 1 },\n });\n\n return rates[toUpper];\n } finally {\n cleanup();\n }\n }\n\n /**\n * Crypto rate fetch, routed through CoinGecko's no-auth simple-price\n * endpoint instead of Frankfurter (fiat-only, has no BTC/ETH concept).\n * Handles all three combinations, crypto→crypto, crypto→fiat\n * fiat→crypto, via prices denominated in USD (or the target fiat\n * directly, which CoinGecko's `vs_currencies` also accepts), then\n * caches the result as a same-shaped base table so getRateSync /\n * convertSync keep working unchanged for crypto pairs too.\n */\n private async getCryptoRate(fromUpper: string, toUpper: string, signal?: AbortSignal): Promise<number> {\n const { signal: fetchSignal, cleanup } = createTimeoutSignal(\n signal,\n CurrencyExchangeService.FETCH_TIMEOUT_MS,\n \"Crypto price API fetch\",\n );\n\n try {\n const fromIsCrypto = this.isCryptoCode(fromUpper);\n const toIsCrypto = this.isCryptoCode(toUpper);\n let rate: number;\n\n if (fromIsCrypto && toIsCrypto) {\n const fromId = CurrencyExchangeService.CRYPTO_IDS[fromUpper];\n const toId = CurrencyExchangeService.CRYPTO_IDS[toUpper];\n const data = await this.fetchCoinGeckoPrices([fromId, toId], \"usd\", fetchSignal);\n const fromUsd = data[fromId]?.usd;\n const toUsd = data[toId]?.usd;\n if (typeof fromUsd !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${fromUpper}`, { code: fromUpper });\n if (typeof toUsd !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n rate = fromUsd / toUsd;\n } else if (fromIsCrypto) {\n const fromId = CurrencyExchangeService.CRYPTO_IDS[fromUpper];\n const vs = toUpper.toLowerCase();\n const data = await this.fetchCoinGeckoPrices([fromId], vs, fetchSignal);\n const value = data[fromId]?.[vs];\n if (typeof value !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n rate = value;\n } else {\n const toId = CurrencyExchangeService.CRYPTO_IDS[toUpper];\n const vs = fromUpper.toLowerCase();\n const data = await this.fetchCoinGeckoPrices([toId], vs, fetchSignal);\n const priceOfToInFrom = data[toId]?.[vs];\n if (typeof priceOfToInFrom !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${fromUpper}`, { code: fromUpper });\n rate = 1 / priceOfToInFrom;\n }\n\n // Cache as a single-pair base table, same shape Frankfurter fetches\n // produce, so getRateSync/convertSync's triangulation logic doesn't\n // need to know or care which source a rate came from.\n this.baseTables.set(fromUpper, {\n fetchedAt: Date.now(),\n rates: { [fromUpper]: 1, [toUpper]: rate },\n });\n\n return rate;\n } finally {\n cleanup();\n }\n }\n\n private async fetchCoinGeckoPrices(ids: string[], vsCurrency: string, signal: AbortSignal): Promise<Record<string, Record<string, number>>> {\n const url = `https://api.coingecko.com/api/v3/simple/price?ids=${ids.join(\",\")}&vs_currencies=${vsCurrency}`;\n const response = await fetch(url, { signal });\n if (!response.ok) throw ErrorFactory.external(CurrencyErrorCodes.CRYPTO_API_ERROR, `Crypto price API returned ${response.status}`, { status: response.status });\n return response.json();\n }\n\n /**\n * Seed a base rate table without a network fetch.\n *\n * Intended for tests and for future user-provided offline rates\n * production live data always comes from {@link getRate}. Seeded rates\n * obey the same freshness window as fetched ones.\n *\n * @param base - Base currency code (e.g. \"USD\").\n * @param rates - Map of currency code → rate relative to the base.\n */\n primeRates(base: string, rates: Record<string, number>): void {\n const baseUpper = base.toUpperCase();\n this.baseTables.set(baseUpper, {\n fetchedAt: Date.now(),\n rates: { ...rates, [baseUpper]: 1 },\n });\n }\n\n /**\n * Drop every cached/primed rate table.\n *\n * Mainly for test isolation: {@link sharedCurrencyExchange} is a\n * module-level singleton, so a rate primed or fetched by one test can\n * silently leak into a later test in the same file. Also usable in\n * production if a caller ever wants to force a full re-fetch.\n */\n clearRates(): void {\n this.baseTables.clear();\n }\n\n /**\n * Synchronous rate lookup: `1` for same-currency pairs, a cached LIVE\n * rate if one was fetched within {@link RATE_FRESHNESS_MS}, otherwise\n * `null`, callers fall through to the async fetch path and the\n * expression shows Pending until real data arrives.\n *\n * There is deliberately no hardcoded fallback table: a stale made-up\n * rate presented as a real conversion is worse than a Pending state.\n */\n getRateSync(from: string, to: string): number | null {\n const fromUpper = from.toUpperCase();\n const toUpper = to.toUpperCase();\n if (fromUpper === toUpper) {\n return 1;\n }\n const now = Date.now();\n for (const table of this.baseTables.values()) {\n if (now - table.fetchedAt > CurrencyExchangeService.RATE_FRESHNESS_MS) continue;\n const fromRate = table.rates[fromUpper];\n const toRate = table.rates[toUpper];\n if (fromRate && toRate) {\n return toRate / fromRate;\n }\n }\n return null;\n }\n\n /** Convert `value` from `from` to `to` using a freshly-fetched live rate (see {@link getRate}). */\n async convert(value: number, from: string, to: string): Promise<number> {\n const rate = await this.getRate(from, to);\n return value * rate;\n }\n\n /**\n * Get all currently cached fresh rates, keyed \"FROM:TO\".\n * @returns Snapshot of fresh live rates, or null when none are cached.\n */\n getAllRates(): Record<string, number> | null {\n const now = Date.now();\n const snapshot: Record<string, number> = {};\n let any = false;\n for (const [base, table] of this.baseTables) {\n if (now - table.fetchedAt > CurrencyExchangeService.RATE_FRESHNESS_MS) continue;\n for (const [code, rate] of Object.entries(table.rates)) {\n snapshot[`${base}:${code}`] = rate;\n any = true;\n }\n }\n return any ? snapshot : null;\n }\n\n /**\n * Check whether any fresh live rates are currently cached.\n */\n hasRates(): boolean {\n return this.getAllRates() !== null;\n }\n\n /**\n * Synchronous conversion using cached rates only\n * Returns null if rate not in cache\n */\n convertSync(value: number, from: string, to: string): number | null {\n const rate = this.getRateSync(from, to);\n if (rate === null) return null;\n return value * rate;\n }\n\n // ------------------------------------------------------------------------\n // CURRENCY VALIDATION\n // ------------------------------------------------------------------------\n\n /**\n * Check whether `code` is a recognized currency code: any active ISO 4217\n * code, or one of the cryptocurrencies in {@link CRYPTO_IDS}.\n *\n * This used to be a hand-written list of forty-six codes, which meant\n * `$100 in UAH` returned an unconverted hundred dollars rather than saying\n * it could not convert. Answering from the standard rather than from\n * whichever codes happened to get added is what stops that class of bug.\n *\n * Recognising a code is not the same as having a rate for it. That is\n * answered later, by the exchange provider; conflating the two is what\n * produced the silent failure.\n */\n isCurrency(code: string): boolean {\n return isIso4217(code) || this.isCryptoCode(code);\n }\n}\n\n// ============================================================================\n// SINGLETON INSTANCE\n// ============================================================================\n\n/** The shared rate cache. See {@link CurrencyExchangeService} for why it is shared. */\nexport const currencyExchangeService = new CurrencyExchangeService();\n\n// Export for backward compatibility\n/** Alias for {@link currencyExchangeService}, kept for older imports. */\nexport const sharedCurrencyExchange = currencyExchangeService;\n\n// Default export\nexport default currencyExchangeService;\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/resolvers/ResolverRegistry.ts"],"names":["ResolverRegistry","resolver","namespace","queryClient","tokens","bytecode","packageId","signal","result"],"mappings":"AAqFO,IAAMA,EAAN,KAAuB,CAAvB,WAAA,EAAA,CACN,IAAA,CAAQ,UAAY,IAAI,IAAA,CAWxB,QAAA,CAASC,CAAAA,CAAgC,CAEpC,IAAA,CAAK,SAAA,CAAU,GAAA,CAAIA,CAAAA,CAAS,SAAS,CAAA,GACxC,OAAA,CAAQ,IAAA,CACP,CAAA,8BAAA,EAAiCA,EAAS,SAAS,CAAA,+FAAA,EAExCA,CAAAA,CAAS,SAAS,YAAYA,CAAAA,CAAS,SAAS,CAAA,0EAAA,CAE5D,CAAA,CACA,KAAK,SAAA,CAAU,GAAA,CAAIA,CAAAA,CAAS,SAAS,EAAG,OAAA,EAAQ,CAAA,CAEjD,IAAA,CAAK,SAAA,CAAU,IAAIA,CAAAA,CAAS,SAAA,CAAWA,CAAQ,EAChD,CAMA,UAAA,CAAWC,CAAAA,CAAmBC,CAAAA,CAAiC,CAC9D,IAAMF,CAAAA,CAAW,IAAA,CAAK,SAAA,CAAU,GAAA,CAAIC,CAAS,CAAA,CACzCD,CAAAA,GACHA,CAAAA,CAAS,OAAA,GACT,IAAA,CAAK,SAAA,CAAU,MAAA,CAAOC,CAAS,GAI5BC,CAAAA,EACHA,CAAAA,CAAY,aAAA,CAAc,CAAE,SAAU,CAACD,CAAS,CAAE,CAAC,EAErD,CASA,YAAA,CAAaE,CAAAA,CAAiBC,CAAAA,CAA2BC,EAAmBC,CAAAA,CAAqBJ,CAAAA,CAAmD,CACnJ,IAAA,IAAWF,KAAY,IAAA,CAAK,SAAA,CAAU,MAAA,EAAO,CAAG,CAC/C,GAAI,CAACA,CAAAA,CAAS,SAAA,CAAW,SACzB,IAAMO,CAAAA,CAASP,CAAAA,CAAS,SAAA,CAAUG,EAAQC,CAAAA,CAAUC,CAAAA,CAAWC,CAAAA,CAAQJ,CAAW,EAClF,GAAIK,CAAAA,CAAQ,OAAOA,CACpB,CACA,OAAO,IACR,CAMA,GAAA,CAAIN,EAA+C,CAClD,OAAO,IAAA,CAAK,SAAA,CAAU,IAAIA,CAAS,CACpC,CAGA,IAAI,MAAe,CAClB,OAAO,IAAA,CAAK,SAAA,CAAU,IACvB,CAKA,GAAA,CAAIA,CAAAA,CAA4B,CAC/B,OAAO,IAAA,CAAK,SAAA,CAAU,GAAA,CAAIA,CAAS,CACpC,CAMA,KAAA,EAAc,CACb,IAAA,IAAWD,KAAY,IAAA,CAAK,SAAA,CAAU,MAAA,EAAO,CAC5CA,EAAS,OAAA,EAAQ,CAElB,KAAK,SAAA,CAAU,KAAA,GAChB,CACD","file":"chunk-7E7NXKQ5.js","sourcesContent":["import type { QueryClient } from \"@tanstack/query-core\";\nimport type { Token } from \"@solve-js/lexer\";\nimport type { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport type { Value } from \"@solve-js/vm/Value\";\n\n/**\n * Result from a resolver's preflight() check.\n * Returned when async data is needed, the orchestrator uses this\n * to subscribe to the resolver and return a Pending value immediately.\n */\nexport interface AsyncCheckResult {\n\t/** Unique cache key for deduplication (e.g., \"{packageId}:rates:USD:GBP\") */\n\tqueryKey: string;\n\t/** Promise that resolves to the final Value */\n\tresolver: Promise<Value>;\n\t/** Package owning this resolver */\n\tpackageId: string;\n\t/** AbortSignal for stale-data prevention */\n\tsignal: AbortSignal;\n\t/** Optional metadata for diagnostics */\n\tmetadata?: Record<string, unknown>;\n\t/**\n\t * Cadence, in ms, at which this value wants proactive background refresh\n\t * (a live quote every minute, an FX rate every few minutes). Absent, or\n\t * paired with no {@link refetch}, means pull-only: the value refreshes on\n\t * re-evaluation, never on its own. Only acted on when the host has enabled\n\t * background refresh; see {@link BackgroundRefreshConfig}.\n\t */\n\trefetchIntervalMs?: number;\n\t/**\n\t * Force a fresh fetch of this exact query, bypassing `staleTime`, and return\n\t * the new value. Supplied alongside {@link refetchIntervalMs} so the engine\n\t * can drive the background refresh without re-scanning bytecode.\n\t */\n\trefetch?: () => Promise<Value>;\n}\n\n/**\n * Interface for async resolvers registered by packages/plugins.\n *\n * Each resolver handles a domain of async data (currency rates,\n * weather, stock prices, etc.). The preflight() method is called\n * BEFORE VM execution to check if all data is cached. If not,\n * it returns an AsyncCheckResult and the engine skips the VM,\n * returning a Pending value instead.\n */\nexport interface IAsyncResolver {\n\t/** Unique namespace for cache key scoping (e.g., \"currency\", \"weather\") */\n\treadonly namespace: string;\n\n\t/**\n\t * Pre-flight check: called BEFORE VM execution.\n\t *\n\t * Returns null if all data for this expression is cached and ready.\n\t * Returns an AsyncCheckResult if async work is needed.\n\t *\n\t * This method is synchronous, it only checks caches, never fetches.\n\t * If data is missing, it creates a Promise and returns immediately.\n\t *\n\t * @param tokens - The lexed tokens for the expression\n\t * @param bytecode - The compiled bytecode program\n\t * @param pluginId - The plugin ID (for cache key scoping)\n\t * @param signal - AbortSignal for the current evaluation\n\t */\n\tpreflight?(tokens: Token[], bytecode: BytecodeProgram, packageId: string, signal: AbortSignal, queryClient: QueryClient): AsyncCheckResult | null;\n\n\t/**\n\t * Called when the resolver's namespace is being unregistered.\n\t * Clean up any in-flight promises, clear caches, unsubscribe.\n\t */\n\tdestroy(): void;\n}\n\n/**\n * Registry of async resolvers, keyed by namespace.\n *\n * Plugins/packages register resolvers alongside their parselets\n * and opcode handlers. The engine calls preflightAll() before\n * VM execution to short-circuit async expressions.\n *\n * Lifecycle:\n * - register(), when a package is loaded\n * - unregister(), when a package is unloaded (clears cache entries)\n * - clear(), on document switch (clears all resolvers)\n */\nexport class ResolverRegistry {\n\tprivate resolvers = new Map<string, IAsyncResolver>();\n\n\t/**\n\t * Register an async resolver.\n\t *\n\t * Each resolver must have a unique `namespace`. If a resolver with the\n\t * same namespace is already registered, the old one is destroyed and\n\t * replaced (with a console warning). Packages that need multiple async\n\t * operations should use `asyncResolvers: [...]` with distinct namespaces\n\t * (e.g., `\"weather:current\"`, `\"weather:forecast\"`).\n\t */\n\tregister(resolver: IAsyncResolver): void {\n\t\t// Clean up previous resolver with same namespace if any\n\t\tif (this.resolvers.has(resolver.namespace)) {\n\t\t\tconsole.warn(\n\t\t\t\t`[ResolverRegistry] Namespace \"${resolver.namespace}\" already registered. ` +\n\t\t\t\t`Destroying old resolver and overwriting. Use distinct namespaces ` +\n\t\t\t\t`(e.g., \"${resolver.namespace}:sub1\", \"${resolver.namespace}:sub2\") ` +\n\t\t\t\t`to avoid collisions when a package needs multiple async resolvers.`,\n\t\t\t);\n\t\t\tthis.resolvers.get(resolver.namespace)!.destroy();\n\t\t}\n\t\tthis.resolvers.set(resolver.namespace, resolver);\n\t}\n\n\t/**\n\t * Unregister a resolver by namespace.\n\t * Calls destroy() and clears all cache entries with that namespace prefix.\n\t */\n\tunregister(namespace: string, queryClient?: QueryClient): void {\n\t\tconst resolver = this.resolvers.get(namespace);\n\t\tif (resolver) {\n\t\t\tresolver.destroy();\n\t\t\tthis.resolvers.delete(namespace);\n\t\t}\n\t\t// Clear all cache entries for this namespace via TanStack Query\n\t\t// Hierarchical keys: [\"osrs\"] clears all [\"osrs\", ...] queries\n\t\tif (queryClient) {\n\t\t\tqueryClient.removeQueries({ queryKey: [namespace] });\n\t\t}\n\t}\n\n\t/**\n\t * Run all registered resolvers' preflight checks against compiled bytecode.\n\t *\n\t * Returns the first AsyncCheckResult found, or null if all data is ready.\n\t * Short-circuits on first pending, subsequent pending ops will be\n\t * discovered on re-evaluation when the first resolves.\n\t */\n\tpreflightAll(tokens: Token[], bytecode: BytecodeProgram, packageId: string, signal: AbortSignal, queryClient: QueryClient): AsyncCheckResult | null {\n\t\tfor (const resolver of this.resolvers.values()) {\n\t\t\tif (!resolver.preflight) continue;\n\t\t\tconst result = resolver.preflight(tokens, bytecode, packageId, signal, queryClient);\n\t\t\tif (result) return result;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Get a resolver by namespace.\n\t * Returns undefined if no resolver is registered for that namespace.\n\t */\n\tget(namespace: string): IAsyncResolver | undefined {\n\t\treturn this.resolvers.get(namespace);\n\t}\n\n\t/** Number of registered resolvers. */\n\tget size(): number {\n\t\treturn this.resolvers.size;\n\t}\n\n\t/**\n\t * Check if a resolver is registered for the given namespace.\n\t */\n\thas(namespace: string): boolean {\n\t\treturn this.resolvers.has(namespace);\n\t}\n\n\t/**\n\t * Clear all resolvers (document switch, engine reset).\n\t * Calls destroy() on each resolver and clears the map.\n\t */\n\tclear(): void {\n\t\tfor (const resolver of this.resolvers.values()) {\n\t\t\tresolver.destroy();\n\t\t}\n\t\tthis.resolvers.clear();\n\t}\n}\n"]}
|
package/dist/chunk-7SZBEE5R.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkCO2BI6WL_cjs=require('./chunk-CO2BI6WL.cjs');var d="2.23.0";var m=d;var l={date:{maxOffsetYears:100,minOffsetYears:-100,defaultFormat:"YYYY-MM-DD",inputOrder:"auto"},performance:{defaultCacheSize:2e3,maxDocumentLines:1e5},validation:{maxExpressionLength:2e3,maxComplexity:500,maxNestingDepth:50,autoBalanceParens:false},vm:{maxStackDepth:200,maxInstructions:5e4,maxCollectionSize:1e5,maxAllocatedElements:2e6,maxFunctionCalls:1e4,maxGoalSeekIterations:100},worker:{maxConcurrentWorkers:4,idleTimeoutMs:3e4,maxRetries:3,baseBackoffMs:1e3},diagnostic:{enabled:false,vmTraceEnabled:false},backgroundRefresh:{enabled:false}};function r(s,e){return {date:{...s.date,...e.date},performance:{...s.performance,...e.performance},validation:{...s.validation,...e.validation},vm:{...s.vm,...e.vm},worker:{...s.worker,...e.worker},diagnostic:{...s.diagnostic,...e.diagnostic},backgroundRefresh:{...s.backgroundRefresh,...e.backgroundRefresh}}}var c=class{constructor(e={}){this.config=r(l,e);}get(e){let o=e.split("."),t=this.config;for(let i of o)if(t&&typeof t=="object"&&i in t)t=t[i];else throw chunkCO2BI6WL_cjs.c.config("CONFIG_PATH_NOT_FOUND",`Configuration path not found: ${e}`,{path:e});return t}set(e,o){let t=e.split(".");if(t.length<2)throw chunkCO2BI6WL_cjs.c.config("INVALID_CONFIG_PATH",`Invalid path: ${e}. Must be in format 'section.property'`,{path:e});let i=t[0],u=t[1];if(!(i in this.config))throw chunkCO2BI6WL_cjs.c.config("CONFIG_SECTION_NOT_FOUND",`Configuration section not found: ${i}`,{section:i,path:e});let a=this.config[i];if(a&&typeof a=="object")a[u]=o;else throw chunkCO2BI6WL_cjs.c.config("CONFIG_PROPERTY_NOT_FOUND",`Configuration property not found: ${e}`,{path:e})}getConfig(){return r(this.config,{})}update(e){this.config=r(this.config,e);}reset(){this.config=r(l,{});}validate(){let e=[];return this.config.performance.maxDocumentLines>1e5&&e.push("maxDocumentLines cannot exceed 100,000"),this.config.date.maxOffsetYears>1e3&&e.push("maxOffsetYears cannot exceed 1000"),{valid:e.length===0,error:e.join("; "),warnings:[]}}};exports.a=m;exports.b=l;exports.c=r;exports.d=c;//# sourceMappingURL=chunk-7SZBEE5R.cjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-7SZBEE5R.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../package.json","../src/constants/version.ts","../src/constants/Configuration.ts"],"names":["version","ENGINE_VERSION","DEFAULT_CONFIG","mergeEngineConfig","base","override","ConfigManager","config","path","keys","current","key","ErrorFactory","value","section","property","sectionConfig","errors"],"mappings":"mEAEE,IAAAA,EAAW,QAAA,CCcN,IAAMC,EAAyBD,ECkV/B,IAAME,EAA+B,CACzC,IAAA,CAAM,CAIJ,cAAA,CAAgB,IAChB,cAAA,CAAgB,IAAA,CAChB,cAAe,YAAA,CACf,UAAA,CAAY,MACd,CAAA,CACA,WAAA,CAAa,CAIX,gBAAA,CAAkB,IAalB,gBAAA,CAAkB,GACpB,EACC,UAAA,CAAY,CACV,oBAAqB,GAAA,CACrB,aAAA,CAAe,IACf,eAAA,CAAiB,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EAAE,CAC1C,CAKA,MAAA,CAAOI,EAAqC,CAC1C,IAAA,CAAK,OAASJ,CAAAA,CAAkB,IAAA,CAAK,OAAQI,CAAM,EACrD,CAcA,KAAA,EAAc,CACZ,KAAK,MAAA,CAASJ,CAAAA,CAAkBD,CAAAA,CAAgB,EAAE,EACpD,CAKA,UAA6B,CAC3B,IAAMe,EAAmB,EAAC,CAG1B,OAAI,IAAA,CAAK,MAAA,CAAO,YAAY,gBAAA,CAAmB,GAAA,EAC7CA,EAAO,IAAA,CAAK,wCAAwC,EAIlD,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,cAAA,CAAiB,KACpCA,CAAAA,CAAO,IAAA,CAAK,mCAAmC,CAAA,CAG1C,CACL,MAAOA,CAAAA,CAAO,MAAA,GAAW,EACzB,KAAA,CAAOA,CAAAA,CAAO,KAAK,IAAI,CAAA,CACvB,SAAU,EACZ,CACF,CACF","file":"chunk-7SZBEE5R.cjs","sourcesContent":["{\n \"name\": \"solve-engine\",\n \"version\": \"2.23.0\",\n \"description\": \"An embeddable expression engine for natural-language calculations: units, currencies, percentages, dates and matrices, with the parsing and evaluation plumbing already built.\",\n \"keywords\": [\n \"expression-evaluator\",\n \"calculator\",\n \"bytecode-vm\",\n \"parser\",\n \"lexer\",\n \"dsl\",\n \"markdown\",\n \"obsidian\"\n ],\n \"license\": \"MIT\",\n \"author\": \"Liam Riddell\",\n \"homepage\": \"https://liamriddell.github.io/solve-engine/\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/LiamRiddell/solve-engine.git\",\n \"directory\": \"packages/engine\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/LiamRiddell/solve-engine/issues\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=22\"\n },\n \"files\": [\n \"dist\",\n \"LICENSE\"\n ],\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./engine\": {\n \"import\": {\n \"types\": \"./dist/engine.d.ts\",\n \"default\": \"./dist/engine.js\"\n },\n \"require\": {\n \"types\": \"./dist/engine.d.cts\",\n \"default\": \"./dist/engine.cjs\"\n }\n },\n \"./vm\": {\n \"import\": {\n \"types\": \"./dist/vm.d.ts\",\n \"default\": \"./dist/vm.js\"\n },\n \"require\": {\n \"types\": \"./dist/vm.d.cts\",\n \"default\": \"./dist/vm.cjs\"\n }\n },\n \"./format\": {\n \"import\": {\n \"types\": \"./dist/format.d.ts\",\n \"default\": \"./dist/format.js\"\n },\n \"require\": {\n \"types\": \"./dist/format.d.cts\",\n \"default\": \"./dist/format.cjs\"\n }\n },\n \"./language\": {\n \"import\": {\n \"types\": \"./dist/language.d.ts\",\n \"default\": \"./dist/language.js\"\n },\n \"require\": {\n \"types\": \"./dist/language.d.cts\",\n \"default\": \"./dist/language.cjs\"\n }\n },\n \"./packages\": {\n \"import\": {\n \"types\": \"./dist/packages.d.ts\",\n \"default\": \"./dist/packages.js\"\n },\n \"require\": {\n \"types\": \"./dist/packages.d.cts\",\n \"default\": \"./dist/packages.cjs\"\n }\n },\n \"./constants\": {\n \"import\": {\n \"types\": \"./dist/constants.d.ts\",\n \"default\": \"./dist/constants.js\"\n },\n \"require\": {\n \"types\": \"./dist/constants.d.cts\",\n \"default\": \"./dist/constants.cjs\"\n }\n },\n \"./lexer\": {\n \"import\": {\n \"types\": \"./dist/lexer.d.ts\",\n \"default\": \"./dist/lexer.js\"\n },\n \"require\": {\n \"types\": \"./dist/lexer.d.cts\",\n \"default\": \"./dist/lexer.cjs\"\n }\n },\n \"./parser\": {\n \"import\": {\n \"types\": \"./dist/parser.d.ts\",\n \"default\": \"./dist/parser.js\"\n },\n \"require\": {\n \"types\": \"./dist/parser.d.cts\",\n \"default\": \"./dist/parser.cjs\"\n }\n },\n \"./normalizer\": {\n \"import\": {\n \"types\": \"./dist/normalizer.d.ts\",\n \"default\": \"./dist/normalizer.js\"\n },\n \"require\": {\n \"types\": \"./dist/normalizer.d.cts\",\n \"default\": \"./dist/normalizer.cjs\"\n }\n },\n \"./resolvers\": {\n \"import\": {\n \"types\": \"./dist/resolvers.d.ts\",\n \"default\": \"./dist/resolvers.js\"\n },\n \"require\": {\n \"types\": \"./dist/resolvers.d.cts\",\n \"default\": \"./dist/resolvers.cjs\"\n }\n },\n \"./errors\": {\n \"import\": {\n \"types\": \"./dist/errors.d.ts\",\n \"default\": \"./dist/errors.js\"\n },\n \"require\": {\n \"types\": \"./dist/errors.d.cts\",\n \"default\": \"./dist/errors.cjs\"\n }\n },\n \"./utilities\": {\n \"import\": {\n \"types\": \"./dist/utilities.d.ts\",\n \"default\": \"./dist/utilities.js\"\n },\n \"require\": {\n \"types\": \"./dist/utilities.d.cts\",\n \"default\": \"./dist/utilities.cjs\"\n }\n },\n \"./uom\": {\n \"import\": {\n \"types\": \"./dist/uom.d.ts\",\n \"default\": \"./dist/uom.js\"\n },\n \"require\": {\n \"types\": \"./dist/uom.d.cts\",\n \"default\": \"./dist/uom.cjs\"\n }\n },\n \"./services\": {\n \"import\": {\n \"types\": \"./dist/services.d.ts\",\n \"default\": \"./dist/services.js\"\n },\n \"require\": {\n \"types\": \"./dist/services.d.cts\",\n \"default\": \"./dist/services.cjs\"\n }\n },\n \"./worker\": {\n \"import\": {\n \"types\": \"./dist/worker.d.ts\",\n \"default\": \"./dist/worker.js\"\n },\n \"require\": {\n \"types\": \"./dist/worker.d.cts\",\n \"default\": \"./dist/worker.cjs\"\n }\n },\n \"./testing\": {\n \"import\": {\n \"types\": \"./dist/testing.d.ts\",\n \"default\": \"./dist/testing.js\"\n },\n \"require\": {\n \"types\": \"./dist/testing.d.cts\",\n \"default\": \"./dist/testing.cjs\"\n }\n }\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"prepublishOnly\": \"npm run build && node ../../scripts/assert-publishable.mjs .\",\n \"dev\": \"tsup --watch\",\n \"test\": \"jest --config jest.config.cjs --no-coverage\",\n \"typecheck\": \"tsgo --noEmit --skipLibCheck\",\n \"typecheck:tsc\": \"tsc --noEmit --skipLibCheck\"\n },\n \"dependencies\": {\n \"@tanstack/query-core\": \"^5.100.10\"\n },\n \"devDependencies\": {\n \"@jest/globals\": \"^30.4.1\",\n \"@types/node\": \"^26.2.0\",\n \"convert\": \"^7.0.0\",\n \"jest\": \"^30.4.2\",\n \"ts-jest\": \"^29.4.12\",\n \"tsup\": \"8.5.1\",\n \"typescript\": \"5.9.3\"\n },\n \"//sideEffects\": \"Load-bearing claim, not boilerplate. tsup's splitting emits bare chunk imports at the top of dist/index.js, and this field tells Rollup, webpack and Vite they may delete them, which esbuild reports as [ignored-bare-import] once per import during `npm run size`. The engine does have module-level work to lose: registerAllTokenTypes(), _PrecedenceParser.BP_TABLE and its cached token ids, and several process-wide registries. It is safe because every chunk doing that work is also imported for its bindings somewhere, so no bundler can drop it. That is a property of how tsup currently splits the code rather than a design guarantee, so `npm run smoke:bundled` (scripts/check-tree-shaking.mjs) proves it on every run of `npm run verify` instead of assuming it, and its header explains the two fixes if it ever stops holding.\",\n \"sideEffects\": false\n}\n","/**\n * The running engine's own semver version, sourced directly from this\n * package's package.json so it can never drift from what's actually\n * published. Exists so IEnginePackage.engineVersion range checks\n * (api/EngineVersionCompatibility.ts) have something real to check\n * against.\n */\nimport { version } from \"../../package.json\";\n\n/**\n * The running engine's version, taken from package.json.\n *\n * What a package's `engineVersion` range is checked against at registration.\n * A prerelease is compared by its coerced release version, so a 1.0.0 beta\n * satisfies `^1.0.0`. See `api/EngineVersionCompatibility.ts`.\n */\nexport const ENGINE_VERSION: string = version;\n","/**\n * Configuration Module for solve-js Engine\n * \n * This module provides the **single source of truth** for all engine configuration.\n * Every configurable aspect of the engine, from safety limits and performance\n * budgets to VM constraints and worker pool sizing, is defined here.\n * \n * ### Design principles\n * \n * 1. **Engine owns its config.** The engine defines its own config shape and defaults.\n * Consumers (e.g., the Obsidian plugin) pass partial overrides; all unspecified\n * fields fall back to `DEFAULT_CONFIG`.\n * \n * 2. **Self-documenting.** Every interface and field has descriptive JSDoc so the\n * config is understandable at a glance, whether you're using the engine as an\n * npm package or reading the source.\n * \n * 3. **Minimal consumer knowledge.** Consumers only need to pass `Partial<EngineConfig>`.\n * They don't need to replicate the full config shape, just the fields they\n * want to override.\n * \n * @module Configuration\n */\n\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * A host's test for whether a calendar date is a public holiday, given the\n * `Date` for that day at local midnight. Return `true` to exclude it from\n * working-day arithmetic.\n */\nexport type HolidayPredicate = (date: Date) => boolean;\n\n/**\n * The host-supplied public-holiday calendar, in the same \"bring your own data\"\n * shape the stocks and weather packages already use for a host callback (see\n * `packages/stocks/StocksPackage.ts`): weekends are decidable from the date\n * alone, holidays are not, so they come from the host or not at all.\n *\n * Either a {@link HolidayPredicate}, for a host that computes holidays itself\n * (an existing library, a region rule), or an iterable of specific dates as\n * `YYYY-MM-DD` strings, epoch-millisecond numbers or `Date` objects, for a host\n * that just has a list. Resolved to one internal predicate by\n * `vm/HolidayCalendar.ts`'s `resolveHolidayPredicate()`.\n *\n * Left unset, working-day arithmetic skips weekends only, which is the honest\n * default: the engine excludes exactly the days it can prove are non-working.\n */\nexport type HolidayCalendar = HolidayPredicate | Iterable<string | number | Date>;\n\n/**\n * Date-related configuration.\n * Controls the bounds and formatting for date/time expression evaluation\n * (e.g., `today + 20 days`, `last monday`).\n */\n/**\n * How an ambiguous all-numeric date literal is read.\n *\n * - `'auto'`: by separator, the historic behaviour. A slash date is\n * day-first (`25/12/2023`), a hyphen date is month-first (`12-25-2023`)\n * unless its first group is four digits, which makes it ISO (`2023-12-25`).\n * - `'DMY'` / `'MDY'` / `'YMD'`: a fixed order for every numeric separator, so\n * a host can match its readers' locale. `'MDY'` is what lets a US reader's\n * `12/25/2023` parse, which `'auto'` refuses because the slash defaults to\n * day-first.\n *\n * Only the all-numeric literals are affected. A spelled-out month (`March 9,\n * 2024`) is never ambiguous, and an ISO timestamp is always read as ISO.\n */\nexport type DateInputOrder = 'auto' | 'DMY' | 'MDY' | 'YMD';\n\n/** Date-related engine configuration: offset limits, input order, holidays. */\nexport interface DateConfig {\n /**\n * The order an ambiguous all-numeric date literal is read in. Defaults to\n * `'auto'` (by separator, the historic behaviour). See {@link DateInputOrder}.\n */\n readonly inputOrder: DateInputOrder;\n /**\n * How far forward a date offset whose COST grows with the offset may reach,\n * in years. Enforced by `vm/VM.ts`'s `addBusinessDays()`.\n *\n * Bounds the walk, not the calendar. Every other date offset in the engine\n * is arithmetic on a Date field, so `today + 100000 days` costs exactly what\n * one day costs and needs no ceiling; workdays are the one offset that has\n * to step day by day, because which days are skipped depends on where each\n * step lands. `today + 100000000 workdays` therefore froze the host for\n * thirteen seconds inside a single ADD opcode (where `vm.maxInstructions`\n * cannot see it) and then answered \"Invalid Date\", and a trillion never\n * returned at all.\n *\n * Release hardening: this field was declared, documented as a \"safety\n * limit\", and read nowhere, so it bounded nothing. A limit a host can\n * configure and the engine ignores is worse than no limit, because it reads\n * as protection that is not there.\n */\n readonly maxOffsetYears: number;\n /** How far BACK the same walk may reach, in years, as a negative number. See {@link maxOffsetYears}. */\n readonly minOffsetYears: number;\n /** Default date string format for display (moment.js format string) */\n readonly defaultFormat: string;\n /**\n * Public-holiday calendar for working-day arithmetic (`N working days after\n * <date>`, `working days between <date> and <date>`, `<date> + N workdays`).\n * See {@link HolidayCalendar}.\n *\n * Optional and unset by default: with no calendar, working-day arithmetic\n * skips weekends only. A host that wants holidays excluded too supplies one\n * here (`new ExpressionEngine({ config: { date: { holidays } } })`), the\n * same way stocks and weather take a host data source. Threaded into the VM\n * by `engine/ExpressionEngine.ts` exactly as {@link maxOffsetYears} is,\n * because working-day math is a VM operation several grammar forms share, so\n * the calendar has to be one source the VM owns rather than per-package state\n * the VM cannot see.\n */\n readonly holidays?: HolidayCalendar;\n}\n\n/**\n * Performance-related configuration.\n * Controls caching, timeouts, and processing limits to prevent runaway\n * resource consumption on large documents.\n */\nexport interface PerformanceConfig {\n /**\n * Maximum number of entries in {@link ExpressionEngine}'s bytecode cache\n * (per-instance, keyed by expression text) before the oldest entry is\n * evicted. Raise this for documents with many distinct expressions if\n * repeated re-evaluation (e.g. scrolling) is re-parsing instead of\n * hitting cache, bug fix (release hardening pass): this field used to\n * be read nowhere; the cache size was a hardcoded, unconfigurable\n * constant. Note this does NOT bound {@link LineCache}, which has no\n * size limit of its own.\n */\n readonly defaultCacheSize: number;\n /**\n * Maximum lines a document may have for the engine to process it in one\n * pass. Enforced by `ExpressionEngine.parseDocument()` and by\n * `engine/DocumentModel.ts`'s `setDocument()`, the two entry points that\n * take a whole document.\n *\n * A document costs memory per line whatever each line says: a parsed line\n * record, a cache entry, a dependency-graph node. Two hundred thousand\n * lines of `1 + 1` therefore exhausted the heap and aborted the process\n * before any per-line limit had anything to object to, which is the same\n * shape of hole as an unbounded expression and needs the same kind of\n * ceiling. Refusing the document names the limit; a host that genuinely has\n * a larger one raises this field.\n *\n * Release hardening: declared and read nowhere until now.\n */\n readonly maxDocumentLines: number;\n}\n\n/**\n * Validation / safety-limit configuration.\n * Protects against runaway expressions that could cause excessive memory use\n * or stack overflow. These limits are checked during lexing and parsing.\n */\n/** Bounds on untrusted input: expression length and nesting depth. */\nexport interface ValidationConfig {\n /** Maximum expression length in characters. Prevents excessively long strings from entering the pipeline. */\n readonly maxExpressionLength: number;\n /** Maximum expression complexity score (`tokens + functionCalls×5 + nestingDepth×10`). Protects against deeply nested or combinatorially complex expressions. */\n readonly maxComplexity: number;\n /** Maximum parentheses nesting depth. Prevents stack overflow in the recursive-descent parser. */\n readonly maxNestingDepth: number;\n /**\n * Auto-balance unmatched parentheses by appending missing closing parens\n * or prepending missing opening parens. When disabled, unbalanced expressions\n * cause parse errors instead of being silently corrected.\n *\n * Disabled by default for strict parsing. Enable for forgiving user input\n * (e.g., chat-style calculators where users often omit closing parens).\n * Has zero overhead when disabled, the O(n) paren-count scan is skipped.\n */\n readonly autoBalanceParens: boolean;\n}\n\n/**\n * Worker pool configuration.\n * Controls the parallel execution workers used for batch evaluation.\n */\nexport interface WorkerConfig {\n /** Maximum number of concurrent Web Workers allowed */\n readonly maxConcurrentWorkers: number;\n /** Time (ms) a worker stays alive while idle before being terminated */\n readonly idleTimeoutMs: number;\n /** Maximum retry attempts for a failed worker operation */\n readonly maxRetries: number;\n /** Base backoff delay (ms) between retries (exponential backoff applied on top) */\n readonly baseBackoffMs: number;\n} /**\n * Diagnostic / telemetry configuration.\n * Controls the diagnostic event pipeline for profiling and debugging.\n * All diagnostics are disabled by default for maximum production performance.\n */\n export interface DiagnosticConfig {\n /** Master switch: enable the diagnostic pipeline (collectors receive events for all pipeline stages) */\n readonly enabled: boolean;\n /** Enable VM trace mode, emits per-opcode execution events (very verbose; disables some optimizations) */\n readonly vmTraceEnabled: boolean;\n }\n\n /**\n * Proactive background refresh of live async values.\n *\n * Off by default. When a live value (a stock quote, an FX rate) has gone\n * stale, today it only refetches on the next re-evaluation (a keystroke), so a\n * note left open silently ages. With this enabled, the engine drives a refetch\n * on each such value's own cadence (the resolver's `refetchIntervalMs`) for the\n * values currently on screen, and pushes the fresh result to the host through\n * the same event stream the pull path uses. It needs timers and a live editor\n * consuming that stream, so a headless or batch host leaves it off.\n */\n export interface BackgroundRefreshConfig {\n /** Master switch. When false, no timers run and every value refreshes only on re-evaluation. */\n readonly enabled: boolean;\n }\n\n /**\n * Virtual Machine configuration.\n * Controls the internal bytecode VM that executes compiled expressions.\n */\n export interface VMConfig {\n /** Maximum stack depth (value slots) for VM execution, prevents stack overflow in recursive/pratt-parser generated bytecode */\n readonly maxStackDepth: number;\n /** Maximum opcodes executed per expression, halts runaway infinite loops */\n readonly maxInstructions: number;\n /**\n * Maximum elements a collection may be expanded to before `map`/`reduce`/\n * `sum`/`prod` will iterate it.\n *\n * A Range is stored as its two bounds and costs nothing until something\n * materializes it, at which point it becomes one Value per element. Twenty\n * characters (`sum(x, 1:100000000)`) therefore asked for a hundred million\n * of them, and neither `maxInstructions` nor `maxStackDepth` could see it:\n * the expansion happens inside a single opcode, so the instruction counter\n * is never consulted while it runs, and the elements never reach the value\n * stack. V8 aborted the whole process with \"Reached heap limit\", which a\n * host embedding the engine cannot catch.\n */\n readonly maxCollectionSize: number;\n /**\n * Maximum elements (collection Values, matrix cells) one evaluation may\n * materialize in total.\n *\n * `maxCollectionSize` above bounds a single collection. This bounds the sum\n * of everything an expression asks for, which is a different question and\n * the one that actually protects the host: two collections that are\n * individually legal are legal together, and an operation whose result is\n * the PRODUCT of two legal operands is bounded by neither of them. A matrix\n * multiply is exactly that shape, so three lines within every other limit\n * (`:a = map(1*x, 0:20000)`, `:b = transpose(a)`, `b * a`) asked for four\n * hundred million cells and aborted the process.\n *\n * Counted in elements rather than bytes, because a count is what a call\n * site has before it allocates. An element is 8 bytes as a numeric matrix\n * cell and closer to a hundred as a full Value, so the default is worth\n * roughly 16 MB of matrix or 200 MB of expanded collection: far past any\n * document and far short of what an editor cannot survive.\n */\n readonly maxAllocatedElements: number;\n /**\n * Maximum user-defined-function calls one evaluation may make in TOTAL,\n * however deeply or widely they nest.\n *\n * `maxFunctionRecursionDepth` bounds how DEEP calls nest and cannot see\n * how MANY there are, and those are different numbers. Twenty-two lines of\n * `f(n)(v) = f(n-1)(v) + f(n-1)(v)` reach a depth of only 22 against a\n * limit of 50, and make 2,097,152 calls doing it: a fatal heap abort in\n * under a second. `maxInstructions` cannot bound it either, because\n * `executeBytecode()` re-enters itself per call and each reentrant call\n * gets its OWN instruction count, so recursion refreshes its allowance on\n * the way in. This is the tally that does not refresh; see\n * `vm/AllocationBudget.ts`, which holds it for the same reason it holds\n * the element tally.\n *\n * Counted in calls rather than in the instructions they run, because the\n * call is the thing that multiplies: every call allocates a frame, its\n * arguments and its result whatever its body says.\n */\n readonly maxFunctionCalls: number;\n /**\n * Hard ceiling on how many bisection steps goal seek (`solve line N for\n * <var> = <target>`, see `packages/goalseek/`) may take before it gives up\n * with a structured error rather than continuing.\n *\n * Goal seek re-evaluates the target line's expression once per step while\n * narrowing an interval, and an untrusted document must never be able to\n * make that loop spin. `maxInstructions` bounds each individual\n * re-evaluation, but not how many of them the search performs, so this is\n * the tally that bounds the search itself, the same reason `maxFunctionCalls`\n * exists alongside `maxInstructions`. Bisection halves the interval every\n * step, so a hundred steps resolves an input to roughly one part in 2^100:\n * far past any precision a document needs, and a definite stop either way.\n */\n readonly maxGoalSeekIterations: number;\n }\n\n/**\n * Complete engine configuration.\n *\n * Every field has a default in `DEFAULT_CONFIG`. To customize, pass a\n * `Partial<EngineConfig>` when constructing `ExpressionEngine`. Only the\n * sections/fields you supply are overridden; all others use their defaults.\n *\n * @example\n * ```typescript\n * import { ExpressionEngine } from \"solve-js\";\n *\n * const engine = new ExpressionEngine({ config: {\n * validation: {\n * maxExpressionLength: 1000,\n * maxComplexity: 200,\n * },\n * // date, performance, vm, worker, diagnostic all use defaults\n * } });\n * ```\n */\nexport interface EngineConfig {\n /** Date/time expression evaluation bounds and formatting */\n readonly date: DateConfig;\n /** Performance budgets and cache sizing */\n readonly performance: PerformanceConfig;\n /** Safety limits for expression complexity */\n readonly validation: ValidationConfig;\n /** Internal bytecode VM configuration */\n readonly vm: VMConfig;\n /** Parallel worker pool configuration */\n readonly worker: WorkerConfig;\n /** Diagnostic pipeline configuration */\n readonly diagnostic: DiagnosticConfig;\n /** Proactive background refresh of live async values */\n readonly backgroundRefresh: BackgroundRefreshConfig;\n }\n\n/**\n * A partial {@link EngineConfig} override, one section at a time.\n *\n * Overrides are merged per section over {@link DEFAULT_CONFIG}, so you can set a\n * single field of one section (`{ validation: { maxExpressionLength: 1000 } }`)\n * and keep every other default in that section. A plain `Partial<EngineConfig>`\n * cannot express that, it demands a whole section object, which is why the\n * documented overrides never typechecked against it. This is the type the\n * constructor and {@link createEngine} accept.\n */\nexport type EngineConfigOverride = {\n readonly [K in keyof EngineConfig]?: Partial<EngineConfig[K]>;\n};\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONFIG: EngineConfig = {\n date: {\n // A century of workdays is about 26,000 steps, which is microseconds,\n // and past any offset a person means. The walk is what these bound; see\n // DateConfig above for why no other date offset needs a ceiling.\n maxOffsetYears: 100,\n minOffsetYears: -100,\n defaultFormat: 'YYYY-MM-DD',\n inputOrder: 'auto',\n },\n performance: {\n // Preserves the effective cache size the hardcoded (now-removed)\n // BYTECODE_CACHE_MAX_ENTRIES constant had, so wiring this field up\n // doesn't silently shrink the default cache for existing consumers.\n defaultCacheSize: 2000,\n // Raised from the 10,000 this field was declared with, which was never\n // enforced and turned out to be under what this engine already supports:\n // its paging design is tested against a 20,000-line document\n // (`engine/PageManager.ts` and its spec) and its throughput benchmark\n // parses a 50,000-line one. Twice the largest of those, and the same\n // number `ConfigManager.validate()` already refuses to go above.\n //\n // Measured under a 256MB heap: setting a 100,000-line document costs\n // 64MB, evaluating every line of a 20,000-line one costs 106MB, and\n // 200,000 lines aborts the process before a single expression is looked\n // at. A host with a small heap should lower this; the ceiling is here to\n // stop the size that cannot work anywhere.\n maxDocumentLines: 100000,\n },\n validation: {\n maxExpressionLength: 2000,\n maxComplexity: 500,\n maxNestingDepth: 50,\n autoBalanceParens: false,\n },\n vm: {\n maxStackDepth: 200,\n maxInstructions: 50000,\n // Two orders of magnitude above anything a person types by hand (the\n // longest range in the test suite is 1000 elements) and small enough\n // that expanding it is measured in milliseconds rather than in whether\n // the host survives.\n maxCollectionSize: 100000,\n // Twenty times the single-collection ceiling above, so an expression may\n // legitimately handle a number of large collections, and two hundred\n // times below the allocation that took the process down.\n maxAllocatedElements: 2000000,\n // Six hundred times the largest call count any test or example makes\n // (five levels of composition is sixteen calls), and small enough that\n // the calls it does allow cost single-digit megabytes rather than the\n // heap. A document that needs more than ten thousand calls on one line\n // is doing something a calculator was not built for.\n maxFunctionCalls: 10000,\n // A hundred bisection steps resolve an input to one part in 2^100, far\n // finer than any document needs and a firm stop for an untrusted one. A\n // continuous, monotonic relationship converges in tens of steps, well\n // under this; hitting it means the target is unreachable or the\n // relationship is not the smooth one goal seek assumes.\n maxGoalSeekIterations: 100,\n },\n worker: {\n maxConcurrentWorkers: 4,\n idleTimeoutMs: 30000,\n maxRetries: 3,\n baseBackoffMs: 1000,\n },\n diagnostic: {\n enabled: false,\n vmTraceEnabled: false,\n },\n backgroundRefresh: {\n enabled: false,\n },\n };\n\n/**\n * Merge a partial config override onto a base `EngineConfig`, section by\n * section, `{ ...base.section, ...override.section }` for each of the 7\n * top-level sections, not a single top-level spread.\n *\n * A shallow `{ ...base, ...override }` at the TOP level replaces an entire\n * section wholesale the moment a caller overrides even one field in it\n * (e.g. `{ performance: { defaultCacheSize: 500 } }` would silently drop\n * every other `performance.*` field back to `undefined`, not to its\n * default). This function exists specifically so every config consumer\n * shares one correct merge instead of each hand-rolling (and risking) its\n * own. `ConfigManager` and `ExpressionEngine` both call this rather than\n * either duplicating the section list or instantiating a whole\n * `ConfigManager` just to reuse its private merge logic.\n */\nexport function mergeEngineConfig(\n base: EngineConfig,\n override: EngineConfigOverride\n): EngineConfig {\n return {\n date: { ...base.date, ...override.date },\n performance: { ...base.performance, ...override.performance },\n validation: { ...base.validation, ...override.validation },\n vm: { ...base.vm, ...override.vm },\n worker: { ...base.worker, ...override.worker },\n diagnostic: { ...base.diagnostic, ...override.diagnostic },\n backgroundRefresh: { ...base.backgroundRefresh, ...override.backgroundRefresh },\n };\n}\n\n/**\n * Configuration manager for engine settings\n *\n * @example\n * ```typescript\n * const configManager = new ConfigManager();\n * configManager.set('performance.defaultCacheSize', 2000);\n * const cacheSize = configManager.get('performance.defaultCacheSize');\n * ```\n */\nexport class ConfigManager {\n private config: EngineConfig;\n\n constructor(config: Partial<EngineConfig> = {}) {\n this.config = mergeEngineConfig(DEFAULT_CONFIG, config);\n }\n\n /**\n * Get configuration value by path\n * \n * @param path - Dot-notation path to config value\n * @returns Configuration value\n */\n get<T>(path: string): T {\n const keys = path.split('.');\n let current: unknown = this.config;\n\n for (const key of keys) {\n if (current && typeof current === 'object' && key in current) {\n current = (current as Record<string, unknown>)[key];\n } else {\n throw ErrorFactory.config(\n \"CONFIG_PATH_NOT_FOUND\",\n `Configuration path not found: ${path}`,\n { path }\n );\n }\n }\n\n return current as T;\n }\n\n /**\n * Set configuration value by path\n * \n * @param path - Dot-notation path to config value\n * @param value - New value\n */\n set<T>(path: string, value: T): void {\n const keys = path.split('.');\n if (keys.length < 2) {\n throw ErrorFactory.config(\n \"INVALID_CONFIG_PATH\",\n `Invalid path: ${path}. Must be in format 'section.property'`,\n { path }\n );\n }\n \n const section = keys[0];\n const property = keys[1];\n \n if (!(section in this.config)) {\n throw ErrorFactory.config(\n \"CONFIG_SECTION_NOT_FOUND\",\n `Configuration section not found: ${section}`,\n { section, path }\n );\n }\n \n const sectionConfig = this.config[section as keyof EngineConfig];\n if (sectionConfig && typeof sectionConfig === 'object') {\n (sectionConfig as unknown as Record<string, unknown>)[property] = value;\n } else {\n throw ErrorFactory.config(\n \"CONFIG_PROPERTY_NOT_FOUND\",\n `Configuration property not found: ${path}`,\n { path }\n );\n }\n }\n\n /**\n * Get complete configuration.\n *\n * A detached copy, section objects included. A top-level spread would hand\n * the caller this manager's own section objects, so `getConfig().vm.x = 1`\n * would be an undeclared back door into {@link set}, bypassing its path\n * validation and reaching every later {@link get}.\n */\n getConfig(): EngineConfig {\n return mergeEngineConfig(this.config, {});\n }\n\n /**\n * Update multiple configuration values\n */\n update(config: Partial<EngineConfig>): void {\n this.config = mergeEngineConfig(this.config, config);\n }\n\n /**\n * Reset to default configuration.\n *\n * Goes through {@link mergeEngineConfig} for the same reason the constructor\n * does. A top-level `{ ...DEFAULT_CONFIG }` copies the six section\n * references, not the sections, so after a reset this manager's\n * `performance` object WAS `DEFAULT_CONFIG.performance` and the next\n * `set('performance.x', ...)` wrote into the module constant. That constant\n * is what every `ExpressionEngine` is built from, so one manager's reset\n * could change the cache size, instruction ceiling or allocation budget of\n * every engine constructed later in the process.\n */\n reset(): void {\n this.config = mergeEngineConfig(DEFAULT_CONFIG, {});\n }\n\n /**\n * Validate configuration values\n */\n validate(): ValidationResult {\n const errors: string[] = [];\n\n // Validate performance config\n if (this.config.performance.maxDocumentLines > 100000) {\n errors.push('maxDocumentLines cannot exceed 100,000');\n }\n\n // Validate date config\n if (this.config.date.maxOffsetYears > 1000) {\n errors.push('maxOffsetYears cannot exceed 1000');\n }\n\n return {\n valid: errors.length === 0,\n error: errors.join('; '),\n warnings: []\n };\n }\n}\n\n/**\n * Result type for {@link ConfigManager.validate}.\n */\nexport interface ValidationResult {\n valid: boolean;\n error?: string;\n warnings?: string[];\n}\n\n"]}
|