solve-engine 1.0.1 → 1.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 (237) hide show
  1. package/dist/{BytecodeBuilder-B0xskcv5.d.cts → BytecodeBuilder-Bp9xeTmX.d.cts} +4 -0
  2. package/dist/{BytecodeBuilder-B0xskcv5.d.ts → BytecodeBuilder-Bp9xeTmX.d.ts} +4 -0
  3. package/dist/{Configuration-B-G5gTRn.d.cts → Configuration-C9W8tJv_.d.cts} +53 -1
  4. package/dist/{Configuration-B-G5gTRn.d.ts → Configuration-C9W8tJv_.d.ts} +53 -1
  5. package/dist/{EngineError-LU7W7AgI.d.cts → EngineError-B61GS1jp.d.cts} +14 -0
  6. package/dist/{EngineError-LU7W7AgI.d.ts → EngineError-B61GS1jp.d.ts} +14 -0
  7. package/dist/FormattingSettings-CJHyxcYu.d.cts +27 -0
  8. package/dist/FormattingSettings-CJHyxcYu.d.ts +27 -0
  9. package/dist/{Lexer-D78E2yDW.d.cts → Lexer-BOs7euZe.d.cts} +58 -1
  10. package/dist/{Lexer-BN5mt30n.d.ts → Lexer-CSI_lwbW.d.ts} +58 -1
  11. package/dist/PackageCompatibility-B-7rK1TD.d.cts +76 -0
  12. package/dist/PackageCompatibility-Dh59eF-X.d.ts +76 -0
  13. package/dist/{PackageRegistry-B37mRvvz.d.cts → PackageRegistry-BHWJP83F.d.cts} +449 -11
  14. package/dist/{PackageRegistry-DCUEzbQt.d.ts → PackageRegistry-_8rDlvxI.d.ts} +449 -11
  15. package/dist/{Parselet-BaySkMV3.d.ts → Parselet-BBT8riYh.d.ts} +12 -3
  16. package/dist/{Parselet-DuI1Pjiq.d.cts → Parselet-BHcgK9S7.d.cts} +12 -3
  17. package/dist/{ScopeManager-B6GzdhVG.d.cts → ScopeManager-8vf02dwj.d.cts} +56 -5
  18. package/dist/{ScopeManager-udv4Twwq.d.ts → ScopeManager-CxA24W5n.d.ts} +56 -5
  19. package/dist/{Token-BzG5G4ja.d.cts → Token-B1hdkedD.d.cts} +9 -0
  20. package/dist/{Token-BzG5G4ja.d.ts → Token-B1hdkedD.d.ts} +9 -0
  21. package/dist/{TokenNormalizer-t_GotBxr.d.ts → TokenNormalizer-C6VzZgHa.d.ts} +1 -1
  22. package/dist/{TokenNormalizer-DGVa24Q-.d.cts → TokenNormalizer-DRc1Js1V.d.cts} +1 -1
  23. package/dist/{VMCheckpoints-DwLjivM7.d.cts → VMCheckpoints-ELYqITdF.d.cts} +3 -3
  24. package/dist/{VMCheckpoints-BiaIlOOY.d.ts → VMCheckpoints-MK--EBH2.d.ts} +3 -3
  25. package/dist/{Value-CXJqDH9J.d.cts → Value-BUi1RA3S.d.cts} +124 -5
  26. package/dist/{Value-CXJqDH9J.d.ts → Value-BUi1RA3S.d.ts} +124 -5
  27. package/dist/WorkerError-_-RkoQ5P.d.ts +75 -0
  28. package/dist/WorkerError-gzmaopj2.d.cts +75 -0
  29. package/dist/{chunk-GQCOSXMG.js → chunk-267JPOTF.js} +43 -5
  30. package/dist/chunk-267JPOTF.js.map +1 -0
  31. package/dist/{chunk-JMXUNXQS.cjs → chunk-2TZKENDH.cjs} +51 -8
  32. package/dist/chunk-2TZKENDH.cjs.map +1 -0
  33. package/dist/chunk-3OWCDIPN.js +215 -0
  34. package/dist/chunk-3OWCDIPN.js.map +1 -0
  35. package/dist/{chunk-VB37OC6I.js → chunk-4D6NIHE2.js} +40 -3
  36. package/dist/chunk-4D6NIHE2.js.map +1 -0
  37. package/dist/{chunk-TY3TLZAW.cjs → chunk-536WPM2V.cjs} +18 -2
  38. package/dist/chunk-536WPM2V.cjs.map +1 -0
  39. package/dist/chunk-5HRB36DK.js +405 -0
  40. package/dist/chunk-5HRB36DK.js.map +1 -0
  41. package/dist/chunk-5ON7PUAZ.js +12 -0
  42. package/dist/chunk-5ON7PUAZ.js.map +1 -0
  43. package/dist/{chunk-KV7UW6T6.js → chunk-7KYSUDQO.js} +12 -5
  44. package/dist/chunk-7KYSUDQO.js.map +1 -0
  45. package/dist/{chunk-6WFMPTGB.cjs → chunk-7ZX6B7SY.cjs} +774 -528
  46. package/dist/chunk-7ZX6B7SY.cjs.map +1 -0
  47. package/dist/chunk-ALYRJ72W.cjs +434 -0
  48. package/dist/chunk-ALYRJ72W.cjs.map +1 -0
  49. package/dist/{chunk-5KMIY374.cjs → chunk-B4HBEFTB.cjs} +17 -2
  50. package/dist/chunk-B4HBEFTB.cjs.map +1 -0
  51. package/dist/chunk-B7NLZMQ3.cjs +74 -0
  52. package/dist/chunk-B7NLZMQ3.cjs.map +1 -0
  53. package/dist/{chunk-UQ3UIZJC.js → chunk-BLI4NIQY.js} +6 -2
  54. package/dist/chunk-BLI4NIQY.js.map +1 -0
  55. package/dist/{chunk-BHTNFEGZ.cjs → chunk-C75AFGVD.cjs} +11 -11
  56. package/dist/{chunk-BHTNFEGZ.cjs.map → chunk-C75AFGVD.cjs.map} +1 -1
  57. package/dist/{chunk-G535KJEG.js → chunk-CCBZZQAE.js} +2 -2
  58. package/dist/{chunk-G535KJEG.js.map → chunk-CCBZZQAE.js.map} +1 -1
  59. package/dist/chunk-CKQMXMHR.cjs +219 -0
  60. package/dist/chunk-CKQMXMHR.cjs.map +1 -0
  61. package/dist/{chunk-PFUESQTW.cjs → chunk-EJ3ILXX6.cjs} +48 -2
  62. package/dist/chunk-EJ3ILXX6.cjs.map +1 -0
  63. package/dist/{chunk-526PMQOA.js → chunk-ENKKJYD3.js} +10 -4
  64. package/dist/chunk-ENKKJYD3.js.map +1 -0
  65. package/dist/{chunk-5X2PTP6F.cjs → chunk-ENRIK36Q.cjs} +2 -12
  66. package/dist/chunk-ENRIK36Q.cjs.map +1 -0
  67. package/dist/{chunk-3D7V24DG.js → chunk-ERCOHGXD.js} +17 -2
  68. package/dist/chunk-ERCOHGXD.js.map +1 -0
  69. package/dist/{chunk-IF532O7C.js → chunk-FD5ZZHEU.js} +3 -12
  70. package/dist/chunk-FD5ZZHEU.js.map +1 -0
  71. package/dist/{chunk-TBN7DEHO.js → chunk-G7Z4HJQA.js} +11 -5
  72. package/dist/chunk-G7Z4HJQA.js.map +1 -0
  73. package/dist/{chunk-QY25VWBF.js → chunk-GQMUHVE3.js} +142 -6
  74. package/dist/chunk-GQMUHVE3.js.map +1 -0
  75. package/dist/chunk-GUG7SNSV.js +1764 -0
  76. package/dist/chunk-GUG7SNSV.js.map +1 -0
  77. package/dist/{chunk-UM6BVY2S.cjs → chunk-HIQ5HSZL.cjs} +175 -43
  78. package/dist/chunk-HIQ5HSZL.cjs.map +1 -0
  79. package/dist/{chunk-HVQFNJKE.cjs → chunk-HVRVSI2Z.cjs} +104 -86
  80. package/dist/chunk-HVRVSI2Z.cjs.map +1 -0
  81. package/dist/{chunk-3LAEG75D.js → chunk-I4GAWIPW.js} +24 -6
  82. package/dist/chunk-I4GAWIPW.js.map +1 -0
  83. package/dist/{chunk-PA4VC73I.cjs → chunk-J45BCEZ4.cjs} +33 -27
  84. package/dist/chunk-J45BCEZ4.cjs.map +1 -0
  85. package/dist/{chunk-V5PYO44Y.js → chunk-JIPATHVY.js} +1853 -2638
  86. package/dist/chunk-JIPATHVY.js.map +1 -0
  87. package/dist/{chunk-YPPPYLSR.js → chunk-JJIXHXFQ.js} +5 -5
  88. package/dist/{chunk-YPPPYLSR.js.map → chunk-JJIXHXFQ.js.map} +1 -1
  89. package/dist/chunk-L2TE7PMO.cjs +14 -0
  90. package/dist/chunk-L2TE7PMO.cjs.map +1 -0
  91. package/dist/{chunk-B7TLZABL.cjs → chunk-MG6Q3DUO.cjs} +1962 -2746
  92. package/dist/chunk-MG6Q3DUO.cjs.map +1 -0
  93. package/dist/{chunk-R3PY4G7J.js → chunk-MVTOCRV2.js} +48 -3
  94. package/dist/chunk-MVTOCRV2.js.map +1 -0
  95. package/dist/{chunk-Y7FT4IQT.js → chunk-NKW7LKYU.js} +266 -28
  96. package/dist/chunk-NKW7LKYU.js.map +1 -0
  97. package/dist/{chunk-O3ANBHSA.js → chunk-NNQ2TYDF.js} +123 -5
  98. package/dist/chunk-NNQ2TYDF.js.map +1 -0
  99. package/dist/{chunk-5F4C26RU.js → chunk-OADDUPT3.js} +4 -4
  100. package/dist/{chunk-5F4C26RU.js.map → chunk-OADDUPT3.js.map} +1 -1
  101. package/dist/{chunk-3AFRJYP4.cjs → chunk-OTN6SZOD.cjs} +1868 -393
  102. package/dist/chunk-OTN6SZOD.cjs.map +1 -0
  103. package/dist/{chunk-5LI5EPGJ.cjs → chunk-QFTDTX6K.cjs} +40 -3
  104. package/dist/chunk-QFTDTX6K.cjs.map +1 -0
  105. package/dist/{chunk-HMOISHXR.js → chunk-RRLHC37V.js} +1530 -57
  106. package/dist/chunk-RRLHC37V.js.map +1 -0
  107. package/dist/chunk-SNHVVOJK.cjs +1768 -0
  108. package/dist/chunk-SNHVVOJK.cjs.map +1 -0
  109. package/dist/{chunk-HDP7VK3C.cjs → chunk-SRGQ72IR.cjs} +649 -349
  110. package/dist/chunk-SRGQ72IR.cjs.map +1 -0
  111. package/dist/{chunk-4B2CNWQU.cjs → chunk-SSV46KFA.cjs} +14 -7
  112. package/dist/chunk-SSV46KFA.cjs.map +1 -0
  113. package/dist/{chunk-AJA6LUI7.js → chunk-UO6BUV6K.js} +18 -2
  114. package/dist/chunk-UO6BUV6K.js.map +1 -0
  115. package/dist/chunk-WWQEY7BV.js +67 -0
  116. package/dist/chunk-WWQEY7BV.js.map +1 -0
  117. package/dist/{chunk-5WVP4YHP.js → chunk-WXEHD6TT.js} +333 -33
  118. package/dist/chunk-WXEHD6TT.js.map +1 -0
  119. package/dist/{chunk-47LRVGOT.cjs → chunk-XA4CKRML.cjs} +2 -2
  120. package/dist/{chunk-47LRVGOT.cjs.map → chunk-XA4CKRML.cjs.map} +1 -1
  121. package/dist/{chunk-6KFYJ6TD.cjs → chunk-XIYYHA65.cjs} +6 -2
  122. package/dist/chunk-XIYYHA65.cjs.map +1 -0
  123. package/dist/{chunk-KBSXGXPM.cjs → chunk-XJGJCF2R.cjs} +6 -6
  124. package/dist/{chunk-KBSXGXPM.cjs.map → chunk-XJGJCF2R.cjs.map} +1 -1
  125. package/dist/{chunk-YWQ6V4ZN.cjs → chunk-YTIYVHL7.cjs} +211 -75
  126. package/dist/chunk-YTIYVHL7.cjs.map +1 -0
  127. package/dist/{chunk-TMA4RCEN.js → chunk-Z7XGGLI2.js} +3 -3
  128. package/dist/{chunk-TMA4RCEN.js.map → chunk-Z7XGGLI2.js.map} +1 -1
  129. package/dist/{chunk-A2N2GFCG.cjs → chunk-ZVTWQLK4.cjs} +10 -10
  130. package/dist/{chunk-A2N2GFCG.cjs.map → chunk-ZVTWQLK4.cjs.map} +1 -1
  131. package/dist/{chunk-2XLQPQKI.cjs → chunk-ZXCESUJS.cjs} +15 -9
  132. package/dist/chunk-ZXCESUJS.cjs.map +1 -0
  133. package/dist/constants.cjs +5 -5
  134. package/dist/constants.d.cts +1 -1
  135. package/dist/constants.d.ts +1 -1
  136. package/dist/constants.js +2 -2
  137. package/dist/engine.cjs +52 -35
  138. package/dist/engine.d.cts +13 -13
  139. package/dist/engine.d.ts +13 -13
  140. package/dist/engine.js +26 -21
  141. package/dist/errors.cjs +44 -19
  142. package/dist/errors.d.cts +3 -2
  143. package/dist/errors.d.ts +3 -2
  144. package/dist/errors.js +2 -1
  145. package/dist/format.cjs +19 -169
  146. package/dist/format.cjs.map +1 -1
  147. package/dist/format.d.cts +18 -26
  148. package/dist/format.d.ts +18 -26
  149. package/dist/format.js +7 -171
  150. package/dist/format.js.map +1 -1
  151. package/dist/index.cjs +250 -31
  152. package/dist/index.cjs.map +1 -1
  153. package/dist/index.d.cts +110 -74
  154. package/dist/index.d.ts +110 -74
  155. package/dist/index.js +228 -23
  156. package/dist/index.js.map +1 -1
  157. package/dist/language.cjs +9 -9
  158. package/dist/language.d.cts +12 -12
  159. package/dist/language.d.ts +12 -12
  160. package/dist/language.js +3 -3
  161. package/dist/lexer.cjs +16 -16
  162. package/dist/lexer.d.cts +3 -3
  163. package/dist/lexer.d.ts +3 -3
  164. package/dist/lexer.js +5 -5
  165. package/dist/normalizer.cjs +10 -10
  166. package/dist/normalizer.d.cts +3 -3
  167. package/dist/normalizer.d.ts +3 -3
  168. package/dist/normalizer.js +4 -4
  169. package/dist/packages.cjs +45 -36
  170. package/dist/packages.d.cts +135 -31
  171. package/dist/packages.d.ts +135 -31
  172. package/dist/packages.js +14 -13
  173. package/dist/parser.cjs +16 -16
  174. package/dist/parser.d.cts +6 -5
  175. package/dist/parser.d.ts +6 -5
  176. package/dist/parser.js +6 -6
  177. package/dist/{pipeline-BEb3hujr.d.cts → pipeline-CtfJtPQc.d.cts} +3 -3
  178. package/dist/{pipeline-B6k5lCB7.d.ts → pipeline-DCd5M6Gk.d.ts} +3 -3
  179. package/dist/resolvers.d.cts +3 -3
  180. package/dist/resolvers.d.ts +3 -3
  181. package/dist/testing.cjs +478 -0
  182. package/dist/testing.cjs.map +1 -0
  183. package/dist/testing.d.cts +271 -0
  184. package/dist/testing.d.ts +271 -0
  185. package/dist/testing.js +470 -0
  186. package/dist/testing.js.map +1 -0
  187. package/dist/uom.cjs +16 -16
  188. package/dist/uom.d.cts +3 -3
  189. package/dist/uom.d.ts +3 -3
  190. package/dist/uom.js +6 -6
  191. package/dist/utilities.cjs +6 -5
  192. package/dist/utilities.js +2 -1
  193. package/dist/vm.cjs +34 -34
  194. package/dist/vm.d.cts +8 -8
  195. package/dist/vm.d.ts +8 -8
  196. package/dist/vm.js +9 -9
  197. package/dist/worker.cjs +493 -0
  198. package/dist/worker.cjs.map +1 -0
  199. package/dist/worker.d.cts +509 -0
  200. package/dist/worker.d.ts +509 -0
  201. package/dist/worker.js +484 -0
  202. package/dist/worker.js.map +1 -0
  203. package/package.json +21 -1
  204. package/dist/chunk-2XLQPQKI.cjs.map +0 -1
  205. package/dist/chunk-3AFRJYP4.cjs.map +0 -1
  206. package/dist/chunk-3D7V24DG.js.map +0 -1
  207. package/dist/chunk-3LAEG75D.js.map +0 -1
  208. package/dist/chunk-4B2CNWQU.cjs.map +0 -1
  209. package/dist/chunk-526PMQOA.js.map +0 -1
  210. package/dist/chunk-5KMIY374.cjs.map +0 -1
  211. package/dist/chunk-5LI5EPGJ.cjs.map +0 -1
  212. package/dist/chunk-5WVP4YHP.js.map +0 -1
  213. package/dist/chunk-5X2PTP6F.cjs.map +0 -1
  214. package/dist/chunk-6KFYJ6TD.cjs.map +0 -1
  215. package/dist/chunk-6WFMPTGB.cjs.map +0 -1
  216. package/dist/chunk-AJA6LUI7.js.map +0 -1
  217. package/dist/chunk-B7TLZABL.cjs.map +0 -1
  218. package/dist/chunk-GQCOSXMG.js.map +0 -1
  219. package/dist/chunk-HDP7VK3C.cjs.map +0 -1
  220. package/dist/chunk-HMOISHXR.js.map +0 -1
  221. package/dist/chunk-HVQFNJKE.cjs.map +0 -1
  222. package/dist/chunk-IF532O7C.js.map +0 -1
  223. package/dist/chunk-JMXUNXQS.cjs.map +0 -1
  224. package/dist/chunk-KV7UW6T6.js.map +0 -1
  225. package/dist/chunk-O3ANBHSA.js.map +0 -1
  226. package/dist/chunk-PA4VC73I.cjs.map +0 -1
  227. package/dist/chunk-PFUESQTW.cjs.map +0 -1
  228. package/dist/chunk-QY25VWBF.js.map +0 -1
  229. package/dist/chunk-R3PY4G7J.js.map +0 -1
  230. package/dist/chunk-TBN7DEHO.js.map +0 -1
  231. package/dist/chunk-TY3TLZAW.cjs.map +0 -1
  232. package/dist/chunk-UM6BVY2S.cjs.map +0 -1
  233. package/dist/chunk-UQ3UIZJC.js.map +0 -1
  234. package/dist/chunk-V5PYO44Y.js.map +0 -1
  235. package/dist/chunk-VB37OC6I.js.map +0 -1
  236. package/dist/chunk-Y7FT4IQT.js.map +0 -1
  237. package/dist/chunk-YWQ6V4ZN.cjs.map +0 -1
@@ -0,0 +1,1764 @@
1
+ import { isEmptyLine, engine_worker_default } from './chunk-JIPATHVY.js';
2
+ import { djb2Hash } from './chunk-5ON7PUAZ.js';
3
+ import { countLines } from './chunk-3BOK2LDK.js';
4
+ import { sharedGlobalVariableStore, globalDagKey } from './chunk-NKW7LKYU.js';
5
+ import { enableValueArena, disableValueArena, errorValue } from './chunk-267JPOTF.js';
6
+ import { DEFAULT_CONFIG } from './chunk-G7Z4HJQA.js';
7
+ import { sharedLexer } from './chunk-OADDUPT3.js';
8
+ import { ErrorFactory, EngineError } from './chunk-ERCOHGXD.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
+ const lines = [];
1112
+ const resultMap = /* @__PURE__ */ new Map();
1113
+ const tierCounts = { tier1: 0, tier2: 0, tier3: 0, skipped: 0 };
1114
+ const docEnd = this.doc.lineCount;
1115
+ const evalEnd = Math.min(viewport.endLine, docEnd);
1116
+ for (let pos = 1; pos <= evalEnd; pos++) {
1117
+ const state = this.doc.getLineAt(pos);
1118
+ if (!state) {
1119
+ tierCounts.skipped++;
1120
+ continue;
1121
+ }
1122
+ const inViewport = pos >= viewport.startLine && pos <= viewport.endLine;
1123
+ const lineResult = this.evaluateSingleLine(state, pos, inViewport);
1124
+ lines.push(lineResult);
1125
+ if (lineResult.tier === 1 /* Tier1 */) tierCounts.tier1++;
1126
+ else if (lineResult.tier === 2 /* Tier2 */) tierCounts.tier2++;
1127
+ else if (lineResult.tier === 3 /* Tier3 */) tierCounts.tier3++;
1128
+ else tierCounts.skipped++;
1129
+ if (lineResult.results && inViewport) {
1130
+ resultMap.set(pos, lineResult.results.flat());
1131
+ }
1132
+ }
1133
+ this.pageManager.maintainAfterEval(viewport, this.doc);
1134
+ return { lines, resultMap, tierCounts };
1135
+ } finally {
1136
+ this.engine.setKeystrokeSignal(null);
1137
+ disableValueArena();
1138
+ }
1139
+ }
1140
+ /**
1141
+ * Background-compile invisible dirty lines beyond the viewport (Tier 3 only).
1142
+ *
1143
+ * Compiles expressions to discover reads/writes for the dependency graph
1144
+ * without executing display-only expressions. Variable definitions are
1145
+ * executed to maintain VM state for future Tier-2 executions.
1146
+ *
1147
+ * This is intended to be called after evaluate() so visible lines are
1148
+ * rendered first, then background work fills in the dependency graph.
1149
+ *
1150
+ * **Phase 5.2h:** This synchronous method is retained for environments
1151
+ * without Worker support. Prefer `dispatchBackgroundCompiles()` which
1152
+ * offloads compilation to a Web Worker with Transferable bytecode.
1153
+ */
1154
+ backgroundCompile(viewport) {
1155
+ const results = [];
1156
+ const docEnd = this.doc.lineCount;
1157
+ const startPos = viewport.endLine + 1;
1158
+ for (let pos = startPos; pos <= docEnd; pos++) {
1159
+ const state = this.doc.getLineAt(pos);
1160
+ if (!state) continue;
1161
+ if (!state.dirty) continue;
1162
+ if (state.bytecodes.length > 0 && !state.isVariableDef) continue;
1163
+ const lineResult = this.evaluateSingleLine(state, pos, false);
1164
+ results.push(lineResult);
1165
+ }
1166
+ return results;
1167
+ }
1168
+ /**
1169
+ * Dispatch background compilation to a Web Worker (Phase 5.2h).
1170
+ *
1171
+ * Collects invisible dirty lines beyond the viewport that need compilation,
1172
+ * sends them to the compilation worker, and asynchronously stores the
1173
+ * transferred bytecode in the DocumentModel when the worker responds.
1174
+ *
1175
+ * This is the non-blocking alternative to `backgroundCompile()`. The worker
1176
+ * compiles expressions with Transferable ArrayBuffers (zero-copy postMessage),
1177
+ * so bytecode appears on the main thread without serialization overhead.
1178
+ *
1179
+ * Lines that already have cached bytecode (from a previous worker pass or
1180
+ * synchronous compile) are skipped, only truly uncompiled dirty lines are
1181
+ * sent to the worker.
1182
+ *
1183
+ * **Usage:** Call after `evaluate()` so visible lines render first, then
1184
+ * this fills the bytecode cache for future Tier-2 scrolls.
1185
+ *
1186
+ * @param viewport The current visible range. Lines beyond viewport.endLine
1187
+ * that are dirty and don't have bytecode are dispatched.
1188
+ */
1189
+ dispatchBackgroundCompiles(viewport) {
1190
+ const items = this.collectInvisibleCompileTargets(viewport);
1191
+ if (items.length === 0) return;
1192
+ if (!this.compilationWorker) {
1193
+ this.compilationWorker = new CompilationWorkerManager();
1194
+ }
1195
+ this.compilationWorker.compileBatch(items).then((results) => {
1196
+ this.compilationWorker.storeResults(results, this.doc);
1197
+ }).catch((_err) => {
1198
+ });
1199
+ }
1200
+ /**
1201
+ * Terminate the compilation worker if active, and unsubscribe from
1202
+ * sharedGlobalVariableStore. Call this when the evaluator is no longer
1203
+ * needed to clean up resources, every call site that retires a
1204
+ * ThreeTierEvaluator (document switch, pane destroy()) already calls
1205
+ * this unconditionally, so folding the global-store unsubscribe in here
1206
+ * needs no new call sites anywhere.
1207
+ */
1208
+ terminateWorker() {
1209
+ if (this.compilationWorker) {
1210
+ this.compilationWorker.terminate();
1211
+ this.compilationWorker = null;
1212
+ }
1213
+ if (this.globalUnsubscribe) {
1214
+ this.globalUnsubscribe();
1215
+ this.globalUnsubscribe = null;
1216
+ }
1217
+ }
1218
+ /**
1219
+ * Get the DocumentModel (read-only access for decoration building).
1220
+ */
1221
+ getDoc() {
1222
+ return this.doc;
1223
+ }
1224
+ /**
1225
+ * Evaluate all dirty lines in the document, regardless of viewport.
1226
+ * Used for full re-evaluation after plugin register/unregister.
1227
+ */
1228
+ evaluateAll(signal) {
1229
+ const viewport = { startLine: 1, endLine: this.doc.lineCount };
1230
+ const result = this.evaluate(viewport, signal);
1231
+ return result;
1232
+ }
1233
+ /**
1234
+ * Zero-allocation viewport evaluation, the Phase 5.2e "holy grail."
1235
+ *
1236
+ * **Key insight:** When the user scrolls (viewport-only change, no edits),
1237
+ * we don't need to re-evaluate from line 1. Instead:
1238
+ *
1239
+ * 1. Restore the VM to just before the viewport via the nearest checkpoint.
1240
+ * 2. Evaluate ONLY the visible lines (Tier 2 for clean cached, Tier 1 for dirty).
1241
+ * 3. Lines before the viewport are completely skipped, their state lives in
1242
+ * the VM checkpointer's prototypal chain.
1243
+ *
1244
+ * **Correctness guard:** If any variable-definition line before the viewport
1245
+ * is dirty (e.g., the user edited a variable def that hasn't been
1246
+ * re-evaluated yet), we clear stale checkpoints and fall back to `evaluate()`
1247
+ * which processes from line 1 and rebuilds fresh checkpoints. This
1248
+ * guarantees that stale checkpoints are never used as restoration targets.
1249
+ * Only variable-def lines matter here, `VMCheckpointer.snapshot()` only
1250
+ * records state for lines that write a variable, so a dirty plain-expression
1251
+ * line before the viewport has no checkpoint to invalidate (see
1252
+ * `DocumentModel.hasAnyDirtyVariableDefLineBefore()`).
1253
+ *
1254
+ * **Performance:** O(visible lines) instead of O(document length). Target:
1255
+ * < 1ms for a typical ~30-line viewport, independent of document size.
1256
+ *
1257
+ * @param viewport The visible line range.
1258
+ * @returns Results for visible lines only. Lines before the viewport are
1259
+ * not included in `lines[]` or `resultMap`.
1260
+ */
1261
+ setViewport(viewport, signal) {
1262
+ this.engine.setKeystrokeSignal(signal ?? null);
1263
+ if (viewport.startLine > 1 && this.hasDirtyLinesBefore(viewport.startLine)) {
1264
+ this.checkpointer?.clear();
1265
+ return this.evaluate(viewport, signal);
1266
+ }
1267
+ this.pageManager.maintainAfterEval(viewport, this.doc);
1268
+ this.preloadNextPages(viewport);
1269
+ this.restoreTo(viewport.startLine - 1);
1270
+ enableValueArena();
1271
+ try {
1272
+ const result = this.collectEvalResults(viewport.startLine, viewport.endLine);
1273
+ return result;
1274
+ } finally {
1275
+ this.engine.setKeystrokeSignal(null);
1276
+ disableValueArena();
1277
+ }
1278
+ }
1279
+ /**
1280
+ * Apply incremental line-level changes to the document model.
1281
+ *
1282
+ * **Phase 5.2f:** Replaces the O(N) `setDocument()` + full re-evaluation
1283
+ * with O(changed) incremental updates. Key benefits:
1284
+ *
1285
+ * 1. Unchanged lines retain their persistent lineIds → bytecode survives
1286
+ * 2. Only changed + DAG-downstream lines are marked dirty → Tier 1 re-evaluation
1287
+ * 3. Clean lines in viewport use Tier 2 (cached bytecode execution)
1288
+ * 4. Clean lines outside viewport are skipped entirely
1289
+ *
1290
+ * The DAG is fully cleared after propagation: shifted lines would have
1291
+ * stale entries keyed by old line numbers, so the DAG is rebuilt from
1292
+ * scratch during the subsequent `evaluate()` call.
1293
+ *
1294
+ * **Caller should follow up with `evaluate(viewport)`** to re-evaluate
1295
+ * dirty lines from line 1 and rebuild the DAG + checkpoints.
1296
+ *
1297
+ * @param changes Line-level changes to apply. Must be non-overlapping.
1298
+ * @returns Metadata about the applied changes.
1299
+ */
1300
+ applyTransaction(changes) {
1301
+ const allWrites = /* @__PURE__ */ new Set();
1302
+ for (const change of changes) {
1303
+ for (let i = 0; i < change.deleteCount; i++) {
1304
+ const lineNum = change.startLine + i;
1305
+ const writes = this.dag.getWrites(lineNum);
1306
+ for (const w of writes) {
1307
+ allWrites.add(w);
1308
+ }
1309
+ this.dag.removeLine(lineNum);
1310
+ this.engine.getLineCache().removeAllForLine(lineNum);
1311
+ }
1312
+ }
1313
+ const downstreamLineIds = /* @__PURE__ */ new Set();
1314
+ for (const writeVar of allWrites) {
1315
+ const affected = this.dag.getAffectedLines(writeVar);
1316
+ for (const lineNum of affected) {
1317
+ const state = this.doc.getLineAt(lineNum);
1318
+ if (state) {
1319
+ downstreamLineIds.add(state.lineId);
1320
+ }
1321
+ }
1322
+ }
1323
+ const result = this.doc.applyChanges(changes);
1324
+ this.checkpointer?.clear();
1325
+ for (const lineId of downstreamLineIds) {
1326
+ this.doc.markDirty(lineId);
1327
+ }
1328
+ this.dag.clear();
1329
+ return {
1330
+ inserted: result.inserted,
1331
+ removed: result.removed
1332
+ };
1333
+ }
1334
+ // ── Private helpers ─────────────────────────────────────────────────
1335
+ /**
1336
+ * Collect evaluation results for a contiguous range of lines.
1337
+ *
1338
+ * Used by both `evaluate()` (startLine=1) and `setViewport()` (any start).
1339
+ * All lines in the range are treated as in-viewport (visible), callers that
1340
+ * need the invisible/dirty → Tier 3 handling should use `evaluate()` instead.
1341
+ *
1342
+ * @param startLine First line to evaluate (1-based, inclusive).
1343
+ * @param endLine Last line to evaluate (1-based, inclusive). Clamped to docEnd.
1344
+ */
1345
+ collectEvalResults(startLine, endLine) {
1346
+ const lines = [];
1347
+ const resultMap = /* @__PURE__ */ new Map();
1348
+ const tierCounts = { tier1: 0, tier2: 0, tier3: 0, skipped: 0 };
1349
+ const docEnd = this.doc.lineCount;
1350
+ const evalEnd = Math.min(endLine, docEnd);
1351
+ for (let pos = startLine; pos <= evalEnd; pos++) {
1352
+ const state = this.doc.getLineAt(pos);
1353
+ if (!state) continue;
1354
+ const lineResult = this.evaluateSingleLine(state, pos, true);
1355
+ lines.push(lineResult);
1356
+ if (lineResult.tier === 1 /* Tier1 */) tierCounts.tier1++;
1357
+ else if (lineResult.tier === 2 /* Tier2 */) tierCounts.tier2++;
1358
+ else if (lineResult.tier === 3 /* Tier3 */) tierCounts.tier3++;
1359
+ else tierCounts.skipped++;
1360
+ if (lineResult.results) {
1361
+ resultMap.set(pos, lineResult.results.flat());
1362
+ }
1363
+ }
1364
+ return { lines, resultMap, tierCounts };
1365
+ }
1366
+ /**
1367
+ * Check whether any **variable-definition** line before `position`
1368
+ * (1-based, exclusive) is dirty.
1369
+ *
1370
+ * Used by `setViewport()` to decide whether to fall back to `evaluate()`:
1371
+ * if a variable-def before the viewport is dirty, the checkpoint state
1372
+ * `restoreTo()` would use may be stale and we need to reprocess from
1373
+ * line 1 to rebuild checkpoints correctly.
1374
+ *
1375
+ * Deliberately narrower than `DocumentModel.hasAnyDirtyLineBefore()`:
1376
+ * checkpoints only snapshot variable-def lines (see VMCheckpointer), so a
1377
+ * dirty plain-expression line before the viewport can't have invalidated
1378
+ * one, there's nothing checkpointed for it to invalidate. Using the
1379
+ * broader check here previously caused a real perf bug: `PageManager`'s
1380
+ * cold-page eviction marks evicted non-variable-def lines dirty, so
1381
+ * scrolling far into a large, variable-def-free document would trip this
1382
+ * guard, fall back to `evaluate()`, which recompiles those lines via
1383
+ * Tier 3 (never clearing their dirty flag by design), causing the very
1384
+ * next `maintainAfterEval()` to re-evict and re-dirty them, a
1385
+ * self-sustaining loop that pinned every subsequent `setViewport()` call
1386
+ * to the cost of a full re-evaluation instead of O(visible lines).
1387
+ *
1388
+ * Delegates to DocumentModel.hasAnyDirtyVariableDefLineBefore(), which
1389
+ * tracks dirty lineIds incrementally instead of scanning every line up to
1390
+ * `position` on every call. This used to be a real per-scroll cost
1391
+ * (benchmarked at ~10ms scrolled near the bottom of a 20k-line document)
1392
+ * since it fired on every viewport change, not just edits.
1393
+ */
1394
+ hasDirtyLinesBefore(position) {
1395
+ return this.doc.hasAnyDirtyVariableDefLineBefore(position);
1396
+ }
1397
+ /**
1398
+ * Evaluate a single line using the appropriate tier.
1399
+ *
1400
+ * Tier assignment logic:
1401
+ * - Empty/markdown-only lines → skipped
1402
+ * - Dirty + in-viewport → Tier 1 (full pipeline)
1403
+ * - Dirty + not in viewport → Tier 3 (compile-only, execute variable defs)
1404
+ * - Clean + has bytecode + in viewport → Tier 2 (execute from cache)
1405
+ * - Clean + no bytecode → skipped (non-evaluable)
1406
+ */
1407
+ evaluateSingleLine(state, lineNumber, inViewport) {
1408
+ const baseResult = {
1409
+ lineId: state.lineId,
1410
+ lineNumber
1411
+ };
1412
+ if (state.isEmpty || isEmptyLine(state.text)) {
1413
+ state.isEmpty = true;
1414
+ this.doc.markClean(state.lineId);
1415
+ return { ...baseResult, tier: 0 /* Skipped */, result: null, error: null };
1416
+ }
1417
+ const { expressions, inlineSolveCount } = this.extractExpressions(state);
1418
+ if (expressions.length === 0) {
1419
+ state.isEmpty = true;
1420
+ this.doc.markClean(state.lineId);
1421
+ return { ...baseResult, tier: 0 /* Skipped */, result: null, error: null };
1422
+ }
1423
+ if (state.dirty) {
1424
+ if (inViewport) {
1425
+ return this.evaluateTier1(state, lineNumber, expressions, inlineSolveCount, baseResult);
1426
+ } else {
1427
+ if (state.bytecodes.length > 0 && state.bytecodes.length === expressions.length && !state.isVariableDef) {
1428
+ return { ...baseResult, tier: 0 /* Skipped */, result: null, error: null };
1429
+ }
1430
+ return this.evaluateTier3(state, lineNumber, expressions, inlineSolveCount, baseResult);
1431
+ }
1432
+ }
1433
+ if (inViewport && state.bytecodes.length > 0) {
1434
+ return this.evaluateTier2(state, lineNumber, baseResult);
1435
+ }
1436
+ return { ...baseResult, tier: 0 /* Skipped */, result: null, error: null };
1437
+ }
1438
+ /**
1439
+ * Tier 1: Full pipeline, lex, parse, compile, execute.
1440
+ * Uses the engine's existing evaluateLine() which handles all pipeline
1441
+ * stages including DAG updates and LineCache population.
1442
+ *
1443
+ * Supports multiple expressions per line (inline solves). Evaluates each
1444
+ * expression left-to-right through the engine so variable definitions in
1445
+ * earlier solves update the VM state before later solves are evaluated.
1446
+ * Reads/writes are aggregated across all expressions for the DAG.
1447
+ */
1448
+ evaluateTier1(state, lineNumber, expressions, inlineSolveCount, baseResult) {
1449
+ const allResults = [];
1450
+ const allBytecodes = [];
1451
+ const allReads = /* @__PURE__ */ new Set();
1452
+ const allWrites = /* @__PURE__ */ new Set();
1453
+ let hasVariableDef = false;
1454
+ let lastValue = null;
1455
+ let firstError = null;
1456
+ let anyFailed = false;
1457
+ let anyPending = false;
1458
+ for (const expression of expressions) {
1459
+ if (!expression.trim()) continue;
1460
+ let value = null;
1461
+ let entry;
1462
+ try {
1463
+ const evaluation = this.engine.evaluateLineDetailed(lineNumber, expression);
1464
+ value = evaluation.values;
1465
+ lastValue = value[0];
1466
+ entry = this.engine.getLineCache().get(lineNumber, expression);
1467
+ } catch (e) {
1468
+ const errorMessage = e instanceof Error ? e.message : String(e);
1469
+ if (!firstError) firstError = errorMessage;
1470
+ anyFailed = true;
1471
+ value = null;
1472
+ }
1473
+ if (value && value.some((v) => v.type === 12 /* Pending */)) {
1474
+ anyPending = true;
1475
+ }
1476
+ if (value) {
1477
+ allResults.push(value);
1478
+ } else {
1479
+ allResults.push([errorValue("eval_failed", firstError ?? "unknown error")]);
1480
+ }
1481
+ if (entry) {
1482
+ allBytecodes.push(entry.bytecode);
1483
+ for (const r of entry.readVariables) allReads.add(r);
1484
+ if (entry.writeVariable) {
1485
+ allWrites.add(entry.writeVariable);
1486
+ hasVariableDef = true;
1487
+ }
1488
+ } else {
1489
+ try {
1490
+ const { program, reads: reads2, writes: writes2 } = this.engine.compileExpression(expression);
1491
+ allBytecodes.push(program);
1492
+ for (const r of reads2) allReads.add(r);
1493
+ for (const w of writes2) allWrites.add(w);
1494
+ if (writes2.length > 0) hasVariableDef = true;
1495
+ } catch (compileErr) {
1496
+ allBytecodes.push({ opcodes: new Uint8Array(0), numbers: new Float64Array(0), strings: [], hasAsync: false });
1497
+ if (compileErr instanceof EngineError && compileErr.context) {
1498
+ const errReads = compileErr.context.reads;
1499
+ const errWrites = compileErr.context.writes;
1500
+ if (Array.isArray(errReads)) for (const r of errReads) allReads.add(r);
1501
+ if (Array.isArray(errWrites)) for (const w of errWrites) allWrites.add(w);
1502
+ }
1503
+ }
1504
+ }
1505
+ }
1506
+ const reads = [...allReads];
1507
+ const writes = [...allWrites];
1508
+ if (anyFailed || anyPending) {
1509
+ this.doc.updateLineCompiled(
1510
+ state.lineId,
1511
+ expressions,
1512
+ allBytecodes,
1513
+ reads,
1514
+ writes,
1515
+ hasVariableDef,
1516
+ inlineSolveCount
1517
+ );
1518
+ state.results = allResults;
1519
+ state.result = allResults[0]?.[0] ?? null;
1520
+ state.inlineSolveCount = inlineSolveCount;
1521
+ state.expressions = expressions;
1522
+ } else {
1523
+ this.doc.updateLineResult(
1524
+ state.lineId,
1525
+ allResults,
1526
+ allBytecodes,
1527
+ expressions,
1528
+ reads,
1529
+ writes,
1530
+ hasVariableDef,
1531
+ inlineSolveCount
1532
+ );
1533
+ }
1534
+ this.dag.registerLine(lineNumber, reads, writes);
1535
+ if (this.checkpointer && writes.length > 0 && !anyFailed && !anyPending) {
1536
+ this.checkpointer.snapshot(lineNumber, state.lineId, writes);
1537
+ }
1538
+ return {
1539
+ ...baseResult,
1540
+ tier: 1 /* Tier1 */,
1541
+ result: lastValue,
1542
+ results: allResults,
1543
+ error: firstError
1544
+ };
1545
+ }
1546
+ /**
1547
+ * Tier 2: Execute from cached bytecode only.
1548
+ * Skips lexing, parsing, and compiling, runs the pre-compiled bytecode
1549
+ * against the engine's shared VM. Supports multiple bytecodes per line
1550
+ * (inline solves), each is executed left-to-right so variable definitions
1551
+ * in earlier bytecodes update the VM before later ones run.
1552
+ * Assumes the VM already has correct variable state from preceding
1553
+ * Tier-1 evaluations.
1554
+ */
1555
+ evaluateTier2(state, lineNumber, baseResult) {
1556
+ if (state.bytecodes.length === 0) {
1557
+ return { ...baseResult, tier: 0 /* Skipped */, result: null, error: null };
1558
+ }
1559
+ const results = [];
1560
+ let lastValue = null;
1561
+ let firstError = null;
1562
+ let anyFailed = false;
1563
+ for (const bytecode of state.bytecodes) {
1564
+ if (bytecode.opcodes.length === 0) continue;
1565
+ try {
1566
+ const value = this.engine.executeCached(bytecode, lineNumber);
1567
+ lastValue = value;
1568
+ results.push([value]);
1569
+ } catch (e) {
1570
+ const errorMessage = e instanceof Error ? e.message : String(e);
1571
+ if (!firstError) firstError = errorMessage;
1572
+ anyFailed = true;
1573
+ results.push([errorValue("exec_failed", errorMessage)]);
1574
+ }
1575
+ }
1576
+ this.dag.registerLine(lineNumber, state.reads, state.writes);
1577
+ state.results = results;
1578
+ state.result = results[0]?.[0] ?? null;
1579
+ if (anyFailed) {
1580
+ this.doc.markDirty(state.lineId);
1581
+ }
1582
+ return { ...baseResult, tier: 2 /* Tier2 */, result: lastValue, results, error: firstError };
1583
+ }
1584
+ /**
1585
+ * Tier 3: Compile-only for invisible lines.
1586
+ * Lex → Parse → Compile to discover reads/writes for the dependency graph.
1587
+ * Executes the bytecode ONLY if the line defines a variable (isVariableDef
1588
+ * or writes.length > 0), because variable assignments affect VM state
1589
+ * that other lines depend on. Pure expression lines are compiled but NOT
1590
+ * executed, saving CPU for large documents.
1591
+ *
1592
+ * Supports multiple expressions per line (inline solves). Each is compiled
1593
+ * separately; variable-def expressions are also executed.
1594
+ */
1595
+ evaluateTier3(state, lineNumber, expressions, inlineSolveCount, baseResult) {
1596
+ const allBytecodes = [];
1597
+ const allReads = /* @__PURE__ */ new Set();
1598
+ const allWrites = /* @__PURE__ */ new Set();
1599
+ let hasVariableDef = false;
1600
+ let lastResult = null;
1601
+ let firstError = null;
1602
+ let anyFailed = false;
1603
+ let anyPending = false;
1604
+ for (const expression of expressions) {
1605
+ if (!expression.trim()) continue;
1606
+ try {
1607
+ const { program, reads: reads2, writes: writes2 } = this.engine.compileExpression(expression);
1608
+ allBytecodes.push(program);
1609
+ for (const r of reads2) allReads.add(r);
1610
+ for (const w of writes2) allWrites.add(w);
1611
+ if (writes2.length > 0) hasVariableDef = true;
1612
+ if (writes2.length > 0 && program.opcodes.length > 0) {
1613
+ lastResult = this.engine.executeCached(program, lineNumber);
1614
+ if (lastResult && lastResult.type === 12 /* Pending */) {
1615
+ anyPending = true;
1616
+ }
1617
+ }
1618
+ } catch (e) {
1619
+ const errorMessage = e instanceof Error ? e.message : String(e);
1620
+ if (!firstError) firstError = errorMessage;
1621
+ anyFailed = true;
1622
+ allBytecodes.push({ opcodes: new Uint8Array(0), numbers: new Float64Array(0), strings: [], hasAsync: false });
1623
+ }
1624
+ }
1625
+ const reads = [...allReads];
1626
+ const writes = [...allWrites];
1627
+ this.doc.updateLineCompiled(
1628
+ state.lineId,
1629
+ expressions,
1630
+ allBytecodes,
1631
+ reads,
1632
+ writes,
1633
+ hasVariableDef,
1634
+ inlineSolveCount
1635
+ );
1636
+ this.dag.registerLine(lineNumber, reads, writes);
1637
+ if (hasVariableDef && lastResult && !anyFailed && !anyPending) {
1638
+ state.results = [[lastResult]];
1639
+ state.result = lastResult;
1640
+ this.doc.markClean(state.lineId);
1641
+ if (this.checkpointer) {
1642
+ this.checkpointer.snapshot(lineNumber, state.lineId, writes);
1643
+ }
1644
+ }
1645
+ return { ...baseResult, tier: 3 /* Tier3 */, result: lastResult, results: hasVariableDef && lastResult && !anyFailed && !anyPending ? [[lastResult]] : void 0, error: firstError };
1646
+ }
1647
+ // ── Public checkpoint API (used by Phase 5.2e setViewport) ──────
1648
+ /**
1649
+ * Restore the VM to the state at or just after the given line number.
1650
+ *
1651
+ * Finds the nearest checkpoint at or before `lineNumber` and replays
1652
+ * all variable definitions from the checkpoint chain into the VM.
1653
+ * After calling this, the VM is ready to evaluate lines starting at
1654
+ * `lineNumber + 1` without re-evaluating all preceding lines.
1655
+ *
1656
+ * **Usage:** Phase 5.2e's `setViewport()` calls `restoreTo(viewport.startLine - 1)`
1657
+ * before evaluating only the newly visible lines. This is the key to
1658
+ * O(visible lines) scrolling.
1659
+ *
1660
+ * @param lineNumber The line number to restore to. Variables defined
1661
+ * at lines ≤ this number will be available in the VM.
1662
+ */
1663
+ restoreTo(lineNumber) {
1664
+ if (this.checkpointer) {
1665
+ this.checkpointer.restoreTo(lineNumber);
1666
+ }
1667
+ }
1668
+ /**
1669
+ * Get the VM checkpointer, or null if checkpointing is disabled.
1670
+ */
1671
+ getCheckpointer() {
1672
+ return this.checkpointer;
1673
+ }
1674
+ /**
1675
+ * Get the PageManager (Phase 5.2g).
1676
+ * Exposed for testing.
1677
+ */
1678
+ getPageManager() {
1679
+ return this.pageManager;
1680
+ }
1681
+ // ── Phase 5.2g: Directional preloading ──────────────────────────
1682
+ /**
1683
+ * Preload the next 1–2 pages in the current scroll direction.
1684
+ *
1685
+ * Called during `setViewport()` (scroll-only path). Collects dirty
1686
+ * uncompiled lines in pages just beyond the viewport and dispatches
1687
+ * them to the background compilation worker so bytecode is ready
1688
+ * before the user scrolls those lines into view.
1689
+ */
1690
+ preloadNextPages(viewport) {
1691
+ const targets = this.pageManager.getPreloadTargets(viewport, this.doc);
1692
+ if (targets.length === 0) return;
1693
+ if (!this.compilationWorker) {
1694
+ this.compilationWorker = new CompilationWorkerManager();
1695
+ }
1696
+ this.compilationWorker.compileBatch(targets).then((results) => {
1697
+ this.compilationWorker.storeResults(results, this.doc);
1698
+ }).catch((_err) => {
1699
+ });
1700
+ }
1701
+ /**
1702
+ * Collect invisible dirty lines that need background compilation.
1703
+ *
1704
+ * Iterates lines beyond `viewport.endLine`, filtering for:
1705
+ * - Dirty lines (need re-compilation)
1706
+ * - Non-empty, non-markdown lines
1707
+ * - No existing bytecode (skip already-compiled Tier 3 lines)
1708
+ *
1709
+ * Returns CompileRequestItem[] suitable for CompilationWorkerManager.
1710
+ */
1711
+ collectInvisibleCompileTargets(viewport) {
1712
+ const items = [];
1713
+ const docEnd = this.doc.lineCount;
1714
+ const startPos = viewport.endLine + 1;
1715
+ for (let pos = startPos; pos <= docEnd; pos++) {
1716
+ const state = this.doc.getLineAt(pos);
1717
+ if (!state) continue;
1718
+ if (!state.dirty) continue;
1719
+ if (state.bytecodes.length > 0 && !state.isVariableDef) continue;
1720
+ if (state.isEmpty || isEmptyLine(state.text)) continue;
1721
+ const { expressions } = this.extractExpressions(state);
1722
+ if (expressions.length === 0) continue;
1723
+ for (const expression of expressions) {
1724
+ if (!expression.trim()) continue;
1725
+ items.push({
1726
+ lineId: state.lineId,
1727
+ expression,
1728
+ textHash: state.textHash
1729
+ });
1730
+ }
1731
+ }
1732
+ return items;
1733
+ }
1734
+ /**
1735
+ * Extract all evaluable expressions from a LineState.
1736
+ *
1737
+ * For full-line expressions: returns `{ expressions: [trimmedText], inlineSolveCount: 0 }`.
1738
+ * For inline solve lines: returns `{ expressions: [...allSolves], inlineSolveCount: N }`.
1739
+ * For pre-extracted (cached) expressions: returns the cached array.
1740
+ *
1741
+ * Inline solves are extracted left-to-right via the sharedLexer, so variable
1742
+ * definitions in earlier solves (e.g., `s\`x = 5\` more text s\`x + 1\``)
1743
+ * correctly update the VM state before later solves are evaluated.
1744
+ */
1745
+ extractExpressions(state) {
1746
+ if (state.expressions.length > 0) {
1747
+ return { expressions: state.expressions, inlineSolveCount: state.inlineSolveCount };
1748
+ }
1749
+ const trimmed = state.text.trim();
1750
+ if (trimmed.length === 0) return { expressions: [], inlineSolveCount: 0 };
1751
+ const inlineSpans = sharedLexer.findInlineSolves(state.text);
1752
+ if (inlineSpans.length > 0) {
1753
+ return {
1754
+ expressions: inlineSpans.map((s) => s.expression),
1755
+ inlineSolveCount: inlineSpans.length
1756
+ };
1757
+ }
1758
+ return { expressions: [trimmed], inlineSolveCount: 0 };
1759
+ }
1760
+ };
1761
+
1762
+ export { DocumentModel, EvalTier, ThreeTierEvaluator };
1763
+ //# sourceMappingURL=chunk-GUG7SNSV.js.map
1764
+ //# sourceMappingURL=chunk-GUG7SNSV.js.map