solve-engine 1.0.2 → 1.1.1
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/dist/{BytecodeBuilder-B0xskcv5.d.cts → BytecodeBuilder-Bp9xeTmX.d.cts} +4 -0
- package/dist/{BytecodeBuilder-B0xskcv5.d.ts → BytecodeBuilder-Bp9xeTmX.d.ts} +4 -0
- package/dist/{Configuration-B-G5gTRn.d.cts → Configuration-C9W8tJv_.d.cts} +53 -1
- package/dist/{Configuration-B-G5gTRn.d.ts → Configuration-C9W8tJv_.d.ts} +53 -1
- package/dist/{EngineError-LU7W7AgI.d.cts → EngineError-B61GS1jp.d.cts} +14 -0
- package/dist/{EngineError-LU7W7AgI.d.ts → EngineError-B61GS1jp.d.ts} +14 -0
- package/dist/FormattingSettings-CJHyxcYu.d.cts +27 -0
- package/dist/FormattingSettings-CJHyxcYu.d.ts +27 -0
- package/dist/{Lexer-DpjdaQ98.d.cts → Lexer-BOs7euZe.d.cts} +28 -1
- package/dist/{Lexer-CNmWxabg.d.ts → Lexer-CSI_lwbW.d.ts} +28 -1
- package/dist/PackageCompatibility-B-7rK1TD.d.cts +76 -0
- package/dist/PackageCompatibility-Dh59eF-X.d.ts +76 -0
- package/dist/{PackageRegistry-zuzqt51V.d.cts → PackageRegistry-BHWJP83F.d.cts} +449 -11
- package/dist/{PackageRegistry-ClIFXxAe.d.ts → PackageRegistry-_8rDlvxI.d.ts} +449 -11
- package/dist/{Parselet-BaySkMV3.d.ts → Parselet-BBT8riYh.d.ts} +12 -3
- package/dist/{Parselet-DuI1Pjiq.d.cts → Parselet-BHcgK9S7.d.cts} +12 -3
- package/dist/{ScopeManager-B6GzdhVG.d.cts → ScopeManager-8vf02dwj.d.cts} +56 -5
- package/dist/{ScopeManager-udv4Twwq.d.ts → ScopeManager-CxA24W5n.d.ts} +56 -5
- package/dist/{Token-BzG5G4ja.d.cts → Token-B1hdkedD.d.cts} +9 -0
- package/dist/{Token-BzG5G4ja.d.ts → Token-B1hdkedD.d.ts} +9 -0
- package/dist/{TokenNormalizer-t_GotBxr.d.ts → TokenNormalizer-C6VzZgHa.d.ts} +1 -1
- package/dist/{TokenNormalizer-DGVa24Q-.d.cts → TokenNormalizer-DRc1Js1V.d.cts} +1 -1
- package/dist/{VMCheckpoints-DwLjivM7.d.cts → VMCheckpoints-ELYqITdF.d.cts} +3 -3
- package/dist/{VMCheckpoints-BiaIlOOY.d.ts → VMCheckpoints-MK--EBH2.d.ts} +3 -3
- package/dist/{Value-CXJqDH9J.d.cts → Value-BUi1RA3S.d.cts} +124 -5
- package/dist/{Value-CXJqDH9J.d.ts → Value-BUi1RA3S.d.ts} +124 -5
- package/dist/WorkerError-_-RkoQ5P.d.ts +75 -0
- package/dist/WorkerError-gzmaopj2.d.cts +75 -0
- package/dist/{chunk-GQCOSXMG.js → chunk-267JPOTF.js} +43 -5
- package/dist/chunk-267JPOTF.js.map +1 -0
- package/dist/{chunk-JMXUNXQS.cjs → chunk-2TZKENDH.cjs} +51 -8
- package/dist/chunk-2TZKENDH.cjs.map +1 -0
- package/dist/chunk-3OWCDIPN.js +215 -0
- package/dist/chunk-3OWCDIPN.js.map +1 -0
- package/dist/{chunk-VB37OC6I.js → chunk-4D6NIHE2.js} +40 -3
- package/dist/chunk-4D6NIHE2.js.map +1 -0
- package/dist/{chunk-YXCTLWOH.js → chunk-4HQKTMWG.js} +1530 -57
- package/dist/chunk-4HQKTMWG.js.map +1 -0
- package/dist/{chunk-TY3TLZAW.cjs → chunk-536WPM2V.cjs} +18 -2
- package/dist/chunk-536WPM2V.cjs.map +1 -0
- package/dist/chunk-5HRB36DK.js +405 -0
- package/dist/chunk-5HRB36DK.js.map +1 -0
- package/dist/chunk-5ON7PUAZ.js +12 -0
- package/dist/chunk-5ON7PUAZ.js.map +1 -0
- package/dist/{chunk-KV7UW6T6.js → chunk-7KYSUDQO.js} +12 -5
- package/dist/chunk-7KYSUDQO.js.map +1 -0
- package/dist/{chunk-6WFMPTGB.cjs → chunk-7ZX6B7SY.cjs} +774 -528
- package/dist/chunk-7ZX6B7SY.cjs.map +1 -0
- package/dist/chunk-ALYRJ72W.cjs +434 -0
- package/dist/chunk-ALYRJ72W.cjs.map +1 -0
- package/dist/{chunk-5KMIY374.cjs → chunk-B4HBEFTB.cjs} +17 -2
- package/dist/chunk-B4HBEFTB.cjs.map +1 -0
- package/dist/chunk-B7NLZMQ3.cjs +74 -0
- package/dist/chunk-B7NLZMQ3.cjs.map +1 -0
- package/dist/{chunk-UQ3UIZJC.js → chunk-BLI4NIQY.js} +6 -2
- package/dist/chunk-BLI4NIQY.js.map +1 -0
- package/dist/{chunk-IP7ASJEW.js → chunk-BYJBUL7U.js} +5 -5
- package/dist/{chunk-IP7ASJEW.js.map → chunk-BYJBUL7U.js.map} +1 -1
- package/dist/{chunk-G535KJEG.js → chunk-CCBZZQAE.js} +2 -2
- package/dist/{chunk-G535KJEG.js.map → chunk-CCBZZQAE.js.map} +1 -1
- package/dist/chunk-CKQMXMHR.cjs +219 -0
- package/dist/chunk-CKQMXMHR.cjs.map +1 -0
- package/dist/{chunk-T556MJDZ.cjs → chunk-CUR2WLI4.cjs} +11 -11
- package/dist/{chunk-T556MJDZ.cjs.map → chunk-CUR2WLI4.cjs.map} +1 -1
- package/dist/{chunk-AA3KTWTX.js → chunk-DLEBSLF4.js} +4 -4
- package/dist/{chunk-AA3KTWTX.js.map → chunk-DLEBSLF4.js.map} +1 -1
- package/dist/{chunk-524F3ATQ.cjs → chunk-E23GZEWL.cjs} +15 -9
- package/dist/chunk-E23GZEWL.cjs.map +1 -0
- package/dist/{chunk-PFUESQTW.cjs → chunk-EJ3ILXX6.cjs} +48 -2
- package/dist/chunk-EJ3ILXX6.cjs.map +1 -0
- package/dist/{chunk-526PMQOA.js → chunk-ENKKJYD3.js} +10 -4
- package/dist/chunk-ENKKJYD3.js.map +1 -0
- package/dist/{chunk-5X2PTP6F.cjs → chunk-ENRIK36Q.cjs} +2 -12
- package/dist/chunk-ENRIK36Q.cjs.map +1 -0
- package/dist/{chunk-3D7V24DG.js → chunk-ERCOHGXD.js} +17 -2
- package/dist/chunk-ERCOHGXD.js.map +1 -0
- package/dist/{chunk-IF532O7C.js → chunk-FD5ZZHEU.js} +3 -12
- package/dist/chunk-FD5ZZHEU.js.map +1 -0
- package/dist/{chunk-7FSDNNNC.js → chunk-GLA4JXBO.js} +11 -5
- package/dist/chunk-GLA4JXBO.js.map +1 -0
- package/dist/{chunk-UM6BVY2S.cjs → chunk-HIQ5HSZL.cjs} +175 -43
- package/dist/chunk-HIQ5HSZL.cjs.map +1 -0
- package/dist/{chunk-HVQFNJKE.cjs → chunk-HVRVSI2Z.cjs} +104 -86
- package/dist/chunk-HVRVSI2Z.cjs.map +1 -0
- package/dist/{chunk-3LAEG75D.js → chunk-I4GAWIPW.js} +24 -6
- package/dist/chunk-I4GAWIPW.js.map +1 -0
- package/dist/{chunk-PA4VC73I.cjs → chunk-J45BCEZ4.cjs} +33 -27
- package/dist/chunk-J45BCEZ4.cjs.map +1 -0
- package/dist/{chunk-FQGX2PA2.js → chunk-JG6ZJ2WU.js} +128 -4
- package/dist/chunk-JG6ZJ2WU.js.map +1 -0
- package/dist/chunk-L2TE7PMO.cjs +14 -0
- package/dist/chunk-L2TE7PMO.cjs.map +1 -0
- package/dist/chunk-LHZ6VOA7.js +1764 -0
- package/dist/chunk-LHZ6VOA7.js.map +1 -0
- package/dist/{chunk-SESSWASV.cjs → chunk-MN3LHRGV.cjs} +1868 -393
- package/dist/chunk-MN3LHRGV.cjs.map +1 -0
- package/dist/{chunk-R3PY4G7J.js → chunk-MVTOCRV2.js} +48 -3
- package/dist/chunk-MVTOCRV2.js.map +1 -0
- package/dist/{chunk-FE23VSSA.cjs → chunk-N5NNW4VG.cjs} +6 -6
- package/dist/{chunk-FE23VSSA.cjs.map → chunk-N5NNW4VG.cjs.map} +1 -1
- package/dist/{chunk-Y7FT4IQT.js → chunk-NKW7LKYU.js} +266 -28
- package/dist/chunk-NKW7LKYU.js.map +1 -0
- package/dist/{chunk-O3ANBHSA.js → chunk-NNQ2TYDF.js} +123 -5
- package/dist/chunk-NNQ2TYDF.js.map +1 -0
- package/dist/{chunk-NG2JHZHE.js → chunk-NNZAEUDW.js} +1853 -2640
- package/dist/chunk-NNZAEUDW.js.map +1 -0
- package/dist/{chunk-5LI5EPGJ.cjs → chunk-QFTDTX6K.cjs} +40 -3
- package/dist/chunk-QFTDTX6K.cjs.map +1 -0
- package/dist/{chunk-HDP7VK3C.cjs → chunk-SRGQ72IR.cjs} +649 -349
- package/dist/chunk-SRGQ72IR.cjs.map +1 -0
- package/dist/{chunk-4B2CNWQU.cjs → chunk-SSV46KFA.cjs} +14 -7
- package/dist/chunk-SSV46KFA.cjs.map +1 -0
- package/dist/{chunk-HBVFFBRR.cjs → chunk-T6ZYQJ63.cjs} +1962 -2748
- package/dist/chunk-T6ZYQJ63.cjs.map +1 -0
- package/dist/{chunk-AJA6LUI7.js → chunk-UO6BUV6K.js} +18 -2
- package/dist/chunk-UO6BUV6K.js.map +1 -0
- package/dist/chunk-WWQEY7BV.js +67 -0
- package/dist/chunk-WWQEY7BV.js.map +1 -0
- package/dist/{chunk-5WVP4YHP.js → chunk-WXEHD6TT.js} +333 -33
- package/dist/chunk-WXEHD6TT.js.map +1 -0
- package/dist/{chunk-47LRVGOT.cjs → chunk-XA4CKRML.cjs} +2 -2
- package/dist/{chunk-47LRVGOT.cjs.map → chunk-XA4CKRML.cjs.map} +1 -1
- package/dist/{chunk-6KFYJ6TD.cjs → chunk-XIYYHA65.cjs} +6 -2
- package/dist/chunk-XIYYHA65.cjs.map +1 -0
- package/dist/chunk-YRIKITGF.cjs +1768 -0
- package/dist/chunk-YRIKITGF.cjs.map +1 -0
- package/dist/{chunk-TMA4RCEN.js → chunk-Z7XGGLI2.js} +3 -3
- package/dist/{chunk-TMA4RCEN.js.map → chunk-Z7XGGLI2.js.map} +1 -1
- package/dist/{chunk-R7YVBHCV.cjs → chunk-ZMW6NU2K.cjs} +197 -73
- package/dist/chunk-ZMW6NU2K.cjs.map +1 -0
- package/dist/{chunk-A2N2GFCG.cjs → chunk-ZVTWQLK4.cjs} +10 -10
- package/dist/{chunk-A2N2GFCG.cjs.map → chunk-ZVTWQLK4.cjs.map} +1 -1
- package/dist/constants.cjs +5 -5
- package/dist/constants.d.cts +1 -1
- package/dist/constants.d.ts +1 -1
- package/dist/constants.js +2 -2
- package/dist/engine.cjs +52 -35
- package/dist/engine.d.cts +13 -13
- package/dist/engine.d.ts +13 -13
- package/dist/engine.js +26 -21
- package/dist/errors.cjs +44 -19
- package/dist/errors.d.cts +3 -2
- package/dist/errors.d.ts +3 -2
- package/dist/errors.js +2 -1
- package/dist/format.cjs +19 -169
- package/dist/format.cjs.map +1 -1
- package/dist/format.d.cts +18 -26
- package/dist/format.d.ts +18 -26
- package/dist/format.js +7 -171
- package/dist/format.js.map +1 -1
- package/dist/index.cjs +250 -31
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +110 -74
- package/dist/index.d.ts +110 -74
- package/dist/index.js +228 -23
- package/dist/index.js.map +1 -1
- package/dist/language.cjs +9 -9
- package/dist/language.d.cts +12 -12
- package/dist/language.d.ts +12 -12
- package/dist/language.js +3 -3
- package/dist/lexer.cjs +16 -16
- package/dist/lexer.d.cts +3 -3
- package/dist/lexer.d.ts +3 -3
- package/dist/lexer.js +5 -5
- package/dist/normalizer.cjs +10 -10
- package/dist/normalizer.d.cts +3 -3
- package/dist/normalizer.d.ts +3 -3
- package/dist/normalizer.js +4 -4
- package/dist/packages.cjs +45 -36
- package/dist/packages.d.cts +135 -31
- package/dist/packages.d.ts +135 -31
- package/dist/packages.js +14 -13
- package/dist/parser.cjs +16 -16
- package/dist/parser.d.cts +6 -5
- package/dist/parser.d.ts +6 -5
- package/dist/parser.js +6 -6
- package/dist/{pipeline-BEb3hujr.d.cts → pipeline-CtfJtPQc.d.cts} +3 -3
- package/dist/{pipeline-B6k5lCB7.d.ts → pipeline-DCd5M6Gk.d.ts} +3 -3
- package/dist/resolvers.d.cts +3 -3
- package/dist/resolvers.d.ts +3 -3
- package/dist/testing.cjs +478 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +271 -0
- package/dist/testing.d.ts +271 -0
- package/dist/testing.js +470 -0
- package/dist/testing.js.map +1 -0
- package/dist/uom.cjs +16 -16
- package/dist/uom.d.cts +3 -3
- package/dist/uom.d.ts +3 -3
- package/dist/uom.js +6 -6
- package/dist/utilities.cjs +6 -5
- package/dist/utilities.js +2 -1
- package/dist/vm.cjs +34 -34
- package/dist/vm.d.cts +8 -8
- package/dist/vm.d.ts +8 -8
- package/dist/vm.js +9 -9
- package/dist/worker.cjs +493 -0
- package/dist/worker.cjs.map +1 -0
- package/dist/worker.d.cts +509 -0
- package/dist/worker.d.ts +509 -0
- package/dist/worker.js +484 -0
- package/dist/worker.js.map +1 -0
- package/package.json +21 -1
- package/dist/chunk-3D7V24DG.js.map +0 -1
- package/dist/chunk-3LAEG75D.js.map +0 -1
- package/dist/chunk-4B2CNWQU.cjs.map +0 -1
- package/dist/chunk-524F3ATQ.cjs.map +0 -1
- package/dist/chunk-526PMQOA.js.map +0 -1
- package/dist/chunk-5KMIY374.cjs.map +0 -1
- package/dist/chunk-5LI5EPGJ.cjs.map +0 -1
- package/dist/chunk-5WVP4YHP.js.map +0 -1
- package/dist/chunk-5X2PTP6F.cjs.map +0 -1
- package/dist/chunk-6KFYJ6TD.cjs.map +0 -1
- package/dist/chunk-6WFMPTGB.cjs.map +0 -1
- package/dist/chunk-7FSDNNNC.js.map +0 -1
- package/dist/chunk-AJA6LUI7.js.map +0 -1
- package/dist/chunk-FQGX2PA2.js.map +0 -1
- package/dist/chunk-GQCOSXMG.js.map +0 -1
- package/dist/chunk-HBVFFBRR.cjs.map +0 -1
- package/dist/chunk-HDP7VK3C.cjs.map +0 -1
- package/dist/chunk-HVQFNJKE.cjs.map +0 -1
- package/dist/chunk-IF532O7C.js.map +0 -1
- package/dist/chunk-JMXUNXQS.cjs.map +0 -1
- package/dist/chunk-KV7UW6T6.js.map +0 -1
- package/dist/chunk-NG2JHZHE.js.map +0 -1
- package/dist/chunk-O3ANBHSA.js.map +0 -1
- package/dist/chunk-PA4VC73I.cjs.map +0 -1
- package/dist/chunk-PFUESQTW.cjs.map +0 -1
- package/dist/chunk-R3PY4G7J.js.map +0 -1
- package/dist/chunk-R7YVBHCV.cjs.map +0 -1
- package/dist/chunk-SESSWASV.cjs.map +0 -1
- package/dist/chunk-TY3TLZAW.cjs.map +0 -1
- package/dist/chunk-UM6BVY2S.cjs.map +0 -1
- package/dist/chunk-UQ3UIZJC.js.map +0 -1
- package/dist/chunk-VB37OC6I.js.map +0 -1
- package/dist/chunk-Y7FT4IQT.js.map +0 -1
- package/dist/chunk-YXCTLWOH.js.map +0 -1
|
@@ -164,8 +164,54 @@ function getBestUnit(value, unit) {
|
|
|
164
164
|
return { value, unit: u };
|
|
165
165
|
}
|
|
166
166
|
}
|
|
167
|
+
function expandUnitToRate(value, unit) {
|
|
168
|
+
const slash = unit.indexOf("/");
|
|
169
|
+
if (slash >= 0) {
|
|
170
|
+
return { value, numerator: unit.slice(0, slash), denominator: unit.slice(slash + 1) };
|
|
171
|
+
}
|
|
172
|
+
const ext = chunkAMOJYLG2_cjs.EXTENDED_UNITS[unit];
|
|
173
|
+
if (ext !== void 0 && ext.measure === "speed") {
|
|
174
|
+
return { value: value * ext.toBase, numerator: "m", denominator: "s" };
|
|
175
|
+
}
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
function rateAxisFactor(from, to) {
|
|
179
|
+
if (from === to) return 1;
|
|
180
|
+
if (from === "" || to === "") return null;
|
|
181
|
+
const fromMeasure = getMeasure(from);
|
|
182
|
+
const toMeasure = getMeasure(to);
|
|
183
|
+
if (fromMeasure === void 0 || toMeasure === void 0 || fromMeasure !== toMeasure) {
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
return convertUnit(1, from, to);
|
|
187
|
+
}
|
|
188
|
+
function convertRate(value, from, to) {
|
|
189
|
+
const source = expandUnitToRate(value, from);
|
|
190
|
+
if (source === null) return null;
|
|
191
|
+
let targetNumerator;
|
|
192
|
+
let targetDenominator;
|
|
193
|
+
let targetScale;
|
|
194
|
+
const slash = to.indexOf("/");
|
|
195
|
+
if (slash >= 0) {
|
|
196
|
+
targetNumerator = to.slice(0, slash);
|
|
197
|
+
targetDenominator = to.slice(slash + 1);
|
|
198
|
+
targetScale = 1;
|
|
199
|
+
} else {
|
|
200
|
+
const ext = chunkAMOJYLG2_cjs.EXTENDED_UNITS[to];
|
|
201
|
+
if (ext === void 0 || ext.measure !== "speed") return null;
|
|
202
|
+
targetNumerator = "m";
|
|
203
|
+
targetDenominator = "s";
|
|
204
|
+
targetScale = ext.toBase;
|
|
205
|
+
}
|
|
206
|
+
const numeratorFactor = rateAxisFactor(source.numerator, targetNumerator);
|
|
207
|
+
if (numeratorFactor === null) return null;
|
|
208
|
+
const denominatorFactor = rateAxisFactor(source.denominator, targetDenominator);
|
|
209
|
+
if (denominatorFactor === null) return null;
|
|
210
|
+
return source.value * numeratorFactor / denominatorFactor / targetScale;
|
|
211
|
+
}
|
|
167
212
|
|
|
168
213
|
exports.canConvert = canConvert;
|
|
214
|
+
exports.convertRate = convertRate;
|
|
169
215
|
exports.convertUnit = convertUnit;
|
|
170
216
|
exports.getBestUnit = getBestUnit;
|
|
171
217
|
exports.getConvertiblePossibilities = getConvertiblePossibilities;
|
|
@@ -173,5 +219,5 @@ exports.getMeasure = getMeasure;
|
|
|
173
219
|
exports.isConvertibleUnit = isConvertibleUnit;
|
|
174
220
|
exports.isWorkdayUnit = isWorkdayUnit;
|
|
175
221
|
exports.resolveUnit = resolveUnit;
|
|
176
|
-
//# sourceMappingURL=chunk-
|
|
177
|
-
//# sourceMappingURL=chunk-
|
|
222
|
+
//# sourceMappingURL=chunk-EJ3ILXX6.cjs.map
|
|
223
|
+
//# sourceMappingURL=chunk-EJ3ILXX6.c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GAAA,CAAI,MAAA;AAAA,EACpB;AAEA,EAAA,MAAM,eAAA,GAAkB,cAAA,CAAe,MAAA,CAAO,SAAA,EAAW,eAAe,CAAA;AACxE,EAAA,IAAI,eAAA,KAAoB,MAAM,OAAO,IAAA;AACrC,EAAA,MAAM,iBAAA,GAAoB,cAAA,CAAe,MAAA,CAAO,WAAA,EAAa,iBAAiB,CAAA;AAC9E,EAAA,IAAI,iBAAA,KAAsB,MAAM,OAAO,IAAA;AAEvC,EAAA,OAAQ,MAAA,CAAO,KAAA,GAAQ,eAAA,GAAmB,iBAAA,GAAoB,WAAA;AAChE","file":"chunk-EJ3ILXX6.cjs","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"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { TokenTypes, tokenTypeId } from './chunk-
|
|
1
|
+
import { TokenTypes, tokenTypeId } from './chunk-4D6NIHE2.js';
|
|
2
2
|
import { getLocale } from './chunk-XBTEO4OB.js';
|
|
3
|
-
import { ErrorFactory } from './chunk-
|
|
3
|
+
import { ErrorFactory } from './chunk-ERCOHGXD.js';
|
|
4
4
|
|
|
5
5
|
// src/parser/BindingPower.ts
|
|
6
6
|
var BindingPower = {
|
|
@@ -47,6 +47,12 @@ var BindingPower = {
|
|
|
47
47
|
// `<<`, `>>`, `>>>`
|
|
48
48
|
Sum: 30,
|
|
49
49
|
Product: 40,
|
|
50
|
+
// `±` (the uncertainty operator), tighter than `+ - * /` and looser than `^`,
|
|
51
|
+
// so the tolerance attaches to its adjacent values: `12.3 ± 0.5 * 4` reads as
|
|
52
|
+
// `(12.3 ± 0.5) * 4` (the parenthesised headline case), and `2 + 3 ± 0.5` as
|
|
53
|
+
// `2 + (3 ± 0.5)`. A Tier-2 parselet (packages/uncertainty/), so this level is
|
|
54
|
+
// read off the parselet rather than the Tier-1 BUILTIN_INFIX_BP table below.
|
|
55
|
+
Uncertainty: 45,
|
|
50
56
|
// `^`, RIGHT-associative: "2 ^ 3 ^ 2" is 2^(3^2) = 512, as in mathematics,
|
|
51
57
|
// Python, Ruby and JavaScript's `**`. See PrecedenceParser.parseExpression
|
|
52
58
|
// and BinaryOpParselet for the two places that associativity is implemented.
|
|
@@ -323,5 +329,5 @@ function stripLocaleGrouping(text, localeCode) {
|
|
|
323
329
|
}
|
|
324
330
|
|
|
325
331
|
export { BindingPower, BytecodeBuilder, bigIntLiteralDigits, buildBindingPowerTable, invalidateBindingPowerTable };
|
|
326
|
-
//# sourceMappingURL=chunk-
|
|
327
|
-
//# sourceMappingURL=chunk-
|
|
332
|
+
//# sourceMappingURL=chunk-ENKKJYD3.js.map
|
|
333
|
+
//# sourceMappingURL=chunk-ENKKJYD3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/parser/BindingPower.ts","../src/parser/BytecodeBuilder.ts","../src/parser/BigIntLiteral.ts"],"names":[],"mappings":";;;;;AAWO,IAAM,YAAA,GAAe;AAAA,EAC1B,MAAA,EAAQ,CAAA;AAAA,EACR,UAAA,EAAY,EAAA;AAAA,EACZ,SAAA,EAAW,EAAA;AAAA;AAAA,EACX,UAAA,EAAY,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaZ,WAA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hD,EAAA,IAAI,CAAC,WAAA,CAAY,IAAA,CAAK,MAAM,CAAA,EAAG;AAC9B,IAAA,MAAM,SAAA,GAAY,aAAA,CAAc,QAAA,CAAS,GAAG,CAAA,GAAI,MAAM,aAAA,CAAc,QAAA,CAAS,GAAG,CAAA,GAAI,GAAA,GAAM,aAAA;AAC1F,IAAA,MAAM,YAAA,CAAa,OAAA;AAAA,MAClB,wBAAA;AAAA,MACA,CAAA,CAAA,EAAI,GAAG,CAAA,0BAAA,EAA6B,SAAS,+BAA+B,UAAU,CAAA,0DAAA,CAAA;AAAA,MACtF,EAAE,GAAA,EAAK,UAAA,EAAY,SAAA;AAAU,KAC9B;AAAA,EACD;AACA,EAAA,OAAO,MAAA;AACR;AASA,SAAS,mBAAA,CAAoB,MAAc,UAAA,EAA4B;AACtE,EAAA,MAAM,kBAAA,GAAqB,SAAA,CAAU,UAAU,CAAA,CAAE,OAAA,CAAQ,kBAAA;AACzD,EAAA,OAAO,qBAAqB,IAAA,CAAK,KAAA,CAAM,kBAAkB,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA,GAAI,IAAA;AACvE","file":"chunk-ENKKJYD3.js","sourcesContent":["/**\n * Named precedence levels for the Pratt parser, from loosest (`Lowest`) to\n * tightest (`Call`) binding. A custom infix parselet compares its own\n * binding power against the current expression's to decide whether to\n * consume the next operator (higher power binds tighter, e.g. `*` over `+`).\n *\n * Package authors reference these when registering an infix parselet via\n * `IPackageRegistry.registerInfixParselet`. See the built-in packages for\n * examples of picking an appropriate level (e.g. arithmetic `+`/`-` use\n * `Sum`, `*`/`/` use `Product`).\n */\nexport const BindingPower = {\n Lowest: 0,\n Assignment: 10,\n LogicalOr: 12, // `or`, `||` — loosest of the boolean-logic operators\n LogicalAnd: 14, // `&&` — binds tighter than `or` (\"a or b and c\" = \"a or (b and c)\")\n // The word \"and\" (`AND_CONJ`), which is both arithmetic addition (\"5 and 3\"\n // is 8) and boolean conjunction (\"true and false\"). A phrase parselet\n // collecting a list (\"average of X, Y and Z\") parses each argument at this\n // level, and an argument stops at any operator whose power is <= the level it\n // was parsed at, so putting \"and\" here is what makes it end an argument\n // rather than be consumed as the addition it also is. Everything an argument\n // should keep binds tighter, including a genuine \"+\" (`Sum`).\n //\n // It sits BELOW `Conditional` because the boolean reading needs comparisons\n // to be its operands: at 28, \"5 > 3 and 2 > 1\" parsed as \"5 > (3 and 2) > 1\"\n // and answered false. Above `LogicalAnd` so that \"and\" is still the tighter\n // of the two conjunctions, and two steps off each neighbour to leave room.\n Conjunction: 16,\n // The bitwise trio and the shifts, ordered exactly as C and JavaScript order\n // them, which is the order every language that borrowed these operators from\n // C uses: `|` looser than `xor`, `xor` looser than `&`, all three looser than\n // comparison, and the shifts tighter than comparison but looser than `+`.\n // They used to share one level (35) between `Sum` and `Product`, so\n // \"1 + 2 << 3\" answered 17 where JavaScript answers 24 and \"4 & 3 + 1\"\n // answered 1 where JavaScript answers 4. Each has its own level now because\n // a shared level makes \"4 | 6 & 3\" group left instead of letting `&` win.\n //\n // They stay TIGHTER than `Conjunction` so that a phrase argument parsed at\n // that level (\"average of 5 | 3, 2 and 4\") keeps its bitwise operators\n // instead of stopping at the first one.\n BitwiseOr: 18, // `|`\n BitwiseXor: 20, // the `xor` keyword (`BIT_XOR`), not the `^` exponent token\n BitwiseAnd: 22, // `&`\n Conditional: 24, // comparisons (`==`, `<`, `>=`, ...), tighter than the bitwise trio, looser than the shifts\n Shift: 27, // `<<`, `>>`, `>>>`\n Sum: 30,\n Product: 40,\n // `±` (the uncertainty operator), tighter than `+ - * /` and looser than `^`,\n // so the tolerance attaches to its adjacent values: `12.3 ± 0.5 * 4` reads as\n // `(12.3 ± 0.5) * 4` (the parenthesised headline case), and `2 + 3 ± 0.5` as\n // `2 + (3 ± 0.5)`. A Tier-2 parselet (packages/uncertainty/), so this level is\n // read off the parselet rather than the Tier-1 BUILTIN_INFIX_BP table below.\n Uncertainty: 45,\n // `^`, RIGHT-associative: \"2 ^ 3 ^ 2\" is 2^(3^2) = 512, as in mathematics,\n // Python, Ruby and JavaScript's `**`. See PrecedenceParser.parseExpression\n // and BinaryOpParselet for the two places that associativity is implemented.\n Exponent: 50,\n Prefix: 60,\n Postfix: 70,\n Call: 80,\n} as const;\n\n/**\n * Set the binding power of a named operator.\n *\n * Binding power is what decides precedence in the Pratt parser: a higher number\n * binds tighter, so `*` outranks `+`. Changing one changes how every existing\n * expression using that operator parses, which is why packages should allocate\n * a new name rather than adjust a built-in.\n *\n * @param name - Operator name.\n * @param power - Higher binds tighter.\n */\nexport function setBindingPower(name: string, power: number): void {\n (BindingPower as Record<string, number>)[name] = power;\n}\n\n/**\n * Read the binding power of a named operator.\n *\n * @param name - Operator name.\n * @returns Its binding power, or 0 when the name is unknown, which makes an\n * unregistered operator terminate an expression rather than swallow the rest\n * of it.\n */\nexport function getBindingPower(name: string): number {\n return (BindingPower as Record<string, number>)[name] ?? 0;\n}\n\n// ── Built-in Infix Operator Binding Power Table ──────────────────────────────\n// Pre-computed Uint8Array lookup indexed by token typeId.\n// value > 0 → built-in infix operator with that binding power\n// value = 0 → not a built-in infix, fall through to Tier 2 parselet registry\n//\n// Built at module load via buildBindingPowerTable(). The table is sparse\n// most entries are 0 since only ~15 of 80+ token types are infix operators.\n//\n// Performance: Uint8Array[typeId] is a single typed array load, no Map.get()\n// no string hashing, no property chain. V8 eliminates bounds checks when typeId\n// is known to be within array length.\n\nimport { TokenTypes } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\n\n/**\n * Mapping of token type names → binding powers for built-in infix operators.\n * Only operators listed here get the Tier 1 fast path in PrecedenceParser.\n * All other infix tokens use the Tier 2 parselet registry fallback.\n */\nconst BUILTIN_INFIX_BP: Record<string, number> = {\n // Arithmetic (infix, left-associative)\n [TokenTypes.PLUS]: BindingPower.Sum,\n [TokenTypes.MINUS]: BindingPower.Sum,\n [TokenTypes.STAR]: BindingPower.Product,\n [TokenTypes.SLASH]: BindingPower.Product,\n [TokenTypes.MOD]: BindingPower.Product,\n\n // Arithmetic (infix, RIGHT-associative, PrecedenceParser handles this specially)\n [TokenTypes.CARET]: BindingPower.Exponent,\n\n // Bitwise and shift (infix, left-associative), one level each, ordered as C\n // and JavaScript order them. `>>>` used to be missing from this table\n // entirely, which left it running at its Tier 2 parselet level while `>>`\n // ran at the Tier 1 one, so \"16 >> 3 & 1\" and \"16 >>> 3 & 1\" grouped\n // differently and answered 0 and 8.\n [TokenTypes.BIT_OR]: BindingPower.BitwiseOr,\n [TokenTypes.BIT_XOR]: BindingPower.BitwiseXor,\n [TokenTypes.BIT_AND]: BindingPower.BitwiseAnd,\n [TokenTypes.LSHIFT]: BindingPower.Shift,\n [TokenTypes.RSHIFT]: BindingPower.Shift,\n [TokenTypes.URSHIFT]: BindingPower.Shift,\n\n // Postfix (no right operand, PrecedenceParser handles this specially)\n [TokenTypes.PERCENT]: BindingPower.Postfix,\n\n // Percentage keyword (infix, left-associative: \"50% of 200\" → MUL)\n [TokenTypes.OF]: BindingPower.Product,\n};\n\n// Note: These token types are intentionally NOT in the BP_TABLE, they stay in\n// the Tier 2 parselet registry because they require complex handling:\n// IN, TO → UoM conversion parselets (peek at target unit token, complex logic)\n// DOT → Property access (chained OBJ_GET, needs left-token tracking)\n// EQUALS → Assignment (VariableParselet handles :var = expr pattern)\n// EQUALITY, NEQ, GTE, LTE → Comparison ops (need dedicated VM opcodes, task 2.15a)\n// COMMA → Argument separator (function calls, array/object literals)\n\n/** Cached BP_TABLE, built once at module load, immutable thereafter. */\nlet _bpTable: Uint8Array | null = null;\n\n/**\n * Build the Uint8Array binding power table indexed by token typeId.\n * Idempotent, returns cached table on subsequent calls.\n *\n * Must be called after all token types are registered (via registerAllTokenTypes())\n * and after plugin providers have registered their token types.\n */\nexport function buildBindingPowerTable(): Uint8Array {\n if (_bpTable) return _bpTable;\n\n // Size to the largest registered typeId + 1\n let maxId = 0;\n for (const name of Object.keys(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n // Also scan all TokenTypes to ensure table covers all registered IDs\n for (const name of Object.values(TokenTypes)) {\n const id = tokenTypeId(name);\n if (id > maxId) maxId = id;\n }\n\n const table = new Uint8Array(maxId + 1);\n for (const [name, bp] of Object.entries(BUILTIN_INFIX_BP)) {\n const id = tokenTypeId(name);\n table[id] = bp;\n }\n\n _bpTable = table;\n return table;\n}\n\n/**\n * Drop the cached table, so the next {@link buildBindingPowerTable} call builds\n * a fresh one sized to the token types registered by then.\n *\n * It does NOT add a plugin's operator to the Tier 1 fast path, which is what\n * this comment used to promise. The values in the table come from\n * `BUILTIN_INFIX_BP`, which is module-private and has no registration path, so\n * a rebuilt table holds the same binding powers and a plugin token still reads\n * 0. `PrecedenceParser.BP_TABLE` is a static initialized once at class\n * definition time and never re-read, so it would not see a rebuild anyway.\n *\n * A plugin's infix operator takes the Tier 2 parselet-registry route instead,\n * which is where an operator whose binding power the engine does not already\n * know is meant to live.\n */\nexport function invalidateBindingPowerTable(): void {\n _bpTable = null;\n}\n","import { OpCode } from \"@solve-js/parser/OpCode\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * `BytecodeProgram.opcodes` is a `Uint8Array`, every operand written into\n * it (including constant-pool indices from {@link BytecodeBuilder.emitNumber}/\n * {@link BytecodeBuilder.emitString}) is truncated to a single byte on\n * `build()`. Exceeding this silently wraps the index (e.g. entry 300 reads\n * back as entry 44), producing a wrong result with no error. See\n * {@link BytecodeBuilder.emitNumber} for the guard that turns this into a\n * thrown error instead.\n */\nconst MAX_CONSTANT_POOL_INDEX = 255;\n\n/**\n * Compiled bytecode program produced by {@link BytecodeBuilder}.\n * Ready for consumption by {@link executeBytecode} without further processing.\n */\nexport interface BytecodeProgram {\n\topcodes: Uint8Array;\n\tnumbers: Float64Array;\n\tstrings: string[];\n\tconstants?: Map<number, number>;\n\t/**\n\t * Whether the program contains any async opcodes (CALL_PLUGIN, etc.).\n\t * Set during compilation by the BytecodeBuilder. Allows the engine\n\t * to skip the O(n) resolver preflight check in O(1) for purely\n\t * synchronous expressions like `2 + 2`.\n\t */\n\thasAsync: boolean;\n\t/**\n\t * User-defined-function bodies compiled alongside this program (one\n\t * entry per `name(params) = body` definition on this line). See\n\t * {@link BytecodeBuilder.emitUserFunctionBody}. `OpCode.DEFINE_USER_FUNCTION`'s\n\t * operand is an index into this array, resolved at VM-execution time\n\t * (not parse time) so a diagnostic/lookahead parse that never actually\n\t * executes the definition line has no side effect on `vm.userFunctions`.\n\t */\n\tuserFunctionBodies?: UserFunctionDef[];\n\t/**\n\t * Anonymous function bodies compiled alongside this program, one entry\n\t * per `map`/`reduce` inline transform expression (e.g. the `10*x` in\n\t * `map(10*x, [0,1,500])`). See {@link BytecodeBuilder.emitAnonymousBody}.\n\t * Deliberately a SEPARATE side-table from `userFunctionBodies`, not\n\t * routed through `vm.userFunctions` at all: an inline body has no name\n\t * and must never leak into the persistent name-keyed registry the way\n\t * a real `f(x) = ...` definition does.\n\t */\n\tanonymousBodies?: AnonymousBodyDef[];\n}\n\n/**\n * An anonymous transform body for `map`/`reduce`'s inline-expression form\n * (e.g. `10*x` in `map(10*x, [0,1,500])`, or `acc+x` in `reduce(acc+x,\n * [1,2,3])`). Structurally identical to {@link UserFunctionDef} minus the\n * `name`. See `OpCode.MAP_INVOKE`/`REDUCE_INVOKE` and\n * `vm/VM.ts`'s handlers, which build a call frame from `params`/`args`\n * exactly like `CALL_USER_FUNCTION` does, just without ever registering\n * the body in `vm.userFunctions`.\n */\nexport interface AnonymousBodyDef {\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * A user-defined, parameterized, reusable function's compiled form\n * (`f(x) = 2*x + 1`). See `OpCode.DEFINE_USER_FUNCTION`/`CALL_USER_FUNCTION`\n * and `vm/VM.ts`'s `VM.defineUserFunction`/`getUserFunction`.\n *\n * `program` is the body compiled to its OWN independent `BytecodeProgram`,\n * not a fragment of the definition line's own bytecode. Parameter names\n * inside the body compile to ORDINARY `LOAD_VAR <name>` opcodes, no\n * parse-time rewriting, because parameter resolution happens dynamically\n * at the VM level: `CALL_USER_FUNCTION` pushes a name-keyed call frame\n * (`Map<string, Value>`) before re-executing `program`, and `VM.getVar()`\n * checks the innermost call frame before falling back to the flat\n * document-variable store. This is why a `UNIT`-collision parameter name\n * (e.g. `h` in `area(w, h) = w * h`, which lexes as the \"hour\" unit) needs\n * no special handling anywhere, it's just another `LOAD_VAR \"h\"`, resolved\n * the same way as any other name.\n */\nexport interface UserFunctionDef {\n\tname: string;\n\tparams: string[];\n\tprogram: BytecodeProgram;\n}\n\n/**\n * Direct-to-bytecode compiler for the Pratt parser.\n *\n * Accumulates opcodes, numeric constants, and string references during parsing,\n * then produces a {@link BytecodeProgram} for VM execution. Supports:\n * - Standard build via {@link build}\n * - Zero-copy build into pre-allocated buffers via {@link buildInto}\n * - In-place reset for reuse without reallocation\n */\nexport class BytecodeBuilder {\n\tprivate opcodes: number[] = [];\n\tprivate numbers: number[] = [];\n\tprivate strings: string[] = [];\n\tprivate stringIndex = new Map<string, number>();\n\tprivate _hasAsync = false;\n\tprivate userFunctionBodies: UserFunctionDef[] = [];\n\tprivate anonymousBodies: AnonymousBodyDef[] = [];\n\n\t/** Emit an {@link OpCode} instruction. */\n\temitOpcode(op: OpCode): void {\n\t\tthis.opcodes.push(op);\n\t\tif (op === OpCode.CALL_PLUGIN) {\n\t\t\tthis._hasAsync = true;\n\t\t}\n\t}\n\n\t/**\n\t * Emit a numeric literal: appends `n` to the program's constant pool and\n\t * writes its index into the opcode stream (read back by the VM as e.g.\n\t * `PUSH_NUMBER <idx>`).\n\t *\n\t * Numeric constants are NOT deduplicated (unlike {@link emitString})\n\t * every call appends a new entry, so an expression with more than\n\t * {@link MAX_CONSTANT_POOL_INDEX}+1 distinct numeric-literal occurrences\n\t * throws rather than silently wrapping the index (see\n\t * `MAX_CONSTANT_POOL_INDEX`'s doc for what that would otherwise do).\n\t *\n\t * @throws If the constant pool would exceed 256 entries.\n\t */\n\temitNumber(n: number): void {\n\t\tconst idx = this.numbers.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_NUMERIC_CONSTANTS\",\n\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} numeric literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.numbers.push(n);\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a string literal: interns `s` into the program's string pool\n\t * (deduplicated via `stringIndex`) and writes its index into the opcode\n\t * stream. Subject to the same constant-pool bound as {@link emitNumber},\n\t * but since strings ARE deduplicated, only distinct string values count\n\t * against the limit.\n\t *\n\t * @throws If the string pool would exceed 256 distinct entries.\n\t */\n\temitString(s: string): void {\n\t\tlet idx = this.stringIndex.get(s);\n\t\tif (idx === undefined) {\n\t\t\tidx = this.strings.length;\n\t\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\t\"TOO_MANY_STRING_CONSTANTS\",\n\t\t\t\t\t`Expression has more than ${MAX_CONSTANT_POOL_INDEX + 1} distinct string literals, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.strings.push(s);\n\t\t\tthis.stringIndex.set(s, idx);\n\t\t}\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/**\n\t * Emit a raw numeric operand (0-255) following an opcode, e.g. a\n\t * plugin-function index for `CALL_PLUGIN`, or an argument count. Unlike\n\t * {@link emitOpcode}, this does not go through the `OpCode` enum, so\n\t * package authors use this (not an unsafe cast to `OpCode`) to push\n\t * operands their own opcode handler expects to read positionally.\n\t */\n\temitIndex(idx: number): void {\n\t\tthis.opcodes.push(idx);\n\t}\n\n\t/** Emit a raw byte (0-255), used for fixed small operands like argument counts. */\n\temitByte(b: number): void {\n\t\tthis.opcodes.push(b);\n\t}\n\n\t/** Number of opcodes/operands emitted so far, used to compute jump targets before {@link patchJump}. */\n\tget currentLength(): number {\n\t\treturn this.opcodes.length;\n\t}\n\n\t/**\n\t * Register a compiled user-defined-function body, returning its index\n\t * into this program's `userFunctionBodies` side-table, the caller emits\n\t * that index as `DEFINE_USER_FUNCTION`'s operand via {@link emitIndex}.\n\t * Subject to the same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitNumber}/{@link emitString} (the index itself is a single\n\t * opcode-stream byte), in practice a single line defines at most a\n\t * handful of functions, so this limit is never realistically reached.\n\t *\n\t * @throws If more than 256 function bodies are registered on one program.\n\t */\n\temitUserFunctionBody(name: string, params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.userFunctionBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_FUNCTION_DEFINITIONS\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} function definitions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.userFunctionBodies.push({ name, params, program });\n\t\treturn idx;\n\t}\n\n\t/**\n\t * Register a compiled `map`/`reduce` anonymous transform body, returning\n\t * its index into this program's `anonymousBodies` side-table, the\n\t * caller emits that index as `MAP_INVOKE`/`REDUCE_INVOKE`'s operand via\n\t * {@link emitIndex}. Same {@link MAX_CONSTANT_POOL_INDEX} bound as\n\t * {@link emitUserFunctionBody}.\n\t *\n\t * @throws If more than 256 anonymous bodies are registered on one program.\n\t */\n\temitAnonymousBody(params: string[], program: BytecodeProgram): number {\n\t\tconst idx = this.anonymousBodies.length;\n\t\tif (idx > MAX_CONSTANT_POOL_INDEX) {\n\t\t\tthrow ErrorFactory.parsing(\n\t\t\t\t\"TOO_MANY_ANONYMOUS_BODIES\",\n\t\t\t\t`More than ${MAX_CONSTANT_POOL_INDEX + 1} map/reduce transform expressions on one line, exceeding the bytecode constant pool's limit.`,\n\t\t\t\t{ limit: MAX_CONSTANT_POOL_INDEX + 1 }\n\t\t\t);\n\t\t}\n\t\tthis.anonymousBodies.push({ params, program });\n\t\treturn idx;\n\t}\n\n\t/** Overwrite a previously-emitted placeholder operand at `position` with the real jump `target`, once known. */\n\tpatchJump(position: number, target: number): void {\n\t\tthis.opcodes[position] = target;\n\t}\n\n\t/**\n\t * Build the accumulated opcodes/numbers/strings into a BytecodeProgram.\n\t * Creates new TypedArrays, the builder can be reused after this call.\n\t */\n\tbuild(): BytecodeProgram {\n\t\treturn {\n\t\t\topcodes: new Uint8Array(this.opcodes),\n\t\t\tnumbers: new Float64Array(this.numbers),\n\t\t\t// Defensive copy: .length = 0 in reset() would clear a shared reference.\n\t\t\t// Strings are rare (only UoM/datetime parselets emit them), so the copy\n\t\t\t// cost is negligible.\n\t\t\tstrings: [...this.strings],\n\t\t\tconstants: new Map(),\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Build directly into a pre-allocated buffer for zero-copy VM consumption.\n\t *\n\t * When `buf` is provided and large enough, writes into it and returns\n\t * subarray **views** (not copies), the returned TypedArrays share the\n\t * buffer's underlying ArrayBuffer. The caller MUST NOT mutate the buffer\n\t * until the returned BytecodeProgram is no longer needed.\n\t *\n\t * If the caller intends to cache the result, they must copy the TypedArrays\n\t * (e.g. `new Uint8Array(program.opcodes)`) before reusing the buffer pool.\n\t *\n\t * When `buf` is omitted or too small, allocates fresh TypedArrays.\n\t */\n\tbuildInto(buf?: { opcodes: Uint8Array; numbers: Float64Array }): BytecodeProgram {\n\t\tconst opLen = this.opcodes.length;\n\t\tconst numLen = this.numbers.length;\n\n\t\tconst reuseOpcodes = buf && buf.opcodes.length >= opLen;\n\t\tconst reuseNumbers = buf && buf.numbers.length >= numLen;\n\n\t\t// Subarray views that share the buffer's ArrayBuffer (zero-copy)\n\t\tconst opcodes = reuseOpcodes\n\t\t\t? new Uint8Array(buf!.opcodes.buffer, buf!.opcodes.byteOffset, opLen)\n\t\t\t: new Uint8Array(opLen);\n\t\tconst numbers = reuseNumbers\n\t\t\t? new Float64Array(buf!.numbers.buffer, buf!.numbers.byteOffset, numLen)\n\t\t\t: new Float64Array(numLen);\n\n\t\t// Write data into the views\n\t\tfor (let i = 0; i < opLen; i++) opcodes[i] = this.opcodes[i];\n\t\tfor (let i = 0; i < numLen; i++) numbers[i] = this.numbers[i];\n\n\t\treturn {\n\t\t\topcodes,\n\t\t\tnumbers,\n\t\t\tstrings: [...this.strings],\n\t\t\tconstants: new Map(),\n\t\t\thasAsync: this._hasAsync,\n\t\t\tuserFunctionBodies: this.userFunctionBodies.length > 0 ? [...this.userFunctionBodies] : undefined,\n\t\t\tanonymousBodies: this.anonymousBodies.length > 0 ? [...this.anonymousBodies] : undefined,\n\t\t};\n\t}\n\n\treset(): void {\n\t\t// Retain backing stores with .length = 0 to avoid reallocation on growth.\n\t\t// = [] discards the ArrayBuffer, forcing V8 to reallocate on every push()\n\t\t// threshold (4→8→16→32...). For a 50-opcode expression, that's 3-4 copies.\n\t\tthis.opcodes.length = 0;\n\t\tthis.numbers.length = 0;\n\t\tthis.strings.length = 0;\n\t\tthis.stringIndex.clear();\n\t\tthis._hasAsync = false;\n\t\tthis.userFunctionBodies.length = 0;\n\t\tthis.anonymousBodies.length = 0;\n\t}\n}\n","/**\n * Turning a `123n` literal's source text into the digits `PUSH_BIGINT` stores.\n *\n * The lexer coalesces thousands groups into the number token it is building,\n * accepting both `,` and `.` as the separator regardless of locale (see\n * `lexer/ExpressionLexer.ts`'s \"Thousands separators\" block). For a NUMBER that\n * is fine, because the separators are stripped again when the text is turned\n * into a double. For a BIGINT nothing stripped them: both consumers took the\n * token text, removed the trailing `n`, and handed the rest straight to\n * `BigInt()`.\n *\n * So `1.000n` reached `BigInt(\"1.000\")`, which throws a raw `SyntaxError` that\n * arrived at the host as UNEXPECTED_ERROR/INTERNAL: the engine reporting its\n * own bug for six characters a user typed. `1.01n` and `1.1n` were fine, which\n * is the tell that the `n` suffix was never the problem, the three-digit\n * thousands group was: a dot followed by exactly three digits is what the lexer\n * swallows, and one followed by one or two digits it leaves alone.\n *\n * Written once here rather than inline at both call sites. There are two\n * (`parser/PrecedenceParser.ts`'s Tier-1 switch and\n * `packages/biginteger/parselets/BigIntNumberParselet.ts`), they already held\n * identical copies of the `n`-stripping, and the two tiers disagreeing about a\n * literal is a bug shape this codebase has had before.\n *\n * @module BigIntLiteral\n */\n\nimport { getLocale } from \"@solve-js/constants/locales\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Two or more dot-separated groups of three, e.g. `1.234.567`.\n *\n * Unambiguous in any locale, since no locale writes two decimal points, so this\n * is stripped without consulting one. Same regex and same reasoning as\n * `NumberParselet.ts`'s copy for the NUMBER path.\n */\nconst CHAINED_DOT_THOUSANDS_GROUPS = /^\\d{1,3}(\\.\\d{3}){2,}$/;\n\n/** Digits and nothing else, which is what `BigInt()` can be handed safely. */\nconst DIGITS_ONLY = /^\\d+$/;\n\n/**\n * The digit string behind a bigint literal.\n *\n * A bigint literal has no fractional part by construction: the lexer only emits\n * BIGINT when it saw no decimal point of its own and no exponent, so any `.` or\n * `,` still in the text got there as a thousands group. Which of the two the\n * writer meant is a locale question, and answering it wrongly would silently\n * change the value by three orders of magnitude, so only the separator this\n * locale actually uses for grouping is removed. Anything left over is refused\n * rather than guessed at.\n *\n * @param raw - The token's text, with or without the trailing `n`.\n * @param localeCode - The engine's active locale.\n * @returns A string of digits, ready for `BigInt()`.\n * @throws An `INVALID_NUMBER_LITERAL` parsing error when what is left is not a\n * whole number, e.g. `1.000n` in a locale that writes decimals with a dot.\n */\nexport function bigIntLiteralDigits(raw: string, localeCode: string): string {\n\tconst withoutSuffix = raw.endsWith(\"n\") ? raw.slice(0, -1) : raw;\n\n\t// The common case first: nothing was grouped, so there is nothing to decide.\n\tif (DIGITS_ONLY.test(withoutSuffix)) return withoutSuffix;\n\n\tconst digits = CHAINED_DOT_THOUSANDS_GROUPS.test(withoutSuffix)\n\t\t? withoutSuffix.split(\".\").join(\"\")\n\t\t: stripLocaleGrouping(withoutSuffix, localeCode);\n\n\tif (!DIGITS_ONLY.test(digits)) {\n\t\tconst separator = withoutSuffix.includes(\".\") ? \".\" : withoutSuffix.includes(\",\") ? \",\" : withoutSuffix;\n\t\tthrow ErrorFactory.parsing(\n\t\t\t\"INVALID_NUMBER_LITERAL\",\n\t\t\t`\"${raw}\" is not a whole number: \"${separator}\" separates decimals in the ${localeCode} locale, and a whole number cannot have a fractional part.`,\n\t\t\t{ raw, localeCode, separator },\n\t\t);\n\t}\n\treturn digits;\n}\n\n/**\n * Removes the active locale's own thousands separator and nothing else.\n *\n * @param text - The literal without its `n`.\n * @param localeCode - The engine's active locale.\n * @returns The text with grouping removed, which the caller then re-checks.\n */\nfunction stripLocaleGrouping(text: string, localeCode: string): string {\n\tconst thousandsSeparator = getLocale(localeCode).display.thousandsSeparator;\n\treturn thousandsSeparator ? text.split(thousandsSeparator).join(\"\") : text;\n}\n"]}
|
|
@@ -89,16 +89,6 @@ var abortLogger = {
|
|
|
89
89
|
}
|
|
90
90
|
};
|
|
91
91
|
|
|
92
|
-
// src/utilities/Hash.ts
|
|
93
|
-
function djb2Hash(str) {
|
|
94
|
-
let hash = 5381;
|
|
95
|
-
for (let i = 0; i < str.length; i++) {
|
|
96
|
-
hash = (hash << 5) + hash + str.charCodeAt(i) | 0;
|
|
97
|
-
}
|
|
98
|
-
return hash >>> 0;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
92
|
exports.abortLogger = abortLogger;
|
|
102
|
-
|
|
103
|
-
//# sourceMappingURL=chunk-
|
|
104
|
-
//# sourceMappingURL=chunk-5X2PTP6F.cjs.map
|
|
93
|
+
//# sourceMappingURL=chunk-ENRIK36Q.cjs.map
|
|
94
|
+
//# sourceMappingURL=chunk-ENRIK36Q.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utilities/AbortControllerLogger.ts"],"names":[],"mappings":";;;AA4BA,IAAM,iBAAiB,OAAO,OAAA,KAAY,WAAA,IAAe,OAAA,CAAQ,IAAI,eAAA,KAAoB,MAAA;AAQlF,IAAM,WAAA,GAAc;AAAA;AAAA,EAE1B,IAAI,OAAA,GAAmB;AACtB,IAAA,OAAO,cAAA;AAAA,EACR,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,gBAAA,GAAyB;AACxB,IAAA,IAAI,CAAC,cAAA,EAAgB;AACrB,IAAA,OAAA,CAAQ,MAAM,+BAA+B,CAAA;AAAA,EAC9C,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,iBAAiB,MAAA,EAAsB;AACtC,IAAA,IAAI,CAAC,cAAA,EAAgB;AACrB,IAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,+BAAA,EAAkC,MAAM,CAAA,CAAE,CAAA;AAAA,EACzD,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,uBAAuB,MAAA,EAAsB;AAC5C,IAAA,IAAI,CAAC,cAAA,EAAgB;AACrB,IAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,2BAAA,EAA8B,MAAM,CAAA,CAAA,CAAG,CAAA;AAAA,EACtD,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,aAAa,MAAA,EAAsB;AAClC,IAAA,IAAI,CAAC,cAAA,EAAgB;AACrB,IAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,0BAAA,EAA6B,MAAM,CAAA,kBAAA,CAAe,CAAA;AAAA,EACjE,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,eAAe,MAAA,EAAsB;AACpC,IAAA,IAAI,CAAC,cAAA,EAAgB;AACrB,IAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,4BAAA,EAA+B,MAAM,CAAA,CAAA,CAAG,CAAA;AAAA,EACvD,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,mBAAmB,SAAA,EAA0B;AAC5C,IAAA,IAAI,CAAC,cAAA,EAAgB;AACrB,IAAA,OAAA,CAAQ,KAAA;AAAA,MACP,uDAAkD,SAAS,CAAA,CAAA;AAAA,KAC5D;AAAA,EACD,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,sBAAA,GAA+B;AAC9B,IAAA,IAAI,CAAC,cAAA,EAAgB;AACrB,IAAA,OAAA,CAAQ,MAAM,6CAA6C,CAAA;AAAA,EAC5D,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,kBAAA,CAAmB,UAAkB,OAAA,EAAuB;AAC3D,IAAA,IAAI,CAAC,cAAA,EAAgB;AACrB,IAAA,OAAA,CAAQ,KAAA;AAAA,MACP,CAAA,2BAAA,EAA8B,QAAQ,CAAA,EAAA,EAAK,OAAO,CAAA,CAAA;AAAA,KACnD;AAAA,EACD;AACD","file":"chunk-ENRIK36Q.cjs","sourcesContent":["/**\n * Debug logging for the AbortController lifecycle in the \"One AbortController\n * Per Keystroke\" pattern.\n *\n * Enabled when `process.env.DEBUG_ABORTCTRL === \"true\"`.\n *\n * This is **opt-in only**, even in development mode you must explicitly\n * set the flag to avoid log noise from large documents.\n *\n * Logs controller creation, abortion, signal linking, keystroke signal\n * propagation, and stale-data discard guards. All messages are output via\n * `console.debug` with an `[AbortCtrl]` prefix so they can be filtered\n * in the DevTools console.\n *\n * ── Usage ─────────────────────────────────────────────────────────────\n * import { abortLogger } from \"@solve-js/utilities/AbortControllerLogger\";\n *\n * // Enable explicitly (before the plugin boots):\n * // process.env.DEBUG_ABORTCTRL = \"true\";\n *\n * abortLogger.keystrokeCreated();\n * abortLogger.localControllerCreated(\"executeAndStore\");\n * abortLogger.signalLinked(\"executeAndStore\", \"keystroke\");\n * abortLogger.keystrokeAborted(\"New keystroke\");\n * abortLogger.staleDataDiscarded(\"USD:GBP\", \"signal aborted\");\n * abortLogger.keystrokeSignalSet(true); // signal set, not aborted\n * abortLogger.keystrokeSignalCleared();\n */\nconst isDebugEnabled = typeof process !== \"undefined\" && process.env.DEBUG_ABORTCTRL === \"true\";\n\n/**\n * Records abort-signal lifecycle for debugging cancellation.\n *\n * Keystroke cancellation is hard to reason about after the fact, because the\n * evidence is gone by the time anything looks wrong. This keeps it.\n */\nexport const abortLogger = {\n\t/** Whether debug logging is currently active. */\n\tget enabled(): boolean {\n\t\treturn isDebugEnabled;\n\t},\n\n\t// ── Keystroke-level controller (MarkdownEditorViewPlugin) ──────\n\n\t/**\n\t * Log creation of the keystroke-level AbortController.\n\t * Called in the plugin constructor and on each new keystroke.\n\t */\n\tkeystrokeCreated(): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(\"[AbortCtrl] KEYSTROKE CREATED\");\n\t},\n\n\t/**\n\t * Log abortion of the keystroke-level AbortController.\n\t * @param reason Why the keystroke was aborted (e.g. \"New keystroke\",\n\t * \"Document switch\", \"Plugin destroyed\").\n\t */\n\tkeystrokeAborted(reason: string): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(`[AbortCtrl] KEYSTROKE ABORTED: ${reason}`);\n\t},\n\n\t// ── Local per-evaluation controllers (ExpressionEngine) ─────────\n\n\t/**\n\t * Log creation of a local AbortController that is linked to the\n\t * keystroke signal.\n\t * @param source Which code path created the controller\n\t * (e.g. \"executeAndStore\", \"executeRaw\", \"preflight\", \"vm\").\n\t */\n\tlocalControllerCreated(source: string): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(`[AbortCtrl] LOCAL CREATED (${source})`);\n\t},\n\n\t/**\n\t * Log that a local AbortController was linked to the keystroke signal.\n\t * When the keystroke signal is aborted, this local controller will\n\t * be aborted automatically.\n\t * @param source The code path that created the controller.\n\t */\n\tsignalLinked(source: string): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(`[AbortCtrl] LOCAL LINKED (${source}) → keystroke`);\n\t},\n\n\t/**\n\t * Log that a local AbortController's listener was removed from the\n\t * keystroke signal (cleanup).\n\t * @param source The code path.\n\t */\n\tsignalUnlinked(source: string): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(`[AbortCtrl] LOCAL UNLINKED (${source})`);\n\t},\n\n\t// ── Keystroke signal propagation (ThreeTierEvaluator → ExpressionEngine) ──\n\n\t/**\n\t * Log that the keystroke signal was propagated INTO the engine.\n\t * @param isAborted Whether the signal was already aborted when set.\n\t */\n\tkeystrokeSignalSet(isAborted: boolean): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(\n\t\t\t`[AbortCtrl] KEYSTROKE_SIGNAL → engine (aborted=${isAborted})`,\n\t\t);\n\t},\n\n\t/**\n\t * Log that the keystroke signal was CLEARED from the engine\n\t * (typically in the evaluator's finally block).\n\t */\n\tkeystrokeSignalCleared(): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(\"[AbortCtrl] KEYSTROKE_SIGNAL cleared (null)\");\n\t},\n\n\t// ── Stale-data discard guards (resolveAsync) ────────────────────\n\n\t/**\n\t * Log that a stale async result was discarded because its signal\n\t * was aborted.\n\t * @param queryKey The cache key for the discarded result.\n\t * @param context Additional context (e.g. \"after await\", \"after error\").\n\t */\n\tstaleDataDiscarded(queryKey: string, context: string): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(\n\t\t\t`[AbortCtrl] STALE DISCARD: ${queryKey} (${context})`,\n\t\t);\n\t},\n};\n"]}
|
|
@@ -225,12 +225,20 @@ var CoreErrorCodes = {
|
|
|
225
225
|
MAP_REDUCE_ASYNC_UNSUPPORTED: "MAP_REDUCE_ASYNC_UNSUPPORTED",
|
|
226
226
|
/** An algebra verb's expression argument (`BIND_UNKNOWN`'s body) calling an async plugin. Same v1 scope restriction as the two above, and likewise refused at parse time first (`SYMBOLIC_ARGUMENT_MUST_BE_SYNCHRONOUS`, packages/symbolic/). */
|
|
227
227
|
SYMBOLIC_ASYNC_UNSUPPORTED: "SYMBOLIC_ASYNC_UNSUPPORTED",
|
|
228
|
+
/** `explainLine()` asked to derive a line that resolves data asynchronously (a live-data or async-plugin line). A derivation is a sequence of settled intermediate values, which a pending result has none of, so the line is refused rather than explained with a hole in it. */
|
|
229
|
+
EXPLAIN_ASYNC_UNSUPPORTED: "EXPLAIN_ASYNC_UNSUPPORTED",
|
|
228
230
|
/** `pushCallFrame()`'s recursion guard, a nested `CALL_USER_FUNCTION` re-enters `executeBytecode()`, so `maxInstructions` alone can't catch e.g. `f(x) = f(x)`; this is the dedicated backstop. `recoverable: true` (the default for `.execution()`), ordinary user-written infinite recursion, not an engine bug; the guard exists precisely so it surfaces as a clear error instead of overflowing the native call stack uncatchably. */
|
|
229
231
|
FUNCTION_RECURSION_LIMIT_EXCEEDED: "FUNCTION_RECURSION_LIMIT_EXCEEDED",
|
|
230
232
|
/** The companion to the code above, and the half it could never see: how MANY user-defined-function calls one evaluation makes, rather than how deeply they nest. A twenty-two-line doubling chain nests twenty-two deep (legal) and makes two million calls (a fatal heap abort). Counted in `vm/AllocationBudget.ts`, because the tally has to survive `executeBytecode()` re-entering itself. Recoverable. */
|
|
231
233
|
FUNCTION_CALL_LIMIT_EXCEEDED: "FUNCTION_CALL_LIMIT_EXCEEDED",
|
|
232
234
|
/** A `<date> + N workdays` offset outside `date.maxOffsetYears`/`minOffsetYears`. Workdays are the one date offset that walks the calendar a day at a time, so the one whose cost is the offset; every other one moves a Date field once. Recoverable. */
|
|
233
235
|
DATE_OFFSET_LIMIT_EXCEEDED: "DATE_OFFSET_LIMIT_EXCEEDED",
|
|
236
|
+
/** The anchor of `N working days after/before/from <expr>` was not a date (e.g. `5 working days after 3`). The grammar guarantees the count is a number, so this only fires on the anchor. Emitted as a recoverable Error value, not thrown, matching the datetime package's other type guards. See `vm/VM.ts`'s `DATE_WORKDAY_OFFSET` case. */
|
|
237
|
+
WORKDAY_OFFSET_EXPECTED_DATE: "WORKDAY_OFFSET_EXPECTED_DATE",
|
|
238
|
+
/** An endpoint of `working days between <expr> and <expr>` was not a date. Recoverable Error value. See `vm/VM.ts`'s `DATE_WORKDAYS_BETWEEN` case. */
|
|
239
|
+
WORKDAYS_BETWEEN_EXPECTED_DATES: "WORKDAYS_BETWEEN_EXPECTED_DATES",
|
|
240
|
+
/** The two endpoints of `working days between <expr> and <expr>` are further apart than `date.maxOffsetYears`/`minOffsetYears` allow the count's calendar walk to run. Recoverable Error value, the between-count's equivalent of `DATE_OFFSET_LIMIT_EXCEEDED`. See `vm/VM.ts`'s `DATE_WORKDAYS_BETWEEN` case. */
|
|
241
|
+
WORKDAYS_BETWEEN_RANGE_TOO_LARGE: "WORKDAYS_BETWEEN_RANGE_TOO_LARGE",
|
|
234
242
|
/** A `<<`/`>>` with a bigint operand whose exact result would pass `MAX_EXACT_SHIFT_BITS`, whichever operand is the bigint. Both spellings refuse as of 1.0.0: a bigint on the left used to fall through to `x * 2^n` in doubles and report a 19,870-digit integer as Infinity. See `vm/VM.ts`'s `bigIntShift()`. Recoverable. */
|
|
235
243
|
BIGINT_SHIFT_LIMIT_EXCEEDED: "BIGINT_SHIFT_LIMIT_EXCEEDED",
|
|
236
244
|
/** The same ceiling for `^`, the operator it was written for: `2n ^ 100000` asks for the same 100,001-bit integer `1n << 100000` does, so the two spellings answer the same way. Also new in 1.0.0, and for the same reason: this used to fall through to the double path and answer Infinity. A fractional or negative exponent (`4n ^ 0.5`, `2n ^ -1`) has no exact answer to bound and still uses the double path. See `vm/VM.ts`'s `MAX_EXACT_POW_BITS`. Recoverable. */
|
|
@@ -311,6 +319,13 @@ var CoreErrorCodes = {
|
|
|
311
319
|
THEREFORE_ASYNC_UNSUPPORTED: "THEREFORE_ASYNC_UNSUPPORTED",
|
|
312
320
|
/** Colon-separated numbers that are not a time any clock can show ("24:00", "9:60", "100:5"). Raised by the labeled-line fallback, which used to answer them with whatever stood after the colon. */
|
|
313
321
|
INVALID_TIME_LITERAL: "INVALID_TIME_LITERAL",
|
|
322
|
+
// ── Snapshot / restore (engine/EngineSnapshot.ts, engine/ExpressionEngine.ts) ──
|
|
323
|
+
/** `fromJSON()` handed an object that is not a snapshot at all, or whose serialised-shape version does not match this engine's reader. The versioning gate that refuses an incompatible snapshot clearly rather than restoring it wrongly. See `engine/EngineSnapshot.ts`'s `assertRestorable()`. */
|
|
324
|
+
SNAPSHOT_VERSION_MISMATCH: "SNAPSHOT_VERSION_MISMATCH",
|
|
325
|
+
/** A snapshot with the right envelope but internally inconsistent contents (an unrecognised number sentinel, an unknown value tag). Distinct from a version mismatch: the format is right, the payload is not. */
|
|
326
|
+
SNAPSHOT_MALFORMED: "SNAPSHOT_MALFORMED",
|
|
327
|
+
/** A value the v1 snapshot format cannot yet represent (a symbolic/algebra value, a symbolic matrix cell). Deferred to a follow-up; refused by name rather than dropped silently. */
|
|
328
|
+
SNAPSHOT_UNSUPPORTED_VALUE: "SNAPSHOT_UNSUPPORTED_VALUE",
|
|
314
329
|
// ── Config (constants/Configuration.ts) ──
|
|
315
330
|
CONFIG_PATH_NOT_FOUND: "CONFIG_PATH_NOT_FOUND",
|
|
316
331
|
INVALID_CONFIG_PATH: "INVALID_CONFIG_PATH",
|
|
@@ -337,5 +352,5 @@ var CoreErrorCodes = {
|
|
|
337
352
|
};
|
|
338
353
|
|
|
339
354
|
export { CoreErrorCodes, EngineError, ErrorCategory, ErrorFactory, andThen, combine, err, isErr, isOk, map, mapErr, match, normalizeUnknownError, ok, throwIfErr, tryCatch, tryCatchAsync, unwrapOr };
|
|
340
|
-
//# sourceMappingURL=chunk-
|
|
341
|
-
//# sourceMappingURL=chunk-
|
|
355
|
+
//# sourceMappingURL=chunk-ERCOHGXD.js.map
|
|
356
|
+
//# sourceMappingURL=chunk-ERCOHGXD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors/EngineError.ts","../src/errors/Result.ts","../src/errors/ErrorCode.ts"],"names":["ErrorCategory"],"mappings":";AA6BO,IAAK,aAAA,qBAAAA,cAAAA,KAAL;AAEL,EAAAA,eAAA,SAAA,CAAA,GAAU,SAAA;AAEV,EAAAA,eAAA,WAAA,CAAA,GAAY,WAAA;AAEZ,EAAAA,eAAA,YAAA,CAAA,GAAa,YAAA;AAEb,EAAAA,eAAA,UAAA,CAAA,GAAW,UAAA;AAEX,EAAAA,eAAA,UAAA,CAAA,GAAW,UAAA;AAEX,EAAAA,eAAA,QAAA,CAAA,GAAS,QAAA;AAZC,EAAA,OAAAA,cAAAA;AAAA,CAAA,EAAA,aAAA,IAAA,EAAA;AAmEL,IAAM,WAAA,GAAN,MAAM,YAAA,SAAoB,KAAA,CAAM;AAAA,EAsBrC,WAAA,CAAY,UAAyB,IAAA,EAAuB;AAC1D,IAAA,KAAA,CAAM,KAAK,OAAO,CAAA;AAClB,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAChB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,WAAW,IAAA,CAAK,QAAA;AACrB,IAAA,IAAA,CAAK,QAAQ,IAAA,CAAK,KAAA;AAClB,IAAA,IAAA,CAAK,aAAa,IAAA,CAAK,UAAA;AACvB,IAAA,IAAA,CAAK,WAAA,GAAc,KAAK,WAAA,IAAe,IAAA;AACvC,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,UAAU,IAAA,CAAK,OAAA;AACpB,IAAA,IAAA,CAAK,QAAQ,IAAA,CAAK,KAAA;AAClB,IAAA,IAAA,CAAK,S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AAA;AAAA;AAAA,EAE/B,2BAAA,EAA6B,6BAAA;AAAA;AAAA,EAE7B,oBAAA,EAAsB,sBAAA;AAAA;AAAA;AAAA,EAItB,yBAAA,EAA2B,2BAAA;AAAA;AAAA,EAE3B,kBAAA,EAAoB,oBAAA;AAAA;AAAA,EAEpB,0BAAA,EAA4B,4BAAA;AAAA;AAAA,EAG5B,qBAAA,EAAuB,uBAAA;AAAA,EACvB,mBAAA,EAAqB,qBAAA;AAAA,EACrB,wBAAA,EAA0B,0BAAA;AAAA,EAC1B,yBAAA,EAA2B,2BAAA;AAAA;AAAA,EAG3B,yBAAA,EAA2B,2BAAA;AAAA,EAC3B,wBAAA,EAA0B,0BAAA;AAAA,EAC1B,qBAAA,EAAuB,uBAAA;AAAA;AAAA,EAEvB,+BAAA,EAAiC,iCAAA;AAAA;AAAA,EAEjC,oCAAA,EAAsC,sCAAA;AAAA;AAAA,EAEtC,qBAAA,EAAuB,uBAAA;AAAA;AAAA,EAEvB,oCAAA,EAAsC,sCAAA;AAAA;AAAA,EAGtC,iBAAA,EAAmB,mBAAA;AAAA,EACnB,qBAAA,EAAuB,uBAAA;AAAA;AAAA,EAGvB,gBAAA,EAAkB,kBAAA;AAAA,EAClB,aAAA,EAAe;AACjB","file":"chunk-ERCOHGXD.js","sourcesContent":["/**\n * The engine's structured error type, the \"Rust/Go-style, verbose, easy to\n * tell the issue\" half of the error-handling redesign (the other half is\n * `Result.ts`).\n *\n * Historical note: an earlier version of this class (`UnifiedErrorFramework.ts`,\n * still the import path most of the codebase uses. See that file, now a\n * pure re-export barrel) had a much larger field set (`severity`,\n * `recovery`, a 5-value enum, `ErrorRecoveryManager`) that was almost\n * entirely dead: nothing downstream ever read `.severity`/`.recovery`,\n * only `.message` reliably survived to a caller. This version is smaller\n * and deliberately keeps only fields something actually consumes.\n */\n\nimport type { ErrorCode } from \"@solve-js/errors/ErrorCode\";\n\n/** A character-offset (and optional line/col) span into the original expression text, for a future \"underline the offending token\" UI, not yet wired to one. */\nexport interface SourceSpan {\n start: number;\n end: number;\n line?: number;\n col?: number;\n}\n\n/**\n * Error classification, kept from the original framework, now actually\n * consulted: it's the `format()` header and lets host code group errors\n * by pipeline stage without string-matching `.code`.\n */\nexport enum ErrorCategory {\n /** Errors during expression parsing. */\n PARSING = \"PARSING\",\n /** Errors during bytecode execution. */\n EXECUTION = \"EXECUTION\",\n /** Errors from input validation (safety limits, config). */\n VALIDATION = \"VALIDATION\",\n /** Errors from external services/APIs (currency rates, weather, stocks). */\n EXTERNAL = \"EXTERNAL\",\n /** Internal engine invariant violations. See `recoverable`'s doc comment. */\n INTERNAL = \"INTERNAL\",\n /** Configuration errors. */\n CONFIG = \"CONFIG\",\n}\n\n/** Fields accepted when constructing an {@link EngineError}. */\nexport interface EngineErrorInit {\n /** Catalog code. See `errors/ErrorCode.ts`. Not a free string: every code used by a BUILT-IN package should be registered there so `ErrorCodeCatalog.spec.ts` can catch collisions/typos. Third-party packages may still use any string here, `EngineError.code`'s runtime type is `string`. */\n code: ErrorCode | (string & {});\n /** Short, single-line, `Error.message`-compatible. Existing `.toThrow(/pattern/)`/`.message` assertions keep working against this field, richer detail goes in `expected`/`found`/`suggestion`, not crammed into this string. */\n message: string;\n /** What the parser/validator/VM expected to see, in plain words, e.g. \"a city name\", \"a 4-digit year\", \"end of expression\". */\n expected?: string;\n /** What was actually found instead, e.g. \"end of expression\", `NUMBER \"5\"`, the offending token's literal text. */\n found?: string;\n /** An actionable, worked-example fix, e.g. `e.g. \"weather in London\"`. Mirrors this codebase's best existing messages (`WEATHER_EXPECTED_CITY`, `AS_CONVERTER_EXPECTED_NAME`). */\n suggestion?: string;\n /**\n * Whether this engine instance is still usable. `true` for everything that\n * went wrong on ONE line, whether the line's fault (bad syntax, an unknown\n * variable, a safety limit exceeded), the environment's (an external API\n * down), or the engine's own (corrupted bytecode, a stack underflow from a\n * buggy plugin). `false` is for the far rarer case where there is no working\n * engine to go on with: a configuration or package-registration failure,\n * which is what `ErrorFactory.config()` is for and the only factory method\n * that still defaults to it.\n *\n * The category answers a different question, and the two used to be answered\n * as one. Category INTERNAL says whose fault this is, the engine's, worth\n * reporting as a bug. `recoverable` says whether the host may carry on, and\n * after an internal slip on one line it may:\n * `__tests__/hardening/RobustnessEngineLifecycle.spec.ts` alternates a\n * throwing line with a good one five hundred times and every answer stays\n * correct. Reporting that as `isFatal()` told a host the opposite, and a host\n * that honours the name would tear a document down over one bad line.\n *\n * This has never gated \"does evaluation of the rest of the document\n * continue\"; with this engine's per-line containment it always does, even for\n * a `recoverable: false` error (see `ARCHITECTURE.md`'s async-batcher/Tier-2\n * hardening notes). It gates what a host is TOLD. See\n * {@link EngineError.isFatal}.\n */\n recoverable?: boolean;\n /** Character-offset span into the source expression, when available. Not yet threaded through every call site, populate opportunistically, don't block on retrofitting every existing throw site. */\n span?: SourceSpan;\n /** Free-form structured context. The one field the pre-existing framework's real consumer (`ThreeTierEvaluator.ts`'s DAG-preservation-on-compile-error path) actually reads, kept name- and shape-compatible on purpose. */\n context?: Record<string, unknown>;\n /** The underlying error this one wraps, if any, passed straight through to native `Error.cause` (ES2022), so Node's default printer, most loggers, and `instanceof Error` tooling understand the chain for free. */\n cause?: unknown;\n}\n\n/**\n * The engine's structured error type. Still a real `Error` subclass (so\n * `throw`/`catch`/`instanceof Error` all keep working exactly as before),\n * but now every field except the removed `severity`/`recovery` pair is\n * something real code reads.\n */\nexport class EngineError extends Error {\n readonly category: ErrorCategory;\n readonly code: string;\n readonly expected?: string;\n readonly found?: string;\n readonly suggestion?: string;\n readonly recoverable: boolean;\n readonly span?: SourceSpan;\n readonly context?: Record<string, unknown>;\n readonly timestamp: Date;\n /**\n * Set explicitly (not via `super(message, {cause})`). This repo's\n * `tsconfig.json` targets ES6/ES5-ES7 lib, which predates TypeScript's\n * ES2022 `Error` constructor `cause`-option overload. `Error.prototype.cause`\n * is still a real runtime feature in every target this engine actually\n * runs in (Node 16.9+, all evergreen browsers, Electron/Obsidian's\n * bundled Chromium) regardless of the TS lib target used to type-check\n * against it, assigning it directly gets the same Node-printer/logger\n * interop with no build-config change needed.\n */\n readonly cause?: unknown;\n\n constructor(category: ErrorCategory, init: EngineErrorInit) {\n super(init.message);\n this.name = \"EngineError\";\n this.category = category;\n this.code = init.code;\n this.expected = init.expected;\n this.found = init.found;\n this.suggestion = init.suggestion;\n this.recoverable = init.recoverable ?? true;\n this.span = init.span;\n this.context = init.context;\n this.cause = init.cause;\n this.timestamp = new Date();\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, EngineError);\n }\n }\n\n /** `!recoverable`. See `EngineErrorInit.recoverable`'s doc comment for what this actually gates (message framing/telemetry, not whether evaluation continues). */\n isFatal(): boolean {\n return !this.recoverable;\n }\n\n /** Walk `.cause` repeatedly, collecting the full chain (this error first). */\n causeChain(): unknown[] {\n const chain: unknown[] = [this];\n let current: unknown = this.cause;\n while (current !== undefined && current !== null) {\n chain.push(current);\n current = current instanceof Error ? (current as Error & { cause?: unknown }).cause : undefined;\n }\n return chain;\n }\n\n /**\n * Rust/Go-style multi-line renderer, the NEW thing a host/CLI/test\n * reaches for when it wants the full, verbose picture, as distinct from\n * `.message` (kept short and stable for existing assertions). Example:\n *\n * ```\n * error[WEATHER_EXPECTED_CITY]: Expected a city name after \"weather in\"\n * expected: a city name\n * found: end of expression\n * suggestion: e.g. \"weather in London\"\n * ```\n */\n format(): string {\n const lines = [`error[${this.code}]: ${this.message}`];\n if (this.expected) lines.push(` expected: ${this.expected}`);\n if (this.found) lines.push(` found: ${this.found}`);\n if (this.suggestion) lines.push(` suggestion: ${this.suggestion}`);\n return lines.join(\"\\n\");\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n category: this.category,\n code: this.code,\n message: this.message,\n expected: this.expected,\n found: this.found,\n suggestion: this.suggestion,\n recoverable: this.recoverable,\n span: this.span,\n context: this.context,\n timestamp: this.timestamp.toISOString(),\n };\n }\n}\n\n/**\n * Factory for creating classified `EngineError`s. Every method accepts\n * EITHER the original, minimal 3-arg shape (`code, message, context?`\n * every existing call site across the codebase keeps compiling unchanged)\n * OR the richer `EngineErrorInit` object (for `expected`/`found`/\n * `suggestion`/`recoverable`/`span`/`cause`), upgrade a call site to the\n * richer form only when you're already touching it, no separate churn\n * pass required.\n */\nexport class ErrorFactory {\n private static build(\n category: ErrorCategory,\n defaultRecoverable: boolean,\n codeOrInit: string | EngineErrorInit,\n message?: string,\n context?: Record<string, unknown>,\n ): EngineError {\n const init: EngineErrorInit =\n typeof codeOrInit === \"string\"\n ? { code: codeOrInit, message: message!, context }\n : codeOrInit;\n return new EngineError(category, { recoverable: defaultRecoverable, ...init });\n }\n\n static validation(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static validation(init: EngineErrorInit): EngineError;\n static validation(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.VALIDATION, true, codeOrInit, message, context);\n }\n\n static parsing(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static parsing(init: EngineErrorInit): EngineError;\n static parsing(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.PARSING, true, codeOrInit, message, context);\n }\n\n static execution(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static execution(init: EngineErrorInit): EngineError;\n static execution(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.EXECUTION, true, codeOrInit, message, context);\n }\n\n static external(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static external(init: EngineErrorInit): EngineError;\n static external(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.EXTERNAL, true, codeOrInit, message, context);\n }\n\n /**\n * Reserve for genuine engine-internal invariant violations (corrupted\n * bytecode, a stack underflow from a buggy plugin, an \"impossible\" state),\n * not for user-input errors: the category is a bug report.\n *\n * Defaults `recoverable: true` all the same, because every one of these sites\n * is an invariant that failed on ONE line and none of them leaves the engine\n * unusable. This used to default to `false`, which conflated \"the engine's\n * fault\" with \"the engine is finished\" and told a host to tear a document\n * down over a line it could simply have shown an error against. A site that\n * has looked at its own case and concluded the instance really is gone can\n * still pass `recoverable: false` explicitly. See {@link\n * EngineErrorInit.recoverable}.\n */\n static internal(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static internal(init: EngineErrorInit): EngineError;\n static internal(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.INTERNAL, true, codeOrInit, message, context);\n }\n\n /** Defaults `recoverable: false`, and is now the only method that does: a configuration or package-registration failure is the one class that leaves no working engine to carry on with, rather than one bad line in a document. */\n static config(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static config(init: EngineErrorInit): EngineError;\n static config(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.CONFIG, false, codeOrInit, message, context);\n }\n}\n\n/**\n * Normalize any thrown value into an `EngineError`, an `EngineError`\n * passes through as-is; a plain `Error` gets wrapped (message preserved,\n * original attached via `cause`); anything else becomes a generic\n * \"unknown error\" wrapping the stringified value. Used at every\n * throw-space/Result-space boundary (`Result.tryCatch`'s default\n * `normalize`, the VM's outer execution try/catch, `AsyncResolutionBatcher`'s\n * per-line containment) so a raw `TypeError` from a genuine engine bug\n * still surfaces as a structured, catalogued error instead of an opaque\n * uncaught exception.\n *\n * Both branches state RECOVERABLE explicitly, while keeping the INTERNAL\n * category. The two fields answer different questions and were previously\n * answering the same one:\n *\n * category INTERNAL whose fault is this? The engine's. Worth reporting.\n * recoverable is this engine instance still usable? Yes.\n *\n * Everything reaching here is by definition something the engine did not\n * anticipate on ONE line, and per-line containment means the next line\n * evaluates normally, which `__tests__/hardening/RobustnessEngineLifecycle`\n * demonstrates over hundreds of alternating failure/success pairs. Reporting\n * that as `isFatal()` told a host the opposite, and a host that honours the\n * name would tear a document down over a single bad line. The \"this is an\n * engine bug rather than your syntax\" signal a caller wants for telemetry is\n * the CATEGORY, which is unchanged.\n *\n * The flag is written out here rather than inherited from\n * `ErrorFactory.internal()`, which now defaults the same way, so that this\n * function's contract survives a future change to that default.\n */\nexport function normalizeUnknownError(error: unknown): EngineError {\n if (error instanceof EngineError) return error;\n if (error instanceof Error) {\n return ErrorFactory.internal({\n code: \"UNEXPECTED_ERROR\",\n message: error.message,\n context: { originalErrorName: error.name },\n cause: error,\n recoverable: true,\n });\n }\n return ErrorFactory.internal({\n code: \"UNKNOWN_ERROR\",\n message: \"An unknown error occurred\",\n context: { error: String(error) },\n recoverable: true,\n });\n}\n","import { type EngineError, normalizeUnknownError } from \"@solve-js/errors/EngineError\";\n\n/**\n * A Rust-style `Result<T, E>`, the value half of this engine's error-handling\n * redesign. `E` defaults to `EngineError` (this engine's structured error\n * type) but every combinator here is generic over `E`, so `Result` works\n * equally well for a domain that isn't `EngineError`-shaped.\n *\n * This exact shape used to live in `errors/UnifiedErrorFramework.ts` (kept\n * there as a barrel re-export for backward compatibility), moved here as\n * its own module because it's genuinely generic (no dependency on\n * `EngineError` beyond the default type parameter) and because the engine\n * is migrating callers to it incrementally: parsing/VM/package code that\n * expects \"a failure is a possibility, not an exception\" returns\n * `Result<T, EngineError>` instead of throwing; two explicit adapters\n * {@link throwIfErr} and {@link tryCatch}, are the sanctioned way to cross\n * the boundary between Result-based code and still-throw-based code during\n * the migration (and permanently, at the public API boundary. See\n * `ExpressionEngine.evaluateExpression()`'s documented throw contract).\n */\nexport type Result<T, E = EngineError> =\n | { ok: true; value: T }\n | { ok: false; error: E };\n\n/** Wrap a successful value. */\nexport function ok<T>(value: T): Result<T, never> {\n return { ok: true, value };\n}\n\n/** Wrap a failure. */\nexport function err<E>(error: E): Result<never, E> {\n return { ok: false, error };\n}\n\n/**\n * Narrow a {@link Result} to its success arm.\n *\n * @param r - The result to test.\n * @returns True when it succeeded, narrowing `r` so `r.value` is reachable.\n */\nexport function isOk<T, E>(r: Result<T, E>): r is { ok: true; value: T } {\n return r.ok;\n}\n\n/**\n * Narrow a {@link Result} to its failure arm.\n *\n * @param r - The result to test.\n * @returns True when it failed, narrowing `r` so `r.error` is reachable.\n */\nexport function isErr<T, E>(r: Result<T, E>): r is { ok: false; error: E } {\n return !r.ok;\n}\n\n/** Transform the success value; a failure passes through untouched. */\nexport function map<T, U, E>(r: Result<T, E>, fn: (value: T) => U): Result<U, E> {\n return r.ok ? ok(fn(r.value)) : r;\n}\n\n/** Transform the error; a success passes through untouched. */\nexport function mapErr<T, E, F>(r: Result<T, E>, fn: (error: E) => F): Result<T, F> {\n return r.ok ? r : err(fn(r.error));\n}\n\n/** Chain a Result-returning operation onto a success (a.k.a. flatMap/bind). */\nexport function andThen<T, U, E>(r: Result<T, E>, fn: (value: T) => Result<U, E>): Result<U, E> {\n return r.ok ? fn(r.value) : r;\n}\n\n/** Unwrap a success, or return `fallback` for a failure. Never throws. */\nexport function unwrapOr<T, E>(r: Result<T, E>, fallback: T): T {\n return r.ok ? r.value : fallback;\n}\n\n/** Exhaustive pattern-match, the `match`/`switch` a Rust enum gets for free. */\nexport function match<T, E, R>(r: Result<T, E>, arms: { ok: (value: T) => R; err: (error: E) => R }): R {\n return r.ok ? arms.ok(r.value) : arms.err(r.error);\n}\n\n/**\n * Combine several Results into one, succeeds with a tuple of all values\n * iff every input succeeded; otherwise fails with the FIRST error\n * encountered (left-to-right), matching this codebase's existing\n * fail-fast convention elsewhere (e.g. `BytecodeBuilder`'s constant-pool\n * limit checks).\n */\nexport function combine<T extends readonly unknown[], E>(\n results: { [K in keyof T]: Result<T[K], E> },\n): Result<T, E> {\n const values: unknown[] = [];\n for (const r of results as readonly Result<unknown, E>[]) {\n if (!r.ok) return r;\n values.push(r.value);\n }\n return ok(values as unknown as T);\n}\n\n/**\n * Cross from Result-space back to throw-space, the sanctioned boundary\n * adapter for callers (public API surface, older not-yet-migrated code,\n * tests) that still want exception-based control flow. Throws `r.error`\n * as-is (an `EngineError` is already a real `Error` subclass, so this\n * needs no wrapping).\n */\nexport function throwIfErr<T, E>(r: Result<T, E>): T {\n if (r.ok) return r.value;\n throw r.error;\n}\n\n/**\n * Cross from throw-space into Result-space, runs `fn`, converting any\n * thrown value into a Result via `normalize` (defaults to\n * {@link normalizeUnknownError}). The inverse of {@link throwIfErr}; the\n * pairing that lets Result-based and throw-based code interoperate during\n * an incremental migration instead of requiring a single flag-day rewrite.\n */\nexport function tryCatch<T>(\n fn: () => T,\n normalize: (e: unknown) => EngineError = normalizeUnknownError,\n): Result<T, EngineError> {\n try {\n return ok(fn());\n } catch (e) {\n return err(normalize(e));\n }\n}\n\n/** Async sibling of {@link tryCatch}. */\nexport async function tryCatchAsync<T>(\n fn: () => Promise<T>,\n normalize: (e: unknown) => EngineError = normalizeUnknownError,\n): Promise<Result<T, EngineError>> {\n try {\n return ok(await fn());\n } catch (e) {\n return err(normalize(e));\n }\n}\n","/**\n * The built-in error-code catalog, one typed const object per domain\n * unioned together here for autocomplete/exhaustiveness in core engine\n * code. Deliberately NOT one central enum: `IEnginePackage` is documented\n * public SDK surface for third-party packages (see `api/PackageRegistry.ts`),\n * and a closed enum would block an external package author from defining\n * their own codes without editing this file. `EngineError.code`'s runtime\n * type stays `string` for exactly that reason. This catalog is for the\n * codes THIS repo owns and wants collision/typo checking on (see\n * `__tests__/errors/ErrorCodeCatalog.spec.ts`), not a hard runtime\n * whitelist.\n *\n * As each package migrates to `Result<void, EngineError>` (see this\n * session's error-handling-refactor plan, Phase 5), it should export its\n * own small `XxxErrorCodes` const object co-located with its parselets\n * exactly like `CoreErrorCodes` below, just scoped to one domain, and get\n * unioned into `ErrorCode` here. Until a package migrates, its existing\n * free-string codes keep working (ErrorFactory accepts any string); they\n * just aren't caught by the catalog's uniqueness/orphan checks yet.\n */\n\n/**\n * Codes used directly by the parser/VM/engine/errors layers themselves\n * confirmed against the current source, not aspirational. Grouped by\n * pipeline stage via the comments, not a naming prefix (these predate any\n * naming convention and renaming them is out of scope for introducing the\n * catalog, only NEW codes need to follow a scoped/prefixed style, see\n * `STACK_UNDERFLOW` etc. below).\n */\nexport const CoreErrorCodes = {\n // ── Parser (parser/PrecedenceParser.ts, parser/BytecodeBuilder.ts, parser/PhrasePattern.ts) ──\n INVALID_NUMBER_LITERAL: \"INVALID_NUMBER_LITERAL\",\n /** A `\"` that never meets its closing partner (`lexer/ExpressionLexer.ts`'s `tokenizeString()`). Previously the tokenizer ran off the end of the input and returned what it had, so `\"abc` lexed to an ordinary String and an unterminated literal was indistinguishable from a terminated one. */\n UNTERMINATED_STRING: \"UNTERMINATED_STRING\",\n NO_PREFIX_PARSELET: \"NO_PREFIX_PARSELET\",\n UNEXPECTED_END_OF_INPUT: \"UNEXPECTED_END_OF_INPUT\",\n UNEXPECTED_TOKEN_TYPE: \"UNEXPECTED_TOKEN_TYPE\",\n NESTING_DEPTH_EXCEEDED: \"NESTING_DEPTH_EXCEEDED\",\n UNEXPECTED_END: \"UNEXPECTED_END\",\n UNEXPECTED_TRAILING_TOKEN: \"UNEXPECTED_TRAILING_TOKEN\",\n PARSE_ERROR: \"PARSE_ERROR\",\n TOO_MANY_NUMERIC_CONSTANTS: \"TOO_MANY_NUMERIC_CONSTANTS\",\n TOO_MANY_STRING_CONSTANTS: \"TOO_MANY_STRING_CONSTANTS\",\n NO_MATCHING_PHRASE_ALTERNATIVE: \"NO_MATCHING_PHRASE_ALTERNATIVE\",\n INVALID_PHRASE_PATTERN: \"INVALID_PHRASE_PATTERN\",\n PHRASE_KEYWORD_MISMATCH: \"PHRASE_KEYWORD_MISMATCH\",\n /** User-defined-function definition parsing (`f(x, y) = ...`), an invalid token where a parameter name was expected. */\n USER_FUNCTION_INVALID_PARAM_NAME: \"USER_FUNCTION_INVALID_PARAM_NAME\",\n /** `f() = ...` with zero parameters, indistinguishable from a plain no-arg function call, so rejected at definition time. */\n USER_FUNCTION_NO_PARAMS: \"USER_FUNCTION_NO_PARAMS\",\n /** A user-defined function body calling an async plugin (weather/stocks/currency/...), rejected at definition time; v1 scope excludes async function bodies. */\n FUNCTION_BODY_MUST_BE_SYNCHRONOUS: \"FUNCTION_BODY_MUST_BE_SYNCHRONOUS\",\n /** `BytecodeBuilder`'s `userFunctionBodies` side-table exceeding its capacity. Same class as `TOO_MANY_NUMERIC_CONSTANTS`/`TOO_MANY_STRING_CONSTANTS` below. */\n TOO_MANY_FUNCTION_DEFINITIONS: \"TOO_MANY_FUNCTION_DEFINITIONS\",\n /** `BytecodeBuilder`'s `anonymousBodies` side-table (map/reduce inline transform bodies) exceeding its capacity. Same class as `TOO_MANY_FUNCTION_DEFINITIONS` above. */\n TOO_MANY_ANONYMOUS_BODIES: \"TOO_MANY_ANONYMOUS_BODIES\",\n\n // ── VM (vm/VM.ts, vm/OpRegistry.ts, vm/VMBuiltins.ts) ──\n EVALUATION_ERROR: \"EVALUATION_ERROR\",\n INSTRUCTION_LIMIT_EXCEEDED: \"INSTRUCTION_LIMIT_EXCEEDED\",\n STACK_LIMIT_EXCEEDED: \"STACK_LIMIT_EXCEEDED\",\n /** One evaluation asking for more elements (collection Values, matrix cells) than `vm.maxAllocatedElements` allows. The counter the two limits above cannot be: both are checked between opcodes, so neither can see what a single opcode allocates inside a loop of its own. See `vm/AllocationBudget.ts`. Recoverable, since it describes this expression rather than the engine. */\n ALLOCATION_LIMIT_EXCEEDED: \"ALLOCATION_LIMIT_EXCEEDED\",\n /** New this phase. See `VM.ts`'s `safePop()`: a stack-underflow (corrupted bytecode, a buggy plugin) is now a controlled EngineError instead of a raw TypeError. Category INTERNAL, since it is an engine or plugin fault rather than a typed line, but recoverable: it happened on one line and the engine is still usable. */\n STACK_UNDERFLOW: \"STACK_UNDERFLOW\",\n UNDEFINED_VARIABLE: \"UNDEFINED_VARIABLE\",\n /** New this phase, the Tier-2/`LOAD_GLOBAL_VAR` hardening: a global variable read before its async preflight resolved, surfaced as a controlled error instead of pushing `undefined`. */\n GLOBAL_VARIABLE_NOT_RESOLVED: \"GLOBAL_VARIABLE_NOT_RESOLVED\",\n UNKNOWN_FUNCTION: \"UNKNOWN_FUNCTION\",\n /** `unwrapEvalResult()`'s pending-when-expecting-value case, a caller-contract violation, not user-input. */\n UNEXPECTED_PENDING_RESULT: \"UNEXPECTED_PENDING_RESULT\",\n /** User-defined-function call/definition errors (`CALL_USER_FUNCTION`/`DEFINE_USER_FUNCTION` opcodes), calling a name with no matching definition, calling with the wrong argument count, and the deliberate v1 restriction that a function body can't itself contain async work. */\n UNDEFINED_FUNCTION: \"UNDEFINED_FUNCTION\",\n FUNCTION_ARITY_MISMATCH: \"FUNCTION_ARITY_MISMATCH\",\n /** The same mistake against a BUILT-IN rather than a user-defined function (`sqrt()`, `atan2(1)`, `sqrt(1,2,3)`). Separate from `FUNCTION_ARITY_MISMATCH` above because the two are raised by different opcodes and a host may want to word them differently. Checked at the `CALL_BUILTIN` dispatch against `vm/VMBuiltinArity.ts`; recoverable, since it is a typo in the line, not an engine fault. */\n BUILTIN_ARITY_MISMATCH: \"BUILTIN_ARITY_MISMATCH\",\n USER_FUNCTION_ASYNC_UNSUPPORTED: \"USER_FUNCTION_ASYNC_UNSUPPORTED\",\n /** A map/reduce transform body (inline expression or user-defined function) calling an async plugin. Same v1 scope restriction as `USER_FUNCTION_ASYNC_UNSUPPORTED` above, enforced both at parse time (`MAP_REDUCE_TRANSFORM_MUST_BE_SYNCHRONOUS`, packages/mapreduce/) and as a defense-in-depth runtime backstop here. */\n MAP_REDUCE_ASYNC_UNSUPPORTED: \"MAP_REDUCE_ASYNC_UNSUPPORTED\",\n /** An algebra verb's expression argument (`BIND_UNKNOWN`'s body) calling an async plugin. Same v1 scope restriction as the two above, and likewise refused at parse time first (`SYMBOLIC_ARGUMENT_MUST_BE_SYNCHRONOUS`, packages/symbolic/). */\n SYMBOLIC_ASYNC_UNSUPPORTED: \"SYMBOLIC_ASYNC_UNSUPPORTED\",\n /** `explainLine()` asked to derive a line that resolves data asynchronously (a live-data or async-plugin line). A derivation is a sequence of settled intermediate values, which a pending result has none of, so the line is refused rather than explained with a hole in it. */\n EXPLAIN_ASYNC_UNSUPPORTED: \"EXPLAIN_ASYNC_UNSUPPORTED\",\n /** `pushCallFrame()`'s recursion guard, a nested `CALL_USER_FUNCTION` re-enters `executeBytecode()`, so `maxInstructions` alone can't catch e.g. `f(x) = f(x)`; this is the dedicated backstop. `recoverable: true` (the default for `.execution()`), ordinary user-written infinite recursion, not an engine bug; the guard exists precisely so it surfaces as a clear error instead of overflowing the native call stack uncatchably. */\n FUNCTION_RECURSION_LIMIT_EXCEEDED: \"FUNCTION_RECURSION_LIMIT_EXCEEDED\",\n /** The companion to the code above, and the half it could never see: how MANY user-defined-function calls one evaluation makes, rather than how deeply they nest. A twenty-two-line doubling chain nests twenty-two deep (legal) and makes two million calls (a fatal heap abort). Counted in `vm/AllocationBudget.ts`, because the tally has to survive `executeBytecode()` re-entering itself. Recoverable. */\n FUNCTION_CALL_LIMIT_EXCEEDED: \"FUNCTION_CALL_LIMIT_EXCEEDED\",\n /** A `<date> + N workdays` offset outside `date.maxOffsetYears`/`minOffsetYears`. Workdays are the one date offset that walks the calendar a day at a time, so the one whose cost is the offset; every other one moves a Date field once. Recoverable. */\n DATE_OFFSET_LIMIT_EXCEEDED: \"DATE_OFFSET_LIMIT_EXCEEDED\",\n /** The anchor of `N working days after/before/from <expr>` was not a date (e.g. `5 working days after 3`). The grammar guarantees the count is a number, so this only fires on the anchor. Emitted as a recoverable Error value, not thrown, matching the datetime package's other type guards. See `vm/VM.ts`'s `DATE_WORKDAY_OFFSET` case. */\n WORKDAY_OFFSET_EXPECTED_DATE: \"WORKDAY_OFFSET_EXPECTED_DATE\",\n /** An endpoint of `working days between <expr> and <expr>` was not a date. Recoverable Error value. See `vm/VM.ts`'s `DATE_WORKDAYS_BETWEEN` case. */\n WORKDAYS_BETWEEN_EXPECTED_DATES: \"WORKDAYS_BETWEEN_EXPECTED_DATES\",\n /** The two endpoints of `working days between <expr> and <expr>` are further apart than `date.maxOffsetYears`/`minOffsetYears` allow the count's calendar walk to run. Recoverable Error value, the between-count's equivalent of `DATE_OFFSET_LIMIT_EXCEEDED`. See `vm/VM.ts`'s `DATE_WORKDAYS_BETWEEN` case. */\n WORKDAYS_BETWEEN_RANGE_TOO_LARGE: \"WORKDAYS_BETWEEN_RANGE_TOO_LARGE\",\n /** A `<<`/`>>` with a bigint operand whose exact result would pass `MAX_EXACT_SHIFT_BITS`, whichever operand is the bigint. Both spellings refuse as of 1.0.0: a bigint on the left used to fall through to `x * 2^n` in doubles and report a 19,870-digit integer as Infinity. See `vm/VM.ts`'s `bigIntShift()`. Recoverable. */\n BIGINT_SHIFT_LIMIT_EXCEEDED: \"BIGINT_SHIFT_LIMIT_EXCEEDED\",\n /** The same ceiling for `^`, the operator it was written for: `2n ^ 100000` asks for the same 100,001-bit integer `1n << 100000` does, so the two spellings answer the same way. Also new in 1.0.0, and for the same reason: this used to fall through to the double path and answer Infinity. A fractional or negative exponent (`4n ^ 0.5`, `2n ^ -1`) has no exact answer to bound and still uses the double path. See `vm/VM.ts`'s `MAX_EXACT_POW_BITS`. Recoverable. */\n BIGINT_POW_LIMIT_EXCEEDED: \"BIGINT_POW_LIMIT_EXCEEDED\",\n /** An operand with no whole-number form (a fraction, an infinity, a NaN) meeting a bigint: `1n + 0.5`, `1n & 1.5`, `5n/pi`. `BigInt()` answers those with a raw RangeError, which the VM relabelled UNEXPECTED_ERROR, so a typo in the line was reported as an engine fault. Recoverable; see `vm/VMConversion.ts`'s `toBigIntOperand()`. */\n BIGINT_INEXACT_OPERAND: \"BIGINT_INEXACT_OPERAND\",\n /** `10n / 0n` and `10n mod 0n`. Deliberately NOT what `1 / 0` does, which is Infinity: a bigint division is exact integer division (`7n / 2n` is 3n), and integer division by zero has no answer, exactly as it has none in C, Java, Python or JavaScript's own BigInt. Previously V8's own RangeError, relabelled UNEXPECTED_ERROR. Recoverable; see `vm/VMConversion.ts`'s `bigIntDivisionByZero()`. */\n BIGINT_DIVISION_BY_ZERO: \"BIGINT_DIVISION_BY_ZERO\",\n /** `DEFINE_USER_FUNCTION`'s body-index lookup failing, a compiler/VM invariant violation (the opcode stream referenced a `userFunctionBodies` slot that doesn't exist), never a user-input error. */\n INTERNAL_MISSING_FUNCTION_BODY: \"INTERNAL_MISSING_FUNCTION_BODY\",\n /** `MAP_INVOKE`/`REDUCE_INVOKE`'s anonymous-body-index lookup failing. Same class as `INTERNAL_MISSING_FUNCTION_BODY` above, for the `anonymousBodies` side-table instead of `userFunctionBodies`. */\n INTERNAL_MISSING_ANONYMOUS_BODY: \"INTERNAL_MISSING_ANONYMOUS_BODY\",\n\n // ── Malformed bytecode on the public `./vm` surface (vm/VM.ts) ──\n //\n // `executeBytecode` is exported, so a bytecode program is caller input in\n // the same sense an expression string is, and these five say so. They are\n // VALIDATION rather than INTERNAL for exactly that reason: before they\n // existed, every one of these cases reached a raw TypeError (`BigInt(undefined)`,\n // `code.toUpperCase()` on a boolean, destructuring a program that was not\n // there), which normalised to UNEXPECTED_ERROR and told the caller the\n // engine was broken when their eleven bytes were. Reachable from ordinary\n // source only through a compiler bug, which is why the messages name the\n // opcode and the operand rather than the user's line.\n /** An operand byte read past the end of the stream: the program ends in the middle of an instruction. */\n MALFORMED_BYTECODE_TRUNCATED: \"MALFORMED_BYTECODE_TRUNCATED\",\n /** A constant-pool operand indexing a `numbers`/`strings` entry that does not exist, or that is not of the pool's type. */\n MALFORMED_BYTECODE_CONSTANT_INDEX: \"MALFORMED_BYTECODE_CONSTANT_INDEX\",\n /** A unit or converter name read off the value stack that is not a string. Distinct from the pool case above: the operand is a Value another opcode pushed, not a pool entry. */\n MALFORMED_BYTECODE_OPERAND_TYPE: \"MALFORMED_BYTECODE_OPERAND_TYPE\",\n /** `MAP_INVOKE`/`REDUCE_INVOKE` carrying a body kind other than 0/1/2. Used to fall through every arm with no body and recurse into `executeBytecode(undefined)`. */\n MALFORMED_BYTECODE_BODY_KIND: \"MALFORMED_BYTECODE_BODY_KIND\",\n /** A `PUSH_BIGINT` pool entry that is not a whole number, e.g. `\"1.000\"`. `BigInt()` answers that with a raw SyntaxError. */\n MALFORMED_BYTECODE_BIGINT_LITERAL: \"MALFORMED_BYTECODE_BIGINT_LITERAL\",\n /** `executeBytecode()` called with something that is not a runnable program at all. Checked before the destructure that used to throw outside the function's own try/catch. */\n MALFORMED_BYTECODE_PROGRAM: \"MALFORMED_BYTECODE_PROGRAM\",\n\n // ── Symbolic algebra (symbolic/, vm/SymbolicOps.ts) ──\n /** A coefficient grew past `RATIONAL_MAX_BITS`, e.g. repeated exact elimination multiplying denominators together. */\n SYMBOLIC_RATIONAL_OVERFLOW: \"SYMBOLIC_RATIONAL_OVERFLOW\",\n /** `NaN` or `±Infinity` reaching a symbolic expression, neither of which has an exact rational value. */\n SYMBOLIC_NONFINITE_OPERAND: \"SYMBOLIC_NONFINITE_OPERAND\",\n /** Division by an exactly-zero rational. Exact, unlike the double comparison it replaced, which could not distinguish a true zero from `5.551e-17`. */\n SYMBOLIC_DIVISION_BY_ZERO: \"SYMBOLIC_DIVISION_BY_ZERO\",\n /** A tree exceeding `SYMBOLIC_MAX_NODES` entering the simplifier. */\n SYMBOLIC_NODE_LIMIT_EXCEEDED: \"SYMBOLIC_NODE_LIMIT_EXCEEDED\",\n /** A builtin with no symbolic reading (`min`, `random`, the finance block, ...) applied to an expression still containing an unknown. Returned rather than computing against `toNumber()`'s placeholder zero. */\n SYMBOLIC_UNSUPPORTED_FUNCTION: \"SYMBOLIC_UNSUPPORTED_FUNCTION\",\n /** The rational-root search exceeding `FACTOR_MAX_ROOT_CANDIDATES`. The candidate set is the product of two divisor sets, so a highly-composite coefficient escapes quickly. */\n SYMBOLIC_FACTOR_LIMIT_EXCEEDED: \"SYMBOLIC_FACTOR_LIMIT_EXCEEDED\",\n /** An equation outside what the solver attempts: not a polynomial, above the degree ceiling, or non-linear in the unknown while another unknown is present. */\n SYMBOLIC_SOLVE_UNSUPPORTED: \"SYMBOLIC_SOLVE_UNSUPPORTED\",\n /** Some but not all of an equation's roots were found. Reported rather than returned, because a partial list of roots looks exactly like a complete one. */\n SYMBOLIC_SOLVE_INCOMPLETE: \"SYMBOLIC_SOLVE_INCOMPLETE\",\n /** `solve`'s second argument not being a bare name. */\n SOLVE_REQUIRES_VARIABLE_NAME: \"SOLVE_REQUIRES_VARIABLE_NAME\",\n /** A derivative order outside 0..`DERIVATIVE_MAX_ORDER`. */\n SYMBOLIC_DERIVATIVE_ORDER_LIMIT: \"SYMBOLIC_DERIVATIVE_ORDER_LIMIT\",\n /** An expression with no known elementary antiderivative. Reported rather than approximated, since a wrong integral is indistinguishable from a right one at the point of use. */\n SYMBOLIC_INTEGRAL_UNSUPPORTED: \"SYMBOLIC_INTEGRAL_UNSUPPORTED\",\n /** A Taylor degree outside 0..`TAYLOR_MAX_DEGREE`. */\n SYMBOLIC_TAYLOR_DEGREE_LIMIT: \"SYMBOLIC_TAYLOR_DEGREE_LIMIT\",\n /** A Taylor coefficient that does not reduce to an exact number at the expansion point. */\n SYMBOLIC_TAYLOR_INEXACT: \"SYMBOLIC_TAYLOR_INEXACT\",\n /** An algebra verb's variable-name argument not being a bare name. */\n SYMBOLIC_REQUIRES_VARIABLE_NAME: \"SYMBOLIC_REQUIRES_VARIABLE_NAME\",\n /** `jacobian` called with expressions containing no unknown to differentiate against. */\n SYMBOLIC_JACOBIAN_NO_VARIABLES: \"SYMBOLIC_JACOBIAN_NO_VARIABLES\",\n /** A finite number whose decimal form could not be read back, which the regex covering every `Number.prototype.toString` output should make unreachable. */\n INTERNAL_RATIONAL_PARSE: \"INTERNAL_RATIONAL_PARSE\",\n\n // ── Engine (engine/ExpressionEngine.ts, engine/ExpressionEngineSafety.ts, engine/AsyncResolutionBatcher.ts) ──\n EXPRESSION_TOO_LONG: \"EXPRESSION_TOO_LONG\",\n EXPRESSION_TOO_COMPLEX: \"EXPRESSION_TOO_COMPLEX\",\n /** A document with more lines than `performance.maxDocumentLines`. The per-line limits above bound what one line may ask for and say nothing about how many lines there are; two hundred thousand of `1 + 1` exhausted the heap on the line records alone. Recoverable. */\n DOCUMENT_TOO_LARGE: \"DOCUMENT_TOO_LARGE\",\n NORMALIZED_TOKEN_LIMIT_EXCEEDED: \"NORMALIZED_TOKEN_LIMIT_EXCEEDED\",\n /** `\"=>\"` with nothing before it, needs an expression or variable name to solve/simplify. */\n THEREFORE_REQUIRES_EXPRESSION: \"THEREFORE_REQUIRES_EXPRESSION\",\n /** A `\"=>\"`-triggered expression called an async plugin (weather/stocks/currency). Same v1 scope restriction as user-function/map-reduce bodies. */\n THEREFORE_ASYNC_UNSUPPORTED: \"THEREFORE_ASYNC_UNSUPPORTED\",\n /** Colon-separated numbers that are not a time any clock can show (\"24:00\", \"9:60\", \"100:5\"). Raised by the labeled-line fallback, which used to answer them with whatever stood after the colon. */\n INVALID_TIME_LITERAL: \"INVALID_TIME_LITERAL\",\n\n // ── Snapshot / restore (engine/EngineSnapshot.ts, engine/ExpressionEngine.ts) ──\n /** `fromJSON()` handed an object that is not a snapshot at all, or whose serialised-shape version does not match this engine's reader. The versioning gate that refuses an incompatible snapshot clearly rather than restoring it wrongly. See `engine/EngineSnapshot.ts`'s `assertRestorable()`. */\n SNAPSHOT_VERSION_MISMATCH: \"SNAPSHOT_VERSION_MISMATCH\",\n /** A snapshot with the right envelope but internally inconsistent contents (an unrecognised number sentinel, an unknown value tag). Distinct from a version mismatch: the format is right, the payload is not. */\n SNAPSHOT_MALFORMED: \"SNAPSHOT_MALFORMED\",\n /** A value the v1 snapshot format cannot yet represent (a symbolic/algebra value, a symbolic matrix cell). Deferred to a follow-up; refused by name rather than dropped silently. */\n SNAPSHOT_UNSUPPORTED_VALUE: \"SNAPSHOT_UNSUPPORTED_VALUE\",\n\n // ── Config (constants/Configuration.ts) ──\n CONFIG_PATH_NOT_FOUND: \"CONFIG_PATH_NOT_FOUND\",\n INVALID_CONFIG_PATH: \"INVALID_CONFIG_PATH\",\n CONFIG_SECTION_NOT_FOUND: \"CONFIG_SECTION_NOT_FOUND\",\n CONFIG_PROPERTY_NOT_FOUND: \"CONFIG_PROPERTY_NOT_FOUND\",\n\n // ── Package/lexer registration-time collisions (lexer/ExpressionLexer.ts) ──\n PLUGIN_OPERATOR_COLLISION: \"PLUGIN_OPERATOR_COLLISION\",\n PLUGIN_KEYWORD_COLLISION: \"PLUGIN_KEYWORD_COLLISION\",\n PLUGIN_UNIT_COLLISION: \"PLUGIN_UNIT_COLLISION\",\n /** A package's declared `IEnginePackage.engineVersion` semver range doesn't satisfy the running engine's ENGINE_VERSION. See api/EngineVersionCompatibility.ts. */\n PACKAGE_ENGINE_VERSION_MISMATCH: \"PACKAGE_ENGINE_VERSION_MISMATCH\",\n /** A package's declared `IEnginePackage.engineVersion` isn't a parseable semver range at all (a typo in the package's own descriptor). */\n PACKAGE_ENGINE_VERSION_INVALID_RANGE: \"PACKAGE_ENGINE_VERSION_INVALID_RANGE\",\n /** `OpRegistry.allocateOpcode()`'s dynamic opcode pool (started at 201) exhausted, too many packages calling it. */\n OPCODE_POOL_EXHAUSTED: \"OPCODE_POOL_EXHAUSTED\",\n /** `VMBuiltins.allocatePluginFunctionIndex()`'s 0-255 index pool (a single opcode-stream byte) exhausted. */\n PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED: \"PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED\",\n\n // ── vm/Value.ts caller-contract violations (check isRateUnit()/isTimecodeUnit() first) ──\n INVALID_RATE_UNIT: \"INVALID_RATE_UNIT\",\n INVALID_TIMECODE_UNIT: \"INVALID_TIMECODE_UNIT\",\n\n // ── errors/EngineError.ts's own fallback normalization ──\n UNEXPECTED_ERROR: \"UNEXPECTED_ERROR\",\n UNKNOWN_ERROR: \"UNKNOWN_ERROR\",\n} as const;\n\n/** Every error code the engine's own layers can produce, from {@link CoreErrorCodes}. */\nexport type CoreErrorCode = (typeof CoreErrorCodes)[keyof typeof CoreErrorCodes];\n\n/**\n * The aggregated catalog type. Currently just `CoreErrorCode`, union in\n * each package's own code-object type here as Phase 5 converts it, e.g.\n * `CoreErrorCode | WeatherErrorCode | StocksErrorCode | ...`.\n */\nexport type ErrorCode = CoreErrorCode;\n"]}
|
|
@@ -87,15 +87,6 @@ var abortLogger = {
|
|
|
87
87
|
}
|
|
88
88
|
};
|
|
89
89
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
for (let i = 0; i < str.length; i++) {
|
|
94
|
-
hash = (hash << 5) + hash + str.charCodeAt(i) | 0;
|
|
95
|
-
}
|
|
96
|
-
return hash >>> 0;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
export { abortLogger, djb2Hash };
|
|
100
|
-
//# sourceMappingURL=chunk-IF532O7C.js.map
|
|
101
|
-
//# sourceMappingURL=chunk-IF532O7C.js.map
|
|
90
|
+
export { abortLogger };
|
|
91
|
+
//# sourceMappingURL=chunk-FD5ZZHEU.js.map
|
|
92
|
+
//# sourceMappingURL=chunk-FD5ZZHEU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utilities/AbortControllerLogger.ts"],"names":[],"mappings":";AA4BA,IAAM,iBAAiB,OAAO,OAAA,KAAY,WAAA,IAAe,OAAA,CAAQ,IAAI,eAAA,KAAoB,MAAA;AAQlF,IAAM,WAAA,GAAc;AAAA;AAAA,EAE1B,IAAI,OAAA,GAAmB;AACtB,IAAA,OAAO,cAAA;AAAA,EACR,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,gBAAA,GAAyB;AACxB,IAAA,IAAI,CAAC,cAAA,EAAgB;AACrB,IAAA,OAAA,CAAQ,MAAM,+BAA+B,CAAA;AAAA,EAC9C,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,iBAAiB,MAAA,EAAsB;AACtC,IAAA,IAAI,CAAC,cAAA,EAAgB;AACrB,IAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,+BAAA,EAAkC,MAAM,CAAA,CAAE,CAAA;AAAA,EACzD,CAAA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KACnD;AAAA,EACD;AACD","file":"chunk-FD5ZZHEU.js","sourcesContent":["/**\n * Debug logging for the AbortController lifecycle in the \"One AbortController\n * Per Keystroke\" pattern.\n *\n * Enabled when `process.env.DEBUG_ABORTCTRL === \"true\"`.\n *\n * This is **opt-in only**, even in development mode you must explicitly\n * set the flag to avoid log noise from large documents.\n *\n * Logs controller creation, abortion, signal linking, keystroke signal\n * propagation, and stale-data discard guards. All messages are output via\n * `console.debug` with an `[AbortCtrl]` prefix so they can be filtered\n * in the DevTools console.\n *\n * ── Usage ─────────────────────────────────────────────────────────────\n * import { abortLogger } from \"@solve-js/utilities/AbortControllerLogger\";\n *\n * // Enable explicitly (before the plugin boots):\n * // process.env.DEBUG_ABORTCTRL = \"true\";\n *\n * abortLogger.keystrokeCreated();\n * abortLogger.localControllerCreated(\"executeAndStore\");\n * abortLogger.signalLinked(\"executeAndStore\", \"keystroke\");\n * abortLogger.keystrokeAborted(\"New keystroke\");\n * abortLogger.staleDataDiscarded(\"USD:GBP\", \"signal aborted\");\n * abortLogger.keystrokeSignalSet(true); // signal set, not aborted\n * abortLogger.keystrokeSignalCleared();\n */\nconst isDebugEnabled = typeof process !== \"undefined\" && process.env.DEBUG_ABORTCTRL === \"true\";\n\n/**\n * Records abort-signal lifecycle for debugging cancellation.\n *\n * Keystroke cancellation is hard to reason about after the fact, because the\n * evidence is gone by the time anything looks wrong. This keeps it.\n */\nexport const abortLogger = {\n\t/** Whether debug logging is currently active. */\n\tget enabled(): boolean {\n\t\treturn isDebugEnabled;\n\t},\n\n\t// ── Keystroke-level controller (MarkdownEditorViewPlugin) ──────\n\n\t/**\n\t * Log creation of the keystroke-level AbortController.\n\t * Called in the plugin constructor and on each new keystroke.\n\t */\n\tkeystrokeCreated(): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(\"[AbortCtrl] KEYSTROKE CREATED\");\n\t},\n\n\t/**\n\t * Log abortion of the keystroke-level AbortController.\n\t * @param reason Why the keystroke was aborted (e.g. \"New keystroke\",\n\t * \"Document switch\", \"Plugin destroyed\").\n\t */\n\tkeystrokeAborted(reason: string): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(`[AbortCtrl] KEYSTROKE ABORTED: ${reason}`);\n\t},\n\n\t// ── Local per-evaluation controllers (ExpressionEngine) ─────────\n\n\t/**\n\t * Log creation of a local AbortController that is linked to the\n\t * keystroke signal.\n\t * @param source Which code path created the controller\n\t * (e.g. \"executeAndStore\", \"executeRaw\", \"preflight\", \"vm\").\n\t */\n\tlocalControllerCreated(source: string): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(`[AbortCtrl] LOCAL CREATED (${source})`);\n\t},\n\n\t/**\n\t * Log that a local AbortController was linked to the keystroke signal.\n\t * When the keystroke signal is aborted, this local controller will\n\t * be aborted automatically.\n\t * @param source The code path that created the controller.\n\t */\n\tsignalLinked(source: string): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(`[AbortCtrl] LOCAL LINKED (${source}) → keystroke`);\n\t},\n\n\t/**\n\t * Log that a local AbortController's listener was removed from the\n\t * keystroke signal (cleanup).\n\t * @param source The code path.\n\t */\n\tsignalUnlinked(source: string): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(`[AbortCtrl] LOCAL UNLINKED (${source})`);\n\t},\n\n\t// ── Keystroke signal propagation (ThreeTierEvaluator → ExpressionEngine) ──\n\n\t/**\n\t * Log that the keystroke signal was propagated INTO the engine.\n\t * @param isAborted Whether the signal was already aborted when set.\n\t */\n\tkeystrokeSignalSet(isAborted: boolean): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(\n\t\t\t`[AbortCtrl] KEYSTROKE_SIGNAL → engine (aborted=${isAborted})`,\n\t\t);\n\t},\n\n\t/**\n\t * Log that the keystroke signal was CLEARED from the engine\n\t * (typically in the evaluator's finally block).\n\t */\n\tkeystrokeSignalCleared(): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(\"[AbortCtrl] KEYSTROKE_SIGNAL cleared (null)\");\n\t},\n\n\t// ── Stale-data discard guards (resolveAsync) ────────────────────\n\n\t/**\n\t * Log that a stale async result was discarded because its signal\n\t * was aborted.\n\t * @param queryKey The cache key for the discarded result.\n\t * @param context Additional context (e.g. \"after await\", \"after error\").\n\t */\n\tstaleDataDiscarded(queryKey: string, context: string): void {\n\t\tif (!isDebugEnabled) return;\n\t\tconsole.debug(\n\t\t\t`[AbortCtrl] STALE DISCARD: ${queryKey} (${context})`,\n\t\t);\n\t},\n};\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { ErrorFactory } from './chunk-
|
|
1
|
+
import { ErrorFactory } from './chunk-ERCOHGXD.js';
|
|
2
2
|
|
|
3
3
|
// package.json
|
|
4
|
-
var version = "1.
|
|
4
|
+
var version = "1.1.1";
|
|
5
5
|
|
|
6
6
|
// src/constants/version.ts
|
|
7
7
|
var ENGINE_VERSION = version;
|
|
@@ -58,7 +58,13 @@ var DEFAULT_CONFIG = {
|
|
|
58
58
|
// the calls it does allow cost single-digit megabytes rather than the
|
|
59
59
|
// heap. A document that needs more than ten thousand calls on one line
|
|
60
60
|
// is doing something a calculator was not built for.
|
|
61
|
-
maxFunctionCalls: 1e4
|
|
61
|
+
maxFunctionCalls: 1e4,
|
|
62
|
+
// A hundred bisection steps resolve an input to one part in 2^100, far
|
|
63
|
+
// finer than any document needs and a firm stop for an untrusted one. A
|
|
64
|
+
// continuous, monotonic relationship converges in tens of steps, well
|
|
65
|
+
// under this; hitting it means the target is unreachable or the
|
|
66
|
+
// relationship is not the smooth one goal seek assumes.
|
|
67
|
+
maxGoalSeekIterations: 100
|
|
62
68
|
},
|
|
63
69
|
worker: {
|
|
64
70
|
maxConcurrentWorkers: 4,
|
|
@@ -194,5 +200,5 @@ var ConfigManager = class {
|
|
|
194
200
|
};
|
|
195
201
|
|
|
196
202
|
export { ConfigManager, DEFAULT_CONFIG, ENGINE_VERSION, mergeEngineConfig };
|
|
197
|
-
//# sourceMappingURL=chunk-
|
|
198
|
-
//# sourceMappingURL=chunk-
|
|
203
|
+
//# sourceMappingURL=chunk-GLA4JXBO.js.map
|
|
204
|
+
//# sourceMappingURL=chunk-GLA4JXBO.js.map
|