solve-engine 2.14.0 → 2.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{BytecodeBuilder-BGq9ZiO3.d.cts → BytecodeBuilder-CRYfrFfq.d.cts} +2 -1
- package/dist/{BytecodeBuilder-BGq9ZiO3.d.ts → BytecodeBuilder-CRYfrFfq.d.ts} +2 -1
- package/dist/{EngineError-Ce1lPkjZ.d.cts → EngineError-Cv5q4Rbv.d.cts} +3 -1
- package/dist/{EngineError-Ce1lPkjZ.d.ts → EngineError-Cv5q4Rbv.d.ts} +3 -1
- package/dist/{Lexer-B4C1qHXu.d.cts → Lexer-CCHFDcgP.d.cts} +1 -1
- package/dist/{Lexer-DKMlj7Sy.d.ts → Lexer-CqagTewQ.d.ts} +1 -1
- package/dist/{PackageCompatibility-BG0iur4I.d.cts → PackageCompatibility-C2IQZ_w3.d.cts} +1 -1
- package/dist/{PackageCompatibility-BlIcQg5v.d.ts → PackageCompatibility-Cl7GF_Iu.d.ts} +1 -1
- package/dist/{PackageRegistry-BJ0QQd3k.d.ts → PackageRegistry-CK_JoX50.d.ts} +14 -7
- package/dist/{PackageRegistry-DeGDZkNt.d.cts → PackageRegistry-CZO1IbS-.d.cts} +14 -7
- package/dist/{Parselet-Blq8B0Gj.d.ts → Parselet-CK0bNO1l.d.ts} +2 -2
- package/dist/{Parselet-BSndkWEY.d.cts → Parselet-DOGmj6N6.d.cts} +2 -2
- package/dist/{ScopeManager-D8nLv--u.d.cts → ScopeManager-BtqiTVjG.d.cts} +3 -3
- package/dist/{ScopeManager-CF3cZUqW.d.ts → ScopeManager-C6c1WmJD.d.ts} +3 -3
- package/dist/{TokenNormalizer-DnlL7_8c.d.cts → TokenNormalizer-BfTHg1qt.d.cts} +35 -0
- package/dist/{TokenNormalizer-DCWdZjGz.d.ts → TokenNormalizer-d7F1KQFs.d.ts} +35 -0
- package/dist/{VMCheckpoints-Dy39SVHa.d.cts → VMCheckpoints-BFDlaGse.d.cts} +2 -2
- package/dist/{VMCheckpoints-BsR5_auF.d.ts → VMCheckpoints-DJdvpliw.d.ts} +2 -2
- package/dist/{WorkerError-B4p6PNfx.d.cts → WorkerError-FH7KXX4_.d.cts} +1 -1
- package/dist/{WorkerError-Dhj9BQ_A.d.ts → WorkerError-J3v3ix_z.d.ts} +1 -1
- package/dist/{chunk-75XDS65A.cjs → chunk-2XZCLDHJ.cjs} +2 -2
- package/dist/chunk-2XZCLDHJ.cjs.map +1 -0
- package/dist/{chunk-BW6FR7DA.js → chunk-3PDDKWTJ.js} +3 -3
- package/dist/{chunk-BW6FR7DA.js.map → chunk-3PDDKWTJ.js.map} +1 -1
- package/dist/{chunk-3MBENI4Q.cjs → chunk-3Y56PSQD.cjs} +3 -3
- package/dist/{chunk-3MBENI4Q.cjs.map → chunk-3Y56PSQD.cjs.map} +1 -1
- package/dist/{chunk-YOHM2WQT.js → chunk-4IIFFJTJ.js} +4 -4
- package/dist/chunk-4IIFFJTJ.js.map +1 -0
- package/dist/chunk-5SDSIRPL.js +2 -0
- package/dist/chunk-5SDSIRPL.js.map +1 -0
- package/dist/{chunk-PNDQRCRQ.cjs → chunk-6U66HQKQ.cjs} +2 -2
- package/dist/chunk-6U66HQKQ.cjs.map +1 -0
- package/dist/{chunk-VBSMA7WJ.cjs → chunk-ABVDKMNF.cjs} +2 -2
- package/dist/chunk-ABVDKMNF.cjs.map +1 -0
- package/dist/chunk-AYTEPHRO.js +3 -0
- package/dist/chunk-AYTEPHRO.js.map +1 -0
- package/dist/chunk-C5MP74ER.js +2 -0
- package/dist/chunk-C5MP74ER.js.map +1 -0
- package/dist/{chunk-JQBG3LX4.js → chunk-CUDPOWXA.js} +2 -2
- package/dist/{chunk-JQBG3LX4.js.map → chunk-CUDPOWXA.js.map} +1 -1
- package/dist/{chunk-LUMVKVFQ.cjs → chunk-EEUA3OJ6.cjs} +2 -2
- package/dist/{chunk-LUMVKVFQ.cjs.map → chunk-EEUA3OJ6.cjs.map} +1 -1
- package/dist/chunk-EEVUKZ5B.cjs +2 -0
- package/dist/{chunk-EURCQMZK.cjs.map → chunk-EEVUKZ5B.cjs.map} +1 -1
- package/dist/{chunk-3HYO3QYW.cjs → chunk-EXCFCHAT.cjs} +2 -2
- package/dist/{chunk-3HYO3QYW.cjs.map → chunk-EXCFCHAT.cjs.map} +1 -1
- package/dist/chunk-FAGFPVYK.cjs +2 -0
- package/dist/chunk-FAGFPVYK.cjs.map +1 -0
- package/dist/chunk-FPGYRFJY.cjs +5 -0
- package/dist/chunk-FPGYRFJY.cjs.map +1 -0
- package/dist/chunk-FVQWN5HZ.cjs +2 -0
- package/dist/chunk-FVQWN5HZ.cjs.map +1 -0
- package/dist/{chunk-4BZIYU7S.cjs → chunk-GWCBPITD.cjs} +3 -3
- package/dist/{chunk-4BZIYU7S.cjs.map → chunk-GWCBPITD.cjs.map} +1 -1
- package/dist/{chunk-YAYBVVG2.js → chunk-GWJJRH32.js} +3 -3
- package/dist/{chunk-YAYBVVG2.js.map → chunk-GWJJRH32.js.map} +1 -1
- package/dist/chunk-HDGARCI2.cjs +2 -0
- package/dist/chunk-HDGARCI2.cjs.map +1 -0
- package/dist/{chunk-MVP2YD4X.cjs → chunk-HG4NPDN5.cjs} +2 -2
- package/dist/{chunk-MVP2YD4X.cjs.map → chunk-HG4NPDN5.cjs.map} +1 -1
- package/dist/{chunk-FNNIAJNY.cjs → chunk-IMXSVHQK.cjs} +2 -2
- package/dist/{chunk-FNNIAJNY.cjs.map → chunk-IMXSVHQK.cjs.map} +1 -1
- package/dist/{chunk-LH7URJZT.js → chunk-IPOU3JTA.js} +3 -3
- package/dist/{chunk-LH7URJZT.js.map → chunk-IPOU3JTA.js.map} +1 -1
- package/dist/{chunk-WTEXBPBR.js → chunk-JOIQFDZQ.js} +2 -2
- package/dist/chunk-JOIQFDZQ.js.map +1 -0
- package/dist/{chunk-KHCNMNZZ.js → chunk-JP4JMQOG.js} +2 -2
- package/dist/{chunk-KHCNMNZZ.js.map → chunk-JP4JMQOG.js.map} +1 -1
- package/dist/chunk-KKMLFYVW.cjs +3 -0
- package/dist/chunk-KKMLFYVW.cjs.map +1 -0
- package/dist/{chunk-62LMTO4F.js → chunk-LHLW7JLS.js} +2 -2
- package/dist/{chunk-62LMTO4F.js.map → chunk-LHLW7JLS.js.map} +1 -1
- package/dist/{chunk-SOMGSIO4.cjs → chunk-NAZ6PGLS.cjs} +2 -2
- package/dist/chunk-NAZ6PGLS.cjs.map +1 -0
- package/dist/{chunk-A33K7NY4.js → chunk-O3ALJLYC.js} +2 -2
- package/dist/chunk-O3ALJLYC.js.map +1 -0
- package/dist/chunk-P4ETODMP.js +2 -0
- package/dist/chunk-P4ETODMP.js.map +1 -0
- package/dist/{chunk-P6WPEUAJ.cjs → chunk-PREIL3IB.cjs} +2 -2
- package/dist/{chunk-P6WPEUAJ.cjs.map → chunk-PREIL3IB.cjs.map} +1 -1
- package/dist/chunk-Q3PSTNSY.js +2 -0
- package/dist/chunk-Q3PSTNSY.js.map +1 -0
- package/dist/{chunk-NQSWT3UO.js → chunk-Q7HPPLMG.js} +2 -2
- package/dist/{chunk-NQSWT3UO.js.map → chunk-Q7HPPLMG.js.map} +1 -1
- package/dist/chunk-RC4M6HBX.cjs +2 -0
- package/dist/chunk-RC4M6HBX.cjs.map +1 -0
- package/dist/{chunk-MSYX32PF.cjs → chunk-S3DFU33X.cjs} +2 -2
- package/dist/{chunk-MSYX32PF.cjs.map → chunk-S3DFU33X.cjs.map} +1 -1
- package/dist/chunk-TVE2DNPU.js +2 -0
- package/dist/chunk-TVE2DNPU.js.map +1 -0
- package/dist/{chunk-YNMMRH44.js → chunk-TZYMXNIB.js} +2 -2
- package/dist/chunk-TZYMXNIB.js.map +1 -0
- package/dist/{chunk-6TPXH6Y5.cjs → chunk-UUAFDZK6.cjs} +3 -3
- package/dist/{chunk-6TPXH6Y5.cjs.map → chunk-UUAFDZK6.cjs.map} +1 -1
- package/dist/{chunk-QYO7IEPR.js → chunk-UZSPBFZN.js} +2 -2
- package/dist/{chunk-QYO7IEPR.js.map → chunk-UZSPBFZN.js.map} +1 -1
- package/dist/chunk-VJP4GGCW.cjs +2 -0
- package/dist/chunk-VJP4GGCW.cjs.map +1 -0
- package/dist/chunk-W5ELYJ4Z.cjs +2 -0
- package/dist/chunk-W5ELYJ4Z.cjs.map +1 -0
- package/dist/{chunk-YTCTUBR2.js → chunk-WOIJPV7Z.js} +2 -2
- package/dist/{chunk-YTCTUBR2.js.map → chunk-WOIJPV7Z.js.map} +1 -1
- package/dist/{chunk-MVZUTETT.js → chunk-XK23K3EJ.js} +2 -2
- package/dist/{chunk-MVZUTETT.js.map → chunk-XK23K3EJ.js.map} +1 -1
- package/dist/{chunk-MPB7KUN5.js → chunk-YAZ4DUJJ.js} +2 -2
- package/dist/chunk-YAZ4DUJJ.js.map +1 -0
- package/dist/chunk-YFX53MZF.js +2 -0
- package/dist/chunk-YFX53MZF.js.map +1 -0
- package/dist/constants.cjs +1 -1
- package/dist/constants.js +1 -1
- package/dist/engine.cjs +1 -1
- package/dist/engine.d.cts +10 -10
- package/dist/engine.d.ts +10 -10
- package/dist/engine.js +1 -1
- package/dist/errors.cjs +1 -1
- package/dist/errors.d.cts +3 -3
- package/dist/errors.d.ts +3 -3
- package/dist/errors.js +1 -1
- package/dist/format.cjs +1 -1
- package/dist/format.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +10 -10
- package/dist/index.d.ts +10 -10
- package/dist/index.js +1 -1
- package/dist/language.d.cts +9 -9
- package/dist/language.d.ts +9 -9
- package/dist/lexer.cjs +1 -1
- package/dist/lexer.d.cts +2 -2
- package/dist/lexer.d.ts +2 -2
- package/dist/lexer.js +1 -1
- package/dist/normalizer.cjs +1 -1
- package/dist/normalizer.d.cts +2 -2
- package/dist/normalizer.d.ts +2 -2
- package/dist/normalizer.js +1 -1
- package/dist/packages.cjs +1 -1
- package/dist/packages.d.cts +8 -8
- package/dist/packages.d.ts +8 -8
- package/dist/packages.js +1 -1
- package/dist/parser.cjs +1 -1
- package/dist/parser.d.cts +3 -3
- package/dist/parser.d.ts +3 -3
- package/dist/parser.js +1 -1
- package/dist/{pipeline-BM8xc0CZ.d.cts → pipeline-B4wf3M1h.d.cts} +5 -24
- package/dist/{pipeline-J2ehIm7t.d.ts → pipeline-QIT4iD8f.d.ts} +5 -24
- package/dist/resolvers.d.cts +1 -1
- package/dist/resolvers.d.ts +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.d.cts +9 -9
- package/dist/testing.d.ts +9 -9
- package/dist/testing.js +1 -1
- package/dist/uom.cjs +1 -1
- package/dist/uom.d.cts +1 -1
- package/dist/uom.d.ts +1 -1
- package/dist/uom.js +1 -1
- package/dist/vm.cjs +1 -1
- package/dist/vm.d.cts +8 -7
- package/dist/vm.d.ts +8 -7
- package/dist/vm.js +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.d.cts +9 -9
- package/dist/worker.d.ts +9 -9
- package/dist/worker.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-2VK3NH5S.cjs +0 -3
- package/dist/chunk-2VK3NH5S.cjs.map +0 -1
- package/dist/chunk-3GAWAMT4.js +0 -2
- package/dist/chunk-3GAWAMT4.js.map +0 -1
- package/dist/chunk-4FCHZYAH.js +0 -3
- package/dist/chunk-4FCHZYAH.js.map +0 -1
- package/dist/chunk-4QVBSG6B.cjs +0 -2
- package/dist/chunk-4QVBSG6B.cjs.map +0 -1
- package/dist/chunk-556Q7VZC.cjs +0 -2
- package/dist/chunk-556Q7VZC.cjs.map +0 -1
- package/dist/chunk-75XDS65A.cjs.map +0 -1
- package/dist/chunk-A33K7NY4.js.map +0 -1
- package/dist/chunk-C65UDMWH.cjs +0 -2
- package/dist/chunk-C65UDMWH.cjs.map +0 -1
- package/dist/chunk-EURCQMZK.cjs +0 -2
- package/dist/chunk-FUDVKPB7.cjs +0 -2
- package/dist/chunk-FUDVKPB7.cjs.map +0 -1
- package/dist/chunk-GMSBBLUQ.js +0 -2
- package/dist/chunk-GMSBBLUQ.js.map +0 -1
- package/dist/chunk-JEFMG6CV.js +0 -2
- package/dist/chunk-JEFMG6CV.js.map +0 -1
- package/dist/chunk-K4MME6ZT.js +0 -2
- package/dist/chunk-K4MME6ZT.js.map +0 -1
- package/dist/chunk-MPB7KUN5.js.map +0 -1
- package/dist/chunk-PL7AH5EU.cjs +0 -5
- package/dist/chunk-PL7AH5EU.cjs.map +0 -1
- package/dist/chunk-PNDQRCRQ.cjs.map +0 -1
- package/dist/chunk-SNVPM27Q.cjs +0 -2
- package/dist/chunk-SNVPM27Q.cjs.map +0 -1
- package/dist/chunk-SOMGSIO4.cjs.map +0 -1
- package/dist/chunk-T3FBAFRR.js +0 -2
- package/dist/chunk-T3FBAFRR.js.map +0 -1
- package/dist/chunk-VBSMA7WJ.cjs.map +0 -1
- package/dist/chunk-WTEXBPBR.js.map +0 -1
- package/dist/chunk-WYIOXAFW.cjs +0 -2
- package/dist/chunk-WYIOXAFW.cjs.map +0 -1
- package/dist/chunk-YNMMRH44.js.map +0 -1
- package/dist/chunk-YOHM2WQT.js.map +0 -1
- package/dist/chunk-YVKHEAFT.js +0 -2
- package/dist/chunk-YVKHEAFT.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/vm/AllocationBudget.ts","../src/vm/Value.ts"],"names":["depth","used","limit","calls","callLimit","exceeded","requested","what","alreadyUsed","ErrorFactory","beginEvaluation","vm","endEvaluation","chargeAllocation","count","checkAllocation","checkedArray","chargeFunctionCall","ValueType","_ValueArena","initialSize","i","Value","type","value","unit","v","usedLastCycle","ValueArena","_arena","_arenaActive","enableValueArena","size","disableValueArena","isArenaActive","persistentValue","p","isDevelopmentBuild","freezeIfDev","m","result","numberValue","n","numberValueExact","exact","numberValueRational","rational","numberValueUncertain","uncertainty","hexValue","base","tag","bigIntValue","stringValue","s","uomValue","uomValueExact","rateValue","magnitude","numeratorUnit","denominatorUnit","isRateUnit","splitRateUnit","idx","TIMECODE_UNIT_PREFIX","timecodeUnit","fps","isTimecodeUnit","timecodeFps","matrixValue","rows","cols","data","hasSymbolic","cell","rowVectorValue","colVectorValue","rangeValue","min","max","colourValue","c","splitValue","chartValue","ipCidrValue","symbolicValue","node","boolValue","b","datetimeValue","percentageValue","pendingValue","queryKey","errorValue","code","message","faultedOperand","a","faultedIn","values"],"mappings":"2CAwDA,IAAIA,CAAAA,CAAQ,EAGRC,CAAAA,CAAO,CAAA,CAGPC,EAAQ,MAAA,CAAO,iBAAA,CAGfC,EAAQ,CAAA,CAGRC,CAAAA,CAAY,OAAO,iBAAA,CAMvB,SAASC,EAASC,CAAAA,CAAmBC,CAAAA,CAAcC,EAA4B,CAC9E,OAAOC,IAAa,SAAA,CAAU,CAC7B,KAAM,2BAAA,CACN,OAAA,CACC,gDAAgDH,CAAAA,CAAU,cAAA,CAAe,OAAO,CAAC,CAAA,CAAA,EAAIC,CAAI,CAAA,oBAAA,EACpEL,CAAAA,CAAM,eAAe,OAAO,CAAC,+BACnD,QAAA,CAAU,CAAA,QAAA,EAAWA,EAAM,cAAA,CAAe,OAAO,CAAC,CAAA,sDAAA,CAAA,CAClD,KAAA,CAAO,iBAAiBI,CAAAA,CAAU,cAAA,CAAe,OAAO,CAAC,CAAA,MAAA,EAASC,CAAI,CAAA,YAAA,EAAeC,CAAAA,CAAY,eAAe,OAAO,CAAC,wBACxH,UAAA,CAAY,2FAAA,CACZ,QAAS,CAAE,SAAA,CAAAF,EAAW,IAAA,CAAAC,CAAAA,CAAM,KAAMC,CAAAA,CAAa,KAAA,CAAAN,CAAM,CACtD,CAAC,CACF,CAQO,SAASQ,EAAgBC,CAAAA,CAAc,CACzCX,MAAY,CAAA,GACfC,CAAAA,CAAO,EACPC,CAAAA,CAAQS,CAAAA,CAAG,yBAAwB,CACnCR,CAAAA,CAAQ,EACRC,CAAAA,CAAYO,CAAAA,CAAG,mBAAA,EAAoB,EAErC,CAGO,SAASC,GAAsB,CACjCZ,CAAAA,CA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ASC,EAAAA,CAAWC,CAAAA,CAAcC,EAAwB,CAChE,OAAO,IAAIzE,CAAAA,CAAM,EAAA,CAAiBwE,EAAMC,CAAO,CAChD,CA2BO,SAASC,EAAAA,CAAeC,EAAUT,CAAAA,CAAWP,CAAAA,CAAyB,CAC5E,OAAIgB,CAAAA,CAAE,OAAS,EAAA,EAAmBA,CAAAA,CAAE,IAAA,GAAS,EAAA,CAA0BA,CAAAA,CACnET,CAAAA,GAAM,SAAcA,CAAAA,CAAE,IAAA,GAAS,IAAmBA,CAAAA,CAAE,IAAA,GAAS,IAA2BA,CAAAA,CACxFP,CAAAA,GAAM,SAAcA,CAAAA,CAAE,IAAA,GAAS,IAAmBA,CAAAA,CAAE,IAAA,GAAS,IAA2BA,CAAAA,CACrF,IACR,CAQO,SAASiB,EAAAA,CAAUC,EAAwC,CACjE,IAAA,IAAS9E,EAAI,CAAA,CAAGA,CAAAA,CAAI8E,EAAO,MAAA,CAAQ9E,CAAAA,EAAAA,CAAK,CACvC,IAAMK,CAAAA,CAAIyE,EAAO9E,CAAC,CAAA,CAClB,GAAIK,CAAAA,CAAE,IAAA,GAAS,IAAmBA,CAAAA,CAAE,IAAA,GAAS,GAAmB,OAAOA,CACxE,CACA,OAAO,IACR","file":"chunk-A33K7NY4.js","sourcesContent":["/**\n * The ceiling on how much memory one evaluation is allowed to ask for.\n *\n * The VM's other two counters bound how many opcodes run and how deep the value\n * stack gets, and both are checked BETWEEN opcodes. That leaves a hole the size\n * of a single opcode: whatever one opcode allocates in a loop of its own is\n * invisible to both, so twenty-four characters of input (`map(10*x,\n * 0:2000000000)`) could allocate until V8 aborted the process, which no\n * `try`/`catch` in the host can contain. Per-site caps close one hole each and\n * do not compose: two collections that are individually legal are legal\n * together, and an operation whose result is the PRODUCT of two legal inputs (a\n * matrix multiply) is bounded by neither of them.\n *\n * This is the counter that composes. Everything an evaluation materialises is\n * charged against one running tally, so the bound is on the total rather than\n * on any single step, and a new opcode inherits it by allocating through\n * {@link chargedArray} or by building a Value through a constructor that\n * already charges ({@link matrixValue}).\n *\n * The tally is module state rather than something threaded through every\n * signature. `executeBytecode()` opens an evaluation and every charge inside\n * that window lands on it, which is what lets a helper five call levels down\n * (`vm/MatrixOps.ts`'s `collectionToValues()`) charge without the four frames\n * in between passing a parameter along, and what keeps a charge down to an add\n * and a compare. This mirrors the value arena in `vm/Value.ts`, which is\n * ambient for the same reason and rests on the same fact: `executeBytecode()`\n * is synchronous, so exactly one evaluation is ever in flight in a realm.\n *\n * An \"element\" is one thing a user's input caused to exist: a `Value` in an\n * expanded collection, a cell in a matrix. They are counted rather than\n * measured in bytes, because a count is the quantity every call site already\n * has in hand before it allocates, and asking V8 how big something is costs\n * more than the allocation being guarded.\n *\n * A second tally lives here for the same structural reason and not because it\n * counts the same thing: {@link chargeFunctionCall} bounds how many\n * user-defined-function calls one evaluation may make in total. Surviving\n * reentry is the whole property both need, and this module is where reentry is\n * already tracked.\n *\n * @module AllocationBudget\n */\n\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport type { VM } from \"@solve-js/vm/OpRegistry\";\n\n/**\n * How deep the evaluation is: 0 outside one, higher inside a reentrant call.\n *\n * `executeBytecode()` re-enters itself for a user-defined function call, a map\n * or reduce transform body, and an algebra verb's bound-unknown body. Only the\n * outermost entry clears the tally, so a runaway recursion cannot refresh its\n * own allowance the way it can refresh `maxInstructions` (each reentrant call\n * gets a fresh local instruction count, which is why function recursion needed\n * a separate guard of its own).\n */\nlet depth = 0;\n\n/** Elements charged so far in the evaluation currently in flight. */\nlet used = 0;\n\n/** The in-flight evaluation's ceiling, read from its VM when the evaluation opened. */\nlet limit = Number.POSITIVE_INFINITY;\n\n/** User-defined-function calls made so far in the evaluation currently in flight. */\nlet calls = 0;\n\n/** The in-flight evaluation's call ceiling, read from its VM when the evaluation opened. */\nlet callLimit = Number.POSITIVE_INFINITY;\n\n/**\n * The refusal itself, built in one place so the wording of the engine's most\n * likely \"this is too big\" message is not reinvented per site.\n */\nfunction exceeded(requested: number, what: string, alreadyUsed: number): Error {\n\treturn ErrorFactory.execution({\n\t\tcode: \"ALLOCATION_LIMIT_EXCEEDED\",\n\t\tmessage:\n\t\t\t`Evaluating this expression would materialise ${requested.toLocaleString(\"en-US\")} ${what}, ` +\n\t\t\t`past the limit of ${limit.toLocaleString(\"en-US\")} elements for one evaluation`,\n\t\texpected: `at most ${limit.toLocaleString(\"en-US\")} elements materialised while evaluating one expression`,\n\t\tfound: `a request for ${requested.toLocaleString(\"en-US\")} more ${what}, on top of ${alreadyUsed.toLocaleString(\"en-US\")} already materialised`,\n\t\tsuggestion: \"use a smaller collection or matrix, or raise the engine's vm.maxAllocatedElements setting\",\n\t\tcontext: { requested, what, used: alreadyUsed, limit },\n\t});\n}\n\n/**\n * Open an evaluation, taking its ceiling from the VM about to run it.\n *\n * @param vm - The VM running this program. Only consulted on the outermost\n * entry, so a reentrant call costs one increment.\n */\nexport function beginEvaluation(vm: VM): void {\n\tif (depth++ === 0) {\n\t\tused = 0;\n\t\tlimit = vm.getMaxAllocatedElements();\n\t\tcalls = 0;\n\t\tcallLimit = vm.getMaxFunctionCalls();\n\t}\n}\n\n/** Close the innermost evaluation. Always call from a `finally`, so a throw cannot leave one open. */\nexport function endEvaluation(): void {\n\tif (depth > 0) depth--;\n}\n\n/**\n * Record elements materialised by the evaluation in flight.\n *\n * Each thing is charged exactly once, where it comes into existence: a matrix\n * in `matrixValue()`, an expanded collection where it is expanded. A site that\n * knows a size in advance and whose result will be charged on birth uses\n * {@link checkAllocation} instead, so that refusing early does not mean\n * counting twice.\n *\n * Outside an evaluation this is a plain no-op rather than an error:\n * `matrixValue()` and the `vm/MatrixOps.ts` helpers are exported and get called\n * by tests, by the formatter and by hosts with no evaluation in flight, and\n * none of those is user input being executed.\n *\n * @param count - How many elements now exist.\n * @param what - What they are, in the plural and in a user's words (\"matrix\n * cells\", \"collection elements\"). Quoted verbatim in the error, so it should\n * name the thing rather than the code that makes it.\n * @throws `ALLOCATION_LIMIT_EXCEEDED` when this evaluation has had enough.\n * Recoverable: it describes this expression, not the engine.\n */\nexport function chargeAllocation(count: number, what: string): void {\n\tif (depth === 0) return;\n\t// Written as a negated `>=` so that NaN takes this branch. A NaN count would\n\t// otherwise be added to the tally and make every later `used > limit`\n\t// comparison false, silently switching the guard off for the rest of the\n\t// evaluation, which is the one failure mode a safety limit must not have.\n\tif (!(count >= 0)) throw exceeded(count, what, used);\n\tused += count;\n\tif (used > limit) throw exceeded(count, what, used - count);\n}\n\n/**\n * Refuse an allocation this evaluation cannot afford, without recording it.\n *\n * For the sites that know how big a result will be BEFORE building it and whose\n * result is charged later, when it is born. A matrix product is the case that\n * matters: its size is the product of two operands that are each affordable, so\n * it has to be refused from the shapes alone, before `matrixMultiply()` takes\n * the memory. Charging here as well as at birth would bill every matrix twice\n * and halve the ceiling the host asked for.\n *\n * @param count - How many elements the result would have.\n * @param what - What they are, in the plural. See {@link chargeAllocation}.\n * @throws `ALLOCATION_LIMIT_EXCEEDED` when the evaluation could not afford them.\n */\nexport function checkAllocation(count: number, what: string): void {\n\tif (depth === 0) return;\n\tif (!(count >= 0) || used + count > limit) throw exceeded(count, what, used);\n}\n\n/**\n * Check that an array is affordable, then allocate it.\n *\n * The intended way to build any user-sized array inside the VM whose contents\n * end up inside a Value that charges on birth, so that \"ask before you take\" is\n * a property of the allocator rather than something each new opcode has to be\n * told.\n *\n * @param count - Element count, checked before a single element exists.\n * @param what - What the elements are, in the plural. See {@link chargeAllocation}.\n * @returns An empty array of that length.\n * @throws `ALLOCATION_LIMIT_EXCEEDED` before allocating anything, when the\n * evaluation cannot afford it.\n */\nexport function checkedArray<T>(count: number, what: string): T[] {\n\tcheckAllocation(count, what);\n\treturn new Array<T>(count);\n}\n\n/**\n * Record one user-defined-function call, and refuse the one past the ceiling.\n *\n * Lives in this module rather than in the VM for the single reason the element\n * tally does: it has to survive `executeBytecode()` re-entering itself. A call\n * count kept per invocation would be reset by the very calls it is counting,\n * which is exactly what happens to `maxInstructions` and exactly why counting\n * instructions could never bound this.\n *\n * The thing being bounded is BREADTH, which no existing guard could see.\n * `maxFunctionRecursionDepth` bounds nesting, and a doubling chain\n * (`f22(v) = f21(v) + f21(v)`, twenty-two lines of it) nests only twenty-two\n * deep while making 2,097,152 calls, which was a fatal heap abort in under a\n * second. Depth 22 against a limit of 50 is comfortably legal, and it was.\n *\n * @throws `FUNCTION_CALL_LIMIT_EXCEEDED` when this evaluation has made\n * enough. Recoverable: the engine is fine, this line is not.\n */\nexport function chargeFunctionCall(): void {\n\tif (depth === 0) return;\n\tif (++calls > callLimit) {\n\t\tthrow ErrorFactory.execution({\n\t\t\tcode: \"FUNCTION_CALL_LIMIT_EXCEEDED\",\n\t\t\tmessage:\n\t\t\t\t`Evaluating this expression would make more than ${callLimit.toLocaleString(\"en-US\")} ` +\n\t\t\t\t`user-defined-function calls, which is the limit for one evaluation`,\n\t\t\texpected: `at most ${callLimit.toLocaleString(\"en-US\")} function calls while evaluating one expression`,\n\t\t\tfound: \"a call past that limit, from a chain of functions that each call others more than once\",\n\t\t\tsuggestion: \"check for a function that calls itself (or a chain of them) more times than intended, or raise the engine's vm.maxFunctionCalls setting\",\n\t\t\tcontext: { calls, callLimit },\n\t\t});\n\t}\n}\n\n/**\n * Elements charged so far in the evaluation in flight, or in the one that just\n * finished. For tests and for a host reporting on a refusal.\n *\n * @returns The running tally.\n */\nexport function allocationUsed(): number {\n\treturn used;\n}\n\n/**\n * User-defined-function calls made so far in the evaluation in flight, or in\n * the one that just finished. For tests and for a host reporting on a refusal.\n *\n * @returns The running tally.\n */\nexport function functionCallsUsed(): number {\n\treturn calls;\n}\n\n/**\n * Drop all in-flight evaluation state.\n *\n * For tests that need a known starting point, and as a repair for a host that\n * somehow lost an `endEvaluation()`. Ordinary execution never needs it:\n * `executeBytecode()` pairs its own begin and end in a `finally`, and the\n * outermost begin clears the tally regardless of what came before.\n */\nexport function resetAllocationTracking(): void {\n\tdepth = 0;\n\tused = 0;\n\tlimit = Number.POSITIVE_INFINITY;\n\tcalls = 0;\n\tcallLimit = Number.POSITIVE_INFINITY;\n}\n","import { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { chargeAllocation } from \"@solve-js/vm/AllocationBudget\";\nimport type { SymbolicNode, Rational } from \"@solve-js/symbolic\";\nimport type { DecimalData } from \"@solve-js/decimal\";\n\n/**\n * A single matrix cell. `boolean` covers element-wise comparison results\n * (`[1,6;3,8] < [5,2;7,4]` produces a Matrix of booleans, not numbers). A\n * `SymbolicNode` cell is a free-variable algebraic entry, e.g. `s =\n * [sx,0,0;0,sy,0;0,0,1]` where `sx`/`sy` are never assigned, so those\n * cells store a real `SymbolicNode` (a bare `var` node initially) rather\n * than degrading to `0`. See `MatrixOps.ts`'s `entryToSymbolic()`/\n * `symbolicToEntry()` for the two-way conversion every symbolic-aware\n * matrix op (multiply, inverse, determinant) uses.\n */\nexport type MatrixEntry = number | boolean | SymbolicNode;\n\n/**\n * A general rows×cols matrix, a vector is just a 1×N (row) or N×1 (column)\n * matrix. `data` is COLUMN-MAJOR (`data[row + col*rows]`), matching the\n * spec's own `a[index]` column-major indexing semantics directly (no\n * translation needed for single-index reads). `hasSymbolic` lets every\n * numeric matrix op fast-path the all-numeric case with one boolean check,\n * mirroring `binaryOp()`'s existing Number+Number fast path, computed by\n * `matrixValue()` itself (true the moment any cell is a `SymbolicNode`\n * object rather than a plain number/boolean), not something callers set\n * by hand.\n */\nexport interface MatrixData {\n\treadonly rows: number;\n\treadonly cols: number;\n\treadonly data: readonly MatrixEntry[];\n\treadonly hasSymbolic: boolean;\n}\n\n/** A first-class integer range `min:max`, both bounds inclusive. */\nexport interface RangeData {\n\treadonly min: number;\n\treadonly max: number;\n}\n\n/**\n * How a colour was authored, and therefore how it should display. It never\n * changes the channels: a colour is always stored as canonical sRGB (`r`,`g`,`b`\n * integers 0-255, `a` in 0-1), and `format` only decides whether `formatValue`\n * renders it as `#rrggbb`, `rgb(...)`, `hsl(...)` or a named keyword.\n */\nexport type ColourFormat = \"hex\" | \"rgb\" | \"rgba\" | \"hsl\" | \"hsla\" | \"named\";\n\n/**\n * A colour value. Canonical channels are sRGB (`r`,`g`,`b` are integers 0-255,\n * `a` is 0-1); HSL is never stored, it is derived on demand for display and for\n * hue/saturation/lightness operations, then re-quantised back to RGBA. A\n * `lighten` followed by an equal `darken` returns to within one rounding step of\n * the original (integer channels re-quantise each way), and does not drift on\n * repetition, rather than storing both HSL and RGB and letting them disagree.\n * `format`\n * records the authored/display form; `name` carries the CSS keyword only when\n * `format === \"named\"` (e.g. `\"rebeccapurple\"`). Lives in a {@link Value}'s\n * `value` slot exactly as {@link MatrixData}/{@link RangeData} do.\n */\nexport interface ColourData {\n\treadonly r: number;\n\treadonly g: number;\n\treadonly b: number;\n\treadonly a: number;\n\treadonly format: ColourFormat;\n\treadonly name?: string;\n}\n\n/**\n * One tier of a bill split: an amount and how many people pay it. An even\n * split is a single share; the odd-penny case is two shares (the base amount\n * most people pay, then the base plus a cent that the remaining `count` pay),\n * so the shares always add back to the exact total. `exact` carries the\n * base-ten cents of a currency share so display rounds from the decimal rather\n * than a drifted double, exactly as money does everywhere else.\n */\nexport interface SplitShare {\n\treadonly value: number;\n\treadonly exact?: DecimalData;\n\treadonly count: number;\n}\n\n/**\n * The result of a per-person bill split (`split $180 between 4`). `unit` is the\n * currency code when the amount was money, undefined for a bare number.\n * `shares` is ordered base-first: `shares[0]` is the \"each\" amount, and a\n * second share, when present, is the slightly larger amount the odd penny falls\n * on. Lives in a {@link Value}'s `value` slot exactly as {@link ColourData} and\n * {@link RangeData} do, a display-only payload the formatter renders.\n */\nexport interface SplitData {\n\treadonly unit?: string;\n\treadonly shares: readonly SplitShare[];\n}\n\n/**\n * What a {@link ChartData} draws, and therefore how a host renders it: a\n * `sparkline` is a tiny inline line with no axes, a `plot` a framed curve over a\n * domain. New kinds (a bar chart, a scatter) are added here, and every host that\n * switches on `kind` keeps working for the ones it already knows.\n */\nexport type ChartKind = \"sparkline\" | \"plot\";\n\n/**\n * A chart specification: the DATA to draw, never pixels. One shape holds every\n * visual the engine produces, `[1,2,3] as sparkline` and `plot sin(x) from 0 to\n * 2pi` alike, so a host reads `kind` to choose a renderer and draws `points`\n * scaled to `domain` × `range`. The engine brings the numbers; the developer\n * brings the charting library. `label` is the plain-text answer a reader without\n * a canvas still gets. A sparkline's points are `(index, value)`; a plot's are\n * `(x, y)`. Lives in a {@link Value}'s `value` slot exactly as\n * {@link MatrixData}/{@link ColourData} do (issues #186, #187).\n */\nexport interface ChartData {\n\treadonly kind: ChartKind;\n\t/** The points to draw, `(x, y)`. A sparkline indexes x from 0. */\n\treadonly points: readonly (readonly [number, number])[];\n\t/** The plain-text answer, e.g. `sin(x) over [0, 6.28]` or the series itself. */\n\treadonly label: string;\n\t/** The x-axis extent `[min, max]`. */\n\treadonly domain: readonly [number, number];\n\t/** The y-axis extent `[min, max]`, for scaling the drawn height. */\n\treadonly range: readonly [number, number];\n\t/** The source expression, for a plot; absent for a sparkline. */\n\treadonly expr?: string;\n}\n\n/**\n * An IPv4 address and/or subnet prefix (issue #189). `addr` is the 32-bit\n * address (`192.168.1.10` held as one number); `prefix` is the CIDR prefix\n * length in `/24`. A bare address has no `prefix`, a bare `/24` has no `addr`,\n * and a full block (`192.168.1.0/24`) has both. Lives in a {@link Value}'s\n * `value` slot as the other struct payloads do; the formatter renders it as the\n * dotted quad (plus `/prefix` when present).\n */\nexport interface IpCidrData {\n\treadonly addr?: number;\n\treadonly prefix?: number;\n}\n\n/**\n * Discriminated union tag for {@link Value} objects.\n *\n * Determines the runtime type of a Value and how its `value` field should\n * be interpreted. Used by the VM for type-aware dispatch in arithmetic,\n * comparison, and conversion operations.\n */\nexport enum ValueType {\n\t/** Plain 64-bit floating point number (IEEE 754 double) */\n\tNumber = 0,\n\tHex = 1,\n\tBigInt = 2,\n\tString = 3,\n\tDatetime = 4,\n\tPercentage = 5,\n\tUom = 6,\n\t/** General rows×cols matrix (a vector is a 1×N or N×1 matrix). Value is {@link MatrixData}. */\n\tMatrix = 7,\n\t/** A first-class integer range `min:max`, both inclusive. Value is {@link RangeData}. */\n\tRange = 8,\n\t/** A symbolic/algebraic expression tree (free-variable formula, not a concrete number). Value is a `SymbolicNode` (`@solve-js/symbolic`). */\n\tSymbolic = 9,\n\t/** Boolean true/false. Value is `boolean`. */\n\tBoolean = 10,\n\t/** Unit of measurement token (lexer only, not a runtime value). */\n\tUnit = 11,\n\t/** Async result pending resolution. Value stores the queryKey string. */\n\tPending = 12,\n\t/** Plugin-raised error propagated through the DAG. Value stores error code, unit stores message. */\n\tError = 13,\n\t/** A colour (hex/rgb/hsl/named). Value is {@link ColourData}. */\n\tColour = 14,\n\t/** A per-person bill split (`split $180 between 4`). Value is {@link SplitData}. */\n\tSplit = 15,\n\t/** A chart to draw (`[1,2,3] as sparkline`, `plot sin(x) from 0 to 2pi`). Value is {@link ChartData}. */\n\tChart = 16,\n\t/** An IPv4 address or subnet (`192.168.1.0/24`). Value is {@link IpCidrData}. */\n\tIpCidr = 17,\n}\n\n// ── ValueArena ────────────────────────────────────────────────────────────\n// Phase 5.3: Bump-allocator arena for zero-allocation Value reuse during scroll.\n// Instead of allocating new Value objects per instruction, we pre-allocate a\n// block and bump an index. A single arena.reset() per scroll frame recycles all\n// Values, no per-value release overhead, no GC pressure during 60fps scrolling.\n\n/**\n * Bump-allocator arena for zero-allocation Value reuse during scroll.\n *\n * Instead of allocating new Value objects per instruction, pre-allocates a\n * block and bumps an index. `arena.reset()` per scroll frame recycles all\n * Values, no per-value release overhead, no GC pressure during 60fps scrolling.\n *\n * Only active during Tier 2 scroll execution (ThreeTierEvaluator).\n */\nexport class ValueArena {\n\tprivate arena: Value[] = [];\n\tprivate index: number = 0;\n\t/** The block size to come back down to. Kept so {@link reset} can. */\n\tprivate readonly initialSize: number;\n\n\t/**\n\t * How much more than the last cycle needed the arena may go on holding\n\t * before it gives the difference back, and how much of it it keeps when it\n\t * does.\n\t *\n\t * A bump allocator that grows to serve one expensive line is working as\n\t * intended; one that never comes down is a leak wearing a cache's clothes.\n\t * `map(x*1, 1:100000)` is an ordinary line by every limit the engine has,\n\t * and it took the arena from 512 Values to 300,004, about 24MB that stayed\n\t * live through two forced full collections and through every later `1 + 1`,\n\t * because `acquire()` handles overflow with `push()` and `reset()` only\n\t * zeroed the bump index. The instance is module-level and survives\n\t * `disableValueArena()` on purpose, so that high-water mark was for the\n\t * life of the process.\n\t *\n\t * Keeping twice what the last cycle used, and only shrinking once holding\n\t * four times that, is what stops the release from becoming a different\n\t * performance bug: a steady scroll uses about the same number of Values\n\t * every frame, so it never meets the condition at all, and an alternating\n\t * heavy/light document degrades at worst to allocating the Values it would\n\t * have allocated with no arena in the first place.\n\t */\n\tprivate static readonly SHRINK_WHEN_HOLDING_TIMES = 4;\n\tprivate static readonly KEEP_TIMES = 2;\n\n\t/** Pre-allocate initial block. 512 Values covers ~30-line viewport comfortably. */\n\tconstructor(initialSize: number = 512) {\n\t\tthis.initialSize = initialSize;\n\t\tfor (let i = 0; i < initialSize; i++) {\n\t\t\tthis.arena.push(new Value(ValueType.Number, 0));\n\t\t}\n\t}\n\n\t/** Bump-allocate a recycled Value. Falls back to allocation only for overflow. */\n\tacquire(type: ValueType, value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | ChartData | IpCidrData | SymbolicNode, unit?: string): Value {\n\t\tif (this.index < this.arena.length) {\n\t\t\tconst v = this.arena[this.index++];\n\t\t\tv.recycle(type, value, unit);\n\t\t\treturn v;\n\t\t}\n\t\t// Arena overflow, allocate fresh (rare, only for very complex expressions)\n\t\tconst v = new Value(type, value, unit);\n\t\tthis.arena.push(v);\n\t\tthis.index++;\n\t\treturn v;\n\t}\n\n\t/**\n\t * Reset for the next scroll frame, releasing a block the last frame turned\n\t * out not to need.\n\t *\n\t * Still O(1) in the ordinary case: one comparison against what the cycle\n\t * that just ended used, and the truncation only on the frame after an\n\t * unusually expensive one. Reading the usage here rather than at\n\t * `disableValueArena()` is what makes the policy \"the first cycle that does\n\t * not need the block gives it back\", which is the first thing a host does\n\t * after the line that grew it.\n\t */\n\treset(): void {\n\t\tconst usedLastCycle = this.index;\n\t\tthis.index = 0;\n\t\tif (this.arena.length <= this.initialSize) return;\n\t\tif (this.arena.length <= usedLastCycle * ValueArena.SHRINK_WHEN_HOLDING_TIMES) return;\n\t\t// Never below the initial block, and never above what is already held,\n\t\t// so this only ever truncates.\n\t\tthis.arena.length = Math.max(this.initialSize, usedLastCycle * ValueArena.KEEP_TIMES);\n\t}\n\n\t/** Current arena utilization (for diagnostics). */\n\tget usage(): number { return this.index; }\n\tget capacity(): number { return this.arena.length; }\n}\n\n// Module-level arena toggle. Single-threaded JS, so global state is safe.\n// The arena is ONLY active during Tier 2 scroll execution, the ThreeTierEvaluator\n// enables it before evaluating visible lines and disables it after.\n//\n// The arena INSTANCE survives disable(): constructing a ValueArena allocates\n// its whole initial block (512 Values), so dropping it on every disable would\n// pay that allocation cost again on the next enable, more garbage than the\n// arena saves. Instead, an `_arenaActive` flag gates use of the long-lived\n// instance; enable() just resets the bump index.\nlet _arena: ValueArena | null = null;\nlet _arenaActive = false;\n\n/** Enable the Value arena for zero-allocation scroll execution. */\nexport function enableValueArena(size?: number): ValueArena {\n\tif (!_arena) _arena = new ValueArena(size);\n\t_arena.reset();\n\t_arenaActive = true;\n\treturn _arena;\n}\n\n/** Disable the arena (returns to normal GC-collected allocation). */\nexport function disableValueArena(): void {\n\t_arenaActive = false;\n}\n\n/** Check if arena is active (used by STORE_VAR / HALT to decide cloning). */\nexport function isArenaActive(): boolean {\n\treturn _arenaActive;\n}\n\n/**\n * Allocate a Value that persists beyond the current arena cycle.\n * Used for values stored in variables (STORE_VAR) and final expression results\n * (HALT return), these must survive arena.reset() in the next scroll frame.\n */\nexport function persistentValue(v: Value): Value {\n\tconst p = new Value(v.type, v.value, v.unit);\n\t// The exact sidecar has to survive being stored in a variable, or a\n\t// referenced money value would silently drop back to the double: \"a = $0.10,\n\t// b = $0.20, a + b\" must still be exact across the STORE_VAR round trip.\n\tif (v.exact !== undefined) p.exact = v.exact;\n\t// The rational sidecar survives the same round trip, so \"a = 1/3, a + a + a\"\n\t// is exactly 1 rather than the drifted double a stored fraction would carry.\n\tif (v.rational !== undefined) p.rational = v.rational;\n\t// The uncertainty sidecar survives too, so \"a = 12.3 +/- 0.5, a * 4\" still\n\t// propagates the tolerance across the STORE_VAR round trip.\n\tif (v.uncertainty !== undefined) p.uncertainty = v.uncertainty;\n\treturn p;\n}\n\n// ── Dev-mode immutability guard (Part II, L5, Value model hardening) ──\n//\n// Value is documented immutable by convention, not enforcement: the arena\n// mutates objects in place via recycle() (by design, for Tier-2 scroll\n// performance), so Value can never be unconditionally frozen. This guard\n// freezes a Value ONLY when it is safe to do so, i.e. NOT while the arena\n// is active, since an arena-active Value may still be recycled later in\n// the same scroll frame. It is a no-op outside development builds (matches\n// the existing `process.env.NODE_ENV === \"development\"` convention used by\n// the app-layer logger) so there is zero runtime cost in production.\nconst isDevelopmentBuild = process.env.NODE_ENV === \"development\";\n\n/**\n * Freeze a Value in development builds, catching accidental external\n * mutation of \"immutable\" results early. Safe to call unconditionally\n * it is a no-op in production and a no-op whenever the arena is active\n * (an arena-active Value may still be recycle()'d before this scroll\n * frame ends, and freezing it would make recycle() throw).\n *\n * Intended for values leaving a public evaluation boundary\n * (ExpressionEngine.evaluateLine* / evaluateExpression), not for values\n * still moving through internal VM/arena machinery.\n */\nexport function freezeIfDev<T extends Value>(value: T): T {\n\tif (isDevelopmentBuild && !isArenaActive()) {\n\t\t// toNumber() lazily memoizes _cachedNumber for bigint/string values\n\t\t// (Number/Hex are already eagerly cached by the constructor), warm\n\t\t// it now so a later toNumber() call on the frozen object doesn't\n\t\t// try to write to a frozen field.\n\t\tvalue.toNumber();\n\t\tObject.freeze(value);\n\t}\n\treturn value;\n}\n\n/**\n * Universal runtime value for the solve-js VM.\n *\n * Carries a {@link ValueType} discriminant, a polymorphic `value` payload,\n * and an optional `unit` string (for UoM values). Treated as immutable after\n * construction, the arena reuses objects internally via `recycle()`, but\n * external code should never mutate Value fields.\n *\n * A cached `_cachedNumber` avoids repeated `toNumber()` computation on\n * hot paths (ADD/SUB/MUL in the VM dispatch loop).\n */\nexport class Value {\n\t// Cached numeric representation, computed once on first toNumber() call.\n\t// Cleared on recycle() when the arena reuses this Value for a new value.\n\tprivate _cachedNumber: number | undefined;\n\n\t// Fields are NOT readonly, the arena reuses Value objects by calling\n\t// recycle() which overwrites all fields. External code should treat Values\n\t// as immutable after construction (arena handles mutation internally).\n\tpublic type: ValueType;\n\tpublic value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | ChartData | IpCidrData | SymbolicNode;\n\tpublic unit?: string;\n\t/** Set by async resolvers when a fetch timed out, the result is a fallback (typically 0). */\n\tpublic timedOut?: boolean;\n\t/**\n\t * The exact base-ten value this Value stands for, when it has one.\n\t *\n\t * A sidecar rather than a replacement for `value`: money and decimal-point\n\t * literals set it to a {@link DecimalData} so that same-currency arithmetic\n\t * and display can be exact (\"$0.10 + $0.20\" is \"$0.30\", not\n\t * \"$0.30000000000000004\"), while `value` stays the nearest double so every\n\t * existing consumer that reads `.value` or `toNumber()` is unchanged. The\n\t * plain Number-times-Number fast paths deliberately ignore it, which is why\n\t * a bare \"0.1 + 0.2\" still answers the double it always did: exactness is\n\t * carried only where a unit-bearing operand asks for it. Cleared by\n\t * {@link recycle} so a reused arena Value never inherits a stale exact.\n\t */\n\tpublic exact?: DecimalData;\n\t/**\n\t * The exact rational value this Value stands for, when it has one.\n\t *\n\t * The second sidecar, the same shape as {@link exact} and for the same\n\t * reason: a fraction has no exact base-ten form (`1/3` is not any decimal),\n\t * so exact fraction arithmetic needs a numerator/denominator pair rather\n\t * than a coefficient and a scale. Integer division seeds it (\"1/3\" carries\n\t * the {@link Rational} 1/3), and `+`, `-`, `*`, `/` between rational-bearing\n\t * numbers keep it reduced, so \"1/49 * 49\" is exactly 1 and \"5/6 - 1/6 - 1/6\n\t * - 1/6 - 1/6 - 1/6\" is exactly 0 rather than the 1.6e-16 the doubles drift\n\t * to. `value` still holds the nearest double, recomputed from the exact\n\t * rational so accumulation error never creeps in, which is why the default\n\t * display and every `.value`/`toNumber()` reader are unchanged. Only a\n\t * fraction written with \"/\" carries it, so a decimal literal (\"0.1\") and a\n\t * transcendental result (\"sqrt(2)\") stay the plain doubles they were.\n\t * Cleared by {@link recycle} alongside {@link exact}.\n\t */\n\tpublic rational?: Rational;\n\t/**\n\t * The one-sigma uncertainty (standard error) this value carries, when it\n\t * has one.\n\t *\n\t * The third sidecar, the same shape as {@link exact} and {@link rational}\n\t * and for the same reason: a measurement written `12.3 ± 0.5` is still the\n\t * number 12.3 everywhere it is read as one, so the type stays\n\t * {@link ValueType.Number} and `value` stays the center, while this non\n\t * negative field carries the tolerance. The `±` (or ASCII `+/-`) operator\n\t * seeds it, and `+`, `-`, `*`, `/` propagate it in quadrature for\n\t * independent errors (see `vm/VMConversion.ts`'s `uncertainOp`). Everything\n\t * else (a comparison, a transcendental function, a unit conversion) reads\n\t * the center through `toNumber()` and drops the tolerance, which is why a\n\t * value with no uncertainty behaves exactly as a plain number always did.\n\t * Cleared by {@link recycle} alongside the other two sidecars.\n\t */\n\tpublic uncertainty?: number;\n\t/**\n\t * The number of decimal places this value should DISPLAY at, when it has been\n\t * given an explicit precision.\n\t *\n\t * A display sidecar, not a value one: `value` is unchanged, so every\n\t * `.value`/`toNumber()` reader and all arithmetic behave exactly as before,\n\t * and a value with no `decimalPlaces` formats the way it always did (the\n\t * global two-place default with trailing zeros trimmed). It is set only by an\n\t * explicit precision request, `<x> to N dp` and `round(x, N)`, so that\n\t * `3.14159 to 4 dp` shows `3.1416` and `1.5 to 2 dp` shows `1.50` rather than\n\t * the value being rounded but then displayed at the default two places. It is\n\t * NOT propagated through arithmetic (a later `+ 1` re-decides precision),\n\t * which is why nothing that did not ask for a precision is affected. Cleared\n\t * by {@link recycle} alongside the other sidecars.\n\t */\n\tpublic decimalPlaces?: number;\n\n\tconstructor(\n\t\ttype: ValueType,\n\t\tvalue: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | ChartData | IpCidrData | SymbolicNode,\n\t\tunit?: string\n\t) {\n\t\tthis.type = type;\n\t\tthis.value = value;\n\t\tthis.unit = unit;\n\t\t// Eagerly cache for Number and Hex types (the most common case).\n\t\t// This avoids a method call + type-check on first toNumber().\n\t\tif (typeof value === 'number') {\n\t\t\tthis._cachedNumber = value;\n\t\t}\n\t}\n\n\t/**\n\t * Phase 5.3: Reset all fields for arena reuse.\n\t * Called by ValueArena.acquire(), zero allocation, just field assignment.\n\t */\n\trecycle(type: ValueType, value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | ChartData | IpCidrData | SymbolicNode, unit?: string): void {\n\t\tthis.type = type;\n\t\tthis.value = value;\n\t\tthis.unit = unit;\n\t\t// Clear cache, value changed, cached number is stale.\n\t\t// Re-eager-cache for Number type (most common).\n\t\tthis._cachedNumber = typeof value === 'number' ? value : undefined;\n\t\t// Clear timeout flag, recycled Values shouldn't inherit stale metadata.\n\t\tthis.timedOut = undefined;\n\t\t// Clear the exact sidecar for the same reason: a reused Value that once\n\t\t// held money must not carry that money's decimal into a plain number.\n\t\tthis.exact = undefined;\n\t\t// The rational sidecar clears with it: a reused Value that once held a\n\t\t// fraction must not carry that fraction into a plain number.\n\t\tthis.rational = undefined;\n\t\t// The uncertainty sidecar clears the same way: a reused Value that once\n\t\t// carried a tolerance must not lend it to a plain number.\n\t\tthis.uncertainty = undefined;\n\t\t// The display-precision sidecar clears too: a reused Value that once had\n\t\t// an explicit `to N dp` must not display a plain number at that precision.\n\t\tthis.decimalPlaces = undefined;\n\t}\n\n\tisNumber(): this is Value & { value: number } {\n\t\treturn this.type === ValueType.Number;\n\t}\n\n\tisHex(): this is Value & { value: number } {\n\t\treturn this.type === ValueType.Hex;\n\t}\n\n\tisBigInt(): this is Value & { value: bigint } {\n\t\treturn this.type === ValueType.BigInt;\n\t}\n\n\tisString(): this is Value & { value: string } {\n\t\treturn this.type === ValueType.String;\n\t}\n\n\tisMatrix(): this is Value & { value: MatrixData } {\n\t\treturn this.type === ValueType.Matrix;\n\t}\n\n\t/** A Matrix shaped like a vector, 1×N (row) or N×1 (column). */\n\tisVectorShape(): boolean {\n\t\tif (this.type !== ValueType.Matrix) return false;\n\t\tconst m = this.value as MatrixData;\n\t\treturn m.rows === 1 || m.cols === 1;\n\t}\n\n\tisRange(): this is Value & { value: RangeData } {\n\t\treturn this.type === ValueType.Range;\n\t}\n\n\tisColour(): this is Value & { value: ColourData } {\n\t\treturn this.type === ValueType.Colour;\n\t}\n\n\tisChart(): this is Value & { value: ChartData } {\n\t\treturn this.type === ValueType.Chart;\n\t}\n\n\tisIpCidr(): this is Value & { value: IpCidrData } {\n\t\treturn this.type === ValueType.IpCidr;\n\t}\n\n\tisSymbolic(): this is Value & { value: SymbolicNode } {\n\t\treturn this.type === ValueType.Symbolic;\n\t}\n\n\t/**\n\t * An Error value: a fault carrying a code and message, propagated through the\n\t * DAG when a plugin or opcode cannot produce a quantity.\n\t *\n\t * An Error reads as the number 0 through {@link toNumber}, so a numeric\n\t * consumer that does not check this first cannot tell the fault apart from a\n\t * real zero: exactly the silently-wrong result the engine guards against\n\t * internally with {@link faultedOperand}. A host reading a live {@link Value}\n\t * off a result should branch on this (or {@link isFault}) before trusting the\n\t * number, and read {@link errorCode}/{@link errorMessage} for the detail.\n\t */\n\tisError(): boolean {\n\t\treturn this.type === ValueType.Error;\n\t}\n\n\t/**\n\t * A Pending value: an async result that has not yet resolved, holding the\n\t * query key it is waiting on. Reads as 0 through {@link toNumber}, the same\n\t * caveat as {@link isError}: a settled value arrives on a later evaluation.\n\t */\n\tisPending(): boolean {\n\t\treturn this.type === ValueType.Pending;\n\t}\n\n\t/**\n\t * Either fault, an Error or a Pending: the single predicate to check before\n\t * trusting {@link toNumber}. It mirrors the internal {@link faultedOperand}\n\t * rule that every opcode applies to its operands, so a host reading a result\n\t * makes the same distinction the engine does rather than computing with a\n\t * zero it cannot tell from a real one.\n\t */\n\tisFault(): boolean {\n\t\treturn this.type === ValueType.Error || this.type === ValueType.Pending;\n\t}\n\n\t/**\n\t * The stable {@link ErrorFactory} code of an Error value, else `undefined`.\n\t *\n\t * The code is the machine-branchable identifier (the message is the\n\t * human-facing text, {@link errorMessage}). It reads from the same slot\n\t * {@link errorValue} writes, so it is defined for exactly the values\n\t * {@link isError} accepts and `undefined` for every other type.\n\t */\n\tget errorCode(): string | undefined {\n\t\treturn this.type === ValueType.Error ? (this.value as string) : undefined;\n\t}\n\n\t/**\n\t * The human-facing message of an Error value, else `undefined`. Paired with\n\t * {@link errorCode}, which carries the branchable identifier.\n\t */\n\tget errorMessage(): string | undefined {\n\t\treturn this.type === ValueType.Error ? this.unit : undefined;\n\t}\n\n\ttoNumber(): number {\n\t\t// Pending/Error have no numeric representation at all, 0 (established\n\t\t// convention). A genuinely multi-cell Matrix has no single numeric\n\t\t// representation either (real callers branch on `.isMatrix()` BEFORE\n\t\t// reaching this fallback. See e.g. VM.ts's MUL/comparison dispatch)\n\t\t// but a 1x1 Matrix, the shape `float(x)`'s legacy sugar produces, see\n\t\t// packages/vector/parselets/FloatParselet.ts, IS a scalar in every\n\t\t// meaningful sense, so it degrades to that single cell's numeric value\n\t\t// rather than 0 (this exact case used to work \"by accident\" pre-Matrix,\n\t\t// since `parseFloat([2].toString())` happened to yield `2`).\n\t\tif (this.type === ValueType.Pending) return 0;\n\t\tif (this.type === ValueType.Error) return 0;\n\t\tif (this.type === ValueType.Matrix) {\n\t\t\tconst m = this.value as MatrixData;\n\t\t\tif (m.rows === 1 && m.cols === 1 && typeof m.data[0] === \"number\") return m.data[0];\n\t\t\treturn 0;\n\t\t}\n\t\tif (this.type === ValueType.Range) return 0;\n\t\t// A colour is a struct of channels, not a scalar; like Matrix/Range it has\n\t\t// no single numeric reading. Callers branch on `.isColour()` first.\n\t\tif (this.type === ValueType.Colour) return 0;\n\t\t// A chart is a set of points, not a scalar; callers branch on `.isChart()`.\n\t\tif (this.type === ValueType.Chart) return 0;\n\t\t// An IP/CIDR reads as its 32-bit address where a number is wanted (`as int`).\n\t\tif (this.type === ValueType.IpCidr) return (this.value as IpCidrData).addr ?? 0;\n\t\t// A split is a structured multi-share result; its scalar reading is the\n\t\t// \"each\" (base) share, so a numeric consumer or the worker DTO's number\n\t\t// field still gets a sensible value where a caller does not branch first.\n\t\tif (this.type === ValueType.Split) return (this.value as SplitData).shares[0].value;\n\t\t// A symbolic expression has no single concrete numeric value by\n\t\t// definition (it's a free-variable formula), 0, matching the\n\t\t// Pending/Error/Range convention. Real callers branch on\n\t\t// `.isSymbolic()` BEFORE reaching this fallback (see\n\t\t// `VMConversion.ts`'s `binaryOp()`).\n\t\tif (this.type === ValueType.Symbolic) return 0;\n\t\t// A boolean has an obvious numeric reading and no branch used to give it\n\t\t// one, so it fell through to `parseFloat(true)` -> NaN -> 0, and BOTH\n\t\t// booleans read as zero: `true == false` answered true, and every\n\t\t// arithmetic path that mixes a boolean with a number (\"true and 5\")\n\t\t// contributed nothing. 1/0 is the reading every language with a numeric\n\t\t// boolean coercion uses, and the one `if 1 then` already implies.\n\t\tif (this.type === ValueType.Boolean) return this.value === true ? 1 : 0;\n\n\t\tif (this._cachedNumber !== undefined) return this._cachedNumber;\n\n\t\tif (typeof this.value === 'bigint') {\n\t\t\tthis._cachedNumber = Number(this.value);\n\t\t\treturn this._cachedNumber;\n\t\t}\n\t\t// Prevent silent NaN propagation from non-numeric strings\n\t\tconst result = parseFloat(this.value as string);\n\t\tthis._cachedNumber = isNaN(result) ? 0 : result;\n\t\treturn this._cachedNumber;\n\t}\n\n\tisNaN(): boolean {\n\t\tif (this.type === ValueType.Pending) return false;\n\t\tif (this.type === ValueType.Error) return false;\n\t\tif (this.type === ValueType.Matrix) {\n\t\t\tconst m = this.value as MatrixData;\n\t\t\tif (m.rows === 1 && m.cols === 1 && typeof m.data[0] === \"number\") return isNaN(m.data[0]);\n\t\t\treturn false;\n\t\t}\n\t\tif (this.type === ValueType.Range) return false;\n\t\tif (this.type === ValueType.Colour) return false;\n\t\tif (this.type === ValueType.Split) return false;\n\t\tif (this.type === ValueType.Chart) return false;\n\t\tif (this.type === ValueType.IpCidr) return false;\n\t\tif (this.type === ValueType.Symbolic) return false;\n\t\t// Matches toNumber()'s boolean reading above. Without this a Boolean\n\t\t// reached the string branch at the bottom and `parseFloat(true)` made\n\t\t// every boolean report itself as NaN.\n\t\tif (this.type === ValueType.Boolean) return false;\n\t\tif (typeof this.value === 'number') return isNaN(this.value);\n\t\tif (typeof this.value === 'bigint') return false;\n\t\treturn isNaN(parseFloat(this.value as string));\n\t}\n}\n\n/**\n * Create a Number-typed Value. Uses the arena when active for zero-allocation.\n * This is the most common factory, over 90% of all Value creations.\n */\nexport function numberValue(n: number): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Number, n);\n\treturn new Value(ValueType.Number, n);\n}\n\n/**\n * A Number that also carries the exact decimal it was written as.\n *\n * The type stays {@link ValueType.Number} and `value` stays the nearest double,\n * so this Value behaves exactly like any other number everywhere it is read as\n * one. The `exact` sidecar only matters when it later meets a currency: that is\n * what lets \"$0.70 * 1.10\" be exact while \"0.1 + 0.2\" stays the double it was.\n * Decimal-point literals are compiled to this (see the PUSH_DECIMAL opcode).\n */\nexport function numberValueExact(n: number, exact: DecimalData): Value {\n\tconst v = numberValue(n);\n\tv.exact = exact;\n\treturn v;\n}\n\n/**\n * A Number that also carries the exact rational it evaluates to.\n *\n * The rational counterpart of {@link numberValueExact}: the type stays\n * {@link ValueType.Number} and `value` stays the nearest double (recomputed\n * from the rational, so a chain of fraction operations never accumulates\n * float error), so this reads as an ordinary number everywhere. The `rational`\n * sidecar is what keeps the next fraction operation and any `as fraction`\n * exact. Integer division produces this (see the DIV opcode).\n */\nexport function numberValueRational(n: number, rational: Rational): Value {\n\tconst v = numberValue(n);\n\tv.rational = rational;\n\treturn v;\n}\n\n/**\n * A Number that also carries a one-sigma uncertainty (standard error).\n *\n * The uncertainty counterpart of {@link numberValueExact}: the type stays\n * {@link ValueType.Number} and `value` stays the center, so this reads as an\n * ordinary number everywhere. The `uncertainty` sidecar is what lets `+`, `-`,\n * `*`, `/` propagate the tolerance in quadrature. The `±` operator produces\n * this (see the MAKE_UNCERTAIN opcode), as does any of those four ops when an\n * operand already carries one. The magnitude is stored as given, callers pass a\n * non-negative value (`Math.abs` at the seam, quadrature results are already\n * non-negative).\n */\nexport function numberValueUncertain(n: number, uncertainty: number): Value {\n\tconst v = numberValue(n);\n\tv.uncertainty = uncertainty;\n\treturn v;\n}\n\n/** Which base a {@link ValueType.Hex} value is displayed in. */\nexport type DisplayBase = \"hex\" | \"bin\" | \"oct\";\n\n/**\n * Create a Hex-typed Value: a **number** that displays in another base.\n *\n * The type is numeric on purpose, and that is the whole point of it. A base is\n * a way of writing a quantity, not a different kind of quantity, so `0xFF + 1`\n * has to be 256. Returning a string instead makes it 1, because a string reads\n * as zero in arithmetic, and nothing about that failure is visible at the point\n * of use.\n *\n * @param n - The number itself, in full precision. A `bigint` is accepted for\n * the same reason the type is numeric at all: `12345678901234567890n as hex`\n * has an exact answer, and forcing it through a double first rendered\n * 0xAB54A98CEB1F0800 for a value ending 0AD2.\n * @param base - How to display it, defaulting to hexadecimal. Carried in the\n * `unit` slot, which is free for this type.\n */\nexport function hexValue(n: number | bigint, base: DisplayBase = \"hex\"): Value {\n\tconst tag = base === \"hex\" ? undefined : base;\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Hex, n, tag);\n\treturn new Value(ValueType.Hex, n, tag);\n}\n\n/** Create a BigInt-typed Value (arbitrary-precision integer). */\nexport function bigIntValue(n: bigint): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.BigInt, n);\n\treturn new Value(ValueType.BigInt, n);\n}\n\n/** Create a String-typed Value. */\nexport function stringValue(s: string): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.String, s);\n\treturn new Value(ValueType.String, s);\n}\n\n/** Create a Unit-of-Measurement Value (typed number with unit annotation). */\nexport function uomValue(n: number, unit: string): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Uom, n, unit);\n\treturn new Value(ValueType.Uom, n, unit);\n}\n\n/**\n * A unit-of-measurement Value that also carries an exact decimal magnitude.\n *\n * This is how money keeps its precision: `value` is the nearest double (so\n * `toNumber()` and every existing Uom path are unchanged), and `exact` is the\n * decimal the amount really is. Same-currency arithmetic reads `exact` to stay\n * exact, and the formatter reads it to round a half-cent the way a ledger does\n * rather than the way `toFixed` does on a double.\n */\nexport function uomValueExact(n: number, unit: string, exact: DecimalData): Value {\n\tconst v = uomValue(n, unit);\n\tv.exact = exact;\n\treturn v;\n}\n\n// ── Rate, \"quantity per unit of something\" (SoulverCore: `$99/week`\n// `3 hours/day`, `30 fps`). Represented as a `ValueType.Uom` (no new\n// ValueType, a rate IS a unit-of-measurement, just a compound one) whose\n// `unit` string is `\"<numerator>/<denominator>\"`. The numerator is an\n// opaque label (may be a real convertible unit like \"USD\"/\"km\", or a bare\n// tag like \"frames\" that the `convert` package doesn't know about, rate\n// arithmetic never needs to convert the numerator, only compare it for\n// equality when combining two rates). The denominator MUST be a unit\n// `convertUnit()`/`getMeasure()` (uom/UomConverter.ts) recognizes, since\n// that's the part rate arithmetic actually rescales. See `vm/VM.ts`'s\n// `RATE_CONVERT`/`RATE_MUL`/`RATE_DIV` opcodes for the operations built on\n// this representation.\n\n/** Create a Rate value: `magnitude` of `numeratorUnit` per one `denominatorUnit`. */\nexport function rateValue(magnitude: number, numeratorUnit: string, denominatorUnit: string): Value {\n\treturn uomValue(magnitude, `${numeratorUnit}/${denominatorUnit}`);\n}\n\n/** Whether `unit` is a compound rate unit (`\"X/Y\"`) rather than a plain unit. */\nexport function isRateUnit(unit: string | undefined): unit is string {\n\treturn typeof unit === \"string\" && unit.includes(\"/\");\n}\n\n/**\n * Split a rate unit string into its numerator/denominator halves.\n * @throws if `unit` isn't a rate unit, check with {@link isRateUnit} first.\n */\nexport function splitRateUnit(unit: string): { numerator: string; denominator: string } {\n\tconst idx = unit.indexOf(\"/\");\n\tif (idx < 0) {\n\t\tthrow ErrorFactory.internal(\n\t\t\t\"INVALID_RATE_UNIT\",\n\t\t\t`splitRateUnit: \"${unit}\" is not a rate unit (expected \"numerator/denominator\")`,\n\t\t\t{ unit },\n\t\t);\n\t}\n\treturn { numerator: unit.slice(0, idx), denominator: unit.slice(idx + 1) };\n}\n\n/** Join a numerator/denominator pair back into a rate unit string. */\nexport function joinRateUnit(numeratorUnit: string, denominatorUnit: string): string {\n\treturn `${numeratorUnit}/${denominatorUnit}`;\n}\n\n// ── Video timecode, \"HH:MM:SS:FF at a given fps\" (SoulverCore: video\n// editing timecode literals, e.g. `01:02:03:04 at 30fps`). Represented the\n// same way Rate is above: NOT a new ValueType, just a `ValueType.Uom` whose\n// `unit` string is `\"timecode@<fps>\"` and whose numeric `value` is the\n// TOTAL FRAME COUNT since 00:00:00:00 at that fps, e.g. \"00:00:01:00 at\n// 30fps\" is `Uom(30, \"timecode@30\")`.\n//\n// Storing the total frame count (rather than four separate H/M/S/F fields)\n// means ordinary integer addition/subtraction on the numeric value is\n// ALREADY correct carry/borrow-aware arithmetic with zero extra logic\n// e.g. \"frame 29 + 2 frames\" at 30fps is just `29 + 2 = 31`, and 31 total\n// frames at 30fps IS frame 1 of the next second, with no explicit carry\n// step required. Carry/borrow only needs to be reconstructed when\n// converting a total frame count back into HH:MM:SS:FF display notation\n// see `packages/time/timecode/TimecodeMath.ts`'s `framesToTimecodeString()`.\n// See `vm/VM.ts`'s ADD/SUB dispatch for the arithmetic built on this\n// representation (timecode + frames, + duration, + timecode, - timecode).\n\nconst TIMECODE_UNIT_PREFIX = \"timecode@\";\n\n/** Build a timecode Uom unit string embedding its frame rate, e.g. `timecodeUnit(30)` -> `\"timecode@30\"`. */\nexport function timecodeUnit(fps: number): string {\n\treturn `${TIMECODE_UNIT_PREFIX}${fps}`;\n}\n\n/** Whether `unit` is a compound video-timecode unit (`\"timecode@<fps>\"`). */\nexport function isTimecodeUnit(unit: string | undefined): unit is string {\n\treturn typeof unit === \"string\" && unit.startsWith(TIMECODE_UNIT_PREFIX);\n}\n\n/**\n * Extract the fps from a timecode unit string.\n * @throws if `unit` isn't a timecode unit, check with {@link isTimecodeUnit} first.\n */\nexport function timecodeFps(unit: string): number {\n\tif (!isTimecodeUnit(unit)) {\n\t\tthrow ErrorFactory.internal(\n\t\t\t\"INVALID_TIMECODE_UNIT\",\n\t\t\t`timecodeFps: \"${unit}\" is not a timecode unit (expected \"timecode@<fps>\")`,\n\t\t\t{ unit },\n\t\t);\n\t}\n\treturn parseFloat(unit.slice(TIMECODE_UNIT_PREFIX.length));\n}\n\n/**\n * Create a Matrix value from an explicit shape + column-major data array.\n * `data.length` must equal `rows*cols`, callers building a matrix from\n * row-major source syntax (e.g. the `[1,2;3,4]` literal) must transpose\n * into column-major order before calling this; see `MatrixOps.ts`'s\n * `rowMajorToColumnMajor()`.\n */\nexport function matrixValue(rows: number, cols: number, data: readonly MatrixEntry[]): Value {\n\t// Every matrix in the engine is born here, which makes this the one place\n\t// that can charge for one without each producer having to remember to. The\n\t// charge lands after `data` exists, so it is a backstop rather than a\n\t// refusal: it cannot stop a single allocation that is already fatal (the\n\t// sites whose size is knowable in advance charge before allocating, see\n\t// `vm/VM.ts`'s matrix cases), but it does stop the second one, and it means\n\t// an opcode added later inherits the bound without being told about it.\n\t// Free in relative terms: the hasSymbolic scan just below is already O(n)\n\t// over the same cells.\n\tchargeAllocation(data.length, \"matrix cells\");\n\t// A SymbolicNode cell is the only object-typed MatrixEntry variant\n\t// (number/boolean are primitives), a cheap, always-correct way to\n\t// derive hasSymbolic without asking every caller to track it by hand.\n\t// The `\"kind\" in cell` half is a tripwire, not redundancy. MatrixEntry is\n\t// `number | boolean | SymbolicNode`, so an object cell should always be a\n\t// node; requiring the discriminant means a Rational that escaped\n\t// MatrixOps.ts's symbolicToEntry() shows up as a wrong result rather than as\n\t// a matrix that silently believes it is symbolic.\n\tconst hasSymbolic = data.some(cell => typeof cell === \"object\" && cell !== null && \"kind\" in cell);\n\tconst m: MatrixData = { rows, cols, data, hasSymbolic };\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Matrix, m);\n\treturn new Value(ValueType.Matrix, m);\n}\n\n/** A 1×N row-vector Matrix, row-major and column-major storage are identical for a single row. */\nexport function rowVectorValue(data: readonly number[]): Value {\n\treturn matrixValue(1, data.length, data);\n}\n\n/** An N×1 column-vector Matrix, row-major and column-major storage are identical for a single column. */\nexport function colVectorValue(data: readonly number[]): Value {\n\treturn matrixValue(data.length, 1, data);\n}\n\n/** Create a Range value, a first-class integer range `min:max`, both bounds inclusive. */\nexport function rangeValue(min: number, max: number): Value {\n\tconst r: RangeData = { min, max };\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Range, r);\n\treturn new Value(ValueType.Range, r);\n}\n\n/**\n * Create a Colour value from canonical sRGB channels plus a display format.\n * Arena-backed like the other synchronous factories; the `ColourData` struct in\n * the `value` slot is immutable, so arena recycle is safe with no extra clearing\n * (matching {@link matrixValue}/{@link rangeValue}).\n */\nexport function colourValue(c: ColourData): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Colour, c);\n\treturn new Value(ValueType.Colour, c);\n}\n\n/**\n * Create a Split value from its structured per-share payload. Arena-backed like\n * the other synchronous factories; the {@link SplitData} struct in the `value`\n * slot is immutable, so arena recycle is safe with no extra clearing (matching\n * {@link colourValue}/{@link rangeValue}).\n */\nexport function splitValue(data: SplitData): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Split, data);\n\treturn new Value(ValueType.Split, data);\n}\n\n/** Create a Chart value from its specification. Arena-backed like the other\n * struct factories; the {@link ChartData} in the `value` slot is immutable, so\n * arena recycle is safe with no extra clearing. */\nexport function chartValue(data: ChartData): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Chart, data);\n\treturn new Value(ValueType.Chart, data);\n}\n\n/** Create an IPv4 address/subnet Value. Arena-backed; the {@link IpCidrData} is immutable. */\nexport function ipCidrValue(data: IpCidrData): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.IpCidr, data);\n\treturn new Value(ValueType.IpCidr, data);\n}\n\n/** Create a Symbolic value, a free-variable algebraic expression tree (`symbolic/SymbolicNode.ts`'s `SymbolicNode`), not a concrete number. */\nexport function symbolicValue(node: SymbolicNode): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Symbolic, node);\n\treturn new Value(ValueType.Symbolic, node);\n}\n\n\n\n/** Create a Boolean-typed Value. */\nexport function boolValue(b: boolean): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Boolean, b);\n\treturn new Value(ValueType.Boolean, b);\n}\n\n/** Create a Datetime-typed Value (Unix timestamp in milliseconds). */\nexport function datetimeValue(n: number): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Datetime, n);\n\treturn new Value(ValueType.Datetime, n);\n}\n\n/** Create a Percentage-typed Value (stored as fraction, e.g. 0.5 for 50%). */\nexport function percentageValue(n: number): Value {\n\tif (_arenaActive && _arena) return _arena.acquire(ValueType.Percentage, n);\n\treturn new Value(ValueType.Percentage, n);\n}\n\n/**\n * Create a Pending value, signals that an async result is not yet resolved.\n * The value field stores the queryKey string for deduplication and diagnostics.\n * Pending values should NEVER be stored in the arena (they persist across\n * scroll frames until resolution completes).\n */\nexport function pendingValue(queryKey: string): Value {\n\treturn new Value(ValueType.Pending, queryKey);\n}\n\n/**\n * Create an Error value, propagated through the DAG when a plugin raises an error.\n * The value field stores the EngineError code, unit stores the message.\n * Downstream consumers (lines that depend on errored data) bubble this up.\n * Should NEVER be stored in the arena.\n */\nexport function errorValue(code: string, message: string): Value {\n\treturn new Value(ValueType.Error, code, message);\n}\n\n/**\n * The first operand carrying a fault rather than a quantity, if any does.\n *\n * `Error` and `Pending` both read as the number 0 through {@link Value.toNumber},\n * by a convention that only holds up as long as nothing asks. Every opcode and\n * builtin that reaches for an operand's number without asking its type first\n * therefore computes with a zero it cannot tell apart from a real one, and\n * hands back an answer dressed in whatever type it was going to produce\n * anyway. That is how `(5 kg to m) to s` came to answer `0.00 s`: the failed\n * conversion is an Error, the second conversion read it as zero, and the unit\n * the reader asked for made the result look like a conversion that worked.\n *\n * Operands are checked left to right, matching evaluation order, and the\n * faulted Value is returned AS IT IS rather than replaced with a fresh one, so\n * the original code and message (or the pending query key) reach the caller\n * unchanged. `binaryOp` (vm/VMConversion.ts) and `OpCode.EXP` already did this\n * inline; this is the same rule for every other site, in one place so a site\n * added later can adopt it in a line.\n *\n * Three operands cover every call site in the VM (`MAT_INDEX2` and `MAT_SLICE`\n * are the widest). A variadic signature would allocate an arguments array on\n * paths that run per instruction; see {@link faultedIn} for the list case.\n *\n * @returns The faulted operand, or `null` when all of them carry a value.\n */\nexport function faultedOperand(a: Value, b?: Value, c?: Value): Value | null {\n\tif (a.type === ValueType.Error || a.type === ValueType.Pending) return a;\n\tif (b !== undefined && (b.type === ValueType.Error || b.type === ValueType.Pending)) return b;\n\tif (c !== undefined && (c.type === ValueType.Error || c.type === ValueType.Pending)) return c;\n\treturn null;\n}\n\n/**\n * {@link faultedOperand} over an already-built list, for the call sites that\n * have one (a builtin's arguments, a plugin function's).\n *\n * @returns The first faulted element, or `null` when every element carries a value.\n */\nexport function faultedIn(values: readonly Value[]): Value | null {\n\tfor (let i = 0; i < values.length; i++) {\n\t\tconst v = values[i];\n\t\tif (v.type === ValueType.Error || v.type === ValueType.Pending) return v;\n\t}\n\treturn null;\n}\n"]}
|
package/dist/chunk-C65UDMWH.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkSNVPM27Q_cjs=require('./chunk-SNVPM27Q.cjs'),chunk5IJD5L3O_cjs=require('./chunk-5IJD5L3O.cjs'),chunkSOMGSIO4_cjs=require('./chunk-SOMGSIO4.cjs');var v={maxPasses:100,maxTokens:1e4,onFusion:()=>{}};function N(a,e,r){let n=r[0],o=r[r.length-1],t=new chunkSNVPM27Q_cjs.a(a,chunk5IJD5L3O_cjs.c(a),e,e,n.offset,n.lineBreaks??0,n.line,n.col);return t.sourceEnd=o.sourceEnd??o.offset+o.text.length,t}function C(a,e){let r=e[e.length-1];r&&(a.sourceEnd=r.sourceEnd??r.offset+r.text.length);}var w=["NUMBER","HEX","BIGINT","FLOAT","LSHIFT","RSHIFT","BIT_AND","BIT_OR","BIT_XOR","LPAREN","RPAREN","LBRACKET","RBRACKET","COMMA","COLON","EQUALS","THEREFORE","PIPE","AMPERSAND","AT","SEMICOLON","QUESTION","EXCLAMATION","EOF","WS","NEWLINE"],I=(()=>{let a=w.map(n=>chunk5IJD5L3O_cjs.c(n)),e=Math.max(...a)+1,r=new Uint8Array(e);for(let n of a)r[n]=1;return r})(),L=class{constructor(e={}){this.rules=[];this.sortedRulesCache=null;this.phraseTrie=new T;this.options={...v,...e};}register(e){this.rules.push(e),this.sortedRulesCache=null;}unregister(e){this.rules=this.rules.filter(r=>r.name!==e),this.sortedRulesCache=null;}clear(){this.rules=[],this.sortedRulesCache=null,this.phraseTrie=new T;}getSortedRules(){return this.sortedRulesCache===null&&(this.sortedRulesCache=[...this.rules].sort((e,r)=>r.priority-e.priority)),this.sortedRulesCache}get ruleCount(){return this.rules.length}addPhrase(e,r){this.phraseTrie.addPhrase(e,r);}getPhrases(){return this.phraseTrie.getAllPhrases()}canStartPhrase(e){return this.phraseTrie.canStart(e)}normalize(e,r){if(e.length===0)return e;let n=this.getSortedRules(),o=r??this.options.onFusion,t=this.options.maxPasses,s=this.options.maxTokens,i=e,m=true,p=0;for(;m&&p<t;){m=false,p++;let h=[],u=0;for(;u<i.length;){let E=false,y=i[u].typeId;if(y>=I.length||I[y]===0){let c=this.phraseTrie.matchAt(i,u);if(c){let l=i.slice(u,u+c.consumed);for(let d of c.replacement)h.push(d);c.consumed>1&&c.replacement.length===1&&(C(c.replacement[0],l),o({rule:c.ruleName??"phrase-trie",sourceTokens:l,fusedToken:c.replacement[0]})),u+=c.consumed,m=true;continue}}for(let c of n){let l=c.match(i,u);if(l){let d=i.slice(u,u+l.consumed);for(let g of l.replacement)h.push(g);if(l.consumed>1&&l.replacement.length===1)C(l.replacement[0],d),o({rule:c.name,sourceTokens:d,fusedToken:l.replacement[0]});else if(l.consumed>1&&l.replacement.length<l.consumed)for(let g of l.replacement)o({rule:c.name,sourceTokens:d,fusedToken:g});u+=l.consumed,m=true,E=true;break}}E||(h.push(i[u]),u++);}if(h.length>s)throw chunkSOMGSIO4_cjs.c.validation("NORMALIZED_TOKEN_LIMIT_EXCEEDED",`Normalized token count (${h.length}) exceeds safety limit (${s})`,{tokenCount:h.length,maxTokens:s});i=h;}return i}};var T=class{constructor(){this.startWords=new Set;this.root=new Map;}addPhrase(e,r){let n=e.toLowerCase().trim().split(/\s+/);if(n.length===0||n[0]==="")return;this.startWords.add(n[0]);let o=n[0],t;if(this.root.has(o)?t=this.root.get(o):(t={children:new Map,terminal:null},this.root.set(o,t)),n.length===1){t.terminal={tokenType:r,phrase:e,consumed:1};return}for(let s=1;s<n.length;s++){let i=n[s];t.children.has(i)||t.children.set(i,{children:new Map,terminal:null}),t=t.children.get(i);}t.terminal={tokenType:r,phrase:e,consumed:n.length};}matchAt(e,r){if(r>=e.length)return null;let n=e[r].type;if(n==="TAG"||n.startsWith("TAG_"))return null;let o=e[r].value.toLowerCase();if(!this.startWords.has(o))return null;let t=this.root.get(o);if(!t)return null;let s=null,i=1;if(t.terminal){let m=e.slice(r,r+1);s={consumed:1,replacement:[N(t.terminal.tokenType,t.terminal.phrase,m)],ruleName:t.terminal.phrase};}for(let m=r+1;m<e.length&&t?.children;m++){let p=e[m].type;if(p==="TAG"||p.startsWith("TAG_"))break;let h=e[m].value.toLowerCase();if(t=t.children.get(h),!t)break;if(i++,t.terminal){let u=e.slice(r,r+i);s={consumed:i,replacement:[N(t.terminal.tokenType,t.terminal.phrase,u)],ruleName:t.terminal.phrase};}}return s}get size(){return this.root.size}getAllPhrases(){let e={},r=(n,o)=>{n.terminal&&(e[o.join(" ")]=n.terminal.tokenType);for(let[t,s]of n.children)r(s,[...o,t]);};for(let[n,o]of this.root)r(o,[n]);return e}canStart(e){return this.startWords.has(e.toLowerCase())}};var S=new Set(["per","a","an","each","every"]),k=new Set(["to","power","increase","decrease","times","multiply","divide","by"]);function x(a=50,e){let r=e??(n=>k.has(n.toLowerCase()));return {name:"implicit:multiply",priority:a,match(n,o){if(o+1>=n.length)return null;let t=n[o],s=n[o+1],i=s.value.toLowerCase();if(r(i)||S.has(i)&&n[o+2]?.type==="UNIT"||!((t.type==="NUMBER"||t.type==="RPAREN")&&(s.type==="IDENT"||s.type==="LPAREN"||s.type==="PI"||s.type==="E")))return null;let p=new chunkSNVPM27Q_cjs.a("STAR",chunk5IJD5L3O_cjs.c("STAR"),"*","*",s.offset,0,s.line,s.col);return {consumed:1,replacement:[t,p]}}}}function W(a,e){let r=[];for(let n=0;n<e;n++){let o=a[n];if(o.type==="LBRACKET")r.push(true);else if(o.type==="LPAREN"){let t=a[n-1],s=!!t&&(t.type==="MAP"||t.type==="REDUCE"||t.type==="SUM_FN"||t.type==="PROD_FN"||t.type==="IDENT"&&(t.value.toLowerCase()==="map"||t.value.toLowerCase()==="reduce"||t.value.toLowerCase()==="sum"||t.value.toLowerCase()==="prod"));r.push(s);}else (o.type==="RBRACKET"||o.type==="RPAREN")&&r.pop();}return r.length>0&&r[r.length-1]}function U(){return [x()]}var Y={"to the power of":"CARET","power of":"CARET","increase by":"INCREASE_BY","decrease by":"DECREASE_BY","times by":"TIMES_BY","multiply by":"MULTIPLY_BY","divide by":"DIVIDE_BY","multiplied by":"MULTIPLY_BY","divided by":"DIVIDE_BY"};exports.a=T;exports.b=N;exports.c=L;exports.d=x;exports.e=W;exports.f=U;exports.g=Y;//# sourceMappingURL=chunk-C65UDMWH.cjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-C65UDMWH.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/normalizer/TokenNormalizer.ts","../src/normalizer/PhraseTrie.ts","../src/normalizer/BuiltinNormalizerRules.ts"],"names":["DEFAULT_OPTIONS","createFusedToken","type","text","sourceTokens","first","last","token","LexerToken","tokenTypeId","recordSourceSpan","fused","NON_WORD_NAMES","NON_WORD_TABLE","ids","len","table","id","TokenNormalizer","options","PhraseTrie","rule","ruleName","a","b","phrase","tokenType","word","tokens","onFusion","sorted","fusionHandler","maxPasses","maxTokens","current","changed","passCount","result","pos","matched","tid","trieMatch","rt","match","ErrorFactory","words","firstWord","node","i","startType","best","depth","contType","collect","path","child","RATE_DENOMINATOR_WORDS","PHRASE_START_WORDS","implicitMultiplyRule","priority","canStart","phraseGuard","next","nextValue","starToken","isInsideRangeContext","safeStack","t","prev","opensMapReduceCall","createBuiltinNormalizerRules","BUILTIN_PHRASES"],"mappings":"uKA2EA,IAAMA,CAAAA,CAA+C,CACnD,SAAA,CAAW,GAAA,CACX,UAAW,GAAA,CACX,QAAA,CAAU,IAAM,CAAC,CACnB,CAAA,CAwBO,SAASC,CAAAA,CACdC,EACAC,CAAAA,CACAC,CAAAA,CACO,CACP,IAAMC,CAAAA,CAAQD,CAAAA,CAAa,CAAC,CAAA,CACtBE,EAAOF,CAAAA,CAAaA,CAAAA,CAAa,MAAA,CAAS,CAAC,EAC3CG,CAAAA,CAAQ,IAAIC,mBAAAA,CAChBN,CAAAA,CACAO,oBAAYP,CAAI,CAAA,CAChBC,CAAAA,CACAA,CAAAA,CACAE,CAAAA,CAAM,MAAA,CACNA,CAAAA,CAAM,UAAA,EAAc,EACpBA,CAAAA,CAAM,IAAA,CACNA,CAAAA,CAAM,GACR,EAGA,OAAAE,CAAAA,CAAM,SAAA,CAAYD,CAAAA,CAAK,WAAaA,CAAAA,CAAK,MAAA,CAASA,CAAAA,CAAK,IAAA,CAAK,MAAA,CACrDC,CACT,CAkBA,SAASG,EAAiBC,CAAAA,CAAcP,CAAAA,CAA6B,CACnE,IAAME,EAAOF,CAAAA,CAAaA,CAAA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AYA,CAAAA,CAAK,IAAA,GAAS,SAAA,EACxFA,EAAK,IAAA,GAAS,OAAA,GAAYA,CAAAA,CAAK,KAAA,CAAM,WAAA,EAAY,GAAM,KAAA,EAASA,CAAAA,CAAK,MAAM,WAAA,EAAY,GAAM,QAAA,EAAYA,CAAAA,CAAK,MAAM,WAAA,EAAY,GAAM,KAAA,EAASA,CAAAA,CAAK,MAAM,WAAA,EAAY,GAAM,MAAA,CAAA,CAAA,CAE/KF,CAAAA,CAAU,IAAA,CAAKG,CAAkB,EACnC,CAAA,KAAA,CAAWF,EAAE,IAAA,GAAS,UAAA,EAAcA,CAAAA,CAAE,IAAA,GAAS,WAC7CD,CAAAA,CAAU,GAAA,GAEd,CACA,OAAOA,CAAAA,CAAU,MAAA,CAAS,CAAA,EAAKA,CAAAA,CAAUA,CAAAA,CAAU,MAAA,CAAS,CAAC,CAC/D,CAoBO,SAASI,CAAAA,EAAiD,CAC/D,OAAO,CAELZ,CAAAA,EACF,CACF,KASaa,CAAAA,CAA0C,CACtD,iBAAA,CAAmB,OAAA,CACnB,UAAA,CAAY,OAAA,CACZ,aAAA,CAAe,aAAA,CACf,cAAe,aAAA,CACf,UAAA,CAAY,UAAA,CACZ,aAAA,CAAe,cACf,WAAA,CAAa,WAAA,CAKb,eAAA,CAAiB,aAAA,CACjB,aAAc,WACf","file":"chunk-C65UDMWH.cjs","sourcesContent":["//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * TokenNormalizer, post-lexer token normalization pass.\n *\n * ## Purpose\n * Applies domain-specific {@link NormalizerRule | NormalizerRules} to the raw\n * token stream produced by the {@link ExpressionLexer}. This keeps the lexer\n * slim and focused on single-token production, while multi-token pattern\n * matching (phrases, implicit operators, domain merges) lives here.\n *\n * ## What rules can do\n * - **Phrase fusion**: Merge consecutive words into compound tokens\n * (e.g., `IDENT + ... + IDENT` → `CARET`)\n * - **Implicit operator insertion**: Insert missing operators between tokens\n * (e.g., `NUMBER IDENT` → `NUMBER STAR IDENT`)\n * - **Domain-specific transformations**: Coalesce item names, currency pairs,\n * percentage syntax, etc.\n *\n * ## Architecture\n * Providers register NormalizerRules alongside Parselets and OpCode handlers\n * via {@link IEnginePackage.normalizerRules}. The normalizer applies them\n * greedily left-to-right in multiple passes with safety limits.\n *\n * @module TokenNormalizer\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, TokenFusion } from \"./NormalizerRule\";\nimport { PhraseTrie } from \"./PhraseTrie\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n//#endregion\n//#region ─── NormalizerOptions, Configuration ────────────────────────────────\n\n/**\n * Configuration options for the normalization pass.\n *\n * These control safety limits and diagnostic callbacks. The defaults\n * are chosen to be generous enough for any realistic expression while\n * preventing runaway token expansion from recursive rules.\n */\nexport interface NormalizerOptions {\n /**\n * Maximum number of full passes over the token stream before bailing out.\n * Prevents infinite loops from recursive rule chains.\n * @default 100\n */\n maxPasses?: number;\n\n /**\n * Maximum number of tokens allowed after normalization.\n * If exceeded, an Error is thrown rather than passing a bloated stream\n * to the parser.\n * @default 10000\n */\n maxTokens?: number;\n\n /**\n * Callback invoked for each fusion event during normalization.\n * Used by diagnostic mode to populate {@link NormalizerOutput.fusions}.\n * When `undefined`, fusions are still tracked internally but no callbacks fire.\n */\n onFusion?: (fusion: TokenFusion) => void;\n}\n\n//#endregion\n//#region ─── Default Options ──────────────────────────────────────────────────\n\n/** Sensible defaults that catch infinite loops without limiting real expressions. */\nconst DEFAULT_OPTIONS: Required<NormalizerOptions> = {\n maxPasses: 100,\n maxTokens: 10000,\n onFusion: () => {},\n};\n\n//#endregion\n//#region ─── createFusedToken, Token Factory ──────────────────────────────────\n\n/**\n * Creates a new normalized token from fused source tokens.\n *\n * The fused token inherits position information (offset, line, column)\n * from the first source token, which preserves source-map accuracy\n * for error messages and diagnostic highlighting.\n *\n * It also records where the source text ENDS, on `sourceEnd`. The start alone\n * is not enough to describe the span a fusion covers, because `text` is the\n * replacement rather than the original: `10 frames` fuses into a FRAME_COUNT\n * whose text is `10`, and a timecode fuses into a token whose text is a\n * comma-separated tuple that appears nowhere in the line. Anything painting the\n * line needs both ends, and only this function is in a position to know them.\n *\n * @param type - The new token type (e.g., \"CARET\", \"TIMES_BY\")\n * @param text - The combined text representation (e.g., \"to the power of\")\n * @param sourceTokens - The original tokens being fused (at least 2)\n * @returns A new {@link LexerToken} with the fused type and combined text\n */\nexport function createFusedToken(\n type: string,\n text: string,\n sourceTokens: Token[]\n): Token {\n const first = sourceTokens[0];\n const last = sourceTokens[sourceTokens.length - 1];\n const token = new LexerToken(\n type,\n tokenTypeId(type),\n text,\n text,\n first.offset,\n first.lineBreaks ?? 0,\n first.line,\n first.col,\n );\n // `text`, not `value`: this is where the SOURCE ended, and the two differ\n // for a string literal, whose value is the payload without its quotes.\n token.sourceEnd = last.sourceEnd ?? last.offset + last.text.length;\n return token;\n}\n\n/**\n * Record, on a token that replaced several, where its source text ended.\n *\n * Called centrally rather than left to each rule. A rule that builds its\n * replacement by hand rather than through {@link createFusedToken} is doing\n * nothing wrong, and several do: the date-literal rule needs a token whose\n * value is an epoch and whose text is the source, which that factory cannot\n * express. Stamping here means every fusion carries its span, including ones\n * written after this was.\n *\n * Reads `sourceEnd` off the last source token when it has one, so a fusion of\n * a fusion still describes the original text rather than the intermediate.\n *\n * @param fused - The single token the rule produced.\n * @param sourceTokens - The tokens it consumed.\n */\nfunction recordSourceSpan(fused: Token, sourceTokens: Token[]): void {\n const last = sourceTokens[sourceTokens.length - 1];\n if (!last) return;\n fused.sourceEnd = last.sourceEnd ?? last.offset + last.text.length;\n}\n\n//#endregion\n//#region ─── NON_WORD_TOKEN_TYPES, Type-guard skip set ────────────────────────\n\n/**\n * Token types that can NEVER start a multi-word phrase.\n *\n * Used by {@link normalize} to skip the PhraseTrie walk entirely at\n * positions where the token type makes phrase matching impossible.\n * This avoids even the O(1) {@link PhraseTrie.canStart} check.\n *\n * Types NOT in this set (IDENT, KEYWORD, FUNC, UNIT, and any custom\n * types registered by packages) still pass through to the trie for\n * a full match attempt.\n */\n// ── Non-word type ID lookup table (flat Uint8Array, true O(1) array index) ──\n//\n// Index = token typeId, value = 1 if non-word (skip trie), 0 otherwise.\n// Array indexing avoids ALL hashing: no Set.has(), no Map.get(), no string ops.\n//\n// Custom types from packages get IDs beyond the table length, so the bounds\n// check `tid < TABLE.length` safely passes them through to the trie.\n//\n// Arithmetic operators (PLUS, MINUS, STAR, SLASH, CARET, MOD, PERCENT) are\n// intentionally excluded: in keyword locales the lexer maps \"times\"→STAR,\n// \"divide\"→SLASH etc., and those tokens CAN start phrases like \"times by\".\n/**\n * Token type names that can NEVER start a multi-word phrase.\n *\n * Exported for testing only, consumers should use the type-guard behavior\n * of {@link TokenNormalizer.normalize} rather than this list directly.\n */\nexport const NON_WORD_NAMES = [\n\t\"NUMBER\", \"HEX\", \"BIGINT\", \"FLOAT\",\n\t\"LSHIFT\", \"RSHIFT\", \"BIT_AND\", \"BIT_OR\", \"BIT_XOR\",\n\t\"LPAREN\", \"RPAREN\", \"LBRACKET\", \"RBRACKET\",\n\t\"COMMA\", \"COLON\", \"EQUALS\", \"THEREFORE\", \"PIPE\", \"AMPERSAND\", \"AT\",\n\t\"SEMICOLON\", \"QUESTION\", \"EXCLAMATION\",\n\t\"EOF\", \"WS\", \"NEWLINE\",\n] as const;\n\n/**\n * Flat Uint8Array lookup table: index = token typeId, value = 1 if non-word.\n *\n * Exported for testing only, consumers should not depend on the internal\n * table layout, as the set of non-word types may change.\n */\nexport const NON_WORD_TABLE: Uint8Array = (() => {\n\t// Resolve all non-word type names to their numeric IDs\n\tconst ids = NON_WORD_NAMES.map(n => tokenTypeId(n));\n\t// Size the table to cover the largest ID + 1\n\tconst len = Math.max(...ids) + 1;\n\tconst table = new Uint8Array(len);\n\t// Mark non-word type positions\n\tfor (const id of ids) table[id] = 1;\n\treturn table;\n})();\n\n//#endregion\n//#region ─── TokenNormalizer Class ─────────────────────────────────────────────\n\n/**\n * Token normalizer: applies {@link NormalizerRule | NormalizerRules} to a token stream.\n *\n * ## Lifecycle\n * 1. **Registration**: Rules are added via {@link register} and sorted by priority\n * 2. **Normalization**: {@link normalize} applies rules greedily left-to-right\n * 3. **Cleanup**: {@link clear} or {@link unregister} removes rules\n *\n * ## Normalization algorithm\n * The normalizer uses a greedy left-to-right multi-pass algorithm:\n * - At each token position, rules are tried in priority order (highest first)\n * - When a rule matches, matched tokens are consumed and replaced\n * - Processing continues from the replacement position\n * - Multiple passes handle cascading matches (one rule's output triggers another)\n * - Safety limits ({@link NormalizerOptions.maxPasses}) prevent infinite loops\n *\n * @example\n * ```ts\n * const normalizer = new TokenNormalizer();\n * normalizer.register(phraseRule); // \"to the power of\" → CARET\n * normalizer.register(implicitMultRule); // \"2 x\" → \"2 * x\"\n * const normalized = normalizer.normalize(rawTokens);\n * ```\n */\nexport class TokenNormalizer {\n /** Registered rules, unsorted, the source of truth. */\n private rules: NormalizerRule[] = [];\n\n /**\n * Priority-sorted copy of {@link rules}, rebuilt lazily on the next\n * {@link normalize} call after a mutation. Rules are registered once at\n * engine/package-registration time and essentially never change during a\n * session, but normalize() runs on every keystroke-driven evaluation, an\n * earlier version re-sorted a fresh copy of `rules` on every single call,\n * which meant every keystroke paid for an allocation + sort of a list that\n * had usually not changed since the last one. `null` means \"stale, rebuild\n * on next use\"; {@link register}/{@link unregister}/{@link clear} all\n * invalidate it.\n */\n private sortedRulesCache: NormalizerRule[] | null = null;\n\n /**\n * Phrase trie for single-pass multi-word phrase fusion.\n * Tried at each token position BEFORE other rules, the trie walk\n * is O(depth) vs O(R × W) for separate rule matching.\n */\n private phraseTrie = new PhraseTrie();\n\n /** Merged options with defaults applied. */\n private options: Required<NormalizerOptions>;\n\n // ── Constructor ──────────────────────────────────────────────────────────\n\n /**\n * @param options - Configuration overrides for safety limits and diagnostic callbacks\n */\n constructor(options: NormalizerOptions = {}) {\n this.options = { ...DEFAULT_OPTIONS, ...options };\n }\n\n // ── Rule Management ──────────────────────────────────────────────────────\n\n /**\n * Register a normalization rule.\n *\n * Rules are sorted by priority (descending) on each {@link normalize} call.\n * Multiple rules can share the same priority, they are tried in registration\n * order when priorities are equal.\n *\n * @param rule - The rule to register\n */\n register(rule: NormalizerRule): void {\n this.rules.push(rule);\n this.sortedRulesCache = null;\n }\n\n /**\n * Unregister a normalization rule by its {@link NormalizerRule.name | name}.\n *\n * If multiple rules share the same name, all are removed. This is safe to\n * call with a name that doesn't match any rule, it simply has no effect.\n *\n * @param ruleName - The name of the rule to remove\n */\n unregister(ruleName: string): void {\n this.rules = this.rules.filter(r => r.name !== ruleName);\n this.sortedRulesCache = null;\n }\n\n /**\n * Remove all registered rules, resetting the normalizer to its initial state.\n * Also clears the phrase trie.\n */\n clear(): void {\n this.rules = [];\n this.sortedRulesCache = null;\n this.phraseTrie = new PhraseTrie();\n }\n\n /**\n * Priority-sorted view of {@link rules} (descending priority; registration\n * order preserved for ties, since {@link Array.prototype.sort} is stable).\n * Cached until the next mutation. See {@link sortedRulesCache}.\n */\n private getSortedRules(): NormalizerRule[] {\n if (this.sortedRulesCache === null) {\n this.sortedRulesCache = [...this.rules].sort((a, b) => b.priority - a.priority);\n }\n return this.sortedRulesCache;\n }\n\n /**\n * Get the number of currently registered rules (excludes phrase trie entries).\n */\n get ruleCount(): number {\n return this.rules.length;\n }\n\n // ── Phrase Registration ────────────────────────────────────────────────\n\n /**\n * Register a multi-word phrase for fusion into a single compound token.\n *\n * This is the preferred way to add phrase patterns. It inserts into the\n * internal {@link PhraseTrie}, which collapses all phrase rules into a\n * single O(depth) trie walk per position, no separate rule scanning.\n *\n * @param phrase - Multi-word phrase (e.g., \"to the power of\", \"abyssal whip\")\n * @param tokenType - Target token type after fusion (e.g., \"CARET\", \"ITEM\")\n */\n addPhrase(phrase: string, tokenType: string): void {\n this.phraseTrie.addPhrase(phrase, tokenType);\n }\n\n /**\n * Check whether a word can start any registered phrase.\n *\n * Used by {@link implicitMultiplyRule} to suppress `*` insertion\n * before phrase-starting identifiers (e.g., \"2 power of 3\" → `2 ^ 3`,\n * not `2 * power of 3`). Delegates to {@link PhraseTrie.canStart}.\n */\n /**\n * Get all registered phrases and their target token types.\n *\n * Exposes the full phrase trie structure for diagnostic rendering\n * in the playground's NormalizerTab. Returns ALL registered phrases,\n * not just the ones that matched in the last evaluation.\n */\n getPhrases(): Record<string, string> {\n return this.phraseTrie.getAllPhrases();\n }\n\n canStartPhrase(word: string): boolean {\n return this.phraseTrie.canStart(word);\n }\n\n // ── Normalization ────────────────────────────────────────────────────────\n\n /**\n * Normalize a token stream by applying all registered rules.\n *\n * ## Algorithm\n * Applies rules greedily left-to-right in multiple passes:\n * 1. Sort rules by priority (descending)\n * 2. Walk the token stream left to right\n * 3. At each position, try rules in priority order\n * 4. On match: consume matched tokens, insert replacements, restart from insert point\n * 5. On no match: pass token through unchanged\n * 6. Repeat until a full pass produces no changes, or maxPasses is reached\n *\n * ## Fusion tracking\n * When a rule consumes more tokens than it produces, the normalizer calls\n * `onFusion` with a {@link TokenFusion} record for diagnostic collection.\n * This populates {@link NormalizerOutput.fusions} in the playground pipeline view.\n *\n * ## Safety\n * If the normalized token count exceeds {@link NormalizerOptions.maxTokens},\n * an Error is thrown to prevent memory exhaustion from runaway rule expansion.\n *\n * @param tokens - Raw tokens from the lexer\n * @param onFusion - Optional fusion callback (overrides {@link NormalizerOptions.onFusion})\n * @returns Normalized tokens ready for parsing\n * @throws {Error} If the normalized token count exceeds maxTokens\n */\n normalize(tokens: Token[], onFusion?: (fusion: TokenFusion) => void): Token[] {\n // ── Early exit: nothing to normalize ──\n if (tokens.length === 0) return tokens;\n\n // ── Priority-sorted rules, cached across calls, see getSortedRules() ──\n const sorted = this.getSortedRules();\n const fusionHandler = onFusion ?? this.options.onFusion;\n const maxPasses = this.options.maxPasses;\n const maxTokens = this.options.maxTokens;\n\n let current = tokens;\n let changed = true;\n let passCount = 0;\n\n // Multi-pass loop: rules may trigger cascading matches across passes\n while (changed && passCount < maxPasses) {\n changed = false;\n passCount++;\n\n const result: Token[] = [];\n let pos = 0;\n\n // Single-pass left-to-right greedy walk\n while (pos < current.length) {\n let matched = false;\n\n // ── Fast path: phrase trie (O(depth) single walk vs O(R × W) per rule) ──\n // O(1) type-guard: skip trie entirely for tokens that can't start phrases.\n // Flat Uint8Array indexed by typeId, no hashing, no Set lookup, true O(1).\n const tid = current[pos].typeId;\n if (tid >= NON_WORD_TABLE.length || NON_WORD_TABLE[tid] === 0) {\n const trieMatch = this.phraseTrie.matchAt(current, pos);\n if (trieMatch) {\n const sourceTokens = current.slice(pos, pos + trieMatch.consumed);\n for (const rt of trieMatch.replacement) {\n result.push(rt);\n }\n if (trieMatch.consumed > 1 && trieMatch.replacement.length === 1) {\n recordSourceSpan(trieMatch.replacement[0], sourceTokens);\n fusionHandler({\n rule: trieMatch.ruleName ?? \"phrase-trie\",\n sourceTokens,\n fusedToken: trieMatch.replacement[0],\n });\n }\n pos += trieMatch.consumed;\n changed = true;\n continue; // trie matched — skip other rules at this position (no need to set matched)\n }\n }\n\n // Try every rule in priority order at this position\n for (const rule of sorted) {\n const match = rule.match(current, pos);\n if (match) {\n // Collect source tokens for fusion tracking\n const sourceTokens = current.slice(pos, pos + match.consumed);\n\n // Insert replacement tokens into result\n for (const rt of match.replacement) {\n result.push(rt);\n }\n\n // Track fusion events for diagnostics:\n // - Multiple tokens → single token: classic fusion\n // - Multiple tokens → fewer tokens: partial fusion\n if (match.consumed > 1 && match.replacement.length === 1) {\n recordSourceSpan(match.replacement[0], sourceTokens);\n fusionHandler({\n rule: rule.name,\n sourceTokens,\n fusedToken: match.replacement[0],\n });\n } else if (match.consumed > 1 && match.replacement.length < match.consumed) {\n for (const rt of match.replacement) {\n fusionHandler({\n rule: rule.name,\n sourceTokens,\n fusedToken: rt,\n });\n }\n }\n\n // Advance position past consumed tokens\n pos += match.consumed;\n changed = true;\n matched = true;\n break; // Rule matched — restart at new position with highest-priority rules\n }\n }\n\n if (!matched) {\n // No rule matched at this position, pass token through unchanged\n result.push(current[pos]);\n pos++;\n }\n }\n\n // Safety: bail if token count explodes (runaway rule expansion)\n if (result.length > maxTokens) {\n // A raw Error here would bypass ThreeTierEvaluator's DAG-preservation\n // enrichment on compile failure (it specifically checks for\n // EngineError). Same reasoning as ExpressionEngineSafety.ts's\n // complexity/length checks, which this mirrors.\n throw ErrorFactory.validation(\n \"NORMALIZED_TOKEN_LIMIT_EXCEEDED\",\n `Normalized token count (${result.length}) exceeds safety limit (${maxTokens})`,\n { tokenCount: result.length, maxTokens }\n );\n }\n\n current = result;\n }\n\n return current;\n }\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * PhraseTrie, optimized word-level trie for multi-word phrase fusion.\n *\n * ## Problem\n * The normalizer previously applied N separate `phraseFusionRule` instances,\n * each scanning forward from the current token position. For R phrase rules\n * and W average phrase length, this cost O(N × R × W) per pass.\n *\n * ## Solution\n * A single trie walk per position collapses all phrase rules into O(D)\n * where D ≤ longest phrase depth (typically ≤ 5 words). The trie tracks\n * the deepest terminal node reached, implementing longest-match-wins\n * without priority sorting.\n *\n * ## Optimizations\n * 1. **Set<string> quick-reject**, the `startWords` set contains the first\n * word of every registered phrase. At each position, if the token's\n * lowercase value isn't in the set, we bail in O(1) without touching\n * the trie. ~80% of tokens (numbers, operators) hit this fast path.\n * 2. **Longest-match-wins**, the `matchAt()` walk continues past terminal\n * nodes, tracking the deepest one. Shorter overlapping phrases (e.g.,\n * \"power of\") don't need lower priority, the trie naturally prefers\n * the longer match.\n * 3. **Map-based children**, `Map<string, TrieNode>` gives O(1) amortized\n * child lookup per word, faster than array scanning for sparse branches.\n *\n * ## Package integration\n * Packages add phrases via {@link TokenNormalizer.addPhrase} (public API)\n * or the {@link IEnginePackage.phrases} declarative field. Each call to\n * `addPhrase()` inserts the phrase into this trie and updates `startWords`.\n *\n * @module PhraseTrie\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport type { NormalizerMatch } from \"./NormalizerRule\";\nimport { createFusedToken } from \"./TokenNormalizer\";\n\n//#endregion\n//#region ─── TrieNode ─────────────────────────────────────────────────────────\n\n/**\n * Internal trie node.\n *\n * Each node represents a matched word in a phrase. The path from root\n * to a node spells out a partial or complete phrase.\n */\ninterface TrieNode {\n\t/** Child nodes keyed by next word (all lowercase). */\n\tchildren: Map<string, TrieNode>;\n\t/**\n\t * If this node completes a phrase, the terminal metadata.\n\t * A node can be both terminal AND have children. This handles\n\t * overlapping phrases like \"power of\" and \"to the power of\".\n\t */\n\tterminal: TrieTerminal | null;\n}\n\n/** Metadata stored at terminal nodes for deferred token creation. */\ninterface TrieTerminal {\n\t/** The target token type after fusion (e.g., \"CARET\", \"TIMES_BY\"). */\n\ttokenType: string;\n\t/** The original phrase string (e.g., \"to the power of\"). */\n\tphrase: string;\n\t/** Number of tokens consumed by this phrase. */\n\tconsumed: number;\n}\n\n//#endregion\n//#region ─── PhraseTrie ─────────────────────────────────────────────────────\n\n/**\n * Word-level trie for single-pass multi-word phrase matching.\n *\n * @example\n * ```ts\n * const trie = new PhraseTrie();\n * trie.addPhrase(\"to the power of\", \"CARET\");\n * trie.addPhrase(\"power of\", \"CARET\");\n * trie.addPhrase(\"abyssal whip\", \"ITEM\");\n *\n * // At position 0 with tokens [\"to\",\"the\",\"power\",\"of\",\"3\"]\n * const match = trie.matchAt(tokens, 0);\n * // → { consumed: 4, replacement: [CARET(\"to the power of\")] }\n * ```\n */\nexport class PhraseTrie {\n\t/**\n\t * First words that can start any registered phrase (all lowercase).\n\t * O(1) quick-reject: if `tokens[pos].value.toLowerCase()` isn't here,\n\t * no phrase can match at this position.\n\t */\n\tprivate startWords = new Set<string>();\n\n\t/**\n\t * Root maps first word → child node.\n\t * Two-level root avoids an unnecessary intermediate TrieNode.\n\t */\n\tprivate root = new Map<string, TrieNode>();\n\n\t// ── Registration ──────────────────────────────────────────────────────\n\n\t/**\n\t * Register a phrase for fusion into a single compound token.\n\t *\n\t * @param phrase - Multi-word phrase (e.g., \"to the power of\")\n\t * @param tokenType - Target token type after fusion (e.g., \"CARET\")\n\t */\n\taddPhrase(phrase: string, tokenType: string): void {\n\t\tconst words = phrase.toLowerCase().trim().split(/\\s+/);\n\t\tif (words.length === 0 || words[0] === \"\") return;\n\n\t\tthis.startWords.add(words[0]);\n\n\t\tconst firstWord = words[0];\n\t\tlet node: TrieNode;\n\n\t\tif (this.root.has(firstWord)) {\n\t\t\tnode = this.root.get(firstWord)!;\n\t\t} else {\n\t\t\tnode = { children: new Map(), terminal: null };\n\t\t\tthis.root.set(firstWord, node);\n\t\t}\n\n\t\t// Single-word phrase: terminal at root's child\n\t\tif (words.length === 1) {\n\t\t\tnode.terminal = { tokenType, phrase, consumed: 1 };\n\t\t\treturn;\n\t\t}\n\n\t\t// Walk/insert remaining words\n\t\tfor (let i = 1; i < words.length; i++) {\n\t\t\tconst word = words[i];\n\t\t\tif (!node.children.has(word)) {\n\t\t\t\tnode.children.set(word, { children: new Map(), terminal: null });\n\t\t\t}\n\t\t\tnode = node.children.get(word)!;\n\t\t}\n\n\t\tnode.terminal = { tokenType, phrase, consumed: words.length };\n\t}\n\n\t// ── Matching ──────────────────────────────────────────────────────────\n\n\t/**\n\t * Attempt to match a phrase starting at `pos` in the token stream.\n\t *\n\t * Walks the trie one token at a time, tracking the deepest terminal\n\t * node reached. Returns the longest match found, or `null` if no\n\t * phrase starts at this position.\n\t *\n\t * @param tokens - The current token stream\n\t * @param pos - Position to attempt matching from\n\t * @returns The longest {@link NormalizerMatch}, or `null` on no match\n\t */\n\tmatchAt(tokens: Token[], pos: number): NormalizerMatch | null {\n\t\t// ── Bounds guard ──\n\t\tif (pos >= tokens.length) return null;\n\n\t\t// ── A tag token never takes part in phrase fusion (#197, #213) ──\n\t\t// A `#tag` is a typed token, not a bare word, so it must not start or\n\t\t// complete a phrase. The trie matches on written value alone, so without\n\t\t// this guard a tag whose name equals a phrase or a phrase-continuation\n\t\t// word (`1200 #assuming`, `total of #column`) is fused into that grammar\n\t\t// before the category-tag rules ever run, and the tag is lost.\n\t\t//\n\t\t// The guard also covers the fused aggregate tokens the tags package emits\n\t\t// (`TAG_SUM` / `TAG_COUNT` / `TAG_AVERAGE`), whose value is the tag NAME:\n\t\t// otherwise `total of #assuming` fuses correctly to TAG_SUM(\"assuming\"),\n\t\t// then the trie re-reads that value on the next pass and turns it back\n\t\t// into the finance ASSUMING keyword (#213). The whole `TAG` / `TAG_*`\n\t\t// namespace belongs to the tags package.\n\t\tconst startType = tokens[pos].type;\n\t\tif (startType === \"TAG\" || startType.startsWith(\"TAG_\")) return null;\n\n\t\t// ── O(1) quick-reject: first word not a phrase starter ──\n\t\tconst firstWord = tokens[pos].value.toLowerCase();\n\t\tif (!this.startWords.has(firstWord)) return null;\n\n\t\t// ── Walk trie, tracking deepest terminal ──\n\t\tlet node: TrieNode | undefined = this.root.get(firstWord);\n\t\tif (!node) return null;\n\n\t\tlet best: NormalizerMatch | null = null;\n\t\tlet depth = 1;\n\n\t\t// Check single-word phrase at first node\n\t\tif (node.terminal) {\n\t\t\tconst sourceTokens = tokens.slice(pos, pos + 1);\n\t\t\tbest = {\n\t\t\t\tconsumed: 1,\n\t\t\t\treplacement: [createFusedToken(node.terminal.tokenType, node.terminal.phrase, sourceTokens)],\n\t\t\t\truleName: node.terminal.phrase,\n\t\t\t};\n\t\t}\n\n\t\t// Walk deeper for multi-word phrases\n\t\tfor (let i = pos + 1; i < tokens.length && node?.children; i++) {\n\t\t\tconst contType = tokens[i].type;\n\t\t\tif (contType === \"TAG\" || contType.startsWith(\"TAG_\")) break; // a tag token can't continue a phrase (#197, #213)\n\t\t\tconst word = tokens[i].value.toLowerCase();\n\t\t\tnode = node.children.get(word);\n\t\t\tif (!node) break; // dead end\n\t\t\tdepth++;\n\n\t\t\tif (node.terminal) {\n\t\t\t\t// Deferred fused-token creation, only on deepest match found\n\t\t\t\tconst sourceTokens = tokens.slice(pos, pos + depth);\n\t\t\t\tbest = {\n\t\t\t\t\tconsumed: depth,\n\t\t\t\t\treplacement: [\n\t\t\t\t\t\tcreateFusedToken(node.terminal.tokenType, node.terminal.phrase, sourceTokens),\n\t\t\t\t\t],\n\t\t\t\t\truleName: node.terminal.phrase,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn best;\n\t}\n\n\t// ── Introspection ─────────────────────────────────────────────────────\n\n\t/** Number of unique first words (not total phrases). */\n\tget size(): number {\n\t\treturn this.root.size;\n\t}\n\n\t/**\n\t * Return all registered phrases and their target token types.\n\t *\n\t * Used by diagnostic mode to expose the complete trie structure to the\n\t * playground's NormalizerTab for rendering ALL registered phrases\n\t * (not just the ones that matched in this evaluation).\n\t */\n\tgetAllPhrases(): Record<string, string> {\n\t\tconst result: Record<string, string> = {};\n\n\t\tconst collect = (node: TrieNode, path: string[]): void => {\n\t\t\tif (node.terminal) {\n\t\t\t\tresult[path.join(' ')] = node.terminal.tokenType;\n\t\t\t}\n\t\t\tfor (const [word, child] of node.children) {\n\t\t\t\tcollect(child, [...path, word]);\n\t\t\t}\n\t\t};\n\n\t\tfor (const [firstWord, node] of this.root) {\n\t\t\tcollect(node, [firstWord]);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/** Check if any phrase starts with this word (case-insensitive). */\n\tcanStart(word: string): boolean {\n\t\treturn this.startWords.has(word.toLowerCase());\n\t}\n}\n\n//#endregion\n","//#region ─── Module Overview ───────────────────────────────────────────────────\n\n/**\n * Built-in normalization rules for the {@link TokenNormalizer}.\n *\n * These rules handle common expression patterns that span multiple tokens.\n * Phrase fusion (e.g., \"to the power of\" → CARET) is handled by the\n * internal {@link PhraseTrie}. See {@link TokenNormalizer.addPhrase}.\n * This module only exports non-phrase rules like {@link implicitMultiplyRule}.\n *\n * @module BuiltinNormalizerRules\n */\n\n//#endregion\n//#region ─── Imports ──────────────────────────────────────────────────────────\n\nimport type { Token } from \"@solve-js/lexer/Token\";\nimport { tokenTypeId } from \"@solve-js/lexer/Token\";\nimport { LexerToken } from \"@solve-js/lexer/ExpressionLexer\";\nimport type { NormalizerRule, NormalizerMatch } from \"./NormalizerRule\";\n\n//#endregion\n//#region ─── PHRASE_START_WORDS, Implicit Multiply Guard ─────────────────────\n\n/**\n * Words that can start multi-word phrases, hardcoded fallback.\n *\n * This is ONLY used as the default fallback in {@link implicitMultiplyRule}\n * when no `canStart` predicate is provided. In the recommended pattern,\n * the {@link PhraseTrie}'s live `canStart()` set is passed instead, keeping\n * the guard in sync with package-registered phrases.\n *\n * @see {@link TokenNormalizer.canStartPhrase}\n */\n/**\n * Words that introduce a rate denominator when a unit follows.\n *\n * Kept next to the implicit-multiplication rule because that is the only\n * thing they change here; the rate itself is built in the uom package.\n */\nconst RATE_DENOMINATOR_WORDS = new Set([\"per\", \"a\", \"an\", \"each\", \"every\"]);\n\nconst PHRASE_START_WORDS = new Set([\n \"to\", \"power\", \"increase\", \"decrease\", \"times\", \"multiply\", \"divide\", \"by\",\n]);\n\n//#endregion\n//#region ─── implicitMultiplyRule, Implicit Operator Insertion ────────────────\n\n/**\n * Creates a normalization rule that inserts an implicit multiplication operator\n * between adjacent tokens where multiplication is implied.\n *\n * ## When it fires\n * Inserts a STAR token between:\n * - `NUMBER IDENT` (e.g., \"2 x\" → \"2 * x\")\n * - `RPAREN IDENT` (e.g., \"(x+1)y\" → \"(x+1) * y\")\n * - `NUMBER LPAREN` (e.g., \"2(x+1)\" → \"2 * (x+1)\")\n * - `NUMBER PI` / `NUMBER E` (e.g., \"2π\" → \"2 * π\")\n *\n * ## When it doesn't fire\n * - When the following identifier starts a multi-word phrase\n * (checked against {@link PHRASE_START_WORDS})\n * - When the following token is not an identifier or parenthesized expression\n *\n * ## Priority\n * Default priority is 50, below phrase fusion so phrases match first.\n *\n * @param priority - Rule priority (default 50)\n * @returns A {@link NormalizerRule} that inserts implicit multiply operators\n */\nexport function implicitMultiplyRule(\n\tpriority: number = 50,\n\tcanStart?: (word: string) => boolean\n): NormalizerRule {\n\tconst phraseGuard = canStart ?? ((word: string) => PHRASE_START_WORDS.has(word.toLowerCase()));\n\n\treturn {\n name: \"implicit:multiply\",\n priority,\n match(tokens: Token[], pos: number): NormalizerMatch | null {\n // ── Need at least one token after the current position ──\n if (pos + 1 >= tokens.length) return null;\n\n const t = tokens[pos];\n const next = tokens[pos + 1];\n\n // ── Guard: suppress if the next identifier starts a phrase ──\n // Uses the trie's canStart when available, falls back to hardcoded set.\n // This prevents \"2 power of 3\" from becoming \"2 * power of 3\".\n const nextValue = next.value.toLowerCase();\n if (phraseGuard(nextValue)) return null;\n\n // ── Guard: a rate denominator, not a multiplication ──\n // \"99 per week\" is ninety-nine a week, not ninety-nine times something\n // called per. The trie guard above cannot cover this, because these are\n // not registered phrases; they are recognised by the uom package's\n // bare-denominator rule, which runs after this one and then finds its\n // fused token stranded in operand position. The slash spelling never had\n // the problem, which is what made it hard to see.\n if (RATE_DENOMINATOR_WORDS.has(nextValue) && tokens[pos + 2]?.type === \"UNIT\") return null;\n\n // ── Check trigger conditions ──\n const triggers =\n (t.type === \"NUMBER\" || t.type === \"RPAREN\") &&\n (next.type === \"IDENT\" || next.type === \"LPAREN\" || next.type === \"PI\" || next.type === \"E\");\n\n if (!triggers) return null;\n\n // ── Insert a STAR token at the next token's position ──\n const starToken = new LexerToken(\n \"STAR\", tokenTypeId(\"STAR\"), \"*\", \"*\",\n next.offset, 0, next.line, next.col,\n );\n\n // consumed = 1: only the current token is replaced with [current, STAR]\n // The next token is NOT consumed, it stays for the next iteration\n return { consumed: 1, replacement: [t, starToken] };\n },\n };\n}\n\n//#endregion\n//#region ─── isInsideRangeContext, Bracket/Call-Paren Context Guard ───────────\n\n/**\n * Whether token `pos` sits inside a context where a bare `NUMBER:NUMBER`\n * sequence means a Range, not a clock-time/laptime/video-timecode literal:\n * a matrix literal/index/slice (`[1,2,3]`, `a[0:3]`), OR a `map`/`reduce`/\n * `sum`/`prod` call's own argument-list parens (`map(f, 0:3)`, these\n * accept a bare Range argument directly, per the Calca spec's own\n * example). Scans backward from `pos` over the CURRENT pass's token array,\n * tracking `[`/`(` nesting depth, the same \"positional guard via\n * backward scan\" idiom already used elsewhere in this normalizer layer\n * (e.g. `LineRefNormalizerRule`'s previous-token check), generalized to\n * depth-tracking. An `LBRACKET` is unconditionally a range-safe opener; an\n * `LPAREN` is range-safe ONLY when immediately preceded by MAP/REDUCE/\n * SUM_FN/PROD_FN, an ordinary grouping/function-call paren is NOT, so\n * `(9:00) + 5` still means a clock time, not a range.\n *\n * Needed because the clock-time/laptime/video-timecode rules each match a\n * bare `NUMBER COLON NUMBER...` shape with ZERO context-awareness, a real\n * collision discovered when adding Range support, since e.g. \"0:3\" is\n * valid input to BOTH features. These contexts have no legitimate use for\n * a clock-time/laptime/timecode literal, so the carve-out costs the time\n * features nothing.\n *\n * IMPORTANT cross-pass-timing gotcha (a real bug found and fixed here,\n * not a hypothetical): the `LPAREN`-opener check deliberately tests the\n * RAW word text (`prev.value.toLowerCase()`), not `prev.type ===\n * \"MAP\"/\"REDUCE\"/...`. The normalizer's multi-pass loop hands every rule\n * the SAME frozen `tokens` snapshot for an entire pass, a rule scanning\n * a LATER position in that pass cannot see a fusion `mapReduceCallNormalizerRule`\n * performs at an EARLIER position in that SAME pass (fusion results only\n * become visible to other rules starting the NEXT pass). Checking the\n * fused token type here would miss exactly the case that matters most\n * `map(f, 0:3)` on its very first normalization pass, silently letting\n * `0:3` fuse into a clock time before `map(`'s own fusion ever lands.\n * Testing the raw word is immune to this: it's true from the very first\n * pass, regardless of whether `mapReduceCallNormalizerRule` has run yet.\n * (`LBRACKET` above has no equivalent issue, it's a genuine lexer token\n * from the start, never itself the product of a fusion.)\n */\nexport function isInsideRangeContext(tokens: Token[], pos: number): boolean {\n const safeStack: boolean[] = [];\n for (let i = 0; i < pos; i++) {\n const t = tokens[i];\n if (t.type === \"LBRACKET\") {\n safeStack.push(true);\n } else if (t.type === \"LPAREN\") {\n const prev = tokens[i - 1];\n const opensMapReduceCall = !!prev && (\n prev.type === \"MAP\" || prev.type === \"REDUCE\" || prev.type === \"SUM_FN\" || prev.type === \"PROD_FN\" ||\n (prev.type === \"IDENT\" && (prev.value.toLowerCase() === \"map\" || prev.value.toLowerCase() === \"reduce\" || prev.value.toLowerCase() === \"sum\" || prev.value.toLowerCase() === \"prod\"))\n );\n safeStack.push(opensMapReduceCall);\n } else if (t.type === \"RBRACKET\" || t.type === \"RPAREN\") {\n safeStack.pop();\n }\n }\n return safeStack.length > 0 && safeStack[safeStack.length - 1];\n}\n\n//#endregion\n//#region ─── createBuiltinNormalizerRules, All Built-in Rules ─────────────────\n\n/**\n * Creates built-in non-phrase normalization rules.\n *\n * Returns implicit multiply insertion (priority 50).\n *\n * **Prefer** calling {@link implicitMultiplyRule} directly with a\n * `canStart` predicate wired to the normalizer's phrase trie:\n * ```ts\n * normalizer.register(implicitMultiplyRule(50, (w) => normalizer.canStartPhrase(w)));\n * ```\n * Without the predicate, this function falls back to a hardcoded\n * {@link PHRASE_START_WORDS} set that won't reflect package-registered phrases.\n *\n * @returns An array of {@link NormalizerRule} instances ready for registration\n */\nexport function createBuiltinNormalizerRules(): NormalizerRule[] {\n return [\n // ── Implicit operator insertion (priority 50) ──\n implicitMultiplyRule(),\n ];\n}\n\n/**\n * Built-in phrase → tokenType mappings.\n *\n * These are registered into the engine's {@link PhraseTrie} during\n * construction. Tests that create a standalone {@link TokenNormalizer}\n * should register these via {@link TokenNormalizer.addPhrase}.\n */\nexport const BUILTIN_PHRASES: Record<string, string> = {\n\t\"to the power of\": \"CARET\",\n\t\"power of\": \"CARET\",\n\t\"increase by\": \"INCREASE_BY\",\n\t\"decrease by\": \"DECREASE_BY\",\n\t\"times by\": \"TIMES_BY\",\n\t\"multiply by\": \"MULTIPLY_BY\",\n\t\"divide by\": \"DIVIDE_BY\",\n\t// The past-tense spellings, which is how the operation is usually written\n\t// out: \"3 multiplied by 4\". Same tokens, so no new parselets. Both this\n\t// branch and the parity branch added \"multiplied by\" independently; the\n\t// merge kept both copies and the locale table rejected the duplicate key.\n\t\"multiplied by\": \"MULTIPLY_BY\",\n\t\"divided by\": \"DIVIDE_BY\",\n};\n\n//#endregion\n"]}
|
package/dist/chunk-EURCQMZK.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
'use strict';var chunk4BZIYU7S_cjs=require('./chunk-4BZIYU7S.cjs'),chunk75XDS65A_cjs=require('./chunk-75XDS65A.cjs'),chunkPNDQRCRQ_cjs=require('./chunk-PNDQRCRQ.cjs'),chunkBKSKZA4W_cjs=require('./chunk-BKSKZA4W.cjs'),chunk6QRHN3I6_cjs=require('./chunk-6QRHN3I6.cjs'),chunkSOMGSIO4_cjs=require('./chunk-SOMGSIO4.cjs');function Yt(e,t){let n=t===2?chunk75XDS65A_cjs.L:chunk75XDS65A_cjs.M,o=n(e.n),r=n(e.d);return o===null||r===null?null:{n:o,d:r}}function Gt(e,t){let n=chunk75XDS65A_cjs.y(e),o=new Map;for(let[r,i]of n){if(i%t!==0)return null;o.set(r,i/t);}return chunk75XDS65A_cjs.x(o)}function jn(e,t){let n=chunk75XDS65A_cjs.y(e);for(let[o,r]of chunk75XDS65A_cjs.y(t))n.set(o,(n.get(o)??0)+r);return chunk75XDS65A_cjs.x(n)}function jt(e,t){let n=chunk75XDS65A_cjs.y(e);for(let[o,r]of chunk75XDS65A_cjs.y(t)){let i=(n.get(o)??0)-r;i<=0?n.delete(o):n.set(o,i);}return chunk75XDS65A_cjs.x(n)}function Kn(e,t){let n=chunk75XDS65A_cjs.y(e),o=new Map;for(let[r,i]of chunk75XDS65A_cjs.y(t)){let a=n.get(r);a!==void 0&&o.set(r,Math.min(a,i));}return chunk75XDS65A_cjs.x(o)}function Xn(e){let t=new Set;for(let n of e)for(let o of chunk75XDS65A_cjs.y(n).keys())t.add(o);return [...t].sort()}function Q(e){let t=new Map;for(let n of e)t.set(n.key,n.coefficient);return chunk75XDS65A_cjs.E({terms:t,vars:Xn(e.map(n=>n.key))})}function Ze(e){let t=e[0];for(let n=1;n<e.length;n++)t={kind:"mul",left:t,right:e[n]};return t}function Zn(e){return [...e.terms].map(([n,o])=>({key:n,coefficient:o})).sort((n,o)=>chunk75XDS65A_cjs.D(n.key,o.key,e.vars))}function Zt(e){if(e.vars.length<2)return null;let t=Zn(e);return t.length===2?Hn(t[0],t[1]):t.length===3?Wn(t):t.length===4?Qn(t):null}function Hn(e,t){let n=e.coefficient.n>0n,o=t.coefficient.n>0n;if(!n)return null;let r=He(e,t,2);if(r!==null&&!o)return Ze([Q([r.a,Te(r.b)]),Q([r.a,r.b])]);let i=He(e,t,3);if(i===null)return null;let a=Q(o?[i.a,i.b]:[i.a,Te(i.b)]),u=o?Te(Oe(i.a,i.b)):Oe(i.a,i.b);return Ze([a,Q([Kt(i.a),u,Kt(i.b)])])}function He(e,t,n){let o=t.coefficient.n<0n?chunk75XDS65A_cjs.j(t.coefficient):t.coefficient,r=Yt(e.coefficient,n),i=Yt(o,n);if(r===null||i===null)return null;let a=Gt(e.key,n),u=Gt(t.key,n);return a===null||u===null?null:{a:{key:a,coefficient:r},b:{key:u,coefficient:i}}}function Te(e){return {key:e.key,coefficient:chunk75XDS65A_cjs.j(e.coefficient)}}function Oe(e,t){return {key:jn(e.key,t.key),coefficient:chunk75XDS65A_cjs.h(e.coefficient,t.coefficient)}}function Kt(e){return Oe(e,e)}function Wn(e){let[t,n,o]=e;if(t.coefficient.n<0n||o.coefficient.n<0n)return null;let r=He(t,o,2);if(r===null)return null;let i=Oe(r.a,r.b);if(i.key!==n.key)return null;let a=chunk75XDS65A_cjs.h(i.coefficient,{n:2n,d:1n}),u=n.coefficient.n<0n,l=u?chunk75XDS65A_cjs.j(n.coefficient):n.coefficient;return chunk75XDS65A_cjs.m(chunk75XDS65A_cjs.i(l,a))?{kind:"pow",base:Q([r.a,u?Te(r.b):r.b]),exponent:chunk75XDS65A_cjs.p(2)}:null}function Qn(e){let t=[[[0,1],[2,3]],[[0,2],[1,3]],[[0,3],[1,2]]];for(let n of t){let o=Xt(e[n[0][0]],e[n[0][1]]),r=Xt(e[n[1][0]],e[n[1][1]]);if(!(o===null||r===null)&&zn(o.cofactor,r.cofactor))return Ze([Q([o.common,r.common]),Q(o.cofactor)])}return null}function Xt(e,t){let n=Kn(e.key,t.key),o={key:n,coefficient:e.coefficient},r=[{key:jt(e.key,n),coefficient:{n:1n,d:1n}},{key:jt(t.key,n),coefficient:chunk75XDS65A_cjs.i(t.coefficient,e.coefficient)}];return r[0].key===r[1].key?null:{common:o,cofactor:r}}function zn(e,t){return e.length!==t.length?false:e.every((n,o)=>n.key===t[o].key&&n.coefficient.n===t[o].coefficient.n&&n.coefficient.d===t[o].coefficient.d)}var Jn=12,_e=4096;function we(e,t){let n=e<0n?-e:e,o=t<0n?-t:t;for(;o!==0n;){let r=n%o;n=o,o=r;}return n}function Wt(e,t){return e===0n||t===0n?0n:e/we(e,t)*t}function Ht(e){let t=e<0n?-e:e;if(t===0n)return null;let n=[];for(let o=1n;o*o<=t;o++){if(t%o!==0n)continue;n.push(o);let r=t/o;if(r!==o&&n.push(r),n.length>_e)return null}return n}function Qt(e,t){let n=chunk75XDS65A_cjs.a;for(let o of e)n=chunk75XDS65A_cjs.f(chunk75XDS65A_cjs.h(n,t),o);return n}function eo(e,t){let n=[e[0]];for(let o=1;o<e.length-1;o++)n.push(chunk75XDS65A_cjs.f(e[o],chunk75XDS65A_cjs.h(n[o-1],t)));return n}function ue(e){if(e.length<2)return [];let t=1n;for(let s of e)t=Wt(t,s.d);let n=e.map(s=>s.n*t/s.d),o=n[0],r=n[n.length-1];if(r===0n)return [];let i=Ht(r),a=Ht(o);if(i===null||a===null)throw chunkSOMGSIO4_cjs.c.execution("SYMBOLIC_FACTOR_LIMIT_EXCEEDED","This polynomial's coefficients have too many divisors to search for rational roots.",{limit:_e});if(i.length*a.length>_e)throw chunkSOMGSIO4_cjs.c.execution("SYMBOLIC_FACTOR_LIMIT_EXCEEDED","This polynomial has too many candidate rational roots to test.",{limit:_e});let u=[],l=new Set;for(let s of i)for(let p of a)for(let h of [1n,-1n]){let x={n:h*s/we(s,p),d:p/we(s,p)},V=`${x.n}/${x.d}`;l.has(V)||(l.add(V),chunk75XDS65A_cjs.l(Qt(e,x))&&u.push(x));}return u}function to(e,t){return chunk75XDS65A_cjs.l(t)?chunk75XDS65A_cjs.q(e):t.n>0n?{kind:"sub",left:chunk75XDS65A_cjs.q(e),right:chunk75XDS65A_cjs.p(t)}:{kind:"add",left:chunk75XDS65A_cjs.q(e),right:chunk75XDS65A_cjs.p(chunk75XDS65A_cjs.j(t))}}function no(e,t){let n=e.length-1,o=new Map;return e.forEach((r,i)=>{if(chunk75XDS65A_cjs.l(r))return;let a=n-i;o.set(a===0?"":a===1?t:`${t}^${a}`,r);}),chunk75XDS65A_cjs.E({terms:o,vars:o.size>0?[t]:[]})}function Qe(e,t){let n=[],o=[...e],r=ue(o);for(;r.length>0&&o.length>2;){for(let a of r){let u=0;for(;o.length>1&&chunk75XDS65A_cjs.l(Qt(o,a));)o=eo(o,a),u++;u>0&&n.push({base:to(t,a),power:u});}r=o.length>2?ue(o):[];}return o.length-1>=1?(n.push({base:no(o,t),power:1}),{content:chunk75XDS65A_cjs.b,factors:n}):{content:o.length===1?o[0]:chunk75XDS65A_cjs.b,factors:n}}function oo(e){let t=[];chunk75XDS65A_cjs.m(e.content)||t.push(chunk75XDS65A_cjs.p(e.content));for(let o of e.factors)t.push(o.power===1?o.base:chunk75XDS65A_cjs.r(o.base,chunk75XDS65A_cjs.p({n:BigInt(o.power),d:1n})));if(t.length===0)return chunk75XDS65A_cjs.p(chunk75XDS65A_cjs.b);let n=t[0];for(let o=1;o<t.length;o++)n={kind:"mul",left:n,right:t[o]};return n}function ro(e){let t=0n,n=1n;for(let o of e.terms.values())t=we(t,o.n),n=Wt(n,o.d);return t===0n?chunk75XDS65A_cjs.b:{n:t,d:n}}function io(e){let t=new Map;for(let r of e.vars){let i=1/0;for(let a of e.terms.keys()){let u=ao(a,r);u<i&&(i=u);}i>0&&i!==1/0&&t.set(r,i);}if(t.size===0)return {monomial:t,reduced:e};let n=new Map;for(let[r,i]of e.terms){let a=We(r);for(let[u,l]of t)a.set(u,(a.get(u)??0)-l);n.set(uo(a),i);}let o=new Set;for(let r of n.keys())for(let i of We(r).keys())o.add(i);return {monomial:t,reduced:{terms:n,vars:[...o].sort()}}}function ao(e,t){return We(e).get(t)??0}function We(e){let t=new Map;if(e==="")return t;for(let n of e.split("*")){let o=n.indexOf("^");o===-1?t.set(n,1):t.set(n.slice(0,o),Number(n.slice(o+1)));}return t}function uo(e){return [...e.keys()].filter(n=>(e.get(n)??0)>0).sort().map(n=>e.get(n)===1?n:`${n}^${e.get(n)}`).join("*")}function lo(e){let t=[...e.keys()].sort(),n=null;for(let o of t){let r=e.get(o),i=r===1?chunk75XDS65A_cjs.q(o):chunk75XDS65A_cjs.r(chunk75XDS65A_cjs.q(o),chunk75XDS65A_cjs.p({n:BigInt(r),d:1n}));n=n===null?i:{kind:"mul",left:n,right:i};}return n}function zt(e){let t=chunk75XDS65A_cjs.C(e);if(t===null||t.terms.size===0||chunk75XDS65A_cjs.z(t)>Jn||t.vars.length===0)return e;let n=ro(t),o=chunk75XDS65A_cjs.m(n)?t:so(t,chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.b,n)),{monomial:r,reduced:i}=io(o),a=lo(r),u=chunk75XDS65A_cjs.A(i);if(u===null){let te=Zt(i);return te!==null?co(n,a,te):mo(n,a,i)??e}let l=[...chunk75XDS65A_cjs.B(i,u)].reverse(),s=Qe(l,u),p=chunk75XDS65A_cjs.h(n,s.content);if(s.factors.length<=1&&(s.factors[0]?.power??1)===1&&a===null&&chunk75XDS65A_cjs.m(p))return e;let x=[];chunk75XDS65A_cjs.m(p)||x.push(chunk75XDS65A_cjs.p(p)),a!==null&&x.push(a),x.push(oo({content:chunk75XDS65A_cjs.b,factors:s.factors}));let V=x[0];for(let te=1;te<x.length;te++)V={kind:"mul",left:V,right:x[te]};return V}function so(e,t){let n=new Map;for(let[o,r]of e.terms)n.set(o,chunk75XDS65A_cjs.h(r,t));return {terms:n,vars:e.vars}}function co(e,t,n){let o=[];chunk75XDS65A_cjs.m(e)||o.push(chunk75XDS65A_cjs.p(e)),t!==null&&o.push(t),o.push(n);let r=o[0];for(let i=1;i<o.length;i++)r={kind:"mul",left:r,right:o[i]};return r}function mo(e,t,n){if(t===null&&chunk75XDS65A_cjs.m(e))return null;let o=[];chunk75XDS65A_cjs.m(e)||o.push(chunk75XDS65A_cjs.p(e)),t!==null&&o.push(t),o.push(chunk75XDS65A_cjs.E(n));let r=o[0];for(let i=1;i<o.length;i++)r={kind:"mul",left:r,right:o[i]};return r}var k={n:2n,d:1n},B={n:3n,d:1n},be={n:4n,d:1n};function fo(e,t,n,o){let r=chunk75XDS65A_cjs.j(chunk75XDS65A_cjs.i(t,chunk75XDS65A_cjs.h(B,e))),i=chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.g(chunk75XDS65A_cjs.h(B,chunk75XDS65A_cjs.h(e,n)),chunk75XDS65A_cjs.h(t,t)),chunk75XDS65A_cjs.h(B,chunk75XDS65A_cjs.h(e,e))),a=chunk75XDS65A_cjs.h(k,chunk75XDS65A_cjs.h(t,chunk75XDS65A_cjs.h(t,t))),u=chunk75XDS65A_cjs.h({n:9n,d:1n},chunk75XDS65A_cjs.h(e,chunk75XDS65A_cjs.h(t,n))),l=chunk75XDS65A_cjs.h({n:27n,d:1n},chunk75XDS65A_cjs.h(chunk75XDS65A_cjs.h(e,e),o)),s=chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.f(chunk75XDS65A_cjs.g(a,u),l),chunk75XDS65A_cjs.h({n:27n,d:1n},chunk75XDS65A_cjs.h(e,chunk75XDS65A_cjs.h(e,e))));return {p:i,q:s,shift:r}}function en(e,t,n,o){let{p:r,q:i,shift:a}=fo(e,t,n,o),u=chunk75XDS65A_cjs.j(chunk75XDS65A_cjs.f(chunk75XDS65A_cjs.h(be,chunk75XDS65A_cjs.h(r,chunk75XDS65A_cjs.h(r,r))),chunk75XDS65A_cjs.h({n:27n,d:1n},chunk75XDS65A_cjs.h(i,i))));return chunk75XDS65A_cjs.k(u,chunk75XDS65A_cjs.a)>0?{exact:[],approximate:yo(r,i,a)}:chunk75XDS65A_cjs.l(u)?{exact:po(r,i,a),approximate:[]}:{exact:bo(r,i,a),approximate:[]}}function po(e,t,n){if(chunk75XDS65A_cjs.l(e))return [chunk75XDS65A_cjs.p(n)];let o=chunk75XDS65A_cjs.f(chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.h(B,t),e),n),r=chunk75XDS65A_cjs.f(chunk75XDS65A_cjs.j(chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.h(B,t),chunk75XDS65A_cjs.h(k,e))),n);return [o,r].sort(chunk75XDS65A_cjs.k).map(chunk75XDS65A_cjs.p)}function bo(e,t,n){let o=chunk75XDS65A_cjs.j(chunk75XDS65A_cjs.i(t,k)),r=chunk75XDS65A_cjs.f(chunk75XDS65A_cjs.h(chunk75XDS65A_cjs.i(t,k),chunk75XDS65A_cjs.i(t,k)),chunk75XDS65A_cjs.h(chunk75XDS65A_cjs.i(e,B),chunk75XDS65A_cjs.h(chunk75XDS65A_cjs.i(e,B),chunk75XDS65A_cjs.i(e,B)))),i=chunk75XDS65A_cjs.O(r),a={kind:"call",name:"cbrt",args:[{kind:"add",left:chunk75XDS65A_cjs.p(o),right:i}]},u={kind:"call",name:"cbrt",args:[{kind:"sub",left:chunk75XDS65A_cjs.p(o),right:i}]},l={kind:"add",left:a,right:u},s={kind:"sub",left:a,right:u},p={kind:"add",left:chunk75XDS65A_cjs.p(n),right:{kind:"div",left:{kind:"neg",operand:l},right:chunk75XDS65A_cjs.p(k)}},h={kind:"mul",left:{kind:"div",left:{kind:"mul",left:s,right:chunk75XDS65A_cjs.O(B)},right:chunk75XDS65A_cjs.p(k)},right:chunk75XDS65A_cjs.w(chunk75XDS65A_cjs.n)};return [{kind:"add",left:chunk75XDS65A_cjs.p(n),right:l},{kind:"sub",left:p,right:h},{kind:"add",left:p,right:h}]}function yo(e,t,n){let o=chunk75XDS65A_cjs.e(e),r=chunk75XDS65A_cjs.e(t),i=chunk75XDS65A_cjs.e(n),a=2*Math.sqrt(-o/3),u=3*r/(2*o)*Math.sqrt(-3/o),l=Math.acos(Math.min(1,Math.max(-1,u)))/3;return [0,1,2].map(s=>a*Math.cos(l-2*Math.PI*s/3)+i).sort((s,p)=>s-p)}function ho(e,t,n,o){let r=chunk75XDS65A_cjs.j(chunk75XDS65A_cjs.i(e,be)),i=chunk75XDS65A_cjs.h(e,e),a=chunk75XDS65A_cjs.g(t,chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.h(B,i),{n:8n,d:1n})),u=chunk75XDS65A_cjs.f(chunk75XDS65A_cjs.g(n,chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.h(e,t),k)),chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.h(i,e),{n:8n,d:1n})),l=chunk75XDS65A_cjs.g(chunk75XDS65A_cjs.f(chunk75XDS65A_cjs.g(o,chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.h(e,n),be)),chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.h(i,t),{n:16n,d:1n})),chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.h(B,chunk75XDS65A_cjs.h(i,i)),{n:256n,d:1n}));return {p:a,q:u,r:l,shift:r}}function tn(e,t,n,o,r,i){let a=V=>chunk75XDS65A_cjs.i(V,e),{p:u,q:l,r:s,shift:p}=ho(a(t),a(n),a(o),a(r)),h=chunk75XDS65A_cjs.l(l)?go(u,s):Io(u,l,s,i);if(h===null)return null;let x=chunk75XDS65A_cjs.l(p)?h:h.map(V=>({kind:"add",left:chunk75XDS65A_cjs.p(p),right:V}));return {exact:No(x),approximate:[]}}function No(e){let t=new Set,n=[];for(let o of e){let r=chunk75XDS65A_cjs.t(chunk75XDS65A_cjs.Q(o));t.has(r)||(t.add(r),n.push(o));}return n}function go(e,t){let n=chunk75XDS65A_cjs.g(chunk75XDS65A_cjs.h(e,e),chunk75XDS65A_cjs.h(be,t));if(chunk75XDS65A_cjs.k(n,chunk75XDS65A_cjs.a)<0)return vo(e,t);let o=chunk75XDS65A_cjs.N(n);return o!==null?Ro(chunk75XDS65A_cjs.j(e),o,chunk75XDS65A_cjs.l(n)):xo(e,t,n)}function Ro(e,t,n){let o=n?[chunk75XDS65A_cjs.i(e,k)]:[chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.f(e,t),k),chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.g(e,t),k)],r=[];for(let i of o){if(chunk75XDS65A_cjs.l(i)){r.push(chunk75XDS65A_cjs.p(chunk75XDS65A_cjs.a));continue}let a=chunk75XDS65A_cjs.P(i);r.push({kind:"neg",operand:a},a);}return r}function xo(e,t,n){let o=chunk75XDS65A_cjs.p(chunk75XDS65A_cjs.j(e)),r=chunk75XDS65A_cjs.O(n),i=chunk75XDS65A_cjs.k(e,chunk75XDS65A_cjs.a)<=0,a=[{node:ze({kind:"add",left:o,right:r}),positive:i||chunk75XDS65A_cjs.k(t,chunk75XDS65A_cjs.a)<=0},{node:ze({kind:"sub",left:o,right:r}),positive:i&&chunk75XDS65A_cjs.k(t,chunk75XDS65A_cjs.a)>=0}],u=[];for(let{node:l,positive:s}of a){let h={kind:"call",name:"sqrt",args:[s?l:{kind:"neg",operand:l}]},x=s?h:{kind:"mul",left:h,right:chunk75XDS65A_cjs.w(chunk75XDS65A_cjs.n)};u.push({kind:"neg",operand:x},x);}return u}function ze(e){return {kind:"div",left:e,right:chunk75XDS65A_cjs.p(k)}}function vo(e,t){let n=chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.j(e),k),o=chunk75XDS65A_cjs.N(t),r=o===null?Jt(chunk75XDS65A_cjs.O(t),n):chunk75XDS65A_cjs.O(chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.f(o,n),k)),a={kind:"mul",left:o===null?Jt(chunk75XDS65A_cjs.O(t),chunk75XDS65A_cjs.j(n)):chunk75XDS65A_cjs.O(chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.g(o,n),k)),right:chunk75XDS65A_cjs.w(chunk75XDS65A_cjs.n)},u={kind:"add",left:r,right:a},l={kind:"sub",left:r,right:a};return [{kind:"neg",operand:u},{kind:"neg",operand:l},l,u]}function Jt(e,t){let n=t.n>=0n?{kind:"add",left:e,right:chunk75XDS65A_cjs.p(t)}:{kind:"sub",left:e,right:chunk75XDS65A_cjs.p(chunk75XDS65A_cjs.j(t))};return {kind:"call",name:"sqrt",args:[ze(n)]}}function Io(e,t,n,o){let r=[{n:1n,d:1n},chunk75XDS65A_cjs.h(k,e),chunk75XDS65A_cjs.g(chunk75XDS65A_cjs.h(e,e),chunk75XDS65A_cjs.h(be,n)),chunk75XDS65A_cjs.j(chunk75XDS65A_cjs.h(t,t))];for(let i of ue(r)){if(chunk75XDS65A_cjs.k(i,chunk75XDS65A_cjs.a)<=0)continue;let a=chunk75XDS65A_cjs.N(i);if(a===null)continue;let u=chunk75XDS65A_cjs.f(e,i),l=chunk75XDS65A_cjs.i(t,a),s=chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.g(u,l),k),p=chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.f(u,l),k),h={n:1n,d:1n};return [...o(h,a,s),...o(h,chunk75XDS65A_cjs.j(a),p)]}return null}var Mo=200,So=1e-14,Eo=1e-10,Ao=1e-10,nn=1e-9,ko=1e-8,Vo=4;function ye(e,t){return {re:e.re-t.re,im:e.im-t.im}}function To(e,t){return {re:e.re*t.re-e.im*t.im,im:e.re*t.im+e.im*t.re}}function rn(e,t){if(Math.abs(t.re)>=Math.abs(t.im)){let r=t.im/t.re,i=t.re+t.im*r;return {re:(e.re+e.im*r)/i,im:(e.im-e.re*r)/i}}let n=t.re/t.im,o=t.re*n+t.im;return {re:(e.re*n+e.im)/o,im:(e.im*n-e.re)/o}}function K(e){return Math.hypot(e.re,e.im)}function De(e,t){let n=0,o=0;for(let r of e){let i=n*t.re-o*t.im+r;o=n*t.im+o*t.re,n=i;}return {re:n,im:o}}function Oo(e,t){let n=K(t),o=0;for(let r of e)o=o*n+Math.abs(r);return o}function _o(e){let t=e.length-1,n=[];for(let o=0;o<t;o++)n.push(e[o]*(t-o));return n}function wo(e){let t=[...e].reverse(),o=[...chunk75XDS65A_cjs.K(t)].reverse().map(chunk75XDS65A_cjs.e);return o.some(r=>!Number.isFinite(r))?null:o}function Do(e){let t=e.length-1,n=0;for(let a=1;a<e.length;a++)n=Math.max(n,Math.abs(e[a]));let o=1+n,r=-e[1]/t,i=[];for(let a=0;a<t;a++){let u=2*Math.PI*a/t+Math.PI/(2*t);i.push({re:r+o*Math.cos(u),im:o*Math.sin(u)});}return i}function Co(e){let t=e.length-1,n=Do(e);for(let o=0;o<Mo;o++){let r=0,i=1;for(let a=0;a<t;a++){let u={re:1,im:0};for(let s=0;s<t;s++)a!==s&&(u=To(u,ye(n[a],n[s])));if(u.re===0&&u.im===0){n[a]={re:n[a].re+1e-6*(a+1),im:n[a].im+1e-6};continue}let l=rn(De(e,n[a]),u);if(!Number.isFinite(l.re)||!Number.isFinite(l.im))return null;n[a]=ye(n[a],l),r=Math.max(r,K(l)),i=Math.max(i,K(n[a]));}if(r<=So*i)return n}return null}function on(e,t,n){let o=n;for(let r=0;r<Vo;r++){let i=De(t,o);if(i.re===0&&i.im===0)break;let a=ye(o,rn(De(e,o),i));if(!Number.isFinite(a.re)||!Number.isFinite(a.im))break;o=a;}return o}function Po(e,t,n){let o=Math.max(1,K(n));if(n.im!==0&&Math.abs(n.im)<=nn*o){let r=on(e,t,{re:n.re,im:0});if(Je(e,r))return {re:r.re,im:0}}if(n.re!==0&&Math.abs(n.re)<=nn*o){let r=on(e,t,{re:0,im:n.im});if(Je(e,r))return {re:0,im:r.im}}return n}function Je(e,t){return !Number.isFinite(t.re)||!Number.isFinite(t.im)?false:K(De(e,t))<=Eo*Oo(e,t)}function Lo(e){let t=[...e],n=t.map(o=>o.im===0);for(let o=0;o<t.length;o++){if(n[o])continue;let r={re:t[o].re,im:-t[o].im},i=-1,a=Number.POSITIVE_INFINITY;for(let p=o+1;p<t.length;p++){if(n[p])continue;let h=K(ye(t[p],r));h<a&&(a=h,i=p);}if(i===-1||a>ko*Math.max(1,K(t[o])))continue;let u=(t[o].re+t[i].re)/2,l=(Math.abs(t[o].im)+Math.abs(t[i].im))/2,s=t[o].im<0?-1:1;t[o]={re:u,im:s*l},t[i]={re:u,im:-s*l},n[o]=true,n[i]=true;}return t}function Fo(e){for(let t=0;t<e.length;t++)for(let n=t+1;n<e.length;n++){let o=Math.max(1,K(e[t]),K(e[n]));if(K(ye(e[t],e[n]))<=Ao*o)return false}return true}function an(e){let t=wo(e);if(t===null)return null;if(t.length<2)return [];let n=Co(t);if(n===null)return null;let o=_o(t),r=Lo(n).map(i=>Po(t,o,i));for(let i of r)if(!Je(t,i))return null;return Fo(r)?[...r].sort((i,a)=>i.re-a.re||i.im-a.im):null}var un=8;function Uo(e,t){let n=chunk75XDS65A_cjs.a;for(let o of e)n=chunk75XDS65A_cjs.f(chunk75XDS65A_cjs.h(n,t),o);return n}function $o(e,t){let n=[e[0]];for(let o=1;o<e.length-1;o++)n.push(chunk75XDS65A_cjs.f(e[o],chunk75XDS65A_cjs.h(n[o-1],t)));return n}function ln(e,t,n){let o=chunk75XDS65A_cjs.g(chunk75XDS65A_cjs.h(t,t),chunk75XDS65A_cjs.h(Yo(),chunk75XDS65A_cjs.h(e,n))),r=chunk75XDS65A_cjs.h(qo(),e);if(chunk75XDS65A_cjs.k(o,chunk75XDS65A_cjs.a)<0)return Bo(chunk75XDS65A_cjs.j(t),o,r);if(chunk75XDS65A_cjs.l(o))return [chunk75XDS65A_cjs.p(chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.j(t),r))];let i=chunk75XDS65A_cjs.L(o.n),a=chunk75XDS65A_cjs.L(o.d);if(i!==null&&a!==null){let h={n:i,d:a},x=chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.f(chunk75XDS65A_cjs.j(t),h),r),V=chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.g(chunk75XDS65A_cjs.j(t),h),r);return chunk75XDS65A_cjs.k(V,x)<=0?[chunk75XDS65A_cjs.p(V),chunk75XDS65A_cjs.p(x)]:[chunk75XDS65A_cjs.p(x),chunk75XDS65A_cjs.p(V)]}let u=chunk75XDS65A_cjs.O(o),l=chunk75XDS65A_cjs.k(r,chunk75XDS65A_cjs.a)>0,s={kind:"div",left:{kind:"sub",left:chunk75XDS65A_cjs.p(chunk75XDS65A_cjs.j(t)),right:u},right:chunk75XDS65A_cjs.p(r)},p={kind:"div",left:{kind:"add",left:chunk75XDS65A_cjs.p(chunk75XDS65A_cjs.j(t)),right:u},right:chunk75XDS65A_cjs.p(r)};return l?[s,p]:[p,s]}function Bo(e,t,n){let o=chunk75XDS65A_cjs.j(t),r=chunk75XDS65A_cjs.L(o.n),i=chunk75XDS65A_cjs.L(o.d);if(r!==null&&i!==null){let s=chunk75XDS65A_cjs.i({n:r,d:i},n),p=chunk75XDS65A_cjs.i(e,n);return [chunk75XDS65A_cjs.w(chunk75XDS65A_cjs.o(p,chunk75XDS65A_cjs.j(s))),chunk75XDS65A_cjs.w(chunk75XDS65A_cjs.o(p,s))]}let a=chunk75XDS65A_cjs.i(e,n),u=chunk75XDS65A_cjs.i(o,chunk75XDS65A_cjs.h(n,n)),l={kind:"mul",left:chunk75XDS65A_cjs.O(u),right:chunk75XDS65A_cjs.w(chunk75XDS65A_cjs.n)};return chunk75XDS65A_cjs.l(a)?[{kind:"neg",operand:l},l]:[{kind:"sub",left:chunk75XDS65A_cjs.p(a),right:l},{kind:"add",left:chunk75XDS65A_cjs.p(a),right:l}]}function qo(){return {n:2n,d:1n}}function Yo(){return {n:4n,d:1n}}function Go(e){return {re:e,im:0}}function sn(e,t,n){let o=chunk75XDS65A_cjs.C({kind:"sub",left:e,right:t});if(o===null)return {kind:"unsupported",reason:"this is not a polynomial equation (it divides by an unknown, or calls a function of one)"};let r=o.vars.filter(u=>u!==n),i=chunk75XDS65A_cjs.z(o,n);if(r.length>0)return i!==1?{kind:"unsupported",reason:`solving for "${n}" needs the equation to be linear in it when other unknowns (${r.join(", ")}) are present`}:jo(o,n);if(i===0)return o.terms.size===0?{kind:"identity"}:{kind:"contradiction"};if(i>un)return {kind:"unsupported",reason:`degree ${i} is above the supported maximum of ${un}`};let a=[...chunk75XDS65A_cjs.B(o,n)].reverse();return Zo(a)}function jo(e,t){let n=new Map,o=new Map;for(let[u,l]of e.terms){let s=u.split("*").filter(h=>h.length>0),p=s.indexOf(t);p===-1?o.set(u,l):(s.splice(p,1),n.set(s.join("*"),l));}let r=u=>{let l=new Set;for(let s of u.keys())for(let p of s.split("*"))p.length>0&&l.add(p.split("^")[0]);return [...l].sort()},i=chunk75XDS65A_cjs.E({terms:n,vars:r(n)});return {kind:"roots",exact:[{kind:"div",left:{kind:"neg",operand:chunk75XDS65A_cjs.E({terms:o,vars:r(o)})},right:i}],approximate:[]}}function Ko(e){return e.length===4?en(e[0],e[1],e[2],e[3]):e.length===5?tn(e[0],e[1],e[2],e[3],e[4],ln):null}function Xo(e){let t=[],n=[...e],o=0;for(;n.length>1&&chunk75XDS65A_cjs.l(n[n.length-1]);)n=n.slice(0,-1),o++;for(o>0&&t.push(chunk75XDS65A_cjs.a);n.length>1;){let r=ue(n);if(r.length===0)break;for(let i of r){let a=0;for(;n.length>1&&chunk75XDS65A_cjs.l(Uo(n,i));)n=$o(n,i),a++;a>0&&t.push(i);}}return {roots:t.sort(chunk75XDS65A_cjs.k),remaining:n}}function Zo(e){let{roots:t,remaining:n}=Xo(e),o=t.map(chunk75XDS65A_cjs.p),r=[],i=n.length-1,a=e.length-n.length;if(i<=0)return le(o,r,a,0,"");if(i===1)return o.push(chunk75XDS65A_cjs.p(chunk75XDS65A_cjs.i(chunk75XDS65A_cjs.j(n[1]),n[0]))),le(o,r,a+1,0,"");if(i===2)return o.push(...ln(n[0],n[1],n[2])),le(o,r,a+2,0,"");let u=Ko(n);if(u!==null)return o.push(...u.exact),r.push(...u.approximate.map(Go)),le(o,r,a+i,0,"");let l=an(n);return l!==null?(r.push(...l),le(o,r,a+i,0,"")):le(o,r,a,i,`a degree-${i} factor of it has no exact solution here and the numerical method did not converge on that factor`)}function le(e,t,n,o,r){let i=e.length+t.length,a=n>=1&&(i<1||i>n);return o>0||a?{kind:"incomplete",exact:e,approximate:t,missing:a?Math.max(1,n+o-i):o,reason:a?`${i} root${i===1?"":"s"} were produced for a degree-${n+o} equation, which does not add up`:r}:{kind:"roots",exact:e,approximate:t}}var cn={0:"sqrt",1:"abs",2:"sin",3:"cos",4:"tan",5:"log",6:"ceil",7:"floor",8:"round",11:"asin",12:"acos",13:"atan",14:"atan2",15:"sinh",16:"cosh",17:"tanh",18:"asinh",19:"acosh",20:"atanh",21:"cbrt",23:"expm1",24:"exp",26:"hypot",28:"log10",29:"log1p",30:"log2",33:"sign",34:"trunc",35:"degtorad",36:"radtodeg",61:"root",62:"fact"},Ho=31,hi=new Set([67,68,69,70,71,72,73,74,75,76,77,78,79]);function O(e){if(e.type===9)return e.value;if(e.type===13||e.type===12)return null;let t=e.toNumber();return Number.isFinite(t)?chunk75XDS65A_cjs.p(chunk75XDS65A_cjs.d(t)):null}function _(e){let t=chunk75XDS65A_cjs.Q(e);return t.kind==="const"?chunkPNDQRCRQ_cjs.n(chunk75XDS65A_cjs.e(t.value)):chunkPNDQRCRQ_cjs.K(t)}function Ce(e){return chunkPNDQRCRQ_cjs.P("SYMBOLIC_UNSUPPORTED_FUNCTION",`"${e}" cannot be applied to an expression that still contains an unknown.`)}function Ni(e,t){let n=O(e),o=O(t);return n===null||o===null?Ce("^"):_(chunk75XDS65A_cjs.r(n,o))}function gi(e){let t=O(e);return t===null?Ce("-"):_({kind:"neg",operand:t})}function Ri(e,t){let n=[];for(let r of t){let i=chunkPNDQRCRQ_cjs.Q(r);if(i)return i;let a=O(r);if(a===null)return Ce(cn[e]??`builtin ${e}`);n.push(a);}if(e===Ho&&n.length===2)return _(chunk75XDS65A_cjs.r(n[0],n[1]));let o=cn[e];return o===void 0?Ce(`builtin ${e}`):_(chunk75XDS65A_cjs.s(o,n))}function Wo(e){let t=_(e);return t.type===0&&!Number.isInteger(t.toNumber())?chunkPNDQRCRQ_cjs.K(e):t}function Qo(e){return e.im===0?chunkPNDQRCRQ_cjs.n(e.re):chunkPNDQRCRQ_cjs.K(chunk75XDS65A_cjs.w(chunk75XDS65A_cjs.o(chunk75XDS65A_cjs.d(e.re),chunk75XDS65A_cjs.d(e.im))))}function zo(e){switch(e.kind){case "identity":return chunkPNDQRCRQ_cjs.t("true for every value");case "contradiction":return chunkPNDQRCRQ_cjs.t("no solution");case "unsupported":return chunkPNDQRCRQ_cjs.P("SYMBOLIC_SOLVE_UNSUPPORTED",`Cannot solve this equation: ${e.reason}.`);case "incomplete":{let t=e.exact.length+e.approximate.length;return chunkPNDQRCRQ_cjs.P("SYMBOLIC_SOLVE_INCOMPLETE",`Only ${t} of this equation's ${t+e.missing} roots could be found: ${e.reason}.`)}case "roots":{let t=e.exact.map(Wo);for(let n of e.approximate)t.push(Qo(n));return t.length===0?chunkPNDQRCRQ_cjs.t("no solution"):t.length===1?t[0]:chunkPNDQRCRQ_cjs.C(1,t.length,t.map(n=>n.type===9?n.value:n.toNumber()))}}}function fn(e,t,n){let o=O(e),r=O(t);return o===null||r===null?chunkPNDQRCRQ_cjs.P("SYMBOLIC_NONFINITE_OPERAND","An equation side has no exact value to solve with."):zo(sn(o,r,n))}function he(e,t){if(e.type===6&&t.type===6){if(e.unit===t.unit)return {lv:e.toNumber(),rv:t.toNumber(),unit:e.unit,sameMeasure:true};let n=chunkBKSKZA4W_cjs.c(e.unit),o=chunkBKSKZA4W_cjs.c(t.unit),r=chunk4BZIYU7S_cjs.c.isCurrency(e.unit)&&chunk4BZIYU7S_cjs.c.isCurrency(t.unit);if(n&&n===o){let i=chunkBKSKZA4W_cjs.e(t.toNumber(),t.unit,e.unit);return {lv:e.toNumber(),rv:i,unit:e.unit,sameMeasure:true}}if(r){let i=chunk4BZIYU7S_cjs.c.convertSync(t.toNumber(),t.unit,e.unit);if(i!==null)return {lv:e.toNumber(),rv:i,unit:e.unit,sameMeasure:true}}return {lv:e.toNumber(),rv:t.toNumber(),unit:void 0,sameMeasure:false}}return e.type===6?{lv:e.toNumber(),rv:t.toNumber(),unit:e.unit,sameMeasure:true}:t.type===6?{lv:e.toNumber(),rv:t.toNumber(),unit:t.unit,sameMeasure:true}:{lv:e.toNumber(),rv:t.toNumber(),unit:void 0,sameMeasure:true}}var Jo=1e-12;function er(e,t,n){let o=0;return Number.isFinite(e)&&Math.abs(e)>o&&(o=Math.abs(e)),Number.isFinite(t)&&Math.abs(t)>o&&(o=Math.abs(t)),Number.isFinite(n)&&Math.abs(n)>o&&(o=Math.abs(n)),o}function Oi(e,t){let{lv:n,rv:o,sameMeasure:r}=he(e,t);if(!r)return {lv:n,rv:o,equal:false,sameMeasure:false};if(e.type===6&&t.type===6&&e.unit!==void 0&&e.unit===t.unit&&e.exact!==void 0&&t.exact!==void 0&&chunk4BZIYU7S_cjs.c.isCurrency(e.unit))return {lv:n,rv:o,equal:chunk75XDS65A_cjs.qa(e.exact,t.exact)===0,sameMeasure:true};if(n===o)return {lv:n,rv:o,equal:true,sameMeasure:true};if(!Number.isFinite(n)||!Number.isFinite(o))return {lv:n,rv:o,equal:false,sameMeasure:true};let i=er(n,o,t.toNumber());return {lv:n,rv:o,equal:Math.abs(n-o)<=i*Jo,sameMeasure:true}}var tr={time:"duration",luminousIntensity:"luminous intensity"},nr=new Set(["money","data"]),or={add:"added",sub:"subtracted",mul:"multiplied",div:"divided"};function Pe(e){if(chunk4BZIYU7S_cjs.c.isCurrency(e))return "money";let t=chunkBKSKZA4W_cjs.c(e);if(t!==void 0)return tr[t]??t}function dn(e){return nr.has(e)?e:/^[aeiou]/.test(e)?`an ${e}`:`a ${e}`}function Fe(e,t,n){let o=e===void 0?void 0:Pe(e),r=t===void 0?void 0:Pe(t);if(o!==void 0&&r!==void 0&&o!==r)return `${o} and ${r} cannot be ${n}`}function rr(e){return e!==void 0?or[e]??"combined":"combined"}function _i(e,t){let n=Pe(e),o=Pe(t);if(n!==void 0&&o!==void 0&&n!==o)return `${dn(n)} cannot be converted to ${dn(o)}`}function wi(e,t){let n=e.type===6?e.unit:void 0,o=t.type===6?t.unit:void 0,r=Fe(n,o,"compared");return chunkPNDQRCRQ_cjs.P("INCOMPATIBLE_UNITS",r??`Cannot compare incompatible units: ${n??"?"} and ${o??"?"}`)}function pn(e){if(e.type===2)return e.value;let t=e.toNumber();if(!Number.isInteger(t)){let n=Number.isNaN(t)?"NaN":String(t);throw chunkSOMGSIO4_cjs.c.execution("BIGINT_INEXACT_OPERAND",`A whole-number (n) value can only be combined with another whole number, and ${n} is not one`,{operand:n})}return BigInt(t)}function Di(){return chunkSOMGSIO4_cjs.c.execution("BIGINT_DIVISION_BY_ZERO","Division by zero: a whole-number (n) division is exact integer division, which has no answer at zero, unlike 1 / 0 which is Infinity")}function Ci(e,t){let n=bn(e),o=bn(t);return n===null||o===null?null:n<o?-1:n>o?1:0}function bn(e){if(e.type===2)return e.value;let t=e.toNumber();return Number.isInteger(t)?BigInt(t):null}function et(e,t){return Number.isFinite(t)?Math.pow(e,t):e===1||e===-1&&!Number.isNaN(t)?1:Math.pow(e,t)}function yn(e){return e.exact!==void 0?e.exact:chunk75XDS65A_cjs.ha(e.toNumber())}function ir(e,t,n){let o=e.type===6&&e.unit!==void 0&&e.exact!==void 0&&chunk4BZIYU7S_cjs.c.isCurrency(e.unit),r=t.type===6&&t.unit!==void 0&&t.exact!==void 0&&chunk4BZIYU7S_cjs.c.isCurrency(t.unit);if(!o&&!r)return null;let i,a,u;if(o&&r){if(e.unit!==t.unit||n==="div")return null;i=e.exact,a=t.exact,u=e.unit;}else if(o&&t.type!==6)i=e.exact,u=e.unit,a=yn(t);else if(r&&e.type!==6)a=t.exact,u=t.unit,i=yn(e);else return null;if(i===null||a===null)return null;let l;switch(n){case "add":l=chunk75XDS65A_cjs.ja(i,a);break;case "sub":l=chunk75XDS65A_cjs.ka(i,a);break;case "mul":l=chunk75XDS65A_cjs.la(i,a);break;case "div":if(chunk75XDS65A_cjs.na(a))return null;l=chunk75XDS65A_cjs.pa(i,a);break}return chunkPNDQRCRQ_cjs.v(chunk75XDS65A_cjs.ra(l),u,l)}function Le(e){return e.rational!==void 0?e.rational:(e.type===0||e.type===1)&&typeof e.value=="number"&&Number.isInteger(e.value)?chunk75XDS65A_cjs.c(BigInt(e.value)):null}function Pi(e,t,n){let o=Le(e);if(o===null)return null;let r=Le(t);if(r===null||n==="div"&&chunk75XDS65A_cjs.l(r))return null;let i;try{switch(n){case "add":i=chunk75XDS65A_cjs.f(o,r);break;case "sub":i=chunk75XDS65A_cjs.g(o,r);break;case "mul":i=chunk75XDS65A_cjs.h(o,r);break;case "div":i=chunk75XDS65A_cjs.i(o,r);break}}catch{return null}return chunkPNDQRCRQ_cjs.p(chunk75XDS65A_cjs.e(i),i)}function Li(e,t,n){if(e.type!==0||t.type!==0)return null;let o=e.value,r=t.value,i=e.uncertainty??0,a=t.uncertainty??0,u,l;switch(n){case "add":u=o+r,l=Math.hypot(i,a);break;case "sub":u=o-r,l=Math.hypot(i,a);break;case "mul":u=o*r,l=Math.hypot(r*i,o*a);break;case "div":u=o/r,l=Math.hypot(i/r,o*a/(r*r));break}return chunkPNDQRCRQ_cjs.q(u,l)}function Fi(e,t){let n=Le(e);if(n===null)return null;let o=Le(t);return o===null?null:chunk75XDS65A_cjs.k(n,o)}function Ui(e,t,n,o,r){if(e.type===13)return e;if(t.type===13)return t;if(e.type===12)return e;if(t.type===12)return t;if(r&&(e.type===9||t.type===9)){let i=O(e),a=O(t);return i===null||a===null?chunkPNDQRCRQ_cjs.P("SYMBOLIC_NONFINITE_OPERAND","A symbolic expression cannot combine with a value that has no exact number (NaN or infinity)."):chunkPNDQRCRQ_cjs.K(chunk75XDS65A_cjs.Q({kind:r,left:i,right:a}))}if(e.type===0&&t.type===0)return chunkPNDQRCRQ_cjs.n(n(e.value,t.value));if(e.type===2||t.type===2){let i=pn(e),a=pn(t);return o?chunkPNDQRCRQ_cjs.s(o(i,a)):chunkPNDQRCRQ_cjs.s(i+a)}if(e.type===6||t.type===6){if(r){let s=ir(e,t,r);if(s)return s}let{lv:i,rv:a,unit:u,sameMeasure:l}=he(e,t);if(!l){let s=e.type===6?e.unit:void 0,p=t.type===6?t.unit:void 0,h=Fe(s,p,rr(r));return chunkPNDQRCRQ_cjs.P("INCOMPATIBLE_UNITS",h??`Cannot combine incompatible units: ${s??"?"} and ${p??"?"}`)}return chunkPNDQRCRQ_cjs.u(n(i,a),u)}if(e.type===7&&t.type===7){let i=e.value,a=t.value;if(!chunk75XDS65A_cjs.V(i,a))return chunkPNDQRCRQ_cjs.P("DIMENSION_MISMATCH",`Cannot combine matrices of different shapes: ${i.rows}x${i.cols} and ${a.rows}x${a.cols}`);let u=new Array(i.data.length);for(let l=0;l<i.data.length;l++)u[l]=n(i.data[l],a.data[l]);return chunkPNDQRCRQ_cjs.C(i.rows,i.cols,u)}if(e.type===7){let i=e.value,a=t.toNumber(),u=i.data.map(l=>n(l,a));return chunkPNDQRCRQ_cjs.C(i.rows,i.cols,u)}if(t.type===7){let i=t.value,a=e.toNumber(),u=i.data.map(l=>n(a,l));return chunkPNDQRCRQ_cjs.C(i.rows,i.cols,u)}return chunkPNDQRCRQ_cjs.n(n(e.toNumber(),t.toNumber()))}var hn=254,Nn=200,Ne=class{constructor(){this.handlers=new Map;this.nextOpcode=Nn+1;}register(t){this.handlers.set(t.opcode,t.handler);}unregister(t){this.handlers.delete(t);}get(t){return this.handlers.get(t)}has(t){return this.handlers.has(t)}allocateOpcode(){if(this.nextOpcode>hn)throw chunkSOMGSIO4_cjs.c.config("OPCODE_POOL_EXHAUSTED",`OpRegistry: dynamic opcode pool exhausted (max ${hn-Nn} allocations).`);return this.nextOpcode++}},qi=new Ne;var Rn=chunk75XDS65A_cjs.ga(1);function ge(e,t){return chunk4BZIYU7S_cjs.c.isCurrency(t)?e.exact??chunk75XDS65A_cjs.ha(e.toNumber()):null}function tt(e){if(!Number.isFinite(e))return null;if(Number.isInteger(e))return chunk75XDS65A_cjs.ga(BigInt(e));let t=String(e);return /^-?\d+\.\d+$/.test(t)?chunk75XDS65A_cjs.ia(t):null}function xn(e,t,n){let o=ge(e,n),r=tt(t);if(o!==null&&r!==null){let i=chunk75XDS65A_cjs.la(o,r);return chunkPNDQRCRQ_cjs.v(chunk75XDS65A_cjs.ra(i),n,i)}return chunkPNDQRCRQ_cjs.u(e.toNumber()*t,n)}function vn(e,t,n,o){let r=ge(e,t),i=tt(n);if(r!==null&&i!==null){let a=chunk75XDS65A_cjs.ja(Rn,o===1?i:chunk75XDS65A_cjs.ma(i)),u=chunk75XDS65A_cjs.la(r,a);return chunkPNDQRCRQ_cjs.v(chunk75XDS65A_cjs.ra(u),t,u)}return chunkPNDQRCRQ_cjs.u(e.toNumber()*(1+o*n),t)}function In(e){let t=tt(e);return t===null?null:chunk75XDS65A_cjs.ja(Rn,t)}function Mn(e,t,n){let o=ge(e,t),r=In(n);if(o===null||r===null||chunk75XDS65A_cjs.na(r))return null;let i=chunk75XDS65A_cjs.pa(o,r);return chunkPNDQRCRQ_cjs.v(chunk75XDS65A_cjs.ra(i),t,i)}function Sn(e,t,n){let o=ge(e,t),r=In(n);if(o===null||r===null||chunk75XDS65A_cjs.na(r))return null;let i=chunk75XDS65A_cjs.ka(o,chunk75XDS65A_cjs.pa(o,r));return chunkPNDQRCRQ_cjs.v(chunk75XDS65A_cjs.ra(i),t,i)}function En(e,t){let n=e.unit,o=n!==void 0&&chunk4BZIYU7S_cjs.c.isCurrency(n)?ar(e,n):null;if(o===null)return {unit:n,shares:[{value:e.toNumber()/t,count:t}]};let r=BigInt(t),i=o/r,a=o-i*r,u=Number(a<0n?-a:a),l=o<0n?-1n:1n,s=gn(i,t-u);return u===0?{unit:n,shares:[s]}:{unit:n,shares:[s,gn(i+l,u)]}}function gn(e,t){let n=chunk75XDS65A_cjs.fa(e,2);return {value:chunk75XDS65A_cjs.ra(n),exact:n,count:t}}function ar(e,t){let n=ge(e,t);return n===null?null:chunk75XDS65A_cjs.oa(n,2).coef}var ur=12;function An(e,t){if(e.length===0||t.length===0)return [];let n=new Array(e.length+t.length-1).fill(chunk75XDS65A_cjs.a);return e.forEach((o,r)=>{t.forEach((i,a)=>{n[r+a]=chunk75XDS65A_cjs.f(n[r+a],chunk75XDS65A_cjs.h(o,i));});}),n}function lr(e,t){let n=[chunk75XDS65A_cjs.b];for(let o=0;o<t;o++)n=An(n,e);return n}function nt(e,t){return e.map(n=>chunk75XDS65A_cjs.i(n,t))}function sr(e,t){let n=[],o=0;for(;o<e.length&&chunk75XDS65A_cjs.l(e[o]);)o++;o>0&&n.push({base:[chunk75XDS65A_cjs.a,chunk75XDS65A_cjs.b],power:o});let r=e.slice(o);if(r.length>1){let i=Qe([...r].reverse(),t);for(let a of i.factors){let u=chunk75XDS65A_cjs.C(a.base);if(u===null)return null;n.push({base:[...chunk75XDS65A_cjs.B(u,t)],power:a.power});}}return n.length>0?n:null}function cr(e){let t=[];return e.forEach((n,o)=>{let r=n.base.length-1;for(let i=1;i<=n.power;i++)for(let a=0;a<r;a++)t.push({factor:o,power:i,degree:a});}),t}function mr(e,t,n){let o=lr(t[e.factor].base,e.power),{quotient:r,remainder:i}=chunk75XDS65A_cjs.H(n,o);if(!chunk75XDS65A_cjs.G(i))return null;let a=new Array(e.degree).fill(chunk75XDS65A_cjs.a);return a.push(chunk75XDS65A_cjs.b),An(r,a)}function fr(e,t){let n=t.length;for(let o=0;o<n;o++){let r=-1;for(let i=o;i<n;i++)if(!chunk75XDS65A_cjs.l(e[i][o])){r=i;break}if(r===-1)return null;[e[o],e[r]]=[e[r],e[o]],[t[o],t[r]]=[t[r],t[o]];for(let i=0;i<n;i++){if(i===o||chunk75XDS65A_cjs.l(e[i][o]))continue;let a=chunk75XDS65A_cjs.i(e[i][o],e[o][o]);for(let u=o;u<n;u++)e[i][u]=chunk75XDS65A_cjs.g(e[i][u],chunk75XDS65A_cjs.h(a,e[o][u]));t[i]=chunk75XDS65A_cjs.g(t[i],chunk75XDS65A_cjs.h(a,t[o]));}}return t.map((o,r)=>chunk75XDS65A_cjs.i(o,e[r][r]))}function ot(e,t,n){if(t.length<2||t.length-1>ur)return null;let o=chunk75XDS65A_cjs.I(e,t),r=o.length>1?chunk75XDS65A_cjs.H(e,o).quotient:[...e],i=o.length>1?chunk75XDS65A_cjs.H(t,o).quotient:[...t];if(i.length===1)return {polynomial:nt(r,i[0]),terms:[]};if(i.length===0)return null;let a=i[i.length-1],u=nt(i,a),l=nt(r,a),{quotient:s,remainder:p}=chunk75XDS65A_cjs.H(l,u);if(chunk75XDS65A_cjs.G(p))return {polynomial:s,terms:[]};let h=sr(u,n);if(h===null)return null;let x=dr(h,u,p);return x===null?null:{polynomial:s,terms:x}}function dr(e,t,n){let o=cr(e),r=t.length-1;if(o.length!==r)return null;let i=[];for(let s of o){let p=mr(s,e,t);if(p===null)return null;i.push(p);}let a=[];for(let s=0;s<r;s++)a.push(i.map(p=>p[s]??chunk75XDS65A_cjs.a));let u=[];for(let s=0;s<r;s++)u.push(n[s]??chunk75XDS65A_cjs.a);let l=fr(a,u);return l===null?null:pr(o,l,e)}function pr(e,t,n){let o=new Map;e.forEach((i,a)=>{let u=`${i.factor}:${i.power}`,l=o.get(u)??[];l[i.degree]=t[a],o.set(u,l);});let r=[];for(let[i,a]of o){let[u,l]=i.split(":").map(Number),s=[...a].map(p=>p??chunk75XDS65A_cjs.a);s.every(chunk75XDS65A_cjs.l)||r.push({numerator:s,base:n[u].base,power:l});}return r}function Re(e,t){let n=new Map;return e.forEach((o,r)=>{chunk75XDS65A_cjs.l(o)||n.set(r===0?"":r===1?t:`${t}^${r}`,o);}),n.size===0?chunk75XDS65A_cjs.p(chunk75XDS65A_cjs.a):chunk75XDS65A_cjs.E({terms:n,vars:e.length>1?[t]:[]})}function kn(e){let t=rt(e);if(t===null)return e;let n=ot(t.numerator,t.denominator,t.variable);if(n===null||n.terms.length===0)return e;let o=n.polynomial.length>0?Re(n.polynomial,t.variable):null;for(let r of n.terms){let i=Re(r.base,t.variable),a=r.power===1?i:chunk75XDS65A_cjs.r(i,chunk75XDS65A_cjs.p({n:BigInt(r.power),d:1n})),u=br(r.numerator),l=u?r.numerator.map(p=>chunk75XDS65A_cjs.j(p)):r.numerator,s={kind:"div",left:Re(l,t.variable),right:a};o===null?o=u?{kind:"neg",operand:s}:s:o={kind:u?"sub":"add",left:o,right:s};}return o===null?e:chunk75XDS65A_cjs.Q(o)}function br(e){return e.some(t=>t.n<0n)&&e.every(t=>t.n<=0n)}function rt(e){if(e.kind!=="div")return null;let t=chunk75XDS65A_cjs.C(e.left),n=chunk75XDS65A_cjs.C(e.right);if(t===null||n===null)return null;let o=chunk75XDS65A_cjs.A(n);return o===null||t.vars.some(r=>r!==o)?null:{numerator:chunk75XDS65A_cjs.B(t,o),denominator:chunk75XDS65A_cjs.B(n,o),variable:o}}var it=16;function Vn(){return chunk75XDS65A_cjs.p(chunk75XDS65A_cjs.a)}function X(){return chunk75XDS65A_cjs.p(chunk75XDS65A_cjs.b)}function yr(e,t){switch(e){case "sin":return chunk75XDS65A_cjs.s("cos",[t]);case "cos":return {kind:"neg",operand:chunk75XDS65A_cjs.s("sin",[t])};case "tan":return {kind:"div",left:X(),right:chunk75XDS65A_cjs.r(chunk75XDS65A_cjs.s("cos",[t]),chunk75XDS65A_cjs.p(2))};case "exp":return chunk75XDS65A_cjs.s("exp",[t]);case "log":return {kind:"div",left:X(),right:t};case "sqrt":return {kind:"div",left:X(),right:{kind:"mul",left:chunk75XDS65A_cjs.p(2),right:chunk75XDS65A_cjs.s("sqrt",[t])}};case "asin":return {kind:"div",left:X(),right:chunk75XDS65A_cjs.s("sqrt",[Tn(t)])};case "acos":return {kind:"neg",operand:{kind:"div",left:X(),right:chunk75XDS65A_cjs.s("sqrt",[Tn(t)])}};case "atan":return {kind:"div",left:X(),right:hr(t)};case "sinh":return chunk75XDS65A_cjs.s("cosh",[t]);case "cosh":return chunk75XDS65A_cjs.s("sinh",[t]);case "tanh":return {kind:"div",left:X(),right:chunk75XDS65A_cjs.r(chunk75XDS65A_cjs.s("cosh",[t]),chunk75XDS65A_cjs.p(2))};case "abs":return chunk75XDS65A_cjs.s("sign",[t]);default:return null}}function Tn(e){return {kind:"sub",left:X(),right:chunk75XDS65A_cjs.r(e,chunk75XDS65A_cjs.p(2))}}function hr(e){return {kind:"add",left:X(),right:chunk75XDS65A_cjs.r(e,chunk75XDS65A_cjs.p(2))}}function xe(e,t,n=1){if(n<0||!Number.isInteger(n))throw chunkSOMGSIO4_cjs.c.execution("SYMBOLIC_DERIVATIVE_ORDER_LIMIT","A derivative order must be a whole number, at least zero.");if(n>it)throw chunkSOMGSIO4_cjs.c.execution("SYMBOLIC_DERIVATIVE_ORDER_LIMIT",`A derivative order above ${it} is not supported.`,{limit:it});let o=chunk75XDS65A_cjs.Q(e);for(let r=0;r<n;r++)o=chunk75XDS65A_cjs.Q(P(o,t));return o}function P(e,t){switch(e.kind){case "const":case "complex":return Vn();case "var":return e.name===t?X():Vn();case "add":return {kind:"add",left:P(e.left,t),right:P(e.right,t)};case "sub":return {kind:"sub",left:P(e.left,t),right:P(e.right,t)};case "neg":return {kind:"neg",operand:P(e.operand,t)};case "mul":return {kind:"add",left:{kind:"mul",left:P(e.left,t),right:e.right},right:{kind:"mul",left:e.left,right:P(e.right,t)}};case "div":return {kind:"div",left:{kind:"sub",left:{kind:"mul",left:P(e.left,t),right:e.right},right:{kind:"mul",left:e.left,right:P(e.right,t)}},right:chunk75XDS65A_cjs.r(e.right,chunk75XDS65A_cjs.p(2))};case "pow":return Nr(e,t);case "call":{if(e.args.length!==1)return at(e,t);let n=yr(e.name,e.args[0]);return n===null?at(e,t):{kind:"mul",left:n,right:P(e.args[0],t)}}}}function Nr(e,t){if(e.exponent.kind==="const"){let n=chunk75XDS65A_cjs.p(chunk75XDS65A_cjs.g(e.exponent.value,chunk75XDS65A_cjs.b));return {kind:"mul",left:{kind:"mul",left:e.exponent,right:chunk75XDS65A_cjs.r(e.base,n)},right:P(e.base,t)}}return e.base.kind==="const"&&e.base.value.n>0n?{kind:"mul",left:{kind:"mul",left:e,right:chunk75XDS65A_cjs.s("log",[e.base])},right:P(e.exponent,t)}:at(e,t)}function at(e,t){return chunk75XDS65A_cjs.s("der",[e,chunk75XDS65A_cjs.q(t)])}function On(e,t){let n=chunk75XDS65A_cjs.C(e);if(n===null||n.vars.filter(u=>u!==t).length>0||chunk75XDS65A_cjs.z(n,t)>1)return null;let r=chunk75XDS65A_cjs.B(n,t),i=r[0]??{n:0n,d:1n},a=r[1]??{n:0n,d:1n};return chunk75XDS65A_cjs.l(a)?null:{slope:a,intercept:i}}function gr(e,t){let n=chunk75XDS65A_cjs.C(e);if(n===null)return null;let o=n.vars.filter(a=>a!==t);if(o.length>0)return {ok:false,reason:`it involves more than one unknown (${o.join(", ")})`};let r=chunk75XDS65A_cjs.B(n,t),i=chunk75XDS65A_cjs.p(0);return r.forEach((a,u)=>{if(chunk75XDS65A_cjs.l(a))return;let l=u+1,s=chunk75XDS65A_cjs.i(a,{n:BigInt(l),d:1n}),p={kind:"mul",left:chunk75XDS65A_cjs.p(s),right:l===1?chunk75XDS65A_cjs.q(t):chunk75XDS65A_cjs.r(chunk75XDS65A_cjs.q(t),chunk75XDS65A_cjs.p(l))};i={kind:"add",left:i,right:p};}),{ok:true,value:chunk75XDS65A_cjs.Q(i)}}function Rr(e,t){if(e.kind!=="call"||e.args.length!==1)return null;let n=On(e.args[0],t);if(n===null)return null;let o=e.args[0],r=i=>chunk75XDS65A_cjs.Q({kind:"div",left:i,right:chunk75XDS65A_cjs.p(n.slope)});switch(e.name){case "exp":return {ok:true,value:r(chunk75XDS65A_cjs.s("exp",[o]))};case "sin":return {ok:true,value:r({kind:"neg",operand:chunk75XDS65A_cjs.s("cos",[o])})};case "cos":return {ok:true,value:r(chunk75XDS65A_cjs.s("sin",[o]))};case "log":return {ok:true,value:r({kind:"sub",left:{kind:"mul",left:o,right:chunk75XDS65A_cjs.s("log",[o])},right:o})};default:return null}}function xr(e,t){if(e.kind!=="div"||e.left.kind!=="const"||!ut(e.left.value))return null;let n=On(e.right,t);if(n!==null)return {ok:true,value:chunk75XDS65A_cjs.Q({kind:"div",left:chunk75XDS65A_cjs.s("log",[e.right]),right:chunk75XDS65A_cjs.p(n.slope)})};let o=chunk75XDS65A_cjs.C(e.right);if(o!==null&&o.vars.length===1&&o.vars[0]===t){let r=chunk75XDS65A_cjs.B(o,t);if(r.length===3&&ut(r[0])&&chunk75XDS65A_cjs.l(r[1])&&ut(r[2]))return {ok:true,value:chunk75XDS65A_cjs.s("atan",[chunk75XDS65A_cjs.q(t)])}}return null}function ut(e){return e.n===1n&&e.d===1n}function vr(e,t){let n=rt(e);if(n===null||n.variable!==t)return null;let o=ot(n.numerator,n.denominator,t);if(o===null)return null;let r=o.polynomial.length>0?Sr(o.polynomial,t):chunk75XDS65A_cjs.p(0);for(let i of o.terms){let a=Ir(i,t);if(a===null)return {ok:false,reason:"its denominator has a repeated irreducible quadratic factor, which needs a reduction formula this does not have"};r={kind:"add",left:r,right:a};}return {ok:true,value:chunk75XDS65A_cjs.Q(r)}}function Ir(e,t){let n=e.base.length-1,o=Re(e.base,t);if(n===1){let r=e.numerator[0]??chunk75XDS65A_cjs.a;if(e.power===1)return {kind:"mul",left:chunk75XDS65A_cjs.p(r),right:chunk75XDS65A_cjs.s("log",[o])};let i=e.power-1,a=chunk75XDS65A_cjs.i(r,{n:BigInt(-i),d:1n});return {kind:"div",left:chunk75XDS65A_cjs.p(a),right:chunk75XDS65A_cjs.r(o,chunk75XDS65A_cjs.p({n:BigInt(i),d:1n}))}}return n!==2||e.power!==1?null:Mr(e,t,o)}function Mr(e,t,n){let o=e.numerator[0]??chunk75XDS65A_cjs.a,r=e.numerator[1]??chunk75XDS65A_cjs.a,[i,a]=e.base,u={n:1n,d:2n},l=chunk75XDS65A_cjs.h(a,u),s={kind:"mul",left:chunk75XDS65A_cjs.p(chunk75XDS65A_cjs.h(r,u)),right:chunk75XDS65A_cjs.s("log",[n])},p=chunk75XDS65A_cjs.g(o,chunk75XDS65A_cjs.h(r,l));if(chunk75XDS65A_cjs.l(p))return s;let h=chunk75XDS65A_cjs.O(chunk75XDS65A_cjs.g(i,chunk75XDS65A_cjs.h(l,l))),x={kind:"add",left:chunk75XDS65A_cjs.q(t),right:chunk75XDS65A_cjs.p(l)},V={kind:"mul",left:{kind:"div",left:chunk75XDS65A_cjs.p(p),right:h},right:chunk75XDS65A_cjs.s("atan",[{kind:"div",left:x,right:h}])};return chunk75XDS65A_cjs.l(r)?V:{kind:"add",left:s,right:V}}function Sr(e,t){let n=chunk75XDS65A_cjs.p(0);return e.forEach((o,r)=>{if(chunk75XDS65A_cjs.l(o))return;let i=r+1,a=chunk75XDS65A_cjs.i(o,{n:BigInt(i),d:1n}),u={kind:"mul",left:chunk75XDS65A_cjs.p(a),right:i===1?chunk75XDS65A_cjs.q(t):chunk75XDS65A_cjs.r(chunk75XDS65A_cjs.q(t),chunk75XDS65A_cjs.p(i))};n={kind:"add",left:n,right:u};}),n}function ve(e,t){let n=chunk75XDS65A_cjs.Q(e);if(!chunk75XDS65A_cjs.u(n).has(t))return {ok:true,value:chunk75XDS65A_cjs.Q({kind:"mul",left:n,right:chunk75XDS65A_cjs.q(t)})};let o=gr(n,t);if(o!==null)return o;let r=Rr(n,t);if(r!==null)return r;let i=xr(n,t);if(i!==null)return i;let a=vr(n,t);if(a!==null)return a;if(n.kind==="add"||n.kind==="sub"){let u=ve(n.left,t);if(!u.ok)return u;let l=ve(n.right,t);return l.ok?{ok:true,value:chunk75XDS65A_cjs.Q({kind:n.kind,left:u.value,right:l.value})}:l}if(n.kind==="mul"&&n.left.kind==="const"){let u=ve(n.right,t);return u.ok?{ok:true,value:chunk75XDS65A_cjs.Q({kind:"mul",left:n.left,right:u.value})}:u}return {ok:false,reason:"no elementary antiderivative is known for this expression"}}var lt=16;function _n(e,t,n,o){if(o<0||!Number.isInteger(o)||o>lt)throw chunkSOMGSIO4_cjs.c.execution("SYMBOLIC_TAYLOR_DEGREE_LIMIT",`A Taylor degree must be a whole number from 0 to ${lt}.`,{limit:lt});let r=chunk75XDS65A_cjs.p(n),i=1n,a=chunk75XDS65A_cjs.p(chunk75XDS65A_cjs.a);for(let u=0;u<=o;u++){u>0&&(i*=BigInt(u));let l=xe(e,t,u),s=chunk75XDS65A_cjs.Q(chunk75XDS65A_cjs.v(l,t,r));if(s.kind!=="const")throw chunkSOMGSIO4_cjs.c.execution("SYMBOLIC_TAYLOR_INEXACT",`The derivative of order ${u} does not reduce to an exact number at the expansion point, so this series cannot be computed exactly.`,{order:u});let p=chunk75XDS65A_cjs.i(s.value,{n:i,d:1n});if(chunk75XDS65A_cjs.l(p))continue;let h=chunk75XDS65A_cjs.l(n)?chunk75XDS65A_cjs.q(t):{kind:"sub",left:chunk75XDS65A_cjs.q(t),right:r},x=u===0?chunk75XDS65A_cjs.p(1):u===1?h:chunk75XDS65A_cjs.r(h,chunk75XDS65A_cjs.p(u));a={kind:"add",left:a,right:{kind:"mul",left:chunk75XDS65A_cjs.p(p),right:x}};}return chunk75XDS65A_cjs.Q(a)}function wn(e,t){return e.map(n=>t.map(o=>xe(n,o)))}function Er(){return {pluginFunctions:{},opRegistry:new Ne,pluginFunctionOwners:{}}}var Dn=Er();var Ar={1970:38.8,1971:40.5,1972:41.8,1973:44.4,1974:49.3,1975:53.8,1976:56.9,1977:60.6,1978:65.2,1979:72.6,1980:82.4,1981:90.9,1982:96.5,1983:99.6,1984:103.9,1985:107.6,1986:109.6,1987:113.6,1988:118.3,1989:124,1990:130.7,1991:136.2,1992:140.3,1993:144.5,1994:148.2,1995:152.4,1996:156.9,1997:160.5,1998:163,1999:166.6,2e3:172.2,2001:177.1,2002:179.9,2003:184,2004:188.9,2005:195.3,2006:201.6,2007:207.3,2008:215.3,2009:214.5,2010:218.1,2011:224.9,2012:229.6,2013:233,2014:236.7,2015:237,2016:240,2017:245.1,2018:251.1,2019:255.7,2020:258.8,2021:271,2022:292.7,2023:304.7,2024:313.7,2025:322.2,2026:332.7},Pn=1970,Ln=2026;function Cn(e){return Ar[Math.trunc(e)]}function st(e,t){let n=Cn(e),o=Cn(t);if(!(n===void 0||o===void 0||n===0))return o/n}function va(e,t,n){let o=st(t,n);if(o!==void 0)return e*o}var kr=0;function ct(e){if(e.type===6&&e.unit!==void 0){let t=chunk6QRHN3I6_cjs.a[e.unit.toLowerCase()];if(t!==void 0&&t[0]===kr)return e.toNumber()*t[1]}return e.toNumber()}function Vr(e,t){if(t===1)return e;let n=`${e}s`;return chunk6QRHN3I6_cjs.a[n.toLowerCase()]===void 0?e:n}function Fn(e,t){let n,o=false;for(let r of e){if(Number.isNaN(r.toNumber())){o=true;continue}if(n===void 0){n=r;continue}let{lv:i,rv:a,sameMeasure:u}=he(n,r);if(!u){let l=n.type===6?n.unit:void 0,s=r.type===6?r.unit:void 0,p=Fe(l,s,"compared");return chunkPNDQRCRQ_cjs.P("INCOMPATIBLE_UNITS",p??`Cannot compare incompatible units: ${l??"?"} and ${s??"?"}`)}(t?a>i:a<i)&&(n=r);}return o?chunkPNDQRCRQ_cjs.n(NaN):n===void 0?chunkPNDQRCRQ_cjs.n(t?-1/0:1/0):n.type===6?n:chunkPNDQRCRQ_cjs.n(n.toNumber())}function Ue(e,t){return e.type===6&&e.unit!==void 0?chunkPNDQRCRQ_cjs.u(t,e.unit):chunkPNDQRCRQ_cjs.n(t)}function Un(e,t){let n=Number.isFinite(t)?Math.min(100,Math.max(0,Math.trunc(t))):0;if(e.exact!==void 0){let a=chunk75XDS65A_cjs.oa(e.exact,n);return $e(e,chunk75XDS65A_cjs.ra(a),n,a)}let o=e.toNumber();if(!Number.isFinite(o))return $e(e,o,n);let r=Math.pow(10,n),i=o*r;return !Number.isFinite(i)||Math.abs(i)>Number.MAX_SAFE_INTEGER?$e(e,o,n):$e(e,Math.round(i)/r,n)}function $e(e,t,n,o){let r=e.type===6&&e.unit!==void 0?chunkPNDQRCRQ_cjs.u(t,e.unit):chunkPNDQRCRQ_cjs.n(t);return r.decimalPlaces=n,o!==void 0&&(r.exact=o),r}function $n(e,t,n){if(Number.isFinite(e)&&Number.isFinite(t))return null;let o=Number.isFinite(e)?t:e;return chunkPNDQRCRQ_cjs.P("INVALID_INTEGER_OPERAND",`${n} needs two whole numbers, and ${Number.isNaN(o)?"one of them has no value":"one of them is infinite"}`)}function Bn(e,t){let n=e,o=t;for(;o!==0;){let r=o;o=n%o,n=r;}return n}function Tr(e){let t=e.length;if(t===0)return 0;let n=e.reduce((o,r)=>o+r,0)/t;return e.reduce((o,r)=>o+(r-n)*(r-n),0)}function Be(e,t){let n=e.length;if(n===0)return 0;let o=t?n-1:n;return o<=0?0:Tr(e)/o}var Ga={0:e=>{let t=e[0].toNumber();return t>=0?chunkPNDQRCRQ_cjs.n(Math.sqrt(t)):_(chunk75XDS65A_cjs.s("sqrt",[chunk75XDS65A_cjs.p(t)]))},1:e=>e[0].type===7?chunk75XDS65A_cjs.ca(e[0].value):Ue(e[0],Math.abs(e[0].toNumber())),2:e=>chunkPNDQRCRQ_cjs.n(Math.sin(ct(e[0]))),3:e=>chunkPNDQRCRQ_cjs.n(Math.cos(ct(e[0]))),4:e=>chunkPNDQRCRQ_cjs.n(Math.tan(ct(e[0]))),5:e=>chunkPNDQRCRQ_cjs.n(Math.log(e[0].toNumber())),6:e=>Ue(e[0],Math.ceil(e[0].toNumber())),7:e=>Ue(e[0],Math.floor(e[0].toNumber())),8:e=>e.length>=2?Un(e[0],e[1].toNumber()):Ue(e[0],Math.round(e[0].toNumber())),9:e=>Fn(e,false),10:e=>Fn(e,true),11:e=>chunkPNDQRCRQ_cjs.n(Math.asin(e[0].toNumber())),12:e=>chunkPNDQRCRQ_cjs.n(Math.acos(e[0].toNumber())),13:e=>chunkPNDQRCRQ_cjs.n(Math.atan(e[0].toNumber())),14:e=>chunkPNDQRCRQ_cjs.n(Math.atan2(e[0].toNumber(),e[1].toNumber())),15:e=>chunkPNDQRCRQ_cjs.n(Math.sinh(e[0].toNumber())),16:e=>chunkPNDQRCRQ_cjs.n(Math.cosh(e[0].toNumber())),17:e=>chunkPNDQRCRQ_cjs.n(Math.tanh(e[0].toNumber())),18:e=>chunkPNDQRCRQ_cjs.n(Math.asinh(e[0].toNumber())),19:e=>chunkPNDQRCRQ_cjs.n(Math.acosh(e[0].toNumber())),20:e=>chunkPNDQRCRQ_cjs.n(Math.atanh(e[0].toNumber())),21:e=>chunkPNDQRCRQ_cjs.n(Math.cbrt(e[0].toNumber())),22:e=>chunkPNDQRCRQ_cjs.n(Math.clz32(e[0].toNumber())),23:e=>chunkPNDQRCRQ_cjs.n(Math.expm1(e[0].toNumber())),24:e=>chunkPNDQRCRQ_cjs.n(Math.exp(e[0].toNumber())),25:e=>chunkPNDQRCRQ_cjs.n(Math.fround(e[0].toNumber())),26:e=>chunkPNDQRCRQ_cjs.n(Math.hypot(...e.map(t=>t.toNumber()))),27:e=>chunkPNDQRCRQ_cjs.n(Math.imul(e[0].toNumber(),e[1].toNumber())),28:e=>chunkPNDQRCRQ_cjs.n(Math.log10(e[0].toNumber())),29:e=>chunkPNDQRCRQ_cjs.n(Math.log1p(e[0].toNumber())),30:e=>chunkPNDQRCRQ_cjs.n(Math.log2(e[0].toNumber())),31:e=>e[0].type===7?e[1].type!==0?chunkPNDQRCRQ_cjs.P("MATRIX_POWER_UNSUPPORTED",`pow: a matrix's exponent must be a whole number, as in "pow([1,2;3,4], 2)".`):chunk75XDS65A_cjs.$(e[0].value,e[1].value):e[1].type===7?chunkPNDQRCRQ_cjs.P("MATRIX_POWER_UNSUPPORTED",'pow: a matrix may only be the base, as in "pow([1,2;3,4], 2)".'):chunkPNDQRCRQ_cjs.n(et(e[0].toNumber(),e[1].toNumber())),32:()=>chunkPNDQRCRQ_cjs.n(Math.random()),33:e=>chunkPNDQRCRQ_cjs.n(Math.sign(e[0].toNumber())),34:e=>chunkPNDQRCRQ_cjs.n(Math.trunc(e[0].toNumber())),35:e=>chunkPNDQRCRQ_cjs.n(e[0].toNumber()*Math.PI/180),36:e=>chunkPNDQRCRQ_cjs.n(e[0].toNumber()*180/Math.PI),37:e=>{let t=e[0].toNumber(),n=e[1].toNumber();return t>n?chunkPNDQRCRQ_cjs.P("INVALID_RANGE",`roll: invalid range, ${t} is greater than ${n}`):chunkPNDQRCRQ_cjs.n(Math.floor(Math.random()*(n-t+1))+t)},38:e=>{let t=Math.trunc(Math.abs(e[0].toNumber())),n=Math.trunc(Math.abs(e[1].toNumber())),o=$n(t,n,"gcd");return o||chunkPNDQRCRQ_cjs.n(Bn(t,n))},39:e=>{let t=Math.trunc(Math.abs(e[0].toNumber())),n=Math.trunc(Math.abs(e[1].toNumber())),o=$n(t,n,"lcm");return o||(t===0||n===0?chunkPNDQRCRQ_cjs.n(0):chunkPNDQRCRQ_cjs.n(t/Bn(t,n)*n))},40:e=>{let t=Math.trunc(e[0].toNumber()),n=Math.trunc(e[1].toNumber());if(t<0||n<0||n>t)return chunkPNDQRCRQ_cjs.P("INVALID_RANGE",`permutation: invalid n=${t}, r=${n} (require 0 <= r <= n)`);let o=1;for(let r=0;r<n;r++)if(o*=t-r,!Number.isFinite(o))return chunkPNDQRCRQ_cjs.P("PERMUTATION_OVERFLOW",`permutation: P(${t}, ${n}) exceeds the maximum representable double (it passed it after ${r+1} of ${n} factors)`);return chunkPNDQRCRQ_cjs.n(o)},41:e=>{let t=Math.trunc(e[0].toNumber()),n=Math.trunc(e[1].toNumber());if(t<0||n<0||n>t)return chunkPNDQRCRQ_cjs.P("INVALID_RANGE",`combination: invalid n=${t}, r=${n} (require 0 <= r <= n)`);let o=Math.min(n,t-n),r=1;for(let i=0;i<o;i++)if(r=r*(t-i)/(i+1),!Number.isFinite(r))return chunkPNDQRCRQ_cjs.P("COMBINATION_OVERFLOW",`combination: C(${t}, ${n}) exceeds the maximum representable double (it passed it after ${i+1} of ${o} steps)`);return chunkPNDQRCRQ_cjs.n(Math.round(r))},42:e=>{if(e.length===0)return chunkPNDQRCRQ_cjs.n(0);let t=e.reduce((n,o)=>n+o.toNumber(),0);return chunkPNDQRCRQ_cjs.n(t/e.length)},43:e=>{if(e.length===0)return chunkPNDQRCRQ_cjs.n(0);let t=e.map(o=>o.toNumber()).sort((o,r)=>o-r),n=Math.floor(t.length/2);return chunkPNDQRCRQ_cjs.n(t.length%2===0?(t[n-1]+t[n])/2:t[n])},44:e=>chunkPNDQRCRQ_cjs.n(e.reduce((t,n)=>t+n.toNumber(),0)),45:e=>chunkPNDQRCRQ_cjs.n(e.length),46:e=>{let[t,n,o]=e,{lv:r,rv:i}=he(t,n);if(r===0)return chunkPNDQRCRQ_cjs.P("PROPORTION_DIVIDE_BY_ZERO",`Cannot compute proportion: "${t.value}" is zero`);let a=o.toNumber()*(i/r);return o.type===6?chunkPNDQRCRQ_cjs.u(a,o.unit):chunkPNDQRCRQ_cjs.n(a)},47:e=>{let t=e[0].toNumber(),n=e[1].toNumber(),o=e[2].toNumber();return n>o?chunkPNDQRCRQ_cjs.P("INVALID_RANGE",`clamp: invalid range, ${n} is greater than ${o}`):chunkPNDQRCRQ_cjs.n(Math.min(Math.max(t,n),o))},48:e=>chunkPNDQRCRQ_cjs.r(e[0].toNumber()),49:e=>chunkPNDQRCRQ_cjs.r(e[0].toNumber(),"bin"),50:e=>chunkPNDQRCRQ_cjs.n(Math.trunc(e[0].toNumber())),51:e=>{let t=e[0].toNumber(),n=e[1].toNumber(),o=e[2].toNumber();if(1+n<=0)return chunkPNDQRCRQ_cjs.P("INVALID_RATE",`compoundInterest: rate ${n} makes (1 + rate) non-positive`);let r=t*Math.pow(1+n,o);return e[0].type===6?chunkPNDQRCRQ_cjs.u(r,e[0].unit):chunkPNDQRCRQ_cjs.n(r)},52:e=>{let t=e[0].toNumber(),n=e[1].toNumber(),o=e[2].toNumber();if(1+n<=0)return chunkPNDQRCRQ_cjs.P("INVALID_RATE",`interestEarned: rate ${n} makes (1 + rate) non-positive`);let r=t*(Math.pow(1+n,o)-1);return e[0].type===6?chunkPNDQRCRQ_cjs.u(r,e[0].unit):chunkPNDQRCRQ_cjs.n(r)},53:e=>{let t=e[0].toNumber(),n=e[1].toNumber(),o=e[2].toNumber();return t<=0||n<=0?chunkPNDQRCRQ_cjs.P("INVALID_RANGE","compoundInterestRate: principal and futureValue must both be positive"):o<=0?chunkPNDQRCRQ_cjs.P("INVALID_RANGE","compoundInterestRate: years must be greater than 0"):chunkPNDQRCRQ_cjs.n(Math.pow(n/t,1/o)-1)},54:e=>{let t=e[0].toNumber(),n=e[1].toNumber(),o=e[2].toNumber();return t<=0||n<=0?chunkPNDQRCRQ_cjs.P("INVALID_RANGE","compoundInterestYears: principal and futureValue must both be positive"):1+o<=0||o===0?chunkPNDQRCRQ_cjs.P("INVALID_RATE",`compoundInterestYears: rate ${o} is not usable (must be > -1 and not 0)`):chunkPNDQRCRQ_cjs.n(Math.log(n/t)/Math.log(1+o))},55:e=>{let t=e[0].toNumber(),n=e[1].toNumber(),o=e[2].toNumber(),r=e[3].toNumber();if(t<=0)return chunkPNDQRCRQ_cjs.P("INVALID_RANGE","loanRepayment: principal must be positive");if(o<=0)return chunkPNDQRCRQ_cjs.P("INVALID_RANGE","loanRepayment: years must be positive");if(n<0)return chunkPNDQRCRQ_cjs.P("INVALID_RATE","loanRepayment: rate must not be negative");if(r<0)return chunkPNDQRCRQ_cjs.P("INVALID_RANGE","loanRepayment: periodsPerYear must not be negative");let{totalRepayment:i}=dt(t,n,o),a=r===0?i:i/(o*r);return e[0].type===6?chunkPNDQRCRQ_cjs.u(a,e[0].unit):chunkPNDQRCRQ_cjs.n(a)},56:e=>{let t=e[0].toNumber(),n=e[1].toNumber(),o=e[2].toNumber(),r=e[3].toNumber();if(t<=0)return chunkPNDQRCRQ_cjs.P("INVALID_RANGE","loanInterest: principal must be positive");if(o<=0)return chunkPNDQRCRQ_cjs.P("INVALID_RANGE","loanInterest: years must be positive");if(n<0)return chunkPNDQRCRQ_cjs.P("INVALID_RATE","loanInterest: rate must not be negative");if(r<0)return chunkPNDQRCRQ_cjs.P("INVALID_RANGE","loanInterest: periodsPerYear must not be negative");let{totalInterest:i}=dt(t,n,o),a=r===0?i:i/(o*r);return e[0].type===6?chunkPNDQRCRQ_cjs.u(a,e[0].unit):chunkPNDQRCRQ_cjs.n(a)},57:e=>{let t=e[0].toNumber(),n=e[1].toNumber(),o=e[2].toNumber();if(t<=0)return chunkPNDQRCRQ_cjs.P("INVALID_RANGE","monthlyPayment: principal must be positive");if(o<=0)return chunkPNDQRCRQ_cjs.P("INVALID_RANGE","monthlyPayment: years must be positive");if(n<0)return chunkPNDQRCRQ_cjs.P("INVALID_RATE","monthlyPayment: rate must not be negative");let{monthlyPayment:r}=dt(t,n,o);return e[0].type===6?chunkPNDQRCRQ_cjs.u(r,e[0].unit):chunkPNDQRCRQ_cjs.n(r)},58:e=>{let t=e[0].toNumber(),n=e[1].toNumber();return e[0].type===6?vn(e[0],e[0].unit,n,1):chunkPNDQRCRQ_cjs.n(t*(1+n))},59:e=>{let t=e[0].toNumber(),n=e[1].toNumber();return 1+n<=0?chunkPNDQRCRQ_cjs.P("INVALID_RATE",`taxRemove: rate ${n} makes (1 + rate) non-positive`):e[0].type===6?Mn(e[0],e[0].unit,n)??chunkPNDQRCRQ_cjs.u(t/(1+n),e[0].unit):chunkPNDQRCRQ_cjs.n(t/(1+n))},60:e=>{let t=e[0].toNumber(),n=e[1].toNumber(),o=e[2].toNumber(),r=st(n,o);if(r===void 0)return chunkPNDQRCRQ_cjs.P("INFLATION_YEAR_OUT_OF_RANGE",`inflationAdjust: fromYear ${n} or toYear ${o} is outside the bundled CPI table's range (${Pn}-${Ln})`);let i=t*r;return e[0].type===6?chunkPNDQRCRQ_cjs.u(i,e[0].unit):chunkPNDQRCRQ_cjs.n(i)},61:e=>{let t=e[0].toNumber(),n=e[1].toNumber();return chunkPNDQRCRQ_cjs.n(et(n,1/t))},62:e=>{let t=e[0].toNumber();if(!Number.isInteger(t)||t<0)return chunkPNDQRCRQ_cjs.P("INVALID_FACTORIAL_INPUT",`fact: ${t} is not a non-negative integer`);if(t>170)return chunkPNDQRCRQ_cjs.P("FACTORIAL_OVERFLOW",`fact: ${t}! exceeds the maximum representable double (170! is the largest finite factorial)`);let n=1;for(let o=2;o<=t;o++)n*=o;return chunkPNDQRCRQ_cjs.n(n)},63:e=>e[0].type===7?chunk75XDS65A_cjs.ba(e[0].value):e[0],64:e=>e[0].type===7?chunk75XDS65A_cjs.ca(e[0].value):chunkPNDQRCRQ_cjs.n(e[0].toNumber()),65:e=>e[0].type===7?chunk75XDS65A_cjs.da(e[0].value):chunkPNDQRCRQ_cjs.n(1/e[0].toNumber()),66:e=>{let[t,n]=e;if(t.type===0&&n.type===0)return chunkPNDQRCRQ_cjs.n(t.toNumber()*n.toNumber());let o=r=>r.type===7?r.value:{rows:1,cols:1,data:[r.toNumber()],hasSymbolic:false};return chunk75XDS65A_cjs._(o(t),o(n))},67:e=>{let[t]=e;return t.type!==9?t:_(chunk75XDS65A_cjs.F(t.value))},68:e=>{let[t]=e;return t.type!==9?t:_(zt(t.value))},69:e=>{let[t,n,o]=e;return o?.type!==3?chunkPNDQRCRQ_cjs.P("SOLVE_REQUIRES_VARIABLE_NAME","solve's second argument must be the name of the unknown."):fn(t,n,o.value)},70:e=>{let[t,n,o]=e,r=ft(n,"der");if(typeof r!="string")return r;let i=O(t);return i===null?chunkPNDQRCRQ_cjs.P("SYMBOLIC_NONFINITE_OPERAND","der needs an expression with an exact value."):_(xe(i,r,o?.toNumber()??1))},71:e=>{let[t,n]=e,o=ft(n,"integral");if(typeof o!="string")return o;let r=O(t);if(r===null)return chunkPNDQRCRQ_cjs.P("SYMBOLIC_NONFINITE_OPERAND","integral needs an expression with an exact value.");let i=ve(r,o);return i.ok?_(i.value):chunkPNDQRCRQ_cjs.P("SYMBOLIC_INTEGRAL_UNSUPPORTED",`Cannot integrate this: ${i.reason}.`)},72:e=>{let[t,n,o,r]=e,i=ft(n,"taylor");if(typeof i!="string")return i;let a=O(t),u=O(o);return a===null||u===null||u.kind!=="const"?chunkPNDQRCRQ_cjs.P("SYMBOLIC_NONFINITE_OPERAND","taylor needs an expression and an exact expansion point."):_(_n(a,i,u.value,r.toNumber()))},73:e=>{let t=[];for(let a of e){let u=O(a);if(u===null)return chunkPNDQRCRQ_cjs.P("SYMBOLIC_NONFINITE_OPERAND","jacobian needs expressions with exact values.");t.push(u);}let n=new Set;for(let a of t)for(let u of chunk75XDS65A_cjs.u(a))n.add(u);let o=[...n].sort();if(o.length===0)return chunkPNDQRCRQ_cjs.P("SYMBOLIC_JACOBIAN_NO_VARIABLES","jacobian needs at least one unknown to differentiate against.");let r=wn(t,o),i=[];for(let a of r)for(let u of a)i.push(chunk75XDS65A_cjs.W(u));return chunkPNDQRCRQ_cjs.C(r.length,o.length,chunk75XDS65A_cjs.Y(r.length,o.length,i))},74:e=>_(chunk75XDS65A_cjs.w(chunk75XDS65A_cjs.o(chunk75XDS65A_cjs.a,chunk75XDS65A_cjs.d(e[0].toNumber())))),75:e=>mt("conj",e[0]),76:e=>mt("re",e[0]),77:e=>mt("im",e[0]),78:e=>{let t=e[0];return t.type!==9?t:_(chunk75XDS65A_cjs.J(t.value))},79:e=>{let t=e[0];return t.type!==9?t:_(kn(t.value))},85:e=>{let t=e[0].toNumber(),n=e[1].toNumber();if(1+n<=0)return chunkPNDQRCRQ_cjs.P("INVALID_RATE",`taxIn: rate ${n} makes (1 + rate) non-positive`);let o=t-t/(1+n);return e[0].type===6?Sn(e[0],e[0].unit,n)??chunkPNDQRCRQ_cjs.u(o,e[0].unit):chunkPNDQRCRQ_cjs.n(o)},86:e=>{let t=e[0].toNumber(),n=e[1].toNumber();return e[0].type===6?xn(e[0],n,e[0].unit):chunkPNDQRCRQ_cjs.n(t*n)},87:e=>chunkPNDQRCRQ_cjs.n(Math.sin(e[0].toNumber()*Math.PI/180)),88:e=>chunkPNDQRCRQ_cjs.n(Math.cos(e[0].toNumber()*Math.PI/180)),89:e=>chunkPNDQRCRQ_cjs.n(Math.tan(e[0].toNumber()*Math.PI/180)),90:e=>chunkPNDQRCRQ_cjs.n(Math.asin(e[0].toNumber())*180/Math.PI),91:e=>chunkPNDQRCRQ_cjs.n(Math.acos(e[0].toNumber())*180/Math.PI),92:e=>chunkPNDQRCRQ_cjs.n(Math.atan(e[0].toNumber())*180/Math.PI),93:e=>chunkPNDQRCRQ_cjs.u(e[0].toNumber(),"days"),94:e=>{let t=typeof e[1]?.value=="string"?e[1].value:void 0,n=typeof e[2]?.value=="string"?e[2].value:void 0;if(t===void 0||n===void 0)return chunkPNDQRCRQ_cjs.P("UNKNOWN_UNIT",'both units have to be named, as in "12.5 minutes in minutes and seconds"');let o=chunk6QRHN3I6_cjs.a[t.toLowerCase()],r=chunk6QRHN3I6_cjs.a[n.toLowerCase()];if(o===void 0||r===void 0)return chunkPNDQRCRQ_cjs.P("UNKNOWN_UNIT",`${t} and ${n}: one of these is not a unit`);if(o[0]!==r[0])return chunkPNDQRCRQ_cjs.P("INCOMPATIBLE_UNITS",`${t} and ${n} measure different things`);if(r[1]>=o[1])return chunkPNDQRCRQ_cjs.P("INCOMPATIBLE_UNITS",`${t} and ${n}: name the larger unit first`);let i=e[0],a=i.type===6&&i.unit!==void 0?chunk6QRHN3I6_cjs.a[i.unit.toLowerCase()]:void 0,u=i.toNumber()*(a?.[1]??o[1]),l=Math.floor(u/o[1]),s=Math.round((u-l*o[1])/r[1]*1e3)/1e3;return chunkPNDQRCRQ_cjs.t(`${l} ${t} ${s} ${n}`)},95:e=>{let t=e[0],n=String(e[1].value),o=t.type===6&&t.unit!==void 0?t.unit:"";return o.includes("/")?chunkPNDQRCRQ_cjs.P("INVALID_RATE_UNIT",`${o}/${n}: that is already a rate`):chunkPNDQRCRQ_cjs.u(t.toNumber(),`${o}/${n}`)},96:e=>{let t=e[0],n=e[1];if(n.type!==6||n.unit===void 0||!n.unit.includes("/"))return chunkPNDQRCRQ_cjs.P("INVALID_RATE",'at: the right-hand side has to be a rate, as in "$30/hour"');let o=n.unit.indexOf("/"),r=n.unit.slice(0,o),i=n.unit.slice(o+1),a=t.type===6?t.unit:void 0,u=chunk6QRHN3I6_cjs.a[i.toLowerCase()],l=a===void 0?void 0:chunk6QRHN3I6_cjs.a[a.toLowerCase()];if(l!==void 0&&u!==void 0&&l[0]===u[0]){let p=t.toNumber()*l[1]/u[1]*n.toNumber();return r===""?chunkPNDQRCRQ_cjs.n(p):chunkPNDQRCRQ_cjs.u(p,r)}if(a!==void 0&&a===r){let s=t.toNumber()/n.toNumber();return chunkPNDQRCRQ_cjs.u(s,Vr(i,s))}if(a===void 0){let s=t.toNumber()*n.toNumber();return r===""?chunkPNDQRCRQ_cjs.n(s):chunkPNDQRCRQ_cjs.u(s,r)}return chunkPNDQRCRQ_cjs.P("INCOMPATIBLE_UNITS",`at: ${a} matches neither side of ${n.unit}`)},80:e=>{let t=e[0].toNumber(),n=e[1].toNumber(),o=e[2].toNumber(),r=e[3].toNumber();if(r<=0)return chunkPNDQRCRQ_cjs.P("INVALID_RATE",`compounding: ${r} periods per year is not a period`);if(1+n/r<=0)return chunkPNDQRCRQ_cjs.P("INVALID_RATE",`compounding: rate ${n} makes each period non-positive`);let i=t*Math.pow(1+n/r,r*o);return e[0].type===6?chunkPNDQRCRQ_cjs.u(i,e[0].unit):chunkPNDQRCRQ_cjs.n(i)},81:e=>{let t=e[0].toNumber(),n=e[1].toNumber(),o=e[2].toNumber(),r=e[3].toNumber();if(r<=0||1+n/r<=0)return chunkPNDQRCRQ_cjs.P("INVALID_RATE",`compounding: rate ${n} over ${r} periods per year is not usable`);let i=t*(Math.pow(1+n/r,r*o)-1);return e[0].type===6?chunkPNDQRCRQ_cjs.u(i,e[0].unit):chunkPNDQRCRQ_cjs.n(i)},82:e=>{let t=e[0].toNumber(),n=e[1].toNumber(),o=e[2].toNumber();if(1+n<=0)return chunkPNDQRCRQ_cjs.P("INVALID_RATE",`presentValue: rate ${n} makes (1 + rate) non-positive`);let r=t/Math.pow(1+n,o);return e[0].type===6?chunkPNDQRCRQ_cjs.u(r,e[0].unit):chunkPNDQRCRQ_cjs.n(r)},83:e=>{let t=e[0].toNumber(),n=e[1].toNumber();return t===0?chunkPNDQRCRQ_cjs.P("INVALID_RATE","roi: nothing was invested, so there is no return on it"):chunkPNDQRCRQ_cjs.n((n-t)/t)},84:e=>{let t=e[0].toNumber(),n=e[1].toNumber(),o=e[2].toNumber();return t<=0?chunkPNDQRCRQ_cjs.P("INVALID_RATE","annual return: the amount invested must be positive"):o<=0?chunkPNDQRCRQ_cjs.P("INVALID_RATE","annual return: the period must be longer than zero"):n<=0?chunkPNDQRCRQ_cjs.P("INVALID_RATE","annual return: nothing was returned, so there is no annual rate"):chunkPNDQRCRQ_cjs.N(Math.pow(n/t,1/o)-1)},97:e=>Un(e[0],e[1].toNumber()),98:e=>{let t=e[1].toNumber();return !Number.isInteger(t)||t<1?chunkPNDQRCRQ_cjs.P("INVALID_RANGE",`split: the number of shares must be a whole number of at least 1, not ${e[1].toNumber()}.`):chunkPNDQRCRQ_cjs.H(En(e[0],t))},99:e=>{let t=e[0].toNumber(),n=Or(e[1]),o=e[2].toNumber();if(n===null)return chunkPNDQRCRQ_cjs.P("INVALID_RANGE",'savings goal: the duration must be in months or years, e.g. "in 2 years".');if(t<=0)return chunkPNDQRCRQ_cjs.P("INVALID_RANGE","savings goal: the target must be positive.");if(n<=0)return chunkPNDQRCRQ_cjs.P("INVALID_RANGE","savings goal: the duration must be positive.");if(o<0)return chunkPNDQRCRQ_cjs.P("INVALID_RATE","savings goal: the rate must not be negative.");let r=_r(t,o/12,n);return e[0].type===6?chunkPNDQRCRQ_cjs.u(r,e[0].unit):chunkPNDQRCRQ_cjs.n(r)},100:e=>{let t=e[0].toNumber(),n=e[1].toNumber(),o=e[2].toNumber(),r=e[3].toNumber(),i=typeof e[4]?.value=="string"?e[4].value:"periods";if(t<=0)return chunkPNDQRCRQ_cjs.P("INVALID_RANGE","savings goal: the target must be positive.");if(n<=0)return chunkPNDQRCRQ_cjs.P("INVALID_RANGE","savings goal: the contribution must be positive.");if(r<0)return chunkPNDQRCRQ_cjs.P("INVALID_RATE","savings goal: the rate must not be negative.");let a=wr(t,n,r/o);return chunkPNDQRCRQ_cjs.u(a,i)},101:e=>chunkPNDQRCRQ_cjs.n(Math.sqrt(Be(e.map(t=>t.toNumber()),false))),102:e=>chunkPNDQRCRQ_cjs.n(Math.sqrt(Be(e.map(t=>t.toNumber()),true))),103:e=>chunkPNDQRCRQ_cjs.n(Be(e.map(t=>t.toNumber()),false)),104:e=>chunkPNDQRCRQ_cjs.n(Be(e.map(t=>t.toNumber()),true)),105:e=>{if(e.length===0)return chunkPNDQRCRQ_cjs.n(0);let t=e.map(n=>n.toNumber());return chunkPNDQRCRQ_cjs.n(Math.max(...t)-Math.min(...t))},106:e=>{if(e.length===0)return chunkPNDQRCRQ_cjs.n(0);let t=new Map,n=e[0].toNumber(),o=0;for(let r of e){let i=r.toNumber(),a=(t.get(i)??0)+1;t.set(i,a),a>o&&(o=a,n=i);}return chunkPNDQRCRQ_cjs.n(n)},107:e=>{let t=0,n=0;for(let o=0;o+1<e.length;o+=2){let r=e[o].toNumber(),i=e[o+1].toNumber();t+=r*i,n+=i;}return n===0?chunkPNDQRCRQ_cjs.P("WEIGHTED_AVERAGE_ZERO_WEIGHT","weighted average: the weights sum to zero, so there is nothing to divide by"):chunkPNDQRCRQ_cjs.n(t/n)}};function Or(e){if(e.type!==6)return null;let t=e.unit;return t==="months"||t==="month"?e.toNumber():t==="years"||t==="year"?e.toNumber()*12:null}function _r(e,t,n){return t===0?e/n:e*t/(Math.pow(1+t,n)-1)}function wr(e,t,n){let o=n===0?e/t:Math.log(1+e*n/t)/Math.log(1+n);return Math.ceil(o-1e-9)}function mt(e,t){let n=O(t);return n===null?chunkPNDQRCRQ_cjs.P("SYMBOLIC_NONFINITE_OPERAND",e+" needs a value with an exact number."):_(chunk75XDS65A_cjs.s(e,[n]))}function ft(e,t){return e?.type!==3?chunkPNDQRCRQ_cjs.P("SYMBOLIC_REQUIRES_VARIABLE_NAME",`${t} needs the name of an unknown.`):e.value}function dt(e,t,n){let o=n*12,r=t/12,i=r===0?e/o:e*r/(1-Math.pow(1+r,-o)),a=i*o,u=a-e;return {monthlyPayment:i,totalRepayment:a,totalInterest:u}}var ja=Dn.pluginFunctions,qn=255,Yn=0;function Dr(){if(Yn>qn)throw chunkSOMGSIO4_cjs.c.config("PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED",`allocatePluginFunctionIndex: pool exhausted (max ${qn+1} allocations).`);return Yn++}var Gn=new Map;function Ka(e){let t=Gn.get(e);return t===void 0&&(t=Dr(),Gn.set(e,t)),t}var pt=new Map;function Xa(e,t){let n=e.toLowerCase(),o=pt.get(n);o&&o!==t&&console.warn(`[asConverterRegistry] Converter name "${n}" is already registered \u2014 overwriting.`),pt.set(n,t);}function Za(e){pt.delete(e.toLowerCase());}var qe=class qe{constructor(){this.values=new Map;this.listeners=new Set;this.notifyDepth=0;}get(t){return this.values.get(t)}has(t){return this.values.has(t)}set(t,n){let o=this.values.get(t);this.values.set(t,n),!(o!==void 0&&Cr(o,n))&&this.notify(t,n);}notify(t,n){if(!(this.notifyDepth>=qe.MAX_NOTIFY_DEPTH)){this.notifyDepth++;try{for(let o of this.listeners)o(t,n);}finally{this.notifyDepth--;}}}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t);}}clear(){this.values.clear(),this.listeners.clear(),this.notifyDepth=0;}};qe.MAX_NOTIFY_DEPTH=64;var bt=qe;function Cr(e,t){if(e.type!==t.type||e.unit!==t.unit||(e.timedOut??false)!==(t.timedOut??false))return false;let n=e.value,o=t.value;if(Array.isArray(n)||Array.isArray(o)){if(!Array.isArray(n)||!Array.isArray(o)||n.length!==o.length)return false;for(let r=0;r<n.length;r++)if(!Object.is(n[r],o[r]))return false;return true}return Object.is(n,o)}var Wa=new bt;function Qa(e){return `global:${e}`}exports.A=Ln;exports.B=va;exports.C=Ga;exports.D=ja;exports.E=Dr;exports.F=Ka;exports.G=pt;exports.H=Xa;exports.I=Za;exports.J=Wa;exports.K=Qa;exports.a=ge;exports.b=xn;exports.c=vn;exports.d=sn;exports.e=hi;exports.f=Ni;exports.g=gi;exports.h=Ri;exports.i=fn;exports.j=he;exports.k=Oi;exports.l=_i;exports.m=wi;exports.n=pn;exports.o=Di;exports.p=Ci;exports.q=et;exports.r=Pi;exports.s=Li;exports.t=Fi;exports.u=Ui;exports.v=Ne;exports.w=qi;exports.x=Er;exports.y=Dn;exports.z=Pn;//# sourceMappingURL=chunk-EURCQMZK.cjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-EURCQMZK.cjs.map
|
package/dist/chunk-FUDVKPB7.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
'use strict';var chunk4BZIYU7S_cjs=require('./chunk-4BZIYU7S.cjs'),chunkPNDQRCRQ_cjs=require('./chunk-PNDQRCRQ.cjs');var u=[10,11,12,13,14,16,60,61,62,63,150,159,95,96],E=[50,51,151,152,160],m=[157,158],L=(()=>{let r=new Array(256).fill(0);for(let e of u)r[e]=1;for(let e of E)r[e]=2;for(let e of m)r[e]=3;return r})();[...u,...E,...m];function C(r,e){return e+1+(L[r[e]]??0)}var R="currency",A=class{constructor(e){this.namespace=R;this.exchange=e??chunk4BZIYU7S_cjs.b;}preflight(e,N,U,S,y){let{opcodes:c,strings:l}=N,f=c.length,o=0,i=-1,p=-1;for(;o<f;){let t=c[o];if(t===13&&(p=i,i=c[o+1]),(t===84||t===81||t===20||t===21||t===22||t===23)&&p>=0&&i>=0){let n=l[p],s=l[i];if(this.exchange.isCurrency(n)&&this.exchange.isCurrency(s)&&n.toUpperCase()!==s.toUpperCase()&&this.exchange.getRateSync(n,s)===null){let d=n.toUpperCase(),I=s.toUpperCase(),a=[R,d,I];if(y.getQueryData(a)!==void 0){o++;continue}let g=y.fetchQuery({queryKey:a,queryFn:({signal:h})=>this.exchange.getRate(n,s,h).then(T=>chunkPNDQRCRQ_cjs.n(T)),staleTime:300*1e3});return {queryKey:a.join(":"),resolver:g,packageId:U,signal:S,metadata:{fromUnit:n,toUnit:s}}}}o=C(c,o);}return null}destroy(){}};exports.a=C;exports.b=A;//# sourceMappingURL=chunk-FUDVKPB7.cjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-FUDVKPB7.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/parser/OperandWidth.ts","../src/uom/CurrencyResolver.ts"],"names":["ONE_OPERAND","TWO_OPERANDS","THREE_OPERANDS","OPERAND_BYTES","widths","op","nextInstruction","opcodes","index","CURRENCY_NS","CurrencyAsyncResolver","exchange","currencyExchangeService","_tokens","bytecode","packageId","signal","queryClient","strings","len","i","lastStrIdx","prevStrIdx","fromUnit","toUnit","fromUpper","toUpper","cacheKey","resolver","qSignal","rate","numberValue"],"mappings":"qHAwBA,IAAMA,CAAAA,CAAiC,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,EAAA,CAAA,GAAA,CAAA,GAAA,CAAA,EAAA,CAAA,EAwBvC,CAAA,CAOMC,CAAAA,CAAkC,CAAA,EAAA,CAAA,EAAA,CAAA,GAAA,CAAA,GAAA,CAAA,GAOxC,CAAA,CAQMC,CAAAA,CAAoC,CAAA,GAAA,CAAA,GAAwC,CAAA,CAQrEC,CAAAA,CAAAA,CAAoC,IAAM,CACtD,IAAMC,CAAAA,CAAS,IAAI,KAAA,CAAc,GAAG,CAAA,CAAE,IAAA,CAAK,CAAC,CAAA,CAC5C,IAAA,IAAWC,CAA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,CAAAA,CAAW,MAAA,CAAAC,CAAAA,CAAQ,QAAA,CAAU,CAAE,SAAAO,CAAAA,CAAU,MAAA,CAAAC,CAAO,CAAE,CACpG,CAEF,CAKDJ,CAAAA,CAAId,EAAgBC,CAAAA,CAASa,CAAC,EAC/B,CAEA,OAAO,IACR,CAEA,OAAA,EAAgB,CAEhB,CACD","file":"chunk-FUDVKPB7.cjs","sourcesContent":["/**\n * How many operand bytes follow each opcode, and how to step over one.\n *\n * Anything walking a bytecode stream without executing it needs this: the\n * resolver preflight scanners look for specific opcodes and must skip past\n * everything else without mistaking an operand byte for an instruction.\n *\n * It used to be a hand-copied switch in each of those scanners. They had\n * already drifted: two counted `CALL_PLUGIN` as three bytes wide and the third\n * omitted it from that arm, so a stream containing one desynchronised there and\n * every opcode after it was read at the wrong offset. Adding an opcode meant\n * remembering every copy, and nothing checked that you had.\n *\n * `__tests__/parser/OperandWidth.spec.ts` asserts every opcode has a width, so\n * a new one fails a test rather than silently defaulting to zero operands.\n */\n\nimport { OpCode } from \"@solve-js/parser/OpCode\";\n\n/**\n * Opcodes taking one operand byte.\n *\n * A constant-pool index, or a variable-name index.\n */\nconst ONE_OPERAND: readonly OpCode[] = [\n\tOpCode.PUSH_NUMBER,\n\tOpCode.PUSH_BIGINT,\n\tOpCode.PUSH_HEX,\n\tOpCode.PUSH_STRING,\n\tOpCode.PUSH_BOOLEAN,\n\t// Its operand is a string-pool index holding the exact decimal text, so a\n\t// scanner must step over one byte exactly as it does for PUSH_STRING.\n\tOpCode.PUSH_DECIMAL,\n\tOpCode.LOAD_VAR,\n\tOpCode.STORE_VAR,\n\tOpCode.LOAD_GLOBAL_VAR,\n\tOpCode.STORE_GLOBAL_VAR,\n\tOpCode.DEFINE_USER_FUNCTION,\n\tOpCode.BIND_UNKNOWN,\n\t// Its operand is a constant-pool index, like PUSH_NUMBER's: the epoch-ms\n\t// was resolved at parse time and stored in `numbers`. Omitting it made\n\t// every scanner read that index byte as an opcode, so an ordinary date\n\t// literal desynchronised the whole preflight walk.\n\tOpCode.DATE_LITERAL,\n\t// One byte, the offset direction (0 forward, 1 backward) for \"N working\n\t// days after/before/from <date>\". See WorkdayOffsetParselet. DATE_WORKDAYS_BETWEEN\n\t// takes no operand and so is not listed here.\n\tOpCode.DATE_WORKDAY_OFFSET,\n];\n\n/**\n * Opcodes taking two operand bytes.\n *\n * A callable index plus an argument count, or a matrix's row and column counts.\n */\nconst TWO_OPERANDS: readonly OpCode[] = [\n\tOpCode.CALL_PLUGIN,\n\tOpCode.CALL_BUILTIN,\n\tOpCode.CALL_USER_FUNCTION,\n\tOpCode.MAT_NEW,\n\t// A body index plus the pooled source-expression string.\n\tOpCode.PLOT_INVOKE,\n];\n\n/**\n * Opcodes taking three operand bytes.\n *\n * The map and reduce invocations, which carry a body index alongside their\n * other operands.\n */\nconst THREE_OPERANDS: readonly OpCode[] = [OpCode.MAP_INVOKE, OpCode.REDUCE_INVOKE];\n\n/**\n * Operand byte count for every opcode, indexed by opcode value.\n *\n * A dense array rather than a map, because the preflight scanners run on every\n * keystroke and this is read once per instruction.\n */\nexport const OPERAND_BYTES: readonly number[] = (() => {\n\tconst widths = new Array<number>(256).fill(0);\n\tfor (const op of ONE_OPERAND) widths[op] = 1;\n\tfor (const op of TWO_OPERANDS) widths[op] = 2;\n\tfor (const op of THREE_OPERANDS) widths[op] = 3;\n\treturn widths;\n})();\n\n/**\n * Every opcode that takes at least one operand.\n *\n * Exported so a test can assert the table stays complete as opcodes are added.\n */\nexport const OPCODES_WITH_OPERANDS: readonly OpCode[] = [\n\t...ONE_OPERAND,\n\t...TWO_OPERANDS,\n\t...THREE_OPERANDS,\n];\n\n/**\n * Offset of the instruction after the one at `index`.\n *\n * @param opcodes - The bytecode stream.\n * @param index - Offset of an opcode, not of an operand byte. Passing an\n * operand offset yields nonsense, which is the failure mode this exists to\n * prevent: a caller stepping by hand and getting one width wrong reads the rest\n * of the stream misaligned.\n * @returns Offset of the next opcode. May be past the end when the instruction\n * at `index` is the last one, so callers loop while it is under `opcodes.length`.\n */\nexport function nextInstruction(opcodes: Uint8Array, index: number): number {\n\treturn index + 1 + (OPERAND_BYTES[opcodes[index]] ?? 0);\n}\n","/**\n * Currency async resolver, bridges CurrencyExchangeService to the\n * IAsyncResolver interface for the Suspense architecture.\n *\n * Uses TanStack Query (injected via queryClient) as the single cache layer.\n */\nimport type { QueryClient } from \"@tanstack/query-core\";\nimport type { Token } from \"@solve-js/lexer\";\nimport type { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { numberValue } from \"@solve-js/vm/Value\";\nimport {\n\tcurrencyExchangeService,\n\tCurrencyExchangeService,\n} from \"@solve-js/uom/CurrencyExchange\";\nimport type { IAsyncResolver, AsyncCheckResult } from \"@solve-js/resolvers/ResolverRegistry\";\nimport { nextInstruction } from \"@solve-js/parser/OperandWidth\";\n\nconst CURRENCY_NS = \"currency\";\n\n/**\n * Fetches exchange rates before the VM runs, so a conversion has real numbers.\n *\n * Until rates arrive the line evaluates to a pending value rather than a\n * guessed one, and re-evaluates when they land.\n */\nexport class CurrencyAsyncResolver implements IAsyncResolver {\n\treadonly namespace = CURRENCY_NS;\n\n\tprivate exchange: CurrencyExchangeService;\n\n\tconstructor(exchange?: CurrencyExchangeService) {\n\t\tthis.exchange = exchange ?? currencyExchangeService;\n\t}\n\n\tpreflight(_tokens: Token[], bytecode: BytecodeProgram, packageId: string, signal: AbortSignal, queryClient: QueryClient): AsyncCheckResult | null {\n\t\tconst { opcodes, strings } = bytecode;\n\t\tconst len = opcodes.length;\n\t\tlet i = 0;\n\n\t\tlet lastStrIdx = -1;\n\t\tlet prevStrIdx = -1;\n\n\t\twhile (i < len) {\n\t\t\tconst op = opcodes[i] as OpCode;\n\n\t\t\tif (op === OpCode.PUSH_STRING) {\n\t\t\t\tprevStrIdx = lastStrIdx;\n\t\t\t\tlastStrIdx = opcodes[i + 1];\n\t\t\t}\n\n\t\t\t// Explicit \"X to Y\"/\"X in Y\" conversions (UOM_CONVERT_IN/_TO) are\n\t\t\t// the obvious case, but arithmetic directly on two differently-\n\t\t\t// denominated currency literals, \"0.01 BTC + 1 ETH\", needs the\n\t\t\t// exact same preflight fetch and previously never got it: this\n\t\t\t// scanner only looked for the CONVERT opcodes, so ADD/SUB/MUL/DIV\n\t\t\t// between two currency UOMs skipped preflight entirely, ran with\n\t\t\t// no cached rate, and fell through to the VM's silent-wrong-math\n\t\t\t// fallback instead of ever reaching a network fetch.\n\t\t\tconst isCurrencyCombiningOp =\n\t\t\t\top === OpCode.UOM_CONVERT_IN || op === OpCode.UOM_CONVERT_TO ||\n\t\t\t\top === OpCode.ADD || op === OpCode.SUB || op === OpCode.MUL || op === OpCode.DIV;\n\t\t\tif (isCurrencyCombiningOp) {\n\t\t\t\tif (prevStrIdx >= 0 && lastStrIdx >= 0) {\n\t\t\t\t\tconst fromUnit = strings[prevStrIdx];\n\t\t\t\t\tconst toUnit = strings[lastStrIdx];\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tthis.exchange.isCurrency(fromUnit) &&\n\t\t\t\t\t\tthis.exchange.isCurrency(toUnit) &&\n\t\t\t\t\t\tfromUnit.toUpperCase() !== toUnit.toUpperCase()\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst syncRate = this.exchange.getRateSync(fromUnit, toUnit);\n\t\t\t\t\t\tif (syncRate === null) {\n\t\t\t\t\t\t\tconst fromUpper = fromUnit.toUpperCase();\n\t\t\t\t\t\t\tconst toUpper = toUnit.toUpperCase();\n\n\t\t\t\t\t\t\t// Check TanStack Query cache\n\t\t\t\t\t\t\tconst cacheKey = [CURRENCY_NS, fromUpper, toUpper];\n\t\t\t\t\t\t\tif (queryClient.getQueryData(cacheKey) !== undefined) {\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Fetch via TanStack Query (dedup + retry automatic)\n\t\t\t\t\t\t\tconst resolver = queryClient.fetchQuery({\n\t\t\t\t\t\t\t\tqueryKey: cacheKey,\n\t\t\t\t\t\t\t\tqueryFn: ({ signal: qSignal }) => {\n\t\t\t\t\t\t\t\t\treturn this.exchange.getRate(fromUnit, toUnit, qSignal).then((rate) => numberValue(rate));\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tstaleTime: 5 * 60 * 1000,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\treturn { queryKey: cacheKey.join(\":\"), resolver, packageId, signal, metadata: { fromUnit, toUnit } };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Step over this instruction and its operands. Shared table, because\n\t\t\t// three hand-copied versions of this had already drifted.\n\t\t\ti = nextInstruction(opcodes, i);\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tdestroy(): void {\n\t\t// Cache cleared by ResolverRegistry.unregister() via removeQueries({ queryKey: [\"currency\"] })\n\t}\n}\n"]}
|