solve-engine 1.2.0 → 2.1.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 (385) hide show
  1. package/README.md +12 -17
  2. package/dist/{BytecodeBuilder-Bp9xeTmX.d.cts → BytecodeBuilder-DGGeByAP.d.cts} +18 -0
  3. package/dist/{BytecodeBuilder-Bp9xeTmX.d.ts → BytecodeBuilder-DGGeByAP.d.ts} +18 -0
  4. package/dist/{Configuration-C9W8tJv_.d.cts → Configuration-B6W0-T67.d.cts} +17 -4
  5. package/dist/{Configuration-C9W8tJv_.d.ts → Configuration-B6W0-T67.d.ts} +17 -4
  6. package/dist/{EngineError-CNA_rHY-.d.cts → EngineError-Ce1lPkjZ.d.cts} +2 -0
  7. package/dist/{EngineError-CNA_rHY-.d.ts → EngineError-Ce1lPkjZ.d.ts} +2 -0
  8. package/dist/{PackageCompatibility-B6NX9IaN.d.cts → PackageCompatibility-Bn5jnBtA.d.cts} +2 -2
  9. package/dist/{PackageCompatibility-Ceg5XdAp.d.ts → PackageCompatibility-CIvq2MP5.d.ts} +2 -2
  10. package/dist/{PackageRegistry-DrCPQNyy.d.ts → PackageRegistry-DzeiWcv4.d.ts} +93 -172
  11. package/dist/{PackageRegistry-DnJYVw9G.d.cts → PackageRegistry-dpdurBVO.d.cts} +93 -172
  12. package/dist/{Parselet-Bhf7d0_W.d.ts → Parselet-B-zoPrTa.d.ts} +8 -5
  13. package/dist/{Parselet-Cv7S7KRt.d.cts → Parselet-C4Wu055_.d.cts} +8 -5
  14. package/dist/{ScopeManager-Bzq87GfA.d.ts → ScopeManager-C2LDOrDx.d.ts} +7 -16
  15. package/dist/{ScopeManager-DRDBVfan.d.cts → ScopeManager-D7uMXbhS.d.cts} +7 -16
  16. package/dist/{VMCheckpoints-C6c17Hbo.d.ts → VMCheckpoints-CGyFhivM.d.ts} +3 -3
  17. package/dist/{VMCheckpoints-dZxSMGHG.d.cts → VMCheckpoints-I9jg3jWR.d.cts} +3 -3
  18. package/dist/{Value-DZNQ_PU7.d.cts → Value-CCi_Eecs.d.cts} +40 -0
  19. package/dist/{Value-DZNQ_PU7.d.ts → Value-CCi_Eecs.d.ts} +40 -0
  20. package/dist/{WorkerError-Djd7GGGa.d.cts → WorkerError-B4p6PNfx.d.cts} +1 -1
  21. package/dist/{WorkerError-B7t7R2-m.d.ts → WorkerError-Dhj9BQ_A.d.ts} +1 -1
  22. package/dist/chunk-2JMFUQZH.js +2 -0
  23. package/dist/chunk-2JMFUQZH.js.map +1 -0
  24. package/dist/chunk-2LFLR3VZ.cjs +2 -0
  25. package/dist/chunk-2LFLR3VZ.cjs.map +1 -0
  26. package/dist/chunk-2RWAXT6O.js +0 -1
  27. package/dist/chunk-32GC2FHC.cjs +2 -0
  28. package/dist/chunk-32GC2FHC.cjs.map +1 -0
  29. package/dist/chunk-4BZIYU7S.cjs +3 -0
  30. package/dist/chunk-4BZIYU7S.cjs.map +1 -0
  31. package/dist/chunk-4E4YVQKK.js +5 -0
  32. package/dist/chunk-4E4YVQKK.js.map +1 -0
  33. package/dist/chunk-4QVBSG6B.cjs +2 -0
  34. package/dist/chunk-4QVBSG6B.cjs.map +1 -0
  35. package/dist/chunk-5FO4PDIG.js +2 -0
  36. package/dist/chunk-5FO4PDIG.js.map +1 -0
  37. package/dist/chunk-5IJD5L3O.cjs +2 -0
  38. package/dist/chunk-5IJD5L3O.cjs.map +1 -0
  39. package/dist/chunk-62LMTO4F.js +2 -0
  40. package/dist/chunk-62LMTO4F.js.map +1 -0
  41. package/dist/chunk-6G3PMEPA.js +2 -0
  42. package/dist/chunk-6G3PMEPA.js.map +1 -0
  43. package/dist/chunk-6INX773F.cjs +2 -0
  44. package/dist/chunk-6INX773F.cjs.map +1 -0
  45. package/dist/chunk-76F3LCIL.js +4 -0
  46. package/dist/chunk-76F3LCIL.js.map +1 -0
  47. package/dist/chunk-7BXPCWKM.cjs +2 -0
  48. package/dist/chunk-7BXPCWKM.cjs.map +1 -0
  49. package/dist/chunk-7GK3XEZF.js +2 -0
  50. package/dist/chunk-7GK3XEZF.js.map +1 -0
  51. package/dist/chunk-AXMQG5TS.cjs +2 -0
  52. package/dist/chunk-AXMQG5TS.cjs.map +1 -0
  53. package/dist/chunk-CIQOK7Q4.cjs +2 -0
  54. package/dist/chunk-CIQOK7Q4.cjs.map +1 -0
  55. package/dist/chunk-E2Q3PQ2G.js +3 -0
  56. package/dist/chunk-E2Q3PQ2G.js.map +1 -0
  57. package/dist/chunk-E6Z4NQAS.js +2 -0
  58. package/dist/chunk-E6Z4NQAS.js.map +1 -0
  59. package/dist/chunk-EFJCC6FJ.cjs +2 -0
  60. package/dist/chunk-EFJCC6FJ.cjs.map +1 -0
  61. package/dist/chunk-ESUN2THE.cjs +2 -0
  62. package/dist/chunk-ESUN2THE.cjs.map +1 -0
  63. package/dist/chunk-EVAOPEO4.js +2 -0
  64. package/dist/chunk-EVAOPEO4.js.map +1 -0
  65. package/dist/chunk-EVI6OHQH.cjs +2 -0
  66. package/dist/chunk-EVI6OHQH.cjs.map +1 -0
  67. package/dist/chunk-FDE5HWDI.cjs +2 -0
  68. package/dist/chunk-FDE5HWDI.cjs.map +1 -0
  69. package/dist/chunk-FWW3M36J.cjs +2 -0
  70. package/dist/chunk-FWW3M36J.cjs.map +1 -0
  71. package/dist/chunk-G7TBEQRQ.js +2 -0
  72. package/dist/chunk-G7TBEQRQ.js.map +1 -0
  73. package/dist/chunk-GK2OHWRF.cjs +5 -0
  74. package/dist/chunk-GK2OHWRF.cjs.map +1 -0
  75. package/dist/chunk-HFKDWQUL.js +2 -0
  76. package/dist/chunk-HFKDWQUL.js.map +1 -0
  77. package/dist/chunk-HLBYHXQD.cjs +3 -0
  78. package/dist/chunk-HLBYHXQD.cjs.map +1 -0
  79. package/dist/chunk-I52MYCVI.js +3 -0
  80. package/dist/chunk-I52MYCVI.js.map +1 -0
  81. package/dist/chunk-IANAMBJQ.cjs +2 -0
  82. package/dist/chunk-IANAMBJQ.cjs.map +1 -0
  83. package/dist/chunk-IJMNVBIS.js +2 -0
  84. package/dist/chunk-IJMNVBIS.js.map +1 -0
  85. package/dist/chunk-J4LZD4ZY.js +3 -0
  86. package/dist/chunk-J4LZD4ZY.js.map +1 -0
  87. package/dist/chunk-JAK3RAFA.cjs +2 -0
  88. package/dist/chunk-JAK3RAFA.cjs.map +1 -0
  89. package/dist/chunk-JFAJN3C2.cjs +2 -0
  90. package/dist/chunk-JFAJN3C2.cjs.map +1 -0
  91. package/dist/chunk-JPFCXLJV.js +2 -0
  92. package/dist/chunk-JPFCXLJV.js.map +1 -0
  93. package/dist/chunk-JUIJ6NRD.cjs +3 -0
  94. package/dist/chunk-JUIJ6NRD.cjs.map +1 -0
  95. package/dist/chunk-MIQBJGGR.js +2 -0
  96. package/dist/chunk-MIQBJGGR.js.map +1 -0
  97. package/dist/chunk-MPB7KUN5.js +3 -0
  98. package/dist/chunk-MPB7KUN5.js.map +1 -0
  99. package/dist/chunk-MSYX32PF.cjs +2 -0
  100. package/dist/chunk-MSYX32PF.cjs.map +1 -0
  101. package/dist/chunk-MVZUTETT.js +2 -0
  102. package/dist/chunk-MVZUTETT.js.map +1 -0
  103. package/dist/chunk-N7N7MPMK.cjs +2 -0
  104. package/dist/chunk-N7N7MPMK.cjs.map +1 -0
  105. package/dist/chunk-NGBBNL4K.cjs +1 -3
  106. package/dist/chunk-OVKDDTXO.cjs +3 -0
  107. package/dist/chunk-OVKDDTXO.cjs.map +1 -0
  108. package/dist/chunk-P6WPEUAJ.cjs +2 -0
  109. package/dist/chunk-P6WPEUAJ.cjs.map +1 -0
  110. package/dist/chunk-PS272DZJ.cjs +2 -0
  111. package/dist/chunk-PS272DZJ.cjs.map +1 -0
  112. package/dist/chunk-R2ENWQ76.js +2 -0
  113. package/dist/chunk-R2ENWQ76.js.map +1 -0
  114. package/dist/chunk-R2SZFJTT.cjs +2 -0
  115. package/dist/chunk-R2SZFJTT.cjs.map +1 -0
  116. package/dist/chunk-RAF57WYO.js +2 -0
  117. package/dist/chunk-RAF57WYO.js.map +1 -0
  118. package/dist/chunk-RSF25YSJ.js +2 -0
  119. package/dist/chunk-RSF25YSJ.js.map +1 -0
  120. package/dist/chunk-SOMGSIO4.cjs +3 -0
  121. package/dist/chunk-SOMGSIO4.cjs.map +1 -0
  122. package/dist/chunk-SYYE3QAX.cjs +2 -0
  123. package/dist/chunk-SYYE3QAX.cjs.map +1 -0
  124. package/dist/chunk-TCZSPH4A.js +2 -0
  125. package/dist/chunk-TCZSPH4A.js.map +1 -0
  126. package/dist/chunk-TLG7VZRX.cjs +2 -0
  127. package/dist/chunk-TLG7VZRX.cjs.map +1 -0
  128. package/dist/chunk-TN5E6JU6.js +2 -0
  129. package/dist/chunk-TN5E6JU6.js.map +1 -0
  130. package/dist/chunk-TRBXW6HW.js +2 -0
  131. package/dist/{chunk-AQNHHJMJ.cjs.map → chunk-TRBXW6HW.js.map} +1 -1
  132. package/dist/chunk-TTFO4YDP.cjs +2 -0
  133. package/dist/chunk-TTFO4YDP.cjs.map +1 -0
  134. package/dist/chunk-TWC7K3ZX.js +2 -0
  135. package/dist/chunk-TWC7K3ZX.js.map +1 -0
  136. package/dist/chunk-U4AEVL5Z.js +2 -0
  137. package/dist/chunk-U4AEVL5Z.js.map +1 -0
  138. package/dist/chunk-UURM7P3P.cjs +4 -0
  139. package/dist/chunk-UURM7P3P.cjs.map +1 -0
  140. package/dist/chunk-VAGS5JS7.cjs +2 -0
  141. package/dist/chunk-VAGS5JS7.cjs.map +1 -0
  142. package/dist/chunk-W2JAR233.js +2 -0
  143. package/dist/chunk-W2JAR233.js.map +1 -0
  144. package/dist/chunk-WGZ3FNHI.js +2 -0
  145. package/dist/chunk-WGZ3FNHI.js.map +1 -0
  146. package/dist/chunk-XEIDV5JP.js +2 -0
  147. package/dist/chunk-XEIDV5JP.js.map +1 -0
  148. package/dist/chunk-XNIWQHXY.js +2 -0
  149. package/dist/chunk-XNIWQHXY.js.map +1 -0
  150. package/dist/chunk-Y7O4D3BJ.cjs +2 -0
  151. package/dist/chunk-Y7O4D3BJ.cjs.map +1 -0
  152. package/dist/chunk-YAHGSBMC.js +2 -0
  153. package/dist/chunk-YAHGSBMC.js.map +1 -0
  154. package/dist/chunk-YAYBVVG2.js +3 -0
  155. package/dist/chunk-YAYBVVG2.js.map +1 -0
  156. package/dist/chunk-YJ2OPULK.js +2 -0
  157. package/dist/chunk-YJ2OPULK.js.map +1 -0
  158. package/dist/chunk-YVKHEAFT.js +2 -0
  159. package/dist/chunk-YVKHEAFT.js.map +1 -0
  160. package/dist/chunk-ZCNBT44X.cjs +2 -0
  161. package/dist/chunk-ZCNBT44X.cjs.map +1 -0
  162. package/dist/chunk-ZLRJ7TDP.cjs +2 -0
  163. package/dist/chunk-ZLRJ7TDP.cjs.map +1 -0
  164. package/dist/constants.cjs +1 -21
  165. package/dist/constants.d.cts +1 -1
  166. package/dist/constants.d.ts +1 -1
  167. package/dist/constants.js +1 -4
  168. package/dist/engine.cjs +1 -94
  169. package/dist/engine.d.cts +10 -11
  170. package/dist/engine.d.ts +10 -11
  171. package/dist/engine.js +1 -37
  172. package/dist/errors.cjs +1 -105
  173. package/dist/errors.d.cts +3 -3
  174. package/dist/errors.d.ts +3 -3
  175. package/dist/errors.js +1 -4
  176. package/dist/format.cjs +1 -26
  177. package/dist/format.d.cts +2 -2
  178. package/dist/format.d.ts +2 -2
  179. package/dist/format.js +1 -9
  180. package/dist/index.cjs +1 -314
  181. package/dist/index.cjs.map +1 -1
  182. package/dist/index.d.cts +52 -20
  183. package/dist/index.d.ts +52 -20
  184. package/dist/index.js +1 -278
  185. package/dist/index.js.map +1 -1
  186. package/dist/language.cjs +1 -369
  187. package/dist/language.cjs.map +1 -1
  188. package/dist/language.d.cts +9 -10
  189. package/dist/language.d.ts +9 -10
  190. package/dist/language.js +1 -348
  191. package/dist/language.js.map +1 -1
  192. package/dist/lexer.cjs +1 -63
  193. package/dist/lexer.js +1 -10
  194. package/dist/normalizer.cjs +1 -39
  195. package/dist/normalizer.js +1 -10
  196. package/dist/packages.cjs +1 -132
  197. package/dist/packages.d.cts +8 -9
  198. package/dist/packages.d.ts +8 -9
  199. package/dist/packages.js +1 -23
  200. package/dist/parser.cjs +1 -54
  201. package/dist/parser.d.cts +8 -8
  202. package/dist/parser.d.ts +8 -8
  203. package/dist/parser.js +1 -9
  204. package/dist/{pipeline-D-PS9gVw.d.ts → pipeline-72QmQlGx.d.ts} +1 -1
  205. package/dist/{pipeline-DtSBJ8TS.d.cts → pipeline-DCQicwWX.d.cts} +1 -1
  206. package/dist/resolvers.cjs +1 -12
  207. package/dist/resolvers.d.cts +2 -2
  208. package/dist/resolvers.d.ts +2 -2
  209. package/dist/resolvers.js +1 -3
  210. package/dist/services.cjs +1 -20
  211. package/dist/services.js +1 -3
  212. package/dist/testing.cjs +3 -477
  213. package/dist/testing.cjs.map +1 -1
  214. package/dist/testing.d.cts +9 -10
  215. package/dist/testing.d.ts +9 -10
  216. package/dist/testing.js +3 -469
  217. package/dist/testing.js.map +1 -1
  218. package/dist/uom.cjs +1 -55
  219. package/dist/uom.d.cts +2 -2
  220. package/dist/uom.d.ts +2 -2
  221. package/dist/uom.js +1 -10
  222. package/dist/utilities.cjs +1 -36
  223. package/dist/utilities.js +1 -7
  224. package/dist/vm.cjs +1 -295
  225. package/dist/vm.cjs.map +1 -1
  226. package/dist/vm.d.cts +22 -10
  227. package/dist/vm.d.ts +22 -10
  228. package/dist/vm.js +1 -193
  229. package/dist/vm.js.map +1 -1
  230. package/dist/worker.cjs +2 -492
  231. package/dist/worker.cjs.map +1 -1
  232. package/dist/worker.d.cts +16 -17
  233. package/dist/worker.d.ts +16 -17
  234. package/dist/worker.js +2 -483
  235. package/dist/worker.js.map +1 -1
  236. package/package.json +1 -13
  237. package/dist/chunk-3BOK2LDK.js +0 -17
  238. package/dist/chunk-3BOK2LDK.js.map +0 -1
  239. package/dist/chunk-3VGDNEE3.js +0 -84
  240. package/dist/chunk-3VGDNEE3.js.map +0 -1
  241. package/dist/chunk-4K5W7EH2.cjs +0 -112
  242. package/dist/chunk-4K5W7EH2.cjs.map +0 -1
  243. package/dist/chunk-5EFKSKMA.js +0 -413
  244. package/dist/chunk-5EFKSKMA.js.map +0 -1
  245. package/dist/chunk-5HRB36DK.js +0 -405
  246. package/dist/chunk-5HRB36DK.js.map +0 -1
  247. package/dist/chunk-5ON7PUAZ.js +0 -12
  248. package/dist/chunk-5ON7PUAZ.js.map +0 -1
  249. package/dist/chunk-7AXJNQMF.cjs +0 -297
  250. package/dist/chunk-7AXJNQMF.cjs.map +0 -1
  251. package/dist/chunk-7JM3F4KL.js +0 -1795
  252. package/dist/chunk-7JM3F4KL.js.map +0 -1
  253. package/dist/chunk-7USV76HV.cjs +0 -341
  254. package/dist/chunk-7USV76HV.cjs.map +0 -1
  255. package/dist/chunk-A2DZ5BEJ.cjs +0 -1930
  256. package/dist/chunk-A2DZ5BEJ.cjs.map +0 -1
  257. package/dist/chunk-ADBA3XBE.cjs +0 -20
  258. package/dist/chunk-ADBA3XBE.cjs.map +0 -1
  259. package/dist/chunk-AKNGX4TZ.cjs +0 -236
  260. package/dist/chunk-AKNGX4TZ.cjs.map +0 -1
  261. package/dist/chunk-ALYRJ72W.cjs +0 -434
  262. package/dist/chunk-ALYRJ72W.cjs.map +0 -1
  263. package/dist/chunk-AMOJYLG2.cjs +0 -1692
  264. package/dist/chunk-AMOJYLG2.cjs.map +0 -1
  265. package/dist/chunk-AOH6UR2L.js +0 -825
  266. package/dist/chunk-AOH6UR2L.js.map +0 -1
  267. package/dist/chunk-AQNHHJMJ.cjs +0 -261
  268. package/dist/chunk-B7LXJ6LC.cjs +0 -36
  269. package/dist/chunk-B7LXJ6LC.cjs.map +0 -1
  270. package/dist/chunk-BESTLPRK.cjs +0 -6919
  271. package/dist/chunk-BESTLPRK.cjs.map +0 -1
  272. package/dist/chunk-BLI4NIQY.js +0 -98
  273. package/dist/chunk-BLI4NIQY.js.map +0 -1
  274. package/dist/chunk-BSPXMGIS.js +0 -455
  275. package/dist/chunk-BSPXMGIS.js.map +0 -1
  276. package/dist/chunk-C2OMO3WN.cjs +0 -2806
  277. package/dist/chunk-C2OMO3WN.cjs.map +0 -1
  278. package/dist/chunk-CSDQMDU2.js +0 -204
  279. package/dist/chunk-CSDQMDU2.js.map +0 -1
  280. package/dist/chunk-EJ3ILXX6.cjs +0 -223
  281. package/dist/chunk-EJ3ILXX6.cjs.map +0 -1
  282. package/dist/chunk-ENRIK36Q.cjs +0 -94
  283. package/dist/chunk-ENRIK36Q.cjs.map +0 -1
  284. package/dist/chunk-F4UB4XIL.js +0 -109
  285. package/dist/chunk-F4UB4XIL.js.map +0 -1
  286. package/dist/chunk-FD5ZZHEU.js +0 -92
  287. package/dist/chunk-FD5ZZHEU.js.map +0 -1
  288. package/dist/chunk-FE4RC37D.js +0 -2801
  289. package/dist/chunk-FE4RC37D.js.map +0 -1
  290. package/dist/chunk-FEAIOR7N.cjs +0 -91
  291. package/dist/chunk-FEAIOR7N.cjs.map +0 -1
  292. package/dist/chunk-FR7RNOPT.cjs +0 -3303
  293. package/dist/chunk-FR7RNOPT.cjs.map +0 -1
  294. package/dist/chunk-G2YPPLGX.cjs +0 -484
  295. package/dist/chunk-G2YPPLGX.cjs.map +0 -1
  296. package/dist/chunk-GCM5JHMX.js +0 -88
  297. package/dist/chunk-GCM5JHMX.js.map +0 -1
  298. package/dist/chunk-GDEU72RG.cjs +0 -829
  299. package/dist/chunk-GDEU72RG.cjs.map +0 -1
  300. package/dist/chunk-HKTQCQ4Z.cjs +0 -8383
  301. package/dist/chunk-HKTQCQ4Z.cjs.map +0 -1
  302. package/dist/chunk-HWHU642X.cjs +0 -316
  303. package/dist/chunk-HWHU642X.cjs.map +0 -1
  304. package/dist/chunk-ICEKS6YC.cjs +0 -507
  305. package/dist/chunk-ICEKS6YC.cjs.map +0 -1
  306. package/dist/chunk-IJGOFP2J.js +0 -6904
  307. package/dist/chunk-IJGOFP2J.js.map +0 -1
  308. package/dist/chunk-IQJGDZOP.js +0 -333
  309. package/dist/chunk-IQJGDZOP.js.map +0 -1
  310. package/dist/chunk-IT74O4BE.cjs +0 -456
  311. package/dist/chunk-IT74O4BE.cjs.map +0 -1
  312. package/dist/chunk-KXDQKVNX.cjs +0 -459
  313. package/dist/chunk-KXDQKVNX.cjs.map +0 -1
  314. package/dist/chunk-L2TE7PMO.cjs +0 -14
  315. package/dist/chunk-L2TE7PMO.cjs.map +0 -1
  316. package/dist/chunk-L5YHV6BQ.js +0 -499
  317. package/dist/chunk-L5YHV6BQ.js.map +0 -1
  318. package/dist/chunk-LO7HU5WB.cjs +0 -209
  319. package/dist/chunk-LO7HU5WB.cjs.map +0 -1
  320. package/dist/chunk-LSALB3IN.js +0 -292
  321. package/dist/chunk-LSALB3IN.js.map +0 -1
  322. package/dist/chunk-MI7OTUHL.cjs +0 -339
  323. package/dist/chunk-MI7OTUHL.cjs.map +0 -1
  324. package/dist/chunk-MIGXCBXT.cjs +0 -381
  325. package/dist/chunk-MIGXCBXT.cjs.map +0 -1
  326. package/dist/chunk-MVTOCRV2.js +0 -213
  327. package/dist/chunk-MVTOCRV2.js.map +0 -1
  328. package/dist/chunk-N7FNVFXW.cjs +0 -32
  329. package/dist/chunk-N7FNVFXW.cjs.map +0 -1
  330. package/dist/chunk-N7OA4WPJ.js +0 -362
  331. package/dist/chunk-N7OA4WPJ.js.map +0 -1
  332. package/dist/chunk-NAWZATKT.js +0 -478
  333. package/dist/chunk-NAWZATKT.js.map +0 -1
  334. package/dist/chunk-NLNDMWZC.js +0 -31
  335. package/dist/chunk-NLNDMWZC.js.map +0 -1
  336. package/dist/chunk-ORM7CHYZ.js +0 -1531
  337. package/dist/chunk-ORM7CHYZ.js.map +0 -1
  338. package/dist/chunk-OUHT5Z36.cjs +0 -393
  339. package/dist/chunk-OUHT5Z36.cjs.map +0 -1
  340. package/dist/chunk-PCZVMMWU.cjs +0 -74
  341. package/dist/chunk-PCZVMMWU.cjs.map +0 -1
  342. package/dist/chunk-RNKDIXDV.js +0 -336
  343. package/dist/chunk-RNKDIXDV.js.map +0 -1
  344. package/dist/chunk-SBUFNJVE.js +0 -258
  345. package/dist/chunk-SBUFNJVE.js.map +0 -1
  346. package/dist/chunk-TC6BTUSU.cjs +0 -1799
  347. package/dist/chunk-TC6BTUSU.cjs.map +0 -1
  348. package/dist/chunk-TPOK3UNI.js +0 -8355
  349. package/dist/chunk-TPOK3UNI.js.map +0 -1
  350. package/dist/chunk-UF6JG5SG.js +0 -312
  351. package/dist/chunk-UF6JG5SG.js.map +0 -1
  352. package/dist/chunk-UKQHXPGW.js +0 -30
  353. package/dist/chunk-UKQHXPGW.js.map +0 -1
  354. package/dist/chunk-V4XG5QF6.js +0 -1685
  355. package/dist/chunk-V4XG5QF6.js.map +0 -1
  356. package/dist/chunk-VEKIWQ3F.cjs +0 -39
  357. package/dist/chunk-VEKIWQ3F.cjs.map +0 -1
  358. package/dist/chunk-WMQRJTAO.js +0 -3266
  359. package/dist/chunk-WMQRJTAO.js.map +0 -1
  360. package/dist/chunk-X6K3HUOY.cjs +0 -86
  361. package/dist/chunk-X6K3HUOY.cjs.map +0 -1
  362. package/dist/chunk-XBTEO4OB.js +0 -391
  363. package/dist/chunk-XBTEO4OB.js.map +0 -1
  364. package/dist/chunk-XIYYHA65.cjs +0 -101
  365. package/dist/chunk-XIYYHA65.cjs.map +0 -1
  366. package/dist/chunk-YJHY7CMN.cjs +0 -1534
  367. package/dist/chunk-YJHY7CMN.cjs.map +0 -1
  368. package/dist/chunk-YLJ4XMA6.js +0 -33
  369. package/dist/chunk-YLJ4XMA6.js.map +0 -1
  370. package/dist/chunk-YNIWOYW6.js +0 -232
  371. package/dist/chunk-YNIWOYW6.js.map +0 -1
  372. package/dist/chunk-Z2XP767T.cjs +0 -35
  373. package/dist/chunk-Z2XP767T.cjs.map +0 -1
  374. package/dist/chunk-Z4X2RWOF.js +0 -37
  375. package/dist/chunk-Z4X2RWOF.js.map +0 -1
  376. package/dist/chunk-ZN6YYPIW.js +0 -67
  377. package/dist/chunk-ZN6YYPIW.js.map +0 -1
  378. package/dist/chunk-ZNFFTYWH.js +0 -1854
  379. package/dist/chunk-ZNFFTYWH.js.map +0 -1
  380. package/dist/variables.cjs +0 -17
  381. package/dist/variables.cjs.map +0 -1
  382. package/dist/variables.d.cts +0 -87
  383. package/dist/variables.d.ts +0 -87
  384. package/dist/variables.js +0 -4
  385. package/dist/variables.js.map +0 -1
@@ -0,0 +1,2 @@
1
+ import {a as a$1,b as b$1,f,e,d,c}from'./chunk-2JMFUQZH.js';var p=new Map(Object.entries(a$1)),_=new Map(Object.entries(b$1));function a(n){return p.get(n)}function b(n,e,t){let r=p.get(e);if(r===void 0)throw new RangeError(`${e} is not a valid unit`);let i=p.get(t);if(i===void 0)throw new RangeError(`${t} is not a valid unit`);return x(n,e,t,r,i)}function x(n,e,t,r,i){let s=r,u=i;if(s[0]!==u[0])throw new RangeError(`Cannot convert between different measures: ${e} and ${t}`);let o=s[1],d=u[1],f=_.get(e),l=_.get(t);return f!==void 0?l!==void 0?(n+f)*(o/d)-l:(n+f)*(o/d):l!==void 0?n*(o/d)-l:n*(o/d)}function B(n,e){let t=p.get(e);if(t===void 0)throw new RangeError(`${e} is not a valid unit`);let r=c[t[0]],i=r[0][0],s=i,u=b(n,e,i),o=u<0?-u:u;for(let d=0;d<r.length;d++){let f=r[d];if(o>=f[1])s=f[0];else break}return {quantity:b(n,e,s),unit:s}}var v=new Set(["workday","workdays"]),F=7/5;function g(n){return typeof n=="string"&&v.has(n)}function k(n){return n}function m(n){if(g(n))return m("day");let e$1=f[n];if(e$1)return e$1.measure;let t=a(n);if(t!==void 0)return e[t[0]]}function K(n,e){if(n===e)return true;if(g(n)||g(e)){let u=m(n),o=m(e);return !!u&&u===o}let t=a(n),r=a(e);if(t!==void 0&&r!==void 0)return t[0]===r[0];let i=f[n],s=f[e];return i!==void 0&&s!==void 0?i.measure===s.measure:y(n,e)||y(e,n)}function y(n,e$1){let t=f[n];if(t===void 0)return false;let r=a(e$1);return r===void 0?false:e[r[0]]===t.measure}function R(n,e,t){if(e===t)return n;let r=a(e),i=a(t);if(r!==void 0&&i!==void 0)return x(n,e,t,r,i);if(g(e)&&g(t))return n;if(g(e)){let o=n*F;return t==="day"?o:R(o,"day",t)}if(g(t))return (e==="day"?n:R(n,e,"day"))/F;let s=f[e],u=f[t];return s!==void 0&&u!==void 0?n*(s.toBase/u.toBase):s!==void 0&&y(e,t)?b(n*s.toBase,N(t),t):u!==void 0&&y(t,e)?b(n,e,N(e))/u.toBase:b(n,e,t)}function N(n){let e=a(n);if(e===void 0)return n;for(let t of Object.keys(a$1)){let r=a$1[t];if(r[0]===e[0]&&r[1]===1)return t}return n}function L(n){let e=n,t=a(e);if(t===void 0)return [];let r=d[t[0]];return r?r.filter(i=>i!==e):[]}function $(n){return g(n)||f[n]?true:a(n)!==void 0}function Y(n,e){let t=e;try{let r=B(n,t);return {value:r.quantity,unit:r.unit}}catch{return {value:n,unit:t}}}function S(n,e){let t=e.indexOf("/");if(t>=0)return {value:n,numerator:e.slice(0,t),denominator:e.slice(t+1)};let r=f[e];return r!==void 0&&r.measure==="speed"?{value:n*r.toBase,numerator:"m",denominator:"s"}:null}function O(n,e){if(n===e)return 1;if(n===""||e==="")return null;let t=m(n),r=m(e);return t===void 0||r===void 0||t!==r?null:R(1,n,e)}function j(n,e,t){let r=S(n,e);if(r===null)return null;let i,s,u,o=t.indexOf("/");if(o>=0)i=t.slice(0,o),s=t.slice(o+1),u=1;else {let l=f[t];if(l===void 0||l.measure!=="speed")return null;i="m",s="s",u=l.toBase;}let d=O(r.numerator,i);if(d===null)return null;let f$1=O(r.denominator,s);return f$1===null?null:r.value*d/f$1/u}export{g as a,k as b,m as c,K as d,R as e,L as f,$ as g,Y as h,j as i};//# sourceMappingURL=chunk-WGZ3FNHI.js.map
2
+ //# sourceMappingURL=chunk-WGZ3FNHI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/uom/UnitConversion.ts","../src/uom/UomConverter.ts"],"names":["UNIT_LOOKUP","UNIT_TABLE","DIFFERENCE_LOOKUP","UNIT_DIFFERENCES","lookupUnit","unit","convertRaw","quantity","from","to","parsedFrom","parsedTo","convertResolved","fromEntry","toEntry","fromRatio","toRatio","fromDifference","toDifference","convertToBestMetric","best","BEST_UNITS_METRIC","smallestUnit","bestUnit","baseQuantity","absQuantity","i","bestEntry","WORKDAY_UNIT_NAMES","WORKDAY_TO_DAY_FACTOR","isWorkdayUnit","resolveUnit","getMeasure","extended","EXTENDED_UNITS","entry","MEASURE_KIND_NAMES","canConvert","fromMeasure","toMeasure","fromExtended","toExtended","bridgesToBaseMeasure","extendedUnit","baseUnit","base","convertUnit","value","days","fExt","tExt","baseUnitFor","symbol","candidate","getConvertiblePossibilities","resolved","symbols","MEASURE_SYMBOLS","s","isConvertibleUnit","getBestUnit","u","result","expandUnitToRate","slash","ext","rateAxisFactor","convertRate","source","targetNumerator","targetDenominator","targetScale","numeratorFactor","denominatorFactor"],"mappings":"4DAmCA,IAAMA,CAAAA,CAA8C,IAAI,GAAA,CAAI,MAAA,CAAO,QAAQC,GAAU,CAAC,CAAA,CAShFC,CAAAA,CAAiD,IAAI,GAAA,CAAI,OAAO,OAAA,CAAQC,GAAgB,CAAC,CAAA,CAgBxF,SAASC,EAAWC,CAAAA,CAAqC,CAC9D,OAAOL,CAAAA,CAAY,GAAA,CAAIK,CAAI,CAC7B,CAWO,SAASC,EAAWC,CAAAA,CAAkBC,CAAAA,CAAcC,EAAoB,CAC7E,IAAMC,CAAAA,CAAaV,CAAAA,CAAY,GAAA,CAAIQ,CAAI,EACvC,GAAIE,CAAAA,GAAe,MAAA,CACjB,MAAM,IAAI,UAAA,CAAW,GAAGF,CAAI,CAAA,oBAAA,CAAsB,CAAA,CAGpD,IAAMG,CAAAA,CAAWX,CAAAA,CAAY,IAAIS,CAAE,CAAA,CACnC,GAAIE,CAAAA,GAAa,MAAA,CACf,MAAM,IAAI,UAAA,CAAW,CAAA,EAAGF,CA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A,CAAGtC,CAAAA,CAAMC,CAAE,CAChC,CAiBO,SAAS0D,CAAAA,CAAYpB,CAAAA,CAAevC,CAAAA,CAAcC,CAAAA,CAA2B,CAClF,IAAM2D,CAAAA,CAASL,CAAAA,CAAiBhB,CAAAA,CAAOvC,CAAI,CAAA,CAC3C,GAAI4D,IAAW,IAAA,CAAM,OAAO,KAK5B,IAAIC,CAAAA,CACAC,EACAC,CAAAA,CACEP,CAAAA,CAAQvD,CAAAA,CAAG,OAAA,CAAQ,GAAG,CAAA,CAC5B,GAAIuD,CAAAA,EAAS,CAAA,CACXK,CAAAA,CAAkB5D,CAAAA,CAAG,KAAA,CAAM,CAAA,CAAGuD,CAAK,CAAA,CACnCM,CAAAA,CAAoB7D,CAAAA,CAAG,KAAA,CAAMuD,CAAAA,CAAQ,CAAC,EACtCO,CAAAA,CAAc,CAAA,CAAA,KACT,CACL,IAAMN,CAAAA,CAAM/B,EAAezB,CAAE,CAAA,CAC7B,GAAIwD,CAAAA,GAAQ,MAAA,EAAaA,CAAAA,CAAI,UAAY,OAAA,CAAS,OAAO,IAAA,CACzDI,CAAAA,CAAkB,GAAA,CAClBC,CAAAA,CAAoB,IACpBC,CAAAA,CAAcN,CAAAA,CAAI,OACpB,CAEA,IAAMO,CAAAA,CAAkBN,EAAeE,CAAAA,CAAO,SAAA,CAAWC,CAAe,CAAA,CACxE,GAAIG,IAAoB,IAAA,CAAM,OAAO,IAAA,CACrC,IAAMC,GAAAA,CAAoBP,CAAAA,CAAeE,EAAO,WAAA,CAAaE,CAAiB,CAAA,CAC9E,OAAIG,GAAAA,GAAsB,IAAA,CAAa,KAE/BL,CAAAA,CAAO,KAAA,CAAQI,CAAAA,CAAmBC,GAAAA,CAAoBF,CAChE","file":"chunk-WGZ3FNHI.js","sourcesContent":["/**\n * The unit conversion algorithm, ported from the `convert` npm package v7.0.2\n * alongside its tables (see `generated/UnitTable.generated.ts` and\n * THIRD-PARTY-NOTICES.md).\n *\n * Transliterated expression for expression rather than rewritten. Floating\n * point is not associative, so `(q + d) * (a / b) - d2` and any algebraically\n * equal rearrangement disagree in the last bits. Those bits are observable:\n * `0.5 l` best-converts to `500.00000000000006 mL` today, and the test suite\n * pins several conversions to ten decimal places.\n *\n * This module is deliberately unaware of the engine's own additions. Workdays,\n * extended units, currency and the caches all live in `UomConverter.ts`, which\n * layers them on top of these three functions.\n */\n\nimport {\n UNIT_TABLE,\n UNIT_DIFFERENCES,\n BEST_UNITS_METRIC,\n type UnitEntry,\n} from \"./generated/UnitTable.generated\";\n\n/**\n * The generated tables re-keyed into Maps once at module load.\n *\n * Not a micro-optimization. A 1456-key object literal lands in V8's dictionary\n * mode, and guarding a read on it against inherited names (`constructor`,\n * `toString`) costs about 123ns per call with either `hasOwnProperty.call` or\n * `Object.hasOwn`, measured. `Map.get` is about 6ns and needs no guard at all,\n * because a Map has no prototype chain to fall through to. That is a 20x\n * difference on the single hottest operation in the unit system: `convertRaw`\n * performs two of these per call, and `LanguageService` sweeps all 1456 keys\n * to build completions.\n */\nconst UNIT_LOOKUP: ReadonlyMap<string, UnitEntry> = new Map(Object.entries(UNIT_TABLE));\n\n/**\n * Temperature offsets, as a Map for the same reason.\n *\n * Also removes a latent hazard: the upstream code tests membership with `in`,\n * and `\"toString\" in UNIT_DIFFERENCES` is true, so an inherited name reaching\n * that branch would add a function to a number.\n */\nconst DIFFERENCE_LOOKUP: ReadonlyMap<string, number> = new Map(Object.entries(UNIT_DIFFERENCES));\n\n/**\n * Looks up a unit spelling.\n *\n * @returns its `[kind, ratio]` entry, or `undefined` if the spelling is not a\n * unit. Case-sensitive: no normalization or aliasing happens anywhere in this\n * module.\n *\n * The one deliberate deviation from upstream. `convert` tests membership with\n * `in` and reads the property directly, so inherited names like \"constructor\"\n * and \"toString\" reach its measure comparison and fail there with \"Cannot\n * convert between different measures\" instead of \"is not a valid unit\". Both\n * throw a RangeError and both report no measure, so nothing downstream can\n * tell the difference, and naming the real problem is the better message.\n */\nexport function lookupUnit(unit: string): UnitEntry | undefined {\n return UNIT_LOOKUP.get(unit);\n}\n\n/**\n * Converts `quantity` from one unit to another.\n *\n * THROWS a `RangeError` for an unknown unit or a pair in different measures.\n * Callers depend on that: `VM.ts`'s `extractDurationMs()` calls this with an\n * arbitrary unit inside a bare try/catch and treats the throw as \"not a\n * duration, contribute zero\". Returning NaN or the input unchanged instead\n * would turn `<date> + 5 kg` into an Invalid Date rather than a no-op.\n */\nexport function convertRaw(quantity: number, from: string, to: string): number {\n const parsedFrom = UNIT_LOOKUP.get(from);\n if (parsedFrom === undefined) {\n throw new RangeError(`${from} is not a valid unit`);\n }\n\n const parsedTo = UNIT_LOOKUP.get(to);\n if (parsedTo === undefined) {\n throw new RangeError(`${to} is not a valid unit`);\n }\n\n return convertResolved(quantity, from, to, parsedFrom, parsedTo);\n}\n\n/**\n * The conversion arithmetic, for callers that have already looked both units\n * up and want to skip doing it twice.\n *\n * Split out for `UomConverter.convertUnit()`, which has to check whether\n * either side is a workday or an extended unit before it can dispatch, and\n * would otherwise resolve each unit once to decide and again to convert. The\n * entries MUST be the ones this module returned for these exact spellings.\n */\nexport function convertResolved(\n quantity: number,\n from: string,\n to: string,\n fromEntry: UnitEntry,\n toEntry: UnitEntry\n): number {\n const parsedFrom = fromEntry;\n const parsedTo = toEntry;\n\n if (parsedFrom[0] !== parsedTo[0]) {\n // DELIBERATE DEVIATION from the ported original, which silently reinterpreted\n // \"m\" as minutes whenever the other side was a time unit. That is a guess,\n // and this project's stated position is that refusing to guess is the safer\n // default for a tool doing arithmetic on someone's real numbers (see\n // docs/architecture/design-decisions.md). The guess was not harmless: it\n // reached `<date> + <duration>` through VM.ts's extractDurationMs(), where\n // `today + 5 m` silently added five MINUTES for someone who wrote metres.\n //\n // Minutes are spelled \"min\", \"minute\" or \"minutes\", all of which the table\n // has always accepted.\n throw new RangeError(`Cannot convert between different measures: ${from} and ${to}`);\n }\n\n const fromRatio = parsedFrom[1];\n const toRatio = parsedTo[1];\n\n // Only six units in the whole table carry an offset, so the common path is\n // both misses. Reading the Map once per side and reusing the value beats\n // testing membership and then reading it again.\n const fromDifference = DIFFERENCE_LOOKUP.get(from);\n const toDifference = DIFFERENCE_LOOKUP.get(to);\n\n // Scales that do not share an origin (temperature) need the offset applied\n // around the ratio. Do not refactor the four branches into one expression:\n // the grouping is what makes the result bit-identical to the original.\n if (fromDifference !== undefined) {\n if (toDifference !== undefined) {\n return (quantity + fromDifference) * (fromRatio / toRatio) - toDifference;\n }\n return (quantity + fromDifference) * (fromRatio / toRatio);\n }\n\n if (toDifference !== undefined) {\n return quantity * (fromRatio / toRatio) - toDifference;\n }\n\n return quantity * (fromRatio / toRatio);\n}\n\n/**\n * Picks the most readable metric unit for a magnitude and converts to it.\n *\n * Only the metric lists are ported; nothing has ever requested the imperial\n * ones. Note the final conversion goes from the ORIGINAL unit to the chosen\n * one directly rather than via the smallest unit, which is what keeps the\n * result exact.\n */\nexport function convertToBestMetric(\n quantity: number,\n from: string\n): { quantity: number; unit: string } {\n const parsedFrom = UNIT_LOOKUP.get(from);\n if (parsedFrom === undefined) {\n throw new RangeError(`${from} is not a valid unit`);\n }\n\n const best = BEST_UNITS_METRIC[parsedFrom[0]];\n const smallestUnit = best[0][0];\n let bestUnit = smallestUnit;\n\n const baseQuantity = convertRaw(quantity, from, smallestUnit);\n const absQuantity = baseQuantity < 0 ? -baseQuantity : baseQuantity;\n\n // Thresholds are expressed in the smallest unit and ascend, so the last one\n // the magnitude reaches wins. Breaking early rather than scanning the whole\n // list matters for zero and for negatives, which stay on the smallest unit.\n for (let i = 0; i < best.length; i++) {\n const bestEntry = best[i];\n if (absQuantity >= bestEntry[1]) {\n bestUnit = bestEntry[0];\n } else {\n break;\n }\n }\n\n return { quantity: convertRaw(quantity, from, bestUnit), unit: bestUnit };\n}\n","/**\n * UoM Converter, built on the in-house unit tables in `UnitConversion.ts` and\n * `generated/UnitTable.generated.ts` (ported from the `convert` npm package\n * v7.0.2 so the engine ships with no runtime dependencies).\n *\n * Units are strictly case-sensitive and are looked up without aliasing. No unit\n * remapping, what you type is what you get.\n * e.g. 'C' = Celsius, 'c' = cup; 'MB' = megabytes, 'mb' = millibits.\n *\n * This file owns everything the base tables do not: the workday shim, the\n * extended (custom-measure) units, and the two caches.\n */\n\nimport { lookupUnit, convertRaw, convertResolved, convertToBestMetric } from \"@solve-js/uom/UnitConversion\";\nimport { MEASURE_KIND_NAMES, MEASURE_SYMBOLS, UNIT_TABLE } from \"@solve-js/uom/generated/UnitTable.generated\";\nimport { EXTENDED_UNITS } from \"@solve-js/uom/ExtendedUnits\";\n\n// ── \"workday\", a synthetic unit with no entry in the base table ───────────\n//\n// A business day (Mon-Fri) backing the datetime package's `<date> + N\n// workdays` arithmetic and `$X/workday` Rate literals\n// (packages/datetime/). NOT a real physical unit, a business day has no\n// fixed duration, since it depends on which calendar dates are weekends\n// so the ported base table has no concept of it and can't be\n// taught one without monkey-patching its internal unit table.\n//\n// For RATE-MATH purposes only (e.g. \"$500/workday x 4 weeks\" needs a\n// workday count to multiply by), a workday is treated as a FIXED 7/5 of a\n// calendar day: 5 workdays span exactly 7 calendar days in a whole week,\n// so this ratio is exact for whole-week spans and a reasonable linear\n// approximation otherwise. This is deliberately NOT the same\n// calendar-aware, weekend-skipping logic real \"<date> + N workdays\" date\n// arithmetic needs (see vm/VM.ts's addBusinessDays()), that can't be\n// reduced to a fixed ratio, since the exact skip pattern depends on which\n// day of the week the calculation actually starts from.\n//\n// Handled here as a thin pre/post layer in front of the normal\n// base-table path (rather than inside the tables themselves) so every\n// caller of getMeasure()/convertUnit()/canConvert() automatically gets\n// workday support for free.\nconst WORKDAY_UNIT_NAMES = new Set([\"workday\", \"workdays\"]);\nconst WORKDAY_TO_DAY_FACTOR = 7 / 5; // 1 workday == 1.4 calendar days\n\n/** Whether `unit` is the synthetic \"workday\" unit (see module note above). */\nexport function isWorkdayUnit(unit: string | undefined): unit is string {\n return typeof unit === \"string\" && WORKDAY_UNIT_NAMES.has(unit);\n}\n\n/**\n * Validate `unit` against the known unit table.\n *\n * @returns `unit` unchanged in all cases. This does NOT normalize casing\n * or aliasing (units are strictly case-sensitive, see the module note\n * above). A unit the table doesn't recognize is still\n * returned as-is (not thrown), so callers must not assume a returned\n * string is actually convertible, check with {@link isConvertibleUnit}\n * or {@link canConvert} first if that matters.\n *\n * Kept as an identity function purely for API compatibility. It used to guard\n * a validity cache, which existed because validating a unit meant a\n * throw/catch round trip through the old dependency. Validation is now a Map\n * lookup, so the cache cost more than it saved: worse, it was capped at 1000\n * entries against a 1456-unit table, so any sweep over the full vocabulary\n * (which is exactly what LanguageService does to build completions) evicted\n * on almost every call. That one change took the full-table sweep from 7.7ms\n * to under 20us.\n */\nexport function resolveUnit(unit: string): string {\n return unit;\n}\n\n// MEASURE_KIND_NAMES now comes from the generated table (it is derived data,\n// so the generator emits it rather than it being retyped here). The reason it\n// is a module-level constant has not changed: getMeasure() runs at least twice\n// per conversion, and this used to be reallocated on every call.\n\n/**\n * Get the measure/dimension kind for `unit` (e.g. `\"length\"`, `\"mass\"`,\n * `\"temperature\"`), used to check whether two units are even in the same\n * dimension before attempting a conversion.\n *\n * @returns `undefined` if `unit` isn't recognized, rather than throwing.\n */\nexport function getMeasure(unit: string): string | undefined {\n // Workday is a Time-measure unit by convention (see isWorkdayUnit's doc\n // comment) and is not in the base table, so resolve its measure via \"day\"\n // instead of attempting the real lookup below.\n if (isWorkdayUnit(unit)) return getMeasure(\"day\");\n\n // Extended (custom) categories the base table has no measure kind for,\n // see ExtendedUnits.ts.\n const extended = EXTENDED_UNITS[unit];\n if (extended) return extended.measure;\n\n const entry = lookupUnit(unit);\n if (entry === undefined) return undefined;\n\n return MEASURE_KIND_NAMES[entry[0]];\n}\n\n/**\n * Check whether `from` can be converted to `to`. Same unit, or same\n * measure kind (length, mass, ...) and the underlying tables accept the pair.\n * Never throws; returns `false` on any failure.\n */\nexport function canConvert(from: string, to: string): boolean {\n if (from === to) return true;\n if (isWorkdayUnit(from) || isWorkdayUnit(to)) {\n const fromMeasure = getMeasure(from);\n const toMeasure = getMeasure(to);\n return !!fromMeasure && fromMeasure === toMeasure;\n }\n // One table read per side, comparing numeric kind ids. The old shape called\n // getMeasure() on each side (two more reads) purely to compare the resulting\n // STRINGS, then did a throwaway conversion to confirm what the kind check had\n // already established.\n const fromEntry = lookupUnit(from);\n const toEntry = lookupUnit(to);\n if (fromEntry !== undefined && toEntry !== undefined) {\n return fromEntry[0] === toEntry[0];\n }\n\n // Extended (custom) categories aren't in the base table at all, so they are\n // compared on their own measure names instead.\n const fromExtended = EXTENDED_UNITS[from];\n const toExtended = EXTENDED_UNITS[to];\n if (fromExtended !== undefined && toExtended !== undefined) {\n return fromExtended.measure === toExtended.measure;\n }\n\n // Mixed: one side is in the base table and the other is extended. That used\n // to be refused outright, on the grounds that the two measure spaces are\n // disjoint. They are not, once an extended unit names a measure the base\n // table also has: `furlong` is a length and so is `m`, and the ratio between\n // them is exactly what both tables already record.\n return bridgesToBaseMeasure(from, to) || bridgesToBaseMeasure(to, from);\n}\n\n/**\n * Whether `extendedUnit` extends a measure the base table also knows, so a\n * value in it can reach `baseUnit`.\n *\n * The bridge works because both tables express a unit as a ratio to the same\n * physical base: the generated table's length ratios are metres and its mass\n * ratios are grams, and an extended unit declaring `measure: \"length\"` states\n * its `toBase` in the same metres. Composing the two ratios is then ordinary\n * arithmetic rather than a second conversion system.\n *\n * A measure the base table has no concept of, such as pace, still fails here,\n * which is the behaviour this replaced and the reason the check is by measure\n * name rather than by presence in the extended table.\n */\nfunction bridgesToBaseMeasure(extendedUnit: string, baseUnit: string): boolean {\n const extended = EXTENDED_UNITS[extendedUnit];\n if (extended === undefined) return false;\n\n const base = lookupUnit(resolveUnit(baseUnit));\n if (base === undefined) return false;\n\n return MEASURE_KIND_NAMES[base[0]] === extended.measure;\n}\n\n/**\n * Convert `value` from unit `from` to unit `to`.\n *\n * Does not validate that the conversion is possible, callers should check\n * with {@link canConvert} first if `from`/`to` aren't already known-good.\n *\n * THROWS a RangeError for an unknown unit or a cross-measure pair. `VM.ts`'s\n * `extractDurationMs()` depends on that, see {@link convertRaw}.\n *\n * This used to memoize a per-pair conversion factor in an LFU cache. The cache\n * is gone: computing the factor is now two Map reads, while the cache cost a\n * template-string key allocation on every call plus the LFU's own frequency\n * bookkeeping, so it was slower than the work it avoided. Removing it is\n * bit-exact, not merely close: the cache stored `convertRaw(1, f, t)`, which is\n * exactly `fromRatio / toRatio`, and then multiplied, which is the identical\n * expression `convertRaw(value, f, t)` evaluates. It also deleted the special\n * case that existed only to keep offset-based temperature pairs out of a\n * factor cache.\n */\nexport function convertUnit(value: number, from: string, to: string): number {\n if (from === to) return value;\n\n // Fast path first: two ordinary units, which is nearly every call. Resolving\n // both here and handing the entries to convertResolved() avoids looking them\n // up again inside convertRaw(). Neither workdays nor extended units appear in\n // the base table, so they always fall through to the branches below and this\n // ordering cannot steal a case from them. UnitVocabulary.spec.ts pins that\n // the two vocabularies stay disjoint.\n const fromEntry = lookupUnit(from);\n const toEntry = lookupUnit(to);\n if (fromEntry !== undefined && toEntry !== undefined) {\n return convertResolved(value, from, to, fromEntry, toEntry);\n }\n\n // Workday <-> any other Time-measure unit: pivot through \"day\" using the\n // fixed 7/5 ratio (see isWorkdayUnit's doc comment above).\n if (isWorkdayUnit(from) && isWorkdayUnit(to)) return value; // \"workday\" <-> \"workdays\" alias\n if (isWorkdayUnit(from)) {\n const days = value * WORKDAY_TO_DAY_FACTOR;\n return to === \"day\" ? days : convertUnit(days, \"day\", to);\n }\n if (isWorkdayUnit(to)) {\n const days = from === \"day\" ? value : convertUnit(value, from, \"day\");\n return days / WORKDAY_TO_DAY_FACTOR;\n }\n\n // Extended (custom) categories the base table has no measure kind for\n // (see ExtendedUnits.ts), compute the ratio directly from each unit's\n // factor-to-base value instead of calling convertRaw(), which would throw\n // on an unrecognized unit string. Every extended category is a pure linear\n // ratio scale (no Temperature-style offset), so this is always safe.\n const fExt = EXTENDED_UNITS[from];\n const tExt = EXTENDED_UNITS[to];\n if (fExt !== undefined && tExt !== undefined) {\n return value * (fExt.toBase / tExt.toBase);\n }\n\n // One side extended, the other in the base table, sharing a measure. Convert\n // through the measure's base unit, which both tables state their ratios\n // against: an extended length declares its `toBase` in metres, and the\n // generated table's length ratios are metres too.\n if (fExt !== undefined && bridgesToBaseMeasure(from, to)) {\n return convertRaw(value * fExt.toBase, baseUnitFor(to), to);\n }\n if (tExt !== undefined && bridgesToBaseMeasure(to, from)) {\n return convertRaw(value, from, baseUnitFor(from)) / tExt.toBase;\n }\n\n // Offsets, cross-measure rejection and the unknown-unit throw all live in\n // convertRaw. Nothing is layered on top here any more.\n return convertRaw(value, from, to);\n}\n\n/**\n * The unit a measure states its ratios against, found from any unit in it.\n *\n * Read out of the table rather than hard-coded, so it cannot drift from the\n * ratios it has to agree with: the base is whichever unit of that measure has\n * a ratio of exactly one.\n */\nfunction baseUnitFor(unit: string): string {\n const entry = lookupUnit(resolveUnit(unit));\n if (entry === undefined) return unit;\n\n for (const symbol of Object.keys(UNIT_TABLE)) {\n const candidate = UNIT_TABLE[symbol];\n if (candidate[0] === entry[0] && candidate[1] === 1) return symbol;\n }\n return unit;\n}\n\n/**\n * List every unit symbol in the same measure/dimension as `unit` (wiki:\n * Units-Of-Measurement, \"Conversion Possibilities\", `sourceUnit to ?`\n * e.g. `cm to ?\"` → every Length unit). Excludes `unit` itself.\n *\n * Reads MEASURE_SYMBOLS, which is a curated symbols-only vocabulary and\n * deliberately NOT the keys of the unit table filtered by kind. The two\n * differ: Volume's symbols include `c` and `pt` but not `cup`/`cups`, and\n * Time's include `wk` and `mo` but not `week`/`month`. Deriving this list\n * from the unit table instead would roughly quadruple every answer.\n *\n * @returns `[]` if `unit` isn't recognized, rather than throwing.\n */\nexport function getConvertiblePossibilities(unit: string): string[] {\n const resolved = resolveUnit(unit);\n const entry = lookupUnit(resolved);\n if (entry === undefined) return [];\n const symbols = MEASURE_SYMBOLS[entry[0]];\n if (!symbols) return [];\n return symbols.filter((s) => s !== resolved);\n}\n\n/** Check whether `unit` is a unit the conversion tables recognize. Never throws. */\nexport function isConvertibleUnit(unit: string): boolean {\n if (isWorkdayUnit(unit)) return true;\n if (EXTENDED_UNITS[unit]) return true;\n return lookupUnit(resolveUnit(unit)) !== undefined;\n}\n\n/**\n * Convert `value` (in `unit`) to whichever unit of the same measure gives\n * the most human-readable magnitude, e.g. 1500 metres becomes 1.5 km. Falls\n * back to returning `value`/`unit` unchanged if `unit` isn't recognized,\n * which is what every extended unit and workday does.\n *\n * Note the chosen unit is drawn from the best-unit lists, which are not\n * restricted to spellings the lexer accepts: 0.5 l reports \"mL\".\n */\nexport function getBestUnit(value: number, unit: string): { value: number; unit: string } {\n const u = resolveUnit(unit);\n try {\n const result = convertToBestMetric(value, u);\n return { value: result.quantity, unit: result.unit };\n } catch {\n return { value, unit: u };\n }\n}\n\n// ── Rate and derived-unit conversion ───────────────────────────────────────\n//\n// A rate value carries a compound unit spelled \"numerator/denominator\" (e.g.\n// \"km/h\", \"m/s\"), see vm/Value.ts's rateValue(). Plain convertUnit() cannot\n// touch one, because neither half is the whole unit and getMeasure(\"km/h\") is\n// undefined. This section converts a rate to another rate, and bridges a rate\n// to the single-token speed spellings (mph, kph, mps, ...) that ExtendedUnits.ts\n// already carries, so \"100 km/h in mph\" and \"60 mph in km/h\" resolve instead of\n// reporting incompatible units.\n\n/** A rate reduced to a numerator unit over a denominator unit. */\ninterface RateForm {\n /** Magnitude, scaled so `value numerator/denominator` is the physical quantity. */\n value: number;\n /** Numerator unit spelling, or `\"\"` for a countless rate such as `30/week`. */\n numerator: string;\n /** Denominator unit spelling. */\n denominator: string;\n}\n\n/**\n * Express `value unit` as a numerator/denominator rate, or `null` when `unit`\n * is neither a compound rate spelling nor a single-token speed alias.\n *\n * A speed alias (mph, kph, ...) is one unit standing for a length/time rate, so\n * it expands to the base pair `m`/`s` with its value scaled by the alias's\n * metres-per-second factor. That collapses both inputs to one shape, so a\n * single routine handles rate/rate and rate/alias without a second code path.\n */\nfunction expandUnitToRate(value: number, unit: string): RateForm | null {\n const slash = unit.indexOf(\"/\");\n if (slash >= 0) {\n return { value, numerator: unit.slice(0, slash), denominator: unit.slice(slash + 1) };\n }\n const ext = EXTENDED_UNITS[unit];\n if (ext !== undefined && ext.measure === \"speed\") {\n // 1 alias == ext.toBase m/s, so `value alias` is `value * toBase` m/s.\n return { value: value * ext.toBase, numerator: \"m\", denominator: \"s\" };\n }\n return null;\n}\n\n/**\n * The factor that turns one `from` into `to` along a single rate axis, or\n * `null` when the two cannot line up.\n *\n * Same spelling needs no conversion. A countless axis (`\"\"`) only lines up with\n * another countless one, never with a real unit. Otherwise both sides must name\n * the same measure, which is what keeps a length numerator from pairing with a\n * mass one.\n */\nfunction rateAxisFactor(from: string, to: string): number | null {\n if (from === to) return 1;\n if (from === \"\" || to === \"\") return null;\n const fromMeasure = getMeasure(from);\n const toMeasure = getMeasure(to);\n if (fromMeasure === undefined || toMeasure === undefined || fromMeasure !== toMeasure) {\n return null;\n }\n return convertUnit(1, from, to);\n}\n\n/**\n * Convert `value` from a rate/speed unit `from` to a rate/speed unit `to`,\n * returning the converted magnitude, or `null` when the pair is not\n * rate-convertible (so the caller falls back to its own incompatible-units\n * handling).\n *\n * Handles rate to rate (`10 m/s in km/h`), rate to speed alias\n * (`100 km/h in mph`) and speed alias to rate (`60 mph in km/h`). Plain\n * same-measure pairs (`kph in mph`, `km in miles`) never reach here, they are\n * resolved by {@link convertUnit} first.\n *\n * The rule is the ordinary one for a quotient of quantities: convert the\n * numerator and the denominator each on their own, so `A/B -> C/D` scales by\n * `(A->C) / (B->D)`.\n */\nexport function convertRate(value: number, from: string, to: string): number | null {\n const source = expandUnitToRate(value, from);\n if (source === null) return null;\n\n // The target is either a rate spelling or a single-token speed alias. An\n // alias expands to the base m/s pair, and `targetScale` is what the base-form\n // magnitude is divided by to read out in the alias itself.\n let targetNumerator: string;\n let targetDenominator: string;\n let targetScale: number;\n const slash = to.indexOf(\"/\");\n if (slash >= 0) {\n targetNumerator = to.slice(0, slash);\n targetDenominator = to.slice(slash + 1);\n targetScale = 1;\n } else {\n const ext = EXTENDED_UNITS[to];\n if (ext === undefined || ext.measure !== \"speed\") return null;\n targetNumerator = \"m\";\n targetDenominator = \"s\";\n targetScale = ext.toBase;\n }\n\n const numeratorFactor = rateAxisFactor(source.numerator, targetNumerator);\n if (numeratorFactor === null) return null;\n const denominatorFactor = rateAxisFactor(source.denominator, targetDenominator);\n if (denominatorFactor === null) return null;\n\n return (source.value * numeratorFactor) / denominatorFactor / targetScale;\n}\n"]}
@@ -0,0 +1,2 @@
1
+ function o(i,t,r){return i.toLocaleString(t,{useGrouping:false,maximumFractionDigits:r,minimumFractionDigits:r})}function m(i,t=2,r=false,n="en-US"){return Number.isInteger(i)?r?i.toLocaleString(n,{minimumFractionDigits:0,maximumFractionDigits:0}):o(Math.trunc(i),n,0):r?i.toLocaleString(n,{maximumFractionDigits:t,minimumFractionDigits:t}):o(i,n,t)}export{m as a};//# sourceMappingURL=chunk-XEIDV5JP.js.map
2
+ //# sourceMappingURL=chunk-XEIDV5JP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utilities/Number.ts"],"names":["removeThousandsSeparators","value","locale","decimalPlaces","autoFormatIntegerOrFloat","number","includeThousandSeparators","numberLocale"],"mappings":"AAoBA,SAASA,CAAAA,CACRC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACC,CACD,OAAOF,CAAAA,CAAM,cAAA,CAAeC,CAAAA,CAAQ,CACnC,WAAA,CAAa,KAAA,CACb,qBAAA,CAAuBC,EACvB,qBAAA,CAAuBA,CACxB,CAAC,CACF,CAcO,SAASC,CAAAA,CACfC,CAAAA,CACAF,EAAwB,CAAA,CACxBG,CAAAA,CAAqC,KAAA,CACrCC,CAAAA,CAAuB,OAAA,CACtB,CACD,OAAI,MAAA,CAAO,UAAUF,CAAM,CAAA,CACtBC,CAAAA,CAEID,CAAAA,CAAO,cAAA,CAAeE,CAAAA,CAAc,CAC1C,qBAAA,CAAuB,EACvB,qBAAA,CAAuB,CACxB,CAAC,CAAA,CAGKP,CAAAA,CAA0B,IAAA,CAAK,KAAA,CAAMK,CAAM,EAAGE,CAAAA,CAAc,CAAC,CAAA,CAIjED,CAAAA,CAEID,CAAAA,CAAO,cAAA,CAAeE,CAAAA,CAAc,CAC1C,sBAAuBJ,CAAAA,CACvB,qBAAA,CAAuBA,CACxB,CAAC,CAAA,CAKKH,CAAAA,CAA0BK,CAAAA,CAAQE,CAAAA,CAAcJ,CAAa,CACrE","file":"chunk-XEIDV5JP.js","sourcesContent":["/**\n * Render `value` in `locale` with `decimalPlaces` fractional digits and no\n * digit grouping, leaving the locale's own decimal separator alone.\n *\n * Asks `Intl` not to group in the first place rather than formatting with\n * grouping and then deleting a character afterwards. Deleting was wrong twice\n * over. It used `String.replace` with a string pattern, which removes one\n * occurrence, so \"1,234,567\" came back as \"1234,567\" and the surviving comma\n * read as a decimal point. And it chose the character to delete from a\n * two-case switch, \"de-DE\" or a comma for everything else, when a comma is the\n * DECIMAL separator in French, Spanish, Italian, Portuguese and every other\n * comma-decimal locale: deleting it turned 1.5 into \"150\", a hundred times the\n * number, while leaving French's actual group separator (a narrow no-break\n * space) in place. `numberResult.decimalSeparatorLocale` is an unvalidated\n * host string, so no locale can be assumed.\n *\n * An unusable locale tag still throws the `RangeError` `toLocaleString` has\n * always thrown for one, since swallowing it would hide the host's typo behind\n * silently different output.\n */\nfunction removeThousandsSeparators(\n\tvalue: number,\n\tlocale: string,\n\tdecimalPlaces: number\n) {\n\treturn value.toLocaleString(locale, {\n\t\tuseGrouping: false,\n\t\tmaximumFractionDigits: decimalPlaces,\n\t\tminimumFractionDigits: decimalPlaces,\n\t});\n}\n\n/**\n * Format `number` for display, branching on whether it's a whole number:\n * integers are always rendered with zero decimal places (never padded to\n * `decimalPlaces`), while non-integers are rendered with up to\n * `decimalPlaces` fractional digits. `includeThousandSeparators` controls\n * whether groups are separated (e.g. `\"1,234\"`) per `numberLocale`.\n *\n * @param number - The value to format.\n * @param decimalPlaces - Max fractional digits for non-integer values (default 2).\n * @param includeThousandSeparators - Whether to group digits (default false).\n * @param numberLocale - `Intl`/`toLocaleString` locale to format with (default \"en-US\").\n */\nexport function autoFormatIntegerOrFloat(\n\tnumber: number,\n\tdecimalPlaces: number = 2,\n\tincludeThousandSeparators: boolean = false,\n\tnumberLocale: string = \"en-US\"\n) {\n\tif (Number.isInteger(number)) {\n\t\tif (includeThousandSeparators) {\n\t\t\t// We can return the format early as we don't need to strip thousands\n\t\t\treturn number.toLocaleString(numberLocale, {\n\t\t\t\tminimumFractionDigits: 0,\n\t\t\t\tmaximumFractionDigits: 0,\n\t\t\t});\n\t\t}\n\n\t\treturn removeThousandsSeparators(Math.trunc(number), numberLocale, 0);\n\t}\n\n\t// Decimal\n\tif (includeThousandSeparators) {\n\t\t// We can return the format early as we don't need to strip thousands\n\t\treturn number.toLocaleString(numberLocale, {\n\t\t\tmaximumFractionDigits: decimalPlaces,\n\t\t\tminimumFractionDigits: decimalPlaces,\n\t\t});\n\t}\n\n\t// number.toFixed(decimalPlaces)\n\n\treturn removeThousandsSeparators(number, numberLocale, decimalPlaces);\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import {c as c$2}from'./chunk-TWC7K3ZX.js';import {b,a as a$1,e,d}from'./chunk-YVKHEAFT.js';import {c,a}from'./chunk-IJMNVBIS.js';import {a as a$2}from'./chunk-62LMTO4F.js';import {c as c$1}from'./chunk-MPB7KUN5.js';var D=/^\d{1,3}(\.\d{3}){2,}$/,T=/^\d*\.\d*$/,n=class n{constructor(e,t=50,r="en",o){this.tokens=[];this.current=0;this.depth=0;this.currentExpression="";this.infixMinBindingPower=0;this.registry=e,this.maxDepth=t,this.localeCode=r,this.pluginFunctionIndex=o;}getLocaleCode(){return this.localeCode}setDiagnosticPipeline(e,t){this.diagnosticPipeline=e,this.currentExpression=t??"";}load(e,t){if(t===false){this.tokens=e,this.current=0,this.depth=0;return}let r=c(a.LPAREN),o=c(a.RPAREN),a$1=0;for(let l=0;l<e.length;l++)e[l].typeId===r?a$1++:e[l].typeId===o&&a$1--;this.tokens=a$1===0?e:this.balanceParens(e,a$1),this.current=0,this.depth=0;}balanceParens(e,t){let r=e.slice();if(t>0){let o=c(a.RPAREN);for(let a$1=0;a$1<t;a$1++){let l=e[e.length-1];r.push({type:a.RPAREN,typeId:o,value:")",text:")",offset:l?l.offset+l.text.length:0,lineBreaks:0,line:l?l.line:1,col:l?l.col+l.text.length:1});}}else if(t<0){let o=c(a.LPAREN);for(let a$1=0;a$1<-t;a$1++)r.unshift({type:a.LPAREN,typeId:o,value:"(",text:"(",offset:0,lineBreaks:0,line:1,col:1});}return r}parseExpression(e=0,t){if(t&&(this.builder=t),this.depth++,this.depth>this.maxDepth)throw this.depth--,c$1.parsing("NESTING_DEPTH_EXCEEDED",`Parse nesting depth ${this.depth} exceeds maximum of ${this.maxDepth}`,{maxDepth:this.maxDepth,currentDepth:this.depth});let r=this.consume();if(!r)throw this.depth--,c$1.parsing("UNEXPECTED_END","Unexpected end of expression");this.parsePrefix(r);let o=this.tokens,a=o.length,l=n.BP_TABLE,p=this.registry,d=this.builder,f=this.current;for(;f<a;){let u=o[f];if(!u)break;let c=l[u.typeId];if(c>0){if(c<=e)break;if(this.diagnosticPipeline){let m=p.getInfix(u.typeId);m&&this.fireParseletMatched(m,u,false,c);}this.current=++f;let I=u.typeId;if(I===n.PERCENT_ID)d.emitOpcode(10),d.emitNumber(100),d.emitOpcode(23),d.emitOpcode(74);else if(!(I===n.CARET_ID&&this.tryEmitMatrixCaretOp(d))){let m=I===n.CARET_ID?c-1:c+1;this.parseExpression(m,d),d.emitOpcode(n.INFIX_OPCODE[I]);}}else {let I=p.getInfix(u.typeId);if(!I||I.bindingPower<=e)break;this.current=++f,this.diagnosticPipeline&&this.fireParseletMatched(I,u,false,I.bindingPower),this.infixMinBindingPower=e,I.parse(this,r,u,d);}f=this.current;}this.current=f,this.depth--;}parsePrefix(e$1){let t=this.builder,r=e$1.typeId;if(this.diagnosticPipeline){let a=this.registry.getPrefix(r);a&&this.fireParseletMatched(a,e$1,true);}switch(r){case n.NUMBER_ID:{let a,l=null,p=e$1.value;if(p.startsWith("0x")||p.startsWith("0X")){if(a=parseInt(p,16),Number.isNaN(a))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid hex literal: "${p}"`,{raw:p})}else if(p.startsWith("0b")||p.startsWith("0B")){if(a=parseInt(p.slice(2),2),Number.isNaN(a))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid binary literal: "${p}"`,{raw:p})}else if(p.startsWith("0o")||p.startsWith("0O")){if(a=parseInt(p.slice(2),8),Number.isNaN(a))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid octal literal: "${p}"`,{raw:p})}else if(D.test(p))a=parseFloat(p.split(".").join(""));else {let d=a$2(this.localeCode),f=d.display.decimalSeparator,u=d.display.thousandsSeparator,c=p;u&&(c=c.split(u).join("")),f&&f!=="."&&(c=c.replace(f,".")),a=parseFloat(c),T.test(c)&&(l=c);}if(l!==null){t.emitOpcode(16),t.emitString(l);return}t.emitOpcode(10),t.emitNumber(a);return}case n.BIGINT_ID:{t.emitOpcode(11),t.emitString(e(e$1.value,this.localeCode));return}case n.STRING_ID:{t.emitOpcode(13),t.emitString(e$1.value);return}case n.IDENT_ID:{if(this.peek()?.typeId===n.LPAREN_ID){this.parseUserFunctionDefOrCall(e$1,t);return}t.emitOpcode(60),t.emitString(e$1.value);return}case n.LPAREN_ID:{this.parseExpression(0,t);let a$1=1;for(;this.match(a.COMMA);)this.parseExpression(0,t),a$1++;this.consume(a.RPAREN),a$1>1&&(t.emitOpcode(152),t.emitIndex(1),t.emitIndex(a$1));return}case n.MINUS_ID:{this.parseExpression(a$1.Prefix,t),t.emitOpcode(26);return}case n.PLUS_ID:{this.parseExpression(a$1.Prefix,t),t.emitOpcode(27);return}case n.KEYWORD_ID:}let o=this.registry.getPrefix(r);if(!o)throw c$1.parsing("NO_PREFIX_PARSELET",`No prefix parselet found for token: ${e$1.type} ("${e$1.value}")`,{tokenType:e$1.type,tokenValue:e$1.value});o.parse(this,e$1,t);}tryEmitMatrixCaretOp(e){for(let t of n.CARET_SUFFIX_RULES)if(t.matches(this))return t.emit(this,e),true;return false}findMatchingRParen(e){let t=0;for(let r=e;r<this.tokens.length;r++){let o=this.tokens[r];if(o.typeId===n.LPAREN_ID)t++;else if(o.typeId===n.RPAREN_ID&&(t--,t===0))return r}return null}parseUserFunctionDefOrCall(e,t){let r=this.findMatchingRParen(this.current);if(r===null){t.emitOpcode(60),t.emitString(e.value);return}this.tokens[r+1]?.type===a.EQUALS?this.parseUserFunctionDefinition(e,t):this.parseUserFunctionCall(e,t);}consumeParamName(){let e=this.peek();if(e?.type===a.IDENT||e?.type===a.UNIT)return this.consume(),e.value;throw c$1.parsing("USER_FUNCTION_INVALID_PARAM_NAME",`Expected a parameter name but got "${e?.type??"end of input"}"${e?` ("${e.value}")`:""}`,{actualType:e?.type})}parseUserFunctionDefinition(e,t){this.consume(a.LPAREN);let r=[];if(this.peek()?.type!==a.RPAREN)for(r.push(this.consumeParamName());this.match(a.COMMA);)r.push(this.consumeParamName());if(this.consume(a.RPAREN),this.consume(a.EQUALS),r.length===0)throw c$1.parsing("USER_FUNCTION_NO_PARAMS",`"${e.value}()" has no parameters -- user-defined functions need at least one (a zero-argument definition is indistinguishable from a plain function CALL with no args, which this grammar doesn't otherwise support)`,{name:e.value});let o=new d(this.pluginFunctionIndex);this.parseExpression(a$1.Lowest,o),this.setBuilder(t);let a$2=o.build();if(a$2.hasAsync)throw c$1.parsing("FUNCTION_BODY_MUST_BE_SYNCHRONOUS",`"${e.value}(...)"'s body calls an async operation (weather, stocks, currency, ...) \u2014 user-defined function bodies must be synchronous`,{name:e.value});let l=t.emitUserFunctionBody(e.value,r,a$2);t.emitOpcode(150),t.emitIndex(l),t.emitOpcode(13),t.emitString(`${e.value}(${r.join(", ")}) defined`);}parseUserFunctionCall(e,t){this.consume(a.LPAREN);let r=0;if(this.peek()?.type!==a.RPAREN)for(this.parseExpression(a$1.Lowest,t),r++;this.match(a.COMMA);)this.parseExpression(a$1.Lowest,t),r++;this.consume(a.RPAREN),t.emitOpcode(151),t.emitString(e.value),t.emitByte(r);}consume(e){let t=this.tokens[this.current];if(!t)throw c$1.parsing("UNEXPECTED_END_OF_INPUT","Unexpected end of input");if(e!==void 0){let r=c(e);if(t.typeId!==r)throw c$1.parsing("UNEXPECTED_TOKEN_TYPE",`Expected token type "${e}" but got "${t.type}" ("${t.value}")`,{expectedType:e,actualType:t.type,actualValue:t.value})}return this.current++,t}match(e){let t=this.peek();return t&&t.typeId===c(e)?(this.advance(),true):false}peek(){return this.tokens[this.current]}peekAt(e){return this.tokens[this.current+e]}previous(){return this.current>0?this.tokens[this.current-1]:void 0}advance(){this.current++;}setBuilder(e){this.builder=e;}fireParseletMatched(e,t,r,o){let a=this.diagnosticPipeline,l={type:c$2.ParseletMatched,elapsedNs:0,expression:this.currentExpression,tokenType:t.type,tokenValue:t.value,parseletCategory:e.category,parseletType:e.constructor?.name??"unknown",isPrefix:r,bindingPower:o,tokenOffset:t.offset||0};a.fireParseletMatched(l);}};n.BP_TABLE=b(),n.NUMBER_ID=c(a.NUMBER),n.BIGINT_ID=c(a.BIGINT),n.STRING_ID=c(a.STRING),n.IDENT_ID=c(a.IDENT),n.LPAREN_ID=c(a.LPAREN),n.RPAREN_ID=c(a.RPAREN),n.MINUS_ID=c(a.MINUS),n.PLUS_ID=c(a.PLUS),n.KEYWORD_ID=c(a.KEYWORD),n.STAR_ID=c(a.STAR),n.SLASH_ID=c(a.SLASH),n.MOD_ID=c(a.MOD),n.CARET_ID=c(a.CARET),n.LSHIFT_ID=c(a.LSHIFT),n.RSHIFT_ID=c(a.RSHIFT),n.URSHIFT_ID=c(a.URSHIFT),n.BIT_AND_ID=c(a.BIT_AND),n.BIT_OR_ID=c(a.BIT_OR),n.BIT_XOR_ID=c(a.BIT_XOR),n.PERCENT_ID=c(a.PERCENT),n.OF_ID=c(a.OF),n.INFIX_OPCODE={[c(a.PLUS)]:20,[c(a.MINUS)]:21,[c(a.STAR)]:22,[c(a.SLASH)]:23,[c(a.MOD)]:24,[c(a.CARET)]:25,[c(a.LSHIFT)]:30,[c(a.RSHIFT)]:31,[c(a.URSHIFT)]:32,[c(a.BIT_AND)]:33,[c(a.BIT_OR)]:34,[c(a.BIT_XOR)]:35,[c(a.OF)]:22},n.CARET_SUFFIX_RULES=[{name:"transpose (^T)",matches:e=>{let t=e.peek();return t?.type===a.IDENT&&t.value==="T"},emit:(e,t)=>{e.advance(),t.emitOpcode(51),t.emitIndex(63),t.emitIndex(1);}},{name:"inverse (^-1)",matches:e=>{if(e.peek()?.typeId!==n.MINUS_ID)return false;let r=e.peekAt(1);return r?.type===a.NUMBER&&r.value==="1"},emit:(e,t)=>{e.advance(),e.advance(),t.emitOpcode(51),t.emitIndex(65),t.emitIndex(1);}}];var v=n;var y=class{constructor(){this.prefixParselets=new Map;this.infixParselets=new Map;this.prefixById=new Map;this.infixById=new Map;}registerPrefix(e,t){let r=this.prefixParselets.get(e);r&&r!==t&&console.warn(`[ParseletRegistry] Prefix parselet for token "${e}" is already registered (category: "${r.category??"unknown"}"). Overwriting with a new parselet (category: "${t.category??"unknown"}") \u2014 the previous parselet is now unreachable. Two packages may be claiming the same token type.`),this.prefixParselets.set(e,t),this.prefixById.set(c(e),t);}registerInfix(e,t){let r=this.infixParselets.get(e);r&&r!==t&&console.warn(`[ParseletRegistry] Infix parselet for token "${e}" is already registered (category: "${r.category??"unknown"}"). Overwriting with a new parselet (category: "${t.category??"unknown"}") \u2014 the previous parselet is now unreachable. Two packages may be claiming the same token type.`),this.infixParselets.set(e,t),this.infixById.set(c(e),t);}getAllPrefix(){let e=[];for(let[t,r]of this.prefixParselets)e.push({tokenType:t,bindingPower:r.bindingPower??a$1.Prefix,category:r.category});return e}getAllInfix(){let e=[];for(let[t,r]of this.infixParselets){let o=r.bindingPower??0;e.push({tokenType:t,leftBindingPower:o,rightBindingPower:o+1,category:r.category});}return e}get prefixCount(){return this.prefixParselets.size}get infixCount(){return this.infixParselets.size}getPrefix(e){return typeof e=="number"?this.prefixById.get(e):this.prefixParselets.get(e)}getInfix(e){return typeof e=="number"?this.infixById.get(e):this.infixParselets.get(e)}hasPrefix(e){return this.prefixParselets.has(e)}hasInfix(e){return this.infixParselets.has(e)}clear(){this.prefixParselets.clear(),this.infixParselets.clear(),this.prefixById.clear(),this.infixById.clear();}},H=new y;export{v as a,y as b,H as c};//# sourceMappingURL=chunk-XNIWQHXY.js.map
2
+ //# sourceMappingURL=chunk-XNIWQHXY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/parser/PrecedenceParser.ts","../src/parser/registry/ParseletRegistry.ts"],"names":["CHAINED_DOT_THOUSANDS_GROUPS","PLAIN_DECIMAL","_PrecedenceParser","parseletRegistry","maxDepth","localeCode","pluginFunctionIndex","pipeline","expression","tokens","hasParens","LPAREN_ID","tokenTypeId","TokenTypes","RPAREN_ID","openCount","i","result","lastToken","minBp","_builder","ErrorFactory","token","len","bpTable","registry","builder","idx","lookahead","bp","infixParselet","typeId","rightBp","parselet","v","decimalText","raw","locale","getLocale","decimalSep","thousandsSep","normalized","bigIntLiteralDigits","count","BindingPower","prefixParselet","rule","openIdx","depth","t","nameToken","closeIdx","params","bodyBuilder","BytecodeBuilder","bodyProgram","bodyIdx","argCount","expectedType","expectedId","offset","isPrefix","bindingPower","event","DiagnosticEventType","buildBindingPowerTable","p","next","afterMinus","PrecedenceParser","ParseletRegistry","tokenType","existing","left","sharedParseletRegistry"],"mappings":"wNAmBA,IAAMA,CAAAA,CAA+B,wBAAA,CAU/BC,CAAAA,CAAgB,YAAA,CAqBTC,CAAAA,CAAN,MAAMA,CAAiB,CAkF5B,WAAA,CAAYC,CAAAA,CAAoCC,CAAAA,CAAW,EAAA,CAAIC,CAAAA,CAAa,KAAMC,CAAAA,CAAmD,CAjFrI,IAAA,CAAQ,MAAA,CAAkB,EAAC,CAC3B,I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CACzC,CAEA,KAAA,EAAc,CACb,IAAA,CAAK,eAAA,CAAgB,KAAA,EAAM,CAC3B,IAAA,CAAK,cAAA,CAAe,KAAA,EAAM,CAC1B,IAAA,CAAK,UAAA,CAAW,KAAA,EAAM,CACtB,IAAA,CAAK,SAAA,CAAU,KAAA,GAChB,CACD,CAAA,CAUaG,CAAAA,CAAyB,IAAIJ","file":"chunk-XNIWQHXY.js","sourcesContent":["import { ParseletRegistry } from \"@solve-js/parser/registry/ParseletRegistry\";\nimport { Token, tokenTypeId, TokenTypes } from \"@solve-js/lexer/Token\";\nimport { BytecodeBuilder } from \"@solve-js/parser/BytecodeBuilder\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { DiagnosticPipeline, DiagnosticEventType, type DiagnosticEvent } from \"@solve-js/diagnostics\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { BindingPower, buildBindingPowerTable } from \"@solve-js/parser/BindingPower\";\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { bigIntLiteralDigits } from \"@solve-js/parser/BigIntLiteral\";\n\n/**\n * Matches a CHAINED thousands-grouped integer using \".\" as the group\n * separator (e.g. \"1.234.567\"), independent of locale. Kept in sync with\n * the identical constant in NumberParselet.ts (not imported from there\n * that file transitively re-imports PrecedenceParser via Parser.ts's\n * `export { PrecedenceParser as Parser }`, so importing the other\n * direction would create a circular dependency for the sake of one\n * regex literal). See NumberParselet.ts's copy for the full explanation.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/**\n * A plain fractional literal: digits, exactly one dot, digits, nothing else.\n *\n * The gate for compiling to PUSH_DECIMAL. It admits \"0.10\", \"1.005\", \".5\" and\n * \"5.\" and refuses anything with an exponent (\"2.5e-3\"), which parses as an\n * ordinary double instead, since scientific notation has no exact base-ten\n * value this representation would keep.\n */\nconst PLAIN_DECIMAL = /^\\d*\\.\\d*$/;\n\n/**\n * ── Hybrid Precedence Climbing Parser ─────────────────────────────────────────\n *\n * Two-tier dispatch strategy:\n *\n * Tier 1 (Fast Path): Inline switch on token.typeId for built-in operators.\n * - Prefix: NUMBER, IDENT, LPAREN, MINUS, PLUS, STRING\n * - Infix: checked via static BP_TABLE (Uint8Array indexed by typeId)\n * - No Map.get(), no parselet function call overhead for ~95% of tokens\n *\n * Tier 2 (Plugin Path): ParseletRegistry fallback for custom/plugin tokens.\n * - Prefix: Map.get(tokenTypeId) for PrefixParselet\n * - Infix: Map.get(tokenTypeId) for InfixParselet\n * - Full flexibility for custom syntax\n *\n * The parser emits directly to a BytecodeBuilder, no AST intermediate.\n * Implements the same public API as the legacy Parser class so existing\n * parselets continue to work without modification.\n */\nexport class PrecedenceParser {\n private tokens: Token[] = [];\n private current = 0;\n private depth = 0;\n private maxDepth: number;\n\n /** Cached registry reference, avoids property chain in hot loop */\n private registry: ParseletRegistry;\n\n /** BytecodeBuilder, set before each parseExpression call */\n private builder!: BytecodeBuilder;\n\n /** Diagnostic pipeline for parselet-matched events */\n private diagnosticPipeline: DiagnosticPipeline | undefined;\n private currentExpression: string = \"\";\n private localeCode: string;\n\n /**\n * The binding power the current infix parselet is being invoked at, i.e. the\n * `minBp` of the expression it sits inside. Set immediately before each Tier-2\n * parselet runs. A parselet that decides whether to swallow a following\n * loose operator (UomLiteralParselet with a trailing `in`/`to`) reads this to\n * respect precedence it cannot otherwise see: `120 km / 2 hours in kph` must\n * group as `(120 km / 2 hours) in kph`, not `120 km / (2 hours in kph)`.\n */\n infixMinBindingPower = 0;\n\n /**\n * Static binding power table, built once at module load, shared across all instances.\n * Index = tokenTypeId, value = binding power (0 = not a built-in infix).\n */\n static readonly BP_TABLE: Uint8Array = buildBindingPowerTable();\n\n // ── Pre-computed token type IDs for inline dispatch ────────────────────────\n // Prefix built-ins\n private static readonly NUMBER_ID = tokenTypeId(TokenTypes.NUMBER);\n private static readonly BIGINT_ID = tokenTypeId(TokenTypes.BIGINT);\n private static readonly STRING_ID = tokenTypeId(TokenTypes.STRING);\n private static readonly IDENT_ID = tokenTypeId(TokenTypes.IDENT);\n private static readonly LPAREN_ID = tokenTypeId(TokenTypes.LPAREN);\n private static readonly RPAREN_ID = tokenTypeId(TokenTypes.RPAREN);\n private static readonly MINUS_ID = tokenTypeId(TokenTypes.MINUS);\n private static readonly PLUS_ID = tokenTypeId(TokenTypes.PLUS);\n private static readonly KEYWORD_ID = tokenTypeId(TokenTypes.KEYWORD);\n\n // Infix built-ins (Tier 1, full inline emission)\n private static readonly STAR_ID = tokenTypeId(TokenTypes.STAR);\n private static readonly SLASH_ID = tokenTypeId(TokenTypes.SLASH);\n private static readonly MOD_ID = tokenTypeId(TokenTypes.MOD);\n private static readonly CARET_ID = tokenTypeId(TokenTypes.CARET);\n private static readonly LSHIFT_ID = tokenTypeId(TokenTypes.LSHIFT);\n private static readonly RSHIFT_ID = tokenTypeId(TokenTypes.RSHIFT);\n private static readonly URSHIFT_ID = tokenTypeId(TokenTypes.URSHIFT);\n private static readonly BIT_AND_ID = tokenTypeId(TokenTypes.BIT_AND);\n private static readonly BIT_OR_ID = tokenTypeId(TokenTypes.BIT_OR);\n private static readonly BIT_XOR_ID = tokenTypeId(TokenTypes.BIT_XOR);\n private static readonly PERCENT_ID = tokenTypeId(TokenTypes.PERCENT);\n private static readonly OF_ID = tokenTypeId(TokenTypes.OF);\n\n /**\n * Inline opcode map for Tier 1 infix operators.\n * tokenTypeId → OpCode. PERCENT and CARET are handled specially (not in this map).\n */\n private static readonly INFIX_OPCODE: Record<number, OpCode> = {\n [tokenTypeId(TokenTypes.PLUS)]: OpCode.ADD,\n [tokenTypeId(TokenTypes.MINUS)]: OpCode.SUB,\n [tokenTypeId(TokenTypes.STAR)]: OpCode.MUL,\n [tokenTypeId(TokenTypes.SLASH)]: OpCode.DIV,\n [tokenTypeId(TokenTypes.MOD)]: OpCode.MOD,\n [tokenTypeId(TokenTypes.CARET)]: OpCode.EXP,\n [tokenTypeId(TokenTypes.LSHIFT)]: OpCode.LSHIFT,\n [tokenTypeId(TokenTypes.RSHIFT)]: OpCode.RSHIFT,\n [tokenTypeId(TokenTypes.URSHIFT)]: OpCode.URSHIFT,\n [tokenTypeId(TokenTypes.BIT_AND)]: OpCode.BIT_AND,\n [tokenTypeId(TokenTypes.BIT_OR)]: OpCode.BIT_OR,\n [tokenTypeId(TokenTypes.BIT_XOR)]: OpCode.BIT_XOR,\n [tokenTypeId(TokenTypes.OF)]: OpCode.MUL,\n };\n\n /** Shared with every BytecodeBuilder so a nested-body builder resolves plugin calls by name. */\n private pluginFunctionIndex?: ReadonlyMap<string, number>;\n\n constructor(parseletRegistry: ParseletRegistry, maxDepth = 50, localeCode = \"en\", pluginFunctionIndex?: ReadonlyMap<string, number>) {\n this.registry = parseletRegistry;\n this.maxDepth = maxDepth;\n this.localeCode = localeCode;\n this.pluginFunctionIndex = pluginFunctionIndex;\n }\n\n /** Get locale code for NumberParselet to normalize separators */\n getLocaleCode(): string {\n return this.localeCode;\n }\n\n /**\n * Set the diagnostic pipeline for parselet matching events.\n * Cleared after each non-cached parse to avoid holding refs.\n */\n setDiagnosticPipeline(pipeline: DiagnosticPipeline | undefined, expression: string): void {\n this.diagnosticPipeline = pipeline;\n this.currentExpression = expression ?? \"\";\n }\n\n /**\n * Load tokens for parsing. Identical to Parser.load().\n *\n * @param hasParens - if false, skips the O(n) paren balance scan (~90% of expressions)\n */\n load(tokens: Token[], hasParens?: boolean): void {\n if (hasParens === false) {\n this.tokens = tokens;\n this.current = 0;\n this.depth = 0;\n return;\n }\n // Paren scan: count balance to skip array copy for balanced expressions.\n const LPAREN_ID = tokenTypeId(TokenTypes.LPAREN);\n const RPAREN_ID = tokenTypeId(TokenTypes.RPAREN);\n let openCount = 0;\n for (let i = 0; i < tokens.length; i++) {\n if (tokens[i].typeId === LPAREN_ID) openCount++;\n else if (tokens[i].typeId === RPAREN_ID) openCount--;\n }\n this.tokens = openCount === 0 ? tokens : this.balanceParens(tokens, openCount);\n this.current = 0;\n this.depth = 0;\n }\n\n /**\n * Auto-balance unmatched parentheses.\n */\n private balanceParens(tokens: Token[], openCount: number): Token[] {\n const result = tokens.slice();\n if (openCount > 0) {\n const RPAREN_ID = tokenTypeId(TokenTypes.RPAREN);\n for (let i = 0; i < openCount; i++) {\n const lastToken = tokens[tokens.length - 1];\n result.push({\n type: TokenTypes.RPAREN,\n typeId: RPAREN_ID,\n value: \")\",\n text: \")\",\n offset: lastToken ? lastToken.offset + lastToken.text.length : 0,\n lineBreaks: 0,\n line: lastToken ? lastToken.line : 1,\n col: lastToken ? lastToken.col + lastToken.text.length : 1,\n } as Token);\n }\n } else if (openCount < 0) {\n const LPAREN_ID = tokenTypeId(TokenTypes.LPAREN);\n for (let i = 0; i < -openCount; i++) {\n result.unshift({\n type: TokenTypes.LPAREN,\n typeId: LPAREN_ID,\n value: \"(\",\n text: \"(\",\n offset: 0,\n lineBreaks: 0,\n line: 1,\n col: 1,\n } as Token);\n }\n }\n return result;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Main entry point: precedence climbing parse expression\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /**\n * Parse a full expression starting at the current token position.\n *\n * @param minBp - minimum binding power (precedence climbing threshold).\n * For left-associative operators, the recursive call uses `bp + 1`.\n * For right-associative operators (^), it uses `bp - 1`.\n * @param _builder - accepted for parselet API compatibility; always uses `this.builder`.\n */\n parseExpression(minBp: number = 0, _builder?: BytecodeBuilder): void {\n // Accept builder via parameter for backward compatibility with the old Parser API.\n // The ExpressionEngine always calls setBuilder() before parseExpression(),\n // but tests and parselets pass builder as a parameter.\n if (_builder) {\n this.builder = _builder;\n }\n this.depth++;\n if (this.depth > this.maxDepth) {\n this.depth--;\n throw ErrorFactory.parsing(\n \"NESTING_DEPTH_EXCEEDED\",\n `Parse nesting depth ${this.depth} exceeds maximum of ${this.maxDepth}`,\n { maxDepth: this.maxDepth, currentDepth: this.depth }\n );\n }\n\n const token = this.consume();\n if (!token) {\n this.depth--;\n throw ErrorFactory.parsing(\"UNEXPECTED_END\", \"Unexpected end of expression\");\n }\n\n // ── Prefix ──────────────────────────────────────────────────────────────\n this.parsePrefix(token);\n\n // ── Infix loop (precedence climbing with inline Tier 1 dispatch) ──────────\n const tokens = this.tokens;\n const len = tokens.length;\n const bpTable = PrecedenceParser.BP_TABLE;\n const registry = this.registry;\n const builder = this.builder;\n let idx = this.current;\n\n while (idx < len) {\n const lookahead = tokens[idx];\n if (!lookahead) break;\n\n const bp = bpTable[lookahead.typeId];\n if (bp > 0) {\n // Tier 1: Built-in infix, full inline emission, zero parselet delegation\n if (bp <= minBp) break;\n\n if (this.diagnosticPipeline) {\n // Fast path skips the registry, but built-ins are still registered\n // there (for introspection/tests), look them up only in this\n // diagnostics-only branch so the playground's \"matched parselets\"\n // view isn't permanently blind to every arithmetic operator.\n const infixParselet = registry.getInfix(lookahead.typeId);\n if (infixParselet) {\n this.fireParseletMatched(infixParselet, lookahead, false, bp);\n }\n }\n\n this.current = ++idx;\n const typeId = lookahead.typeId;\n\n if (typeId === PrecedenceParser.PERCENT_ID) {\n // Postfix: no right operand. \"50%\" → Percentage holding 0.5.\n //\n // Must stay byte-for-byte equivalent to PercentParselet, which is\n // the Tier-2 registration of the same operator. This path is the one\n // that actually runs for ordinary expressions, so a change made only\n // in the parselet does nothing at all: that is exactly how the\n // divide-by-100 here outlived its replacement and kept `200 + 10%`\n // answering 200.10.\n builder.emitOpcode(OpCode.PUSH_NUMBER);\n builder.emitNumber(100);\n builder.emitOpcode(OpCode.DIV);\n builder.emitOpcode(OpCode.TO_PERCENTAGE);\n } else if (typeId === PrecedenceParser.CARET_ID && this.tryEmitMatrixCaretOp(builder)) {\n // `^T` (transpose) or `^-1` (inverse), already fully handled\n // including consuming their own trailing tokens.\n } else {\n // Infix: parse right operand, then emit opcode.\n // Right-associative for CARET (^), left-associative for all others.\n //\n // The threshold has to be bp - 1, not bp. The loop above breaks on\n // `bp <= minBp`, so a right operand parsed at `bp` stops at the next\n // `^` exactly as one parsed at `bp + 1` does: the old special case\n // was dead code and \"2 ^ 3 ^ 2\" grouped left, answering 64. One\n // below lets the recursive call keep consuming `^`, which is what\n // makes it 2^(3^2) = 512, as in mathematics, Python, Ruby and\n // JavaScript's `**`.\n //\n // Nothing else sits between Exponent (50) and Product (40), so\n // 49 cannot collide with another operator's level. Unary minus is\n // unaffected: it parses its operand at Prefix (60), above `^`\n // either way, so \"-2 ^ 2\" is still (-2)^2 = 4.\n const rightBp = (typeId === PrecedenceParser.CARET_ID) ? bp - 1 : bp + 1;\n this.parseExpression(rightBp, builder);\n builder.emitOpcode(PrecedenceParser.INFIX_OPCODE[typeId]);\n }\n } else {\n // Tier 2: Plugin parselet fallback, full flexibility for custom syntax\n const infixParselet = registry.getInfix(lookahead.typeId);\n if (!infixParselet) break;\n if (infixParselet.bindingPower <= minBp) break;\n\n this.current = ++idx;\n\n if (this.diagnosticPipeline) {\n this.fireParseletMatched(infixParselet, lookahead, false, infixParselet.bindingPower);\n }\n // Expose the level this parselet is bound at, so one that peeks past its\n // own token (a unit literal weighing whether a trailing `in`/`to` is\n // its own or an outer operator's) can respect precedence. See\n // infixMinBindingPower's doc comment.\n this.infixMinBindingPower = minBp;\n // Parselet handles its own recursion for right operand internally\n infixParselet.parse(this, token, lookahead, builder);\n }\n\n idx = this.current;\n }\n\n this.current = idx;\n this.depth--;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Prefix dispatch: inline switch for built-ins, parselet registry for plugins\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /**\n * Parse a prefix token. Built-in tokens (NUMBER, IDENT, LPAREN, etc.) are\n * handled inline with zero registry lookup. Everything else falls through\n * to the parselet registry (Tier 2).\n */\n private parsePrefix(token: Token): void {\n const builder = this.builder;\n const typeId = token.typeId;\n\n if (this.diagnosticPipeline) {\n // Fast path below skips the registry for built-ins, but they're still\n // registered there (for introspection/tests), look up here so the\n // playground's \"matched parselets\" view isn't permanently blind to\n // every number, identifier, paren, and unary operator.\n const parselet = this.registry.getPrefix(typeId);\n if (parselet) {\n this.fireParseletMatched(parselet, token, true);\n }\n }\n\n switch (typeId) {\n // ── Numeric literals ──────────────────────────────────────────────────\n case PrecedenceParser.NUMBER_ID: {\n // Parse number with locale-aware separator normalization\n let v: number;\n // The exact dot-decimal text for a literal written with a fractional\n // point, so it can be pushed as PUSH_DECIMAL and keep its precision\n // where it later meets money. Stays null for every integer shape\n // (hex/bin/oct, chained-dot grouping, plain integers), which push the\n // ordinary PUSH_NUMBER and are unchanged.\n let decimalText: string | null = null;\n const raw = token.value;\n if (raw.startsWith(\"0x\") || raw.startsWith(\"0X\")) {\n v = parseInt(raw, 16);\n // A prefix with no digits after it (\"0x\" alone) makes parseInt\n // return NaN. This used to push straight through as a silent\n // NaN Number value instead of a visible error.\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid hex literal: \"${raw}\"`, { raw });\n }\n } else if (raw.startsWith(\"0b\") || raw.startsWith(\"0B\")) {\n v = parseInt(raw.slice(2), 2);\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid binary literal: \"${raw}\"`, { raw });\n }\n } else if (raw.startsWith(\"0o\") || raw.startsWith(\"0O\")) {\n v = parseInt(raw.slice(2), 8);\n if (Number.isNaN(v)) {\n throw ErrorFactory.parsing(\"INVALID_NUMBER_LITERAL\", `Invalid octal literal: \"${raw}\"`, { raw });\n }\n } else if (CHAINED_DOT_THOUSANDS_GROUPS.test(raw)) {\n // The lexer accepts \".\" as a thousands-group separator\n // independent of locale (ExpressionLexer's number-scanning\n // \"Thousands separators\" block), but the locale-based\n // normalization below only strips the ACTIVE locale's own\n // configured thousandsSeparator character, for \"en\" that's\n // \",\", not \".\", so a chained dot-grouped literal like\n // \"1.234.567\" fell through to parseFloat() untouched, which\n // stops at the second \".\" and silently truncated it to 1.234\n // (over 99% of the digits dropped, with no error). This is the\n // REAL number-parsing path for actual evaluation, Tier 1 of\n // the two-tier dispatch above always returns for NUMBER_ID, so\n // NumberParselet.parse() (which has the identical fix) never\n // actually runs except via direct unit tests / the \"matched\n // parselets\" diagnostic display.\n v = parseFloat(raw.split(\".\").join(\"\"));\n } else {\n const locale = getLocale(this.localeCode);\n const decimalSep = locale.display.decimalSeparator;\n const thousandsSep = locale.display.thousandsSeparator;\n let normalized = raw;\n // Replace thousands separator with empty string (split+join avoids per-call RegExp compilation)\n if (thousandsSep) {\n normalized = normalized.split(thousandsSep).join(\"\");\n }\n // Replace locale decimal separator with \".\" for JavaScript parsing\n if (decimalSep && decimalSep !== \".\") {\n normalized = normalized.replace(decimalSep, \".\");\n }\n v = parseFloat(normalized);\n // A plain fractional literal (digits, one dot, digits) is what carries\n // an exact decimal. Scientific notation like \"2.5e-3\" has a dot too\n // but no exact base-ten form worth the trouble, so it stays a\n // PUSH_NUMBER double, and so does any integer (grouping stripped).\n if (PLAIN_DECIMAL.test(normalized)) decimalText = normalized;\n }\n if (decimalText !== null) {\n builder.emitOpcode(OpCode.PUSH_DECIMAL);\n builder.emitString(decimalText);\n return;\n }\n builder.emitOpcode(OpCode.PUSH_NUMBER);\n builder.emitNumber(v);\n return;\n }\n\n case PrecedenceParser.BIGINT_ID: {\n // Strips the `n` and any thousands grouping the lexer coalesced in.\n // This used to be `raw.slice(0, -1)` and nothing else, so `1.000n`\n // reached BigInt(\"1.000\") and threw a raw SyntaxError. See\n // parser/BigIntLiteral.ts, which the parselet tier shares.\n builder.emitOpcode(OpCode.PUSH_BIGINT);\n builder.emitString(bigIntLiteralDigits(token.value, this.localeCode));\n return;\n }\n\n case PrecedenceParser.STRING_ID: {\n builder.emitOpcode(OpCode.PUSH_STRING);\n builder.emitString(token.value);\n return;\n }\n\n // ── Identifiers (variables) ────────────────────────────────────────────\n case PrecedenceParser.IDENT_ID: {\n // An identifier immediately followed by \"(\" may be a user-defined\n // function DEFINITION (`f(x) = ...`) or CALL (`f(5)`). See\n // parseUserFunctionDefOrCall's doc comment for the full\n // disambiguation. Only the (cheap) LPAREN check runs for the\n // overwhelmingly common case of a bare identifier with nothing\n // following it.\n if (this.peek()?.typeId === PrecedenceParser.LPAREN_ID) {\n this.parseUserFunctionDefOrCall(token, builder);\n return;\n }\n // IDENT tokens map to LOAD_VAR by default. The IdentifierParselet\n // and VariableParselet add STORE_VAR for assignments, those are\n // handled via the parselet registry below. Note this is also how a\n // user-defined function's own PARAMETER references compile. See\n // UserFunctionDef's doc comment in BytecodeBuilder.ts for why there\n // is no separate parameter-load opcode: `LOAD_VAR` resolution\n // dynamically checks the VM's innermost call frame first.\n builder.emitOpcode(OpCode.LOAD_VAR);\n builder.emitString(token.value);\n return;\n }\n\n // ── Grouping / bare-tuple vector literal ─────────────────────────────────\n // `(expr)` groups for precedence; `(x, y[, z[, w]])` is the bare-tuple\n // vector literal documented as an alternative to vec2/vec3/vec4(...)\n // (wiki: Arithmetic/Vector). This Tier-1 case is what actually runs for\n // every LPAREN in production parsing, GroupParselet.ts mirrors this\n // logic for registry-introspection/diagnostic-listing purposes, but a\n // package can never override LPAREN's dispatch here (Tier 1 always\n // wins over the ParseletRegistry fallback below), so both must be kept\n // in sync by hand.\n case PrecedenceParser.LPAREN_ID: {\n this.parseExpression(0, builder);\n let count = 1;\n while (this.match(TokenTypes.COMMA)) {\n this.parseExpression(0, builder);\n count++;\n }\n this.consume(TokenTypes.RPAREN);\n if (count > 1) {\n // Legacy bare-tuple vector sugar, a 1xN row-vector Matrix (see\n // packages/vector/parselets/VectorParselet.ts's comment).\n builder.emitOpcode(OpCode.MAT_NEW);\n builder.emitIndex(1);\n builder.emitIndex(count);\n }\n return;\n }\n\n // ── Unary operators ───────────────────────────────────────────────────\n case PrecedenceParser.MINUS_ID: {\n this.parseExpression(BindingPower.Prefix, builder);\n builder.emitOpcode(OpCode.NEG);\n return;\n }\n\n case PrecedenceParser.PLUS_ID: {\n this.parseExpression(BindingPower.Prefix, builder);\n builder.emitOpcode(OpCode.POS);\n return;\n }\n\n // ── Keyword constants ─────────────────────────────────────────────────\n case PrecedenceParser.KEYWORD_ID: {\n // Keywords are handled by parselets (pi→PI, e→E, etc.)\n // Fall through to registry below.\n }\n }\n\n // ── Tier 2: Plugin/parselet prefix path ──────────────────────────────────\n const prefixParselet = this.registry.getPrefix(typeId);\n if (!prefixParselet) {\n throw ErrorFactory.parsing(\n \"NO_PREFIX_PARSELET\",\n `No prefix parselet found for token: ${token.type} (\"${token.value}\")`,\n { tokenType: token.type, tokenValue: token.value }\n );\n }\n\n prefixParselet.parse(this, token, builder);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // The \"Tier-1 shape-exception\" pattern\n // ═══════════════════════════════════════════════════════════════════════════════\n //\n // Tier 1 exists purely for performance, avoid a Map lookup + parselet call\n // on ~95% of tokens (see this file's own module doc comment above). A\n // recurring consequence: any grammar shape tied to a Tier-1 token type can\n // ONLY be implemented by hand-editing this switch, since a package-\n // registered ParseletRegistry parselet for that same token type would\n // simply never run in production (Tier 1 always wins over the registry\n // fallback). Five confirmed instances of this tension exist in this file\n // (plus one that had to move OUTSIDE it entirely):\n // 1. NUMBER_ID, the full locale-aware number-literal parsing (hex/\n // binary/octal, chained-dot thousands grouping, decimal-separator\n // normalization) is inlined in parsePrefix() above; NumberParselet.ts's\n // own copy is dead code for real evaluation, kept registered only for\n // the \"matched parselets\" diagnostic view.\n // 2. IDENT_ID, parseUserFunctionDefOrCall's lookahead (below) disambig-\n // uates a function DEFINITION from a CALL from a plain variable load.\n // 3. LPAREN_ID, the bare-tuple vector-literal sugar (\"(x,y[,z[,w]])\" ->\n // MAT_NEW) is inlined in parsePrefix() above; GroupParselet.ts mirrors\n // it for introspection only and must be kept in sync by hand.\n // 4. CARET_ID, the transpose/inverse suffix table just below.\n // 5. PLUS_ID, the locale word \"and\" lexes as PLUS (Tier-1, fixed Sum\n // binding power), so a registry parselet can never intercept it the\n // way LogicalParselet.ts intercepts \"or\"/&&/||; unlike the other four,\n // there's no SHAPE to special-case on here (the token itself IS the\n // operator), so the workaround lives entirely outside this file, as a\n // runtime Boolean/Boolean type-check inside vm/VM.ts's OpCode.ADD\n // handler instead.\n //\n // Deliberate non-goal: none of this is exposed as an IEnginePackage\n // extension point (unlike prefixParselets/infixParselets). Letting\n // third-party packages register their own Tier-1 shape-matchers would put\n // per-package matcher iteration on a genuinely hot path (every CARET/\n // NUMBER/IDENT/LPAREN/PLUS token, matched or not), a materially bigger\n // separate product decision than \"make this one table more concise,\" and\n // not one this pattern write-up makes.\n\n /**\n * A single `^`-suffix shape: `matches` peeks ahead (consuming nothing) to\n * check whether this shape starts at the current position; `emit` is only\n * called immediately after `matches` returned true for that SAME position,\n * and is responsible for consuming that shape's own trailing tokens and\n * emitting its bytecode.\n */\n private static readonly CARET_SUFFIX_RULES: ReadonlyArray<{\n name: string;\n matches(parser: PrecedenceParser): boolean;\n emit(parser: PrecedenceParser, builder: BytecodeBuilder): void;\n }> = [\n {\n name: \"transpose (^T)\",\n matches: (p) => {\n const next = p.peek();\n return next?.type === TokenTypes.IDENT && next.value === \"T\";\n },\n emit: (p, builder) => {\n p.advance();\n builder.emitOpcode(OpCode.CALL_BUILTIN);\n builder.emitIndex(63); // transpose — see VMBuiltins.ts\n builder.emitIndex(1);\n },\n },\n {\n name: \"inverse (^-1)\",\n matches: (p) => {\n const next = p.peek();\n if (next?.typeId !== PrecedenceParser.MINUS_ID) return false;\n const afterMinus = p.peekAt(1);\n return afterMinus?.type === TokenTypes.NUMBER && afterMinus.value === \"1\";\n },\n emit: (p, builder) => {\n p.advance();\n p.advance();\n builder.emitOpcode(OpCode.CALL_BUILTIN);\n builder.emitIndex(65); // inv — see VMBuiltins.ts\n builder.emitIndex(1);\n },\n },\n ];\n\n /**\n * After a `^` token (already consumed by the Tier-1 infix loop above),\n * checks {@link CARET_SUFFIX_RULES} in order for a shape that means\n * something other than ordinary exponentiation: `^T` (transpose) and `^-1`\n * (matrix inverse, LITERALLY the integer exponent `-1`; `^-2`, `^-1.5`\n * etc. still mean ordinary exponentiation). On a match, the rule's `emit`\n * consumes that shape's own tokens and this returns `true`. On no match,\n * consumes NOTHING, returning `false` so the caller falls through to\n * ordinary `EXP` parsing.\n *\n * Every rule dispatches purely on SHAPE, never on operand type (unknowable\n * at parse time): `inv()`'s own handler (`VMBuiltins.ts` index 65) returns\n * `1/x` for a plain Number, byte-identical to what `Math.pow(x, -1)`\n * already computed for `x^-1` before this feature existed, and a real\n * matrix inverse for a Matrix, so `5^-1` still means exactly what it always\n * has; only a Matrix operand actually inverts.\n *\n * Adding a future `^`-suffix shape is a new table entry here, not a new\n * if-block. See the \"Tier-1 shape-exception\" pattern write-up above for\n * why this table can't instead be a package-registered parselet.\n */\n private tryEmitMatrixCaretOp(builder: BytecodeBuilder): boolean {\n for (const rule of PrecedenceParser.CARET_SUFFIX_RULES) {\n if (rule.matches(this)) {\n rule.emit(this, builder);\n return true;\n }\n }\n return false;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // User-defined, parameterized, reusable functions (f(x) = 2*x + 1, then f(5))\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /**\n * From an LPAREN token index, scan forward tracking paren depth and\n * return the index of the matching RPAREN, or `null` if the parens never\n * balance before the token stream ends. No emission, no position\n * advance. Same class of technique as {@link balanceParens}'s own\n * pre-scan, just exposed mid-parse instead of only at `load()` time.\n * `openIdx` must point AT the LPAREN itself.\n */\n private findMatchingRParen(openIdx: number): number | null {\n let depth = 0;\n for (let i = openIdx; i < this.tokens.length; i++) {\n const t = this.tokens[i];\n if (t.typeId === PrecedenceParser.LPAREN_ID) depth++;\n else if (t.typeId === PrecedenceParser.RPAREN_ID) {\n depth--;\n if (depth === 0) return i;\n }\n }\n return null;\n }\n\n /**\n * Disambiguates a bare `IDENT` immediately followed by `(` between three\n * things, using ONLY a bracket-depth scan (no backtracking, nothing is\n * consumed until the shape is known):\n * - `f(x) = expr`, a DEFINITION: the matching `)` is followed by `=`.\n * - `f(5)`, a CALL to a (possibly not-yet-defined) function: anything\n * else. This was never valid syntax before this feature (a bare\n * `IDENT` immediately before `(` has no pre-existing \"plain variable\n * read + separately grouped `(...)`\" meaning to preserve, confirmed\n * via `BuiltinNormalizerRules.ts`'s `implicitMultiplyRule()`, which\n * only inserts an implicit `*` for `NUMBER/RPAREN` immediately before\n * `IDENT/LPAREN`, never for a bare `IDENT` immediately before\n * `LPAREN`). Always commits to a CALL; an unregistered name produces a\n * clear `UNDEFINED_FUNCTION` error at VM-execution time, the same\n * forward-reference philosophy `LOAD_VAR`/`UNDEFINED_VARIABLE` already\n * uses, rather than any parse-time registry lookup.\n * If the parens never balance, this falls through to the ordinary\n * `LOAD_VAR` path (a malformed expression surfaces its own parse error\n * shortly after, from the normal expression grammar).\n */\n private parseUserFunctionDefOrCall(nameToken: Token, builder: BytecodeBuilder): void {\n const closeIdx = this.findMatchingRParen(this.current);\n if (closeIdx === null) {\n builder.emitOpcode(OpCode.LOAD_VAR);\n builder.emitString(nameToken.value);\n return;\n }\n const afterClose = this.tokens[closeIdx + 1];\n if (afterClose?.type === TokenTypes.EQUALS) {\n this.parseUserFunctionDefinition(nameToken, builder);\n } else {\n this.parseUserFunctionCall(nameToken, builder);\n }\n }\n\n /**\n * A parameter name, accepted as either `IDENT` or `UNIT`, matches this\n * codebase's established `:name = value` variable-name policy\n * (`VariableParselet.ts` explicitly accepts `UNIT`-typed tokens too, e.g.\n * `:b = 5` for the \"b\" bits unit) since common short parameter names\n * like `h`/`l`/`b`/`t`/`s`/`m` collide with real unit abbreviations\n * (hour, liter, bits, ton, second, meter, ...) and lex as `UNIT`, not\n * `IDENT`.\n */\n private consumeParamName(): string {\n const token = this.peek();\n if (token?.type === TokenTypes.IDENT || token?.type === TokenTypes.UNIT) {\n this.consume();\n return token.value;\n }\n throw ErrorFactory.parsing(\n \"USER_FUNCTION_INVALID_PARAM_NAME\",\n `Expected a parameter name but got \"${token?.type ?? \"end of input\"}\"${token ? ` (\"${token.value}\")` : \"\"}`,\n { actualType: token?.type },\n );\n }\n\n private parseUserFunctionDefinition(nameToken: Token, builder: BytecodeBuilder): void {\n this.consume(TokenTypes.LPAREN);\n const params: string[] = [];\n if (this.peek()?.type !== TokenTypes.RPAREN) {\n params.push(this.consumeParamName());\n while (this.match(TokenTypes.COMMA)) {\n params.push(this.consumeParamName());\n }\n }\n this.consume(TokenTypes.RPAREN);\n this.consume(TokenTypes.EQUALS);\n\n if (params.length === 0) {\n throw ErrorFactory.parsing(\n \"USER_FUNCTION_NO_PARAMS\",\n `\"${nameToken.value}()\" has no parameters -- user-defined functions need at least one (a zero-argument definition is indistinguishable from a plain function CALL with no args, which this grammar doesn't otherwise support)`,\n { name: nameToken.value },\n );\n }\n\n // Compile the body into its OWN independent BytecodeBuilder, reusing\n // the SAME parser/token stream but directing emission elsewhere.\n // `parseExpression(minBp, _builder)` sets `this.builder = _builder`\n // with NO automatic restore, explicitly restoring via `setBuilder()`\n // afterward (not a `finally`, since a thrown parse error here should\n // propagate as-is; there's no further use of `this.builder` on that\n // path before the whole parse aborts) avoids silently emitting\n // whatever parses next (in this same expression, or, via\n // ExpressionEngine's builder pool, a LATER, unrelated line) into a\n // stale, already-.build()'d body builder.\n const bodyBuilder = new BytecodeBuilder(this.pluginFunctionIndex);\n this.parseExpression(BindingPower.Lowest, bodyBuilder);\n this.setBuilder(builder);\n\n const bodyProgram = bodyBuilder.build();\n if (bodyProgram.hasAsync) {\n // v1 scope decision: a function body calling an async plugin\n // (weather, stocks, currency, ...) isn't supported yet, propagating\n // a 'pending' result up through a reentrant executeBytecode() call\n // would need the OUTER expression's own bytecode position/stack\n // state to also be resumable later, which this first pass doesn't\n // implement. Rejecting at DEFINITION time (not call time) gives the\n // clearest possible error, matching this codebase's \"never silently\n // pretend to support something it doesn't\" convention (e.g.\n // addBusinessDays()'s own disclosed holiday-exclusion scope-down).\n throw ErrorFactory.parsing(\n \"FUNCTION_BODY_MUST_BE_SYNCHRONOUS\",\n `\"${nameToken.value}(...)\"'s body calls an async operation (weather, stocks, currency, ...) — user-defined function bodies must be synchronous`,\n { name: nameToken.value },\n );\n }\n\n const bodyIdx = builder.emitUserFunctionBody(nameToken.value, params, bodyProgram);\n builder.emitOpcode(OpCode.DEFINE_USER_FUNCTION);\n builder.emitIndex(bodyIdx);\n\n // A definition line has no single input value to echo back the way an\n // assignment does, push a plain confirmation string, matching this\n // codebase's \"never silently produce a misleading numeric 0\" principle.\n builder.emitOpcode(OpCode.PUSH_STRING);\n builder.emitString(`${nameToken.value}(${params.join(\", \")}) defined`);\n }\n\n private parseUserFunctionCall(nameToken: Token, builder: BytecodeBuilder): void {\n this.consume(TokenTypes.LPAREN);\n let argCount = 0;\n if (this.peek()?.type !== TokenTypes.RPAREN) {\n this.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n while (this.match(TokenTypes.COMMA)) {\n this.parseExpression(BindingPower.Lowest, builder);\n argCount++;\n }\n }\n this.consume(TokenTypes.RPAREN);\n\n builder.emitOpcode(OpCode.CALL_USER_FUNCTION);\n builder.emitString(nameToken.value);\n builder.emitByte(argCount);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Token stream navigation (identical API to Parser)\n // ═══════════════════════════════════════════════════════════════════════════════\n\n consume(expectedType?: string): Token {\n const token = this.tokens[this.current];\n if (!token) {\n throw ErrorFactory.parsing(\n \"UNEXPECTED_END_OF_INPUT\",\n \"Unexpected end of input\"\n );\n }\n if (expectedType !== undefined) {\n const expectedId = tokenTypeId(expectedType);\n if (token.typeId !== expectedId) {\n throw ErrorFactory.parsing(\n \"UNEXPECTED_TOKEN_TYPE\",\n `Expected token type \"${expectedType}\" but got \"${token.type}\" (\"${token.value}\")`,\n { expectedType, actualType: token.type, actualValue: token.value }\n );\n }\n }\n this.current++;\n return token;\n }\n\n match(expectedType: string): boolean {\n const token = this.peek();\n if (token && token.typeId === tokenTypeId(expectedType)) {\n this.advance();\n return true;\n }\n return false;\n }\n\n peek(): Token | undefined {\n return this.tokens[this.current];\n }\n\n /**\n * Read-only lookahead `offset` tokens past the current position, without\n * consuming anything, `peekAt(0)` is equivalent to {@link peek}.\n * `this.tokens` is a plain in-memory array (not a stream), so this is a\n * simple, safe index read; no rewind/checkpoint mechanism is needed since\n * nothing is consumed.\n */\n peekAt(offset: number): Token | undefined {\n return this.tokens[this.current + offset];\n }\n\n previous(): Token | undefined {\n return this.current > 0 ? this.tokens[this.current - 1] : undefined;\n }\n\n private advance(): void {\n this.current++;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Builder access, set before parse, read by inline prefix handlers\n // ═══════════════════════════════════════════════════════════════════════════════\n\n /** Set the builder to use for the current parse. Called by ExpressionEngine. */\n setBuilder(builder: BytecodeBuilder): void {\n this.builder = builder;\n }\n\n // ═══════════════════════════════════════════════════════════════════════════════\n // Diagnostics\n // ═══════════════════════════════════════════════════════════════════════════════\n\n private fireParseletMatched(\n parselet: { category: string },\n token: Token,\n isPrefix: boolean,\n bindingPower?: number\n ): void {\n const pipeline = this.diagnosticPipeline!;\n const event: DiagnosticEvent & { type: \"parselet_matched\" } = {\n type: DiagnosticEventType.ParseletMatched,\n elapsedNs: 0,\n expression: this.currentExpression,\n tokenType: token.type,\n tokenValue: token.value,\n parseletCategory: parselet.category,\n parseletType: parselet.constructor?.name ?? \"unknown\",\n isPrefix,\n bindingPower,\n tokenOffset: token.offset || 0,\n };\n pipeline.fireParseletMatched(event);\n }\n}\n","import { PrefixParselet, InfixParselet } from \"@solve-js/parser/Parselet\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { BindingPower } from \"@solve-js/parser/BindingPower\";\n\n/**\n * The one binding-power field a parselet may expose beyond what its interface\n * requires, read only for diagnostic display.\n *\n * `InfixParselet` requires `bindingPower`; `PrefixParselet` declares none, and\n * some prefix parselets carry one anyway. That single field is the whole\n * optional surface deliberately. A `leftBindingPower`/`rightBindingPower` pair\n * used to be read here as well, and reading a name off an object this way finds\n * PRIVATE fields too, since TypeScript's `private` exists only at compile time:\n * `BinaryOpParselet` holds a private `rightBindingPower` meaning \"the minimum\n * power to parse my right operand at\", which is a different quantity from \"the\n * power at which I bind to my right\" and differs from it by one. Reading it\n * silently reported that other number. So neither is read.\n *\n * `category` is not here: both interfaces already declare it.\n */\ninterface ParseletBindingPowers {\n\treadonly bindingPower?: number;\n}\n\n/** Reads the optional binding-power field off a parselet for diagnostics. */\nfunction bindingPowersOf(parselet: PrefixParselet | InfixParselet): ParseletBindingPowers {\n\treturn parselet as ParseletBindingPowers;\n}\n\n/**\n * Dual-keyed ParseletRegistry, accepts both string token types and\n * integer token type IDs for fast dispatch in the Parser hot path.\n *\n * Providers call registerPrefix(\"NUMBER\", ...) with string token types.\n * Internally, we populate both string-keyed and integer-keyed maps so\n * Parser.parseExpression() can use token.typeId (integer) for lookup\n * while diagnostics and error messages use token.type (string).\n *\n * Performance: Integer Map.get() avoids string hashing, saving ~2-5ns\n * per dispatch. With ~10-15 dispatches per expression, that's ~20-75ns.\n */\nexport class ParseletRegistry {\n\t// String-keyed maps (kept for diagnostics + backwards compat)\n\tprivate prefixParselets: Map<string, PrefixParselet> = new Map();\n\tprivate infixParselets: Map<string, InfixParselet> = new Map();\n\n\t// Integer-keyed maps for parser hot path\n\tprivate prefixById: Map<number, PrefixParselet> = new Map();\n\tprivate infixById: Map<number, InfixParselet> = new Map();\n\n\t/**\n\t * Register a prefix parselet for `tokenType`.\n\t *\n\t * If another parselet is already registered for this token type, it is\n\t * silently overwritten by default (`Map.set()` semantics), the old\n\t * parselet is simply unreachable from then on, with no error. This is\n\t * a real footgun for third-party packages: two packages independently\n\t * choosing the same custom token type will collide with zero signal\n\t * about which one \"won\". Mirrors ResolverRegistry.register()'s and\n\t * ExpressionEngine.registerPackage()'s existing \"warn and replace\"\n\t * pattern for the same class of problem at the resolver-namespace and\n\t * package-name levels.\n\t *\n\t * Note: this warns about registry-level collisions only. It does NOT\n\t * detect the separate case where `tokenType` is one of PrecedenceParser's\n\t * Tier-1 fast-path token types (NUMBER, STRING, IDENT, LPAREN, MINUS,\n\t * PLUS, and the Tier-1 infix operators), those are deliberately kept\n\t * registered here for introspection/diagnostics even though Tier-1\n\t * always intercepts them before this registry is consulted (see\n\t * PrecedenceParser.parsePrefix()'s docs), so warning there would\n\t * misfire on that intentional, already-documented pattern.\n\t */\n\tregisterPrefix(tokenType: string, parselet: PrefixParselet): void {\n\t\tconst existing = this.prefixParselets.get(tokenType);\n\t\tif (existing && existing !== parselet) {\n\t\t\tconsole.warn(\n\t\t\t\t`[ParseletRegistry] Prefix parselet for token \"${tokenType}\" is already registered ` +\n\t\t\t\t`(category: \"${existing.category ?? \"unknown\"}\"). Overwriting with a new ` +\n\t\t\t\t`parselet (category: \"${parselet.category ?? \"unknown\"}\") — the previous ` +\n\t\t\t\t`parselet is now unreachable. Two packages may be claiming the same token type.`,\n\t\t\t);\n\t\t}\n\t\tthis.prefixParselets.set(tokenType, parselet);\n\t\tthis.prefixById.set(tokenTypeId(tokenType), parselet);\n\t}\n\n\t/** Register an infix parselet for `tokenType`. See {@link registerPrefix} for the collision-warning behavior this mirrors. */\n\tregisterInfix(tokenType: string, parselet: InfixParselet): void {\n\t\tconst existing = this.infixParselets.get(tokenType);\n\t\tif (existing && existing !== parselet) {\n\t\t\tconsole.warn(\n\t\t\t\t`[ParseletRegistry] Infix parselet for token \"${tokenType}\" is already registered ` +\n\t\t\t\t`(category: \"${existing.category ?? \"unknown\"}\"). Overwriting with a new ` +\n\t\t\t\t`parselet (category: \"${parselet.category ?? \"unknown\"}\") — the previous ` +\n\t\t\t\t`parselet is now unreachable. Two packages may be claiming the same token type.`,\n\t\t\t);\n\t\t}\n\t\tthis.infixParselets.set(tokenType, parselet);\n\t\tthis.infixById.set(tokenTypeId(tokenType), parselet);\n\t}\n\n\t/**\n\t * Iterate all registered prefix parselets for diagnostic display.\n\t *\n\t * `PrefixParselet` declares no binding power, and this used to read a field\n\t * of that name and report 0 for every one of them. 0 is not a neutral\n\t * wrong answer: it is the value that means \"not an operator, stop the\n\t * expression\", so a host drawing a table from this was told none of them\n\t * bind at all. A prefix parselet in this parser has no per-parselet power\n\t * to report, they all bind at the prefix level and each chooses for itself\n\t * at what power to parse its own operand, so that level is what is\n\t * reported. A parselet that does carry its own `bindingPower` still wins.\n\t */\n\tgetAllPrefix(): Array<{ tokenType: string; bindingPower: number; category?: string }> {\n\t\tconst result: Array<{ tokenType: string; bindingPower: number; category?: string }> = [];\n\t\tfor (const [tokenType, parselet] of this.prefixParselets) {\n\t\t\tresult.push({\n\t\t\t\ttokenType,\n\t\t\t\tbindingPower: bindingPowersOf(parselet).bindingPower ?? BindingPower.Prefix,\n\t\t\t\tcategory: parselet.category,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Iterate all registered infix parselets for diagnostic display.\n\t *\n\t * The field an `InfixParselet` actually declares is `bindingPower`. This\n\t * used to read `leftBindingPower` and `rightBindingPower`, which no\n\t * parselet in this codebase declares, so both reads were `undefined`, both\n\t * fell to the `?? 0` default, and the public `getParseletRegistry()`\n\t * reported a binding power of 0 for every one of the ~60 infix operators.\n\t * A host building a precedence table from it was told `*` and `+` bind\n\t * equally, and that neither binds at all.\n\t *\n\t * The left/right split: `bindingPower` is the LEFT power, and the right is\n\t * one higher. That is the standard encoding for a left-associative\n\t * operator, and it is what the parser itself does, see\n\t * `PrecedenceParser.parseExpression()`'s `bp + 1` for the right operand.\n\t * Every operator is reported that way, `^` included. Associativity is not\n\t * something a parselet declares, it is a property of how each one calls\n\t * `parseExpression`, so this API cannot report it without a new field on\n\t * the interface. See {@link ParseletBindingPowers} for why scraping a\n\t * plausible-looking one off the parselet is worse than not reporting it.\n\t */\n\tgetAllInfix(): Array<{ tokenType: string; leftBindingPower: number; rightBindingPower: number; category?: string }> {\n\t\tconst result: Array<{ tokenType: string; leftBindingPower: number; rightBindingPower: number; category?: string }> = [];\n\t\tfor (const [tokenType, parselet] of this.infixParselets) {\n\t\t\tconst left = bindingPowersOf(parselet).bindingPower ?? 0;\n\t\t\tresult.push({\n\t\t\t\ttokenType,\n\t\t\t\tleftBindingPower: left,\n\t\t\t\trightBindingPower: left + 1,\n\t\t\t\tcategory: parselet.category,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Number of registered prefix parselets. */\n\tget prefixCount(): number { return this.prefixParselets.size; }\n\n\t/** Number of registered infix parselets. */\n\tget infixCount(): number { return this.infixParselets.size; }\n\n\t/**\n\t * Get prefix parselet by string token type OR integer typeId.\n\t * Fast path for integer IDs (Parser hot path), fallback for strings\n\t * (diagnostics, error messages, backwards compatibility).\n\t */\n\tgetPrefix(tokenType: string | number): PrefixParselet | undefined {\n\t\tif (typeof tokenType === 'number') return this.prefixById.get(tokenType);\n\t\treturn this.prefixParselets.get(tokenType);\n\t}\n\n\t/**\n\t * Get infix parselet by string token type OR integer typeId.\n\t * Fast path for integer IDs (Parser hot path), fallback for strings.\n\t */\n\tgetInfix(tokenType: string | number): InfixParselet | undefined {\n\t\tif (typeof tokenType === 'number') return this.infixById.get(tokenType);\n\t\treturn this.infixParselets.get(tokenType);\n\t}\n\n\thasPrefix(tokenType: string): boolean {\n\t\treturn this.prefixParselets.has(tokenType);\n\t}\n\n\thasInfix(tokenType: string): boolean {\n\t\treturn this.infixParselets.has(tokenType);\n\t}\n\n\tclear(): void {\n\t\tthis.prefixParselets.clear();\n\t\tthis.infixParselets.clear();\n\t\tthis.prefixById.clear();\n\t\tthis.infixById.clear();\n\t}\n}\n\n/**\n * A process-wide parselet registry.\n *\n * @deprecated An engine builds its own registry and does not read this one, so\n * registering here reaches nothing that evaluates. Nothing writes to it now\n * that the global package-registration path is gone; it remains only so the\n * `@solve-js/parser` escape hatch keeps a stable shape.\n */\nexport const sharedParseletRegistry = new ParseletRegistry();\n"]}
@@ -0,0 +1,2 @@
1
+ 'use strict';var E={NUMBER:"number",BIGINT:"number",FLOAT:"number",STRING:"string",PI:"keyword",E:"keyword",NOW:"keyword",TODAY:"keyword",TOMORROW:"keyword",YESTERDAY:"keyword",ROLL:"keyword",GLOBAL:"keyword",OF:"keyword",DURATION_DAY:"keyword",DURATION_WEEK:"keyword",DURATION_MONTH:"keyword",DURATION_YEAR:"keyword",DURATION_HOUR:"keyword",DURATION_MINUTE:"keyword",DURATION_SECOND:"keyword",NEXT:"keyword",LAST:"keyword",UNTIL:"keyword",SINCE:"keyword",BETWEEN:"keyword",SPLIT:"keyword",SPLIT_WAYS:"keyword",WAYS:"keyword",PEOPLE:"keyword",FROM:"keyword",BEST:"keyword",KEYWORD:"keyword",TRUE:"keyword",FALSE:"keyword",IF:"keyword",THEN:"keyword",ELSE:"keyword",AS:"keyword",CONVERTER_NAME:"keyword",ROUNDED:"keyword",TO_NEAREST:"keyword",DECIMAL_PLACES:"keyword",AVERAGE_OF:"keyword",MEDIAN_OF:"keyword",TOTAL_OF:"keyword",COUNT_OF:"keyword",LARGER_OF:"keyword",SMALLER_OF:"keyword",HALF_OF:"keyword",MIDPOINT_BETWEEN:"keyword",REMAINDER_OF:"keyword",NTH_ROOT:"keyword",LOG_PHRASE:"keyword",LOG_BASE:"keyword",GCD_OF:"keyword",LCM_OF:"keyword",SQUARE_ROOT_OF:"keyword",CUBE_ROOT_OF:"keyword",CLAMP:"keyword",MAP:"keyword",REDUCE:"keyword",SUM_FN:"keyword",PROD_FN:"keyword",EXPAND_FN:"keyword",FACTOR_FN:"keyword",SOLVE_FN:"keyword",DER_FN:"keyword",INTEGRAL_FN:"keyword",TAYLOR_FN:"keyword",JACOBIAN_FN:"keyword",IMAGINARY:"number",CONJ_FN:"keyword",RE_FN:"keyword",IM_FN:"keyword",CANCEL_FN:"keyword",APART_FN:"keyword",TIME_IN:"keyword",DATE_IN:"keyword",TIME_DIFFERENCE_BETWEEN:"keyword",CITY_NAME:"keyword",OVER:"keyword",AFTER:"keyword",PRESENT_VALUE_OF:"keyword",ANNUAL_RETURN_ON:"keyword",FOR_DURATION:"keyword",COMPOUNDING:"keyword",INVESTED:"keyword",RETURNED:"keyword",RATE_AT:"keyword",COMPOUND_INTEREST_ON:"keyword",INTEREST_ON:"keyword",DAILY_REPAYMENT_ON:"keyword",MONTHLY_REPAYMENT_ON:"keyword",ANNUAL_REPAYMENT_ON:"keyword",TOTAL_REPAYMENT_ON:"keyword",DAILY_LOAN_INTEREST_ON:"keyword",MONTHLY_LOAN_INTEREST_ON:"keyword",ANNUAL_LOAN_INTEREST_ON:"keyword",TOTAL_LOAN_INTEREST_ON:"keyword",TAX_ON:"keyword",TAX_OFF:"keyword",TAX_IN_PHRASE:"keyword",IS_TO:"keyword",IS:"keyword",PCT_ON:"operator",PCT_OFF:"operator",PCT_UP:"operator",PCT_DOWN:"operator",OF_WHAT:"keyword",OFF_WHAT:"keyword",ON_WHAT:"keyword",RANDOM_NUMBER:"keyword",WHAT_IS:"keyword",WHAT_WAS:"keyword",VALUE_OF:"keyword",WORTH_IN:"keyword",SAVINGS_HOW_LONG:"keyword",SAVINGS_HOW_MUCH:"keyword",IN_YEAR_DOLLARS:"keyword",INGREDIENT_NAME:"keyword",ASSUMING:"keyword",WORKDAYS_IN:"keyword",WEEKDAY_ON:"keyword",WEEKDAY_IN:"keyword",MONTH_ON:"keyword",MONTH_IN:"keyword",WEEK_ON:"keyword",DAYS_IN_PERIOD:"keyword",IN_TWO_UNITS:"unit",PER_UNIT:"unit",AT_RATE:"keyword",WEEK_IN:"keyword",BETWEEN_UNIT:"keyword",WORKDAYS_AFTER:"keyword",WORKDAYS_BEFORE:"keyword",WORKDAYS_BETWEEN:"keyword",IS_WEEKEND:"keyword",IS_WORKDAY:"keyword",CURRENT_TIMESTAMP:"keyword",TO_DATE:"keyword",TO_TIMESTAMP:"keyword",VIDEO_TIMECODE:"datetime",FRAME_COUNT:"datetime",AT:"keyword",PLUS:"operator",AND_CONJ:"operator",MINUS:"operator",STAR:"operator",SLASH:"operator",PLUS_MINUS:"operator",CARET:"operator",PERCENT:"operator",LSHIFT:"operator",RSHIFT:"operator",EQUALS:"operator",PLUS_EQUALS:"operator",MINUS_EQUALS:"operator",THEREFORE:"operator",INCREASE_BY:"operator",DECREASE_BY:"operator",OF_WHAT_IS:"keyword",ON_WHAT_IS:"keyword",OFF_WHAT_IS:"keyword",TIMES_BY:"operator",MULTIPLY_BY:"operator",DIVIDE_BY:"operator",MOD:"operator",INCREASE:"operator",DECREASE:"operator",UNICODE_MATH:"operator",QUESTION:"operator",BANG:"operator",NEQ:"comparison",IN:"comparison",GTE:"comparison",LTE:"comparison",EQUALITY:"comparison",LT:"comparison",GT:"comparison",LOGICAL_AND:"comparison",LOGICAL_OR:"comparison",OR:"comparison",URSHIFT:"bitwise",BIT_AND:"bitwise",BIT_OR:"bitwise",BIT_NOT:"bitwise",BIT_XOR:"bitwise",FUNC:"function",DOLLAR:"variable",COLON:"variable",IDENT:"variable",UNIT:"unit",CONVERT:"unit",TO:"unit",POUND:"unit",EURO:"unit",YEN:"unit",RUBLE:"unit",WON:"unit",CURRENCY_SYMBOL:"unit",PREV:"keyword",LINE_REF:"keyword",SUM_RANGE_CALL:"keyword",AVERAGE_RANGE_CALL:"keyword",TOTAL_ABOVE:"keyword",SUM_ABOVE:"keyword",AVERAGE_ABOVE:"keyword",GOAL_SEEK:"keyword",HEX_COLOUR:"colour",COLOUR_CALL:"function",DATETIME_LITERAL:"datetime",DURATION:"datetime",VEC2:"vector",VEC3:"vector",VEC4:"vector",LPAREN:"punctuation",RPAREN:"punctuation",LBRACKET:"punctuation",RBRACKET:"punctuation",LBRACE:"punctuation",RBRACE:"punctuation",DOT:"punctuation",COMMA:"punctuation",SEMICOLON:"punctuation",ERROR:"error"},N=new Set(["WS","NEWLINE","EOF","BACKTICK_OPEN","INLINE_SOLVE_START","COMMENT","TAG"]),r=new Map;function T(o,e){r.set(o,e);}function _(o){r.delete(o);}function O(o){return r.get(o)??E[o]}exports.a=N;exports.b=T;exports.c=_;exports.d=O;//# sourceMappingURL=chunk-Y7O4D3BJ.cjs.map
2
+ //# sourceMappingURL=chunk-Y7O4D3BJ.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/language/TokenCategoryMap.ts"],"names":["TOKEN_CATEGORY_MAP","UNCATEGORIZED_TOKEN_TYPES","pluginCategories","registerTokenCategory","tokenType","category","unregisterTokenCategory","getTokenCategory"],"mappings":"aAiBA,IAAMA,CAAAA,CAAoD,CAEzD,MAAA,CAAQ,QAAA,CACR,MAAA,CAAQ,QAAA,CACR,KAAA,CAAO,QAAA,CACP,MAAA,CAAQ,QAAA,CAGR,EAAA,CAAI,SAAA,CACJ,CAAA,CAAG,SAAA,CACH,GAAA,CAAK,SAAA,CACL,KAAA,CAAO,SAAA,CACP,QAAA,CAAU,SAAA,CACV,SAAA,CAAW,SAAA,CACX,IAAA,CAAM,SAAA,CACN,MAAA,CAAQ,SAAA,CACR,EAAA,CAAI,SAAA,CACJ,YAAA,CAAc,SAAA,CACd,aAAA,CAAe,SAAA,CACf,cAAA,CAAgB,SAAA,CAChB,aAAA,CAAe,SAAA,CACf,aAAA,CAAe,SAAA,CACf,eAAA,CAAiB,SAAA,CACjB,eAAA,CAAiB,SAAA,CACjB,IAAA,CAAM,SAAA,CACN,IAAA,CAAM,SAAA,CACN,KAAA,CAAO,SAAA,CACP,KAAA,CAAO,SAAA,CACP,OAAA,CAAS,SAAA,CAGT,KAAA,CAAO,SAAA,CACP,UAAA,CAAY,SAAA,CACZ,IAAA,CAAM,SAAA,CACN,MAAA,CAAQ,SAAA,CACR,IAAA,CAAM,UACN,IAAA,CAAM,SAAA,CACN,OAAA,CAAS,SAAA,CACT,IAAA,CAAM,SAAA,CACN,KAAA,CAAO,SAAA,CACP,EAAA,CAAI,SAAA,CACJ,IAAA,CAAM,SAAA,CACN,IAAA,CAAM,SAAA,CACN,EAAA,CAAI,SAAA,CACJ,cAAA,CAAgB,SAAA,CAChB,OAAA,CAAS,SAAA,CACT,UAAA,CAAY,SAAA,CACZ,cAAA,CAAgB,SAAA,CAChB,UAAA,CAAY,SAAA,CACZ,SAAA,CAAW,SAAA,CACX,QAAA,CAAU,SAAA,CACV,QAAA,CAAU,SAAA,CACV,SAAA,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AAoB,SAAA,CACpB,WAAA,CAAa,SAAA,CACb,SAAA,CAAW,SAAA,CACX,aAAA,CAAe,SAAA,CAGf,SAAA,CAAW,SAAA,CAKX,UAAA,CAAY,QAAA,CACZ,WAAA,CAAa,UAAA,CAGb,gBAAA,CAAkB,UAAA,CAClB,QAAA,CAAU,UAAA,CAGV,IAAA,CAAM,QAAA,CACN,IAAA,CAAM,QAAA,CACN,IAAA,CAAM,QAAA,CAKN,MAAA,CAAQ,aAAA,CACR,MAAA,CAAQ,aAAA,CACR,QAAA,CAAU,aAAA,CACV,QAAA,CAAU,cACV,MAAA,CAAQ,aAAA,CACR,MAAA,CAAQ,aAAA,CACR,GAAA,CAAK,aAAA,CACL,KAAA,CAAO,aAAA,CACP,SAAA,CAAW,aAAA,CAGX,KAAA,CAAO,OACR,CAAA,CAQaC,CAAAA,CAAiD,IAAI,GAAA,CAAI,CACrE,IAAA,CACA,SAAA,CACA,KAAA,CACA,eAAA,CACA,oBAAA,CACA,SAAA,CAIA,KACD,CAAC,CAAA,CAUKC,CAAAA,CAAmB,IAAI,IAQtB,SAASC,CAAAA,CAAsBC,CAAAA,CAAmBC,CAAAA,CAA+B,CACvFH,CAAAA,CAAiB,GAAA,CAAIE,CAAAA,CAAWC,CAAQ,EACzC,CAOO,SAASC,CAAAA,CAAwBF,CAAAA,CAAyB,CAChEF,CAAAA,CAAiB,MAAA,CAAOE,CAAS,EAClC,CAWO,SAASG,CAAAA,CAAiBH,CAAAA,CAA8C,CAC9E,OAAOF,CAAAA,CAAiB,GAAA,CAAIE,CAAS,CAAA,EAAKJ,CAAAA,CAAmBI,CAAS,CACvE","file":"chunk-Y7O4D3BJ.cjs","sourcesContent":["import type { TokenCategory } from \"@solve-js/language/TokenCategory\";\n\n/**\n * Static, built-in token-type → semantic-category table.\n *\n * Covers the full `TokenTypes` surface (see Token.ts) so nothing recognized\n * by the lexer's grammar goes uncategorized by omission. Structural/internal\n * token types (WS, NEWLINE, EOF, BACKTICK_OPEN, INLINE_SOLVE_START, COMMENT)\n * are intentionally absent, they're either filtered out before reaching\n * this lookup (see Lexer.getHighlightTokens) or simply have nothing\n * meaningful to highlight. COMMENT specifically: it reaches\n * Lexer.getHighlightTokens() (unlike WS/NEWLINE, filtered earlier), so a\n * future \"give comments their own color\" pass would add a real category\n * here. This is a rendering-scope decision, not a correctness\n * requirement, since COMMENT tokens are already filtered out of the\n * parser's input regardless of how they're highlighted.\n */\nconst TOKEN_CATEGORY_MAP: Record<string, TokenCategory> = {\n\t// Literals\n\tNUMBER: \"number\",\n\tBIGINT: \"number\",\n\tFLOAT: \"number\",\n\tSTRING: \"string\",\n\n\t// Keywords (constants, date words, dice, misc grammar keywords)\n\tPI: \"keyword\",\n\tE: \"keyword\",\n\tNOW: \"keyword\",\n\tTODAY: \"keyword\",\n\tTOMORROW: \"keyword\",\n\tYESTERDAY: \"keyword\",\n\tROLL: \"keyword\",\n\tGLOBAL: \"keyword\",\n\tOF: \"keyword\",\n\tDURATION_DAY: \"keyword\",\n\tDURATION_WEEK: \"keyword\",\n\tDURATION_MONTH: \"keyword\",\n\tDURATION_YEAR: \"keyword\",\n\tDURATION_HOUR: \"keyword\",\n\tDURATION_MINUTE: \"keyword\",\n\tDURATION_SECOND: \"keyword\",\n\tNEXT: \"keyword\",\n\tLAST: \"keyword\",\n\tUNTIL: \"keyword\",\n\tSINCE: \"keyword\",\n\tBETWEEN: \"keyword\",\n\t// Bill split (finance): the split verb, its two spellings, and the trailing\n\t// words the normalizer retypes only inside the full split shape.\n\tSPLIT: \"keyword\",\n\tSPLIT_WAYS: \"keyword\",\n\tWAYS: \"keyword\",\n\tPEOPLE: \"keyword\",\n\tFROM: \"keyword\",\n\tBEST: \"keyword\",\n\tKEYWORD: \"keyword\",\n\tTRUE: \"keyword\",\n\tFALSE: \"keyword\",\n\tIF: \"keyword\",\n\tTHEN: \"keyword\",\n\tELSE: \"keyword\",\n\tAS: \"keyword\",\n\tCONVERTER_NAME: \"keyword\",\n\tROUNDED: \"keyword\",\n\tTO_NEAREST: \"keyword\",\n\tDECIMAL_PLACES: \"keyword\",\n\tAVERAGE_OF: \"keyword\",\n\tMEDIAN_OF: \"keyword\",\n\tTOTAL_OF: \"keyword\",\n\tCOUNT_OF: \"keyword\",\n\tLARGER_OF: \"keyword\",\n\tSMALLER_OF: \"keyword\",\n\tHALF_OF: \"keyword\",\n\tMIDPOINT_BETWEEN: \"keyword\",\n\tREMAINDER_OF: \"keyword\",\n\tNTH_ROOT: \"keyword\",\n\tLOG_PHRASE: \"keyword\",\n\tLOG_BASE: \"keyword\",\n\tGCD_OF: \"keyword\",\n\tLCM_OF: \"keyword\",\n\tSQUARE_ROOT_OF: \"keyword\",\n\tCUBE_ROOT_OF: \"keyword\",\n\tCLAMP: \"keyword\",\n\tMAP: \"keyword\",\n\tREDUCE: \"keyword\",\n\tSUM_FN: \"keyword\",\n\tPROD_FN: \"keyword\",\n\t// Symbolic algebra verbs (packages/symbolic/). Declared here alongside\n\t// map/reduce rather than only on the package descriptor, so highlighting is\n\t// correct without depending on registration order.\n\tEXPAND_FN: \"keyword\",\n\tFACTOR_FN: \"keyword\",\n\tSOLVE_FN: \"keyword\",\n\tDER_FN: \"keyword\",\n\tINTEGRAL_FN: \"keyword\",\n\tTAYLOR_FN: \"keyword\",\n\tJACOBIAN_FN: \"keyword\",\n\tIMAGINARY: \"number\",\n\tCONJ_FN: \"keyword\",\n\tRE_FN: \"keyword\",\n\tIM_FN: \"keyword\",\n\tCANCEL_FN: \"keyword\",\n\tAPART_FN: \"keyword\",\n\tTIME_IN: \"keyword\",\n\tDATE_IN: \"keyword\",\n\tTIME_DIFFERENCE_BETWEEN: \"keyword\",\n\tCITY_NAME: \"keyword\",\n\tOVER: \"keyword\",\n\t// The investment grammar's connectives (packages/finance/).\n\tAFTER: \"keyword\",\n\tPRESENT_VALUE_OF: \"keyword\",\n\tANNUAL_RETURN_ON: \"keyword\",\n\tFOR_DURATION: \"keyword\",\n\tCOMPOUNDING: \"keyword\",\n\tINVESTED: \"keyword\",\n\tRETURNED: \"keyword\",\n\tRATE_AT: \"keyword\",\n\tCOMPOUND_INTEREST_ON: \"keyword\",\n\tINTEREST_ON: \"keyword\",\n\tDAILY_REPAYMENT_ON: \"keyword\",\n\tMONTHLY_REPAYMENT_ON: \"keyword\",\n\tANNUAL_REPAYMENT_ON: \"keyword\",\n\tTOTAL_REPAYMENT_ON: \"keyword\",\n\tDAILY_LOAN_INTEREST_ON: \"keyword\",\n\tMONTHLY_LOAN_INTEREST_ON: \"keyword\",\n\tANNUAL_LOAN_INTEREST_ON: \"keyword\",\n\tTOTAL_LOAN_INTEREST_ON: \"keyword\",\n\tTAX_ON: \"keyword\",\n\tTAX_OFF: \"keyword\",\n\tTAX_IN_PHRASE: \"keyword\",\n\tIS_TO: \"keyword\",\n\tIS: \"keyword\",\n\tPCT_ON: \"operator\",\n\tPCT_OFF: \"operator\",\n\tPCT_UP: \"operator\",\n\tPCT_DOWN: \"operator\",\n\tOF_WHAT: \"keyword\",\n\tOFF_WHAT: \"keyword\",\n\tON_WHAT: \"keyword\",\n\tRANDOM_NUMBER: \"keyword\",\n\tWHAT_IS: \"keyword\",\n\tWHAT_WAS: \"keyword\",\n\tVALUE_OF: \"keyword\",\n\tWORTH_IN: \"keyword\",\n\tSAVINGS_HOW_LONG: \"keyword\",\n\tSAVINGS_HOW_MUCH: \"keyword\",\n\tIN_YEAR_DOLLARS: \"keyword\",\n\tINGREDIENT_NAME: \"keyword\",\n\tASSUMING: \"keyword\",\n\t// Datetime, workdays/weekdays/timestamps (packages/datetime/); Time\n\t// video timecode (packages/time/). See Token.ts's TokenTypes doc\n\t// comments for why each is a fused phrase/sequence token rather than a\n\t// bare keyword.\n\tWORKDAYS_IN: \"keyword\",\n\tWEEKDAY_ON: \"keyword\",\n\tWEEKDAY_IN: \"keyword\",\n\tMONTH_ON: \"keyword\",\n\tMONTH_IN: \"keyword\",\n\tWEEK_ON: \"keyword\",\n\tDAYS_IN_PERIOD: \"keyword\",\n\tIN_TWO_UNITS: \"unit\",\n\tPER_UNIT: \"unit\",\n\tAT_RATE: \"keyword\",\n\tWEEK_IN: \"keyword\",\n\tBETWEEN_UNIT: \"keyword\",\n\tWORKDAYS_AFTER: \"keyword\",\n\tWORKDAYS_BEFORE: \"keyword\",\n\tWORKDAYS_BETWEEN: \"keyword\",\n\tIS_WEEKEND: \"keyword\",\n\tIS_WORKDAY: \"keyword\",\n\tCURRENT_TIMESTAMP: \"keyword\",\n\tTO_DATE: \"keyword\",\n\tTO_TIMESTAMP: \"keyword\",\n\tVIDEO_TIMECODE: \"datetime\",\n\tFRAME_COUNT: \"datetime\",\n\tAT: \"keyword\",\n\n\t// Arithmetic / assignment-style operators\n\tPLUS: \"operator\",\n\t// The word \"and\". An operator rather than a keyword: it adds, and syntax\n\t// highlighting that painted it as a keyword would make \"5 and 3\" look\n\t// structurally different from \"5 + 3\" when the two mean the same thing.\n\tAND_CONJ: \"operator\",\n\tMINUS: \"operator\",\n\tSTAR: \"operator\",\n\tSLASH: \"operator\",\n\t// `±` / `+/-`, the uncertainty operator (packages/uncertainty/). A core\n\t// lexer token, so its category lives in the built-in map alongside the other\n\t// operators rather than being registered by the package.\n\tPLUS_MINUS: \"operator\",\n\tCARET: \"operator\",\n\tPERCENT: \"operator\",\n\tLSHIFT: \"operator\",\n\tRSHIFT: \"operator\",\n\tEQUALS: \"operator\",\n\tPLUS_EQUALS: \"operator\",\n\tMINUS_EQUALS: \"operator\",\n\tTHEREFORE: \"operator\",\n\tINCREASE_BY: \"operator\",\n\tDECREASE_BY: \"operator\",\n\tOF_WHAT_IS: \"keyword\",\n\tON_WHAT_IS: \"keyword\",\n\tOFF_WHAT_IS: \"keyword\",\n\tTIMES_BY: \"operator\",\n\tMULTIPLY_BY: \"operator\",\n\tDIVIDE_BY: \"operator\",\n\tMOD: \"operator\",\n\tINCREASE: \"operator\",\n\tDECREASE: \"operator\",\n\tUNICODE_MATH: \"operator\",\n\tQUESTION: \"operator\",\n\tBANG: \"operator\",\n\n\t// Comparison operators\n\tNEQ: \"comparison\",\n\tIN: \"comparison\",\n\tGTE: \"comparison\",\n\tLTE: \"comparison\",\n\tEQUALITY: \"comparison\",\n\tLT: \"comparison\",\n\tGT: \"comparison\",\n\tLOGICAL_AND: \"comparison\",\n\tLOGICAL_OR: \"comparison\",\n\tOR: \"comparison\",\n\n\t// Bitwise operators\n\tURSHIFT: \"bitwise\",\n\tBIT_AND: \"bitwise\",\n\tBIT_OR: \"bitwise\",\n\tBIT_NOT: \"bitwise\",\n\tBIT_XOR: \"bitwise\",\n\n\t// Functions\n\tFUNC: \"function\",\n\n\t// Variable references/definitions, DOLLAR/COLON are the sigils, IDENT is\n\t// a bare identifier reference. All three are recognized-by-the-grammar\n\t// variable syntax at LEX time, independent of whether the variable turns\n\t// out to be defined at eval time (that's a separate, later concern).\n\tDOLLAR: \"variable\",\n\tCOLON: \"variable\",\n\tIDENT: \"variable\",\n\n\t// Units / conversions / currency symbols\n\tUNIT: \"unit\",\n\tCONVERT: \"unit\",\n\tTO: \"unit\",\n\tPOUND: \"unit\",\n\tEURO: \"unit\",\n\tYEN: \"unit\",\n\tRUBLE: \"unit\",\n\tWON: \"unit\",\n\tCURRENCY_SYMBOL: \"unit\",\n\n\t// Cross-line data access (packages/lines/)\n\tPREV: \"keyword\",\n\tLINE_REF: \"keyword\",\n\tSUM_RANGE_CALL: \"keyword\",\n\tAVERAGE_RANGE_CALL: \"keyword\",\n\tTOTAL_ABOVE: \"keyword\",\n\tSUM_ABOVE: \"keyword\",\n\tAVERAGE_ABOVE: \"keyword\",\n\n\t// Goal seek (packages/goalseek/)\n\tGOAL_SEEK: \"keyword\",\n\n\t// Colour (packages/colour/). HEX_COLOUR gets its own \"colour\" category so a\n\t// host can render an inline swatch on the literal; the call token highlights\n\t// like any function.\n\tHEX_COLOUR: \"colour\",\n\tCOLOUR_CALL: \"function\",\n\n\t// Datetime literals/durations\n\tDATETIME_LITERAL: \"datetime\",\n\tDURATION: \"datetime\",\n\n\t// Vectors\n\tVEC2: \"vector\",\n\tVEC3: \"vector\",\n\tVEC4: \"vector\",\n\n\t// Punctuation, grouping/separators, deliberately neutral/muted rather\n\t// than left uncategorized: they're still recognized grammar, just not\n\t// semantically interesting enough to earn a \"loud\" color.\n\tLPAREN: \"punctuation\",\n\tRPAREN: \"punctuation\",\n\tLBRACKET: \"punctuation\",\n\tRBRACKET: \"punctuation\",\n\tLBRACE: \"punctuation\",\n\tRBRACE: \"punctuation\",\n\tDOT: \"punctuation\",\n\tCOMMA: \"punctuation\",\n\tSEMICOLON: \"punctuation\",\n\n\t// Errors\n\tERROR: \"error\",\n};\n\n/**\n * Token types intentionally left uncategorized, either purely structural\n * (never meant to be visibly styled) or already filtered out upstream\n * before reaching a category lookup. Used only by the completeness test to\n * distinguish \"deliberately unstyled\" from \"forgotten.\"\n */\nexport const UNCATEGORIZED_TOKEN_TYPES: ReadonlySet<string> = new Set([\n\t\"WS\",\n\t\"NEWLINE\",\n\t\"EOF\",\n\t\"BACKTICK_OPEN\",\n\t\"INLINE_SOLVE_START\",\n\t\"COMMENT\",\n\t// A mid-line `#tag` reaches the highlight stream like COMMENT but has no\n\t// evaluation role of its own (it is stripped or folded into an aggregate),\n\t// so it is deliberately unstyled rather than categorised.\n\t\"TAG\",\n]);\n\n/**\n * Runtime registry for package-contributed categories (e.g. a plugin's\n * custom token types). Overrides/extends the static table above, never\n * replaces it, so a package can't accidentally break core highlighting.\n * Register/unregister symmetry mirrors this codebase's other pluggable\n * registries (e.g. sharedOpRegistry). See ExpressionEngine.registerPackage\n * / unregisterPackage, which call these on behalf of IEnginePackage.tokenCategories.\n */\nconst pluginCategories = new Map<string, TokenCategory>();\n\n/**\n * Map a token type to a highlighting category.\n *\n * @param tokenType - Token type a package registered.\n * @param category - Category deciding how an editor colours it.\n */\nexport function registerTokenCategory(tokenType: string, category: TokenCategory): void {\n\tpluginCategories.set(tokenType, category);\n}\n\n/**\n * Remove a token type's highlighting category.\n *\n * @param tokenType - Token type to forget. Unknown types are ignored.\n */\nexport function unregisterTokenCategory(tokenType: string): void {\n\tpluginCategories.delete(tokenType);\n}\n\n/**\n * Resolve a token type to its semantic category, checking plugin-contributed\n * categories first (so a plugin could theoretically re-categorize a builtin\n * token type, though in practice plugins only ever add categories for their\n * own new types).\n *\n * @returns The category, or `undefined` if the token type has no category\n * the signal to a UI adapter that this token should render unstyled.\n */\nexport function getTokenCategory(tokenType: string): TokenCategory | undefined {\n\treturn pluginCategories.get(tokenType) ?? TOKEN_CATEGORY_MAP[tokenType];\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import {d}from'./chunk-JPFCXLJV.js';import {b}from'./chunk-G7TBEQRQ.js';import {a}from'./chunk-62LMTO4F.js';import {a as a$1}from'./chunk-TRBXW6HW.js';var u=(s=>(s.Main="main",s.Inline="inline",s.String="string",s))(u||{});var l=class{constructor(e="en",t){this.currentState="main";this.hasPeeked=false;this.tokens=[];this.tokenIdx=0;this.expressionLexer=new b(e,t);}reset(e,t){let s=t??"main";if(this.currentState=s,this.hasPeeked=false,this.peekedToken=void 0,s==="main"){if(this.expressionLexer.classifyLine(e).skip){this.tokens=[],this.tokenIdx=0;return}this.expressionLexer.reset(e),this.tokens=this.expressionLexer.tokenizeAll(),this.tokenIdx=0;}else this.expressionLexer.reset(e),this.tokens=this.expressionLexer.tokenizeAll(),this.tokenIdx=0;}classifyLine(e){return this.expressionLexer.classifyLine(e)}findInlineSolves(e){return this.expressionLexer.findInlineSolves(e)}getKeywords(){return this.expressionLexer.getKeywords()}next(){if(this.hasPeeked)return this.hasPeeked=false,this.peekedToken;if(this.tokenIdx<this.tokens.length)return this.tokens[this.tokenIdx++]}peek(){return this.hasPeeked?this.peekedToken:(this.peekedToken=this.next(),this.hasPeeked=true,this.peekedToken)}[Symbol.iterator](){return this.tokens[Symbol.iterator]()}registerVocabulary(e){this.expressionLexer.registerVocabulary(e);}unregisterVocabulary(e){this.expressionLexer.unregisterVocabulary(e);}resetExpression(e){this.currentState="main",this.hasPeeked=false,this.peekedToken=void 0,this.expressionLexer.reset(e),this.tokens=this.expressionLexer.tokenizeAll(),this.tokenIdx=0;}scanDocument(e){return this.expressionLexer.scanDocument(e)}getState(){return this.currentState}setState(e){this.currentState=e;}getHighlightTokens(e){let t=this.expressionLexer.classifyLine(e);return t.skip&&e.startsWith("> ")?this.collectHighlightTokens(e.slice(2)):t.skip?[]:this.collectHighlightTokens(e)}getHighlightTokenObjects(e){let t=this.expressionLexer.classifyLine(e);return t.skip&&e.startsWith("> ")?this.collectTokenObjects(e.slice(2)):t.skip?[]:this.collectTokenObjects(e)}collectTokenObjects(e){this.resetExpression(e);let t=[];for(let s of this)s.type==="WS"||s.type==="NEWLINE"||s.type.startsWith("MD_")||s.type==="INLINE_SOLVE_START"||s.type==="BACKTICK_CLOSE"||t.push(s);return t}collectHighlightTokens(e){return this.collectTokenObjects(e).map(t=>({type:t.type,value:t.value,offset:t.offset,col:t.col,length:t.text.length,category:d(t.type)}))}},T=new l("en",void 0);var n=class{constructor(){this.classes=[];this.localeKeywordMap=null;this.localePhraseMap=null;this.unitNames=null;}register(e){this.classes.push(e);}unregister(e){this.classes=this.classes.filter(t=>t.tokenType!==e);}setLocale(e,t){this.localeKeywordMap=e,this.localePhraseMap=t??null;}setUnits(e){this.unitNames=e;}build(){let e=new Map;if(this.localeKeywordMap)for(let[r,i]of Object.entries(this.localeKeywordMap))e.set(r.toLowerCase(),i);let t=[...this.classes].sort((r,i)=>(r.priority??0)-(i.priority??0));for(let r of t)for(let i of Object.keys(r.keywords))e.set(i.toLowerCase(),r.tokenType);let s=this.buildPhraseTrie(),o=this.buildPhraseStartWords();return {keywordToType:e,phraseTrie:s,phraseStartWords:o,unitNames:this.unitNames??new Set}}buildPhraseTrie(){let e={children:new Map};if(this.localePhraseMap)for(let[t,s]of Object.entries(this.localePhraseMap))this.insertPhrase(e,t.toLowerCase(),s);for(let t of this.classes)if(t.phrases)for(let s of Object.keys(t.phrases))this.insertPhrase(e,s.toLowerCase(),t.tokenType);return e.children.size>0?e:null}insertPhrase(e,t,s){let o=t.split(" "),r=e;for(let i of o)r.children.has(i)||r.children.set(i,{children:new Map}),r=r.children.get(i);r.type||(r.type=s);}buildPhraseStartWords(){let e=new Set;if(this.localePhraseMap)for(let t of Object.keys(this.localePhraseMap)){let s=t.split(" ")[0].toLowerCase();e.add(s);}for(let t of this.classes)if(t.phrases)for(let s of Object.keys(t.phrases)){let o=s.split(" ")[0].toLowerCase();e.add(o);}return e}};var k={"to the power of":"CARET","power of":"CARET","increase by":"INCREASE_BY","decrease by":"DECREASE_BY","times by":"TIMES_BY","multiply by":"MULTIPLY_BY","multiplied by":"MULTIPLY_BY","divide by":"DIVIDE_BY"};function P(a$2="en"){let e=a(a$2),t=new n;return t.setLocale(e.keywordMap,k),t.setUnits(a$1),t.build()}export{u as a,l as b,T as c,P as d};//# sourceMappingURL=chunk-YAHGSBMC.js.map
2
+ //# sourceMappingURL=chunk-YAHGSBMC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lexer/LexerState.ts","../src/lexer/Lexer.ts","../src/lexer/TokenClassRegistry.ts","../src/lexer/tokenRegistration.ts"],"names":["LexerState","Lexer","localeCode","tokenLookup","ExpressionLexer","input","state","newState","lineText","plugin","text","classification","result","token","getTokenCategory","sharedLexer","TokenClassRegistry","tokenClass","tokenType","c","keywordMap","phraseMap","unitNames","keywordToType","keyword","sorted","a","b","tc","phraseTrie","phraseStartWords","root","phrase","words","node","word","startWords","first","BUILTIN_PHRASES","buildTokenLookup","locale","getLocale","registry","knownUnits"],"mappings":"uJAMO,IAAKA,CAAAA,CAAAA,CAAAA,CAAAA,GACXA,EAAA,IAAA,CAAO,MAAA,CACPA,EAAA,MAAA,CAAS,QAAA,CACTA,EAAA,MAAA,CAAS,QAAA,CAHEA,OAAA,EAAA,ECaL,IAAMC,EAAN,KAAY,CAkBjB,YAAYC,CAAAA,CAAa,IAAA,CAAMC,EAA2B,CAf1D,IAAA,CAAQ,aAA2B,MAA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AA,CAAK,eAAe,CAAA,CAAG,CACtD,IAAMK,CAAAA,CAAQL,CAAAA,CAAO,MAAM,GAAG,CAAA,CAAE,CAAC,CAAA,CAAE,WAAA,GACnCI,CAAAA,CAAW,GAAA,CAAIC,CAAK,EACtB,CAIF,QAAWT,CAAAA,IAAM,IAAA,CAAK,QACpB,GAAKA,CAAAA,CAAG,QACR,IAAA,IAAWI,CAAAA,IAAU,OAAO,IAAA,CAAKJ,CAAAA,CAAG,OAAO,CAAA,CAAG,CAC5C,IAAMS,CAAAA,CAAQL,CAAAA,CAAO,MAAM,GAAG,CAAA,CAAE,CAAC,CAAA,CAAE,WAAA,GACnCI,CAAAA,CAAW,GAAA,CAAIC,CAAK,EACtB,CAGF,OAAOD,CACT,CACF,EClOA,IAAME,CAAAA,CAA0C,CAC9C,iBAAA,CAAmB,OAAA,CACnB,WAAY,OAAA,CACZ,aAAA,CAAe,cACf,aAAA,CAAe,aAAA,CACf,WAAY,UAAA,CACZ,aAAA,CAAe,cACf,eAAA,CAAiB,aAAA,CACjB,YAAa,WACf,CAAA,CAiBO,SAASC,CAAAA,CAAiBrC,GAAAA,CAAa,KAAmB,CAC/D,IAAMsC,EAAkBC,CAAAA,CAAUvC,GAAU,EACtCwC,CAAAA,CAAW,IAAI1B,EAGrB,OAAA0B,CAAAA,CAAS,UAAUF,CAAAA,CAAO,UAAA,CAAYF,CAAe,CAAA,CAGrDI,CAAAA,CAAS,SAASC,GAAU,CAAA,CAGrBD,CAAAA,CAAS,KAAA,EAClB","file":"chunk-YAHGSBMC.js","sourcesContent":["/**\n * Lexer state machine modes.\n * - Main: document-level scanning with markdown classification\n * - Inline: expression embedded in markdown inline solve (`s\\`...\\``)\n * - String: inside a double-quoted string literal\n */\nexport enum LexerState {\n\tMain = \"main\",\n\tInline = \"inline\",\n\tString = \"string\",\n}\n","import { ExpressionLexer, LineClassification, LexerVocabulary, type ScanLineResult } from \"./ExpressionLexer\";\nimport { Token } from \"@solve-js/lexer/Token\";\nimport { LexerState } from \"@solve-js/lexer/LexerState\";\nimport { getTokenCategory } from \"@solve-js/language/TokenCategoryMap\";\nimport type { TokenCategory } from \"@solve-js/language/TokenCategory\";\nimport type { TokenLookup } from \"@solve-js/lexer/TokenClassRegistry\";\n\n/**\n * Public tokenizer wrapper around {@link ExpressionLexer}.\n *\n * `ExpressionLexer` does the actual character-by-character scanning;\n * `Lexer` adds a materialized-token-array streaming interface\n * (`next()`/`peek()`) plus line-classification state (`reset()`) so\n * callers can iterate a line's tokens without re-scanning on each peek.\n *\n * Each `ExpressionEngine` instance owns its own `Lexer`, and packages\n * extend it via {@link registerVocabulary} (keywords, operators, units)\n * see `IEnginePackage.lexerVocabulary`.\n */\nexport class Lexer {\n /** Expression-mode lexer (Phase A: V8-optimized, replaces moo) */\n private expressionLexer: ExpressionLexer;\n private currentState: LexerState = LexerState.Main;\n private peekedToken: Token | undefined;\n private hasPeeked = false;\n\n // Materialized token array from the last reset() call, used for\n // next()/peek() streaming access.\n private tokens: Token[] = [];\n private tokenIdx: number = 0;\n\n /**\n * @param localeCode - Locale code (e.g., \"en\", \"de\"). Defaults to \"en\".\n * @param tokenLookup - Optional TokenLookup from TokenClassRegistry.\n * When provided, configures ExpressionLexer to use registry-built\n * keyword/unit/phrase lookups instead of internal instance maps.\n */\n constructor(localeCode = \"en\", tokenLookup?: TokenLookup) {\n // Pass the lookup directly to ExpressionLexer's constructor, it's an\n // instance field now, not a static. Each Lexer instance gets its own\n // isolated lookup, preventing cross-instance corruption.\n this.expressionLexer = new ExpressionLexer(localeCode, tokenLookup);\n }\n\n reset(input: string, state?: LexerState): void {\n const newState = state ?? LexerState.Main;\n this.currentState = newState;\n this.hasPeeked = false;\n this.peekedToken = undefined;\n\n // Phase B: Main state classifies the line with the markdown scanner.\n // Skip lines (headings, fences, HRs, etc.) produce empty token arrays.\n // Expression lines and lines with inline solves are tokenized normally.\n if (newState === LexerState.Main) {\n const classification = this.expressionLexer.classifyLine(input);\n if (classification.skip) {\n this.tokens = [];\n this.tokenIdx = 0;\n return;\n }\n // Expression line or markdown line with inline solves, tokenize.\n this.expressionLexer.reset(input);\n this.tokens = this.expressionLexer.tokenizeAll();\n this.tokenIdx = 0;\n } else {\n // Non-main states (Inline, String), expression tokenization.\n this.expressionLexer.reset(input);\n this.tokens = this.expressionLexer.tokenizeAll();\n this.tokenIdx = 0;\n }\n }\n\n /**\n * Classify a single line of markdown text (Phase B).\n * Delegates to the ExpressionLexer's character-by-character scanner.\n */\n classifyLine(lineText: string): LineClassification {\n return this.expressionLexer.classifyLine(lineText);\n }\n\n /**\n * Find all inline solve markers in a line (Phase B).\n * Delegates to the ExpressionLexer's character-by-character scanner.\n */\n findInlineSolves(lineText: string) {\n return this.expressionLexer.findInlineSolves(lineText);\n }\n\n /**\n * Every keyword this lexer currently recognizes (locale + plugin-contributed),\n * mapped to the token type it lexes to. Delegates to the ExpressionLexer.\n */\n getKeywords(): Record<string, string> {\n return this.expressionLexer.getKeywords();\n }\n\n next(): Token | undefined {\n if (this.hasPeeked) {\n this.hasPeeked = false;\n return this.peekedToken;\n }\n // Materialized token array (ExpressionLexer path).\n if (this.tokenIdx < this.tokens.length) {\n return this.tokens[this.tokenIdx++];\n }\n return undefined;\n }\n\n peek(): Token | undefined {\n if (this.hasPeeked) return this.peekedToken;\n this.peekedToken = this.next();\n this.hasPeeked = true;\n return this.peekedToken;\n }\n\n [Symbol.iterator](): Iterator<Token> {\n return this.tokens[Symbol.iterator]();\n }\n\n /**\n * Register a plugin to extend the lexer with custom tokens.\n * Delegates to the underlying ExpressionLexer.\n *\n * @see LexerVocabulary for the supported extension points.\n */\n registerVocabulary(plugin: LexerVocabulary): void {\n this.expressionLexer.registerVocabulary(plugin);\n }\n\n /**\n * Unregister a plugin, removing its custom tokens from the lexer.\n * Delegates to the underlying ExpressionLexer.\n */\n unregisterVocabulary(plugin: LexerVocabulary): void {\n this.expressionLexer.unregisterVocabulary(plugin);\n }\n\n /**\n * Reset the lexer for expression-only text, skips the classifyLine()\n * overhead in reset() for callers that already know the input is an\n * evaluable expression (e.g., after isEmptyLine() confirmed non-skip).\n */\n resetExpression(input: string): void {\n this.currentState = LexerState.Main;\n this.hasPeeked = false;\n this.peekedToken = undefined;\n this.expressionLexer.reset(input);\n this.tokens = this.expressionLexer.tokenizeAll();\n this.tokenIdx = 0;\n }\n\n /**\n * Scan a full document in one pass, classifying each line and\n * tokenizing non-skipped lines. Delegates to ExpressionLexer.\n *\n * @returns ScanLineResult[], one per line, with classification + tokens.\n */\n scanDocument(text: string): ScanLineResult[] {\n return this.expressionLexer.scanDocument(text);\n }\n\n getState(): LexerState {\n return this.currentState;\n }\n\n setState(state: LexerState): void {\n this.currentState = state;\n }\n\n getHighlightTokens(lineText: string): {type: string; value: string; offset: number; col: number; length: number; category: TokenCategory | undefined}[] {\n const classification = this.expressionLexer.classifyLine(lineText);\n\n // For blockquote lines, strip the \"> \" prefix and tokenize the expression content.\n // This lets expressions inside blockquotes (e.g., \"> 1 + 2\") get syntax highlighted\n // while pure structural lines (headings, code fences) remain unhighlighted.\n if (classification.skip && lineText.startsWith(\"> \")) {\n return this.collectHighlightTokens(lineText.slice(2));\n }\n\n if (classification.skip) {\n return [];\n }\n\n return this.collectHighlightTokens(lineText);\n }\n\n /**\n * The same tokens {@link getHighlightTokens} reduces, before reduction.\n *\n * Exists because normalization operates on tokens, not on the flattened\n * shape, and a consumer that wants phrase-fused highlighting has to run the\n * normalizer between the two. See `LanguageService.getSemanticTokens`.\n *\n * @param lineText - One line of source.\n * @returns Every token on the line that is worth painting, unreduced.\n */\n getHighlightTokenObjects(lineText: string): Token[] {\n const classification = this.expressionLexer.classifyLine(lineText);\n if (classification.skip && lineText.startsWith(\"> \")) {\n return this.collectTokenObjects(lineText.slice(2));\n }\n if (classification.skip) return [];\n return this.collectTokenObjects(lineText);\n }\n\n private collectTokenObjects(lineText: string): Token[] {\n this.resetExpression(lineText);\n const result: Token[] = [];\n for (const token of this) {\n if (token.type === \"WS\" || token.type === \"NEWLINE\") continue;\n if (token.type.startsWith(\"MD_\")) continue;\n if (token.type === \"INLINE_SOLVE_START\" || token.type === \"BACKTICK_CLOSE\") continue;\n result.push(token);\n }\n return result;\n }\n\n private collectHighlightTokens(lineText: string): {type: string; value: string; offset: number; col: number; length: number; category: TokenCategory | undefined}[] {\n return this.collectTokenObjects(lineText).map(token => ({\n type: token.type,\n value: token.value,\n offset: token.offset,\n col: token.col,\n // `text`, not `value`: this is a span into the source, and the two\n // differ for a string literal, whose value is the payload while its\n // text still carries the quote characters the reader typed.\n length: token.text.length,\n category: getTokenCategory(token.type),\n }));\n }\n}\n\n/**\n * A lexer for operations that do not depend on registered vocabulary.\n *\n * Line classification and inline-solve detection read characters looking for\n * headings, comment markers, fences and backtick spans, and never consult the\n * keyword, unit or operator tables. Every lexer therefore returns the same\n * answer, so the callers that have no engine to ask can use this one. Checked\n * by `__tests__/lexer/LineClassificationIsVocabularyIndependent.spec.ts`.\n *\n * Do not tokenize with this. An engine's own lexer carries the vocabulary its\n * packages registered; this one carries none.\n */\nexport const sharedLexer = new Lexer(\"en\", undefined);","/**\n * TokenClass, Plugin-extensible keyword registration for the Lexer.\n *\n * Providers call `registry.register(tokenClass)` to teach the lexer about\n * their keywords. The registry merges locale keywords, provider keywords,\n * phrase mappings, and unit names into an optimized TokenLookup structure\n * consumed by the Lexer.\n *\n * @example\n * registry.register({\n * tokenType: 'CARET',\n * keywords: {},\n * phrases: { 'to the power of': true, 'power of': true },\n * priority: 10,\n * description: 'Exponentiation operators (x^y)',\n * });\n */\nexport interface TokenClass {\n /** The token type string produced by the lexer (e.g., \"FUNC\", \"PI\", \"CARET\").\n * Must match a token type that a ParseletRegistry has a parselet for. */\n tokenType: string;\n\n /** Single-word keywords (case-insensitive). The lexer lowercases input\n * before lookup, so these should be lowercase. Example:\n * { sqrt: true, abs: true, sin: true, cos: true } for tokenType \"FUNC\" */\n keywords: Record<string, boolean>;\n\n /** Multi-word phrases (case-insensitive). Matched by the built-in PhraseMatcher\n * via the phrase trie. Example:\n * { \"to the power of\": true, \"power of\": true } for tokenType \"CARET\" */\n phrases?: Record<string, boolean>;\n\n /** Priority for conflict resolution. When two TokenClasses register\n * the same keyword, the higher-priority class wins. Locale keywords\n * have priority 0 (set via setLocale). Providers should use\n * priority >= 10 to override locale defaults. Default: 0 */\n priority?: number;\n\n /** Human-readable description for debugging and introspection */\n description?: string;\n}\n\n// ── Phrase Trie ──────────────────────────────────────────────────────────────\n\n/** Trie node for multi-word phrase matching. */\nexport interface PhraseNode {\n /** Complete phrase token type (null = intermediate node) */\n type?: string;\n children: Map<string, PhraseNode>;\n}\n\n// ── TokenLookup, Optimized lookup structure for the Lexer ──────────────────\n\n/**\n * The optimized lookup structure built by TokenClassRegistry.build().\n * Consumed by the Lexer for O(1) keyword → token type lookups and\n * O(word-count) phrase matching.\n */\nexport interface TokenLookup {\n /** Lowercase keyword → token type. O(1) Map lookup. */\n keywordToType: Map<string, string>;\n\n /** Phrase trie for multi-word matching. Root node with children maps.\n * Null if no phrases registered. */\n phraseTrie: PhraseNode | null;\n\n /** Set of lowercase first-words of all registered phrases.\n * Used by the lexer to emit IDENT (not a phrase keyword) for words\n * that start multi-word phrases, deferring to the PhraseMatcher.\n *\n * Example: \"to\" is in phraseStartWords because \"to the power of\" is a phrase.\n * When the lexer sees \"to\", it emits IDENT and lets the phrase matcher\n * combine \"to the power of\" into a single CARET token.\n *\n * This prevents plugins from accidentally overriding phrase-start words.\n */\n phraseStartWords: Set<string>;\n\n /** Case-sensitive unit names for UNIT fallback after keyword lookup fails. */\n unitNames: ReadonlySet<string>;\n}\n\n// ── TokenClassRegistry ───────────────────────────────────────────────────────\n\n/**\n * Central registry for keyword→token-type mappings.\n *\n * Providers register TokenClasses; locales provide keyword maps;\n * units provide a name set. `build()` merges all sources into an\n * optimized TokenLookup consumed by the Lexer.\n *\n * Merge order (later overrides earlier):\n * 1. Locale keywords (priority 0)\n * 2. Provider keywords (sorted by priority ascending, higher priority wins)\n *\n * Unit names are stored separately (checked AFTER keyword lookup fails).\n * Phrases are stored in a trie for O(phrase-length) matching.\n */\nexport class TokenClassRegistry {\n private classes: TokenClass[] = [];\n private localeKeywordMap: Record<string, string> | null = null;\n private localePhraseMap: Record<string, string> | null = null;\n private unitNames: ReadonlySet<string> | null = null;\n\n /**\n * Register a provider's TokenClass. Must be called BEFORE build().\n * Can be called multiple times to add more entries.\n *\n * Built-in token types CANNOT be overridden, throws a EngineError\n * if the TokenClass attempts to register a keyword that conflicts\n * with an already-registered token type.\n */\n register(tokenClass: TokenClass): void {\n this.classes.push(tokenClass);\n }\n\n /**\n * Unregister all TokenClasses for a given token type.\n * Useful for plugin unload. Requires rebuild() to take effect.\n */\n unregister(tokenType: string): void {\n this.classes = this.classes.filter(c => c.tokenType !== tokenType);\n }\n\n /**\n * Set the locale's keyword→type map and optional phrase map.\n * Called on locale change. Priority 0 (cannot override providers with higher priority).\n */\n setLocale(keywordMap: Record<string, string>, phraseMap?: Record<string, string>): void {\n this.localeKeywordMap = keywordMap;\n this.localePhraseMap = phraseMap ?? null;\n }\n\n /**\n * Set the unit name set. Called when unit list changes.\n * Units are stored separately (checked AFTER keyword lookup fails).\n *\n * Takes a ReadonlySet because the caller's set is derived from the\n * conversion tables and must not be mutated; this class only ever reads it.\n */\n setUnits(unitNames: ReadonlySet<string>): void {\n this.unitNames = unitNames;\n }\n\n /**\n * Build the optimized TokenLookup from all registered sources.\n *\n * Merge order (later overrides earlier):\n * 1. Locale keywords (priority 0)\n * 2. Provider classes (sorted by priority ascending)\n *\n * Returns a frozen TokenLookup that the Lexer consumes.\n * Call build() again after register()/setLocale()/setUnits() changes.\n */\n build(): TokenLookup {\n const keywordToType = new Map<string, string>();\n\n // Layer 1: Locale keywords (priority 0, lowest)\n if (this.localeKeywordMap) {\n for (const [keyword, tokenType] of Object.entries(this.localeKeywordMap)) {\n keywordToType.set(keyword.toLowerCase(), tokenType);\n }\n }\n\n // Layer 2: Provider keywords (sorted by priority ascending, higher wins)\n const sorted = [...this.classes].sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));\n for (const tc of sorted) {\n for (const keyword of Object.keys(tc.keywords)) {\n keywordToType.set(keyword.toLowerCase(), tc.tokenType);\n }\n }\n\n // Build phrase trie from locale + provider phrases\n const phraseTrie = this.buildPhraseTrie();\n\n // Build phraseStartWords set (first word of every phrase)\n const phraseStartWords = this.buildPhraseStartWords();\n\n return {\n keywordToType,\n phraseTrie,\n phraseStartWords,\n unitNames: this.unitNames ?? new Set(),\n };\n }\n\n // ── Private helpers ─────────────────────────────────────────────────────\n\n private buildPhraseTrie(): PhraseNode | null {\n const root: PhraseNode = { children: new Map() };\n\n // Layer 1: Locale phrases\n if (this.localePhraseMap) {\n for (const [phrase, tokenType] of Object.entries(this.localePhraseMap)) {\n this.insertPhrase(root, phrase.toLowerCase(), tokenType);\n }\n }\n\n // Layer 2: Provider phrases\n for (const tc of this.classes) {\n if (!tc.phrases) continue;\n for (const phrase of Object.keys(tc.phrases)) {\n this.insertPhrase(root, phrase.toLowerCase(), tc.tokenType);\n }\n }\n\n return root.children.size > 0 ? root : null;\n }\n\n private insertPhrase(root: PhraseNode, phrase: string, tokenType: string): void {\n const words = phrase.split(' ');\n let node = root;\n for (const word of words) {\n if (!node.children.has(word)) {\n node.children.set(word, { children: new Map() });\n }\n node = node.children.get(word)!;\n }\n // Only set type if not already set, first-registered (locale) wins\n if (!node.type) {\n node.type = tokenType;\n }\n }\n\n private buildPhraseStartWords(): Set<string> {\n const startWords = new Set<string>();\n\n // Locale phrase first words\n if (this.localePhraseMap) {\n for (const phrase of Object.keys(this.localePhraseMap)) {\n const first = phrase.split(' ')[0].toLowerCase();\n startWords.add(first);\n }\n }\n\n // Provider phrase first words\n for (const tc of this.classes) {\n if (!tc.phrases) continue;\n for (const phrase of Object.keys(tc.phrases)) {\n const first = phrase.split(' ')[0].toLowerCase();\n startWords.add(first);\n }\n }\n\n return startWords;\n }\n}","/**\n * tokenRegistration.ts, Bootstrap for building TokenLookup from locale, units, and phrases.\n *\n * This module centralizes the assembly of the TokenLookup consumed by ExpressionLexer.\n * It merges:\n * 1. Locale keywords (from ILocale.keywordMap)\n * 2. Built-in phrase patterns (to the power of, increase by, etc.)\n * 3. Known unit names (from units.ts)\n *\n * The resulting TokenLookup is frozen and passed to ExpressionLexer.configuredLookup\n * at construction time, enabling data-driven keyword/unit/phrase resolution.\n */\nimport { TokenClassRegistry } from '@solve-js/lexer/TokenClassRegistry';\nimport type { TokenLookup } from '@solve-js/lexer/TokenClassRegistry';\nimport { getLocale, type ILocale } from '@solve-js/constants/locales';\nimport { knownUnits } from '@solve-js/lexer/units';\n\n// ── Built-in phrase map ───────────────────────────────────────────────────\n// These are the multi-word expressions handled as compound tokens.\n// Matched by the PhraseMatcher (trie-based) in ExpressionLexer.tryMatchPhrase().\nconst BUILTIN_PHRASES: Record<string, string> = {\n 'to the power of': 'CARET',\n 'power of': 'CARET',\n 'increase by': 'INCREASE_BY',\n 'decrease by': 'DECREASE_BY',\n 'times by': 'TIMES_BY',\n 'multiply by': 'MULTIPLY_BY',\n 'multiplied by': 'MULTIPLY_BY',\n 'divide by': 'DIVIDE_BY',\n};\n\n/**\n * Build a TokenLookup from locale keywords, known units, and built-in phrases.\n *\n * Merge order (later overrides earlier):\n * 1. Locale keywords (priority 0, lowest, can be overridden by providers)\n * 2. Built-in phrases (via locale phraseMap)\n * 3. Known units (checked AFTER keyword lookup fails, via unitNames set)\n *\n * The resulting TokenLookup replaces the internal keyword map, unit set,\n * phrase trie, and phraseStartWords in ExpressionLexer when set via\n * ExpressionLexer.configuredLookup.\n *\n * @param localeCode - The locale code (e.g., \"en\", \"de\"). Defaults to \"en\".\n * @returns A frozen TokenLookup ready for consumption by the lexer.\n */\nexport function buildTokenLookup(localeCode = 'en'): TokenLookup {\n const locale: ILocale = getLocale(localeCode);\n const registry = new TokenClassRegistry();\n\n // Layer 1: Locale keywords (priority 0, lowest)\n registry.setLocale(locale.keywordMap, BUILTIN_PHRASES);\n\n // Layer 2: Known units (checked after keyword lookup)\n registry.setUnits(knownUnits);\n\n // Build and return the lookup\n return registry.build();\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import {a}from'./chunk-HFKDWQUL.js';import {c}from'./chunk-MPB7KUN5.js';var T=new Set(["AED","AFN","ALL","AMD","ANG","AOA","ARS","AUD","AWG","AZN","BAM","BBD","BDT","BGN","BHD","BIF","BMD","BND","BOB","BOV","BRL","BSD","BTN","BWP","BYN","BZD","CAD","CDF","CHE","CHF","CHW","CLF","CLP","CNY","COP","COU","CRC","CUP","CVE","CZK","DJF","DKK","DOP","DZD","EGP","ERN","ETB","EUR","FJD","FKP","GBP","GEL","GHS","GIP","GMD","GNF","GTQ","GYD","HKD","HNL","HTG","HUF","IDR","ILS","INR","IQD","IRR","ISK","JMD","JOD","JPY","KES","KGS","KHR","KMF","KPW","KRW","KWD","KYD","KZT","LAK","LBP","LKR","LRD","LSL","LYD","MAD","MDL","MGA","MKD","MMK","MNT","MOP","MRU","MUR","MVR","MWK","MXN","MXV","MYR","MZN","NAD","NGN","NIO","NOK","NPR","NZD","OMR","PAB","PEN","PGK","PHP","PKR","PLN","PYG","QAR","RON","RSD","RUB","RWF","SAR","SBD","SCR","SDG","SEK","SGD","SHP","SLE","SOS","SRD","SSP","STN","SVC","SYP","SZL","THB","TJS","TMT","TND","TOP","TRY","TTD","TWD","TZS","UAH","UGX","USD","USN","UYI","UYU","UYW","UZS","VED","VES","VND","VUV","WST","XAF","XCD","XCG","XOF","XPF","YER","ZAR","ZMW","ZWG"]);function N(O){return T.has(O.toUpperCase())}var d={API_ERROR:"CURRENCY_API_ERROR",UNKNOWN_CODE:"UNKNOWN_CURRENCY_CODE",CRYPTO_API_ERROR:"CRYPTO_PRICE_API_ERROR"},o=class o{constructor(){this.baseTables=new Map;}isCryptoCode(t){return t.toUpperCase()in o.CRYPTO_IDS}async getRate(t,e,r){let n=t.toUpperCase(),s=e.toUpperCase();if(this.isCryptoCode(n)||this.isCryptoCode(s))return this.getCryptoRate(n,s,r);let{signal:C,cleanup:l}=a(r,o.FETCH_TIMEOUT_MS,"Currency API fetch");try{let a=await fetch(`https://api.frankfurter.dev/v2/rates?base=${n}`,{signal:C});if(!a.ok)throw c.external(d.API_ERROR,`Currency API returned ${a.status}`,{status:a.status});let i=await a.json(),c$1=Array.isArray(i)?Object.fromEntries(i.filter(R=>{if(typeof R!="object"||R===null)return !1;let u=R;return typeof u.quote=="string"&&typeof u.rate=="number"}).map(R=>[R.quote.toUpperCase(),R.rate])):i.rates??{};if(c$1[s]===void 0)throw c.validation(d.UNKNOWN_CODE,`Unknown currency: ${s}`,{code:s});return this.baseTables.set(n,{fetchedAt:Date.now(),rates:{...c$1,[n]:1}}),c$1[s]}finally{l();}}async getCryptoRate(t,e,r){let{signal:n,cleanup:s}=a(r,o.FETCH_TIMEOUT_MS,"Crypto price API fetch");try{let C=this.isCryptoCode(t),l=this.isCryptoCode(e),a;if(C&&l){let i=o.CRYPTO_IDS[t],c$1=o.CRYPTO_IDS[e],R=await this.fetchCoinGeckoPrices([i,c$1],"usd",n),u=R[i]?.usd,P=R[c$1]?.usd;if(typeof u!="number")throw c.validation(d.UNKNOWN_CODE,`Unknown currency: ${t}`,{code:t});if(typeof P!="number")throw c.validation(d.UNKNOWN_CODE,`Unknown currency: ${e}`,{code:e});a=u/P;}else if(C){let i=o.CRYPTO_IDS[t],c$1=e.toLowerCase(),u=(await this.fetchCoinGeckoPrices([i],c$1,n))[i]?.[c$1];if(typeof u!="number")throw c.validation(d.UNKNOWN_CODE,`Unknown currency: ${e}`,{code:e});a=u;}else {let i=o.CRYPTO_IDS[e],c$1=t.toLowerCase(),u=(await this.fetchCoinGeckoPrices([i],c$1,n))[i]?.[c$1];if(typeof u!="number")throw c.validation(d.UNKNOWN_CODE,`Unknown currency: ${t}`,{code:t});a=1/u;}return this.baseTables.set(t,{fetchedAt:Date.now(),rates:{[t]:1,[e]:a}}),a}finally{s();}}async fetchCoinGeckoPrices(t,e,r){let n=`https://api.coingecko.com/api/v3/simple/price?ids=${t.join(",")}&vs_currencies=${e}`,s=await fetch(n,{signal:r});if(!s.ok)throw c.external(d.CRYPTO_API_ERROR,`Crypto price API returned ${s.status}`,{status:s.status});return s.json()}primeRates(t,e){let r=t.toUpperCase();this.baseTables.set(r,{fetchedAt:Date.now(),rates:{...e,[r]:1}});}clearRates(){this.baseTables.clear();}getRateSync(t,e){let r=t.toUpperCase(),n=e.toUpperCase();if(r===n)return 1;let s=Date.now();for(let C of this.baseTables.values()){if(s-C.fetchedAt>o.RATE_FRESHNESS_MS)continue;let l=C.rates[r],a=C.rates[n];if(l&&a)return a/l}return null}async convert(t,e,r){let n=await this.getRate(e,r);return t*n}getAllRates(){let t=Date.now(),e={},r=false;for(let[n,s]of this.baseTables)if(!(t-s.fetchedAt>o.RATE_FRESHNESS_MS))for(let[C,l]of Object.entries(s.rates))e[`${n}:${C}`]=l,r=true;return r?e:null}hasRates(){return this.getAllRates()!==null}convertSync(t,e,r){let n=this.getRateSync(e,r);return n===null?null:t*n}isCurrency(t){return N(t)||this.isCryptoCode(t)}};o.RATE_FRESHNESS_MS=900*1e3,o.CRYPTO_IDS={BTC:"bitcoin",ETH:"ethereum",SOL:"solana",XRP:"ripple",ADA:"cardano",DOGE:"dogecoin",DOT:"polkadot"},o.FETCH_TIMEOUT_MS=1e4;var f=o,b=new f,h=b;
2
+ export{f as a,b,h as c};//# sourceMappingURL=chunk-YAYBVVG2.js.map
3
+ //# sourceMappingURL=chunk-YAYBVVG2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/uom/Iso4217.ts","../src/uom/CurrencyExchange.ts"],"names":["ISO_4217_CODES","isIso4217","code","CurrencyErrorCodes","_CurrencyExchangeService","from","to","signal","fromUpper","toUpper","fetchSignal","cleanup","createTimeoutSignal","response","ErrorFactory","data","rates","entry","candidate","fromIsCrypto","toIsCrypto","rate","fromId","toId","fromUsd","toUsd","vs","value","priceOfToInFrom","ids","vsCurrency","url","base","baseUpper","now","table","fromR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CAAI,CAAA,CAAA,EAAI9B,CAAI,CAAA,CAAE,CAAA,CAAImB,CAAAA,CAC9BkB,CAAAA,CAAM,KAGV,OAAOA,CAAAA,CAAMD,CAAAA,CAAW,IAC1B,CAKA,QAAA,EAAoB,CAClB,OAAO,IAAA,CAAK,WAAA,EAAY,GAAM,IAChC,CAMA,WAAA,CAAYX,CAAAA,CAAetB,CAAAA,CAAcC,CAAAA,CAA2B,CAClE,IAAMe,CAAAA,CAAO,IAAA,CAAK,YAAYhB,CAAAA,CAAMC,CAAE,CAAA,CACtC,OAAIe,CAAAA,GAAS,IAAA,CAAa,KACnBM,CAAAA,CAAQN,CACjB,CAmBA,UAAA,CAAWnB,CAAAA,CAAuB,CAChC,OAAOD,CAAAA,CAAUC,CAAI,CAAA,EAAK,IAAA,CAAK,YAAA,CAAaA,CAAI,CAClD,CACF,CAAA,CA/SaE,CAAAA,CAiBa,iBAAA,CAAoB,GAAA,CAAU,GAAA,CAjB3CA,EA4Ba,UAAA,CAAqC,CAC3D,GAAA,CAAK,SAAA,CAAW,GAAA,CAAK,UAAA,CAAY,IAAK,QAAA,CAAU,GAAA,CAAK,QAAA,CACrD,GAAA,CAAK,SAAA,CAAW,IAAA,CAAM,WAAY,GAAA,CAAK,UACzC,CAAA,CA/BWA,CAAAA,CAkDa,gBAAA,CAAmB,GAAA,CAlDtC,IAAMoC,CAAAA,CAANpC,CAAAA,CAsTMqC,CAAAA,CAA0B,IAAID,CAAAA,CAI9BE,CAAAA,CAAyBD","file":"chunk-YAYBVVG2.js","sourcesContent":["/**\n * Every active ISO 4217 currency code.\n *\n * This exists because `CurrencyExchange.isCurrency()` used to hold a\n * hand-written list of forty-six codes, and a code missing from it did not\n * error: `$100 in UAH` returned the original hundred dollars, unconverted, as\n * though the rate were 1. A wrong answer, not a missing feature.\n *\n * The list is the ISO 4217 active set, so \"is this a currency\" is answered by\n * the standard rather than by whichever codes happened to get added. Whether a\n * *rate* is available for one is a separate question, answered at resolution\n * time by whatever the exchange provider supports; conflating the two is what\n * produced the silent failure.\n *\n * Deliberately excluded:\n * - The historical/withdrawn codes (DEM, FRF, and the rest). They are not\n * active, no provider quotes them, and recognising them would only move the\n * failure later.\n * - The X-series non-currencies: XAU/XAG/XPT/XPD (metals), XDR (IMF special\n * drawing rights), XTS (reserved for testing) and XXX (explicitly \"no\n * currency\"). XXX in particular must never resolve.\n *\n * Cryptocurrencies are not here either. They are not ISO 4217 and are tracked\n * separately in `CurrencyExchangeService.CRYPTO_IDS`.\n */\nexport const ISO_4217_CODES: ReadonlySet<string> = new Set([\n\t\"AED\", \"AFN\", \"ALL\", \"AMD\", \"ANG\", \"AOA\", \"ARS\", \"AUD\", \"AWG\", \"AZN\",\n\t\"BAM\", \"BBD\", \"BDT\", \"BGN\", \"BHD\", \"BIF\", \"BMD\", \"BND\", \"BOB\", \"BOV\",\n\t\"BRL\", \"BSD\", \"BTN\", \"BWP\", \"BYN\", \"BZD\",\n\t\"CAD\", \"CDF\", \"CHE\", \"CHF\", \"CHW\", \"CLF\", \"CLP\", \"CNY\", \"COP\", \"COU\",\n\t\"CRC\", \"CUP\", \"CVE\", \"CZK\",\n\t\"DJF\", \"DKK\", \"DOP\", \"DZD\",\n\t\"EGP\", \"ERN\", \"ETB\", \"EUR\",\n\t\"FJD\", \"FKP\",\n\t\"GBP\", \"GEL\", \"GHS\", \"GIP\", \"GMD\", \"GNF\", \"GTQ\", \"GYD\",\n\t\"HKD\", \"HNL\", \"HTG\", \"HUF\",\n\t\"IDR\", \"ILS\", \"INR\", \"IQD\", \"IRR\", \"ISK\",\n\t\"JMD\", \"JOD\", \"JPY\",\n\t\"KES\", \"KGS\", \"KHR\", \"KMF\", \"KPW\", \"KRW\", \"KWD\", \"KYD\", \"KZT\",\n\t\"LAK\", \"LBP\", \"LKR\", \"LRD\", \"LSL\", \"LYD\",\n\t\"MAD\", \"MDL\", \"MGA\", \"MKD\", \"MMK\", \"MNT\", \"MOP\", \"MRU\", \"MUR\", \"MVR\",\n\t\"MWK\", \"MXN\", \"MXV\", \"MYR\", \"MZN\",\n\t\"NAD\", \"NGN\", \"NIO\", \"NOK\", \"NPR\", \"NZD\",\n\t\"OMR\",\n\t\"PAB\", \"PEN\", \"PGK\", \"PHP\", \"PKR\", \"PLN\", \"PYG\",\n\t\"QAR\",\n\t\"RON\", \"RSD\", \"RUB\", \"RWF\",\n\t\"SAR\", \"SBD\", \"SCR\", \"SDG\", \"SEK\", \"SGD\", \"SHP\", \"SLE\", \"SOS\", \"SRD\",\n\t\"SSP\", \"STN\", \"SVC\", \"SYP\", \"SZL\",\n\t\"THB\", \"TJS\", \"TMT\", \"TND\", \"TOP\", \"TRY\", \"TTD\", \"TWD\", \"TZS\",\n\t\"UAH\", \"UGX\", \"USD\", \"USN\", \"UYI\", \"UYU\", \"UYW\", \"UZS\",\n\t\"VED\", \"VES\", \"VND\", \"VUV\",\n\t\"WST\",\n\t\"XAF\", \"XCD\", \"XCG\", \"XOF\", \"XPF\",\n\t\"YER\",\n\t\"ZAR\", \"ZMW\", \"ZWG\",\n]);\n\n/**\n * Whether `code` is an active ISO 4217 currency code.\n *\n * @param code - A three-letter code, in any case.\n */\nexport function isIso4217(code: string): boolean {\n\treturn ISO_4217_CODES.has(code.toUpperCase());\n}\n","/**\n * Production-grade currency exchange service with scalable architecture\n * Integrates with DataQueryService for worker-based execution\n */\n\nimport { isIso4217 } from \"@solve-js/uom/Iso4217\";\nimport { createTimeoutSignal } from \"@solve-js/utilities/TimeoutSignal\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Error codes for this service. Co-located rather than unioned into\n * `errors/ErrorCode.ts`'s core catalog (that catalog is scoped to the\n * parser/VM/engine/errors/config/lexer layers, not yet the ~17 domain\n * packages. See that file's module doc for the intended per-package\n * pattern this follows).\n */\nexport const CurrencyErrorCodes = {\n /** Frankfurter's rates endpoint returned a non-OK HTTP status. */\n API_ERROR: \"CURRENCY_API_ERROR\",\n /** A requested currency/crypto code isn't in the fetched rate table, an unrecognized code, not an API failure. */\n UNKNOWN_CODE: \"UNKNOWN_CURRENCY_CODE\",\n /** CoinGecko's simple-price endpoint returned a non-OK HTTP status. */\n CRYPTO_API_ERROR: \"CRYPTO_PRICE_API_ERROR\",\n} as const;\n\n// ============================================================================\n// CURRENCY EXCHANGE SERVICE\n// ============================================================================\n\n/**\n * Caches exchange rates fetched from an external source.\n *\n * Rates are global market data rather than per-engine configuration, which is\n * why one instance is shared. Two engines with private copies would fetch the\n * same endpoint twice and could disagree about one pair at one moment. See\n * `engine/EngineContext.ts`.\n */\nexport class CurrencyExchangeService {\n /**\n * Live rate tables cached from successful getRate() fetches, keyed by\n * uppercase base currency. Each table holds every rate the API returned\n * for that base (plus the base itself at 1), so any pair whose two codes\n * appear in one fresh table can be served synchronously, including\n * cross pairs via triangulation (EUR→GBP through a USD-base table).\n * Stale tables are ignored, not evicted; the next successful fetch for\n * the same base overwrites them.\n */\n private baseTables: Map<string, { fetchedAt: number; rates: Record<string, number> }> = new Map();\n\n /**\n * How long a fetched rate may be served synchronously by getRateSync().\n * Beyond this window callers fall through to the async path (expression\n * shows Pending until the fetch lands).\n */\n private static readonly RATE_FRESHNESS_MS = 15 * 60 * 1000;\n\n /**\n * Ticker → CoinGecko coin id, for the cryptocurrencies `isCurrency()`\n * recognizes. Frankfurter (the fiat rate source below) is ECB reference\n * rates only and has no concept of BTC/ETH/etc, routing a crypto code\n * through it as `base=BTC` fails outright, which is why crypto pairs\n * previously never resolved (see CurrencyAsyncResolver/VM.ts's ADD\n * handling for the two bugs that let that failure pass silently instead\n * of surfacing as a real fetch).\n */\n private static readonly CRYPTO_IDS: Record<string, string> = {\n BTC: \"bitcoin\", ETH: \"ethereum\", SOL: \"solana\", XRP: \"ripple\",\n ADA: \"cardano\", DOGE: \"dogecoin\", DOT: \"polkadot\",\n };\n\n private isCryptoCode(code: string): boolean {\n return code.toUpperCase() in CurrencyExchangeService.CRYPTO_IDS;\n }\n\n constructor() {}\n\n // ------------------------------------------------------------------------\n // RATE FETCHING\n // ------------------------------------------------------------------------\n\n /**\n * Timeout (ms) for currency exchange rate fetches.\n *\n * If the frankfurter API doesn't respond within this window, the fetch\n * is aborted, preventing indefinite \"Pending\" states in the playground\n * and Obsidian plugin when the exchange rate API is unreachable.\n */\n private static readonly FETCH_TIMEOUT_MS = 10_000;\n\n /**\n * Fetch the live exchange rate for converting 1 unit of `from` into `to`.\n *\n * Routes cryptocurrency codes (see {@link CRYPTO_IDS}) to CoinGecko and\n * everything else to Frankfurter (ECB reference rates, fiat-only). On\n * success, caches the whole returned rate table for `from` so subsequent\n * lookups, including cross-pairs via triangulation, can be served\n * synchronously by {@link getRateSync} within the freshness window.\n *\n * @throws If the currency code is unrecognized or the fetch fails/times out.\n */\n async getRate(from: string, to: string, signal?: AbortSignal): Promise<number> {\n const fromUpper = from.toUpperCase();\n const toUpper = to.toUpperCase();\n\n if (this.isCryptoCode(fromUpper) || this.isCryptoCode(toUpper)) {\n return this.getCryptoRate(fromUpper, toUpper, signal);\n }\n\n // Combine the caller's optional abort signal with a hard timeout so a\n // hanging currency API never blocks re-evaluation indefinitely.\n const { signal: fetchSignal, cleanup } = createTimeoutSignal(\n signal,\n CurrencyExchangeService.FETCH_TIMEOUT_MS,\n \"Currency API fetch\",\n );\n\n try {\n const response = await fetch(`https://api.frankfurter.dev/v2/rates?base=${fromUpper}`, { signal: fetchSignal });\n if (!response.ok) throw ErrorFactory.external(CurrencyErrorCodes.API_ERROR, `Currency API returned ${response.status}`, { status: response.status });\n const data = await response.json();\n // The v2 endpoint returns a flat array of { date, base, quote, rate }\n // entries (one per target currency) rather than the classic v1 shape\n // { base, date, rates: { CODE: rate } }. Reading data.rates against\n // the real response is always undefined, so every conversion used to\n // throw \"Unknown currency\" no matter which currencies were requested.\n // Accept both shapes so a future API revision back to the object form\n // doesn't silently break this again.\n const rates: Record<string, number> = Array.isArray(data)\n ? Object.fromEntries(\n data\n .filter((entry: unknown): entry is { quote: string; rate: number } => {\n if (typeof entry !== \"object\" || entry === null) return false;\n const candidate = entry as { quote?: unknown; rate?: unknown };\n return typeof candidate.quote === \"string\" && typeof candidate.rate === \"number\";\n })\n .map((entry: { quote: string; rate: number }) => [entry.quote.toUpperCase(), entry.rate])\n )\n : (data.rates ?? {});\n if (rates[toUpper] === undefined) throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n\n // The API returns ALL rates for the base currency, cache the whole\n // table so subsequent conversions (including cross pairs via\n // triangulation) resolve synchronously within the freshness window\n // instead of going Pending again.\n this.baseTables.set(fromUpper, {\n fetchedAt: Date.now(),\n rates: { ...rates, [fromUpper]: 1 },\n });\n\n return rates[toUpper];\n } finally {\n cleanup();\n }\n }\n\n /**\n * Crypto rate fetch, routed through CoinGecko's no-auth simple-price\n * endpoint instead of Frankfurter (fiat-only, has no BTC/ETH concept).\n * Handles all three combinations, crypto→crypto, crypto→fiat\n * fiat→crypto, via prices denominated in USD (or the target fiat\n * directly, which CoinGecko's `vs_currencies` also accepts), then\n * caches the result as a same-shaped base table so getRateSync /\n * convertSync keep working unchanged for crypto pairs too.\n */\n private async getCryptoRate(fromUpper: string, toUpper: string, signal?: AbortSignal): Promise<number> {\n const { signal: fetchSignal, cleanup } = createTimeoutSignal(\n signal,\n CurrencyExchangeService.FETCH_TIMEOUT_MS,\n \"Crypto price API fetch\",\n );\n\n try {\n const fromIsCrypto = this.isCryptoCode(fromUpper);\n const toIsCrypto = this.isCryptoCode(toUpper);\n let rate: number;\n\n if (fromIsCrypto && toIsCrypto) {\n const fromId = CurrencyExchangeService.CRYPTO_IDS[fromUpper];\n const toId = CurrencyExchangeService.CRYPTO_IDS[toUpper];\n const data = await this.fetchCoinGeckoPrices([fromId, toId], \"usd\", fetchSignal);\n const fromUsd = data[fromId]?.usd;\n const toUsd = data[toId]?.usd;\n if (typeof fromUsd !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${fromUpper}`, { code: fromUpper });\n if (typeof toUsd !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n rate = fromUsd / toUsd;\n } else if (fromIsCrypto) {\n const fromId = CurrencyExchangeService.CRYPTO_IDS[fromUpper];\n const vs = toUpper.toLowerCase();\n const data = await this.fetchCoinGeckoPrices([fromId], vs, fetchSignal);\n const value = data[fromId]?.[vs];\n if (typeof value !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n rate = value;\n } else {\n const toId = CurrencyExchangeService.CRYPTO_IDS[toUpper];\n const vs = fromUpper.toLowerCase();\n const data = await this.fetchCoinGeckoPrices([toId], vs, fetchSignal);\n const priceOfToInFrom = data[toId]?.[vs];\n if (typeof priceOfToInFrom !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${fromUpper}`, { code: fromUpper });\n rate = 1 / priceOfToInFrom;\n }\n\n // Cache as a single-pair base table, same shape Frankfurter fetches\n // produce, so getRateSync/convertSync's triangulation logic doesn't\n // need to know or care which source a rate came from.\n this.baseTables.set(fromUpper, {\n fetchedAt: Date.now(),\n rates: { [fromUpper]: 1, [toUpper]: rate },\n });\n\n return rate;\n } finally {\n cleanup();\n }\n }\n\n private async fetchCoinGeckoPrices(ids: string[], vsCurrency: string, signal: AbortSignal): Promise<Record<string, Record<string, number>>> {\n const url = `https://api.coingecko.com/api/v3/simple/price?ids=${ids.join(\",\")}&vs_currencies=${vsCurrency}`;\n const response = await fetch(url, { signal });\n if (!response.ok) throw ErrorFactory.external(CurrencyErrorCodes.CRYPTO_API_ERROR, `Crypto price API returned ${response.status}`, { status: response.status });\n return response.json();\n }\n\n /**\n * Seed a base rate table without a network fetch.\n *\n * Intended for tests and for future user-provided offline rates\n * production live data always comes from {@link getRate}. Seeded rates\n * obey the same freshness window as fetched ones.\n *\n * @param base - Base currency code (e.g. \"USD\").\n * @param rates - Map of currency code → rate relative to the base.\n */\n primeRates(base: string, rates: Record<string, number>): void {\n const baseUpper = base.toUpperCase();\n this.baseTables.set(baseUpper, {\n fetchedAt: Date.now(),\n rates: { ...rates, [baseUpper]: 1 },\n });\n }\n\n /**\n * Drop every cached/primed rate table.\n *\n * Mainly for test isolation: {@link sharedCurrencyExchange} is a\n * module-level singleton, so a rate primed or fetched by one test can\n * silently leak into a later test in the same file. Also usable in\n * production if a caller ever wants to force a full re-fetch.\n */\n clearRates(): void {\n this.baseTables.clear();\n }\n\n /**\n * Synchronous rate lookup: `1` for same-currency pairs, a cached LIVE\n * rate if one was fetched within {@link RATE_FRESHNESS_MS}, otherwise\n * `null`, callers fall through to the async fetch path and the\n * expression shows Pending until real data arrives.\n *\n * There is deliberately no hardcoded fallback table: a stale made-up\n * rate presented as a real conversion is worse than a Pending state.\n */\n getRateSync(from: string, to: string): number | null {\n const fromUpper = from.toUpperCase();\n const toUpper = to.toUpperCase();\n if (fromUpper === toUpper) {\n return 1;\n }\n const now = Date.now();\n for (const table of this.baseTables.values()) {\n if (now - table.fetchedAt > CurrencyExchangeService.RATE_FRESHNESS_MS) continue;\n const fromRate = table.rates[fromUpper];\n const toRate = table.rates[toUpper];\n if (fromRate && toRate) {\n return toRate / fromRate;\n }\n }\n return null;\n }\n\n /** Convert `value` from `from` to `to` using a freshly-fetched live rate (see {@link getRate}). */\n async convert(value: number, from: string, to: string): Promise<number> {\n const rate = await this.getRate(from, to);\n return value * rate;\n }\n\n /**\n * Get all currently cached fresh rates, keyed \"FROM:TO\".\n * @returns Snapshot of fresh live rates, or null when none are cached.\n */\n getAllRates(): Record<string, number> | null {\n const now = Date.now();\n const snapshot: Record<string, number> = {};\n let any = false;\n for (const [base, table] of this.baseTables) {\n if (now - table.fetchedAt > CurrencyExchangeService.RATE_FRESHNESS_MS) continue;\n for (const [code, rate] of Object.entries(table.rates)) {\n snapshot[`${base}:${code}`] = rate;\n any = true;\n }\n }\n return any ? snapshot : null;\n }\n\n /**\n * Check whether any fresh live rates are currently cached.\n */\n hasRates(): boolean {\n return this.getAllRates() !== null;\n }\n\n /**\n * Synchronous conversion using cached rates only\n * Returns null if rate not in cache\n */\n convertSync(value: number, from: string, to: string): number | null {\n const rate = this.getRateSync(from, to);\n if (rate === null) return null;\n return value * rate;\n }\n\n // ------------------------------------------------------------------------\n // CURRENCY VALIDATION\n // ------------------------------------------------------------------------\n\n /**\n * Check whether `code` is a recognized currency code: any active ISO 4217\n * code, or one of the cryptocurrencies in {@link CRYPTO_IDS}.\n *\n * This used to be a hand-written list of forty-six codes, which meant\n * `$100 in UAH` returned an unconverted hundred dollars rather than saying\n * it could not convert. Answering from the standard rather than from\n * whichever codes happened to get added is what stops that class of bug.\n *\n * Recognising a code is not the same as having a rate for it. That is\n * answered later, by the exchange provider; conflating the two is what\n * produced the silent failure.\n */\n isCurrency(code: string): boolean {\n return isIso4217(code) || this.isCryptoCode(code);\n }\n}\n\n// ============================================================================\n// SINGLETON INSTANCE\n// ============================================================================\n\n/** The shared rate cache. See {@link CurrencyExchangeService} for why it is shared. */\nexport const currencyExchangeService = new CurrencyExchangeService();\n\n// Export for backward compatibility\n/** Alias for {@link currencyExchangeService}, kept for older imports. */\nexport const sharedCurrencyExchange = currencyExchangeService;\n\n// Default export\nexport default currencyExchangeService;\n"]}