solve-engine 2.23.0 → 2.24.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.
Files changed (202) hide show
  1. package/README.md +82 -32
  2. package/dist/{Configuration-BGQn-cJ8.d.cts → Configuration-DnzYPmoK.d.cts} +33 -0
  3. package/dist/{Configuration-BGQn-cJ8.d.ts → Configuration-DnzYPmoK.d.ts} +33 -0
  4. package/dist/{EngineError-DTk7I7hZ.d.cts → EngineError-D1kXsjIj.d.cts} +4 -0
  5. package/dist/{EngineError-DTk7I7hZ.d.ts → EngineError-D1kXsjIj.d.ts} +4 -0
  6. package/dist/{PackageCompatibility-BGXSFuL9.d.ts → PackageCompatibility-Bq82y0ZN.d.ts} +1 -1
  7. package/dist/{PackageCompatibility-BZCqaTOO.d.cts → PackageCompatibility-CeAPVHZr.d.cts} +1 -1
  8. package/dist/{PackageRegistry-rMGnTh7W.d.cts → PackageRegistry-B9-7fJGH.d.cts} +16 -11
  9. package/dist/{PackageRegistry-BRoVOYzg.d.ts → PackageRegistry-CDEgfhT_.d.ts} +16 -11
  10. package/dist/{Parselet-Bkbp9CKD.d.cts → Parselet-4oH5OuRt.d.cts} +1 -1
  11. package/dist/{Parselet-B-WyUtX4.d.ts → Parselet-BwDqKFfK.d.ts} +1 -1
  12. package/dist/{ScopeManager-gB9UengK.d.ts → ScopeManager-BQBhlDAu.d.ts} +38 -7
  13. package/dist/{ScopeManager-bCYewWVt.d.cts → ScopeManager-DrXB3Nvm.d.cts} +38 -7
  14. package/dist/{VMCheckpoints-DGar9Yg8.d.cts → VMCheckpoints-BK32PTl2.d.cts} +2 -2
  15. package/dist/{VMCheckpoints-BDRY1Kx8.d.ts → VMCheckpoints-C5jC92o3.d.ts} +2 -2
  16. package/dist/{Value-DCTqTSeP.d.cts → Value-Ds3Gy07C.d.cts} +1 -1
  17. package/dist/{Value-DCTqTSeP.d.ts → Value-Ds3Gy07C.d.ts} +1 -1
  18. package/dist/{WorkerError-DpZgKRks.d.ts → WorkerError-CVQbs6_D.d.ts} +1 -1
  19. package/dist/{WorkerError-DGBNM3gA.d.cts → WorkerError-DaNWQFp1.d.cts} +1 -1
  20. package/dist/chunk-2BXNZM3G.js +2 -0
  21. package/dist/chunk-2BXNZM3G.js.map +1 -0
  22. package/dist/chunk-2JSNWYYA.cjs +3 -0
  23. package/dist/chunk-2JSNWYYA.cjs.map +1 -0
  24. package/dist/{chunk-J7ABVGZH.cjs → chunk-2VE4OW4A.cjs} +2 -2
  25. package/dist/{chunk-J7ABVGZH.cjs.map → chunk-2VE4OW4A.cjs.map} +1 -1
  26. package/dist/{chunk-HMC7FJO7.js → chunk-3SHWTGTP.js} +2 -2
  27. package/dist/{chunk-HMC7FJO7.js.map → chunk-3SHWTGTP.js.map} +1 -1
  28. package/dist/{chunk-EN3CDYOS.cjs → chunk-5GL4SAVH.cjs} +2 -2
  29. package/dist/{chunk-EN3CDYOS.cjs.map → chunk-5GL4SAVH.cjs.map} +1 -1
  30. package/dist/{chunk-SGIDBZ4T.cjs → chunk-72N3ZRVE.cjs} +2 -2
  31. package/dist/chunk-72N3ZRVE.cjs.map +1 -0
  32. package/dist/{chunk-CHSO3DCS.js → chunk-7EP36NXE.js} +3 -3
  33. package/dist/{chunk-CHSO3DCS.js.map → chunk-7EP36NXE.js.map} +1 -1
  34. package/dist/chunk-A4JV7HRB.js +3 -0
  35. package/dist/chunk-A4JV7HRB.js.map +1 -0
  36. package/dist/chunk-AUOE7MFI.cjs +2 -0
  37. package/dist/chunk-AUOE7MFI.cjs.map +1 -0
  38. package/dist/chunk-BDF4VCQX.js +3 -0
  39. package/dist/chunk-BDF4VCQX.js.map +1 -0
  40. package/dist/{chunk-3SSMOVWB.cjs → chunk-CDNJZBM3.cjs} +2 -2
  41. package/dist/{chunk-3SSMOVWB.cjs.map → chunk-CDNJZBM3.cjs.map} +1 -1
  42. package/dist/{chunk-YAONCEAW.cjs → chunk-CMZSK6FY.cjs} +3 -3
  43. package/dist/{chunk-YAONCEAW.cjs.map → chunk-CMZSK6FY.cjs.map} +1 -1
  44. package/dist/chunk-D2Q2VFJ6.js +2 -0
  45. package/dist/chunk-D2Q2VFJ6.js.map +1 -0
  46. package/dist/{chunk-75JLWK4L.cjs → chunk-DA7M6H63.cjs} +2 -2
  47. package/dist/{chunk-75JLWK4L.cjs.map → chunk-DA7M6H63.cjs.map} +1 -1
  48. package/dist/chunk-ELQQKZN3.cjs +3 -0
  49. package/dist/{chunk-PIZQIQVM.js.map → chunk-ELQQKZN3.cjs.map} +1 -1
  50. package/dist/chunk-F7QIBC4B.cjs +3 -0
  51. package/dist/chunk-F7QIBC4B.cjs.map +1 -0
  52. package/dist/chunk-GP4H5OIT.js +3 -0
  53. package/dist/chunk-GP4H5OIT.js.map +1 -0
  54. package/dist/chunk-HQ7BKXG7.js +2 -0
  55. package/dist/chunk-HQ7BKXG7.js.map +1 -0
  56. package/dist/{chunk-KRXO3MOW.cjs → chunk-IHAZL4EF.cjs} +2 -2
  57. package/dist/chunk-IHAZL4EF.cjs.map +1 -0
  58. package/dist/{chunk-7E7NXKQ5.js → chunk-IJHL3LMH.js} +2 -2
  59. package/dist/chunk-IJHL3LMH.js.map +1 -0
  60. package/dist/{chunk-3GR46UOX.js → chunk-IPSOWFCA.js} +2 -2
  61. package/dist/{chunk-3GR46UOX.js.map → chunk-IPSOWFCA.js.map} +1 -1
  62. package/dist/chunk-LM6ZQUEU.js +2 -0
  63. package/dist/chunk-LM6ZQUEU.js.map +1 -0
  64. package/dist/{chunk-N37PUZJR.cjs → chunk-LTJV3VJE.cjs} +2 -2
  65. package/dist/{chunk-N37PUZJR.cjs.map → chunk-LTJV3VJE.cjs.map} +1 -1
  66. package/dist/chunk-MWWAKZOD.cjs +3 -0
  67. package/dist/chunk-MWWAKZOD.cjs.map +1 -0
  68. package/dist/chunk-NUF66H57.js +5 -0
  69. package/dist/chunk-NUF66H57.js.map +1 -0
  70. package/dist/{chunk-MRRMIBHE.js → chunk-OMHRBKAT.js} +2 -2
  71. package/dist/{chunk-MRRMIBHE.js.map → chunk-OMHRBKAT.js.map} +1 -1
  72. package/dist/{chunk-4ETS224G.js → chunk-PTQCHMYA.js} +2 -2
  73. package/dist/{chunk-4ETS224G.js.map → chunk-PTQCHMYA.js.map} +1 -1
  74. package/dist/{chunk-4DJJIUQF.js → chunk-PWWQZFAE.js} +2 -2
  75. package/dist/chunk-PWWQZFAE.js.map +1 -0
  76. package/dist/chunk-RE6AIU6Y.js +3 -0
  77. package/dist/chunk-RE6AIU6Y.js.map +1 -0
  78. package/dist/chunk-RECRD45C.cjs +5 -0
  79. package/dist/chunk-RECRD45C.cjs.map +1 -0
  80. package/dist/{chunk-O3BDXOQJ.js → chunk-RENO2AWO.js} +2 -2
  81. package/dist/{chunk-O3BDXOQJ.js.map → chunk-RENO2AWO.js.map} +1 -1
  82. package/dist/chunk-RMCN5WFO.cjs +2 -0
  83. package/dist/chunk-RMCN5WFO.cjs.map +1 -0
  84. package/dist/{chunk-TL545PXW.cjs → chunk-RN3ISTM3.cjs} +2 -2
  85. package/dist/{chunk-TL545PXW.cjs.map → chunk-RN3ISTM3.cjs.map} +1 -1
  86. package/dist/{chunk-JYLNQOPU.cjs → chunk-S46R5QZP.cjs} +2 -2
  87. package/dist/{chunk-JYLNQOPU.cjs.map → chunk-S46R5QZP.cjs.map} +1 -1
  88. package/dist/{chunk-USQ4KL6S.cjs → chunk-UPH22K2T.cjs} +2 -2
  89. package/dist/chunk-UPH22K2T.cjs.map +1 -0
  90. package/dist/{chunk-KEA5HRL3.js → chunk-UXR7JIPX.js} +2 -2
  91. package/dist/{chunk-KEA5HRL3.js.map → chunk-UXR7JIPX.js.map} +1 -1
  92. package/dist/chunk-UY3ID6JF.cjs +2 -0
  93. package/dist/chunk-UY3ID6JF.cjs.map +1 -0
  94. package/dist/{chunk-JVMINMAB.js → chunk-WFOQRPA6.js} +2 -2
  95. package/dist/{chunk-JVMINMAB.js.map → chunk-WFOQRPA6.js.map} +1 -1
  96. package/dist/{chunk-AF7HQN6I.js → chunk-XFJABR3B.js} +2 -2
  97. package/dist/chunk-XFJABR3B.js.map +1 -0
  98. package/dist/{chunk-LNZNJSRW.cjs → chunk-ZVPZQ66D.cjs} +2 -2
  99. package/dist/chunk-ZVPZQ66D.cjs.map +1 -0
  100. package/dist/constants.cjs +1 -1
  101. package/dist/constants.d.cts +1 -1
  102. package/dist/constants.d.ts +1 -1
  103. package/dist/constants.js +1 -1
  104. package/dist/engine.cjs +1 -1
  105. package/dist/engine.d.cts +9 -9
  106. package/dist/engine.d.ts +9 -9
  107. package/dist/engine.js +1 -1
  108. package/dist/errors.cjs +1 -1
  109. package/dist/errors.d.cts +3 -3
  110. package/dist/errors.d.ts +3 -3
  111. package/dist/errors.js +1 -1
  112. package/dist/format.cjs +1 -1
  113. package/dist/format.d.cts +1 -1
  114. package/dist/format.d.ts +1 -1
  115. package/dist/format.js +1 -1
  116. package/dist/index.cjs +1 -1
  117. package/dist/index.cjs.map +1 -1
  118. package/dist/index.d.cts +11 -9
  119. package/dist/index.d.ts +11 -9
  120. package/dist/index.js +1 -1
  121. package/dist/index.js.map +1 -1
  122. package/dist/language.d.cts +8 -8
  123. package/dist/language.d.ts +8 -8
  124. package/dist/lexer.cjs +1 -1
  125. package/dist/lexer.js +1 -1
  126. package/dist/normalizer.cjs +1 -1
  127. package/dist/normalizer.d.cts +14 -8
  128. package/dist/normalizer.d.ts +14 -8
  129. package/dist/normalizer.js +1 -1
  130. package/dist/packages.cjs +1 -1
  131. package/dist/packages.d.cts +7 -7
  132. package/dist/packages.d.ts +7 -7
  133. package/dist/packages.js +1 -1
  134. package/dist/parser.cjs +1 -1
  135. package/dist/parser.d.cts +3 -3
  136. package/dist/parser.d.ts +3 -3
  137. package/dist/parser.js +1 -1
  138. package/dist/{pipeline-B4wf3M1h.d.cts → pipeline-69q2tsLE.d.cts} +1 -1
  139. package/dist/{pipeline-QIT4iD8f.d.ts → pipeline-DTqGLPsV.d.ts} +1 -1
  140. package/dist/resolvers.cjs +1 -1
  141. package/dist/resolvers.d.cts +18 -2
  142. package/dist/resolvers.d.ts +18 -2
  143. package/dist/resolvers.js +1 -1
  144. package/dist/testing.cjs +2 -2
  145. package/dist/testing.d.cts +8 -8
  146. package/dist/testing.d.ts +8 -8
  147. package/dist/testing.js +1 -1
  148. package/dist/uom.cjs +1 -1
  149. package/dist/uom.d.cts +1 -1
  150. package/dist/uom.d.ts +1 -1
  151. package/dist/uom.js +1 -1
  152. package/dist/vm.cjs +1 -1
  153. package/dist/vm.d.cts +7 -7
  154. package/dist/vm.d.ts +7 -7
  155. package/dist/vm.js +1 -1
  156. package/dist/worker.cjs +2 -2
  157. package/dist/worker.cjs.map +1 -1
  158. package/dist/worker.d.cts +31 -22
  159. package/dist/worker.d.ts +31 -22
  160. package/dist/worker.js +1 -1
  161. package/dist/worker.js.map +1 -1
  162. package/package.json +1 -1
  163. package/dist/chunk-42JXN3BH.js +0 -5
  164. package/dist/chunk-42JXN3BH.js.map +0 -1
  165. package/dist/chunk-4DJJIUQF.js.map +0 -1
  166. package/dist/chunk-6YM67DWH.cjs +0 -3
  167. package/dist/chunk-6YM67DWH.cjs.map +0 -1
  168. package/dist/chunk-7E7NXKQ5.js.map +0 -1
  169. package/dist/chunk-7SZBEE5R.cjs +0 -2
  170. package/dist/chunk-7SZBEE5R.cjs.map +0 -1
  171. package/dist/chunk-A5M4QZIK.js +0 -2
  172. package/dist/chunk-A5M4QZIK.js.map +0 -1
  173. package/dist/chunk-AF7HQN6I.js.map +0 -1
  174. package/dist/chunk-ALY4ZMYO.js +0 -2
  175. package/dist/chunk-ALY4ZMYO.js.map +0 -1
  176. package/dist/chunk-BRJ4RT5U.js +0 -2
  177. package/dist/chunk-BRJ4RT5U.js.map +0 -1
  178. package/dist/chunk-CO2BI6WL.cjs +0 -3
  179. package/dist/chunk-CO2BI6WL.cjs.map +0 -1
  180. package/dist/chunk-EQDT42JG.js +0 -3
  181. package/dist/chunk-EQDT42JG.js.map +0 -1
  182. package/dist/chunk-FMMT5C5H.cjs +0 -3
  183. package/dist/chunk-FMMT5C5H.cjs.map +0 -1
  184. package/dist/chunk-FP6Z6PYR.js +0 -2
  185. package/dist/chunk-FP6Z6PYR.js.map +0 -1
  186. package/dist/chunk-H3JXNH7X.cjs +0 -3
  187. package/dist/chunk-H3JXNH7X.cjs.map +0 -1
  188. package/dist/chunk-HZOLIL5T.js +0 -3
  189. package/dist/chunk-HZOLIL5T.js.map +0 -1
  190. package/dist/chunk-KRXO3MOW.cjs.map +0 -1
  191. package/dist/chunk-KVLJDOZ7.cjs +0 -5
  192. package/dist/chunk-KVLJDOZ7.cjs.map +0 -1
  193. package/dist/chunk-LNZNJSRW.cjs.map +0 -1
  194. package/dist/chunk-PIZQIQVM.js +0 -3
  195. package/dist/chunk-QTSDIDAS.js +0 -3
  196. package/dist/chunk-QTSDIDAS.js.map +0 -1
  197. package/dist/chunk-SGIDBZ4T.cjs.map +0 -1
  198. package/dist/chunk-UNKSCVIL.cjs +0 -2
  199. package/dist/chunk-UNKSCVIL.cjs.map +0 -1
  200. package/dist/chunk-USQ4KL6S.cjs.map +0 -1
  201. package/dist/chunk-XDXIPVZB.cjs +0 -2
  202. package/dist/chunk-XDXIPVZB.cjs.map +0 -1
@@ -1,2 +1,2 @@
1
- import {b}from'./chunk-EQDT42JG.js';import {n}from'./chunk-3GR46UOX.js';var u=[10,11,12,13,14,16,60,61,62,63,150,159,95,96],E=[50,51,151,152,160],C=[157,158,161],L=(()=>{let r=new Array(256).fill(0);for(let e of u)r[e]=1;for(let e of E)r[e]=2;for(let e of C)r[e]=3;return r})();[...u,...E,...C];function m(r,e){return e+1+(L[r[e]]??0)}var R="currency",A=class{constructor(e){this.namespace=R;this.exchange=e??b;}preflight(e,N,U,S,y){let{opcodes:c,strings:_}=N,f=c.length,o=0,i=-1,p=-1;for(;o<f;){let t=c[o];if(t===13&&(p=i,i=c[o+1]),(t===84||t===81||t===20||t===21||t===22||t===23)&&p>=0&&i>=0){let n$1=_[p],s=_[i];if(this.exchange.isCurrency(n$1)&&this.exchange.isCurrency(s)&&n$1.toUpperCase()!==s.toUpperCase()&&this.exchange.getRateSync(n$1,s)===null){let I=n$1.toUpperCase(),d=s.toUpperCase(),a=[R,I,d];if(y.getQueryData(a)!==void 0){o++;continue}let g=y.fetchQuery({queryKey:a,queryFn:({signal:h})=>this.exchange.getRate(n$1,s,h).then(T=>n(T)),staleTime:300*1e3});return {queryKey:a.join(":"),resolver:g,packageId:U,signal:S,metadata:{fromUnit:n$1,toUnit:s}}}}o=m(c,o);}return null}destroy(){}};export{m as a,A as b};//# sourceMappingURL=chunk-MRRMIBHE.js.map
2
- //# sourceMappingURL=chunk-MRRMIBHE.js.map
1
+ import {b}from'./chunk-GP4H5OIT.js';import {n}from'./chunk-IPSOWFCA.js';var u=[10,11,12,13,14,16,60,61,62,63,150,159,95,96],E=[50,51,151,152,160],C=[157,158,161],L=(()=>{let r=new Array(256).fill(0);for(let e of u)r[e]=1;for(let e of E)r[e]=2;for(let e of C)r[e]=3;return r})();[...u,...E,...C];function m(r,e){return e+1+(L[r[e]]??0)}var R="currency",A=class{constructor(e){this.namespace=R;this.exchange=e??b;}preflight(e,N,U,S,y){let{opcodes:c,strings:_}=N,f=c.length,o=0,i=-1,p=-1;for(;o<f;){let t=c[o];if(t===13&&(p=i,i=c[o+1]),(t===84||t===81||t===20||t===21||t===22||t===23)&&p>=0&&i>=0){let n$1=_[p],s=_[i];if(this.exchange.isCurrency(n$1)&&this.exchange.isCurrency(s)&&n$1.toUpperCase()!==s.toUpperCase()&&this.exchange.getRateSync(n$1,s)===null){let I=n$1.toUpperCase(),d=s.toUpperCase(),a=[R,I,d];if(y.getQueryData(a)!==void 0){o++;continue}let g=y.fetchQuery({queryKey:a,queryFn:({signal:h})=>this.exchange.getRate(n$1,s,h).then(T=>n(T)),staleTime:300*1e3});return {queryKey:a.join(":"),resolver:g,packageId:U,signal:S,metadata:{fromUnit:n$1,toUnit:s}}}}o=m(c,o);}return null}destroy(){}};export{m as a,A as b};//# sourceMappingURL=chunk-OMHRBKAT.js.map
2
+ //# sourceMappingURL=chunk-OMHRBKAT.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/parser/OperandWidth.ts","../src/uom/CurrencyResolver.ts"],"names":["ONE_OPERAND","TWO_OPERANDS","THREE_OPERANDS","OPERAND_BYTES","widths","op","nextInstruction","opcodes","index","CURRENCY_NS","CurrencyAsyncResolver","exchange","currencyExchangeService","_tokens","bytecode","packageId","signal","queryClient","strings","len","i","lastStrIdx","prevStrIdx","fromUnit","toUnit","fromUpper","toUpper","cacheKey","resolver","qSignal","rate","numberValue"],"mappings":"wEAwBA,IAAMA,CAAAA,CAAiC,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,GAAA,CAAA,GAAA,CAAA,EAAA,CAAA,EAwBvC,CAAA,CAOMC,CAAAA,CAAkC,CAAA,EAAA,CAAA,EAAA,CAAA,GAAA,CAAA,GAAA,CAAA,GAOxC,CAAA,CASMC,CAAAA,CAAoC,CAAA,GAAA,CAAA,GAAA,CAAA,GAAiE,CAAA,CAQ9FC,CAAAA,CAAAA,CAAoC,IAAM,CACtD,IAAMC,CAAAA,CAAS,IAAI,KAAA,CAAc,GAAG,CAAA,CAAE,IAAA,CAAK,CAAC,CAAA,CAC5C,IAAA,IAAWC,CAAAA,IAAML,CAAAA,CAAaI,CAAAA,CAAOC,CAAE,CAAA,CAAI,CAAA,CAC3C,IAAA,IAAWA,KAAMJ,CAAAA,CAAcG,CAAAA,CAAOC,CAAE,CAAA,CAAI,CAAA,CAC5C,IAAA,IAAWA,CAAAA,IAAMH,CAAAA,CAAgBE,CAAAA,CAAOC,CAAE,CAAA,CAAI,CAAA,CAC9C,OAAOD,CACR,CAAA,GAAG,CAOqD,CACvD,GAAGJ,CAAAA,CACH,GAAGC,CAAAA,C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AWE,GAAQ,CAAA,EACjC,IAAA,CAAK,QAAA,CAAS,UAAA,CAAWC,CAAM,GAC/BD,GAAAA,CAAS,WAAA,EAAY,GAAMC,CAAAA,CAAO,WAAA,EAAY,EAE7B,IAAA,CAAK,QAAA,CAAS,WAAA,CAAYD,GAAAA,CAAUC,CAAM,CAAA,GAC1C,IAAA,CAAM,CACtB,IAAMC,CAAAA,CAAYF,IAAS,WAAA,EAAY,CACjCG,CAAAA,CAAUF,CAAAA,CAAO,WAAA,EAAY,CAG7BG,CAAAA,CAAW,CAAClB,EAAagB,CAAAA,CAAWC,CAAO,CAAA,CACjD,GAAIT,CAAAA,CAAY,YAAA,CAAaU,CAAQ,CAAA,GAAM,OAAW,CACrDP,CAAAA,EAAAA,CACA,QACD,CAGA,IAAMQ,CAAAA,CAAWX,CAAAA,CAAY,UAAA,CAAW,CACvC,QAAA,CAAUU,CAAAA,CACV,OAAA,CAAS,CAAC,CAAE,MAAA,CAAQE,CAAQ,IACpB,IAAA,CAAK,QAAA,CAAS,OAAA,CAAQN,GAAAA,CAAUC,CAAAA,CAAQK,CAAO,CAAA,CAAE,IAAA,CAAMC,CAAAA,EAASC,CAAAA,CAAYD,CAAI,CAAC,CAAA,CAEzF,SAAA,CAAW,GAAA,CAAS,GACrB,CAAC,CAAA,CAED,OAAO,CAAE,QAAA,CAAUH,CAAAA,CAAS,IAAA,CAAK,GAAG,CAAA,CAAG,QAAA,CAAAC,CAAAA,CAAU,SAAA,CAAAb,CAAAA,CAAW,MAAA,CAAAC,CAAAA,CAAQ,QAAA,CAAU,CAAE,SAAAO,GAAAA,CAAU,MAAA,CAAAC,CAAO,CAAE,CACpG,CAEF,CAKDJ,CAAAA,CAAId,EAAgBC,CAAAA,CAASa,CAAC,EAC/B,CAEA,OAAO,IACR,CAEA,OAAA,EAAgB,CAEhB,CACD","file":"chunk-MRRMIBHE.js","sourcesContent":["/**\n * How many operand bytes follow each opcode, and how to step over one.\n *\n * Anything walking a bytecode stream without executing it needs this: the\n * resolver preflight scanners look for specific opcodes and must skip past\n * everything else without mistaking an operand byte for an instruction.\n *\n * It used to be a hand-copied switch in each of those scanners. They had\n * already drifted: two counted `CALL_PLUGIN` as three bytes wide and the third\n * omitted it from that arm, so a stream containing one desynchronised there and\n * every opcode after it was read at the wrong offset. Adding an opcode meant\n * remembering every copy, and nothing checked that you had.\n *\n * `__tests__/parser/OperandWidth.spec.ts` asserts every opcode has a width, so\n * a new one fails a test rather than silently defaulting to zero operands.\n */\n\nimport { OpCode } from \"@solve-js/parser/OpCode\";\n\n/**\n * Opcodes taking one operand byte.\n *\n * A constant-pool index, or a variable-name index.\n */\nconst ONE_OPERAND: readonly OpCode[] = [\n\tOpCode.PUSH_NUMBER,\n\tOpCode.PUSH_BIGINT,\n\tOpCode.PUSH_HEX,\n\tOpCode.PUSH_STRING,\n\tOpCode.PUSH_BOOLEAN,\n\t// Its operand is a string-pool index holding the exact decimal text, so a\n\t// scanner must step over one byte exactly as it does for PUSH_STRING.\n\tOpCode.PUSH_DECIMAL,\n\tOpCode.LOAD_VAR,\n\tOpCode.STORE_VAR,\n\tOpCode.LOAD_GLOBAL_VAR,\n\tOpCode.STORE_GLOBAL_VAR,\n\tOpCode.DEFINE_USER_FUNCTION,\n\tOpCode.BIND_UNKNOWN,\n\t// Its operand is a constant-pool index, like PUSH_NUMBER's: the epoch-ms\n\t// was resolved at parse time and stored in `numbers`. Omitting it made\n\t// every scanner read that index byte as an opcode, so an ordinary date\n\t// literal desynchronised the whole preflight walk.\n\tOpCode.DATE_LITERAL,\n\t// One byte, the offset direction (0 forward, 1 backward) for \"N working\n\t// days after/before/from <date>\". See WorkdayOffsetParselet. DATE_WORKDAYS_BETWEEN\n\t// takes no operand and so is not listed here.\n\tOpCode.DATE_WORKDAY_OFFSET,\n];\n\n/**\n * Opcodes taking two operand bytes.\n *\n * A callable index plus an argument count, or a matrix's row and column counts.\n */\nconst TWO_OPERANDS: readonly OpCode[] = [\n\tOpCode.CALL_PLUGIN,\n\tOpCode.CALL_BUILTIN,\n\tOpCode.CALL_USER_FUNCTION,\n\tOpCode.MAT_NEW,\n\t// A body index plus the pooled source-expression string.\n\tOpCode.PLOT_INVOKE,\n];\n\n/**\n * Opcodes taking three operand bytes.\n *\n * The map and reduce invocations, which carry a body index alongside their\n * other operands.\n */\n// CALL_PLUGIN_WIDE: a two-byte plugin index plus the one-byte argument count.\nconst THREE_OPERANDS: readonly OpCode[] = [OpCode.MAP_INVOKE, OpCode.REDUCE_INVOKE, OpCode.CALL_PLUGIN_WIDE];\n\n/**\n * Operand byte count for every opcode, indexed by opcode value.\n *\n * A dense array rather than a map, because the preflight scanners run on every\n * keystroke and this is read once per instruction.\n */\nexport const OPERAND_BYTES: readonly number[] = (() => {\n\tconst widths = new Array<number>(256).fill(0);\n\tfor (const op of ONE_OPERAND) widths[op] = 1;\n\tfor (const op of TWO_OPERANDS) widths[op] = 2;\n\tfor (const op of THREE_OPERANDS) widths[op] = 3;\n\treturn widths;\n})();\n\n/**\n * Every opcode that takes at least one operand.\n *\n * Exported so a test can assert the table stays complete as opcodes are added.\n */\nexport const OPCODES_WITH_OPERANDS: readonly OpCode[] = [\n\t...ONE_OPERAND,\n\t...TWO_OPERANDS,\n\t...THREE_OPERANDS,\n];\n\n/**\n * Offset of the instruction after the one at `index`.\n *\n * @param opcodes - The bytecode stream.\n * @param index - Offset of an opcode, not of an operand byte. Passing an\n * operand offset yields nonsense, which is the failure mode this exists to\n * prevent: a caller stepping by hand and getting one width wrong reads the rest\n * of the stream misaligned.\n * @returns Offset of the next opcode. May be past the end when the instruction\n * at `index` is the last one, so callers loop while it is under `opcodes.length`.\n */\nexport function nextInstruction(opcodes: Uint8Array, index: number): number {\n\treturn index + 1 + (OPERAND_BYTES[opcodes[index]] ?? 0);\n}\n","/**\n * Currency async resolver, bridges CurrencyExchangeService to the\n * IAsyncResolver interface for the Suspense architecture.\n *\n * Uses TanStack Query (injected via queryClient) as the single cache layer.\n */\nimport type { QueryClient } from \"@tanstack/query-core\";\nimport type { Token } from \"@solve-js/lexer\";\nimport type { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { numberValue } from \"@solve-js/vm/Value\";\nimport {\n\tcurrencyExchangeService,\n\tCurrencyExchangeService,\n} from \"@solve-js/uom/CurrencyExchange\";\nimport type { IAsyncResolver, AsyncCheckResult } from \"@solve-js/resolvers/ResolverRegistry\";\nimport { nextInstruction } from \"@solve-js/parser/OperandWidth\";\n\nconst CURRENCY_NS = \"currency\";\n\n/**\n * Fetches exchange rates before the VM runs, so a conversion has real numbers.\n *\n * Until rates arrive the line evaluates to a pending value rather than a\n * guessed one, and re-evaluates when they land.\n */\nexport class CurrencyAsyncResolver implements IAsyncResolver {\n\treadonly namespace = CURRENCY_NS;\n\n\tprivate exchange: CurrencyExchangeService;\n\n\tconstructor(exchange?: CurrencyExchangeService) {\n\t\tthis.exchange = exchange ?? currencyExchangeService;\n\t}\n\n\tpreflight(_tokens: Token[], bytecode: BytecodeProgram, packageId: string, signal: AbortSignal, queryClient: QueryClient): AsyncCheckResult | null {\n\t\tconst { opcodes, strings } = bytecode;\n\t\tconst len = opcodes.length;\n\t\tlet i = 0;\n\n\t\tlet lastStrIdx = -1;\n\t\tlet prevStrIdx = -1;\n\n\t\twhile (i < len) {\n\t\t\tconst op = opcodes[i] as OpCode;\n\n\t\t\tif (op === OpCode.PUSH_STRING) {\n\t\t\t\tprevStrIdx = lastStrIdx;\n\t\t\t\tlastStrIdx = opcodes[i + 1];\n\t\t\t}\n\n\t\t\t// Explicit \"X to Y\"/\"X in Y\" conversions (UOM_CONVERT_IN/_TO) are\n\t\t\t// the obvious case, but arithmetic directly on two differently-\n\t\t\t// denominated currency literals, \"0.01 BTC + 1 ETH\", needs the\n\t\t\t// exact same preflight fetch and previously never got it: this\n\t\t\t// scanner only looked for the CONVERT opcodes, so ADD/SUB/MUL/DIV\n\t\t\t// between two currency UOMs skipped preflight entirely, ran with\n\t\t\t// no cached rate, and fell through to the VM's silent-wrong-math\n\t\t\t// fallback instead of ever reaching a network fetch.\n\t\t\tconst isCurrencyCombiningOp =\n\t\t\t\top === OpCode.UOM_CONVERT_IN || op === OpCode.UOM_CONVERT_TO ||\n\t\t\t\top === OpCode.ADD || op === OpCode.SUB || op === OpCode.MUL || op === OpCode.DIV;\n\t\t\tif (isCurrencyCombiningOp) {\n\t\t\t\tif (prevStrIdx >= 0 && lastStrIdx >= 0) {\n\t\t\t\t\tconst fromUnit = strings[prevStrIdx];\n\t\t\t\t\tconst toUnit = strings[lastStrIdx];\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tthis.exchange.isCurrency(fromUnit) &&\n\t\t\t\t\t\tthis.exchange.isCurrency(toUnit) &&\n\t\t\t\t\t\tfromUnit.toUpperCase() !== toUnit.toUpperCase()\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst syncRate = this.exchange.getRateSync(fromUnit, toUnit);\n\t\t\t\t\t\tif (syncRate === null) {\n\t\t\t\t\t\t\tconst fromUpper = fromUnit.toUpperCase();\n\t\t\t\t\t\t\tconst toUpper = toUnit.toUpperCase();\n\n\t\t\t\t\t\t\t// Check TanStack Query cache\n\t\t\t\t\t\t\tconst cacheKey = [CURRENCY_NS, fromUpper, toUpper];\n\t\t\t\t\t\t\tif (queryClient.getQueryData(cacheKey) !== undefined) {\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Fetch via TanStack Query (dedup + retry automatic)\n\t\t\t\t\t\t\tconst resolver = queryClient.fetchQuery({\n\t\t\t\t\t\t\t\tqueryKey: cacheKey,\n\t\t\t\t\t\t\t\tqueryFn: ({ signal: qSignal }) => {\n\t\t\t\t\t\t\t\t\treturn this.exchange.getRate(fromUnit, toUnit, qSignal).then((rate) => numberValue(rate));\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tstaleTime: 5 * 60 * 1000,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\treturn { queryKey: cacheKey.join(\":\"), resolver, packageId, signal, metadata: { fromUnit, toUnit } };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Step over this instruction and its operands. Shared table, because\n\t\t\t// three hand-copied versions of this had already drifted.\n\t\t\ti = nextInstruction(opcodes, i);\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tdestroy(): void {\n\t\t// Cache cleared by ResolverRegistry.unregister() via removeQueries({ queryKey: [\"currency\"] })\n\t}\n}\n"]}
1
+ {"version":3,"sources":["../src/parser/OperandWidth.ts","../src/uom/CurrencyResolver.ts"],"names":["ONE_OPERAND","TWO_OPERANDS","THREE_OPERANDS","OPERAND_BYTES","widths","op","nextInstruction","opcodes","index","CURRENCY_NS","CurrencyAsyncResolver","exchange","currencyExchangeService","_tokens","bytecode","packageId","signal","queryClient","strings","len","i","lastStrIdx","prevStrIdx","fromUnit","toUnit","fromUpper","toUpper","cacheKey","resolver","qSignal","rate","numberValue"],"mappings":"wEAwBA,IAAMA,CAAAA,CAAiC,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,GAAA,CAAA,GAAA,CAAA,EAAA,CAAA,EAwBvC,CAAA,CAOMC,CAAAA,CAAkC,CAAA,EAAA,CAAA,EAAA,CAAA,GAAA,CAAA,GAAA,CAAA,GAOxC,CAAA,CASMC,CAAAA,CAAoC,CAAA,GAAA,CAAA,GAAA,CAAA,GAAiE,CAAA,CAQ9FC,CAAAA,CAAAA,CAAoC,IAAM,CACtD,IAAMC,CAAAA,CAAS,IAAI,KAAA,CAAc,GAAG,CAAA,CAAE,IAAA,CAAK,CAAC,CAAA,CAC5C,IAAA,IAAWC,CAAAA,IAAML,CAAAA,CAAaI,CAAAA,CAAOC,CAAE,CAAA,CA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AAE,SAAAO,GAAAA,CAAU,MAAA,CAAAC,CAAO,CAAE,CACpG,CAEF,CAKDJ,CAAAA,CAAId,EAAgBC,CAAAA,CAASa,CAAC,EAC/B,CAEA,OAAO,IACR,CAEA,OAAA,EAAgB,CAEhB,CACD","file":"chunk-OMHRBKAT.js","sourcesContent":["/**\n * How many operand bytes follow each opcode, and how to step over one.\n *\n * Anything walking a bytecode stream without executing it needs this: the\n * resolver preflight scanners look for specific opcodes and must skip past\n * everything else without mistaking an operand byte for an instruction.\n *\n * It used to be a hand-copied switch in each of those scanners. They had\n * already drifted: two counted `CALL_PLUGIN` as three bytes wide and the third\n * omitted it from that arm, so a stream containing one desynchronised there and\n * every opcode after it was read at the wrong offset. Adding an opcode meant\n * remembering every copy, and nothing checked that you had.\n *\n * `__tests__/parser/OperandWidth.spec.ts` asserts every opcode has a width, so\n * a new one fails a test rather than silently defaulting to zero operands.\n */\n\nimport { OpCode } from \"@solve-js/parser/OpCode\";\n\n/**\n * Opcodes taking one operand byte.\n *\n * A constant-pool index, or a variable-name index.\n */\nconst ONE_OPERAND: readonly OpCode[] = [\n\tOpCode.PUSH_NUMBER,\n\tOpCode.PUSH_BIGINT,\n\tOpCode.PUSH_HEX,\n\tOpCode.PUSH_STRING,\n\tOpCode.PUSH_BOOLEAN,\n\t// Its operand is a string-pool index holding the exact decimal text, so a\n\t// scanner must step over one byte exactly as it does for PUSH_STRING.\n\tOpCode.PUSH_DECIMAL,\n\tOpCode.LOAD_VAR,\n\tOpCode.STORE_VAR,\n\tOpCode.LOAD_GLOBAL_VAR,\n\tOpCode.STORE_GLOBAL_VAR,\n\tOpCode.DEFINE_USER_FUNCTION,\n\tOpCode.BIND_UNKNOWN,\n\t// Its operand is a constant-pool index, like PUSH_NUMBER's: the epoch-ms\n\t// was resolved at parse time and stored in `numbers`. Omitting it made\n\t// every scanner read that index byte as an opcode, so an ordinary date\n\t// literal desynchronised the whole preflight walk.\n\tOpCode.DATE_LITERAL,\n\t// One byte, the offset direction (0 forward, 1 backward) for \"N working\n\t// days after/before/from <date>\". See WorkdayOffsetParselet. DATE_WORKDAYS_BETWEEN\n\t// takes no operand and so is not listed here.\n\tOpCode.DATE_WORKDAY_OFFSET,\n];\n\n/**\n * Opcodes taking two operand bytes.\n *\n * A callable index plus an argument count, or a matrix's row and column counts.\n */\nconst TWO_OPERANDS: readonly OpCode[] = [\n\tOpCode.CALL_PLUGIN,\n\tOpCode.CALL_BUILTIN,\n\tOpCode.CALL_USER_FUNCTION,\n\tOpCode.MAT_NEW,\n\t// A body index plus the pooled source-expression string.\n\tOpCode.PLOT_INVOKE,\n];\n\n/**\n * Opcodes taking three operand bytes.\n *\n * The map and reduce invocations, which carry a body index alongside their\n * other operands.\n */\n// CALL_PLUGIN_WIDE: a two-byte plugin index plus the one-byte argument count.\nconst THREE_OPERANDS: readonly OpCode[] = [OpCode.MAP_INVOKE, OpCode.REDUCE_INVOKE, OpCode.CALL_PLUGIN_WIDE];\n\n/**\n * Operand byte count for every opcode, indexed by opcode value.\n *\n * A dense array rather than a map, because the preflight scanners run on every\n * keystroke and this is read once per instruction.\n */\nexport const OPERAND_BYTES: readonly number[] = (() => {\n\tconst widths = new Array<number>(256).fill(0);\n\tfor (const op of ONE_OPERAND) widths[op] = 1;\n\tfor (const op of TWO_OPERANDS) widths[op] = 2;\n\tfor (const op of THREE_OPERANDS) widths[op] = 3;\n\treturn widths;\n})();\n\n/**\n * Every opcode that takes at least one operand.\n *\n * Exported so a test can assert the table stays complete as opcodes are added.\n */\nexport const OPCODES_WITH_OPERANDS: readonly OpCode[] = [\n\t...ONE_OPERAND,\n\t...TWO_OPERANDS,\n\t...THREE_OPERANDS,\n];\n\n/**\n * Offset of the instruction after the one at `index`.\n *\n * @param opcodes - The bytecode stream.\n * @param index - Offset of an opcode, not of an operand byte. Passing an\n * operand offset yields nonsense, which is the failure mode this exists to\n * prevent: a caller stepping by hand and getting one width wrong reads the rest\n * of the stream misaligned.\n * @returns Offset of the next opcode. May be past the end when the instruction\n * at `index` is the last one, so callers loop while it is under `opcodes.length`.\n */\nexport function nextInstruction(opcodes: Uint8Array, index: number): number {\n\treturn index + 1 + (OPERAND_BYTES[opcodes[index]] ?? 0);\n}\n","/**\n * Currency async resolver, bridges CurrencyExchangeService to the\n * IAsyncResolver interface for the Suspense architecture.\n *\n * Uses TanStack Query (injected via queryClient) as the single cache layer.\n */\nimport type { QueryClient } from \"@tanstack/query-core\";\nimport type { Token } from \"@solve-js/lexer\";\nimport type { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { numberValue } from \"@solve-js/vm/Value\";\nimport {\n\tcurrencyExchangeService,\n\tCurrencyExchangeService,\n} from \"@solve-js/uom/CurrencyExchange\";\nimport type { IAsyncResolver, AsyncCheckResult } from \"@solve-js/resolvers/ResolverRegistry\";\nimport { nextInstruction } from \"@solve-js/parser/OperandWidth\";\n\nconst CURRENCY_NS = \"currency\";\n\n/**\n * Fetches exchange rates before the VM runs, so a conversion has real numbers.\n *\n * Until rates arrive the line evaluates to a pending value rather than a\n * guessed one, and re-evaluates when they land.\n */\nexport class CurrencyAsyncResolver implements IAsyncResolver {\n\treadonly namespace = CURRENCY_NS;\n\n\tprivate exchange: CurrencyExchangeService;\n\n\tconstructor(exchange?: CurrencyExchangeService) {\n\t\tthis.exchange = exchange ?? currencyExchangeService;\n\t}\n\n\tpreflight(_tokens: Token[], bytecode: BytecodeProgram, packageId: string, signal: AbortSignal, queryClient: QueryClient): AsyncCheckResult | null {\n\t\tconst { opcodes, strings } = bytecode;\n\t\tconst len = opcodes.length;\n\t\tlet i = 0;\n\n\t\tlet lastStrIdx = -1;\n\t\tlet prevStrIdx = -1;\n\n\t\twhile (i < len) {\n\t\t\tconst op = opcodes[i] as OpCode;\n\n\t\t\tif (op === OpCode.PUSH_STRING) {\n\t\t\t\tprevStrIdx = lastStrIdx;\n\t\t\t\tlastStrIdx = opcodes[i + 1];\n\t\t\t}\n\n\t\t\t// Explicit \"X to Y\"/\"X in Y\" conversions (UOM_CONVERT_IN/_TO) are\n\t\t\t// the obvious case, but arithmetic directly on two differently-\n\t\t\t// denominated currency literals, \"0.01 BTC + 1 ETH\", needs the\n\t\t\t// exact same preflight fetch and previously never got it: this\n\t\t\t// scanner only looked for the CONVERT opcodes, so ADD/SUB/MUL/DIV\n\t\t\t// between two currency UOMs skipped preflight entirely, ran with\n\t\t\t// no cached rate, and fell through to the VM's silent-wrong-math\n\t\t\t// fallback instead of ever reaching a network fetch.\n\t\t\tconst isCurrencyCombiningOp =\n\t\t\t\top === OpCode.UOM_CONVERT_IN || op === OpCode.UOM_CONVERT_TO ||\n\t\t\t\top === OpCode.ADD || op === OpCode.SUB || op === OpCode.MUL || op === OpCode.DIV;\n\t\t\tif (isCurrencyCombiningOp) {\n\t\t\t\tif (prevStrIdx >= 0 && lastStrIdx >= 0) {\n\t\t\t\t\tconst fromUnit = strings[prevStrIdx];\n\t\t\t\t\tconst toUnit = strings[lastStrIdx];\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tthis.exchange.isCurrency(fromUnit) &&\n\t\t\t\t\t\tthis.exchange.isCurrency(toUnit) &&\n\t\t\t\t\t\tfromUnit.toUpperCase() !== toUnit.toUpperCase()\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst syncRate = this.exchange.getRateSync(fromUnit, toUnit);\n\t\t\t\t\t\tif (syncRate === null) {\n\t\t\t\t\t\t\tconst fromUpper = fromUnit.toUpperCase();\n\t\t\t\t\t\t\tconst toUpper = toUnit.toUpperCase();\n\n\t\t\t\t\t\t\t// Check TanStack Query cache\n\t\t\t\t\t\t\tconst cacheKey = [CURRENCY_NS, fromUpper, toUpper];\n\t\t\t\t\t\t\tif (queryClient.getQueryData(cacheKey) !== undefined) {\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Fetch via TanStack Query (dedup + retry automatic)\n\t\t\t\t\t\t\tconst resolver = queryClient.fetchQuery({\n\t\t\t\t\t\t\t\tqueryKey: cacheKey,\n\t\t\t\t\t\t\t\tqueryFn: ({ signal: qSignal }) => {\n\t\t\t\t\t\t\t\t\treturn this.exchange.getRate(fromUnit, toUnit, qSignal).then((rate) => numberValue(rate));\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tstaleTime: 5 * 60 * 1000,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\treturn { queryKey: cacheKey.join(\":\"), resolver, packageId, signal, metadata: { fromUnit, toUnit } };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Step over this instruction and its operands. Shared table, because\n\t\t\t// three hand-copied versions of this had already drifted.\n\t\t\ti = nextInstruction(opcodes, i);\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tdestroy(): void {\n\t\t// Cache cleared by ResolverRegistry.unregister() via removeQueries({ queryKey: [\"currency\"] })\n\t}\n}\n"]}
@@ -1,2 +1,2 @@
1
- import {a as a$1,b,c as c$1}from'./chunk-PIZQIQVM.js';var o={WORKER_CANCELLED:"WORKER_CANCELLED",WORKER_TERMINATED:"WORKER_TERMINATED",WORKER_TRANSPORT_FAILED:"WORKER_TRANSPORT_FAILED",WORKER_UNKNOWN_METHOD:"WORKER_UNKNOWN_METHOD",WORKER_NOT_INITIALISED:"WORKER_NOT_INITIALISED",WORKER_UNKNOWN_PACKAGE:"WORKER_UNKNOWN_PACKAGE"};function t(r){let e={name:r.name,category:r.category,code:r.code,message:r.message,recoverable:r.recoverable};return r.expected!==void 0&&(e.expected=r.expected),r.found!==void 0&&(e.found=r.found),r.suggestion!==void 0&&(e.suggestion=r.suggestion),r.span!==void 0&&(e.span=r.span),e}function a(r){let e=Object.values(a$1).includes(r.category)?r.category:"INTERNAL";return new b(e,{code:r.code,message:r.message,expected:r.expected,found:r.found,suggestion:r.suggestion,recoverable:r.recoverable,span:r.span})}function s(r){return c$1.execution(o.WORKER_CANCELLED,r?`The worker request "${r}" was cancelled`:"The worker request was cancelled",r?{method:r}:void 0)}function c(){return c$1.execution(o.WORKER_TERMINATED,"The worker engine was terminated before this request completed")}function g(r){return c$1.external(o.WORKER_TRANSPORT_FAILED,`The worker transport failed: ${r}`,{detail:r})}export{o as a,t as b,a as c,s as d,c as e,g as f};//# sourceMappingURL=chunk-4ETS224G.js.map
2
- //# sourceMappingURL=chunk-4ETS224G.js.map
1
+ import {a as a$1,b,c as c$1}from'./chunk-BDF4VCQX.js';var o={WORKER_CANCELLED:"WORKER_CANCELLED",WORKER_TERMINATED:"WORKER_TERMINATED",WORKER_TRANSPORT_FAILED:"WORKER_TRANSPORT_FAILED",WORKER_UNKNOWN_METHOD:"WORKER_UNKNOWN_METHOD",WORKER_NOT_INITIALISED:"WORKER_NOT_INITIALISED",WORKER_UNKNOWN_PACKAGE:"WORKER_UNKNOWN_PACKAGE"};function t(r){let e={name:r.name,category:r.category,code:r.code,message:r.message,recoverable:r.recoverable};return r.expected!==void 0&&(e.expected=r.expected),r.found!==void 0&&(e.found=r.found),r.suggestion!==void 0&&(e.suggestion=r.suggestion),r.span!==void 0&&(e.span=r.span),e}function a(r){let e=Object.values(a$1).includes(r.category)?r.category:"INTERNAL";return new b(e,{code:r.code,message:r.message,expected:r.expected,found:r.found,suggestion:r.suggestion,recoverable:r.recoverable,span:r.span})}function s(r){return c$1.execution(o.WORKER_CANCELLED,r?`The worker request "${r}" was cancelled`:"The worker request was cancelled",r?{method:r}:void 0)}function c(){return c$1.execution(o.WORKER_TERMINATED,"The worker engine was terminated before this request completed")}function g(r){return c$1.external(o.WORKER_TRANSPORT_FAILED,`The worker transport failed: ${r}`,{detail:r})}export{o as a,t as b,a as c,s as d,c as e,g as f};//# sourceMappingURL=chunk-PTQCHMYA.js.map
2
+ //# sourceMappingURL=chunk-PTQCHMYA.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors/WorkerError.ts"],"names":["WorkerErrorCodes","serializeEngineError","error","dto","deserializeEngineError","category","ErrorCategory","EngineError","workerCancelledError","method","ErrorFactory","workerTerminatedError","workerTransportError","detail"],"mappings":"sDAoBO,IAAMA,EAAmB,CAE/B,gBAAA,CAAkB,kBAAA,CAElB,iBAAA,CAAmB,oBAEnB,uBAAA,CAAyB,yBAAA,CAEzB,qBAAA,CAAuB,uBAAA,CAEvB,uBAAwB,wBAAA,CAExB,sBAAA,CAAwB,wBACzB,EAyBO,SAASC,CAAAA,CAAqBC,CAAAA,CAA2C,CAC/E,IAAMC,EAA6B,CAClC,IAAA,CAAMD,CAAAA,CAAM,IAAA,CACZ,SAAUA,CAAAA,CAAM,QAAA,CAChB,IAAA,CAAMA,CAAAA,CAAM,KACZ,OAAA,CAASA,CAAAA,CAAM,QACf,WAAA,CAAaA,CAAAA,CAAM,WACpB,CAAA,CAIA,OAAIA,CAAAA,CAAM,QAAA,GAAa,SAAWC,CAAAA,CAAI,QAAA,CAAWD,CAAAA,CAAM,QAAA,CAAA,CACnDA,EAAM,KAAA,GAAU,MAAA,GAAWC,CAAAA,CAAI,KAAA,CAAQD,EAAM,KAAA,CAAA,CAC7CA,CAAAA,CAAM,aAAe,MAAA,GAAWC,CAAAA,CAAI,WAAaD,CAAAA,CAAM,UAAA,CAAA,CAGvDA,CAAAA,CAAM,IAAA,GAAS,SAAWC,CAAAA,CAAI,IAAA,CAAOD,CAAAA,CAAM,IAAA,CAAA,CACxCC,CACR,CAWO,SAASC,CAAAA,CAAuBD,CAAAA,CAAyC,CAC/E,IAAME,CAAAA,CAAW,OAAO,MAAA,CAAOC,GAAa,EAAE,QAAA,CAASH,CAAAA,CAAI,QAAQ,CAAA,CAChEA,EAAI,QAAA,CAAA,UAAA,CAEP,OAAO,IAAII,CAAAA,CAAYF,EAAU,CAChC,IAAA,CAAMF,CAAAA,CAAI,IAAA,CACV,QAASA,CAAAA,CAAI,OAAA,CACb,SAAUA,CAAAA,CAAI,QAAA,CACd,MAAOA,CAAAA,CAAI,KAAA,CACX,UAAA,CAAYA,CAAAA,CAAI,WAChB,WAAA,CAAaA,CAAAA,CAAI,WAAA,CACjB,IAAA,CAAMA,EAAI,IACX,CAAC,CACF,CAGO,SAASK,CAAAA,CAAqBC,CAAAA,CAA8B,CAClE,OAAOC,GAAAA,CAAa,UACnBV,CAAAA,CAAiB,gBAAA,CACjBS,CAAAA,CACG,CAAA,oBAAA,EAAuBA,CAAM,CAAA,eAAA,CAAA,CAC7B,kCAAA,CACHA,CAAAA,CAAS,CAAE,OAAAA,CAAO,CAAA,CAAI,MACvB,CACD,CAGO,SAASE,CAAAA,EAAqC,CACpD,OAAOD,GAAAA,CAAa,UACnBV,CAAAA,CAAiB,iBAAA,CACjB,gEACD,CACD,CAGO,SAASY,CAAAA,CAAqBC,CAAAA,CAA6B,CACjE,OAAOH,GAAAA,CAAa,QAAA,CACnBV,CAAAA,CAAiB,uBAAA,CACjB,gCAAgCa,CAAM,CAAA,CAAA,CACtC,CAAE,MAAA,CAAAA,CAAO,CACV,CACD","file":"chunk-4ETS224G.js","sourcesContent":["/**\n * Structured errors for the off-main-thread worker harness, and the pair of\n * functions that carry an {@link EngineError} across a `postMessage` boundary.\n *\n * A worker runs in another thread, so a failure there cannot be `throw`n back\n * into the caller's stack. It has to be encoded, posted, and rebuilt on the\n * main side, and it must arrive as a real structured error rather than a lost\n * promise or an opaque string. {@link serializeEngineError} projects an\n * `EngineError` onto a plain, clone-safe object; {@link deserializeEngineError}\n * rebuilds one from that object so the main-side `catch` sees the same\n * `code`/`category`/`message` it would have seen in-process.\n */\n\nimport { EngineError, ErrorCategory, ErrorFactory, type SourceSpan } from \"./EngineError\";\n\n/**\n * Codes the worker harness owns, co-located here rather than unioned into the\n * core catalog, matching the convention `errors/ErrorCode.ts` documents for a\n * domain that keeps its own small code object.\n */\nexport const WorkerErrorCodes = {\n\t/** The caller aborted the request through its `AbortSignal`. */\n\tWORKER_CANCELLED: \"WORKER_CANCELLED\",\n\t/** The worker engine was torn down while a request was still in flight. */\n\tWORKER_TERMINATED: \"WORKER_TERMINATED\",\n\t/** The transport failed or the worker exited before answering. */\n\tWORKER_TRANSPORT_FAILED: \"WORKER_TRANSPORT_FAILED\",\n\t/** A request named a method the runtime does not expose. */\n\tWORKER_UNKNOWN_METHOD: \"WORKER_UNKNOWN_METHOD\",\n\t/** A request arrived before the runtime finished building its engine. */\n\tWORKER_NOT_INITIALISED: \"WORKER_NOT_INITIALISED\",\n\t/** An init named a package the runtime could not resolve. */\n\tWORKER_UNKNOWN_PACKAGE: \"WORKER_UNKNOWN_PACKAGE\",\n} as const;\n\n/**\n * A structured error flattened for transport.\n *\n * Every field is a string, a boolean, or an object of numbers, so the whole\n * thing survives both `structuredClone` (what `postMessage` uses) and\n * `JSON.stringify` (what a host may log). `context`, `cause` and `timestamp`\n * are deliberately dropped rather than posted: a context can hold a value that\n * is not clone-safe, and none of the three is part of what a main-side handler\n * branches on.\n */\nexport interface SerializedEngineError {\n\tname: string;\n\tcategory: ErrorCategory;\n\tcode: string;\n\tmessage: string;\n\texpected?: string;\n\tfound?: string;\n\tsuggestion?: string;\n\trecoverable: boolean;\n\tspan?: SourceSpan;\n}\n\n/** Flatten an {@link EngineError} into a clone-safe {@link SerializedEngineError}. */\nexport function serializeEngineError(error: EngineError): SerializedEngineError {\n\tconst dto: SerializedEngineError = {\n\t\tname: error.name,\n\t\tcategory: error.category,\n\t\tcode: error.code,\n\t\tmessage: error.message,\n\t\trecoverable: error.recoverable,\n\t};\n\t// Only the optional string fields that were actually set cross the wire, so\n\t// a rebuilt error has `undefined` exactly where the original did rather than\n\t// an explicit `undefined` property a deep-equal would trip on.\n\tif (error.expected !== undefined) dto.expected = error.expected;\n\tif (error.found !== undefined) dto.found = error.found;\n\tif (error.suggestion !== undefined) dto.suggestion = error.suggestion;\n\t// A span is character offsets (plain numbers), so it is safe to carry and\n\t// useful for a host that highlights the failing range.\n\tif (error.span !== undefined) dto.span = error.span;\n\treturn dto;\n}\n\n/**\n * Rebuild an {@link EngineError} from its transported form.\n *\n * The category string round-trips straight back into the `ErrorCategory` enum\n * (its members ARE their own string values), so a main-side `catch` reads the\n * same category the worker raised. A malformed category (a message that was not\n * produced by {@link serializeEngineError}) falls back to `INTERNAL` rather than\n * constructing an error with an invalid category.\n */\nexport function deserializeEngineError(dto: SerializedEngineError): EngineError {\n\tconst category = Object.values(ErrorCategory).includes(dto.category)\n\t\t? dto.category\n\t\t: ErrorCategory.INTERNAL;\n\treturn new EngineError(category, {\n\t\tcode: dto.code,\n\t\tmessage: dto.message,\n\t\texpected: dto.expected,\n\t\tfound: dto.found,\n\t\tsuggestion: dto.suggestion,\n\t\trecoverable: dto.recoverable,\n\t\tspan: dto.span,\n\t});\n}\n\n/** The error a request rejects with when its caller aborts through an `AbortSignal`. */\nexport function workerCancelledError(method?: string): EngineError {\n\treturn ErrorFactory.execution(\n\t\tWorkerErrorCodes.WORKER_CANCELLED,\n\t\tmethod\n\t\t\t? `The worker request \"${method}\" was cancelled`\n\t\t\t: \"The worker request was cancelled\",\n\t\tmethod ? { method } : undefined,\n\t);\n}\n\n/** The error every pending request rejects with when the worker engine is terminated. */\nexport function workerTerminatedError(): EngineError {\n\treturn ErrorFactory.execution(\n\t\tWorkerErrorCodes.WORKER_TERMINATED,\n\t\t\"The worker engine was terminated before this request completed\",\n\t);\n}\n\n/** The error a request rejects with when the transport fails or the worker exits early. */\nexport function workerTransportError(detail: string): EngineError {\n\treturn ErrorFactory.external(\n\t\tWorkerErrorCodes.WORKER_TRANSPORT_FAILED,\n\t\t`The worker transport failed: ${detail}`,\n\t\t{ detail },\n\t);\n}\n"]}
1
+ {"version":3,"sources":["../src/errors/WorkerError.ts"],"names":["WorkerErrorCodes","serializeEngineError","error","dto","deserializeEngineError","category","ErrorCategory","EngineError","workerCancelledError","method","ErrorFactory","workerTerminatedError","workerTransportError","detail"],"mappings":"sDAoBO,IAAMA,EAAmB,CAE/B,gBAAA,CAAkB,kBAAA,CAElB,iBAAA,CAAmB,oBAEnB,uBA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ACnBV,CAAAA,CAAiB,gBAAA,CACjBS,CAAAA,CACG,CAAA,oBAAA,EAAuBA,CAAM,CAAA,eAAA,CAAA,CAC7B,kCAAA,CACHA,CAAAA,CAAS,CAAE,OAAAA,CAAO,CAAA,CAAI,MACvB,CACD,CAGO,SAASE,CAAAA,EAAqC,CACpD,OAAOD,GAAAA,CAAa,UACnBV,CAAAA,CAAiB,iBAAA,CACjB,gEACD,CACD,CAGO,SAASY,CAAAA,CAAqBC,CAAAA,CAA6B,CACjE,OAAOH,GAAAA,CAAa,QAAA,CACnBV,CAAAA,CAAiB,uBAAA,CACjB,gCAAgCa,CAAM,CAAA,CAAA,CACtC,CAAE,MAAA,CAAAA,CAAO,CACV,CACD","file":"chunk-PTQCHMYA.js","sourcesContent":["/**\n * Structured errors for the off-main-thread worker harness, and the pair of\n * functions that carry an {@link EngineError} across a `postMessage` boundary.\n *\n * A worker runs in another thread, so a failure there cannot be `throw`n back\n * into the caller's stack. It has to be encoded, posted, and rebuilt on the\n * main side, and it must arrive as a real structured error rather than a lost\n * promise or an opaque string. {@link serializeEngineError} projects an\n * `EngineError` onto a plain, clone-safe object; {@link deserializeEngineError}\n * rebuilds one from that object so the main-side `catch` sees the same\n * `code`/`category`/`message` it would have seen in-process.\n */\n\nimport { EngineError, ErrorCategory, ErrorFactory, type SourceSpan } from \"./EngineError\";\n\n/**\n * Codes the worker harness owns, co-located here rather than unioned into the\n * core catalog, matching the convention `errors/ErrorCode.ts` documents for a\n * domain that keeps its own small code object.\n */\nexport const WorkerErrorCodes = {\n\t/** The caller aborted the request through its `AbortSignal`. */\n\tWORKER_CANCELLED: \"WORKER_CANCELLED\",\n\t/** The worker engine was torn down while a request was still in flight. */\n\tWORKER_TERMINATED: \"WORKER_TERMINATED\",\n\t/** The transport failed or the worker exited before answering. */\n\tWORKER_TRANSPORT_FAILED: \"WORKER_TRANSPORT_FAILED\",\n\t/** A request named a method the runtime does not expose. */\n\tWORKER_UNKNOWN_METHOD: \"WORKER_UNKNOWN_METHOD\",\n\t/** A request arrived before the runtime finished building its engine. */\n\tWORKER_NOT_INITIALISED: \"WORKER_NOT_INITIALISED\",\n\t/** An init named a package the runtime could not resolve. */\n\tWORKER_UNKNOWN_PACKAGE: \"WORKER_UNKNOWN_PACKAGE\",\n} as const;\n\n/**\n * A structured error flattened for transport.\n *\n * Every field is a string, a boolean, or an object of numbers, so the whole\n * thing survives both `structuredClone` (what `postMessage` uses) and\n * `JSON.stringify` (what a host may log). `context`, `cause` and `timestamp`\n * are deliberately dropped rather than posted: a context can hold a value that\n * is not clone-safe, and none of the three is part of what a main-side handler\n * branches on.\n */\nexport interface SerializedEngineError {\n\tname: string;\n\tcategory: ErrorCategory;\n\tcode: string;\n\tmessage: string;\n\texpected?: string;\n\tfound?: string;\n\tsuggestion?: string;\n\trecoverable: boolean;\n\tspan?: SourceSpan;\n}\n\n/** Flatten an {@link EngineError} into a clone-safe {@link SerializedEngineError}. */\nexport function serializeEngineError(error: EngineError): SerializedEngineError {\n\tconst dto: SerializedEngineError = {\n\t\tname: error.name,\n\t\tcategory: error.category,\n\t\tcode: error.code,\n\t\tmessage: error.message,\n\t\trecoverable: error.recoverable,\n\t};\n\t// Only the optional string fields that were actually set cross the wire, so\n\t// a rebuilt error has `undefined` exactly where the original did rather than\n\t// an explicit `undefined` property a deep-equal would trip on.\n\tif (error.expected !== undefined) dto.expected = error.expected;\n\tif (error.found !== undefined) dto.found = error.found;\n\tif (error.suggestion !== undefined) dto.suggestion = error.suggestion;\n\t// A span is character offsets (plain numbers), so it is safe to carry and\n\t// useful for a host that highlights the failing range.\n\tif (error.span !== undefined) dto.span = error.span;\n\treturn dto;\n}\n\n/**\n * Rebuild an {@link EngineError} from its transported form.\n *\n * The category string round-trips straight back into the `ErrorCategory` enum\n * (its members ARE their own string values), so a main-side `catch` reads the\n * same category the worker raised. A malformed category (a message that was not\n * produced by {@link serializeEngineError}) falls back to `INTERNAL` rather than\n * constructing an error with an invalid category.\n */\nexport function deserializeEngineError(dto: SerializedEngineError): EngineError {\n\tconst category = Object.values(ErrorCategory).includes(dto.category)\n\t\t? dto.category\n\t\t: ErrorCategory.INTERNAL;\n\treturn new EngineError(category, {\n\t\tcode: dto.code,\n\t\tmessage: dto.message,\n\t\texpected: dto.expected,\n\t\tfound: dto.found,\n\t\tsuggestion: dto.suggestion,\n\t\trecoverable: dto.recoverable,\n\t\tspan: dto.span,\n\t});\n}\n\n/** The error a request rejects with when its caller aborts through an `AbortSignal`. */\nexport function workerCancelledError(method?: string): EngineError {\n\treturn ErrorFactory.execution(\n\t\tWorkerErrorCodes.WORKER_CANCELLED,\n\t\tmethod\n\t\t\t? `The worker request \"${method}\" was cancelled`\n\t\t\t: \"The worker request was cancelled\",\n\t\tmethod ? { method } : undefined,\n\t);\n}\n\n/** The error every pending request rejects with when the worker engine is terminated. */\nexport function workerTerminatedError(): EngineError {\n\treturn ErrorFactory.execution(\n\t\tWorkerErrorCodes.WORKER_TERMINATED,\n\t\t\"The worker engine was terminated before this request completed\",\n\t);\n}\n\n/** The error a request rejects with when the transport fails or the worker exits early. */\nexport function workerTransportError(detail: string): EngineError {\n\treturn ErrorFactory.external(\n\t\tWorkerErrorCodes.WORKER_TRANSPORT_FAILED,\n\t\t`The worker transport failed: ${detail}`,\n\t\t{ detail },\n\t);\n}\n"]}
@@ -1,2 +1,2 @@
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
+ import {a}from'./chunk-XFJABR3B.js';import {c}from'./chunk-IJMNVBIS.js';import {c as c$1}from'./chunk-BDF4VCQX.js';var N=32,L=2;function I(a){return a.shape!==void 0?a.shape:a.startTokenTypes!==void 0?[{types:a.startTokenTypes}]:[]}var x=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(I),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,L),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=O(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 O(a){for(let e=0;e<a.length;e++){let r=a.charCodeAt(e);if(r>=65&&r<=90)return true}return false}var B={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 z(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"],M=(()=>{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})(),P=new Set;function D(a){a.shape!==void 0&&a.shape.length>0||a.startTokenTypes===void 0&&a.unshapedReason===void 0&&(P.has(a.name)||(P.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 U=class{constructor(e={}){this.rules=[];this.sortedRulesCache=null;this.rulesByTokenType=new Map;this.ruleIndexCache=null;this.candidateBuffer=[];this.normalizeCalls=0;this.phraseTrie=new w;this.ruleShapesCache=null;this.options={...B,...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 w;}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 x(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=I(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>=M.length||M[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&&(z(m.replacement[0],d),t({rule:m.ruleName??"phrase-trie",sourceTokens:d,fusedToken:m.replacement[0]})),o+=m.consumed,f=true;continue}}let v=u?l.candidates(c,o):null;if(v!==null&&C(v)){h!==null&&h.push(c[o]),o++;continue}for(let m of this.rulesAt(v,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 b of d.replacement)h.push(b);if(d.consumed>1&&d.replacement.length===1)z(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 b of d.replacement)t({rule:m.name,sourceTokens:A,fusedToken:b});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 w=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 H(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 ne(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 re(){return [H()]}export{w as a,S as b,U as c,H as d,ne as e,re as f};//# sourceMappingURL=chunk-PWWQZFAE.js.map
2
+ //# sourceMappingURL=chunk-PWWQZFAE.js.map
@@ -0,0 +1 @@
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"],"mappings":"mHAiEA,IAAMA,CAAAA,CAAY,EAAA,CAeZC,CAAAA,CAAa,CAAA,CASZ,SAASC,CAAAA,CAAeC,CAAAA,CAA2C,CACzE,OAAIA,CAAAA,CAAK,KAAA,GAAU,MAAA,CAAkBA,EAAK,KAAA,CACtCA,CAAAA,CAAK,eAAA,GAAoB,MAAA,CAAkB,CAAC,CAAE,KAAA,CAAOA,CAAAA,CAAK,eAAgB,CAAC,CAAA,CACxE,EACR,CA8BO,IAAMC,CAAAA,CAAN,KAAgB,CA2BtB,WAAA,CAAYC,CAAAA,CAAwC,CACnD,IAAA,CAAK,KAAA,CAAQA,CAAAA,CACb,IAAMC,CAAAA,CAAID,CAAAA,CAAY,MAAA,CAChBE,CAAAA,CAAI,IAAA,CAAK,GAAA,CAAI,CAAA,CAAG,IAAA,CAAK,KAAKD,CAAAA,CAAIN,CAAS,CAAC,CAAA,CAC9C,IAAA,CAAK,KAAA,CAAQO,CAAAA,CACb,IAAA,CAAK,QAAU,IAAI,WAAA,CAAYA,CAAC,CAAA,CAEhC,IAAMC,CAAAA,CAASH,CAAAA,CAAY,GAAA,CAAIH,CAAc,CAAA,CAOzCO,CAAAA,CAAY,CAAA,CAChB,IAAA,IAAWC,CAAAA,IAASF,CAAAA,CACnB,IAAA,IAAWG,GAAAA,IAAQD,CAAAA,CAClB,IAAA,IAAWE,CAAAA,IAAKD,GAAAA,CAAK,KAAA,EAAS,EAAC,CAAGF,CAAAA,CAAY,KAAK,GAAA,CAAIA,CAAAA,CAAWI,CAAAA,CAAYD,CAAC,CAAC,CAAA,CAGlF,IAAA,CAAK,QAAA,CAAWH,CAAAA,CAAY,CAAA,CAE5B,IAAIK,CAAAA,CAAQ,C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OAAO,CAELX,CAAAA,EACF,CACF","file":"chunk-PWWQZFAE.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}. The table\n * itself lives in `lexer/BuiltinPhrases.ts`, shared with the lexer's token\n * lookup, and is re-exported here so existing imports keep working.\n */\nexport { BUILTIN_PHRASES } from \"@solve-js/lexer/BuiltinPhrases\";\n\n//#endregion\n"]}
@@ -0,0 +1,3 @@
1
+ import {a as a$1}from'./chunk-XEIDV5JP.js';import {g,D}from'./chunk-5TCSFTZD.js';import {Z,R,ua,sa}from'./chunk-UXR7JIPX.js';import {m}from'./chunk-IPSOWFCA.js';import {a}from'./chunk-LHLW7JLS.js';var x={floatResult:{decimalPlaces:2,enableSeperator:true},numberResult:{decimalSeparatorLocale:"en-US"},hexResult:{enablePadding:false,paddingZeros:0},unitOfMeasurementResult:{decimalPlaces:2},percentageResult:{decimalPlaces:2},dateResult:{format:"long"}};function P(t,e,o,r){let n=o.floatResult.enableSeperator,a=o.numberResult.decimalSeparatorLocale;if(r!==void 0&&Number.isFinite(t)){let c=t.toLocaleString(a||"en-US",{minimumFractionDigits:r,maximumFractionDigits:r,useGrouping:n});return `${e.display.resultPrefix}${c}`}let i=o.floatResult.decimalPlaces,s=a$1(t,i,n,a);return `${e.display.resultPrefix}${s}`}function T(t,e,o,r){let n=r.floatResult.decimalPlaces,a=r.floatResult.enableSeperator,i=r.numberResult.decimalSeparatorLocale||"en-US",s=Math.max(n,1),c=t.toLocaleString(i,{useGrouping:a,minimumFractionDigits:0,maximumFractionDigits:n}),l=Math.abs(e).toLocaleString(i,{useGrouping:a,minimumFractionDigits:1,maximumFractionDigits:s});return `${o.display.resultPrefix}${c} \xB1 ${l}`}function w(t,e,o){if(typeof t=="number"&&!Number.isFinite(t))return `= ${t}`;let r=typeof t=="bigint"?t<0n:t<0,n=r?"-":"",a=c=>typeof t=="bigint"?(r?-t:t).toString(c):Math.abs(Math.trunc(t)).toString(c);if(o==="bin")return `= ${n}0b${a(2)}`;if(o==="oct")return `= ${n}0o${a(8)}`;let i=e.hexResult.enablePadding?e.hexResult.paddingZeros:0,s=a(16).toUpperCase().padStart(i,"0");return `= ${n}0x${s}`}var N=2e4;function U(t){let e=t<0n?-t:t;if(Number.isFinite(Number(e)))return `= ${t}`;let o=e.toString(16).length*4;if(o*Math.LN2/Math.LN10<=N)return `= ${t}`;let r=o*Math.LN2/Math.LN10,n=Math.floor(r),a=Math.pow(10,r-n);return `= ${t<0n?"-":""}~${a.toFixed(3)}e+${n} (an exact integer of about ${(n+1).toLocaleString("en-US")} digits, too large to print)`}function C(t){return `= ${t}`}function E(t){return `= ${t}`}function G(t,e,o){let r=new Date(t),n=o.dateResult?.format??"long",a=r.getHours()===0&&r.getMinutes()===0&&r.getSeconds()===0&&r.getMilliseconds()===0;if(n==="long"){let g=r.toLocaleDateString(e.code,{weekday:"long",year:"numeric",month:"long",day:"numeric"});return a?`= ${g}`:`= ${g}, ${r.toLocaleTimeString(e.code)}`}let i=g=>String(g).padStart(2,"0"),s=r.getFullYear(),c=i(r.getMonth()+1),l=i(r.getDate()),u;if(n==="iso"?u=`${s}-${c}-${l}`:n==="dmy"?u=`${l}/${c}/${s}`:u=`${c}/${l}/${s}`,a)return `= ${u}`;let m=`${i(r.getHours())}:${i(r.getMinutes())}:${i(r.getSeconds())}`;return n==="iso"?`= ${u}T${m}`:`= ${u} ${m}`}function j(t){let e=t<0?"-":"",o=Math.round(Math.abs(t)/1e3),r=Math.floor(o/3600),n=Math.floor(o%3600/60),a=o%60,i=String(n).padStart(2,"0");if(a===0)return `${e}${r}:${i}`;let s=String(a).padStart(2,"0");return `${e}${r}:${i}:${s}`}var L=new Map;function k(t){let e=L.get(t);return e===void 0&&(e=new Intl.NumberFormat(t).formatToParts(1.1).find(o=>o.type==="decimal")?.value??".",L.set(t,e)),e}function f(t,e,o){let r=/^(-?)(\d+)(?:\.(\d+))?$/.exec(t);if(!r)return t;let[,n,a,i]=r,s=o?BigInt(a).toLocaleString(e,{useGrouping:true}):a;return i===void 0?`${n}${s}`:`${n}${s}${k(e)}${i}`}function A(t,e,o,r,n){if(e==="ms")return `= ${j(t)}`;e==="l100km"&&(e="l/100km"),e==="mps2"&&(e="m/s\xB2");let a=r.unitOfMeasurementResult.decimalPlaces,i=r.floatResult.enableSeperator,s=r.numberResult.decimalSeparatorLocale||"en-US",l=e&&["days","weeks","months","years","hours","minutes","seconds","day","week","month","year","hour","minute","second"].includes(e),u;l&&t===Math.floor(t)?u=f(t.toString(),s,i):u=f(t.toFixed(a),s,i);let m=e?ua[e.toUpperCase()]:void 0;if(m){let h=n?f(sa(n,a),s,i):u,y=m.spaced?" ":"";return `= ${m.position==="prefix"?`${m.symbol}${y}${h}`:`${h}${y}${m.symbol}`}`}return `= ${n?f(sa(n,a),s,i):u} ${e||""}`.trim()}function I(t,e){if(typeof t=="boolean")return t?"true":"false";if(typeof t=="object"&&t!==null)return R(t);let o=e.floatResult.decimalPlaces,r=e.floatResult.enableSeperator,n=e.numberResult.decimalSeparatorLocale;return a$1(t,o,r,n)}function O(t,e,o){let r=Z(t),n=[];for(let a=0;a<t.rows;a++){let i=[];for(let s=0;s<t.cols;s++)i.push(I(r[a*t.cols+s],o));n.push(i.join(", "));}return `${e.display.resultPrefix}[${n.join("; ")}]`}function at(t,e){let o=e||x,r=Z(t),n=[];for(let i=0;i<t.rows;i++){let s=[];for(let c=0;c<t.cols;c++)s.push(I(r[i*t.cols+c],o));n.push(s);}let a=[];for(let i=0;i<t.cols;i++){let s=0;for(let c=0;c<t.rows;c++)s=Math.max(s,n[c][i].length);a.push(s);}return n.map(i=>`[ ${i.map((s,c)=>s.padStart(a[c])).join(" ")} ]`).join(`
2
+ `)}function _(t,e,o){return `${o.display.resultPrefix}${t}:${e}`}function B(t,e,o){let r=o.percentageResult.decimalPlaces;return `= ${(t*100).toFixed(r)}${e.display.percentageSuffix}`}function H(t,e){return `= ${t} ${e||""}`.trim()}function V(t){if(t.addr===void 0)return `/${t.prefix}`;let e=D(t.addr);return t.prefix===void 0?e:`${e}/${t.prefix}`}function Y(t,e,o){let r=e.display.resultPrefix,n=l=>{let u=t.unit!==void 0?new m(6,l.value,t.unit):new m(0,l.value);u.exact=l.exact;let m$1=W(u,o);return m$1.startsWith(r)?m$1.slice(r.length):m$1},[a,i]=t.shares,s=`${n(a)} each`;if(i===void 0)return `${r}${s}`;let c=i.count===1?"share":"shares";return `${r}${s}, with ${i.count} ${c} paying ${n(i)}`}function W(t,e){let o=e||x,r=o.numberResult.decimalSeparatorLocale||"en",n=a(r);switch(t.type){case 0:return t.uncertainty!==void 0?T(t.value,t.uncertainty,n,o):P(t.value,n,o,t.decimalPlaces);case 1:return w(t.value,o,t.unit);case 2:return U(t.value);case 3:return C(t.value);case 10:return E(t.value);case 4:return G(t.value,n,o);case 6:return A(t.value,t.unit,n,o,t.exact);case 7:return O(t.value,n,o);case 8:{let a=t.value;return _(a.min,a.max,n)}case 14:return `${n.display.resultPrefix}${g(t.value)}`;case 15:return Y(t.value,n,o);case 16:return `${n.display.resultPrefix}${t.value.label}`;case 17:return `${n.display.resultPrefix}${V(t.value)}`;case 9:return R(t.value);case 5:return B(t.value,n,o);case 11:return H(t.value,t.unit);case 13:return t.unit??String(t.value);default:return `= ${String(t.value)}`}}export{x as a,at as b,W as c};//# sourceMappingURL=chunk-RE6AIU6Y.js.map
3
+ //# sourceMappingURL=chunk-RE6AIU6Y.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/format/FormattingSettings.ts","../src/format/FormatEngine.ts"],"names":["DEFAULT_FORMATTING_SETTINGS","formatNumber","value","locale","settings","decimalPlaces","sep","loc","formatted","dp","autoFormatIntegerOrFloat","formatUncertain","center","uncertainty","useGrouping","spreadMax","centerText","spreadText","formatHex","base","negative","sign","digits","radix","padding","hex","MAX_DISPLAYED_BIGINT_DIGITS","formatBigInt","magnitude","bits","log10","exponent","mantissa","formatString","formatBoolean","formatDatetime","d","format","isMidnight","dateStr","p2","n","year","month","day","datePart","time","formatMsDuration","ms","totalSeconds","hours","minutes","seconds","mm","ss","decimalMarkByLocale","decimalMark","mark","part","localiseFixedDecimal","fixed","match","integer","fraction","integerText","formatUom","unit","exact","isTimeSpan","currencyDisplay","CURRENCY_DISPLAY","moneyText","decimalToFixed","formatMatrixEntry","entry","formatSymbolic","formatMatrix","m","rowMajor","columnMajorToRowMajor","rows","r","cells","c","formatMatrixAligned","us","row","colWidth","width","cell","formatRange","min","max","formatPercentage","formatUnit","formatIpCidr","data","dotted","formatIp","formatSplit","prefix","render","share","v","Value","text","formatValue","high","each","shareWord","localeCode","getLocale","formatColour"],"mappings":"qMA8CO,IAAMA,CAAAA,CAAkD,CAC7D,WAAA,CAAa,CACX,aAAA,CAAe,CAAA,CACf,eAAA,CAAiB,IACnB,CAAA,CACA,YAAA,CAAc,CACZ,sBAAA,CAAwB,OAC1B,CAAA,CACA,SAAA,CAAW,CACT,aAAA,CAAe,KAAA,CACf,YAAA,CAAc,CAChB,CAAA,CACA,uBAAA,CAAyB,CACvB,aAAA,CAAe,CACjB,CAAA,CACA,gBAAA,CAAkB,CAChB,aAAA,CAAe,CACjB,CAAA,CACA,UAAA,CAAY,CACV,MAAA,CAAQ,MACV,CACF,ECxDA,SAASC,CAAAA,CAAaC,CAAAA,CAAeC,CAAAA,CAAiBC,CAAAA,CAA8BC,CAAAA,CAAgC,CAClH,IAAMC,CAAAA,CAAMF,EAAS,WAAA,CAAY,eAAA,CAC3BG,CAAAA,CAAMH,CAAAA,CAAS,YAAA,CAAa,sBAAA,CAMlC,GAAIC,CAAAA,GAAkB,MAAA,EAAa,MAAA,CAAO,QAAA,CAASH,CAAK,CAAA,CAAG,CACzD,IAAMM,CAAAA,CAAYN,EAAM,cAAA,CAAeK,CAAAA,EAAO,OAAA,CAAS,CACrD,qBAAA,CAAuBF,CAAAA,CACvB,qBAAA,CAAuBA,CAAAA,CACvB,WAAA,CAAaC,CACf,CAAC,CAAA,CACD,OAAO,CAAA,EAAGH,CAAAA,CAAO,OAAA,CAAQ,YAAY,CAAA,EAAGK,CAAS,CAAA,CACnD,CACA,IAAMC,CAAAA,CAAKL,CAAAA,CAAS,WAAA,CAAY,aAAA,CAC1BI,CAAAA,CA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,QAAQ,YAAY,CAAA,EAAG4F,EAAa7F,CAAAA,CAAM,KAAmB,CAAC,CAAA,CAAA,CACjF,KAAA,CAAA,CACE,OAAOyE,CAAAA,CAAezE,CAAAA,CAAM,KAAqB,CAAA,CACnD,KAAA,CAAA,CACE,OAAO2F,CAAAA,CAAiB3F,CAAAA,CAAM,MAAiBC,CAAAA,CAAQkF,CAAE,EAC3D,KAAA,EAAA,CACE,OAAOS,EAAW5F,CAAAA,CAAM,KAAA,CAAiBA,EAAM,IAAI,CAAA,CACrD,QAKE,OAAOA,CAAAA,CAAM,MAAQ,MAAA,CAAOA,CAAAA,CAAM,KAAK,CAAA,CACzC,QACE,OAAO,CAAA,EAAA,EAAK,MAAA,CAAOA,EAAM,KAAK,CAAC,EACnC,CACF","file":"chunk-RE6AIU6Y.js","sourcesContent":["/**\n * How a Datetime value is rendered.\n *\n * - `'long'`: the spelled-out form, \"Tuesday, March 10, 2026\" (the default).\n * - `'iso'`: \"2026-03-10\" (ISO 8601, with a `T`-separated time when present).\n * - `'dmy'`: \"10/03/2026\" (day first).\n * - `'mdy'`: \"03/10/2026\" (month first).\n *\n * The weekday and long month name in `'long'` are localised through the same\n * locale the number separators come from; the numeric forms are locale-neutral.\n */\nexport type DateOutputFormat = \"long\" | \"iso\" | \"dmy\" | \"mdy\";\n\n/**\n * Minimal formatting settings interface for the engine\n * This allows the engine to format values without depending on app-specific settings\n */\nexport interface FormattingSettings {\n floatResult: {\n decimalPlaces: number;\n enableSeperator: boolean;\n };\n numberResult: {\n decimalSeparatorLocale: string;\n };\n hexResult: {\n enablePadding: boolean;\n paddingZeros: number;\n };\n unitOfMeasurementResult: {\n decimalPlaces: number;\n };\n percentageResult: {\n decimalPlaces: number;\n };\n /**\n * Optional so a host that built a `FormattingSettings` before this field\n * existed still compiles; a missing `dateResult` reads as `'long'`, the\n * historic output.\n */\n dateResult?: {\n format: DateOutputFormat;\n };\n}\n\n/** Formatting used when a host supplies none. */\nexport const DEFAULT_FORMATTING_SETTINGS: FormattingSettings = {\n floatResult: {\n decimalPlaces: 2,\n enableSeperator: true,\n },\n numberResult: {\n decimalSeparatorLocale: \"en-US\",\n },\n hexResult: {\n enablePadding: false,\n paddingZeros: 0,\n },\n unitOfMeasurementResult: {\n decimalPlaces: 2,\n },\n percentageResult: {\n decimalPlaces: 2,\n },\n dateResult: {\n format: \"long\",\n },\n};\n","import { Value, ValueType, type MatrixData, type MatrixEntry, type RangeData, type ColourData, type SplitData, type SplitShare, type ChartData, type IpCidrData } from \"@solve-js/vm/Value\";\nimport { formatColour } from \"@solve-js/packages/colour/ColourMath\";\nimport { formatIp } from \"@solve-js/packages/ip/IpMath\";\nimport { decimalToFixed, type DecimalData } from \"@solve-js/decimal\";\nimport { getLocale, type ILocale } from \"@solve-js/constants/locales\";\nimport { autoFormatIntegerOrFloat } from \"@solve-js/utilities/Number\";\nimport { FormattingSettings, DEFAULT_FORMATTING_SETTINGS } from \"./FormattingSettings\";\nimport { CURRENCY_DISPLAY } from \"@solve-js/uom/CurrencyAliases\";\nimport { columnMajorToRowMajor } from \"@solve-js/vm/MatrixOps\";\nimport { formatSymbolic, type SymbolicNode } from \"@solve-js/symbolic\";\n\nfunction formatNumber(value: number, locale: ILocale, settings: FormattingSettings, decimalPlaces?: number): string {\n const sep = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale;\n // An explicit precision (`3.14159 to 4 dp`, `round(1.5, 2)`) shows EXACTLY that\n // many places with trailing zeros kept, where the default trims them and shows\n // an integer with none. The value was already rounded to this precision when\n // it was set (see VMBuiltins' roundToPlaces, exact where an exact decimal was\n // there), so rendering it to the same place count reproduces that rounding.\n if (decimalPlaces !== undefined && Number.isFinite(value)) {\n const formatted = value.toLocaleString(loc || \"en-US\", {\n minimumFractionDigits: decimalPlaces,\n maximumFractionDigits: decimalPlaces,\n useGrouping: sep,\n });\n return `${locale.display.resultPrefix}${formatted}`;\n }\n const dp = settings.floatResult.decimalPlaces;\n const formatted = autoFormatIntegerOrFloat(value, dp, sep, loc);\n return `${locale.display.resultPrefix}${formatted}`;\n}\n\n/**\n * Renders a measurement that carries a one-sigma uncertainty as\n * `center ± spread`, e.g. `49.2 ± 2.0`.\n *\n * The center is shown the way any number is, whole numbers as integers and\n * trailing zeros trimmed, so a tolerance-free-looking center still reads\n * cleanly (\"30 ± 2.24\", not \"30.00 ± 2.24\"). The spread is shown to the same\n * decimal-place budget but always keeps at least one fractional digit, which is\n * what distinguishes it as a tolerance and gives \"± 2.0\" rather than \"± 2\".\n * Both use `Intl` with `maximumFractionDigits`, so the trailing-zero trimming is\n * locale-correct (a comma-decimal locale is not string-sliced on \".\").\n *\n * The symbol is always the `±` glyph on output, even when the input was the\n * ASCII `+/-`, since the glyph is the conventional notation and unambiguous to\n * read back.\n */\nfunction formatUncertain(center: number, uncertainty: number, locale: ILocale, settings: FormattingSettings): string {\n const dp = settings.floatResult.decimalPlaces;\n const useGrouping = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale || \"en-US\";\n // The spread needs room for at least one fractional digit, so a zero-decimal\n // budget cannot leave minimumFractionDigits above maximumFractionDigits.\n const spreadMax = Math.max(dp, 1);\n const centerText = center.toLocaleString(loc, { useGrouping, minimumFractionDigits: 0, maximumFractionDigits: dp });\n const spreadText = Math.abs(uncertainty).toLocaleString(loc, { useGrouping, minimumFractionDigits: 1, maximumFractionDigits: spreadMax });\n return `${locale.display.resultPrefix}${centerText} ± ${spreadText}`;\n}\n\n/**\n * Renders a number in whichever base it is tagged with.\n *\n * The zero padding is a hexadecimal setting and stays one. Applying it to a\n * binary rendering would pad `0b101` out to the same digit count as a hex\n * value, which is a different quantity of zeros and not what the setting asks\n * for.\n */\nfunction formatHex(value: number | bigint, settings: FormattingSettings, base?: string): string {\n // An infinity or a NaN has no digits in any base, and asking for them\n // produced `0xINFINITY`, a literal that reads back as nothing at all. Render\n // the value itself, which is what every other non-finite result shows.\n if (typeof value === \"number\" && !Number.isFinite(value)) return `= ${value}`;\n\n // Truncate and take the sign off before converting. `Number.toString(radix)`\n // does neither: it renders -255 as \"-ff\", which lands the minus inside the\n // literal as `0x-FF`, and it renders 255.7 as \"ff.b3333333333\", inventing\n // fractional hex digits for a notation that has no use for them. Both were\n // visible on `as hex` until the builtins started sharing this path.\n //\n // A bigint needs neither truncation nor a Math call, and must not be routed\n // through one: passing it to Math.trunc() throws, and converting it to a\n // double first is exactly the precision loss it is carried as a bigint to\n // avoid.\n const negative = typeof value === \"bigint\" ? value < 0n : value < 0;\n const sign = negative ? \"-\" : \"\";\n const digits = (radix: number): string =>\n typeof value === \"bigint\"\n ? (negative ? -value : value).toString(radix)\n : Math.abs(Math.trunc(value)).toString(radix);\n\n if (base === \"bin\") return `= ${sign}0b${digits(2)}`;\n if (base === \"oct\") return `= ${sign}0o${digits(8)}`;\n const padding = settings.hexResult.enablePadding ? settings.hexResult.paddingZeros : 0;\n const hex = digits(16).toUpperCase().padStart(padding, \"0\");\n return `= ${sign}0x${hex}`;\n}\n\n/**\n * How many decimal digits of an exact integer this will render in full.\n *\n * A little above the ~19,729 digits of the largest bigint the VM will build\n * (`vm/VM.ts`'s MAX_EXACT_POW_BITS / MAX_EXACT_SHIFT_BITS, 65,536 bits), so\n * every value the engine can produce through `^` or `<<` still prints exactly\n * and this ceiling only ever meets a value that came from somewhere else.\n */\nconst MAX_DISPLAYED_BIGINT_DIGITS = 20000;\n\n/**\n * Renders an exact integer, or describes it when writing it out is itself the\n * expensive operation.\n *\n * This used to be a bare `= ${value}` template, which renders whatever it is\n * handed: `1n << 100000000` took 8.5 seconds here turning a 12.5MB integer\n * into a thirty-million-character string, and a host has no way to opt out,\n * since displaying the answer is what it asked the engine for. The VM's own\n * ceiling on `<<` and `^` now stops that value existing, so this is the\n * backstop for every other way a large bigint can arrive (repeated `x * x`,\n * a Value a host built itself), and it costs one comparison for every value\n * that is not absurd.\n *\n * The digit count is estimated from the bit length rather than measured, since\n * measuring means doing the conversion this exists to avoid. Bit length comes\n * off the hexadecimal form, which is linear in the size of the value where the\n * decimal form is not.\n */\nfunction formatBigInt(value: bigint): string {\n const magnitude = value < 0n ? -value : value;\n // Every bigint a person actually reads takes this line and nothing else:\n // anything a double can hold is at most 309 digits, so it is printable\n // without measuring it at all.\n if (Number.isFinite(Number(magnitude))) return `= ${value}`;\n const bits = magnitude.toString(16).length * 4;\n if (bits * Math.LN2 / Math.LN10 <= MAX_DISPLAYED_BIGINT_DIGITS) return `= ${value}`;\n const log10 = bits * Math.LN2 / Math.LN10;\n const exponent = Math.floor(log10);\n const mantissa = Math.pow(10, log10 - exponent);\n const sign = value < 0n ? \"-\" : \"\";\n return `= ${sign}~${mantissa.toFixed(3)}e+${exponent} (an exact integer of about ${(exponent + 1).toLocaleString(\"en-US\")} digits, too large to print)`;\n}\n\nfunction formatString(value: string): string {\n return `= ${value}`;\n}\n\nfunction formatBoolean(value: boolean): string {\n return `= ${value}`;\n}\n\n/**\n * Renders a Datetime value locale-aware, the previous implementation\n * called `d.toLocaleString()` with no arguments, which always uses the JS\n * runtime's own default locale and never actually consulted `locale.code`\n * despite receiving it as a parameter (both branches of its old\n * `dateFormat === \"default\"` check were byte-for-byte identical, dead\n * groundwork for a distinction that was never implemented). Concretely,\n * this meant every configured locale (including the shipped German one)\n * always displayed weekday/month names in English. See GitHub issue #77.\n *\n * Uses `weekday`/`month`: \"long\" for a spelled-out date (\"Monday,\n * November 17, 2025\" / \"lundi 17 novembre 2025\") since that's what a\n * literal weekday name is for; a bare numeric date doesn't need\n * localizing beyond the decimal/thousands separators `formatNumber()`\n * already handles. The time-of-day portion is only appended when it's\n * not exactly local midnight, bare date literals (\"today\", \"17/11/2025\")\n * always anchor to local midnight, and showing \"00:00:00\" on every one of\n * those would be noise, not information.\n */\nfunction formatDatetime(value: number, locale: ILocale, settings: FormattingSettings): string {\n const d = new Date(value);\n const format = settings.dateResult?.format ?? \"long\";\n const isMidnight = d.getHours() === 0 && d.getMinutes() === 0 && d.getSeconds() === 0 && d.getMilliseconds() === 0;\n\n // The spelled-out default, localised through the locale's own names.\n if (format === \"long\") {\n const dateStr = d.toLocaleDateString(locale.code, { weekday: \"long\", year: \"numeric\", month: \"long\", day: \"numeric\" });\n if (isMidnight) return `= ${dateStr}`;\n return `= ${dateStr}, ${d.toLocaleTimeString(locale.code)}`;\n }\n\n // The numeric forms, built from the local calendar fields so they read the\n // same regardless of the JS runtime's own default locale.\n const p2 = (n: number) => String(n).padStart(2, \"0\");\n const year = d.getFullYear();\n const month = p2(d.getMonth() + 1);\n const day = p2(d.getDate());\n let datePart: string;\n if (format === \"iso\") datePart = `${year}-${month}-${day}`;\n else if (format === \"dmy\") datePart = `${day}/${month}/${year}`;\n else datePart = `${month}/${day}/${year}`; // mdy\n\n if (isMidnight) return `= ${datePart}`;\n const time = `${p2(d.getHours())}:${p2(d.getMinutes())}:${p2(d.getSeconds())}`;\n // ISO joins date and time with `T`; the slash forms with a space.\n return format === \"iso\" ? `= ${datePart}T${time}` : `= ${datePart} ${time}`;\n}\n\n/**\n * Renders a millisecond duration as clock-style `H:MM` (or `H:MM:SS` when\n * there's a non-zero seconds component). `ms` is never a user-typeable\n * unit (confirmed: it appears nowhere in `lexer/units.ts`), it's only\n * ever produced by subtracting two clock times/datetimes (`9:30 - 8:30`,\n * `VM.ts`'s Datetime SUB case), so this is a safe, narrow special case,\n * not a general change to how durations display.\n */\nfunction formatMsDuration(ms: number): string {\n const sign = ms < 0 ? \"-\" : \"\";\n const totalSeconds = Math.round(Math.abs(ms) / 1000);\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n const mm = String(minutes).padStart(2, \"0\");\n if (seconds === 0) return `${sign}${hours}:${mm}`;\n const ss = String(seconds).padStart(2, \"0\");\n return `${sign}${hours}:${mm}:${ss}`;\n}\n\n/** The decimal mark each locale writes, looked up once per locale rather than on every value. */\nconst decimalMarkByLocale = new Map<string, string>();\n\nfunction decimalMark(loc: string): string {\n let mark = decimalMarkByLocale.get(loc);\n if (mark === undefined) {\n mark = new Intl.NumberFormat(loc).formatToParts(1.1).find((part) => part.type === \"decimal\")?.value ?? \".\";\n decimalMarkByLocale.set(loc, mark);\n }\n return mark;\n}\n\n/**\n * Write a fixed-decimal string (`\"1234567.50\"`) the way `loc` writes numbers:\n * its decimal mark, and its digit grouping when `useGrouping` is on.\n *\n * Every quantity and every money amount used to be rendered with a bare\n * `toFixed`, so a plain `52000` showed as `52,000` while `£52000` showed as\n * `£52000.00`, and the `enableSeperator` setting had no effect on the one\n * value type people most want grouped. The digits are taken from the string\n * rather than re-rendered from the double, because an exact money amount has\n * already been rounded from its decimal (see {@link formatUom}) and\n * re-rendering would undo that. `BigInt` carries the integer part through\n * `Intl` so grouping follows the locale's own rule (Indian lakhs included)\n * rather than a hand-written every-three-digits. Anything that is not plain\n * digits, an `Infinity` or an exponent form, is returned as it came.\n */\nfunction localiseFixedDecimal(fixed: string, loc: string, useGrouping: boolean): string {\n const match = /^(-?)(\\d+)(?:\\.(\\d+))?$/.exec(fixed);\n if (!match) return fixed;\n const [, sign, integer, fraction] = match;\n const integerText = useGrouping ? BigInt(integer).toLocaleString(loc, { useGrouping: true }) : integer;\n if (fraction === undefined) return `${sign}${integerText}`;\n return `${sign}${integerText}${decimalMark(loc)}${fraction}`;\n}\n\nfunction formatUom(value: number, unit: string | undefined, locale: ILocale, settings: FormattingSettings, exact?: DecimalData): string {\n if (unit === \"ms\") return `= ${formatMsDuration(value)}`;\n // A fuel-consumption unit is stored slash-free (so it is not read as a rate)\n // but shown the way it is written.\n if (unit === \"l100km\") unit = \"l/100km\";\n if (unit === \"mps2\") unit = \"m/s²\";\n\n const dp = settings.unitOfMeasurementResult.decimalPlaces;\n const useGrouping = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale || \"en-US\";\n\n // For TimeSpan values (days, weeks, hours, etc.), format as integer if the value is a whole number\n const timeSpanUnits = [\"days\", \"weeks\", \"months\", \"years\", \"hours\", \"minutes\", \"seconds\", \"day\", \"week\", \"month\", \"year\", \"hour\", \"minute\", \"second\"];\n const isTimeSpan = unit && timeSpanUnits.includes(unit);\n\n let formatted: string;\n if (isTimeSpan && value === Math.floor(value)) {\n // For whole number TimeSpan values, format as integer\n formatted = localiseFixedDecimal(value.toString(), loc, useGrouping);\n } else {\n // For other values, use the configured decimal places\n formatted = localiseFixedDecimal(value.toFixed(dp), loc, useGrouping);\n }\n\n // Currency display: symbol + culturally-conventional placement (e.g.\n // \"$100.00\" prefix vs \"100.00 kr\" suffix) instead of the generic\n // \"amount CODE\" fallback below. See uom/CurrencyAliases.ts's\n // CURRENCY_DISPLAY table for the exact set covered and the reasoning\n // behind each placement choice. Any currency code NOT in that table\n // (most of the ~150 `CurrencyExchange.isCurrency()` recognizes) falls\n // through to the unchanged \"amount CODE\" format below.\n const currencyDisplay = unit ? CURRENCY_DISPLAY[unit.toUpperCase()] : undefined;\n if (currencyDisplay) {\n // An exact money amount rounds from its decimal, not from the double: a\n // half-cent like \"$1.005\" reads as \"$1.01\" here, where \"(1.005).toFixed(2)\"\n // answers \"1.00\" because the double it is handed already sits below the\n // value the user typed. Amounts with no exact decimal (a currency\n // conversion, whose rate is a double) keep the toFixed rendering above.\n const moneyText = exact ? localiseFixedDecimal(decimalToFixed(exact, dp), loc, useGrouping) : formatted;\n const sep = currencyDisplay.spaced ? \" \" : \"\";\n const withSymbol = currencyDisplay.position === \"prefix\"\n ? `${currencyDisplay.symbol}${sep}${moneyText}`\n : `${moneyText}${sep}${currencyDisplay.symbol}`;\n return `= ${withSymbol}`;\n }\n\n // The unit is written as the symbol the value carries. There used to be a\n // `unitOfMeasurementResult.unitNames` setting here whose two branches were\n // the same expression, so it never changed anything, and it was removed\n // rather than implemented: the engine has no unit-name data to render from.\n // The generated unit table maps a spelling to [measure, ratio] only, and\n // names cannot be recovered from it, because units that differ by an OFFSET\n // share a ratio, so \"20 C\" would come back as \"20 kelvins\". A real\n // implementation needs a hand-authored name per unit plus pluralization and\n // per-locale spelling (metre against meter), which is a feature rather than\n // the repair of a dead ternary.\n //\n // An exact currency with no symbol in the display table above (one of the\n // less common ISO codes) still rounds from its decimal here, so \"1.005 UYW\"\n // reads the same way \"$1.005\" does. Non-currency Uoms never carry an exact,\n // so this leaves \"1.50 kg\" exactly as it was.\n const genericText = exact ? localiseFixedDecimal(decimalToFixed(exact, dp), loc, useGrouping) : formatted;\n return `= ${genericText} ${unit || \"\"}`.trim();\n}\n\nfunction formatMatrixEntry(entry: MatrixEntry, settings: FormattingSettings): string {\n if (typeof entry === \"boolean\") return entry ? \"true\" : \"false\";\n if (typeof entry === \"object\" && entry !== null) return formatSymbolic(entry);\n const dp = settings.floatResult.decimalPlaces;\n const sep = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale;\n return autoFormatIntegerOrFloat(entry, dp, sep, loc);\n}\n\n/**\n * Renders a Matrix matching its own literal syntax: a single row (1xN,\n * including plain vectors) as `[a, b, c]`, a single column (Nx1) as\n * `[a; b; c]`, and a general shape as `[r0c0, r0c1; r1c0, r1c1]`, row-major\n * textual output read back out of the column-major storage\n * (`columnMajorToRowMajor()`), matching how `[1,2;3,4]` is written.\n */\nfunction formatMatrix(m: MatrixData, locale: ILocale, settings: FormattingSettings): string {\n const rowMajor = columnMajorToRowMajor(m);\n const rows: string[] = [];\n for (let r = 0; r < m.rows; r++) {\n const cells: string[] = [];\n for (let c = 0; c < m.cols; c++) {\n cells.push(formatMatrixEntry(rowMajor[r * m.cols + c], settings));\n }\n rows.push(cells.join(\", \"));\n }\n return `${locale.display.resultPrefix}[${rows.join(\"; \")}]`;\n}\n\n/**\n * Render a matrix as a multi-line, column-aligned block: one row per line (the\n * newline is where {@link formatValue}'s compact form writes `;`), each column\n * right-padded to its widest cell, and every row wrapped in `[ ... ]`. For\n * display where a grid reads better than a line, e.g. a docs notepad or a REPL:\n *\n * ```text\n * [ 1 2 ]\n * [ 30 4 ]\n * ```\n *\n * This is deliberately separate from {@link formatValue}, whose single-line\n * matrix form stays the stable, assertable text the API and the worker DTO use.\n * A 1xN row vector is one line; an Nx1 column vector is N lines.\n */\nexport function formatMatrixAligned(m: MatrixData, settings?: FormattingSettings): string {\n const us = settings || DEFAULT_FORMATTING_SETTINGS;\n const rowMajor = columnMajorToRowMajor(m);\n const cells: string[][] = [];\n for (let r = 0; r < m.rows; r++) {\n const row: string[] = [];\n for (let c = 0; c < m.cols; c++) {\n row.push(formatMatrixEntry(rowMajor[r * m.cols + c], us));\n }\n cells.push(row);\n }\n const colWidth: number[] = [];\n for (let c = 0; c < m.cols; c++) {\n let width = 0;\n for (let r = 0; r < m.rows; r++) width = Math.max(width, cells[r][c].length);\n colWidth.push(width);\n }\n return cells\n .map((row) => `[ ${row.map((cell, c) => cell.padStart(colWidth[c])).join(\" \")} ]`)\n .join(\"\\n\");\n}\n\nfunction formatRange(min: number, max: number, locale: ILocale): string {\n return `${locale.display.resultPrefix}${min}:${max}`;\n}\n\nfunction formatPercentage(value: number, locale: ILocale, settings: FormattingSettings): string {\n // ValueType.Percentage stores a fraction (0.25 for 25%). See Value.ts's\n // documented contract and the sole producer, VM.ts's TO_PERCENTAGE opcode\n // (`right/left - 1`, e.g. 0.25 for \"800 to 1000\"). Multiply by 100 before\n // formatting; without this every percentage-change result displayed as\n // e.g. \"0.25%\" instead of \"25.00%\".\n const dp = settings.percentageResult.decimalPlaces;\n const formatted = (value * 100).toFixed(dp);\n return `= ${formatted}${locale.display.percentageSuffix}`;\n}\n\nfunction formatUnit(value: number, unit: string | undefined): string {\n return `= ${value} ${unit || \"\"}`.trim();\n}\n\n/**\n * Renders a per-person bill split: \"= $45.00 each\", or, when the division is\n * uneven, \"= $33.33 each, with 1 share paying $33.34\". Each share's amount is\n * rendered through the ordinary value formatter (a throwaway {@link Value}), so\n * a currency share honours the same symbol placement, decimal places and locale\n * as any other money and a bare share trims trailing zeros the way a plain\n * number does; the \"= \" prefix is added once, around the whole sentence, not\n * per share.\n */\n/**\n * An IP/CIDR as text: the dotted quad, plus `/prefix` when present, or a bare\n * `/prefix` when there is no address (`netmask of /24` before it resolves).\n */\nfunction formatIpCidr(data: IpCidrData): string {\n\tif (data.addr === undefined) return `/${data.prefix}`;\n\tconst dotted = formatIp(data.addr);\n\treturn data.prefix === undefined ? dotted : `${dotted}/${data.prefix}`;\n}\n\nfunction formatSplit(data: SplitData, locale: ILocale, settings: FormattingSettings): string {\n const prefix = locale.display.resultPrefix;\n const render = (share: SplitShare): string => {\n const v = data.unit !== undefined\n ? new Value(ValueType.Uom, share.value, data.unit)\n : new Value(ValueType.Number, share.value);\n v.exact = share.exact;\n const text = formatValue(v, settings);\n return text.startsWith(prefix) ? text.slice(prefix.length) : text;\n };\n\n const [base, high] = data.shares;\n const each = `${render(base)} each`;\n if (high === undefined) return `${prefix}${each}`;\n const shareWord = high.count === 1 ? \"share\" : \"shares\";\n return `${prefix}${each}, with ${high.count} ${shareWord} paying ${render(high)}`;\n}\n\n/**\n * Render an evaluated {@link Value} as a display string, dispatching on\n * `value.type` to the type-specific formatter (number, hex, datetime, unit\n * of measurement, matrix, range, percentage, ...).\n *\n * Most branches produce a `\"= \"`-prefixed result string (matching the\n * plugin's inline-result convention); `ValueType.Error` is the one\n * exception, it returns the human-readable error message directly\n * (stored in `value.unit`), not an `\"= \"`-prefixed string.\n *\n * @param value - The evaluated value to format.\n * @param settings - Locale/precision/separator options; defaults to\n * {@link DEFAULT_FORMATTING_SETTINGS} when omitted.\n * @example\n * ```typescript\n * const value = engine.evaluateExpression(\"10 USD to GBP\");\n * formatValue(value); // \"= £7.85\" (exact output depends on live exchange rates)\n * ```\n */\nexport function formatValue(value: Value, settings?: FormattingSettings): string {\n const us = settings || DEFAULT_FORMATTING_SETTINGS;\n const localeCode = us.numberResult.decimalSeparatorLocale || \"en\";\n const locale = getLocale(localeCode);\n\n switch (value.type) {\n case ValueType.Number:\n // A measurement with a tolerance renders as \"center ± spread\"; every\n // other number is unchanged, so a plain value is byte-for-byte what it was.\n if (value.uncertainty !== undefined) {\n return formatUncertain(value.value as number, value.uncertainty, locale, us);\n }\n return formatNumber(value.value as number, locale, us, value.decimalPlaces);\n case ValueType.Hex:\n return formatHex(value.value as number | bigint, us, value.unit);\n case ValueType.BigInt:\n return formatBigInt(value.value as bigint);\n case ValueType.String:\n return formatString(value.value as string);\n case ValueType.Boolean:\n return formatBoolean(value.value as boolean);\n case ValueType.Datetime:\n return formatDatetime(value.value as number, locale, us);\n case ValueType.Uom:\n return formatUom(value.value as number, value.unit, locale, us, value.exact);\n case ValueType.Matrix:\n return formatMatrix(value.value as MatrixData, locale, us);\n case ValueType.Range: {\n const r = value.value as RangeData;\n return formatRange(r.min, r.max, locale);\n }\n case ValueType.Colour:\n return `${locale.display.resultPrefix}${formatColour(value.value as ColourData)}`;\n case ValueType.Split:\n return formatSplit(value.value as SplitData, locale, us);\n case ValueType.Chart:\n // A chart is drawn from its data by the host; the text answer is its label\n // (`sin(x) over [0, 6.28]`, or the series a sparkline came from).\n return `${locale.display.resultPrefix}${(value.value as ChartData).label}`;\n case ValueType.IpCidr:\n return `${locale.display.resultPrefix}${formatIpCidr(value.value as IpCidrData)}`;\n case ValueType.Symbolic:\n return formatSymbolic(value.value as SymbolicNode);\n case ValueType.Percentage:\n return formatPercentage(value.value as number, locale, us);\n case ValueType.Unit:\n return formatUnit(value.value as number, value.unit);\n case ValueType.Error:\n // errorValue(code, message) stores the human-readable message in\n // `.unit` (code goes in `.value`), falling through to the default\n // case here previously displayed the raw code (e.g.\n // \"CURRENCY_RATE_UNAVAILABLE\") instead of the actual message.\n return value.unit ?? String(value.value);\n default:\n return `= ${String(value.value)}`;\n }\n}\n"]}