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.
- package/README.md +12 -17
- package/dist/{BytecodeBuilder-Bp9xeTmX.d.cts → BytecodeBuilder-DGGeByAP.d.cts} +18 -0
- package/dist/{BytecodeBuilder-Bp9xeTmX.d.ts → BytecodeBuilder-DGGeByAP.d.ts} +18 -0
- package/dist/{Configuration-C9W8tJv_.d.cts → Configuration-B6W0-T67.d.cts} +17 -4
- package/dist/{Configuration-C9W8tJv_.d.ts → Configuration-B6W0-T67.d.ts} +17 -4
- package/dist/{EngineError-CNA_rHY-.d.cts → EngineError-Ce1lPkjZ.d.cts} +2 -0
- package/dist/{EngineError-CNA_rHY-.d.ts → EngineError-Ce1lPkjZ.d.ts} +2 -0
- package/dist/{PackageCompatibility-B6NX9IaN.d.cts → PackageCompatibility-Bn5jnBtA.d.cts} +2 -2
- package/dist/{PackageCompatibility-Ceg5XdAp.d.ts → PackageCompatibility-CIvq2MP5.d.ts} +2 -2
- package/dist/{PackageRegistry-DrCPQNyy.d.ts → PackageRegistry-DzeiWcv4.d.ts} +93 -172
- package/dist/{PackageRegistry-DnJYVw9G.d.cts → PackageRegistry-dpdurBVO.d.cts} +93 -172
- package/dist/{Parselet-Bhf7d0_W.d.ts → Parselet-B-zoPrTa.d.ts} +8 -5
- package/dist/{Parselet-Cv7S7KRt.d.cts → Parselet-C4Wu055_.d.cts} +8 -5
- package/dist/{ScopeManager-Bzq87GfA.d.ts → ScopeManager-C2LDOrDx.d.ts} +7 -16
- package/dist/{ScopeManager-DRDBVfan.d.cts → ScopeManager-D7uMXbhS.d.cts} +7 -16
- package/dist/{VMCheckpoints-C6c17Hbo.d.ts → VMCheckpoints-CGyFhivM.d.ts} +3 -3
- package/dist/{VMCheckpoints-dZxSMGHG.d.cts → VMCheckpoints-I9jg3jWR.d.cts} +3 -3
- package/dist/{Value-DZNQ_PU7.d.cts → Value-CCi_Eecs.d.cts} +40 -0
- package/dist/{Value-DZNQ_PU7.d.ts → Value-CCi_Eecs.d.ts} +40 -0
- package/dist/{WorkerError-Djd7GGGa.d.cts → WorkerError-B4p6PNfx.d.cts} +1 -1
- package/dist/{WorkerError-B7t7R2-m.d.ts → WorkerError-Dhj9BQ_A.d.ts} +1 -1
- package/dist/chunk-2JMFUQZH.js +2 -0
- package/dist/chunk-2JMFUQZH.js.map +1 -0
- package/dist/chunk-2RWAXT6O.js +0 -1
- package/dist/chunk-4BZIYU7S.cjs +3 -0
- package/dist/chunk-4BZIYU7S.cjs.map +1 -0
- package/dist/chunk-4J7XZSZJ.cjs +5 -0
- package/dist/chunk-4J7XZSZJ.cjs.map +1 -0
- package/dist/chunk-4QVBSG6B.cjs +2 -0
- package/dist/chunk-4QVBSG6B.cjs.map +1 -0
- package/dist/chunk-5IJD5L3O.cjs +2 -0
- package/dist/chunk-5IJD5L3O.cjs.map +1 -0
- package/dist/chunk-62LMTO4F.js +2 -0
- package/dist/chunk-62LMTO4F.js.map +1 -0
- package/dist/chunk-6CY44ZPG.js +2 -0
- package/dist/chunk-6CY44ZPG.js.map +1 -0
- package/dist/chunk-6G3PMEPA.js +2 -0
- package/dist/chunk-6G3PMEPA.js.map +1 -0
- package/dist/chunk-6INX773F.cjs +2 -0
- package/dist/chunk-6INX773F.cjs.map +1 -0
- package/dist/chunk-6KFVG6UY.cjs +2 -0
- package/dist/{chunk-YJHY7CMN.cjs.map → chunk-6KFVG6UY.cjs.map} +1 -1
- package/dist/chunk-76F3LCIL.js +4 -0
- package/dist/chunk-76F3LCIL.js.map +1 -0
- package/dist/chunk-7GK3XEZF.js +2 -0
- package/dist/chunk-7GK3XEZF.js.map +1 -0
- package/dist/chunk-APN442VD.cjs +2 -0
- package/dist/chunk-APN442VD.cjs.map +1 -0
- package/dist/chunk-AXMQG5TS.cjs +2 -0
- package/dist/chunk-AXMQG5TS.cjs.map +1 -0
- package/dist/chunk-CIQOK7Q4.cjs +2 -0
- package/dist/chunk-CIQOK7Q4.cjs.map +1 -0
- package/dist/chunk-E6Z4NQAS.js +2 -0
- package/dist/chunk-E6Z4NQAS.js.map +1 -0
- package/dist/chunk-EFJCC6FJ.cjs +2 -0
- package/dist/chunk-EFJCC6FJ.cjs.map +1 -0
- package/dist/chunk-ESUN2THE.cjs +2 -0
- package/dist/chunk-ESUN2THE.cjs.map +1 -0
- package/dist/chunk-EVAOPEO4.js +2 -0
- package/dist/chunk-EVAOPEO4.js.map +1 -0
- package/dist/chunk-EYRBENHC.js +3 -0
- package/dist/chunk-EYRBENHC.js.map +1 -0
- package/dist/chunk-FDE5HWDI.cjs +2 -0
- package/dist/chunk-FDE5HWDI.cjs.map +1 -0
- package/dist/chunk-FWW3M36J.cjs +2 -0
- package/dist/chunk-FWW3M36J.cjs.map +1 -0
- package/dist/chunk-GOIQYUWV.js +2 -0
- package/dist/chunk-GOIQYUWV.js.map +1 -0
- package/dist/chunk-HFKDWQUL.js +2 -0
- package/dist/chunk-HFKDWQUL.js.map +1 -0
- package/dist/chunk-HLBYHXQD.cjs +3 -0
- package/dist/chunk-HLBYHXQD.cjs.map +1 -0
- package/dist/chunk-IANAMBJQ.cjs +2 -0
- package/dist/chunk-IANAMBJQ.cjs.map +1 -0
- package/dist/chunk-IJMNVBIS.js +2 -0
- package/dist/chunk-IJMNVBIS.js.map +1 -0
- package/dist/chunk-J4LZD4ZY.js +3 -0
- package/dist/chunk-J4LZD4ZY.js.map +1 -0
- package/dist/chunk-JAK3RAFA.cjs +2 -0
- package/dist/chunk-JAK3RAFA.cjs.map +1 -0
- package/dist/chunk-JFAJN3C2.cjs +2 -0
- package/dist/chunk-JFAJN3C2.cjs.map +1 -0
- package/dist/chunk-JPFCXLJV.js +2 -0
- package/dist/chunk-JPFCXLJV.js.map +1 -0
- package/dist/chunk-JSPKKNPQ.js +3 -0
- package/dist/chunk-JSPKKNPQ.js.map +1 -0
- package/dist/chunk-L3FPQSGN.js +2 -0
- package/dist/chunk-L3FPQSGN.js.map +1 -0
- package/dist/chunk-LR4E4A4W.cjs +2 -0
- package/dist/chunk-LR4E4A4W.cjs.map +1 -0
- package/dist/chunk-MIQBJGGR.js +2 -0
- package/dist/chunk-MIQBJGGR.js.map +1 -0
- package/dist/chunk-MPB7KUN5.js +3 -0
- package/dist/chunk-MPB7KUN5.js.map +1 -0
- package/dist/chunk-MSYX32PF.cjs +2 -0
- package/dist/chunk-MSYX32PF.cjs.map +1 -0
- package/dist/chunk-MVZUTETT.js +2 -0
- package/dist/chunk-MVZUTETT.js.map +1 -0
- package/dist/chunk-N7N7MPMK.cjs +2 -0
- package/dist/chunk-N7N7MPMK.cjs.map +1 -0
- package/dist/chunk-NGBBNL4K.cjs +1 -3
- package/dist/chunk-P6WPEUAJ.cjs +2 -0
- package/dist/chunk-P6WPEUAJ.cjs.map +1 -0
- package/dist/chunk-PS272DZJ.cjs +2 -0
- package/dist/chunk-PS272DZJ.cjs.map +1 -0
- package/dist/chunk-QXQE7X4S.js +2 -0
- package/dist/chunk-QXQE7X4S.js.map +1 -0
- package/dist/chunk-R2ENWQ76.js +2 -0
- package/dist/chunk-R2ENWQ76.js.map +1 -0
- package/dist/chunk-R2SZFJTT.cjs +2 -0
- package/dist/chunk-R2SZFJTT.cjs.map +1 -0
- package/dist/chunk-RAF57WYO.js +2 -0
- package/dist/chunk-RAF57WYO.js.map +1 -0
- package/dist/chunk-RSF25YSJ.js +2 -0
- package/dist/chunk-RSF25YSJ.js.map +1 -0
- package/dist/chunk-SOMGSIO4.cjs +3 -0
- package/dist/chunk-SOMGSIO4.cjs.map +1 -0
- package/dist/chunk-SUXRZWH2.cjs +3 -0
- package/dist/chunk-SUXRZWH2.cjs.map +1 -0
- package/dist/chunk-SYYE3QAX.cjs +2 -0
- package/dist/chunk-SYYE3QAX.cjs.map +1 -0
- package/dist/chunk-SZGK6RIP.cjs +2 -0
- package/dist/chunk-SZGK6RIP.cjs.map +1 -0
- package/dist/chunk-TCZSPH4A.js +2 -0
- package/dist/chunk-TCZSPH4A.js.map +1 -0
- package/dist/chunk-TLG7VZRX.cjs +2 -0
- package/dist/chunk-TLG7VZRX.cjs.map +1 -0
- package/dist/chunk-TRBXW6HW.js +2 -0
- package/dist/{chunk-AQNHHJMJ.cjs.map → chunk-TRBXW6HW.js.map} +1 -1
- package/dist/chunk-TTFO4YDP.cjs +2 -0
- package/dist/chunk-TTFO4YDP.cjs.map +1 -0
- package/dist/chunk-TWC7K3ZX.js +2 -0
- package/dist/chunk-TWC7K3ZX.js.map +1 -0
- package/dist/chunk-UDQ57ZRX.cjs +2 -0
- package/dist/chunk-UDQ57ZRX.cjs.map +1 -0
- package/dist/chunk-UI6IFGBT.js +2 -0
- package/dist/chunk-UI6IFGBT.js.map +1 -0
- package/dist/chunk-UURM7P3P.cjs +4 -0
- package/dist/chunk-UURM7P3P.cjs.map +1 -0
- package/dist/chunk-W2JAR233.js +2 -0
- package/dist/chunk-W2JAR233.js.map +1 -0
- package/dist/chunk-WGZ3FNHI.js +2 -0
- package/dist/chunk-WGZ3FNHI.js.map +1 -0
- package/dist/chunk-WN5CMP4T.cjs +3 -0
- package/dist/chunk-WN5CMP4T.cjs.map +1 -0
- package/dist/chunk-XEIDV5JP.js +2 -0
- package/dist/chunk-XEIDV5JP.js.map +1 -0
- package/dist/chunk-XNIWQHXY.js +2 -0
- package/dist/chunk-XNIWQHXY.js.map +1 -0
- package/dist/chunk-XR7HEC7B.js +5 -0
- package/dist/chunk-XR7HEC7B.js.map +1 -0
- package/dist/chunk-Y7O4D3BJ.cjs +2 -0
- package/dist/chunk-Y7O4D3BJ.cjs.map +1 -0
- package/dist/chunk-YAYBVVG2.js +3 -0
- package/dist/chunk-YAYBVVG2.js.map +1 -0
- package/dist/chunk-YJ2OPULK.js +2 -0
- package/dist/chunk-YJ2OPULK.js.map +1 -0
- package/dist/chunk-YVKHEAFT.js +2 -0
- package/dist/chunk-YVKHEAFT.js.map +1 -0
- package/dist/chunk-ZCNBT44X.cjs +2 -0
- package/dist/chunk-ZCNBT44X.cjs.map +1 -0
- package/dist/chunk-ZLRJ7TDP.cjs +2 -0
- package/dist/chunk-ZLRJ7TDP.cjs.map +1 -0
- package/dist/constants.cjs +1 -21
- package/dist/constants.d.cts +1 -1
- package/dist/constants.d.ts +1 -1
- package/dist/constants.js +1 -4
- package/dist/engine.cjs +1 -94
- package/dist/engine.d.cts +10 -11
- package/dist/engine.d.ts +10 -11
- package/dist/engine.js +1 -37
- package/dist/errors.cjs +1 -105
- package/dist/errors.d.cts +3 -3
- package/dist/errors.d.ts +3 -3
- package/dist/errors.js +1 -4
- package/dist/format.cjs +1 -26
- package/dist/format.d.cts +2 -2
- package/dist/format.d.ts +2 -2
- package/dist/format.js +1 -9
- package/dist/index.cjs +1 -314
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +52 -20
- package/dist/index.d.ts +52 -20
- package/dist/index.js +1 -278
- package/dist/index.js.map +1 -1
- package/dist/language.cjs +1 -369
- package/dist/language.cjs.map +1 -1
- package/dist/language.d.cts +9 -10
- package/dist/language.d.ts +9 -10
- package/dist/language.js +1 -348
- package/dist/language.js.map +1 -1
- package/dist/lexer.cjs +1 -63
- package/dist/lexer.js +1 -10
- package/dist/normalizer.cjs +1 -39
- package/dist/normalizer.js +1 -10
- package/dist/packages.cjs +1 -132
- package/dist/packages.d.cts +8 -9
- package/dist/packages.d.ts +8 -9
- package/dist/packages.js +1 -23
- package/dist/parser.cjs +1 -54
- package/dist/parser.d.cts +8 -8
- package/dist/parser.d.ts +8 -8
- package/dist/parser.js +1 -9
- package/dist/{pipeline-D-PS9gVw.d.ts → pipeline-72QmQlGx.d.ts} +1 -1
- package/dist/{pipeline-DtSBJ8TS.d.cts → pipeline-DCQicwWX.d.cts} +1 -1
- package/dist/resolvers.cjs +1 -12
- package/dist/resolvers.d.cts +2 -2
- package/dist/resolvers.d.ts +2 -2
- package/dist/resolvers.js +1 -3
- package/dist/services.cjs +1 -20
- package/dist/services.js +1 -3
- package/dist/testing.cjs +3 -477
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +9 -10
- package/dist/testing.d.ts +9 -10
- package/dist/testing.js +3 -469
- package/dist/testing.js.map +1 -1
- package/dist/uom.cjs +1 -55
- package/dist/uom.d.cts +2 -2
- package/dist/uom.d.ts +2 -2
- package/dist/uom.js +1 -10
- package/dist/utilities.cjs +1 -36
- package/dist/utilities.js +1 -7
- package/dist/vm.cjs +1 -295
- package/dist/vm.cjs.map +1 -1
- package/dist/vm.d.cts +22 -10
- package/dist/vm.d.ts +22 -10
- package/dist/vm.js +1 -193
- package/dist/vm.js.map +1 -1
- package/dist/worker.cjs +2 -492
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +16 -17
- package/dist/worker.d.ts +16 -17
- package/dist/worker.js +2 -483
- package/dist/worker.js.map +1 -1
- package/package.json +1 -13
- package/dist/chunk-3BOK2LDK.js +0 -17
- package/dist/chunk-3BOK2LDK.js.map +0 -1
- package/dist/chunk-3VGDNEE3.js +0 -84
- package/dist/chunk-3VGDNEE3.js.map +0 -1
- package/dist/chunk-4K5W7EH2.cjs +0 -112
- package/dist/chunk-4K5W7EH2.cjs.map +0 -1
- package/dist/chunk-5EFKSKMA.js +0 -413
- package/dist/chunk-5EFKSKMA.js.map +0 -1
- package/dist/chunk-5HRB36DK.js +0 -405
- package/dist/chunk-5HRB36DK.js.map +0 -1
- package/dist/chunk-5ON7PUAZ.js +0 -12
- package/dist/chunk-5ON7PUAZ.js.map +0 -1
- package/dist/chunk-7AXJNQMF.cjs +0 -297
- package/dist/chunk-7AXJNQMF.cjs.map +0 -1
- package/dist/chunk-7JM3F4KL.js +0 -1795
- package/dist/chunk-7JM3F4KL.js.map +0 -1
- package/dist/chunk-7USV76HV.cjs +0 -341
- package/dist/chunk-7USV76HV.cjs.map +0 -1
- package/dist/chunk-A2DZ5BEJ.cjs +0 -1930
- package/dist/chunk-A2DZ5BEJ.cjs.map +0 -1
- package/dist/chunk-ADBA3XBE.cjs +0 -20
- package/dist/chunk-ADBA3XBE.cjs.map +0 -1
- package/dist/chunk-AKNGX4TZ.cjs +0 -236
- package/dist/chunk-AKNGX4TZ.cjs.map +0 -1
- package/dist/chunk-ALYRJ72W.cjs +0 -434
- package/dist/chunk-ALYRJ72W.cjs.map +0 -1
- package/dist/chunk-AMOJYLG2.cjs +0 -1692
- package/dist/chunk-AMOJYLG2.cjs.map +0 -1
- package/dist/chunk-AOH6UR2L.js +0 -825
- package/dist/chunk-AOH6UR2L.js.map +0 -1
- package/dist/chunk-AQNHHJMJ.cjs +0 -261
- package/dist/chunk-B7LXJ6LC.cjs +0 -36
- package/dist/chunk-B7LXJ6LC.cjs.map +0 -1
- package/dist/chunk-BESTLPRK.cjs +0 -6919
- package/dist/chunk-BESTLPRK.cjs.map +0 -1
- package/dist/chunk-BLI4NIQY.js +0 -98
- package/dist/chunk-BLI4NIQY.js.map +0 -1
- package/dist/chunk-BSPXMGIS.js +0 -455
- package/dist/chunk-BSPXMGIS.js.map +0 -1
- package/dist/chunk-C2OMO3WN.cjs +0 -2806
- package/dist/chunk-C2OMO3WN.cjs.map +0 -1
- package/dist/chunk-CSDQMDU2.js +0 -204
- package/dist/chunk-CSDQMDU2.js.map +0 -1
- package/dist/chunk-EJ3ILXX6.cjs +0 -223
- package/dist/chunk-EJ3ILXX6.cjs.map +0 -1
- package/dist/chunk-ENRIK36Q.cjs +0 -94
- package/dist/chunk-ENRIK36Q.cjs.map +0 -1
- package/dist/chunk-F4UB4XIL.js +0 -109
- package/dist/chunk-F4UB4XIL.js.map +0 -1
- package/dist/chunk-FD5ZZHEU.js +0 -92
- package/dist/chunk-FD5ZZHEU.js.map +0 -1
- package/dist/chunk-FE4RC37D.js +0 -2801
- package/dist/chunk-FE4RC37D.js.map +0 -1
- package/dist/chunk-FEAIOR7N.cjs +0 -91
- package/dist/chunk-FEAIOR7N.cjs.map +0 -1
- package/dist/chunk-FR7RNOPT.cjs +0 -3303
- package/dist/chunk-FR7RNOPT.cjs.map +0 -1
- package/dist/chunk-G2YPPLGX.cjs +0 -484
- package/dist/chunk-G2YPPLGX.cjs.map +0 -1
- package/dist/chunk-GCM5JHMX.js +0 -88
- package/dist/chunk-GCM5JHMX.js.map +0 -1
- package/dist/chunk-GDEU72RG.cjs +0 -829
- package/dist/chunk-GDEU72RG.cjs.map +0 -1
- package/dist/chunk-HKTQCQ4Z.cjs +0 -8383
- package/dist/chunk-HKTQCQ4Z.cjs.map +0 -1
- package/dist/chunk-HWHU642X.cjs +0 -316
- package/dist/chunk-HWHU642X.cjs.map +0 -1
- package/dist/chunk-ICEKS6YC.cjs +0 -507
- package/dist/chunk-ICEKS6YC.cjs.map +0 -1
- package/dist/chunk-IJGOFP2J.js +0 -6904
- package/dist/chunk-IJGOFP2J.js.map +0 -1
- package/dist/chunk-IQJGDZOP.js +0 -333
- package/dist/chunk-IQJGDZOP.js.map +0 -1
- package/dist/chunk-IT74O4BE.cjs +0 -456
- package/dist/chunk-IT74O4BE.cjs.map +0 -1
- package/dist/chunk-KXDQKVNX.cjs +0 -459
- package/dist/chunk-KXDQKVNX.cjs.map +0 -1
- package/dist/chunk-L2TE7PMO.cjs +0 -14
- package/dist/chunk-L2TE7PMO.cjs.map +0 -1
- package/dist/chunk-L5YHV6BQ.js +0 -499
- package/dist/chunk-L5YHV6BQ.js.map +0 -1
- package/dist/chunk-LO7HU5WB.cjs +0 -209
- package/dist/chunk-LO7HU5WB.cjs.map +0 -1
- package/dist/chunk-LSALB3IN.js +0 -292
- package/dist/chunk-LSALB3IN.js.map +0 -1
- package/dist/chunk-MI7OTUHL.cjs +0 -339
- package/dist/chunk-MI7OTUHL.cjs.map +0 -1
- package/dist/chunk-MIGXCBXT.cjs +0 -381
- package/dist/chunk-MIGXCBXT.cjs.map +0 -1
- package/dist/chunk-MVTOCRV2.js +0 -213
- package/dist/chunk-MVTOCRV2.js.map +0 -1
- package/dist/chunk-N7FNVFXW.cjs +0 -32
- package/dist/chunk-N7FNVFXW.cjs.map +0 -1
- package/dist/chunk-N7OA4WPJ.js +0 -362
- package/dist/chunk-N7OA4WPJ.js.map +0 -1
- package/dist/chunk-NAWZATKT.js +0 -478
- package/dist/chunk-NAWZATKT.js.map +0 -1
- package/dist/chunk-NLNDMWZC.js +0 -31
- package/dist/chunk-NLNDMWZC.js.map +0 -1
- package/dist/chunk-ORM7CHYZ.js +0 -1531
- package/dist/chunk-ORM7CHYZ.js.map +0 -1
- package/dist/chunk-OUHT5Z36.cjs +0 -393
- package/dist/chunk-OUHT5Z36.cjs.map +0 -1
- package/dist/chunk-PCZVMMWU.cjs +0 -74
- package/dist/chunk-PCZVMMWU.cjs.map +0 -1
- package/dist/chunk-RNKDIXDV.js +0 -336
- package/dist/chunk-RNKDIXDV.js.map +0 -1
- package/dist/chunk-SBUFNJVE.js +0 -258
- package/dist/chunk-SBUFNJVE.js.map +0 -1
- package/dist/chunk-TC6BTUSU.cjs +0 -1799
- package/dist/chunk-TC6BTUSU.cjs.map +0 -1
- package/dist/chunk-TPOK3UNI.js +0 -8355
- package/dist/chunk-TPOK3UNI.js.map +0 -1
- package/dist/chunk-UF6JG5SG.js +0 -312
- package/dist/chunk-UF6JG5SG.js.map +0 -1
- package/dist/chunk-UKQHXPGW.js +0 -30
- package/dist/chunk-UKQHXPGW.js.map +0 -1
- package/dist/chunk-V4XG5QF6.js +0 -1685
- package/dist/chunk-V4XG5QF6.js.map +0 -1
- package/dist/chunk-VEKIWQ3F.cjs +0 -39
- package/dist/chunk-VEKIWQ3F.cjs.map +0 -1
- package/dist/chunk-WMQRJTAO.js +0 -3266
- package/dist/chunk-WMQRJTAO.js.map +0 -1
- package/dist/chunk-X6K3HUOY.cjs +0 -86
- package/dist/chunk-X6K3HUOY.cjs.map +0 -1
- package/dist/chunk-XBTEO4OB.js +0 -391
- package/dist/chunk-XBTEO4OB.js.map +0 -1
- package/dist/chunk-XIYYHA65.cjs +0 -101
- package/dist/chunk-XIYYHA65.cjs.map +0 -1
- package/dist/chunk-YJHY7CMN.cjs +0 -1534
- package/dist/chunk-YLJ4XMA6.js +0 -33
- package/dist/chunk-YLJ4XMA6.js.map +0 -1
- package/dist/chunk-YNIWOYW6.js +0 -232
- package/dist/chunk-YNIWOYW6.js.map +0 -1
- package/dist/chunk-Z2XP767T.cjs +0 -35
- package/dist/chunk-Z2XP767T.cjs.map +0 -1
- package/dist/chunk-Z4X2RWOF.js +0 -37
- package/dist/chunk-Z4X2RWOF.js.map +0 -1
- package/dist/chunk-ZN6YYPIW.js +0 -67
- package/dist/chunk-ZN6YYPIW.js.map +0 -1
- package/dist/chunk-ZNFFTYWH.js +0 -1854
- package/dist/chunk-ZNFFTYWH.js.map +0 -1
- package/dist/variables.cjs +0 -17
- package/dist/variables.cjs.map +0 -1
- package/dist/variables.d.cts +0 -87
- package/dist/variables.d.ts +0 -87
- package/dist/variables.js +0 -4
- package/dist/variables.js.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a as a$1,b as b$1,f,e,d,c}from'./chunk-2JMFUQZH.js';var p=new Map(Object.entries(a$1)),_=new Map(Object.entries(b$1));function a(n){return p.get(n)}function b(n,e,t){let r=p.get(e);if(r===void 0)throw new RangeError(`${e} is not a valid unit`);let i=p.get(t);if(i===void 0)throw new RangeError(`${t} is not a valid unit`);return x(n,e,t,r,i)}function x(n,e,t,r,i){let s=r,u=i;if(s[0]!==u[0])throw new RangeError(`Cannot convert between different measures: ${e} and ${t}`);let o=s[1],d=u[1],f=_.get(e),l=_.get(t);return f!==void 0?l!==void 0?(n+f)*(o/d)-l:(n+f)*(o/d):l!==void 0?n*(o/d)-l:n*(o/d)}function B(n,e){let t=p.get(e);if(t===void 0)throw new RangeError(`${e} is not a valid unit`);let r=c[t[0]],i=r[0][0],s=i,u=b(n,e,i),o=u<0?-u:u;for(let d=0;d<r.length;d++){let f=r[d];if(o>=f[1])s=f[0];else break}return {quantity:b(n,e,s),unit:s}}var v=new Set(["workday","workdays"]),F=7/5;function g(n){return typeof n=="string"&&v.has(n)}function k(n){return n}function m(n){if(g(n))return m("day");let e$1=f[n];if(e$1)return e$1.measure;let t=a(n);if(t!==void 0)return e[t[0]]}function K(n,e){if(n===e)return true;if(g(n)||g(e)){let u=m(n),o=m(e);return !!u&&u===o}let t=a(n),r=a(e);if(t!==void 0&&r!==void 0)return t[0]===r[0];let i=f[n],s=f[e];return i!==void 0&&s!==void 0?i.measure===s.measure:y(n,e)||y(e,n)}function y(n,e$1){let t=f[n];if(t===void 0)return false;let r=a(e$1);return r===void 0?false:e[r[0]]===t.measure}function R(n,e,t){if(e===t)return n;let r=a(e),i=a(t);if(r!==void 0&&i!==void 0)return x(n,e,t,r,i);if(g(e)&&g(t))return n;if(g(e)){let o=n*F;return t==="day"?o:R(o,"day",t)}if(g(t))return (e==="day"?n:R(n,e,"day"))/F;let s=f[e],u=f[t];return s!==void 0&&u!==void 0?n*(s.toBase/u.toBase):s!==void 0&&y(e,t)?b(n*s.toBase,N(t),t):u!==void 0&&y(t,e)?b(n,e,N(e))/u.toBase:b(n,e,t)}function N(n){let e=a(n);if(e===void 0)return n;for(let t of Object.keys(a$1)){let r=a$1[t];if(r[0]===e[0]&&r[1]===1)return t}return n}function L(n){let e=n,t=a(e);if(t===void 0)return [];let r=d[t[0]];return r?r.filter(i=>i!==e):[]}function $(n){return g(n)||f[n]?true:a(n)!==void 0}function Y(n,e){let t=e;try{let r=B(n,t);return {value:r.quantity,unit:r.unit}}catch{return {value:n,unit:t}}}function S(n,e){let t=e.indexOf("/");if(t>=0)return {value:n,numerator:e.slice(0,t),denominator:e.slice(t+1)};let r=f[e];return r!==void 0&&r.measure==="speed"?{value:n*r.toBase,numerator:"m",denominator:"s"}:null}function O(n,e){if(n===e)return 1;if(n===""||e==="")return null;let t=m(n),r=m(e);return t===void 0||r===void 0||t!==r?null:R(1,n,e)}function j(n,e,t){let r=S(n,e);if(r===null)return null;let i,s,u,o=t.indexOf("/");if(o>=0)i=t.slice(0,o),s=t.slice(o+1),u=1;else {let l=f[t];if(l===void 0||l.measure!=="speed")return null;i="m",s="s",u=l.toBase;}let d=O(r.numerator,i);if(d===null)return null;let f$1=O(r.denominator,s);return f$1===null?null:r.value*d/f$1/u}export{g as a,k as b,m as c,K as d,R as e,L as f,$ as g,Y as h,j as i};//# sourceMappingURL=chunk-WGZ3FNHI.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-WGZ3FNHI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/uom/UnitConversion.ts","../src/uom/UomConverter.ts"],"names":["UNIT_LOOKUP","UNIT_TABLE","DIFFERENCE_LOOKUP","UNIT_DIFFERENCES","lookupUnit","unit","convertRaw","quantity","from","to","parsedFrom","parsedTo","convertResolved","fromEntry","toEntry","fromRatio","toRatio","fromDifference","toDifference","convertToBestMetric","best","BEST_UNITS_METRIC","smallestUnit","bestUnit","baseQuantity","absQuantity","i","bestEntry","WORKDAY_UNIT_NAMES","WORKDAY_TO_DAY_FACTOR","isWorkdayUnit","resolveUnit","getMeasure","extended","EXTENDED_UNITS","entry","MEASURE_KIND_NAMES","canConvert","fromMeasure","toMeasure","fromExtended","toExtended","bridgesToBaseMeasure","extendedUnit","baseUnit","base","convertUnit","value","days","fExt","tExt","baseUnitFor","symbol","candidate","getConvertiblePossibilities","resolved","symbols","MEASURE_SYMBOLS","s","isConvertibleUnit","getBestUnit","u","result","expandUnitToRate","slash","ext","rateAxisFactor","convertRate","source","targetNumerator","targetDenominator","targetScale","numeratorFactor","denominatorFactor"],"mappings":"4DAmCA,IAAMA,CAAAA,CAA8C,IAAI,GAAA,CAAI,MAAA,CAAO,QAAQC,GAAU,CAAC,CAAA,CAShFC,CAAAA,CAAiD,IAAI,GAAA,CAAI,OAAO,OAAA,CAAQC,GAAgB,CAAC,CAAA,CAgBxF,SAASC,EAAWC,CAAAA,CAAqC,CAC9D,OAAOL,CAAAA,CAAY,GAAA,CAAIK,CAAI,CAC7B,CAWO,SAASC,EAAWC,CAAAA,CAAkBC,CAAAA,CAAcC,EAAoB,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,EAAO,WAAA,CAAaE,CAAiB,CAAA,CAC9E,OAAIG,GAAAA,GAAsB,IAAA,CAAa,KAE/BL,CAAAA,CAAO,KAAA,CAAQI,CAAAA,CAAmBC,GAAAA,CAAoBF,CAChE","file":"chunk-WGZ3FNHI.js","sourcesContent":["/**\n * The unit conversion algorithm, ported from the `convert` npm package v7.0.2\n * alongside its tables (see `generated/UnitTable.generated.ts` and\n * THIRD-PARTY-NOTICES.md).\n *\n * Transliterated expression for expression rather than rewritten. Floating\n * point is not associative, so `(q + d) * (a / b) - d2` and any algebraically\n * equal rearrangement disagree in the last bits. Those bits are observable:\n * `0.5 l` best-converts to `500.00000000000006 mL` today, and the test suite\n * pins several conversions to ten decimal places.\n *\n * This module is deliberately unaware of the engine's own additions. Workdays,\n * extended units, currency and the caches all live in `UomConverter.ts`, which\n * layers them on top of these three functions.\n */\n\nimport {\n UNIT_TABLE,\n UNIT_DIFFERENCES,\n BEST_UNITS_METRIC,\n type UnitEntry,\n} from \"./generated/UnitTable.generated\";\n\n/**\n * The generated tables re-keyed into Maps once at module load.\n *\n * Not a micro-optimization. A 1456-key object literal lands in V8's dictionary\n * mode, and guarding a read on it against inherited names (`constructor`,\n * `toString`) costs about 123ns per call with either `hasOwnProperty.call` or\n * `Object.hasOwn`, measured. `Map.get` is about 6ns and needs no guard at all,\n * because a Map has no prototype chain to fall through to. That is a 20x\n * difference on the single hottest operation in the unit system: `convertRaw`\n * performs two of these per call, and `LanguageService` sweeps all 1456 keys\n * to build completions.\n */\nconst UNIT_LOOKUP: ReadonlyMap<string, UnitEntry> = new Map(Object.entries(UNIT_TABLE));\n\n/**\n * Temperature offsets, as a Map for the same reason.\n *\n * Also removes a latent hazard: the upstream code tests membership with `in`,\n * and `\"toString\" in UNIT_DIFFERENCES` is true, so an inherited name reaching\n * that branch would add a function to a number.\n */\nconst DIFFERENCE_LOOKUP: ReadonlyMap<string, number> = new Map(Object.entries(UNIT_DIFFERENCES));\n\n/**\n * Looks up a unit spelling.\n *\n * @returns its `[kind, ratio]` entry, or `undefined` if the spelling is not a\n * unit. Case-sensitive: no normalization or aliasing happens anywhere in this\n * module.\n *\n * The one deliberate deviation from upstream. `convert` tests membership with\n * `in` and reads the property directly, so inherited names like \"constructor\"\n * and \"toString\" reach its measure comparison and fail there with \"Cannot\n * convert between different measures\" instead of \"is not a valid unit\". Both\n * throw a RangeError and both report no measure, so nothing downstream can\n * tell the difference, and naming the real problem is the better message.\n */\nexport function lookupUnit(unit: string): UnitEntry | undefined {\n return UNIT_LOOKUP.get(unit);\n}\n\n/**\n * Converts `quantity` from one unit to another.\n *\n * THROWS a `RangeError` for an unknown unit or a pair in different measures.\n * Callers depend on that: `VM.ts`'s `extractDurationMs()` calls this with an\n * arbitrary unit inside a bare try/catch and treats the throw as \"not a\n * duration, contribute zero\". Returning NaN or the input unchanged instead\n * would turn `<date> + 5 kg` into an Invalid Date rather than a no-op.\n */\nexport function convertRaw(quantity: number, from: string, to: string): number {\n const parsedFrom = UNIT_LOOKUP.get(from);\n if (parsedFrom === undefined) {\n throw new RangeError(`${from} is not a valid unit`);\n }\n\n const parsedTo = UNIT_LOOKUP.get(to);\n if (parsedTo === undefined) {\n throw new RangeError(`${to} is not a valid unit`);\n }\n\n return convertResolved(quantity, from, to, parsedFrom, parsedTo);\n}\n\n/**\n * The conversion arithmetic, for callers that have already looked both units\n * up and want to skip doing it twice.\n *\n * Split out for `UomConverter.convertUnit()`, which has to check whether\n * either side is a workday or an extended unit before it can dispatch, and\n * would otherwise resolve each unit once to decide and again to convert. The\n * entries MUST be the ones this module returned for these exact spellings.\n */\nexport function convertResolved(\n quantity: number,\n from: string,\n to: string,\n fromEntry: UnitEntry,\n toEntry: UnitEntry\n): number {\n const parsedFrom = fromEntry;\n const parsedTo = toEntry;\n\n if (parsedFrom[0] !== parsedTo[0]) {\n // DELIBERATE DEVIATION from the ported original, which silently reinterpreted\n // \"m\" as minutes whenever the other side was a time unit. That is a guess,\n // and this project's stated position is that refusing to guess is the safer\n // default for a tool doing arithmetic on someone's real numbers (see\n // docs/architecture/design-decisions.md). The guess was not harmless: it\n // reached `<date> + <duration>` through VM.ts's extractDurationMs(), where\n // `today + 5 m` silently added five MINUTES for someone who wrote metres.\n //\n // Minutes are spelled \"min\", \"minute\" or \"minutes\", all of which the table\n // has always accepted.\n throw new RangeError(`Cannot convert between different measures: ${from} and ${to}`);\n }\n\n const fromRatio = parsedFrom[1];\n const toRatio = parsedTo[1];\n\n // Only six units in the whole table carry an offset, so the common path is\n // both misses. Reading the Map once per side and reusing the value beats\n // testing membership and then reading it again.\n const fromDifference = DIFFERENCE_LOOKUP.get(from);\n const toDifference = DIFFERENCE_LOOKUP.get(to);\n\n // Scales that do not share an origin (temperature) need the offset applied\n // around the ratio. Do not refactor the four branches into one expression:\n // the grouping is what makes the result bit-identical to the original.\n if (fromDifference !== undefined) {\n if (toDifference !== undefined) {\n return (quantity + fromDifference) * (fromRatio / toRatio) - toDifference;\n }\n return (quantity + fromDifference) * (fromRatio / toRatio);\n }\n\n if (toDifference !== undefined) {\n return quantity * (fromRatio / toRatio) - toDifference;\n }\n\n return quantity * (fromRatio / toRatio);\n}\n\n/**\n * Picks the most readable metric unit for a magnitude and converts to it.\n *\n * Only the metric lists are ported; nothing has ever requested the imperial\n * ones. Note the final conversion goes from the ORIGINAL unit to the chosen\n * one directly rather than via the smallest unit, which is what keeps the\n * result exact.\n */\nexport function convertToBestMetric(\n quantity: number,\n from: string\n): { quantity: number; unit: string } {\n const parsedFrom = UNIT_LOOKUP.get(from);\n if (parsedFrom === undefined) {\n throw new RangeError(`${from} is not a valid unit`);\n }\n\n const best = BEST_UNITS_METRIC[parsedFrom[0]];\n const smallestUnit = best[0][0];\n let bestUnit = smallestUnit;\n\n const baseQuantity = convertRaw(quantity, from, smallestUnit);\n const absQuantity = baseQuantity < 0 ? -baseQuantity : baseQuantity;\n\n // Thresholds are expressed in the smallest unit and ascend, so the last one\n // the magnitude reaches wins. Breaking early rather than scanning the whole\n // list matters for zero and for negatives, which stay on the smallest unit.\n for (let i = 0; i < best.length; i++) {\n const bestEntry = best[i];\n if (absQuantity >= bestEntry[1]) {\n bestUnit = bestEntry[0];\n } else {\n break;\n }\n }\n\n return { quantity: convertRaw(quantity, from, bestUnit), unit: bestUnit };\n}\n","/**\n * UoM Converter, built on the in-house unit tables in `UnitConversion.ts` and\n * `generated/UnitTable.generated.ts` (ported from the `convert` npm package\n * v7.0.2 so the engine ships with no runtime dependencies).\n *\n * Units are strictly case-sensitive and are looked up without aliasing. No unit\n * remapping, what you type is what you get.\n * e.g. 'C' = Celsius, 'c' = cup; 'MB' = megabytes, 'mb' = millibits.\n *\n * This file owns everything the base tables do not: the workday shim, the\n * extended (custom-measure) units, and the two caches.\n */\n\nimport { lookupUnit, convertRaw, convertResolved, convertToBestMetric } from \"@solve-js/uom/UnitConversion\";\nimport { MEASURE_KIND_NAMES, MEASURE_SYMBOLS, UNIT_TABLE } from \"@solve-js/uom/generated/UnitTable.generated\";\nimport { EXTENDED_UNITS } from \"@solve-js/uom/ExtendedUnits\";\n\n// ── \"workday\", a synthetic unit with no entry in the base table ───────────\n//\n// A business day (Mon-Fri) backing the datetime package's `<date> + N\n// workdays` arithmetic and `$X/workday` Rate literals\n// (packages/datetime/). NOT a real physical unit, a business day has no\n// fixed duration, since it depends on which calendar dates are weekends\n// so the ported base table has no concept of it and can't be\n// taught one without monkey-patching its internal unit table.\n//\n// For RATE-MATH purposes only (e.g. \"$500/workday x 4 weeks\" needs a\n// workday count to multiply by), a workday is treated as a FIXED 7/5 of a\n// calendar day: 5 workdays span exactly 7 calendar days in a whole week,\n// so this ratio is exact for whole-week spans and a reasonable linear\n// approximation otherwise. This is deliberately NOT the same\n// calendar-aware, weekend-skipping logic real \"<date> + N workdays\" date\n// arithmetic needs (see vm/VM.ts's addBusinessDays()), that can't be\n// reduced to a fixed ratio, since the exact skip pattern depends on which\n// day of the week the calculation actually starts from.\n//\n// Handled here as a thin pre/post layer in front of the normal\n// base-table path (rather than inside the tables themselves) so every\n// caller of getMeasure()/convertUnit()/canConvert() automatically gets\n// workday support for free.\nconst WORKDAY_UNIT_NAMES = new Set([\"workday\", \"workdays\"]);\nconst WORKDAY_TO_DAY_FACTOR = 7 / 5; // 1 workday == 1.4 calendar days\n\n/** Whether `unit` is the synthetic \"workday\" unit (see module note above). */\nexport function isWorkdayUnit(unit: string | undefined): unit is string {\n return typeof unit === \"string\" && WORKDAY_UNIT_NAMES.has(unit);\n}\n\n/**\n * Validate `unit` against the known unit table.\n *\n * @returns `unit` unchanged in all cases. This does NOT normalize casing\n * or aliasing (units are strictly case-sensitive, see the module note\n * above). A unit the table doesn't recognize is still\n * returned as-is (not thrown), so callers must not assume a returned\n * string is actually convertible, check with {@link isConvertibleUnit}\n * or {@link canConvert} first if that matters.\n *\n * Kept as an identity function purely for API compatibility. It used to guard\n * a validity cache, which existed because validating a unit meant a\n * throw/catch round trip through the old dependency. Validation is now a Map\n * lookup, so the cache cost more than it saved: worse, it was capped at 1000\n * entries against a 1456-unit table, so any sweep over the full vocabulary\n * (which is exactly what LanguageService does to build completions) evicted\n * on almost every call. That one change took the full-table sweep from 7.7ms\n * to under 20us.\n */\nexport function resolveUnit(unit: string): string {\n return unit;\n}\n\n// MEASURE_KIND_NAMES now comes from the generated table (it is derived data,\n// so the generator emits it rather than it being retyped here). The reason it\n// is a module-level constant has not changed: getMeasure() runs at least twice\n// per conversion, and this used to be reallocated on every call.\n\n/**\n * Get the measure/dimension kind for `unit` (e.g. `\"length\"`, `\"mass\"`,\n * `\"temperature\"`), used to check whether two units are even in the same\n * dimension before attempting a conversion.\n *\n * @returns `undefined` if `unit` isn't recognized, rather than throwing.\n */\nexport function getMeasure(unit: string): string | undefined {\n // Workday is a Time-measure unit by convention (see isWorkdayUnit's doc\n // comment) and is not in the base table, so resolve its measure via \"day\"\n // instead of attempting the real lookup below.\n if (isWorkdayUnit(unit)) return getMeasure(\"day\");\n\n // Extended (custom) categories the base table has no measure kind for,\n // see ExtendedUnits.ts.\n const extended = EXTENDED_UNITS[unit];\n if (extended) return extended.measure;\n\n const entry = lookupUnit(unit);\n if (entry === undefined) return undefined;\n\n return MEASURE_KIND_NAMES[entry[0]];\n}\n\n/**\n * Check whether `from` can be converted to `to`. Same unit, or same\n * measure kind (length, mass, ...) and the underlying tables accept the pair.\n * Never throws; returns `false` on any failure.\n */\nexport function canConvert(from: string, to: string): boolean {\n if (from === to) return true;\n if (isWorkdayUnit(from) || isWorkdayUnit(to)) {\n const fromMeasure = getMeasure(from);\n const toMeasure = getMeasure(to);\n return !!fromMeasure && fromMeasure === toMeasure;\n }\n // One table read per side, comparing numeric kind ids. The old shape called\n // getMeasure() on each side (two more reads) purely to compare the resulting\n // STRINGS, then did a throwaway conversion to confirm what the kind check had\n // already established.\n const fromEntry = lookupUnit(from);\n const toEntry = lookupUnit(to);\n if (fromEntry !== undefined && toEntry !== undefined) {\n return fromEntry[0] === toEntry[0];\n }\n\n // Extended (custom) categories aren't in the base table at all, so they are\n // compared on their own measure names instead.\n const fromExtended = EXTENDED_UNITS[from];\n const toExtended = EXTENDED_UNITS[to];\n if (fromExtended !== undefined && toExtended !== undefined) {\n return fromExtended.measure === toExtended.measure;\n }\n\n // Mixed: one side is in the base table and the other is extended. That used\n // to be refused outright, on the grounds that the two measure spaces are\n // disjoint. They are not, once an extended unit names a measure the base\n // table also has: `furlong` is a length and so is `m`, and the ratio between\n // them is exactly what both tables already record.\n return bridgesToBaseMeasure(from, to) || bridgesToBaseMeasure(to, from);\n}\n\n/**\n * Whether `extendedUnit` extends a measure the base table also knows, so a\n * value in it can reach `baseUnit`.\n *\n * The bridge works because both tables express a unit as a ratio to the same\n * physical base: the generated table's length ratios are metres and its mass\n * ratios are grams, and an extended unit declaring `measure: \"length\"` states\n * its `toBase` in the same metres. Composing the two ratios is then ordinary\n * arithmetic rather than a second conversion system.\n *\n * A measure the base table has no concept of, such as pace, still fails here,\n * which is the behaviour this replaced and the reason the check is by measure\n * name rather than by presence in the extended table.\n */\nfunction bridgesToBaseMeasure(extendedUnit: string, baseUnit: string): boolean {\n const extended = EXTENDED_UNITS[extendedUnit];\n if (extended === undefined) return false;\n\n const base = lookupUnit(resolveUnit(baseUnit));\n if (base === undefined) return false;\n\n return MEASURE_KIND_NAMES[base[0]] === extended.measure;\n}\n\n/**\n * Convert `value` from unit `from` to unit `to`.\n *\n * Does not validate that the conversion is possible, callers should check\n * with {@link canConvert} first if `from`/`to` aren't already known-good.\n *\n * THROWS a RangeError for an unknown unit or a cross-measure pair. `VM.ts`'s\n * `extractDurationMs()` depends on that, see {@link convertRaw}.\n *\n * This used to memoize a per-pair conversion factor in an LFU cache. The cache\n * is gone: computing the factor is now two Map reads, while the cache cost a\n * template-string key allocation on every call plus the LFU's own frequency\n * bookkeeping, so it was slower than the work it avoided. Removing it is\n * bit-exact, not merely close: the cache stored `convertRaw(1, f, t)`, which is\n * exactly `fromRatio / toRatio`, and then multiplied, which is the identical\n * expression `convertRaw(value, f, t)` evaluates. It also deleted the special\n * case that existed only to keep offset-based temperature pairs out of a\n * factor cache.\n */\nexport function convertUnit(value: number, from: string, to: string): number {\n if (from === to) return value;\n\n // Fast path first: two ordinary units, which is nearly every call. Resolving\n // both here and handing the entries to convertResolved() avoids looking them\n // up again inside convertRaw(). Neither workdays nor extended units appear in\n // the base table, so they always fall through to the branches below and this\n // ordering cannot steal a case from them. UnitVocabulary.spec.ts pins that\n // the two vocabularies stay disjoint.\n const fromEntry = lookupUnit(from);\n const toEntry = lookupUnit(to);\n if (fromEntry !== undefined && toEntry !== undefined) {\n return convertResolved(value, from, to, fromEntry, toEntry);\n }\n\n // Workday <-> any other Time-measure unit: pivot through \"day\" using the\n // fixed 7/5 ratio (see isWorkdayUnit's doc comment above).\n if (isWorkdayUnit(from) && isWorkdayUnit(to)) return value; // \"workday\" <-> \"workdays\" alias\n if (isWorkdayUnit(from)) {\n const days = value * WORKDAY_TO_DAY_FACTOR;\n return to === \"day\" ? days : convertUnit(days, \"day\", to);\n }\n if (isWorkdayUnit(to)) {\n const days = from === \"day\" ? value : convertUnit(value, from, \"day\");\n return days / WORKDAY_TO_DAY_FACTOR;\n }\n\n // Extended (custom) categories the base table has no measure kind for\n // (see ExtendedUnits.ts), compute the ratio directly from each unit's\n // factor-to-base value instead of calling convertRaw(), which would throw\n // on an unrecognized unit string. Every extended category is a pure linear\n // ratio scale (no Temperature-style offset), so this is always safe.\n const fExt = EXTENDED_UNITS[from];\n const tExt = EXTENDED_UNITS[to];\n if (fExt !== undefined && tExt !== undefined) {\n return value * (fExt.toBase / tExt.toBase);\n }\n\n // One side extended, the other in the base table, sharing a measure. Convert\n // through the measure's base unit, which both tables state their ratios\n // against: an extended length declares its `toBase` in metres, and the\n // generated table's length ratios are metres too.\n if (fExt !== undefined && bridgesToBaseMeasure(from, to)) {\n return convertRaw(value * fExt.toBase, baseUnitFor(to), to);\n }\n if (tExt !== undefined && bridgesToBaseMeasure(to, from)) {\n return convertRaw(value, from, baseUnitFor(from)) / tExt.toBase;\n }\n\n // Offsets, cross-measure rejection and the unknown-unit throw all live in\n // convertRaw. Nothing is layered on top here any more.\n return convertRaw(value, from, to);\n}\n\n/**\n * The unit a measure states its ratios against, found from any unit in it.\n *\n * Read out of the table rather than hard-coded, so it cannot drift from the\n * ratios it has to agree with: the base is whichever unit of that measure has\n * a ratio of exactly one.\n */\nfunction baseUnitFor(unit: string): string {\n const entry = lookupUnit(resolveUnit(unit));\n if (entry === undefined) return unit;\n\n for (const symbol of Object.keys(UNIT_TABLE)) {\n const candidate = UNIT_TABLE[symbol];\n if (candidate[0] === entry[0] && candidate[1] === 1) return symbol;\n }\n return unit;\n}\n\n/**\n * List every unit symbol in the same measure/dimension as `unit` (wiki:\n * Units-Of-Measurement, \"Conversion Possibilities\", `sourceUnit to ?`\n * e.g. `cm to ?\"` → every Length unit). Excludes `unit` itself.\n *\n * Reads MEASURE_SYMBOLS, which is a curated symbols-only vocabulary and\n * deliberately NOT the keys of the unit table filtered by kind. The two\n * differ: Volume's symbols include `c` and `pt` but not `cup`/`cups`, and\n * Time's include `wk` and `mo` but not `week`/`month`. Deriving this list\n * from the unit table instead would roughly quadruple every answer.\n *\n * @returns `[]` if `unit` isn't recognized, rather than throwing.\n */\nexport function getConvertiblePossibilities(unit: string): string[] {\n const resolved = resolveUnit(unit);\n const entry = lookupUnit(resolved);\n if (entry === undefined) return [];\n const symbols = MEASURE_SYMBOLS[entry[0]];\n if (!symbols) return [];\n return symbols.filter((s) => s !== resolved);\n}\n\n/** Check whether `unit` is a unit the conversion tables recognize. Never throws. */\nexport function isConvertibleUnit(unit: string): boolean {\n if (isWorkdayUnit(unit)) return true;\n if (EXTENDED_UNITS[unit]) return true;\n return lookupUnit(resolveUnit(unit)) !== undefined;\n}\n\n/**\n * Convert `value` (in `unit`) to whichever unit of the same measure gives\n * the most human-readable magnitude, e.g. 1500 metres becomes 1.5 km. Falls\n * back to returning `value`/`unit` unchanged if `unit` isn't recognized,\n * which is what every extended unit and workday does.\n *\n * Note the chosen unit is drawn from the best-unit lists, which are not\n * restricted to spellings the lexer accepts: 0.5 l reports \"mL\".\n */\nexport function getBestUnit(value: number, unit: string): { value: number; unit: string } {\n const u = resolveUnit(unit);\n try {\n const result = convertToBestMetric(value, u);\n return { value: result.quantity, unit: result.unit };\n } catch {\n return { value, unit: u };\n }\n}\n\n// ── Rate and derived-unit conversion ───────────────────────────────────────\n//\n// A rate value carries a compound unit spelled \"numerator/denominator\" (e.g.\n// \"km/h\", \"m/s\"), see vm/Value.ts's rateValue(). Plain convertUnit() cannot\n// touch one, because neither half is the whole unit and getMeasure(\"km/h\") is\n// undefined. This section converts a rate to another rate, and bridges a rate\n// to the single-token speed spellings (mph, kph, mps, ...) that ExtendedUnits.ts\n// already carries, so \"100 km/h in mph\" and \"60 mph in km/h\" resolve instead of\n// reporting incompatible units.\n\n/** A rate reduced to a numerator unit over a denominator unit. */\ninterface RateForm {\n /** Magnitude, scaled so `value numerator/denominator` is the physical quantity. */\n value: number;\n /** Numerator unit spelling, or `\"\"` for a countless rate such as `30/week`. */\n numerator: string;\n /** Denominator unit spelling. */\n denominator: string;\n}\n\n/**\n * Express `value unit` as a numerator/denominator rate, or `null` when `unit`\n * is neither a compound rate spelling nor a single-token speed alias.\n *\n * A speed alias (mph, kph, ...) is one unit standing for a length/time rate, so\n * it expands to the base pair `m`/`s` with its value scaled by the alias's\n * metres-per-second factor. That collapses both inputs to one shape, so a\n * single routine handles rate/rate and rate/alias without a second code path.\n */\nfunction expandUnitToRate(value: number, unit: string): RateForm | null {\n const slash = unit.indexOf(\"/\");\n if (slash >= 0) {\n return { value, numerator: unit.slice(0, slash), denominator: unit.slice(slash + 1) };\n }\n const ext = EXTENDED_UNITS[unit];\n if (ext !== undefined && ext.measure === \"speed\") {\n // 1 alias == ext.toBase m/s, so `value alias` is `value * toBase` m/s.\n return { value: value * ext.toBase, numerator: \"m\", denominator: \"s\" };\n }\n return null;\n}\n\n/**\n * The factor that turns one `from` into `to` along a single rate axis, or\n * `null` when the two cannot line up.\n *\n * Same spelling needs no conversion. A countless axis (`\"\"`) only lines up with\n * another countless one, never with a real unit. Otherwise both sides must name\n * the same measure, which is what keeps a length numerator from pairing with a\n * mass one.\n */\nfunction rateAxisFactor(from: string, to: string): number | null {\n if (from === to) return 1;\n if (from === \"\" || to === \"\") return null;\n const fromMeasure = getMeasure(from);\n const toMeasure = getMeasure(to);\n if (fromMeasure === undefined || toMeasure === undefined || fromMeasure !== toMeasure) {\n return null;\n }\n return convertUnit(1, from, to);\n}\n\n/**\n * Convert `value` from a rate/speed unit `from` to a rate/speed unit `to`,\n * returning the converted magnitude, or `null` when the pair is not\n * rate-convertible (so the caller falls back to its own incompatible-units\n * handling).\n *\n * Handles rate to rate (`10 m/s in km/h`), rate to speed alias\n * (`100 km/h in mph`) and speed alias to rate (`60 mph in km/h`). Plain\n * same-measure pairs (`kph in mph`, `km in miles`) never reach here, they are\n * resolved by {@link convertUnit} first.\n *\n * The rule is the ordinary one for a quotient of quantities: convert the\n * numerator and the denominator each on their own, so `A/B -> C/D` scales by\n * `(A->C) / (B->D)`.\n */\nexport function convertRate(value: number, from: string, to: string): number | null {\n const source = expandUnitToRate(value, from);\n if (source === null) return null;\n\n // The target is either a rate spelling or a single-token speed alias. An\n // alias expands to the base m/s pair, and `targetScale` is what the base-form\n // magnitude is divided by to read out in the alias itself.\n let targetNumerator: string;\n let targetDenominator: string;\n let targetScale: number;\n const slash = to.indexOf(\"/\");\n if (slash >= 0) {\n targetNumerator = to.slice(0, slash);\n targetDenominator = to.slice(slash + 1);\n targetScale = 1;\n } else {\n const ext = EXTENDED_UNITS[to];\n if (ext === undefined || ext.measure !== \"speed\") return null;\n targetNumerator = \"m\";\n targetDenominator = \"s\";\n targetScale = ext.toBase;\n }\n\n const numeratorFactor = rateAxisFactor(source.numerator, targetNumerator);\n if (numeratorFactor === null) return null;\n const denominatorFactor = rateAxisFactor(source.denominator, targetDenominator);\n if (denominatorFactor === null) return null;\n\n return (source.value * numeratorFactor) / denominatorFactor / targetScale;\n}\n"]}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';var chunkEFJCC6FJ_cjs=require('./chunk-EFJCC6FJ.cjs'),chunk4J7XZSZJ_cjs=require('./chunk-4J7XZSZJ.cjs'),chunkUURM7P3P_cjs=require('./chunk-UURM7P3P.cjs'),chunkJAK3RAFA_cjs=require('./chunk-JAK3RAFA.cjs'),chunkPS272DZJ_cjs=require('./chunk-PS272DZJ.cjs'),chunkUDQ57ZRX_cjs=require('./chunk-UDQ57ZRX.cjs'),chunkLR4E4A4W_cjs=require('./chunk-LR4E4A4W.cjs'),chunkSOMGSIO4_cjs=require('./chunk-SOMGSIO4.cjs');var D=class{constructor(){this.root=null;}get length(){return this.root?this.root.size:0}get isEmpty(){return this.root===null}getAt(e){if(!(e<0||e>=(this.root?.size??0)))return this.nodeAt(this.root,e).lineId}insertAt(e,t){let[n,r]=E(this.root,e);this.root=C(C(n,Y(t)),r);}deleteAt(e){if(e<0||e>=(this.root?.size??0))return;let[t,n]=E(this.root,e),[r,s]=E(n,1),i=r?r.lineId:void 0;return this.root=C(t,s),i}spliceAt(e,t,n){let r=Math.max(0,e),s=Math.min(Math.max(0,t),(this.root?.size??0)-r),[i,a]=E(this.root,r),[l,o]=E(a,s),c=ee(l),d=T(n,0,n.length);return this.root=C(C(i,d),o),c}replaceAll(e){this.root=T(e,0,e.length);}getRange(e,t){let n=Math.max(0,e),r=Math.min((this.root?.size??0)-1,t);if(n>r)return [];let s=[];return this.collectRange(this.root,n,r,0,s),s}clear(){this.root=null;}*[Symbol.iterator](){yield*this.inOrder(this.root);}*inOrder(e){e&&(yield*this.inOrder(e.left),yield e.lineId,yield*this.inOrder(e.right));}nodeAt(e,t){let n=e.left?e.left.size:0;return t<n?this.nodeAt(e.left,t):t===n?e:this.nodeAt(e.right,t-n-1)}collectRange(e,t,n,r,s){if(!e)return;let i=e.left?e.left.size:0,a=r+i;a>t&&e.left&&this.collectRange(e.left,t,n,r,s),a>=t&&a<=n&&s.push(e.lineId),a<n&&e.right&&this.collectRange(e.right,t,n,a+1,s);}};function Y(u){return {lineId:u,size:1,priority:Math.random(),left:null,right:null}}function M(u){u.size=1+(u.left?u.left.size:0)+(u.right?u.right.size:0);}function C(u,e){return u?e?u.priority>e.priority?(u.right=C(u.right,e),M(u),u):(e.left=C(u,e.left),M(e),e):u:e}function E(u,e){if(!u)return [null,null];let t=u.left?u.left.size:0;if(e<=t){let[n,r]=E(u.left,e);return u.left=r,M(u),[n,u]}else {let[n,r]=E(u.right,e-t-1);return u.right=n,M(u),[u,r]}}function ee(u){let e=[];return z(u,e),e}function z(u,e){u&&(z(u.left,e),e.push(u.lineId),z(u.right,e));}function T(u,e,t){if(e>=t)return null;let n=Math.floor((e+t)/2),r=te(n);return {lineId:u[n],size:t-e,priority:r,left:T(u,e,n),right:T(u,n+1,t)}}function te(u){let e=u;return e=(e>>16^e)*73244475,e=(e>>16^e)*73244475,e=e>>16^e,e/4294967295}var N=class{constructor(e=chunkUDQ57ZRX_cjs.b.performance.maxDocumentLines){this.lines=new Map;this.orderTree=new D;this.nextLineId=1;this._positionCache=null;this.dirtyLineIds=new Set;this.maxLines=e;}setDocument(e){if(chunkUURM7P3P_cjs.b(e,this.maxLines)>this.maxLines)throw chunkSOMGSIO4_cjs.c.execution("DOCUMENT_TOO_LARGE",`This document has more than ${this.maxLines.toLocaleString("en-US")} lines, which is the most the engine will hold at once`,{maxLines:this.maxLines});this.lines.clear(),this.orderTree.clear(),this._positionCache=null,this.dirtyLineIds.clear(),this.nextLineId=1;let n=e.split(`
|
|
2
|
+
`),r=new Array(n.length);for(let s=0;s<n.length;s++){let i=this.nextLineId++;r[s]=i,this.lines.set(i,{lineId:i,textHash:chunkEFJCC6FJ_cjs.a(n[s]),text:n[s],expressions:[],bytecodes:[],reads:[],writes:[],results:[],result:null,dirty:true,isVariableDef:false,isEmpty:n[s].trim().length===0,inlineSolveCount:0});}this.orderTree.replaceAll(r);for(let s of r)this.dirtyLineIds.add(s);}applyChanges(e){let t=[],n=[],r=[...e].sort((s,i)=>i.startLine-s.startLine);for(let s of r){let i=s.startLine-1,a=[];for(let o of s.insertLines){let c=this.nextLineId++;a.push(c),t.push(c),this.lines.set(c,{lineId:c,textHash:chunkEFJCC6FJ_cjs.a(o),text:o,expressions:[],bytecodes:[],reads:[],writes:[],results:[],result:null,dirty:true,isVariableDef:false,isEmpty:o.trim().length===0,inlineSolveCount:0});}for(let o of a)this.dirtyLineIds.add(o);let l=this.orderTree.spliceAt(i,s.deleteCount,a);for(let o of l)n.push(o),this.lines.delete(o),this.dirtyLineIds.delete(o);}return this._positionCache=null,{inserted:t,removed:n}}insertLines(e,t){let n={startLine:e,deleteCount:0,insertLines:t};return this.applyChanges([n]).inserted}deleteLines(e,t){let n={startLine:e,deleteCount:t-e+1,insertLines:[]};return this.applyChanges([n]).removed}editLine(e,t){let n=this.getLineAt(e);if(!n)return false;let r=chunkEFJCC6FJ_cjs.a(t);return r===n.textHash?false:(n.text=t,n.textHash=r,n.expressions=[],n.bytecodes=[],n.results=[],n.result=null,n.inlineSolveCount=0,n.dirty=true,this.dirtyLineIds.add(n.lineId),n.isEmpty=t.trim().length===0,true)}getLineAt(e){let t=e-1,n=this.orderTree.getAt(t);if(n!==void 0)return this.lines.get(n)}getLinePosition(e){if(this._positionCache)return this._positionCache.get(e)??-1;this._positionCache=new Map;let t=1;for(let n of this.orderTree)this._positionCache.set(n,t++);return this._positionCache.get(e)??-1}getVisibleLines(e,t){let n=this.orderTree.getRange(e-1,t-1),r=[];for(let s of n){let i=this.lines.get(s);i&&r.push(i);}return r}getAllLines(){return this.getVisibleLines(1,this.lineCount)}getLineById(e){return this.lines.get(e)}getDirtyLines(){let e=[];for(let t of this.lines.values())t.dirty&&e.push(t);return e}hasAnyDirtyLineBefore(e){for(let t of this.dirtyLineIds){let n=this.getLinePosition(t);if(n>=1&&n<e)return true}return false}hasAnyDirtyVariableDefLineBefore(e){for(let t of this.dirtyLineIds){let n=this.lines.get(t);if(!n||!n.isVariableDef)continue;let r=this.getLinePosition(t);if(r>=1&&r<e)return true}return false}get dirtyCount(){return this.dirtyLineIds.size}isBytecodeValid(e,t){let n=this.lines.get(e);return n!==void 0&&n.textHash===t}markClean(e){let t=this.lines.get(e);t&&(t.dirty=false,this.dirtyLineIds.delete(e));}markDirtyByLineNumber(e){let t=this.getLineAt(e);t&&(t.dirty=true,this.dirtyLineIds.add(t.lineId));}markDirty(e){let t=this.lines.get(e);t&&(t.dirty=true,this.dirtyLineIds.add(e));}invalidateAll(){for(let e of this.lines.values())e.dirty=true;this.dirtyLineIds=new Set(this.lines.keys());}updateLineResult(e,t,n,r,s,i,a,l=0){let o=this.lines.get(e);o&&(o.results=t,o.result=t[0]?.[0]??null,o.bytecodes=n,o.expressions=r,o.reads=s,o.writes=i,o.isVariableDef=a,o.inlineSolveCount=l,o.dirty=false,this.dirtyLineIds.delete(e));}updateLineCompiled(e,t,n,r,s,i,a=0){let l=this.lines.get(e);l&&(l.expressions=t,l.bytecodes=n,l.reads=r,l.writes=s,l.isVariableDef=i,l.inlineSolveCount=a);}get lineCount(){return this.orderTree.length}get isEmpty(){return this.orderTree.isEmpty}*[Symbol.iterator](){for(let e of this.orderTree){let t=this.lines.get(e);t&&(yield t);}}clear(){this.lines.clear(),this.orderTree.clear(),this._positionCache=null,this.nextLineId=1;}toJSON(){return {lineCount:this.lineCount,lines:this.getAllLines().map(e=>({lineId:e.lineId,text:e.text.substring(0,80),textHash:e.textHash,dirty:e.dirty,isVariableDef:e.isVariableDef,isEmpty:e.isEmpty,hasBytecode:e.bytecodes.length>0,hasResult:e.results.length>0,inlineSolveCount:e.inlineSolveCount,reads:e.reads,writes:e.writes}))}}};var A=class{constructor(){this.worker=null;this.nextId=1;this.pending=new Map;}ensureWorker(){return this.worker?this.worker:(this.worker=chunk4J7XZSZJ_cjs.g(),this.worker.onmessage=e=>{let t=e.data;if(!t||t.type!=="COMPILE_RESULT")return;let n=this.pending.get(t.id);if(!n)return;this.pending.delete(t.id);let r=[];for(let s of t.results)r.push(this.reconstructResult(s));n.resolve(r);},this.worker.onerror=e=>{for(let[t,n]of this.pending)n.reject(new Error(`Compilation worker error: ${e.message}`)),this.pending.delete(t);},this.worker)}async compileBatch(e){if(e.length===0)return [];let t=this.ensureWorker(),n=this.nextId++;return new Promise((r,s)=>{this.pending.set(n,{resolve:r,reject:s}),t.postMessage({type:"COMPILE_BATCH",id:n,items:e});})}storeResults(e,t){let n=new Map;for(let i of e){if(i.error)continue;let a=t.getLineById(i.lineId);if(!a||a.textHash!==i.compiledAgainstHash)continue;let l=n.get(i.lineId);l||(l={bytecodes:[],reads:new Set,writes:new Set,isVariableDef:false,expressions:a.expressions.length>0?[...a.expressions]:[],textHash:i.compiledAgainstHash},n.set(i.lineId,l)),l.bytecodes.push(i.program);for(let o of i.reads)l.reads.add(o);for(let o of i.writes)l.writes.add(o);i.isVariableDef&&(l.isVariableDef=true);}let s=0;for(let[i,a]of n){if(a.bytecodes.length===0)continue;let o=t.getLineById(i)?.inlineSolveCount??0;t.updateLineCompiled(i,a.expressions,a.bytecodes,[...a.reads],[...a.writes],a.isVariableDef,o),s+=a.bytecodes.length;}return s}terminate(){this.worker&&(this.worker.terminate(),this.worker=null,this.pending.clear());}get isActive(){return this.worker!==null}reconstructResult(e){if(e.error)return {lineId:e.lineId,compiledAgainstHash:e.compiledAgainstHash,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},reads:[],writes:[],isVariableDef:false,error:e.error};let t=e.opcodesLength>0?new Uint8Array(e.opcodesBuffer,0,e.opcodesLength):new Uint8Array(0),n=e.numbersLength>0?new Float64Array(e.numbersBuffer,0,e.numbersLength):new Float64Array(0),r={opcodes:t,numbers:n,strings:e.strings,hasAsync:false};return {lineId:e.lineId,compiledAgainstHash:e.compiledAgainstHash,program:r,reads:e.reads,writes:e.writes,isVariableDef:e.isVariableDef,error:null}}};var O=128,R=3,J=6,Z=2,Q=R,P=class u{constructor(){this.lastViewportStart=null;this.savedDirection=null;this.pageAccess=new Map;this.accessSeq=0;}static pageForLine(e){return Math.floor((e-1)/O)}static pageRange(e,t){return {startLine:e*O+1,endLine:Math.min((e+1)*O,t)}}detectDirection(e){return this.lastViewportStart===null?null:e.startLine>this.lastViewportStart?"down":e.startLine<this.lastViewportStart?"up":null}maintainAfterEval(e,t){this.savedDirection=this.detectDirection(e),this.lastViewportStart=e.startLine;let n=t.lineCount,r=u.pageForLine(e.startLine),s=u.pageForLine(e.endLine),i=u.pageForLine(n),a=Math.max(0,r-R),l=Math.min(i,s+R),o=Math.max(0,r-J),c=Math.min(i,s+J);for(let p=a;p<=l;p++)this.touchPage(p);for(let p=o;p<=c;p++)p>=a&&p<=l||this.evictPageResults(p,t,n);let d=o-1,h=Math.max(0,d-Q+1);for(let p=h;p<=d;p++)this.evictPageBytecode(p,t,n);let f=c+1,g=Math.min(i,f+Q-1);for(let p=f;p<=g;p++)this.evictPageBytecode(p,t,n);}getPreloadTargets(e,t){let n=this.savedDirection;if(!n)return [];let r=[],s=u.pageForLine(e.endLine),i=u.pageForLine(e.startLine),a=u.pageForLine(t.lineCount),l=[];if(n==="down"){let o=s+R+1,c=Math.min(o+Z-1,a);for(let d=o;d<=c&&d<=a;d++)l.push(d);}else {let o=i-R-1;for(let c=o;c>o-Z&&c>=0;c--)l.push(c);}for(let o of l){let c=u.pageRange(o,t.lineCount);for(let d=c.startLine;d<=c.endLine;d++){let h=t.getLineAt(d);if(h&&h.dirty&&!(h.bytecodes.length>0&&!h.isVariableDef)&&!h.isEmpty)if(h.expressions.length>0)for(let f of h.expressions)f.trim()&&r.push({lineId:h.lineId,expression:f,textHash:h.textHash});else {let f=chunkLR4E4A4W_cjs.c.findInlineSolves(h.text);if(f.length>0)for(let g of f)g.expression.trim()&&r.push({lineId:h.lineId,expression:g.expression,textHash:h.textHash});else {let g=h.text.trim();g&&r.push({lineId:h.lineId,expression:g,textHash:h.textHash});}}}}return r}clear(){this.pageAccess.clear(),this.accessSeq=0,this.lastViewportStart=null,this.savedDirection=null;}touchPage(e){this.pageAccess.set(e,++this.accessSeq);}evictPageResults(e,t,n){let r=u.pageRange(e,n);for(let s=r.startLine;s<=r.endLine;s++){let i=t.getLineAt(s);i&&!i.isVariableDef&&i.results.length>0&&(i.results=[],i.result=null);}}evictPageBytecode(e,t,n){let r=u.pageRange(e,n);for(let s=r.startLine;s<=r.endLine;s++){let i=t.getLineAt(s);!i||i.isVariableDef||(i.bytecodes.length>0||i.results.length>0)&&(i.bytecodes=[],i.results=[],i.result=null,t.markDirty(i.lineId));}}};var X=(r=>(r[r.Tier1=1]="Tier1",r[r.Tier2=2]="Tier2",r[r.Tier3=3]="Tier3",r[r.Skipped=0]="Skipped",r))(X||{}),F=class{constructor(e,t,n){this.compilationWorker=null;this.globalUnsubscribe=null;this.doc=e,this.engine=t,this.dag=t.getDag(),this.checkpointer=n??null,this.pageManager=new P,this.engine.setDocumentModel(this.doc),this.globalUnsubscribe=chunkJAK3RAFA_cjs.J.subscribe(r=>{for(let s of this.dag.getAffectedLines(chunkJAK3RAFA_cjs.K(r)))this.doc.markDirtyByLineNumber(s);});}evaluate(e,t){this.engine.setKeystrokeSignal(t??null),chunkPS272DZJ_cjs.h();try{this.reseedAccumulators();let n=[],r=new Map,s={tier1:0,tier2:0,tier3:0,skipped:0},i=this.doc.lineCount,a=Math.min(e.endLine,i);for(let l=1;l<=a;l++){let o=this.doc.getLineAt(l);if(!o){s.skipped++;continue}let c=l>=e.startLine&&l<=e.endLine,d=this.evaluateSingleLine(o,l,c);n.push(d),d.tier===1?s.tier1++:d.tier===2?s.tier2++:d.tier===3?s.tier3++:s.skipped++,d.results&&c&&r.set(l,d.results.flat());}return this.pageManager.maintainAfterEval(e,this.doc),{lines:n,resultMap:r,tierCounts:s}}finally{this.engine.setKeystrokeSignal(null),chunkPS272DZJ_cjs.i();}}backgroundCompile(e){let t=[],n=this.doc.lineCount,r=e.endLine+1;for(let s=r;s<=n;s++){let i=this.doc.getLineAt(s);if(!i||!i.dirty||i.bytecodes.length>0&&!i.isVariableDef)continue;let a=this.evaluateSingleLine(i,s,false);t.push(a);}return t}dispatchBackgroundCompiles(e){let t=this.collectInvisibleCompileTargets(e);t.length!==0&&(this.compilationWorker||(this.compilationWorker=new A),this.compilationWorker.compileBatch(t).then(n=>{this.compilationWorker.storeResults(n,this.doc);}).catch(n=>{}));}terminateWorker(){this.compilationWorker&&(this.compilationWorker.terminate(),this.compilationWorker=null),this.globalUnsubscribe&&(this.globalUnsubscribe(),this.globalUnsubscribe=null);}getDoc(){return this.doc}evaluateAll(e){let t={startLine:1,endLine:this.doc.lineCount};return this.evaluate(t,e)}setViewport(e,t){if(this.engine.setKeystrokeSignal(t??null),e.startLine>1&&this.hasDirtyLinesBefore(e.startLine))return this.checkpointer?.clear(),this.evaluate(e,t);this.pageManager.maintainAfterEval(e,this.doc),this.preloadNextPages(e),this.restoreTo(e.startLine-1),chunkPS272DZJ_cjs.h();try{return this.collectEvalResults(e.startLine,e.endLine)}finally{this.engine.setKeystrokeSignal(null),chunkPS272DZJ_cjs.i();}}applyTransaction(e){let t=new Set;for(let s of e)for(let i=0;i<s.deleteCount;i++){let a=s.startLine+i,l=this.dag.getWrites(a);for(let o of l)t.add(o);this.dag.removeLine(a),this.engine.getLineCache().removeAllForLine(a);}let n=new Set;for(let s of t){let i=this.dag.getAffectedLines(s);for(let a of i){let l=this.doc.getLineAt(a);l&&n.add(l.lineId);}}let r=this.doc.applyChanges(e);this.checkpointer?.clear();for(let s of n)this.doc.markDirty(s);return this.dag.clear(),{inserted:r.inserted,removed:r.removed}}reseedAccumulators(){let e=this.engine.resetAccumulators();if(e.size===0)return;let t=this.doc.lineCount;for(let n=1;n<=t;n++){let r=this.dag.getWrites(n);if(r.size!==0){for(let s of r)if(e.has(s)){this.doc.markDirtyByLineNumber(n);break}}}}collectEvalResults(e,t){let n=[],r=new Map,s={tier1:0,tier2:0,tier3:0,skipped:0},i=this.doc.lineCount,a=Math.min(t,i);for(let l=e;l<=a;l++){let o=this.doc.getLineAt(l);if(!o)continue;let c=this.evaluateSingleLine(o,l,true);n.push(c),c.tier===1?s.tier1++:c.tier===2?s.tier2++:c.tier===3?s.tier3++:s.skipped++,c.results&&r.set(l,c.results.flat());}return {lines:n,resultMap:r,tierCounts:s}}hasDirtyLinesBefore(e){return this.doc.hasAnyDirtyVariableDefLineBefore(e)}evaluateSingleLine(e,t,n){let r={lineId:e.lineId,lineNumber:t};if(e.isEmpty||chunk4J7XZSZJ_cjs.l(e.text))return e.isEmpty=true,this.doc.markClean(e.lineId),{...r,tier:0,result:null,error:null};let{expressions:s,inlineSolveCount:i}=this.extractExpressions(e);return s.length===0?(e.isEmpty=true,this.doc.markClean(e.lineId),{...r,tier:0,result:null,error:null}):e.dirty?n?this.evaluateTier1(e,t,s,i,r):e.bytecodes.length>0&&e.bytecodes.length===s.length&&!e.isVariableDef?{...r,tier:0,result:null,error:null}:this.evaluateTier3(e,t,s,i,r):n&&e.bytecodes.length>0?this.evaluateTier2(e,t,r):{...r,tier:0,result:null,error:null}}evaluateTier1(e,t,n,r,s){let i=[],a=[],l=new Set,o=new Set,c=false,d=null,h=null,f=false,g=false;for(let b of n){if(!b.trim())continue;let y=null,L;try{let m=this.engine.evaluateLine(t,b);y=[m],d=m,L=this.engine.getLineCache().get(t,b);}catch(m){let S=m instanceof Error?m.message:String(m);h||(h=S),f=true,y=null;}if(y&&y.some(m=>m.type===12)&&(g=true),y?i.push(y):i.push([chunkPS272DZJ_cjs.N("eval_failed",h??"unknown error")]),L){a.push(L.bytecode);for(let m of L.readVariables)l.add(m);L.writeVariable&&(o.add(L.writeVariable),c=true);}else try{let{program:m,reads:S,writes:I}=this.engine.compileExpression(b);a.push(m);for(let x of S)l.add(x);for(let x of I)o.add(x);I.length>0&&(c=!0);}catch(m){if(a.push({opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false}),m instanceof chunkSOMGSIO4_cjs.b&&m.context){let S=m.context.reads,I=m.context.writes;if(Array.isArray(S))for(let x of S)l.add(x);if(Array.isArray(I))for(let x of I)o.add(x);}}}let p=[...l],v=[...o];return f||g?(this.doc.updateLineCompiled(e.lineId,n,a,p,v,c,r),e.results=i,e.result=i[0]?.[0]??null,e.inlineSolveCount=r,e.expressions=n):this.doc.updateLineResult(e.lineId,i,a,n,p,v,c,r),this.dag.registerLine(t,p,v),this.checkpointer&&v.length>0&&!f&&!g&&this.checkpointer.snapshot(t,e.lineId,v),{...s,tier:1,result:d,results:i,error:h}}evaluateTier2(e,t,n){if(e.bytecodes.length===0)return {...n,tier:0,result:null,error:null};let r=[],s=null,i=null,a=false;for(let l of e.bytecodes)if(l.opcodes.length!==0)try{let o=this.engine.executeCached(l,t);s=o,r.push([o]);}catch(o){let c=o instanceof Error?o.message:String(o);i||(i=c),a=true,r.push([chunkPS272DZJ_cjs.N("exec_failed",c)]);}return this.dag.registerLine(t,e.reads,e.writes),e.results=r,e.result=r[0]?.[0]??null,a&&this.doc.markDirty(e.lineId),{...n,tier:2,result:s,results:r,error:i}}evaluateTier3(e,t,n,r,s){let i=[],a=new Set,l=new Set,o=false,c=null,d=null,h=false,f=false;for(let v of n)if(v.trim())try{let{program:b,reads:y,writes:L}=this.engine.compileExpression(v);i.push(b);for(let m of y)a.add(m);for(let m of L)l.add(m);L.length>0&&(o=!0),L.length>0&&b.opcodes.length>0&&(c=this.engine.executeCached(b,t),c&&c.type===12&&(f=!0));}catch(b){let y=b instanceof Error?b.message:String(b);d||(d=y),h=true,i.push({opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false});}let g=[...a],p=[...l];return this.doc.updateLineCompiled(e.lineId,n,i,g,p,o,r),this.dag.registerLine(t,g,p),o&&c&&!h&&!f&&(e.results=[[c]],e.result=c,this.doc.markClean(e.lineId),this.checkpointer&&this.checkpointer.snapshot(t,e.lineId,p)),{...s,tier:3,result:c,results:o&&c&&!h&&!f?[[c]]:void 0,error:d}}restoreTo(e){this.checkpointer&&this.checkpointer.restoreTo(e);}getCheckpointer(){return this.checkpointer}getPageManager(){return this.pageManager}preloadNextPages(e){let t=this.pageManager.getPreloadTargets(e,this.doc);t.length!==0&&(this.compilationWorker||(this.compilationWorker=new A),this.compilationWorker.compileBatch(t).then(n=>{this.compilationWorker.storeResults(n,this.doc);}).catch(n=>{}));}collectInvisibleCompileTargets(e){let t=[],n=this.doc.lineCount,r=e.endLine+1;for(let s=r;s<=n;s++){let i=this.doc.getLineAt(s);if(!i||!i.dirty||i.bytecodes.length>0&&!i.isVariableDef||i.isEmpty||chunk4J7XZSZJ_cjs.l(i.text))continue;let{expressions:a}=this.extractExpressions(i);if(a.length!==0)for(let l of a)l.trim()&&t.push({lineId:i.lineId,expression:l,textHash:i.textHash});}return t}extractExpressions(e){if(e.expressions.length>0)return {expressions:e.expressions,inlineSolveCount:e.inlineSolveCount};let t=e.text.trim();if(t.length===0)return {expressions:[],inlineSolveCount:0};let n=chunkLR4E4A4W_cjs.c.findInlineSolves(e.text);return n.length>0?{expressions:n.map(r=>r.expression),inlineSolveCount:n.length}:{expressions:[t],inlineSolveCount:0}}};exports.a=N;exports.b=X;exports.c=F;//# sourceMappingURL=chunk-WN5CMP4T.cjs.map
|
|
3
|
+
//# sourceMappingURL=chunk-WN5CMP4T.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/engine/SegmentTree.ts","../src/engine/DocumentModel.ts","../src/engine/CompilationWorkerManager.ts","../src/engine/PageManager.ts","../src/engine/ThreeTierEvaluator.ts"],"names":["SegmentTree","index","lineId","left","right","split","merge","createNode","midRight","mid","removed","startIndex","deleteCount","newIds","clampedStart","clampedCount","collectInOrder","newTree","buildTreap","lineIds","endIndex","clampedEnd","result","node","leftSize","targetStart","targetEnd","offset","nodeIndex","updateSize","collect","start","end","priority","pseudoRandom","seed","x","DocumentModel","maxLines","DEFAULT_CONFIG","text","countLines","ErrorFactory","rawLines","i","djb2Hash","id","changes","inserted","sorted","a","b","change","startIdx","removedIds","atLine","texts","startLine","endLine","lineNumber","newText","state","newHash","position","idx","pos","compiledAgainstHash","results","bytecodes","expressions","reads","writes","isVariableDef","inlineSolveCount","s","CompilationWorkerManager","engine_worker_default","event","data","pending","raw","err","items","worker","resolve","reject","doc","byLineId","batch","r","w","stored","opcodes","numbers","program","PAGE_SIZE","HOT_PAGE_RADIUS","WARM_PAGE_RADIUS","PRELOAD_PAGE_COUNT","COLD_EVICT_BUFFER","PageManager","_PageManager","pageNum","docLineCount","newViewport","viewport","viewportStartPage","viewportEndPage","lastPage","hotStart","hotEnd","warmStart","warmEnd","coldLeftEnd","coldLeftStart","coldRightStart","coldRightEnd","direction","pages","startPage","endPage","p","firstPreloadPage","range","expression","inlineSpans","sharedLexer","span","EvalTier","ThreeTierEvaluator","engine","checkpointer","sharedGlobalVariableStore","name","globalDagKey","signal","enableValueArena","lines","resultMap","tierCounts","docEnd","evalEnd","inViewport","lineResult","disableValueArena","startPos","_err","allWrites","lineNum","downstreamLineIds","writeVar","affected","names","baseResult","isEmptyLine","allResults","allBytecodes","allReads","hasVariableDef","lastValue","firstError","anyFailed","anyPending","value","entry","evaluated","e","errorMessage","v","errorValue","compileErr","EngineError","errReads","errWrites","bytecode","lastResult","targets","trimmed"],"mappings":"iaA6CO,IAAMA,EAAN,KAAkB,CAAlB,cACN,IAAA,CAAQ,IAAA,CAAoB,MAK5B,IAAI,MAAA,EAAiB,CACpB,OAAO,KAAK,IAAA,CAAO,IAAA,CAAK,KAAK,IAAA,CAAO,CACrC,CAGA,IAAI,OAAA,EAAmB,CACtB,OAAO,KAAK,IAAA,GAAS,IACtB,CAOA,KAAA,CAAMC,CAAAA,CAAmC,CACxC,GAAI,EAAAA,CAAAA,CAAQ,CAAA,EAAKA,IAAU,IAAA,CAAK,IAAA,EAAM,MAAQ,CAAA,CAAA,CAAA,CAC9C,OAAO,KAAK,MAAA,CAAO,IAAA,CAAK,IAAA,CAAMA,CAAK,EAAE,MACtC,CAMA,SAASA,CAAAA,CAAeC,CAAAA,CAAsB,CAC7C,GAAM,CAACC,CAAAA,CAAMC,CAAK,EAAIC,CAAAA,CAAM,IAAA,CAAK,KAAMJ,CAAK,CAAA,CAC5C,KAAK,IAAA,CAAOK,CAAAA,CAAMA,CAAAA,CAAMH,CAAAA,CAAMI,EAAWL,CAAM,CAAC,EAAGE,CAAK,EACzD,CAOA,QAAA,CAASH,CAAAA,CAAmC,CAC3C,GAAIA,CAAAA,CAAQ,GAAKA,CAAAA,GAAU,IAAA,CAAK,MAAM,IAAA,EAAQ,CAAA,CAAA,CAAI,OAElD,GAAM,CAACE,CAAAA,CAAMK,CAAQ,EAAIH,CAAAA,CAAM,IAAA,CAAK,KAAMJ,CAAK,CAAA,CACzC,CAACQ,CAAAA,CAAKL,CAAK,CAAA,CAAIC,CAAAA,CAAMG,EAAU,CAAC,CAAA,CAEhCE,EAAUD,CAAAA,CAAMA,CAAAA,CAAI,OAAS,MAAA,CACnC,OAAA,IAAA,CAAK,IAAA,CAAOH,CAA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,EAAW6F,mBAAAA,CAAY7F,EAAM,IAAI,CAAA,CAAG,SAE9C,GAAM,CAAE,WAAA,CAAAQ,CAAY,CAAA,CAAI,IAAA,CAAK,kBAAA,CAAmBR,CAAK,CAAA,CACrD,GAAIQ,EAAY,MAAA,GAAW,CAAA,CAK3B,IAAA,IAAWuD,CAAAA,IAAcvD,CAAAA,CACnBuD,CAAAA,CAAW,MAAK,EACrB1C,CAAAA,CAAM,IAAA,CAAK,CACV,MAAA,CAAQrB,CAAAA,CAAM,OACd,UAAA,CAAA+D,CAAAA,CACA,QAAA,CAAU/D,CAAAA,CAAM,QACjB,CAAC,EAEH,CAEA,OAAOqB,CACR,CAaQ,kBAAA,CAAmBrB,CAAAA,CAAuE,CAEjG,GAAIA,CAAAA,CAAM,WAAA,CAAY,MAAA,CAAS,CAAA,CAC9B,OAAO,CAAE,YAAaA,CAAAA,CAAM,WAAA,CAAa,gBAAA,CAAkBA,CAAAA,CAAM,gBAAiB,CAAA,CAGnF,IAAMoH,CAAAA,CAAUpH,CAAAA,CAAM,IAAA,CAAK,IAAA,EAAK,CAChC,GAAIoH,EAAQ,MAAA,GAAW,CAAA,CAAG,OAAO,CAAE,WAAA,CAAa,EAAC,CAAG,gBAAA,CAAkB,CAAE,CAAA,CAGxE,IAAMpD,CAAAA,CAAcC,mBAAAA,CAAY,gBAAA,CAAiBjE,EAAM,IAAI,CAAA,CAC3D,OAAIgE,CAAAA,CAAY,MAAA,CAAS,CAAA,CACjB,CACN,WAAA,CAAaA,CAAAA,CAAY,GAAA,CAAInD,CAAAA,EAAKA,CAAAA,CAAE,UAAU,EAC9C,gBAAA,CAAkBmD,CAAAA,CAAY,MAC/B,CAAA,CAIM,CAAE,WAAA,CAAa,CAACoD,CAAO,CAAA,CAAG,gBAAA,CAAkB,CAAE,CACtD,CACD","file":"chunk-WN5CMP4T.cjs","sourcesContent":["/**\n * SegmentTree, an order-statistic Treap (randomized BST).\n *\n * Replaces the flat `lineOrder: number[]` array in DocumentModel with a\n * balanced tree that supports O(log N) insert, delete, and get-at-index\n * operations. Each node stores a `lineId` and its subtree size, enabling\n * order-statistic queries (find the k-th element by position).\n *\n * Key operations:\n * getAt(index), O(log N) expected\n * insertAt(index), O(log N) expected\n * deleteAt(index), O(log N) expected\n * spliceAt(index, deleteCount, newIds), O(log N + deleteCount + insertCount)\n * indexOf(lineId), O(N) without reverse map; cached lazily in DocumentModel\n *\n * Implementation: Treap (Tree + Heap) with implicit keys.\n * Nodes are ordered by position (in-order traversal), not by lineId value.\n * The `size` field enables O(log N) order statistics.\n * Random priorities maintain balance with high probability (O(log N) depth).\n *\n * Memory: ~40 bytes per node (lineId + size + priority + left + right).\n * For 100K lines: ~4MB for tree structure (acceptable).\n */\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\ninterface Node {\n\tlineId: number;\n\t/** Total number of nodes in this subtree (including self). */\n\tsize: number;\n\t/** Random priority for heap property (maintains balance). */\n\tpriority: number;\n\tleft: Node | null;\n\tright: Node | null;\n}\n\n// ── SegmentTree ────────────────────────────────────────────────────────────\n\n/**\n * Maps document offsets to line numbers in logarithmic time.\n *\n * A document is edited constantly, and every edit shifts the offsets of every\n * line after it. Recomputing them linearly on each keystroke is what this\n * avoids.\n */\nexport class SegmentTree {\n\tprivate root: Node | null = null;\n\n\t// ── Public API ───────────────────────────────────────────────────────\n\n\t/** Total number of elements in the tree. */\n\tget length(): number {\n\t\treturn this.root ? this.root.size : 0;\n\t}\n\n\t/** Whether the tree is empty. */\n\tget isEmpty(): boolean {\n\t\treturn this.root === null;\n\t}\n\n\t/**\n\t * Get the lineId at the given 0-based index.\n\t * Returns undefined if index is out of bounds.\n\t * O(log N) expected.\n\t */\n\tgetAt(index: number): number | undefined {\n\t\tif (index < 0 || index >= (this.root?.size ?? 0)) return undefined;\n\t\treturn this.nodeAt(this.root, index).lineId;\n\t}\n\n\t/**\n\t * Insert a single lineId at the given 0-based index.\n\t * O(log N) expected.\n\t */\n\tinsertAt(index: number, lineId: number): void {\n\t\tconst [left, right] = split(this.root, index);\n\t\tthis.root = merge(merge(left, createNode(lineId)), right);\n\t}\n\n\t/**\n\t * Delete a single element at the given 0-based index.\n\t * Returns the removed lineId, or undefined if out of bounds.\n\t * O(log N) expected.\n\t */\n\tdeleteAt(index: number): number | undefined {\n\t\tif (index < 0 || index >= (this.root?.size ?? 0)) return undefined;\n\n\t\tconst [left, midRight] = split(this.root, index);\n\t\tconst [mid, right] = split(midRight, 1);\n\n\t\tconst removed = mid ? mid.lineId : undefined;\n\t\tthis.root = merge(left, right);\n\t\treturn removed;\n\t}\n\n\t/**\n\t * Bulk splice: delete `deleteCount` elements at `startIndex` (0-based),\n\t * then insert `newIds` in their place.\n\t *\n\t * Returns the removed lineId array.\n\t * O(log N + deleteCount + insertCount) expected.\n\t */\n\tspliceAt(\n\t\tstartIndex: number,\n\t\tdeleteCount: number,\n\t\tnewIds: number[]\n\t): number[] {\n\t\tconst clampedStart = Math.max(0, startIndex);\n\t\tconst clampedCount = Math.min(\n\t\t\tMath.max(0, deleteCount),\n\t\t\t(this.root?.size ?? 0) - clampedStart\n\t\t);\n\n\t\t// Split into three parts: [0, start) [start, start+count) [start+count, end)\n\t\tconst [left, midRight] = split(this.root, clampedStart);\n\t\tconst [mid, right] = split(midRight, clampedCount);\n\n\t\t// Collect removed IDs\n\t\tconst removed = collectInOrder(mid);\n\n\t\t// Build a treap from the new IDs and merge\n\t\tconst newTree = buildTreap(newIds, 0, newIds.length);\n\t\tthis.root = merge(merge(left, newTree), right);\n\n\t\treturn removed;\n\t}\n\n\t/**\n\t * Replace the entire tree with a new set of lineIds.\n\t * O(N), builds a balanced treap from a flat array.\n\t */\n\treplaceAll(lineIds: number[]): void {\n\t\tthis.root = buildTreap(lineIds, 0, lineIds.length);\n\t}\n\n\t/**\n\t * Get a contiguous range of lineIds by index.\n\t * O(rangeSize + log N), single in-order walk instead of N × O(log N).\n\t *\n\t * This is the hot path for viewport rendering in DocumentModel.getVisibleLines().\n\t */\n\tgetRange(startIndex: number, endIndex: number): number[] {\n\t\tconst clampedStart = Math.max(0, startIndex);\n\t\tconst clampedEnd = Math.min((this.root?.size ?? 0) - 1, endIndex);\n\t\tif (clampedStart > clampedEnd) return [];\n\n\t\tconst result: number[] = [];\n\t\tthis.collectRange(this.root, clampedStart, clampedEnd, 0, result);\n\t\treturn result;\n\t}\n\n\t/**\n\t * Clear the tree.\n\t */\n\tclear(): void {\n\t\tthis.root = null;\n\t}\n\n\t// ── Iteration ─────────────────────────────────────────────────────────\n\n\t/**\n\t * In-order iterator yielding all lineIds.\n\t */\n\t*[Symbol.iterator](): IterableIterator<number> {\n\t\tyield* this.inOrder(this.root);\n\t}\n\n\tprivate *inOrder(node: Node | null): IterableIterator<number> {\n\t\tif (!node) return;\n\t\tyield* this.inOrder(node.left);\n\t\tyield node.lineId;\n\t\tyield* this.inOrder(node.right);\n\t}\n\n\t// ── Private helpers ───────────────────────────────────────────────────\n\n\tprivate nodeAt(node: Node | null, index: number): Node {\n\t\t// This is only called with valid indices, so node is non-null\n\t\tconst leftSize = node!.left ? node!.left.size : 0;\n\n\t\tif (index < leftSize) {\n\t\t\treturn this.nodeAt(node!.left, index);\n\t\t} else if (index === leftSize) {\n\t\t\treturn node!;\n\t\t} else {\n\t\t\treturn this.nodeAt(node!.right, index - leftSize - 1);\n\t\t}\n\t}\n\n\t/**\n\t * Collect all node values in the range [targetStart, targetEnd] into result.\n\t * `offset` is the 0-based start of the current subtree within the full tree.\n\t * O(rangeSize + log N), skips entire subtrees outside the target range.\n\t */\n\tprivate collectRange(\n\t\tnode: Node | null,\n\t\ttargetStart: number,\n\t\ttargetEnd: number,\n\t\toffset: number,\n\t\tresult: number[]\n\t): void {\n\t\tif (!node) return;\n\n\t\tconst leftSize = node.left ? node.left.size : 0;\n\t\tconst nodeIndex = offset + leftSize;\n\n\t\t// Traverse left subtree if it overlaps the target range\n\t\tif (nodeIndex > targetStart && node.left) {\n\t\t\tthis.collectRange(node.left, targetStart, targetEnd, offset, result);\n\t\t}\n\n\t\t// Include this node if within range\n\t\tif (nodeIndex >= targetStart && nodeIndex <= targetEnd) {\n\t\t\tresult.push(node.lineId);\n\t\t}\n\n\t\t// Traverse right subtree if it overlaps the target range\n\t\tif (nodeIndex < targetEnd && node.right) {\n\t\t\tthis.collectRange(node.right, targetStart, targetEnd, nodeIndex + 1, result);\n\t\t}\n\t}\n}\n\n// ── Free functions ──────────────────────────────────────────────────────────\n\n/** Create a new treap node. */\nfunction createNode(lineId: number): Node {\n\treturn {\n\t\tlineId,\n\t\tsize: 1,\n\t\tpriority: Math.random(),\n\t\tleft: null,\n\t\tright: null,\n\t};\n}\n\n/** Update a node's size from its children. */\nfunction updateSize(node: Node): void {\n\tnode.size = 1 + (node.left ? node.left.size : 0) + (node.right ? node.right.size : 0);\n}\n\n/**\n * Merge two treaps. All keys in `left` must be ≤ all keys in `right`.\n * O(log N) expected.\n */\nfunction merge(left: Node | null, right: Node | null): Node | null {\n\tif (!left) return right;\n\tif (!right) return left;\n\n\tif (left.priority > right.priority) {\n\t\tleft.right = merge(left.right, right);\n\t\tupdateSize(left);\n\t\treturn left;\n\t} else {\n\t\tright.left = merge(left, right.left);\n\t\tupdateSize(right);\n\t\treturn right;\n\t}\n}\n\n/**\n * Split a treap at `index` (0-based).\n * Returns [left, right] where `left` contains the first `index` elements\n * and `right` contains the rest.\n * O(log N) expected.\n */\nfunction split(\n\tnode: Node | null,\n\tindex: number\n): [Node | null, Node | null] {\n\tif (!node) return [null, null];\n\n\tconst leftSize = node.left ? node.left.size : 0;\n\n\tif (index <= leftSize) {\n\t\tconst [left, right] = split(node.left, index);\n\t\tnode.left = right;\n\t\tupdateSize(node);\n\t\treturn [left, node];\n\t} else {\n\t\tconst [left, right] = split(node.right, index - leftSize - 1);\n\t\tnode.right = left;\n\t\tupdateSize(node);\n\t\treturn [node, right];\n\t}\n}\n\n/**\n * Collect all lineIds from a treap in-order.\n * O(N).\n */\nfunction collectInOrder(node: Node | null): number[] {\n\tconst result: number[] = [];\n\tcollect(node, result);\n\treturn result;\n}\n\nfunction collect(node: Node | null, result: number[]): void {\n\tif (!node) return;\n\tcollect(node.left, result);\n\tresult.push(node.lineId);\n\tcollect(node.right, result);\n}\n\n/**\n * Build a balanced treap from a flat array of lineIds.\n * Uses divide-and-conquer with pre-sorted priorities to produce\n * a heap-ordered tree in O(N) time.\n * O(N).\n */\nfunction buildTreap(lineIds: number[], start: number, end: number): Node | null {\n\tif (start >= end) return null;\n\n\tconst mid = Math.floor((start + end) / 2);\n\n\t// Generate a deterministic-but-random priority based on position\n\t// This ensures the same array always produces the same tree shape\n\tconst priority = pseudoRandom(mid);\n\n\tconst node: Node = {\n\t\tlineId: lineIds[mid],\n\t\tsize: end - start,\n\t\tpriority,\n\t\tleft: buildTreap(lineIds, start, mid),\n\t\tright: buildTreap(lineIds, mid + 1, end),\n\t};\n\n\treturn node;\n}\n\n/**\n * Simple pseudo-random number generator for deterministic treap building.\n * Uses a multiplicative hash of the input.\n */\nfunction pseudoRandom(seed: number): number {\n\tlet x = seed;\n\tx = ((x >> 16) ^ x) * 0x45d9f3b;\n\tx = ((x >> 16) ^ x) * 0x45d9f3b;\n\tx = (x >> 16) ^ x;\n\treturn x / 0xffffffff; // normalize to [0, 1)\n}\n","import { Value } from \"@solve-js/vm/Value\";\nimport { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { djb2Hash } from \"@solve-js/utilities/Hash\";\nimport { SegmentTree } from \"@solve-js/engine/SegmentTree\";\nimport { DEFAULT_CONFIG } from \"@solve-js/constants/Configuration\";\nimport { countLines } from \"@solve-js/utilities/Strings\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n// ── LineState ──────────────────────────────────────────────────────────────\n\n/**\n * Persistent per-line state tracked by the DocumentModel.\n *\n * Each line receives an immutable `lineId` that survives structural edits\n * (insertions, deletions, line shifts). This allows caches, the dependency\n * graph, and VM checkpoints to reference lines by ID instead of by volatile\n * line numbers.\n *\n * ── Multi-expression support ─────────────────────────────────────────\n * A single document line may contain multiple inline solves (`s\\`...\\``).\n * To support this without breaking the 1:1 line-to-DAG-node contract:\n * - `expressions[]` holds all extracted expression strings (1 entry for\n * full-line expressions, N entries for N inline solves).\n * - `bytecodes[]` holds compiled bytecode in corresponding order.\n * - `results[]` holds evaluation **result groups** in corresponding order.\n * Each element is a `Value[]`, a group of Values produced by that expression.\n * For variable definitions, the group always has exactly 1 element.\n * For multi-output expressions (e.g., currency conversion), the group\n * may have multiple Values (one per target unit).\n * - `reads[]` and `writes[]` are aggregated across ALL expressions on\n * the line, the DAG treats the line as a single dependency node.\n * - `inlineSolveCount` is 0 for full-line expressions, >0 for inline solves.\n */\nexport interface LineState {\n\t/** Immutable unique identifier, survives all structural edits. */\n\treadonly lineId: number;\n\n\t/** djb2 hash of the line text, used for O(1) change detection. */\n\ttextHash: number;\n\n\t/** The full line text (may include markdown). */\n\ttext: string;\n\n\t/**\n\t * Extracted expression texts.\n\t * - Full-line expressions: one entry (the trimmed text).\n\t * - Inline solve lines: one entry per `s\\`...\\`` span, in left-to-right order.\n\t * - Markdown-only lines: empty array.\n\t */\n\texpressions: string[];\n\n\t/**\n\t * Compiled bytecode for each expression, in corresponding order.\n\t * Parallel to {@link expressions}.\n\t */\n\tbytecodes: BytecodeProgram[];\n\n\t/** Variables this line reads (for dependency tracking). Aggregated across all expressions. */\n\treads: string[];\n\n\t/** Variables this line writes (empty if not a variable definition). Aggregated across all expressions. */\n\twrites: string[];\n\n\t/**\n\t * Evaluation result groups for each expression, in corresponding order.\n\t * Each `Value[]` is a group of Values produced by one expression.\n\t * Variable definitions always produce exactly 1 Value per group.\n\t * Multi-output expressions (e.g. currency conversion) may produce N Values.\n\t */\n\tresults: Value[][];\n\n\t/**\n\t * Convenience accessor for the first expression's first result.\n\t * Equals `results[0]?.[0] ?? null`. For single-expression lines,\n\t * this is the primary result. For multi-expression (inline solve) lines,\n\t * prefer accessing `results[i][j]` directly.\n\t */\n\tresult: Value | null;\n\n\t/** True if this line needs re-evaluation. */\n\tdirty: boolean;\n\n\t/** True if any expression on this line defines a variable (never evict bytecode). */\n\tisVariableDef: boolean;\n\n\t/** True if this line contains only markdown (no evaluable expression). */\n\tisEmpty: boolean;\n\n\t/**\n\t * Number of inline solve expressions on this line.\n\t * 0 = full-line expression (or markdown-only).\n\t * >0 = N inline solves embedded in markdown text.\n\t */\n\tinlineSolveCount: number;\n}\n\n// ── ViewportRange ──────────────────────────────────────────────────────────\n\n/** The visible line range, used to decide which lines are evaluated eagerly. */\nexport interface ViewportRange {\n\tstartLine: number; // 1-based, inclusive\n\tendLine: number; // 1-based, inclusive\n}\n\n// ── LineChange ─────────────────────────────────────────────────────────────\n\n/** Describes a structural change to the document's line list. */\nexport interface LineChange {\n\t/** 1-based line number where the change starts. */\n\tstartLine: number;\n\t/** Number of lines deleted (0 for pure insertion). */\n\tdeleteCount: number;\n\t/** New line texts inserted in place of deleted lines. */\n\tinsertLines: string[];\n}\n\n// ── ApplyChangesResult ─────────────────────────────────────────────────────\n\n/** Result of applying changes to the document model. */\nexport interface ApplyChangesResult {\n\t/** Line IDs of newly inserted lines. */\n\tinserted: number[];\n\t/** Line IDs that were removed. */\n\tremoved: number[];\n}\n\n// ── DocumentModel ──────────────────────────────────────────────────────────\n\n/**\n * Persistent document model with O(log N) line lookups and structural edits.\n *\n * Design:\n * - Each line has an immutable `lineId` (monotonically increasing counter).\n * - `LineState` objects are stored in a `Map<lineId, LineState>` for O(1) access.\n * - Line ordering is maintained in a `SegmentTree` (order-statistic Treap) that\n * supports O(log N) insert, delete, and get-at-index operations.\n * - A lazy position cache (`Map<lineId, number>`) provides O(1) position lookups\n * after the first `getLinePosition()` call and is invalidated on structural edits.\n *\n * Key invariant: line IDs never change, only their positions in the order tree.\n * This means cached bytecode, dependency graph entries, and VM checkpoints\n * keyed by lineId remain valid across all structural edits.\n */\nexport class DocumentModel {\n\t/** Persistent line ID → LineState. */\n\tprivate lines: Map<number, LineState> = new Map();\n\n\t/** Order-statistic treap representing the current document line order. */\n\tprivate orderTree: SegmentTree = new SegmentTree();\n\n\t/** Monotonically increasing counter for new line IDs. */\n\tprivate nextLineId: number = 1;\n\n\t/**\n\t * Lazy position cache: lineId → 1-based position.\n\t * Built on first `getLinePosition()` call, invalidated on structural edits.\n\t */\n\tprivate _positionCache: Map<number, number> | null = null;\n\n\t/**\n\t * Line IDs currently marked dirty, maintained alongside every\n\t * `state.dirty` mutation (in this class and in every other module that\n\t * holds a direct `LineState` reference: ThreeTierEvaluator, PageManager).\n\t * Lets {@link hasAnyDirtyLineBefore} answer \"is anything before position\n\t * X dirty\" in O(d log N), d = current dirty count, typically tiny once\n\t * a document has settled after its initial evaluation, instead of\n\t * O(N log N), which used to mean every scroll event re-walked the WHOLE\n\t * document via `getLineAt()` regardless of how little of it was actually\n\t * dirty. Benchmarked: ~10.6ms per setViewport() call scrolled near the\n\t * bottom of a 20k-line document before this fix.\n\t */\n\tprivate dirtyLineIds: Set<number> = new Set();\n\n\t/**\n\t * Most lines this model will hold. See `constants/Configuration.ts`'s\n\t * `performance.maxDocumentLines`, which is where the default comes from and\n\t * which a host raises through its engine config; a host that builds a\n\t * DocumentModel directly passes it here instead.\n\t */\n\tprivate readonly maxLines: number;\n\n\t/**\n\t * @param maxLines - Ceiling on the line count, defaulting to the engine's\n\t * configured one. Every line costs a LineState with six arrays in it\n\t * whatever the line says, so the cost of a document is its line count and\n\t * nothing else bounds it: two hundred thousand lines of `1 + 1` exhausted\n\t * the heap here, before a single expression had been looked at.\n\t */\n\tconstructor(maxLines: number = DEFAULT_CONFIG.performance.maxDocumentLines) {\n\t\tthis.maxLines = maxLines;\n\t}\n\n\t// ── Initialization ──────────────────────────────────────────────────\n\n\t/**\n\t * Initialize or replace the entire document from a text blob.\n\t * Clears all existing state and assigns new persistent line IDs.\n\t *\n\t * @throws `DOCUMENT_TOO_LARGE` for a document past {@link maxLines}, before\n\t * any of it is stored. Recoverable: nothing has been replaced yet, so the\n\t * model still holds whatever it held.\n\t */\n\tsetDocument(text: string): void {\n\t\t// Counted before anything is cleared, so a refused document leaves the\n\t\t// previous one intact rather than half-replaced.\n\t\tconst lineCount = countLines(text, this.maxLines);\n\t\tif (lineCount > this.maxLines) {\n\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\"DOCUMENT_TOO_LARGE\",\n\t\t\t\t`This document has more than ${this.maxLines.toLocaleString(\"en-US\")} lines, which is the most the engine will hold at once`,\n\t\t\t\t{ maxLines: this.maxLines },\n\t\t\t);\n\t\t}\n\t\tthis.lines.clear();\n\t\tthis.orderTree.clear();\n\t\tthis._positionCache = null;\n\t\tthis.dirtyLineIds.clear();\n\t\tthis.nextLineId = 1;\n\n\t\tconst rawLines = text.split(\"\\n\");\n\t\tconst lineIds = new Array<number>(rawLines.length);\n\n\t\tfor (let i = 0; i < rawLines.length; i++) {\n\t\t\tconst lineId = this.nextLineId++;\n\t\t\tlineIds[i] = lineId;\n\t\t\tthis.lines.set(lineId, {\n\t\t\t\tlineId,\n\t\t\t\ttextHash: djb2Hash(rawLines[i]),\n\t\t\t\ttext: rawLines[i],\n\t\t\t\texpressions: [],\n\t\t\t\tbytecodes: [],\n\t\t\t\treads: [],\n\t\t\t\twrites: [],\n\t\t\t\tresults: [],\n\t\t\t\tresult: null,\n\t\t\t\tdirty: true,\n\t\t\t\tisVariableDef: false,\n\t\t\t\tisEmpty: rawLines[i].trim().length === 0,\n\t\t\t\tinlineSolveCount: 0,\n\t\t\t});\n\t\t}\n\n\t\t// O(N) balanced treap build from flat array\n\t\tthis.orderTree.replaceAll(lineIds);\n\n\t\t// Every line starts dirty (see the object literal above), seed the\n\t\t// tracking set to match. This is the one place the set is legitimately\n\t\t// O(N): a fresh document needs full evaluation anyway.\n\t\tfor (const id of lineIds) this.dirtyLineIds.add(id);\n\t}\n\n\t// ── Structural edits ────────────────────────────────────────────────\n\n\t/**\n\t * Apply one or more line-level changes to the document.\n\t *\n\t * **Precondition:** Changes must be **non-overlapping** in their line ranges.\n\t * If two changes target the same or adjacent lines, the reverse-order\n\t * processing may produce incorrect results because the first-applied\n\t * change shifts the line numbers that the second change references.\n\t *\n\t * Changes are applied in **reverse order** (highest startLine first) so\n\t * that earlier changes in the document don't shift the indices of later\n\t * changes during processing.\n\t *\n\t * Returns both the newly inserted line IDs and the removed line IDs.\n\t * Callers should use `removed` to clean up the dependency graph and\n\t * other data structures keyed by lineId.\n\t */\n\tapplyChanges(changes: LineChange[]): ApplyChangesResult {\n\t\tconst inserted: number[] = [];\n\t\tconst removed: number[] = [];\n\n\t\t// Sort descending by startLine so earlier changes don't shift later indices\n\t\tconst sorted = [...changes].sort((a, b) => b.startLine - a.startLine);\n\n\t\tfor (const change of sorted) {\n\t\t\tconst startIdx = change.startLine - 1; // convert to 0-based\n\n\t\t\t// Create new LineState entries for inserted lines\n\t\t\tconst newIds: number[] = [];\n\t\t\tfor (const text of change.insertLines) {\n\t\t\t\tconst lineId = this.nextLineId++;\n\t\t\t\tnewIds.push(lineId);\n\t\t\t\tinserted.push(lineId);\n\t\t\t\tthis.lines.set(lineId, {\n\t\t\t\t\tlineId,\n\t\t\t\t\ttextHash: djb2Hash(text),\n\t\t\t\t\ttext,\n\t\t\t\t\texpressions: [],\n\t\t\t\t\tbytecodes: [],\n\t\t\t\t\treads: [],\n\t\t\t\t\twrites: [],\n\t\t\t\t\tresults: [],\n\t\t\t\t\tresult: null,\n\t\t\t\t\tdirty: true,\n\t\t\t\t\tisVariableDef: false,\n\t\t\t\t\tisEmpty: text.trim().length === 0,\n\t\t\t\t\tinlineSolveCount: 0,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// New lines start dirty (see the object literal above), track them.\n\t\t\tfor (const id of newIds) this.dirtyLineIds.add(id);\n\n\t\t\t// O(log N) splice: delete old IDs, insert new IDs\n\t\t\tconst removedIds = this.orderTree.spliceAt(\n\t\t\t\tstartIdx,\n\t\t\t\tchange.deleteCount,\n\t\t\t\tnewIds\n\t\t\t);\n\t\t\tfor (const id of removedIds) {\n\t\t\t\tremoved.push(id);\n\t\t\t\tthis.lines.delete(id);\n\t\t\t\tthis.dirtyLineIds.delete(id);\n\t\t\t}\n\t\t}\n\n\t\t// Invalidate position cache, positions shifted for all lines\n\t\tthis._positionCache = null;\n\n\t\treturn { inserted, removed };\n\t}\n\n\t/**\n\t * Insert new lines at the given 1-based position.\n\t * Convenience wrapper around applyChanges.\n\t */\n\tinsertLines(atLine: number, texts: string[]): number[] {\n\t\tconst change: LineChange = {\n\t\t\tstartLine: atLine,\n\t\t\tdeleteCount: 0,\n\t\t\tinsertLines: texts,\n\t\t};\n\t\tconst result = this.applyChanges([change]);\n\t\treturn result.inserted;\n\t}\n\n\t/**\n\t * Delete lines in the given 1-based range [startLine, endLine] inclusive.\n\t * Convenience wrapper around applyChanges.\n\t */\n\tdeleteLines(startLine: number, endLine: number): number[] {\n\t\tconst change: LineChange = {\n\t\t\tstartLine,\n\t\t\tdeleteCount: endLine - startLine + 1,\n\t\t\tinsertLines: [],\n\t\t};\n\t\tconst result = this.applyChanges([change]);\n\t\treturn result.removed;\n\t}\n\n\t/**\n\t * Update the text of a single line in place.\n\t * If the text hash differs, marks the line dirty and clears its\n\t * bytecode/result so it gets re-evaluated.\n\t *\n\t * Returns true if the text actually changed (hash mismatch).\n\t */\n\teditLine(lineNumber: number, newText: string): boolean {\n\t\tconst state = this.getLineAt(lineNumber);\n\t\tif (!state) return false;\n\n\t\tconst newHash = djb2Hash(newText);\n\t\tif (newHash === state.textHash) return false;\n\n\t\tstate.text = newText;\n\t\tstate.textHash = newHash;\n\t\tstate.expressions = [];\n\t\tstate.bytecodes = [];\n\t\tstate.results = [];\n\t\tstate.result = null;\n\t\tstate.inlineSolveCount = 0;\n\t\tstate.dirty = true;\n\t\tthis.dirtyLineIds.add(state.lineId);\n\t\tstate.isEmpty = newText.trim().length === 0;\n\t\treturn true;\n\t}\n\n\t// ── Queries ─────────────────────────────────────────────────────────\n\n\t/**\n\t * Get the LineState at the given 1-based line position. O(1).\n\t */\n\tgetLineAt(position: number): LineState | undefined {\n\t\tconst idx = position - 1;\n\t\tconst lineId = this.orderTree.getAt(idx);\n\t\tif (lineId === undefined) return undefined;\n\t\treturn this.lines.get(lineId);\n\t}\n\n\t/**\n\t * Get the 1-based position of a line by its persistent ID.\n\t * Returns -1 if the line ID is not in the document.\n\t *\n\t * Uses a lazy position cache: O(N) on first call after structural edit,\n\t * O(1) on subsequent calls. The cache is invalidated by any structural edit.\n\t */\n\tgetLinePosition(lineId: number): number {\n\t\tif (this._positionCache) {\n\t\t\treturn this._positionCache.get(lineId) ?? -1;\n\t\t}\n\n\t\t// Build position cache on first call after invalidation\n\t\tthis._positionCache = new Map();\n\t\tlet pos = 1;\n\t\tfor (const id of this.orderTree) {\n\t\t\tthis._positionCache.set(id, pos++);\n\t\t}\n\n\t\treturn this._positionCache.get(lineId) ?? -1;\n\t}\n\n\t/**\n\t * Get all LineState entries within the given viewport range (1-based, inclusive).\n\t * Uses SegmentTree.getRange() for O(viewport + log N) collection instead of\n\t * O(viewport × log N) per-line lookups.\n\t */\n\tgetVisibleLines(startLine: number, endLine: number): LineState[] {\n\t\tconst lineIds = this.orderTree.getRange(startLine - 1, endLine - 1);\n\t\tconst result: LineState[] = [];\n\t\tfor (const lineId of lineIds) {\n\t\t\tconst state = this.lines.get(lineId);\n\t\t\tif (state) result.push(state);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Get all LineState entries in order. Useful for batch processing.\n\t */\n\tgetAllLines(): LineState[] {\n\t\treturn this.getVisibleLines(1, this.lineCount);\n\t}\n\n\t/**\n\t * Get a LineState by its persistent line ID. O(1).\n\t */\n\tgetLineById(lineId: number): LineState | undefined {\n\t\treturn this.lines.get(lineId);\n\t}\n\n\t/**\n\t * Get all lines that are marked dirty.\n\t */\n\tgetDirtyLines(): LineState[] {\n\t\tconst result: LineState[] = [];\n\t\tfor (const state of this.lines.values()) {\n\t\t\tif (state.dirty) result.push(state);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Whether any line before `position` (1-based, exclusive) is dirty.\n\t *\n\t * Used by ThreeTierEvaluator.setViewport() to decide whether cached\n\t * checkpoint state might be stale and a full evaluate() (from line 1) is\n\t * needed instead of the cheap viewport-only path.\n\t *\n\t * O(d log N) where d = current dirty line count via {@link dirtyLineIds},\n\t * not O(N log N), a document that's mostly clean (the steady state after\n\t * initial load) answers this in the cost of resolving a handful of\n\t * lineIds to positions, not walking every line up to `position`.\n\t */\n\thasAnyDirtyLineBefore(position: number): boolean {\n\t\tfor (const lineId of this.dirtyLineIds) {\n\t\t\tconst pos = this.getLinePosition(lineId);\n\t\t\tif (pos >= 1 && pos < position) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Whether any **variable-definition** line before `position` (1-based,\n\t * exclusive) is dirty.\n\t *\n\t * Narrower than {@link hasAnyDirtyLineBefore}: `VMCheckpointer.snapshot()`\n\t * only ever records state for lines with `writes.length > 0` (see\n\t * VMCheckpoints.ts), so a dirty plain-expression line before the viewport\n\t * cannot have invalidated any checkpoint, there's no checkpoint entry\n\t * for it to invalidate. Only a dirty variable-def line can mean the VM\n\t * state a checkpoint would restore is stale.\n\t *\n\t * This distinction matters because `PageManager.evictPageBytecode()`\n\t * marks evicted non-variable-def lines dirty (so they get Tier 1 if\n\t * scrolled back into view), and Tier 3's compile-only path never clears\n\t * `dirty` for non-variable-def lines by design. Using the broader\n\t * `hasAnyDirtyLineBefore` here meant scrolling far into a large,\n\t * variable-def-free document would trip `setViewport()`'s fallback to\n\t * `evaluate()` on every single call, evaluate() reprocesses the evicted\n\t * lines via Tier 3, which recompiles their bytecode without clearing\n\t * dirty, so the very next `maintainAfterEval()` re-evicts and re-dirties\n\t * the same lines, forever re-triggering the fallback on an otherwise\n\t * unchanged viewport.\n\t */\n\thasAnyDirtyVariableDefLineBefore(position: number): boolean {\n\t\tfor (const lineId of this.dirtyLineIds) {\n\t\t\tconst state = this.lines.get(lineId);\n\t\t\tif (!state || !state.isVariableDef) continue;\n\t\t\tconst pos = this.getLinePosition(lineId);\n\t\t\tif (pos >= 1 && pos < position) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/** Number of lines currently marked dirty. For diagnostics/tests. */\n\tget dirtyCount(): number {\n\t\treturn this.dirtyLineIds.size;\n\t}\n\n\t// ── Thread-safety validation ────────────────────────────────────────\n\n\t/**\n\t * Verify that bytecode compiled by a worker is still valid for this line.\n\t *\n\t * When Phase 5.2h sends compilation to a worker, the worker posts back\n\t * `{lineId, bytecode, reads, writes, compiledAgainstHash}`. Between dispatch\n\t * and response, the user may have edited the line. This method lets the\n\t * main thread check whether the bytecode is still applicable.\n\t *\n\t * @returns true if the line still exists and its text hash matches.\n\t */\n\tisBytecodeValid(lineId: number, compiledAgainstHash: number): boolean {\n\t\tconst state = this.lines.get(lineId);\n\t\treturn state !== undefined && state.textHash === compiledAgainstHash;\n\t}\n\n\t// ── State mutations ─────────────────────────────────────────────────\n\n\t/**\n\t * Mark a line as clean (re-evaluated successfully).\n\t */\n\tmarkClean(lineId: number): void {\n\t\tconst state = this.lines.get(lineId);\n\t\tif (state) {\n\t\t\tstate.dirty = false;\n\t\t\tthis.dirtyLineIds.delete(lineId);\n\t\t}\n\t}\n\n\t/**\n\t * Mark a line as dirty (needs re-evaluation) by its 1-based position.\n\t * Convenience for callers that have line numbers instead of line IDs.\n\t */\n\tmarkDirtyByLineNumber(lineNumber: number): void {\n\t\tconst state = this.getLineAt(lineNumber);\n\t\tif (state) {\n\t\t\tstate.dirty = true;\n\t\t\tthis.dirtyLineIds.add(state.lineId);\n\t\t}\n\t}\n\n\t/**\n\t * Mark a line as dirty (needs re-evaluation).\n\t */\n\tmarkDirty(lineId: number): void {\n\t\tconst state = this.lines.get(lineId);\n\t\tif (state) {\n\t\t\tstate.dirty = true;\n\t\t\tthis.dirtyLineIds.add(lineId);\n\t\t}\n\t}\n\n\t/**\n\t * Mark all lines as dirty (e.g., after plugin register/unregister).\n\t */\n\tinvalidateAll(): void {\n\t\tfor (const state of this.lines.values()) {\n\t\t\tstate.dirty = true;\n\t\t}\n\t\tthis.dirtyLineIds = new Set(this.lines.keys());\n\t}\n\n\t/**\n\t * Update a line's evaluation state after successful execution (Tier 1 / Tier 2).\n\t *\n\t * Sets results, bytecodes, reads, writes, and marks the line clean.\n\t * Supports multi-expression lines (inline solves) via parallel arrays.\n\t *\n\t * @param lineId - Persistent line identifier.\n\t * @param results - Evaluation result groups for each expression (in order). Each element is a Value[].\n\t * @param bytecodes - Compiled bytecode for each expression (in order).\n\t * @param expressions - Extracted expression strings (in order).\n\t * @param reads - Aggregated read variables across all expressions.\n\t * @param writes - Aggregated write variables across all expressions.\n\t * @param isVariableDef - True if any expression defines a variable.\n\t * @param inlineSolveCount - Number of inline solves (0 for full-line).\n\t */\n\tupdateLineResult(\n\t\tlineId: number,\n\t\tresults: Value[][],\n\t\tbytecodes: BytecodeProgram[],\n\t\texpressions: string[],\n\t\treads: string[],\n\t\twrites: string[],\n\t\tisVariableDef: boolean,\n\t\tinlineSolveCount: number = 0,\n\t): void {\n\t\tconst state = this.lines.get(lineId);\n\t\tif (!state) return;\n\t\tstate.results = results;\n\t\tstate.result = results[0]?.[0] ?? null;\n\t\tstate.bytecodes = bytecodes;\n\t\tstate.expressions = expressions;\n\t\tstate.reads = reads;\n\t\tstate.writes = writes;\n\t\tstate.isVariableDef = isVariableDef;\n\t\tstate.inlineSolveCount = inlineSolveCount;\n\t\tstate.dirty = false;\n\t\tthis.dirtyLineIds.delete(lineId);\n\t}\n\n\t/**\n\t * Update a line's compile-only state (Tier 3: background compilation).\n\t *\n\t * Stores expressions, bytecodes, reads, and writes. Does NOT set results\n\t * and does NOT mark the line clean, it still needs execution (Tier 1 or\n\t * Tier 2) to produce results. This distinction allows the three-tier\n\t * evaluation strategy: compile invisible lines in the background without\n\t * executing them, then execute from cached bytecode when scrolled into view.\n\t *\n\t * @param lineId - Persistent line identifier.\n\t * @param expressions - Extracted expression strings (in order).\n\t * @param bytecodes - Compiled bytecode for each expression (in order).\n\t * @param reads - Aggregated read variables across all expressions.\n\t * @param writes - Aggregated write variables across all expressions.\n\t * @param isVariableDef - True if any expression defines a variable.\n\t * @param inlineSolveCount - Number of inline solves (0 for full-line).\n\t */\n\tupdateLineCompiled(\n\t\tlineId: number,\n\t\texpressions: string[],\n\t\tbytecodes: BytecodeProgram[],\n\t\treads: string[],\n\t\twrites: string[],\n\t\tisVariableDef: boolean,\n\t\tinlineSolveCount: number = 0,\n\t): void {\n\t\tconst state = this.lines.get(lineId);\n\t\tif (!state) return;\n\t\tstate.expressions = expressions;\n\t\tstate.bytecodes = bytecodes;\n\t\tstate.reads = reads;\n\t\tstate.writes = writes;\n\t\tstate.isVariableDef = isVariableDef;\n\t\tstate.inlineSolveCount = inlineSolveCount;\n\t\t// NOTE: dirty remains unchanged, line still needs execution\n\t}\n\n\t// ── Properties ──────────────────────────────────────────────────────\n\n\tget lineCount(): number {\n\t\treturn this.orderTree.length;\n\t}\n\n\tget isEmpty(): boolean {\n\t\treturn this.orderTree.isEmpty;\n\t}\n\n\t/**\n\t * Iterator over LineState in document order.\n\t */\n\t*[Symbol.iterator](): IterableIterator<LineState> {\n\t\tfor (const lineId of this.orderTree) {\n\t\t\tconst state = this.lines.get(lineId);\n\t\t\tif (state) yield state;\n\t\t}\n\t}\n\n\t// ── Lifecycle ───────────────────────────────────────────────────────\n\n\tclear(): void {\n\t\tthis.lines.clear();\n\t\tthis.orderTree.clear();\n\t\tthis._positionCache = null;\n\t\tthis.nextLineId = 1;\n\t}\n\n\t/**\n\t * Serialize the document model to a plain object for debugging.\n\t */\n\ttoJSON(): object {\n\t\treturn {\n\t\t\tlineCount: this.lineCount,\n\t\t\tlines: this.getAllLines().map((s) => ({\n\t\t\t\tlineId: s.lineId,\n\t\t\t\ttext: s.text.substring(0, 80), // truncate for readability\n\t\t\t\ttextHash: s.textHash,\n\t\t\t\tdirty: s.dirty,\n\t\t\t\tisVariableDef: s.isVariableDef,\n\t\t\t\tisEmpty: s.isEmpty,\n\t\t\t\thasBytecode: s.bytecodes.length > 0,\n\t\t\t\thasResult: s.results.length > 0,\n\t\t\t\tinlineSolveCount: s.inlineSolveCount,\n\t\t\t\treads: s.reads,\n\t\t\t\twrites: s.writes,\n\t\t\t})),\n\t\t};\n\t}\n}\n","/**\n * CompilationWorkerManager, main-thread bridge to the compilation worker.\n *\n * Manages the worker lifecycle and provides a batch compilation API.\n * Receives transferred ArrayBuffers from the worker and reconstructs\n * BytecodeProgram objects with zero-copy TypedArray views.\n *\n * Usage:\n * const manager = new CompilationWorkerManager();\n * const bytecodeByLineId = await manager.compileBatch(items, docModel);\n *\n * Thread safety:\n * Each result includes `compiledAgainstHash`. Before storing bytecode\n * in the DocumentModel, we validate via `docModel.isBytecodeValid()`.\n * If the line was edited between dispatch and response, the bytecode\n * is discarded, the next evaluate() will recompile it synchronously.\n */\n\nimport { DocumentModel } from \"@solve-js/engine/DocumentModel\";\nimport type { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport createCompilationWorker from \"@solve-js/workers/engine.worker\";\n\n// ── Types ─────────────────────────────────────────────────────────────────\n\n/** One line sent to a worker for compilation. */\nexport interface CompileRequestItem {\n\tlineId: number;\n\texpression: string;\n\ttextHash: number;\n}\n\n/** Compiled bytecode returned from a worker, or the error that stopped it. */\nexport interface CompileResponseItem {\n\tlineId: number;\n\t/** Hash of the expression text when the compile was dispatched (for safety validation). */\n\tcompiledAgainstHash: number;\n\tprogram: BytecodeProgram;\n\treads: string[];\n\twrites: string[];\n\tisVariableDef: boolean;\n\terror: string | null;\n}\n\n// Raw result from worker (before BytecodeProgram reconstruction)\ninterface WorkerCompileResult {\n\tlineId: number;\n\tcompiledAgainstHash: number;\n\topcodesBuffer: ArrayBuffer;\n\tnumbersBuffer: ArrayBuffer;\n\topcodesLength: number;\n\tnumbersLength: number;\n\tstrings: string[];\n\treads: string[];\n\twrites: string[];\n\tisVariableDef: boolean;\n\terror: string | null;\n}\n\n// ── CompilationWorkerManager ──────────────────────────────────────────────\n\n/**\n * Compiles lines on a background worker.\n *\n * A response is discarded when the line changed between dispatch and return,\n * because bytecode compiled against stale text would produce a result for an\n * expression the user has already edited. The next evaluation recompiles it\n * synchronously.\n */\nexport class CompilationWorkerManager {\n\tprivate worker: Worker | null = null;\n\tprivate nextId = 1;\n\tprivate pending = new Map<\n\t\tnumber,\n\t\t{\n\t\t\tresolve: (results: CompileResponseItem[]) => void;\n\t\t\treject: (error: Error) => void;\n\t\t}\n\t>();\n\n\tconstructor() {}\n\n\t/**\n\t * Ensure the worker is started (lazy initialization).\n\t * Uses esbuild-plugin-inline-worker to inline the worker as a blob URL.\n\t */\n\tprivate ensureWorker(): Worker {\n\t\tif (this.worker) return this.worker;\n\n\t\tthis.worker = createCompilationWorker();\n\n\t\tthis.worker.onmessage = (event: MessageEvent) => {\n\t\t\tconst data = event.data;\n\t\t\tif (!data || data.type !== \"COMPILE_RESULT\") return;\n\n\t\t\tconst pending = this.pending.get(data.id);\n\t\t\tif (!pending) return;\n\n\t\t\tthis.pending.delete(data.id);\n\n\t\t\tconst results: CompileResponseItem[] = [];\n\t\t\tfor (const raw of data.results as WorkerCompileResult[]) {\n\t\t\t\tresults.push(this.reconstructResult(raw));\n\t\t\t}\n\t\t\tpending.resolve(results);\n\t\t};\n\n\t\tthis.worker.onerror = (err) => {\n\t\t\t// Reject all pending requests on worker error\n\t\t\tfor (const [id, pending] of this.pending) {\n\t\t\t\tpending.reject(\n\t\t\t\t\tnew Error(`Compilation worker error: ${err.message}`)\n\t\t\t\t);\n\t\t\t\tthis.pending.delete(id);\n\t\t\t}\n\t\t};\n\n\t\treturn this.worker;\n\t}\n\n\t/**\n\t * Batch-compile expressions in the worker.\n\t *\n\t * Sends a batch of { lineId, expression, textHash } to the worker,\n\t * which compiles each and transfers bytecode ArrayBuffers back.\n\t * Bytecode is reconstructed into BytecodeProgram objects.\n\t *\n\t * Results are returned in the same order as the input items.\n\t *\n\t * @param items Expressions to compile.\n\t * @returns Compiled bytecode for each item (or error).\n\t */\n\tasync compileBatch(items: CompileRequestItem[]): Promise<CompileResponseItem[]> {\n\t\tif (items.length === 0) return [];\n\n\t\tconst worker = this.ensureWorker();\n\t\tconst id = this.nextId++;\n\n\t\treturn new Promise<CompileResponseItem[]>((resolve, reject) => {\n\t\t\tthis.pending.set(id, { resolve, reject });\n\n\t\t\tworker.postMessage({\n\t\t\t\ttype: \"COMPILE_BATCH\",\n\t\t\t\tid,\n\t\t\t\titems,\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Store worker-compiled bytecode into the DocumentModel, with safety\n\t * validation. Only stores bytecode for lines whose text has not changed\n\t * since the compilation request was dispatched.\n\t *\n\t * Results for the same lineId are batched, all bytecodes from\n\t * successful compilations are passed to updateLineCompiled in a single\n\t * call. This supports multi-expression lines (inline solves).\n\t *\n\t * @param results Compiled results from the worker.\n\t * @param doc The target document model.\n\t * @returns Number of results successfully stored (passed safety check).\n\t */\n\tstoreResults(\n\t\tresults: CompileResponseItem[],\n\t\tdoc: DocumentModel\n\t): number {\n\t\t// Batch results by lineId (multiple inline solves share the same lineId)\n\t\tconst byLineId = new Map<\n\t\t\tnumber,\n\t\t\t{\n\t\t\t\tbytecodes: BytecodeProgram[];\n\t\t\t\treads: Set<string>;\n\t\t\t\twrites: Set<string>;\n\t\t\t\tisVariableDef: boolean;\n\t\t\t\texpressions: string[];\n\t\t\t\ttextHash: number;\n\t\t\t}\n\t\t>();\n\t\tlet validCount = 0;\n\n\t\tfor (const result of results) {\n\t\t\tif (result.error) continue;\n\n\t\t\t// Safety check: has the line been edited since dispatch?\n\t\t\tconst state = doc.getLineById(result.lineId);\n\t\t\tif (!state) continue;\n\n\t\t\t// Validate that the line text hasn't changed since dispatch.\n\t\t\tif (state.textHash !== result.compiledAgainstHash) continue;\n\n\t\t\t// Batch by lineId\n\t\t\tlet batch = byLineId.get(result.lineId);\n\t\t\tif (!batch) {\n\t\t\t\tbatch = {\n\t\t\t\t\tbytecodes: [],\n\t\t\t\t\treads: new Set(),\n\t\t\t\t\twrites: new Set(),\n\t\t\t\t\tisVariableDef: false,\n\t\t\t\t\texpressions: state.expressions.length > 0 ? [...state.expressions] : [],\n\t\t\t\t\ttextHash: result.compiledAgainstHash,\n\t\t\t\t};\n\t\t\t\tbyLineId.set(result.lineId, batch);\n\t\t\t}\n\n\t\t\tbatch.bytecodes.push(result.program);\n\t\t\tfor (const r of result.reads) batch.reads.add(r);\n\t\t\tfor (const w of result.writes) batch.writes.add(w);\n\t\t\tif (result.isVariableDef) batch.isVariableDef = true;\n\t\t\tvalidCount++;\n\t\t}\n\n\t\t// Store batched results\n\t\tlet stored = 0;\n\t\tfor (const [lineId, batch] of byLineId) {\n\t\t\tif (batch.bytecodes.length === 0) continue;\n\t\t\t// Preserve inlineSolveCount from the LineState so the evaluator\n\t\t\t// knows this line has multiple expressions (avoids re-extraction).\n\t\t\tconst state = doc.getLineById(lineId);\n\t\t\tconst inlineSolveCount = state?.inlineSolveCount ?? 0;\n\t\t\tdoc.updateLineCompiled(\n\t\t\t\tlineId,\n\t\t\t\tbatch.expressions,\n\t\t\t\tbatch.bytecodes,\n\t\t\t\t[...batch.reads],\n\t\t\t\t[...batch.writes],\n\t\t\t\tbatch.isVariableDef,\n\t\t\t\tinlineSolveCount,\n\t\t\t);\n\t\t\tstored += batch.bytecodes.length;\n\t\t}\n\n\t\treturn stored;\n\t}\n\n\t/**\n\t * Terminate the worker and clean up.\n\t */\n\tterminate(): void {\n\t\tif (this.worker) {\n\t\t\tthis.worker.terminate();\n\t\t\tthis.worker = null;\n\t\t\tthis.pending.clear();\n\t\t}\n\t}\n\n\t/**\n\t * Whether the worker is currently active.\n\t */\n\tget isActive(): boolean {\n\t\treturn this.worker !== null;\n\t}\n\n\t// ── Private helpers ────────────────────────────────────────────────\n\n\t/**\n\t * Reconstruct a BytecodeProgram from transferred ArrayBuffers.\n\t *\n\t * The transferred ArrayBuffers are zero-copy, we create TypedArray\n\t * views directly over them. No data is copied or serialized.\n\t */\n\tprivate reconstructResult(raw: WorkerCompileResult): CompileResponseItem {\n\t\tif (raw.error) {\n\t\t\treturn {\n\t\t\t\tlineId: raw.lineId,\n\t\t\t\tcompiledAgainstHash: raw.compiledAgainstHash,\n\t\t\t\tprogram: { opcodes: new Uint8Array(0), numbers: new Float64Array(0), strings: [], hasAsync: false },\n\t\t\t\treads: [],\n\t\t\t\twrites: [],\n\t\t\t\tisVariableDef: false,\n\t\t\t\terror: raw.error,\n\t\t\t};\n\t\t}\n\n\t\t// Reconstruct TypedArrays from transferred ArrayBuffers.\n\t\t// These are views over the same memory, zero-copy from worker.\n\t\tconst opcodes =\n\t\t\traw.opcodesLength > 0\n\t\t\t\t? new Uint8Array(raw.opcodesBuffer, 0, raw.opcodesLength)\n\t\t\t\t: new Uint8Array(0);\n\t\tconst numbers =\n\t\t\traw.numbersLength > 0\n\t\t\t\t? new Float64Array(raw.numbersBuffer, 0, raw.numbersLength)\n\t\t\t\t: new Float64Array(0);\n\n\t\tconst program: BytecodeProgram = {\n\t\t\topcodes,\n\t\t\tnumbers,\n\t\t\tstrings: raw.strings,\n\t\t\thasAsync: false,\n\t\t};\n\n\t\treturn {\n\t\t\tlineId: raw.lineId,\n\t\t\tcompiledAgainstHash: raw.compiledAgainstHash,\n\t\t\tprogram,\n\t\t\treads: raw.reads,\n\t\t\twrites: raw.writes,\n\t\t\tisVariableDef: raw.isVariableDef,\n\t\t\terror: null,\n\t\t};\n\t}\n}\n","/**\n * PageManager, page-based LRU eviction + directional preloading.\n *\n * Groups document lines into fixed-size pages (128 lines each) and manages\n * three temperature tiers:\n * • Hot (viewport ± 3 pages): Keep bytecode + results\n * • Warm (viewport ± 6 pages): Keep bytecode, evict results\n * • Cold (beyond ± 6 pages): Evict bytecode + results (except variable defs)\n *\n * Variable definition bytecode is **never evicted** because it forms the\n * backbone of the dependency graph and VM checkpoints.\n *\n * Preloading: When the user scrolls in a consistent direction, the next\n * 1–2 pages are pre-compiled via the background worker so bytecode is\n * cache-hot by the time those lines scroll into view.\n *\n * Usage:\n * const pm = new PageManager();\n * // After evaluation:\n * pm.maintainAfterEval(viewport, doc);\n * // After scroll (viewport-only change):\n * pm.maintainAfterEval(viewport, doc);\n * const targets = pm.getPreloadTargets(viewport, doc);\n * // dispatch targets to compilation worker\n */\n\nimport { DocumentModel } from \"@solve-js/engine/DocumentModel\";\n// Deliberately the shared lexer, not an engine's own.\n//\n// `classifyLine` and `findInlineSolves` are character-level scans for headings,\n// comment markers, code fences and backtick spans. Neither consults the\n// keyword, unit or operator tables, so every lexer returns the same answer and\n// there is nothing per-engine to respect. Pinned by\n// __tests__/lexer/LineClassificationIsVocabularyIndependent.spec.ts, which\n// compares a bare lexer against one carrying extra vocabulary.\n//\n// This matters because these are free functions with no engine to ask. Making\n// them engine-aware would mean changing their signatures and every caller for\n// no behavioural difference.\nimport { sharedLexer } from \"@solve-js/lexer/Lexer\";\n\n// ── Constants ────────────────────────────────────────────────────────────\n\n/** Number of lines per page. Tunable, 128 balances granularity with overhead. */\nexport const PAGE_SIZE = 128;\n\n/** Number of pages on each side of the viewport considered \"hot.\" */\nconst HOT_PAGE_RADIUS = 3;\n\n/** Number of pages on each side of the viewport considered \"warm\" (includes hot). */\nconst WARM_PAGE_RADIUS = 6;\n\n/** Number of pages to preload ahead of the scroll direction. */\nconst PRELOAD_PAGE_COUNT = 2;\n\n/**\n * Pages just beyond the warm range that are \"newly cold\", they were warm\n * on the previous scroll and now need bytecode eviction. Once evicted, they\n * stay cold and don't need re-eviction on subsequent frames (the inner\n * `evictPageBytecode` checks for non-null bytecode and short-circuits).\n *\n * This buffer lets us skip iterating the vast majority of cold pages on\n * every scroll, reducing `maintainAfterEval` from O(total pages) to\n * O(hot + warm + buffer) ≈ O(1) for any document size.\n */\nconst COLD_EVICT_BUFFER = HOT_PAGE_RADIUS;\n\n// ── PageManager ──────────────────────────────────────────────────────────\n\n/**\n * Splits a long document into pages so only what is near the viewport is held\n * in full.\n *\n * A document is edited constantly and most of it is off screen. Paging keeps\n * the cost of a keystroke proportional to what is visible rather than to the\n * length of the document.\n */\nexport class PageManager {\n\t/** Previous viewport for scroll direction detection. null = no previous viewport. */\n\tprivate lastViewportStart: number | null = null;\n\n\t/** Saved scroll direction from the most recent maintainAfterEval call. */\n\tprivate savedDirection: \"down\" | \"up\" | null = null;\n\n\t/** Per-page access counter for LRU tracking. */\n\tprivate pageAccess: Map<number, number> = new Map();\n\n\t/** Monotonically increasing access sequence number. */\n\tprivate accessSeq = 0;\n\n\t// ── Static helpers ─────────────────────────────────────────────────\n\n\t/** Get the page number for a 1-based line number (0-based page index). */\n\tstatic pageForLine(lineNumber: number): number {\n\t\treturn Math.floor((lineNumber - 1) / PAGE_SIZE);\n\t}\n\n\t/** Get the 1-based inclusive line range for a page. */\n\tstatic pageRange(\n\t\tpageNum: number,\n\t\tdocLineCount: number\n\t): { startLine: number; endLine: number } {\n\t\treturn {\n\t\t\tstartLine: pageNum * PAGE_SIZE + 1,\n\t\t\tendLine: Math.min((pageNum + 1) * PAGE_SIZE, docLineCount),\n\t\t};\n\t}\n\n\t// ── Public API ─────────────────────────────────────────────────────\n\n\t/**\n\t * Detect scroll direction from viewport movement.\n\t * Returns null on first call (no previous viewport) or no movement.\n\t */\n\tdetectDirection(newViewport: { startLine: number }): \"down\" | \"up\" | null {\n\t\tif (this.lastViewportStart === null) return null;\n\t\tif (newViewport.startLine > this.lastViewportStart) return \"down\";\n\t\tif (newViewport.startLine < this.lastViewportStart) return \"up\";\n\t\treturn null;\n\t}\n\n\t/**\n\t * Maintain page tiers after evaluation.\n\t *\n\t * 1. Records the new viewport position\n\t * 2. Touches hot pages (viewport ± HOT_PAGE_RADIUS) for LRU\n\t * 3. Evicts cold/warm pages based on distance from viewport\n\t *\n\t * Call this after every `evaluate()`, `setViewport()`, or `evaluateAll()`.\n\t */\n\tmaintainAfterEval(\n\t\tviewport: { startLine: number; endLine: number },\n\t\tdoc: DocumentModel\n\t): void {\n\t\t// ── Capture direction BEFORE updating lastViewportStart ───\n\t\tthis.savedDirection = this.detectDirection(viewport);\n\t\tthis.lastViewportStart = viewport.startLine;\n\n\t\tconst docLineCount = doc.lineCount;\n\t\tconst viewportStartPage = PageManager.pageForLine(viewport.startLine);\n\t\tconst viewportEndPage = PageManager.pageForLine(viewport.endLine);\n\t\tconst lastPage = PageManager.pageForLine(docLineCount);\n\n\t\t// Compute hot/warm page ranges in O(1) using range math:\n\t\t// A page is within RADIUS of the viewport span iff it falls in\n\t\t// [viewportStartPage - RADIUS, viewportEndPage + RADIUS].\n\t\tconst hotStart = Math.max(0, viewportStartPage - HOT_PAGE_RADIUS);\n\t\tconst hotEnd = Math.min(lastPage, viewportEndPage + HOT_PAGE_RADIUS);\n\t\tconst warmStart = Math.max(0, viewportStartPage - WARM_PAGE_RADIUS);\n\t\tconst warmEnd = Math.min(lastPage, viewportEndPage + WARM_PAGE_RADIUS);\n\n\t\t// Touch hot pages to keep them fresh in LRU\n\t\tfor (let p = hotStart; p <= hotEnd; p++) {\n\t\t\tthis.touchPage(p);\n\t\t}\n\n\t\t// Evict warm-but-not-hot pages: keep bytecode, evict results only\n\t\tfor (let p = warmStart; p <= warmEnd; p++) {\n\t\t\tif (p >= hotStart && p <= hotEnd) continue;\n\t\t\tthis.evictPageResults(p, doc, docLineCount);\n\t\t}\n\n\t\t// Evict \"newly cold\" pages: a buffer zone just outside the warm\n\t\t// range. Pages beyond this buffer were already evicted on prior\n\t\t// scrolls and don't need re-eviction.\n\t\t// ── Left side (just above page 0, just below warm range) ──\n\t\tconst coldLeftEnd = warmStart - 1;\n\t\tconst coldLeftStart = Math.max(0, coldLeftEnd - COLD_EVICT_BUFFER + 1);\n\t\tfor (let p = coldLeftStart; p <= coldLeftEnd; p++) {\n\t\t\tthis.evictPageBytecode(p, doc, docLineCount);\n\t\t}\n\t\t// ── Right side (just above warm range, just below lastPage) ──\n\t\tconst coldRightStart = warmEnd + 1;\n\t\tconst coldRightEnd = Math.min(lastPage, coldRightStart + COLD_EVICT_BUFFER - 1);\n\t\tfor (let p = coldRightStart; p <= coldRightEnd; p++) {\n\t\t\tthis.evictPageBytecode(p, doc, docLineCount);\n\t\t}\n\t}\n\n\t/**\n\t * Get lines ahead of the viewport that should be pre-compiled.\n\t *\n\t * Looks PRELOAD_PAGE_COUNT pages ahead of the current scroll direction.\n\t * Only returns lines that are dirty, don't already have bytecode,\n\t * and are not empty/markdown-only.\n\t *\n\t * @param viewport The current viewport.\n\t * @param doc The document model.\n\t * @returns Items ready to send to the compilation worker.\n\t */\n\tgetPreloadTargets(\n\t\tviewport: { startLine: number; endLine: number },\n\t\tdoc: DocumentModel\n\t): Array<{ lineId: number; expression: string; textHash: number }> {\n\t\t// Use the direction saved by the last maintainAfterEval call.\n\t\t// We cannot re-detect because maintainAfterEval already updated\n\t\t// lastViewportStart to the current viewport position.\n\t\tconst direction = this.savedDirection;\n\t\tif (!direction) return [];\n\n\t\tconst items: Array<{ lineId: number; expression: string; textHash: number }> = [];\n\t\t// Use viewport end page for downward preload start, start page for upward.\n\t\t// This ensures we preload *beyond* the full viewport span, not just its start.\n\t\tconst viewportEndPage = PageManager.pageForLine(viewport.endLine);\n\t\tconst viewportStartPage = PageManager.pageForLine(viewport.startLine);\n\t\tconst lastPage = PageManager.pageForLine(doc.lineCount);\n\n\t\tconst pages: number[] = [];\n\t\tif (direction === \"down\") {\n\t\t\t// Preload pages immediately after the viewport's hot radius beyond its end\n\t\t\tconst startPage = viewportEndPage + HOT_PAGE_RADIUS + 1;\n\t\t\tconst endPage = Math.min(startPage + PRELOAD_PAGE_COUNT - 1, lastPage);\n\t\t\tfor (let p = startPage; p <= endPage && p <= lastPage; p++) {\n\t\t\t\tpages.push(p);\n\t\t\t}\n\t\t} else {\n\t\t\t// Preload pages immediately before the viewport's hot radius before its start\n\t\t\tconst firstPreloadPage = viewportStartPage - HOT_PAGE_RADIUS - 1;\n\t\t\tfor (let p = firstPreloadPage; p > firstPreloadPage - PRELOAD_PAGE_COUNT && p >= 0; p--) {\n\t\t\t\tpages.push(p);\n\t\t\t}\n\t\t}\n\n\t\tfor (const pageNum of pages) {\n\t\t\tconst range = PageManager.pageRange(pageNum, doc.lineCount);\n\t\t\tfor (let pos = range.startLine; pos <= range.endLine; pos++) {\n\t\t\t\tconst state = doc.getLineAt(pos);\n\t\t\t\tif (!state) continue;\n\t\t\t\tif (!state.dirty) continue;\n\t\t\t\tif (state.bytecodes.length > 0 && !state.isVariableDef) continue;\n\t\t\t\tif (state.isEmpty) continue;\n\n\t\t\t\t// Extract expressions using the shared lexer to handle inline\n\t\t\t\t// solves (s`...`). For full-line expressions, this returns [text].\n\t\t\t\t// For inline solve lines, this returns each extracted expression.\n\t\t\t\tif (state.expressions.length > 0) {\n\t\t\t\t\t// Use pre-extracted expressions (from prior evaluation)\n\t\t\t\t\tfor (const expression of state.expressions) {\n\t\t\t\t\t\tif (!expression.trim()) continue;\n\t\t\t\t\t\titems.push({\n\t\t\t\t\t\t\tlineId: state.lineId,\n\t\t\t\t\t\t\texpression,\n\t\t\t\t\t\t\ttextHash: state.textHash,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Expressions not yet extracted, use lexer to find inline solves\n\t\t\t\t\tconst inlineSpans = sharedLexer.findInlineSolves(state.text);\n\t\t\t\t\tif (inlineSpans.length > 0) {\n\t\t\t\t\t\tfor (const span of inlineSpans) {\n\t\t\t\t\t\t\tif (!span.expression.trim()) continue;\n\t\t\t\t\t\t\titems.push({\n\t\t\t\t\t\t\t\tlineId: state.lineId,\n\t\t\t\t\t\t\t\texpression: span.expression,\n\t\t\t\t\t\t\t\ttextHash: state.textHash,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Full-line expression\n\t\t\t\t\t\tconst expression = state.text.trim();\n\t\t\t\t\t\tif (expression) {\n\t\t\t\t\t\t\titems.push({\n\t\t\t\t\t\t\t\tlineId: state.lineId,\n\t\t\t\t\t\t\t\texpression,\n\t\t\t\t\t\t\t\ttextHash: state.textHash,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn items;\n\t}\n\n\t/**\n\t * Reset internal state (e.g., after document switch).\n\t */\n\tclear(): void {\n\t\tthis.pageAccess.clear();\n\t\tthis.accessSeq = 0;\n\t\tthis.lastViewportStart = null;\n\t\tthis.savedDirection = null;\n\t}\n\n\t// ── Private helpers ─────────────────────────────────────────────────\n\n\t/** Record a page access with a monotonic sequence number. */\n\tprivate touchPage(pageNum: number): void {\n\t\tthis.pageAccess.set(pageNum, ++this.accessSeq);\n\t}\n\n\t/**\n\t * Evict results from all non-variable-def lines in a page.\n\t * Bytecode is preserved so Tier 2 execution works on scroll-back.\n\t */\n\tprivate evictPageResults(\n\t\tpageNum: number,\n\t\tdoc: DocumentModel,\n\t\tdocLineCount: number\n\t): void {\n\t\tconst range = PageManager.pageRange(pageNum, docLineCount);\n\t\tfor (let pos = range.startLine; pos <= range.endLine; pos++) {\n\t\t\tconst state = doc.getLineAt(pos);\n\t\t\tif (state && !state.isVariableDef && state.results.length > 0) {\n\t\t\t\tstate.results = [];\n\t\t\t\tstate.result = null;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Evict bytecode + results from all non-variable-def lines in a page.\n\t * Variable definition bytecode is **never** evicted, it forms the\n\t * backbone of the DAG and VM checkpoints.\n\t *\n\t * Evicted lines are marked dirty so they get Tier 1 re-evaluation\n\t * when scrolled back into view.\n\t */\n\tprivate evictPageBytecode(\n\t\tpageNum: number,\n\t\tdoc: DocumentModel,\n\t\tdocLineCount: number\n\t): void {\n\t\tconst range = PageManager.pageRange(pageNum, docLineCount);\n\t\tfor (let pos = range.startLine; pos <= range.endLine; pos++) {\n\t\t\tconst state = doc.getLineAt(pos);\n\t\t\tif (!state || state.isVariableDef) continue;\n\n\t\t\tif (state.bytecodes.length > 0 || state.results.length > 0) {\n\t\t\t\tstate.bytecodes = [];\n\t\t\t\tstate.results = [];\n\t\t\t\tstate.result = null;\n\t\t\t\tdoc.markDirty(state.lineId);\n\t\t\t}\n\t\t}\n\t}\n}\n","import { ExpressionEngine } from \"@solve-js/engine/ExpressionEngine\";\nimport {\n\tDocumentModel,\n\tLineChange,\n\tLineState,\n\tViewportRange,\n} from \"@solve-js/engine/DocumentModel\";\nimport { Value, ValueType, enableValueArena, disableValueArena, errorValue } from \"@solve-js/vm/Value\";\nimport { DependencyGraph } from \"@solve-js/vm/DependencyGraph\";\nimport { VMCheckpointer } from \"@solve-js/vm/VMCheckpoints\";\nimport { isEmptyLine } from \"@solve-js/engine/ExpressionEngineSafety\";\n// Deliberately the shared lexer, not an engine's own.\n//\n// `classifyLine` and `findInlineSolves` are character-level scans for headings,\n// comment markers, code fences and backtick spans. Neither consults the\n// keyword, unit or operator tables, so every lexer returns the same answer and\n// there is nothing per-engine to respect. Pinned by\n// __tests__/lexer/LineClassificationIsVocabularyIndependent.spec.ts, which\n// compares a bare lexer against one carrying extra vocabulary.\n//\n// This matters because these are free functions with no engine to ask. Making\n// them engine-aware would mean changing their signatures and every caller for\n// no behavioural difference.\nimport { sharedLexer } from \"@solve-js/lexer/Lexer\";\nimport { CompilationWorkerManager, type CompileRequestItem } from \"@solve-js/engine/CompilationWorkerManager\";\nimport { PageManager } from \"@solve-js/engine/PageManager\";\nimport type { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { EngineError } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { sharedGlobalVariableStore, globalDagKey } from \"@solve-js/vm/GlobalVariableStore\";\n\n// ── EvalTier (diagnostic enum) ──────────────────────────────────────────\n\n/**\n * How much work a line's evaluation required.\n *\n * The tiers exist because most lines in a document have not changed. A line\n * that is clean and cached costs far less than one being compiled fresh, and\n * knowing which happened is how a slow document gets diagnosed.\n */\nexport enum EvalTier {\n\t/** Full pipeline: Lex → Parse → Compile → Execute (visible + dirty). */\n\tTier1 = 1,\n\t/** Execute-only from cached bytecode (visible + cached). */\n\tTier2 = 2,\n\t/** Compile-only for dependency tracking (invisible). Executes only variable assignments. */\n\tTier3 = 3,\n\t/** Skipped, already clean or non-evaluable. */\n\tSkipped = 0,\n}\n\n// ── EvalLineResult ──────────────────────────────────────────────────────\n\n/** Outcome for one line, including which tier handled it. */\nexport interface EvalLineResult {\n\t/** The line's persistent ID from DocumentModel. */\n\tlineId: number;\n\t/** 1-based line position. */\n\tlineNumber: number;\n\t/** Which tier was used. */\n\ttier: EvalTier;\n\t/** The first evaluation result, or null on error / non-evaluable. */\n\tresult: Value | null;\n\t/** All result groups (one per expression/inline-solve), or undefined if skipped. */\n\tresults?: Value[][];\n\t/** Error message, or null. */\n\terror: string | null;\n}\n\n// ── EvalResult ──────────────────────────────────────────────────────────\n\n/** Outcome for a whole evaluation pass, with per-tier counts. */\nexport interface EvalResult {\n\t/** Per-line evaluation results. */\n\tlines: EvalLineResult[];\n\t/** Map of line numbers → flattened results for quick lookup. */\n\tresultMap: Map<number, Value[]>;\n\t/** Number of lines processed at each tier. */\n\ttierCounts: { tier1: number; tier2: number; tier3: number; skipped: number };\n}\n\n// ── ThreeTierEvaluator ──────────────────────────────────────────────────\n\n/**\n * Orchestrates three-tier evaluation over a persistent DocumentModel.\n *\n * ── Tier assignment ─────────────────────────────────────────────────\n * | Tier | Condition | Action |\n * |───────|────────────────────────────────────|───────────────────────────────|\n * | **1** | Visible + Dirty (new/changed) | Full pipeline: lex→parse→compile→execute |\n * | **2** | Visible + Cached (scroll into view)| Execute from cached bytecode |\n * | **3** | Invisible + Dirty | Compile-only; execute only variable defs |\n * | Skip | Clean, empty, or non-evaluable | No action |\n *\n * ── Evaluation order ─────────────────────────────────────────────────\n * Lines are always processed in ascending document order (line 1 → end)\n * so that variable assignments flow correctly through the shared VM.\n * Tier 2 relies on this: by the time a clean cached line is reached,\n * the VM already contains all variables from preceding Tier-1 lines.\n *\n * ── Thread safety ────────────────────────────────────────────────────\n * Tier 1 (visible+dirty) compilation runs synchronously on the main thread\n * for immediate rendering. Tier 3 (invisible+dirty) compilation can be\n * dispatched to a Web Worker via `dispatchBackgroundCompiles()`. Worker-\n * compiled bytecode is stored in the DocumentModel and validated via\n * `isBytecodeValid()` to ensure the line text hasn't changed between\n * dispatch and response.\n */\nexport class ThreeTierEvaluator {\n\tprivate doc: DocumentModel;\n\tprivate engine: ExpressionEngine;\n\tprivate dag: DependencyGraph;\n\tprivate checkpointer: VMCheckpointer | null;\n\tprivate compilationWorker: CompilationWorkerManager | null = null;\n\tprivate pageManager: PageManager;\n\n\t/**\n\t * Unsubscribe from sharedGlobalVariableStore, set in the constructor\n\t * called from terminateWorker(). See the subscription itself below for\n\t * why this only marks lines dirty and never re-evaluates synchronously.\n\t */\n\tprivate globalUnsubscribe: (() => void) | null = null;\n\n\t/**\n\t * @param doc The persistent document model.\n\t * @param engine The expression engine (shared VM is accessed via engine.getVM()).\n\t * @param checkpointer Optional VM state checkpointer. If provided, the evaluator\n\t * will create checkpoints after variable-definition lines and support fast VM\n\t * restoration via `restoreTo()`. If omitted, checkpointing is disabled.\n\t */\n\tconstructor(\n\t\tdoc: DocumentModel,\n\t\tengine: ExpressionEngine,\n\t\tcheckpointer?: VMCheckpointer\n\t) {\n\t\tthis.doc = doc;\n\t\tthis.engine = engine;\n\t\tthis.dag = engine.getDag();\n\t\tthis.checkpointer = checkpointer ?? null;\n\t\tthis.pageManager = new PageManager();\n\n\t\t// Lets the engine answer \"what's line N's cached result\" for\n\t\t// cross-line features (prev/line<N>/aggregation) without owning\n\t\t// document lifecycle itself. See ExpressionEngine.makeLineContext().\n\t\tthis.engine.setDocumentModel(this.doc);\n\n\t\t// ── Cross-document global-variable propagation ──────────────────\n\t\t// GlobalVariableAsyncResolver (via preflight) handles a line's FIRST\n\t\t// resolution when a global it reads wasn't known yet. This handles\n\t\t// the ONGOING case: a line that already has a real (non-pending)\n\t\t// value for `global :x` needs to go dirty again when some OTHER\n\t\t// document writes a NEW value to x, so this document's next\n\t\t// evaluate() picks up the change, \"dealing with the DAG across\n\t\t// pages\", not just first-resolution.\n\t\tthis.globalUnsubscribe = sharedGlobalVariableStore.subscribe((name) => {\n\t\t\t// Mark-dirty ONLY, never synchronously re-evaluate here.\n\t\t\t// enableValueArena/disableValueArena (Value.ts) is a single\n\t\t\t// non-reentrant module-level flag; evaluate()/setViewport() both\n\t\t\t// wrap their body in it, so a re-entrant evaluate() call from\n\t\t\t// inside this callback (itself possibly firing from INSIDE\n\t\t\t// another evaluate() call, via a STORE_GLOBAL_VAR opcode in some\n\t\t\t// other document being evaluated concurrently) would disable the\n\t\t\t// arena out from under the still-running outer call. This\n\t\t\t// mirrors applyTransaction()'s existing contract exactly: mark\n\t\t\t// dirty, let the caller's own evaluate() cadence pick it up.\n\t\t\tfor (const lineNumber of this.dag.getAffectedLines(globalDagKey(name))) {\n\t\t\t\tthis.doc.markDirtyByLineNumber(lineNumber);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Evaluate all lines needed to render the given viewport.\n\t *\n\t * Processes lines from 1 to `viewport.endLine` in document order.\n\t * Dirty lines in the viewport get Tier-1 full pipeline; clean cached\n\t * lines get Tier-2 bytecode execution. Lines after the viewport\n\t * get Tier-3 compile-only (with variable-def execution).\n\t *\n\t * @returns Results for all processed lines, including tier metadata.\n\t */\n\tevaluate(viewport: ViewportRange, signal?: AbortSignal): EvalResult {\n\t\t// ── One AbortController Per Keystroke ────────────────────────\n\t\t// Link the UI layer's keystroke signal to the engine so that\n\t\t// all per-evaluation AbortControllers created during this call\n\t\t// are canceled when the user types a new keystroke.\n\t\tthis.engine.setKeystrokeSignal(signal ?? null);\n\n\t\t// ── Phase 5.3: Enable arena for zero-allocation Value reuse ──\n\t\tenableValueArena();\n\t\ttry {\n\t\t\t// Re-seed running-total accumulators before the from-line-1 pass. A\n\t\t\t// `total += 5` line reads its own running value, so re-running it in\n\t\t\t// place would read the previous evaluation's total and double-count.\n\t\t\t// Reset each accumulator variable and mark every line that touches\n\t\t\t// it dirty, so the loop below recomputes the total from its seed,\n\t\t\t// top to bottom. (No-op when the document has no accumulators.)\n\t\t\tthis.reseedAccumulators();\n\n\t\t\tconst lines: EvalLineResult[] = [];\n\t\t\tconst resultMap = new Map<number, Value[]>();\n\t\t\tconst tierCounts = { tier1: 0, tier2: 0, tier3: 0, skipped: 0 };\n\n\t\t\t// Process from line 1 to the end of the viewport for correct VM state.\n\t\t\t// We go to viewport.endLine because Tier 3 for invisible lines can be\n\t\t\t// done separately via backgroundCompile().\n\t\t\tconst docEnd = this.doc.lineCount;\n\t\t\tconst evalEnd = Math.min(viewport.endLine, docEnd);\n\n\t\t\tfor (let pos = 1; pos <= evalEnd; pos++) {\n\t\t\t\tconst state = this.doc.getLineAt(pos);\n\t\t\t\tif (!state) {\n\t\t\t\t\ttierCounts.skipped++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst inViewport = pos >= viewport.startLine && pos <= viewport.endLine;\n\n\t\t\t\tconst lineResult = this.evaluateSingleLine(state, pos, inViewport);\n\t\t\t\tlines.push(lineResult);\n\n\t\t\t\tif (lineResult.tier === EvalTier.Tier1) tierCounts.tier1++;\n\t\t\t\telse if (lineResult.tier === EvalTier.Tier2) tierCounts.tier2++;\n\t\t\t\telse if (lineResult.tier === EvalTier.Tier3) tierCounts.tier3++;\n\t\t\t\telse tierCounts.skipped++;\n\n\t\t\t\tif (lineResult.results && inViewport) {\n\t\t\t\t\tresultMap.set(pos, lineResult.results.flat());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ── Phase 5.2g: Page-based LRU eviction ──────────────────────\n\t\t\t// Evict bytecode/results from cold/warm pages to bound memory.\n\t\t\tthis.pageManager.maintainAfterEval(viewport, this.doc);\n\n\t\t\treturn { lines, resultMap, tierCounts };\n\t\t} finally {\n\t\t\t// Clear keystroke signal to prevent stale signal references\n\t\t\t// from being used by subsequent evaluations from other code paths.\n\t\t\tthis.engine.setKeystrokeSignal(null);\n\n\t\t\t// Phase 5.3: Always disable arena, even on exception.\n\t\t\t// Prevents arena Values from leaking into subsequent evaluations or tests.\n\t\t\tdisableValueArena();\n\t\t}\n\t}\n\n\t/**\n\t * Background-compile invisible dirty lines beyond the viewport (Tier 3 only).\n\t *\n\t * Compiles expressions to discover reads/writes for the dependency graph\n\t * without executing display-only expressions. Variable definitions are\n\t * executed to maintain VM state for future Tier-2 executions.\n\t *\n\t * This is intended to be called after evaluate() so visible lines are\n\t * rendered first, then background work fills in the dependency graph.\n\t *\n\t * **Phase 5.2h:** This synchronous method is retained for environments\n\t * without Worker support. Prefer `dispatchBackgroundCompiles()` which\n\t * offloads compilation to a Web Worker with Transferable bytecode.\n\t */\n\tbackgroundCompile(viewport: ViewportRange): EvalLineResult[] {\n\t\tconst results: EvalLineResult[] = [];\n\t\tconst docEnd = this.doc.lineCount;\n\t\tconst startPos = viewport.endLine + 1;\n\n\t\tfor (let pos = startPos; pos <= docEnd; pos++) {\n\t\t\tconst state = this.doc.getLineAt(pos);\n\t\t\tif (!state) continue;\n\n\t\t\t// Skip clean lines, already compiled + executed\n\t\t\tif (!state.dirty) continue;\n\n\t\t\t// Skip already-compiled Tier 3 lines, they have bytecode\n\t\t\t// but were compiled without execution (non-variable-def).\n\t\t\t// Recompiling is wasteful since the text hasn't changed\n\t\t\t// (text change clears bytecodes via editLine).\n\t\t\tif (state.bytecodes.length > 0 && !state.isVariableDef) continue;\n\n\t\t\tconst lineResult = this.evaluateSingleLine(state, pos, false);\n\t\t\tresults.push(lineResult);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Dispatch background compilation to a Web Worker (Phase 5.2h).\n\t *\n\t * Collects invisible dirty lines beyond the viewport that need compilation,\n\t * sends them to the compilation worker, and asynchronously stores the\n\t * transferred bytecode in the DocumentModel when the worker responds.\n\t *\n\t * This is the non-blocking alternative to `backgroundCompile()`. The worker\n\t * compiles expressions with Transferable ArrayBuffers (zero-copy postMessage),\n\t * so bytecode appears on the main thread without serialization overhead.\n\t *\n\t * Lines that already have cached bytecode (from a previous worker pass or\n\t * synchronous compile) are skipped, only truly uncompiled dirty lines are\n\t * sent to the worker.\n\t *\n\t * **Usage:** Call after `evaluate()` so visible lines render first, then\n\t * this fills the bytecode cache for future Tier-2 scrolls.\n\t *\n\t * @param viewport The current visible range. Lines beyond viewport.endLine\n\t * that are dirty and don't have bytecode are dispatched.\n\t */\n\tdispatchBackgroundCompiles(viewport: ViewportRange): void {\n\t\t// Collect invisible dirty lines that need compilation\n\t\tconst items = this.collectInvisibleCompileTargets(viewport);\n\t\tif (items.length === 0) return;\n\n\t\t// Lazy-init the worker (only if there are items to compile)\n\t\tif (!this.compilationWorker) {\n\t\t\tthis.compilationWorker = new CompilationWorkerManager();\n\t\t}\n\n\t\t// Fire-and-forget: send to worker, store results when they arrive\n\t\tthis.compilationWorker.compileBatch(items).then((results) => {\n\t\t\tthis.compilationWorker!.storeResults(results, this.doc);\n\t\t}).catch((_err) => {\n\t\t\t// Worker failure is non-fatal, next evaluate() will compile\n\t\t\t// these expressions synchronously.\n\t\t});\n\t}\n\n\t/**\n\t * Terminate the compilation worker if active, and unsubscribe from\n\t * sharedGlobalVariableStore. Call this when the evaluator is no longer\n\t * needed to clean up resources, every call site that retires a\n\t * ThreeTierEvaluator (document switch, pane destroy()) already calls\n\t * this unconditionally, so folding the global-store unsubscribe in here\n\t * needs no new call sites anywhere.\n\t */\n\tterminateWorker(): void {\n\t\tif (this.compilationWorker) {\n\t\t\tthis.compilationWorker.terminate();\n\t\t\tthis.compilationWorker = null;\n\t\t}\n\t\tif (this.globalUnsubscribe) {\n\t\t\tthis.globalUnsubscribe();\n\t\t\tthis.globalUnsubscribe = null;\n\t\t}\n\t}\n\n\t/**\n\t * Get the DocumentModel (read-only access for decoration building).\n\t */\n\tgetDoc(): DocumentModel {\n\t\treturn this.doc;\n\t}\n\n\t/**\n\t * Evaluate all dirty lines in the document, regardless of viewport.\n\t * Used for full re-evaluation after plugin register/unregister.\n\t */\n\tevaluateAll(signal?: AbortSignal): EvalResult {\n\t\tconst viewport = { startLine: 1, endLine: this.doc.lineCount };\n\t\tconst result = this.evaluate(viewport, signal);\n\t\t// evaluate() already calls maintainAfterEval internally\n\t\treturn result;\n\t}\n\n\t/**\n\t * Zero-allocation viewport evaluation, the Phase 5.2e \"holy grail.\"\n\t *\n\t * **Key insight:** When the user scrolls (viewport-only change, no edits),\n\t * we don't need to re-evaluate from line 1. Instead:\n\t *\n\t * 1. Restore the VM to just before the viewport via the nearest checkpoint.\n\t * 2. Evaluate ONLY the visible lines (Tier 2 for clean cached, Tier 1 for dirty).\n\t * 3. Lines before the viewport are completely skipped, their state lives in\n\t * the VM checkpointer's prototypal chain.\n\t *\n\t * **Correctness guard:** If any variable-definition line before the viewport\n\t * is dirty (e.g., the user edited a variable def that hasn't been\n\t * re-evaluated yet), we clear stale checkpoints and fall back to `evaluate()`\n\t * which processes from line 1 and rebuilds fresh checkpoints. This\n\t * guarantees that stale checkpoints are never used as restoration targets.\n\t * Only variable-def lines matter here, `VMCheckpointer.snapshot()` only\n\t * records state for lines that write a variable, so a dirty plain-expression\n\t * line before the viewport has no checkpoint to invalidate (see\n\t * `DocumentModel.hasAnyDirtyVariableDefLineBefore()`).\n\t *\n\t * **Performance:** O(visible lines) instead of O(document length). Target:\n\t * < 1ms for a typical ~30-line viewport, independent of document size.\n\t *\n\t * @param viewport The visible line range.\n\t * @returns Results for visible lines only. Lines before the viewport are\n\t * not included in `lines[]` or `resultMap`.\n\t */\n\tsetViewport(viewport: ViewportRange, signal?: AbortSignal): EvalResult {\n\t\t// ── One AbortController Per Keystroke ────────────────────────\n\t\t// Link the UI layer's keystroke signal to the engine.\n\t\tthis.engine.setKeystrokeSignal(signal ?? null);\n\n\t\t// ── Correctness guard: dirty lines before viewport invalidate checkpoints ──\n\t\tif (viewport.startLine > 1 && this.hasDirtyLinesBefore(viewport.startLine)) {\n\t\t\t// Clear stale checkpoints, evaluate() will rebuild them from line 1.\n\t\t\t// evaluate() handles its own arena enable/disable and signal cleanup.\n\t\t\tthis.checkpointer?.clear();\n\t\t\treturn this.evaluate(viewport, signal);\n\t\t}\n\n\t\t// ── Phase 5.2g: Page-based LRU eviction (MUST run before preload) ──\n\t\t// maintainAfterEval captures the scroll direction and updates lastViewportStart\n\t\t// BEFORE preloadNextPages reads the direction for preloading.\n\t\tthis.pageManager.maintainAfterEval(viewport, this.doc);\n\n\t\t// ── Phase 5.2g: Detect scroll direction & preload ───────────\n\t\tthis.preloadNextPages(viewport);\n\n\t\t// ── Restore VM state from nearest checkpoint before the viewport ──\n\t\t// This sets all variables that were defined at or before startLine-1.\n\t\tthis.restoreTo(viewport.startLine - 1);\n\n\t\t// ── Phase 5.3: Enable arena for zero-allocation Tier 2 execution ──\n\t\tenableValueArena();\n\t\ttry {\n\t\t\t// ── Evaluate only visible lines ──\n\t\t\tconst result = this.collectEvalResults(viewport.startLine, viewport.endLine);\n\t\t\treturn result;\n\t\t} finally {\n\t\t\t// Clear keystroke signal to prevent stale signal references.\n\t\t\tthis.engine.setKeystrokeSignal(null);\n\n\t\t\t// Phase 5.3: Always disable arena, even on exception.\n\t\t\t// Prevents cross-test contamination from arena leaks.\n\t\t\tdisableValueArena();\n\t\t}\n\t}\n\n\t/**\n\t * Apply incremental line-level changes to the document model.\n\t *\n\t * **Phase 5.2f:** Replaces the O(N) `setDocument()` + full re-evaluation\n\t * with O(changed) incremental updates. Key benefits:\n\t *\n\t * 1. Unchanged lines retain their persistent lineIds → bytecode survives\n\t * 2. Only changed + DAG-downstream lines are marked dirty → Tier 1 re-evaluation\n\t * 3. Clean lines in viewport use Tier 2 (cached bytecode execution)\n\t * 4. Clean lines outside viewport are skipped entirely\n\t *\n\t * The DAG is fully cleared after propagation: shifted lines would have\n\t * stale entries keyed by old line numbers, so the DAG is rebuilt from\n\t * scratch during the subsequent `evaluate()` call.\n\t *\n\t * **Caller should follow up with `evaluate(viewport)`** to re-evaluate\n\t * dirty lines from line 1 and rebuild the DAG + checkpoints.\n\t *\n\t * @param changes Line-level changes to apply. Must be non-overlapping.\n\t * @returns Metadata about the applied changes.\n\t */\n\tapplyTransaction(changes: LineChange[]): {\n\t\tinserted: number[];\n\t\tremoved: number[];\n\t} {\n\t\t// ── Phase 1: Collect DAG writes + downstream lineIds ───────────\n\t\t// Must happen BEFORE applyChanges() because line numbers are still\n\t\t// valid at this point. We collect writes from deleted lines and\n\t\t// resolve downstream consumers to lineIds (not line numbers) so\n\t\t// they survive the position shifts that applyChanges() causes.\n\t\tconst allWrites = new Set<string>();\n\n\t\tfor (const change of changes) {\n\t\t\tfor (let i = 0; i < change.deleteCount; i++) {\n\t\t\t\tconst lineNum = change.startLine + i;\n\t\t\t\tconst writes = this.dag.getWrites(lineNum);\n\t\t\t\tfor (const w of writes) {\n\t\t\t\t\tallWrites.add(w);\n\t\t\t\t}\n\t\t\t\t// Clean up DAG references for this line\n\t\t\t\tthis.dag.removeLine(lineNum);\n\t\t\t\t// And its cached bytecode. The dependency graph was already\n\t\t\t\t// pruned here; the LineCache was not, so a deleted line kept its\n\t\t\t\t// entry until the whole cache was dropped on a document switch.\n\t\t\t\t// Editing a long document over a session accumulated entries for\n\t\t\t\t// line numbers that no longer existed.\n\t\t\t\tthis.engine.getLineCache().removeAllForLine(lineNum);\n\t\t\t}\n\t\t}\n\n\t\t// Resolve downstream consumers to persistent lineIds BEFORE the\n\t\t// structural change shifts line numbers. After applyChanges(),\n\t\t// we mark these lineIds dirty, their positions don't matter.\n\t\tconst downstreamLineIds = new Set<number>();\n\t\tfor (const writeVar of allWrites) {\n\t\t\tconst affected = this.dag.getAffectedLines(writeVar);\n\t\t\tfor (const lineNum of affected) {\n\t\t\t\tconst state = this.doc.getLineAt(lineNum);\n\t\t\t\tif (state) {\n\t\t\t\t\tdownstreamLineIds.add(state.lineId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// ── Phase 2: Apply structural changes to DocumentModel ─────────\n\t\tconst result = this.doc.applyChanges(changes);\n\n\t\t// ── Phase 3: Clear checkpointer (line numbers shifted) ─────────\n\t\tthis.checkpointer?.clear();\n\n\t\t// ── Phase 4: Mark DAG-downstream lines dirty by lineId ─────────\n\t\t// Using lineId instead of line number is position-agnostic:\n\t\t// lines that shifted due to insertions/deletions above them are\n\t\t// still correctly targeted. Lines that were deleted (lineId no\n\t\t// longer in the doc) are silently ignored by markDirty().\n\t\tfor (const lineId of downstreamLineIds) {\n\t\t\tthis.doc.markDirty(lineId);\n\t\t}\n\n\t\t// ── Phase 5: Clear DAG to avoid phantom entries ────────────────\n\t\t// Entries keyed by old line numbers are stale after structural\n\t\t// changes. Rather than updating shifted entries, we clear the DAG\n\t\t// and let the subsequent evaluate() call rebuild it from scratch.\n\t\tthis.dag.clear();\n\n\t\treturn {\n\t\t\tinserted: result.inserted,\n\t\t\tremoved: result.removed,\n\t\t};\n\t}\n\n\t// ── Private helpers ─────────────────────────────────────────────────\n\n\t/**\n\t * Reset running-total accumulators and mark the lines that touch them\n\t * dirty, so the from-line-1 pass in {@link evaluate} recomputes each total\n\t * from its seed instead of reading its own previous evaluation's value.\n\t *\n\t * A `total += 5` line compiles to no bytecode (it rides the symbolic\n\t * channel), so a clean one would be skipped by the tier dispatch rather\n\t * than re-run. It must re-run to re-apply its delta over the freshly-reset\n\t * base, so every line that WRITES an accumulator name is forced dirty (the\n\t * DAG drops a self-writing line from its own variable's consumers, so\n\t * getAffectedLines can't surface them). Pure readers of the total keep\n\t * their real bytecode and re-run via Tier 2 once the total is correct, so\n\t * they need no special handling. Cheap: a no-op unless the document\n\t * actually uses `+=`/`-=`, and accumulators are rare.\n\t */\n\tprivate reseedAccumulators(): void {\n\t\tconst names = this.engine.resetAccumulators();\n\t\tif (names.size === 0) return;\n\t\tconst docEnd = this.doc.lineCount;\n\t\tfor (let pos = 1; pos <= docEnd; pos++) {\n\t\t\tconst writes = this.dag.getWrites(pos);\n\t\t\tif (writes.size === 0) continue;\n\t\t\tfor (const w of writes) {\n\t\t\t\tif (names.has(w)) {\n\t\t\t\t\tthis.doc.markDirtyByLineNumber(pos);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Collect evaluation results for a contiguous range of lines.\n\t *\n\t * Used by both `evaluate()` (startLine=1) and `setViewport()` (any start).\n\t * All lines in the range are treated as in-viewport (visible), callers that\n\t * need the invisible/dirty → Tier 3 handling should use `evaluate()` instead.\n\t *\n\t * @param startLine First line to evaluate (1-based, inclusive).\n\t * @param endLine Last line to evaluate (1-based, inclusive). Clamped to docEnd.\n\t */\n\tprivate collectEvalResults(startLine: number, endLine: number): EvalResult {\n\t\tconst lines: EvalLineResult[] = [];\n\t\tconst resultMap = new Map<number, Value[]>();\n\t\tconst tierCounts = { tier1: 0, tier2: 0, tier3: 0, skipped: 0 };\n\n\t\tconst docEnd = this.doc.lineCount;\n\t\tconst evalEnd = Math.min(endLine, docEnd);\n\n\t\tfor (let pos = startLine; pos <= evalEnd; pos++) {\n\t\t\tconst state = this.doc.getLineAt(pos);\n\t\t\tif (!state) continue;\n\n\t\t\t// All processed lines are in-viewport for setViewport, or conditionally\n\t\t\t// in-viewport for evaluate (handled by caller). We pass `true` here\n\t\t\t// because evaluateSingleLine's `inViewport` param controls Tier 1 vs\n\t\t\t// Tier 3 dispatch; callers must manage this distinction externally.\n\t\t\t//\n\t\t\t// evaluate() handles this by passing `inViewport` per-line; it loops\n\t\t\t// directly rather than using this helper for that reason.\n\t\t\tconst lineResult = this.evaluateSingleLine(state, pos, true);\n\t\t\tlines.push(lineResult);\n\n\t\t\tif (lineResult.tier === EvalTier.Tier1) tierCounts.tier1++;\n\t\t\telse if (lineResult.tier === EvalTier.Tier2) tierCounts.tier2++;\n\t\t\telse if (lineResult.tier === EvalTier.Tier3) tierCounts.tier3++;\n\t\t\telse tierCounts.skipped++;\n\n\t\t\tif (lineResult.results) {\n\t\t\t\tresultMap.set(pos, lineResult.results.flat());\n\t\t\t}\n\t\t}\n\n\t\treturn { lines, resultMap, tierCounts };\n\t}\n\n\t/**\n\t * Check whether any **variable-definition** line before `position`\n\t * (1-based, exclusive) is dirty.\n\t *\n\t * Used by `setViewport()` to decide whether to fall back to `evaluate()`:\n\t * if a variable-def before the viewport is dirty, the checkpoint state\n\t * `restoreTo()` would use may be stale and we need to reprocess from\n\t * line 1 to rebuild checkpoints correctly.\n\t *\n\t * Deliberately narrower than `DocumentModel.hasAnyDirtyLineBefore()`:\n\t * checkpoints only snapshot variable-def lines (see VMCheckpointer), so a\n\t * dirty plain-expression line before the viewport can't have invalidated\n\t * one, there's nothing checkpointed for it to invalidate. Using the\n\t * broader check here previously caused a real perf bug: `PageManager`'s\n\t * cold-page eviction marks evicted non-variable-def lines dirty, so\n\t * scrolling far into a large, variable-def-free document would trip this\n\t * guard, fall back to `evaluate()`, which recompiles those lines via\n\t * Tier 3 (never clearing their dirty flag by design), causing the very\n\t * next `maintainAfterEval()` to re-evict and re-dirty them, a\n\t * self-sustaining loop that pinned every subsequent `setViewport()` call\n\t * to the cost of a full re-evaluation instead of O(visible lines).\n\t *\n\t * Delegates to DocumentModel.hasAnyDirtyVariableDefLineBefore(), which\n\t * tracks dirty lineIds incrementally instead of scanning every line up to\n\t * `position` on every call. This used to be a real per-scroll cost\n\t * (benchmarked at ~10ms scrolled near the bottom of a 20k-line document)\n\t * since it fired on every viewport change, not just edits.\n\t */\n\tprivate hasDirtyLinesBefore(position: number): boolean {\n\t\treturn this.doc.hasAnyDirtyVariableDefLineBefore(position);\n\t}\n\n\t/**\n\t * Evaluate a single line using the appropriate tier.\n\t *\n\t * Tier assignment logic:\n\t * - Empty/markdown-only lines → skipped\n\t * - Dirty + in-viewport → Tier 1 (full pipeline)\n\t * - Dirty + not in viewport → Tier 3 (compile-only, execute variable defs)\n\t * - Clean + has bytecode + in viewport → Tier 2 (execute from cache)\n\t * - Clean + no bytecode → skipped (non-evaluable)\n\t */\n\tprivate evaluateSingleLine(\n\t\tstate: LineState,\n\t\tlineNumber: number,\n\t\tinViewport: boolean\n\t): EvalLineResult {\n\t\tconst baseResult: Omit<EvalLineResult, \"tier\" | \"result\" | \"error\"> = {\n\t\t\tlineId: state.lineId,\n\t\t\tlineNumber,\n\t\t};\n\n\t\t// Skip empty/markdown-only lines\n\t\tif (state.isEmpty || isEmptyLine(state.text)) {\n\t\t\tstate.isEmpty = true;\n\t\t\tthis.doc.markClean(state.lineId);\n\t\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t\t}\n\n\t\t// Extract all evaluable expressions (may be multiple inline solves)\n\t\tconst { expressions, inlineSolveCount } = this.extractExpressions(state);\n\t\tif (expressions.length === 0) {\n\t\t\tstate.isEmpty = true;\n\t\t\tthis.doc.markClean(state.lineId);\n\t\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t\t}\n\n\t\t// Determine the expression to evaluate (only needed for dirty lines)\n\t\tif (state.dirty) {\n\t\t\tif (inViewport) {\n\t\t\t\t// ── Tier 1: Visible + Dirty → Full Pipeline ──────────\n\t\t\t\treturn this.evaluateTier1(state, lineNumber, expressions, inlineSolveCount, baseResult);\n\t\t\t} else {\n\t\t\t\t// ── Tier 3: Invisible + Dirty → Compile-only ─────────\n\t\t\t\t// Skip recompilation if already compiled by a previous Tier 3 pass.\n\t\t\t\t// Non-variable-def lines keep dirty=true after Tier 3 (so they get\n\t\t\t\t// Tier 1 when scrolled into view), but recompiling identical text\n\t\t\t\t// produces the same bytecode and DAG entries. Text changes clear\n\t\t\t\t// bytecodes via DocumentModel.editLine(), so a length check is safe.\n\t\t\t\tif (state.bytecodes.length > 0 && state.bytecodes.length === expressions.length && !state.isVariableDef) {\n\t\t\t\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t\t\t\t}\n\t\t\t\treturn this.evaluateTier3(state, lineNumber, expressions, inlineSolveCount, baseResult);\n\t\t\t}\n\t\t}\n\n\t\t// Line is clean\n\t\tif (inViewport && state.bytecodes.length > 0) {\n\t\t\t// ── Tier 2: Visible + Cached → Execute from bytecode ────\n\t\t\treturn this.evaluateTier2(state, lineNumber, baseResult);\n\t\t}\n\n\t\t// Clean, not in viewport, or no bytecode → skip\n\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t}\n\n\t/**\n\t * Tier 1: Full pipeline, lex, parse, compile, execute.\n\t * Uses the engine's existing evaluateLine() which handles all pipeline\n\t * stages including DAG updates and LineCache population.\n\t *\n\t * Supports multiple expressions per line (inline solves). Evaluates each\n\t * expression left-to-right through the engine so variable definitions in\n\t * earlier solves update the VM state before later solves are evaluated.\n\t * Reads/writes are aggregated across all expressions for the DAG.\n\t */\n\tprivate evaluateTier1(\n\t\tstate: LineState,\n\t\tlineNumber: number,\n\t\texpressions: string[],\n\t\tinlineSolveCount: number,\n\t\tbaseResult: Omit<EvalLineResult, \"tier\" | \"result\" | \"error\">\n\t): EvalLineResult {\n\t\tconst allResults: Value[][] = [];\n\t\tconst allBytecodes: BytecodeProgram[] = [];\n\t\tconst allReads = new Set<string>();\n\t\tconst allWrites = new Set<string>();\n\t\tlet hasVariableDef = false;\n\t\tlet lastValue: Value | null = null;\n\t\tlet firstError: string | null = null;\n\t\tlet anyFailed = false;\n\t\t/** Set when any expression returned a value still waiting on a resolver. */\n\t\tlet anyPending = false;\n\n\t\t// Evaluate each expression independently, a failure in one expression\n\t\t// (e.g., parse error in s`bad syntax`) must not prevent other expressions\n\t\t// on the same line from being evaluated and having their results stored.\n\t\t// Without per-expression error handling, same-line cross-reference inline\n\t\t// solves (s`:a = 5` s`:b = a + 3` s`a + b`) would lose ALL results when\n\t\t// the third expression throws because 'b' references cross a VM state\n\t\t// boundary or the engine encounters a transient error.\n\t\tfor (const expression of expressions) {\n\t\t\tif (!expression.trim()) continue;\n\n\t\t\tlet value: Value[] | null = null;\n\t\t\tlet entry: { bytecode: BytecodeProgram; readVariables: string[]; writeVariable: string | null } | undefined;\n\n\t\t\ttry {\n\t\t\t\t// evaluateLine returns the single evaluated Value; this evaluator\n\t\t\t\t// keeps its results grouped as Value[] per expression (allResults\n\t\t\t\t// is Value[][]), so wrap the one value into its group here.\n\t\t\t\tconst evaluated = this.engine.evaluateLine(lineNumber, expression);\n\t\t\t\tvalue = [evaluated];\n\t\t\t\tlastValue = evaluated;\n\t\t\t\t// Sync the DocumentModel from the LineCache.\n\t\t\t\t// Use get(lineNumber, expression) instead of getEntryForLine(lineNumber)\n\t\t\t\t// because multiple expressions on the same line share the same lineNumber\n\t\t\t\t// and getEntryForLine always returns the FIRST entry (Map insertion order).\n\t\t\t\tentry = this.engine.getLineCache().get(lineNumber, expression) as typeof entry;\n\t\t\t} catch (e) {\n\t\t\t\tconst errorMessage = e instanceof Error ? e.message : String(e);\n\t\t\t\tif (!firstError) firstError = errorMessage;\n\t\t\t\tanyFailed = true;\n\t\t\t\tvalue = null;\n\t\t\t}\n\n\t\t\t// An unresolved async value does not throw, so `anyFailed` alone would\n\t\t\t// let this line be marked clean while its data has not arrived. Once\n\t\t\t// clean, nothing re-runs the resolver preflight and the value stays\n\t\t\t// pending for good. Treat it as not-yet-complete instead.\n\t\t\tif (value && value.some((v) => v.type === ValueType.Pending)) {\n\t\t\t\tanyPending = true;\n\t\t\t}\n\n\t\t\tif (value) {\n\t\t\t\tallResults.push(value);\n\t\t\t} else {\n\t\t\t\t// Expression failed, push an ErrorValue sentinel so results[] stays\n\t\t\t\t// aligned with expressions[] and bytecodes[] indices. Downstream code\n\t\t\t\t// checking result.type === Error will find it, vs a raw null that NPEs.\n\t\t\t\tallResults.push([errorValue(\"eval_failed\", firstError ?? \"unknown error\")]);\n\t\t\t}\n\n\t\t\tif (entry) {\n\t\t\t\tallBytecodes.push(entry.bytecode);\n\t\t\t\tfor (const r of entry.readVariables) allReads.add(r);\n\t\t\t\tif (entry.writeVariable) {\n\t\t\t\t\tallWrites.add(entry.writeVariable);\n\t\t\t\t\thasVariableDef = true;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Fallback: LineCache missed, compile expression ourselves\n\t\t\t\ttry {\n\t\t\t\t\tconst { program, reads, writes } = this.engine.compileExpression(expression);\n\t\t\t\t\tallBytecodes.push(program);\n\t\t\t\t\tfor (const r of reads) allReads.add(r);\n\t\t\t\t\tfor (const w of writes) allWrites.add(w);\n\t\t\t\t\tif (writes.length > 0) hasVariableDef = true;\n\t\t\t\t} catch (compileErr) {\n\t\t\t\t\t// Push empty bytecode, expression will recompile on next pass.\n\t\t\t\t\t// The expression still failed to compile, but reads/writes were\n\t\t\t\t\t// already extracted from its tokens before the parse attempt\n\t\t\t\t\t// compileExpression() surfaces them via the thrown error's\n\t\t\t\t\t// context. Register them anyway so the DAG knows this line\n\t\t\t\t\t// depends on those variables and re-evaluates it once they\n\t\t\t\t\t// become defined, instead of losing the dependency entirely.\n\t\t\t\t\tallBytecodes.push({ opcodes: new Uint8Array(0), numbers: new Float64Array(0), strings: [], hasAsync: false });\n\t\t\t\t\tif (compileErr instanceof EngineError && compileErr.context) {\n\t\t\t\t\t\tconst errReads = compileErr.context.reads;\n\t\t\t\t\t\tconst errWrites = compileErr.context.writes;\n\t\t\t\t\t\tif (Array.isArray(errReads)) for (const r of errReads) allReads.add(r);\n\t\t\t\t\t\tif (Array.isArray(errWrites)) for (const w of errWrites) allWrites.add(w);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst reads = [...allReads];\n\t\tconst writes = [...allWrites];\n\n\t\t// Always store results, even partial ones. If any expression failed\n\t\t// the line stays dirty so the failed expression(s) get retried on the\n\t\t// next evaluation pass. But successfully-evaluated expressions' results\n\t\t// are preserved so the DAG, UI decorations, and downstream consumers\n\t\t// can use them immediately.\n\t\tif (anyFailed || anyPending) {\n\t\t\t// Store partial results via updateLineCompiled (doesn't clear dirty).\n\t\t\t// The successful expressions' bytecodes are cached so Tier 2 works\n\t\t\t// for them on the next scroll pass.\n\t\t\tthis.doc.updateLineCompiled(\n\t\t\t\tstate.lineId,\n\t\t\t\texpressions,\n\t\t\t\tallBytecodes,\n\t\t\t\treads,\n\t\t\t\twrites,\n\t\t\t\thasVariableDef,\n\t\t\t\tinlineSolveCount,\n\t\t\t);\n\t\t\t// Also set results for the successful expressions\n\t\t\tstate.results = allResults;\n\t\t\tstate.result = allResults[0]?.[0] ?? null;\n\t\t\tstate.inlineSolveCount = inlineSolveCount;\n\t\t\tstate.expressions = expressions;\n\t\t} else {\n\t\t\t// All expressions succeeded, store full results and mark clean\n\t\t\tthis.doc.updateLineResult(\n\t\t\t\tstate.lineId,\n\t\t\t\tallResults,\n\t\t\t\tallBytecodes,\n\t\t\t\texpressions,\n\t\t\t\treads,\n\t\t\t\twrites,\n\t\t\t\thasVariableDef,\n\t\t\t\tinlineSolveCount,\n\t\t\t);\n\t\t}\n\n\t\t// Register reads/writes in DAG (aggregated across all expressions).\n\t\t// Always register, even lines with no reads/writes (pure expressions\n\t\t// like \"2+2\") need DAG entries so downstream queries for line presence work.\n\t\tthis.dag.registerLine(lineNumber, reads, writes);\n\n\t\t// ── Checkpoint after variable definition ──\n\t\t// A pending value is not a value worth checkpointing: restoring it would\n\t\t// reinstate the unresolved placeholder rather than the eventual result.\n\t\tif (this.checkpointer && writes.length > 0 && !anyFailed && !anyPending) {\n\t\t\tthis.checkpointer.snapshot(lineNumber, state.lineId, writes);\n\t\t}\n\n\t\treturn {\n\t\t\t...baseResult,\n\t\t\ttier: EvalTier.Tier1,\n\t\t\tresult: lastValue,\n\t\t\tresults: allResults,\n\t\t\terror: firstError,\n\t\t};\n\t}\n\n\t/**\n\t * Tier 2: Execute from cached bytecode only.\n\t * Skips lexing, parsing, and compiling, runs the pre-compiled bytecode\n\t * against the engine's shared VM. Supports multiple bytecodes per line\n\t * (inline solves), each is executed left-to-right so variable definitions\n\t * in earlier bytecodes update the VM before later ones run.\n\t * Assumes the VM already has correct variable state from preceding\n\t * Tier-1 evaluations.\n\t */\n\tprivate evaluateTier2(\n\t\tstate: LineState,\n\t\tlineNumber: number,\n\t\tbaseResult: Omit<EvalLineResult, \"tier\" | \"result\" | \"error\">\n\t): EvalLineResult {\n\t\tif (state.bytecodes.length === 0) {\n\t\t\treturn { ...baseResult, tier: EvalTier.Skipped, result: null, error: null };\n\t\t}\n\n\t\tconst results: Value[][] = [];\n\t\tlet lastValue: Value | null = null;\n\t\tlet firstError: string | null = null;\n\t\tlet anyFailed = false;\n\n\t\t// Execute each bytecode independently, a failure in one should not\n\t\t// prevent other bytecodes on the same line from executing. Same-line\n\t\t// inline solves with variable definitions (s`:a = 5` s`a + 3`) rely\n\t\t// on earlier bytecodes updating the VM before later ones execute.\n\t\tfor (const bytecode of state.bytecodes) {\n\t\t\tif (bytecode.opcodes.length === 0) continue;\n\t\t\ttry {\n\t\t\t\tconst value = this.engine.executeCached(bytecode, lineNumber);\n\t\t\t\tlastValue = value;\n\t\t\t\tresults.push([value]);\n\t\t\t} catch (e) {\n\t\t\t\tconst errorMessage = e instanceof Error ? e.message : String(e);\n\t\t\t\tif (!firstError) firstError = errorMessage;\n\t\t\t\tanyFailed = true;\n\t\t\t\t// Push error sentinel to maintain results[i] ↔ bytecodes[i] alignment\n\t\t\t\tresults.push([errorValue(\"exec_failed\", errorMessage)]);\n\t\t\t}\n\t\t}\n\n\t\t// Update DAG: re-register reads/writes from the cached metadata.\n\t\t// Always register, even empty reads/writes so DAG line-presence queries work.\n\t\tthis.dag.registerLine(lineNumber, state.reads, state.writes);\n\n\t\tstate.results = results;\n\t\tstate.result = results[0]?.[0] ?? null;\n\t\tif (anyFailed) {\n\t\t\t// Mark dirty so failed bytecodes are re-compiled (Tier 1) next pass\n\t\t\tthis.doc.markDirty(state.lineId);\n\t\t}\n\n\t\treturn { ...baseResult, tier: EvalTier.Tier2, result: lastValue, results, error: firstError };\n\t}\n\n\t/**\n\t * Tier 3: Compile-only for invisible lines.\n\t * Lex → Parse → Compile to discover reads/writes for the dependency graph.\n\t * Executes the bytecode ONLY if the line defines a variable (isVariableDef\n\t * or writes.length > 0), because variable assignments affect VM state\n\t * that other lines depend on. Pure expression lines are compiled but NOT\n\t * executed, saving CPU for large documents.\n\t *\n\t * Supports multiple expressions per line (inline solves). Each is compiled\n\t * separately; variable-def expressions are also executed.\n\t */\n\tprivate evaluateTier3(\n\t\tstate: LineState,\n\t\tlineNumber: number,\n\t\texpressions: string[],\n\t\tinlineSolveCount: number,\n\t\tbaseResult: Omit<EvalLineResult, \"tier\" | \"result\" | \"error\">\n\t): EvalLineResult {\n\t\tconst allBytecodes: BytecodeProgram[] = [];\n\t\tconst allReads = new Set<string>();\n\t\tconst allWrites = new Set<string>();\n\t\tlet hasVariableDef = false;\n\t\tlet lastResult: Value | null = null;\n\t\tlet firstError: string | null = null;\n\t\tlet anyFailed = false;\n\t\t/** Set when a result is still waiting on a resolver. */\n\t\tlet anyPending = false;\n\n\t\t// Compile each expression independently, a parse error in one\n\t\t// should not prevent other expressions from being compiled and\n\t\t// having their reads/writes registered in the DAG.\n\t\tfor (const expression of expressions) {\n\t\t\tif (!expression.trim()) continue;\n\n\t\t\ttry {\n\t\t\t\tconst { program, reads, writes } = this.engine.compileExpression(expression);\n\t\t\t\tallBytecodes.push(program);\n\t\t\t\tfor (const r of reads) allReads.add(r);\n\t\t\t\tfor (const w of writes) allWrites.add(w);\n\t\t\t\tif (writes.length > 0) hasVariableDef = true;\n\n\t\t\t\tif (writes.length > 0 && program.opcodes.length > 0) {\n\t\t\t\t\t// Variable definitions MUST execute to maintain VM state\n\t\t\t\t\tlastResult = this.engine.executeCached(program, lineNumber);\n\t\t\t\t\t// Same reasoning as Tier 1: a pending result does not throw,\n\t\t\t\t\t// and marking the line clean would strand it unresolved.\n\t\t\t\t\tif (lastResult && lastResult.type === ValueType.Pending) {\n\t\t\t\t\t\tanyPending = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tconst errorMessage = e instanceof Error ? e.message : String(e);\n\t\t\t\tif (!firstError) firstError = errorMessage;\n\t\t\t\tanyFailed = true;\n\t\t\t\t// Push empty bytecode placeholder for alignment\n\t\t\t\tallBytecodes.push({ opcodes: new Uint8Array(0), numbers: new Float64Array(0), strings: [], hasAsync: false });\n\t\t\t}\n\t\t}\n\n\t\tconst reads = [...allReads];\n\t\tconst writes = [...allWrites];\n\n\t\t// Store compile-only state in DocumentModel, even partial results\n\t\t// preserve successful expressions' bytecodes and DAG data.\n\t\tthis.doc.updateLineCompiled(\n\t\t\tstate.lineId,\n\t\t\texpressions,\n\t\t\tallBytecodes,\n\t\t\treads,\n\t\t\twrites,\n\t\t\thasVariableDef,\n\t\t\tinlineSolveCount,\n\t\t);\n\n\t\t// Register reads/writes in DAG regardless, partial data is valid.\n\t\t// Always register, even empty reads/writes for DAG line-presence queries.\n\t\tthis.dag.registerLine(lineNumber, reads, writes);\n\n\t\tif (hasVariableDef && lastResult && !anyFailed && !anyPending) {\n\t\t\tstate.results = [[lastResult]];\n\t\t\tstate.result = lastResult;\n\t\t\tthis.doc.markClean(state.lineId);\n\n\t\t\t// ── Checkpoint after variable definition ────────────\n\t\t\tif (this.checkpointer) {\n\t\t\t\tthis.checkpointer.snapshot(lineNumber, state.lineId, writes);\n\t\t\t}\n\t\t}\n\n\t\treturn { ...baseResult, tier: EvalTier.Tier3, result: lastResult, results: hasVariableDef && lastResult && !anyFailed && !anyPending ? [[lastResult]] : undefined, error: firstError };\n\t}\n\n\t// ── Public checkpoint API (used by Phase 5.2e setViewport) ──────\n\n\t/**\n\t * Restore the VM to the state at or just after the given line number.\n\t *\n\t * Finds the nearest checkpoint at or before `lineNumber` and replays\n\t * all variable definitions from the checkpoint chain into the VM.\n\t * After calling this, the VM is ready to evaluate lines starting at\n\t * `lineNumber + 1` without re-evaluating all preceding lines.\n\t *\n\t * **Usage:** Phase 5.2e's `setViewport()` calls `restoreTo(viewport.startLine - 1)`\n\t * before evaluating only the newly visible lines. This is the key to\n\t * O(visible lines) scrolling.\n\t *\n\t * @param lineNumber The line number to restore to. Variables defined\n\t * at lines ≤ this number will be available in the VM.\n\t */\n\trestoreTo(lineNumber: number): void {\n\t\tif (this.checkpointer) {\n\t\t\tthis.checkpointer.restoreTo(lineNumber);\n\t\t}\n\t}\n\n\t/**\n\t * Get the VM checkpointer, or null if checkpointing is disabled.\n\t */\n\tgetCheckpointer(): VMCheckpointer | null {\n\t\treturn this.checkpointer;\n\t}\n\n\t/**\n\t * Get the PageManager (Phase 5.2g).\n\t * Exposed for testing.\n\t */\n\tgetPageManager(): PageManager {\n\t\treturn this.pageManager;\n\t}\n\n\t// ── Phase 5.2g: Directional preloading ──────────────────────────\n\n\t/**\n\t * Preload the next 1–2 pages in the current scroll direction.\n\t *\n\t * Called during `setViewport()` (scroll-only path). Collects dirty\n\t * uncompiled lines in pages just beyond the viewport and dispatches\n\t * them to the background compilation worker so bytecode is ready\n\t * before the user scrolls those lines into view.\n\t */\n\tprivate preloadNextPages(viewport: ViewportRange): void {\n\t\tconst targets = this.pageManager.getPreloadTargets(viewport, this.doc);\n\t\tif (targets.length === 0) return;\n\n\t\t// Lazy-init worker if needed\n\t\tif (!this.compilationWorker) {\n\t\t\tthis.compilationWorker = new CompilationWorkerManager();\n\t\t}\n\n\t\t// Fire-and-forget: worker compiles, stores bytecode on response\n\t\tthis.compilationWorker.compileBatch(targets).then((results) => {\n\t\t\tthis.compilationWorker!.storeResults(results, this.doc);\n\t\t}).catch((_err) => {\n\t\t\t// Non-fatal, next evaluate() will compile synchronously\n\t\t});\n\t}\n\n\t/**\n\t * Collect invisible dirty lines that need background compilation.\n\t *\n\t * Iterates lines beyond `viewport.endLine`, filtering for:\n\t * - Dirty lines (need re-compilation)\n\t * - Non-empty, non-markdown lines\n\t * - No existing bytecode (skip already-compiled Tier 3 lines)\n\t *\n\t * Returns CompileRequestItem[] suitable for CompilationWorkerManager.\n\t */\n\tprivate collectInvisibleCompileTargets(viewport: ViewportRange): CompileRequestItem[] {\n\t\tconst items: CompileRequestItem[] = [];\n\t\tconst docEnd = this.doc.lineCount;\n\t\tconst startPos = viewport.endLine + 1;\n\n\t\tfor (let pos = startPos; pos <= docEnd; pos++) {\n\t\t\tconst state = this.doc.getLineAt(pos);\n\t\t\tif (!state) continue;\n\n\t\t\t// Skip clean lines\n\t\t\tif (!state.dirty) continue;\n\n\t\t\t// Skip already-compiled lines\n\t\t\tif (state.bytecodes.length > 0 && !state.isVariableDef) continue;\n\n\t\t\t// Skip empty/markdown-only lines\n\t\t\tif (state.isEmpty || isEmptyLine(state.text)) continue;\n\n\t\t\tconst { expressions } = this.extractExpressions(state);\n\t\t\tif (expressions.length === 0) continue;\n\n\t\t\t// Create one CompileRequestItem per expression (inline solves\n\t\t\t// on the same line share the same lineId + textHash). The worker\n\t\t\t// compiles each independently; storeResults batches by lineId.\n\t\t\tfor (const expression of expressions) {\n\t\t\t\tif (!expression.trim()) continue;\n\t\t\t\titems.push({\n\t\t\t\t\tlineId: state.lineId,\n\t\t\t\t\texpression,\n\t\t\t\t\ttextHash: state.textHash,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn items;\n\t}\n\n\t/**\n\t * Extract all evaluable expressions from a LineState.\n\t *\n\t * For full-line expressions: returns `{ expressions: [trimmedText], inlineSolveCount: 0 }`.\n\t * For inline solve lines: returns `{ expressions: [...allSolves], inlineSolveCount: N }`.\n\t * For pre-extracted (cached) expressions: returns the cached array.\n\t *\n\t * Inline solves are extracted left-to-right via the sharedLexer, so variable\n\t * definitions in earlier solves (e.g., `s\\`x = 5\\` more text s\\`x + 1\\``)\n\t * correctly update the VM state before later solves are evaluated.\n\t */\n\tprivate extractExpressions(state: LineState): { expressions: string[]; inlineSolveCount: number } {\n\t\t// Use pre-extracted expressions if available (from cache / previous evaluation)\n\t\tif (state.expressions.length > 0) {\n\t\t\treturn { expressions: state.expressions, inlineSolveCount: state.inlineSolveCount };\n\t\t}\n\n\t\tconst trimmed = state.text.trim();\n\t\tif (trimmed.length === 0) return { expressions: [], inlineSolveCount: 0 };\n\n\t\t// Check for inline solve syntax: s`expression`\n\t\tconst inlineSpans = sharedLexer.findInlineSolves(state.text);\n\t\tif (inlineSpans.length > 0) {\n\t\t\treturn {\n\t\t\t\texpressions: inlineSpans.map(s => s.expression),\n\t\t\t\tinlineSolveCount: inlineSpans.length,\n\t\t\t};\n\t\t}\n\n\t\t// Full-line expression\n\t\treturn { expressions: [trimmed], inlineSolveCount: 0 };\n\t}\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function o(i,t,r){return i.toLocaleString(t,{useGrouping:false,maximumFractionDigits:r,minimumFractionDigits:r})}function m(i,t=2,r=false,n="en-US"){return Number.isInteger(i)?r?i.toLocaleString(n,{minimumFractionDigits:0,maximumFractionDigits:0}):o(Math.trunc(i),n,0):r?i.toLocaleString(n,{maximumFractionDigits:t,minimumFractionDigits:t}):o(i,n,t)}export{m as a};//# sourceMappingURL=chunk-XEIDV5JP.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-XEIDV5JP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utilities/Number.ts"],"names":["removeThousandsSeparators","value","locale","decimalPlaces","autoFormatIntegerOrFloat","number","includeThousandSeparators","numberLocale"],"mappings":"AAoBA,SAASA,CAAAA,CACRC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACC,CACD,OAAOF,CAAAA,CAAM,cAAA,CAAeC,CAAAA,CAAQ,CACnC,WAAA,CAAa,KAAA,CACb,qBAAA,CAAuBC,EACvB,qBAAA,CAAuBA,CACxB,CAAC,CACF,CAcO,SAASC,CAAAA,CACfC,CAAAA,CACAF,EAAwB,CAAA,CACxBG,CAAAA,CAAqC,KAAA,CACrCC,CAAAA,CAAuB,OAAA,CACtB,CACD,OAAI,MAAA,CAAO,UAAUF,CAAM,CAAA,CACtBC,CAAAA,CAEID,CAAAA,CAAO,cAAA,CAAeE,CAAAA,CAAc,CAC1C,qBAAA,CAAuB,EACvB,qBAAA,CAAuB,CACxB,CAAC,CAAA,CAGKP,CAAAA,CAA0B,IAAA,CAAK,KAAA,CAAMK,CAAM,EAAGE,CAAAA,CAAc,CAAC,CAAA,CAIjED,CAAAA,CAEID,CAAAA,CAAO,cAAA,CAAeE,CAAAA,CAAc,CAC1C,sBAAuBJ,CAAAA,CACvB,qBAAA,CAAuBA,CACxB,CAAC,CAAA,CAKKH,CAAAA,CAA0BK,CAAAA,CAAQE,CAAAA,CAAcJ,CAAa,CACrE","file":"chunk-XEIDV5JP.js","sourcesContent":["/**\n * Render `value` in `locale` with `decimalPlaces` fractional digits and no\n * digit grouping, leaving the locale's own decimal separator alone.\n *\n * Asks `Intl` not to group in the first place rather than formatting with\n * grouping and then deleting a character afterwards. Deleting was wrong twice\n * over. It used `String.replace` with a string pattern, which removes one\n * occurrence, so \"1,234,567\" came back as \"1234,567\" and the surviving comma\n * read as a decimal point. And it chose the character to delete from a\n * two-case switch, \"de-DE\" or a comma for everything else, when a comma is the\n * DECIMAL separator in French, Spanish, Italian, Portuguese and every other\n * comma-decimal locale: deleting it turned 1.5 into \"150\", a hundred times the\n * number, while leaving French's actual group separator (a narrow no-break\n * space) in place. `numberResult.decimalSeparatorLocale` is an unvalidated\n * host string, so no locale can be assumed.\n *\n * An unusable locale tag still throws the `RangeError` `toLocaleString` has\n * always thrown for one, since swallowing it would hide the host's typo behind\n * silently different output.\n */\nfunction removeThousandsSeparators(\n\tvalue: number,\n\tlocale: string,\n\tdecimalPlaces: number\n) {\n\treturn value.toLocaleString(locale, {\n\t\tuseGrouping: false,\n\t\tmaximumFractionDigits: decimalPlaces,\n\t\tminimumFractionDigits: decimalPlaces,\n\t});\n}\n\n/**\n * Format `number` for display, branching on whether it's a whole number:\n * integers are always rendered with zero decimal places (never padded to\n * `decimalPlaces`), while non-integers are rendered with up to\n * `decimalPlaces` fractional digits. `includeThousandSeparators` controls\n * whether groups are separated (e.g. `\"1,234\"`) per `numberLocale`.\n *\n * @param number - The value to format.\n * @param decimalPlaces - Max fractional digits for non-integer values (default 2).\n * @param includeThousandSeparators - Whether to group digits (default false).\n * @param numberLocale - `Intl`/`toLocaleString` locale to format with (default \"en-US\").\n */\nexport function autoFormatIntegerOrFloat(\n\tnumber: number,\n\tdecimalPlaces: number = 2,\n\tincludeThousandSeparators: boolean = false,\n\tnumberLocale: string = \"en-US\"\n) {\n\tif (Number.isInteger(number)) {\n\t\tif (includeThousandSeparators) {\n\t\t\t// We can return the format early as we don't need to strip thousands\n\t\t\treturn number.toLocaleString(numberLocale, {\n\t\t\t\tminimumFractionDigits: 0,\n\t\t\t\tmaximumFractionDigits: 0,\n\t\t\t});\n\t\t}\n\n\t\treturn removeThousandsSeparators(Math.trunc(number), numberLocale, 0);\n\t}\n\n\t// Decimal\n\tif (includeThousandSeparators) {\n\t\t// We can return the format early as we don't need to strip thousands\n\t\treturn number.toLocaleString(numberLocale, {\n\t\t\tmaximumFractionDigits: decimalPlaces,\n\t\t\tminimumFractionDigits: decimalPlaces,\n\t\t});\n\t}\n\n\t// number.toFixed(decimalPlaces)\n\n\treturn removeThousandsSeparators(number, numberLocale, decimalPlaces);\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {c as c$2}from'./chunk-TWC7K3ZX.js';import {b,a as a$1,e,d}from'./chunk-YVKHEAFT.js';import {c,a}from'./chunk-IJMNVBIS.js';import {a as a$2}from'./chunk-62LMTO4F.js';import {c as c$1}from'./chunk-MPB7KUN5.js';var D=/^\d{1,3}(\.\d{3}){2,}$/,T=/^\d*\.\d*$/,n=class n{constructor(e,t=50,r="en",o){this.tokens=[];this.current=0;this.depth=0;this.currentExpression="";this.infixMinBindingPower=0;this.registry=e,this.maxDepth=t,this.localeCode=r,this.pluginFunctionIndex=o;}getLocaleCode(){return this.localeCode}setDiagnosticPipeline(e,t){this.diagnosticPipeline=e,this.currentExpression=t??"";}load(e,t){if(t===false){this.tokens=e,this.current=0,this.depth=0;return}let r=c(a.LPAREN),o=c(a.RPAREN),a$1=0;for(let l=0;l<e.length;l++)e[l].typeId===r?a$1++:e[l].typeId===o&&a$1--;this.tokens=a$1===0?e:this.balanceParens(e,a$1),this.current=0,this.depth=0;}balanceParens(e,t){let r=e.slice();if(t>0){let o=c(a.RPAREN);for(let a$1=0;a$1<t;a$1++){let l=e[e.length-1];r.push({type:a.RPAREN,typeId:o,value:")",text:")",offset:l?l.offset+l.text.length:0,lineBreaks:0,line:l?l.line:1,col:l?l.col+l.text.length:1});}}else if(t<0){let o=c(a.LPAREN);for(let a$1=0;a$1<-t;a$1++)r.unshift({type:a.LPAREN,typeId:o,value:"(",text:"(",offset:0,lineBreaks:0,line:1,col:1});}return r}parseExpression(e=0,t){if(t&&(this.builder=t),this.depth++,this.depth>this.maxDepth)throw this.depth--,c$1.parsing("NESTING_DEPTH_EXCEEDED",`Parse nesting depth ${this.depth} exceeds maximum of ${this.maxDepth}`,{maxDepth:this.maxDepth,currentDepth:this.depth});let r=this.consume();if(!r)throw this.depth--,c$1.parsing("UNEXPECTED_END","Unexpected end of expression");this.parsePrefix(r);let o=this.tokens,a=o.length,l=n.BP_TABLE,p=this.registry,d=this.builder,f=this.current;for(;f<a;){let u=o[f];if(!u)break;let c=l[u.typeId];if(c>0){if(c<=e)break;if(this.diagnosticPipeline){let m=p.getInfix(u.typeId);m&&this.fireParseletMatched(m,u,false,c);}this.current=++f;let I=u.typeId;if(I===n.PERCENT_ID)d.emitOpcode(10),d.emitNumber(100),d.emitOpcode(23),d.emitOpcode(74);else if(!(I===n.CARET_ID&&this.tryEmitMatrixCaretOp(d))){let m=I===n.CARET_ID?c-1:c+1;this.parseExpression(m,d),d.emitOpcode(n.INFIX_OPCODE[I]);}}else {let I=p.getInfix(u.typeId);if(!I||I.bindingPower<=e)break;this.current=++f,this.diagnosticPipeline&&this.fireParseletMatched(I,u,false,I.bindingPower),this.infixMinBindingPower=e,I.parse(this,r,u,d);}f=this.current;}this.current=f,this.depth--;}parsePrefix(e$1){let t=this.builder,r=e$1.typeId;if(this.diagnosticPipeline){let a=this.registry.getPrefix(r);a&&this.fireParseletMatched(a,e$1,true);}switch(r){case n.NUMBER_ID:{let a,l=null,p=e$1.value;if(p.startsWith("0x")||p.startsWith("0X")){if(a=parseInt(p,16),Number.isNaN(a))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid hex literal: "${p}"`,{raw:p})}else if(p.startsWith("0b")||p.startsWith("0B")){if(a=parseInt(p.slice(2),2),Number.isNaN(a))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid binary literal: "${p}"`,{raw:p})}else if(p.startsWith("0o")||p.startsWith("0O")){if(a=parseInt(p.slice(2),8),Number.isNaN(a))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid octal literal: "${p}"`,{raw:p})}else if(D.test(p))a=parseFloat(p.split(".").join(""));else {let d=a$2(this.localeCode),f=d.display.decimalSeparator,u=d.display.thousandsSeparator,c=p;u&&(c=c.split(u).join("")),f&&f!=="."&&(c=c.replace(f,".")),a=parseFloat(c),T.test(c)&&(l=c);}if(l!==null){t.emitOpcode(16),t.emitString(l);return}t.emitOpcode(10),t.emitNumber(a);return}case n.BIGINT_ID:{t.emitOpcode(11),t.emitString(e(e$1.value,this.localeCode));return}case n.STRING_ID:{t.emitOpcode(13),t.emitString(e$1.value);return}case n.IDENT_ID:{if(this.peek()?.typeId===n.LPAREN_ID){this.parseUserFunctionDefOrCall(e$1,t);return}t.emitOpcode(60),t.emitString(e$1.value);return}case n.LPAREN_ID:{this.parseExpression(0,t);let a$1=1;for(;this.match(a.COMMA);)this.parseExpression(0,t),a$1++;this.consume(a.RPAREN),a$1>1&&(t.emitOpcode(152),t.emitIndex(1),t.emitIndex(a$1));return}case n.MINUS_ID:{this.parseExpression(a$1.Prefix,t),t.emitOpcode(26);return}case n.PLUS_ID:{this.parseExpression(a$1.Prefix,t),t.emitOpcode(27);return}case n.KEYWORD_ID:}let o=this.registry.getPrefix(r);if(!o)throw c$1.parsing("NO_PREFIX_PARSELET",`No prefix parselet found for token: ${e$1.type} ("${e$1.value}")`,{tokenType:e$1.type,tokenValue:e$1.value});o.parse(this,e$1,t);}tryEmitMatrixCaretOp(e){for(let t of n.CARET_SUFFIX_RULES)if(t.matches(this))return t.emit(this,e),true;return false}findMatchingRParen(e){let t=0;for(let r=e;r<this.tokens.length;r++){let o=this.tokens[r];if(o.typeId===n.LPAREN_ID)t++;else if(o.typeId===n.RPAREN_ID&&(t--,t===0))return r}return null}parseUserFunctionDefOrCall(e,t){let r=this.findMatchingRParen(this.current);if(r===null){t.emitOpcode(60),t.emitString(e.value);return}this.tokens[r+1]?.type===a.EQUALS?this.parseUserFunctionDefinition(e,t):this.parseUserFunctionCall(e,t);}consumeParamName(){let e=this.peek();if(e?.type===a.IDENT||e?.type===a.UNIT)return this.consume(),e.value;throw c$1.parsing("USER_FUNCTION_INVALID_PARAM_NAME",`Expected a parameter name but got "${e?.type??"end of input"}"${e?` ("${e.value}")`:""}`,{actualType:e?.type})}parseUserFunctionDefinition(e,t){this.consume(a.LPAREN);let r=[];if(this.peek()?.type!==a.RPAREN)for(r.push(this.consumeParamName());this.match(a.COMMA);)r.push(this.consumeParamName());if(this.consume(a.RPAREN),this.consume(a.EQUALS),r.length===0)throw c$1.parsing("USER_FUNCTION_NO_PARAMS",`"${e.value}()" has no parameters -- user-defined functions need at least one (a zero-argument definition is indistinguishable from a plain function CALL with no args, which this grammar doesn't otherwise support)`,{name:e.value});let o=new d(this.pluginFunctionIndex);this.parseExpression(a$1.Lowest,o),this.setBuilder(t);let a$2=o.build();if(a$2.hasAsync)throw c$1.parsing("FUNCTION_BODY_MUST_BE_SYNCHRONOUS",`"${e.value}(...)"'s body calls an async operation (weather, stocks, currency, ...) \u2014 user-defined function bodies must be synchronous`,{name:e.value});let l=t.emitUserFunctionBody(e.value,r,a$2);t.emitOpcode(150),t.emitIndex(l),t.emitOpcode(13),t.emitString(`${e.value}(${r.join(", ")}) defined`);}parseUserFunctionCall(e,t){this.consume(a.LPAREN);let r=0;if(this.peek()?.type!==a.RPAREN)for(this.parseExpression(a$1.Lowest,t),r++;this.match(a.COMMA);)this.parseExpression(a$1.Lowest,t),r++;this.consume(a.RPAREN),t.emitOpcode(151),t.emitString(e.value),t.emitByte(r);}consume(e){let t=this.tokens[this.current];if(!t)throw c$1.parsing("UNEXPECTED_END_OF_INPUT","Unexpected end of input");if(e!==void 0){let r=c(e);if(t.typeId!==r)throw c$1.parsing("UNEXPECTED_TOKEN_TYPE",`Expected token type "${e}" but got "${t.type}" ("${t.value}")`,{expectedType:e,actualType:t.type,actualValue:t.value})}return this.current++,t}match(e){let t=this.peek();return t&&t.typeId===c(e)?(this.advance(),true):false}peek(){return this.tokens[this.current]}peekAt(e){return this.tokens[this.current+e]}previous(){return this.current>0?this.tokens[this.current-1]:void 0}advance(){this.current++;}setBuilder(e){this.builder=e;}fireParseletMatched(e,t,r,o){let a=this.diagnosticPipeline,l={type:c$2.ParseletMatched,elapsedNs:0,expression:this.currentExpression,tokenType:t.type,tokenValue:t.value,parseletCategory:e.category,parseletType:e.constructor?.name??"unknown",isPrefix:r,bindingPower:o,tokenOffset:t.offset||0};a.fireParseletMatched(l);}};n.BP_TABLE=b(),n.NUMBER_ID=c(a.NUMBER),n.BIGINT_ID=c(a.BIGINT),n.STRING_ID=c(a.STRING),n.IDENT_ID=c(a.IDENT),n.LPAREN_ID=c(a.LPAREN),n.RPAREN_ID=c(a.RPAREN),n.MINUS_ID=c(a.MINUS),n.PLUS_ID=c(a.PLUS),n.KEYWORD_ID=c(a.KEYWORD),n.STAR_ID=c(a.STAR),n.SLASH_ID=c(a.SLASH),n.MOD_ID=c(a.MOD),n.CARET_ID=c(a.CARET),n.LSHIFT_ID=c(a.LSHIFT),n.RSHIFT_ID=c(a.RSHIFT),n.URSHIFT_ID=c(a.URSHIFT),n.BIT_AND_ID=c(a.BIT_AND),n.BIT_OR_ID=c(a.BIT_OR),n.BIT_XOR_ID=c(a.BIT_XOR),n.PERCENT_ID=c(a.PERCENT),n.OF_ID=c(a.OF),n.INFIX_OPCODE={[c(a.PLUS)]:20,[c(a.MINUS)]:21,[c(a.STAR)]:22,[c(a.SLASH)]:23,[c(a.MOD)]:24,[c(a.CARET)]:25,[c(a.LSHIFT)]:30,[c(a.RSHIFT)]:31,[c(a.URSHIFT)]:32,[c(a.BIT_AND)]:33,[c(a.BIT_OR)]:34,[c(a.BIT_XOR)]:35,[c(a.OF)]:22},n.CARET_SUFFIX_RULES=[{name:"transpose (^T)",matches:e=>{let t=e.peek();return t?.type===a.IDENT&&t.value==="T"},emit:(e,t)=>{e.advance(),t.emitOpcode(51),t.emitIndex(63),t.emitIndex(1);}},{name:"inverse (^-1)",matches:e=>{if(e.peek()?.typeId!==n.MINUS_ID)return false;let r=e.peekAt(1);return r?.type===a.NUMBER&&r.value==="1"},emit:(e,t)=>{e.advance(),e.advance(),t.emitOpcode(51),t.emitIndex(65),t.emitIndex(1);}}];var v=n;var y=class{constructor(){this.prefixParselets=new Map;this.infixParselets=new Map;this.prefixById=new Map;this.infixById=new Map;}registerPrefix(e,t){let r=this.prefixParselets.get(e);r&&r!==t&&console.warn(`[ParseletRegistry] Prefix parselet for token "${e}" is already registered (category: "${r.category??"unknown"}"). Overwriting with a new parselet (category: "${t.category??"unknown"}") \u2014 the previous parselet is now unreachable. Two packages may be claiming the same token type.`),this.prefixParselets.set(e,t),this.prefixById.set(c(e),t);}registerInfix(e,t){let r=this.infixParselets.get(e);r&&r!==t&&console.warn(`[ParseletRegistry] Infix parselet for token "${e}" is already registered (category: "${r.category??"unknown"}"). Overwriting with a new parselet (category: "${t.category??"unknown"}") \u2014 the previous parselet is now unreachable. Two packages may be claiming the same token type.`),this.infixParselets.set(e,t),this.infixById.set(c(e),t);}getAllPrefix(){let e=[];for(let[t,r]of this.prefixParselets)e.push({tokenType:t,bindingPower:r.bindingPower??a$1.Prefix,category:r.category});return e}getAllInfix(){let e=[];for(let[t,r]of this.infixParselets){let o=r.bindingPower??0;e.push({tokenType:t,leftBindingPower:o,rightBindingPower:o+1,category:r.category});}return e}get prefixCount(){return this.prefixParselets.size}get infixCount(){return this.infixParselets.size}getPrefix(e){return typeof e=="number"?this.prefixById.get(e):this.prefixParselets.get(e)}getInfix(e){return typeof e=="number"?this.infixById.get(e):this.infixParselets.get(e)}hasPrefix(e){return this.prefixParselets.has(e)}hasInfix(e){return this.infixParselets.has(e)}clear(){this.prefixParselets.clear(),this.infixParselets.clear(),this.prefixById.clear(),this.infixById.clear();}},H=new y;export{v as a,y as b,H as c};//# sourceMappingURL=chunk-XNIWQHXY.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-XNIWQHXY.js.map
|