solve-engine 1.2.0 → 2.0.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 (384) 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-2RWAXT6O.js +0 -1
  25. package/dist/chunk-4BZIYU7S.cjs +3 -0
  26. package/dist/chunk-4BZIYU7S.cjs.map +1 -0
  27. package/dist/chunk-4J7XZSZJ.cjs +5 -0
  28. package/dist/chunk-4J7XZSZJ.cjs.map +1 -0
  29. package/dist/chunk-4QVBSG6B.cjs +2 -0
  30. package/dist/chunk-4QVBSG6B.cjs.map +1 -0
  31. package/dist/chunk-5IJD5L3O.cjs +2 -0
  32. package/dist/chunk-5IJD5L3O.cjs.map +1 -0
  33. package/dist/chunk-62LMTO4F.js +2 -0
  34. package/dist/chunk-62LMTO4F.js.map +1 -0
  35. package/dist/chunk-6CY44ZPG.js +2 -0
  36. package/dist/chunk-6CY44ZPG.js.map +1 -0
  37. package/dist/chunk-6G3PMEPA.js +2 -0
  38. package/dist/chunk-6G3PMEPA.js.map +1 -0
  39. package/dist/chunk-6INX773F.cjs +2 -0
  40. package/dist/chunk-6INX773F.cjs.map +1 -0
  41. package/dist/chunk-6KFVG6UY.cjs +2 -0
  42. package/dist/{chunk-YJHY7CMN.cjs.map → chunk-6KFVG6UY.cjs.map} +1 -1
  43. package/dist/chunk-76F3LCIL.js +4 -0
  44. package/dist/chunk-76F3LCIL.js.map +1 -0
  45. package/dist/chunk-7GK3XEZF.js +2 -0
  46. package/dist/chunk-7GK3XEZF.js.map +1 -0
  47. package/dist/chunk-APN442VD.cjs +2 -0
  48. package/dist/chunk-APN442VD.cjs.map +1 -0
  49. package/dist/chunk-AXMQG5TS.cjs +2 -0
  50. package/dist/chunk-AXMQG5TS.cjs.map +1 -0
  51. package/dist/chunk-CIQOK7Q4.cjs +2 -0
  52. package/dist/chunk-CIQOK7Q4.cjs.map +1 -0
  53. package/dist/chunk-E6Z4NQAS.js +2 -0
  54. package/dist/chunk-E6Z4NQAS.js.map +1 -0
  55. package/dist/chunk-EFJCC6FJ.cjs +2 -0
  56. package/dist/chunk-EFJCC6FJ.cjs.map +1 -0
  57. package/dist/chunk-ESUN2THE.cjs +2 -0
  58. package/dist/chunk-ESUN2THE.cjs.map +1 -0
  59. package/dist/chunk-EVAOPEO4.js +2 -0
  60. package/dist/chunk-EVAOPEO4.js.map +1 -0
  61. package/dist/chunk-EYRBENHC.js +3 -0
  62. package/dist/chunk-EYRBENHC.js.map +1 -0
  63. package/dist/chunk-FDE5HWDI.cjs +2 -0
  64. package/dist/chunk-FDE5HWDI.cjs.map +1 -0
  65. package/dist/chunk-FWW3M36J.cjs +2 -0
  66. package/dist/chunk-FWW3M36J.cjs.map +1 -0
  67. package/dist/chunk-GOIQYUWV.js +2 -0
  68. package/dist/chunk-GOIQYUWV.js.map +1 -0
  69. package/dist/chunk-HFKDWQUL.js +2 -0
  70. package/dist/chunk-HFKDWQUL.js.map +1 -0
  71. package/dist/chunk-HLBYHXQD.cjs +3 -0
  72. package/dist/chunk-HLBYHXQD.cjs.map +1 -0
  73. package/dist/chunk-IANAMBJQ.cjs +2 -0
  74. package/dist/chunk-IANAMBJQ.cjs.map +1 -0
  75. package/dist/chunk-IJMNVBIS.js +2 -0
  76. package/dist/chunk-IJMNVBIS.js.map +1 -0
  77. package/dist/chunk-J4LZD4ZY.js +3 -0
  78. package/dist/chunk-J4LZD4ZY.js.map +1 -0
  79. package/dist/chunk-JAK3RAFA.cjs +2 -0
  80. package/dist/chunk-JAK3RAFA.cjs.map +1 -0
  81. package/dist/chunk-JFAJN3C2.cjs +2 -0
  82. package/dist/chunk-JFAJN3C2.cjs.map +1 -0
  83. package/dist/chunk-JPFCXLJV.js +2 -0
  84. package/dist/chunk-JPFCXLJV.js.map +1 -0
  85. package/dist/chunk-JSPKKNPQ.js +3 -0
  86. package/dist/chunk-JSPKKNPQ.js.map +1 -0
  87. package/dist/chunk-L3FPQSGN.js +2 -0
  88. package/dist/chunk-L3FPQSGN.js.map +1 -0
  89. package/dist/chunk-LR4E4A4W.cjs +2 -0
  90. package/dist/chunk-LR4E4A4W.cjs.map +1 -0
  91. package/dist/chunk-MIQBJGGR.js +2 -0
  92. package/dist/chunk-MIQBJGGR.js.map +1 -0
  93. package/dist/chunk-MPB7KUN5.js +3 -0
  94. package/dist/chunk-MPB7KUN5.js.map +1 -0
  95. package/dist/chunk-MSYX32PF.cjs +2 -0
  96. package/dist/chunk-MSYX32PF.cjs.map +1 -0
  97. package/dist/chunk-MVZUTETT.js +2 -0
  98. package/dist/chunk-MVZUTETT.js.map +1 -0
  99. package/dist/chunk-N7N7MPMK.cjs +2 -0
  100. package/dist/chunk-N7N7MPMK.cjs.map +1 -0
  101. package/dist/chunk-NGBBNL4K.cjs +1 -3
  102. package/dist/chunk-P6WPEUAJ.cjs +2 -0
  103. package/dist/chunk-P6WPEUAJ.cjs.map +1 -0
  104. package/dist/chunk-PS272DZJ.cjs +2 -0
  105. package/dist/chunk-PS272DZJ.cjs.map +1 -0
  106. package/dist/chunk-QXQE7X4S.js +2 -0
  107. package/dist/chunk-QXQE7X4S.js.map +1 -0
  108. package/dist/chunk-R2ENWQ76.js +2 -0
  109. package/dist/chunk-R2ENWQ76.js.map +1 -0
  110. package/dist/chunk-R2SZFJTT.cjs +2 -0
  111. package/dist/chunk-R2SZFJTT.cjs.map +1 -0
  112. package/dist/chunk-RAF57WYO.js +2 -0
  113. package/dist/chunk-RAF57WYO.js.map +1 -0
  114. package/dist/chunk-RSF25YSJ.js +2 -0
  115. package/dist/chunk-RSF25YSJ.js.map +1 -0
  116. package/dist/chunk-SOMGSIO4.cjs +3 -0
  117. package/dist/chunk-SOMGSIO4.cjs.map +1 -0
  118. package/dist/chunk-SUXRZWH2.cjs +3 -0
  119. package/dist/chunk-SUXRZWH2.cjs.map +1 -0
  120. package/dist/chunk-SYYE3QAX.cjs +2 -0
  121. package/dist/chunk-SYYE3QAX.cjs.map +1 -0
  122. package/dist/chunk-SZGK6RIP.cjs +2 -0
  123. package/dist/chunk-SZGK6RIP.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-TRBXW6HW.js +2 -0
  129. package/dist/{chunk-AQNHHJMJ.cjs.map → chunk-TRBXW6HW.js.map} +1 -1
  130. package/dist/chunk-TTFO4YDP.cjs +2 -0
  131. package/dist/chunk-TTFO4YDP.cjs.map +1 -0
  132. package/dist/chunk-TWC7K3ZX.js +2 -0
  133. package/dist/chunk-TWC7K3ZX.js.map +1 -0
  134. package/dist/chunk-UDQ57ZRX.cjs +2 -0
  135. package/dist/chunk-UDQ57ZRX.cjs.map +1 -0
  136. package/dist/chunk-UI6IFGBT.js +2 -0
  137. package/dist/chunk-UI6IFGBT.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-W2JAR233.js +2 -0
  141. package/dist/chunk-W2JAR233.js.map +1 -0
  142. package/dist/chunk-WGZ3FNHI.js +2 -0
  143. package/dist/chunk-WGZ3FNHI.js.map +1 -0
  144. package/dist/chunk-WN5CMP4T.cjs +3 -0
  145. package/dist/chunk-WN5CMP4T.cjs.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-XR7HEC7B.js +5 -0
  151. package/dist/chunk-XR7HEC7B.js.map +1 -0
  152. package/dist/chunk-Y7O4D3BJ.cjs +2 -0
  153. package/dist/chunk-Y7O4D3BJ.cjs.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-YLJ4XMA6.js +0 -33
  368. package/dist/chunk-YLJ4XMA6.js.map +0 -1
  369. package/dist/chunk-YNIWOYW6.js +0 -232
  370. package/dist/chunk-YNIWOYW6.js.map +0 -1
  371. package/dist/chunk-Z2XP767T.cjs +0 -35
  372. package/dist/chunk-Z2XP767T.cjs.map +0 -1
  373. package/dist/chunk-Z4X2RWOF.js +0 -37
  374. package/dist/chunk-Z4X2RWOF.js.map +0 -1
  375. package/dist/chunk-ZN6YYPIW.js +0 -67
  376. package/dist/chunk-ZN6YYPIW.js.map +0 -1
  377. package/dist/chunk-ZNFFTYWH.js +0 -1854
  378. package/dist/chunk-ZNFFTYWH.js.map +0 -1
  379. package/dist/variables.cjs +0 -17
  380. package/dist/variables.cjs.map +0 -1
  381. package/dist/variables.d.cts +0 -87
  382. package/dist/variables.d.ts +0 -87
  383. package/dist/variables.js +0 -4
  384. package/dist/variables.js.map +0 -1
@@ -1,1795 +0,0 @@
1
- import { isEmptyLine, engine_worker_default } from './chunk-IJGOFP2J.js';
2
- import { djb2Hash } from './chunk-5ON7PUAZ.js';
3
- import { countLines } from './chunk-3BOK2LDK.js';
4
- import { sharedGlobalVariableStore, globalDagKey } from './chunk-WMQRJTAO.js';
5
- import { enableValueArena, disableValueArena, errorValue } from './chunk-5EFKSKMA.js';
6
- import { DEFAULT_CONFIG } from './chunk-CSDQMDU2.js';
7
- import { sharedLexer } from './chunk-RNKDIXDV.js';
8
- import { ErrorFactory, EngineError } from './chunk-N7OA4WPJ.js';
9
-
10
- // src/engine/SegmentTree.ts
11
- var SegmentTree = class {
12
- constructor() {
13
- this.root = null;
14
- }
15
- // ── Public API ───────────────────────────────────────────────────────
16
- /** Total number of elements in the tree. */
17
- get length() {
18
- return this.root ? this.root.size : 0;
19
- }
20
- /** Whether the tree is empty. */
21
- get isEmpty() {
22
- return this.root === null;
23
- }
24
- /**
25
- * Get the lineId at the given 0-based index.
26
- * Returns undefined if index is out of bounds.
27
- * O(log N) expected.
28
- */
29
- getAt(index) {
30
- if (index < 0 || index >= (this.root?.size ?? 0)) return void 0;
31
- return this.nodeAt(this.root, index).lineId;
32
- }
33
- /**
34
- * Insert a single lineId at the given 0-based index.
35
- * O(log N) expected.
36
- */
37
- insertAt(index, lineId) {
38
- const [left, right] = split(this.root, index);
39
- this.root = merge(merge(left, createNode(lineId)), right);
40
- }
41
- /**
42
- * Delete a single element at the given 0-based index.
43
- * Returns the removed lineId, or undefined if out of bounds.
44
- * O(log N) expected.
45
- */
46
- deleteAt(index) {
47
- if (index < 0 || index >= (this.root?.size ?? 0)) return void 0;
48
- const [left, midRight] = split(this.root, index);
49
- const [mid, right] = split(midRight, 1);
50
- const removed = mid ? mid.lineId : void 0;
51
- this.root = merge(left, right);
52
- return removed;
53
- }
54
- /**
55
- * Bulk splice: delete `deleteCount` elements at `startIndex` (0-based),
56
- * then insert `newIds` in their place.
57
- *
58
- * Returns the removed lineId array.
59
- * O(log N + deleteCount + insertCount) expected.
60
- */
61
- spliceAt(startIndex, deleteCount, newIds) {
62
- const clampedStart = Math.max(0, startIndex);
63
- const clampedCount = Math.min(
64
- Math.max(0, deleteCount),
65
- (this.root?.size ?? 0) - clampedStart
66
- );
67
- const [left, midRight] = split(this.root, clampedStart);
68
- const [mid, right] = split(midRight, clampedCount);
69
- const removed = collectInOrder(mid);
70
- const newTree = buildTreap(newIds, 0, newIds.length);
71
- this.root = merge(merge(left, newTree), right);
72
- return removed;
73
- }
74
- /**
75
- * Replace the entire tree with a new set of lineIds.
76
- * O(N), builds a balanced treap from a flat array.
77
- */
78
- replaceAll(lineIds) {
79
- this.root = buildTreap(lineIds, 0, lineIds.length);
80
- }
81
- /**
82
- * Get a contiguous range of lineIds by index.
83
- * O(rangeSize + log N), single in-order walk instead of N × O(log N).
84
- *
85
- * This is the hot path for viewport rendering in DocumentModel.getVisibleLines().
86
- */
87
- getRange(startIndex, endIndex) {
88
- const clampedStart = Math.max(0, startIndex);
89
- const clampedEnd = Math.min((this.root?.size ?? 0) - 1, endIndex);
90
- if (clampedStart > clampedEnd) return [];
91
- const result = [];
92
- this.collectRange(this.root, clampedStart, clampedEnd, 0, result);
93
- return result;
94
- }
95
- /**
96
- * Clear the tree.
97
- */
98
- clear() {
99
- this.root = null;
100
- }
101
- // ── Iteration ─────────────────────────────────────────────────────────
102
- /**
103
- * In-order iterator yielding all lineIds.
104
- */
105
- *[Symbol.iterator]() {
106
- yield* this.inOrder(this.root);
107
- }
108
- *inOrder(node) {
109
- if (!node) return;
110
- yield* this.inOrder(node.left);
111
- yield node.lineId;
112
- yield* this.inOrder(node.right);
113
- }
114
- // ── Private helpers ───────────────────────────────────────────────────
115
- nodeAt(node, index) {
116
- const leftSize = node.left ? node.left.size : 0;
117
- if (index < leftSize) {
118
- return this.nodeAt(node.left, index);
119
- } else if (index === leftSize) {
120
- return node;
121
- } else {
122
- return this.nodeAt(node.right, index - leftSize - 1);
123
- }
124
- }
125
- /**
126
- * Collect all node values in the range [targetStart, targetEnd] into result.
127
- * `offset` is the 0-based start of the current subtree within the full tree.
128
- * O(rangeSize + log N), skips entire subtrees outside the target range.
129
- */
130
- collectRange(node, targetStart, targetEnd, offset, result) {
131
- if (!node) return;
132
- const leftSize = node.left ? node.left.size : 0;
133
- const nodeIndex = offset + leftSize;
134
- if (nodeIndex > targetStart && node.left) {
135
- this.collectRange(node.left, targetStart, targetEnd, offset, result);
136
- }
137
- if (nodeIndex >= targetStart && nodeIndex <= targetEnd) {
138
- result.push(node.lineId);
139
- }
140
- if (nodeIndex < targetEnd && node.right) {
141
- this.collectRange(node.right, targetStart, targetEnd, nodeIndex + 1, result);
142
- }
143
- }
144
- };
145
- function createNode(lineId) {
146
- return {
147
- lineId,
148
- size: 1,
149
- priority: Math.random(),
150
- left: null,
151
- right: null
152
- };
153
- }
154
- function updateSize(node) {
155
- node.size = 1 + (node.left ? node.left.size : 0) + (node.right ? node.right.size : 0);
156
- }
157
- function merge(left, right) {
158
- if (!left) return right;
159
- if (!right) return left;
160
- if (left.priority > right.priority) {
161
- left.right = merge(left.right, right);
162
- updateSize(left);
163
- return left;
164
- } else {
165
- right.left = merge(left, right.left);
166
- updateSize(right);
167
- return right;
168
- }
169
- }
170
- function split(node, index) {
171
- if (!node) return [null, null];
172
- const leftSize = node.left ? node.left.size : 0;
173
- if (index <= leftSize) {
174
- const [left, right] = split(node.left, index);
175
- node.left = right;
176
- updateSize(node);
177
- return [left, node];
178
- } else {
179
- const [left, right] = split(node.right, index - leftSize - 1);
180
- node.right = left;
181
- updateSize(node);
182
- return [node, right];
183
- }
184
- }
185
- function collectInOrder(node) {
186
- const result = [];
187
- collect(node, result);
188
- return result;
189
- }
190
- function collect(node, result) {
191
- if (!node) return;
192
- collect(node.left, result);
193
- result.push(node.lineId);
194
- collect(node.right, result);
195
- }
196
- function buildTreap(lineIds, start, end) {
197
- if (start >= end) return null;
198
- const mid = Math.floor((start + end) / 2);
199
- const priority = pseudoRandom(mid);
200
- const node = {
201
- lineId: lineIds[mid],
202
- size: end - start,
203
- priority,
204
- left: buildTreap(lineIds, start, mid),
205
- right: buildTreap(lineIds, mid + 1, end)
206
- };
207
- return node;
208
- }
209
- function pseudoRandom(seed) {
210
- let x = seed;
211
- x = (x >> 16 ^ x) * 73244475;
212
- x = (x >> 16 ^ x) * 73244475;
213
- x = x >> 16 ^ x;
214
- return x / 4294967295;
215
- }
216
-
217
- // src/engine/DocumentModel.ts
218
- var DocumentModel = class {
219
- /**
220
- * @param maxLines - Ceiling on the line count, defaulting to the engine's
221
- * configured one. Every line costs a LineState with six arrays in it
222
- * whatever the line says, so the cost of a document is its line count and
223
- * nothing else bounds it: two hundred thousand lines of `1 + 1` exhausted
224
- * the heap here, before a single expression had been looked at.
225
- */
226
- constructor(maxLines = DEFAULT_CONFIG.performance.maxDocumentLines) {
227
- /** Persistent line ID → LineState. */
228
- this.lines = /* @__PURE__ */ new Map();
229
- /** Order-statistic treap representing the current document line order. */
230
- this.orderTree = new SegmentTree();
231
- /** Monotonically increasing counter for new line IDs. */
232
- this.nextLineId = 1;
233
- /**
234
- * Lazy position cache: lineId → 1-based position.
235
- * Built on first `getLinePosition()` call, invalidated on structural edits.
236
- */
237
- this._positionCache = null;
238
- /**
239
- * Line IDs currently marked dirty, maintained alongside every
240
- * `state.dirty` mutation (in this class and in every other module that
241
- * holds a direct `LineState` reference: ThreeTierEvaluator, PageManager).
242
- * Lets {@link hasAnyDirtyLineBefore} answer "is anything before position
243
- * X dirty" in O(d log N), d = current dirty count, typically tiny once
244
- * a document has settled after its initial evaluation, instead of
245
- * O(N log N), which used to mean every scroll event re-walked the WHOLE
246
- * document via `getLineAt()` regardless of how little of it was actually
247
- * dirty. Benchmarked: ~10.6ms per setViewport() call scrolled near the
248
- * bottom of a 20k-line document before this fix.
249
- */
250
- this.dirtyLineIds = /* @__PURE__ */ new Set();
251
- this.maxLines = maxLines;
252
- }
253
- // ── Initialization ──────────────────────────────────────────────────
254
- /**
255
- * Initialize or replace the entire document from a text blob.
256
- * Clears all existing state and assigns new persistent line IDs.
257
- *
258
- * @throws `DOCUMENT_TOO_LARGE` for a document past {@link maxLines}, before
259
- * any of it is stored. Recoverable: nothing has been replaced yet, so the
260
- * model still holds whatever it held.
261
- */
262
- setDocument(text) {
263
- const lineCount = countLines(text, this.maxLines);
264
- if (lineCount > this.maxLines) {
265
- throw ErrorFactory.execution(
266
- "DOCUMENT_TOO_LARGE",
267
- `This document has more than ${this.maxLines.toLocaleString("en-US")} lines, which is the most the engine will hold at once`,
268
- { maxLines: this.maxLines }
269
- );
270
- }
271
- this.lines.clear();
272
- this.orderTree.clear();
273
- this._positionCache = null;
274
- this.dirtyLineIds.clear();
275
- this.nextLineId = 1;
276
- const rawLines = text.split("\n");
277
- const lineIds = new Array(rawLines.length);
278
- for (let i = 0; i < rawLines.length; i++) {
279
- const lineId = this.nextLineId++;
280
- lineIds[i] = lineId;
281
- this.lines.set(lineId, {
282
- lineId,
283
- textHash: djb2Hash(rawLines[i]),
284
- text: rawLines[i],
285
- expressions: [],
286
- bytecodes: [],
287
- reads: [],
288
- writes: [],
289
- results: [],
290
- result: null,
291
- dirty: true,
292
- isVariableDef: false,
293
- isEmpty: rawLines[i].trim().length === 0,
294
- inlineSolveCount: 0
295
- });
296
- }
297
- this.orderTree.replaceAll(lineIds);
298
- for (const id of lineIds) this.dirtyLineIds.add(id);
299
- }
300
- // ── Structural edits ────────────────────────────────────────────────
301
- /**
302
- * Apply one or more line-level changes to the document.
303
- *
304
- * **Precondition:** Changes must be **non-overlapping** in their line ranges.
305
- * If two changes target the same or adjacent lines, the reverse-order
306
- * processing may produce incorrect results because the first-applied
307
- * change shifts the line numbers that the second change references.
308
- *
309
- * Changes are applied in **reverse order** (highest startLine first) so
310
- * that earlier changes in the document don't shift the indices of later
311
- * changes during processing.
312
- *
313
- * Returns both the newly inserted line IDs and the removed line IDs.
314
- * Callers should use `removed` to clean up the dependency graph and
315
- * other data structures keyed by lineId.
316
- */
317
- applyChanges(changes) {
318
- const inserted = [];
319
- const removed = [];
320
- const sorted = [...changes].sort((a, b) => b.startLine - a.startLine);
321
- for (const change of sorted) {
322
- const startIdx = change.startLine - 1;
323
- const newIds = [];
324
- for (const text of change.insertLines) {
325
- const lineId = this.nextLineId++;
326
- newIds.push(lineId);
327
- inserted.push(lineId);
328
- this.lines.set(lineId, {
329
- lineId,
330
- textHash: djb2Hash(text),
331
- text,
332
- expressions: [],
333
- bytecodes: [],
334
- reads: [],
335
- writes: [],
336
- results: [],
337
- result: null,
338
- dirty: true,
339
- isVariableDef: false,
340
- isEmpty: text.trim().length === 0,
341
- inlineSolveCount: 0
342
- });
343
- }
344
- for (const id of newIds) this.dirtyLineIds.add(id);
345
- const removedIds = this.orderTree.spliceAt(
346
- startIdx,
347
- change.deleteCount,
348
- newIds
349
- );
350
- for (const id of removedIds) {
351
- removed.push(id);
352
- this.lines.delete(id);
353
- this.dirtyLineIds.delete(id);
354
- }
355
- }
356
- this._positionCache = null;
357
- return { inserted, removed };
358
- }
359
- /**
360
- * Insert new lines at the given 1-based position.
361
- * Convenience wrapper around applyChanges.
362
- */
363
- insertLines(atLine, texts) {
364
- const change = {
365
- startLine: atLine,
366
- deleteCount: 0,
367
- insertLines: texts
368
- };
369
- const result = this.applyChanges([change]);
370
- return result.inserted;
371
- }
372
- /**
373
- * Delete lines in the given 1-based range [startLine, endLine] inclusive.
374
- * Convenience wrapper around applyChanges.
375
- */
376
- deleteLines(startLine, endLine) {
377
- const change = {
378
- startLine,
379
- deleteCount: endLine - startLine + 1,
380
- insertLines: []
381
- };
382
- const result = this.applyChanges([change]);
383
- return result.removed;
384
- }
385
- /**
386
- * Update the text of a single line in place.
387
- * If the text hash differs, marks the line dirty and clears its
388
- * bytecode/result so it gets re-evaluated.
389
- *
390
- * Returns true if the text actually changed (hash mismatch).
391
- */
392
- editLine(lineNumber, newText) {
393
- const state = this.getLineAt(lineNumber);
394
- if (!state) return false;
395
- const newHash = djb2Hash(newText);
396
- if (newHash === state.textHash) return false;
397
- state.text = newText;
398
- state.textHash = newHash;
399
- state.expressions = [];
400
- state.bytecodes = [];
401
- state.results = [];
402
- state.result = null;
403
- state.inlineSolveCount = 0;
404
- state.dirty = true;
405
- this.dirtyLineIds.add(state.lineId);
406
- state.isEmpty = newText.trim().length === 0;
407
- return true;
408
- }
409
- // ── Queries ─────────────────────────────────────────────────────────
410
- /**
411
- * Get the LineState at the given 1-based line position. O(1).
412
- */
413
- getLineAt(position) {
414
- const idx = position - 1;
415
- const lineId = this.orderTree.getAt(idx);
416
- if (lineId === void 0) return void 0;
417
- return this.lines.get(lineId);
418
- }
419
- /**
420
- * Get the 1-based position of a line by its persistent ID.
421
- * Returns -1 if the line ID is not in the document.
422
- *
423
- * Uses a lazy position cache: O(N) on first call after structural edit,
424
- * O(1) on subsequent calls. The cache is invalidated by any structural edit.
425
- */
426
- getLinePosition(lineId) {
427
- if (this._positionCache) {
428
- return this._positionCache.get(lineId) ?? -1;
429
- }
430
- this._positionCache = /* @__PURE__ */ new Map();
431
- let pos = 1;
432
- for (const id of this.orderTree) {
433
- this._positionCache.set(id, pos++);
434
- }
435
- return this._positionCache.get(lineId) ?? -1;
436
- }
437
- /**
438
- * Get all LineState entries within the given viewport range (1-based, inclusive).
439
- * Uses SegmentTree.getRange() for O(viewport + log N) collection instead of
440
- * O(viewport × log N) per-line lookups.
441
- */
442
- getVisibleLines(startLine, endLine) {
443
- const lineIds = this.orderTree.getRange(startLine - 1, endLine - 1);
444
- const result = [];
445
- for (const lineId of lineIds) {
446
- const state = this.lines.get(lineId);
447
- if (state) result.push(state);
448
- }
449
- return result;
450
- }
451
- /**
452
- * Get all LineState entries in order. Useful for batch processing.
453
- */
454
- getAllLines() {
455
- return this.getVisibleLines(1, this.lineCount);
456
- }
457
- /**
458
- * Get a LineState by its persistent line ID. O(1).
459
- */
460
- getLineById(lineId) {
461
- return this.lines.get(lineId);
462
- }
463
- /**
464
- * Get all lines that are marked dirty.
465
- */
466
- getDirtyLines() {
467
- const result = [];
468
- for (const state of this.lines.values()) {
469
- if (state.dirty) result.push(state);
470
- }
471
- return result;
472
- }
473
- /**
474
- * Whether any line before `position` (1-based, exclusive) is dirty.
475
- *
476
- * Used by ThreeTierEvaluator.setViewport() to decide whether cached
477
- * checkpoint state might be stale and a full evaluate() (from line 1) is
478
- * needed instead of the cheap viewport-only path.
479
- *
480
- * O(d log N) where d = current dirty line count via {@link dirtyLineIds},
481
- * not O(N log N), a document that's mostly clean (the steady state after
482
- * initial load) answers this in the cost of resolving a handful of
483
- * lineIds to positions, not walking every line up to `position`.
484
- */
485
- hasAnyDirtyLineBefore(position) {
486
- for (const lineId of this.dirtyLineIds) {
487
- const pos = this.getLinePosition(lineId);
488
- if (pos >= 1 && pos < position) return true;
489
- }
490
- return false;
491
- }
492
- /**
493
- * Whether any **variable-definition** line before `position` (1-based,
494
- * exclusive) is dirty.
495
- *
496
- * Narrower than {@link hasAnyDirtyLineBefore}: `VMCheckpointer.snapshot()`
497
- * only ever records state for lines with `writes.length > 0` (see
498
- * VMCheckpoints.ts), so a dirty plain-expression line before the viewport
499
- * cannot have invalidated any checkpoint, there's no checkpoint entry
500
- * for it to invalidate. Only a dirty variable-def line can mean the VM
501
- * state a checkpoint would restore is stale.
502
- *
503
- * This distinction matters because `PageManager.evictPageBytecode()`
504
- * marks evicted non-variable-def lines dirty (so they get Tier 1 if
505
- * scrolled back into view), and Tier 3's compile-only path never clears
506
- * `dirty` for non-variable-def lines by design. Using the broader
507
- * `hasAnyDirtyLineBefore` here meant scrolling far into a large,
508
- * variable-def-free document would trip `setViewport()`'s fallback to
509
- * `evaluate()` on every single call, evaluate() reprocesses the evicted
510
- * lines via Tier 3, which recompiles their bytecode without clearing
511
- * dirty, so the very next `maintainAfterEval()` re-evicts and re-dirties
512
- * the same lines, forever re-triggering the fallback on an otherwise
513
- * unchanged viewport.
514
- */
515
- hasAnyDirtyVariableDefLineBefore(position) {
516
- for (const lineId of this.dirtyLineIds) {
517
- const state = this.lines.get(lineId);
518
- if (!state || !state.isVariableDef) continue;
519
- const pos = this.getLinePosition(lineId);
520
- if (pos >= 1 && pos < position) return true;
521
- }
522
- return false;
523
- }
524
- /** Number of lines currently marked dirty. For diagnostics/tests. */
525
- get dirtyCount() {
526
- return this.dirtyLineIds.size;
527
- }
528
- // ── Thread-safety validation ────────────────────────────────────────
529
- /**
530
- * Verify that bytecode compiled by a worker is still valid for this line.
531
- *
532
- * When Phase 5.2h sends compilation to a worker, the worker posts back
533
- * `{lineId, bytecode, reads, writes, compiledAgainstHash}`. Between dispatch
534
- * and response, the user may have edited the line. This method lets the
535
- * main thread check whether the bytecode is still applicable.
536
- *
537
- * @returns true if the line still exists and its text hash matches.
538
- */
539
- isBytecodeValid(lineId, compiledAgainstHash) {
540
- const state = this.lines.get(lineId);
541
- return state !== void 0 && state.textHash === compiledAgainstHash;
542
- }
543
- // ── State mutations ─────────────────────────────────────────────────
544
- /**
545
- * Mark a line as clean (re-evaluated successfully).
546
- */
547
- markClean(lineId) {
548
- const state = this.lines.get(lineId);
549
- if (state) {
550
- state.dirty = false;
551
- this.dirtyLineIds.delete(lineId);
552
- }
553
- }
554
- /**
555
- * Mark a line as dirty (needs re-evaluation) by its 1-based position.
556
- * Convenience for callers that have line numbers instead of line IDs.
557
- */
558
- markDirtyByLineNumber(lineNumber) {
559
- const state = this.getLineAt(lineNumber);
560
- if (state) {
561
- state.dirty = true;
562
- this.dirtyLineIds.add(state.lineId);
563
- }
564
- }
565
- /**
566
- * Mark a line as dirty (needs re-evaluation).
567
- */
568
- markDirty(lineId) {
569
- const state = this.lines.get(lineId);
570
- if (state) {
571
- state.dirty = true;
572
- this.dirtyLineIds.add(lineId);
573
- }
574
- }
575
- /**
576
- * Mark all lines as dirty (e.g., after plugin register/unregister).
577
- */
578
- invalidateAll() {
579
- for (const state of this.lines.values()) {
580
- state.dirty = true;
581
- }
582
- this.dirtyLineIds = new Set(this.lines.keys());
583
- }
584
- /**
585
- * Update a line's evaluation state after successful execution (Tier 1 / Tier 2).
586
- *
587
- * Sets results, bytecodes, reads, writes, and marks the line clean.
588
- * Supports multi-expression lines (inline solves) via parallel arrays.
589
- *
590
- * @param lineId - Persistent line identifier.
591
- * @param results - Evaluation result groups for each expression (in order). Each element is a Value[].
592
- * @param bytecodes - Compiled bytecode for each expression (in order).
593
- * @param expressions - Extracted expression strings (in order).
594
- * @param reads - Aggregated read variables across all expressions.
595
- * @param writes - Aggregated write variables across all expressions.
596
- * @param isVariableDef - True if any expression defines a variable.
597
- * @param inlineSolveCount - Number of inline solves (0 for full-line).
598
- */
599
- updateLineResult(lineId, results, bytecodes, expressions, reads, writes, isVariableDef, inlineSolveCount = 0) {
600
- const state = this.lines.get(lineId);
601
- if (!state) return;
602
- state.results = results;
603
- state.result = results[0]?.[0] ?? null;
604
- state.bytecodes = bytecodes;
605
- state.expressions = expressions;
606
- state.reads = reads;
607
- state.writes = writes;
608
- state.isVariableDef = isVariableDef;
609
- state.inlineSolveCount = inlineSolveCount;
610
- state.dirty = false;
611
- this.dirtyLineIds.delete(lineId);
612
- }
613
- /**
614
- * Update a line's compile-only state (Tier 3: background compilation).
615
- *
616
- * Stores expressions, bytecodes, reads, and writes. Does NOT set results
617
- * and does NOT mark the line clean, it still needs execution (Tier 1 or
618
- * Tier 2) to produce results. This distinction allows the three-tier
619
- * evaluation strategy: compile invisible lines in the background without
620
- * executing them, then execute from cached bytecode when scrolled into view.
621
- *
622
- * @param lineId - Persistent line identifier.
623
- * @param expressions - Extracted expression strings (in order).
624
- * @param bytecodes - Compiled bytecode for each expression (in order).
625
- * @param reads - Aggregated read variables across all expressions.
626
- * @param writes - Aggregated write variables across all expressions.
627
- * @param isVariableDef - True if any expression defines a variable.
628
- * @param inlineSolveCount - Number of inline solves (0 for full-line).
629
- */
630
- updateLineCompiled(lineId, expressions, bytecodes, reads, writes, isVariableDef, inlineSolveCount = 0) {
631
- const state = this.lines.get(lineId);
632
- if (!state) return;
633
- state.expressions = expressions;
634
- state.bytecodes = bytecodes;
635
- state.reads = reads;
636
- state.writes = writes;
637
- state.isVariableDef = isVariableDef;
638
- state.inlineSolveCount = inlineSolveCount;
639
- }
640
- // ── Properties ──────────────────────────────────────────────────────
641
- get lineCount() {
642
- return this.orderTree.length;
643
- }
644
- get isEmpty() {
645
- return this.orderTree.isEmpty;
646
- }
647
- /**
648
- * Iterator over LineState in document order.
649
- */
650
- *[Symbol.iterator]() {
651
- for (const lineId of this.orderTree) {
652
- const state = this.lines.get(lineId);
653
- if (state) yield state;
654
- }
655
- }
656
- // ── Lifecycle ───────────────────────────────────────────────────────
657
- clear() {
658
- this.lines.clear();
659
- this.orderTree.clear();
660
- this._positionCache = null;
661
- this.nextLineId = 1;
662
- }
663
- /**
664
- * Serialize the document model to a plain object for debugging.
665
- */
666
- toJSON() {
667
- return {
668
- lineCount: this.lineCount,
669
- lines: this.getAllLines().map((s) => ({
670
- lineId: s.lineId,
671
- text: s.text.substring(0, 80),
672
- // truncate for readability
673
- textHash: s.textHash,
674
- dirty: s.dirty,
675
- isVariableDef: s.isVariableDef,
676
- isEmpty: s.isEmpty,
677
- hasBytecode: s.bytecodes.length > 0,
678
- hasResult: s.results.length > 0,
679
- inlineSolveCount: s.inlineSolveCount,
680
- reads: s.reads,
681
- writes: s.writes
682
- }))
683
- };
684
- }
685
- };
686
-
687
- // src/engine/CompilationWorkerManager.ts
688
- var CompilationWorkerManager = class {
689
- constructor() {
690
- this.worker = null;
691
- this.nextId = 1;
692
- this.pending = /* @__PURE__ */ new Map();
693
- }
694
- /**
695
- * Ensure the worker is started (lazy initialization).
696
- * Uses esbuild-plugin-inline-worker to inline the worker as a blob URL.
697
- */
698
- ensureWorker() {
699
- if (this.worker) return this.worker;
700
- this.worker = engine_worker_default();
701
- this.worker.onmessage = (event) => {
702
- const data = event.data;
703
- if (!data || data.type !== "COMPILE_RESULT") return;
704
- const pending = this.pending.get(data.id);
705
- if (!pending) return;
706
- this.pending.delete(data.id);
707
- const results = [];
708
- for (const raw of data.results) {
709
- results.push(this.reconstructResult(raw));
710
- }
711
- pending.resolve(results);
712
- };
713
- this.worker.onerror = (err) => {
714
- for (const [id, pending] of this.pending) {
715
- pending.reject(
716
- new Error(`Compilation worker error: ${err.message}`)
717
- );
718
- this.pending.delete(id);
719
- }
720
- };
721
- return this.worker;
722
- }
723
- /**
724
- * Batch-compile expressions in the worker.
725
- *
726
- * Sends a batch of { lineId, expression, textHash } to the worker,
727
- * which compiles each and transfers bytecode ArrayBuffers back.
728
- * Bytecode is reconstructed into BytecodeProgram objects.
729
- *
730
- * Results are returned in the same order as the input items.
731
- *
732
- * @param items Expressions to compile.
733
- * @returns Compiled bytecode for each item (or error).
734
- */
735
- async compileBatch(items) {
736
- if (items.length === 0) return [];
737
- const worker = this.ensureWorker();
738
- const id = this.nextId++;
739
- return new Promise((resolve, reject) => {
740
- this.pending.set(id, { resolve, reject });
741
- worker.postMessage({
742
- type: "COMPILE_BATCH",
743
- id,
744
- items
745
- });
746
- });
747
- }
748
- /**
749
- * Store worker-compiled bytecode into the DocumentModel, with safety
750
- * validation. Only stores bytecode for lines whose text has not changed
751
- * since the compilation request was dispatched.
752
- *
753
- * Results for the same lineId are batched, all bytecodes from
754
- * successful compilations are passed to updateLineCompiled in a single
755
- * call. This supports multi-expression lines (inline solves).
756
- *
757
- * @param results Compiled results from the worker.
758
- * @param doc The target document model.
759
- * @returns Number of results successfully stored (passed safety check).
760
- */
761
- storeResults(results, doc) {
762
- const byLineId = /* @__PURE__ */ new Map();
763
- for (const result of results) {
764
- if (result.error) continue;
765
- const state = doc.getLineById(result.lineId);
766
- if (!state) continue;
767
- if (state.textHash !== result.compiledAgainstHash) continue;
768
- let batch = byLineId.get(result.lineId);
769
- if (!batch) {
770
- batch = {
771
- bytecodes: [],
772
- reads: /* @__PURE__ */ new Set(),
773
- writes: /* @__PURE__ */ new Set(),
774
- isVariableDef: false,
775
- expressions: state.expressions.length > 0 ? [...state.expressions] : [],
776
- textHash: result.compiledAgainstHash
777
- };
778
- byLineId.set(result.lineId, batch);
779
- }
780
- batch.bytecodes.push(result.program);
781
- for (const r of result.reads) batch.reads.add(r);
782
- for (const w of result.writes) batch.writes.add(w);
783
- if (result.isVariableDef) batch.isVariableDef = true;
784
- }
785
- let stored = 0;
786
- for (const [lineId, batch] of byLineId) {
787
- if (batch.bytecodes.length === 0) continue;
788
- const state = doc.getLineById(lineId);
789
- const inlineSolveCount = state?.inlineSolveCount ?? 0;
790
- doc.updateLineCompiled(
791
- lineId,
792
- batch.expressions,
793
- batch.bytecodes,
794
- [...batch.reads],
795
- [...batch.writes],
796
- batch.isVariableDef,
797
- inlineSolveCount
798
- );
799
- stored += batch.bytecodes.length;
800
- }
801
- return stored;
802
- }
803
- /**
804
- * Terminate the worker and clean up.
805
- */
806
- terminate() {
807
- if (this.worker) {
808
- this.worker.terminate();
809
- this.worker = null;
810
- this.pending.clear();
811
- }
812
- }
813
- /**
814
- * Whether the worker is currently active.
815
- */
816
- get isActive() {
817
- return this.worker !== null;
818
- }
819
- // ── Private helpers ────────────────────────────────────────────────
820
- /**
821
- * Reconstruct a BytecodeProgram from transferred ArrayBuffers.
822
- *
823
- * The transferred ArrayBuffers are zero-copy, we create TypedArray
824
- * views directly over them. No data is copied or serialized.
825
- */
826
- reconstructResult(raw) {
827
- if (raw.error) {
828
- return {
829
- lineId: raw.lineId,
830
- compiledAgainstHash: raw.compiledAgainstHash,
831
- program: { opcodes: new Uint8Array(0), numbers: new Float64Array(0), strings: [], hasAsync: false },
832
- reads: [],
833
- writes: [],
834
- isVariableDef: false,
835
- error: raw.error
836
- };
837
- }
838
- const opcodes = raw.opcodesLength > 0 ? new Uint8Array(raw.opcodesBuffer, 0, raw.opcodesLength) : new Uint8Array(0);
839
- const numbers = raw.numbersLength > 0 ? new Float64Array(raw.numbersBuffer, 0, raw.numbersLength) : new Float64Array(0);
840
- const program = {
841
- opcodes,
842
- numbers,
843
- strings: raw.strings,
844
- hasAsync: false
845
- };
846
- return {
847
- lineId: raw.lineId,
848
- compiledAgainstHash: raw.compiledAgainstHash,
849
- program,
850
- reads: raw.reads,
851
- writes: raw.writes,
852
- isVariableDef: raw.isVariableDef,
853
- error: null
854
- };
855
- }
856
- };
857
-
858
- // src/engine/PageManager.ts
859
- var PAGE_SIZE = 128;
860
- var HOT_PAGE_RADIUS = 3;
861
- var WARM_PAGE_RADIUS = 6;
862
- var PRELOAD_PAGE_COUNT = 2;
863
- var COLD_EVICT_BUFFER = HOT_PAGE_RADIUS;
864
- var PageManager = class _PageManager {
865
- constructor() {
866
- /** Previous viewport for scroll direction detection. null = no previous viewport. */
867
- this.lastViewportStart = null;
868
- /** Saved scroll direction from the most recent maintainAfterEval call. */
869
- this.savedDirection = null;
870
- /** Per-page access counter for LRU tracking. */
871
- this.pageAccess = /* @__PURE__ */ new Map();
872
- /** Monotonically increasing access sequence number. */
873
- this.accessSeq = 0;
874
- }
875
- // ── Static helpers ─────────────────────────────────────────────────
876
- /** Get the page number for a 1-based line number (0-based page index). */
877
- static pageForLine(lineNumber) {
878
- return Math.floor((lineNumber - 1) / PAGE_SIZE);
879
- }
880
- /** Get the 1-based inclusive line range for a page. */
881
- static pageRange(pageNum, docLineCount) {
882
- return {
883
- startLine: pageNum * PAGE_SIZE + 1,
884
- endLine: Math.min((pageNum + 1) * PAGE_SIZE, docLineCount)
885
- };
886
- }
887
- // ── Public API ─────────────────────────────────────────────────────
888
- /**
889
- * Detect scroll direction from viewport movement.
890
- * Returns null on first call (no previous viewport) or no movement.
891
- */
892
- detectDirection(newViewport) {
893
- if (this.lastViewportStart === null) return null;
894
- if (newViewport.startLine > this.lastViewportStart) return "down";
895
- if (newViewport.startLine < this.lastViewportStart) return "up";
896
- return null;
897
- }
898
- /**
899
- * Maintain page tiers after evaluation.
900
- *
901
- * 1. Records the new viewport position
902
- * 2. Touches hot pages (viewport ± HOT_PAGE_RADIUS) for LRU
903
- * 3. Evicts cold/warm pages based on distance from viewport
904
- *
905
- * Call this after every `evaluate()`, `setViewport()`, or `evaluateAll()`.
906
- */
907
- maintainAfterEval(viewport, doc) {
908
- this.savedDirection = this.detectDirection(viewport);
909
- this.lastViewportStart = viewport.startLine;
910
- const docLineCount = doc.lineCount;
911
- const viewportStartPage = _PageManager.pageForLine(viewport.startLine);
912
- const viewportEndPage = _PageManager.pageForLine(viewport.endLine);
913
- const lastPage = _PageManager.pageForLine(docLineCount);
914
- const hotStart = Math.max(0, viewportStartPage - HOT_PAGE_RADIUS);
915
- const hotEnd = Math.min(lastPage, viewportEndPage + HOT_PAGE_RADIUS);
916
- const warmStart = Math.max(0, viewportStartPage - WARM_PAGE_RADIUS);
917
- const warmEnd = Math.min(lastPage, viewportEndPage + WARM_PAGE_RADIUS);
918
- for (let p = hotStart; p <= hotEnd; p++) {
919
- this.touchPage(p);
920
- }
921
- for (let p = warmStart; p <= warmEnd; p++) {
922
- if (p >= hotStart && p <= hotEnd) continue;
923
- this.evictPageResults(p, doc, docLineCount);
924
- }
925
- const coldLeftEnd = warmStart - 1;
926
- const coldLeftStart = Math.max(0, coldLeftEnd - COLD_EVICT_BUFFER + 1);
927
- for (let p = coldLeftStart; p <= coldLeftEnd; p++) {
928
- this.evictPageBytecode(p, doc, docLineCount);
929
- }
930
- const coldRightStart = warmEnd + 1;
931
- const coldRightEnd = Math.min(lastPage, coldRightStart + COLD_EVICT_BUFFER - 1);
932
- for (let p = coldRightStart; p <= coldRightEnd; p++) {
933
- this.evictPageBytecode(p, doc, docLineCount);
934
- }
935
- }
936
- /**
937
- * Get lines ahead of the viewport that should be pre-compiled.
938
- *
939
- * Looks PRELOAD_PAGE_COUNT pages ahead of the current scroll direction.
940
- * Only returns lines that are dirty, don't already have bytecode,
941
- * and are not empty/markdown-only.
942
- *
943
- * @param viewport The current viewport.
944
- * @param doc The document model.
945
- * @returns Items ready to send to the compilation worker.
946
- */
947
- getPreloadTargets(viewport, doc) {
948
- const direction = this.savedDirection;
949
- if (!direction) return [];
950
- const items = [];
951
- const viewportEndPage = _PageManager.pageForLine(viewport.endLine);
952
- const viewportStartPage = _PageManager.pageForLine(viewport.startLine);
953
- const lastPage = _PageManager.pageForLine(doc.lineCount);
954
- const pages = [];
955
- if (direction === "down") {
956
- const startPage = viewportEndPage + HOT_PAGE_RADIUS + 1;
957
- const endPage = Math.min(startPage + PRELOAD_PAGE_COUNT - 1, lastPage);
958
- for (let p = startPage; p <= endPage && p <= lastPage; p++) {
959
- pages.push(p);
960
- }
961
- } else {
962
- const firstPreloadPage = viewportStartPage - HOT_PAGE_RADIUS - 1;
963
- for (let p = firstPreloadPage; p > firstPreloadPage - PRELOAD_PAGE_COUNT && p >= 0; p--) {
964
- pages.push(p);
965
- }
966
- }
967
- for (const pageNum of pages) {
968
- const range = _PageManager.pageRange(pageNum, doc.lineCount);
969
- for (let pos = range.startLine; pos <= range.endLine; pos++) {
970
- const state = doc.getLineAt(pos);
971
- if (!state) continue;
972
- if (!state.dirty) continue;
973
- if (state.bytecodes.length > 0 && !state.isVariableDef) continue;
974
- if (state.isEmpty) continue;
975
- if (state.expressions.length > 0) {
976
- for (const expression of state.expressions) {
977
- if (!expression.trim()) continue;
978
- items.push({
979
- lineId: state.lineId,
980
- expression,
981
- textHash: state.textHash
982
- });
983
- }
984
- } else {
985
- const inlineSpans = sharedLexer.findInlineSolves(state.text);
986
- if (inlineSpans.length > 0) {
987
- for (const span of inlineSpans) {
988
- if (!span.expression.trim()) continue;
989
- items.push({
990
- lineId: state.lineId,
991
- expression: span.expression,
992
- textHash: state.textHash
993
- });
994
- }
995
- } else {
996
- const expression = state.text.trim();
997
- if (expression) {
998
- items.push({
999
- lineId: state.lineId,
1000
- expression,
1001
- textHash: state.textHash
1002
- });
1003
- }
1004
- }
1005
- }
1006
- }
1007
- }
1008
- return items;
1009
- }
1010
- /**
1011
- * Reset internal state (e.g., after document switch).
1012
- */
1013
- clear() {
1014
- this.pageAccess.clear();
1015
- this.accessSeq = 0;
1016
- this.lastViewportStart = null;
1017
- this.savedDirection = null;
1018
- }
1019
- // ── Private helpers ─────────────────────────────────────────────────
1020
- /** Record a page access with a monotonic sequence number. */
1021
- touchPage(pageNum) {
1022
- this.pageAccess.set(pageNum, ++this.accessSeq);
1023
- }
1024
- /**
1025
- * Evict results from all non-variable-def lines in a page.
1026
- * Bytecode is preserved so Tier 2 execution works on scroll-back.
1027
- */
1028
- evictPageResults(pageNum, doc, docLineCount) {
1029
- const range = _PageManager.pageRange(pageNum, docLineCount);
1030
- for (let pos = range.startLine; pos <= range.endLine; pos++) {
1031
- const state = doc.getLineAt(pos);
1032
- if (state && !state.isVariableDef && state.results.length > 0) {
1033
- state.results = [];
1034
- state.result = null;
1035
- }
1036
- }
1037
- }
1038
- /**
1039
- * Evict bytecode + results from all non-variable-def lines in a page.
1040
- * Variable definition bytecode is **never** evicted, it forms the
1041
- * backbone of the DAG and VM checkpoints.
1042
- *
1043
- * Evicted lines are marked dirty so they get Tier 1 re-evaluation
1044
- * when scrolled back into view.
1045
- */
1046
- evictPageBytecode(pageNum, doc, docLineCount) {
1047
- const range = _PageManager.pageRange(pageNum, docLineCount);
1048
- for (let pos = range.startLine; pos <= range.endLine; pos++) {
1049
- const state = doc.getLineAt(pos);
1050
- if (!state || state.isVariableDef) continue;
1051
- if (state.bytecodes.length > 0 || state.results.length > 0) {
1052
- state.bytecodes = [];
1053
- state.results = [];
1054
- state.result = null;
1055
- doc.markDirty(state.lineId);
1056
- }
1057
- }
1058
- }
1059
- };
1060
-
1061
- // src/engine/ThreeTierEvaluator.ts
1062
- var EvalTier = /* @__PURE__ */ ((EvalTier2) => {
1063
- EvalTier2[EvalTier2["Tier1"] = 1] = "Tier1";
1064
- EvalTier2[EvalTier2["Tier2"] = 2] = "Tier2";
1065
- EvalTier2[EvalTier2["Tier3"] = 3] = "Tier3";
1066
- EvalTier2[EvalTier2["Skipped"] = 0] = "Skipped";
1067
- return EvalTier2;
1068
- })(EvalTier || {});
1069
- var ThreeTierEvaluator = class {
1070
- /**
1071
- * @param doc The persistent document model.
1072
- * @param engine The expression engine (shared VM is accessed via engine.getVM()).
1073
- * @param checkpointer Optional VM state checkpointer. If provided, the evaluator
1074
- * will create checkpoints after variable-definition lines and support fast VM
1075
- * restoration via `restoreTo()`. If omitted, checkpointing is disabled.
1076
- */
1077
- constructor(doc, engine, checkpointer) {
1078
- this.compilationWorker = null;
1079
- /**
1080
- * Unsubscribe from sharedGlobalVariableStore, set in the constructor
1081
- * called from terminateWorker(). See the subscription itself below for
1082
- * why this only marks lines dirty and never re-evaluates synchronously.
1083
- */
1084
- this.globalUnsubscribe = null;
1085
- this.doc = doc;
1086
- this.engine = engine;
1087
- this.dag = engine.getDag();
1088
- this.checkpointer = checkpointer ?? null;
1089
- this.pageManager = new PageManager();
1090
- this.engine.setDocumentModel(this.doc);
1091
- this.globalUnsubscribe = sharedGlobalVariableStore.subscribe((name) => {
1092
- for (const lineNumber of this.dag.getAffectedLines(globalDagKey(name))) {
1093
- this.doc.markDirtyByLineNumber(lineNumber);
1094
- }
1095
- });
1096
- }
1097
- /**
1098
- * Evaluate all lines needed to render the given viewport.
1099
- *
1100
- * Processes lines from 1 to `viewport.endLine` in document order.
1101
- * Dirty lines in the viewport get Tier-1 full pipeline; clean cached
1102
- * lines get Tier-2 bytecode execution. Lines after the viewport
1103
- * get Tier-3 compile-only (with variable-def execution).
1104
- *
1105
- * @returns Results for all processed lines, including tier metadata.
1106
- */
1107
- evaluate(viewport, signal) {
1108
- this.engine.setKeystrokeSignal(signal ?? null);
1109
- enableValueArena();
1110
- try {
1111
- this.reseedAccumulators();
1112
- const lines = [];
1113
- const resultMap = /* @__PURE__ */ new Map();
1114
- const tierCounts = { tier1: 0, tier2: 0, tier3: 0, skipped: 0 };
1115
- const docEnd = this.doc.lineCount;
1116
- const evalEnd = Math.min(viewport.endLine, docEnd);
1117
- for (let pos = 1; pos <= evalEnd; pos++) {
1118
- const state = this.doc.getLineAt(pos);
1119
- if (!state) {
1120
- tierCounts.skipped++;
1121
- continue;
1122
- }
1123
- const inViewport = pos >= viewport.startLine && pos <= viewport.endLine;
1124
- const lineResult = this.evaluateSingleLine(state, pos, inViewport);
1125
- lines.push(lineResult);
1126
- if (lineResult.tier === 1 /* Tier1 */) tierCounts.tier1++;
1127
- else if (lineResult.tier === 2 /* Tier2 */) tierCounts.tier2++;
1128
- else if (lineResult.tier === 3 /* Tier3 */) tierCounts.tier3++;
1129
- else tierCounts.skipped++;
1130
- if (lineResult.results && inViewport) {
1131
- resultMap.set(pos, lineResult.results.flat());
1132
- }
1133
- }
1134
- this.pageManager.maintainAfterEval(viewport, this.doc);
1135
- return { lines, resultMap, tierCounts };
1136
- } finally {
1137
- this.engine.setKeystrokeSignal(null);
1138
- disableValueArena();
1139
- }
1140
- }
1141
- /**
1142
- * Background-compile invisible dirty lines beyond the viewport (Tier 3 only).
1143
- *
1144
- * Compiles expressions to discover reads/writes for the dependency graph
1145
- * without executing display-only expressions. Variable definitions are
1146
- * executed to maintain VM state for future Tier-2 executions.
1147
- *
1148
- * This is intended to be called after evaluate() so visible lines are
1149
- * rendered first, then background work fills in the dependency graph.
1150
- *
1151
- * **Phase 5.2h:** This synchronous method is retained for environments
1152
- * without Worker support. Prefer `dispatchBackgroundCompiles()` which
1153
- * offloads compilation to a Web Worker with Transferable bytecode.
1154
- */
1155
- backgroundCompile(viewport) {
1156
- const results = [];
1157
- const docEnd = this.doc.lineCount;
1158
- const startPos = viewport.endLine + 1;
1159
- for (let pos = startPos; pos <= docEnd; pos++) {
1160
- const state = this.doc.getLineAt(pos);
1161
- if (!state) continue;
1162
- if (!state.dirty) continue;
1163
- if (state.bytecodes.length > 0 && !state.isVariableDef) continue;
1164
- const lineResult = this.evaluateSingleLine(state, pos, false);
1165
- results.push(lineResult);
1166
- }
1167
- return results;
1168
- }
1169
- /**
1170
- * Dispatch background compilation to a Web Worker (Phase 5.2h).
1171
- *
1172
- * Collects invisible dirty lines beyond the viewport that need compilation,
1173
- * sends them to the compilation worker, and asynchronously stores the
1174
- * transferred bytecode in the DocumentModel when the worker responds.
1175
- *
1176
- * This is the non-blocking alternative to `backgroundCompile()`. The worker
1177
- * compiles expressions with Transferable ArrayBuffers (zero-copy postMessage),
1178
- * so bytecode appears on the main thread without serialization overhead.
1179
- *
1180
- * Lines that already have cached bytecode (from a previous worker pass or
1181
- * synchronous compile) are skipped, only truly uncompiled dirty lines are
1182
- * sent to the worker.
1183
- *
1184
- * **Usage:** Call after `evaluate()` so visible lines render first, then
1185
- * this fills the bytecode cache for future Tier-2 scrolls.
1186
- *
1187
- * @param viewport The current visible range. Lines beyond viewport.endLine
1188
- * that are dirty and don't have bytecode are dispatched.
1189
- */
1190
- dispatchBackgroundCompiles(viewport) {
1191
- const items = this.collectInvisibleCompileTargets(viewport);
1192
- if (items.length === 0) return;
1193
- if (!this.compilationWorker) {
1194
- this.compilationWorker = new CompilationWorkerManager();
1195
- }
1196
- this.compilationWorker.compileBatch(items).then((results) => {
1197
- this.compilationWorker.storeResults(results, this.doc);
1198
- }).catch((_err) => {
1199
- });
1200
- }
1201
- /**
1202
- * Terminate the compilation worker if active, and unsubscribe from
1203
- * sharedGlobalVariableStore. Call this when the evaluator is no longer
1204
- * needed to clean up resources, every call site that retires a
1205
- * ThreeTierEvaluator (document switch, pane destroy()) already calls
1206
- * this unconditionally, so folding the global-store unsubscribe in here
1207
- * needs no new call sites anywhere.
1208
- */
1209
- terminateWorker() {
1210
- if (this.compilationWorker) {
1211
- this.compilationWorker.terminate();
1212
- this.compilationWorker = null;
1213
- }
1214
- if (this.globalUnsubscribe) {
1215
- this.globalUnsubscribe();
1216
- this.globalUnsubscribe = null;
1217
- }
1218
- }
1219
- /**
1220
- * Get the DocumentModel (read-only access for decoration building).
1221
- */
1222
- getDoc() {
1223
- return this.doc;
1224
- }
1225
- /**
1226
- * Evaluate all dirty lines in the document, regardless of viewport.
1227
- * Used for full re-evaluation after plugin register/unregister.
1228
- */
1229
- evaluateAll(signal) {
1230
- const viewport = { startLine: 1, endLine: this.doc.lineCount };
1231
- const result = this.evaluate(viewport, signal);
1232
- return result;
1233
- }
1234
- /**
1235
- * Zero-allocation viewport evaluation, the Phase 5.2e "holy grail."
1236
- *
1237
- * **Key insight:** When the user scrolls (viewport-only change, no edits),
1238
- * we don't need to re-evaluate from line 1. Instead:
1239
- *
1240
- * 1. Restore the VM to just before the viewport via the nearest checkpoint.
1241
- * 2. Evaluate ONLY the visible lines (Tier 2 for clean cached, Tier 1 for dirty).
1242
- * 3. Lines before the viewport are completely skipped, their state lives in
1243
- * the VM checkpointer's prototypal chain.
1244
- *
1245
- * **Correctness guard:** If any variable-definition line before the viewport
1246
- * is dirty (e.g., the user edited a variable def that hasn't been
1247
- * re-evaluated yet), we clear stale checkpoints and fall back to `evaluate()`
1248
- * which processes from line 1 and rebuilds fresh checkpoints. This
1249
- * guarantees that stale checkpoints are never used as restoration targets.
1250
- * Only variable-def lines matter here, `VMCheckpointer.snapshot()` only
1251
- * records state for lines that write a variable, so a dirty plain-expression
1252
- * line before the viewport has no checkpoint to invalidate (see
1253
- * `DocumentModel.hasAnyDirtyVariableDefLineBefore()`).
1254
- *
1255
- * **Performance:** O(visible lines) instead of O(document length). Target:
1256
- * < 1ms for a typical ~30-line viewport, independent of document size.
1257
- *
1258
- * @param viewport The visible line range.
1259
- * @returns Results for visible lines only. Lines before the viewport are
1260
- * not included in `lines[]` or `resultMap`.
1261
- */
1262
- setViewport(viewport, signal) {
1263
- this.engine.setKeystrokeSignal(signal ?? null);
1264
- if (viewport.startLine > 1 && this.hasDirtyLinesBefore(viewport.startLine)) {
1265
- this.checkpointer?.clear();
1266
- return this.evaluate(viewport, signal);
1267
- }
1268
- this.pageManager.maintainAfterEval(viewport, this.doc);
1269
- this.preloadNextPages(viewport);
1270
- this.restoreTo(viewport.startLine - 1);
1271
- enableValueArena();
1272
- try {
1273
- const result = this.collectEvalResults(viewport.startLine, viewport.endLine);
1274
- return result;
1275
- } finally {
1276
- this.engine.setKeystrokeSignal(null);
1277
- disableValueArena();
1278
- }
1279
- }
1280
- /**
1281
- * Apply incremental line-level changes to the document model.
1282
- *
1283
- * **Phase 5.2f:** Replaces the O(N) `setDocument()` + full re-evaluation
1284
- * with O(changed) incremental updates. Key benefits:
1285
- *
1286
- * 1. Unchanged lines retain their persistent lineIds → bytecode survives
1287
- * 2. Only changed + DAG-downstream lines are marked dirty → Tier 1 re-evaluation
1288
- * 3. Clean lines in viewport use Tier 2 (cached bytecode execution)
1289
- * 4. Clean lines outside viewport are skipped entirely
1290
- *
1291
- * The DAG is fully cleared after propagation: shifted lines would have
1292
- * stale entries keyed by old line numbers, so the DAG is rebuilt from
1293
- * scratch during the subsequent `evaluate()` call.
1294
- *
1295
- * **Caller should follow up with `evaluate(viewport)`** to re-evaluate
1296
- * dirty lines from line 1 and rebuild the DAG + checkpoints.
1297
- *
1298
- * @param changes Line-level changes to apply. Must be non-overlapping.
1299
- * @returns Metadata about the applied changes.
1300
- */
1301
- applyTransaction(changes) {
1302
- const allWrites = /* @__PURE__ */ new Set();
1303
- for (const change of changes) {
1304
- for (let i = 0; i < change.deleteCount; i++) {
1305
- const lineNum = change.startLine + i;
1306
- const writes = this.dag.getWrites(lineNum);
1307
- for (const w of writes) {
1308
- allWrites.add(w);
1309
- }
1310
- this.dag.removeLine(lineNum);
1311
- this.engine.getLineCache().removeAllForLine(lineNum);
1312
- }
1313
- }
1314
- const downstreamLineIds = /* @__PURE__ */ new Set();
1315
- for (const writeVar of allWrites) {
1316
- const affected = this.dag.getAffectedLines(writeVar);
1317
- for (const lineNum of affected) {
1318
- const state = this.doc.getLineAt(lineNum);
1319
- if (state) {
1320
- downstreamLineIds.add(state.lineId);
1321
- }
1322
- }
1323
- }
1324
- const result = this.doc.applyChanges(changes);
1325
- this.checkpointer?.clear();
1326
- for (const lineId of downstreamLineIds) {
1327
- this.doc.markDirty(lineId);
1328
- }
1329
- this.dag.clear();
1330
- return {
1331
- inserted: result.inserted,
1332
- removed: result.removed
1333
- };
1334
- }
1335
- // ── Private helpers ─────────────────────────────────────────────────
1336
- /**
1337
- * Reset running-total accumulators and mark the lines that touch them
1338
- * dirty, so the from-line-1 pass in {@link evaluate} recomputes each total
1339
- * from its seed instead of reading its own previous evaluation's value.
1340
- *
1341
- * A `total += 5` line compiles to no bytecode (it rides the symbolic
1342
- * channel), so a clean one would be skipped by the tier dispatch rather
1343
- * than re-run. It must re-run to re-apply its delta over the freshly-reset
1344
- * base, so every line that WRITES an accumulator name is forced dirty (the
1345
- * DAG drops a self-writing line from its own variable's consumers, so
1346
- * getAffectedLines can't surface them). Pure readers of the total keep
1347
- * their real bytecode and re-run via Tier 2 once the total is correct, so
1348
- * they need no special handling. Cheap: a no-op unless the document
1349
- * actually uses `+=`/`-=`, and accumulators are rare.
1350
- */
1351
- reseedAccumulators() {
1352
- const names = this.engine.resetAccumulators();
1353
- if (names.size === 0) return;
1354
- const docEnd = this.doc.lineCount;
1355
- for (let pos = 1; pos <= docEnd; pos++) {
1356
- const writes = this.dag.getWrites(pos);
1357
- if (writes.size === 0) continue;
1358
- for (const w of writes) {
1359
- if (names.has(w)) {
1360
- this.doc.markDirtyByLineNumber(pos);
1361
- break;
1362
- }
1363
- }
1364
- }
1365
- }
1366
- /**
1367
- * Collect evaluation results for a contiguous range of lines.
1368
- *
1369
- * Used by both `evaluate()` (startLine=1) and `setViewport()` (any start).
1370
- * All lines in the range are treated as in-viewport (visible), callers that
1371
- * need the invisible/dirty → Tier 3 handling should use `evaluate()` instead.
1372
- *
1373
- * @param startLine First line to evaluate (1-based, inclusive).
1374
- * @param endLine Last line to evaluate (1-based, inclusive). Clamped to docEnd.
1375
- */
1376
- collectEvalResults(startLine, endLine) {
1377
- const lines = [];
1378
- const resultMap = /* @__PURE__ */ new Map();
1379
- const tierCounts = { tier1: 0, tier2: 0, tier3: 0, skipped: 0 };
1380
- const docEnd = this.doc.lineCount;
1381
- const evalEnd = Math.min(endLine, docEnd);
1382
- for (let pos = startLine; pos <= evalEnd; pos++) {
1383
- const state = this.doc.getLineAt(pos);
1384
- if (!state) continue;
1385
- const lineResult = this.evaluateSingleLine(state, pos, true);
1386
- lines.push(lineResult);
1387
- if (lineResult.tier === 1 /* Tier1 */) tierCounts.tier1++;
1388
- else if (lineResult.tier === 2 /* Tier2 */) tierCounts.tier2++;
1389
- else if (lineResult.tier === 3 /* Tier3 */) tierCounts.tier3++;
1390
- else tierCounts.skipped++;
1391
- if (lineResult.results) {
1392
- resultMap.set(pos, lineResult.results.flat());
1393
- }
1394
- }
1395
- return { lines, resultMap, tierCounts };
1396
- }
1397
- /**
1398
- * Check whether any **variable-definition** line before `position`
1399
- * (1-based, exclusive) is dirty.
1400
- *
1401
- * Used by `setViewport()` to decide whether to fall back to `evaluate()`:
1402
- * if a variable-def before the viewport is dirty, the checkpoint state
1403
- * `restoreTo()` would use may be stale and we need to reprocess from
1404
- * line 1 to rebuild checkpoints correctly.
1405
- *
1406
- * Deliberately narrower than `DocumentModel.hasAnyDirtyLineBefore()`:
1407
- * checkpoints only snapshot variable-def lines (see VMCheckpointer), so a
1408
- * dirty plain-expression line before the viewport can't have invalidated
1409
- * one, there's nothing checkpointed for it to invalidate. Using the
1410
- * broader check here previously caused a real perf bug: `PageManager`'s
1411
- * cold-page eviction marks evicted non-variable-def lines dirty, so
1412
- * scrolling far into a large, variable-def-free document would trip this
1413
- * guard, fall back to `evaluate()`, which recompiles those lines via
1414
- * Tier 3 (never clearing their dirty flag by design), causing the very
1415
- * next `maintainAfterEval()` to re-evict and re-dirty them, a
1416
- * self-sustaining loop that pinned every subsequent `setViewport()` call
1417
- * to the cost of a full re-evaluation instead of O(visible lines).
1418
- *
1419
- * Delegates to DocumentModel.hasAnyDirtyVariableDefLineBefore(), which
1420
- * tracks dirty lineIds incrementally instead of scanning every line up to
1421
- * `position` on every call. This used to be a real per-scroll cost
1422
- * (benchmarked at ~10ms scrolled near the bottom of a 20k-line document)
1423
- * since it fired on every viewport change, not just edits.
1424
- */
1425
- hasDirtyLinesBefore(position) {
1426
- return this.doc.hasAnyDirtyVariableDefLineBefore(position);
1427
- }
1428
- /**
1429
- * Evaluate a single line using the appropriate tier.
1430
- *
1431
- * Tier assignment logic:
1432
- * - Empty/markdown-only lines → skipped
1433
- * - Dirty + in-viewport → Tier 1 (full pipeline)
1434
- * - Dirty + not in viewport → Tier 3 (compile-only, execute variable defs)
1435
- * - Clean + has bytecode + in viewport → Tier 2 (execute from cache)
1436
- * - Clean + no bytecode → skipped (non-evaluable)
1437
- */
1438
- evaluateSingleLine(state, lineNumber, inViewport) {
1439
- const baseResult = {
1440
- lineId: state.lineId,
1441
- lineNumber
1442
- };
1443
- if (state.isEmpty || isEmptyLine(state.text)) {
1444
- state.isEmpty = true;
1445
- this.doc.markClean(state.lineId);
1446
- return { ...baseResult, tier: 0 /* Skipped */, result: null, error: null };
1447
- }
1448
- const { expressions, inlineSolveCount } = this.extractExpressions(state);
1449
- if (expressions.length === 0) {
1450
- state.isEmpty = true;
1451
- this.doc.markClean(state.lineId);
1452
- return { ...baseResult, tier: 0 /* Skipped */, result: null, error: null };
1453
- }
1454
- if (state.dirty) {
1455
- if (inViewport) {
1456
- return this.evaluateTier1(state, lineNumber, expressions, inlineSolveCount, baseResult);
1457
- } else {
1458
- if (state.bytecodes.length > 0 && state.bytecodes.length === expressions.length && !state.isVariableDef) {
1459
- return { ...baseResult, tier: 0 /* Skipped */, result: null, error: null };
1460
- }
1461
- return this.evaluateTier3(state, lineNumber, expressions, inlineSolveCount, baseResult);
1462
- }
1463
- }
1464
- if (inViewport && state.bytecodes.length > 0) {
1465
- return this.evaluateTier2(state, lineNumber, baseResult);
1466
- }
1467
- return { ...baseResult, tier: 0 /* Skipped */, result: null, error: null };
1468
- }
1469
- /**
1470
- * Tier 1: Full pipeline, lex, parse, compile, execute.
1471
- * Uses the engine's existing evaluateLine() which handles all pipeline
1472
- * stages including DAG updates and LineCache population.
1473
- *
1474
- * Supports multiple expressions per line (inline solves). Evaluates each
1475
- * expression left-to-right through the engine so variable definitions in
1476
- * earlier solves update the VM state before later solves are evaluated.
1477
- * Reads/writes are aggregated across all expressions for the DAG.
1478
- */
1479
- evaluateTier1(state, lineNumber, expressions, inlineSolveCount, baseResult) {
1480
- const allResults = [];
1481
- const allBytecodes = [];
1482
- const allReads = /* @__PURE__ */ new Set();
1483
- const allWrites = /* @__PURE__ */ new Set();
1484
- let hasVariableDef = false;
1485
- let lastValue = null;
1486
- let firstError = null;
1487
- let anyFailed = false;
1488
- let anyPending = false;
1489
- for (const expression of expressions) {
1490
- if (!expression.trim()) continue;
1491
- let value = null;
1492
- let entry;
1493
- try {
1494
- const evaluation = this.engine.evaluateLineDetailed(lineNumber, expression);
1495
- value = evaluation.values;
1496
- lastValue = value[0];
1497
- entry = this.engine.getLineCache().get(lineNumber, expression);
1498
- } catch (e) {
1499
- const errorMessage = e instanceof Error ? e.message : String(e);
1500
- if (!firstError) firstError = errorMessage;
1501
- anyFailed = true;
1502
- value = null;
1503
- }
1504
- if (value && value.some((v) => v.type === 12 /* Pending */)) {
1505
- anyPending = true;
1506
- }
1507
- if (value) {
1508
- allResults.push(value);
1509
- } else {
1510
- allResults.push([errorValue("eval_failed", firstError ?? "unknown error")]);
1511
- }
1512
- if (entry) {
1513
- allBytecodes.push(entry.bytecode);
1514
- for (const r of entry.readVariables) allReads.add(r);
1515
- if (entry.writeVariable) {
1516
- allWrites.add(entry.writeVariable);
1517
- hasVariableDef = true;
1518
- }
1519
- } else {
1520
- try {
1521
- const { program, reads: reads2, writes: writes2 } = this.engine.compileExpression(expression);
1522
- allBytecodes.push(program);
1523
- for (const r of reads2) allReads.add(r);
1524
- for (const w of writes2) allWrites.add(w);
1525
- if (writes2.length > 0) hasVariableDef = true;
1526
- } catch (compileErr) {
1527
- allBytecodes.push({ opcodes: new Uint8Array(0), numbers: new Float64Array(0), strings: [], hasAsync: false });
1528
- if (compileErr instanceof EngineError && compileErr.context) {
1529
- const errReads = compileErr.context.reads;
1530
- const errWrites = compileErr.context.writes;
1531
- if (Array.isArray(errReads)) for (const r of errReads) allReads.add(r);
1532
- if (Array.isArray(errWrites)) for (const w of errWrites) allWrites.add(w);
1533
- }
1534
- }
1535
- }
1536
- }
1537
- const reads = [...allReads];
1538
- const writes = [...allWrites];
1539
- if (anyFailed || anyPending) {
1540
- this.doc.updateLineCompiled(
1541
- state.lineId,
1542
- expressions,
1543
- allBytecodes,
1544
- reads,
1545
- writes,
1546
- hasVariableDef,
1547
- inlineSolveCount
1548
- );
1549
- state.results = allResults;
1550
- state.result = allResults[0]?.[0] ?? null;
1551
- state.inlineSolveCount = inlineSolveCount;
1552
- state.expressions = expressions;
1553
- } else {
1554
- this.doc.updateLineResult(
1555
- state.lineId,
1556
- allResults,
1557
- allBytecodes,
1558
- expressions,
1559
- reads,
1560
- writes,
1561
- hasVariableDef,
1562
- inlineSolveCount
1563
- );
1564
- }
1565
- this.dag.registerLine(lineNumber, reads, writes);
1566
- if (this.checkpointer && writes.length > 0 && !anyFailed && !anyPending) {
1567
- this.checkpointer.snapshot(lineNumber, state.lineId, writes);
1568
- }
1569
- return {
1570
- ...baseResult,
1571
- tier: 1 /* Tier1 */,
1572
- result: lastValue,
1573
- results: allResults,
1574
- error: firstError
1575
- };
1576
- }
1577
- /**
1578
- * Tier 2: Execute from cached bytecode only.
1579
- * Skips lexing, parsing, and compiling, runs the pre-compiled bytecode
1580
- * against the engine's shared VM. Supports multiple bytecodes per line
1581
- * (inline solves), each is executed left-to-right so variable definitions
1582
- * in earlier bytecodes update the VM before later ones run.
1583
- * Assumes the VM already has correct variable state from preceding
1584
- * Tier-1 evaluations.
1585
- */
1586
- evaluateTier2(state, lineNumber, baseResult) {
1587
- if (state.bytecodes.length === 0) {
1588
- return { ...baseResult, tier: 0 /* Skipped */, result: null, error: null };
1589
- }
1590
- const results = [];
1591
- let lastValue = null;
1592
- let firstError = null;
1593
- let anyFailed = false;
1594
- for (const bytecode of state.bytecodes) {
1595
- if (bytecode.opcodes.length === 0) continue;
1596
- try {
1597
- const value = this.engine.executeCached(bytecode, lineNumber);
1598
- lastValue = value;
1599
- results.push([value]);
1600
- } catch (e) {
1601
- const errorMessage = e instanceof Error ? e.message : String(e);
1602
- if (!firstError) firstError = errorMessage;
1603
- anyFailed = true;
1604
- results.push([errorValue("exec_failed", errorMessage)]);
1605
- }
1606
- }
1607
- this.dag.registerLine(lineNumber, state.reads, state.writes);
1608
- state.results = results;
1609
- state.result = results[0]?.[0] ?? null;
1610
- if (anyFailed) {
1611
- this.doc.markDirty(state.lineId);
1612
- }
1613
- return { ...baseResult, tier: 2 /* Tier2 */, result: lastValue, results, error: firstError };
1614
- }
1615
- /**
1616
- * Tier 3: Compile-only for invisible lines.
1617
- * Lex → Parse → Compile to discover reads/writes for the dependency graph.
1618
- * Executes the bytecode ONLY if the line defines a variable (isVariableDef
1619
- * or writes.length > 0), because variable assignments affect VM state
1620
- * that other lines depend on. Pure expression lines are compiled but NOT
1621
- * executed, saving CPU for large documents.
1622
- *
1623
- * Supports multiple expressions per line (inline solves). Each is compiled
1624
- * separately; variable-def expressions are also executed.
1625
- */
1626
- evaluateTier3(state, lineNumber, expressions, inlineSolveCount, baseResult) {
1627
- const allBytecodes = [];
1628
- const allReads = /* @__PURE__ */ new Set();
1629
- const allWrites = /* @__PURE__ */ new Set();
1630
- let hasVariableDef = false;
1631
- let lastResult = null;
1632
- let firstError = null;
1633
- let anyFailed = false;
1634
- let anyPending = false;
1635
- for (const expression of expressions) {
1636
- if (!expression.trim()) continue;
1637
- try {
1638
- const { program, reads: reads2, writes: writes2 } = this.engine.compileExpression(expression);
1639
- allBytecodes.push(program);
1640
- for (const r of reads2) allReads.add(r);
1641
- for (const w of writes2) allWrites.add(w);
1642
- if (writes2.length > 0) hasVariableDef = true;
1643
- if (writes2.length > 0 && program.opcodes.length > 0) {
1644
- lastResult = this.engine.executeCached(program, lineNumber);
1645
- if (lastResult && lastResult.type === 12 /* Pending */) {
1646
- anyPending = true;
1647
- }
1648
- }
1649
- } catch (e) {
1650
- const errorMessage = e instanceof Error ? e.message : String(e);
1651
- if (!firstError) firstError = errorMessage;
1652
- anyFailed = true;
1653
- allBytecodes.push({ opcodes: new Uint8Array(0), numbers: new Float64Array(0), strings: [], hasAsync: false });
1654
- }
1655
- }
1656
- const reads = [...allReads];
1657
- const writes = [...allWrites];
1658
- this.doc.updateLineCompiled(
1659
- state.lineId,
1660
- expressions,
1661
- allBytecodes,
1662
- reads,
1663
- writes,
1664
- hasVariableDef,
1665
- inlineSolveCount
1666
- );
1667
- this.dag.registerLine(lineNumber, reads, writes);
1668
- if (hasVariableDef && lastResult && !anyFailed && !anyPending) {
1669
- state.results = [[lastResult]];
1670
- state.result = lastResult;
1671
- this.doc.markClean(state.lineId);
1672
- if (this.checkpointer) {
1673
- this.checkpointer.snapshot(lineNumber, state.lineId, writes);
1674
- }
1675
- }
1676
- return { ...baseResult, tier: 3 /* Tier3 */, result: lastResult, results: hasVariableDef && lastResult && !anyFailed && !anyPending ? [[lastResult]] : void 0, error: firstError };
1677
- }
1678
- // ── Public checkpoint API (used by Phase 5.2e setViewport) ──────
1679
- /**
1680
- * Restore the VM to the state at or just after the given line number.
1681
- *
1682
- * Finds the nearest checkpoint at or before `lineNumber` and replays
1683
- * all variable definitions from the checkpoint chain into the VM.
1684
- * After calling this, the VM is ready to evaluate lines starting at
1685
- * `lineNumber + 1` without re-evaluating all preceding lines.
1686
- *
1687
- * **Usage:** Phase 5.2e's `setViewport()` calls `restoreTo(viewport.startLine - 1)`
1688
- * before evaluating only the newly visible lines. This is the key to
1689
- * O(visible lines) scrolling.
1690
- *
1691
- * @param lineNumber The line number to restore to. Variables defined
1692
- * at lines ≤ this number will be available in the VM.
1693
- */
1694
- restoreTo(lineNumber) {
1695
- if (this.checkpointer) {
1696
- this.checkpointer.restoreTo(lineNumber);
1697
- }
1698
- }
1699
- /**
1700
- * Get the VM checkpointer, or null if checkpointing is disabled.
1701
- */
1702
- getCheckpointer() {
1703
- return this.checkpointer;
1704
- }
1705
- /**
1706
- * Get the PageManager (Phase 5.2g).
1707
- * Exposed for testing.
1708
- */
1709
- getPageManager() {
1710
- return this.pageManager;
1711
- }
1712
- // ── Phase 5.2g: Directional preloading ──────────────────────────
1713
- /**
1714
- * Preload the next 1–2 pages in the current scroll direction.
1715
- *
1716
- * Called during `setViewport()` (scroll-only path). Collects dirty
1717
- * uncompiled lines in pages just beyond the viewport and dispatches
1718
- * them to the background compilation worker so bytecode is ready
1719
- * before the user scrolls those lines into view.
1720
- */
1721
- preloadNextPages(viewport) {
1722
- const targets = this.pageManager.getPreloadTargets(viewport, this.doc);
1723
- if (targets.length === 0) return;
1724
- if (!this.compilationWorker) {
1725
- this.compilationWorker = new CompilationWorkerManager();
1726
- }
1727
- this.compilationWorker.compileBatch(targets).then((results) => {
1728
- this.compilationWorker.storeResults(results, this.doc);
1729
- }).catch((_err) => {
1730
- });
1731
- }
1732
- /**
1733
- * Collect invisible dirty lines that need background compilation.
1734
- *
1735
- * Iterates lines beyond `viewport.endLine`, filtering for:
1736
- * - Dirty lines (need re-compilation)
1737
- * - Non-empty, non-markdown lines
1738
- * - No existing bytecode (skip already-compiled Tier 3 lines)
1739
- *
1740
- * Returns CompileRequestItem[] suitable for CompilationWorkerManager.
1741
- */
1742
- collectInvisibleCompileTargets(viewport) {
1743
- const items = [];
1744
- const docEnd = this.doc.lineCount;
1745
- const startPos = viewport.endLine + 1;
1746
- for (let pos = startPos; pos <= docEnd; pos++) {
1747
- const state = this.doc.getLineAt(pos);
1748
- if (!state) continue;
1749
- if (!state.dirty) continue;
1750
- if (state.bytecodes.length > 0 && !state.isVariableDef) continue;
1751
- if (state.isEmpty || isEmptyLine(state.text)) continue;
1752
- const { expressions } = this.extractExpressions(state);
1753
- if (expressions.length === 0) continue;
1754
- for (const expression of expressions) {
1755
- if (!expression.trim()) continue;
1756
- items.push({
1757
- lineId: state.lineId,
1758
- expression,
1759
- textHash: state.textHash
1760
- });
1761
- }
1762
- }
1763
- return items;
1764
- }
1765
- /**
1766
- * Extract all evaluable expressions from a LineState.
1767
- *
1768
- * For full-line expressions: returns `{ expressions: [trimmedText], inlineSolveCount: 0 }`.
1769
- * For inline solve lines: returns `{ expressions: [...allSolves], inlineSolveCount: N }`.
1770
- * For pre-extracted (cached) expressions: returns the cached array.
1771
- *
1772
- * Inline solves are extracted left-to-right via the sharedLexer, so variable
1773
- * definitions in earlier solves (e.g., `s\`x = 5\` more text s\`x + 1\``)
1774
- * correctly update the VM state before later solves are evaluated.
1775
- */
1776
- extractExpressions(state) {
1777
- if (state.expressions.length > 0) {
1778
- return { expressions: state.expressions, inlineSolveCount: state.inlineSolveCount };
1779
- }
1780
- const trimmed = state.text.trim();
1781
- if (trimmed.length === 0) return { expressions: [], inlineSolveCount: 0 };
1782
- const inlineSpans = sharedLexer.findInlineSolves(state.text);
1783
- if (inlineSpans.length > 0) {
1784
- return {
1785
- expressions: inlineSpans.map((s) => s.expression),
1786
- inlineSolveCount: inlineSpans.length
1787
- };
1788
- }
1789
- return { expressions: [trimmed], inlineSolveCount: 0 };
1790
- }
1791
- };
1792
-
1793
- export { DocumentModel, EvalTier, ThreeTierEvaluator };
1794
- //# sourceMappingURL=chunk-7JM3F4KL.js.map
1795
- //# sourceMappingURL=chunk-7JM3F4KL.js.map