solve-engine 2.6.0 → 2.8.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/{PackageCompatibility-CCdud__Q.d.cts → PackageCompatibility-BG0iur4I.d.cts} +1 -1
- package/dist/{PackageCompatibility-4QtIErfx.d.ts → PackageCompatibility-BlIcQg5v.d.ts} +1 -1
- package/dist/{PackageRegistry-B7wkfSrY.d.ts → PackageRegistry-BJ0QQd3k.d.ts} +4 -4
- package/dist/{PackageRegistry-Hx85XD01.d.cts → PackageRegistry-DeGDZkNt.d.cts} +4 -4
- package/dist/{Parselet-CTNpfuEB.d.cts → Parselet-BSndkWEY.d.cts} +1 -1
- package/dist/{Parselet-DONNUpur.d.ts → Parselet-Blq8B0Gj.d.ts} +1 -1
- package/dist/{ScopeManager-BkbDXK_R.d.ts → ScopeManager-CF3cZUqW.d.ts} +2 -2
- package/dist/{ScopeManager-Cvgypcu4.d.cts → ScopeManager-D8nLv--u.d.cts} +2 -2
- package/dist/{VMCheckpoints-9zBQnTsN.d.ts → VMCheckpoints-BsR5_auF.d.ts} +2 -2
- package/dist/{VMCheckpoints-CBMGiSqw.d.cts → VMCheckpoints-Dy39SVHa.d.cts} +2 -2
- package/dist/{Value-D1XlMwe2.d.cts → Value-DCTqTSeP.d.cts} +22 -5
- package/dist/{Value-D1XlMwe2.d.ts → Value-DCTqTSeP.d.ts} +22 -5
- package/dist/{chunk-T52Y5G24.js → chunk-2V44X7GH.js} +4 -4
- package/dist/{chunk-T52Y5G24.js.map → chunk-2V44X7GH.js.map} +1 -1
- package/dist/{chunk-5FO4PDIG.js → chunk-3GAWAMT4.js} +2 -2
- package/dist/{chunk-5FO4PDIG.js.map → chunk-3GAWAMT4.js.map} +1 -1
- package/dist/{chunk-32GC2FHC.cjs → chunk-3HYO3QYW.cjs} +2 -2
- package/dist/{chunk-32GC2FHC.cjs.map → chunk-3HYO3QYW.cjs.map} +1 -1
- package/dist/{chunk-2JMFUQZH.js → chunk-44EOEWGP.js} +2 -2
- package/dist/chunk-44EOEWGP.js.map +1 -0
- package/dist/chunk-5TCSFTZD.js +2 -0
- package/dist/chunk-5TCSFTZD.js.map +1 -0
- package/dist/chunk-5TVI2UPZ.cjs +2 -0
- package/dist/chunk-5TVI2UPZ.cjs.map +1 -0
- package/dist/{chunk-CIQOK7Q4.cjs → chunk-6QRHN3I6.cjs} +2 -2
- package/dist/chunk-6QRHN3I6.cjs.map +1 -0
- package/dist/chunk-6TPXH6Y5.cjs +3 -0
- package/dist/chunk-6TPXH6Y5.cjs.map +1 -0
- package/dist/{chunk-ZOOVGXMK.cjs → chunk-75XDS65A.cjs} +2 -2
- package/dist/{chunk-ZOOVGXMK.cjs.map → chunk-75XDS65A.cjs.map} +1 -1
- package/dist/chunk-A33K7NY4.js +2 -0
- package/dist/chunk-A33K7NY4.js.map +1 -0
- package/dist/chunk-BKSKZA4W.cjs +2 -0
- package/dist/chunk-BKSKZA4W.cjs.map +1 -0
- package/dist/{chunk-VAGS5JS7.cjs → chunk-C65UDMWH.cjs} +2 -2
- package/dist/{chunk-VAGS5JS7.cjs.map → chunk-C65UDMWH.cjs.map} +1 -1
- package/dist/{chunk-OVQ3V4CG.cjs → chunk-CIENDLKV.cjs} +2 -2
- package/dist/{chunk-OVQ3V4CG.cjs.map → chunk-CIENDLKV.cjs.map} +1 -1
- package/dist/chunk-DLAKPF5T.js +2 -0
- package/dist/chunk-DLAKPF5T.js.map +1 -0
- package/dist/chunk-EOMHELRL.js +2 -0
- package/dist/chunk-EOMHELRL.js.map +1 -0
- package/dist/chunk-EURCQMZK.cjs +2 -0
- package/dist/{chunk-Z5KBBQOJ.cjs.map → chunk-EURCQMZK.cjs.map} +1 -1
- package/dist/{chunk-HOQU47MF.cjs → chunk-FNNIAJNY.cjs} +2 -2
- package/dist/{chunk-HOQU47MF.cjs.map → chunk-FNNIAJNY.cjs.map} +1 -1
- package/dist/{chunk-3AVWA5IZ.cjs → chunk-FUDVKPB7.cjs} +2 -2
- package/dist/{chunk-3AVWA5IZ.cjs.map → chunk-FUDVKPB7.cjs.map} +1 -1
- package/dist/{chunk-4XTD4B77.js → chunk-GAAXTO4K.js} +3 -3
- package/dist/{chunk-4XTD4B77.js.map → chunk-GAAXTO4K.js.map} +1 -1
- package/dist/{chunk-G7TBEQRQ.js → chunk-GMSBBLUQ.js} +2 -2
- package/dist/{chunk-G7TBEQRQ.js.map → chunk-GMSBBLUQ.js.map} +1 -1
- package/dist/chunk-HDVZZ7JN.js +3 -0
- package/dist/chunk-HDVZZ7JN.js.map +1 -0
- package/dist/{chunk-SWKYVSMP.js → chunk-JEFMG6CV.js} +2 -2
- package/dist/{chunk-SWKYVSMP.js.map → chunk-JEFMG6CV.js.map} +1 -1
- package/dist/{chunk-P6BLASAA.js → chunk-JQBG3LX4.js} +2 -2
- package/dist/{chunk-P6BLASAA.js.map → chunk-JQBG3LX4.js.map} +1 -1
- package/dist/{chunk-GHW2X7PS.js → chunk-KHCNMNZZ.js} +2 -2
- package/dist/{chunk-GHW2X7PS.js.map → chunk-KHCNMNZZ.js.map} +1 -1
- package/dist/chunk-LH7URJZT.js +3 -0
- package/dist/chunk-LH7URJZT.js.map +1 -0
- package/dist/{chunk-R7T3NGUE.cjs → chunk-MVP2YD4X.cjs} +2 -2
- package/dist/{chunk-R7T3NGUE.cjs.map → chunk-MVP2YD4X.cjs.map} +1 -1
- package/dist/{chunk-KSDTVFXA.cjs → chunk-OZ6SKIPD.cjs} +4 -4
- package/dist/{chunk-KSDTVFXA.cjs.map → chunk-OZ6SKIPD.cjs.map} +1 -1
- package/dist/chunk-PNDQRCRQ.cjs +2 -0
- package/dist/chunk-PNDQRCRQ.cjs.map +1 -0
- package/dist/{chunk-YAHGSBMC.js → chunk-QYO7IEPR.js} +2 -2
- package/dist/{chunk-YAHGSBMC.js.map → chunk-QYO7IEPR.js.map} +1 -1
- package/dist/{chunk-2LFLR3VZ.cjs → chunk-SNVPM27Q.cjs} +2 -2
- package/dist/{chunk-2LFLR3VZ.cjs.map → chunk-SNVPM27Q.cjs.map} +1 -1
- package/dist/{chunk-AR7L5OJ2.js → chunk-T3FBAFRR.js} +2 -2
- package/dist/{chunk-AR7L5OJ2.js.map → chunk-T3FBAFRR.js.map} +1 -1
- package/dist/chunk-TUBLMUTZ.cjs +2 -0
- package/dist/chunk-TUBLMUTZ.cjs.map +1 -0
- package/dist/chunk-U47GA63S.cjs +3 -0
- package/dist/chunk-U47GA63S.cjs.map +1 -0
- package/dist/{chunk-HMEZJXLX.js → chunk-UKDUFMT5.js} +2 -2
- package/dist/{chunk-HMEZJXLX.js.map → chunk-UKDUFMT5.js.map} +1 -1
- package/dist/chunk-UWAXJX5G.js +2 -0
- package/dist/chunk-UWAXJX5G.js.map +1 -0
- package/dist/chunk-WEAKI5V5.cjs +2 -0
- package/dist/chunk-WEAKI5V5.cjs.map +1 -0
- package/dist/{chunk-VYWGUMFW.js → chunk-WTEXBPBR.js} +2 -2
- package/dist/{chunk-VYWGUMFW.js.map → chunk-WTEXBPBR.js.map} +1 -1
- package/dist/{chunk-NXIMGB4S.cjs → chunk-WYIOXAFW.cjs} +2 -2
- package/dist/{chunk-NXIMGB4S.cjs.map → chunk-WYIOXAFW.cjs.map} +1 -1
- package/dist/{chunk-B4P4M4ZW.cjs → chunk-YORX7723.cjs} +3 -3
- package/dist/{chunk-B4P4M4ZW.cjs.map → chunk-YORX7723.cjs.map} +1 -1
- package/dist/chunk-YTCTUBR2.js +2 -0
- package/dist/{chunk-XTM4HTRB.js.map → chunk-YTCTUBR2.js.map} +1 -1
- package/dist/constants.cjs +1 -1
- package/dist/constants.js +1 -1
- package/dist/engine.cjs +1 -1
- package/dist/engine.d.cts +7 -7
- package/dist/engine.d.ts +7 -7
- package/dist/engine.js +1 -1
- package/dist/format.cjs +1 -1
- package/dist/format.d.cts +1 -1
- package/dist/format.d.ts +1 -1
- package/dist/format.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +7 -7
- package/dist/index.d.ts +7 -7
- package/dist/index.js +1 -1
- package/dist/language.cjs +1 -1
- package/dist/language.d.cts +6 -6
- package/dist/language.d.ts +6 -6
- package/dist/language.js +1 -1
- package/dist/lexer.cjs +1 -1
- package/dist/lexer.js +1 -1
- package/dist/normalizer.cjs +1 -1
- package/dist/normalizer.js +1 -1
- package/dist/packages.cjs +1 -1
- package/dist/packages.d.cts +6 -6
- package/dist/packages.d.ts +6 -6
- 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-DY0rhgQG.d.cts → pipeline-BM8xc0CZ.d.cts} +3 -3
- package/dist/{pipeline-BH7BFOTJ.d.ts → pipeline-J2ehIm7t.d.ts} +3 -3
- 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 +6 -6
- package/dist/testing.d.ts +6 -6
- 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 +6 -6
- package/dist/vm.d.ts +6 -6
- package/dist/vm.js +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +15 -5
- package/dist/worker.d.ts +15 -5
- package/dist/worker.js +2 -2
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-2JMFUQZH.js.map +0 -1
- package/dist/chunk-3DD2RVBI.cjs +0 -3
- package/dist/chunk-3DD2RVBI.cjs.map +0 -1
- package/dist/chunk-5FGOIDLS.cjs +0 -2
- package/dist/chunk-5FGOIDLS.cjs.map +0 -1
- package/dist/chunk-5OIXCVB2.js +0 -3
- package/dist/chunk-5OIXCVB2.js.map +0 -1
- package/dist/chunk-CIQOK7Q4.cjs.map +0 -1
- package/dist/chunk-ESUN2THE.cjs +0 -2
- package/dist/chunk-ESUN2THE.cjs.map +0 -1
- package/dist/chunk-FWW3M36J.cjs +0 -2
- package/dist/chunk-FWW3M36J.cjs.map +0 -1
- package/dist/chunk-GKDZ7TSX.cjs +0 -2
- package/dist/chunk-GKDZ7TSX.cjs.map +0 -1
- package/dist/chunk-IANAMBJQ.cjs +0 -2
- package/dist/chunk-IANAMBJQ.cjs.map +0 -1
- package/dist/chunk-IO374J6Z.js +0 -2
- package/dist/chunk-IO374J6Z.js.map +0 -1
- package/dist/chunk-R2ENWQ76.js +0 -2
- package/dist/chunk-R2ENWQ76.js.map +0 -1
- package/dist/chunk-SOSUS2SK.cjs +0 -3
- package/dist/chunk-SOSUS2SK.cjs.map +0 -1
- package/dist/chunk-T4Y5XOT2.js +0 -3
- package/dist/chunk-T4Y5XOT2.js.map +0 -1
- package/dist/chunk-TRBXW6HW.js +0 -2
- package/dist/chunk-TRBXW6HW.js.map +0 -1
- package/dist/chunk-WGZ3FNHI.js +0 -2
- package/dist/chunk-WGZ3FNHI.js.map +0 -1
- package/dist/chunk-XTM4HTRB.js +0 -2
- package/dist/chunk-Z5KBBQOJ.cjs +0 -2
- package/dist/chunk-ZJPAPBP3.js +0 -2
- package/dist/chunk-ZJPAPBP3.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/symbolic/MultivariateFactor.ts","../src/symbolic/Factor.ts","../src/symbolic/CubicQuartic.ts","../src/symbolic/NumericRoots.ts","../src/symbolic/Solve.ts","../src/vm/SymbolicOps.ts","../src/vm/VMConversion.ts","../src/vm/OpRegistry.ts","../src/vm/MoneyExact.ts","../src/symbolic/PartialFractions.ts","../src/symbolic/Derivative.ts","../src/symbolic/Integral.ts","../src/symbolic/Taylor.ts","../src/engine/EngineContext.ts","../src/packages/finance/data/CpiTable.ts","../src/vm/VMBuiltins.ts","../src/vm/GlobalVariableStore.ts"],"names":["exactRoot","value","degree","rootOf","exactIntegerSqrt","exactIntegerCbrt","numerator","denominator","monomialRoot","key","monomial","monomialFromKey","root","name","exponent","monomialToKey","monomialMul","a","b","product","monomialDiv","quotient","remaining","monomialGcd","left","shared","other","namesOf","keys","names","termsToNode","terms","map","term","fromPolynomial","factors","result","i","orderedTerms","p","coefficient","compareMonomials","factorMultivariate","factorBinomial","factorPerfectSquare","factorByGrouping","first","second","firstPositive","secondPositive","squares","asPowerPair","negated","cubes","linear","middle","multiplyTerms","squareOf","magnitude","rationalNeg","firstRoot","secondRoot","firstKey","secondKey","rationalMul","last","roots","cross","twice","negative","isRationalOne","rationalDiv","constNode","pairings","pairing","splitPair","cofactorsAgree","common","cofactor","index","FACTOR_MAX_DEGREE","FACTOR_MAX_ROOT_CANDIDATES","gcd","x","y","remainder","lcm","divisors","found","candidate","paired","evaluateAt","descending","total","RATIONAL_ZERO","coeff","rationalAdd","divideByRoot","rationalRoots","multiplier","integers","leading","trailing","numeratorDivisors","denominatorDivisors","ErrorFactory","seen","q","sign","isRationalZero","linearFactorNode","variable","varNode","coefficientsToNode","power","factorUnivariate","multiplicity","RATIONAL_ONE","factorizationToNode","factorization","pieces","factor","powNode","contentOf","numeratorGcd","denominatorLcm","extractCommonMonomial","lowest","exponentOf","exponents","parseKey","buildKey","caret","monomialNode","factorSymbolic","node","polynomial","toPolynomial","polyDegree","content","primitive","scaleTerms","reduced","monomialFactor","polyUnivariateVar","patterned","assemble","buildPieces","polyCoefficients","combinedContent","k","factored","TWO","THREE","FOUR","depressCubic","c","d","shift","rationalSub","twoBCubed","nineABC","twentySevenAAD","solveCubic","discriminant","rationalCompare","trigonometricRoots","repeatedCubicRoots","cardanoRoots","simple","repeated","half","radicand","inner","surdNode","u","v","sum","difference","real","imaginary","complexNode","COMPLEX_I","pNumber","rationalToNumber","qNumber","shiftNumber","ratio","angle","right","depressQuartic","e","bb","r","solveQuartic","solveQuadratic","monic","biquadraticRoots","splitQuarticRoots","shifted","distinct","unique","symbolicKey","simplifySymbolic","complexBiquadraticRoots","exactRationalSqrt","rationalSquareRoots","nestedSquareRoots","negatedP","values","square","signedSurdNode","surd","negativeP","solutions","halved","positive","centre","modulus","re","nestedSurd","im","offset","resolvent","z","alpha","beta","gamma","one","DURAND_KERNER_MAX_ITERATIONS","DURAND_KERNER_TOLERANCE","ROOT_RESIDUAL_TOLERANCE","ROOT_SEPARATION_TOLERANCE","AXIS_SNAP_TOLERANCE","CONJUGATE_PAIR_TOLERANCE","NEWTON_POLISH_STEPS","subtract","multiply","divide","nextRe","evaluationScale","radius","differentiate","derivative","squareFreeDoubles","ascending","doubles","squareFreePart","initialEstimates","largest","estimates","durandKerner","iteration","largestStep","largestRoot","j","step","polish","start","slope","next","snapToAxes","scale","isRootWithinTolerance","pairConjugates","wanted","partner","closest","distance","allSeparated","approximateRoots","converged","SOLVE_MAX_DEGREE","evaluateRational","rational4","twoA","rational2","complexQuadraticRoots","rootN","rootD","plus","minus","lower","upper","negatedB","complex","scaledRadicand","realApproximation","solveForVariable","lhs","rhs","others","solveLinearWithOtherUnknowns","solveUnivariate","coefficientTerms","constantTerms","part","closedFormRoots","extractRationalRoots","powersOfX","exact","approximate","leftoverDegree","solvedDegree","finish","closedForm","numeric","unsolvedDegree","reason","incoherent","SYMBOLIC_BUILTIN_NAMES","POW_BUILTIN_INDEX","SYMBOLIC_NATIVE_BUILTINS","valueToSymbolic","rationalFromNumber","symbolicToValue","simplified","numberValue","symbolicValue","unsupported","what","errorValue","symbolicPow","l","base","symbolicNeg","operand","symbolicBuiltin","args","nodes","arg","faulted","faultedOperand","callNode","rootToValue","approximateRootToValue","solveOutcomeToValue","outcome","stringValue","matrixValue","solveEquationValues","lhsValue","rhsValue","unifyUom","lMeasure","getMeasure","rMeasure","isCurrency","sharedCurrencyExchange","rvConverted","convertUnit","UNIFIED_COMPARISON_TOLERANCE","largestFiniteMagnitude","compareUom","lv","rv","sameMeasure","decimalCompare","MEASURE_NOUNS","UNCOUNTABLE_MEASURES","COMBINE_VERBS","describeMeasure","unit","measure","withMeasureArticle","noun","describeMeasureMismatch","lUnit","rUnit","verb","combineVerb","op","describeConversionMismatch","fromUnit","toUnit","from","to","incomparableUnitsError","named","toBigIntOperand","n","shown","bigIntDivisionByZero","compareBigIntOperands","lb","exactBigInt","rb","operandExactDecimal","decimalFromNumberIfExact","exactMoneyOp","lMoney","rMoney","ld","rd","decimalAdd","decimalSubtract","decimalMultiply","decimalIsZero","decimalDivide","uomValueExact","decimalToNumber","operandRational","rational","exactRationalOp","lr","rr","numberValueRational","uncertainOp","sa","sb","center","sigma","numberValueUncertain","compareRationalOperands","binaryOp","bigOp","symbolicOp","bigIntValue","exactMoney","uomValue","lm","rm","sameShape","scalar","MAX_OPCODE","DYNAMIC_OPCODE_START","OpRegistry","registration","opcode","sharedOpRegistry","ONE_DECIMAL","decimalFromInteger","moneyExactMagnitude","decimalFromShortDecimal","s","decimalFromLiteral","scaleMoneyExact","amount","factorDecimal","scaleMoneyByPercent","money","percent","percentDecimal","decimalNegate","onePlusRateDecimal","rate","rateDecimal","removeTaxExact","divisor","taxInExact","tax","splitEachExact","cents","centsOfMoney","baseCents","extraShares","centShare","count","makeDecimal","decimalRound","APART_MAX_DEGREE","coefficients","denominatorFactors","enumerateUnknowns","unknowns","factorDegree","unknownColumn","unknown","polynomialDivide","isZeroPolynomial","solveLinearSystem","matrix","target","size","column","pivot","row","partialFractions","coefficientGcd","reducedNumerator","reducedDenominator","monicDenominator","scaledNumerator","solveForNumerators","columns","solution","groupSolution","grouped","existing","factorIndex","termPower","filled","apartSymbolic","parts","asRationalFunction","decomposition","isNegativeNumerator","piece","DERIVATIVE_MAX_ORDER","zero","functionDerivative","argument","oneMinusSquare","onePlusSquare","order","derive","derivePow","unevaluated","outer","asLinear","intercept","integratePolynomial","nextPower","scaled","integrateStandardForm","divideBySlope","integrateReciprocalForms","isRationalOneNode","integrateRationalFunction","polynomialAntiderivative","integrateTerm","baseDegree","integrateQuadraticTerm","constant","halfP","logarithm","leftover","width","arctangent","integrate","freeVariables","standard","reciprocal","rationalFunction","TAYLOR_MAX_DEGREE","taylorSeries","point","pointNode","factorial","atPoint","substitute","jacobian","functions","variables","fn","createEngineContext","defaultEngineContext","CPI_TABLE","CPI_MIN_YEAR","CPI_MAX_YEAR","getCpi","year","inflationRatio","fromYear","toYear","fromCpi","toCpi","adjustForInflation","ANGLE_KIND","angleInRadians","entry","UNIT_TABLE","pluraliseUnit","plural","extremum","wantLargest","best","hasNaN","bestUnit","otherUnit","keepUnit","roundToPlaces","source","places","rounded","withPlaces","nonFiniteEuclidOperand","culprit","euclidGcd","t","sumOfSquares","nums","mean","acc","variance","sample","denom","builtinFunctions","determinant","matrixPower","nonFinite","sorted","mid","aNum","bNum","lo","hi","hexValue","principal","years","fv","interest","futureValue","periodsPerYear","totalRepayment","amortizeLoan","totalInterest","monthlyPayment","transpose","inverse","toMatrix","matrixMultiply","expandSymbolic","variableValue","orderValue","symbolicVariableName","expression","pointValue","degreeValue","rows","rowMajor","cell","symbolicToEntry","rowMajorToColumnMajor","applyComplexAccessor","cancelSymbolic","major","minor","majorEntry","minorEntry","sourceEntry","inBase","majorCount","minorCount","slash","leftUnit","denominatorEntry","leftEntry","perYear","future","pv","invested","returned","percentageValue","splitValue","months","monthsOfDuration","annualRate","payment","annuityPayment","contribution","periods","annuityPeriods","counts","bestCount","weightedSum","weightTotal","weight","duration","raw","rMonthly","pluginFunctionRegistry","MAX_PLUGIN_FUNCTION_INDEX","nextPluginFunctionIndex","allocatePluginFunctionIndex","pluginFunctionIndexByQualifiedName","pluginFunctionIndexFor","qualifiedName","asConverterRegistry","registerAsConverter","handler","unregisterAsConverter","_GlobalVariableStore","previous","sameValue","listener","GlobalVariableStore","av","bv","sharedGlobalVariableStore","globalDagKey"],"mappings":"gkBAmDA,SAASA,EAAAA,CAAUC,CAAAA,CAAiBC,CAAAA,CAAgC,CACnE,IAAMC,CAAAA,CAASD,CAAAA,GAAW,CAAA,CAAIE,CAAAA,CAAmBC,GAAAA,CAC3CC,CAA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A,CAAE,QAAA,EAAY,KAAA,KAAYC,CAAAA,CAAE,QAAA,EAAY,KAAA,CAAA,CAAQ,OAAO,MAAA,CAE5D,IAAMmpB,CAAAA,CAAKppB,CAAAA,CAAE,KAAA,CACPqpB,CAAAA,CAAKppB,CAAAA,CAAE,KAAA,CACb,GAAI,KAAA,CAAM,OAAA,CAAQmpB,CAAE,CAAA,EAAK,KAAA,CAAM,OAAA,CAAQC,CAAE,EAAG,CAE3C,GADI,CAAC,KAAA,CAAM,OAAA,CAAQD,CAAE,CAAA,EAAK,CAAC,KAAA,CAAM,OAAA,CAAQC,CAAE,CAAA,EACvCD,CAAAA,CAAG,MAAA,GAAWC,CAAAA,CAAG,MAAA,CAAQ,OAAO,MAAA,CACpC,IAAA,IAASjoB,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIgoB,CAAAA,CAAG,MAAA,CAAQhoB,CAAAA,EAAAA,CAC9B,GAAI,CAAC,MAAA,CAAO,EAAA,CAAGgoB,CAAAA,CAAGhoB,CAAC,CAAA,CAAGioB,CAAAA,CAAGjoB,CAAC,CAAC,CAAA,CAAG,OAAO,MAAA,CAEtC,OAAO,KACR,CACA,OAAO,MAAA,CAAO,EAAA,CAAGgoB,CAAAA,CAAIC,CAAE,CACxB,CAMO,IAAMC,EAAAA,CAA4B,IAAIH,GAYtC,SAASI,EAAAA,CAAa3pB,CAAAA,CAAsB,CAClD,OAAO,CAAA,OAAA,EAAUA,CAAI,CAAA,CACtB","file":"chunk-XTM4HTRB.js","sourcesContent":["/**\n * Factoring polynomials in more than one variable.\n *\n * `Factor.ts` handles one variable completely, by the rational-root theorem,\n * and stops at content and common-monomial extraction the moment a second\n * variable appears. That stop is principled, because multivariate factoring in\n * general is a much harder problem than the univariate case and the honest\n * options are a real algorithm or none. What it left out, though, is the handful\n * of shapes a person actually writes: `x^2-y^2`, `x^3+y^3`, `x^2+2xy+y^2`, and\n * `ax+ay+bx+by`.\n *\n * So this is patterns, not an algorithm, and it says so. Each one is recognised\n * exactly, over exact coefficients, and produces a factorization that multiplies\n * back to the input. Anything not matching a pattern is declined, which leaves\n * the caller exactly where it was before.\n *\n * ## What it does not do\n *\n * It does not recurse. `x^6-y^6` is both a difference of squares and a\n * difference of cubes; the squares pattern matches first and gives\n * `(x^3-y^3)(x^3+y^3)`, which is correct and not fully factored. Recursing would\n * mean calling back into `Factor.ts`, which calls this, and the extra\n * factorization is not worth a circular dependency between the two.\n */\n\nimport { type SymbolicNode, constNode } from \"@solve-js/symbolic/SymbolicNode\";\nimport {\n\ttype Rational,\n\trationalMul,\n\trationalDiv,\n\trationalNeg,\n\tisRationalOne,\n} from \"@solve-js/symbolic/Rational\";\nimport {\n\ttype Polynomial,\n\ttype MonomialKey,\n\ttype Monomial,\n\tmonomialToKey,\n\tmonomialFromKey,\n\tcompareMonomials,\n\tfromPolynomial,\n} from \"@solve-js/symbolic/Polynomial\";\nimport { exactIntegerSqrt, exactIntegerCbrt } from \"@solve-js/symbolic/Radicals\";\n\n/** One term of a polynomial, pulled out of the term map so the patterns below can read as algebra. */\ninterface Term {\n\treadonly key: MonomialKey;\n\treadonly coefficient: Rational;\n}\n\n/** The exact `n`-th root of a rational, or `null` when it is irrational. Only the second and third roots are needed. */\nfunction exactRoot(value: Rational, degree: 2 | 3): Rational | null {\n\tconst rootOf = degree === 2 ? exactIntegerSqrt : exactIntegerCbrt;\n\tconst numerator = rootOf(value.n);\n\tconst denominator = rootOf(value.d);\n\treturn numerator === null || denominator === null ? null : { n: numerator, d: denominator };\n}\n\n/** The exact `n`-th root of a monomial, or `null` when some exponent is not divisible by `n`. */\nfunction monomialRoot(key: MonomialKey, degree: number): MonomialKey | null {\n\tconst monomial = monomialFromKey(key);\n\tconst root: Monomial = new Map();\n\tfor (const [name, exponent] of monomial) {\n\t\tif (exponent % degree !== 0) return null;\n\t\troot.set(name, exponent / degree);\n\t}\n\treturn monomialToKey(root);\n}\n\n/** Multiplies two monomials. */\nfunction monomialMul(a: MonomialKey, b: MonomialKey): MonomialKey {\n\tconst product = monomialFromKey(a);\n\tfor (const [name, exponent] of monomialFromKey(b)) {\n\t\tproduct.set(name, (product.get(name) ?? 0) + exponent);\n\t}\n\treturn monomialToKey(product);\n}\n\n/** Divides one monomial by another, which the caller must already know divides it. */\nfunction monomialDiv(a: MonomialKey, b: MonomialKey): MonomialKey {\n\tconst quotient = monomialFromKey(a);\n\tfor (const [name, exponent] of monomialFromKey(b)) {\n\t\tconst remaining = (quotient.get(name) ?? 0) - exponent;\n\t\tif (remaining <= 0) quotient.delete(name);\n\t\telse quotient.set(name, remaining);\n\t}\n\treturn monomialToKey(quotient);\n}\n\n/** The highest monomial dividing both, taking the lower exponent of each shared variable. */\nfunction monomialGcd(a: MonomialKey, b: MonomialKey): MonomialKey {\n\tconst left = monomialFromKey(a);\n\tconst shared: Monomial = new Map();\n\tfor (const [name, exponent] of monomialFromKey(b)) {\n\t\tconst other = left.get(name);\n\t\tif (other !== undefined) shared.set(name, Math.min(other, exponent));\n\t}\n\treturn monomialToKey(shared);\n}\n\n/** The variable names a monomial mentions. */\nfunction namesOf(keys: readonly MonomialKey[]): string[] {\n\tconst names = new Set<string>();\n\tfor (const key of keys) for (const name of monomialFromKey(key).keys()) names.add(name);\n\treturn [...names].sort();\n}\n\n/** Builds an expression from a term list, going through {@link fromPolynomial} so the ordering matches everything else. */\nfunction termsToNode(terms: readonly Term[]): SymbolicNode {\n\tconst map = new Map<MonomialKey, Rational>();\n\tfor (const term of terms) map.set(term.key, term.coefficient);\n\treturn fromPolynomial({ terms: map, vars: namesOf(terms.map(term => term.key)) });\n}\n\n/** Multiplies a list of factors into one expression. */\nfunction product(factors: readonly SymbolicNode[]): SymbolicNode {\n\tlet result = factors[0];\n\tfor (let i = 1; i < factors.length; i++) result = { kind: \"mul\", left: result, right: factors[i] };\n\treturn result;\n}\n\n/**\n * The terms of a polynomial in the same order {@link fromPolynomial} prints\n * them, highest first.\n *\n * Through {@link compareMonomials} rather than by sorting the key strings. The\n * patterns below read positionally, so `x^2+2xy+y^2` has to arrive with `x^2`\n * first; sorting keys as text puts `x*y` first, because `*` sorts before `^`.\n */\nfunction orderedTerms(p: Polynomial): Term[] {\n\tconst terms: Term[] = [...p.terms].map(([key, coefficient]) => ({ key, coefficient }));\n\treturn terms.sort((a, b) => compareMonomials(a.key, b.key, p.vars));\n}\n\n/**\n * Factors a multivariate polynomial by pattern.\n *\n * @param p - The polynomial, already stripped of its content and common\n * monomial by the caller.\n * @returns The factored expression, or `null` when no pattern matched.\n */\nexport function factorMultivariate(p: Polynomial): SymbolicNode | null {\n\tif (p.vars.length < 2) return null;\n\n\tconst terms = orderedTerms(p);\n\tif (terms.length === 2) return factorBinomial(terms[0], terms[1]);\n\tif (terms.length === 3) return factorPerfectSquare(terms);\n\tif (terms.length === 4) return factorByGrouping(terms);\n\treturn null;\n}\n\n/**\n * A difference of squares, or a sum or difference of cubes.\n *\n * Each needs both terms to be exact powers, coefficient and monomial together:\n * `4x^2-9y^2` matches because four and nine are squares and both exponents are\n * even, while `2x^2-y^2` does not, since its factorization needs `sqrt(2)` and\n * so is not over the rationals at all.\n */\nfunction factorBinomial(first: Term, second: Term): SymbolicNode | null {\n\tconst firstPositive = first.coefficient.n > 0n;\n\tconst secondPositive = second.coefficient.n > 0n;\n\t// A leading negative is left alone: negating to match a pattern would produce\n\t// a factorization with a spurious -1 out front.\n\tif (!firstPositive) return null;\n\n\tconst squares = asPowerPair(first, second, 2);\n\tif (squares !== null && !secondPositive) {\n\t\t// A^2 - B^2 = (A-B)(A+B)\n\t\treturn product([\n\t\t\ttermsToNode([squares.a, negated(squares.b)]),\n\t\t\ttermsToNode([squares.a, squares.b]),\n\t\t]);\n\t}\n\n\tconst cubes = asPowerPair(first, second, 3);\n\tif (cubes === null) return null;\n\t// A^3 - B^3 = (A-B)(A^2+AB+B^2), and A^3 + B^3 = (A+B)(A^2-AB+B^2).\n\tconst linear = secondPositive\n\t\t? termsToNode([cubes.a, cubes.b])\n\t\t: termsToNode([cubes.a, negated(cubes.b)]);\n\tconst middle = secondPositive ? negated(multiplyTerms(cubes.a, cubes.b)) : multiplyTerms(cubes.a, cubes.b);\n\treturn product([linear, termsToNode([squareOf(cubes.a), middle, squareOf(cubes.b)])]);\n}\n\n/** Both terms as exact `degree`-th powers, or `null` when either is not one. */\nfunction asPowerPair(first: Term, second: Term, degree: 2 | 3): { a: Term; b: Term } | null {\n\tconst magnitude = second.coefficient.n < 0n ? rationalNeg(second.coefficient) : second.coefficient;\n\tconst firstRoot = exactRoot(first.coefficient, degree);\n\tconst secondRoot = exactRoot(magnitude, degree);\n\tif (firstRoot === null || secondRoot === null) return null;\n\n\tconst firstKey = monomialRoot(first.key, degree);\n\tconst secondKey = monomialRoot(second.key, degree);\n\tif (firstKey === null || secondKey === null) return null;\n\n\treturn { a: { key: firstKey, coefficient: firstRoot }, b: { key: secondKey, coefficient: secondRoot } };\n}\n\n/** Negates a term. */\nfunction negated(term: Term): Term {\n\treturn { key: term.key, coefficient: rationalNeg(term.coefficient) };\n}\n\n/** Multiplies two terms. */\nfunction multiplyTerms(a: Term, b: Term): Term {\n\treturn { key: monomialMul(a.key, b.key), coefficient: rationalMul(a.coefficient, b.coefficient) };\n}\n\n/** Squares a term. */\nfunction squareOf(term: Term): Term {\n\treturn multiplyTerms(term, term);\n}\n\n/**\n * A perfect-square trinomial, `A^2 ± 2AB + B^2`.\n *\n * The outer terms have to be squares and the middle one exactly twice their\n * roots' product. `x^2+3xy+y^2` fails that last test and is left alone, which\n * is right: it does not factor over the rationals.\n */\nfunction factorPerfectSquare(terms: readonly Term[]): SymbolicNode | null {\n\tconst [first, middle, last] = terms;\n\tif (first.coefficient.n < 0n || last.coefficient.n < 0n) return null;\n\n\tconst roots = asPowerPair(first, last, 2);\n\tif (roots === null) return null;\n\n\tconst cross = multiplyTerms(roots.a, roots.b);\n\tif (cross.key !== middle.key) return null;\n\n\tconst twice = rationalMul(cross.coefficient, { n: 2n, d: 1n });\n\tconst negative = middle.coefficient.n < 0n;\n\tconst magnitude = negative ? rationalNeg(middle.coefficient) : middle.coefficient;\n\tif (!isRationalOne(rationalDiv(magnitude, twice))) return null;\n\n\tconst base = termsToNode([roots.a, negative ? negated(roots.b) : roots.b]);\n\treturn { kind: \"pow\", base, exponent: constNode(2) };\n}\n\n/**\n * Four terms that split into two pairs sharing a factor.\n *\n * `ax+ay+bx+by` pairs as `a(x+y) + b(x+y)`, so the shared `x+y` comes out and\n * `a+b` is what is left. All three ways of pairing four terms are tried, since\n * the terms arrive in degree order rather than in the order that groups.\n */\nfunction factorByGrouping(terms: readonly Term[]): SymbolicNode | null {\n\tconst pairings: [number, number][][] = [\n\t\t[[0, 1], [2, 3]],\n\t\t[[0, 2], [1, 3]],\n\t\t[[0, 3], [1, 2]],\n\t];\n\n\tfor (const pairing of pairings) {\n\t\tconst first = splitPair(terms[pairing[0][0]], terms[pairing[0][1]]);\n\t\tconst second = splitPair(terms[pairing[1][0]], terms[pairing[1][1]]);\n\t\tif (first === null || second === null) continue;\n\t\tif (!cofactorsAgree(first.cofactor, second.cofactor)) continue;\n\n\t\treturn product([\n\t\t\ttermsToNode([first.common, second.common]),\n\t\t\ttermsToNode(first.cofactor),\n\t\t]);\n\t}\n\treturn null;\n}\n\n/**\n * Splits a pair of terms into what they share and what is left.\n *\n * The shared part takes the first term's whole coefficient rather than a\n * greatest common divisor of the two, which makes the leftover start with one.\n * That is what lets two pairs be compared directly: both leftovers are written\n * in the same normal form, so equality is a term-by-term check rather than a\n * proportionality test.\n */\nfunction splitPair(first: Term, second: Term): { common: Term; cofactor: Term[] } | null {\n\tconst shared = monomialGcd(first.key, second.key);\n\tconst common: Term = { key: shared, coefficient: first.coefficient };\n\tconst cofactor: Term[] = [\n\t\t{ key: monomialDiv(first.key, shared), coefficient: { n: 1n, d: 1n } },\n\t\t{ key: monomialDiv(second.key, shared), coefficient: rationalDiv(second.coefficient, first.coefficient) },\n\t];\n\t// Two terms that shared everything would leave a constant cofactor, which is\n\t// not a factorization of anything.\n\treturn cofactor[0].key === cofactor[1].key ? null : { common, cofactor };\n}\n\n/** Whether two cofactors are the same polynomial, term for term. */\nfunction cofactorsAgree(a: readonly Term[], b: readonly Term[]): boolean {\n\tif (a.length !== b.length) return false;\n\treturn a.every((term, index) =>\n\t\tterm.key === b[index].key\n\t\t&& term.coefficient.n === b[index].coefficient.n\n\t\t&& term.coefficient.d === b[index].coefficient.d);\n}\n","/**\n * Polynomial factoring over the rationals.\n *\n * ## What \"factored\" means here\n *\n * Factoring is only well defined once you say **over what**. `x^2-2` is\n * irreducible over the rationals but factors over the reals as\n * `(x-sqrt(2))(x+sqrt(2))`, and `x^2+1` factors only over the complex numbers.\n * This module factors **over the rationals**, so both of those come back\n * unchanged. That is a real answer, not a failure, and the documentation says\n * so rather than leaving a user to guess.\n *\n * The consequence worth stating plainly: a polynomial with no rational roots is\n * returned as one irreducible factor even in the cases where it does split into\n * higher-degree rational pieces that this module does not search for. See the\n * strategy list on {@link factorSymbolic} for exactly what is attempted.\n *\n * ## Why this is exact\n *\n * The rational-root theorem tests a candidate by evaluating the polynomial at\n * it and asking whether the result is zero. In floating point a near-miss and a\n * true root are indistinguishable, so the whole method depends on the exact\n * arithmetic in `Rational.ts`. This is the clearest reason the CAS could not\n * have been built on doubles.\n */\n\nimport {\n\ttype SymbolicNode,\n\tconstNode,\n\tvarNode,\n\tpowNode,\n} from \"@solve-js/symbolic/SymbolicNode\";\nimport {\n\ttype Rational,\n\tRATIONAL_ZERO,\n\tRATIONAL_ONE,\n\trationalAdd,\n\trationalMul,\n\trationalDiv,\n\trationalNeg,\n\tisRationalZero,\n\tisRationalOne,\n} from \"@solve-js/symbolic/Rational\";\nimport {\n\ttype Polynomial,\n\ttoPolynomial,\n\tfromPolynomial,\n\tpolyDegree,\n\tpolyUnivariateVar,\n\tpolyCoefficients,\n} from \"@solve-js/symbolic/Polynomial\";\nimport { factorMultivariate } from \"@solve-js/symbolic/MultivariateFactor\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Highest degree this module will attempt to factor.\n *\n * The rational-root search is the expensive step and its cost grows with the\n * size of the leading and trailing coefficients rather than with degree alone,\n * but degree bounds how many times that search is repeated as factors are\n * divided out.\n */\nexport const FACTOR_MAX_DEGREE = 12;\n\n/**\n * Ceiling on the number of candidate roots the rational-root theorem may test.\n *\n * This is the step that actually blows up. Candidates are every `±p/q` for `p`\n * dividing the trailing coefficient and `q` the leading one, so the set is the\n * **product** of two divisor sets. A trailing coefficient of 720720 alone has\n * 240 divisors, and a comparable leading coefficient would put the product in\n * the tens of thousands before any of them is tested.\n */\nexport const FACTOR_MAX_ROOT_CANDIDATES = 4_096;\n\n/**\n * A polynomial written as a rational constant times a list of irreducible\n * factors with multiplicity.\n */\nexport interface Factorization {\n\t/** The rational content pulled out front. One when the polynomial was already primitive. */\n\treadonly content: Rational;\n\t/** Irreducible-over-the-rationals factors, in ascending degree. */\n\treadonly factors: readonly { readonly base: SymbolicNode; readonly power: number }[];\n}\n\n/** Greatest common divisor of two non-negative bigints. */\nfunction gcd(a: bigint, b: bigint): bigint {\n\tlet x = a < 0n ? -a : a;\n\tlet y = b < 0n ? -b : b;\n\twhile (y !== 0n) {\n\t\tconst remainder = x % y;\n\t\tx = y;\n\t\ty = remainder;\n\t}\n\treturn x;\n}\n\n/** Least common multiple of two positive bigints. */\nfunction lcm(a: bigint, b: bigint): bigint {\n\tif (a === 0n || b === 0n) return 0n;\n\treturn (a / gcd(a, b)) * b;\n}\n\n/**\n * Every positive divisor of a positive bigint, by trial division to its square\n * root.\n *\n * @returns The divisors, or `null` once more than {@link FACTOR_MAX_ROOT_CANDIDATES}\n * have been found, so a highly-composite coefficient stops the search rather\n * than exhausting time here.\n */\nfunction divisors(value: bigint): bigint[] | null {\n\tconst magnitude = value < 0n ? -value : value;\n\tif (magnitude === 0n) return null;\n\tconst found: bigint[] = [];\n\tfor (let candidate = 1n; candidate * candidate <= magnitude; candidate++) {\n\t\tif (magnitude % candidate !== 0n) continue;\n\t\tfound.push(candidate);\n\t\tconst paired = magnitude / candidate;\n\t\tif (paired !== candidate) found.push(paired);\n\t\tif (found.length > FACTOR_MAX_ROOT_CANDIDATES) return null;\n\t}\n\treturn found;\n}\n\n/** Evaluates a descending-order coefficient list at `x`, by Horner's method. */\nfunction evaluateAt(descending: readonly Rational[], x: Rational): Rational {\n\tlet total = RATIONAL_ZERO;\n\tfor (const coeff of descending) total = rationalAdd(rationalMul(total, x), coeff);\n\treturn total;\n}\n\n/**\n * Divides a descending-order polynomial by `(x - root)` using synthetic\n * division.\n *\n * @returns The quotient's descending coefficients. The remainder is discarded,\n * so only call this with a value already confirmed to be a root.\n */\nfunction divideByRoot(descending: readonly Rational[], root: Rational): Rational[] {\n\tconst quotient: Rational[] = [descending[0]];\n\tfor (let i = 1; i < descending.length - 1; i++) {\n\t\tquotient.push(rationalAdd(descending[i], rationalMul(quotient[i - 1], root)));\n\t}\n\treturn quotient;\n}\n\n/**\n * Every rational root of a univariate polynomial, by the rational-root theorem.\n *\n * @param descending - Coefficients from the highest power down. The leading\n * coefficient must be non-zero and the trailing one must also be non-zero (a\n * zero constant term means `x` itself is a factor, which the caller removes as\n * a common monomial first).\n * @returns The distinct rational roots, each listed once.\n * @throws {EngineError} `SYMBOLIC_FACTOR_LIMIT_EXCEEDED` when the candidate set\n * would exceed {@link FACTOR_MAX_ROOT_CANDIDATES}.\n */\nexport function rationalRoots(descending: readonly Rational[]): readonly Rational[] {\n\tif (descending.length < 2) return [];\n\n\t// Clear denominators so the theorem's integer statement applies.\n\tlet multiplier = 1n;\n\tfor (const coeff of descending) multiplier = lcm(multiplier, coeff.d);\n\tconst integers = descending.map(coeff => (coeff.n * multiplier) / coeff.d);\n\n\tconst leading = integers[0];\n\tconst trailing = integers[integers.length - 1];\n\tif (trailing === 0n) return [];\n\n\tconst numeratorDivisors = divisors(trailing);\n\tconst denominatorDivisors = divisors(leading);\n\tif (numeratorDivisors === null || denominatorDivisors === null) {\n\t\tthrow ErrorFactory.execution(\n\t\t\t\"SYMBOLIC_FACTOR_LIMIT_EXCEEDED\",\n\t\t\t\"This polynomial's coefficients have too many divisors to search for rational roots.\",\n\t\t\t{ limit: FACTOR_MAX_ROOT_CANDIDATES },\n\t\t);\n\t}\n\tif (numeratorDivisors.length * denominatorDivisors.length > FACTOR_MAX_ROOT_CANDIDATES) {\n\t\tthrow ErrorFactory.execution(\n\t\t\t\"SYMBOLIC_FACTOR_LIMIT_EXCEEDED\",\n\t\t\t\"This polynomial has too many candidate rational roots to test.\",\n\t\t\t{ limit: FACTOR_MAX_ROOT_CANDIDATES },\n\t\t);\n\t}\n\n\tconst roots: Rational[] = [];\n\tconst seen = new Set<string>();\n\tfor (const p of numeratorDivisors) {\n\t\tfor (const q of denominatorDivisors) {\n\t\t\tfor (const sign of [1n, -1n]) {\n\t\t\t\tconst candidate: Rational = { n: (sign * p) / gcd(p, q), d: q / gcd(p, q) };\n\t\t\t\tconst key = `${candidate.n}/${candidate.d}`;\n\t\t\t\tif (seen.has(key)) continue;\n\t\t\t\tseen.add(key);\n\t\t\t\tif (isRationalZero(evaluateAt(descending, candidate))) roots.push(candidate);\n\t\t\t}\n\t\t}\n\t}\n\treturn roots;\n}\n\n/** Builds the node for `x - root`, or `x + |root|` when the root is negative, so the display reads naturally. */\nfunction linearFactorNode(variable: string, root: Rational): SymbolicNode {\n\tif (isRationalZero(root)) return varNode(variable);\n\treturn root.n > 0n\n\t\t? { kind: \"sub\", left: varNode(variable), right: constNode(root) }\n\t\t: { kind: \"add\", left: varNode(variable), right: constNode(rationalNeg(root)) };\n}\n\n/** Rebuilds a descending coefficient list into an expression tree in the given variable. */\nfunction coefficientsToNode(descending: readonly Rational[], variable: string): SymbolicNode {\n\tconst degree = descending.length - 1;\n\tconst terms = new Map<string, Rational>();\n\tdescending.forEach((coeff, index) => {\n\t\tif (isRationalZero(coeff)) return;\n\t\tconst power = degree - index;\n\t\tterms.set(power === 0 ? \"\" : power === 1 ? variable : `${variable}^${power}`, coeff);\n\t});\n\treturn fromPolynomial({ terms, vars: terms.size > 0 ? [variable] : [] });\n}\n\n/**\n * Factors a univariate polynomial over the rationals by repeatedly extracting\n * rational roots.\n *\n * @param descending - Coefficients from the highest power down.\n * @param variable - The variable name, used to build the factor nodes.\n * @returns The factorization. A polynomial with no rational roots comes back as\n * a single factor, which is the correct answer over the rationals.\n */\nexport function factorUnivariate(descending: readonly Rational[], variable: string): Factorization {\n\tconst factors: { base: SymbolicNode; power: number }[] = [];\n\tlet remaining = [...descending];\n\n\t// A root can repeat, so each one is divided out until it stops being one.\n\t// That is what turns (x-1)^2 into a single factor with power two rather\n\t// than two identical factors.\n\tlet roots = rationalRoots(remaining);\n\twhile (roots.length > 0 && remaining.length > 2) {\n\t\tfor (const root of roots) {\n\t\t\tlet multiplicity = 0;\n\t\t\twhile (remaining.length > 1 && isRationalZero(evaluateAt(remaining, root))) {\n\t\t\t\tremaining = divideByRoot(remaining, root);\n\t\t\t\tmultiplicity++;\n\t\t\t}\n\t\t\tif (multiplicity > 0) factors.push({ base: linearFactorNode(variable, root), power: multiplicity });\n\t\t}\n\t\troots = remaining.length > 2 ? rationalRoots(remaining) : [];\n\t}\n\n\t// Whatever survives is irreducible over the rationals as far as this module\n\t// searches. A leading coefficient other than one stays inside it rather than\n\t// being pulled out, so the product still multiplies back to the input.\n\tconst leftoverDegree = remaining.length - 1;\n\tif (leftoverDegree >= 1) {\n\t\tfactors.push({ base: coefficientsToNode(remaining, variable), power: 1 });\n\t\treturn { content: RATIONAL_ONE, factors };\n\t}\n\treturn { content: remaining.length === 1 ? remaining[0] : RATIONAL_ONE, factors };\n}\n\n/** Multiplies a content constant and a factor list back into one expression tree. */\nfunction factorizationToNode(factorization: Factorization): SymbolicNode {\n\tconst pieces: SymbolicNode[] = [];\n\tif (!isRationalOne(factorization.content)) pieces.push(constNode(factorization.content));\n\tfor (const factor of factorization.factors) {\n\t\tpieces.push(factor.power === 1 ? factor.base : powNode(factor.base, constNode({ n: BigInt(factor.power), d: 1n })));\n\t}\n\tif (pieces.length === 0) return constNode(RATIONAL_ONE);\n\n\tlet result = pieces[0];\n\tfor (let i = 1; i < pieces.length; i++) result = { kind: \"mul\", left: result, right: pieces[i] };\n\treturn result;\n}\n\n/** The rational content of a polynomial: the gcd of its numerators over the lcm of its denominators. */\nfunction contentOf(p: Polynomial): Rational {\n\tlet numeratorGcd = 0n;\n\tlet denominatorLcm = 1n;\n\tfor (const coeff of p.terms.values()) {\n\t\tnumeratorGcd = gcd(numeratorGcd, coeff.n);\n\t\tdenominatorLcm = lcm(denominatorLcm, coeff.d);\n\t}\n\tif (numeratorGcd === 0n) return RATIONAL_ONE;\n\treturn { n: numeratorGcd, d: denominatorLcm };\n}\n\n/** The highest power of each variable dividing every term, as a monomial key, plus the polynomial with it removed. */\nfunction extractCommonMonomial(p: Polynomial): { monomial: Map<string, number>; reduced: Polynomial } {\n\tconst common = new Map<string, number>();\n\tfor (const name of p.vars) {\n\t\tlet lowest = Infinity;\n\t\tfor (const key of p.terms.keys()) {\n\t\t\tconst exponent = exponentOf(key, name);\n\t\t\tif (exponent < lowest) lowest = exponent;\n\t\t}\n\t\tif (lowest > 0 && lowest !== Infinity) common.set(name, lowest);\n\t}\n\tif (common.size === 0) return { monomial: common, reduced: p };\n\n\tconst terms = new Map<string, Rational>();\n\tfor (const [key, coeff] of p.terms) {\n\t\tconst exponents = parseKey(key);\n\t\tfor (const [name, shared] of common) exponents.set(name, (exponents.get(name) ?? 0) - shared);\n\t\tterms.set(buildKey(exponents), coeff);\n\t}\n\tconst names = new Set<string>();\n\tfor (const key of terms.keys()) for (const name of parseKey(key).keys()) names.add(name);\n\treturn { monomial: common, reduced: { terms, vars: [...names].sort() } };\n}\n\n/** Exponent of one variable within a monomial key. */\nfunction exponentOf(key: string, name: string): number {\n\treturn parseKey(key).get(name) ?? 0;\n}\n\n/** Parses a monomial key into a variable-to-exponent map, mirroring `Polynomial.ts`'s own encoding. */\nfunction parseKey(key: string): Map<string, number> {\n\tconst exponents = new Map<string, number>();\n\tif (key === \"\") return exponents;\n\tfor (const factor of key.split(\"*\")) {\n\t\tconst caret = factor.indexOf(\"^\");\n\t\tif (caret === -1) exponents.set(factor, 1);\n\t\telse exponents.set(factor.slice(0, caret), Number(factor.slice(caret + 1)));\n\t}\n\treturn exponents;\n}\n\n/** Serializes a variable-to-exponent map back into a monomial key, dropping zero exponents. */\nfunction buildKey(exponents: Map<string, number>): string {\n\tconst names = [...exponents.keys()].filter(name => (exponents.get(name) ?? 0) > 0).sort();\n\treturn names.map(name => (exponents.get(name) === 1 ? name : `${name}^${exponents.get(name)}`)).join(\"*\");\n}\n\n/** Builds the node for a common monomial such as `2x` or `x^2*y`. */\nfunction monomialNode(monomial: Map<string, number>): SymbolicNode | null {\n\tconst names = [...monomial.keys()].sort();\n\tlet result: SymbolicNode | null = null;\n\tfor (const name of names) {\n\t\tconst exponent = monomial.get(name)!;\n\t\tconst factor = exponent === 1 ? varNode(name) : powNode(varNode(name), constNode({ n: BigInt(exponent), d: 1n }));\n\t\tresult = result === null ? factor : { kind: \"mul\", left: result, right: factor };\n\t}\n\treturn result;\n}\n\n/**\n * Factors an expression over the rationals.\n *\n * Strategies, in the order attempted:\n *\n * 1. Convert to polynomial form. Anything that is not a polynomial over the\n * rationals is returned unchanged.\n * 2. Pull out the rational content, the shared factor across all coefficients.\n * 3. Pull out the highest power of each variable dividing every term, so\n * `2x^2+4x` becomes `2x*(x+2)`.\n * 4. If more than one variable remains, hand off to\n * {@link factorMultivariate}'s pattern set: a difference of squares, a sum\n * or difference of cubes, a perfect-square trinomial, or four terms that\n * group. Anything it declines stops here, with the content and common\n * monomial extracted and nothing guessed at beyond them.\n * 5. Extract rational roots by the rational-root theorem, dividing each out\n * with its multiplicity.\n * 6. Leave whatever survives as one irreducible-over-the-rationals factor.\n *\n * @param node - The expression to factor.\n * @returns The factored expression, or `node` unchanged when it is not a\n * polynomial, is already irreducible, or exceeds {@link FACTOR_MAX_DEGREE}.\n * @throws {EngineError} `SYMBOLIC_FACTOR_LIMIT_EXCEEDED` when the rational-root\n * candidate set grows past {@link FACTOR_MAX_ROOT_CANDIDATES}.\n */\nexport function factorSymbolic(node: SymbolicNode): SymbolicNode {\n\tconst polynomial = toPolynomial(node);\n\tif (polynomial === null || polynomial.terms.size === 0) return node;\n\tif (polyDegree(polynomial) > FACTOR_MAX_DEGREE) return node;\n\t// A constant has no factorization in this sense. Splitting an integer into\n\t// primes is a different feature, and without this the content-extraction\n\t// path below would hand back `12*1`.\n\tif (polynomial.vars.length === 0) return node;\n\n\tconst content = contentOf(polynomial);\n\tconst primitive = isRationalOne(content)\n\t\t? polynomial\n\t\t: scaleTerms(polynomial, rationalDiv(RATIONAL_ONE, content));\n\n\tconst { monomial, reduced } = extractCommonMonomial(primitive);\n\tconst monomialFactor = monomialNode(monomial);\n\n\tconst variable = polyUnivariateVar(reduced);\n\tif (variable === null) {\n\t\t// Constant remainder, or genuinely multivariate. The pattern set in\n\t\t// `MultivariateFactor.ts` covers the shapes a person actually writes;\n\t\t// anything it declines stops at the content and common monomial.\n\t\tconst patterned = factorMultivariate(reduced);\n\t\tif (patterned !== null) return assemble(content, monomialFactor, patterned);\n\t\tconst pieces = buildPieces(content, monomialFactor, reduced);\n\t\treturn pieces ?? node;\n\t}\n\n\tconst descending = [...polyCoefficients(reduced, variable)].reverse();\n\tconst factorization = factorUnivariate(descending, variable);\n\tconst combinedContent = rationalMul(content, factorization.content);\n\n\t// Nothing was achieved only when the result is a single factor raised to the\n\t// first power, which is the input rewritten. A single factor with a power\n\t// above one is a genuine factorization, `(x-1)^2` being the case that makes\n\t// the distinction matter.\n\tconst isUnchanged =\n\t\tfactorization.factors.length <= 1 &&\n\t\t(factorization.factors[0]?.power ?? 1) === 1 &&\n\t\tmonomialFactor === null &&\n\t\tisRationalOne(combinedContent);\n\tif (isUnchanged) return node;\n\n\tconst pieces: SymbolicNode[] = [];\n\tif (!isRationalOne(combinedContent)) pieces.push(constNode(combinedContent));\n\tif (monomialFactor !== null) pieces.push(monomialFactor);\n\tpieces.push(factorizationToNode({ content: RATIONAL_ONE, factors: factorization.factors }));\n\n\tlet result = pieces[0];\n\tfor (let i = 1; i < pieces.length; i++) result = { kind: \"mul\", left: result, right: pieces[i] };\n\treturn result;\n}\n\n/** Multiplies every coefficient of a polynomial by a rational, used to divide out the content. */\nfunction scaleTerms(p: Polynomial, k: Rational): Polynomial {\n\tconst terms = new Map<string, Rational>();\n\tfor (const [key, coeff] of p.terms) terms.set(key, rationalMul(coeff, k));\n\treturn { terms, vars: p.vars };\n}\n\n/**\n * Multiplies an already-factored remainder back together with the content and\n * common monomial that were pulled off before it.\n *\n * @param content - The rational content, left off when it is one.\n * @param monomialFactor - The common monomial, or `null` when there was none.\n * @param factored - The factored remainder.\n * @returns The whole factorization as one expression.\n */\nfunction assemble(content: Rational, monomialFactor: SymbolicNode | null, factored: SymbolicNode): SymbolicNode {\n\tconst pieces: SymbolicNode[] = [];\n\tif (!isRationalOne(content)) pieces.push(constNode(content));\n\tif (monomialFactor !== null) pieces.push(monomialFactor);\n\tpieces.push(factored);\n\n\tlet result = pieces[0];\n\tfor (let i = 1; i < pieces.length; i++) result = { kind: \"mul\", left: result, right: pieces[i] };\n\treturn result;\n}\n\n/** Assembles the content, common monomial and remainder for the multivariate stop case, or `null` when nothing was extracted. */\nfunction buildPieces(content: Rational, monomialFactor: SymbolicNode | null, reduced: Polynomial): SymbolicNode | null {\n\tif (monomialFactor === null && isRationalOne(content)) return null;\n\tconst pieces: SymbolicNode[] = [];\n\tif (!isRationalOne(content)) pieces.push(constNode(content));\n\tif (monomialFactor !== null) pieces.push(monomialFactor);\n\tpieces.push(fromPolynomial(reduced));\n\n\tlet result = pieces[0];\n\tfor (let i = 1; i < pieces.length; i++) result = { kind: \"mul\", left: result, right: pieces[i] };\n\treturn result;\n}\n","/**\n * Exact solutions for cubics and quartics.\n *\n * These were the two degrees that fell through to numerical root finding\n * whenever no rational root could be extracted. Both have closed forms, and both\n * of those forms need complex intermediates, which is why this could not exist\n * before `Complex.ts` did.\n *\n * ## The case that forced the order of work\n *\n * A cubic with three distinct **real** roots has a positive discriminant, and\n * Cardano's formula reaches those real roots through the cube roots of a complex\n * number. There is no way around that: it is a theorem that the real roots of\n * such a cubic cannot be written using real radicals alone. That is the *casus\n * irreducibilis*, and it is the reason \"add complex numbers\" was a prerequisite\n * for \"solve cubics exactly\" rather than an unrelated feature.\n *\n * ## What comes back, and what does not\n *\n * A closed form is returned whenever one exists in radicals: the single real\n * root and the conjugate pair of a cubic with a negative discriminant, the\n * repeated roots of a cubic with a zero one, both square roots of a\n * biquadratic, and a quartic that splits into two quadratics over the\n * rationals.\n *\n * The *casus irreducibilis* comes back numerically, from the trigonometric\n * form. That is not a gap in effort. Those three roots provably have no\n * expression in real radicals, and writing them as `cos` of an `arccos` of an\n * irrational would produce something exact on paper that nothing else in the\n * system can evaluate, factor or differentiate. Reporting three accurate\n * numbers and saying they are approximate is the more honest answer.\n *\n * Everything else declines by returning `null`, which sends the caller to its\n * own numerical fallback rather than to a guess made here.\n */\n\nimport { type SymbolicNode, constNode, complexNode, symbolicKey } from \"@solve-js/symbolic/SymbolicNode\";\nimport { simplifySymbolic } from \"@solve-js/symbolic/Simplify\";\nimport {\n\ttype Rational,\n\tRATIONAL_ZERO,\n\trationalAdd,\n\trationalSub,\n\trationalMul,\n\trationalDiv,\n\trationalNeg,\n\trationalToNumber,\n\trationalCompare,\n\tisRationalZero,\n} from \"@solve-js/symbolic/Rational\";\nimport { rationalRoots } from \"@solve-js/symbolic/Factor\";\nimport { surdNode, signedSurdNode, exactRationalSqrt } from \"@solve-js/symbolic/Radicals\";\nimport { COMPLEX_I } from \"@solve-js/symbolic/Complex\";\n\n/** Roots split by how exactly they are known, so a caller can label the approximate ones as such. */\nexport interface RootSet {\n\treadonly exact: readonly SymbolicNode[];\n\treadonly approximate: readonly number[];\n}\n\n/** Small rational literals, named so the formulas below read as formulas. */\nconst TWO: Rational = { n: 2n, d: 1n };\nconst THREE: Rational = { n: 3n, d: 1n };\nconst FOUR: Rational = { n: 4n, d: 1n };\n\n/** A cubic reduced to `t^3 + pt + q` by the substitution `x = t + shift`. */\ninterface DepressedCubic {\n\treadonly p: Rational;\n\treadonly q: Rational;\n\treadonly shift: Rational;\n}\n\n/**\n * Removes the quadratic term from a cubic.\n *\n * Every cubic `ax^3+bx^2+cx+d` becomes `t^3+pt+q` under `x = t - b/3a`, and that\n * reduction is what makes a closed form possible at all.\n */\nfunction depressCubic(a: Rational, b: Rational, c: Rational, d: Rational): DepressedCubic {\n\tconst shift = rationalNeg(rationalDiv(b, rationalMul(THREE, a)));\n\t// p = (3ac - b^2) / 3a^2\n\tconst p = rationalDiv(\n\t\trationalSub(rationalMul(THREE, rationalMul(a, c)), rationalMul(b, b)),\n\t\trationalMul(THREE, rationalMul(a, a)),\n\t);\n\t// q = (2b^3 - 9abc + 27a^2 d) / 27a^3\n\tconst twoBCubed = rationalMul(TWO, rationalMul(b, rationalMul(b, b)));\n\tconst nineABC = rationalMul({ n: 9n, d: 1n }, rationalMul(a, rationalMul(b, c)));\n\tconst twentySevenAAD = rationalMul({ n: 27n, d: 1n }, rationalMul(rationalMul(a, a), d));\n\tconst q = rationalDiv(\n\t\trationalAdd(rationalSub(twoBCubed, nineABC), twentySevenAAD),\n\t\trationalMul({ n: 27n, d: 1n }, rationalMul(a, rationalMul(a, a))),\n\t);\n\treturn { p, q, shift };\n}\n\n/**\n * The roots of a cubic in closed form.\n *\n * @param a - Leading coefficient, which must be non-zero.\n * @param b - Quadratic coefficient.\n * @param c - Linear coefficient.\n * @param d - Constant coefficient.\n * @returns All three roots, exact where radicals can express them and\n * approximate in the *casus irreducibilis*. Never `null`: every cubic is\n * covered by one of the three discriminant cases.\n */\nexport function solveCubic(a: Rational, b: Rational, c: Rational, d: Rational): RootSet {\n\tconst { p, q, shift } = depressCubic(a, b, c, d);\n\n\t// discriminant = -(4p^3 + 27q^2), whose sign decides the shape of the answer.\n\tconst discriminant = rationalNeg(\n\t\trationalAdd(\n\t\t\trationalMul(FOUR, rationalMul(p, rationalMul(p, p))),\n\t\t\trationalMul({ n: 27n, d: 1n }, rationalMul(q, q)),\n\t\t),\n\t);\n\n\tif (rationalCompare(discriminant, RATIONAL_ZERO) > 0) {\n\t\treturn { exact: [], approximate: trigonometricRoots(p, q, shift) };\n\t}\n\tif (isRationalZero(discriminant)) return { exact: repeatedCubicRoots(p, q, shift), approximate: [] };\n\treturn { exact: cardanoRoots(p, q, shift), approximate: [] };\n}\n\n/**\n * The roots of a depressed cubic whose discriminant is zero.\n *\n * Both roots are rational here, which is worth stating: a cubic over the\n * rationals with a repeated root has all of its roots rational, so nothing\n * irrational can appear in this branch.\n */\nfunction repeatedCubicRoots(p: Rational, q: Rational, shift: Rational): SymbolicNode[] {\n\t// p and q both zero is a triple root at the shift itself.\n\tif (isRationalZero(p)) return [constNode(shift)];\n\n\tconst simple = rationalAdd(rationalDiv(rationalMul(THREE, q), p), shift);\n\tconst repeated = rationalAdd(rationalNeg(rationalDiv(rationalMul(THREE, q), rationalMul(TWO, p))), shift);\n\tconst ordered = [simple, repeated].sort(rationalCompare);\n\treturn ordered.map(constNode);\n}\n\n/**\n * The three roots of a depressed cubic with a negative discriminant, by\n * Cardano's formula.\n *\n * With `u` and `v` the two real cube roots below, the roots are `u+v` and\n * `u*w + v*w^2` for the two primitive cube roots of unity `w`. Multiplying that\n * out gives one real root and a conjugate pair, which is what this builds.\n *\n * Both cube roots are of real numbers here, because a negative discriminant is\n * exactly the condition that puts the radicand of the inner square root above\n * zero. That is what keeps this branch expressible in radicals while the\n * *casus irreducibilis* is not.\n */\nfunction cardanoRoots(p: Rational, q: Rational, shift: Rational): SymbolicNode[] {\n\tconst half = rationalNeg(rationalDiv(q, TWO));\n\t// (q/2)^2 + (p/3)^3, positive whenever the discriminant is negative.\n\tconst radicand = rationalAdd(\n\t\trationalMul(rationalDiv(q, TWO), rationalDiv(q, TWO)),\n\t\trationalMul(rationalDiv(p, THREE), rationalMul(rationalDiv(p, THREE), rationalDiv(p, THREE))),\n\t);\n\tconst inner = surdNode(radicand);\n\n\t// Emitted as `cbrt` calls so the simplifier folds them when the radicand is\n\t// a perfect square and the result a perfect cube, which is how `x^3 = 8`\n\t// still comes back as a plain `2`.\n\tconst u: SymbolicNode = { kind: \"call\", name: \"cbrt\", args: [{ kind: \"add\", left: constNode(half), right: inner }] };\n\tconst v: SymbolicNode = { kind: \"call\", name: \"cbrt\", args: [{ kind: \"sub\", left: constNode(half), right: inner }] };\n\n\tconst sum: SymbolicNode = { kind: \"add\", left: u, right: v };\n\tconst difference: SymbolicNode = { kind: \"sub\", left: u, right: v };\n\tconst real: SymbolicNode = { kind: \"add\", left: constNode(shift), right: { kind: \"div\", left: { kind: \"neg\", operand: sum }, right: constNode(TWO) } };\n\t// (u-v) * sqrt(3)/2 * i\n\tconst imaginary: SymbolicNode = {\n\t\tkind: \"mul\",\n\t\tleft: { kind: \"div\", left: { kind: \"mul\", left: difference, right: surdNode(THREE) }, right: constNode(TWO) },\n\t\tright: complexNode(COMPLEX_I),\n\t};\n\n\treturn [\n\t\t{ kind: \"add\", left: constNode(shift), right: sum },\n\t\t{ kind: \"sub\", left: real, right: imaginary },\n\t\t{ kind: \"add\", left: real, right: imaginary },\n\t];\n}\n\n/**\n * The three real roots of a depressed cubic in the *casus irreducibilis*, by the\n * trigonometric form.\n *\n * These are returned as numbers on purpose. See this module's header: no\n * expression in real radicals exists for them, and the trigonometric expression\n * that does exist is not something the rest of the system could evaluate\n * exactly anyway.\n */\nfunction trigonometricRoots(p: Rational, q: Rational, shift: Rational): number[] {\n\tconst pNumber = rationalToNumber(p);\n\tconst qNumber = rationalToNumber(q);\n\tconst shiftNumber = rationalToNumber(shift);\n\n\t// t_k = 2 sqrt(-p/3) cos( arccos( (3q)/(2p) sqrt(-3/p) )/3 - 2*pi*k/3 )\n\tconst magnitude = 2 * Math.sqrt(-pNumber / 3);\n\tconst ratio = ((3 * qNumber) / (2 * pNumber)) * Math.sqrt(-3 / pNumber);\n\t// Clamped against the rounding that can push the value a hair outside\n\t// arccos's domain, which would turn a genuine root into a NaN.\n\tconst angle = Math.acos(Math.min(1, Math.max(-1, ratio))) / 3;\n\n\treturn [0, 1, 2]\n\t\t.map(k => magnitude * Math.cos(angle - (2 * Math.PI * k) / 3) + shiftNumber)\n\t\t.sort((left, right) => left - right);\n}\n\n/** A quartic reduced to `t^4 + pt^2 + qt + r` by the substitution `x = t + shift`. */\ninterface DepressedQuartic {\n\treadonly p: Rational;\n\treadonly q: Rational;\n\treadonly r: Rational;\n\treadonly shift: Rational;\n}\n\n/** Removes the cubic term from a monic quartic `x^4 + bx^3 + cx^2 + dx + e`. */\nfunction depressQuartic(b: Rational, c: Rational, d: Rational, e: Rational): DepressedQuartic {\n\tconst shift = rationalNeg(rationalDiv(b, FOUR));\n\tconst bb = rationalMul(b, b);\n\t// p = c - 3b^2/8\n\tconst p = rationalSub(c, rationalDiv(rationalMul(THREE, bb), { n: 8n, d: 1n }));\n\t// q = d - bc/2 + b^3/8\n\tconst q = rationalAdd(\n\t\trationalSub(d, rationalDiv(rationalMul(b, c), TWO)),\n\t\trationalDiv(rationalMul(bb, b), { n: 8n, d: 1n }),\n\t);\n\t// r = e - bd/4 + b^2 c/16 - 3b^4/256\n\tconst r = rationalSub(\n\t\trationalAdd(\n\t\t\trationalSub(e, rationalDiv(rationalMul(b, d), FOUR)),\n\t\t\trationalDiv(rationalMul(bb, c), { n: 16n, d: 1n }),\n\t\t),\n\t\trationalDiv(rationalMul(THREE, rationalMul(bb, bb)), { n: 256n, d: 1n }),\n\t);\n\treturn { p, q, r, shift };\n}\n\n/**\n * The roots of a quartic in closed form, where one exists.\n *\n * Two families are covered. A **biquadratic**, which has no odd-power term once\n * depressed, is a quadratic in `t^2` and its roots are square roots of the two\n * solutions of that quadratic. A general quartic is covered when its resolvent\n * cubic has a rational root that splits it into two quadratics over the\n * rationals, which are then solved exactly, complex roots included.\n *\n * Every other quartic returns `null`. Ferrari's method does produce a closed\n * form for those, but it is a radical nested four deep whose printed form\n * nobody can read and nothing downstream can use, so the caller's numerical\n * fallback is the better answer.\n *\n * @param a - Leading coefficient, which must be non-zero.\n * @param b - Cubic coefficient.\n * @param c - Quadratic coefficient.\n * @param d - Linear coefficient.\n * @param e - Constant coefficient.\n * @param solveQuadratic - The quadratic solver to use for each half of a split.\n * Passed in rather than imported so this module stays independent of `Solve.ts`.\n * @returns The roots, or `null` when no readable closed form exists.\n */\nexport function solveQuartic(\n\ta: Rational,\n\tb: Rational,\n\tc: Rational,\n\td: Rational,\n\te: Rational,\n\tsolveQuadratic: (a: Rational, b: Rational, c: Rational) => readonly SymbolicNode[],\n): RootSet | null {\n\tconst monic = (value: Rational): Rational => rationalDiv(value, a);\n\tconst { p, q, r, shift } = depressQuartic(monic(b), monic(c), monic(d), monic(e));\n\n\tconst roots = isRationalZero(q) ? biquadraticRoots(p, r) : splitQuarticRoots(p, q, r, solveQuadratic);\n\tif (roots === null) return null;\n\n\t// Undo the depression. A zero shift is left off rather than added as `+0`,\n\t// which the simplifier would drop anyway but which reads better in a trace.\n\tconst shifted: SymbolicNode[] = isRationalZero(shift)\n\t\t? roots\n\t\t: roots.map(root => ({ kind: \"add\", left: constNode(shift), right: root }));\n\treturn { exact: distinct(shifted), approximate: [] };\n}\n\n/**\n * Drops repeated roots.\n *\n * A quartic that splits into two quadratics sharing a factor produces the same\n * root from both halves, and a repeated root is one solution rather than\n * several. Comparison is on the simplified structural key, so two roots written\n * differently but equal in structure count once.\n */\nfunction distinct(roots: readonly SymbolicNode[]): SymbolicNode[] {\n\tconst seen = new Set<string>();\n\tconst unique: SymbolicNode[] = [];\n\tfor (const root of roots) {\n\t\tconst key = symbolicKey(simplifySymbolic(root));\n\t\tif (seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tunique.push(root);\n\t}\n\treturn unique;\n}\n\n/**\n * The four roots of `t^4 + pt^2 + r`, as the square roots of the two solutions\n * of `y^2 + py + r`.\n *\n * The sign of each `y` decides whether its square roots are real or imaginary,\n * and that sign is determined exactly rather than by evaluating the surd: `y`\n * is `(-p ± sqrt(D))/2`, so the comparison reduces to the signs of `p` and `r`\n * alone. Deciding it numerically would be one rounding error away from claiming\n * a real root where there is a complex one.\n */\nfunction biquadraticRoots(p: Rational, r: Rational): SymbolicNode[] {\n\tconst discriminant = rationalSub(rationalMul(p, p), rationalMul(FOUR, r));\n\tif (rationalCompare(discriminant, RATIONAL_ZERO) < 0) return complexBiquadraticRoots(p, r);\n\n\tconst root = exactRationalSqrt(discriminant);\n\tif (root !== null) return rationalSquareRoots(rationalNeg(p), root, isRationalZero(discriminant));\n\treturn nestedSquareRoots(p, r, discriminant);\n}\n\n/** The four roots when both solutions of the inner quadratic are rational, so each square root is an ordinary surd. */\nfunction rationalSquareRoots(negatedP: Rational, root: Rational, repeated: boolean): SymbolicNode[] {\n\tconst values = repeated\n\t\t// A zero discriminant makes the two solutions the same one, and emitting it\n\t\t// twice would report `x^4-4x^2+4=0` as having four roots rather than two.\n\t\t? [rationalDiv(negatedP, TWO)]\n\t\t: [rationalDiv(rationalAdd(negatedP, root), TWO), rationalDiv(rationalSub(negatedP, root), TWO)];\n\n\tconst roots: SymbolicNode[] = [];\n\tfor (const value of values) {\n\t\tif (isRationalZero(value)) {\n\t\t\troots.push(constNode(RATIONAL_ZERO));\n\t\t\tcontinue;\n\t\t}\n\t\tconst square = signedSurdNode(value);\n\t\troots.push({ kind: \"neg\", operand: square }, square);\n\t}\n\treturn roots;\n}\n\n/**\n * The four roots when the inner quadratic is itself irrational, so each root is\n * a square root of a surd.\n *\n * `x^4-3x^2+1=0` comes out as `±sqrt((3+sqrt(5))/2)` and `±sqrt((3-sqrt(5))/2)`.\n * Nested, but exact and still readable, which is better than four decimals.\n *\n * Whether each solution is positive decides whether its square roots are real\n * or imaginary, and that is settled exactly rather than by evaluating the surd:\n * with `y = (-p ± sqrt(D))/2` the comparison reduces to the signs of `p` and\n * `r` alone. Deciding it numerically would be one rounding error away from\n * claiming a real root where there is a complex one.\n */\nfunction nestedSquareRoots(p: Rational, r: Rational, discriminant: Rational): SymbolicNode[] {\n\tconst negatedP = constNode(rationalNeg(p));\n\tconst surd = surdNode(discriminant);\n\tconst negativeP = rationalCompare(p, RATIONAL_ZERO) <= 0;\n\tconst solutions = [\n\t\t{ node: halved({ kind: \"add\", left: negatedP, right: surd }), positive: negativeP || rationalCompare(r, RATIONAL_ZERO) <= 0 },\n\t\t{ node: halved({ kind: \"sub\", left: negatedP, right: surd }), positive: negativeP && rationalCompare(r, RATIONAL_ZERO) >= 0 },\n\t];\n\n\tconst roots: SymbolicNode[] = [];\n\tfor (const { node, positive } of solutions) {\n\t\tconst radicand = positive ? node : { kind: \"neg\" as const, operand: node };\n\t\tconst magnitude: SymbolicNode = { kind: \"call\", name: \"sqrt\", args: [radicand] };\n\t\tconst square: SymbolicNode = positive ? magnitude : { kind: \"mul\", left: magnitude, right: complexNode(COMPLEX_I) };\n\t\troots.push({ kind: \"neg\", operand: square }, square);\n\t}\n\treturn roots;\n}\n\n/** Halves an expression, which the biquadratic formula needs twice. */\nfunction halved(node: SymbolicNode): SymbolicNode {\n\treturn { kind: \"div\", left: node, right: constNode(TWO) };\n}\n\n/**\n * The four roots of a biquadratic whose inner quadratic has no real solution.\n *\n * `y` is then `-p/2 ± i*sqrt(|D|)/2`, whose modulus is `sqrt(r)`, and\n * `sqrt(a+bi)` has real part `sqrt((|y|+a)/2)` and imaginary part\n * `sqrt((|y|-a)/2)`. Both of those radicands are non-negative here rather than\n * needing to be checked: `|y|` is `sqrt(r)` and `a` is `-p/2`, and a negative\n * discriminant is exactly the statement that `p^2 < 4r`, so `|y| > |a|`.\n *\n * When `sqrt(r)` is itself rational every component is a square root of a\n * rational and all four roots come out as ordinary surds. `x^4+1=0` is the case\n * worth having: its roots are `±sqrt(2)/2 ± sqrt(2)/2 i`, which no real-only\n * solver can report at all.\n *\n * When `sqrt(r)` is irrational the components nest one level, exactly as\n * {@link nestedSquareRoots} does for the real case. This used to decline\n * instead, which is how `x^4-2x^2+3=0` came to answer \"no real solutions\" while\n * its siblings `x^4+1`, `x^4+4` and `x^4-x^2+1` all returned four complex\n * roots. Same family, same shape of answer, and the difference was only whether\n * a `3` happened to be a perfect square.\n */\nfunction complexBiquadraticRoots(p: Rational, r: Rational): SymbolicNode[] {\n\tconst centre = rationalDiv(rationalNeg(p), TWO);\n\tconst modulus = exactRationalSqrt(r);\n\n\tconst re = modulus === null\n\t\t? nestedSurd(surdNode(r), centre)\n\t\t: surdNode(rationalDiv(rationalAdd(modulus, centre), TWO));\n\tconst imaginaryMagnitude = modulus === null\n\t\t? nestedSurd(surdNode(r), rationalNeg(centre))\n\t\t: surdNode(rationalDiv(rationalSub(modulus, centre), TWO));\n\n\tconst im: SymbolicNode = { kind: \"mul\", left: imaginaryMagnitude, right: complexNode(COMPLEX_I) };\n\tconst first: SymbolicNode = { kind: \"add\", left: re, right: im };\n\tconst second: SymbolicNode = { kind: \"sub\", left: re, right: im };\n\treturn [\n\t\t{ kind: \"neg\", operand: first },\n\t\t{ kind: \"neg\", operand: second },\n\t\tsecond,\n\t\tfirst,\n\t];\n}\n\n/**\n * `sqrt((surd + offset)/2)`, written so the offset's sign reads naturally.\n *\n * A negative offset becomes a subtraction rather than the addition of a\n * negative, so the radicand prints as `(sqrt(3)-1)/2` rather than\n * `(sqrt(3)+-1)/2`.\n */\nfunction nestedSurd(surd: SymbolicNode, offset: Rational): SymbolicNode {\n\tconst shifted: SymbolicNode = offset.n >= 0n\n\t\t? { kind: \"add\", left: surd, right: constNode(offset) }\n\t\t: { kind: \"sub\", left: surd, right: constNode(rationalNeg(offset)) };\n\treturn { kind: \"call\", name: \"sqrt\", args: [halved(shifted)] };\n}\n\n/**\n * The roots of a general depressed quartic, when its resolvent cubic splits it\n * into two quadratics over the rationals.\n *\n * `t^4+pt^2+qt+r` factors as `(t^2+at+B)(t^2-at+C)` exactly when `a^2` is a root\n * of the resolvent `z^3 + 2pz^2 + (p^2-4r)z - q^2`. A rational `z` whose square\n * root is also rational gives a factorization over the rationals, and each half\n * is then an ordinary quadratic with exact roots.\n *\n * @returns The four roots, or `null` when no such split exists.\n */\nfunction splitQuarticRoots(\n\tp: Rational,\n\tq: Rational,\n\tr: Rational,\n\tsolveQuadratic: (a: Rational, b: Rational, c: Rational) => readonly SymbolicNode[],\n): SymbolicNode[] | null {\n\tconst resolvent: Rational[] = [\n\t\t{ n: 1n, d: 1n },\n\t\trationalMul(TWO, p),\n\t\trationalSub(rationalMul(p, p), rationalMul(FOUR, r)),\n\t\trationalNeg(rationalMul(q, q)),\n\t];\n\n\tfor (const z of rationalRoots(resolvent)) {\n\t\tif (rationalCompare(z, RATIONAL_ZERO) <= 0) continue;\n\t\tconst alpha = exactRationalSqrt(z);\n\t\tif (alpha === null) continue;\n\n\t\t// beta + gamma = p + alpha^2 and gamma - beta = q/alpha.\n\t\tconst sum = rationalAdd(p, z);\n\t\tconst difference = rationalDiv(q, alpha);\n\t\tconst beta = rationalDiv(rationalSub(sum, difference), TWO);\n\t\tconst gamma = rationalDiv(rationalAdd(sum, difference), TWO);\n\n\t\tconst one: Rational = { n: 1n, d: 1n };\n\t\treturn [\n\t\t\t...solveQuadratic(one, alpha, beta),\n\t\t\t...solveQuadratic(one, rationalNeg(alpha), gamma),\n\t\t];\n\t}\n\treturn null;\n}\n","/**\n * Every root of a polynomial at once, found numerically in the complex plane.\n *\n * ## Why not sequential deflation\n *\n * The obvious way to find several roots is to find one, divide the polynomial\n * by `(x - root)`, and solve what is left. Each division carries the first\n * root's error into every coefficient of the quotient, so the second root is\n * found from a polynomial that is no longer quite the one that was asked\n * about, and the error compounds down the chain. That is not a theoretical\n * objection. Solving `x^5-x=0` that way answered with `-1` twice, once as `-1`\n * and once as `-1.0000000000004656`, and dropped both complex roots on the way,\n * because a real-only scan for sign changes cannot see them at all.\n *\n * Durand-Kerner (also called the Weierstrass method) moves every estimate at\n * once instead. Each one steps by `p(z_i)` over the product of its distances\n * from the others, which is Newton's method applied to the whole factorization\n * rather than to one factor of it. No coefficient is ever recomputed, so\n * nothing accumulates, and the arithmetic is complex from the first step, so a\n * conjugate pair is found rather than missed.\n *\n * ## Why the input is made square-free first\n *\n * A repeated root is where every simultaneous method loses precision. A double\n * root is only ever located to about the square root of machine epsilon, and\n * the two estimates converging on it arrive straddling the true value rather\n * than on top of it. The usual repair is to cluster the output and read a\n * multiplicity off the cluster size, which is a numerical answer to something\n * the exact arithmetic upstream can remove outright: `gcd(p, p')` is precisely\n * the repeated part, so `p` divided by it has the same roots with every one of\n * them simple. That division happens over the rationals, so what reaches the\n * iteration is a polynomial whose roots are as well separated as they can be.\n *\n * Near-equal output is still merged, but as a check that the iteration\n * separated what it was handed rather than as the mechanism for multiplicity.\n * Two estimates landing on the same value now means the run failed, and\n * {@link approximateRoots} says so by returning `null` instead of quietly\n * reporting one root fewer than the polynomial has.\n */\n\nimport { type Rational, rationalToNumber } from \"@solve-js/symbolic/Rational\";\nimport { squareFreePart } from \"@solve-js/symbolic/Gcd\";\n\n/**\n * One numerically-found root.\n *\n * Complex because the roots of a real polynomial are, and reporting only the\n * real ones is how `x^5-1=0` came to answer with `1` and nothing else.\n */\nexport interface ApproximateRoot {\n\t/** Real part. */\n\treadonly re: number;\n\t/**\n\t * Imaginary part.\n\t *\n\t * Exactly zero for a root on the real line rather than the rounding\n\t * residue an iteration in complex arithmetic leaves behind, so a caller can\n\t * test it without choosing a tolerance of its own.\n\t */\n\treadonly im: number;\n}\n\n/**\n * Iteration ceiling for {@link approximateRoots}.\n *\n * Durand-Kerner converges quadratically once the estimates separate, so a run\n * that has not settled within this many passes is diverging rather than being\n * slow, and continuing would only spend time before failing anyway.\n */\nexport const DURAND_KERNER_MAX_ITERATIONS = 200;\n\n/**\n * Relative step size below which the iteration is considered settled.\n *\n * Scaled by the largest estimate, so it means the same thing for roots near\n * zero and roots in the hundreds.\n */\nexport const DURAND_KERNER_TOLERANCE = 1e-14;\n\n/**\n * How large a residual a root may leave and still be accepted, relative to the\n * magnitude Horner's method accumulated on the way to it.\n *\n * This is a backward-error test: it asks whether the value is a root of a\n * polynomial within rounding distance of the one given, which is the strongest\n * statement double precision can support. An absolute threshold cannot do the\n * job, since `p(z)` for a degree-eight polynomial with coefficients in the\n * thousands is numerically large even at a perfect root.\n */\nexport const ROOT_RESIDUAL_TOLERANCE = 1e-10;\n\n/**\n * How close two estimates may come before they are treated as the same root.\n *\n * The polynomial handed to the iteration is square-free, so all of its roots\n * are simple and a converged pair should be separated by their true distance.\n * Two estimates this close have collapsed onto one root, leaving another\n * undiscovered, which is reported rather than hidden.\n */\nexport const ROOT_SEPARATION_TOLERANCE = 1e-10;\n\n/**\n * How small a component must be, relative to the root's magnitude, to be\n * rounding residue rather than part of the answer.\n *\n * A simple root of a real polynomial is either on an axis or a bounded distance\n * from it, so there is no middle ground to get wrong here. The candidate is\n * confirmed by residual before the component is dropped, so this only decides\n * what is worth trying.\n */\nconst AXIS_SNAP_TOLERANCE = 1e-9;\n\n/**\n * How far two estimates may be from being each other's conjugate and still be\n * averaged into an exact pair.\n *\n * Generous, because for a polynomial with real coefficients the root set is\n * closed under conjugation as a matter of algebra: every non-real root has an\n * exact partner in the set, and the iteration finds it to within its own\n * convergence. This only guards against pairing a root that has no partner.\n */\nconst CONJUGATE_PAIR_TOLERANCE = 1e-8;\n\n/** How many Newton steps re-converge a root after a component is dropped. */\nconst NEWTON_POLISH_STEPS = 4;\n\n/** A complex number as two doubles, the working type of the iteration. */\ninterface Cpx {\n\treadonly re: number;\n\treadonly im: number;\n}\n\n/** `a - b`. */\nfunction subtract(a: Cpx, b: Cpx): Cpx {\n\treturn { re: a.re - b.re, im: a.im - b.im };\n}\n\n/** `a * b`. */\nfunction multiply(a: Cpx, b: Cpx): Cpx {\n\treturn { re: a.re * b.re - a.im * b.im, im: a.re * b.im + a.im * b.re };\n}\n\n/**\n * `a / b`, by Smith's method.\n *\n * Dividing through by the larger component rather than by `|b|^2` keeps the\n * intermediate from overflowing when both components are large, which the\n * naive form does for magnitudes past about 1e154. The iteration divides by a\n * product of up to seven differences, so that is reachable rather than\n * hypothetical.\n */\nfunction divide(a: Cpx, b: Cpx): Cpx {\n\tif (Math.abs(b.re) >= Math.abs(b.im)) {\n\t\tconst ratio = b.im / b.re;\n\t\tconst denominator = b.re + b.im * ratio;\n\t\treturn { re: (a.re + a.im * ratio) / denominator, im: (a.im - a.re * ratio) / denominator };\n\t}\n\tconst ratio = b.re / b.im;\n\tconst denominator = b.re * ratio + b.im;\n\treturn { re: (a.re * ratio + a.im) / denominator, im: (a.im * ratio - a.re) / denominator };\n}\n\n/** `|z|`. */\nfunction magnitude(z: Cpx): number {\n\treturn Math.hypot(z.re, z.im);\n}\n\n/** Evaluates real descending coefficients at a complex point, by Horner's method. */\nfunction evaluateAt(descending: readonly number[], z: Cpx): Cpx {\n\tlet re = 0;\n\tlet im = 0;\n\tfor (const coefficient of descending) {\n\t\tconst nextRe = re * z.re - im * z.im + coefficient;\n\t\tim = re * z.im + im * z.re;\n\t\tre = nextRe;\n\t}\n\treturn { re, im };\n}\n\n/**\n * The magnitude Horner's method accumulates on the way to `p(z)`.\n *\n * This is the scale a residual has to be judged against: it is what `|p(z)|`\n * would be if every rounding error in the evaluation happened to add rather\n * than cancel, so a residual below it says the value is a root as far as double\n * precision can distinguish.\n */\nfunction evaluationScale(descending: readonly number[], z: Cpx): number {\n\tconst radius = magnitude(z);\n\tlet total = 0;\n\tfor (const coefficient of descending) total = total * radius + Math.abs(coefficient);\n\treturn total;\n}\n\n/** Descending coefficients of the derivative. */\nfunction differentiate(descending: readonly number[]): number[] {\n\tconst degree = descending.length - 1;\n\tconst derivative: number[] = [];\n\tfor (let i = 0; i < degree; i++) derivative.push(descending[i] * (degree - i));\n\treturn derivative;\n}\n\n/**\n * The square-free part of a polynomial, as monic descending doubles.\n *\n * @param descending - Descending exact coefficients.\n * @returns The coefficients, or `null` when one of them has no finite double\n * value, which would make every comparison below meaningless.\n */\nfunction squareFreeDoubles(descending: readonly Rational[]): number[] | null {\n\t// `Gcd.ts` works in ascending order and returns a monic result, which is\n\t// what the iteration wants anyway.\n\tconst ascending = [...descending].reverse();\n\tconst squareFree = [...squareFreePart(ascending)].reverse();\n\n\tconst doubles = squareFree.map(rationalToNumber);\n\tif (doubles.some(value => !Number.isFinite(value))) return null;\n\treturn doubles;\n}\n\n/**\n * Starting estimates spread around the circle the roots must lie inside.\n *\n * Two details are load-bearing. The circle is centred on `-a1/n`, the mean of\n * the roots, rather than on the origin, so the estimates start near their\n * targets for a polynomial whose roots are all off to one side. And every angle\n * is offset by half a step, which keeps all `n` of them off the real axis: a\n * real estimate of a real polynomial stays real forever, since every quantity\n * in its update is real, so a conjugate pair started on the axis would have no\n * way to leave it.\n */\nfunction initialEstimates(monic: readonly number[]): Cpx[] {\n\tconst degree = monic.length - 1;\n\n\t// Cauchy's bound: every root of a monic polynomial lies within 1 + max|a_k|.\n\tlet largest = 0;\n\tfor (let i = 1; i < monic.length; i++) largest = Math.max(largest, Math.abs(monic[i]));\n\tconst radius = 1 + largest;\n\tconst centre = -monic[1] / degree;\n\n\tconst estimates: Cpx[] = [];\n\tfor (let k = 0; k < degree; k++) {\n\t\tconst angle = (2 * Math.PI * k) / degree + Math.PI / (2 * degree);\n\t\testimates.push({ re: centre + radius * Math.cos(angle), im: radius * Math.sin(angle) });\n\t}\n\treturn estimates;\n}\n\n/**\n * Runs the Durand-Kerner iteration to convergence.\n *\n * Estimates are updated in place as the sweep goes, so each one sees the\n * already-improved values of those before it. That is the Gauss-Seidel form of\n * the method and it converges in noticeably fewer sweeps than recomputing every\n * estimate from the previous round.\n *\n * @param monic - Monic descending coefficients of a square-free polynomial.\n * @returns The estimates, or `null` when the iteration did not settle.\n */\nfunction durandKerner(monic: readonly number[]): Cpx[] | null {\n\tconst degree = monic.length - 1;\n\tconst estimates = initialEstimates(monic);\n\n\tfor (let iteration = 0; iteration < DURAND_KERNER_MAX_ITERATIONS; iteration++) {\n\t\tlet largestStep = 0;\n\t\tlet largestRoot = 1;\n\n\t\tfor (let i = 0; i < degree; i++) {\n\t\t\tlet denominator: Cpx = { re: 1, im: 0 };\n\t\t\tfor (let j = 0; j < degree; j++) {\n\t\t\t\tif (i !== j) denominator = multiply(denominator, subtract(estimates[i], estimates[j]));\n\t\t\t}\n\n\t\t\t// Two estimates have landed on each other. Nudging one apart lets the\n\t\t\t// sweep continue, where dividing by zero would poison every later\n\t\t\t// value with NaN and lose the roots that had already converged.\n\t\t\tif (denominator.re === 0 && denominator.im === 0) {\n\t\t\t\testimates[i] = { re: estimates[i].re + 1e-6 * (i + 1), im: estimates[i].im + 1e-6 };\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst step = divide(evaluateAt(monic, estimates[i]), denominator);\n\t\t\tif (!Number.isFinite(step.re) || !Number.isFinite(step.im)) return null;\n\n\t\t\testimates[i] = subtract(estimates[i], step);\n\t\t\tlargestStep = Math.max(largestStep, magnitude(step));\n\t\t\tlargestRoot = Math.max(largestRoot, magnitude(estimates[i]));\n\t\t}\n\n\t\tif (largestStep <= DURAND_KERNER_TOLERANCE * largestRoot) return estimates;\n\t}\n\treturn null;\n}\n\n/** Re-converges a value with Newton's method, used after a component is dropped. */\nfunction polish(monic: readonly number[], derivative: readonly number[], start: Cpx): Cpx {\n\tlet candidate = start;\n\tfor (let step = 0; step < NEWTON_POLISH_STEPS; step++) {\n\t\tconst slope = evaluateAt(derivative, candidate);\n\t\tif (slope.re === 0 && slope.im === 0) break;\n\t\tconst next = subtract(candidate, divide(evaluateAt(monic, candidate), slope));\n\t\tif (!Number.isFinite(next.re) || !Number.isFinite(next.im)) break;\n\t\tcandidate = next;\n\t}\n\treturn candidate;\n}\n\n/**\n * Drops a component that is rounding residue rather than part of the answer,\n * re-converging the value onto the axis.\n *\n * Two doubles either side of the same true root are equally correct as far as\n * arithmetic goes, so this is choosing between them on how they read: `i`\n * rather than `-0.0000000000000000122+i`, and `-0.7548776662` rather than the\n * same number with a stray imaginary trace on it. What makes that safe rather\n * than cosmetic is the residual test: the snapped value is kept only when it\n * still satisfies the polynomial to within {@link ROOT_RESIDUAL_TOLERANCE}, so\n * a root with a genuinely small component is never flattened onto an axis.\n *\n * @param monic - Monic descending coefficients.\n * @param derivative - Their derivative, so it is differentiated once per call rather than once per root.\n * @param z - The converged estimate.\n * @returns The estimate, with a negligible component replaced by an exact zero\n * where the polynomial allows it.\n */\nfunction snapToAxes(monic: readonly number[], derivative: readonly number[], z: Cpx): Cpx {\n\tconst scale = Math.max(1, magnitude(z));\n\n\tif (z.im !== 0 && Math.abs(z.im) <= AXIS_SNAP_TOLERANCE * scale) {\n\t\t// Every quantity is real from here, so Newton's method on a real starting\n\t\t// point stays on the real line by construction.\n\t\tconst candidate = polish(monic, derivative, { re: z.re, im: 0 });\n\t\tif (isRootWithinTolerance(monic, candidate)) return { re: candidate.re, im: 0 };\n\t}\n\tif (z.re !== 0 && Math.abs(z.re) <= AXIS_SNAP_TOLERANCE * scale) {\n\t\tconst candidate = polish(monic, derivative, { re: 0, im: z.im });\n\t\tif (isRootWithinTolerance(monic, candidate)) return { re: 0, im: candidate.im };\n\t}\n\treturn z;\n}\n\n/** Whether a value satisfies the polynomial to within the backward error double precision allows. */\nfunction isRootWithinTolerance(monic: readonly number[], z: Cpx): boolean {\n\tif (!Number.isFinite(z.re) || !Number.isFinite(z.im)) return false;\n\treturn magnitude(evaluateAt(monic, z)) <= ROOT_RESIDUAL_TOLERANCE * evaluationScale(monic, z);\n}\n\n/**\n * Replaces each conjugate pair with an exactly-conjugate one.\n *\n * A polynomial with real coefficients has a root set closed under conjugation,\n * so the two estimates of a pair are two independent measurements of one\n * quantity and averaging them is strictly the better estimate of both. It also\n * removes an artefact worth removing on its own: without this the two halves of\n * a pair differ in their last bit, which is enough to order them by real part\n * and print `-0.7071067812+0.7071067812i` above its own conjugate rather than\n * below it.\n *\n * A root with no partner within {@link CONJUGATE_PAIR_TOLERANCE} is left as it\n * is, which is what keeps a real root, whose own conjugate is itself and so\n * lies nowhere near any other estimate, from being dragged into a pair it does\n * not belong to.\n */\nfunction pairConjugates(roots: readonly Cpx[]): Cpx[] {\n\tconst result = [...roots];\n\tconst paired = result.map(root => root.im === 0);\n\n\tfor (let i = 0; i < result.length; i++) {\n\t\tif (paired[i]) continue;\n\t\tconst wanted: Cpx = { re: result[i].re, im: -result[i].im };\n\n\t\tlet partner = -1;\n\t\tlet closest = Number.POSITIVE_INFINITY;\n\t\tfor (let j = i + 1; j < result.length; j++) {\n\t\t\tif (paired[j]) continue;\n\t\t\tconst distance = magnitude(subtract(result[j], wanted));\n\t\t\tif (distance < closest) {\n\t\t\t\tclosest = distance;\n\t\t\t\tpartner = j;\n\t\t\t}\n\t\t}\n\t\tif (partner === -1 || closest > CONJUGATE_PAIR_TOLERANCE * Math.max(1, magnitude(result[i]))) continue;\n\n\t\tconst re = (result[i].re + result[partner].re) / 2;\n\t\tconst im = (Math.abs(result[i].im) + Math.abs(result[partner].im)) / 2;\n\t\tconst sign = result[i].im < 0 ? -1 : 1;\n\t\tresult[i] = { re, im: sign * im };\n\t\tresult[partner] = { re, im: -sign * im };\n\t\tpaired[i] = true;\n\t\tpaired[partner] = true;\n\t}\n\treturn result;\n}\n\n/**\n * Whether every estimate is far enough from every other to be a distinct root.\n *\n * See {@link ROOT_SEPARATION_TOLERANCE} for why a collision is a failure here\n * rather than a multiplicity.\n */\nfunction allSeparated(roots: readonly Cpx[]): boolean {\n\tfor (let i = 0; i < roots.length; i++) {\n\t\tfor (let j = i + 1; j < roots.length; j++) {\n\t\t\tconst scale = Math.max(1, magnitude(roots[i]), magnitude(roots[j]));\n\t\t\tif (magnitude(subtract(roots[i], roots[j])) <= ROOT_SEPARATION_TOLERANCE * scale) return false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/**\n * Every root of a polynomial, found numerically.\n *\n * Roots are returned in ascending order of real part, then imaginary part, so\n * two runs on the same input read identically and a conjugate pair reads\n * negative-first like every other pair the solver produces.\n *\n * @param descending - Descending exact coefficients, the leading one non-zero.\n * @returns One entry per **distinct** root, matching the solver's convention\n * that a repeated root is one solution rather than several. `null` when the\n * iteration did not converge, did not separate its estimates, or left a root\n * with too large a residual, so that a caller reports the shortfall rather than\n * presenting a partial list as a complete one.\n */\nexport function approximateRoots(descending: readonly Rational[]): ApproximateRoot[] | null {\n\tconst monic = squareFreeDoubles(descending);\n\tif (monic === null) return null;\n\tif (monic.length < 2) return [];\n\n\tconst converged = durandKerner(monic);\n\tif (converged === null) return null;\n\n\t// Pairing first, then snapping: the two halves of a pair come out of pairing\n\t// with the same real part and opposite imaginary ones, so any snap applies to\n\t// both alike and the pair stays exactly conjugate.\n\tconst derivative = differentiate(monic);\n\tconst roots = pairConjugates(converged).map(root => snapToAxes(monic, derivative, root));\n\n\tfor (const root of roots) {\n\t\tif (!isRootWithinTolerance(monic, root)) return null;\n\t}\n\tif (!allSeparated(roots)) return null;\n\n\treturn [...roots].sort((a, b) => a.re - b.re || a.im - b.im);\n}\n","/**\n * Solving a polynomial equation for one variable.\n *\n * ## The order of attack, and why it is this order\n *\n * Exact answers first, approximation only as a last resort and always labelled\n * as such.\n *\n * 1. `x` itself, as many times as it divides the polynomial. This step exists\n * because the rational-root theorem is stated for a **non-zero** constant\n * term, so without it `x^5-x=0` found no rational roots at all and fell\n * straight through to numerics, despite every one of its five roots being\n * exact. Dividing `x` out first is what turns that equation back into\n * `x^4-1`, whose roots are `±1` and then `±i`.\n * 2. Every rational root, by the same rational-root theorem `Factor.ts` uses,\n * each divided out **exactly** over the rationals with its full\n * multiplicity. In floating point a near-root and a real root are\n * indistinguishable, which is the whole reason `Rational.ts` exists.\n * 3. The closed form for whatever degree survives: the quadratic formula,\n * Cardano for a cubic, and the biquadratic or resolvent-cubic split for a\n * quartic.\n * 4. Only a remainder that none of those reaches goes to `NumericRoots.ts`,\n * which finds **all** of its roots at once in the complex plane.\n *\n * A quadratic with a positive non-square discriminant returns its **surd**\n * form, so `x^2-2=0` gives `sqrt(2)` rather than `1.41421356`. A system that\n * advertises exact arithmetic and then hands back a rounded decimal has quietly\n * stopped being one. The surd is reduced to lowest form, so the equal but\n * unreadable `sqrt(8)/2` does not surface.\n *\n * ## Complex roots are roots\n *\n * `x^2+1=0` gives `-i` and `i`, and the numerical stage works in complex\n * arithmetic throughout rather than scanning the real line for sign changes.\n * A real-only scan is why `solve(x^5-1=0, x)` used to answer with `1` and\n * nothing else: the other four roots are complex, the scan could not see them,\n * and one root out of five was reported as though it were the whole answer.\n *\n * ## Every root is accounted for\n *\n * Each stage records how much of the degree it consumed. When those do not add\n * up to the degree of the equation, the outcome is `incomplete` rather than\n * `roots`, and it carries how many are missing. A partial list presented as a\n * complete one is the worst answer available here, because nothing about it\n * looks wrong.\n *\n * ## What is deliberately not here\n *\n * The *casus irreducibilis*: a cubic with three distinct real roots and no\n * rational one. Those roots provably cannot be written in real radicals, so\n * `CubicQuartic.ts` returns them numerically and this module labels them\n * approximate. See that module's header for why the trigonometric form is not\n * dressed up as an exact answer.\n *\n * A general quartic that neither is biquadratic nor splits into two rational\n * quadratics. Ferrari's method reaches it, but through a radical nested four\n * deep that nothing downstream could read or use, so its roots come back\n * numerically instead.\n *\n * A quintic's radicals, which by Abel-Ruffini do not exist in general, and the\n * cyclotomic forms that do exist for the special cases such as `x^5-1`. Those\n * nest deeply enough that four accurate decimals are the more useful answer.\n */\n\nimport {\n\ttype SymbolicNode,\n\tconstNode,\n\tcomplexNode,\n} from \"@solve-js/symbolic/SymbolicNode\";\nimport {\n\ttype Rational,\n\tRATIONAL_ZERO,\n\trationalAdd,\n\trationalMul,\n\trationalDiv,\n\trationalNeg,\n\trationalSub,\n\trationalCompare,\n\tisRationalZero,\n} from \"@solve-js/symbolic/Rational\";\nimport {\n\ttype Polynomial,\n\ttoPolynomial,\n\tfromPolynomial,\n\tpolyDegree,\n\tpolyCoefficients,\n} from \"@solve-js/symbolic/Polynomial\";\nimport { rationalRoots } from \"@solve-js/symbolic/Factor\";\nimport { COMPLEX_I, complex as complexValue } from \"@solve-js/symbolic/Complex\";\nimport { exactIntegerSqrt, surdNode } from \"@solve-js/symbolic/Radicals\";\nimport { type RootSet, solveCubic, solveQuartic } from \"@solve-js/symbolic/CubicQuartic\";\nimport { type ApproximateRoot, approximateRoots } from \"@solve-js/symbolic/NumericRoots\";\n\n/**\n * Highest polynomial degree {@link solveForVariable} will attempt.\n *\n * Beyond this the numerical fallback's interval scan becomes the dominant cost\n * and the answers get progressively less trustworthy, so declining is better\n * than a slow guess.\n */\nexport const SOLVE_MAX_DEGREE = 8;\n\n/**\n * The outcome of solving an equation.\n *\n * Several of these are answers rather than failures: an identity is the correct\n * response to `x+1=x+1`, and a contradiction to `1=2`.\n *\n * There is deliberately no \"no real solutions\" case. Every polynomial of degree\n * `n` has `n` roots over the complex numbers, and this solver reports them, so\n * the only honest ways to answer are the complete list, a stated shortfall, or\n * a stated refusal.\n */\nexport type SolveOutcome =\n\t/** Every solution. `exact` carries those expressible as a rational, a surd or a Gaussian rational; `approximate` carries any found numerically. */\n\t| { kind: \"roots\"; readonly exact: readonly SymbolicNode[]; readonly approximate: readonly ApproximateRoot[] }\n\t/**\n\t * Some solutions, and the count of those this solver could not reach.\n\t *\n\t * Distinct from `roots` so that a caller cannot present a partial list as a\n\t * whole one by accident, which is the failure this case exists to stop.\n\t */\n\t| {\n\t\tkind: \"incomplete\";\n\t\treadonly exact: readonly SymbolicNode[];\n\t\treadonly approximate: readonly ApproximateRoot[];\n\t\t/** How many roots, counted with multiplicity, are unaccounted for. */\n\t\treadonly missing: number;\n\t\t/** Why they are, in a sentence fit to show a reader. */\n\t\treadonly reason: string;\n\t}\n\t/** True for every value of the variable, as for `x+1=x+1`. */\n\t| { kind: \"identity\" }\n\t/** True for no value of the variable, as for `x=x+1`. */\n\t| { kind: \"contradiction\" }\n\t/** Outside what this module attempts, with the reason stated. */\n\t| { kind: \"unsupported\"; readonly reason: string };\n\n/** Evaluates descending-order coefficients at a rational point, by Horner's method. */\nfunction evaluateRational(descending: readonly Rational[], x: Rational): Rational {\n\tlet total = RATIONAL_ZERO;\n\tfor (const coeff of descending) total = rationalAdd(rationalMul(total, x), coeff);\n\treturn total;\n}\n\n/** Divides descending-order coefficients by `(x - root)`, discarding the remainder. Only call with a confirmed root. */\nfunction divideByRoot(descending: readonly Rational[], root: Rational): Rational[] {\n\tconst quotient: Rational[] = [descending[0]];\n\tfor (let i = 1; i < descending.length - 1; i++) {\n\t\tquotient.push(rationalAdd(descending[i], rationalMul(quotient[i - 1], root)));\n\t}\n\treturn quotient;\n}\n\n/**\n * Solves `ax^2 + bx + c = 0` over the complex numbers.\n *\n * A negative discriminant gives a conjugate pair rather than nothing. That is\n * what a quadratic actually has, and reporting \"no real solutions\" instead was\n * a limitation of not having a complex number to say it with.\n *\n * @returns The exact roots: rational constants for a perfect-square\n * discriminant, surds for a positive non-square one, and complex values for a\n * negative one.\n */\nfunction solveQuadratic(a: Rational, b: Rational, c: Rational): SymbolicNode[] {\n\t// discriminant = b^2 - 4ac\n\tconst discriminant = rationalSub(rationalMul(b, b), rationalMul(rational4(), rationalMul(a, c)));\n\tconst twoA = rationalMul(rational2(), a);\n\n\tif (rationalCompare(discriminant, RATIONAL_ZERO) < 0) {\n\t\treturn complexQuadraticRoots(rationalNeg(b), discriminant, twoA);\n\t}\n\tif (isRationalZero(discriminant)) return [constNode(rationalDiv(rationalNeg(b), twoA))];\n\n\t// A perfect-square discriminant needs both numerator and denominator to be\n\t// perfect squares, since the rational's own square root is taken componentwise.\n\tconst rootN = exactIntegerSqrt(discriminant.n);\n\tconst rootD = exactIntegerSqrt(discriminant.d);\n\tif (rootN !== null && rootD !== null) {\n\t\tconst root: Rational = { n: rootN, d: rootD };\n\t\tconst plus = rationalDiv(rationalAdd(rationalNeg(b), root), twoA);\n\t\tconst minus = rationalDiv(rationalSub(rationalNeg(b), root), twoA);\n\t\t// Ascending, so a pair of roots always reads low to high.\n\t\treturn rationalCompare(minus, plus) <= 0 ? [constNode(minus), constNode(plus)] : [constNode(plus), constNode(minus)];\n\t}\n\n\t// Irrational but real: return the surd rather than a decimal.\n\tconst surd = surdNode(discriminant);\n\t// Subtracting the surd gives the smaller root when the leading coefficient\n\t// is positive, so this ordering matches the rational case above.\n\tconst ascending = rationalCompare(twoA, RATIONAL_ZERO) > 0;\n\tconst lower: SymbolicNode = { kind: \"div\", left: { kind: \"sub\", left: constNode(rationalNeg(b)), right: surd }, right: constNode(twoA) };\n\tconst upper: SymbolicNode = { kind: \"div\", left: { kind: \"add\", left: constNode(rationalNeg(b)), right: surd }, right: constNode(twoA) };\n\treturn ascending ? [lower, upper] : [upper, lower];\n}\n\n/**\n * The conjugate pair for a quadratic whose discriminant is negative.\n *\n * `sqrt(D)` for negative `D` is `sqrt(-D) * i`, so the roots are\n * `(-b ± sqrt(|D|) i) / 2a`. When `sqrt(|D|)` is rational the whole root is a\n * Gaussian rational and comes back as a single exact complex value; otherwise\n * the irrational part stays as a surd multiplied by `i`.\n *\n * The negative root is returned first, matching the ordering the real cases use.\n *\n * @param negatedB - `-b`, already negated by the caller.\n * @param discriminant - The negative discriminant.\n * @param twoA - `2a`.\n * @returns The two roots.\n */\nfunction complexQuadraticRoots(negatedB: Rational, discriminant: Rational, twoA: Rational): SymbolicNode[] {\n\tconst magnitude = rationalNeg(discriminant);\n\tconst rootN = exactIntegerSqrt(magnitude.n);\n\tconst rootD = exactIntegerSqrt(magnitude.d);\n\n\tif (rootN !== null && rootD !== null) {\n\t\t// Everything stays in the Gaussian rationals, so each root is one exact\n\t\t// complex value rather than an expression.\n\t\tconst imaginary = rationalDiv({ n: rootN, d: rootD }, twoA);\n\t\tconst real = rationalDiv(negatedB, twoA);\n\t\treturn [\n\t\t\tcomplexNode(complexValue(real, rationalNeg(imaginary))),\n\t\t\tcomplexNode(complexValue(real, imaginary)),\n\t\t];\n\t}\n\n\t// The imaginary part is irrational, so it keeps its surd form times `i`.\n\t//\n\t// The division by `2a` is folded into the radicand rather than left outside\n\t// it: `sqrt(m)/2a` is `sqrt(m/(2a)^2)`, which reduces. Building it the naive\n\t// way leaves `-2*sqrt(2)*i/2` for `x^2+2=0`, since the simplifier's\n\t// common-factor cancellation cannot see a `2` buried inside a surd's own\n\t// coefficient. Doing the algebra here instead gives `-sqrt(2)*i`.\n\tconst real = rationalDiv(negatedB, twoA);\n\tconst scaledRadicand = rationalDiv(magnitude, rationalMul(twoA, twoA));\n\tconst imaginary: SymbolicNode = { kind: \"mul\", left: surdNode(scaledRadicand), right: complexNode(COMPLEX_I) };\n\n\tif (isRationalZero(real)) {\n\t\treturn [{ kind: \"neg\", operand: imaginary }, imaginary];\n\t}\n\treturn [\n\t\t{ kind: \"sub\", left: constNode(real), right: imaginary },\n\t\t{ kind: \"add\", left: constNode(real), right: imaginary },\n\t];\n}\n\n/** The rational two, built once per call rather than exported, since it is only needed here. */\nfunction rational2(): Rational {\n\treturn { n: 2n, d: 1n };\n}\n\n/** The rational four. */\nfunction rational4(): Rational {\n\treturn { n: 4n, d: 1n };\n}\n\n/** A real number as an {@link ApproximateRoot}, for the *casus irreducibilis* roots that arrive from `CubicQuartic.ts` as plain doubles. */\nfunction realApproximation(value: number): ApproximateRoot {\n\treturn { re: value, im: 0 };\n}\n\n/**\n * Solves `lhs = rhs` for one variable over the complex numbers.\n *\n * @param lhs - Left-hand side of the equation.\n * @param rhs - Right-hand side.\n * @param variable - The variable to solve for.\n * @returns The outcome. See {@link SolveOutcome}; several of its cases are\n * answers rather than failures.\n */\nexport function solveForVariable(lhs: SymbolicNode, rhs: SymbolicNode, variable: string): SolveOutcome {\n\tconst polynomial = toPolynomial({ kind: \"sub\", left: lhs, right: rhs });\n\tif (polynomial === null) {\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\treason: \"this is not a polynomial equation (it divides by an unknown, or calls a function of one)\",\n\t\t};\n\t}\n\n\tconst others = polynomial.vars.filter(name => name !== variable);\n\tconst degree = polyDegree(polynomial, variable);\n\n\tif (others.length > 0) {\n\t\t// With another unknown present the roots are themselves expressions in\n\t\t// it. That is only worth doing, and only reliably correct, in the linear\n\t\t// case; anything higher would need the quadratic formula over symbolic\n\t\t// coefficients including a symbolic discriminant sign.\n\t\tif (degree !== 1) {\n\t\t\treturn {\n\t\t\t\tkind: \"unsupported\",\n\t\t\t\treason: `solving for \"${variable}\" needs the equation to be linear in it when other unknowns (${others.join(\", \")}) are present`,\n\t\t\t};\n\t\t}\n\t\treturn solveLinearWithOtherUnknowns(polynomial, variable);\n\t}\n\n\tif (degree === 0) {\n\t\treturn polynomial.terms.size === 0 ? { kind: \"identity\" } : { kind: \"contradiction\" };\n\t}\n\tif (degree > SOLVE_MAX_DEGREE) {\n\t\treturn { kind: \"unsupported\", reason: `degree ${degree} is above the supported maximum of ${SOLVE_MAX_DEGREE}` };\n\t}\n\n\tconst descending = [...polyCoefficients(polynomial, variable)].reverse();\n\treturn solveUnivariate(descending);\n}\n\n/** Solves `a*x + b = 0` where `a` and `b` may themselves involve other unknowns. */\nfunction solveLinearWithOtherUnknowns(polynomial: Polynomial, variable: string): SolveOutcome {\n\t// Split terms into those carrying exactly one power of the variable and\n\t// those carrying none, then x = -constantPart / coefficientPart.\n\tconst coefficientTerms = new Map<string, Rational>();\n\tconst constantTerms = new Map<string, Rational>();\n\tfor (const [key, coeff] of polynomial.terms) {\n\t\tconst factors = key.split(\"*\").filter(part => part.length > 0);\n\t\tconst index = factors.indexOf(variable);\n\t\tif (index === -1) {\n\t\t\tconstantTerms.set(key, coeff);\n\t\t} else {\n\t\t\tfactors.splice(index, 1);\n\t\t\tcoefficientTerms.set(factors.join(\"*\"), coeff);\n\t\t}\n\t}\n\n\tconst namesOf = (terms: Map<string, Rational>): string[] => {\n\t\tconst names = new Set<string>();\n\t\tfor (const key of terms.keys()) {\n\t\t\tfor (const part of key.split(\"*\")) {\n\t\t\t\tif (part.length > 0) names.add(part.split(\"^\")[0]);\n\t\t\t}\n\t\t}\n\t\treturn [...names].sort();\n\t};\n\n\tconst coefficient = fromPolynomial({ terms: coefficientTerms, vars: namesOf(coefficientTerms) });\n\tconst constant = fromPolynomial({ terms: constantTerms, vars: namesOf(constantTerms) });\n\treturn {\n\t\tkind: \"roots\",\n\t\texact: [{ kind: \"div\", left: { kind: \"neg\", operand: constant }, right: coefficient }],\n\t\tapproximate: [],\n\t};\n}\n\n/**\n * The closed form for a leftover cubic or quartic, when one exists.\n *\n * Reached only after every rational root has been divided out, so what arrives\n * here genuinely needs radicals. A cubic always has a closed form of some kind;\n * a quartic has one only in the two families {@link solveQuartic} covers.\n *\n * @param descending - Descending coefficients of the leftover polynomial.\n * @returns The roots, or `null` when the numerical fallback should take over.\n */\nfunction closedFormRoots(descending: readonly Rational[]): RootSet | null {\n\tif (descending.length === 4) {\n\t\treturn solveCubic(descending[0], descending[1], descending[2], descending[3]);\n\t}\n\tif (descending.length === 5) {\n\t\treturn solveQuartic(descending[0], descending[1], descending[2], descending[3], descending[4], solveQuadratic);\n\t}\n\treturn null;\n}\n\n/**\n * The rational roots of a polynomial and the factor left once they are gone.\n *\n * `x` comes out first because the rational-root theorem needs a non-zero\n * constant term to say anything at all. Skipping that step is the single defect\n * that made `x^5-x=0` and `x^3-x=0` numerical problems: with a zero constant\n * term {@link rationalRoots} correctly reports no candidates, and the whole\n * equation then fell past every exact method it should have used.\n *\n * @param descending - Descending coefficients, the leading one non-zero.\n * @returns The distinct rational roots in ascending order, and the coefficients\n * of the factor that survives. How much of the degree was consumed is not\n * returned because it does not need to be: every division drops exactly one\n * coefficient, so it is the difference in length and cannot drift from it.\n */\nfunction extractRationalRoots(descending: readonly Rational[]): { roots: Rational[]; remaining: Rational[] } {\n\tconst roots: Rational[] = [];\n\tlet remaining = [...descending];\n\n\tlet powersOfX = 0;\n\twhile (remaining.length > 1 && isRationalZero(remaining[remaining.length - 1])) {\n\t\tremaining = remaining.slice(0, -1);\n\t\tpowersOfX++;\n\t}\n\t// A repeated root is one solution, not several, so zero is recorded once\n\t// however many powers of `x` came out.\n\tif (powersOfX > 0) roots.push(RATIONAL_ZERO);\n\n\twhile (remaining.length > 1) {\n\t\tconst found = rationalRoots(remaining);\n\t\tif (found.length === 0) break;\n\t\tfor (const root of found) {\n\t\t\tlet multiplicity = 0;\n\t\t\twhile (remaining.length > 1 && isRationalZero(evaluateRational(remaining, root))) {\n\t\t\t\tremaining = divideByRoot(remaining, root);\n\t\t\t\tmultiplicity++;\n\t\t\t}\n\t\t\t// Guarded rather than assumed: a candidate that is no longer a root of\n\t\t\t// what is left must not be reported as one.\n\t\t\tif (multiplicity > 0) roots.push(root);\n\t\t}\n\t}\n\n\t// Ascending, so a row of roots reads low to high the way a reader expects.\n\treturn { roots: roots.sort(rationalCompare), remaining };\n}\n\n/**\n * Solves a single-variable polynomial given its descending coefficients.\n *\n * Every path out of here goes through {@link finish}, and what it is told is\n * the degree of the factor still **unsolved**, read off the length of the\n * coefficient array that is left rather than accumulated in a counter as the\n * stages go. That distinction is the point. A counter is a promise each branch\n * has to keep, and the defect this replaces was exactly a branch that answered\n * for one root of five without anything downstream noticing; an array length is\n * a fact about the polynomial that no branch can misremember.\n *\n * Each leftover branch is therefore all-or-nothing: it either solves the whole\n * surviving factor or reports it whole as unsolved.\n */\nfunction solveUnivariate(descending: readonly Rational[]): SolveOutcome {\n\tconst { roots, remaining } = extractRationalRoots(descending);\n\n\tconst exact: SymbolicNode[] = roots.map(constNode);\n\tconst approximate: ApproximateRoot[] = [];\n\tconst leftoverDegree = remaining.length - 1;\n\tconst solvedDegree = descending.length - remaining.length;\n\n\tif (leftoverDegree <= 0) return finish(exact, approximate, solvedDegree, 0, \"\");\n\tif (leftoverDegree === 1) {\n\t\t// Unreachable in practice, since a linear factor's root is rational and so\n\t\t// was already extracted. Kept because the alternative to a cheap branch is\n\t\t// an unhandled degree.\n\t\texact.push(constNode(rationalDiv(rationalNeg(remaining[1]), remaining[0])));\n\t\treturn finish(exact, approximate, solvedDegree + 1, 0, \"\");\n\t}\n\tif (leftoverDegree === 2) {\n\t\texact.push(...solveQuadratic(remaining[0], remaining[1], remaining[2]));\n\t\treturn finish(exact, approximate, solvedDegree + 2, 0, \"\");\n\t}\n\n\tconst closedForm = closedFormRoots(remaining);\n\tif (closedForm !== null) {\n\t\texact.push(...closedForm.exact);\n\t\tapproximate.push(...closedForm.approximate.map(realApproximation));\n\t\treturn finish(exact, approximate, solvedDegree + leftoverDegree, 0, \"\");\n\t}\n\n\t// No closed form this module reaches: a quintic or beyond, or a quartic whose\n\t// radicals nest four deep. Every root of what is left is found at once in the\n\t// complex plane rather than one at a time by deflation.\n\tconst numeric = approximateRoots(remaining);\n\tif (numeric !== null) {\n\t\tapproximate.push(...numeric);\n\t\treturn finish(exact, approximate, solvedDegree + leftoverDegree, 0, \"\");\n\t}\n\treturn finish(\n\t\texact,\n\t\tapproximate,\n\t\tsolvedDegree,\n\t\tleftoverDegree,\n\t\t`a degree-${leftoverDegree} factor of it has no exact solution here and the numerical method did not converge on that factor`,\n\t);\n}\n\n/**\n * The single exit from the univariate solver, where the answer is checked\n * against the question before it is handed back.\n *\n * This exists because of a specific failure that a message could not have\n * prevented. `solve(x^5-1=0, x)` returned `1`: a correct root, a fifth of the\n * answer, and indistinguishable from a complete one to anybody reading it. So\n * the relationship between what was asked and what was found is asserted here\n * rather than left to each branch to remember, and an answer that does not hold\n * up comes back as `incomplete` with the shortfall counted.\n *\n * Two things are checked, and both are cheap because both quantities are\n * already known:\n *\n * 1. **Coverage.** A factor of degree `unsolvedDegree` was not solved, so that\n * many roots are missing however many were found.\n * 2. **Coherence.** A stage that claims to have solved a factor of degree one\n * or more has to have produced at least one root for it and cannot have\n * produced more than its degree. Neither is possible for a correct stage, so\n * either would be a defect in the solver rather than a property of the\n * equation, and handing back roots after seeing one would be trusting\n * exactly what has just been shown to be untrustworthy.\n *\n * @param exact - Roots known exactly.\n * @param approximate - Roots found numerically.\n * @param solvedDegree - How much of the degree the stages above actually solved.\n * @param unsolvedDegree - The degree of the factor they did not.\n * @param reason - Why that factor was not solved, used only when one was not.\n * @returns `roots` when every root is accounted for, `incomplete` otherwise.\n */\nfunction finish(\n\texact: readonly SymbolicNode[],\n\tapproximate: readonly ApproximateRoot[],\n\tsolvedDegree: number,\n\tunsolvedDegree: number,\n\treason: string,\n): SolveOutcome {\n\tconst found = exact.length + approximate.length;\n\tconst incoherent = solvedDegree >= 1 && (found < 1 || found > solvedDegree);\n\tif (unsolvedDegree > 0 || incoherent) {\n\t\treturn {\n\t\t\tkind: \"incomplete\",\n\t\t\texact,\n\t\t\tapproximate,\n\t\t\t// A distinct root can stand for several equal ones, so the count found\n\t\t\t// is a lower bound on what it covers. The degree left unsolved is not.\n\t\t\tmissing: incoherent ? Math.max(1, solvedDegree + unsolvedDegree - found) : unsolvedDegree,\n\t\t\treason: incoherent\n\t\t\t\t? `${found} root${found === 1 ? \"\" : \"s\"} were produced for a degree-${solvedDegree + unsolvedDegree} equation, which does not add up`\n\t\t\t\t: reason,\n\t\t};\n\t}\n\treturn { kind: \"roots\", exact, approximate };\n}\n","/**\n * The adapter between VM {@link Value}s and the symbolic algebra core.\n *\n * This is the only module that legitimately knows both types, which is why it\n * lives in `vm/` rather than in `symbolic/` (which imports nothing from the VM)\n * or in `packages/symbolic/` (which is grammar, and sits above `vm/` in the\n * layering).\n *\n * It exists because of a specific class of silent wrong answer.\n * `Value.toNumber()` reports `0` for a symbolic operand, deliberately, since a\n * free-variable formula has no single numeric value. Any opcode that reaches\n * for `.toNumber()` without checking `.isSymbolic()` first therefore computes\n * with zero and returns a confidently wrong result with no error at all:\n * `x^2 + 3x + 2` evaluated to `3x+2`, `-x` to `-0`, and `sqrt(x)` to `0`. The\n * three entry points below are what `vm/VM.ts` calls instead, for `EXP`, `NEG`\n * and `CALL_BUILTIN` respectively.\n */\n\nimport { Value, ValueType, numberValue, stringValue, errorValue, symbolicValue, matrixValue, faultedOperand } from \"@solve-js/vm/Value\";\nimport { solveForVariable, type SolveOutcome } from \"@solve-js/symbolic/Solve\";\nimport type { ApproximateRoot } from \"@solve-js/symbolic/NumericRoots\";\nimport {\n\ttype SymbolicNode,\n\tcomplex,\n\tcomplexNode,\n\tconstNode,\n\tpowNode,\n\tcallNode,\n\tsimplifySymbolic,\n\trationalFromNumber,\n\trationalToNumber,\n} from \"@solve-js/symbolic\";\n\n/**\n * Builtin function indices that carry a meaning through a symbolic\n * expression, mapped to the name a `call` node records.\n *\n * Declared here rather than derived from\n * `packages/function/parselets/FunctionCallParselet.ts`'s `builtinNameToIndex`,\n * because `vm/` must not import from `packages/`. `__tests__/vm/SymbolicOps.spec.ts`\n * asserts the two agree, which a test file may do since it can import both.\n *\n * Membership is a deliberate judgement, not a transcription. A function is\n * here only when applying it to a free variable is meaningful. Everything\n * absent (`min`/`max`/`random`, the number-base conversions, the finance block\n * at 51 to 60, the matrix block at 63 to 66) has no symbolic reading and is\n * reported as an error rather than silently computed against zero.\n *\n * Index 31 (`pow`) is intentionally absent: it is special-cased in\n * {@link symbolicBuiltin} to build a `pow` node, so that `pow(x, 2)` and `x^2`\n * produce the identical tree.\n */\nexport const SYMBOLIC_BUILTIN_NAMES: Readonly<Record<number, string>> = {\n\t0: \"sqrt\", 1: \"abs\", 2: \"sin\", 3: \"cos\", 4: \"tan\", 5: \"log\",\n\t6: \"ceil\", 7: \"floor\", 8: \"round\",\n\t11: \"asin\", 12: \"acos\", 13: \"atan\", 14: \"atan2\",\n\t15: \"sinh\", 16: \"cosh\", 17: \"tanh\",\n\t18: \"asinh\", 19: \"acosh\", 20: \"atanh\",\n\t21: \"cbrt\", 23: \"expm1\", 24: \"exp\", 26: \"hypot\",\n\t28: \"log10\", 29: \"log1p\", 30: \"log2\",\n\t33: \"sign\", 34: \"trunc\",\n\t// Spelled exactly as `builtinNameToIndex` accepts them, all lower case. A\n\t// `call` node's name is what gets displayed, so a name the parser would not\n\t// accept back would render an expression the user cannot retype.\n\t35: \"degtorad\", 36: \"radtodeg\",\n\t61: \"root\", 62: \"fact\",\n};\n\n/** Builtin index for `pow(base, exponent)`, which becomes a `pow` node rather than a `call` node. */\nconst POW_BUILTIN_INDEX = 31;\n\n/**\n * Builtin indices that take a symbolic argument on purpose and handle it\n * themselves, so `vm/VM.ts` must **not** route them through\n * {@link symbolicBuiltin}.\n *\n * These are the algebra verbs (`expand`, and the later phases' `factor`,\n * `solve` and calculus functions). Every other builtin reads its arguments\n * through `toNumber()` and has to be intercepted; these exist precisely to\n * receive an expression containing unknowns, so intercepting them would report\n * \"cannot be applied to an expression that still contains an unknown\" for the\n * one family of functions where that is the whole point.\n *\n * Listed here rather than imported from `packages/symbolic/` because `vm/` must\n * not import from `packages/`. `__tests__/engine/SymbolicSurfaceParity.spec.ts`\n * asserts this set matches the package's own table.\n */\nexport const SYMBOLIC_NATIVE_BUILTINS: ReadonlySet<number> = new Set([67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79]);\n\n/**\n * Converts a Value into a {@link SymbolicNode}.\n *\n * @param v - The value to convert.\n * @returns The value's own tree when it is already symbolic, otherwise a\n * `const` node wrapping its numeric value. `null` when the value has no exact\n * rational image, which covers `NaN`, `±Infinity`, and the `Error`/`Pending`\n * value types whose `toNumber()` is a placeholder zero rather than a quantity.\n */\nexport function valueToSymbolic(v: Value): SymbolicNode | null {\n\tif (v.type === ValueType.Symbolic) return v.value as SymbolicNode;\n\tif (v.type === ValueType.Error || v.type === ValueType.Pending) return null;\n\tconst numeric = v.toNumber();\n\tif (!Number.isFinite(numeric)) return null;\n\treturn constNode(rationalFromNumber(numeric));\n}\n\n/**\n * Simplifies a tree and wraps it back as a Value.\n *\n * @param node - The tree to finish.\n * @returns A plain `Number` Value when the tree simplified to a bare constant,\n * so an expression whose unknowns all cancelled reads as an ordinary number,\n * otherwise a `Symbolic` Value.\n */\nexport function symbolicToValue(node: SymbolicNode): Value {\n\tconst simplified = simplifySymbolic(node);\n\tif (simplified.kind === \"const\") return numberValue(rationalToNumber(simplified.value));\n\treturn symbolicValue(simplified);\n}\n\n/** The error returned whenever a symbolic operand reaches something with no symbolic meaning, in place of the old silent zero. */\nfunction unsupported(what: string): Value {\n\treturn errorValue(\n\t\t\"SYMBOLIC_UNSUPPORTED_FUNCTION\",\n\t\t`\"${what}\" cannot be applied to an expression that still contains an unknown.`,\n\t);\n}\n\n/**\n * `^` where at least one operand is symbolic.\n *\n * @param l - The base.\n * @param r - The exponent.\n * @returns The resulting Value, or an error Value when either operand has no\n * exact rational image.\n */\nexport function symbolicPow(l: Value, r: Value): Value {\n\tconst base = valueToSymbolic(l);\n\tconst exponent = valueToSymbolic(r);\n\tif (base === null || exponent === null) return unsupported(\"^\");\n\treturn symbolicToValue(powNode(base, exponent));\n}\n\n/**\n * Unary minus where the operand is symbolic.\n *\n * @param v - The operand.\n * @returns The negated Value, or an error Value when the operand has no exact\n * rational image.\n */\nexport function symbolicNeg(v: Value): Value {\n\tconst operand = valueToSymbolic(v);\n\tif (operand === null) return unsupported(\"-\");\n\treturn symbolicToValue({ kind: \"neg\", operand });\n}\n\n/**\n * A builtin function call where at least one argument is symbolic.\n *\n * @param index - The builtin index, as pushed by `OpCode.CALL_BUILTIN`.\n * @param args - The already-ordered argument values.\n * @returns The resulting Value. An index with no symbolic meaning yields an\n * error Value rather than a number computed from a placeholder zero.\n */\nexport function symbolicBuiltin(index: number, args: readonly Value[]): Value {\n\tconst nodes: SymbolicNode[] = [];\n\tfor (const arg of args) {\n\t\t// Propagate a faulted operand unchanged rather than replacing it, so the\n\t\t// original code and message (or pending query key) reach the caller.\n\t\t// Pending counts: valueToSymbolic() below returns null for one, which\n\t\t// would report \"no symbolic reading\" for a value that simply has not\n\t\t// arrived yet.\n\t\tconst faulted = faultedOperand(arg);\n\t\tif (faulted) return faulted;\n\t\tconst node = valueToSymbolic(arg);\n\t\tif (node === null) return unsupported(SYMBOLIC_BUILTIN_NAMES[index] ?? `builtin ${index}`);\n\t\tnodes.push(node);\n\t}\n\n\tif (index === POW_BUILTIN_INDEX && nodes.length === 2) {\n\t\treturn symbolicToValue(powNode(nodes[0], nodes[1]));\n\t}\n\n\tconst name = SYMBOLIC_BUILTIN_NAMES[index];\n\tif (name === undefined) return unsupported(`builtin ${index}`);\n\treturn symbolicToValue(callNode(name, nodes));\n}\n\n/**\n * Renders one root as a value, keeping a fraction exact.\n *\n * A whole-number root becomes an ordinary Number, which reads naturally. A\n * fractional one stays Symbolic so it renders as `1/3`: routing it through\n * {@link symbolicToValue} would collapse it to a double and the number\n * formatter would show `0.33`, throwing away the exactness that solving\n * exactly was for.\n */\nfunction rootToValue(root: SymbolicNode): Value {\n\tconst value = symbolicToValue(root);\n\tif (value.type === ValueType.Number && !Number.isInteger(value.toNumber())) return symbolicValue(root);\n\treturn value;\n}\n\n/**\n * Renders one numerically-found root as a value.\n *\n * A root off the real line becomes an exact complex node built from the two\n * doubles, so it displays as `-0.809+0.5878i` rather than being dropped or\n * flattened to its real part. The rational conversion is of the double's own\n * decimal form, so nothing is invented: the value shown is the value found, and\n * the number formatter rounds it for display exactly as it rounds any other.\n */\nfunction approximateRootToValue(root: ApproximateRoot): Value {\n\tif (root.im === 0) return numberValue(root.re);\n\treturn symbolicValue(complexNode(complex(rationalFromNumber(root.re), rationalFromNumber(root.im))));\n}\n\n/**\n * Renders a {@link SolveOutcome} as a VM value.\n *\n * Some outcomes are answers rather than errors and read as sentences, since\n * \"no solution\" is the complete and correct response to `1=2` and dressing it\n * up as a failure would misrepresent it.\n *\n * An `incomplete` outcome becomes an error even though roots were found. That\n * is the point of it: `solve(x^5-1=0, x)` answering `1` was wrong in the way\n * that matters most, because one root of five looks exactly like the whole\n * answer. Saying how many are missing is the only reading a user cannot be\n * misled by.\n */\nfunction solveOutcomeToValue(outcome: SolveOutcome): Value {\n\tswitch (outcome.kind) {\n\t\tcase \"identity\":\n\t\t\treturn stringValue(\"true for every value\");\n\t\tcase \"contradiction\":\n\t\t\treturn stringValue(\"no solution\");\n\t\tcase \"unsupported\":\n\t\t\treturn errorValue(\"SYMBOLIC_SOLVE_UNSUPPORTED\", `Cannot solve this equation: ${outcome.reason}.`);\n\t\tcase \"incomplete\": {\n\t\t\tconst found = outcome.exact.length + outcome.approximate.length;\n\t\t\treturn errorValue(\n\t\t\t\t\"SYMBOLIC_SOLVE_INCOMPLETE\",\n\t\t\t\t`Only ${found} of this equation's ${found + outcome.missing} roots could be found: ${outcome.reason}.`,\n\t\t\t);\n\t\t}\n\t\tcase \"roots\": {\n\t\t\tconst values = outcome.exact.map(rootToValue);\n\t\t\tfor (const approximate of outcome.approximate) values.push(approximateRootToValue(approximate));\n\t\t\tif (values.length === 0) return stringValue(\"no solution\");\n\t\t\tif (values.length === 1) return values[0];\n\t\t\t// Several roots read best as a row of values, which the matrix\n\t\t\t// formatter already renders as \"[-2, 2]\".\n\t\t\treturn matrixValue(1, values.length, values.map(v => (v.type === ValueType.Symbolic ? (v.value as SymbolicNode) : v.toNumber())));\n\t\t}\n\t}\n}\n\n/**\n * Solves `lhs = rhs` for a variable, given the two sides as already-evaluated\n * Values, and renders the outcome.\n *\n * Shared by the `solve(equation, variable)` builtin and by the stored\n * `x^2-4 = 0` then `x =>` form in `engine/ExpressionEngine.ts`. Both go through\n * here rather than each rendering an outcome themselves, so the two surfaces\n * cannot drift into disagreeing about what an answer looks like.\n *\n * @param lhsValue - The left-hand side, evaluated symbolic-tolerantly.\n * @param rhsValue - The right-hand side, likewise.\n * @param variable - The unknown to solve for.\n * @returns The solution as a Value, or an error Value when a side has no exact\n * value to solve with.\n */\nexport function solveEquationValues(lhsValue: Value, rhsValue: Value, variable: string): Value {\n\tconst lhs = valueToSymbolic(lhsValue);\n\tconst rhs = valueToSymbolic(rhsValue);\n\tif (lhs === null || rhs === null) {\n\t\treturn errorValue(\"SYMBOLIC_NONFINITE_OPERAND\", \"An equation side has no exact value to solve with.\");\n\t}\n\treturn solveOutcomeToValue(solveForVariable(lhs, rhs, variable));\n}\n","import { Value, ValueType, numberValue, numberValueRational, numberValueUncertain, bigIntValue, uomValue, uomValueExact, matrixValue, errorValue, symbolicValue, type MatrixData, type MatrixEntry } from \"@solve-js/vm/Value\";\nimport { convertUnit, getMeasure } from \"@solve-js/uom/UomConverter\";\nimport { sharedCurrencyExchange } from \"@solve-js/uom/CurrencyExchange\";\nimport { decimalAdd, decimalSubtract, decimalMultiply, decimalDivide, decimalIsZero, decimalToNumber, decimalFromNumberIfExact, decimalCompare, type DecimalData } from \"@solve-js/decimal\";\nimport { sameShape } from \"@solve-js/vm/MatrixOps\";\nimport { type SymbolicNode, type Rational, simplifySymbolic, rational, rationalAdd, rationalSub, rationalMul, rationalDiv, rationalToNumber, rationalCompare, isRationalZero } from \"@solve-js/symbolic\";\nimport { valueToSymbolic } from \"@solve-js/vm/SymbolicOps\";\nimport { ErrorFactory, type EngineError } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Unify two Value operands that may carry units of measurement.\n * Returns numeric values in a common unit (or undefined unit if incompatible).\n */\nexport function unifyUom(l: Value, r: Value): { lv: number; rv: number; unit: string | undefined; sameMeasure: boolean } {\n if (l.type === ValueType.Uom && r.type === ValueType.Uom) {\n if (l.unit === r.unit) {\n return { lv: l.toNumber(), rv: r.toNumber(), unit: l.unit, sameMeasure: true };\n }\n const lMeasure = getMeasure(l.unit!);\n const rMeasure = getMeasure(r.unit!);\n const isCurrency = sharedCurrencyExchange.isCurrency(l.unit!) && sharedCurrencyExchange.isCurrency(r.unit!);\n\n if (lMeasure && lMeasure === rMeasure) {\n const rvConverted = convertUnit(r.toNumber(), r.unit!, l.unit!);\n return { lv: l.toNumber(), rv: rvConverted, unit: l.unit, sameMeasure: true };\n }\n if (isCurrency) {\n const rvConverted = sharedCurrencyExchange.convertSync(r.toNumber(), r.unit!, l.unit!);\n if (rvConverted !== null) {\n return { lv: l.toNumber(), rv: rvConverted, unit: l.unit, sameMeasure: true };\n }\n }\n return { lv: l.toNumber(), rv: r.toNumber(), unit: undefined, sameMeasure: false };\n }\n if (l.type === ValueType.Uom) {\n return { lv: l.toNumber(), rv: r.toNumber(), unit: l.unit, sameMeasure: true };\n }\n if (r.type === ValueType.Uom) {\n return { lv: l.toNumber(), rv: r.toNumber(), unit: r.unit, sameMeasure: true };\n }\n return { lv: l.toNumber(), rv: r.toNumber(), unit: undefined, sameMeasure: true };\n}\n\n/**\n * How close two unified magnitudes have to be before a comparison calls them\n * the same number, as a fraction of the magnitudes that produced them.\n *\n * A conversion is arithmetic, and arithmetic rounds. Converting 32 fahrenheit\n * to celsius gives 5.684e-14 rather than the exact zero the two scales are\n * defined to share, because the offset arithmetic runs in binary floating\n * point and five ninths has no finite binary expansion. Comparing that with\n * `===` made `0 C == 32 F` answer false, and with it every other equality that\n * has to cross a temperature scale.\n *\n * 1e-12 sits roughly four decimal digits above the last bit of a double, which\n * is wide enough for the rounding any conversion in the table introduces and\n * far narrower than the gap between two numbers a person meant to be\n * different: at the scale of the 32 in the example above it admits a\n * difference of 3.2e-11, and a user who writes two temperatures apart writes\n * them further apart than that.\n */\nconst UNIFIED_COMPARISON_TOLERANCE = 1e-12;\n\n/** The largest of three magnitudes, ignoring any that is not finite. */\nfunction largestFiniteMagnitude(a: number, b: number, c: number): number {\n let scale = 0;\n if (Number.isFinite(a) && Math.abs(a) > scale) scale = Math.abs(a);\n if (Number.isFinite(b) && Math.abs(b) > scale) scale = Math.abs(b);\n if (Number.isFinite(c) && Math.abs(c) > scale) scale = Math.abs(c);\n return scale;\n}\n\n/**\n * Compare two operands that carry units, in a unit each of them can be read\n * in.\n *\n * Returns the two magnitudes in a common unit plus the two facts a comparison\n * opcode needs that it cannot recover from those magnitudes alone: whether the\n * units share a measure at all, and whether the magnitudes are equal once the\n * conversion's own rounding is allowed for.\n *\n * The tolerance is measured against the ORIGINAL operand magnitudes as well as\n * the converted ones. A converted value sitting near zero has no magnitude of\n * its own to scale against, which is exactly the `0 C == 32 F` case, and yet\n * the arithmetic that produced its rounding worked on numbers the size of the\n * inputs, so those are what the error has to be judged against.\n *\n * NaN is equal to nothing, itself included, which is what makes `0/0 == 0/0`\n * answer false; it falls out of the finiteness check rather than needing its\n * own branch.\n */\nexport function compareUom(l: Value, r: Value): { lv: number; rv: number; equal: boolean; sameMeasure: boolean } {\n const { lv, rv, sameMeasure } = unifyUom(l, r);\n if (!sameMeasure) return { lv, rv, equal: false, sameMeasure: false };\n // Same-currency money compares on its exact decimals, so \"$0.1 + $0.2 ==\n // $0.3\" is true on the value rather than on whichever doubles the two sides\n // happen to land on. The returned lv/rv (already the nearest doubles) order\n // the same way, since rounding to nearest is monotonic.\n if (\n l.type === ValueType.Uom && r.type === ValueType.Uom &&\n l.unit !== undefined && l.unit === r.unit &&\n l.exact !== undefined && r.exact !== undefined &&\n sharedCurrencyExchange.isCurrency(l.unit)\n ) {\n return { lv, rv, equal: decimalCompare(l.exact, r.exact) === 0, sameMeasure: true };\n }\n if (lv === rv) return { lv, rv, equal: true, sameMeasure: true };\n if (!Number.isFinite(lv) || !Number.isFinite(rv)) return { lv, rv, equal: false, sameMeasure: true };\n const scale = largestFiniteMagnitude(lv, rv, r.toNumber());\n return { lv, rv, equal: Math.abs(lv - rv) <= scale * UNIFIED_COMPARISON_TOLERANCE, sameMeasure: true };\n}\n\n/**\n * The dimension nouns that do not read as their measure-kind name. A quantity\n * of `time` reads as a duration in a sentence (\"a duration cannot be converted\n * to a length\"), and the generated measure table spells luminous intensity as\n * one camelCase token. Every other kind (length, mass, area, ...) already reads\n * as the noun, so it is used unchanged.\n */\nconst MEASURE_NOUNS: Readonly<Record<string, string>> = {\n time: \"duration\",\n luminousIntensity: \"luminous intensity\",\n};\n\n/**\n * The dimensions that are uncountable, so they take no indefinite article in\n * the conversion sentence: \"money\", not \"a money\".\n */\nconst UNCOUNTABLE_MEASURES: ReadonlySet<string> = new Set([\"money\", \"data\"]);\n\n/** The past participle each combining op reads as in the mismatch sentence. */\nconst COMBINE_VERBS: Readonly<Record<string, string>> = {\n add: \"added\",\n sub: \"subtracted\",\n mul: \"multiplied\",\n div: \"divided\",\n};\n\n/**\n * Name the dimension a unit measures, as a noun a message can drop into a\n * sentence: `kg` gives \"mass\", `hour` gives \"duration\", `USD` gives \"money\".\n *\n * Returns undefined when the unit has no single dimension to name (a compound\n * rate such as \"km/h\", or a currency code the exchange does not recognise), so\n * a caller can fall back to naming the raw unit rather than printing\n * \"undefined\".\n */\nexport function describeMeasure(unit: string): string | undefined {\n // Currencies are not in the measure table (getMeasure returns undefined for\n // them), so they are named here before the table lookup.\n if (sharedCurrencyExchange.isCurrency(unit)) return \"money\";\n const measure = getMeasure(unit);\n if (measure === undefined) return undefined;\n return MEASURE_NOUNS[measure] ?? measure;\n}\n\n/**\n * A dimension noun with the indefinite article that reads correctly: \"a\n * length\", \"an area\", and the uncountable dimensions (\"money\") left bare.\n */\nfunction withMeasureArticle(noun: string): string {\n if (UNCOUNTABLE_MEASURES.has(noun)) return noun;\n return /^[aeiou]/.test(noun) ? `an ${noun}` : `a ${noun}`;\n}\n\n/**\n * The mismatch sentence naming the two differing dimensions of a refused\n * `+`/`-`/`*` or comparison: \"mass and length cannot be added\".\n *\n * Returns undefined when there is no pair of differing dimensions to name: an\n * unknown or compound unit on either side, or two currencies (both money, the\n * missing-rate case rather than a dimension mismatch). The caller then keeps\n * its own fallback, which names the units instead.\n *\n * @param verb - the past participle for the sentence (\"added\", \"compared\").\n */\nexport function describeMeasureMismatch(\n lUnit: string | undefined,\n rUnit: string | undefined,\n verb: string,\n): string | undefined {\n const left = lUnit === undefined ? undefined : describeMeasure(lUnit);\n const right = rUnit === undefined ? undefined : describeMeasure(rUnit);\n if (left !== undefined && right !== undefined && left !== right) {\n return `${left} and ${right} cannot be ${verb}`;\n }\n return undefined;\n}\n\n/**\n * The past participle for a combining opcode's mismatch sentence. MOD passes no\n * op kind (see {@link binaryOp}), and reads as the neutral \"combined\".\n */\nexport function combineVerb(op: string | undefined): string {\n return op !== undefined ? (COMBINE_VERBS[op] ?? \"combined\") : \"combined\";\n}\n\n/**\n * The mismatch sentence for a conversion the engine cannot make: \"a duration\n * cannot be converted to a length\".\n *\n * Returns undefined when either side has no dimension to name (a compound rate,\n * or a currency code the exchange does not know), so the caller keeps its own\n * fallback that names the two units instead.\n */\nexport function describeConversionMismatch(fromUnit: string, toUnit: string): string | undefined {\n const from = describeMeasure(fromUnit);\n const to = describeMeasure(toUnit);\n if (from !== undefined && to !== undefined && from !== to) {\n return `${withMeasureArticle(from)} cannot be converted to ${withMeasureArticle(to)}`;\n }\n return undefined;\n}\n\n/**\n * The answer an ordered comparison gives when the two quantities share no\n * measure.\n *\n * `<` between a mass and a length is not false, it is a question with no\n * answer, and answering it with a boolean drawn from the bare magnitudes is\n * the same confidently-wrong shape `binaryOp` refuses below for `+`. Equality\n * is the exception and stays a boolean: a kilogram genuinely is not a metre,\n * so `==` can say false and mean it.\n *\n * The two dimensions are named where both are known and differ (\"mass and\n * length cannot be compared\"), falling back to naming the units when they are\n * not (see {@link describeMeasureMismatch}).\n */\nexport function incomparableUnitsError(l: Value, r: Value): Value {\n const lUnit = l.type === ValueType.Uom ? l.unit : undefined;\n const rUnit = r.type === ValueType.Uom ? r.unit : undefined;\n const named = describeMeasureMismatch(lUnit, rUnit, \"compared\");\n return errorValue(\"INCOMPATIBLE_UNITS\", named ?? `Cannot compare incompatible units: ${lUnit ?? \"?\"} and ${rUnit ?? \"?\"}`);\n}\n\n/**\n * Read an operand as a bigint without rounding it through a double first.\n *\n * An already-BigInt operand hands over its raw bigint; anything else converts\n * via `toNumber()`, which is lossless because a value that was only ever a\n * double has no extra precision to lose. Going through `toNumber()`\n * unconditionally is what made every bitwise operator, every comparison and\n * `^` destroy the digits that are the whole point of the type, e.g.\n * `12345678901234567891n & 1n` answered 0 because the left operand became\n * 12345678901234567168 on the way in.\n *\n * @throws A recoverable `BIGINT_INEXACT_OPERAND` execution error for an operand\n * with no whole-number form. This used to be a raw `RangeError` straight out of\n * `BigInt()`, which the VM's outer catch relabelled UNEXPECTED_ERROR/INTERNAL:\n * `1n + 0.5`, `1n & 1.5`, `1n << 1.5`, `5n/pi` and `e/8n` all reported an engine\n * bug for what is a typo in the line. The same shape `vm/VMBuiltinArity.ts` was\n * written to fix for `sqrt()`.\n */\nexport function toBigIntOperand(v: Value): bigint {\n if (v.type === ValueType.BigInt) return v.value as bigint;\n const n = v.toNumber();\n if (!Number.isInteger(n)) {\n // Covers NaN and both infinities as well as fractions, all of which\n // `BigInt()` refuses and none of which has a whole-number form.\n const shown = Number.isNaN(n) ? \"NaN\" : String(n);\n throw ErrorFactory.execution(\n \"BIGINT_INEXACT_OPERAND\",\n `A whole-number (n) value can only be combined with another whole number, and ${shown} is not one`,\n { operand: shown },\n );\n }\n return BigInt(n);\n}\n\n/**\n * What `10n / 0n` and `10n mod 0n` answer.\n *\n * DECIDED, and deliberately NOT the same as `1 / 0`, which is Infinity here.\n * The two numeric types already disagree about division and always did:\n * `7n / 2n` is 3n and `7 / 2` is 3.5, because a bigint division is exact\n * integer division. Every language that has both draws the line in the same\n * place, C, Java, Python and JavaScript's own BigInt included: integer division\n * by zero raises, IEEE-754 division by zero is an infinity. So this is not the\n * two types disagreeing about zero, it is the one difference between them\n * showing up at zero as well as everywhere else, and an infinity is not\n * something exact integer arithmetic has to hand back.\n *\n * What was actually wrong was the reporting, not the decision.\n * `__tests__/hardening/ArithmeticBigInt.spec.ts` already asserted this and its\n * comment already explained it, but nothing implemented it: the test passed\n * because V8's own `RangeError` happens to say \"Division by zero\", and the VM\n * relabelled that raw exception UNEXPECTED_ERROR/INTERNAL. So a user dividing\n * by zero was told the ENGINE had failed. Now it is the engine's own error,\n * with a code a host can branch on.\n *\n * @returns The error for the caller's `bigOp` to throw.\n */\nexport function bigIntDivisionByZero(): EngineError {\n return ErrorFactory.execution(\n \"BIGINT_DIVISION_BY_ZERO\",\n \"Division by zero: a whole-number (n) division is exact integer division, which has no answer at zero, unlike 1 / 0 which is Infinity\",\n );\n}\n\n/**\n * Three-way comparison of two operands, at least one of which is a BigInt,\n * with every digit intact.\n *\n * @returns -1, 0 or 1, or `null` when an operand has no exact bigint image (a\n * fraction, an infinity, a NaN). On null the caller keeps its ordinary double\n * comparison, which is the correct answer for a fractional operand and the\n * only available one for a non-finite operand.\n */\nexport function compareBigIntOperands(l: Value, r: Value): -1 | 0 | 1 | null {\n const lb = exactBigInt(l);\n const rb = exactBigInt(r);\n if (lb === null || rb === null) return null;\n if (lb < rb) return -1;\n if (lb > rb) return 1;\n return 0;\n}\n\n/** An operand's exact bigint image, or null when it has none. */\nfunction exactBigInt(v: Value): bigint | null {\n if (v.type === ValueType.BigInt) return v.value as bigint;\n const n = v.toNumber();\n // Rules out Infinity and NaN as well as fractions.\n return Number.isInteger(n) ? BigInt(n) : null;\n}\n\n/**\n * `base` raised to `exponent`, in doubles.\n *\n * DECIDED (1.0.0, differential run 20260811): where ECMAScript and C99/IEEE 754\n * disagree about `pow`, this engine follows C99.\n *\n * They disagree in exactly one family of cases, a base of exactly ±1 with an\n * exponent that is not a finite number. ECMAScript's `**` answers NaN for\n * `1 ** Infinity` and `1 ** NaN`, on the reasoning that 1^infinity is an\n * indeterminate FORM in the calculus of limits. C99 (F.9.4.4), IEEE 754's\n * `pow`, Python and Ruby all answer 1, on the reasoning that this is not a\n * limit: the base here is the number one, not something approaching it, and one\n * multiplied by itself any number of times is one.\n *\n * `1^2^3^4^5` is what made the choice matter. `^` groups right, so that tower\n * is 1^(2^(3^(4^5))); the inner tower overflows a double to Infinity, and the\n * outermost step is 1^Infinity. Under ECMAScript's rule the answer is NaN, so\n * an expression whose every base is 1 answers \"not a number\", and the reason is\n * a rounding artefact three levels down rather than anything about the\n * question. Under C99's rule it is 1, which is also what it is under exact\n * arithmetic, which settles it: the release that exists to stop the engine\n * answering confidently from an artefact should not itself do that.\n *\n * `NaN ^ 0` is 1 under both rules and needs no branch here.\n */\nexport function power(base: number, exponent: number): number {\n // The overwhelmingly common case, and the one both standards agree on.\n if (Number.isFinite(exponent)) return Math.pow(base, exponent);\n // pow(1, y) is 1 for every y, a NaN exponent included.\n if (base === 1) return 1;\n // pow(-1, +-infinity) is 1 as well, but pow(-1, NaN) is NaN: C99 extends\n // the rule to a NaN exponent only for the base +1.\n if (base === -1 && !Number.isNaN(exponent)) return 1;\n return Math.pow(base, exponent);\n}\n\n/**\n * The exact decimal an operand contributes to a money operation, or null.\n *\n * A currency operand hands over the sidecar its literal or a prior exact result\n * set. A plain scalar (the `3` in `$1.10 * 3`, the `1.10` in `$0.70 * 1.10`)\n * hands over its own exact decimal: a whole number always has one, and a\n * decimal-point literal carries one too, which is what lets a fractional\n * multiplier stay exact against money without the bare `1.005 * 100` between\n * two plain numbers changing at all. A fractional double with no sidecar (a\n * `sqrt` result) has no exact decimal and returns null, dropping that operation\n * back to the float path.\n */\nfunction operandExactDecimal(v: Value): DecimalData | null {\n if (v.exact !== undefined) return v.exact;\n return decimalFromNumberIfExact(v.toNumber());\n}\n\n/**\n * The exact result of a money arithmetic op, or null when it cannot be exact.\n *\n * Exactness is preserved only when the currency stays put: two amounts in the\n * same currency, or a currency against a plain scalar. A cross-currency\n * combination goes through an exchange rate, which is a double, so it is left\n * to the float path below rather than dressed up as exact. Division falls back\n * for a zero divisor so \"$10 / 0\" keeps the double's Infinity, and for two\n * currencies (a ratio the VM computes before this is ever reached).\n */\nfunction exactMoneyOp(l: Value, r: Value, op: \"add\" | \"sub\" | \"mul\" | \"div\"): Value | null {\n const lMoney = l.type === ValueType.Uom && l.unit !== undefined && l.exact !== undefined && sharedCurrencyExchange.isCurrency(l.unit);\n const rMoney = r.type === ValueType.Uom && r.unit !== undefined && r.exact !== undefined && sharedCurrencyExchange.isCurrency(r.unit);\n if (!lMoney && !rMoney) return null;\n\n let ld: DecimalData | null;\n let rd: DecimalData | null;\n let unit: string;\n if (lMoney && rMoney) {\n // Different currencies reconcile through a rate, which is a double, so\n // only a shared currency stays exact. A ratio (money / money) is the\n // VM's own DIV case and never arrives here.\n if (l.unit !== r.unit || op === \"div\") return null;\n ld = l.exact!; rd = r.exact!; unit = l.unit!;\n } else if (lMoney && r.type !== ValueType.Uom) {\n // The other side must be a plain scalar. A different-unit Uom (\"$100 +\n // 5 kg\") is NOT a scalar, and must fall through to the float path so it\n // surfaces the incompatible-units error rather than absorbing the 5 as\n // though it were dollars.\n ld = l.exact!; unit = l.unit!;\n rd = operandExactDecimal(r);\n } else if (rMoney && l.type !== ValueType.Uom) {\n rd = r.exact!; unit = r.unit!;\n ld = operandExactDecimal(l);\n } else {\n return null;\n }\n if (ld === null || rd === null) return null;\n\n let result: DecimalData;\n switch (op) {\n case \"add\": result = decimalAdd(ld, rd); break;\n case \"sub\": result = decimalSubtract(ld, rd); break;\n case \"mul\": result = decimalMultiply(ld, rd); break;\n case \"div\":\n if (decimalIsZero(rd)) return null;\n result = decimalDivide(ld, rd);\n break;\n }\n return uomValueExact(decimalToNumber(result), unit, result);\n}\n\n/**\n * The exact rational an operand contributes to a fraction operation, or null.\n *\n * A value that already carries a `rational` sidecar hands it over. A plain\n * whole number (the \"14\" in \"2/7 * 14\", the \"3\" in \"1/3 * 3\") has the exact\n * rational n/1. Everything else has none: a non-integer double with no sidecar\n * (a decimal literal, a `sqrt` result) returns null so the operation drops to\n * the float path, and a bigint returns null so \"100n / 3n\" stays exact INTEGER\n * division (33n) rather than becoming the fraction 100/3. NaN and the\n * infinities fail the integer test and return null with everything else.\n */\nfunction operandRational(v: Value): Rational | null {\n if (v.rational !== undefined) return v.rational;\n if ((v.type === ValueType.Number || v.type === ValueType.Hex) && typeof v.value === \"number\" && Number.isInteger(v.value)) {\n return rational(BigInt(v.value));\n }\n return null;\n}\n\n/**\n * The exact rational result of a fraction operation, or null when it has none.\n *\n * DIV is the producer: \"1/3\" is two whole numbers, so both operands have a\n * rational image and the quotient 1/3 seeds the sidecar the rest of the system\n * propagates. ADD/SUB/MUL only ever preserve, their call sites reach here only\n * when a `rational` sidecar already rides on an operand, so plain integer sums\n * like \"1e16 + 1 - 1e16\" never grow one and stay the doubles they must be.\n *\n * The double is recomputed from the reduced result rather than from the operand\n * doubles, which is the whole point: \"1/6\" six times over is exactly 1, not the\n * 0.9999999999999999 the doubles accumulate to.\n *\n * Returns null (dropping to the float path) rather than throwing when a\n * fraction cannot stay exact: a zero divisor keeps \"1/0\" as the double Infinity\n * the float path gives, and a value past the rational magnitude ceiling keeps\n * the doubles' answer rather than surfacing a fraction-overflow error for\n * ordinary arithmetic.\n */\nexport function exactRationalOp(l: Value, r: Value, op: \"add\" | \"sub\" | \"mul\" | \"div\"): Value | null {\n const lr = operandRational(l);\n if (lr === null) return null;\n const rr = operandRational(r);\n if (rr === null) return null;\n if (op === \"div\" && isRationalZero(rr)) return null;\n let result: Rational;\n try {\n switch (op) {\n case \"add\": result = rationalAdd(lr, rr); break;\n case \"sub\": result = rationalSub(lr, rr); break;\n case \"mul\": result = rationalMul(lr, rr); break;\n case \"div\": result = rationalDiv(lr, rr); break;\n }\n } catch {\n // Past RATIONAL_MAX_BITS the rational ops throw. The float answer is\n // always available and always valid, so fall back to it rather than\n // fail a line that only happened to build a very large fraction.\n return null;\n }\n return numberValueRational(rationalToNumber(result), result);\n}\n\n/**\n * The result of a `+`/`-`/`*`/`/` between operands, at least one of which\n * carries a one-sigma uncertainty, propagated in quadrature. Null when it does\n * not apply.\n *\n * Independent errors combine in quadrature, the common case the feature scopes\n * itself to (correlated terms are a much larger problem and out of scope). The\n * center follows the ordinary arithmetic; the spread follows the standard\n * first-order rules:\n * add/sub: sigma = sqrt(sigma_a^2 + sigma_b^2)\n * mul: sigma = sqrt((b*sigma_a)^2 + (a*sigma_b)^2)\n * div: sigma = sqrt((sigma_a/b)^2 + (a*sigma_b/b^2)^2)\n * The mul/div forms are the partial-derivative version of the relative-error\n * rule sigma = |result| * sqrt((sigma_a/a)^2 + (sigma_b/b)^2), algebraically the\n * same but without dividing by a center that may be zero. A plain number is\n * read as an exact operand (uncertainty 0), which is what makes a scalar\n * multiply `(a ± s) * k` come out as `s * |k|`.\n *\n * Returns null unless both operands are plain Numbers, so a unit, a matrix or\n * any other typed operand keeps its own path (and drops the uncertainty, as a\n * comparison or a transcendental function does). The VM gates the call on an\n * uncertainty actually being present, so a plain `2 * 3` never reaches here.\n */\nexport function uncertainOp(l: Value, r: Value, op: \"add\" | \"sub\" | \"mul\" | \"div\"): Value | null {\n if (l.type !== ValueType.Number || r.type !== ValueType.Number) return null;\n const a = l.value as number;\n const b = r.value as number;\n const sa = l.uncertainty ?? 0;\n const sb = r.uncertainty ?? 0;\n let center: number;\n let sigma: number;\n switch (op) {\n case \"add\": center = a + b; sigma = Math.hypot(sa, sb); break;\n case \"sub\": center = a - b; sigma = Math.hypot(sa, sb); break;\n case \"mul\": center = a * b; sigma = Math.hypot(b * sa, a * sb); break;\n case \"div\": center = a / b; sigma = Math.hypot(sa / b, (a * sb) / (b * b)); break;\n }\n return numberValueUncertain(center, sigma);\n}\n\n/**\n * Three-way comparison of two operands as exact fractions, or null.\n *\n * Mirrors {@link compareBigIntOperands}: when a rational rides on either side\n * the comparison is decided on the fractions rather than on whichever doubles\n * they rounded to, so \"1/49 * 49 == 1\" is true and two distinct fractions that\n * share a nearest double still compare unequal. Returns null when either side\n * has no rational image, leaving the caller's ordinary double comparison in\n * place. The call sites gate on a rational actually being present first, so a\n * plain \"1 < 2\" never reaches here.\n */\nexport function compareRationalOperands(l: Value, r: Value): -1 | 0 | 1 | null {\n const lr = operandRational(l);\n if (lr === null) return null;\n const rr = operandRational(r);\n if (rr === null) return null;\n return rationalCompare(lr, rr);\n}\n\n/**\n * Apply a numeric binary operation with type-aware dispatch.\n * Handles BigInt, UoM, Vector, Symbolic, and plain Number operands.\n *\n * @param symbolicOp - which SymbolicNode kind to build when either operand\n * is Symbolic (`symbolic/SymbolicNode.ts`). Only ADD/SUB/MUL/DIV pass this (the\n * \"four arithmetic opcodes\" the symbolic-algebra phase scopes itself\n * to), MOD's own call site passes nothing, so a Symbolic operand there\n * falls through to the ordinary numeric path (`toNumber()` -> 0), an\n * explicit, disclosed scope boundary rather than an oversight.\n */\nexport function binaryOp(\n l: Value, r: Value,\n op: (a: number, b: number) => number,\n bigOp?: (a: bigint, b: bigint) => bigint,\n symbolicOp?: \"add\" | \"sub\" | \"mul\" | \"div\"\n): Value {\n // Error/Pending short-circuit, MUST run before any other branch.\n // Value.toNumber() returns 0 for both Error and Pending (see\n // vm/Value.ts), so without this check, every path below (including\n // the plain-number fast path two lines down) would silently treat an\n // errored or not-yet-resolved operand as the number 0, e.g. an\n // errored cross-line reference (`prev + 1` in packages/lines) would\n // quietly evaluate to 1 instead of surfacing the error. Propagate\n // Error/Pending operands as-is (left operand checked first, matching\n // left-to-right evaluation order) rather than manufacturing a new\n // error, so the original error code/message (or pending query key)\n // reaches the caller unchanged. Confirmed via ADD/SUB/MUL/DIV/MOD in\n // vm/VM.ts: none of their type-specific fast paths (Number/Boolean/\n // Datetime/Uom/Rate) match Error or Pending, so every one of them\n // already funnels here on those operand types.\n if (l.type === ValueType.Error) return l;\n if (r.type === ValueType.Error) return r;\n if (l.type === ValueType.Pending) return l;\n if (r.type === ValueType.Pending) return r;\n\n // Symbolic dispatch, either operand carries a free-variable formula.\n // Builds the corresponding SymbolicNode (the non-symbolic side, if\n // any, becomes a `const` node via its own numeric value), simplifies\n // it (symbolic/Simplify.ts's deliberately bounded rule set), and wraps the\n // result back as Symbolic. `symbolicOp` is undefined for opcodes that\n // don't support this (currently just MOD), those fall through to the\n // ordinary numeric path below unchanged.\n if (symbolicOp && (l.type === ValueType.Symbolic || r.type === ValueType.Symbolic)) {\n const left = valueToSymbolic(l);\n const right = valueToSymbolic(r);\n // An operand with no exact rational image (NaN, ±Infinity) used to be\n // folded in as a `const` built from a double, which either threw deep\n // inside the simplifier or produced a nonsense coefficient. Report it.\n if (left === null || right === null) {\n return errorValue(\n \"SYMBOLIC_NONFINITE_OPERAND\",\n \"A symbolic expression cannot combine with a value that has no exact number (NaN or infinity).\",\n );\n }\n const node: SymbolicNode = { kind: symbolicOp, left, right };\n return symbolicValue(simplifySymbolic(node));\n }\n\n // Fast path: both operands are plain numbers, skip all type checks.\n // This is the overwhelmingly common case (90%+ of all binary ops).\n // Inlined arithmetic avoids the overhead of helper function dispatch,\n // UoM unification, Vector iteration, BigInt conversion, and NaN guards.\n if (l.type === ValueType.Number && r.type === ValueType.Number) {\n return numberValue(op(l.value as number, r.value as number));\n }\n\n if (l.type === ValueType.BigInt || r.type === ValueType.BigInt) {\n // Read an already-BigInt operand's raw bigint directly. See\n // toBigIntOperand() above for why, and for the other opcodes that\n // share it.\n const lb = toBigIntOperand(l);\n const rb = toBigIntOperand(r);\n if (bigOp) return bigIntValue(bigOp(lb, rb));\n return bigIntValue(lb + rb);\n }\n\n if (l.type === ValueType.Uom || r.type === ValueType.Uom) {\n // Money in the same currency (or money against a plain scalar) is exact:\n // \"$0.10 + $0.20\" is \"$0.30\", not the double's \"$0.30000000000000004\".\n // Only the four arithmetic ops carry an `op` kind (MOD passes none), and\n // only currencies set the sidecar, so everything else falls straight\n // through to the float unification below unchanged.\n if (symbolicOp) {\n const exactMoney = exactMoneyOp(l, r, symbolicOp);\n if (exactMoney) return exactMoney;\n }\n const { lv, rv, unit, sameMeasure } = unifyUom(l, r);\n // NaN is deliberately NOT intercepted here. A guard used to answer a\n // bare, unitless 0 for it, which turned an operand that means \"no\n // answer\" into a confident one and threw the unit away as well:\n // `(1 kg / 0 * 0) + 1 kg` reported 0 rather than NaN kg. NaN\n // propagates through the arithmetic below exactly as it does for\n // plain numbers, and the comparison opcodes already report false\n // against it, which is how a caller detects it.\n if (!sameMeasure) {\n // unifyUom couldn't reconcile the two units, either they're\n // genuinely incompatible measures (meters + kilograms), or\n // they're both currencies but no rate was available yet.\n // Silently combining the raw magnitudes here used to produce a\n // confidently-wrong, unitless number (e.g. \"0.01 BTC + 1 ETH\"\n // → a bare \"1.01\", the naive 0.01+1 sum with the currency\n // context just dropped) instead of surfacing the failure\n // mirrors the existing UOM_CONVERT_TO/_IN error path in VM.ts.\n const lUnit = l.type === ValueType.Uom ? l.unit : undefined;\n const rUnit = r.type === ValueType.Uom ? r.unit : undefined;\n // Name the two dimensions when they genuinely differ (\"mass and\n // length cannot be added\"). Two currencies with no cached rate reach\n // here too, and share the money dimension, so there is nothing to\n // contrast: describeMeasureMismatch returns undefined and the\n // unit-naming fallback below keeps the \"BTC and ETH\" form.\n const named = describeMeasureMismatch(lUnit, rUnit, combineVerb(symbolicOp));\n return errorValue(\"INCOMPATIBLE_UNITS\", named ?? `Cannot combine incompatible units: ${lUnit ?? \"?\"} and ${rUnit ?? \"?\"}`);\n }\n return uomValue(op(lv, rv), unit!);\n }\n\n // Element-wise Matrix dispatch (ADD/SUB/DIV/MOD land here; MUL's real\n // scalar-vs-matrix-product disambiguation happens in VM.ts's own MUL\n // case BEFORE falling through to binaryOp() at all, so this generic\n // path only ever needs to handle the always-element-wise ops).\n if (l.type === ValueType.Matrix && r.type === ValueType.Matrix) {\n const lm = l.value as MatrixData;\n const rm = r.value as MatrixData;\n if (!sameShape(lm, rm)) {\n // Silently truncating/broadcasting a shape mismatch used to\n // drop components with no indication (the old flat-Array\n // Math.min() truncation bug), surface it instead.\n return errorValue(\"DIMENSION_MISMATCH\", `Cannot combine matrices of different shapes: ${lm.rows}x${lm.cols} and ${rm.rows}x${rm.cols}`);\n }\n const result: MatrixEntry[] = new Array(lm.data.length);\n for (let i = 0; i < lm.data.length; i++) result[i] = op(lm.data[i] as number, rm.data[i] as number);\n return matrixValue(lm.rows, lm.cols, result);\n }\n\n if (l.type === ValueType.Matrix) {\n // Scalar broadcast: [1,2,3]/10 => [0.1,0.2,0.3], preserves shape.\n const lm = l.value as MatrixData;\n const scalar = r.toNumber();\n const result: MatrixEntry[] = lm.data.map(v => op(v as number, scalar));\n return matrixValue(lm.rows, lm.cols, result);\n }\n\n if (r.type === ValueType.Matrix) {\n const rm = r.value as MatrixData;\n const scalar = l.toNumber();\n const result: MatrixEntry[] = rm.data.map(v => op(scalar, v as number));\n return matrixValue(rm.rows, rm.cols, result);\n }\n\n // No NaN guard here either, for the reason given in the Uom branch above:\n // an operand that is NaN has to stay NaN rather than become a zero nobody\n // can tell apart from a real one.\n return numberValue(op(l.toNumber(), r.toNumber()));\n}\n","import type { Value } from \"@solve-js/vm/Value\";\nimport type { BytecodeProgram, UserFunctionDef } from \"@solve-js/parser/BytecodeBuilder\";\nimport type { EngineContext } from \"@solve-js/engine/EngineContext\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * A stored bare (colon-less) equation of the shape `factor1*factor2*...*\n * variable = rhs` (e.g. `a*x = [60;70]`, or `s*t*v = [vx;vy;1]`)\n * registered when that line is EXECUTED (mirroring `UserFunctionDef`'s own\n * execution-time registration, not parse-time), and consulted when\n * `<variable> =>` is later evaluated. Solving is `variable =\n * inv(factor1*factor2*...) * rhs` (`vm/VM.ts`'s THEREFORE-handling code,\n * `vm/MatrixOps.ts`'s `matrixMultiply()`/`inverse()`, both symbolic-aware\n * so a factor whose OWN cells are still-unassigned free variables, e.g.\n * `s = [sx,0,0;...]`, solves correctly too).\n *\n * `factorNames` are looked up via `vm.getVar()` at solve time (ordinary,\n * ALREADY-evaluated Matrix values, ordinary (\"bare\") assignment always\n * evaluates its RHS eagerly, even when that RHS itself contains\n * unassigned names, via symbolic-tolerant evaluation, so by solve time\n * each factor is already a genuine, possibly-partially-symbolic Matrix\n * Value sitting in the variable store), NOT re-compiled bytecode, since\n * this pattern only ever allows bare identifiers as factors (see\n * `ExpressionEngine.ts`'s own equation-detection doc comment for why this\n * stays a narrow, disclosed pattern rather than a general expression).\n * `rhsProgram` IS a real compiled program (the right-hand side can be an\n * arbitrary expression, e.g. `[vx;vy;1]`), evaluated in symbolic-tolerant\n * mode at solve time.\n */\nexport interface EquationDef {\n\tvariable: string;\n\tfactorNames: string[];\n\trhsProgram: BytecodeProgram;\n}\n\n/**\n * A stored scalar equation, the general `x^2 - 4 = 0` shape, kept separate from\n * {@link EquationDef} rather than merged into it.\n *\n * The two are genuinely different problems solved by different machinery.\n * {@link EquationDef} is a product chain of matrix factors solved by inverting\n * their product; this is an arbitrary polynomial in one unknown solved by\n * `symbolic/Solve.ts`. Merging them into one optional-field type would mean\n * every consumer branching on which half is populated, and would put the older,\n * already-shipped matrix path at risk of being changed by accident.\n *\n * Both sides are compiled programs rather than pre-evaluated values, because\n * neither side can be evaluated until solve time: they contain the very unknown\n * being solved for.\n */\nexport interface ScalarEquationDef {\n\t/** The unknown this equation is keyed by and will be solved for. */\n\tvariable: string;\n\t/** Compiled left-hand side, evaluated symbolic-tolerantly at solve time. */\n\tlhsProgram: BytecodeProgram;\n\t/** Compiled right-hand side, likewise. */\n\trhsProgram: BytecodeProgram;\n}\n\n/**\n * Handler function for plugin-registered opcodes via CALL_PLUGIN (opcode 50).\n * No longer dispatched directly from the VM switch, plugins register\n * functions in pluginFunctionRegistry instead.\n *\n * @deprecated Use CALL_PLUGIN + pluginFunctionRegistry for plugin functionality.\n * OpRegistry remains for the VM interface contract only.\n */\nexport type OpcodeHandler = (vm: VM, opcodes: Uint8Array, ip: number, numbers: Float64Array, strings: string[]) => number;\n\n/** Registration payload for an opcode handler. Binds an OpCode to its handler function with plugin attribution. */\nexport interface IOpcodeHandlerRegistration {\n\topcode: number;\n\thandler: OpcodeHandler;\n\tpluginName: string;\n}\n\n/** Maximum safe opcode value for Uint8Array storage. */\nconst MAX_OPCODE = 254;\n\n/** Starting point for dynamic opcode allocation. */\nconst DYNAMIC_OPCODE_START = 200;\n\n/**\n * Legacy opcode registry, retained for the VM interface contract.\n *\n * Previously dispatched custom opcodes (>= 200) from the VM switch-default\n * branch. Now plugins should use CALL_PLUGIN (opcode 50) via\n * pluginFunctionRegistry instead.\n */\nexport class OpRegistry {\n\tprivate handlers = new Map<number, OpcodeHandler>();\n\tprivate nextOpcode = DYNAMIC_OPCODE_START + 1;\n\n\tregister(registration: IOpcodeHandlerRegistration): void {\n\t\tthis.handlers.set(registration.opcode, registration.handler);\n\t}\n\n\t/**\n\t * Remove a previously registered opcode handler.\n\t * Used by package unregistration to reverse shared-registry contributions.\n\t */\n\tunregister(opcode: number): void {\n\t\tthis.handlers.delete(opcode);\n\t}\n\n\tget(opcode: number): OpcodeHandler | undefined {\n\t\treturn this.handlers.get(opcode);\n\t}\n\n\thas(opcode: number): boolean {\n\t\treturn this.handlers.has(opcode);\n\t}\n\n\t/**\n\t * Allocate a unique opcode for a plugin's custom bytecode handler.\n\t *\n\t * Returns the next available opcode (starting at 201). Each call\n\t * returns a distinct value. Plugins should call this once during\n\t * registration and store the result.\n\t *\n\t * @throws If the dynamic opcode pool is exhausted.\n\t * @returns A unique opcode number for the calling plugin.\n\t */\n\tallocateOpcode(): number {\n\t\tif (this.nextOpcode > MAX_OPCODE) {\n\t\t\tthrow ErrorFactory.config(\n\t\t\t\t\"OPCODE_POOL_EXHAUSTED\",\n\t\t\t\t`OpRegistry: dynamic opcode pool exhausted (max ${MAX_OPCODE - DYNAMIC_OPCODE_START} allocations).`\n\t\t\t);\n\t\t}\n\t\treturn this.nextOpcode++;\n\t}\n\n}\n\n/**\n * VM interface consumed by opcode handlers and the bytecode executor.\n *\n * Provides stack operations, variable access, instruction counting,\n * and abort signal management for async cancellation.\n */\nexport interface VM {\n\tpush(value: Value): void;\n\tpop(): Value;\n\t/**\n\t * Pop the top of the stack as a number.\n\t *\n\t * @throws `STACK_UNDERFLOW` (INTERNAL) if the stack is empty. Unlike\n\t * `pop()`, which answers an empty stack with `0`, this reports it: a\n\t * handler asking for a number has no way to tell that `0` from a real\n\t * one. Every Value converts, so there is no operand-type throw here.\n\t */\n\tpopNumber(): number;\n\t/**\n\t * Pop the top of the stack as a string, e.g. a unit name a handler's own\n\t * bytecode pushed for it to read.\n\t *\n\t * @throws `STACK_UNDERFLOW` (INTERNAL) if the stack is empty, and\n\t * `MALFORMED_BYTECODE_OPERAND_TYPE` (VALIDATION, recoverable) if the\n\t * value on top is not a string. Both are structured `EngineError`s\n\t * naming this method, in place of the raw TypeError a bare `pop()!` and\n\t * a compile-time-only cast used to produce somewhere further along. A\n\t * handler that would rather branch than throw can `peek()` first.\n\t */\n\tpopString(): string;\n\tpeek(): Value;\n\tgetStack(): Value[];\n\tregistry: OpRegistry;\n\t/**\n\t * Read a variable by name, checks the INNERMOST active user-defined-\n\t * function call frame first (see `pushCallFrame`), then falls back to\n\t * the flat, session-scoped variable store. This is why a function\n\t * parameter needs no dedicated load opcode: an ordinary `LOAD_VAR\n\t * \"x\"` inside a function body resolves to the current call's bound\n\t * argument automatically, without the parser needing to know it's\n\t * compiling a function body at all.\n\t */\n\tgetVar(key: string): Value | undefined;\n\tsetVar(key: string, value: Value): void;\n\t/**\n\t * Remove a top-level variable binding. Used at the start of each document\n\t * pass to re-seed accumulators (`total += 5`): a running total must reset\n\t * to its seed each full re-parse, otherwise it reads its own previous\n\t * pass's value and grows without bound on every keystroke.\n\t */\n\tdeleteVar(key: string): void;\n\t/**\n\t * User-defined-function call frame, a name-keyed `Map` of this call's\n\t * bound arguments, PUSHED before `CALL_USER_FUNCTION` executes the\n\t * callee's body and POPPED immediately after (even if the body throws),\n\t * so nested/recursive calls (`double(double(5))`) each get their own\n\t * frame instead of clobbering a shared flat map. See `vm/VM.ts`'s\n\t * `CALL_USER_FUNCTION` case. Deliberately NOT the same store as\n\t * `setVar`'s flat `:name` variables, a call frame is call-scoped and\n\t * stacked (only the INNERMOST frame is ever consulted by `getVar`, see\n\t * its own doc comment, no lexical capture of an outer call's\n\t * parameters), a variable is session-scoped and flat.\n\t *\n\t * @throws `FUNCTION_RECURSION_LIMIT_EXCEEDED` if pushing would exceed\n\t * the VM's configured `maxFunctionRecursionDepth`, the backstop for\n\t * `f(x) = f(x)`, which would otherwise recurse via nested\n\t * `executeBytecode()` calls until the native V8 stack overflows\n\t * uncatchably (each reentrant call gets its OWN fresh\n\t * `localInstructionCount`, so `maxInstructions` cannot catch this).\n\t */\n\tpushCallFrame(frame: Map<string, Value>): void;\n\tpopCallFrame(): void;\n\t/** Register (or redefine, overwrites any previous definition, matching `:name = value`'s own reassignment semantics) a user-defined function. */\n\tdefineUserFunction(name: string, params: string[], program: BytecodeProgram): void;\n\tgetUserFunction(name: string): UserFunctionDef | undefined;\n\thasUserFunction(name: string): boolean;\n\t/**\n\t * Every session-scoped variable currently defined, as `[name, value]` pairs,\n\t * for snapshotting the VM's state (see `engine/EngineSnapshot.ts`). The\n\t * returned array is a fresh copy, so mutating it does not touch the store,\n\t * and it reads the flat document-variable table only, never a transient\n\t * user-function call frame (those are call-scoped and gone by the time any\n\t * snapshot is taken).\n\t */\n\tgetVariableEntries(): [string, Value][];\n\t/** Every user-defined function currently defined, as a fresh array copy, for snapshotting (see {@link getVariableEntries}). */\n\tgetUserFunctionDefs(): UserFunctionDef[];\n\t/** Register (or redefine) a bare equation (`a*x = rhs`), keyed by its free variable. See {@link EquationDef}. */\n\tdefineEquation(variable: string, factorNames: string[], rhsProgram: BytecodeProgram): void;\n\tgetEquation(variable: string): EquationDef | undefined;\n\thasEquation(variable: string): boolean;\n\t/** Register (or redefine) a stored scalar equation (`x^2-4 = 0`), keyed by its unknown. See {@link ScalarEquationDef}. */\n\tdefineScalarEquation(variable: string, lhsProgram: BytecodeProgram, rhsProgram: BytecodeProgram): void;\n\tgetScalarEquation(variable: string): ScalarEquationDef | undefined;\n\thasScalarEquation(variable: string): boolean;\n\treset(): void;\n\t/** The innermost call frame's bindings, or `undefined` when no call is in progress. Read-only, for building a frame that extends the current one rather than replacing it (see `BIND_UNKNOWN`'s handler). */\n\tgetCallFrame(): ReadonlyMap<string, Value> | undefined;\n\tgetMaxInstructions(): number;\n\tgetMaxStackDepth(): number;\n\t/** Maximum elements a Range or Matrix may be expanded to by `map`/`reduce`. See `constants/Configuration.ts`'s `maxCollectionSize`. */\n\tgetMaxCollectionSize(): number;\n\t/**\n\t * Maximum elements (collection Values, matrix cells) one evaluation may\n\t * materialise in total.\n\t *\n\t * The bound the two limits above cannot be. Both are checked between\n\t * opcodes, so neither sees what one opcode allocates inside a loop of its\n\t * own, and `getMaxCollectionSize()` bounds one collection without bounding\n\t * the total. See `vm/AllocationBudget.ts` for the counter this configures\n\t * and for why charging goes through that module rather than through the VM.\n\t */\n\tgetMaxAllocatedElements(): number;\n\t/**\n\t * Maximum user-defined-function calls one evaluation may make in total.\n\t *\n\t * `maxFunctionRecursionDepth` (see `pushCallFrame` above) bounds how DEEP\n\t * calls nest; this bounds how MANY there are, which is a different number\n\t * and the one a doubling chain runs away with: twenty-two lines of\n\t * `f(v) = g(v) + g(v)` reach two million calls at a depth of twenty-two.\n\t * Held by `vm/AllocationBudget.ts` rather than counted here, because it has\n\t * to survive `executeBytecode()` re-entering itself, exactly like the\n\t * element tally and unlike `maxInstructions`.\n\t */\n\tgetMaxFunctionCalls(): number;\n\t/** How far forward `<date> + N workdays` may reach, in years. The one date offset that walks the calendar rather than computing, so the one with a ceiling. See `constants/Configuration.ts`'s `date.maxOffsetYears`. */\n\tgetMaxDateOffsetYears(): number;\n\t/** The same bound backwards, as a negative number of years. */\n\tgetMinDateOffsetYears(): number;\n\t/** Whether the host's public-holiday calendar marks `epochMs` a holiday, for working-day arithmetic. Always `false` when no calendar is configured (weekends-only). Set from `constants/Configuration.ts`'s `date.holidays`; see `vm/HolidayCalendar.ts`. */\n\tisHoliday(epochMs: number): boolean;\n\tgetInstructionCount(): number;\n\tincrementInstructions(n: number): void;\n\t/** Active AbortSignal for the current expression evaluation. Checked before cache writes. */\n\tactiveSignal?: AbortSignal;\n\t/** Abort the current evaluation (called when expression changes before resolution). */\n\tabortCurrent?: () => void;\n\t/**\n\t * Registries belonging to the engine that created this VM.\n\t *\n\t * `CALL_PLUGIN` resolves handlers through here rather than through a\n\t * module-level registry, so two engines in one process no longer share the\n\t * plugin functions their packages registered. This follows what\n\t * `userFunctions` and `equations` already do by being VM-instance scoped.\n\t */\n\tcontext: EngineContext;\n}\n\n/** Shared singleton OpRegistry, used when no custom opcodes are needed. */\nexport const sharedOpRegistry = new OpRegistry();\n","/**\n * Exact-decimal scaling for money, shared by the percentage operators (`VM.ts`)\n * and the tax builtins (`VMBuiltins.ts`).\n *\n * A price is a decimal, not a binary fraction, so `$X * factor` has to be formed\n * in base ten. Computed as a float it lands a hair below the true value and the\n * half-cent then rounds the wrong way: `$0.10 * 1.15` is `0.1149999...`, which a\n * till reads as `$0.12` but a double rounds down to `$0.11`. These helpers\n * recover the exact decimals of the amount and the factor, multiply them\n * exactly, and hand back a value carrying the exact sidecar; they fall back to\n * the float path only where an operand has no exact value, so nothing that was\n * exact before loses exactness.\n */\n\nimport { Value, uomValue, uomValueExact, type SplitData, type SplitShare } from \"@solve-js/vm/Value\";\nimport {\n\tdecimalFromLiteral,\n\tdecimalFromInteger,\n\tdecimalFromNumberIfExact,\n\tdecimalNegate,\n\tdecimalToNumber,\n\tdecimalAdd,\n\tdecimalSubtract,\n\tdecimalMultiply,\n\tdecimalDivide,\n\tdecimalIsZero,\n\tdecimalRound,\n\tmakeDecimal,\n\ttype DecimalData,\n} from \"@solve-js/decimal\";\nimport { sharedCurrencyExchange } from \"@solve-js/uom/CurrencyExchange\";\n\n/** Exact base-ten `1`, the constant term in a `1 + p%` scaling factor. */\nconst ONE_DECIMAL: DecimalData = decimalFromInteger(1);\n\n/**\n * The exact decimal a currency amount should carry, or null when it has none.\n *\n * Gated on the unit being a currency, so the exact-decimal machinery is money's\n * and money's alone in this slice, every other Uom (km, kg, minutes) is left\n * exactly as it was. The amount's exact value is either the sidecar a decimal\n * literal already set, or, for a whole-number amount, the integer itself. A\n * fractional double with no sidecar (`$sqrt(2)`, `$ (1/3) `) returns null and\n * stays a float, which is the deliberate boundary: exactness only where an\n * exact value actually exists.\n */\nexport function moneyExactMagnitude(operand: Value, unit: string): DecimalData | null {\n\tif (!sharedCurrencyExchange.isCurrency(unit)) return null;\n\treturn operand.exact ?? decimalFromNumberIfExact(operand.toNumber());\n}\n\n/**\n * The exact base-ten value of a number that is exactly a short decimal (the\n * proportion a percentage the user typed reduces to, e.g. `15%` -> `0.15`), via\n * its shortest round-tripping string, or null for a value that is not (a computed\n * irrational, or scientific-notation extreme). Wider than\n * {@link decimalFromNumberIfExact} (integers only), and used only to recover a\n * percentage's intended decimal, where the printed proportion is the meaning.\n */\nexport function decimalFromShortDecimal(n: number): DecimalData | null {\n\tif (!Number.isFinite(n)) return null;\n\tif (Number.isInteger(n)) return decimalFromInteger(BigInt(n));\n\tconst s = String(n);\n\tif (!/^-?\\d+\\.\\d+$/.test(s)) return null;\n\treturn decimalFromLiteral(s);\n}\n\n/**\n * Scale a money amount by a bare factor, keeping it exact.\n *\n * `tax on $X at R%` is `$X * R`, and money multiplication is exact wherever the\n * inputs are, so `tax on $10.10 at 15%` is `$1.515 -> $1.52`, not the `$1.51` a\n * bare double (`10.10 * 0.15 = 1.5149999...`) rounds down to. The factor is\n * recovered from its shortest decimal, the proportion the rate was typed as.\n * Falls back to the float path only when an operand has no exact value (the same\n * boundary {@link moneyExactMagnitude} draws), so nothing that was exact before\n * loses exactness, and a non-currency unit passes straight through it unchanged.\n */\nexport function scaleMoneyExact(amount: Value, factor: number, unit: string): Value {\n\tconst base = moneyExactMagnitude(amount, unit);\n\tconst factorDecimal = decimalFromShortDecimal(factor);\n\tif (base !== null && factorDecimal !== null) {\n\t\tconst result = decimalMultiply(base, factorDecimal);\n\t\treturn uomValueExact(decimalToNumber(result), unit, result);\n\t}\n\treturn uomValue(amount.toNumber() * factor, unit);\n}\n\n/**\n * Scale a money amount by `1 + sign * percent`, keeping it exact.\n *\n * `$X + p%` is `$X * (1 + p%)`, and money multiplication is exact wherever the\n * inputs are, so the till answer for `$0.10 + 15%` is `$0.115 -> $0.12`, not the\n * `$0.11` a bare double (`0.10 * 1.15 = 0.1149999...`) rounds down to. The\n * one-plus-percent factor is formed in base ten so no double drift creeps in.\n * Falls back to the float path only when an operand has no exact value (the same\n * boundary {@link moneyExactMagnitude} draws), so nothing that was exact before\n * loses exactness.\n */\nexport function scaleMoneyByPercent(money: Value, unit: string, percent: number, sign: 1 | -1): Value {\n\tconst base = moneyExactMagnitude(money, unit);\n\tconst percentDecimal = decimalFromShortDecimal(percent);\n\tif (base !== null && percentDecimal !== null) {\n\t\tconst factor = decimalAdd(ONE_DECIMAL, sign === 1 ? percentDecimal : decimalNegate(percentDecimal));\n\t\tconst result = decimalMultiply(base, factor);\n\t\treturn uomValueExact(decimalToNumber(result), unit, result);\n\t}\n\treturn uomValue(money.toNumber() * (1 + sign * percent), unit);\n}\n\n/**\n * The exact base-ten `1 + rate` divisor of a tax-inclusive total, or null when\n * the rate has no short decimal. Formed in base ten (not as the double `1 +\n * rate`) so the tax-inclusive divisor carries no drift, the same reason\n * {@link scaleMoneyByPercent} builds its factor this way.\n */\nfunction onePlusRateDecimal(rate: number): DecimalData | null {\n\tconst rateDecimal = decimalFromShortDecimal(rate);\n\treturn rateDecimal === null ? null : decimalAdd(ONE_DECIMAL, rateDecimal);\n}\n\n/**\n * `$X / (1 + rate)`, the pre-tax amount inside a tax-inclusive total, kept exact.\n *\n * `tax off $0.09 at 20%` is `$0.09 / 1.2 = $0.075`, which the half-cent rule\n * rounds to `$0.08`, not the `$0.07` a bare double (`0.09 / 1.2 = 0.0749999...`)\n * rounds down to. {@link decimalDivide} carries the quotient exactly where it\n * terminates (the cases that can land on a half-cent, at 20%/25%/50%) and rounds\n * it far below the cent where it does not, so the displayed cent is right either\n * way. Falls back (returns null) only when an operand has no exact value or the\n * divisor is zero, leaving the caller's float path, the same boundary the other\n * MoneyExact helpers draw.\n */\nexport function removeTaxExact(money: Value, unit: string, rate: number): Value | null {\n\tconst base = moneyExactMagnitude(money, unit);\n\tconst divisor = onePlusRateDecimal(rate);\n\tif (base === null || divisor === null || decimalIsZero(divisor)) return null;\n\tconst quotient = decimalDivide(base, divisor);\n\treturn uomValueExact(decimalToNumber(quotient), unit, quotient);\n}\n\n/**\n * `$X - $X / (1 + rate)`, the tax already inside a tax-inclusive total, kept\n * exact. The complement of {@link removeTaxExact}: the two sum back to `$X`.\n *\n * `tax in $0.09 at 20%` is `$0.09 - $0.075 = $0.015`, which rounds to `$0.02`,\n * not the `$0.01` the drifted double rounds down to. The subtraction is done in\n * base ten so the tax and the net a matching `tax off` reports stay consistent.\n */\nexport function taxInExact(money: Value, unit: string, rate: number): Value | null {\n\tconst base = moneyExactMagnitude(money, unit);\n\tconst divisor = onePlusRateDecimal(rate);\n\tif (base === null || divisor === null || decimalIsZero(divisor)) return null;\n\tconst tax = decimalSubtract(base, decimalDivide(base, divisor));\n\treturn uomValueExact(decimalToNumber(tax), unit, tax);\n}\n\n/**\n * Allocate a bill split into whole-cent shares that add back to the exact\n * total. `split $100 between 3` is $33.34 once and $33.33 twice: 2 × $33.33 +\n * 1 × $33.34 is $100.00 to the cent, not the bare $33.33 each that loses a\n * penny. Largest-remainder allocation on the amount's exact decimal cents, so\n * the reconciliation is exact wherever the amount is (a money literal, or a\n * percentage-scaled one like `$120 + 18%`). A non-currency amount (a bare\n * number, or a unit such as km) divides evenly into a single share, carrying\n * its unit for display; money with no exact magnitude (a live-rate conversion)\n * falls back to a float even split, the same boundary the other helpers draw.\n *\n * `n` is assumed a positive integer, the split builtin validates it first.\n * Shares are ordered base-first: the \"each\" amount, then, on an uneven split,\n * the slightly larger amount the odd penny falls on.\n */\nexport function splitEachExact(amount: Value, n: number): SplitData {\n\tconst unit = amount.unit;\n\tconst cents = unit !== undefined && sharedCurrencyExchange.isCurrency(unit)\n\t\t? centsOfMoney(amount, unit)\n\t\t: null;\n\tif (cents === null) {\n\t\treturn { unit, shares: [{ value: amount.toNumber() / n, count: n }] };\n\t}\n\n\tconst divisor = BigInt(n);\n\tconst baseCents = cents / divisor; // truncates toward zero\n\tconst remainder = cents - baseCents * divisor; // sign follows `cents`\n\tconst extraShares = Number(remainder < 0n ? -remainder : remainder);\n\t// A refund (negative total) puts the extra cent on the more-negative share.\n\tconst step = cents < 0n ? -1n : 1n;\n\n\tconst base = centShare(baseCents, n - extraShares);\n\tif (extraShares === 0) return { unit, shares: [base] };\n\treturn { unit, shares: [base, centShare(baseCents + step, extraShares)] };\n}\n\n/** A currency share built from its whole-cent coefficient. */\nfunction centShare(cents: bigint, count: number): SplitShare {\n\tconst exact = makeDecimal(cents, 2);\n\treturn { value: decimalToNumber(exact), exact, count };\n}\n\n/**\n * The exact whole-cent coefficient of a money amount, or null when it has no\n * exact magnitude (a live-rate conversion), so the caller falls back to a float\n * even split. Rounds to two places half-away-from-zero, the till rule the rest\n * of the money arithmetic uses.\n */\nfunction centsOfMoney(amount: Value, unit: string): bigint | null {\n\tconst base = moneyExactMagnitude(amount, unit);\n\treturn base === null ? null : decimalRound(base, 2).coef;\n}\n","/**\n * Partial-fraction decomposition of a rational function.\n *\n * `(3x+5)/(x^2-1)` becomes `4/(x-1) - 1/(x+1)`. Two quite different things want\n * this. A person reading a rational function wants to see what it is made of,\n * and the integrator needs it, because a rational function has no general\n * antiderivative rule but every one of these pieces does.\n *\n * ## How the coefficients are found\n *\n * By undetermined coefficients, solved as an exact linear system. The\n * alternative, the cover-up or residue method, is shorter but only handles\n * distinct linear factors directly and needs separate machinery for repeated\n * factors and irreducible quadratics. One linear solve covers all three, and\n * over exact rationals it is answering a question with a definite answer rather\n * than converging on one.\n *\n * ## The one thing it inherits\n *\n * Decomposition is only as fine as the factorization behind it. `Factor.ts`\n * finds rational roots, so it splits off every linear factor, but it does not\n * split a quartic into two irreducible quadratics. When that happens the\n * quartic stays as one denominator with a cubic numerator over it. The result\n * is still correct, just less decomposed than a textbook would write it, and\n * `Integral.ts` then declines rather than guessing.\n */\n\nimport { type SymbolicNode, constNode, powNode } from \"@solve-js/symbolic/SymbolicNode\";\nimport {\n\ttype Rational,\n\tRATIONAL_ZERO,\n\tRATIONAL_ONE,\n\trationalAdd,\n\trationalSub,\n\trationalMul,\n\trationalDiv,\n\trationalNeg,\n\tisRationalZero,\n} from \"@solve-js/symbolic/Rational\";\nimport { toPolynomial, fromPolynomial, polyCoefficients, polyUnivariateVar } from \"@solve-js/symbolic/Polynomial\";\nimport { polynomialDivide, coefficientGcd, isZeroPolynomial } from \"@solve-js/symbolic/Gcd\";\nimport { factorUnivariate } from \"@solve-js/symbolic/Factor\";\nimport { simplifySymbolic } from \"@solve-js/symbolic/Simplify\";\n\n/**\n * Highest denominator degree {@link partialFractions} will decompose.\n *\n * The linear system is one unknown per degree, so the solve is cubic in this\n * number. Twelve keeps a pathological input from turning into a long exact\n * elimination, and matches the degree ceiling factoring already works under.\n */\nexport const APART_MAX_DEGREE = 12;\n\n/** One `numerator / base^power` piece of a decomposition. */\nexport interface PartialFractionTerm {\n\t/** Ascending coefficients of the numerator, of lower degree than the base. */\n\treadonly numerator: readonly Rational[];\n\t/** Ascending coefficients of the irreducible denominator factor, monic. */\n\treadonly base: readonly Rational[];\n\t/** Which power of the base this piece sits over, counting from one. */\n\treadonly power: number;\n}\n\n/** A rational function written as a polynomial plus a sum of simple fractions. */\nexport interface PartialFractionDecomposition {\n\t/** Ascending coefficients of the polynomial part, empty when the fraction was already proper. */\n\treadonly polynomial: readonly Rational[];\n\t/** The fraction pieces, in the order the denominator's factors were found. */\n\treadonly terms: readonly PartialFractionTerm[];\n}\n\n/** Multiplies two ascending coefficient lists. */\nfunction multiply(a: readonly Rational[], b: readonly Rational[]): Rational[] {\n\tif (a.length === 0 || b.length === 0) return [];\n\tconst product: Rational[] = new Array(a.length + b.length - 1).fill(RATIONAL_ZERO);\n\ta.forEach((left, i) => {\n\t\tb.forEach((right, j) => {\n\t\t\tproduct[i + j] = rationalAdd(product[i + j], rationalMul(left, right));\n\t\t});\n\t});\n\treturn product;\n}\n\n/** Raises an ascending coefficient list to a non-negative integer power. */\nfunction power(base: readonly Rational[], exponent: number): Rational[] {\n\tlet result: Rational[] = [RATIONAL_ONE];\n\tfor (let i = 0; i < exponent; i++) result = multiply(result, base);\n\treturn result;\n}\n\n/** Scales an ascending coefficient list. */\nfunction scale(coefficients: readonly Rational[], factor: Rational): Rational[] {\n\treturn coefficients.map(coefficient => rationalDiv(coefficient, factor));\n}\n\n/**\n * The irreducible factors of a monic denominator, as ascending coefficient\n * lists with multiplicity.\n *\n * Routed through {@link factorUnivariate} rather than repeating its rational\n * root search, at the cost of a round trip through the expression tree.\n *\n * The one thing done here first is pulling out the powers of the variable\n * itself. The rational-root theorem needs a non-zero constant term to have any\n * candidates at all, so `x^3-x` comes back from {@link factorUnivariate}\n * unfactored, and a decomposition over `1/(x^3-x)` would then be no\n * decomposition. `factorSymbolic` extracts the common monomial before calling\n * it for the same reason.\n *\n * @param ascending - Ascending coefficients of the monic denominator.\n * @param variable - The variable it is written in.\n * @returns The factors, or `null` when one cannot be read back as a polynomial.\n */\nfunction denominatorFactors(\n\tascending: readonly Rational[],\n\tvariable: string,\n): { base: Rational[]; power: number }[] | null {\n\tconst factors: { base: Rational[]; power: number }[] = [];\n\n\tlet lowest = 0;\n\twhile (lowest < ascending.length && isRationalZero(ascending[lowest])) lowest++;\n\tif (lowest > 0) factors.push({ base: [RATIONAL_ZERO, RATIONAL_ONE], power: lowest });\n\n\tconst remaining = ascending.slice(lowest);\n\tif (remaining.length > 1) {\n\t\tconst factorization = factorUnivariate([...remaining].reverse(), variable);\n\t\tfor (const factor of factorization.factors) {\n\t\t\tconst polynomial = toPolynomial(factor.base);\n\t\t\tif (polynomial === null) return null;\n\t\t\tfactors.push({ base: [...polyCoefficients(polynomial, variable)], power: factor.power });\n\t\t}\n\t}\n\treturn factors.length > 0 ? factors : null;\n}\n\n/** One unknown in the linear system: which factor, which power of it, and which coefficient of that numerator. */\ninterface Unknown {\n\treadonly factor: number;\n\treadonly power: number;\n\treadonly degree: number;\n}\n\n/**\n * Enumerates the unknowns a decomposition needs.\n *\n * A factor of degree `d` appearing to the power `m` contributes `m` numerators\n * of degree below `d`, so `m*d` unknowns. Summed over the factorization that is\n * exactly the degree of the denominator, which is why the system below is\n * square.\n */\nfunction enumerateUnknowns(factors: readonly { base: Rational[]; power: number }[]): Unknown[] {\n\tconst unknowns: Unknown[] = [];\n\tfactors.forEach((factor, index) => {\n\t\tconst factorDegree = factor.base.length - 1;\n\t\tfor (let p = 1; p <= factor.power; p++) {\n\t\t\tfor (let degree = 0; degree < factorDegree; degree++) {\n\t\t\t\tunknowns.push({ factor: index, power: p, degree });\n\t\t\t}\n\t\t}\n\t});\n\treturn unknowns;\n}\n\n/**\n * The polynomial each unknown multiplies once the identity is cleared of\n * denominators.\n *\n * Multiplying `N/(f^p)` by the whole denominator leaves `N` times everything\n * except `f^p`, so the column for the coefficient of `x^k` in `N` is `x^k`\n * times that cofactor.\n */\nfunction unknownColumn(\n\tunknown: Unknown,\n\tfactors: readonly { base: Rational[]; power: number }[],\n\tdenominator: readonly Rational[],\n): Rational[] | null {\n\tconst divisor = power(factors[unknown.factor].base, unknown.power);\n\tconst { quotient, remainder } = polynomialDivide(denominator, divisor);\n\t// The divisor is a factor of the denominator by construction, so a remainder\n\t// here would mean the factorization did not multiply back and the answer\n\t// would be silently wrong.\n\tif (!isZeroPolynomial(remainder)) return null;\n\n\tconst shift: Rational[] = new Array(unknown.degree).fill(RATIONAL_ZERO);\n\tshift.push(RATIONAL_ONE);\n\treturn multiply(quotient, shift);\n}\n\n/**\n * Solves a square linear system over the rationals by Gaussian elimination.\n *\n * @param matrix - Row-major coefficients, modified in place.\n * @param target - The right-hand side, modified in place.\n * @returns The solution, or `null` when the system is singular.\n */\nfunction solveLinearSystem(matrix: Rational[][], target: Rational[]): Rational[] | null {\n\tconst size = target.length;\n\tfor (let column = 0; column < size; column++) {\n\t\tlet pivot = -1;\n\t\tfor (let row = column; row < size; row++) {\n\t\t\tif (!isRationalZero(matrix[row][column])) {\n\t\t\t\tpivot = row;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (pivot === -1) return null;\n\t\t[matrix[column], matrix[pivot]] = [matrix[pivot], matrix[column]];\n\t\t[target[column], target[pivot]] = [target[pivot], target[column]];\n\n\t\tfor (let row = 0; row < size; row++) {\n\t\t\tif (row === column || isRationalZero(matrix[row][column])) continue;\n\t\t\tconst factor = rationalDiv(matrix[row][column], matrix[column][column]);\n\t\t\tfor (let k = column; k < size; k++) {\n\t\t\t\tmatrix[row][k] = rationalSub(matrix[row][k], rationalMul(factor, matrix[column][k]));\n\t\t\t}\n\t\t\ttarget[row] = rationalSub(target[row], rationalMul(factor, target[column]));\n\t\t}\n\t}\n\treturn target.map((value, index) => rationalDiv(value, matrix[index][index]));\n}\n\n/**\n * Decomposes a rational function into partial fractions.\n *\n * @param numerator - Ascending coefficients of the numerator.\n * @param denominator - Ascending coefficients of the denominator.\n * @param variable - The variable both are written in.\n * @returns The decomposition, or `null` when the denominator is constant, above\n * {@link APART_MAX_DEGREE}, or does not factor into pieces this can solve over.\n */\nexport function partialFractions(\n\tnumerator: readonly Rational[],\n\tdenominator: readonly Rational[],\n\tvariable: string,\n): PartialFractionDecomposition | null {\n\tif (denominator.length < 2 || denominator.length - 1 > APART_MAX_DEGREE) return null;\n\n\t// Cancel first, so a fraction that is secretly a polynomial does not get\n\t// decomposed over a factor that is not really there.\n\tconst shared = coefficientGcd(numerator, denominator);\n\tconst reducedNumerator = shared.length > 1 ? polynomialDivide(numerator, shared).quotient : [...numerator];\n\tconst reducedDenominator = shared.length > 1 ? polynomialDivide(denominator, shared).quotient : [...denominator];\n\t// Cancelling can leave no denominator at all, as it does for\n\t// `(x^2-1)/(x-1)`. That is a polynomial and an answer, not a failure.\n\tif (reducedDenominator.length === 1) {\n\t\treturn { polynomial: scale(reducedNumerator, reducedDenominator[0]), terms: [] };\n\t}\n\tif (reducedDenominator.length === 0) return null;\n\n\t// Made monic, so the factorization carries no content and every factor below\n\t// is monic too.\n\tconst leading = reducedDenominator[reducedDenominator.length - 1];\n\tconst monicDenominator = scale(reducedDenominator, leading);\n\tconst scaledNumerator = scale(reducedNumerator, leading);\n\n\tconst { quotient, remainder } = polynomialDivide(scaledNumerator, monicDenominator);\n\tif (isZeroPolynomial(remainder)) return { polynomial: quotient, terms: [] };\n\n\tconst factors = denominatorFactors(monicDenominator, variable);\n\tif (factors === null) return null;\n\n\tconst terms = solveForNumerators(factors, monicDenominator, remainder);\n\treturn terms === null ? null : { polynomial: quotient, terms };\n}\n\n/**\n * Builds and solves the undetermined-coefficient system, then groups the\n * solution back into one numerator per piece.\n */\nfunction solveForNumerators(\n\tfactors: readonly { base: Rational[]; power: number }[],\n\tdenominator: readonly Rational[],\n\tremainder: readonly Rational[],\n): PartialFractionTerm[] | null {\n\tconst unknowns = enumerateUnknowns(factors);\n\tconst size = denominator.length - 1;\n\tif (unknowns.length !== size) return null;\n\n\tconst columns: Rational[][] = [];\n\tfor (const unknown of unknowns) {\n\t\tconst column = unknownColumn(unknown, factors, denominator);\n\t\tif (column === null) return null;\n\t\tcolumns.push(column);\n\t}\n\n\t// Row `i` is the coefficient of `x^i`, which is what makes the system square.\n\tconst matrix: Rational[][] = [];\n\tfor (let row = 0; row < size; row++) {\n\t\tmatrix.push(columns.map(column => column[row] ?? RATIONAL_ZERO));\n\t}\n\tconst target: Rational[] = [];\n\tfor (let row = 0; row < size; row++) target.push(remainder[row] ?? RATIONAL_ZERO);\n\n\tconst solution = solveLinearSystem(matrix, target);\n\tif (solution === null) return null;\n\treturn groupSolution(unknowns, solution, factors);\n}\n\n/** Collects the solved coefficients back into one numerator per `base^power` piece. */\nfunction groupSolution(\n\tunknowns: readonly Unknown[],\n\tsolution: readonly Rational[],\n\tfactors: readonly { base: Rational[]; power: number }[],\n): PartialFractionTerm[] {\n\tconst grouped = new Map<string, Rational[]>();\n\tunknowns.forEach((unknown, index) => {\n\t\tconst key = `${unknown.factor}:${unknown.power}`;\n\t\tconst existing = grouped.get(key) ?? [];\n\t\texisting[unknown.degree] = solution[index];\n\t\tgrouped.set(key, existing);\n\t});\n\n\tconst terms: PartialFractionTerm[] = [];\n\tfor (const [key, coefficients] of grouped) {\n\t\tconst [factorIndex, termPower] = key.split(\":\").map(Number);\n\t\tconst filled = [...coefficients].map(value => value ?? RATIONAL_ZERO);\n\t\t// A piece whose numerator solved to zero is not part of the answer.\n\t\tif (filled.every(isRationalZero)) continue;\n\t\tterms.push({ numerator: filled, base: factors[factorIndex].base, power: termPower });\n\t}\n\treturn terms;\n}\n\n/** Rebuilds an ascending coefficient list as an expression in one variable. */\nexport function coefficientsToNode(coefficients: readonly Rational[], variable: string): SymbolicNode {\n\tconst terms = new Map<string, Rational>();\n\tcoefficients.forEach((coefficient, exponent) => {\n\t\tif (isRationalZero(coefficient)) return;\n\t\tterms.set(exponent === 0 ? \"\" : exponent === 1 ? variable : `${variable}^${exponent}`, coefficient);\n\t});\n\tif (terms.size === 0) return constNode(RATIONAL_ZERO);\n\treturn fromPolynomial({ terms, vars: coefficients.length > 1 ? [variable] : [] });\n}\n\n/**\n * Decomposes a quotient of polynomials into partial fractions.\n *\n * @param node - The expression to decompose.\n * @returns The decomposed sum, or `node` unchanged when it is not a rational\n * function in one variable or has nothing to decompose.\n */\nexport function apartSymbolic(node: SymbolicNode): SymbolicNode {\n\tconst parts = asRationalFunction(node);\n\tif (parts === null) return node;\n\n\tconst decomposition = partialFractions(parts.numerator, parts.denominator, parts.variable);\n\tif (decomposition === null || decomposition.terms.length === 0) return node;\n\n\tlet result: SymbolicNode | null = decomposition.polynomial.length > 0\n\t\t? coefficientsToNode(decomposition.polynomial, parts.variable)\n\t\t: null;\n\n\tfor (const term of decomposition.terms) {\n\t\tconst base = coefficientsToNode(term.base, parts.variable);\n\t\tconst denominator = term.power === 1 ? base : powNode(base, constNode({ n: BigInt(term.power), d: 1n }));\n\t\t// A wholly negative numerator becomes a subtraction rather than the\n\t\t// addition of a negative, which is how partial fractions are written and\n\t\t// which avoids the literal `+-1/(x+1)`.\n\t\tconst negative = isNegativeNumerator(term.numerator);\n\t\tconst numerator = negative ? term.numerator.map(coefficient => rationalNeg(coefficient)) : term.numerator;\n\t\tconst piece: SymbolicNode = {\n\t\t\tkind: \"div\",\n\t\t\tleft: coefficientsToNode(numerator, parts.variable),\n\t\t\tright: denominator,\n\t\t};\n\t\tif (result === null) result = negative ? { kind: \"neg\", operand: piece } : piece;\n\t\telse result = { kind: negative ? \"sub\" : \"add\", left: result, right: piece };\n\t}\n\treturn result === null ? node : simplifySymbolic(result);\n}\n\n/** Whether every coefficient of a numerator is at most zero, so the whole piece reads better subtracted. */\nfunction isNegativeNumerator(coefficients: readonly Rational[]): boolean {\n\treturn coefficients.some(coefficient => coefficient.n < 0n)\n\t\t&& coefficients.every(coefficient => coefficient.n <= 0n);\n}\n\n/** A quotient split into ascending numerator and denominator coefficients over one variable. */\nexport interface RationalFunctionParts {\n\treadonly numerator: readonly Rational[];\n\treadonly denominator: readonly Rational[];\n\treadonly variable: string;\n}\n\n/**\n * Reads a quotient of univariate polynomials out of an expression.\n *\n * @param node - The expression to read.\n * @returns The two coefficient lists and the variable, or `null` when the\n * expression is not such a quotient.\n */\nexport function asRationalFunction(node: SymbolicNode): RationalFunctionParts | null {\n\tif (node.kind !== \"div\") return null;\n\n\tconst numerator = toPolynomial(node.left);\n\tconst denominator = toPolynomial(node.right);\n\tif (numerator === null || denominator === null) return null;\n\n\t// The variable has to come from the denominator: a numerator can legitimately\n\t// be a constant, and a constant denominator is not a rational function at all.\n\tconst variable = polyUnivariateVar(denominator);\n\tif (variable === null) return null;\n\tif (numerator.vars.some(name => name !== variable)) return null;\n\n\treturn {\n\t\tnumerator: polyCoefficients(numerator, variable),\n\t\tdenominator: polyCoefficients(denominator, variable),\n\t\tvariable,\n\t};\n}\n\n/** Multiplies two ascending coefficient lists, exposed so a caller can rebuild a decomposition and check it. */\nexport function multiplyCoefficients(a: readonly Rational[], b: readonly Rational[]): Rational[] {\n\treturn multiply(a, b);\n}\n\n/** Raises an ascending coefficient list to a power, exposed alongside {@link multiplyCoefficients}. */\nexport function powerCoefficients(base: readonly Rational[], exponent: number): Rational[] {\n\treturn power(base, exponent);\n}\n","/**\n * Symbolic differentiation.\n *\n * Genuinely symbolic, not a finite-difference approximation. Once a `pow` node\n * and a function-application node exist, applying the differentiation rules to\n * the tree is both easier to get right and exact, where a finite difference\n * needs a step size chosen against competing truncation and rounding errors and\n * is wrong in the last digits by construction.\n *\n * An unknown function is left as an unevaluated `der` call rather than guessed\n * at. Returning something plausible for a function whose derivative this module\n * does not know would be the worst available outcome.\n */\n\nimport {\n\ttype SymbolicNode,\n\tconstNode,\n\tvarNode,\n\tpowNode,\n\tcallNode,\n} from \"@solve-js/symbolic/SymbolicNode\";\nimport { RATIONAL_ONE, RATIONAL_ZERO, rationalSub } from \"@solve-js/symbolic/Rational\";\nimport { simplifySymbolic } from \"@solve-js/symbolic/Simplify\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Highest derivative order accepted by {@link differentiate}.\n *\n * Each order re-differentiates the previous result, and the quotient rule in\n * particular grows a tree quickly, so repeated differentiation is the operation\n * most able to run away.\n */\nexport const DERIVATIVE_MAX_ORDER = 16;\n\n/** Shorthand for the constant zero node. */\nfunction zero(): SymbolicNode {\n\treturn constNode(RATIONAL_ZERO);\n}\n\n/** Shorthand for the constant one node. */\nfunction one(): SymbolicNode {\n\treturn constNode(RATIONAL_ONE);\n}\n\n/**\n * The derivative of a known single-argument function, in terms of its own\n * argument, before the chain rule multiplies by the argument's derivative.\n *\n * @param name - The function name.\n * @param argument - The argument expression, substituted into the result.\n * @returns The derivative expression, or `null` when the function is not one\n * this module knows how to differentiate.\n */\nexport function functionDerivative(name: string, argument: SymbolicNode): SymbolicNode | null {\n\tswitch (name) {\n\t\tcase \"sin\":\n\t\t\treturn callNode(\"cos\", [argument]);\n\t\tcase \"cos\":\n\t\t\treturn { kind: \"neg\", operand: callNode(\"sin\", [argument]) };\n\t\tcase \"tan\":\n\t\t\t// 1/cos(u)^2, avoiding a sec() this engine has no name for.\n\t\t\treturn { kind: \"div\", left: one(), right: powNode(callNode(\"cos\", [argument]), constNode(2)) };\n\t\tcase \"exp\":\n\t\t\treturn callNode(\"exp\", [argument]);\n\t\tcase \"log\":\n\t\t\treturn { kind: \"div\", left: one(), right: argument };\n\t\tcase \"sqrt\":\n\t\t\treturn {\n\t\t\t\tkind: \"div\",\n\t\t\t\tleft: one(),\n\t\t\t\tright: { kind: \"mul\", left: constNode(2), right: callNode(\"sqrt\", [argument]) },\n\t\t\t};\n\t\tcase \"asin\":\n\t\t\treturn { kind: \"div\", left: one(), right: callNode(\"sqrt\", [oneMinusSquare(argument)]) };\n\t\tcase \"acos\":\n\t\t\treturn { kind: \"neg\", operand: { kind: \"div\", left: one(), right: callNode(\"sqrt\", [oneMinusSquare(argument)]) } };\n\t\tcase \"atan\":\n\t\t\treturn { kind: \"div\", left: one(), right: onePlusSquare(argument) };\n\t\tcase \"sinh\":\n\t\t\treturn callNode(\"cosh\", [argument]);\n\t\tcase \"cosh\":\n\t\t\treturn callNode(\"sinh\", [argument]);\n\t\tcase \"tanh\":\n\t\t\treturn { kind: \"div\", left: one(), right: powNode(callNode(\"cosh\", [argument]), constNode(2)) };\n\t\tcase \"abs\":\n\t\t\treturn callNode(\"sign\", [argument]);\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/** `1 - u^2`, shared by the inverse trigonometric derivatives. */\nfunction oneMinusSquare(argument: SymbolicNode): SymbolicNode {\n\treturn { kind: \"sub\", left: one(), right: powNode(argument, constNode(2)) };\n}\n\n/** `1 + u^2`, for the arctangent derivative. */\nfunction onePlusSquare(argument: SymbolicNode): SymbolicNode {\n\treturn { kind: \"add\", left: one(), right: powNode(argument, constNode(2)) };\n}\n\n/**\n * Differentiates an expression with respect to one variable.\n *\n * @param node - The expression to differentiate.\n * @param variable - The variable to differentiate with respect to.\n * @param order - How many times, defaulting to once.\n * @returns The simplified derivative.\n * @throws {EngineError} `SYMBOLIC_DERIVATIVE_ORDER_LIMIT` past\n * {@link DERIVATIVE_MAX_ORDER}.\n */\nexport function differentiate(node: SymbolicNode, variable: string, order = 1): SymbolicNode {\n\tif (order < 0 || !Number.isInteger(order)) {\n\t\tthrow ErrorFactory.execution(\"SYMBOLIC_DERIVATIVE_ORDER_LIMIT\", \"A derivative order must be a whole number, at least zero.\");\n\t}\n\tif (order > DERIVATIVE_MAX_ORDER) {\n\t\tthrow ErrorFactory.execution(\n\t\t\t\"SYMBOLIC_DERIVATIVE_ORDER_LIMIT\",\n\t\t\t`A derivative order above ${DERIVATIVE_MAX_ORDER} is not supported.`,\n\t\t\t{ limit: DERIVATIVE_MAX_ORDER },\n\t\t);\n\t}\n\n\tlet result = simplifySymbolic(node);\n\tfor (let i = 0; i < order; i++) result = simplifySymbolic(derive(result, variable));\n\treturn result;\n}\n\n/** One differentiation pass, before simplification. */\nfunction derive(node: SymbolicNode, variable: string): SymbolicNode {\n\tswitch (node.kind) {\n\t\tcase \"const\":\n\t\tcase \"complex\":\n\t\t\treturn zero();\n\t\tcase \"var\":\n\t\t\treturn node.name === variable ? one() : zero();\n\t\tcase \"add\":\n\t\t\treturn { kind: \"add\", left: derive(node.left, variable), right: derive(node.right, variable) };\n\t\tcase \"sub\":\n\t\t\treturn { kind: \"sub\", left: derive(node.left, variable), right: derive(node.right, variable) };\n\t\tcase \"neg\":\n\t\t\treturn { kind: \"neg\", operand: derive(node.operand, variable) };\n\t\tcase \"mul\":\n\t\t\t// Product rule.\n\t\t\treturn {\n\t\t\t\tkind: \"add\",\n\t\t\t\tleft: { kind: \"mul\", left: derive(node.left, variable), right: node.right },\n\t\t\t\tright: { kind: \"mul\", left: node.left, right: derive(node.right, variable) },\n\t\t\t};\n\t\tcase \"div\":\n\t\t\t// Quotient rule.\n\t\t\treturn {\n\t\t\t\tkind: \"div\",\n\t\t\t\tleft: {\n\t\t\t\t\tkind: \"sub\",\n\t\t\t\t\tleft: { kind: \"mul\", left: derive(node.left, variable), right: node.right },\n\t\t\t\t\tright: { kind: \"mul\", left: node.left, right: derive(node.right, variable) },\n\t\t\t\t},\n\t\t\t\tright: powNode(node.right, constNode(2)),\n\t\t\t};\n\t\tcase \"pow\":\n\t\t\treturn derivePow(node, variable);\n\t\tcase \"call\": {\n\t\t\tif (node.args.length !== 1) return unevaluated(node, variable);\n\t\t\tconst outer = functionDerivative(node.name, node.args[0]);\n\t\t\tif (outer === null) return unevaluated(node, variable);\n\t\t\t// Chain rule.\n\t\t\treturn { kind: \"mul\", left: outer, right: derive(node.args[0], variable) };\n\t\t}\n\t}\n}\n\n/**\n * Differentiates a power.\n *\n * The constant-exponent case is the ordinary power rule with the chain rule\n * applied to the base. The general `f^g` case is only attempted when it is\n * sound to do so: with a constant positive base, where it reduces to\n * `f^g * ln(f) * g'`. A general `f^g` would need `ln(f)`, which is undefined\n * for a negative base, so guessing there could produce a formula that is wrong\n * exactly where the original expression was fine.\n */\nfunction derivePow(node: SymbolicNode & { kind: \"pow\" }, variable: string): SymbolicNode {\n\tif (node.exponent.kind === \"const\") {\n\t\tconst reduced = constNode(rationalSub(node.exponent.value, RATIONAL_ONE));\n\t\treturn {\n\t\t\tkind: \"mul\",\n\t\t\tleft: { kind: \"mul\", left: node.exponent, right: powNode(node.base, reduced) },\n\t\t\tright: derive(node.base, variable),\n\t\t};\n\t}\n\tif (node.base.kind === \"const\" && node.base.value.n > 0n) {\n\t\treturn {\n\t\t\tkind: \"mul\",\n\t\t\tleft: { kind: \"mul\", left: node, right: callNode(\"log\", [node.base]) },\n\t\t\tright: derive(node.exponent, variable),\n\t\t};\n\t}\n\treturn unevaluated(node, variable);\n}\n\n/** Leaves an unknown derivative as an explicit `der(expr, variable)` call rather than inventing an answer for it. */\nfunction unevaluated(node: SymbolicNode, variable: string): SymbolicNode {\n\treturn callNode(\"der\", [node, varNode(variable)]);\n}\n","/**\n * Symbolic indefinite integration.\n *\n * ## Failing loudly is the feature\n *\n * Integration, unlike differentiation, has no algorithm that always succeeds:\n * plenty of perfectly ordinary expressions have no elementary antiderivative at\n * all, `exp(x^2)` and `sin(x)/x` among them. So this handles polynomials\n * exactly, plus a small table of standard forms with a linear inner argument,\n * and **reports what it cannot do rather than approximating**.\n *\n * A CAS that quietly returns something wrong for `integral(exp(x^2), x)` is\n * worse than one that says it cannot, because the wrong answer is\n * indistinguishable from a right one at the point of use.\n *\n * The constant of integration is omitted, as is conventional for a calculator.\n */\n\nimport {\n\ttype SymbolicNode,\n\tconstNode,\n\tvarNode,\n\tpowNode,\n\tcallNode,\n\tfreeVariables,\n} from \"@solve-js/symbolic/SymbolicNode\";\nimport {\n\ttype Rational,\n\tRATIONAL_ZERO,\n\trationalSub,\n\trationalMul,\n\trationalDiv,\n\tisRationalZero,\n} from \"@solve-js/symbolic/Rational\";\nimport { toPolynomial, polyCoefficients, polyDegree } from \"@solve-js/symbolic/Polynomial\";\nimport { simplifySymbolic } from \"@solve-js/symbolic/Simplify\";\nimport {\n\ttype PartialFractionTerm,\n\tpartialFractions,\n\tasRationalFunction,\n\tcoefficientsToNode,\n} from \"@solve-js/symbolic/PartialFractions\";\nimport { surdNode } from \"@solve-js/symbolic/Radicals\";\n\n/** The result of an integration attempt, which may legitimately fail. */\nexport type IntegralResult =\n\t/** An antiderivative was found. */\n\t| { readonly ok: true; readonly value: SymbolicNode }\n\t/** None was found, with the reason stated so the caller can pass it on. */\n\t| { readonly ok: false; readonly reason: string };\n\n/** `a*x + b` decomposed, or `null` when the expression is not linear in `variable`. */\ninterface LinearArgument {\n\treadonly slope: Rational;\n\treadonly intercept: Rational;\n}\n\n/** Reads `a*x + b` out of an expression, which is the only inner-argument shape the table below handles. */\nfunction asLinear(node: SymbolicNode, variable: string): LinearArgument | null {\n\tconst polynomial = toPolynomial(node);\n\tif (polynomial === null) return null;\n\tconst others = polynomial.vars.filter(name => name !== variable);\n\tif (others.length > 0) return null;\n\tif (polyDegree(polynomial, variable) > 1) return null;\n\n\tconst ascending = polyCoefficients(polynomial, variable);\n\tconst intercept = ascending[0] ?? { n: 0n, d: 1n };\n\tconst slope = ascending[1] ?? { n: 0n, d: 1n };\n\treturn isRationalZero(slope) ? null : { slope, intercept };\n}\n\n/**\n * Integrates a polynomial term by term with the power rule.\n *\n * `x^-1` is deliberately excluded here and handled by the table instead, since\n * its antiderivative is a logarithm rather than a power. In practice the\n * polynomial form cannot carry a negative exponent anyway, but stating the\n * boundary keeps the two paths from overlapping silently.\n */\nfunction integratePolynomial(node: SymbolicNode, variable: string): IntegralResult | null {\n\tconst polynomial = toPolynomial(node);\n\tif (polynomial === null) return null;\n\tconst others = polynomial.vars.filter(name => name !== variable);\n\tif (others.length > 0) {\n\t\treturn { ok: false, reason: `it involves more than one unknown (${others.join(\", \")})` };\n\t}\n\n\tconst ascending = polyCoefficients(polynomial, variable);\n\tlet result: SymbolicNode = constNode(0);\n\tascending.forEach((coeff, power) => {\n\t\tif (isRationalZero(coeff)) return;\n\t\tconst nextPower = power + 1;\n\t\tconst scaled = rationalDiv(coeff, { n: BigInt(nextPower), d: 1n });\n\t\tconst term: SymbolicNode = {\n\t\t\tkind: \"mul\",\n\t\t\tleft: constNode(scaled),\n\t\t\tright: nextPower === 1 ? varNode(variable) : powNode(varNode(variable), constNode(nextPower)),\n\t\t};\n\t\tresult = { kind: \"add\", left: result, right: term };\n\t});\n\treturn { ok: true, value: simplifySymbolic(result) };\n}\n\n/**\n * The standard-form table, for a function of a linear argument.\n *\n * Every entry divides by the inner slope, which is the linear-substitution rule\n * `integral f(ax+b) dx = F(ax+b)/a`.\n */\nfunction integrateStandardForm(node: SymbolicNode, variable: string): IntegralResult | null {\n\tif (node.kind !== \"call\" || node.args.length !== 1) return null;\n\tconst linear = asLinear(node.args[0], variable);\n\tif (linear === null) return null;\n\n\tconst inner = node.args[0];\n\tconst divideBySlope = (value: SymbolicNode): SymbolicNode =>\n\t\tsimplifySymbolic({ kind: \"div\", left: value, right: constNode(linear.slope) });\n\n\tswitch (node.name) {\n\t\tcase \"exp\":\n\t\t\treturn { ok: true, value: divideBySlope(callNode(\"exp\", [inner])) };\n\t\tcase \"sin\":\n\t\t\treturn { ok: true, value: divideBySlope({ kind: \"neg\", operand: callNode(\"cos\", [inner]) }) };\n\t\tcase \"cos\":\n\t\t\treturn { ok: true, value: divideBySlope(callNode(\"sin\", [inner])) };\n\t\tcase \"log\":\n\t\t\t// integral ln(u) du = u*ln(u) - u, then divided by the inner slope.\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tvalue: divideBySlope({\n\t\t\t\t\tkind: \"sub\",\n\t\t\t\t\tleft: { kind: \"mul\", left: inner, right: callNode(\"log\", [inner]) },\n\t\t\t\t\tright: inner,\n\t\t\t\t}),\n\t\t\t};\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/** `1/x` and `1/(1+x^2)`, whose antiderivatives are a logarithm and an arctangent rather than powers. */\nfunction integrateReciprocalForms(node: SymbolicNode, variable: string): IntegralResult | null {\n\tif (node.kind !== \"div\") return null;\n\tif (node.left.kind !== \"const\" || !isRationalOneNode(node.left.value)) return null;\n\n\tconst linear = asLinear(node.right, variable);\n\tif (linear !== null) {\n\t\t// integral 1/(ax+b) dx = ln(|ax+b|)/a. Written without the absolute value\n\t\t// bars, matching how the rest of this engine treats log's domain.\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: simplifySymbolic({\n\t\t\t\tkind: \"div\",\n\t\t\t\tleft: callNode(\"log\", [node.right]),\n\t\t\t\tright: constNode(linear.slope),\n\t\t\t}),\n\t\t};\n\t}\n\n\t// integral 1/(1+x^2) dx = atan(x), the one non-linear denominator worth a\n\t// table entry because it turns up constantly.\n\tconst denominator = toPolynomial(node.right);\n\tif (denominator !== null && denominator.vars.length === 1 && denominator.vars[0] === variable) {\n\t\tconst ascending = polyCoefficients(denominator, variable);\n\t\tconst isOnePlusSquare =\n\t\t\tascending.length === 3 &&\n\t\t\tisRationalOneNode(ascending[0]) &&\n\t\t\tisRationalZero(ascending[1]) &&\n\t\t\tisRationalOneNode(ascending[2]);\n\t\tif (isOnePlusSquare) return { ok: true, value: callNode(\"atan\", [varNode(variable)]) };\n\t}\n\treturn null;\n}\n\n/** Whether a rational is exactly one. */\nfunction isRationalOneNode(value: Rational): boolean {\n\treturn value.n === 1n && value.d === 1n;\n}\n\n/**\n * Integrates any rational function whose denominator factors into linear pieces\n * and distinct irreducible quadratics.\n *\n * A quotient of polynomials has no single antiderivative rule, but partial\n * fractions turns it into a sum of pieces that each do have one, which is what\n * makes this the general method rather than another table entry. The four\n * shapes are `A/(x-a)` giving a logarithm, `A/(x-a)^k` giving a power,\n * `(Bx+C)/(quadratic)` giving a logarithm plus an arctangent, and the\n * polynomial part left over from the division.\n */\nfunction integrateRationalFunction(node: SymbolicNode, variable: string): IntegralResult | null {\n\tconst parts = asRationalFunction(node);\n\tif (parts === null || parts.variable !== variable) return null;\n\n\tconst decomposition = partialFractions(parts.numerator, parts.denominator, variable);\n\tif (decomposition === null) return null;\n\n\tlet result: SymbolicNode = decomposition.polynomial.length > 0\n\t\t? polynomialAntiderivative(decomposition.polynomial, variable)\n\t\t: constNode(0);\n\n\tfor (const term of decomposition.terms) {\n\t\tconst piece = integrateTerm(term, variable);\n\t\tif (piece === null) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\treason: \"its denominator has a repeated irreducible quadratic factor, which needs a reduction formula this does not have\",\n\t\t\t};\n\t\t}\n\t\tresult = { kind: \"add\", left: result, right: piece };\n\t}\n\treturn { ok: true, value: simplifySymbolic(result) };\n}\n\n/** The antiderivative of one partial-fraction piece, or `null` for a shape with no rule here. */\nfunction integrateTerm(term: PartialFractionTerm, variable: string): SymbolicNode | null {\n\tconst baseDegree = term.base.length - 1;\n\tconst base = coefficientsToNode(term.base, variable);\n\n\tif (baseDegree === 1) {\n\t\tconst coefficient = term.numerator[0] ?? RATIONAL_ZERO;\n\t\t// integral A/(x-a) dx = A ln(x-a), written without absolute-value bars to\n\t\t// match how the rest of this module treats log's domain.\n\t\tif (term.power === 1) {\n\t\t\treturn { kind: \"mul\", left: constNode(coefficient), right: callNode(\"log\", [base]) };\n\t\t}\n\t\t// integral A/(x-a)^k dx = -A / ((k-1)(x-a)^(k-1))\n\t\tconst reduced = term.power - 1;\n\t\tconst scaled = rationalDiv(coefficient, { n: BigInt(-reduced), d: 1n });\n\t\treturn {\n\t\t\tkind: \"div\",\n\t\t\tleft: constNode(scaled),\n\t\t\tright: powNode(base, constNode({ n: BigInt(reduced), d: 1n })),\n\t\t};\n\t}\n\n\t// A repeated quadratic needs the reduction formula, which is a genuinely\n\t// different piece of machinery and is declined rather than approximated.\n\tif (baseDegree !== 2 || term.power !== 1) return null;\n\treturn integrateQuadraticTerm(term, variable, base);\n}\n\n/**\n * The antiderivative of `(Bx+C)/(x^2+px+q)` for an irreducible quadratic.\n *\n * Split as `(B/2)` times the derivative of the denominator over the\n * denominator, which integrates to a logarithm, plus what is left over, which\n * is a constant over a completed square and integrates to an arctangent. The\n * half-width of that square is `sqrt(q - p^2/4)`, real and positive exactly\n * because the quadratic is irreducible.\n */\nfunction integrateQuadraticTerm(term: PartialFractionTerm, variable: string, base: SymbolicNode): SymbolicNode {\n\tconst constant = term.numerator[0] ?? RATIONAL_ZERO;\n\tconst linear = term.numerator[1] ?? RATIONAL_ZERO;\n\tconst [q, p] = term.base;\n\n\tconst half = { n: 1n, d: 2n };\n\tconst halfP = rationalMul(p, half);\n\tconst logarithm: SymbolicNode = {\n\t\tkind: \"mul\",\n\t\tleft: constNode(rationalMul(linear, half)),\n\t\tright: callNode(\"log\", [base]),\n\t};\n\n\t// What the logarithm did not account for: C - B*p/2, over the shifted square.\n\tconst leftover = rationalSub(constant, rationalMul(linear, halfP));\n\tif (isRationalZero(leftover)) return logarithm;\n\n\tconst width = surdNode(rationalSub(q, rationalMul(halfP, halfP)));\n\tconst shifted: SymbolicNode = {\n\t\tkind: \"add\",\n\t\tleft: varNode(variable),\n\t\tright: constNode(halfP),\n\t};\n\tconst arctangent: SymbolicNode = {\n\t\tkind: \"mul\",\n\t\tleft: { kind: \"div\", left: constNode(leftover), right: width },\n\t\tright: callNode(\"atan\", [{ kind: \"div\", left: shifted, right: width }]),\n\t};\n\treturn isRationalZero(linear) ? arctangent : { kind: \"add\", left: logarithm, right: arctangent };\n}\n\n/** The antiderivative of a polynomial given as ascending coefficients. */\nfunction polynomialAntiderivative(ascending: readonly Rational[], variable: string): SymbolicNode {\n\tlet result: SymbolicNode = constNode(0);\n\tascending.forEach((coeff, exponent) => {\n\t\tif (isRationalZero(coeff)) return;\n\t\tconst nextPower = exponent + 1;\n\t\tconst scaled = rationalDiv(coeff, { n: BigInt(nextPower), d: 1n });\n\t\tconst term: SymbolicNode = {\n\t\t\tkind: \"mul\",\n\t\t\tleft: constNode(scaled),\n\t\t\tright: nextPower === 1 ? varNode(variable) : powNode(varNode(variable), constNode(nextPower)),\n\t\t};\n\t\tresult = { kind: \"add\", left: result, right: term };\n\t});\n\treturn result;\n}\n\n/**\n * Finds an indefinite integral, or reports that it could not.\n *\n * @param node - The expression to integrate.\n * @param variable - The variable of integration.\n * @returns The antiderivative, without a constant of integration, or a stated\n * reason for declining.\n */\nexport function integrate(node: SymbolicNode, variable: string): IntegralResult {\n\tconst simplified = simplifySymbolic(node);\n\n\t// A constant integrates to itself times the variable, including the case\n\t// where the expression involves other unknowns but not this one.\n\tif (!freeVariables(simplified).has(variable)) {\n\t\treturn { ok: true, value: simplifySymbolic({ kind: \"mul\", left: simplified, right: varNode(variable) }) };\n\t}\n\n\tconst polynomial = integratePolynomial(simplified, variable);\n\tif (polynomial !== null) return polynomial;\n\n\tconst standard = integrateStandardForm(simplified, variable);\n\tif (standard !== null) return standard;\n\n\tconst reciprocal = integrateReciprocalForms(simplified, variable);\n\tif (reciprocal !== null) return reciprocal;\n\n\t// Tried after the two tables above, which reach the same shapes by a shorter\n\t// route and produce a tidier answer for them: `1/(2x+1)` is better read as\n\t// `log(2x+1)/2` than as the same thing routed through a decomposition.\n\tconst rationalFunction = integrateRationalFunction(simplified, variable);\n\tif (rationalFunction !== null) return rationalFunction;\n\n\t// A sum is integrable term by term whenever each term is, which covers the\n\t// common \"polynomial plus a standard form\" shape.\n\tif (simplified.kind === \"add\" || simplified.kind === \"sub\") {\n\t\tconst left = integrate(simplified.left, variable);\n\t\tif (!left.ok) return left;\n\t\tconst right = integrate(simplified.right, variable);\n\t\tif (!right.ok) return right;\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: simplifySymbolic({ kind: simplified.kind, left: left.value, right: right.value }),\n\t\t};\n\t}\n\n\t// A constant multiple comes out front.\n\tif (simplified.kind === \"mul\" && simplified.left.kind === \"const\") {\n\t\tconst inner = integrate(simplified.right, variable);\n\t\tif (!inner.ok) return inner;\n\t\treturn { ok: true, value: simplifySymbolic({ kind: \"mul\", left: simplified.left, right: inner.value }) };\n\t}\n\n\treturn {\n\t\tok: false,\n\t\treason: \"no elementary antiderivative is known for this expression\",\n\t};\n}\n\n","/**\n * Taylor series expansion, and the Jacobian matrix.\n *\n * Both are built directly on {@link differentiate}, so both are exact wherever\n * differentiation is. A Taylor coefficient is `f^(n)(a) / n!`, which needs the\n * n-th derivative evaluated *at a point*, and that evaluation is the one place\n * this can fail: a derivative that does not reduce to a plain number at the\n * point has no exact rational coefficient, and this reports that rather than\n * approximating one.\n *\n * That is why the exact values of the standard functions at zero (`sin(0)`,\n * `cos(0)`, `exp(0)`, and so on) matter to the simplifier's own folding: they\n * are what makes the familiar series around the origin come out exactly.\n */\n\nimport {\n\ttype SymbolicNode,\n\tconstNode,\n\tvarNode,\n\tpowNode,\n\tsubstitute,\n} from \"@solve-js/symbolic/SymbolicNode\";\nimport { type Rational, RATIONAL_ZERO, rationalDiv, isRationalZero } from \"@solve-js/symbolic/Rational\";\nimport { simplifySymbolic } from \"@solve-js/symbolic/Simplify\";\nimport { differentiate } from \"@solve-js/symbolic/Derivative\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Highest Taylor degree accepted.\n *\n * Each term needs one more derivative than the last, so cost grows with the\n * square of the degree once the expressions themselves start growing.\n */\nexport const TAYLOR_MAX_DEGREE = 16;\n\n/**\n * Expands an expression as a Taylor series about a point.\n *\n * @param node - The expression to expand.\n * @param variable - The variable to expand in.\n * @param point - The point to expand about, `0` giving a Maclaurin series.\n * @param degree - The highest power to include.\n * @returns The series as an expression.\n * @throws {EngineError} `SYMBOLIC_TAYLOR_DEGREE_LIMIT` past\n * {@link TAYLOR_MAX_DEGREE}, or `SYMBOLIC_TAYLOR_INEXACT` when a coefficient\n * does not reduce to an exact number at the point.\n */\nexport function taylorSeries(node: SymbolicNode, variable: string, point: Rational, degree: number): SymbolicNode {\n\tif (degree < 0 || !Number.isInteger(degree) || degree > TAYLOR_MAX_DEGREE) {\n\t\tthrow ErrorFactory.execution(\n\t\t\t\"SYMBOLIC_TAYLOR_DEGREE_LIMIT\",\n\t\t\t`A Taylor degree must be a whole number from 0 to ${TAYLOR_MAX_DEGREE}.`,\n\t\t\t{ limit: TAYLOR_MAX_DEGREE },\n\t\t);\n\t}\n\n\tconst pointNode = constNode(point);\n\tlet factorial = 1n;\n\tlet result: SymbolicNode = constNode(RATIONAL_ZERO);\n\n\tfor (let order = 0; order <= degree; order++) {\n\t\tif (order > 0) factorial *= BigInt(order);\n\n\t\tconst derivative = differentiate(node, variable, order);\n\t\tconst atPoint = simplifySymbolic(substitute(derivative, variable, pointNode));\n\t\tif (atPoint.kind !== \"const\") {\n\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\"SYMBOLIC_TAYLOR_INEXACT\",\n\t\t\t\t`The derivative of order ${order} does not reduce to an exact number at the expansion point, so this series cannot be computed exactly.`,\n\t\t\t\t{ order },\n\t\t\t);\n\t\t}\n\n\t\tconst coefficient = rationalDiv(atPoint.value, { n: factorial, d: 1n });\n\t\tif (isRationalZero(coefficient)) continue;\n\n\t\t// (x - a)^order, collapsing to 1 and to (x - a) at the low orders so the\n\t\t// series reads the way it is written rather than carrying `^1` and `^0`.\n\t\tconst shifted: SymbolicNode = isRationalZero(point)\n\t\t\t? varNode(variable)\n\t\t\t: { kind: \"sub\", left: varNode(variable), right: pointNode };\n\t\tconst power: SymbolicNode =\n\t\t\torder === 0 ? constNode(1) : order === 1 ? shifted : powNode(shifted, constNode(order));\n\n\t\tresult = { kind: \"add\", left: result, right: { kind: \"mul\", left: constNode(coefficient), right: power } };\n\t}\n\n\treturn simplifySymbolic(result);\n}\n\n/**\n * The Jacobian: each row is one function's gradient.\n *\n * @param functions - The functions, in row order.\n * @param variables - The variables, in column order.\n * @returns A row-major grid of partial derivatives, entry `[i][j]` being the\n * derivative of `functions[i]` with respect to `variables[j]`.\n */\nexport function jacobian(functions: readonly SymbolicNode[], variables: readonly string[]): SymbolicNode[][] {\n\treturn functions.map(fn => variables.map(variable => differentiate(fn, variable)));\n}\n","/**\n * Per-engine state that used to live in module-level singletons.\n *\n * Two {@link ExpressionEngine} instances in one process could not be isolated\n * from each other, because the registries they depend on were module globals\n * shared by every instance. Registering a package mutated state that another\n * engine was already reading. Tests worked only because they cleared those\n * globals by hand, and per-document engines were safe only because\n * registration happened to be idempotent.\n *\n * An `EngineContext` is created by the `ExpressionEngine` constructor and owned\n * by that engine. Anything that needs one of these registries receives the\n * context rather than importing a singleton.\n *\n * Runtime imports here are restricted to leaf modules of `vm/`. This file is\n * imported by `vm/`, which `engine/` imports in turn, so pulling in anything\n * that reaches back into `engine/` would close a cycle. `OpRegistry` is safe\n * because it imports only types plus the error factory. Everything else arrives\n * through `import type`, which is erased before the code runs.\n */\n\nimport type { Value } from \"@solve-js/vm/Value\";\nimport type { LineExecutionContext } from \"@solve-js/vm/VM\";\nimport { OpRegistry } from \"@solve-js/vm/OpRegistry\";\n\n/**\n * A function a package contributes to the VM, reachable from bytecode through\n * `CALL_PLUGIN`.\n *\n * Returning a promise puts the line into the pending state rather than\n * blocking: the engine resolves it and re-executes.\n */\nexport type PluginFunctionHandler = (\n\targs: Value[],\n\tcontext?: LineExecutionContext,\n) => Value | Promise<Value>;\n\n/**\n * The registries one engine instance owns.\n *\n * Members are added here as each former singleton is migrated. The migration\n * order is deliberate and recorded in `docs-internal/plans`: plugin functions,\n * then the opcode registry, the variable resolver, the lexer, and finally\n * currency exchange. The lexer comes near the end because package registration\n * writes vocabularies into it, so moving it early would churn every package.\n *\n * Currency exchange is deliberately NOT migrated, which is a departure from\n * that plan. `CurrencyExchangeService` holds a cache of live market rates with\n * a fifteen minute freshness window and no per-engine configuration. Sharing is\n * the correct behaviour there: giving each engine its own would make two\n * engines in one process fetch the same public endpoint independently, and let\n * them disagree about the rate for one currency pair at one moment. The\n * singleton rationale, that one engine's registration should not be visible to\n * another, does not apply to a cache of state that is global in the real world.\n *\n * If a host ever needs per-engine rates, for a what-if scenario against\n * historical figures, the answer is an optional override on the context that\n * falls back to the shared cache, not a private copy per engine.\n */\nexport interface EngineContext {\n\t/**\n\t * Package-contributed VM functions, keyed by the index the bytecode\n\t * carries.\n\t *\n\t * Indices come from `allocatePluginFunctionIndex()`. Two packages picking\n\t * the same number by hand would silently overwrite one another, which is\n\t * why the allocator exists and why nothing should hardcode an index.\n\t */\n\treadonly pluginFunctions: Record<number, PluginFunctionHandler>;\n\n\t/**\n\t * Custom opcode handlers a package registered.\n\t *\n\t * Largely vestigial: packages reach the VM through `CALL_PLUGIN` and\n\t * {@link EngineContext.pluginFunctions} now, and nothing in the built-in\n\t * set registers an opcode. It moves here anyway because the VM interface\n\t * still requires a registry, and one shared instance would put any future\n\t * registration back into every engine at once.\n\t */\n\treadonly opRegistry: OpRegistry;\n\n\t/**\n\t * Which package registered each plugin function index.\n\t *\n\t * The VM emits a pending result when a plugin function returns a promise,\n\t * and that result carries the owning package so diagnostics and the error\n\t * surface can name it. Without this the VM had nothing to report and sent an\n\t * empty string, so every async failure looked as though it came from\n\t * nowhere.\n\t */\n\treadonly pluginFunctionOwners: Record<number, string>;\n}\n\n/**\n * Create a context with empty registries.\n *\n * @returns A context owned by exactly one engine.\n */\nexport function createEngineContext(): EngineContext {\n\treturn {\n\t\tpluginFunctions: {},\n\t\topRegistry: new OpRegistry(),\n\t\tpluginFunctionOwners: {},\n\t};\n}\n\n/**\n * The context backing the deprecated module-level exports.\n *\n * Exists so the `shared*` singletons can keep working, against real state,\n * while callers move across one at a time. It is not a fallback for an engine\n * that forgot to make its own: an engine always creates its own context, and\n * anything reaching for this one is code that has not been migrated yet.\n *\n * @deprecated Take an {@link EngineContext} instead. This is removed once the\n * migration finishes.\n */\nexport const defaultEngineContext: EngineContext = createEngineContext();\n","/**\n * U.S. CPI-U (Consumer Price Index for All Urban Consumers, \"U.S. city\n * average, all items\", 1982-84=100 base) annual average index values.\n *\n * ── DATA VINTAGE / SOURCE / ACCURACY NOTE (read before trusting a number) ──\n * These are APPROXIMATE annual-average CPI-U figures recalled from the\n * assistant's general knowledge (training data through ~January 2026), not\n * a live fetch from the U.S. Bureau of Labor Statistics (bls.gov/cpi). They\n * are representative of the real, published series and good enough for a\n * calculator-notepad's inflation-adjustment feature, but:\n * - Years up to ~2024 are close to BLS-published annual averages but may\n * be off by a small amount (rounding/recall, not a live re-derivation).\n * - 2025 and 2026 are forward-leaning ESTIMATES (2025 not fully finalized,\n * 2026 projected from recent trend), expect these to be the least\n * accurate entries and the first that need replacing with real BLS\n * data as it's published.\n * - This table is NOT authoritative for financial, legal, tax, contract\n * escalation (COLA), or any decision with real money on the line\n * consult bls.gov/cpi directly for that. It exists so `inflationAdjust`\n * and the \"what is/was ... worth\" phrase grammar (see\n * `packages/finance/parselets/InflationQueryParselet.ts`) have a real,\n * working, demonstrably-correct-shaped implementation to run against,\n * matching this session's established honesty principle for bundled\n * approximate data (see `SalesTaxParselet.ts`'s doc comment on never\n * silently faking a rate).\n *\n * Coverage: 1970-2026 inclusive (57 years), additive; extend this table in\n * future years by appending new entries, no other code needs to change.\n * A year outside this range (e.g. \"what was $500 worth in 1920\") produces a\n * clear `INFLATION_YEAR_OUT_OF_RANGE` error rather than a silently wrong\n * extrapolation.\n */\nexport const CPI_TABLE: Readonly<Record<number, number>> = {\n 1970: 38.8, 1971: 40.5, 1972: 41.8, 1973: 44.4, 1974: 49.3,\n 1975: 53.8, 1976: 56.9, 1977: 60.6, 1978: 65.2, 1979: 72.6,\n 1980: 82.4, 1981: 90.9, 1982: 96.5, 1983: 99.6, 1984: 103.9,\n 1985: 107.6, 1986: 109.6, 1987: 113.6, 1988: 118.3, 1989: 124.0,\n 1990: 130.7, 1991: 136.2, 1992: 140.3, 1993: 144.5, 1994: 148.2,\n 1995: 152.4, 1996: 156.9, 1997: 160.5, 1998: 163.0, 1999: 166.6,\n 2000: 172.2, 2001: 177.1, 2002: 179.9, 2003: 184.0, 2004: 188.9,\n 2005: 195.3, 2006: 201.6, 2007: 207.3, 2008: 215.3, 2009: 214.5,\n 2010: 218.1, 2011: 224.9, 2012: 229.6, 2013: 233.0, 2014: 236.7,\n 2015: 237.0, 2016: 240.0, 2017: 245.1, 2018: 251.1, 2019: 255.7,\n 2020: 258.8, 2021: 271.0, 2022: 292.7, 2023: 304.7, 2024: 313.7,\n // 2025-2026 were projected from model knowledge and are now derived from\n // the IMF monthly CPI series (statisticsoftheworld.com,\n // IMF.CPI.YOY.M?geo=USA), chained forward from the published 2024 figure\n // using annual mean year-over-year rates. 2026 covers January to June only,\n // so it remains a partial year and will move.\n //\n // The projections were 320.6 and 327.4, low by 0.49% and 1.63%. Everything\n // from 2021 to 2024 reproduced the same series to within 0.02%, which is\n // what makes those two the only entries worth changing.\n 2025: 322.2, 2026: 332.7,\n} as const;\n\n/** Earliest/latest year this table has data for, used for range-check error messages. */\nexport const CPI_MIN_YEAR = 1970;\n/**\n * Most recent year in {@link CPI_TABLE}.\n *\n * A request beyond this is rejected rather than extrapolated, since inflation\n * past the last published figure is a forecast and not a conversion.\n */\nexport const CPI_MAX_YEAR = 2026;\n\n/** Look up the CPI-U annual average for `year`, or `undefined` if out of range. */\nexport function getCpi(year: number): number | undefined {\n return CPI_TABLE[Math.trunc(year)];\n}\n\n/**\n * Ratio to multiply a `fromYear` dollar amount by to express it in\n * `toYear` dollars: `amount(toYear) = amount(fromYear) * inflationRatio(fromYear, toYear)`.\n *\n * @returns `undefined` if either year is outside the table's range, or if\n * `fromYear`'s CPI is exactly 0 (never true for real data, guarded anyway\n * since it would otherwise divide by zero).\n */\nexport function inflationRatio(fromYear: number, toYear: number): number | undefined {\n const fromCpi = getCpi(fromYear);\n const toCpi = getCpi(toYear);\n if (fromCpi === undefined || toCpi === undefined || fromCpi === 0) return undefined;\n return toCpi / fromCpi;\n}\n\n/**\n * Adjust `amount` from `fromYear` dollars to `toYear` dollars using the CPI\n * table above.\n *\n * @returns `undefined` if either year is out of the table's covered range\n * (caller should surface this as a clear error, not a silently wrong number).\n */\nexport function adjustForInflation(amount: number, fromYear: number, toYear: number): number | undefined {\n const ratio = inflationRatio(fromYear, toYear);\n if (ratio === undefined) return undefined;\n return amount * ratio;\n}\n","import { Value, ValueType, numberValue, hexValue, uomValue, errorValue, matrixValue, percentageValue, stringValue, splitValue, type MatrixData } from \"@solve-js/vm/Value\";\nimport { decimalRound, decimalToNumber, type DecimalData } from \"@solve-js/decimal\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { unifyUom, power, describeMeasureMismatch } from \"@solve-js/vm/VMConversion\";\nimport { scaleMoneyExact, scaleMoneyByPercent, removeTaxExact, taxInExact, splitEachExact } from \"@solve-js/vm/MoneyExact\";\nimport { transpose, determinant, inverse, matrixMultiply, matrixPower, symbolicToEntry, rowMajorToColumnMajor } from \"@solve-js/vm/MatrixOps\";\nimport { symbolicToValue, valueToSymbolic, solveEquationValues } from \"@solve-js/vm/SymbolicOps\";\nimport { expandSymbolic } from \"@solve-js/symbolic/Polynomial\";\nimport { factorSymbolic } from \"@solve-js/symbolic/Factor\";\nimport { cancelSymbolic } from \"@solve-js/symbolic/Gcd\";\nimport { apartSymbolic } from \"@solve-js/symbolic/PartialFractions\";\nimport { differentiate } from \"@solve-js/symbolic/Derivative\";\nimport { integrate } from \"@solve-js/symbolic/Integral\";\nimport { taylorSeries, jacobian } from \"@solve-js/symbolic/Taylor\";\nimport { freeVariables, callNode, constNode, complexNode, complex as complexValue, type SymbolicNode } from \"@solve-js/symbolic\";\nimport { RATIONAL_ZERO, rationalFromNumber } from \"@solve-js/symbolic/Rational\";\n// Type-only, VM.ts imports pluginFunctionRegistry FROM this file, so a\n// runtime import the other direction would be circular; `import type` is\n// erased before compilation and doesn't create that problem.\nimport { defaultEngineContext } from \"@solve-js/engine/EngineContext\";\n// EngineContext is imported for the {@link EngineContext} reference in\n// pluginFunctionRegistry's deprecation note below. Dropping it would leave that\n// link dangling, which is worse than an unused-import warning.\n// eslint-disable-next-line no-unused-vars\nimport type { EngineContext, PluginFunctionHandler } from \"@solve-js/engine/EngineContext\";\nimport { inflationRatio, CPI_MIN_YEAR, CPI_MAX_YEAR } from \"@solve-js/packages/finance/data/CpiTable\";\nimport { UNIT_TABLE } from \"@solve-js/uom/generated/UnitTable.generated\";\n\n/** The angle measure's kind in UNIT_TABLE. Its base unit is the radian. */\nconst ANGLE_KIND = 0;\n\n/**\n * A trig argument in radians.\n *\n * `sin(90 degrees)` used to answer 0.89, because the builtin read the number\n * and discarded the unit, so 90 was taken as 90 radians. The engine already\n * knew the conversion, `90 degrees in radians` has always given 1.5708; the\n * trig functions simply never asked.\n *\n * A plain number is still radians, which is the convention everywhere else and\n * what `sin(pi/2)` relies on.\n */\nfunction angleInRadians(value: Value): number {\n if (value.type === ValueType.Uom && value.unit !== undefined) {\n const entry = UNIT_TABLE[value.unit.toLowerCase()];\n // Every angle entry's ratio converts that spelling to radians.\n if (entry !== undefined && entry[0] === ANGLE_KIND) return value.toNumber() * entry[1];\n }\n return value.toNumber();\n}\n\n/**\n * The plural spelling of a unit, when the count calls for one and the table\n * has it.\n *\n * `$500 at $20/hour` is twenty-five hours, not twenty-five hour. The\n * denominator is written singular in the rate, so a count derived from it\n * inherits the wrong number unless it is adjusted here. Only spellings the\n * unit table already knows are used, so nothing is invented.\n *\n * @param unit - The unit as written.\n * @param count - How many, deciding singular or plural.\n */\nfunction pluraliseUnit(unit: string, count: number): string {\n if (count === 1) return unit;\n const plural = `${unit}s`;\n return UNIT_TABLE[plural.toLowerCase()] === undefined ? unit : plural;\n}\n\n/**\n * The largest or smallest of a list of arguments.\n *\n * A plain loop, replicating Math.min/Math.max's exact semantics for bare\n * numbers (NaN poisons the result wherever it appears; an empty list gives\n * ±Infinity) without the intermediate array a .map()+spread allocates on every\n * call.\n *\n * The two things this does that reading `.toNumber()` off each argument did\n * not:\n *\n * Quantities are compared through unifyUom rather than by their magnitudes, so\n * `max(1 km, 500 m)` is the kilometre. Comparing the bare numbers made 500 the\n * larger of the two, which is the same defect the ordering opcodes in VM.ts\n * had.\n *\n * The winner is returned as it was written rather than as a bare number, so\n * the answer still carries its unit. `max(1 km, 500 m)` returning 500 was\n * wrong twice over: it named the shorter distance AND dropped the unit that\n * would have made the mistake visible. Only a Uom winner is passed through\n * whole; anything else still reduces to a Number, because that is what every\n * other numeric builtin here returns and widening min/max to hand back\n * Datetimes or Percentages is a separate decision from fixing the unit bug.\n *\n * Arguments whose measures do not match cannot be ordered at all, so that is\n * an error rather than an arbitrary pick, matching the ordering opcodes.\n *\n * @param wantLargest - max when true, min when false.\n */\nfunction extremum(args: Value[], wantLargest: boolean): Value {\n let best: Value | undefined;\n let hasNaN = false;\n for (const a of args) {\n if (Number.isNaN(a.toNumber())) { hasNaN = true; continue; }\n if (best === undefined) { best = a; continue; }\n const { lv, rv, sameMeasure } = unifyUom(best, a);\n if (!sameMeasure) {\n const bestUnit = best.type === ValueType.Uom ? best.unit : undefined;\n const otherUnit = a.type === ValueType.Uom ? a.unit : undefined;\n // Same phrasing as the ordering opcodes: name the two dimensions\n // where they differ (\"mass and length cannot be compared\"), keeping\n // the unit-naming fallback for anything with no dimension to name.\n const named = describeMeasureMismatch(bestUnit, otherUnit, \"compared\");\n return errorValue(\n \"INCOMPATIBLE_UNITS\",\n named ?? `Cannot compare incompatible units: ${bestUnit ?? \"?\"} and ${otherUnit ?? \"?\"}`,\n );\n }\n if (wantLargest ? rv > lv : rv < lv) best = a;\n }\n if (hasNaN) return numberValue(NaN);\n if (best === undefined) return numberValue(wantLargest ? -Infinity : Infinity);\n return best.type === ValueType.Uom ? best : numberValue(best.toNumber());\n}\n\n/**\n * Re-wrap a computed magnitude in its operand's unit.\n *\n * The rounding family (round/ceil/floor) and abs change how much of something\n * there is, never what it is, so throwing the unit away is a straight loss of\n * information: `$490 rounded to nearest hundred` answered a bare 500 and\n * `abs(-5 kg)` a bare 5. The first of those is written in\n * `converters/parselets/RoundingParselets.ts`'s own header as `$500`.\n *\n * Only Uom is carried across, matching {@link extremum} above: widening this\n * to Datetime or Percentage is a separate decision from restoring a unit that\n * was already there.\n */\nfunction keepUnit(operand: Value, magnitude: number): Value {\n if (operand.type === ValueType.Uom && operand.unit !== undefined) return uomValue(magnitude, operand.unit);\n return numberValue(magnitude);\n}\n\n/**\n * Round a value to an explicit number of decimal places, recording that place\n * count so the result DISPLAYS at it (see Value's `decimalPlaces`).\n *\n * Backs both spellings of the same idea: the phrase `<x> to N dp` (builtin 97)\n * and the function `round(x, N)` (builtin 8's two-argument form). Rounds from the\n * exact decimal where the value carries one, so `1.005 to 2 dp` and\n * `round(1.005, 2)` are `1.01`, half away from zero, not the `1.00` a double\n * (1.00499...) rounds down to. Without an exact decimal it rounds the double,\n * guarding the point past 2^53 where a double has no fractional digits left to\n * round (scaling further only adds error, so `1e21 to 2 dp` is `1e21`). The\n * unit, if any, rides along.\n */\nfunction roundToPlaces(source: Value, places: number): Value {\n const p = Number.isFinite(places) ? Math.min(100, Math.max(0, Math.trunc(places))) : 0;\n if (source.exact !== undefined) {\n const rounded = decimalRound(source.exact, p);\n return withPlaces(source, decimalToNumber(rounded), p, rounded);\n }\n const value = source.toNumber();\n if (!Number.isFinite(value)) return withPlaces(source, value, p);\n const scale = Math.pow(10, p);\n const scaled = value * scale;\n if (!Number.isFinite(scaled) || Math.abs(scaled) > Number.MAX_SAFE_INTEGER) return withPlaces(source, value, p);\n return withPlaces(source, Math.round(scaled) / scale, p);\n}\n\n/** Carry `source`'s unit onto `magnitude` and stamp its display precision (and exact decimal, when the rounding was exact). */\nfunction withPlaces(source: Value, magnitude: number, places: number, exact?: DecimalData): Value {\n const result = source.type === ValueType.Uom && source.unit !== undefined ? uomValue(magnitude, source.unit) : numberValue(magnitude);\n result.decimalPlaces = places;\n if (exact !== undefined) result.exact = exact;\n return result;\n}\n\n/**\n * Refuses a `gcd`/`lcm` operand that the Euclidean loop cannot terminate on.\n *\n * `while (b !== 0) { [a, b] = [b, a % b] }` relies on the remainder shrinking\n * to zero. A NaN never does, because `NaN !== 0` is true and `NaN % x` is NaN,\n * and an infinity turns into a NaN on the first step and then never does\n * either. So `gcd(4, arccos(2))` spun forever inside ONE opcode, which no\n * ceiling in the engine can see: `maxInstructions` is checked between\n * instructions and the allocation budget counts allocations, and this loop\n * makes neither. The host froze, uninterruptibly, on nine characters of input.\n *\n * Found by the fuzzer as a hang. The same class `DenialOfServiceUnboundedWork.spec.ts`\n * exists for, and the fix is that file's own prescription: bound the loop at\n * the one place that knows the trip count is a number the user typed.\n *\n * @param a - The first operand, already truncated and made positive.\n * @param b - The second, likewise.\n * @param name - Which function to name in the message.\n * @returns An Error Value to return instead, or `null` when the loop is safe.\n */\nfunction nonFiniteEuclidOperand(a: number, b: number, name: string): Value | null {\n if (Number.isFinite(a) && Number.isFinite(b)) return null;\n const culprit = Number.isFinite(a) ? b : a;\n return errorValue(\n \"INVALID_INTEGER_OPERAND\",\n `${name} needs two whole numbers, and ${Number.isNaN(culprit) ? \"one of them has no value\" : \"one of them is infinite\"}`,\n );\n}\n\n/**\n * The Euclidean algorithm, shared by `gcd` and `lcm`.\n *\n * Both had their own inline copy, which is how only one of them would have\n * been fixed. Callers must have refused a non-finite operand first, see\n * {@link nonFiniteEuclidOperand}.\n *\n * @param a - A non-negative, finite integer.\n * @param b - The same.\n * @returns Their greatest common divisor.\n */\nfunction euclidGcd(a: number, b: number): number {\n let x = a;\n let y = b;\n while (y !== 0) {\n const t = y;\n y = x % y;\n x = t;\n }\n return x;\n}\n\n/**\n * Sum of squared deviations from the mean, the numerator both variance forms\n * share. Zero for an empty list.\n */\nfunction sumOfSquares(nums: number[]): number {\n const n = nums.length;\n if (n === 0) return 0;\n const mean = nums.reduce((acc, x) => acc + x, 0) / n;\n return nums.reduce((acc, x) => acc + (x - mean) * (x - mean), 0);\n}\n\n/**\n * Variance in the population form (divide by n) or the sample form (divide by\n * n-1). Returns 0 for an empty list, and for a one-element sample, whose\n * n-1 = 0 has no defined spread, rather than a NaN.\n */\nfunction variance(nums: number[], sample: boolean): number {\n const n = nums.length;\n if (n === 0) return 0;\n const denom = sample ? n - 1 : n;\n if (denom <= 0) return 0;\n return sumOfSquares(nums) / denom;\n}\n\n/**\n * Registry of built-in mathematical functions.\n * Indexed by the number pushed as an operand of OpCode.CALL_BUILTIN.\n */\nexport const builtinFunctions: Record<number, (args: Value[]) => Value> = {\n // ── Populated below ──\n // sqrt: a negative argument has a complex answer now that there is a complex\n // number to give, so this no longer quietly returns NaN. The exact path runs\n // first, so sqrt(-4) is 2i rather than an approximation.\n 0: (args) => {\n const value = args[0].toNumber();\n if (value >= 0) return numberValue(Math.sqrt(value));\n return symbolicToValue(callNode(\"sqrt\", [constNode(value)]));\n },\n // abs(a): for a Matrix, \"|a|\" (Calca's determinant-pipe notation) is a\n // valid alias for det(a) (index 64), reusing the SAME implementation\n // not a separate one. Plain-number abs is unaffected.\n 1: (args) => args[0].type === ValueType.Matrix ? determinant(args[0].value as MatrixData) : keepUnit(args[0], Math.abs(args[0].toNumber())),\n // sin/cos/tan accept an angle with a unit; see angleInRadians().\n 2: (args) => numberValue(Math.sin(angleInRadians(args[0]))),\n 3: (args) => numberValue(Math.cos(angleInRadians(args[0]))),\n 4: (args) => numberValue(Math.tan(angleInRadians(args[0]))),\n 5: (args) => numberValue(Math.log(args[0].toNumber())),\n // round/ceil/floor keep a unit for the same reason abs does; see keepUnit().\n 6: (args) => keepUnit(args[0], Math.ceil(args[0].toNumber())),\n 7: (args) => keepUnit(args[0], Math.floor(args[0].toNumber())),\n 8: (args) =>\n args.length >= 2\n ? // round(x, n): round to n decimal places and display at that precision.\n roundToPlaces(args[0], args[1].toNumber())\n : // round(x): nearest whole number, the way it always was.\n keepUnit(args[0], Math.round(args[0].toNumber())),\n // min/max: see extremum() for why the winner is carried around as a Value\n // rather than as a running number.\n 9: (args) => extremum(args, false),\n 10: (args) => extremum(args, true),\n 11: (args) => numberValue(Math.asin(args[0].toNumber())),\n 12: (args) => numberValue(Math.acos(args[0].toNumber())),\n 13: (args) => numberValue(Math.atan(args[0].toNumber())),\n 14: (args) => numberValue(Math.atan2(args[0].toNumber(), args[1].toNumber())),\n 15: (args) => numberValue(Math.sinh(args[0].toNumber())),\n 16: (args) => numberValue(Math.cosh(args[0].toNumber())),\n 17: (args) => numberValue(Math.tanh(args[0].toNumber())),\n 18: (args) => numberValue(Math.asinh(args[0].toNumber())),\n 19: (args) => numberValue(Math.acosh(args[0].toNumber())),\n 20: (args) => numberValue(Math.atanh(args[0].toNumber())),\n 21: (args) => numberValue(Math.cbrt(args[0].toNumber())),\n 22: (args) => numberValue(Math.clz32(args[0].toNumber())),\n 23: (args) => numberValue(Math.expm1(args[0].toNumber())),\n 24: (args) => numberValue(Math.exp(args[0].toNumber())),\n 25: (args) => numberValue(Math.fround(args[0].toNumber())),\n // hypot: left as .map()+spread (unlike min/max above), Math.hypot uses\n // a numerically-stable scaling algorithm internally to avoid overflow\n // for very large/small inputs; a naive manual reimplementation risks\n // silently changing results at the extremes, so the tiny array\n // allocation here is the safer trade.\n 26: (args) => numberValue(Math.hypot(...args.map(a => a.toNumber()))),\n 27: (args) => numberValue(Math.imul(args[0].toNumber(), args[1].toNumber())),\n 28: (args) => numberValue(Math.log10(args[0].toNumber())),\n 29: (args) => numberValue(Math.log1p(args[0].toNumber())),\n 30: (args) => numberValue(Math.log2(args[0].toNumber())),\n // pow(): the spelled-out form of `^`, so a Matrix base means the same\n // repeated matrix multiplication `^` means. Without this branch\n // `pow([1,2;3,4], 2)` was Math.pow of a value whose toNumber() is 0, and\n // came back as the number 0. See vm/MatrixOps.ts's matrixPower().\n 31: (args) => {\n if (args[0].type === ValueType.Matrix) {\n if (args[1].type !== ValueType.Number) {\n return errorValue(\"MATRIX_POWER_UNSUPPORTED\", `pow: a matrix's exponent must be a whole number, as in \"pow([1,2;3,4], 2)\".`);\n }\n return matrixPower(args[0].value as MatrixData, args[1].value as number);\n }\n if (args[1].type === ValueType.Matrix) {\n return errorValue(\"MATRIX_POWER_UNSUPPORTED\", `pow: a matrix may only be the base, as in \"pow([1,2;3,4], 2)\".`);\n }\n // The spelled-out form of `^` answers what `^` answers, edge cases\n // included. See power() in vm/VMConversion.ts.\n return numberValue(power(args[0].toNumber(), args[1].toNumber()));\n },\n 32: () => numberValue(Math.random()), // takes no arguments, unlike its neighbours\n 33: (args) => numberValue(Math.sign(args[0].toNumber())),\n 34: (args) => numberValue(Math.trunc(args[0].toNumber())),\n 35: (args) => numberValue(args[0].toNumber() * Math.PI / 180),\n 36: (args) => numberValue(args[0].toNumber() * 180 / Math.PI),\n // 37: diceRoll(from, to), random integer in range [from, to] inclusive.\n // A reversed range (from > to) used to silently produce values outside\n // [to, from] via a negative-length Math.random() spread (e.g.\n // \"roll(6, 1)\" returning values like 2-5, never 1 or 6) instead of\n // erroring on the invalid input.\n 37: (args) => {\n const from = args[0].toNumber();\n const to = args[1].toNumber();\n if (from > to) {\n return errorValue(\"INVALID_RANGE\", `roll: invalid range, ${from} is greater than ${to}`);\n }\n return numberValue(Math.floor(Math.random() * (to - from + 1)) + from);\n },\n // gcd(a, b), Euclidean algorithm. Negative inputs are treated by\n // magnitude (gcd is conventionally defined over non-negative integers).\n 38: (args) => {\n const a = Math.trunc(Math.abs(args[0].toNumber()));\n const b = Math.trunc(Math.abs(args[1].toNumber()));\n const nonFinite = nonFiniteEuclidOperand(a, b, \"gcd\");\n if (nonFinite) return nonFinite;\n return numberValue(euclidGcd(a, b));\n },\n // lcm(a, b) = |a*b| / gcd(a, b), via the same Euclidean gcd inline\n // (a standalone gcd() call site, no shared helper needed for two uses).\n 39: (args) => {\n const a = Math.trunc(Math.abs(args[0].toNumber()));\n const b = Math.trunc(Math.abs(args[1].toNumber()));\n const nonFinite = nonFiniteEuclidOperand(a, b, \"lcm\");\n if (nonFinite) return nonFinite;\n if (a === 0 || b === 0) return numberValue(0);\n return numberValue((a / euclidGcd(a, b)) * b);\n },\n // permutation(n, r) = n! / (n-r)!, computed as a running product\n // rather than two full factorials, so it stays exact for n well\n // beyond where n! itself would exceed Number.MAX_SAFE_INTEGER.\n //\n // The loop stops the moment the product stops being a representable\n // double, which is both the answer `fact` (index 62) already gives for\n // the same question and the thing that bounds the loop at all. `r` comes\n // straight off the stack: `permutation(1000000000000, 1000000000000)`\n // used to run a trillion iterations, of which the first ~170 computed\n // something and the rest multiplied Infinity by a number, and it had not\n // returned after thirty seconds. Every factor here is at least 1 and they\n // descend from `n`, so a product that is still finite after 170 steps\n // means the factors are small, which in turn means `r <= n` is small: the\n // early exit bounds the trip count without a separate estimate, and\n // without ever refusing a permutation that does have an answer.\n 40: (args) => {\n const n = Math.trunc(args[0].toNumber());\n const r = Math.trunc(args[1].toNumber());\n if (n < 0 || r < 0 || r > n) {\n return errorValue(\"INVALID_RANGE\", `permutation: invalid n=${n}, r=${r} (require 0 <= r <= n)`);\n }\n let result = 1;\n for (let i = 0; i < r; i++) {\n result *= (n - i);\n if (!Number.isFinite(result)) {\n return errorValue(\n \"PERMUTATION_OVERFLOW\",\n `permutation: P(${n}, ${r}) exceeds the maximum representable double (it passed it after ${i + 1} of ${r} factors)`,\n );\n }\n }\n return numberValue(result);\n },\n // combination(n, r) = n! / (r! * (n-r)!), multiply-then-divide one\n // step at a time (standard technique) keeps every intermediate result\n // an integer, avoiding the overflow a naive factorial-ratio would hit.\n //\n // Same early exit, and needed for the same reason: `k = min(r, n-r)`\n // halves the trip count and bounds nothing, so `combination(1e12, 5e11)`\n // asked for five hundred billion iterations. The running value is C(n, i),\n // which grows monotonically to the middle, so once it is past what a\n // double can hold it never comes back, and the largest run this can now\n // take is the thousand-odd steps C(n, k) needs to cross that line.\n 41: (args) => {\n const n = Math.trunc(args[0].toNumber());\n const r = Math.trunc(args[1].toNumber());\n if (n < 0 || r < 0 || r > n) {\n return errorValue(\"INVALID_RANGE\", `combination: invalid n=${n}, r=${r} (require 0 <= r <= n)`);\n }\n const k = Math.min(r, n - r);\n let result = 1;\n for (let i = 0; i < k; i++) {\n result = (result * (n - i)) / (i + 1);\n if (!Number.isFinite(result)) {\n return errorValue(\n \"COMBINATION_OVERFLOW\",\n `combination: C(${n}, ${r}) exceeds the maximum representable double (it passed it after ${i + 1} of ${k} steps)`,\n );\n }\n }\n return numberValue(Math.round(result));\n },\n // average(...), arithmetic mean of any number of arguments. Backs the\n // MathPhrases package's \"average of X, Y, Z\" (packages/mathphrases/).\n 42: (args) => {\n if (args.length === 0) return numberValue(0);\n const sum = args.reduce((acc, a) => acc + a.toNumber(), 0);\n return numberValue(sum / args.length);\n },\n // median(...), middle value; average of the two middle values for an\n // even argument count.\n 43: (args) => {\n if (args.length === 0) return numberValue(0);\n const sorted = args.map((a) => a.toNumber()).sort((a, b) => a - b);\n const mid = Math.floor(sorted.length / 2);\n return numberValue(\n sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid]\n );\n },\n // total(...), sum of any number of arguments.\n 44: (args) => numberValue(args.reduce((acc, a) => acc + a.toNumber(), 0)),\n // count(...), number of arguments passed.\n 45: (args) => numberValue(args.length),\n // proportion(a, b, c) -> d such that a:b = c:d, i.e. d = c * (b/a)\n // \"A is to B as C is to what\". Unit-aware via unifyUom: \"5 km is to\n // 500m as 5 cm is to what\" unifies 5km/500m to a 10:1 ratio (500m ==\n // 0.5km), so 5cm at the same ratio -> 0.5cm. Falls back to plain\n // toNumber() ratios when the units aren't the same measure (unifyUom's\n // own fallback) rather than guessing at an unsupported conversion.\n 46: (args) => {\n const [a, b, c] = args;\n const { lv: aNum, rv: bNum } = unifyUom(a, b);\n if (aNum === 0) {\n return errorValue(\"PROPORTION_DIVIDE_BY_ZERO\", `Cannot compute proportion: \"${a.value}\" is zero`);\n }\n const result = c.toNumber() * (bNum / aNum);\n return c.type === ValueType.Uom ? uomValue(result, c.unit!) : numberValue(result);\n },\n // clamp(value, lo, hi), restrict value to [lo, hi]. Backs\n // \"clamp X between Y and Z\" / \"clamp X from Y to Z\".\n 47: (args) => {\n const value = args[0].toNumber();\n const lo = args[1].toNumber();\n const hi = args[2].toNumber();\n if (lo > hi) {\n return errorValue(\"INVALID_RANGE\", `clamp: invalid range, ${lo} is greater than ${hi}`);\n }\n return numberValue(Math.min(Math.max(value, lo), hi));\n },\n // hex(n), Python/JS-style call-syntax hex formatting, e.g. hex(255) ->\n // \"0xFF\". Distinct from the Converters package's `255 as hex` (see\n // packages/converters/parselets/AsConverterParselet.ts): \"as hex\"\n // produces a ValueType.Hex (a typed NUMBER that still participates in\n // arithmetic, formatted specially on display), while hex() is a plain\n // function call that returns an ordinary String value, matching\n // Python's hex()/JS convention of a function returning display text,\n // not a numeric type.\n 48: (args) => hexValue(args[0].toNumber()),\n // bin(n). Same call-syntax shape as hex() above, e.g. bin(10) -> \"0b1010\".\n 49: (args) => hexValue(args[0].toNumber(), \"bin\"),\n // int(x), coerce ANY value (Number, Percentage, Uom, String, Hex, ...)\n // to a plain integer Number, truncating any fractional part toward\n // zero (Math.trunc semantics: int(5.7) -> 5, int(-5.7) -> -5). Distinct\n // from the Converters package's `x as number` (TO_NUMBER opcode),\n // which only strips a unit/percentage wrapper and keeps any decimal\n // part (e.g. \"5.7 as number\" -> 5.7), int() additionally truncates.\n 50: (args) => numberValue(Math.trunc(args[0].toNumber())),\n\n // ── Finance (packages/finance/) ──────────────────────────────────────\n // All finance builtins preserve the principal/amount argument's Uom\n // unit (e.g. a currency like \"$\") onto the result, matching\n // ProportionParselet's convention (index 46, above), a plain-number\n // input produces a plain-number result.\n //\n // `rate` arguments are always a decimal fraction (e.g. 0.07 for 7%)\n // this is how \"%\" already normalizes everywhere else in this codebase\n // (see packages/percentage/parselets/PercentParselet.ts: \"7%\" divides\n // by 100 at parse time, producing a plain Number 0.07, not a distinct\n // percentage type). Writing \"at 7\" instead of \"at 7%\" in a phrase form\n // passes 7 as-is (not 0.07), the \"%\" is not implicit.\n\n // compoundFutureValue(principal, rate, years) -> FV = P*(1+r)^years.\n // Backs \"compound interest on $P over Y years at R%\" and the\n // compoundInterest(principal, rate, years) function-call form.\n 51: (args) => {\n const principal = args[0].toNumber();\n const rate = args[1].toNumber();\n const years = args[2].toNumber();\n if (1 + rate <= 0) {\n return errorValue(\"INVALID_RATE\", `compoundInterest: rate ${rate} makes (1 + rate) non-positive`);\n }\n const fv = principal * Math.pow(1 + rate, years);\n return args[0].type === ValueType.Uom ? uomValue(fv, args[0].unit!) : numberValue(fv);\n },\n // compoundInterestEarned(principal, rate, years) -> FV - principal, the\n // interest-only portion. Backs \"interest on $P over Y years at R%\" and\n // the interestEarned(principal, rate, years) function-call form.\n 52: (args) => {\n const principal = args[0].toNumber();\n const rate = args[1].toNumber();\n const years = args[2].toNumber();\n if (1 + rate <= 0) {\n return errorValue(\"INVALID_RATE\", `interestEarned: rate ${rate} makes (1 + rate) non-positive`);\n }\n const interest = principal * (Math.pow(1 + rate, years) - 1);\n return args[0].type === ValueType.Uom ? uomValue(interest, args[0].unit!) : numberValue(interest);\n },\n // compoundInterestRate(principal, futureValue, years) -> the rate (as a\n // decimal fraction) needed to grow principal to futureValue over years.\n // Function-call only, no clean phrase form for a reverse calculation\n // like this without inventing awkward new keywords, so it's scoped to\n // compoundInterestRate(...) rather than a natural-language phrase.\n 53: (args) => {\n const principal = args[0].toNumber();\n const futureValue = args[1].toNumber();\n const years = args[2].toNumber();\n if (principal <= 0 || futureValue <= 0) {\n return errorValue(\"INVALID_RANGE\", `compoundInterestRate: principal and futureValue must both be positive`);\n }\n if (years <= 0) {\n return errorValue(\"INVALID_RANGE\", `compoundInterestRate: years must be greater than 0`);\n }\n return numberValue(Math.pow(futureValue / principal, 1 / years) - 1);\n },\n // compoundInterestYears(principal, futureValue, rate) -> the number of\n // years needed to grow principal to futureValue at a fixed rate.\n // Function-call only, same reasoning as index 53 above.\n 54: (args) => {\n const principal = args[0].toNumber();\n const futureValue = args[1].toNumber();\n const rate = args[2].toNumber();\n if (principal <= 0 || futureValue <= 0) {\n return errorValue(\"INVALID_RANGE\", `compoundInterestYears: principal and futureValue must both be positive`);\n }\n if (1 + rate <= 0 || rate === 0) {\n return errorValue(\"INVALID_RATE\", `compoundInterestYears: rate ${rate} is not usable (must be > -1 and not 0)`);\n }\n return numberValue(Math.log(futureValue / principal) / Math.log(1 + rate));\n },\n // loanRepayment(principal, rate, years, periodsPerYear), standard\n // amortizing-loan repayment (mortgage formula), redistributed evenly\n // across `periodsPerYear` periods/year: 365=daily, 12=monthly, 1=annual,\n // 0=total over the life of the loan. The loan is ALWAYS amortized\n // monthly internally (the standard mortgage convention) regardless of\n // periodsPerYear, \"daily\"/\"annual\"/\"total\" are the same total\n // repayment redistributed, not separately-amortized loans. Verified\n // against real worked numbers (principal=$10,000, rate=6%, years=6):\n // monthly $165.73, annual $1,988.75 (== total/years exactly), daily\n // $5.45 (== total/(years*365)), total $11,932.48.\n // Backs \"daily/monthly/annual/total repayment on $P over Y years at R%\".\n 55: (args) => {\n const principal = args[0].toNumber();\n const rate = args[1].toNumber();\n const years = args[2].toNumber();\n const periodsPerYear = args[3].toNumber();\n if (principal <= 0) return errorValue(\"INVALID_RANGE\", `loanRepayment: principal must be positive`);\n if (years <= 0) return errorValue(\"INVALID_RANGE\", `loanRepayment: years must be positive`);\n if (rate < 0) return errorValue(\"INVALID_RATE\", `loanRepayment: rate must not be negative`);\n if (periodsPerYear < 0) return errorValue(\"INVALID_RANGE\", `loanRepayment: periodsPerYear must not be negative`);\n const { totalRepayment } = amortizeLoan(principal, rate, years);\n const result = periodsPerYear === 0 ? totalRepayment : totalRepayment / (years * periodsPerYear);\n return args[0].type === ValueType.Uom ? uomValue(result, args[0].unit!) : numberValue(result);\n },\n // loanInterest(principal, rate, years, periodsPerYear), the interest\n // portion of index 55's repayment, same periodsPerYear convention.\n // Backs \"daily/monthly/annual/total interest on $P over Y years at R%\".\n 56: (args) => {\n const principal = args[0].toNumber();\n const rate = args[1].toNumber();\n const years = args[2].toNumber();\n const periodsPerYear = args[3].toNumber();\n if (principal <= 0) return errorValue(\"INVALID_RANGE\", `loanInterest: principal must be positive`);\n if (years <= 0) return errorValue(\"INVALID_RANGE\", `loanInterest: years must be positive`);\n if (rate < 0) return errorValue(\"INVALID_RATE\", `loanInterest: rate must not be negative`);\n if (periodsPerYear < 0) return errorValue(\"INVALID_RANGE\", `loanInterest: periodsPerYear must not be negative`);\n const { totalInterest } = amortizeLoan(principal, rate, years);\n const result = periodsPerYear === 0 ? totalInterest : totalInterest / (years * periodsPerYear);\n return args[0].type === ValueType.Uom ? uomValue(result, args[0].unit!) : numberValue(result);\n },\n // monthlyPayment(principal, rate, years), convenience 3-arg wrapper\n // around index 55's monthly case, for direct function-call use without\n // the periodsPerYear parameter (the task's minimum-ask function form).\n 57: (args) => {\n const principal = args[0].toNumber();\n const rate = args[1].toNumber();\n const years = args[2].toNumber();\n if (principal <= 0) return errorValue(\"INVALID_RANGE\", `monthlyPayment: principal must be positive`);\n if (years <= 0) return errorValue(\"INVALID_RANGE\", `monthlyPayment: years must be positive`);\n if (rate < 0) return errorValue(\"INVALID_RATE\", `monthlyPayment: rate must not be negative`);\n const { monthlyPayment } = amortizeLoan(principal, rate, years);\n return args[0].type === ValueType.Uom ? uomValue(monthlyPayment, args[0].unit!) : numberValue(monthlyPayment);\n },\n // taxAdd(amount, rate) -> amount * (1 + rate), the tax-inclusive total.\n // Backs the taxAdd() function-call form, whose name promises exactly this.\n // The \"tax on $X at R%\" PHRASE does NOT use it, see index 86.\n //\n // No default rate is baked in anywhere, the caller always supplies one\n // explicitly, since tax rates vary by region and change over time; this\n // package makes no assumption about which rate applies.\n 58: (args) => {\n const amount = args[0].toNumber();\n const rate = args[1].toNumber();\n // Money stays exact: `$X * (1 + R)` is formed in base ten so the\n // tax-inclusive total does not drift a half-cent (see MoneyExact.ts). A\n // non-currency Uom and a bare number keep their existing float result.\n if (args[0].type === ValueType.Uom) return scaleMoneyByPercent(args[0], args[0].unit!, rate, 1);\n return numberValue(amount * (1 + rate));\n },\n // taxRemove(amount, rate) -> amount / (1 + rate), extracts the\n // pre-tax amount from a tax-INCLUSIVE total. Backs \"tax off $X at R%\" /\n // \"VAT off $X at R%\".\n 59: (args) => {\n const amount = args[0].toNumber();\n const rate = args[1].toNumber();\n if (1 + rate <= 0) {\n return errorValue(\"INVALID_RATE\", `taxRemove: rate ${rate} makes (1 + rate) non-positive`);\n }\n if (args[0].type === ValueType.Uom) {\n // Money stays exact: `$X / (1 + R)` rounds the half-cent like a till\n // (`tax off $0.09 at 20%` is `$0.08`, not the `$0.07` the float lands\n // on). A non-currency Uom passes straight through the same helper to\n // the float path. See MoneyExact.ts.\n return removeTaxExact(args[0], args[0].unit!, rate) ?? uomValue(amount / (1 + rate), args[0].unit!);\n }\n return numberValue(amount / (1 + rate));\n },\n\n // inflationAdjust(amount, fromYear, toYear) -- CPI-based inflation\n // adjustment between two arbitrary years, using the bundled CPI-U\n // table (packages/finance/data/CpiTable.ts -- see its doc comment for\n // vintage/accuracy notes). Backs the function-call form\n // inflationAdjust(...) (FunctionCallParselet's builtinNameToIndex map)\n // and the \"what is $X in fromYear worth in toYear\" phrase form\n // (InflationQueryParselet.ts). The two present-year-relative phrase\n // forms (\"what is $X from year\" / \"what was $X worth in year\" / \"$X\n // in year dollars\") and the flat-rate future-value projection (\"value\n // of $X in year assuming N% inflation\") are collision-safe\n // pluginFunctions instead, not indices here -- see\n // packages/finance/parselets/InflationPluginFunctions.ts.\n 60: (args) => {\n const amount = args[0].toNumber();\n const fromYear = args[1].toNumber();\n const toYear = args[2].toNumber();\n const ratio = inflationRatio(fromYear, toYear);\n if (ratio === undefined) {\n return errorValue(\n \"INFLATION_YEAR_OUT_OF_RANGE\",\n `inflationAdjust: fromYear ${fromYear} or toYear ${toYear} is outside the bundled CPI table's range (${CPI_MIN_YEAR}-${CPI_MAX_YEAR})`,\n );\n }\n const result = amount * ratio;\n return args[0].type === ValueType.Uom ? uomValue(result, args[0].unit!) : numberValue(result);\n },\n\n // root(n, x) -- the n-th root of x (Numi's `root n (x)` phrasing maps\n // to this same call-style form; see FunctionCallParselet's name map).\n // No native Math.root exists (unlike Math.cbrt for n=3 specifically),\n // so this is Math.pow(x, 1/n) directly -- exact for n=2/n=3 modulo the\n // usual floating-point pow() rounding, same precision class as every\n // other builtin here.\n 61: (args) => {\n const n = args[0].toNumber();\n const x = args[1].toNumber();\n return numberValue(power(x, 1 / n));\n },\n\n // fact(n) / factorial(n) -- integer factorial. Deliberately rejects\n // negative or non-integer input (factorial isn't defined for either\n // without a gamma-function generalization this engine doesn't need) and\n // caps at 170 -- Number.MAX_VALUE overflows to Infinity at 171!, so\n // returning a silently-wrong (or silently-infinite) result past that\n // point would be worse than a clear error.\n 62: (args) => {\n const n = args[0].toNumber();\n if (!Number.isInteger(n) || n < 0) {\n return errorValue(\"INVALID_FACTORIAL_INPUT\", `fact: ${n} is not a non-negative integer`);\n }\n if (n > 170) {\n return errorValue(\"FACTORIAL_OVERFLOW\", `fact: ${n}! exceeds the maximum representable double (170! is the largest finite factorial)`);\n }\n let result = 1;\n for (let i = 2; i <= n; i++) result *= i;\n return numberValue(result);\n },\n\n // ── Matrix (packages/matrix/) ────────────────────────────────────────\n // transpose(a)/det(a)/inv(a)/dot(a,b), reachable both via ordinary\n // function-call syntax (this map) and via operator syntax (`^T`, `^-1`\n //. See PrecedenceParser.ts's CARET special-casing, which emits these\n // SAME indices) and `|a|` (abs()'s Matrix branch, index 1 above).\n // Real linear-algebra work lives in vm/MatrixOps.ts, shared by both\n // entry points rather than duplicated.\n\n // transpose(a), for a Matrix, swaps rows/cols. A plain Number is its\n // own transpose (a 1x1 \"matrix\" transposed is itself), matches this\n // engine's existing convention of treating a scalar as a trivial 1x1\n // matrix (see Value.ts's toNumber()/isNaN() 1x1 special case).\n 63: (args) => args[0].type === ValueType.Matrix ? transpose(args[0].value as MatrixData) : args[0],\n // det(a), determinant. A plain Number's \"determinant\" is itself (the\n // determinant of a 1x1 matrix [x] is x).\n 64: (args) => args[0].type === ValueType.Matrix ? determinant(args[0].value as MatrixData) : numberValue(args[0].toNumber()),\n // inv(a), matrix inverse for a Matrix; for a plain Number, `1/x`\n // (byte-identical to `Math.pow(x, -1)`, which is what `x^-1` computed\n // before this feature existed. See PrecedenceParser.ts's `^-1`\n // special-case doc comment for why this must stay exact).\n 65: (args) => {\n if (args[0].type === ValueType.Matrix) return inverse(args[0].value as MatrixData);\n return numberValue(1 / args[0].toNumber());\n },\n // dot(a, b), matrix product / scalar-broadcast, the SAME dispatch as\n // the `*` operator between two matrices (vm/VM.ts's MUL case). Plain\n // Number operands multiply directly; a Number mixed with a Matrix\n // promotes the Number to a 1x1 Matrix first, so it broadcasts exactly\n // like matrixMultiply()'s own 1x1-scalar case.\n 66: (args) => {\n const [a, b] = args;\n if (a.type === ValueType.Number && b.type === ValueType.Number) {\n return numberValue(a.toNumber() * b.toNumber());\n }\n const toMatrix = (v: Value): MatrixData =>\n v.type === ValueType.Matrix ? (v.value as MatrixData) : { rows: 1, cols: 1, data: [v.toNumber()], hasSymbolic: false };\n return matrixMultiply(toMatrix(a), toMatrix(b));\n },\n // ── Symbolic algebra (packages/symbolic/) ──\n // expand(expr), multiplying out every product and power. Reached only\n // through its own parselet, never the builtinNameToIndex name map, so that\n // `expand` keeps working as an ordinary variable name; see\n // packages/symbolic/normalizer/SymbolicCallNormalizerRule.ts.\n //\n // A non-symbolic argument has nothing to expand and is returned unchanged,\n // which is why this does not go through the CALL_BUILTIN symbolic dispatch:\n // `expand(2+3)` is simply 5.\n 67: (args) => {\n const [value] = args;\n if (value.type !== ValueType.Symbolic) return value;\n return symbolicToValue(expandSymbolic(value.value as SymbolicNode));\n },\n // factor(expr), writing a polynomial as a product of irreducible factors\n // over the RATIONALS. x^2-2 and x^2+1 come back unchanged, which is the\n // correct answer over that field rather than a failure; see symbolic/Factor.ts.\n 68: (args) => {\n const [value] = args;\n if (value.type !== ValueType.Symbolic) return value;\n return symbolicToValue(factorSymbolic(value.value as SymbolicNode));\n },\n // solve(equation, variable), emitted by its own parselet as three stack\n // values: the two sides of the equation, then the variable NAME as a\n // String. Reading the name as a string rather than compiling it as a\n // variable read is what lets `solve(x^2-4=0, x)` work without `x` existing.\n 69: (args) => {\n const [lhsValue, rhsValue, variableValue] = args;\n if (variableValue?.type !== ValueType.String) {\n return errorValue(\"SOLVE_REQUIRES_VARIABLE_NAME\", \"solve's second argument must be the name of the unknown.\");\n }\n return solveEquationValues(lhsValue, rhsValue, variableValue.value as string);\n },\n // der(expr, variable, order), the symbolic derivative. Genuinely symbolic\n // rather than a finite difference, so it is exact.\n 70: (args) => {\n const [target, variableValue, orderValue] = args;\n const variable = symbolicVariableName(variableValue, \"der\");\n if (typeof variable !== \"string\") return variable;\n const expression = valueToSymbolic(target);\n if (expression === null) return errorValue(\"SYMBOLIC_NONFINITE_OPERAND\", \"der needs an expression with an exact value.\");\n return symbolicToValue(differentiate(expression, variable, orderValue?.toNumber() ?? 1));\n },\n // integral(expr, variable), the indefinite integral without a constant of\n // integration. Reports what it cannot do rather than approximating; see\n // symbolic/Integral.ts.\n 71: (args) => {\n const [target, variableValue] = args;\n const variable = symbolicVariableName(variableValue, \"integral\");\n if (typeof variable !== \"string\") return variable;\n const expression = valueToSymbolic(target);\n if (expression === null) return errorValue(\"SYMBOLIC_NONFINITE_OPERAND\", \"integral needs an expression with an exact value.\");\n const result = integrate(expression, variable);\n if (!result.ok) return errorValue(\"SYMBOLIC_INTEGRAL_UNSUPPORTED\", `Cannot integrate this: ${result.reason}.`);\n return symbolicToValue(result.value);\n },\n // taylor(expr, variable = point, degree).\n 72: (args) => {\n const [target, variableValue, pointValue, degreeValue] = args;\n const variable = symbolicVariableName(variableValue, \"taylor\");\n if (typeof variable !== \"string\") return variable;\n const expression = valueToSymbolic(target);\n const point = valueToSymbolic(pointValue);\n if (expression === null || point === null || point.kind !== \"const\") {\n return errorValue(\"SYMBOLIC_NONFINITE_OPERAND\", \"taylor needs an expression and an exact expansion point.\");\n }\n return symbolicToValue(taylorSeries(expression, variable, point.value, degreeValue.toNumber()));\n },\n // jacobian(f1, f2, ...), variadic. The variables are not named: they come\n // from the union of the functions' own unknowns, sorted, matching Calca.\n 73: (args) => {\n const functions: SymbolicNode[] = [];\n for (const arg of args) {\n const node = valueToSymbolic(arg);\n if (node === null) return errorValue(\"SYMBOLIC_NONFINITE_OPERAND\", \"jacobian needs expressions with exact values.\");\n functions.push(node);\n }\n const variables = new Set<string>();\n for (const fn of functions) for (const name of freeVariables(fn)) variables.add(name);\n const sorted = [...variables].sort();\n if (sorted.length === 0) return errorValue(\"SYMBOLIC_JACOBIAN_NO_VARIABLES\", \"jacobian needs at least one unknown to differentiate against.\");\n\n const rows = jacobian(functions, sorted);\n // Row-major here, which matrixValue's own helper converts to the\n // column-major storage MatrixData uses.\n const rowMajor: (number | boolean | SymbolicNode)[] = [];\n for (const row of rows) {\n for (const cell of row) rowMajor.push(symbolicToEntry(cell));\n }\n return matrixValue(rows.length, sorted.length, rowMajorToColumnMajor(rows.length, sorted.length, rowMajor));\n },\n // An imaginary literal, 3i. The parselet pushes the numeric part and this\n // turns it into an exact imaginary value.\n 74: (args) => symbolicToValue(complexNode(complexValue(RATIONAL_ZERO, rationalFromNumber(args[0].toNumber())))),\n // conj(z), re(z) and im(z). Each folds immediately for a literal and stays\n // symbolic for anything still carrying an unknown.\n 75: (args) => applyComplexAccessor(\"conj\", args[0]),\n 76: (args) => applyComplexAccessor(\"re\", args[0]),\n 77: (args) => applyComplexAccessor(\"im\", args[0]),\n // cancel(expr), reducing a quotient of polynomials to lowest terms.\n 78: (args) => {\n const value = args[0];\n if (value.type !== ValueType.Symbolic) return value;\n return symbolicToValue(cancelSymbolic(value.value as SymbolicNode));\n },\n // apart(expr), the partial-fraction decomposition of a rational function.\n 79: (args) => {\n const value = args[0];\n if (value.type !== ValueType.Symbolic) return value;\n return symbolicToValue(apartSymbolic(value.value as SymbolicNode));\n },\n // taxIn(amount, rate) -> amount - amount/(1 + rate), the tax already\n // contained in a tax-INCLUSIVE total. Backs \"tax in/of/from $X at R%\".\n // The complement of taxRemove (index 59): the two sum to the gross amount.\n 85: (args) => {\n const amount = args[0].toNumber();\n const rate = args[1].toNumber();\n if (1 + rate <= 0) {\n return errorValue(\"INVALID_RATE\", `taxIn: rate ${rate} makes (1 + rate) non-positive`);\n }\n const tax = amount - amount / (1 + rate);\n if (args[0].type === ValueType.Uom) {\n // Money stays exact: `$X - $X / (1 + R)` rounds the half-cent like a\n // till (`tax in $0.09 at 20%` is `$0.02`, not `$0.01`), and stays the\n // exact complement of `tax off` so the two sum back to the gross. A\n // non-currency Uom keeps the float. See MoneyExact.ts.\n return taxInExact(args[0], args[0].unit!, rate) ?? uomValue(tax, args[0].unit!);\n }\n return numberValue(tax);\n },\n // taxOn(amount, rate) -> amount * rate, the tax itself.\n //\n // The \"tax on $X at R%\" phrase used to compile to taxAdd (index 58) and\n // answer $345.00 for \"tax on $300 at 15%\". Soulver answers $45.00, and\n // \"the tax on $300\" is the tax, not the bill. The total is \"$300 + 15%\",\n // which reads as a relative increase (see PercentParselet.ts), or\n // taxAdd(300, 0.15) for the function form.\n 86: (args) => {\n const amount = args[0].toNumber();\n const rate = args[1].toNumber();\n // Money stays exact: `$X * R` is formed in base ten so the tax rounds\n // like a till (`tax on $10.10 at 15%` is `$1.52`, not the `$1.51` a\n // double lands on). See MoneyExact.ts. A non-currency Uom passes\n // straight through the same helper; a bare number keeps its float.\n if (args[0].type === ValueType.Uom) return scaleMoneyExact(args[0], rate, args[0].unit!);\n return numberValue(amount * rate);\n },\n // ── Degree-taking trig (sind/cosd/tand and the inverses) ──────────────\n // The \"d\" spellings take and return degrees rather than radians, which is\n // the convention every scientific calculator uses. sin(90 degrees) is the\n // other way to say the same thing; both exist because both get typed.\n 87: (args) => numberValue(Math.sin(args[0].toNumber() * Math.PI / 180)),\n 88: (args) => numberValue(Math.cos(args[0].toNumber() * Math.PI / 180)),\n 89: (args) => numberValue(Math.tan(args[0].toNumber() * Math.PI / 180)),\n 90: (args) => numberValue(Math.asin(args[0].toNumber()) * 180 / Math.PI),\n 91: (args) => numberValue(Math.acos(args[0].toNumber()) * 180 / Math.PI),\n 92: (args) => numberValue(Math.atan(args[0].toNumber()) * 180 / Math.PI),\n // daysCount(n) -> n labelled as days. \"days in Q3\" is a count of days\n // and should say so; a bare 92 loses what was being counted.\n 93: (args) => uomValue(args[0].toNumber(), \"days\"),\n // asTwoUnits(value, majorUnit, minorUnit) -> \"12 min 30 s\".\n //\n // \"12.5 minutes in minutes and seconds\" asks for one quantity split\n // across two units, which every other conversion path cannot express:\n // they each produce a single number in a single unit.\n //\n // The whole part goes to the major unit and the remainder to the minor,\n // so nothing is lost. A pair that is not ordered major-then-minor, or\n // that spans two different measures, reports rather than guessing.\n 94: (args) => {\n // Read rather than cast. The parselet always pairs this builtin with two\n // PUSH_STRINGs, but `executeBytecode` is a public export, so a\n // hand-built stream can leave any Value here and the cast is\n // compile-time only: `major.toLowerCase()` on a boolean threw a raw\n // TypeError that reached the host as an unexplained internal error.\n const major = typeof args[1]?.value === \"string\" ? args[1].value : undefined;\n const minor = typeof args[2]?.value === \"string\" ? args[2].value : undefined;\n if (major === undefined || minor === undefined) {\n return errorValue(\"UNKNOWN_UNIT\", \"both units have to be named, as in \\\"12.5 minutes in minutes and seconds\\\"\");\n }\n const majorEntry = UNIT_TABLE[major.toLowerCase()] as readonly [number, number] | undefined;\n const minorEntry = UNIT_TABLE[minor.toLowerCase()] as readonly [number, number] | undefined;\n if (majorEntry === undefined || minorEntry === undefined) {\n return errorValue(\"UNKNOWN_UNIT\", `${major} and ${minor}: one of these is not a unit`);\n }\n if (majorEntry[0] !== minorEntry[0]) {\n return errorValue(\"INCOMPATIBLE_UNITS\", `${major} and ${minor} measure different things`);\n }\n if (minorEntry[1] >= majorEntry[1]) {\n return errorValue(\"INCOMPATIBLE_UNITS\", `${major} and ${minor}: name the larger unit first`);\n }\n const source = args[0];\n const sourceEntry = source.type === ValueType.Uom && source.unit !== undefined\n ? (UNIT_TABLE[source.unit.toLowerCase()] as readonly [number, number] | undefined)\n : undefined;\n const inBase = source.toNumber() * (sourceEntry?.[1] ?? majorEntry[1]);\n const majorCount = Math.floor(inBase / majorEntry[1]);\n const minorCount = Math.round(((inBase - majorCount * majorEntry[1]) / minorEntry[1]) * 1000) / 1000;\n return stringValue(`${majorCount} ${major} ${minorCount} ${minor}`);\n },\n // makeRate(value, denominatorUnit) -> value per that unit.\n //\n // `3 hours / day` is a rate, `3 hours / 3 days` is a division. The\n // difference is whether a number was written in the denominator, which\n // is decided at parse time, so this only ever receives the rate case.\n //\n // Building the rate directly rather than dividing by an implied 1 is the\n // whole point: a division makes same-measure units cancel, which turned\n // `3 hours / day` into 0.125 when that shortcut was tried.\n 95: (args) => {\n const source = args[0];\n const denominator = String(args[1].value);\n const numerator = source.type === ValueType.Uom && source.unit !== undefined\n ? source.unit\n : \"\";\n if (numerator.includes(\"/\")) {\n return errorValue(\"INVALID_RATE_UNIT\", `${numerator}/${denominator}: that is already a rate`);\n }\n // A bare number over a unit is a countless rate, \"30/week\", which the\n // rate machinery already renders without a numerator unit.\n return uomValue(source.toNumber(), `${numerator}/${denominator}`);\n },\n // atRate(quantity, rate) -> whichever of the two the question implies.\n //\n // 30 hours at $30/hour $900 a duration at a price per duration\n // $500 at $20/hour 25 hours money at a price per duration\n //\n // Both are written with the same word and mean opposite operations. Which\n // one applies is decided by which half of the rate the left side matches:\n // match the denominator and you are buying that many, match the numerator\n // and you are asking how many it buys.\n 96: (args) => {\n const left = args[0];\n const rate = args[1];\n if (rate.type !== ValueType.Uom || rate.unit === undefined || !rate.unit.includes(\"/\")) {\n return errorValue(\"INVALID_RATE\", \"at: the right-hand side has to be a rate, as in \\\"$30/hour\\\"\");\n }\n const slash = rate.unit.indexOf(\"/\");\n const numerator = rate.unit.slice(0, slash);\n const denominator = rate.unit.slice(slash + 1);\n const leftUnit = left.type === ValueType.Uom ? left.unit : undefined;\n\n const denominatorEntry = UNIT_TABLE[denominator.toLowerCase()] as readonly [number, number] | undefined;\n const leftEntry = leftUnit === undefined ? undefined : (UNIT_TABLE[leftUnit.toLowerCase()] as readonly [number, number] | undefined);\n\n // \"30 hours at $30/hour\": the left side counts denominators.\n if (leftEntry !== undefined && denominatorEntry !== undefined && leftEntry[0] === denominatorEntry[0]) {\n const inDenominator = left.toNumber() * leftEntry[1] / denominatorEntry[1];\n const total = inDenominator * rate.toNumber();\n return numerator === \"\" ? numberValue(total) : uomValue(total, numerator);\n }\n\n // \"$500 at $20/hour\": the left side is the numerator, so divide.\n if (leftUnit !== undefined && leftUnit === numerator) {\n const count = left.toNumber() / rate.toNumber();\n return uomValue(count, pluraliseUnit(denominator, count));\n }\n\n // A bare number counts denominators too: \"30 at $30/hour\".\n if (leftUnit === undefined) {\n const total = left.toNumber() * rate.toNumber();\n return numerator === \"\" ? numberValue(total) : uomValue(total, numerator);\n }\n\n return errorValue(\"INCOMPATIBLE_UNITS\", `at: ${leftUnit} matches neither side of ${rate.unit}`);\n },\n // ── Investments (packages/finance/) ────────────────────────────────────\n // compoundFutureValueEvery(principal, rate, years, periodsPerYear)\n // FV = P(1 + r/n)^(n·y). Index 51 is the same formula with n fixed at 1;\n // this one backs \"compounding monthly\"/\"quarterly\"/\"daily\"/\"weekly\".\n // Kept separate rather than widening 51, because 51 is also the public\n // compoundInterest(principal, rate, years) call and its arity is part of\n // that contract.\n 80: (args) => {\n const principal = args[0].toNumber();\n const rate = args[1].toNumber();\n const years = args[2].toNumber();\n const perYear = args[3].toNumber();\n if (perYear <= 0) {\n return errorValue(\"INVALID_RATE\", `compounding: ${perYear} periods per year is not a period`);\n }\n if (1 + rate / perYear <= 0) {\n return errorValue(\"INVALID_RATE\", `compounding: rate ${rate} makes each period non-positive`);\n }\n const fv = principal * Math.pow(1 + rate / perYear, perYear * years);\n return args[0].type === ValueType.Uom ? uomValue(fv, args[0].unit!) : numberValue(fv);\n },\n // compoundInterestEarnedEvery(principal, rate, years, periodsPerYear)\n // The interest-only portion of index 80, i.e. FV - P.\n 81: (args) => {\n const principal = args[0].toNumber();\n const rate = args[1].toNumber();\n const years = args[2].toNumber();\n const perYear = args[3].toNumber();\n if (perYear <= 0 || 1 + rate / perYear <= 0) {\n return errorValue(\"INVALID_RATE\", `compounding: rate ${rate} over ${perYear} periods per year is not usable`);\n }\n const interest = principal * (Math.pow(1 + rate / perYear, perYear * years) - 1);\n return args[0].type === ValueType.Uom ? uomValue(interest, args[0].unit!) : numberValue(interest);\n },\n // presentValue(futureValue, rate, years) -> FV / (1 + r)^y, what a sum\n // promised in the future is worth today. The inverse of index 51.\n 82: (args) => {\n const future = args[0].toNumber();\n const rate = args[1].toNumber();\n const years = args[2].toNumber();\n if (1 + rate <= 0) {\n return errorValue(\"INVALID_RATE\", `presentValue: rate ${rate} makes (1 + rate) non-positive`);\n }\n const pv = future / Math.pow(1 + rate, years);\n return args[0].type === ValueType.Uom ? uomValue(pv, args[0].unit!) : numberValue(pv);\n },\n // returnOnInvestment(invested, returned) -> (returned - invested) /\n // invested, the gain as a multiple of what was put in. $500 in and $1,500\n // out is 2x, not 3x: ROI conventionally measures the profit against the\n // cost, so doubling your money is 1x return and tripling it is 2x. The\n // money multiple (3x here) is a different figure; `$1,500 / $500` gives it.\n 83: (args) => {\n const invested = args[0].toNumber();\n const returned = args[1].toNumber();\n if (invested === 0) {\n return errorValue(\"INVALID_RATE\", \"roi: nothing was invested, so there is no return on it\");\n }\n return numberValue((returned - invested) / invested);\n },\n // annualisedReturn(invested, returned, years) -> CAGR, the constant\n // yearly rate that turns `invested` into `returned` over `years`:\n // (returned/invested)^(1/years) - 1. Returned as a Percentage so it\n // renders \"13.99%\" rather than 0.1399.\n 84: (args) => {\n const invested = args[0].toNumber();\n const returned = args[1].toNumber();\n const years = args[2].toNumber();\n if (invested <= 0) {\n return errorValue(\"INVALID_RATE\", \"annual return: the amount invested must be positive\");\n }\n if (years <= 0) {\n return errorValue(\"INVALID_RATE\", \"annual return: the period must be longer than zero\");\n }\n if (returned <= 0) {\n // A total loss has no finite compound rate; -100% a year is the\n // limit, and pretending otherwise would invent a number.\n return errorValue(\"INVALID_RATE\", \"annual return: nothing was returned, so there is no annual rate\");\n }\n return percentageValue(Math.pow(returned / invested, 1 / years) - 1);\n },\n // roundToPlaces(value, places) -> value rounded to that many decimal\n // places, backing `<value> to <n> dp` (converters/parselets/\n // RoundingParselets.ts).\n //\n // It exists because the obvious bytecode for it, \"multiply by 10^p, round,\n // divide by 10^p\", is only safe for values small enough that the multiply\n // is exact. `1e21 to 2 dp` came back as 999999999999999900000: 1e21 has no\n // fractional part to round at all, and the round trip through 1e23 was\n // pure loss. Asking for fewer decimal places than a number has cannot\n // change it, so a value that is already whole is returned untouched.\n 97: (args) => roundToPlaces(args[0], args[1].toNumber()),\n // splitEach(amount, n): a per-person bill split, `split $180 between 4` and\n // `$120 + 18% split 3 ways`. Backs both split spellings (see\n // BillSplitParselets.ts). Money stays exact and the shares add back to the\n // total to the cent (see splitEachExact in MoneyExact.ts). A bare number\n // splits to a bare number; the odd penny is named, not rounded away.\n 98: (args) => {\n const n = args[1].toNumber();\n if (!Number.isInteger(n) || n < 1) {\n return errorValue(\"INVALID_RANGE\", `split: the number of shares must be a whole number of at least 1, not ${args[1].toNumber()}.`);\n }\n return splitValue(splitEachExact(args[0], n));\n },\n // ── Savings goals ──────────────────────────────────────────────\n // savingsGoalPayment(target, duration, annualRate): the level contribution\n // per month that reaches `target` over `duration` (months or years), at an\n // optional annual rate compounded monthly. Backs \"how much per month to\n // save/reach <target> in <duration> [at <rate>]\".\n 99: (args) => {\n const target = args[0].toNumber();\n const months = monthsOfDuration(args[1]);\n const annualRate = args[2].toNumber();\n if (months === null) return errorValue(\"INVALID_RANGE\", `savings goal: the duration must be in months or years, e.g. \"in 2 years\".`);\n if (target <= 0) return errorValue(\"INVALID_RANGE\", `savings goal: the target must be positive.`);\n if (months <= 0) return errorValue(\"INVALID_RANGE\", `savings goal: the duration must be positive.`);\n if (annualRate < 0) return errorValue(\"INVALID_RATE\", `savings goal: the rate must not be negative.`);\n const payment = annuityPayment(target, annualRate / 12, months);\n return args[0].type === ValueType.Uom ? uomValue(payment, args[0].unit!) : numberValue(payment);\n },\n // savingsGoalPeriods(target, contribution, periodsPerYear, annualRate,\n // periodUnit): how many whole periods of `contribution` reach `target`,\n // rounded UP, since a part period has not yet reached the goal. Backs\n // \"how long to save <target> at <amount> <period> [at <rate>]\".\n 100: (args) => {\n const target = args[0].toNumber();\n const contribution = args[1].toNumber();\n const periodsPerYear = args[2].toNumber();\n const annualRate = args[3].toNumber();\n const unit = typeof args[4]?.value === \"string\" ? (args[4].value as string) : \"periods\";\n if (target <= 0) return errorValue(\"INVALID_RANGE\", `savings goal: the target must be positive.`);\n if (contribution <= 0) return errorValue(\"INVALID_RANGE\", `savings goal: the contribution must be positive.`);\n if (annualRate < 0) return errorValue(\"INVALID_RATE\", `savings goal: the rate must not be negative.`);\n const periods = annuityPeriods(target, contribution, annualRate / periodsPerYear);\n return uomValue(periods, unit);\n },\n // ── Spread and shape aggregates (MathPhrases \"standard deviation of X, Y\",\n // \"variance of ...\", \"spread of ...\", \"mode of ...\"). Population form is the\n // default; the sample form is a separate index. See issue #184. ──\n // standard deviation (population): the spread in the same units as the data.\n 101: (args) => numberValue(Math.sqrt(variance(args.map((a) => a.toNumber()), false))),\n // sample standard deviation (divide by n-1).\n 102: (args) => numberValue(Math.sqrt(variance(args.map((a) => a.toNumber()), true))),\n // variance (population): the mean squared deviation.\n 103: (args) => numberValue(variance(args.map((a) => a.toNumber()), false)),\n // sample variance (divide by n-1).\n 104: (args) => numberValue(variance(args.map((a) => a.toNumber()), true)),\n // spread: largest minus smallest. Named \"spread\" because \"range\" already\n // means a start:end interval elsewhere in the engine.\n 105: (args) => {\n if (args.length === 0) return numberValue(0);\n const nums = args.map((a) => a.toNumber());\n return numberValue(Math.max(...nums) - Math.min(...nums));\n },\n // mode: the most frequent value. A tie is broken by first appearance, so the\n // result is deterministic for the same list.\n 106: (args) => {\n if (args.length === 0) return numberValue(0);\n const counts = new Map<number, number>();\n let best = args[0].toNumber();\n let bestCount = 0;\n for (const a of args) {\n const n = a.toNumber();\n const c = (counts.get(n) ?? 0) + 1;\n counts.set(n, c);\n if (c > bestCount) {\n bestCount = c;\n best = n;\n }\n }\n return numberValue(best);\n },\n // weighted average: the arguments arrive interleaved [v1, w1, v2, w2, ...]\n // from WeightedAverageParselet, which has already rejected any value with no\n // weight. Weights are normalised by their own total, so they need not sum to\n // 1 or 100%. See issue #185.\n 107: (args) => {\n let weightedSum = 0;\n let weightTotal = 0;\n for (let i = 0; i + 1 < args.length; i += 2) {\n const value = args[i].toNumber();\n const weight = args[i + 1].toNumber();\n weightedSum += value * weight;\n weightTotal += weight;\n }\n if (weightTotal === 0) {\n return errorValue(\"WEIGHTED_AVERAGE_ZERO_WEIGHT\", \"weighted average: the weights sum to zero, so there is nothing to divide by\");\n }\n return numberValue(weightedSum / weightTotal);\n },\n};\n\n/**\n * The months a savings-goal duration stands for: a Uom in `months` is its own\n * count, a Uom in `years` is twelve to the year. Any other or absent time unit\n * has no clean month count, so the builtin reports it rather than guessing.\n */\nfunction monthsOfDuration(duration: Value): number | null {\n if (duration.type !== ValueType.Uom) return null;\n const unit = duration.unit;\n if (unit === \"months\" || unit === \"month\") return duration.toNumber();\n if (unit === \"years\" || unit === \"year\") return duration.toNumber() * 12;\n return null;\n}\n\n/**\n * The level contribution whose annuity future value reaches `target` after\n * `months` at monthly rate `i`, the sinking-fund payment. A zero rate is the\n * plain `target / months`, avoiding the 0/0 the closed form would produce, the\n * same special case {@link amortizeLoan} draws.\n */\nfunction annuityPayment(target: number, i: number, months: number): number {\n return i === 0 ? target / months : (target * i) / (Math.pow(1 + i, months) - 1);\n}\n\n/**\n * The number of periods of `contribution` whose annuity future value reaches\n * `target` at per-period rate `i`, the inverse of {@link annuityPayment},\n * rounded UP: a part period has not yet reached the goal, the deliberate inverse\n * of the recurring-schedule rule that floors a part period. A tiny snap before\n * the ceiling keeps a clean whole result (a `20.0000001` float) at 20. A zero\n * rate is the plain `target / contribution`.\n */\nfunction annuityPeriods(target: number, contribution: number, i: number): number {\n const raw = i === 0 ? target / contribution : Math.log(1 + (target * i) / contribution) / Math.log(1 + i);\n return Math.ceil(raw - 1e-9);\n}\n\n/**\n * Applies one of the complex accessors to a value.\n *\n * @param name - The accessor name, matching what the simplifier folds.\n * @param value - The argument.\n * @returns The folded result, or the call left symbolic when the argument still\n * contains an unknown.\n */\nfunction applyComplexAccessor(name: string, value: Value): Value {\n const node = valueToSymbolic(value);\n if (node === null) return errorValue(\"SYMBOLIC_NONFINITE_OPERAND\", name + \" needs a value with an exact number.\");\n return symbolicToValue(callNode(name, [node]));\n}\n\n/**\n * Reads the variable-name argument the algebra verbs push as a String.\n *\n * @param value - The argument in the name position.\n * @param verb - The verb's name, for the error message.\n * @returns The name, or an error Value to return directly.\n */\nfunction symbolicVariableName(value: Value | undefined, verb: string): string | Value {\n if (value?.type !== ValueType.String) {\n return errorValue(\"SYMBOLIC_REQUIRES_VARIABLE_NAME\", `${verb} needs the name of an unknown.`);\n }\n return value.value as string;\n}\n\n/**\n * Standard amortizing-loan math shared by the loanRepayment/loanInterest/\n * monthlyPayment builtins (indices 55-57, above). Always amortizes monthly\n * (the standard mortgage convention), `annualRate` is the nominal annual\n * rate as a decimal fraction (e.g. 0.06 for 6%).\n *\n * A zero rate is handled as a special case (plain principal/periods split)\n * since the closed-form annuity formula divides by rate and would\n * otherwise produce a NaN from 0/0.\n */\nfunction amortizeLoan(\n principal: number,\n annualRate: number,\n years: number,\n): { monthlyPayment: number; totalRepayment: number; totalInterest: number } {\n const n = years * 12;\n const rMonthly = annualRate / 12;\n const monthlyPayment = rMonthly === 0\n ? principal / n\n : (principal * rMonthly) / (1 - Math.pow(1 + rMonthly, -n));\n const totalRepayment = monthlyPayment * n;\n const totalInterest = totalRepayment - principal;\n return { monthlyPayment, totalRepayment, totalInterest };\n}\n\n/**\n * Registry of package-registered functions, indexed by the number pushed as an\n * operand of `OpCode.CALL_PLUGIN`.\n *\n * Functions may return a promise. The orchestrator resolves it and re-executes\n * rather than blocking the VM.\n *\n * Populated declaratively via {@link IEnginePackage.pluginFunctions} at\n * package-registration time. Entries are cleared on unregister.\n *\n * @deprecated This is the {@link defaultEngineContext}'s map, kept as a\n * module-level alias so existing callers keep working during the context\n * migration. An engine registers into its own context, so writing here affects\n * only code that has not been migrated. Take an {@link EngineContext} instead.\n */\nexport const pluginFunctionRegistry: Record<number, PluginFunctionHandler> =\n defaultEngineContext.pluginFunctions;\n\n/** Highest index that fits in a single Uint8Array opcode-stream byte. */\nconst MAX_PLUGIN_FUNCTION_INDEX = 255;\nlet nextPluginFunctionIndex = 0;\n\n/**\n * Allocate a unique index into {@link pluginFunctionRegistry} for a package's\n * plugin function.\n *\n * Call once per function, typically at module scope, right where the\n * function is defined, and store the result in a constant. Don't hardcode\n * an index: two packages independently picking the same arbitrary number\n * would silently overwrite each other's handler in the shared registry.\n *\n * @throws If the index pool (0-255, a single opcode-stream byte) is exhausted.\n */\nexport function allocatePluginFunctionIndex(): number {\n if (nextPluginFunctionIndex > MAX_PLUGIN_FUNCTION_INDEX) {\n throw ErrorFactory.config(\n \"PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED\",\n `allocatePluginFunctionIndex: pool exhausted (max ${MAX_PLUGIN_FUNCTION_INDEX + 1} allocations).`\n );\n }\n return nextPluginFunctionIndex++;\n}\n\nconst pluginFunctionIndexByQualifiedName = new Map<string, number>();\n\n/**\n * The stable index for a package's named plugin function, allocated once per\n * `${packageName}:${functionName}` and cached process-wide, so the same function\n * always maps to the same {@link pluginFunctionRegistry} slot no matter which\n * engine registers it or in what order: the property compiled bytecode, and so\n * a snapshot, relies on.\n *\n * The engine calls this at {@link ExpressionEngine.registerPackage} time for each\n * entry of a package's `pluginFunctions` record, so a package author names the\n * function and never sees an index. {@link allocatePluginFunctionIndex} remains\n * for a host that needs a raw index directly.\n */\nexport function pluginFunctionIndexFor(qualifiedName: string): number {\n let index = pluginFunctionIndexByQualifiedName.get(qualifiedName);\n if (index === undefined) {\n index = allocatePluginFunctionIndex();\n pluginFunctionIndexByQualifiedName.set(qualifiedName, index);\n }\n return index;\n}\n\n/**\n * Registry of package-registered `as <name>` converters, the SDK extension\n * point for `IEnginePackage.asConverters` (see ExpressionEngine.registerPackage()).\n *\n * String-keyed rather than index-allocated like {@link pluginFunctionRegistry}:\n * converter names ARE the natural key (there's no bytecode-stream byte-width\n * constraint to economize for, the name is only read at parse time to\n * decide whether it's one of the fixed built-ins with a dedicated fast\n * opcode; anything else falls through to `OpCode.CALL_AS_CONVERTER`, which\n * embeds the name as a string constant and looks it up here at runtime).\n */\nexport const asConverterRegistry = new Map<string, (value: Value) => Value>();\n\n/**\n * Register a custom `as <name>` converter. Called by\n * ExpressionEngine.registerPackage() for each entry in a package's\n * `asConverters`. Warns (does not throw) on a name collision, mirrors\n * ParseletRegistry's collision warning, since two independently-authored\n * packages picking the same converter name is a real possibility with a\n * shared string-keyed registry, and silently overwriting is worse than a\n * visible warning.\n *\n * Skips the warning when `handler` is REFERENCE-IDENTICAL to what's\n * already registered (mirrors `ParseletRegistry.registerPrefix()`'s own\n * `existing !== parselet` guard), a package's `asConverters` object is a\n * module-level constant, so re-constructing an `ExpressionEngine` (which\n * re-registers every built-in package's converters from scratch each\n * time. This is not a per-instance cache) passes the exact same function\n * reference every time, not a genuine second package claiming the name.\n * Without this, every `iso8601` converter registration warned on every\n * single `new ExpressionEngine()` call after the first in a process\n * pure noise, not a real collision signal, surfaced by\n * `DatetimePackage.ts` becoming this registry's first real consumer.\n */\nexport function registerAsConverter(name: string, handler: (value: Value) => Value): void {\n const key = name.toLowerCase();\n const existing = asConverterRegistry.get(key);\n if (existing && existing !== handler) {\n console.warn(`[asConverterRegistry] Converter name \"${key}\" is already registered — overwriting.`);\n }\n asConverterRegistry.set(key, handler);\n}\n\n/** Reverse a {@link registerAsConverter} call, used by unregisterPackage(). */\nexport function unregisterAsConverter(name: string): void {\n asConverterRegistry.delete(name.toLowerCase());\n}\n","import { Value } from \"@solve-js/vm/Value\";\n\n/**\n * Process-wide store for `global :name` variables, distinct from, and\n * unrelated to, the per-document `Map<string, Value>` each VM instance owns\n * for ordinary `:x` variables (see VM.ts's `createVM()`). Every document's\n * VM stays fully isolated for local variables; this is the one deliberate\n * exception, shared across every ExpressionEngine in the same JS realm.\n *\n * Distinct from the package-contributed async data sources (currency rates,\n * OSRS prices) reached through the ResolverRegistry: this store backs a\n * completely separate opcode pair (LOAD_GLOBAL_VAR/\n * STORE_GLOBAL_VAR) and is the synchronous fast-path cache underneath\n * GlobalVariableAsyncResolver, which handles the \"not yet declared by any\n * loaded document\" case via the engine's existing async-resolution pipeline\n * (see that file's doc comment for the full picture).\n */\nexport class GlobalVariableStore {\n\tprivate values = new Map<string, Value>();\n\tprivate listeners = new Set<GlobalVariableListener>();\n\n\t/**\n\t * Guards against runaway cross-document write cycles: doc A's write\n\t * notifies doc B, whose dirty line, once evaluated, writes a global\n\t * that notifies doc C, ... eventually back to A. Same philosophy as the\n\t * VM's own instruction-limit safety net: stop propagating past the\n\t * limit rather than let a genuine cycle recurse unboundedly. The store\n\t * itself is left in a well-defined state either way. This only bounds\n\t * *notification* depth, never the value actually stored.\n\t */\n\tprivate static readonly MAX_NOTIFY_DEPTH = 64;\n\tprivate notifyDepth = 0;\n\n\tget(name: string): Value | undefined {\n\t\treturn this.values.get(name);\n\t}\n\n\thas(name: string): boolean {\n\t\treturn this.values.has(name);\n\t}\n\n\t/**\n\t * Last-write-wins: any document may call this for any name at any time.\n\t * Notifies listeners synchronously, within the same call, before\n\t * returning, so that ThreeTierEvaluator's dirty-marking (a listener)\n\t * and GlobalVariableAsyncResolver's first-write promise (also a\n\t * listener) both observe the new value immediately, no microtask delay.\n\t *\n\t * A write that does not CHANGE the stored value notifies nobody. This\n\t * is not just an optimisation, it is what stops a re-evaluation cycle\n\t * from sustaining itself. Every listener re-runs work in response to a\n\t * write (ThreeTierEvaluator marks dependent lines dirty; the playground\n\t * worker refreshes other documents), and those re-runs re-execute the\n\t * very STORE_GLOBAL_VAR opcode that produced this write. Re-evaluating\n\t * an unchanged `global :x = 5` line therefore used to re-notify, which\n\t * re-triggered the listeners, which re-evaluated... bounded only by\n\t * MAX_NOTIFY_DEPTH below, and only in DEPTH, so with more than one\n\t * writer the work per keystroke grew exponentially. Nothing observable\n\t * changed, so there is nothing for a listener to react to.\n\t */\n\tset(name: string, value: Value): void {\n\t\tconst previous = this.values.get(name);\n\t\tthis.values.set(name, value);\n\t\tif (previous !== undefined && sameValue(previous, value)) return;\n\t\tthis.notify(name, value);\n\t}\n\n\tprivate notify(name: string, value: Value): void {\n\t\tif (this.notifyDepth >= GlobalVariableStore.MAX_NOTIFY_DEPTH) return;\n\t\tthis.notifyDepth++;\n\t\ttry {\n\t\t\tfor (const listener of this.listeners) listener(name, value);\n\t\t} finally {\n\t\t\tthis.notifyDepth--;\n\t\t}\n\t}\n\n\t/**\n\t * Subscribe to every global-variable write (all names, callers filter\n\t * for the name(s) they care about). Returns an unsubscribe function;\n\t * callers MUST invoke it when disposing (e.g. ThreeTierEvaluator's\n\t * terminateWorker()) to avoid leaking listeners for closed documents.\n\t */\n\tsubscribe(listener: GlobalVariableListener): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\t/**\n\t * Full reset, test-only. Never called from production code paths;\n\t * globals must outlive any single engine's own clear()/dispose cycle.\n\t * Tests MUST call this in beforeEach/afterEach since this is a\n\t * module-level singleton whose state and listeners otherwise leak\n\t * across test cases and files.\n\t */\n\tclear(): void {\n\t\tthis.values.clear();\n\t\tthis.listeners.clear();\n\t\tthis.notifyDepth = 0;\n\t}\n}\n\n/**\n * Structural equality for two stored globals, used by `set()` to decide\n * whether a write is worth notifying about. Deliberately NOT identity:\n * VM.ts stores `persistentValue(val)`, a fresh object, on every\n * STORE_GLOBAL_VAR while the arena is active, so two writes of the same\n * literal are never the same object.\n *\n * `Object.is` rather than `===` so a global holding NaN compares equal to\n * itself; otherwise `global :x = 0/0` would re-notify on every\n * re-evaluation, which is exactly the cycle `set()` is trying to break.\n */\nfunction sameValue(a: Value, b: Value): boolean {\n\tif (a.type !== b.type) return false;\n\tif (a.unit !== b.unit) return false;\n\tif ((a.timedOut ?? false) !== (b.timedOut ?? false)) return false;\n\n\tconst av = a.value;\n\tconst bv = b.value;\n\tif (Array.isArray(av) || Array.isArray(bv)) {\n\t\tif (!Array.isArray(av) || !Array.isArray(bv)) return false;\n\t\tif (av.length !== bv.length) return false;\n\t\tfor (let i = 0; i < av.length; i++) {\n\t\t\tif (!Object.is(av[i], bv[i])) return false;\n\t\t}\n\t\treturn true;\n\t}\n\treturn Object.is(av, bv);\n}\n\n/** Called when a cross-document global changes, so dependents can re-evaluate. */\nexport type GlobalVariableListener = (name: string, value: Value) => void;\n\n/** Process-wide singleton, shared across every engine in the same JS realm. */\nexport const sharedGlobalVariableStore = new GlobalVariableStore();\n\n/**\n * DAG bookkeeping key for a `global :name` reference, distinct from the\n * plain `name` key used for a local `:name`, so a single document that\n * reads/writes BOTH a local `:hello` and `global :hello` never collides\n * them in that document's own DependencyGraph reads/writes tracking. This\n * prefix exists ONLY at the DAG-bookkeeping layer (ExpressionEngineSafety's\n * extractReadsAndWrites, and ThreeTierEvaluator's dirty-marking subscriber)\n *, the VM-level storage key in this store, and the LOAD_GLOBAL_VAR/\n * STORE_GLOBAL_VAR bytecode operand, both stay unprefixed.\n */\nexport function globalDagKey(name: string): string {\n\treturn `global:${name}`;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/symbolic/MultivariateFactor.ts","../src/symbolic/Factor.ts","../src/symbolic/CubicQuartic.ts","../src/symbolic/NumericRoots.ts","../src/symbolic/Solve.ts","../src/vm/SymbolicOps.ts","../src/vm/VMConversion.ts","../src/vm/OpRegistry.ts","../src/vm/MoneyExact.ts","../src/symbolic/PartialFractions.ts","../src/symbolic/Derivative.ts","../src/symbolic/Integral.ts","../src/symbolic/Taylor.ts","../src/engine/EngineContext.ts","../src/packages/finance/data/CpiTable.ts","../src/vm/VMBuiltins.ts","../src/vm/GlobalVariableStore.ts"],"names":["exactRoot","value","degree","rootOf","exactIntegerSqrt","exactIntegerCbrt","numerator","denominator","monomialRoot","key","monomial","monomialFromKey","root","name","exponent","monomialToKey","monomialMul","a","b","product","monomialDiv","quotient","remaining","monomialGcd","left","shared","other","namesOf","keys","names","termsToNode","terms","map","term","fromPolynomial","factors","result","i","orderedTerms","p","coefficient","compareMonomials","factorMultivariate","factorBinomial","factorPerfectSquare","factorByGrouping","first","second","firstPositive","secondPositive","squares","asPowerPair","negated","cubes","linear","middle","multiplyTerms","squareOf","magnitude","rationalNeg","firstRoot","secondRoot","firstKey","secondKey","rationalMul","last","roots","cross","twice","negative","isRationalOne","rationalDiv","constNode","pairings","pairing","splitPair","cofactorsAgree","common","cofactor","index","FACTOR_MAX_DEGREE","FACTOR_MAX_ROOT_CANDIDATES","gcd","x","y","remainder","lcm","divisors","found","candidate","paired","evaluateAt","descending","total","RATIONAL_ZERO","coeff","rationalAdd","divideByRoot","rationalRoots","multiplier","integers","leading","trailing","numeratorDivisors","denominatorDivisors","ErrorFactory","seen","q","sign","isRationalZero","linearFactorNode","variable","varNode","coefficientsToNode","power","factorUnivariate","multiplicity","RATIONAL_ONE","factorizationToNode","factorization","pieces","factor","powNode","contentOf","numeratorGcd","denominatorLcm","extractCommonMonomial","lowest","exponentOf","exponents","parseKey","buildKey","caret","monomialNode","factorSymbolic","node","polynomial","toPolynomial","polyDegree","content","primitive","scaleTerms","reduced","monomialFactor","polyUnivariateVar","patterned","assemble","buildPieces","polyCoefficients","combinedContent","k","factored","TWO","THREE","FOUR","depressCubic","c","d","shift","rationalSub","twoBCubed","nineABC","twentySevenAAD","solveCubic","discriminant","rationalCompare","trigonometricRoots","repeatedCubicRoots","cardanoRoots","simple","repeated","half","radicand","inner","surdNode","u","v","sum","difference","real","imaginary","complexNode","COMPLEX_I","pNumber","rationalToNumber","qNumber","shiftNumber","ratio","angle","right","depressQuartic","e","bb","r","solveQuartic","solveQuadratic","monic","biquadraticRoots","splitQuarticRoots","shifted","distinct","unique","symbolicKey","simplifySymbolic","complexBiquadraticRoots","exactRationalSqrt","rationalSquareRoots","nestedSquareRoots","negatedP","values","square","signedSurdNode","surd","negativeP","solutions","halved","positive","centre","modulus","re","nestedSurd","im","offset","resolvent","z","alpha","beta","gamma","one","DURAND_KERNER_MAX_ITERATIONS","DURAND_KERNER_TOLERANCE","ROOT_RESIDUAL_TOLERANCE","ROOT_SEPARATION_TOLERANCE","AXIS_SNAP_TOLERANCE","CONJUGATE_PAIR_TOLERANCE","NEWTON_POLISH_STEPS","subtract","multiply","divide","nextRe","evaluationScale","radius","differentiate","derivative","squareFreeDoubles","ascending","doubles","squareFreePart","initialEstimates","largest","estimates","durandKerner","iteration","largestStep","largestRoot","j","step","polish","start","slope","next","snapToAxes","scale","isRootWithinTolerance","pairConjugates","wanted","partner","closest","distance","allSeparated","approximateRoots","converged","SOLVE_MAX_DEGREE","evaluateRational","rational4","twoA","rational2","complexQuadraticRoots","rootN","rootD","plus","minus","lower","upper","negatedB","complex","scaledRadicand","realApproximation","solveForVariable","lhs","rhs","others","solveLinearWithOtherUnknowns","solveUnivariate","coefficientTerms","constantTerms","part","closedFormRoots","extractRationalRoots","powersOfX","exact","approximate","leftoverDegree","solvedDegree","finish","closedForm","numeric","unsolvedDegree","reason","incoherent","SYMBOLIC_BUILTIN_NAMES","POW_BUILTIN_INDEX","SYMBOLIC_NATIVE_BUILTINS","valueToSymbolic","rationalFromNumber","symbolicToValue","simplified","numberValue","symbolicValue","unsupported","what","errorValue","symbolicPow","l","base","symbolicNeg","operand","symbolicBuiltin","args","nodes","arg","faulted","faultedOperand","callNode","rootToValue","approximateRootToValue","solveOutcomeToValue","outcome","stringValue","matrixValue","solveEquationValues","lhsValue","rhsValue","unifyUom","lMeasure","getMeasure","rMeasure","isCurrency","sharedCurrencyExchange","rvConverted","convertUnit","UNIFIED_COMPARISON_TOLERANCE","largestFiniteMagnitude","compareUom","lv","rv","sameMeasure","decimalCompare","MEASURE_NOUNS","UNCOUNTABLE_MEASURES","COMBINE_VERBS","describeMeasure","unit","measure","withMeasureArticle","noun","describeMeasureMismatch","lUnit","rUnit","verb","combineVerb","op","describeConversionMismatch","fromUnit","toUnit","from","to","incomparableUnitsError","named","toBigIntOperand","n","shown","bigIntDivisionByZero","compareBigIntOperands","lb","exactBigInt","rb","operandExactDecimal","decimalFromNumberIfExact","exactMoneyOp","lMoney","rMoney","ld","rd","decimalAdd","decimalSubtract","decimalMultiply","decimalIsZero","decimalDivide","uomValueExact","decimalToNumber","operandRational","rational","exactRationalOp","lr","rr","numberValueRational","uncertainOp","sa","sb","center","sigma","numberValueUncertain","compareRationalOperands","binaryOp","bigOp","symbolicOp","bigIntValue","exactMoney","uomValue","lm","rm","sameShape","scalar","MAX_OPCODE","DYNAMIC_OPCODE_START","OpRegistry","registration","opcode","sharedOpRegistry","ONE_DECIMAL","decimalFromInteger","moneyExactMagnitude","decimalFromShortDecimal","s","decimalFromLiteral","scaleMoneyExact","amount","factorDecimal","scaleMoneyByPercent","money","percent","percentDecimal","decimalNegate","onePlusRateDecimal","rate","rateDecimal","removeTaxExact","divisor","taxInExact","tax","splitEachExact","cents","centsOfMoney","baseCents","extraShares","centShare","count","makeDecimal","decimalRound","APART_MAX_DEGREE","coefficients","denominatorFactors","enumerateUnknowns","unknowns","factorDegree","unknownColumn","unknown","polynomialDivide","isZeroPolynomial","solveLinearSystem","matrix","target","size","column","pivot","row","partialFractions","coefficientGcd","reducedNumerator","reducedDenominator","monicDenominator","scaledNumerator","solveForNumerators","columns","solution","groupSolution","grouped","existing","factorIndex","termPower","filled","apartSymbolic","parts","asRationalFunction","decomposition","isNegativeNumerator","piece","DERIVATIVE_MAX_ORDER","zero","functionDerivative","argument","oneMinusSquare","onePlusSquare","order","derive","derivePow","unevaluated","outer","asLinear","intercept","integratePolynomial","nextPower","scaled","integrateStandardForm","divideBySlope","integrateReciprocalForms","isRationalOneNode","integrateRationalFunction","polynomialAntiderivative","integrateTerm","baseDegree","integrateQuadraticTerm","constant","halfP","logarithm","leftover","width","arctangent","integrate","freeVariables","standard","reciprocal","rationalFunction","TAYLOR_MAX_DEGREE","taylorSeries","point","pointNode","factorial","atPoint","substitute","jacobian","functions","variables","fn","createEngineContext","defaultEngineContext","CPI_TABLE","CPI_MIN_YEAR","CPI_MAX_YEAR","getCpi","year","inflationRatio","fromYear","toYear","fromCpi","toCpi","adjustForInflation","ANGLE_KIND","angleInRadians","entry","UNIT_TABLE","pluraliseUnit","plural","extremum","wantLargest","best","hasNaN","bestUnit","otherUnit","keepUnit","roundToPlaces","source","places","rounded","withPlaces","nonFiniteEuclidOperand","culprit","euclidGcd","t","sumOfSquares","nums","mean","acc","variance","sample","denom","builtinFunctions","determinant","matrixPower","nonFinite","sorted","mid","aNum","bNum","lo","hi","hexValue","principal","years","fv","interest","futureValue","periodsPerYear","totalRepayment","amortizeLoan","totalInterest","monthlyPayment","transpose","inverse","toMatrix","matrixMultiply","expandSymbolic","variableValue","orderValue","symbolicVariableName","expression","pointValue","degreeValue","rows","rowMajor","cell","symbolicToEntry","rowMajorToColumnMajor","applyComplexAccessor","cancelSymbolic","major","minor","majorEntry","minorEntry","sourceEntry","inBase","majorCount","minorCount","slash","leftUnit","denominatorEntry","leftEntry","perYear","future","pv","invested","returned","percentageValue","splitValue","months","monthsOfDuration","annualRate","payment","annuityPayment","contribution","periods","annuityPeriods","counts","bestCount","weightedSum","weightTotal","weight","duration","raw","rMonthly","pluginFunctionRegistry","MAX_PLUGIN_FUNCTION_INDEX","nextPluginFunctionIndex","allocatePluginFunctionIndex","pluginFunctionIndexByQualifiedName","pluginFunctionIndexFor","qualifiedName","asConverterRegistry","registerAsConverter","handler","unregisterAsConverter","_GlobalVariableStore","previous","sameValue","listener","GlobalVariableStore","av","bv","sharedGlobalVariableStore","globalDagKey"],"mappings":"gkBAmDA,SAASA,EAAAA,CAAUC,CAAAA,CAAiBC,CAAAA,CAAgC,CACnE,IAAMC,CAAAA,CAASD,CAAAA,GAAW,C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AAA,GAASC,CAAAA,CAAE,IAAA,EAAA,CACZD,CAAAA,CAAE,QAAA,EAAY,KAAA,KAAYC,CAAAA,CAAE,QAAA,EAAY,KAAA,CAAA,CAAQ,OAAO,MAAA,CAE5D,IAAMmpB,CAAAA,CAAKppB,CAAAA,CAAE,KAAA,CACPqpB,CAAAA,CAAKppB,CAAAA,CAAE,KAAA,CACb,GAAI,KAAA,CAAM,OAAA,CAAQmpB,CAAE,CAAA,EAAK,KAAA,CAAM,OAAA,CAAQC,CAAE,EAAG,CAE3C,GADI,CAAC,KAAA,CAAM,OAAA,CAAQD,CAAE,CAAA,EAAK,CAAC,KAAA,CAAM,OAAA,CAAQC,CAAE,CAAA,EACvCD,CAAAA,CAAG,MAAA,GAAWC,CAAAA,CAAG,MAAA,CAAQ,OAAO,MAAA,CACpC,IAAA,IAASjoB,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIgoB,CAAAA,CAAG,MAAA,CAAQhoB,CAAAA,EAAAA,CAC9B,GAAI,CAAC,MAAA,CAAO,EAAA,CAAGgoB,CAAAA,CAAGhoB,CAAC,CAAA,CAAGioB,CAAAA,CAAGjoB,CAAC,CAAC,CAAA,CAAG,OAAO,MAAA,CAEtC,OAAO,KACR,CACA,OAAO,MAAA,CAAO,EAAA,CAAGgoB,CAAAA,CAAIC,CAAE,CACxB,CAMO,IAAMC,EAAAA,CAA4B,IAAIH,GAYtC,SAASI,EAAAA,CAAa3pB,CAAAA,CAAsB,CAClD,OAAO,CAAA,OAAA,EAAUA,CAAI,CAAA,CACtB","file":"chunk-YTCTUBR2.js","sourcesContent":["/**\n * Factoring polynomials in more than one variable.\n *\n * `Factor.ts` handles one variable completely, by the rational-root theorem,\n * and stops at content and common-monomial extraction the moment a second\n * variable appears. That stop is principled, because multivariate factoring in\n * general is a much harder problem than the univariate case and the honest\n * options are a real algorithm or none. What it left out, though, is the handful\n * of shapes a person actually writes: `x^2-y^2`, `x^3+y^3`, `x^2+2xy+y^2`, and\n * `ax+ay+bx+by`.\n *\n * So this is patterns, not an algorithm, and it says so. Each one is recognised\n * exactly, over exact coefficients, and produces a factorization that multiplies\n * back to the input. Anything not matching a pattern is declined, which leaves\n * the caller exactly where it was before.\n *\n * ## What it does not do\n *\n * It does not recurse. `x^6-y^6` is both a difference of squares and a\n * difference of cubes; the squares pattern matches first and gives\n * `(x^3-y^3)(x^3+y^3)`, which is correct and not fully factored. Recursing would\n * mean calling back into `Factor.ts`, which calls this, and the extra\n * factorization is not worth a circular dependency between the two.\n */\n\nimport { type SymbolicNode, constNode } from \"@solve-js/symbolic/SymbolicNode\";\nimport {\n\ttype Rational,\n\trationalMul,\n\trationalDiv,\n\trationalNeg,\n\tisRationalOne,\n} from \"@solve-js/symbolic/Rational\";\nimport {\n\ttype Polynomial,\n\ttype MonomialKey,\n\ttype Monomial,\n\tmonomialToKey,\n\tmonomialFromKey,\n\tcompareMonomials,\n\tfromPolynomial,\n} from \"@solve-js/symbolic/Polynomial\";\nimport { exactIntegerSqrt, exactIntegerCbrt } from \"@solve-js/symbolic/Radicals\";\n\n/** One term of a polynomial, pulled out of the term map so the patterns below can read as algebra. */\ninterface Term {\n\treadonly key: MonomialKey;\n\treadonly coefficient: Rational;\n}\n\n/** The exact `n`-th root of a rational, or `null` when it is irrational. Only the second and third roots are needed. */\nfunction exactRoot(value: Rational, degree: 2 | 3): Rational | null {\n\tconst rootOf = degree === 2 ? exactIntegerSqrt : exactIntegerCbrt;\n\tconst numerator = rootOf(value.n);\n\tconst denominator = rootOf(value.d);\n\treturn numerator === null || denominator === null ? null : { n: numerator, d: denominator };\n}\n\n/** The exact `n`-th root of a monomial, or `null` when some exponent is not divisible by `n`. */\nfunction monomialRoot(key: MonomialKey, degree: number): MonomialKey | null {\n\tconst monomial = monomialFromKey(key);\n\tconst root: Monomial = new Map();\n\tfor (const [name, exponent] of monomial) {\n\t\tif (exponent % degree !== 0) return null;\n\t\troot.set(name, exponent / degree);\n\t}\n\treturn monomialToKey(root);\n}\n\n/** Multiplies two monomials. */\nfunction monomialMul(a: MonomialKey, b: MonomialKey): MonomialKey {\n\tconst product = monomialFromKey(a);\n\tfor (const [name, exponent] of monomialFromKey(b)) {\n\t\tproduct.set(name, (product.get(name) ?? 0) + exponent);\n\t}\n\treturn monomialToKey(product);\n}\n\n/** Divides one monomial by another, which the caller must already know divides it. */\nfunction monomialDiv(a: MonomialKey, b: MonomialKey): MonomialKey {\n\tconst quotient = monomialFromKey(a);\n\tfor (const [name, exponent] of monomialFromKey(b)) {\n\t\tconst remaining = (quotient.get(name) ?? 0) - exponent;\n\t\tif (remaining <= 0) quotient.delete(name);\n\t\telse quotient.set(name, remaining);\n\t}\n\treturn monomialToKey(quotient);\n}\n\n/** The highest monomial dividing both, taking the lower exponent of each shared variable. */\nfunction monomialGcd(a: MonomialKey, b: MonomialKey): MonomialKey {\n\tconst left = monomialFromKey(a);\n\tconst shared: Monomial = new Map();\n\tfor (const [name, exponent] of monomialFromKey(b)) {\n\t\tconst other = left.get(name);\n\t\tif (other !== undefined) shared.set(name, Math.min(other, exponent));\n\t}\n\treturn monomialToKey(shared);\n}\n\n/** The variable names a monomial mentions. */\nfunction namesOf(keys: readonly MonomialKey[]): string[] {\n\tconst names = new Set<string>();\n\tfor (const key of keys) for (const name of monomialFromKey(key).keys()) names.add(name);\n\treturn [...names].sort();\n}\n\n/** Builds an expression from a term list, going through {@link fromPolynomial} so the ordering matches everything else. */\nfunction termsToNode(terms: readonly Term[]): SymbolicNode {\n\tconst map = new Map<MonomialKey, Rational>();\n\tfor (const term of terms) map.set(term.key, term.coefficient);\n\treturn fromPolynomial({ terms: map, vars: namesOf(terms.map(term => term.key)) });\n}\n\n/** Multiplies a list of factors into one expression. */\nfunction product(factors: readonly SymbolicNode[]): SymbolicNode {\n\tlet result = factors[0];\n\tfor (let i = 1; i < factors.length; i++) result = { kind: \"mul\", left: result, right: factors[i] };\n\treturn result;\n}\n\n/**\n * The terms of a polynomial in the same order {@link fromPolynomial} prints\n * them, highest first.\n *\n * Through {@link compareMonomials} rather than by sorting the key strings. The\n * patterns below read positionally, so `x^2+2xy+y^2` has to arrive with `x^2`\n * first; sorting keys as text puts `x*y` first, because `*` sorts before `^`.\n */\nfunction orderedTerms(p: Polynomial): Term[] {\n\tconst terms: Term[] = [...p.terms].map(([key, coefficient]) => ({ key, coefficient }));\n\treturn terms.sort((a, b) => compareMonomials(a.key, b.key, p.vars));\n}\n\n/**\n * Factors a multivariate polynomial by pattern.\n *\n * @param p - The polynomial, already stripped of its content and common\n * monomial by the caller.\n * @returns The factored expression, or `null` when no pattern matched.\n */\nexport function factorMultivariate(p: Polynomial): SymbolicNode | null {\n\tif (p.vars.length < 2) return null;\n\n\tconst terms = orderedTerms(p);\n\tif (terms.length === 2) return factorBinomial(terms[0], terms[1]);\n\tif (terms.length === 3) return factorPerfectSquare(terms);\n\tif (terms.length === 4) return factorByGrouping(terms);\n\treturn null;\n}\n\n/**\n * A difference of squares, or a sum or difference of cubes.\n *\n * Each needs both terms to be exact powers, coefficient and monomial together:\n * `4x^2-9y^2` matches because four and nine are squares and both exponents are\n * even, while `2x^2-y^2` does not, since its factorization needs `sqrt(2)` and\n * so is not over the rationals at all.\n */\nfunction factorBinomial(first: Term, second: Term): SymbolicNode | null {\n\tconst firstPositive = first.coefficient.n > 0n;\n\tconst secondPositive = second.coefficient.n > 0n;\n\t// A leading negative is left alone: negating to match a pattern would produce\n\t// a factorization with a spurious -1 out front.\n\tif (!firstPositive) return null;\n\n\tconst squares = asPowerPair(first, second, 2);\n\tif (squares !== null && !secondPositive) {\n\t\t// A^2 - B^2 = (A-B)(A+B)\n\t\treturn product([\n\t\t\ttermsToNode([squares.a, negated(squares.b)]),\n\t\t\ttermsToNode([squares.a, squares.b]),\n\t\t]);\n\t}\n\n\tconst cubes = asPowerPair(first, second, 3);\n\tif (cubes === null) return null;\n\t// A^3 - B^3 = (A-B)(A^2+AB+B^2), and A^3 + B^3 = (A+B)(A^2-AB+B^2).\n\tconst linear = secondPositive\n\t\t? termsToNode([cubes.a, cubes.b])\n\t\t: termsToNode([cubes.a, negated(cubes.b)]);\n\tconst middle = secondPositive ? negated(multiplyTerms(cubes.a, cubes.b)) : multiplyTerms(cubes.a, cubes.b);\n\treturn product([linear, termsToNode([squareOf(cubes.a), middle, squareOf(cubes.b)])]);\n}\n\n/** Both terms as exact `degree`-th powers, or `null` when either is not one. */\nfunction asPowerPair(first: Term, second: Term, degree: 2 | 3): { a: Term; b: Term } | null {\n\tconst magnitude = second.coefficient.n < 0n ? rationalNeg(second.coefficient) : second.coefficient;\n\tconst firstRoot = exactRoot(first.coefficient, degree);\n\tconst secondRoot = exactRoot(magnitude, degree);\n\tif (firstRoot === null || secondRoot === null) return null;\n\n\tconst firstKey = monomialRoot(first.key, degree);\n\tconst secondKey = monomialRoot(second.key, degree);\n\tif (firstKey === null || secondKey === null) return null;\n\n\treturn { a: { key: firstKey, coefficient: firstRoot }, b: { key: secondKey, coefficient: secondRoot } };\n}\n\n/** Negates a term. */\nfunction negated(term: Term): Term {\n\treturn { key: term.key, coefficient: rationalNeg(term.coefficient) };\n}\n\n/** Multiplies two terms. */\nfunction multiplyTerms(a: Term, b: Term): Term {\n\treturn { key: monomialMul(a.key, b.key), coefficient: rationalMul(a.coefficient, b.coefficient) };\n}\n\n/** Squares a term. */\nfunction squareOf(term: Term): Term {\n\treturn multiplyTerms(term, term);\n}\n\n/**\n * A perfect-square trinomial, `A^2 ± 2AB + B^2`.\n *\n * The outer terms have to be squares and the middle one exactly twice their\n * roots' product. `x^2+3xy+y^2` fails that last test and is left alone, which\n * is right: it does not factor over the rationals.\n */\nfunction factorPerfectSquare(terms: readonly Term[]): SymbolicNode | null {\n\tconst [first, middle, last] = terms;\n\tif (first.coefficient.n < 0n || last.coefficient.n < 0n) return null;\n\n\tconst roots = asPowerPair(first, last, 2);\n\tif (roots === null) return null;\n\n\tconst cross = multiplyTerms(roots.a, roots.b);\n\tif (cross.key !== middle.key) return null;\n\n\tconst twice = rationalMul(cross.coefficient, { n: 2n, d: 1n });\n\tconst negative = middle.coefficient.n < 0n;\n\tconst magnitude = negative ? rationalNeg(middle.coefficient) : middle.coefficient;\n\tif (!isRationalOne(rationalDiv(magnitude, twice))) return null;\n\n\tconst base = termsToNode([roots.a, negative ? negated(roots.b) : roots.b]);\n\treturn { kind: \"pow\", base, exponent: constNode(2) };\n}\n\n/**\n * Four terms that split into two pairs sharing a factor.\n *\n * `ax+ay+bx+by` pairs as `a(x+y) + b(x+y)`, so the shared `x+y` comes out and\n * `a+b` is what is left. All three ways of pairing four terms are tried, since\n * the terms arrive in degree order rather than in the order that groups.\n */\nfunction factorByGrouping(terms: readonly Term[]): SymbolicNode | null {\n\tconst pairings: [number, number][][] = [\n\t\t[[0, 1], [2, 3]],\n\t\t[[0, 2], [1, 3]],\n\t\t[[0, 3], [1, 2]],\n\t];\n\n\tfor (const pairing of pairings) {\n\t\tconst first = splitPair(terms[pairing[0][0]], terms[pairing[0][1]]);\n\t\tconst second = splitPair(terms[pairing[1][0]], terms[pairing[1][1]]);\n\t\tif (first === null || second === null) continue;\n\t\tif (!cofactorsAgree(first.cofactor, second.cofactor)) continue;\n\n\t\treturn product([\n\t\t\ttermsToNode([first.common, second.common]),\n\t\t\ttermsToNode(first.cofactor),\n\t\t]);\n\t}\n\treturn null;\n}\n\n/**\n * Splits a pair of terms into what they share and what is left.\n *\n * The shared part takes the first term's whole coefficient rather than a\n * greatest common divisor of the two, which makes the leftover start with one.\n * That is what lets two pairs be compared directly: both leftovers are written\n * in the same normal form, so equality is a term-by-term check rather than a\n * proportionality test.\n */\nfunction splitPair(first: Term, second: Term): { common: Term; cofactor: Term[] } | null {\n\tconst shared = monomialGcd(first.key, second.key);\n\tconst common: Term = { key: shared, coefficient: first.coefficient };\n\tconst cofactor: Term[] = [\n\t\t{ key: monomialDiv(first.key, shared), coefficient: { n: 1n, d: 1n } },\n\t\t{ key: monomialDiv(second.key, shared), coefficient: rationalDiv(second.coefficient, first.coefficient) },\n\t];\n\t// Two terms that shared everything would leave a constant cofactor, which is\n\t// not a factorization of anything.\n\treturn cofactor[0].key === cofactor[1].key ? null : { common, cofactor };\n}\n\n/** Whether two cofactors are the same polynomial, term for term. */\nfunction cofactorsAgree(a: readonly Term[], b: readonly Term[]): boolean {\n\tif (a.length !== b.length) return false;\n\treturn a.every((term, index) =>\n\t\tterm.key === b[index].key\n\t\t&& term.coefficient.n === b[index].coefficient.n\n\t\t&& term.coefficient.d === b[index].coefficient.d);\n}\n","/**\n * Polynomial factoring over the rationals.\n *\n * ## What \"factored\" means here\n *\n * Factoring is only well defined once you say **over what**. `x^2-2` is\n * irreducible over the rationals but factors over the reals as\n * `(x-sqrt(2))(x+sqrt(2))`, and `x^2+1` factors only over the complex numbers.\n * This module factors **over the rationals**, so both of those come back\n * unchanged. That is a real answer, not a failure, and the documentation says\n * so rather than leaving a user to guess.\n *\n * The consequence worth stating plainly: a polynomial with no rational roots is\n * returned as one irreducible factor even in the cases where it does split into\n * higher-degree rational pieces that this module does not search for. See the\n * strategy list on {@link factorSymbolic} for exactly what is attempted.\n *\n * ## Why this is exact\n *\n * The rational-root theorem tests a candidate by evaluating the polynomial at\n * it and asking whether the result is zero. In floating point a near-miss and a\n * true root are indistinguishable, so the whole method depends on the exact\n * arithmetic in `Rational.ts`. This is the clearest reason the CAS could not\n * have been built on doubles.\n */\n\nimport {\n\ttype SymbolicNode,\n\tconstNode,\n\tvarNode,\n\tpowNode,\n} from \"@solve-js/symbolic/SymbolicNode\";\nimport {\n\ttype Rational,\n\tRATIONAL_ZERO,\n\tRATIONAL_ONE,\n\trationalAdd,\n\trationalMul,\n\trationalDiv,\n\trationalNeg,\n\tisRationalZero,\n\tisRationalOne,\n} from \"@solve-js/symbolic/Rational\";\nimport {\n\ttype Polynomial,\n\ttoPolynomial,\n\tfromPolynomial,\n\tpolyDegree,\n\tpolyUnivariateVar,\n\tpolyCoefficients,\n} from \"@solve-js/symbolic/Polynomial\";\nimport { factorMultivariate } from \"@solve-js/symbolic/MultivariateFactor\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Highest degree this module will attempt to factor.\n *\n * The rational-root search is the expensive step and its cost grows with the\n * size of the leading and trailing coefficients rather than with degree alone,\n * but degree bounds how many times that search is repeated as factors are\n * divided out.\n */\nexport const FACTOR_MAX_DEGREE = 12;\n\n/**\n * Ceiling on the number of candidate roots the rational-root theorem may test.\n *\n * This is the step that actually blows up. Candidates are every `±p/q` for `p`\n * dividing the trailing coefficient and `q` the leading one, so the set is the\n * **product** of two divisor sets. A trailing coefficient of 720720 alone has\n * 240 divisors, and a comparable leading coefficient would put the product in\n * the tens of thousands before any of them is tested.\n */\nexport const FACTOR_MAX_ROOT_CANDIDATES = 4_096;\n\n/**\n * A polynomial written as a rational constant times a list of irreducible\n * factors with multiplicity.\n */\nexport interface Factorization {\n\t/** The rational content pulled out front. One when the polynomial was already primitive. */\n\treadonly content: Rational;\n\t/** Irreducible-over-the-rationals factors, in ascending degree. */\n\treadonly factors: readonly { readonly base: SymbolicNode; readonly power: number }[];\n}\n\n/** Greatest common divisor of two non-negative bigints. */\nfunction gcd(a: bigint, b: bigint): bigint {\n\tlet x = a < 0n ? -a : a;\n\tlet y = b < 0n ? -b : b;\n\twhile (y !== 0n) {\n\t\tconst remainder = x % y;\n\t\tx = y;\n\t\ty = remainder;\n\t}\n\treturn x;\n}\n\n/** Least common multiple of two positive bigints. */\nfunction lcm(a: bigint, b: bigint): bigint {\n\tif (a === 0n || b === 0n) return 0n;\n\treturn (a / gcd(a, b)) * b;\n}\n\n/**\n * Every positive divisor of a positive bigint, by trial division to its square\n * root.\n *\n * @returns The divisors, or `null` once more than {@link FACTOR_MAX_ROOT_CANDIDATES}\n * have been found, so a highly-composite coefficient stops the search rather\n * than exhausting time here.\n */\nfunction divisors(value: bigint): bigint[] | null {\n\tconst magnitude = value < 0n ? -value : value;\n\tif (magnitude === 0n) return null;\n\tconst found: bigint[] = [];\n\tfor (let candidate = 1n; candidate * candidate <= magnitude; candidate++) {\n\t\tif (magnitude % candidate !== 0n) continue;\n\t\tfound.push(candidate);\n\t\tconst paired = magnitude / candidate;\n\t\tif (paired !== candidate) found.push(paired);\n\t\tif (found.length > FACTOR_MAX_ROOT_CANDIDATES) return null;\n\t}\n\treturn found;\n}\n\n/** Evaluates a descending-order coefficient list at `x`, by Horner's method. */\nfunction evaluateAt(descending: readonly Rational[], x: Rational): Rational {\n\tlet total = RATIONAL_ZERO;\n\tfor (const coeff of descending) total = rationalAdd(rationalMul(total, x), coeff);\n\treturn total;\n}\n\n/**\n * Divides a descending-order polynomial by `(x - root)` using synthetic\n * division.\n *\n * @returns The quotient's descending coefficients. The remainder is discarded,\n * so only call this with a value already confirmed to be a root.\n */\nfunction divideByRoot(descending: readonly Rational[], root: Rational): Rational[] {\n\tconst quotient: Rational[] = [descending[0]];\n\tfor (let i = 1; i < descending.length - 1; i++) {\n\t\tquotient.push(rationalAdd(descending[i], rationalMul(quotient[i - 1], root)));\n\t}\n\treturn quotient;\n}\n\n/**\n * Every rational root of a univariate polynomial, by the rational-root theorem.\n *\n * @param descending - Coefficients from the highest power down. The leading\n * coefficient must be non-zero and the trailing one must also be non-zero (a\n * zero constant term means `x` itself is a factor, which the caller removes as\n * a common monomial first).\n * @returns The distinct rational roots, each listed once.\n * @throws {EngineError} `SYMBOLIC_FACTOR_LIMIT_EXCEEDED` when the candidate set\n * would exceed {@link FACTOR_MAX_ROOT_CANDIDATES}.\n */\nexport function rationalRoots(descending: readonly Rational[]): readonly Rational[] {\n\tif (descending.length < 2) return [];\n\n\t// Clear denominators so the theorem's integer statement applies.\n\tlet multiplier = 1n;\n\tfor (const coeff of descending) multiplier = lcm(multiplier, coeff.d);\n\tconst integers = descending.map(coeff => (coeff.n * multiplier) / coeff.d);\n\n\tconst leading = integers[0];\n\tconst trailing = integers[integers.length - 1];\n\tif (trailing === 0n) return [];\n\n\tconst numeratorDivisors = divisors(trailing);\n\tconst denominatorDivisors = divisors(leading);\n\tif (numeratorDivisors === null || denominatorDivisors === null) {\n\t\tthrow ErrorFactory.execution(\n\t\t\t\"SYMBOLIC_FACTOR_LIMIT_EXCEEDED\",\n\t\t\t\"This polynomial's coefficients have too many divisors to search for rational roots.\",\n\t\t\t{ limit: FACTOR_MAX_ROOT_CANDIDATES },\n\t\t);\n\t}\n\tif (numeratorDivisors.length * denominatorDivisors.length > FACTOR_MAX_ROOT_CANDIDATES) {\n\t\tthrow ErrorFactory.execution(\n\t\t\t\"SYMBOLIC_FACTOR_LIMIT_EXCEEDED\",\n\t\t\t\"This polynomial has too many candidate rational roots to test.\",\n\t\t\t{ limit: FACTOR_MAX_ROOT_CANDIDATES },\n\t\t);\n\t}\n\n\tconst roots: Rational[] = [];\n\tconst seen = new Set<string>();\n\tfor (const p of numeratorDivisors) {\n\t\tfor (const q of denominatorDivisors) {\n\t\t\tfor (const sign of [1n, -1n]) {\n\t\t\t\tconst candidate: Rational = { n: (sign * p) / gcd(p, q), d: q / gcd(p, q) };\n\t\t\t\tconst key = `${candidate.n}/${candidate.d}`;\n\t\t\t\tif (seen.has(key)) continue;\n\t\t\t\tseen.add(key);\n\t\t\t\tif (isRationalZero(evaluateAt(descending, candidate))) roots.push(candidate);\n\t\t\t}\n\t\t}\n\t}\n\treturn roots;\n}\n\n/** Builds the node for `x - root`, or `x + |root|` when the root is negative, so the display reads naturally. */\nfunction linearFactorNode(variable: string, root: Rational): SymbolicNode {\n\tif (isRationalZero(root)) return varNode(variable);\n\treturn root.n > 0n\n\t\t? { kind: \"sub\", left: varNode(variable), right: constNode(root) }\n\t\t: { kind: \"add\", left: varNode(variable), right: constNode(rationalNeg(root)) };\n}\n\n/** Rebuilds a descending coefficient list into an expression tree in the given variable. */\nfunction coefficientsToNode(descending: readonly Rational[], variable: string): SymbolicNode {\n\tconst degree = descending.length - 1;\n\tconst terms = new Map<string, Rational>();\n\tdescending.forEach((coeff, index) => {\n\t\tif (isRationalZero(coeff)) return;\n\t\tconst power = degree - index;\n\t\tterms.set(power === 0 ? \"\" : power === 1 ? variable : `${variable}^${power}`, coeff);\n\t});\n\treturn fromPolynomial({ terms, vars: terms.size > 0 ? [variable] : [] });\n}\n\n/**\n * Factors a univariate polynomial over the rationals by repeatedly extracting\n * rational roots.\n *\n * @param descending - Coefficients from the highest power down.\n * @param variable - The variable name, used to build the factor nodes.\n * @returns The factorization. A polynomial with no rational roots comes back as\n * a single factor, which is the correct answer over the rationals.\n */\nexport function factorUnivariate(descending: readonly Rational[], variable: string): Factorization {\n\tconst factors: { base: SymbolicNode; power: number }[] = [];\n\tlet remaining = [...descending];\n\n\t// A root can repeat, so each one is divided out until it stops being one.\n\t// That is what turns (x-1)^2 into a single factor with power two rather\n\t// than two identical factors.\n\tlet roots = rationalRoots(remaining);\n\twhile (roots.length > 0 && remaining.length > 2) {\n\t\tfor (const root of roots) {\n\t\t\tlet multiplicity = 0;\n\t\t\twhile (remaining.length > 1 && isRationalZero(evaluateAt(remaining, root))) {\n\t\t\t\tremaining = divideByRoot(remaining, root);\n\t\t\t\tmultiplicity++;\n\t\t\t}\n\t\t\tif (multiplicity > 0) factors.push({ base: linearFactorNode(variable, root), power: multiplicity });\n\t\t}\n\t\troots = remaining.length > 2 ? rationalRoots(remaining) : [];\n\t}\n\n\t// Whatever survives is irreducible over the rationals as far as this module\n\t// searches. A leading coefficient other than one stays inside it rather than\n\t// being pulled out, so the product still multiplies back to the input.\n\tconst leftoverDegree = remaining.length - 1;\n\tif (leftoverDegree >= 1) {\n\t\tfactors.push({ base: coefficientsToNode(remaining, variable), power: 1 });\n\t\treturn { content: RATIONAL_ONE, factors };\n\t}\n\treturn { content: remaining.length === 1 ? remaining[0] : RATIONAL_ONE, factors };\n}\n\n/** Multiplies a content constant and a factor list back into one expression tree. */\nfunction factorizationToNode(factorization: Factorization): SymbolicNode {\n\tconst pieces: SymbolicNode[] = [];\n\tif (!isRationalOne(factorization.content)) pieces.push(constNode(factorization.content));\n\tfor (const factor of factorization.factors) {\n\t\tpieces.push(factor.power === 1 ? factor.base : powNode(factor.base, constNode({ n: BigInt(factor.power), d: 1n })));\n\t}\n\tif (pieces.length === 0) return constNode(RATIONAL_ONE);\n\n\tlet result = pieces[0];\n\tfor (let i = 1; i < pieces.length; i++) result = { kind: \"mul\", left: result, right: pieces[i] };\n\treturn result;\n}\n\n/** The rational content of a polynomial: the gcd of its numerators over the lcm of its denominators. */\nfunction contentOf(p: Polynomial): Rational {\n\tlet numeratorGcd = 0n;\n\tlet denominatorLcm = 1n;\n\tfor (const coeff of p.terms.values()) {\n\t\tnumeratorGcd = gcd(numeratorGcd, coeff.n);\n\t\tdenominatorLcm = lcm(denominatorLcm, coeff.d);\n\t}\n\tif (numeratorGcd === 0n) return RATIONAL_ONE;\n\treturn { n: numeratorGcd, d: denominatorLcm };\n}\n\n/** The highest power of each variable dividing every term, as a monomial key, plus the polynomial with it removed. */\nfunction extractCommonMonomial(p: Polynomial): { monomial: Map<string, number>; reduced: Polynomial } {\n\tconst common = new Map<string, number>();\n\tfor (const name of p.vars) {\n\t\tlet lowest = Infinity;\n\t\tfor (const key of p.terms.keys()) {\n\t\t\tconst exponent = exponentOf(key, name);\n\t\t\tif (exponent < lowest) lowest = exponent;\n\t\t}\n\t\tif (lowest > 0 && lowest !== Infinity) common.set(name, lowest);\n\t}\n\tif (common.size === 0) return { monomial: common, reduced: p };\n\n\tconst terms = new Map<string, Rational>();\n\tfor (const [key, coeff] of p.terms) {\n\t\tconst exponents = parseKey(key);\n\t\tfor (const [name, shared] of common) exponents.set(name, (exponents.get(name) ?? 0) - shared);\n\t\tterms.set(buildKey(exponents), coeff);\n\t}\n\tconst names = new Set<string>();\n\tfor (const key of terms.keys()) for (const name of parseKey(key).keys()) names.add(name);\n\treturn { monomial: common, reduced: { terms, vars: [...names].sort() } };\n}\n\n/** Exponent of one variable within a monomial key. */\nfunction exponentOf(key: string, name: string): number {\n\treturn parseKey(key).get(name) ?? 0;\n}\n\n/** Parses a monomial key into a variable-to-exponent map, mirroring `Polynomial.ts`'s own encoding. */\nfunction parseKey(key: string): Map<string, number> {\n\tconst exponents = new Map<string, number>();\n\tif (key === \"\") return exponents;\n\tfor (const factor of key.split(\"*\")) {\n\t\tconst caret = factor.indexOf(\"^\");\n\t\tif (caret === -1) exponents.set(factor, 1);\n\t\telse exponents.set(factor.slice(0, caret), Number(factor.slice(caret + 1)));\n\t}\n\treturn exponents;\n}\n\n/** Serializes a variable-to-exponent map back into a monomial key, dropping zero exponents. */\nfunction buildKey(exponents: Map<string, number>): string {\n\tconst names = [...exponents.keys()].filter(name => (exponents.get(name) ?? 0) > 0).sort();\n\treturn names.map(name => (exponents.get(name) === 1 ? name : `${name}^${exponents.get(name)}`)).join(\"*\");\n}\n\n/** Builds the node for a common monomial such as `2x` or `x^2*y`. */\nfunction monomialNode(monomial: Map<string, number>): SymbolicNode | null {\n\tconst names = [...monomial.keys()].sort();\n\tlet result: SymbolicNode | null = null;\n\tfor (const name of names) {\n\t\tconst exponent = monomial.get(name)!;\n\t\tconst factor = exponent === 1 ? varNode(name) : powNode(varNode(name), constNode({ n: BigInt(exponent), d: 1n }));\n\t\tresult = result === null ? factor : { kind: \"mul\", left: result, right: factor };\n\t}\n\treturn result;\n}\n\n/**\n * Factors an expression over the rationals.\n *\n * Strategies, in the order attempted:\n *\n * 1. Convert to polynomial form. Anything that is not a polynomial over the\n * rationals is returned unchanged.\n * 2. Pull out the rational content, the shared factor across all coefficients.\n * 3. Pull out the highest power of each variable dividing every term, so\n * `2x^2+4x` becomes `2x*(x+2)`.\n * 4. If more than one variable remains, hand off to\n * {@link factorMultivariate}'s pattern set: a difference of squares, a sum\n * or difference of cubes, a perfect-square trinomial, or four terms that\n * group. Anything it declines stops here, with the content and common\n * monomial extracted and nothing guessed at beyond them.\n * 5. Extract rational roots by the rational-root theorem, dividing each out\n * with its multiplicity.\n * 6. Leave whatever survives as one irreducible-over-the-rationals factor.\n *\n * @param node - The expression to factor.\n * @returns The factored expression, or `node` unchanged when it is not a\n * polynomial, is already irreducible, or exceeds {@link FACTOR_MAX_DEGREE}.\n * @throws {EngineError} `SYMBOLIC_FACTOR_LIMIT_EXCEEDED` when the rational-root\n * candidate set grows past {@link FACTOR_MAX_ROOT_CANDIDATES}.\n */\nexport function factorSymbolic(node: SymbolicNode): SymbolicNode {\n\tconst polynomial = toPolynomial(node);\n\tif (polynomial === null || polynomial.terms.size === 0) return node;\n\tif (polyDegree(polynomial) > FACTOR_MAX_DEGREE) return node;\n\t// A constant has no factorization in this sense. Splitting an integer into\n\t// primes is a different feature, and without this the content-extraction\n\t// path below would hand back `12*1`.\n\tif (polynomial.vars.length === 0) return node;\n\n\tconst content = contentOf(polynomial);\n\tconst primitive = isRationalOne(content)\n\t\t? polynomial\n\t\t: scaleTerms(polynomial, rationalDiv(RATIONAL_ONE, content));\n\n\tconst { monomial, reduced } = extractCommonMonomial(primitive);\n\tconst monomialFactor = monomialNode(monomial);\n\n\tconst variable = polyUnivariateVar(reduced);\n\tif (variable === null) {\n\t\t// Constant remainder, or genuinely multivariate. The pattern set in\n\t\t// `MultivariateFactor.ts` covers the shapes a person actually writes;\n\t\t// anything it declines stops at the content and common monomial.\n\t\tconst patterned = factorMultivariate(reduced);\n\t\tif (patterned !== null) return assemble(content, monomialFactor, patterned);\n\t\tconst pieces = buildPieces(content, monomialFactor, reduced);\n\t\treturn pieces ?? node;\n\t}\n\n\tconst descending = [...polyCoefficients(reduced, variable)].reverse();\n\tconst factorization = factorUnivariate(descending, variable);\n\tconst combinedContent = rationalMul(content, factorization.content);\n\n\t// Nothing was achieved only when the result is a single factor raised to the\n\t// first power, which is the input rewritten. A single factor with a power\n\t// above one is a genuine factorization, `(x-1)^2` being the case that makes\n\t// the distinction matter.\n\tconst isUnchanged =\n\t\tfactorization.factors.length <= 1 &&\n\t\t(factorization.factors[0]?.power ?? 1) === 1 &&\n\t\tmonomialFactor === null &&\n\t\tisRationalOne(combinedContent);\n\tif (isUnchanged) return node;\n\n\tconst pieces: SymbolicNode[] = [];\n\tif (!isRationalOne(combinedContent)) pieces.push(constNode(combinedContent));\n\tif (monomialFactor !== null) pieces.push(monomialFactor);\n\tpieces.push(factorizationToNode({ content: RATIONAL_ONE, factors: factorization.factors }));\n\n\tlet result = pieces[0];\n\tfor (let i = 1; i < pieces.length; i++) result = { kind: \"mul\", left: result, right: pieces[i] };\n\treturn result;\n}\n\n/** Multiplies every coefficient of a polynomial by a rational, used to divide out the content. */\nfunction scaleTerms(p: Polynomial, k: Rational): Polynomial {\n\tconst terms = new Map<string, Rational>();\n\tfor (const [key, coeff] of p.terms) terms.set(key, rationalMul(coeff, k));\n\treturn { terms, vars: p.vars };\n}\n\n/**\n * Multiplies an already-factored remainder back together with the content and\n * common monomial that were pulled off before it.\n *\n * @param content - The rational content, left off when it is one.\n * @param monomialFactor - The common monomial, or `null` when there was none.\n * @param factored - The factored remainder.\n * @returns The whole factorization as one expression.\n */\nfunction assemble(content: Rational, monomialFactor: SymbolicNode | null, factored: SymbolicNode): SymbolicNode {\n\tconst pieces: SymbolicNode[] = [];\n\tif (!isRationalOne(content)) pieces.push(constNode(content));\n\tif (monomialFactor !== null) pieces.push(monomialFactor);\n\tpieces.push(factored);\n\n\tlet result = pieces[0];\n\tfor (let i = 1; i < pieces.length; i++) result = { kind: \"mul\", left: result, right: pieces[i] };\n\treturn result;\n}\n\n/** Assembles the content, common monomial and remainder for the multivariate stop case, or `null` when nothing was extracted. */\nfunction buildPieces(content: Rational, monomialFactor: SymbolicNode | null, reduced: Polynomial): SymbolicNode | null {\n\tif (monomialFactor === null && isRationalOne(content)) return null;\n\tconst pieces: SymbolicNode[] = [];\n\tif (!isRationalOne(content)) pieces.push(constNode(content));\n\tif (monomialFactor !== null) pieces.push(monomialFactor);\n\tpieces.push(fromPolynomial(reduced));\n\n\tlet result = pieces[0];\n\tfor (let i = 1; i < pieces.length; i++) result = { kind: \"mul\", left: result, right: pieces[i] };\n\treturn result;\n}\n","/**\n * Exact solutions for cubics and quartics.\n *\n * These were the two degrees that fell through to numerical root finding\n * whenever no rational root could be extracted. Both have closed forms, and both\n * of those forms need complex intermediates, which is why this could not exist\n * before `Complex.ts` did.\n *\n * ## The case that forced the order of work\n *\n * A cubic with three distinct **real** roots has a positive discriminant, and\n * Cardano's formula reaches those real roots through the cube roots of a complex\n * number. There is no way around that: it is a theorem that the real roots of\n * such a cubic cannot be written using real radicals alone. That is the *casus\n * irreducibilis*, and it is the reason \"add complex numbers\" was a prerequisite\n * for \"solve cubics exactly\" rather than an unrelated feature.\n *\n * ## What comes back, and what does not\n *\n * A closed form is returned whenever one exists in radicals: the single real\n * root and the conjugate pair of a cubic with a negative discriminant, the\n * repeated roots of a cubic with a zero one, both square roots of a\n * biquadratic, and a quartic that splits into two quadratics over the\n * rationals.\n *\n * The *casus irreducibilis* comes back numerically, from the trigonometric\n * form. That is not a gap in effort. Those three roots provably have no\n * expression in real radicals, and writing them as `cos` of an `arccos` of an\n * irrational would produce something exact on paper that nothing else in the\n * system can evaluate, factor or differentiate. Reporting three accurate\n * numbers and saying they are approximate is the more honest answer.\n *\n * Everything else declines by returning `null`, which sends the caller to its\n * own numerical fallback rather than to a guess made here.\n */\n\nimport { type SymbolicNode, constNode, complexNode, symbolicKey } from \"@solve-js/symbolic/SymbolicNode\";\nimport { simplifySymbolic } from \"@solve-js/symbolic/Simplify\";\nimport {\n\ttype Rational,\n\tRATIONAL_ZERO,\n\trationalAdd,\n\trationalSub,\n\trationalMul,\n\trationalDiv,\n\trationalNeg,\n\trationalToNumber,\n\trationalCompare,\n\tisRationalZero,\n} from \"@solve-js/symbolic/Rational\";\nimport { rationalRoots } from \"@solve-js/symbolic/Factor\";\nimport { surdNode, signedSurdNode, exactRationalSqrt } from \"@solve-js/symbolic/Radicals\";\nimport { COMPLEX_I } from \"@solve-js/symbolic/Complex\";\n\n/** Roots split by how exactly they are known, so a caller can label the approximate ones as such. */\nexport interface RootSet {\n\treadonly exact: readonly SymbolicNode[];\n\treadonly approximate: readonly number[];\n}\n\n/** Small rational literals, named so the formulas below read as formulas. */\nconst TWO: Rational = { n: 2n, d: 1n };\nconst THREE: Rational = { n: 3n, d: 1n };\nconst FOUR: Rational = { n: 4n, d: 1n };\n\n/** A cubic reduced to `t^3 + pt + q` by the substitution `x = t + shift`. */\ninterface DepressedCubic {\n\treadonly p: Rational;\n\treadonly q: Rational;\n\treadonly shift: Rational;\n}\n\n/**\n * Removes the quadratic term from a cubic.\n *\n * Every cubic `ax^3+bx^2+cx+d` becomes `t^3+pt+q` under `x = t - b/3a`, and that\n * reduction is what makes a closed form possible at all.\n */\nfunction depressCubic(a: Rational, b: Rational, c: Rational, d: Rational): DepressedCubic {\n\tconst shift = rationalNeg(rationalDiv(b, rationalMul(THREE, a)));\n\t// p = (3ac - b^2) / 3a^2\n\tconst p = rationalDiv(\n\t\trationalSub(rationalMul(THREE, rationalMul(a, c)), rationalMul(b, b)),\n\t\trationalMul(THREE, rationalMul(a, a)),\n\t);\n\t// q = (2b^3 - 9abc + 27a^2 d) / 27a^3\n\tconst twoBCubed = rationalMul(TWO, rationalMul(b, rationalMul(b, b)));\n\tconst nineABC = rationalMul({ n: 9n, d: 1n }, rationalMul(a, rationalMul(b, c)));\n\tconst twentySevenAAD = rationalMul({ n: 27n, d: 1n }, rationalMul(rationalMul(a, a), d));\n\tconst q = rationalDiv(\n\t\trationalAdd(rationalSub(twoBCubed, nineABC), twentySevenAAD),\n\t\trationalMul({ n: 27n, d: 1n }, rationalMul(a, rationalMul(a, a))),\n\t);\n\treturn { p, q, shift };\n}\n\n/**\n * The roots of a cubic in closed form.\n *\n * @param a - Leading coefficient, which must be non-zero.\n * @param b - Quadratic coefficient.\n * @param c - Linear coefficient.\n * @param d - Constant coefficient.\n * @returns All three roots, exact where radicals can express them and\n * approximate in the *casus irreducibilis*. Never `null`: every cubic is\n * covered by one of the three discriminant cases.\n */\nexport function solveCubic(a: Rational, b: Rational, c: Rational, d: Rational): RootSet {\n\tconst { p, q, shift } = depressCubic(a, b, c, d);\n\n\t// discriminant = -(4p^3 + 27q^2), whose sign decides the shape of the answer.\n\tconst discriminant = rationalNeg(\n\t\trationalAdd(\n\t\t\trationalMul(FOUR, rationalMul(p, rationalMul(p, p))),\n\t\t\trationalMul({ n: 27n, d: 1n }, rationalMul(q, q)),\n\t\t),\n\t);\n\n\tif (rationalCompare(discriminant, RATIONAL_ZERO) > 0) {\n\t\treturn { exact: [], approximate: trigonometricRoots(p, q, shift) };\n\t}\n\tif (isRationalZero(discriminant)) return { exact: repeatedCubicRoots(p, q, shift), approximate: [] };\n\treturn { exact: cardanoRoots(p, q, shift), approximate: [] };\n}\n\n/**\n * The roots of a depressed cubic whose discriminant is zero.\n *\n * Both roots are rational here, which is worth stating: a cubic over the\n * rationals with a repeated root has all of its roots rational, so nothing\n * irrational can appear in this branch.\n */\nfunction repeatedCubicRoots(p: Rational, q: Rational, shift: Rational): SymbolicNode[] {\n\t// p and q both zero is a triple root at the shift itself.\n\tif (isRationalZero(p)) return [constNode(shift)];\n\n\tconst simple = rationalAdd(rationalDiv(rationalMul(THREE, q), p), shift);\n\tconst repeated = rationalAdd(rationalNeg(rationalDiv(rationalMul(THREE, q), rationalMul(TWO, p))), shift);\n\tconst ordered = [simple, repeated].sort(rationalCompare);\n\treturn ordered.map(constNode);\n}\n\n/**\n * The three roots of a depressed cubic with a negative discriminant, by\n * Cardano's formula.\n *\n * With `u` and `v` the two real cube roots below, the roots are `u+v` and\n * `u*w + v*w^2` for the two primitive cube roots of unity `w`. Multiplying that\n * out gives one real root and a conjugate pair, which is what this builds.\n *\n * Both cube roots are of real numbers here, because a negative discriminant is\n * exactly the condition that puts the radicand of the inner square root above\n * zero. That is what keeps this branch expressible in radicals while the\n * *casus irreducibilis* is not.\n */\nfunction cardanoRoots(p: Rational, q: Rational, shift: Rational): SymbolicNode[] {\n\tconst half = rationalNeg(rationalDiv(q, TWO));\n\t// (q/2)^2 + (p/3)^3, positive whenever the discriminant is negative.\n\tconst radicand = rationalAdd(\n\t\trationalMul(rationalDiv(q, TWO), rationalDiv(q, TWO)),\n\t\trationalMul(rationalDiv(p, THREE), rationalMul(rationalDiv(p, THREE), rationalDiv(p, THREE))),\n\t);\n\tconst inner = surdNode(radicand);\n\n\t// Emitted as `cbrt` calls so the simplifier folds them when the radicand is\n\t// a perfect square and the result a perfect cube, which is how `x^3 = 8`\n\t// still comes back as a plain `2`.\n\tconst u: SymbolicNode = { kind: \"call\", name: \"cbrt\", args: [{ kind: \"add\", left: constNode(half), right: inner }] };\n\tconst v: SymbolicNode = { kind: \"call\", name: \"cbrt\", args: [{ kind: \"sub\", left: constNode(half), right: inner }] };\n\n\tconst sum: SymbolicNode = { kind: \"add\", left: u, right: v };\n\tconst difference: SymbolicNode = { kind: \"sub\", left: u, right: v };\n\tconst real: SymbolicNode = { kind: \"add\", left: constNode(shift), right: { kind: \"div\", left: { kind: \"neg\", operand: sum }, right: constNode(TWO) } };\n\t// (u-v) * sqrt(3)/2 * i\n\tconst imaginary: SymbolicNode = {\n\t\tkind: \"mul\",\n\t\tleft: { kind: \"div\", left: { kind: \"mul\", left: difference, right: surdNode(THREE) }, right: constNode(TWO) },\n\t\tright: complexNode(COMPLEX_I),\n\t};\n\n\treturn [\n\t\t{ kind: \"add\", left: constNode(shift), right: sum },\n\t\t{ kind: \"sub\", left: real, right: imaginary },\n\t\t{ kind: \"add\", left: real, right: imaginary },\n\t];\n}\n\n/**\n * The three real roots of a depressed cubic in the *casus irreducibilis*, by the\n * trigonometric form.\n *\n * These are returned as numbers on purpose. See this module's header: no\n * expression in real radicals exists for them, and the trigonometric expression\n * that does exist is not something the rest of the system could evaluate\n * exactly anyway.\n */\nfunction trigonometricRoots(p: Rational, q: Rational, shift: Rational): number[] {\n\tconst pNumber = rationalToNumber(p);\n\tconst qNumber = rationalToNumber(q);\n\tconst shiftNumber = rationalToNumber(shift);\n\n\t// t_k = 2 sqrt(-p/3) cos( arccos( (3q)/(2p) sqrt(-3/p) )/3 - 2*pi*k/3 )\n\tconst magnitude = 2 * Math.sqrt(-pNumber / 3);\n\tconst ratio = ((3 * qNumber) / (2 * pNumber)) * Math.sqrt(-3 / pNumber);\n\t// Clamped against the rounding that can push the value a hair outside\n\t// arccos's domain, which would turn a genuine root into a NaN.\n\tconst angle = Math.acos(Math.min(1, Math.max(-1, ratio))) / 3;\n\n\treturn [0, 1, 2]\n\t\t.map(k => magnitude * Math.cos(angle - (2 * Math.PI * k) / 3) + shiftNumber)\n\t\t.sort((left, right) => left - right);\n}\n\n/** A quartic reduced to `t^4 + pt^2 + qt + r` by the substitution `x = t + shift`. */\ninterface DepressedQuartic {\n\treadonly p: Rational;\n\treadonly q: Rational;\n\treadonly r: Rational;\n\treadonly shift: Rational;\n}\n\n/** Removes the cubic term from a monic quartic `x^4 + bx^3 + cx^2 + dx + e`. */\nfunction depressQuartic(b: Rational, c: Rational, d: Rational, e: Rational): DepressedQuartic {\n\tconst shift = rationalNeg(rationalDiv(b, FOUR));\n\tconst bb = rationalMul(b, b);\n\t// p = c - 3b^2/8\n\tconst p = rationalSub(c, rationalDiv(rationalMul(THREE, bb), { n: 8n, d: 1n }));\n\t// q = d - bc/2 + b^3/8\n\tconst q = rationalAdd(\n\t\trationalSub(d, rationalDiv(rationalMul(b, c), TWO)),\n\t\trationalDiv(rationalMul(bb, b), { n: 8n, d: 1n }),\n\t);\n\t// r = e - bd/4 + b^2 c/16 - 3b^4/256\n\tconst r = rationalSub(\n\t\trationalAdd(\n\t\t\trationalSub(e, rationalDiv(rationalMul(b, d), FOUR)),\n\t\t\trationalDiv(rationalMul(bb, c), { n: 16n, d: 1n }),\n\t\t),\n\t\trationalDiv(rationalMul(THREE, rationalMul(bb, bb)), { n: 256n, d: 1n }),\n\t);\n\treturn { p, q, r, shift };\n}\n\n/**\n * The roots of a quartic in closed form, where one exists.\n *\n * Two families are covered. A **biquadratic**, which has no odd-power term once\n * depressed, is a quadratic in `t^2` and its roots are square roots of the two\n * solutions of that quadratic. A general quartic is covered when its resolvent\n * cubic has a rational root that splits it into two quadratics over the\n * rationals, which are then solved exactly, complex roots included.\n *\n * Every other quartic returns `null`. Ferrari's method does produce a closed\n * form for those, but it is a radical nested four deep whose printed form\n * nobody can read and nothing downstream can use, so the caller's numerical\n * fallback is the better answer.\n *\n * @param a - Leading coefficient, which must be non-zero.\n * @param b - Cubic coefficient.\n * @param c - Quadratic coefficient.\n * @param d - Linear coefficient.\n * @param e - Constant coefficient.\n * @param solveQuadratic - The quadratic solver to use for each half of a split.\n * Passed in rather than imported so this module stays independent of `Solve.ts`.\n * @returns The roots, or `null` when no readable closed form exists.\n */\nexport function solveQuartic(\n\ta: Rational,\n\tb: Rational,\n\tc: Rational,\n\td: Rational,\n\te: Rational,\n\tsolveQuadratic: (a: Rational, b: Rational, c: Rational) => readonly SymbolicNode[],\n): RootSet | null {\n\tconst monic = (value: Rational): Rational => rationalDiv(value, a);\n\tconst { p, q, r, shift } = depressQuartic(monic(b), monic(c), monic(d), monic(e));\n\n\tconst roots = isRationalZero(q) ? biquadraticRoots(p, r) : splitQuarticRoots(p, q, r, solveQuadratic);\n\tif (roots === null) return null;\n\n\t// Undo the depression. A zero shift is left off rather than added as `+0`,\n\t// which the simplifier would drop anyway but which reads better in a trace.\n\tconst shifted: SymbolicNode[] = isRationalZero(shift)\n\t\t? roots\n\t\t: roots.map(root => ({ kind: \"add\", left: constNode(shift), right: root }));\n\treturn { exact: distinct(shifted), approximate: [] };\n}\n\n/**\n * Drops repeated roots.\n *\n * A quartic that splits into two quadratics sharing a factor produces the same\n * root from both halves, and a repeated root is one solution rather than\n * several. Comparison is on the simplified structural key, so two roots written\n * differently but equal in structure count once.\n */\nfunction distinct(roots: readonly SymbolicNode[]): SymbolicNode[] {\n\tconst seen = new Set<string>();\n\tconst unique: SymbolicNode[] = [];\n\tfor (const root of roots) {\n\t\tconst key = symbolicKey(simplifySymbolic(root));\n\t\tif (seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tunique.push(root);\n\t}\n\treturn unique;\n}\n\n/**\n * The four roots of `t^4 + pt^2 + r`, as the square roots of the two solutions\n * of `y^2 + py + r`.\n *\n * The sign of each `y` decides whether its square roots are real or imaginary,\n * and that sign is determined exactly rather than by evaluating the surd: `y`\n * is `(-p ± sqrt(D))/2`, so the comparison reduces to the signs of `p` and `r`\n * alone. Deciding it numerically would be one rounding error away from claiming\n * a real root where there is a complex one.\n */\nfunction biquadraticRoots(p: Rational, r: Rational): SymbolicNode[] {\n\tconst discriminant = rationalSub(rationalMul(p, p), rationalMul(FOUR, r));\n\tif (rationalCompare(discriminant, RATIONAL_ZERO) < 0) return complexBiquadraticRoots(p, r);\n\n\tconst root = exactRationalSqrt(discriminant);\n\tif (root !== null) return rationalSquareRoots(rationalNeg(p), root, isRationalZero(discriminant));\n\treturn nestedSquareRoots(p, r, discriminant);\n}\n\n/** The four roots when both solutions of the inner quadratic are rational, so each square root is an ordinary surd. */\nfunction rationalSquareRoots(negatedP: Rational, root: Rational, repeated: boolean): SymbolicNode[] {\n\tconst values = repeated\n\t\t// A zero discriminant makes the two solutions the same one, and emitting it\n\t\t// twice would report `x^4-4x^2+4=0` as having four roots rather than two.\n\t\t? [rationalDiv(negatedP, TWO)]\n\t\t: [rationalDiv(rationalAdd(negatedP, root), TWO), rationalDiv(rationalSub(negatedP, root), TWO)];\n\n\tconst roots: SymbolicNode[] = [];\n\tfor (const value of values) {\n\t\tif (isRationalZero(value)) {\n\t\t\troots.push(constNode(RATIONAL_ZERO));\n\t\t\tcontinue;\n\t\t}\n\t\tconst square = signedSurdNode(value);\n\t\troots.push({ kind: \"neg\", operand: square }, square);\n\t}\n\treturn roots;\n}\n\n/**\n * The four roots when the inner quadratic is itself irrational, so each root is\n * a square root of a surd.\n *\n * `x^4-3x^2+1=0` comes out as `±sqrt((3+sqrt(5))/2)` and `±sqrt((3-sqrt(5))/2)`.\n * Nested, but exact and still readable, which is better than four decimals.\n *\n * Whether each solution is positive decides whether its square roots are real\n * or imaginary, and that is settled exactly rather than by evaluating the surd:\n * with `y = (-p ± sqrt(D))/2` the comparison reduces to the signs of `p` and\n * `r` alone. Deciding it numerically would be one rounding error away from\n * claiming a real root where there is a complex one.\n */\nfunction nestedSquareRoots(p: Rational, r: Rational, discriminant: Rational): SymbolicNode[] {\n\tconst negatedP = constNode(rationalNeg(p));\n\tconst surd = surdNode(discriminant);\n\tconst negativeP = rationalCompare(p, RATIONAL_ZERO) <= 0;\n\tconst solutions = [\n\t\t{ node: halved({ kind: \"add\", left: negatedP, right: surd }), positive: negativeP || rationalCompare(r, RATIONAL_ZERO) <= 0 },\n\t\t{ node: halved({ kind: \"sub\", left: negatedP, right: surd }), positive: negativeP && rationalCompare(r, RATIONAL_ZERO) >= 0 },\n\t];\n\n\tconst roots: SymbolicNode[] = [];\n\tfor (const { node, positive } of solutions) {\n\t\tconst radicand = positive ? node : { kind: \"neg\" as const, operand: node };\n\t\tconst magnitude: SymbolicNode = { kind: \"call\", name: \"sqrt\", args: [radicand] };\n\t\tconst square: SymbolicNode = positive ? magnitude : { kind: \"mul\", left: magnitude, right: complexNode(COMPLEX_I) };\n\t\troots.push({ kind: \"neg\", operand: square }, square);\n\t}\n\treturn roots;\n}\n\n/** Halves an expression, which the biquadratic formula needs twice. */\nfunction halved(node: SymbolicNode): SymbolicNode {\n\treturn { kind: \"div\", left: node, right: constNode(TWO) };\n}\n\n/**\n * The four roots of a biquadratic whose inner quadratic has no real solution.\n *\n * `y` is then `-p/2 ± i*sqrt(|D|)/2`, whose modulus is `sqrt(r)`, and\n * `sqrt(a+bi)` has real part `sqrt((|y|+a)/2)` and imaginary part\n * `sqrt((|y|-a)/2)`. Both of those radicands are non-negative here rather than\n * needing to be checked: `|y|` is `sqrt(r)` and `a` is `-p/2`, and a negative\n * discriminant is exactly the statement that `p^2 < 4r`, so `|y| > |a|`.\n *\n * When `sqrt(r)` is itself rational every component is a square root of a\n * rational and all four roots come out as ordinary surds. `x^4+1=0` is the case\n * worth having: its roots are `±sqrt(2)/2 ± sqrt(2)/2 i`, which no real-only\n * solver can report at all.\n *\n * When `sqrt(r)` is irrational the components nest one level, exactly as\n * {@link nestedSquareRoots} does for the real case. This used to decline\n * instead, which is how `x^4-2x^2+3=0` came to answer \"no real solutions\" while\n * its siblings `x^4+1`, `x^4+4` and `x^4-x^2+1` all returned four complex\n * roots. Same family, same shape of answer, and the difference was only whether\n * a `3` happened to be a perfect square.\n */\nfunction complexBiquadraticRoots(p: Rational, r: Rational): SymbolicNode[] {\n\tconst centre = rationalDiv(rationalNeg(p), TWO);\n\tconst modulus = exactRationalSqrt(r);\n\n\tconst re = modulus === null\n\t\t? nestedSurd(surdNode(r), centre)\n\t\t: surdNode(rationalDiv(rationalAdd(modulus, centre), TWO));\n\tconst imaginaryMagnitude = modulus === null\n\t\t? nestedSurd(surdNode(r), rationalNeg(centre))\n\t\t: surdNode(rationalDiv(rationalSub(modulus, centre), TWO));\n\n\tconst im: SymbolicNode = { kind: \"mul\", left: imaginaryMagnitude, right: complexNode(COMPLEX_I) };\n\tconst first: SymbolicNode = { kind: \"add\", left: re, right: im };\n\tconst second: SymbolicNode = { kind: \"sub\", left: re, right: im };\n\treturn [\n\t\t{ kind: \"neg\", operand: first },\n\t\t{ kind: \"neg\", operand: second },\n\t\tsecond,\n\t\tfirst,\n\t];\n}\n\n/**\n * `sqrt((surd + offset)/2)`, written so the offset's sign reads naturally.\n *\n * A negative offset becomes a subtraction rather than the addition of a\n * negative, so the radicand prints as `(sqrt(3)-1)/2` rather than\n * `(sqrt(3)+-1)/2`.\n */\nfunction nestedSurd(surd: SymbolicNode, offset: Rational): SymbolicNode {\n\tconst shifted: SymbolicNode = offset.n >= 0n\n\t\t? { kind: \"add\", left: surd, right: constNode(offset) }\n\t\t: { kind: \"sub\", left: surd, right: constNode(rationalNeg(offset)) };\n\treturn { kind: \"call\", name: \"sqrt\", args: [halved(shifted)] };\n}\n\n/**\n * The roots of a general depressed quartic, when its resolvent cubic splits it\n * into two quadratics over the rationals.\n *\n * `t^4+pt^2+qt+r` factors as `(t^2+at+B)(t^2-at+C)` exactly when `a^2` is a root\n * of the resolvent `z^3 + 2pz^2 + (p^2-4r)z - q^2`. A rational `z` whose square\n * root is also rational gives a factorization over the rationals, and each half\n * is then an ordinary quadratic with exact roots.\n *\n * @returns The four roots, or `null` when no such split exists.\n */\nfunction splitQuarticRoots(\n\tp: Rational,\n\tq: Rational,\n\tr: Rational,\n\tsolveQuadratic: (a: Rational, b: Rational, c: Rational) => readonly SymbolicNode[],\n): SymbolicNode[] | null {\n\tconst resolvent: Rational[] = [\n\t\t{ n: 1n, d: 1n },\n\t\trationalMul(TWO, p),\n\t\trationalSub(rationalMul(p, p), rationalMul(FOUR, r)),\n\t\trationalNeg(rationalMul(q, q)),\n\t];\n\n\tfor (const z of rationalRoots(resolvent)) {\n\t\tif (rationalCompare(z, RATIONAL_ZERO) <= 0) continue;\n\t\tconst alpha = exactRationalSqrt(z);\n\t\tif (alpha === null) continue;\n\n\t\t// beta + gamma = p + alpha^2 and gamma - beta = q/alpha.\n\t\tconst sum = rationalAdd(p, z);\n\t\tconst difference = rationalDiv(q, alpha);\n\t\tconst beta = rationalDiv(rationalSub(sum, difference), TWO);\n\t\tconst gamma = rationalDiv(rationalAdd(sum, difference), TWO);\n\n\t\tconst one: Rational = { n: 1n, d: 1n };\n\t\treturn [\n\t\t\t...solveQuadratic(one, alpha, beta),\n\t\t\t...solveQuadratic(one, rationalNeg(alpha), gamma),\n\t\t];\n\t}\n\treturn null;\n}\n","/**\n * Every root of a polynomial at once, found numerically in the complex plane.\n *\n * ## Why not sequential deflation\n *\n * The obvious way to find several roots is to find one, divide the polynomial\n * by `(x - root)`, and solve what is left. Each division carries the first\n * root's error into every coefficient of the quotient, so the second root is\n * found from a polynomial that is no longer quite the one that was asked\n * about, and the error compounds down the chain. That is not a theoretical\n * objection. Solving `x^5-x=0` that way answered with `-1` twice, once as `-1`\n * and once as `-1.0000000000004656`, and dropped both complex roots on the way,\n * because a real-only scan for sign changes cannot see them at all.\n *\n * Durand-Kerner (also called the Weierstrass method) moves every estimate at\n * once instead. Each one steps by `p(z_i)` over the product of its distances\n * from the others, which is Newton's method applied to the whole factorization\n * rather than to one factor of it. No coefficient is ever recomputed, so\n * nothing accumulates, and the arithmetic is complex from the first step, so a\n * conjugate pair is found rather than missed.\n *\n * ## Why the input is made square-free first\n *\n * A repeated root is where every simultaneous method loses precision. A double\n * root is only ever located to about the square root of machine epsilon, and\n * the two estimates converging on it arrive straddling the true value rather\n * than on top of it. The usual repair is to cluster the output and read a\n * multiplicity off the cluster size, which is a numerical answer to something\n * the exact arithmetic upstream can remove outright: `gcd(p, p')` is precisely\n * the repeated part, so `p` divided by it has the same roots with every one of\n * them simple. That division happens over the rationals, so what reaches the\n * iteration is a polynomial whose roots are as well separated as they can be.\n *\n * Near-equal output is still merged, but as a check that the iteration\n * separated what it was handed rather than as the mechanism for multiplicity.\n * Two estimates landing on the same value now means the run failed, and\n * {@link approximateRoots} says so by returning `null` instead of quietly\n * reporting one root fewer than the polynomial has.\n */\n\nimport { type Rational, rationalToNumber } from \"@solve-js/symbolic/Rational\";\nimport { squareFreePart } from \"@solve-js/symbolic/Gcd\";\n\n/**\n * One numerically-found root.\n *\n * Complex because the roots of a real polynomial are, and reporting only the\n * real ones is how `x^5-1=0` came to answer with `1` and nothing else.\n */\nexport interface ApproximateRoot {\n\t/** Real part. */\n\treadonly re: number;\n\t/**\n\t * Imaginary part.\n\t *\n\t * Exactly zero for a root on the real line rather than the rounding\n\t * residue an iteration in complex arithmetic leaves behind, so a caller can\n\t * test it without choosing a tolerance of its own.\n\t */\n\treadonly im: number;\n}\n\n/**\n * Iteration ceiling for {@link approximateRoots}.\n *\n * Durand-Kerner converges quadratically once the estimates separate, so a run\n * that has not settled within this many passes is diverging rather than being\n * slow, and continuing would only spend time before failing anyway.\n */\nexport const DURAND_KERNER_MAX_ITERATIONS = 200;\n\n/**\n * Relative step size below which the iteration is considered settled.\n *\n * Scaled by the largest estimate, so it means the same thing for roots near\n * zero and roots in the hundreds.\n */\nexport const DURAND_KERNER_TOLERANCE = 1e-14;\n\n/**\n * How large a residual a root may leave and still be accepted, relative to the\n * magnitude Horner's method accumulated on the way to it.\n *\n * This is a backward-error test: it asks whether the value is a root of a\n * polynomial within rounding distance of the one given, which is the strongest\n * statement double precision can support. An absolute threshold cannot do the\n * job, since `p(z)` for a degree-eight polynomial with coefficients in the\n * thousands is numerically large even at a perfect root.\n */\nexport const ROOT_RESIDUAL_TOLERANCE = 1e-10;\n\n/**\n * How close two estimates may come before they are treated as the same root.\n *\n * The polynomial handed to the iteration is square-free, so all of its roots\n * are simple and a converged pair should be separated by their true distance.\n * Two estimates this close have collapsed onto one root, leaving another\n * undiscovered, which is reported rather than hidden.\n */\nexport const ROOT_SEPARATION_TOLERANCE = 1e-10;\n\n/**\n * How small a component must be, relative to the root's magnitude, to be\n * rounding residue rather than part of the answer.\n *\n * A simple root of a real polynomial is either on an axis or a bounded distance\n * from it, so there is no middle ground to get wrong here. The candidate is\n * confirmed by residual before the component is dropped, so this only decides\n * what is worth trying.\n */\nconst AXIS_SNAP_TOLERANCE = 1e-9;\n\n/**\n * How far two estimates may be from being each other's conjugate and still be\n * averaged into an exact pair.\n *\n * Generous, because for a polynomial with real coefficients the root set is\n * closed under conjugation as a matter of algebra: every non-real root has an\n * exact partner in the set, and the iteration finds it to within its own\n * convergence. This only guards against pairing a root that has no partner.\n */\nconst CONJUGATE_PAIR_TOLERANCE = 1e-8;\n\n/** How many Newton steps re-converge a root after a component is dropped. */\nconst NEWTON_POLISH_STEPS = 4;\n\n/** A complex number as two doubles, the working type of the iteration. */\ninterface Cpx {\n\treadonly re: number;\n\treadonly im: number;\n}\n\n/** `a - b`. */\nfunction subtract(a: Cpx, b: Cpx): Cpx {\n\treturn { re: a.re - b.re, im: a.im - b.im };\n}\n\n/** `a * b`. */\nfunction multiply(a: Cpx, b: Cpx): Cpx {\n\treturn { re: a.re * b.re - a.im * b.im, im: a.re * b.im + a.im * b.re };\n}\n\n/**\n * `a / b`, by Smith's method.\n *\n * Dividing through by the larger component rather than by `|b|^2` keeps the\n * intermediate from overflowing when both components are large, which the\n * naive form does for magnitudes past about 1e154. The iteration divides by a\n * product of up to seven differences, so that is reachable rather than\n * hypothetical.\n */\nfunction divide(a: Cpx, b: Cpx): Cpx {\n\tif (Math.abs(b.re) >= Math.abs(b.im)) {\n\t\tconst ratio = b.im / b.re;\n\t\tconst denominator = b.re + b.im * ratio;\n\t\treturn { re: (a.re + a.im * ratio) / denominator, im: (a.im - a.re * ratio) / denominator };\n\t}\n\tconst ratio = b.re / b.im;\n\tconst denominator = b.re * ratio + b.im;\n\treturn { re: (a.re * ratio + a.im) / denominator, im: (a.im * ratio - a.re) / denominator };\n}\n\n/** `|z|`. */\nfunction magnitude(z: Cpx): number {\n\treturn Math.hypot(z.re, z.im);\n}\n\n/** Evaluates real descending coefficients at a complex point, by Horner's method. */\nfunction evaluateAt(descending: readonly number[], z: Cpx): Cpx {\n\tlet re = 0;\n\tlet im = 0;\n\tfor (const coefficient of descending) {\n\t\tconst nextRe = re * z.re - im * z.im + coefficient;\n\t\tim = re * z.im + im * z.re;\n\t\tre = nextRe;\n\t}\n\treturn { re, im };\n}\n\n/**\n * The magnitude Horner's method accumulates on the way to `p(z)`.\n *\n * This is the scale a residual has to be judged against: it is what `|p(z)|`\n * would be if every rounding error in the evaluation happened to add rather\n * than cancel, so a residual below it says the value is a root as far as double\n * precision can distinguish.\n */\nfunction evaluationScale(descending: readonly number[], z: Cpx): number {\n\tconst radius = magnitude(z);\n\tlet total = 0;\n\tfor (const coefficient of descending) total = total * radius + Math.abs(coefficient);\n\treturn total;\n}\n\n/** Descending coefficients of the derivative. */\nfunction differentiate(descending: readonly number[]): number[] {\n\tconst degree = descending.length - 1;\n\tconst derivative: number[] = [];\n\tfor (let i = 0; i < degree; i++) derivative.push(descending[i] * (degree - i));\n\treturn derivative;\n}\n\n/**\n * The square-free part of a polynomial, as monic descending doubles.\n *\n * @param descending - Descending exact coefficients.\n * @returns The coefficients, or `null` when one of them has no finite double\n * value, which would make every comparison below meaningless.\n */\nfunction squareFreeDoubles(descending: readonly Rational[]): number[] | null {\n\t// `Gcd.ts` works in ascending order and returns a monic result, which is\n\t// what the iteration wants anyway.\n\tconst ascending = [...descending].reverse();\n\tconst squareFree = [...squareFreePart(ascending)].reverse();\n\n\tconst doubles = squareFree.map(rationalToNumber);\n\tif (doubles.some(value => !Number.isFinite(value))) return null;\n\treturn doubles;\n}\n\n/**\n * Starting estimates spread around the circle the roots must lie inside.\n *\n * Two details are load-bearing. The circle is centred on `-a1/n`, the mean of\n * the roots, rather than on the origin, so the estimates start near their\n * targets for a polynomial whose roots are all off to one side. And every angle\n * is offset by half a step, which keeps all `n` of them off the real axis: a\n * real estimate of a real polynomial stays real forever, since every quantity\n * in its update is real, so a conjugate pair started on the axis would have no\n * way to leave it.\n */\nfunction initialEstimates(monic: readonly number[]): Cpx[] {\n\tconst degree = monic.length - 1;\n\n\t// Cauchy's bound: every root of a monic polynomial lies within 1 + max|a_k|.\n\tlet largest = 0;\n\tfor (let i = 1; i < monic.length; i++) largest = Math.max(largest, Math.abs(monic[i]));\n\tconst radius = 1 + largest;\n\tconst centre = -monic[1] / degree;\n\n\tconst estimates: Cpx[] = [];\n\tfor (let k = 0; k < degree; k++) {\n\t\tconst angle = (2 * Math.PI * k) / degree + Math.PI / (2 * degree);\n\t\testimates.push({ re: centre + radius * Math.cos(angle), im: radius * Math.sin(angle) });\n\t}\n\treturn estimates;\n}\n\n/**\n * Runs the Durand-Kerner iteration to convergence.\n *\n * Estimates are updated in place as the sweep goes, so each one sees the\n * already-improved values of those before it. That is the Gauss-Seidel form of\n * the method and it converges in noticeably fewer sweeps than recomputing every\n * estimate from the previous round.\n *\n * @param monic - Monic descending coefficients of a square-free polynomial.\n * @returns The estimates, or `null` when the iteration did not settle.\n */\nfunction durandKerner(monic: readonly number[]): Cpx[] | null {\n\tconst degree = monic.length - 1;\n\tconst estimates = initialEstimates(monic);\n\n\tfor (let iteration = 0; iteration < DURAND_KERNER_MAX_ITERATIONS; iteration++) {\n\t\tlet largestStep = 0;\n\t\tlet largestRoot = 1;\n\n\t\tfor (let i = 0; i < degree; i++) {\n\t\t\tlet denominator: Cpx = { re: 1, im: 0 };\n\t\t\tfor (let j = 0; j < degree; j++) {\n\t\t\t\tif (i !== j) denominator = multiply(denominator, subtract(estimates[i], estimates[j]));\n\t\t\t}\n\n\t\t\t// Two estimates have landed on each other. Nudging one apart lets the\n\t\t\t// sweep continue, where dividing by zero would poison every later\n\t\t\t// value with NaN and lose the roots that had already converged.\n\t\t\tif (denominator.re === 0 && denominator.im === 0) {\n\t\t\t\testimates[i] = { re: estimates[i].re + 1e-6 * (i + 1), im: estimates[i].im + 1e-6 };\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst step = divide(evaluateAt(monic, estimates[i]), denominator);\n\t\t\tif (!Number.isFinite(step.re) || !Number.isFinite(step.im)) return null;\n\n\t\t\testimates[i] = subtract(estimates[i], step);\n\t\t\tlargestStep = Math.max(largestStep, magnitude(step));\n\t\t\tlargestRoot = Math.max(largestRoot, magnitude(estimates[i]));\n\t\t}\n\n\t\tif (largestStep <= DURAND_KERNER_TOLERANCE * largestRoot) return estimates;\n\t}\n\treturn null;\n}\n\n/** Re-converges a value with Newton's method, used after a component is dropped. */\nfunction polish(monic: readonly number[], derivative: readonly number[], start: Cpx): Cpx {\n\tlet candidate = start;\n\tfor (let step = 0; step < NEWTON_POLISH_STEPS; step++) {\n\t\tconst slope = evaluateAt(derivative, candidate);\n\t\tif (slope.re === 0 && slope.im === 0) break;\n\t\tconst next = subtract(candidate, divide(evaluateAt(monic, candidate), slope));\n\t\tif (!Number.isFinite(next.re) || !Number.isFinite(next.im)) break;\n\t\tcandidate = next;\n\t}\n\treturn candidate;\n}\n\n/**\n * Drops a component that is rounding residue rather than part of the answer,\n * re-converging the value onto the axis.\n *\n * Two doubles either side of the same true root are equally correct as far as\n * arithmetic goes, so this is choosing between them on how they read: `i`\n * rather than `-0.0000000000000000122+i`, and `-0.7548776662` rather than the\n * same number with a stray imaginary trace on it. What makes that safe rather\n * than cosmetic is the residual test: the snapped value is kept only when it\n * still satisfies the polynomial to within {@link ROOT_RESIDUAL_TOLERANCE}, so\n * a root with a genuinely small component is never flattened onto an axis.\n *\n * @param monic - Monic descending coefficients.\n * @param derivative - Their derivative, so it is differentiated once per call rather than once per root.\n * @param z - The converged estimate.\n * @returns The estimate, with a negligible component replaced by an exact zero\n * where the polynomial allows it.\n */\nfunction snapToAxes(monic: readonly number[], derivative: readonly number[], z: Cpx): Cpx {\n\tconst scale = Math.max(1, magnitude(z));\n\n\tif (z.im !== 0 && Math.abs(z.im) <= AXIS_SNAP_TOLERANCE * scale) {\n\t\t// Every quantity is real from here, so Newton's method on a real starting\n\t\t// point stays on the real line by construction.\n\t\tconst candidate = polish(monic, derivative, { re: z.re, im: 0 });\n\t\tif (isRootWithinTolerance(monic, candidate)) return { re: candidate.re, im: 0 };\n\t}\n\tif (z.re !== 0 && Math.abs(z.re) <= AXIS_SNAP_TOLERANCE * scale) {\n\t\tconst candidate = polish(monic, derivative, { re: 0, im: z.im });\n\t\tif (isRootWithinTolerance(monic, candidate)) return { re: 0, im: candidate.im };\n\t}\n\treturn z;\n}\n\n/** Whether a value satisfies the polynomial to within the backward error double precision allows. */\nfunction isRootWithinTolerance(monic: readonly number[], z: Cpx): boolean {\n\tif (!Number.isFinite(z.re) || !Number.isFinite(z.im)) return false;\n\treturn magnitude(evaluateAt(monic, z)) <= ROOT_RESIDUAL_TOLERANCE * evaluationScale(monic, z);\n}\n\n/**\n * Replaces each conjugate pair with an exactly-conjugate one.\n *\n * A polynomial with real coefficients has a root set closed under conjugation,\n * so the two estimates of a pair are two independent measurements of one\n * quantity and averaging them is strictly the better estimate of both. It also\n * removes an artefact worth removing on its own: without this the two halves of\n * a pair differ in their last bit, which is enough to order them by real part\n * and print `-0.7071067812+0.7071067812i` above its own conjugate rather than\n * below it.\n *\n * A root with no partner within {@link CONJUGATE_PAIR_TOLERANCE} is left as it\n * is, which is what keeps a real root, whose own conjugate is itself and so\n * lies nowhere near any other estimate, from being dragged into a pair it does\n * not belong to.\n */\nfunction pairConjugates(roots: readonly Cpx[]): Cpx[] {\n\tconst result = [...roots];\n\tconst paired = result.map(root => root.im === 0);\n\n\tfor (let i = 0; i < result.length; i++) {\n\t\tif (paired[i]) continue;\n\t\tconst wanted: Cpx = { re: result[i].re, im: -result[i].im };\n\n\t\tlet partner = -1;\n\t\tlet closest = Number.POSITIVE_INFINITY;\n\t\tfor (let j = i + 1; j < result.length; j++) {\n\t\t\tif (paired[j]) continue;\n\t\t\tconst distance = magnitude(subtract(result[j], wanted));\n\t\t\tif (distance < closest) {\n\t\t\t\tclosest = distance;\n\t\t\t\tpartner = j;\n\t\t\t}\n\t\t}\n\t\tif (partner === -1 || closest > CONJUGATE_PAIR_TOLERANCE * Math.max(1, magnitude(result[i]))) continue;\n\n\t\tconst re = (result[i].re + result[partner].re) / 2;\n\t\tconst im = (Math.abs(result[i].im) + Math.abs(result[partner].im)) / 2;\n\t\tconst sign = result[i].im < 0 ? -1 : 1;\n\t\tresult[i] = { re, im: sign * im };\n\t\tresult[partner] = { re, im: -sign * im };\n\t\tpaired[i] = true;\n\t\tpaired[partner] = true;\n\t}\n\treturn result;\n}\n\n/**\n * Whether every estimate is far enough from every other to be a distinct root.\n *\n * See {@link ROOT_SEPARATION_TOLERANCE} for why a collision is a failure here\n * rather than a multiplicity.\n */\nfunction allSeparated(roots: readonly Cpx[]): boolean {\n\tfor (let i = 0; i < roots.length; i++) {\n\t\tfor (let j = i + 1; j < roots.length; j++) {\n\t\t\tconst scale = Math.max(1, magnitude(roots[i]), magnitude(roots[j]));\n\t\t\tif (magnitude(subtract(roots[i], roots[j])) <= ROOT_SEPARATION_TOLERANCE * scale) return false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/**\n * Every root of a polynomial, found numerically.\n *\n * Roots are returned in ascending order of real part, then imaginary part, so\n * two runs on the same input read identically and a conjugate pair reads\n * negative-first like every other pair the solver produces.\n *\n * @param descending - Descending exact coefficients, the leading one non-zero.\n * @returns One entry per **distinct** root, matching the solver's convention\n * that a repeated root is one solution rather than several. `null` when the\n * iteration did not converge, did not separate its estimates, or left a root\n * with too large a residual, so that a caller reports the shortfall rather than\n * presenting a partial list as a complete one.\n */\nexport function approximateRoots(descending: readonly Rational[]): ApproximateRoot[] | null {\n\tconst monic = squareFreeDoubles(descending);\n\tif (monic === null) return null;\n\tif (monic.length < 2) return [];\n\n\tconst converged = durandKerner(monic);\n\tif (converged === null) return null;\n\n\t// Pairing first, then snapping: the two halves of a pair come out of pairing\n\t// with the same real part and opposite imaginary ones, so any snap applies to\n\t// both alike and the pair stays exactly conjugate.\n\tconst derivative = differentiate(monic);\n\tconst roots = pairConjugates(converged).map(root => snapToAxes(monic, derivative, root));\n\n\tfor (const root of roots) {\n\t\tif (!isRootWithinTolerance(monic, root)) return null;\n\t}\n\tif (!allSeparated(roots)) return null;\n\n\treturn [...roots].sort((a, b) => a.re - b.re || a.im - b.im);\n}\n","/**\n * Solving a polynomial equation for one variable.\n *\n * ## The order of attack, and why it is this order\n *\n * Exact answers first, approximation only as a last resort and always labelled\n * as such.\n *\n * 1. `x` itself, as many times as it divides the polynomial. This step exists\n * because the rational-root theorem is stated for a **non-zero** constant\n * term, so without it `x^5-x=0` found no rational roots at all and fell\n * straight through to numerics, despite every one of its five roots being\n * exact. Dividing `x` out first is what turns that equation back into\n * `x^4-1`, whose roots are `±1` and then `±i`.\n * 2. Every rational root, by the same rational-root theorem `Factor.ts` uses,\n * each divided out **exactly** over the rationals with its full\n * multiplicity. In floating point a near-root and a real root are\n * indistinguishable, which is the whole reason `Rational.ts` exists.\n * 3. The closed form for whatever degree survives: the quadratic formula,\n * Cardano for a cubic, and the biquadratic or resolvent-cubic split for a\n * quartic.\n * 4. Only a remainder that none of those reaches goes to `NumericRoots.ts`,\n * which finds **all** of its roots at once in the complex plane.\n *\n * A quadratic with a positive non-square discriminant returns its **surd**\n * form, so `x^2-2=0` gives `sqrt(2)` rather than `1.41421356`. A system that\n * advertises exact arithmetic and then hands back a rounded decimal has quietly\n * stopped being one. The surd is reduced to lowest form, so the equal but\n * unreadable `sqrt(8)/2` does not surface.\n *\n * ## Complex roots are roots\n *\n * `x^2+1=0` gives `-i` and `i`, and the numerical stage works in complex\n * arithmetic throughout rather than scanning the real line for sign changes.\n * A real-only scan is why `solve(x^5-1=0, x)` used to answer with `1` and\n * nothing else: the other four roots are complex, the scan could not see them,\n * and one root out of five was reported as though it were the whole answer.\n *\n * ## Every root is accounted for\n *\n * Each stage records how much of the degree it consumed. When those do not add\n * up to the degree of the equation, the outcome is `incomplete` rather than\n * `roots`, and it carries how many are missing. A partial list presented as a\n * complete one is the worst answer available here, because nothing about it\n * looks wrong.\n *\n * ## What is deliberately not here\n *\n * The *casus irreducibilis*: a cubic with three distinct real roots and no\n * rational one. Those roots provably cannot be written in real radicals, so\n * `CubicQuartic.ts` returns them numerically and this module labels them\n * approximate. See that module's header for why the trigonometric form is not\n * dressed up as an exact answer.\n *\n * A general quartic that neither is biquadratic nor splits into two rational\n * quadratics. Ferrari's method reaches it, but through a radical nested four\n * deep that nothing downstream could read or use, so its roots come back\n * numerically instead.\n *\n * A quintic's radicals, which by Abel-Ruffini do not exist in general, and the\n * cyclotomic forms that do exist for the special cases such as `x^5-1`. Those\n * nest deeply enough that four accurate decimals are the more useful answer.\n */\n\nimport {\n\ttype SymbolicNode,\n\tconstNode,\n\tcomplexNode,\n} from \"@solve-js/symbolic/SymbolicNode\";\nimport {\n\ttype Rational,\n\tRATIONAL_ZERO,\n\trationalAdd,\n\trationalMul,\n\trationalDiv,\n\trationalNeg,\n\trationalSub,\n\trationalCompare,\n\tisRationalZero,\n} from \"@solve-js/symbolic/Rational\";\nimport {\n\ttype Polynomial,\n\ttoPolynomial,\n\tfromPolynomial,\n\tpolyDegree,\n\tpolyCoefficients,\n} from \"@solve-js/symbolic/Polynomial\";\nimport { rationalRoots } from \"@solve-js/symbolic/Factor\";\nimport { COMPLEX_I, complex as complexValue } from \"@solve-js/symbolic/Complex\";\nimport { exactIntegerSqrt, surdNode } from \"@solve-js/symbolic/Radicals\";\nimport { type RootSet, solveCubic, solveQuartic } from \"@solve-js/symbolic/CubicQuartic\";\nimport { type ApproximateRoot, approximateRoots } from \"@solve-js/symbolic/NumericRoots\";\n\n/**\n * Highest polynomial degree {@link solveForVariable} will attempt.\n *\n * Beyond this the numerical fallback's interval scan becomes the dominant cost\n * and the answers get progressively less trustworthy, so declining is better\n * than a slow guess.\n */\nexport const SOLVE_MAX_DEGREE = 8;\n\n/**\n * The outcome of solving an equation.\n *\n * Several of these are answers rather than failures: an identity is the correct\n * response to `x+1=x+1`, and a contradiction to `1=2`.\n *\n * There is deliberately no \"no real solutions\" case. Every polynomial of degree\n * `n` has `n` roots over the complex numbers, and this solver reports them, so\n * the only honest ways to answer are the complete list, a stated shortfall, or\n * a stated refusal.\n */\nexport type SolveOutcome =\n\t/** Every solution. `exact` carries those expressible as a rational, a surd or a Gaussian rational; `approximate` carries any found numerically. */\n\t| { kind: \"roots\"; readonly exact: readonly SymbolicNode[]; readonly approximate: readonly ApproximateRoot[] }\n\t/**\n\t * Some solutions, and the count of those this solver could not reach.\n\t *\n\t * Distinct from `roots` so that a caller cannot present a partial list as a\n\t * whole one by accident, which is the failure this case exists to stop.\n\t */\n\t| {\n\t\tkind: \"incomplete\";\n\t\treadonly exact: readonly SymbolicNode[];\n\t\treadonly approximate: readonly ApproximateRoot[];\n\t\t/** How many roots, counted with multiplicity, are unaccounted for. */\n\t\treadonly missing: number;\n\t\t/** Why they are, in a sentence fit to show a reader. */\n\t\treadonly reason: string;\n\t}\n\t/** True for every value of the variable, as for `x+1=x+1`. */\n\t| { kind: \"identity\" }\n\t/** True for no value of the variable, as for `x=x+1`. */\n\t| { kind: \"contradiction\" }\n\t/** Outside what this module attempts, with the reason stated. */\n\t| { kind: \"unsupported\"; readonly reason: string };\n\n/** Evaluates descending-order coefficients at a rational point, by Horner's method. */\nfunction evaluateRational(descending: readonly Rational[], x: Rational): Rational {\n\tlet total = RATIONAL_ZERO;\n\tfor (const coeff of descending) total = rationalAdd(rationalMul(total, x), coeff);\n\treturn total;\n}\n\n/** Divides descending-order coefficients by `(x - root)`, discarding the remainder. Only call with a confirmed root. */\nfunction divideByRoot(descending: readonly Rational[], root: Rational): Rational[] {\n\tconst quotient: Rational[] = [descending[0]];\n\tfor (let i = 1; i < descending.length - 1; i++) {\n\t\tquotient.push(rationalAdd(descending[i], rationalMul(quotient[i - 1], root)));\n\t}\n\treturn quotient;\n}\n\n/**\n * Solves `ax^2 + bx + c = 0` over the complex numbers.\n *\n * A negative discriminant gives a conjugate pair rather than nothing. That is\n * what a quadratic actually has, and reporting \"no real solutions\" instead was\n * a limitation of not having a complex number to say it with.\n *\n * @returns The exact roots: rational constants for a perfect-square\n * discriminant, surds for a positive non-square one, and complex values for a\n * negative one.\n */\nfunction solveQuadratic(a: Rational, b: Rational, c: Rational): SymbolicNode[] {\n\t// discriminant = b^2 - 4ac\n\tconst discriminant = rationalSub(rationalMul(b, b), rationalMul(rational4(), rationalMul(a, c)));\n\tconst twoA = rationalMul(rational2(), a);\n\n\tif (rationalCompare(discriminant, RATIONAL_ZERO) < 0) {\n\t\treturn complexQuadraticRoots(rationalNeg(b), discriminant, twoA);\n\t}\n\tif (isRationalZero(discriminant)) return [constNode(rationalDiv(rationalNeg(b), twoA))];\n\n\t// A perfect-square discriminant needs both numerator and denominator to be\n\t// perfect squares, since the rational's own square root is taken componentwise.\n\tconst rootN = exactIntegerSqrt(discriminant.n);\n\tconst rootD = exactIntegerSqrt(discriminant.d);\n\tif (rootN !== null && rootD !== null) {\n\t\tconst root: Rational = { n: rootN, d: rootD };\n\t\tconst plus = rationalDiv(rationalAdd(rationalNeg(b), root), twoA);\n\t\tconst minus = rationalDiv(rationalSub(rationalNeg(b), root), twoA);\n\t\t// Ascending, so a pair of roots always reads low to high.\n\t\treturn rationalCompare(minus, plus) <= 0 ? [constNode(minus), constNode(plus)] : [constNode(plus), constNode(minus)];\n\t}\n\n\t// Irrational but real: return the surd rather than a decimal.\n\tconst surd = surdNode(discriminant);\n\t// Subtracting the surd gives the smaller root when the leading coefficient\n\t// is positive, so this ordering matches the rational case above.\n\tconst ascending = rationalCompare(twoA, RATIONAL_ZERO) > 0;\n\tconst lower: SymbolicNode = { kind: \"div\", left: { kind: \"sub\", left: constNode(rationalNeg(b)), right: surd }, right: constNode(twoA) };\n\tconst upper: SymbolicNode = { kind: \"div\", left: { kind: \"add\", left: constNode(rationalNeg(b)), right: surd }, right: constNode(twoA) };\n\treturn ascending ? [lower, upper] : [upper, lower];\n}\n\n/**\n * The conjugate pair for a quadratic whose discriminant is negative.\n *\n * `sqrt(D)` for negative `D` is `sqrt(-D) * i`, so the roots are\n * `(-b ± sqrt(|D|) i) / 2a`. When `sqrt(|D|)` is rational the whole root is a\n * Gaussian rational and comes back as a single exact complex value; otherwise\n * the irrational part stays as a surd multiplied by `i`.\n *\n * The negative root is returned first, matching the ordering the real cases use.\n *\n * @param negatedB - `-b`, already negated by the caller.\n * @param discriminant - The negative discriminant.\n * @param twoA - `2a`.\n * @returns The two roots.\n */\nfunction complexQuadraticRoots(negatedB: Rational, discriminant: Rational, twoA: Rational): SymbolicNode[] {\n\tconst magnitude = rationalNeg(discriminant);\n\tconst rootN = exactIntegerSqrt(magnitude.n);\n\tconst rootD = exactIntegerSqrt(magnitude.d);\n\n\tif (rootN !== null && rootD !== null) {\n\t\t// Everything stays in the Gaussian rationals, so each root is one exact\n\t\t// complex value rather than an expression.\n\t\tconst imaginary = rationalDiv({ n: rootN, d: rootD }, twoA);\n\t\tconst real = rationalDiv(negatedB, twoA);\n\t\treturn [\n\t\t\tcomplexNode(complexValue(real, rationalNeg(imaginary))),\n\t\t\tcomplexNode(complexValue(real, imaginary)),\n\t\t];\n\t}\n\n\t// The imaginary part is irrational, so it keeps its surd form times `i`.\n\t//\n\t// The division by `2a` is folded into the radicand rather than left outside\n\t// it: `sqrt(m)/2a` is `sqrt(m/(2a)^2)`, which reduces. Building it the naive\n\t// way leaves `-2*sqrt(2)*i/2` for `x^2+2=0`, since the simplifier's\n\t// common-factor cancellation cannot see a `2` buried inside a surd's own\n\t// coefficient. Doing the algebra here instead gives `-sqrt(2)*i`.\n\tconst real = rationalDiv(negatedB, twoA);\n\tconst scaledRadicand = rationalDiv(magnitude, rationalMul(twoA, twoA));\n\tconst imaginary: SymbolicNode = { kind: \"mul\", left: surdNode(scaledRadicand), right: complexNode(COMPLEX_I) };\n\n\tif (isRationalZero(real)) {\n\t\treturn [{ kind: \"neg\", operand: imaginary }, imaginary];\n\t}\n\treturn [\n\t\t{ kind: \"sub\", left: constNode(real), right: imaginary },\n\t\t{ kind: \"add\", left: constNode(real), right: imaginary },\n\t];\n}\n\n/** The rational two, built once per call rather than exported, since it is only needed here. */\nfunction rational2(): Rational {\n\treturn { n: 2n, d: 1n };\n}\n\n/** The rational four. */\nfunction rational4(): Rational {\n\treturn { n: 4n, d: 1n };\n}\n\n/** A real number as an {@link ApproximateRoot}, for the *casus irreducibilis* roots that arrive from `CubicQuartic.ts` as plain doubles. */\nfunction realApproximation(value: number): ApproximateRoot {\n\treturn { re: value, im: 0 };\n}\n\n/**\n * Solves `lhs = rhs` for one variable over the complex numbers.\n *\n * @param lhs - Left-hand side of the equation.\n * @param rhs - Right-hand side.\n * @param variable - The variable to solve for.\n * @returns The outcome. See {@link SolveOutcome}; several of its cases are\n * answers rather than failures.\n */\nexport function solveForVariable(lhs: SymbolicNode, rhs: SymbolicNode, variable: string): SolveOutcome {\n\tconst polynomial = toPolynomial({ kind: \"sub\", left: lhs, right: rhs });\n\tif (polynomial === null) {\n\t\treturn {\n\t\t\tkind: \"unsupported\",\n\t\t\treason: \"this is not a polynomial equation (it divides by an unknown, or calls a function of one)\",\n\t\t};\n\t}\n\n\tconst others = polynomial.vars.filter(name => name !== variable);\n\tconst degree = polyDegree(polynomial, variable);\n\n\tif (others.length > 0) {\n\t\t// With another unknown present the roots are themselves expressions in\n\t\t// it. That is only worth doing, and only reliably correct, in the linear\n\t\t// case; anything higher would need the quadratic formula over symbolic\n\t\t// coefficients including a symbolic discriminant sign.\n\t\tif (degree !== 1) {\n\t\t\treturn {\n\t\t\t\tkind: \"unsupported\",\n\t\t\t\treason: `solving for \"${variable}\" needs the equation to be linear in it when other unknowns (${others.join(\", \")}) are present`,\n\t\t\t};\n\t\t}\n\t\treturn solveLinearWithOtherUnknowns(polynomial, variable);\n\t}\n\n\tif (degree === 0) {\n\t\treturn polynomial.terms.size === 0 ? { kind: \"identity\" } : { kind: \"contradiction\" };\n\t}\n\tif (degree > SOLVE_MAX_DEGREE) {\n\t\treturn { kind: \"unsupported\", reason: `degree ${degree} is above the supported maximum of ${SOLVE_MAX_DEGREE}` };\n\t}\n\n\tconst descending = [...polyCoefficients(polynomial, variable)].reverse();\n\treturn solveUnivariate(descending);\n}\n\n/** Solves `a*x + b = 0` where `a` and `b` may themselves involve other unknowns. */\nfunction solveLinearWithOtherUnknowns(polynomial: Polynomial, variable: string): SolveOutcome {\n\t// Split terms into those carrying exactly one power of the variable and\n\t// those carrying none, then x = -constantPart / coefficientPart.\n\tconst coefficientTerms = new Map<string, Rational>();\n\tconst constantTerms = new Map<string, Rational>();\n\tfor (const [key, coeff] of polynomial.terms) {\n\t\tconst factors = key.split(\"*\").filter(part => part.length > 0);\n\t\tconst index = factors.indexOf(variable);\n\t\tif (index === -1) {\n\t\t\tconstantTerms.set(key, coeff);\n\t\t} else {\n\t\t\tfactors.splice(index, 1);\n\t\t\tcoefficientTerms.set(factors.join(\"*\"), coeff);\n\t\t}\n\t}\n\n\tconst namesOf = (terms: Map<string, Rational>): string[] => {\n\t\tconst names = new Set<string>();\n\t\tfor (const key of terms.keys()) {\n\t\t\tfor (const part of key.split(\"*\")) {\n\t\t\t\tif (part.length > 0) names.add(part.split(\"^\")[0]);\n\t\t\t}\n\t\t}\n\t\treturn [...names].sort();\n\t};\n\n\tconst coefficient = fromPolynomial({ terms: coefficientTerms, vars: namesOf(coefficientTerms) });\n\tconst constant = fromPolynomial({ terms: constantTerms, vars: namesOf(constantTerms) });\n\treturn {\n\t\tkind: \"roots\",\n\t\texact: [{ kind: \"div\", left: { kind: \"neg\", operand: constant }, right: coefficient }],\n\t\tapproximate: [],\n\t};\n}\n\n/**\n * The closed form for a leftover cubic or quartic, when one exists.\n *\n * Reached only after every rational root has been divided out, so what arrives\n * here genuinely needs radicals. A cubic always has a closed form of some kind;\n * a quartic has one only in the two families {@link solveQuartic} covers.\n *\n * @param descending - Descending coefficients of the leftover polynomial.\n * @returns The roots, or `null` when the numerical fallback should take over.\n */\nfunction closedFormRoots(descending: readonly Rational[]): RootSet | null {\n\tif (descending.length === 4) {\n\t\treturn solveCubic(descending[0], descending[1], descending[2], descending[3]);\n\t}\n\tif (descending.length === 5) {\n\t\treturn solveQuartic(descending[0], descending[1], descending[2], descending[3], descending[4], solveQuadratic);\n\t}\n\treturn null;\n}\n\n/**\n * The rational roots of a polynomial and the factor left once they are gone.\n *\n * `x` comes out first because the rational-root theorem needs a non-zero\n * constant term to say anything at all. Skipping that step is the single defect\n * that made `x^5-x=0` and `x^3-x=0` numerical problems: with a zero constant\n * term {@link rationalRoots} correctly reports no candidates, and the whole\n * equation then fell past every exact method it should have used.\n *\n * @param descending - Descending coefficients, the leading one non-zero.\n * @returns The distinct rational roots in ascending order, and the coefficients\n * of the factor that survives. How much of the degree was consumed is not\n * returned because it does not need to be: every division drops exactly one\n * coefficient, so it is the difference in length and cannot drift from it.\n */\nfunction extractRationalRoots(descending: readonly Rational[]): { roots: Rational[]; remaining: Rational[] } {\n\tconst roots: Rational[] = [];\n\tlet remaining = [...descending];\n\n\tlet powersOfX = 0;\n\twhile (remaining.length > 1 && isRationalZero(remaining[remaining.length - 1])) {\n\t\tremaining = remaining.slice(0, -1);\n\t\tpowersOfX++;\n\t}\n\t// A repeated root is one solution, not several, so zero is recorded once\n\t// however many powers of `x` came out.\n\tif (powersOfX > 0) roots.push(RATIONAL_ZERO);\n\n\twhile (remaining.length > 1) {\n\t\tconst found = rationalRoots(remaining);\n\t\tif (found.length === 0) break;\n\t\tfor (const root of found) {\n\t\t\tlet multiplicity = 0;\n\t\t\twhile (remaining.length > 1 && isRationalZero(evaluateRational(remaining, root))) {\n\t\t\t\tremaining = divideByRoot(remaining, root);\n\t\t\t\tmultiplicity++;\n\t\t\t}\n\t\t\t// Guarded rather than assumed: a candidate that is no longer a root of\n\t\t\t// what is left must not be reported as one.\n\t\t\tif (multiplicity > 0) roots.push(root);\n\t\t}\n\t}\n\n\t// Ascending, so a row of roots reads low to high the way a reader expects.\n\treturn { roots: roots.sort(rationalCompare), remaining };\n}\n\n/**\n * Solves a single-variable polynomial given its descending coefficients.\n *\n * Every path out of here goes through {@link finish}, and what it is told is\n * the degree of the factor still **unsolved**, read off the length of the\n * coefficient array that is left rather than accumulated in a counter as the\n * stages go. That distinction is the point. A counter is a promise each branch\n * has to keep, and the defect this replaces was exactly a branch that answered\n * for one root of five without anything downstream noticing; an array length is\n * a fact about the polynomial that no branch can misremember.\n *\n * Each leftover branch is therefore all-or-nothing: it either solves the whole\n * surviving factor or reports it whole as unsolved.\n */\nfunction solveUnivariate(descending: readonly Rational[]): SolveOutcome {\n\tconst { roots, remaining } = extractRationalRoots(descending);\n\n\tconst exact: SymbolicNode[] = roots.map(constNode);\n\tconst approximate: ApproximateRoot[] = [];\n\tconst leftoverDegree = remaining.length - 1;\n\tconst solvedDegree = descending.length - remaining.length;\n\n\tif (leftoverDegree <= 0) return finish(exact, approximate, solvedDegree, 0, \"\");\n\tif (leftoverDegree === 1) {\n\t\t// Unreachable in practice, since a linear factor's root is rational and so\n\t\t// was already extracted. Kept because the alternative to a cheap branch is\n\t\t// an unhandled degree.\n\t\texact.push(constNode(rationalDiv(rationalNeg(remaining[1]), remaining[0])));\n\t\treturn finish(exact, approximate, solvedDegree + 1, 0, \"\");\n\t}\n\tif (leftoverDegree === 2) {\n\t\texact.push(...solveQuadratic(remaining[0], remaining[1], remaining[2]));\n\t\treturn finish(exact, approximate, solvedDegree + 2, 0, \"\");\n\t}\n\n\tconst closedForm = closedFormRoots(remaining);\n\tif (closedForm !== null) {\n\t\texact.push(...closedForm.exact);\n\t\tapproximate.push(...closedForm.approximate.map(realApproximation));\n\t\treturn finish(exact, approximate, solvedDegree + leftoverDegree, 0, \"\");\n\t}\n\n\t// No closed form this module reaches: a quintic or beyond, or a quartic whose\n\t// radicals nest four deep. Every root of what is left is found at once in the\n\t// complex plane rather than one at a time by deflation.\n\tconst numeric = approximateRoots(remaining);\n\tif (numeric !== null) {\n\t\tapproximate.push(...numeric);\n\t\treturn finish(exact, approximate, solvedDegree + leftoverDegree, 0, \"\");\n\t}\n\treturn finish(\n\t\texact,\n\t\tapproximate,\n\t\tsolvedDegree,\n\t\tleftoverDegree,\n\t\t`a degree-${leftoverDegree} factor of it has no exact solution here and the numerical method did not converge on that factor`,\n\t);\n}\n\n/**\n * The single exit from the univariate solver, where the answer is checked\n * against the question before it is handed back.\n *\n * This exists because of a specific failure that a message could not have\n * prevented. `solve(x^5-1=0, x)` returned `1`: a correct root, a fifth of the\n * answer, and indistinguishable from a complete one to anybody reading it. So\n * the relationship between what was asked and what was found is asserted here\n * rather than left to each branch to remember, and an answer that does not hold\n * up comes back as `incomplete` with the shortfall counted.\n *\n * Two things are checked, and both are cheap because both quantities are\n * already known:\n *\n * 1. **Coverage.** A factor of degree `unsolvedDegree` was not solved, so that\n * many roots are missing however many were found.\n * 2. **Coherence.** A stage that claims to have solved a factor of degree one\n * or more has to have produced at least one root for it and cannot have\n * produced more than its degree. Neither is possible for a correct stage, so\n * either would be a defect in the solver rather than a property of the\n * equation, and handing back roots after seeing one would be trusting\n * exactly what has just been shown to be untrustworthy.\n *\n * @param exact - Roots known exactly.\n * @param approximate - Roots found numerically.\n * @param solvedDegree - How much of the degree the stages above actually solved.\n * @param unsolvedDegree - The degree of the factor they did not.\n * @param reason - Why that factor was not solved, used only when one was not.\n * @returns `roots` when every root is accounted for, `incomplete` otherwise.\n */\nfunction finish(\n\texact: readonly SymbolicNode[],\n\tapproximate: readonly ApproximateRoot[],\n\tsolvedDegree: number,\n\tunsolvedDegree: number,\n\treason: string,\n): SolveOutcome {\n\tconst found = exact.length + approximate.length;\n\tconst incoherent = solvedDegree >= 1 && (found < 1 || found > solvedDegree);\n\tif (unsolvedDegree > 0 || incoherent) {\n\t\treturn {\n\t\t\tkind: \"incomplete\",\n\t\t\texact,\n\t\t\tapproximate,\n\t\t\t// A distinct root can stand for several equal ones, so the count found\n\t\t\t// is a lower bound on what it covers. The degree left unsolved is not.\n\t\t\tmissing: incoherent ? Math.max(1, solvedDegree + unsolvedDegree - found) : unsolvedDegree,\n\t\t\treason: incoherent\n\t\t\t\t? `${found} root${found === 1 ? \"\" : \"s\"} were produced for a degree-${solvedDegree + unsolvedDegree} equation, which does not add up`\n\t\t\t\t: reason,\n\t\t};\n\t}\n\treturn { kind: \"roots\", exact, approximate };\n}\n","/**\n * The adapter between VM {@link Value}s and the symbolic algebra core.\n *\n * This is the only module that legitimately knows both types, which is why it\n * lives in `vm/` rather than in `symbolic/` (which imports nothing from the VM)\n * or in `packages/symbolic/` (which is grammar, and sits above `vm/` in the\n * layering).\n *\n * It exists because of a specific class of silent wrong answer.\n * `Value.toNumber()` reports `0` for a symbolic operand, deliberately, since a\n * free-variable formula has no single numeric value. Any opcode that reaches\n * for `.toNumber()` without checking `.isSymbolic()` first therefore computes\n * with zero and returns a confidently wrong result with no error at all:\n * `x^2 + 3x + 2` evaluated to `3x+2`, `-x` to `-0`, and `sqrt(x)` to `0`. The\n * three entry points below are what `vm/VM.ts` calls instead, for `EXP`, `NEG`\n * and `CALL_BUILTIN` respectively.\n */\n\nimport { Value, ValueType, numberValue, stringValue, errorValue, symbolicValue, matrixValue, faultedOperand } from \"@solve-js/vm/Value\";\nimport { solveForVariable, type SolveOutcome } from \"@solve-js/symbolic/Solve\";\nimport type { ApproximateRoot } from \"@solve-js/symbolic/NumericRoots\";\nimport {\n\ttype SymbolicNode,\n\tcomplex,\n\tcomplexNode,\n\tconstNode,\n\tpowNode,\n\tcallNode,\n\tsimplifySymbolic,\n\trationalFromNumber,\n\trationalToNumber,\n} from \"@solve-js/symbolic\";\n\n/**\n * Builtin function indices that carry a meaning through a symbolic\n * expression, mapped to the name a `call` node records.\n *\n * Declared here rather than derived from\n * `packages/function/parselets/FunctionCallParselet.ts`'s `builtinNameToIndex`,\n * because `vm/` must not import from `packages/`. `__tests__/vm/SymbolicOps.spec.ts`\n * asserts the two agree, which a test file may do since it can import both.\n *\n * Membership is a deliberate judgement, not a transcription. A function is\n * here only when applying it to a free variable is meaningful. Everything\n * absent (`min`/`max`/`random`, the number-base conversions, the finance block\n * at 51 to 60, the matrix block at 63 to 66) has no symbolic reading and is\n * reported as an error rather than silently computed against zero.\n *\n * Index 31 (`pow`) is intentionally absent: it is special-cased in\n * {@link symbolicBuiltin} to build a `pow` node, so that `pow(x, 2)` and `x^2`\n * produce the identical tree.\n */\nexport const SYMBOLIC_BUILTIN_NAMES: Readonly<Record<number, string>> = {\n\t0: \"sqrt\", 1: \"abs\", 2: \"sin\", 3: \"cos\", 4: \"tan\", 5: \"log\",\n\t6: \"ceil\", 7: \"floor\", 8: \"round\",\n\t11: \"asin\", 12: \"acos\", 13: \"atan\", 14: \"atan2\",\n\t15: \"sinh\", 16: \"cosh\", 17: \"tanh\",\n\t18: \"asinh\", 19: \"acosh\", 20: \"atanh\",\n\t21: \"cbrt\", 23: \"expm1\", 24: \"exp\", 26: \"hypot\",\n\t28: \"log10\", 29: \"log1p\", 30: \"log2\",\n\t33: \"sign\", 34: \"trunc\",\n\t// Spelled exactly as `builtinNameToIndex` accepts them, all lower case. A\n\t// `call` node's name is what gets displayed, so a name the parser would not\n\t// accept back would render an expression the user cannot retype.\n\t35: \"degtorad\", 36: \"radtodeg\",\n\t61: \"root\", 62: \"fact\",\n};\n\n/** Builtin index for `pow(base, exponent)`, which becomes a `pow` node rather than a `call` node. */\nconst POW_BUILTIN_INDEX = 31;\n\n/**\n * Builtin indices that take a symbolic argument on purpose and handle it\n * themselves, so `vm/VM.ts` must **not** route them through\n * {@link symbolicBuiltin}.\n *\n * These are the algebra verbs (`expand`, and the later phases' `factor`,\n * `solve` and calculus functions). Every other builtin reads its arguments\n * through `toNumber()` and has to be intercepted; these exist precisely to\n * receive an expression containing unknowns, so intercepting them would report\n * \"cannot be applied to an expression that still contains an unknown\" for the\n * one family of functions where that is the whole point.\n *\n * Listed here rather than imported from `packages/symbolic/` because `vm/` must\n * not import from `packages/`. `__tests__/engine/SymbolicSurfaceParity.spec.ts`\n * asserts this set matches the package's own table.\n */\nexport const SYMBOLIC_NATIVE_BUILTINS: ReadonlySet<number> = new Set([67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79]);\n\n/**\n * Converts a Value into a {@link SymbolicNode}.\n *\n * @param v - The value to convert.\n * @returns The value's own tree when it is already symbolic, otherwise a\n * `const` node wrapping its numeric value. `null` when the value has no exact\n * rational image, which covers `NaN`, `±Infinity`, and the `Error`/`Pending`\n * value types whose `toNumber()` is a placeholder zero rather than a quantity.\n */\nexport function valueToSymbolic(v: Value): SymbolicNode | null {\n\tif (v.type === ValueType.Symbolic) return v.value as SymbolicNode;\n\tif (v.type === ValueType.Error || v.type === ValueType.Pending) return null;\n\tconst numeric = v.toNumber();\n\tif (!Number.isFinite(numeric)) return null;\n\treturn constNode(rationalFromNumber(numeric));\n}\n\n/**\n * Simplifies a tree and wraps it back as a Value.\n *\n * @param node - The tree to finish.\n * @returns A plain `Number` Value when the tree simplified to a bare constant,\n * so an expression whose unknowns all cancelled reads as an ordinary number,\n * otherwise a `Symbolic` Value.\n */\nexport function symbolicToValue(node: SymbolicNode): Value {\n\tconst simplified = simplifySymbolic(node);\n\tif (simplified.kind === \"const\") return numberValue(rationalToNumber(simplified.value));\n\treturn symbolicValue(simplified);\n}\n\n/** The error returned whenever a symbolic operand reaches something with no symbolic meaning, in place of the old silent zero. */\nfunction unsupported(what: string): Value {\n\treturn errorValue(\n\t\t\"SYMBOLIC_UNSUPPORTED_FUNCTION\",\n\t\t`\"${what}\" cannot be applied to an expression that still contains an unknown.`,\n\t);\n}\n\n/**\n * `^` where at least one operand is symbolic.\n *\n * @param l - The base.\n * @param r - The exponent.\n * @returns The resulting Value, or an error Value when either operand has no\n * exact rational image.\n */\nexport function symbolicPow(l: Value, r: Value): Value {\n\tconst base = valueToSymbolic(l);\n\tconst exponent = valueToSymbolic(r);\n\tif (base === null || exponent === null) return unsupported(\"^\");\n\treturn symbolicToValue(powNode(base, exponent));\n}\n\n/**\n * Unary minus where the operand is symbolic.\n *\n * @param v - The operand.\n * @returns The negated Value, or an error Value when the operand has no exact\n * rational image.\n */\nexport function symbolicNeg(v: Value): Value {\n\tconst operand = valueToSymbolic(v);\n\tif (operand === null) return unsupported(\"-\");\n\treturn symbolicToValue({ kind: \"neg\", operand });\n}\n\n/**\n * A builtin function call where at least one argument is symbolic.\n *\n * @param index - The builtin index, as pushed by `OpCode.CALL_BUILTIN`.\n * @param args - The already-ordered argument values.\n * @returns The resulting Value. An index with no symbolic meaning yields an\n * error Value rather than a number computed from a placeholder zero.\n */\nexport function symbolicBuiltin(index: number, args: readonly Value[]): Value {\n\tconst nodes: SymbolicNode[] = [];\n\tfor (const arg of args) {\n\t\t// Propagate a faulted operand unchanged rather than replacing it, so the\n\t\t// original code and message (or pending query key) reach the caller.\n\t\t// Pending counts: valueToSymbolic() below returns null for one, which\n\t\t// would report \"no symbolic reading\" for a value that simply has not\n\t\t// arrived yet.\n\t\tconst faulted = faultedOperand(arg);\n\t\tif (faulted) return faulted;\n\t\tconst node = valueToSymbolic(arg);\n\t\tif (node === null) return unsupported(SYMBOLIC_BUILTIN_NAMES[index] ?? `builtin ${index}`);\n\t\tnodes.push(node);\n\t}\n\n\tif (index === POW_BUILTIN_INDEX && nodes.length === 2) {\n\t\treturn symbolicToValue(powNode(nodes[0], nodes[1]));\n\t}\n\n\tconst name = SYMBOLIC_BUILTIN_NAMES[index];\n\tif (name === undefined) return unsupported(`builtin ${index}`);\n\treturn symbolicToValue(callNode(name, nodes));\n}\n\n/**\n * Renders one root as a value, keeping a fraction exact.\n *\n * A whole-number root becomes an ordinary Number, which reads naturally. A\n * fractional one stays Symbolic so it renders as `1/3`: routing it through\n * {@link symbolicToValue} would collapse it to a double and the number\n * formatter would show `0.33`, throwing away the exactness that solving\n * exactly was for.\n */\nfunction rootToValue(root: SymbolicNode): Value {\n\tconst value = symbolicToValue(root);\n\tif (value.type === ValueType.Number && !Number.isInteger(value.toNumber())) return symbolicValue(root);\n\treturn value;\n}\n\n/**\n * Renders one numerically-found root as a value.\n *\n * A root off the real line becomes an exact complex node built from the two\n * doubles, so it displays as `-0.809+0.5878i` rather than being dropped or\n * flattened to its real part. The rational conversion is of the double's own\n * decimal form, so nothing is invented: the value shown is the value found, and\n * the number formatter rounds it for display exactly as it rounds any other.\n */\nfunction approximateRootToValue(root: ApproximateRoot): Value {\n\tif (root.im === 0) return numberValue(root.re);\n\treturn symbolicValue(complexNode(complex(rationalFromNumber(root.re), rationalFromNumber(root.im))));\n}\n\n/**\n * Renders a {@link SolveOutcome} as a VM value.\n *\n * Some outcomes are answers rather than errors and read as sentences, since\n * \"no solution\" is the complete and correct response to `1=2` and dressing it\n * up as a failure would misrepresent it.\n *\n * An `incomplete` outcome becomes an error even though roots were found. That\n * is the point of it: `solve(x^5-1=0, x)` answering `1` was wrong in the way\n * that matters most, because one root of five looks exactly like the whole\n * answer. Saying how many are missing is the only reading a user cannot be\n * misled by.\n */\nfunction solveOutcomeToValue(outcome: SolveOutcome): Value {\n\tswitch (outcome.kind) {\n\t\tcase \"identity\":\n\t\t\treturn stringValue(\"true for every value\");\n\t\tcase \"contradiction\":\n\t\t\treturn stringValue(\"no solution\");\n\t\tcase \"unsupported\":\n\t\t\treturn errorValue(\"SYMBOLIC_SOLVE_UNSUPPORTED\", `Cannot solve this equation: ${outcome.reason}.`);\n\t\tcase \"incomplete\": {\n\t\t\tconst found = outcome.exact.length + outcome.approximate.length;\n\t\t\treturn errorValue(\n\t\t\t\t\"SYMBOLIC_SOLVE_INCOMPLETE\",\n\t\t\t\t`Only ${found} of this equation's ${found + outcome.missing} roots could be found: ${outcome.reason}.`,\n\t\t\t);\n\t\t}\n\t\tcase \"roots\": {\n\t\t\tconst values = outcome.exact.map(rootToValue);\n\t\t\tfor (const approximate of outcome.approximate) values.push(approximateRootToValue(approximate));\n\t\t\tif (values.length === 0) return stringValue(\"no solution\");\n\t\t\tif (values.length === 1) return values[0];\n\t\t\t// Several roots read best as a row of values, which the matrix\n\t\t\t// formatter already renders as \"[-2, 2]\".\n\t\t\treturn matrixValue(1, values.length, values.map(v => (v.type === ValueType.Symbolic ? (v.value as SymbolicNode) : v.toNumber())));\n\t\t}\n\t}\n}\n\n/**\n * Solves `lhs = rhs` for a variable, given the two sides as already-evaluated\n * Values, and renders the outcome.\n *\n * Shared by the `solve(equation, variable)` builtin and by the stored\n * `x^2-4 = 0` then `x =>` form in `engine/ExpressionEngine.ts`. Both go through\n * here rather than each rendering an outcome themselves, so the two surfaces\n * cannot drift into disagreeing about what an answer looks like.\n *\n * @param lhsValue - The left-hand side, evaluated symbolic-tolerantly.\n * @param rhsValue - The right-hand side, likewise.\n * @param variable - The unknown to solve for.\n * @returns The solution as a Value, or an error Value when a side has no exact\n * value to solve with.\n */\nexport function solveEquationValues(lhsValue: Value, rhsValue: Value, variable: string): Value {\n\tconst lhs = valueToSymbolic(lhsValue);\n\tconst rhs = valueToSymbolic(rhsValue);\n\tif (lhs === null || rhs === null) {\n\t\treturn errorValue(\"SYMBOLIC_NONFINITE_OPERAND\", \"An equation side has no exact value to solve with.\");\n\t}\n\treturn solveOutcomeToValue(solveForVariable(lhs, rhs, variable));\n}\n","import { Value, ValueType, numberValue, numberValueRational, numberValueUncertain, bigIntValue, uomValue, uomValueExact, matrixValue, errorValue, symbolicValue, type MatrixData, type MatrixEntry } from \"@solve-js/vm/Value\";\nimport { convertUnit, getMeasure } from \"@solve-js/uom/UomConverter\";\nimport { sharedCurrencyExchange } from \"@solve-js/uom/CurrencyExchange\";\nimport { decimalAdd, decimalSubtract, decimalMultiply, decimalDivide, decimalIsZero, decimalToNumber, decimalFromNumberIfExact, decimalCompare, type DecimalData } from \"@solve-js/decimal\";\nimport { sameShape } from \"@solve-js/vm/MatrixOps\";\nimport { type SymbolicNode, type Rational, simplifySymbolic, rational, rationalAdd, rationalSub, rationalMul, rationalDiv, rationalToNumber, rationalCompare, isRationalZero } from \"@solve-js/symbolic\";\nimport { valueToSymbolic } from \"@solve-js/vm/SymbolicOps\";\nimport { ErrorFactory, type EngineError } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Unify two Value operands that may carry units of measurement.\n * Returns numeric values in a common unit (or undefined unit if incompatible).\n */\nexport function unifyUom(l: Value, r: Value): { lv: number; rv: number; unit: string | undefined; sameMeasure: boolean } {\n if (l.type === ValueType.Uom && r.type === ValueType.Uom) {\n if (l.unit === r.unit) {\n return { lv: l.toNumber(), rv: r.toNumber(), unit: l.unit, sameMeasure: true };\n }\n const lMeasure = getMeasure(l.unit!);\n const rMeasure = getMeasure(r.unit!);\n const isCurrency = sharedCurrencyExchange.isCurrency(l.unit!) && sharedCurrencyExchange.isCurrency(r.unit!);\n\n if (lMeasure && lMeasure === rMeasure) {\n const rvConverted = convertUnit(r.toNumber(), r.unit!, l.unit!);\n return { lv: l.toNumber(), rv: rvConverted, unit: l.unit, sameMeasure: true };\n }\n if (isCurrency) {\n const rvConverted = sharedCurrencyExchange.convertSync(r.toNumber(), r.unit!, l.unit!);\n if (rvConverted !== null) {\n return { lv: l.toNumber(), rv: rvConverted, unit: l.unit, sameMeasure: true };\n }\n }\n return { lv: l.toNumber(), rv: r.toNumber(), unit: undefined, sameMeasure: false };\n }\n if (l.type === ValueType.Uom) {\n return { lv: l.toNumber(), rv: r.toNumber(), unit: l.unit, sameMeasure: true };\n }\n if (r.type === ValueType.Uom) {\n return { lv: l.toNumber(), rv: r.toNumber(), unit: r.unit, sameMeasure: true };\n }\n return { lv: l.toNumber(), rv: r.toNumber(), unit: undefined, sameMeasure: true };\n}\n\n/**\n * How close two unified magnitudes have to be before a comparison calls them\n * the same number, as a fraction of the magnitudes that produced them.\n *\n * A conversion is arithmetic, and arithmetic rounds. Converting 32 fahrenheit\n * to celsius gives 5.684e-14 rather than the exact zero the two scales are\n * defined to share, because the offset arithmetic runs in binary floating\n * point and five ninths has no finite binary expansion. Comparing that with\n * `===` made `0 C == 32 F` answer false, and with it every other equality that\n * has to cross a temperature scale.\n *\n * 1e-12 sits roughly four decimal digits above the last bit of a double, which\n * is wide enough for the rounding any conversion in the table introduces and\n * far narrower than the gap between two numbers a person meant to be\n * different: at the scale of the 32 in the example above it admits a\n * difference of 3.2e-11, and a user who writes two temperatures apart writes\n * them further apart than that.\n */\nconst UNIFIED_COMPARISON_TOLERANCE = 1e-12;\n\n/** The largest of three magnitudes, ignoring any that is not finite. */\nfunction largestFiniteMagnitude(a: number, b: number, c: number): number {\n let scale = 0;\n if (Number.isFinite(a) && Math.abs(a) > scale) scale = Math.abs(a);\n if (Number.isFinite(b) && Math.abs(b) > scale) scale = Math.abs(b);\n if (Number.isFinite(c) && Math.abs(c) > scale) scale = Math.abs(c);\n return scale;\n}\n\n/**\n * Compare two operands that carry units, in a unit each of them can be read\n * in.\n *\n * Returns the two magnitudes in a common unit plus the two facts a comparison\n * opcode needs that it cannot recover from those magnitudes alone: whether the\n * units share a measure at all, and whether the magnitudes are equal once the\n * conversion's own rounding is allowed for.\n *\n * The tolerance is measured against the ORIGINAL operand magnitudes as well as\n * the converted ones. A converted value sitting near zero has no magnitude of\n * its own to scale against, which is exactly the `0 C == 32 F` case, and yet\n * the arithmetic that produced its rounding worked on numbers the size of the\n * inputs, so those are what the error has to be judged against.\n *\n * NaN is equal to nothing, itself included, which is what makes `0/0 == 0/0`\n * answer false; it falls out of the finiteness check rather than needing its\n * own branch.\n */\nexport function compareUom(l: Value, r: Value): { lv: number; rv: number; equal: boolean; sameMeasure: boolean } {\n const { lv, rv, sameMeasure } = unifyUom(l, r);\n if (!sameMeasure) return { lv, rv, equal: false, sameMeasure: false };\n // Same-currency money compares on its exact decimals, so \"$0.1 + $0.2 ==\n // $0.3\" is true on the value rather than on whichever doubles the two sides\n // happen to land on. The returned lv/rv (already the nearest doubles) order\n // the same way, since rounding to nearest is monotonic.\n if (\n l.type === ValueType.Uom && r.type === ValueType.Uom &&\n l.unit !== undefined && l.unit === r.unit &&\n l.exact !== undefined && r.exact !== undefined &&\n sharedCurrencyExchange.isCurrency(l.unit)\n ) {\n return { lv, rv, equal: decimalCompare(l.exact, r.exact) === 0, sameMeasure: true };\n }\n if (lv === rv) return { lv, rv, equal: true, sameMeasure: true };\n if (!Number.isFinite(lv) || !Number.isFinite(rv)) return { lv, rv, equal: false, sameMeasure: true };\n const scale = largestFiniteMagnitude(lv, rv, r.toNumber());\n return { lv, rv, equal: Math.abs(lv - rv) <= scale * UNIFIED_COMPARISON_TOLERANCE, sameMeasure: true };\n}\n\n/**\n * The dimension nouns that do not read as their measure-kind name. A quantity\n * of `time` reads as a duration in a sentence (\"a duration cannot be converted\n * to a length\"), and the generated measure table spells luminous intensity as\n * one camelCase token. Every other kind (length, mass, area, ...) already reads\n * as the noun, so it is used unchanged.\n */\nconst MEASURE_NOUNS: Readonly<Record<string, string>> = {\n time: \"duration\",\n luminousIntensity: \"luminous intensity\",\n};\n\n/**\n * The dimensions that are uncountable, so they take no indefinite article in\n * the conversion sentence: \"money\", not \"a money\".\n */\nconst UNCOUNTABLE_MEASURES: ReadonlySet<string> = new Set([\"money\", \"data\"]);\n\n/** The past participle each combining op reads as in the mismatch sentence. */\nconst COMBINE_VERBS: Readonly<Record<string, string>> = {\n add: \"added\",\n sub: \"subtracted\",\n mul: \"multiplied\",\n div: \"divided\",\n};\n\n/**\n * Name the dimension a unit measures, as a noun a message can drop into a\n * sentence: `kg` gives \"mass\", `hour` gives \"duration\", `USD` gives \"money\".\n *\n * Returns undefined when the unit has no single dimension to name (a compound\n * rate such as \"km/h\", or a currency code the exchange does not recognise), so\n * a caller can fall back to naming the raw unit rather than printing\n * \"undefined\".\n */\nexport function describeMeasure(unit: string): string | undefined {\n // Currencies are not in the measure table (getMeasure returns undefined for\n // them), so they are named here before the table lookup.\n if (sharedCurrencyExchange.isCurrency(unit)) return \"money\";\n const measure = getMeasure(unit);\n if (measure === undefined) return undefined;\n return MEASURE_NOUNS[measure] ?? measure;\n}\n\n/**\n * A dimension noun with the indefinite article that reads correctly: \"a\n * length\", \"an area\", and the uncountable dimensions (\"money\") left bare.\n */\nfunction withMeasureArticle(noun: string): string {\n if (UNCOUNTABLE_MEASURES.has(noun)) return noun;\n return /^[aeiou]/.test(noun) ? `an ${noun}` : `a ${noun}`;\n}\n\n/**\n * The mismatch sentence naming the two differing dimensions of a refused\n * `+`/`-`/`*` or comparison: \"mass and length cannot be added\".\n *\n * Returns undefined when there is no pair of differing dimensions to name: an\n * unknown or compound unit on either side, or two currencies (both money, the\n * missing-rate case rather than a dimension mismatch). The caller then keeps\n * its own fallback, which names the units instead.\n *\n * @param verb - the past participle for the sentence (\"added\", \"compared\").\n */\nexport function describeMeasureMismatch(\n lUnit: string | undefined,\n rUnit: string | undefined,\n verb: string,\n): string | undefined {\n const left = lUnit === undefined ? undefined : describeMeasure(lUnit);\n const right = rUnit === undefined ? undefined : describeMeasure(rUnit);\n if (left !== undefined && right !== undefined && left !== right) {\n return `${left} and ${right} cannot be ${verb}`;\n }\n return undefined;\n}\n\n/**\n * The past participle for a combining opcode's mismatch sentence. MOD passes no\n * op kind (see {@link binaryOp}), and reads as the neutral \"combined\".\n */\nexport function combineVerb(op: string | undefined): string {\n return op !== undefined ? (COMBINE_VERBS[op] ?? \"combined\") : \"combined\";\n}\n\n/**\n * The mismatch sentence for a conversion the engine cannot make: \"a duration\n * cannot be converted to a length\".\n *\n * Returns undefined when either side has no dimension to name (a compound rate,\n * or a currency code the exchange does not know), so the caller keeps its own\n * fallback that names the two units instead.\n */\nexport function describeConversionMismatch(fromUnit: string, toUnit: string): string | undefined {\n const from = describeMeasure(fromUnit);\n const to = describeMeasure(toUnit);\n if (from !== undefined && to !== undefined && from !== to) {\n return `${withMeasureArticle(from)} cannot be converted to ${withMeasureArticle(to)}`;\n }\n return undefined;\n}\n\n/**\n * The answer an ordered comparison gives when the two quantities share no\n * measure.\n *\n * `<` between a mass and a length is not false, it is a question with no\n * answer, and answering it with a boolean drawn from the bare magnitudes is\n * the same confidently-wrong shape `binaryOp` refuses below for `+`. Equality\n * is the exception and stays a boolean: a kilogram genuinely is not a metre,\n * so `==` can say false and mean it.\n *\n * The two dimensions are named where both are known and differ (\"mass and\n * length cannot be compared\"), falling back to naming the units when they are\n * not (see {@link describeMeasureMismatch}).\n */\nexport function incomparableUnitsError(l: Value, r: Value): Value {\n const lUnit = l.type === ValueType.Uom ? l.unit : undefined;\n const rUnit = r.type === ValueType.Uom ? r.unit : undefined;\n const named = describeMeasureMismatch(lUnit, rUnit, \"compared\");\n return errorValue(\"INCOMPATIBLE_UNITS\", named ?? `Cannot compare incompatible units: ${lUnit ?? \"?\"} and ${rUnit ?? \"?\"}`);\n}\n\n/**\n * Read an operand as a bigint without rounding it through a double first.\n *\n * An already-BigInt operand hands over its raw bigint; anything else converts\n * via `toNumber()`, which is lossless because a value that was only ever a\n * double has no extra precision to lose. Going through `toNumber()`\n * unconditionally is what made every bitwise operator, every comparison and\n * `^` destroy the digits that are the whole point of the type, e.g.\n * `12345678901234567891n & 1n` answered 0 because the left operand became\n * 12345678901234567168 on the way in.\n *\n * @throws A recoverable `BIGINT_INEXACT_OPERAND` execution error for an operand\n * with no whole-number form. This used to be a raw `RangeError` straight out of\n * `BigInt()`, which the VM's outer catch relabelled UNEXPECTED_ERROR/INTERNAL:\n * `1n + 0.5`, `1n & 1.5`, `1n << 1.5`, `5n/pi` and `e/8n` all reported an engine\n * bug for what is a typo in the line. The same shape `vm/VMBuiltinArity.ts` was\n * written to fix for `sqrt()`.\n */\nexport function toBigIntOperand(v: Value): bigint {\n if (v.type === ValueType.BigInt) return v.value as bigint;\n const n = v.toNumber();\n if (!Number.isInteger(n)) {\n // Covers NaN and both infinities as well as fractions, all of which\n // `BigInt()` refuses and none of which has a whole-number form.\n const shown = Number.isNaN(n) ? \"NaN\" : String(n);\n throw ErrorFactory.execution(\n \"BIGINT_INEXACT_OPERAND\",\n `A whole-number (n) value can only be combined with another whole number, and ${shown} is not one`,\n { operand: shown },\n );\n }\n return BigInt(n);\n}\n\n/**\n * What `10n / 0n` and `10n mod 0n` answer.\n *\n * DECIDED, and deliberately NOT the same as `1 / 0`, which is Infinity here.\n * The two numeric types already disagree about division and always did:\n * `7n / 2n` is 3n and `7 / 2` is 3.5, because a bigint division is exact\n * integer division. Every language that has both draws the line in the same\n * place, C, Java, Python and JavaScript's own BigInt included: integer division\n * by zero raises, IEEE-754 division by zero is an infinity. So this is not the\n * two types disagreeing about zero, it is the one difference between them\n * showing up at zero as well as everywhere else, and an infinity is not\n * something exact integer arithmetic has to hand back.\n *\n * What was actually wrong was the reporting, not the decision.\n * `__tests__/hardening/ArithmeticBigInt.spec.ts` already asserted this and its\n * comment already explained it, but nothing implemented it: the test passed\n * because V8's own `RangeError` happens to say \"Division by zero\", and the VM\n * relabelled that raw exception UNEXPECTED_ERROR/INTERNAL. So a user dividing\n * by zero was told the ENGINE had failed. Now it is the engine's own error,\n * with a code a host can branch on.\n *\n * @returns The error for the caller's `bigOp` to throw.\n */\nexport function bigIntDivisionByZero(): EngineError {\n return ErrorFactory.execution(\n \"BIGINT_DIVISION_BY_ZERO\",\n \"Division by zero: a whole-number (n) division is exact integer division, which has no answer at zero, unlike 1 / 0 which is Infinity\",\n );\n}\n\n/**\n * Three-way comparison of two operands, at least one of which is a BigInt,\n * with every digit intact.\n *\n * @returns -1, 0 or 1, or `null` when an operand has no exact bigint image (a\n * fraction, an infinity, a NaN). On null the caller keeps its ordinary double\n * comparison, which is the correct answer for a fractional operand and the\n * only available one for a non-finite operand.\n */\nexport function compareBigIntOperands(l: Value, r: Value): -1 | 0 | 1 | null {\n const lb = exactBigInt(l);\n const rb = exactBigInt(r);\n if (lb === null || rb === null) return null;\n if (lb < rb) return -1;\n if (lb > rb) return 1;\n return 0;\n}\n\n/** An operand's exact bigint image, or null when it has none. */\nfunction exactBigInt(v: Value): bigint | null {\n if (v.type === ValueType.BigInt) return v.value as bigint;\n const n = v.toNumber();\n // Rules out Infinity and NaN as well as fractions.\n return Number.isInteger(n) ? BigInt(n) : null;\n}\n\n/**\n * `base` raised to `exponent`, in doubles.\n *\n * DECIDED (1.0.0, differential run 20260811): where ECMAScript and C99/IEEE 754\n * disagree about `pow`, this engine follows C99.\n *\n * They disagree in exactly one family of cases, a base of exactly ±1 with an\n * exponent that is not a finite number. ECMAScript's `**` answers NaN for\n * `1 ** Infinity` and `1 ** NaN`, on the reasoning that 1^infinity is an\n * indeterminate FORM in the calculus of limits. C99 (F.9.4.4), IEEE 754's\n * `pow`, Python and Ruby all answer 1, on the reasoning that this is not a\n * limit: the base here is the number one, not something approaching it, and one\n * multiplied by itself any number of times is one.\n *\n * `1^2^3^4^5` is what made the choice matter. `^` groups right, so that tower\n * is 1^(2^(3^(4^5))); the inner tower overflows a double to Infinity, and the\n * outermost step is 1^Infinity. Under ECMAScript's rule the answer is NaN, so\n * an expression whose every base is 1 answers \"not a number\", and the reason is\n * a rounding artefact three levels down rather than anything about the\n * question. Under C99's rule it is 1, which is also what it is under exact\n * arithmetic, which settles it: the release that exists to stop the engine\n * answering confidently from an artefact should not itself do that.\n *\n * `NaN ^ 0` is 1 under both rules and needs no branch here.\n */\nexport function power(base: number, exponent: number): number {\n // The overwhelmingly common case, and the one both standards agree on.\n if (Number.isFinite(exponent)) return Math.pow(base, exponent);\n // pow(1, y) is 1 for every y, a NaN exponent included.\n if (base === 1) return 1;\n // pow(-1, +-infinity) is 1 as well, but pow(-1, NaN) is NaN: C99 extends\n // the rule to a NaN exponent only for the base +1.\n if (base === -1 && !Number.isNaN(exponent)) return 1;\n return Math.pow(base, exponent);\n}\n\n/**\n * The exact decimal an operand contributes to a money operation, or null.\n *\n * A currency operand hands over the sidecar its literal or a prior exact result\n * set. A plain scalar (the `3` in `$1.10 * 3`, the `1.10` in `$0.70 * 1.10`)\n * hands over its own exact decimal: a whole number always has one, and a\n * decimal-point literal carries one too, which is what lets a fractional\n * multiplier stay exact against money without the bare `1.005 * 100` between\n * two plain numbers changing at all. A fractional double with no sidecar (a\n * `sqrt` result) has no exact decimal and returns null, dropping that operation\n * back to the float path.\n */\nfunction operandExactDecimal(v: Value): DecimalData | null {\n if (v.exact !== undefined) return v.exact;\n return decimalFromNumberIfExact(v.toNumber());\n}\n\n/**\n * The exact result of a money arithmetic op, or null when it cannot be exact.\n *\n * Exactness is preserved only when the currency stays put: two amounts in the\n * same currency, or a currency against a plain scalar. A cross-currency\n * combination goes through an exchange rate, which is a double, so it is left\n * to the float path below rather than dressed up as exact. Division falls back\n * for a zero divisor so \"$10 / 0\" keeps the double's Infinity, and for two\n * currencies (a ratio the VM computes before this is ever reached).\n */\nfunction exactMoneyOp(l: Value, r: Value, op: \"add\" | \"sub\" | \"mul\" | \"div\"): Value | null {\n const lMoney = l.type === ValueType.Uom && l.unit !== undefined && l.exact !== undefined && sharedCurrencyExchange.isCurrency(l.unit);\n const rMoney = r.type === ValueType.Uom && r.unit !== undefined && r.exact !== undefined && sharedCurrencyExchange.isCurrency(r.unit);\n if (!lMoney && !rMoney) return null;\n\n let ld: DecimalData | null;\n let rd: DecimalData | null;\n let unit: string;\n if (lMoney && rMoney) {\n // Different currencies reconcile through a rate, which is a double, so\n // only a shared currency stays exact. A ratio (money / money) is the\n // VM's own DIV case and never arrives here.\n if (l.unit !== r.unit || op === \"div\") return null;\n ld = l.exact!; rd = r.exact!; unit = l.unit!;\n } else if (lMoney && r.type !== ValueType.Uom) {\n // The other side must be a plain scalar. A different-unit Uom (\"$100 +\n // 5 kg\") is NOT a scalar, and must fall through to the float path so it\n // surfaces the incompatible-units error rather than absorbing the 5 as\n // though it were dollars.\n ld = l.exact!; unit = l.unit!;\n rd = operandExactDecimal(r);\n } else if (rMoney && l.type !== ValueType.Uom) {\n rd = r.exact!; unit = r.unit!;\n ld = operandExactDecimal(l);\n } else {\n return null;\n }\n if (ld === null || rd === null) return null;\n\n let result: DecimalData;\n switch (op) {\n case \"add\": result = decimalAdd(ld, rd); break;\n case \"sub\": result = decimalSubtract(ld, rd); break;\n case \"mul\": result = decimalMultiply(ld, rd); break;\n case \"div\":\n if (decimalIsZero(rd)) return null;\n result = decimalDivide(ld, rd);\n break;\n }\n return uomValueExact(decimalToNumber(result), unit, result);\n}\n\n/**\n * The exact rational an operand contributes to a fraction operation, or null.\n *\n * A value that already carries a `rational` sidecar hands it over. A plain\n * whole number (the \"14\" in \"2/7 * 14\", the \"3\" in \"1/3 * 3\") has the exact\n * rational n/1. Everything else has none: a non-integer double with no sidecar\n * (a decimal literal, a `sqrt` result) returns null so the operation drops to\n * the float path, and a bigint returns null so \"100n / 3n\" stays exact INTEGER\n * division (33n) rather than becoming the fraction 100/3. NaN and the\n * infinities fail the integer test and return null with everything else.\n */\nfunction operandRational(v: Value): Rational | null {\n if (v.rational !== undefined) return v.rational;\n if ((v.type === ValueType.Number || v.type === ValueType.Hex) && typeof v.value === \"number\" && Number.isInteger(v.value)) {\n return rational(BigInt(v.value));\n }\n return null;\n}\n\n/**\n * The exact rational result of a fraction operation, or null when it has none.\n *\n * DIV is the producer: \"1/3\" is two whole numbers, so both operands have a\n * rational image and the quotient 1/3 seeds the sidecar the rest of the system\n * propagates. ADD/SUB/MUL only ever preserve, their call sites reach here only\n * when a `rational` sidecar already rides on an operand, so plain integer sums\n * like \"1e16 + 1 - 1e16\" never grow one and stay the doubles they must be.\n *\n * The double is recomputed from the reduced result rather than from the operand\n * doubles, which is the whole point: \"1/6\" six times over is exactly 1, not the\n * 0.9999999999999999 the doubles accumulate to.\n *\n * Returns null (dropping to the float path) rather than throwing when a\n * fraction cannot stay exact: a zero divisor keeps \"1/0\" as the double Infinity\n * the float path gives, and a value past the rational magnitude ceiling keeps\n * the doubles' answer rather than surfacing a fraction-overflow error for\n * ordinary arithmetic.\n */\nexport function exactRationalOp(l: Value, r: Value, op: \"add\" | \"sub\" | \"mul\" | \"div\"): Value | null {\n const lr = operandRational(l);\n if (lr === null) return null;\n const rr = operandRational(r);\n if (rr === null) return null;\n if (op === \"div\" && isRationalZero(rr)) return null;\n let result: Rational;\n try {\n switch (op) {\n case \"add\": result = rationalAdd(lr, rr); break;\n case \"sub\": result = rationalSub(lr, rr); break;\n case \"mul\": result = rationalMul(lr, rr); break;\n case \"div\": result = rationalDiv(lr, rr); break;\n }\n } catch {\n // Past RATIONAL_MAX_BITS the rational ops throw. The float answer is\n // always available and always valid, so fall back to it rather than\n // fail a line that only happened to build a very large fraction.\n return null;\n }\n return numberValueRational(rationalToNumber(result), result);\n}\n\n/**\n * The result of a `+`/`-`/`*`/`/` between operands, at least one of which\n * carries a one-sigma uncertainty, propagated in quadrature. Null when it does\n * not apply.\n *\n * Independent errors combine in quadrature, the common case the feature scopes\n * itself to (correlated terms are a much larger problem and out of scope). The\n * center follows the ordinary arithmetic; the spread follows the standard\n * first-order rules:\n * add/sub: sigma = sqrt(sigma_a^2 + sigma_b^2)\n * mul: sigma = sqrt((b*sigma_a)^2 + (a*sigma_b)^2)\n * div: sigma = sqrt((sigma_a/b)^2 + (a*sigma_b/b^2)^2)\n * The mul/div forms are the partial-derivative version of the relative-error\n * rule sigma = |result| * sqrt((sigma_a/a)^2 + (sigma_b/b)^2), algebraically the\n * same but without dividing by a center that may be zero. A plain number is\n * read as an exact operand (uncertainty 0), which is what makes a scalar\n * multiply `(a ± s) * k` come out as `s * |k|`.\n *\n * Returns null unless both operands are plain Numbers, so a unit, a matrix or\n * any other typed operand keeps its own path (and drops the uncertainty, as a\n * comparison or a transcendental function does). The VM gates the call on an\n * uncertainty actually being present, so a plain `2 * 3` never reaches here.\n */\nexport function uncertainOp(l: Value, r: Value, op: \"add\" | \"sub\" | \"mul\" | \"div\"): Value | null {\n if (l.type !== ValueType.Number || r.type !== ValueType.Number) return null;\n const a = l.value as number;\n const b = r.value as number;\n const sa = l.uncertainty ?? 0;\n const sb = r.uncertainty ?? 0;\n let center: number;\n let sigma: number;\n switch (op) {\n case \"add\": center = a + b; sigma = Math.hypot(sa, sb); break;\n case \"sub\": center = a - b; sigma = Math.hypot(sa, sb); break;\n case \"mul\": center = a * b; sigma = Math.hypot(b * sa, a * sb); break;\n case \"div\": center = a / b; sigma = Math.hypot(sa / b, (a * sb) / (b * b)); break;\n }\n return numberValueUncertain(center, sigma);\n}\n\n/**\n * Three-way comparison of two operands as exact fractions, or null.\n *\n * Mirrors {@link compareBigIntOperands}: when a rational rides on either side\n * the comparison is decided on the fractions rather than on whichever doubles\n * they rounded to, so \"1/49 * 49 == 1\" is true and two distinct fractions that\n * share a nearest double still compare unequal. Returns null when either side\n * has no rational image, leaving the caller's ordinary double comparison in\n * place. The call sites gate on a rational actually being present first, so a\n * plain \"1 < 2\" never reaches here.\n */\nexport function compareRationalOperands(l: Value, r: Value): -1 | 0 | 1 | null {\n const lr = operandRational(l);\n if (lr === null) return null;\n const rr = operandRational(r);\n if (rr === null) return null;\n return rationalCompare(lr, rr);\n}\n\n/**\n * Apply a numeric binary operation with type-aware dispatch.\n * Handles BigInt, UoM, Vector, Symbolic, and plain Number operands.\n *\n * @param symbolicOp - which SymbolicNode kind to build when either operand\n * is Symbolic (`symbolic/SymbolicNode.ts`). Only ADD/SUB/MUL/DIV pass this (the\n * \"four arithmetic opcodes\" the symbolic-algebra phase scopes itself\n * to), MOD's own call site passes nothing, so a Symbolic operand there\n * falls through to the ordinary numeric path (`toNumber()` -> 0), an\n * explicit, disclosed scope boundary rather than an oversight.\n */\nexport function binaryOp(\n l: Value, r: Value,\n op: (a: number, b: number) => number,\n bigOp?: (a: bigint, b: bigint) => bigint,\n symbolicOp?: \"add\" | \"sub\" | \"mul\" | \"div\"\n): Value {\n // Error/Pending short-circuit, MUST run before any other branch.\n // Value.toNumber() returns 0 for both Error and Pending (see\n // vm/Value.ts), so without this check, every path below (including\n // the plain-number fast path two lines down) would silently treat an\n // errored or not-yet-resolved operand as the number 0, e.g. an\n // errored cross-line reference (`prev + 1` in packages/lines) would\n // quietly evaluate to 1 instead of surfacing the error. Propagate\n // Error/Pending operands as-is (left operand checked first, matching\n // left-to-right evaluation order) rather than manufacturing a new\n // error, so the original error code/message (or pending query key)\n // reaches the caller unchanged. Confirmed via ADD/SUB/MUL/DIV/MOD in\n // vm/VM.ts: none of their type-specific fast paths (Number/Boolean/\n // Datetime/Uom/Rate) match Error or Pending, so every one of them\n // already funnels here on those operand types.\n if (l.type === ValueType.Error) return l;\n if (r.type === ValueType.Error) return r;\n if (l.type === ValueType.Pending) return l;\n if (r.type === ValueType.Pending) return r;\n\n // Symbolic dispatch, either operand carries a free-variable formula.\n // Builds the corresponding SymbolicNode (the non-symbolic side, if\n // any, becomes a `const` node via its own numeric value), simplifies\n // it (symbolic/Simplify.ts's deliberately bounded rule set), and wraps the\n // result back as Symbolic. `symbolicOp` is undefined for opcodes that\n // don't support this (currently just MOD), those fall through to the\n // ordinary numeric path below unchanged.\n if (symbolicOp && (l.type === ValueType.Symbolic || r.type === ValueType.Symbolic)) {\n const left = valueToSymbolic(l);\n const right = valueToSymbolic(r);\n // An operand with no exact rational image (NaN, ±Infinity) used to be\n // folded in as a `const` built from a double, which either threw deep\n // inside the simplifier or produced a nonsense coefficient. Report it.\n if (left === null || right === null) {\n return errorValue(\n \"SYMBOLIC_NONFINITE_OPERAND\",\n \"A symbolic expression cannot combine with a value that has no exact number (NaN or infinity).\",\n );\n }\n const node: SymbolicNode = { kind: symbolicOp, left, right };\n return symbolicValue(simplifySymbolic(node));\n }\n\n // Fast path: both operands are plain numbers, skip all type checks.\n // This is the overwhelmingly common case (90%+ of all binary ops).\n // Inlined arithmetic avoids the overhead of helper function dispatch,\n // UoM unification, Vector iteration, BigInt conversion, and NaN guards.\n if (l.type === ValueType.Number && r.type === ValueType.Number) {\n return numberValue(op(l.value as number, r.value as number));\n }\n\n if (l.type === ValueType.BigInt || r.type === ValueType.BigInt) {\n // Read an already-BigInt operand's raw bigint directly. See\n // toBigIntOperand() above for why, and for the other opcodes that\n // share it.\n const lb = toBigIntOperand(l);\n const rb = toBigIntOperand(r);\n if (bigOp) return bigIntValue(bigOp(lb, rb));\n return bigIntValue(lb + rb);\n }\n\n if (l.type === ValueType.Uom || r.type === ValueType.Uom) {\n // Money in the same currency (or money against a plain scalar) is exact:\n // \"$0.10 + $0.20\" is \"$0.30\", not the double's \"$0.30000000000000004\".\n // Only the four arithmetic ops carry an `op` kind (MOD passes none), and\n // only currencies set the sidecar, so everything else falls straight\n // through to the float unification below unchanged.\n if (symbolicOp) {\n const exactMoney = exactMoneyOp(l, r, symbolicOp);\n if (exactMoney) return exactMoney;\n }\n const { lv, rv, unit, sameMeasure } = unifyUom(l, r);\n // NaN is deliberately NOT intercepted here. A guard used to answer a\n // bare, unitless 0 for it, which turned an operand that means \"no\n // answer\" into a confident one and threw the unit away as well:\n // `(1 kg / 0 * 0) + 1 kg` reported 0 rather than NaN kg. NaN\n // propagates through the arithmetic below exactly as it does for\n // plain numbers, and the comparison opcodes already report false\n // against it, which is how a caller detects it.\n if (!sameMeasure) {\n // unifyUom couldn't reconcile the two units, either they're\n // genuinely incompatible measures (meters + kilograms), or\n // they're both currencies but no rate was available yet.\n // Silently combining the raw magnitudes here used to produce a\n // confidently-wrong, unitless number (e.g. \"0.01 BTC + 1 ETH\"\n // → a bare \"1.01\", the naive 0.01+1 sum with the currency\n // context just dropped) instead of surfacing the failure\n // mirrors the existing UOM_CONVERT_TO/_IN error path in VM.ts.\n const lUnit = l.type === ValueType.Uom ? l.unit : undefined;\n const rUnit = r.type === ValueType.Uom ? r.unit : undefined;\n // Name the two dimensions when they genuinely differ (\"mass and\n // length cannot be added\"). Two currencies with no cached rate reach\n // here too, and share the money dimension, so there is nothing to\n // contrast: describeMeasureMismatch returns undefined and the\n // unit-naming fallback below keeps the \"BTC and ETH\" form.\n const named = describeMeasureMismatch(lUnit, rUnit, combineVerb(symbolicOp));\n return errorValue(\"INCOMPATIBLE_UNITS\", named ?? `Cannot combine incompatible units: ${lUnit ?? \"?\"} and ${rUnit ?? \"?\"}`);\n }\n return uomValue(op(lv, rv), unit!);\n }\n\n // Element-wise Matrix dispatch (ADD/SUB/DIV/MOD land here; MUL's real\n // scalar-vs-matrix-product disambiguation happens in VM.ts's own MUL\n // case BEFORE falling through to binaryOp() at all, so this generic\n // path only ever needs to handle the always-element-wise ops).\n if (l.type === ValueType.Matrix && r.type === ValueType.Matrix) {\n const lm = l.value as MatrixData;\n const rm = r.value as MatrixData;\n if (!sameShape(lm, rm)) {\n // Silently truncating/broadcasting a shape mismatch used to\n // drop components with no indication (the old flat-Array\n // Math.min() truncation bug), surface it instead.\n return errorValue(\"DIMENSION_MISMATCH\", `Cannot combine matrices of different shapes: ${lm.rows}x${lm.cols} and ${rm.rows}x${rm.cols}`);\n }\n const result: MatrixEntry[] = new Array(lm.data.length);\n for (let i = 0; i < lm.data.length; i++) result[i] = op(lm.data[i] as number, rm.data[i] as number);\n return matrixValue(lm.rows, lm.cols, result);\n }\n\n if (l.type === ValueType.Matrix) {\n // Scalar broadcast: [1,2,3]/10 => [0.1,0.2,0.3], preserves shape.\n const lm = l.value as MatrixData;\n const scalar = r.toNumber();\n const result: MatrixEntry[] = lm.data.map(v => op(v as number, scalar));\n return matrixValue(lm.rows, lm.cols, result);\n }\n\n if (r.type === ValueType.Matrix) {\n const rm = r.value as MatrixData;\n const scalar = l.toNumber();\n const result: MatrixEntry[] = rm.data.map(v => op(scalar, v as number));\n return matrixValue(rm.rows, rm.cols, result);\n }\n\n // No NaN guard here either, for the reason given in the Uom branch above:\n // an operand that is NaN has to stay NaN rather than become a zero nobody\n // can tell apart from a real one.\n return numberValue(op(l.toNumber(), r.toNumber()));\n}\n","import type { Value } from \"@solve-js/vm/Value\";\nimport type { BytecodeProgram, UserFunctionDef } from \"@solve-js/parser/BytecodeBuilder\";\nimport type { EngineContext } from \"@solve-js/engine/EngineContext\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * A stored bare (colon-less) equation of the shape `factor1*factor2*...*\n * variable = rhs` (e.g. `a*x = [60;70]`, or `s*t*v = [vx;vy;1]`)\n * registered when that line is EXECUTED (mirroring `UserFunctionDef`'s own\n * execution-time registration, not parse-time), and consulted when\n * `<variable> =>` is later evaluated. Solving is `variable =\n * inv(factor1*factor2*...) * rhs` (`vm/VM.ts`'s THEREFORE-handling code,\n * `vm/MatrixOps.ts`'s `matrixMultiply()`/`inverse()`, both symbolic-aware\n * so a factor whose OWN cells are still-unassigned free variables, e.g.\n * `s = [sx,0,0;...]`, solves correctly too).\n *\n * `factorNames` are looked up via `vm.getVar()` at solve time (ordinary,\n * ALREADY-evaluated Matrix values, ordinary (\"bare\") assignment always\n * evaluates its RHS eagerly, even when that RHS itself contains\n * unassigned names, via symbolic-tolerant evaluation, so by solve time\n * each factor is already a genuine, possibly-partially-symbolic Matrix\n * Value sitting in the variable store), NOT re-compiled bytecode, since\n * this pattern only ever allows bare identifiers as factors (see\n * `ExpressionEngine.ts`'s own equation-detection doc comment for why this\n * stays a narrow, disclosed pattern rather than a general expression).\n * `rhsProgram` IS a real compiled program (the right-hand side can be an\n * arbitrary expression, e.g. `[vx;vy;1]`), evaluated in symbolic-tolerant\n * mode at solve time.\n */\nexport interface EquationDef {\n\tvariable: string;\n\tfactorNames: string[];\n\trhsProgram: BytecodeProgram;\n}\n\n/**\n * A stored scalar equation, the general `x^2 - 4 = 0` shape, kept separate from\n * {@link EquationDef} rather than merged into it.\n *\n * The two are genuinely different problems solved by different machinery.\n * {@link EquationDef} is a product chain of matrix factors solved by inverting\n * their product; this is an arbitrary polynomial in one unknown solved by\n * `symbolic/Solve.ts`. Merging them into one optional-field type would mean\n * every consumer branching on which half is populated, and would put the older,\n * already-shipped matrix path at risk of being changed by accident.\n *\n * Both sides are compiled programs rather than pre-evaluated values, because\n * neither side can be evaluated until solve time: they contain the very unknown\n * being solved for.\n */\nexport interface ScalarEquationDef {\n\t/** The unknown this equation is keyed by and will be solved for. */\n\tvariable: string;\n\t/** Compiled left-hand side, evaluated symbolic-tolerantly at solve time. */\n\tlhsProgram: BytecodeProgram;\n\t/** Compiled right-hand side, likewise. */\n\trhsProgram: BytecodeProgram;\n}\n\n/**\n * Handler function for plugin-registered opcodes via CALL_PLUGIN (opcode 50).\n * No longer dispatched directly from the VM switch, plugins register\n * functions in pluginFunctionRegistry instead.\n *\n * @deprecated Use CALL_PLUGIN + pluginFunctionRegistry for plugin functionality.\n * OpRegistry remains for the VM interface contract only.\n */\nexport type OpcodeHandler = (vm: VM, opcodes: Uint8Array, ip: number, numbers: Float64Array, strings: string[]) => number;\n\n/** Registration payload for an opcode handler. Binds an OpCode to its handler function with plugin attribution. */\nexport interface IOpcodeHandlerRegistration {\n\topcode: number;\n\thandler: OpcodeHandler;\n\tpluginName: string;\n}\n\n/** Maximum safe opcode value for Uint8Array storage. */\nconst MAX_OPCODE = 254;\n\n/** Starting point for dynamic opcode allocation. */\nconst DYNAMIC_OPCODE_START = 200;\n\n/**\n * Legacy opcode registry, retained for the VM interface contract.\n *\n * Previously dispatched custom opcodes (>= 200) from the VM switch-default\n * branch. Now plugins should use CALL_PLUGIN (opcode 50) via\n * pluginFunctionRegistry instead.\n */\nexport class OpRegistry {\n\tprivate handlers = new Map<number, OpcodeHandler>();\n\tprivate nextOpcode = DYNAMIC_OPCODE_START + 1;\n\n\tregister(registration: IOpcodeHandlerRegistration): void {\n\t\tthis.handlers.set(registration.opcode, registration.handler);\n\t}\n\n\t/**\n\t * Remove a previously registered opcode handler.\n\t * Used by package unregistration to reverse shared-registry contributions.\n\t */\n\tunregister(opcode: number): void {\n\t\tthis.handlers.delete(opcode);\n\t}\n\n\tget(opcode: number): OpcodeHandler | undefined {\n\t\treturn this.handlers.get(opcode);\n\t}\n\n\thas(opcode: number): boolean {\n\t\treturn this.handlers.has(opcode);\n\t}\n\n\t/**\n\t * Allocate a unique opcode for a plugin's custom bytecode handler.\n\t *\n\t * Returns the next available opcode (starting at 201). Each call\n\t * returns a distinct value. Plugins should call this once during\n\t * registration and store the result.\n\t *\n\t * @throws If the dynamic opcode pool is exhausted.\n\t * @returns A unique opcode number for the calling plugin.\n\t */\n\tallocateOpcode(): number {\n\t\tif (this.nextOpcode > MAX_OPCODE) {\n\t\t\tthrow ErrorFactory.config(\n\t\t\t\t\"OPCODE_POOL_EXHAUSTED\",\n\t\t\t\t`OpRegistry: dynamic opcode pool exhausted (max ${MAX_OPCODE - DYNAMIC_OPCODE_START} allocations).`\n\t\t\t);\n\t\t}\n\t\treturn this.nextOpcode++;\n\t}\n\n}\n\n/**\n * VM interface consumed by opcode handlers and the bytecode executor.\n *\n * Provides stack operations, variable access, instruction counting,\n * and abort signal management for async cancellation.\n */\nexport interface VM {\n\tpush(value: Value): void;\n\tpop(): Value;\n\t/**\n\t * Pop the top of the stack as a number.\n\t *\n\t * @throws `STACK_UNDERFLOW` (INTERNAL) if the stack is empty. Unlike\n\t * `pop()`, which answers an empty stack with `0`, this reports it: a\n\t * handler asking for a number has no way to tell that `0` from a real\n\t * one. Every Value converts, so there is no operand-type throw here.\n\t */\n\tpopNumber(): number;\n\t/**\n\t * Pop the top of the stack as a string, e.g. a unit name a handler's own\n\t * bytecode pushed for it to read.\n\t *\n\t * @throws `STACK_UNDERFLOW` (INTERNAL) if the stack is empty, and\n\t * `MALFORMED_BYTECODE_OPERAND_TYPE` (VALIDATION, recoverable) if the\n\t * value on top is not a string. Both are structured `EngineError`s\n\t * naming this method, in place of the raw TypeError a bare `pop()!` and\n\t * a compile-time-only cast used to produce somewhere further along. A\n\t * handler that would rather branch than throw can `peek()` first.\n\t */\n\tpopString(): string;\n\tpeek(): Value;\n\tgetStack(): Value[];\n\tregistry: OpRegistry;\n\t/**\n\t * Read a variable by name, checks the INNERMOST active user-defined-\n\t * function call frame first (see `pushCallFrame`), then falls back to\n\t * the flat, session-scoped variable store. This is why a function\n\t * parameter needs no dedicated load opcode: an ordinary `LOAD_VAR\n\t * \"x\"` inside a function body resolves to the current call's bound\n\t * argument automatically, without the parser needing to know it's\n\t * compiling a function body at all.\n\t */\n\tgetVar(key: string): Value | undefined;\n\tsetVar(key: string, value: Value): void;\n\t/**\n\t * Remove a top-level variable binding. Used at the start of each document\n\t * pass to re-seed accumulators (`total += 5`): a running total must reset\n\t * to its seed each full re-parse, otherwise it reads its own previous\n\t * pass's value and grows without bound on every keystroke.\n\t */\n\tdeleteVar(key: string): void;\n\t/**\n\t * User-defined-function call frame, a name-keyed `Map` of this call's\n\t * bound arguments, PUSHED before `CALL_USER_FUNCTION` executes the\n\t * callee's body and POPPED immediately after (even if the body throws),\n\t * so nested/recursive calls (`double(double(5))`) each get their own\n\t * frame instead of clobbering a shared flat map. See `vm/VM.ts`'s\n\t * `CALL_USER_FUNCTION` case. Deliberately NOT the same store as\n\t * `setVar`'s flat `:name` variables, a call frame is call-scoped and\n\t * stacked (only the INNERMOST frame is ever consulted by `getVar`, see\n\t * its own doc comment, no lexical capture of an outer call's\n\t * parameters), a variable is session-scoped and flat.\n\t *\n\t * @throws `FUNCTION_RECURSION_LIMIT_EXCEEDED` if pushing would exceed\n\t * the VM's configured `maxFunctionRecursionDepth`, the backstop for\n\t * `f(x) = f(x)`, which would otherwise recurse via nested\n\t * `executeBytecode()` calls until the native V8 stack overflows\n\t * uncatchably (each reentrant call gets its OWN fresh\n\t * `localInstructionCount`, so `maxInstructions` cannot catch this).\n\t */\n\tpushCallFrame(frame: Map<string, Value>): void;\n\tpopCallFrame(): void;\n\t/** Register (or redefine, overwrites any previous definition, matching `:name = value`'s own reassignment semantics) a user-defined function. */\n\tdefineUserFunction(name: string, params: string[], program: BytecodeProgram): void;\n\tgetUserFunction(name: string): UserFunctionDef | undefined;\n\thasUserFunction(name: string): boolean;\n\t/**\n\t * Every session-scoped variable currently defined, as `[name, value]` pairs,\n\t * for snapshotting the VM's state (see `engine/EngineSnapshot.ts`). The\n\t * returned array is a fresh copy, so mutating it does not touch the store,\n\t * and it reads the flat document-variable table only, never a transient\n\t * user-function call frame (those are call-scoped and gone by the time any\n\t * snapshot is taken).\n\t */\n\tgetVariableEntries(): [string, Value][];\n\t/** Every user-defined function currently defined, as a fresh array copy, for snapshotting (see {@link getVariableEntries}). */\n\tgetUserFunctionDefs(): UserFunctionDef[];\n\t/** Register (or redefine) a bare equation (`a*x = rhs`), keyed by its free variable. See {@link EquationDef}. */\n\tdefineEquation(variable: string, factorNames: string[], rhsProgram: BytecodeProgram): void;\n\tgetEquation(variable: string): EquationDef | undefined;\n\thasEquation(variable: string): boolean;\n\t/** Register (or redefine) a stored scalar equation (`x^2-4 = 0`), keyed by its unknown. See {@link ScalarEquationDef}. */\n\tdefineScalarEquation(variable: string, lhsProgram: BytecodeProgram, rhsProgram: BytecodeProgram): void;\n\tgetScalarEquation(variable: string): ScalarEquationDef | undefined;\n\thasScalarEquation(variable: string): boolean;\n\treset(): void;\n\t/** The innermost call frame's bindings, or `undefined` when no call is in progress. Read-only, for building a frame that extends the current one rather than replacing it (see `BIND_UNKNOWN`'s handler). */\n\tgetCallFrame(): ReadonlyMap<string, Value> | undefined;\n\tgetMaxInstructions(): number;\n\tgetMaxStackDepth(): number;\n\t/** Maximum elements a Range or Matrix may be expanded to by `map`/`reduce`. See `constants/Configuration.ts`'s `maxCollectionSize`. */\n\tgetMaxCollectionSize(): number;\n\t/**\n\t * Maximum elements (collection Values, matrix cells) one evaluation may\n\t * materialise in total.\n\t *\n\t * The bound the two limits above cannot be. Both are checked between\n\t * opcodes, so neither sees what one opcode allocates inside a loop of its\n\t * own, and `getMaxCollectionSize()` bounds one collection without bounding\n\t * the total. See `vm/AllocationBudget.ts` for the counter this configures\n\t * and for why charging goes through that module rather than through the VM.\n\t */\n\tgetMaxAllocatedElements(): number;\n\t/**\n\t * Maximum user-defined-function calls one evaluation may make in total.\n\t *\n\t * `maxFunctionRecursionDepth` (see `pushCallFrame` above) bounds how DEEP\n\t * calls nest; this bounds how MANY there are, which is a different number\n\t * and the one a doubling chain runs away with: twenty-two lines of\n\t * `f(v) = g(v) + g(v)` reach two million calls at a depth of twenty-two.\n\t * Held by `vm/AllocationBudget.ts` rather than counted here, because it has\n\t * to survive `executeBytecode()` re-entering itself, exactly like the\n\t * element tally and unlike `maxInstructions`.\n\t */\n\tgetMaxFunctionCalls(): number;\n\t/** How far forward `<date> + N workdays` may reach, in years. The one date offset that walks the calendar rather than computing, so the one with a ceiling. See `constants/Configuration.ts`'s `date.maxOffsetYears`. */\n\tgetMaxDateOffsetYears(): number;\n\t/** The same bound backwards, as a negative number of years. */\n\tgetMinDateOffsetYears(): number;\n\t/** Whether the host's public-holiday calendar marks `epochMs` a holiday, for working-day arithmetic. Always `false` when no calendar is configured (weekends-only). Set from `constants/Configuration.ts`'s `date.holidays`; see `vm/HolidayCalendar.ts`. */\n\tisHoliday(epochMs: number): boolean;\n\tgetInstructionCount(): number;\n\tincrementInstructions(n: number): void;\n\t/** Active AbortSignal for the current expression evaluation. Checked before cache writes. */\n\tactiveSignal?: AbortSignal;\n\t/** Abort the current evaluation (called when expression changes before resolution). */\n\tabortCurrent?: () => void;\n\t/**\n\t * Registries belonging to the engine that created this VM.\n\t *\n\t * `CALL_PLUGIN` resolves handlers through here rather than through a\n\t * module-level registry, so two engines in one process no longer share the\n\t * plugin functions their packages registered. This follows what\n\t * `userFunctions` and `equations` already do by being VM-instance scoped.\n\t */\n\tcontext: EngineContext;\n}\n\n/** Shared singleton OpRegistry, used when no custom opcodes are needed. */\nexport const sharedOpRegistry = new OpRegistry();\n","/**\n * Exact-decimal scaling for money, shared by the percentage operators (`VM.ts`)\n * and the tax builtins (`VMBuiltins.ts`).\n *\n * A price is a decimal, not a binary fraction, so `$X * factor` has to be formed\n * in base ten. Computed as a float it lands a hair below the true value and the\n * half-cent then rounds the wrong way: `$0.10 * 1.15` is `0.1149999...`, which a\n * till reads as `$0.12` but a double rounds down to `$0.11`. These helpers\n * recover the exact decimals of the amount and the factor, multiply them\n * exactly, and hand back a value carrying the exact sidecar; they fall back to\n * the float path only where an operand has no exact value, so nothing that was\n * exact before loses exactness.\n */\n\nimport { Value, uomValue, uomValueExact, type SplitData, type SplitShare } from \"@solve-js/vm/Value\";\nimport {\n\tdecimalFromLiteral,\n\tdecimalFromInteger,\n\tdecimalFromNumberIfExact,\n\tdecimalNegate,\n\tdecimalToNumber,\n\tdecimalAdd,\n\tdecimalSubtract,\n\tdecimalMultiply,\n\tdecimalDivide,\n\tdecimalIsZero,\n\tdecimalRound,\n\tmakeDecimal,\n\ttype DecimalData,\n} from \"@solve-js/decimal\";\nimport { sharedCurrencyExchange } from \"@solve-js/uom/CurrencyExchange\";\n\n/** Exact base-ten `1`, the constant term in a `1 + p%` scaling factor. */\nconst ONE_DECIMAL: DecimalData = decimalFromInteger(1);\n\n/**\n * The exact decimal a currency amount should carry, or null when it has none.\n *\n * Gated on the unit being a currency, so the exact-decimal machinery is money's\n * and money's alone in this slice, every other Uom (km, kg, minutes) is left\n * exactly as it was. The amount's exact value is either the sidecar a decimal\n * literal already set, or, for a whole-number amount, the integer itself. A\n * fractional double with no sidecar (`$sqrt(2)`, `$ (1/3) `) returns null and\n * stays a float, which is the deliberate boundary: exactness only where an\n * exact value actually exists.\n */\nexport function moneyExactMagnitude(operand: Value, unit: string): DecimalData | null {\n\tif (!sharedCurrencyExchange.isCurrency(unit)) return null;\n\treturn operand.exact ?? decimalFromNumberIfExact(operand.toNumber());\n}\n\n/**\n * The exact base-ten value of a number that is exactly a short decimal (the\n * proportion a percentage the user typed reduces to, e.g. `15%` -> `0.15`), via\n * its shortest round-tripping string, or null for a value that is not (a computed\n * irrational, or scientific-notation extreme). Wider than\n * {@link decimalFromNumberIfExact} (integers only), and used only to recover a\n * percentage's intended decimal, where the printed proportion is the meaning.\n */\nexport function decimalFromShortDecimal(n: number): DecimalData | null {\n\tif (!Number.isFinite(n)) return null;\n\tif (Number.isInteger(n)) return decimalFromInteger(BigInt(n));\n\tconst s = String(n);\n\tif (!/^-?\\d+\\.\\d+$/.test(s)) return null;\n\treturn decimalFromLiteral(s);\n}\n\n/**\n * Scale a money amount by a bare factor, keeping it exact.\n *\n * `tax on $X at R%` is `$X * R`, and money multiplication is exact wherever the\n * inputs are, so `tax on $10.10 at 15%` is `$1.515 -> $1.52`, not the `$1.51` a\n * bare double (`10.10 * 0.15 = 1.5149999...`) rounds down to. The factor is\n * recovered from its shortest decimal, the proportion the rate was typed as.\n * Falls back to the float path only when an operand has no exact value (the same\n * boundary {@link moneyExactMagnitude} draws), so nothing that was exact before\n * loses exactness, and a non-currency unit passes straight through it unchanged.\n */\nexport function scaleMoneyExact(amount: Value, factor: number, unit: string): Value {\n\tconst base = moneyExactMagnitude(amount, unit);\n\tconst factorDecimal = decimalFromShortDecimal(factor);\n\tif (base !== null && factorDecimal !== null) {\n\t\tconst result = decimalMultiply(base, factorDecimal);\n\t\treturn uomValueExact(decimalToNumber(result), unit, result);\n\t}\n\treturn uomValue(amount.toNumber() * factor, unit);\n}\n\n/**\n * Scale a money amount by `1 + sign * percent`, keeping it exact.\n *\n * `$X + p%` is `$X * (1 + p%)`, and money multiplication is exact wherever the\n * inputs are, so the till answer for `$0.10 + 15%` is `$0.115 -> $0.12`, not the\n * `$0.11` a bare double (`0.10 * 1.15 = 0.1149999...`) rounds down to. The\n * one-plus-percent factor is formed in base ten so no double drift creeps in.\n * Falls back to the float path only when an operand has no exact value (the same\n * boundary {@link moneyExactMagnitude} draws), so nothing that was exact before\n * loses exactness.\n */\nexport function scaleMoneyByPercent(money: Value, unit: string, percent: number, sign: 1 | -1): Value {\n\tconst base = moneyExactMagnitude(money, unit);\n\tconst percentDecimal = decimalFromShortDecimal(percent);\n\tif (base !== null && percentDecimal !== null) {\n\t\tconst factor = decimalAdd(ONE_DECIMAL, sign === 1 ? percentDecimal : decimalNegate(percentDecimal));\n\t\tconst result = decimalMultiply(base, factor);\n\t\treturn uomValueExact(decimalToNumber(result), unit, result);\n\t}\n\treturn uomValue(money.toNumber() * (1 + sign * percent), unit);\n}\n\n/**\n * The exact base-ten `1 + rate` divisor of a tax-inclusive total, or null when\n * the rate has no short decimal. Formed in base ten (not as the double `1 +\n * rate`) so the tax-inclusive divisor carries no drift, the same reason\n * {@link scaleMoneyByPercent} builds its factor this way.\n */\nfunction onePlusRateDecimal(rate: number): DecimalData | null {\n\tconst rateDecimal = decimalFromShortDecimal(rate);\n\treturn rateDecimal === null ? null : decimalAdd(ONE_DECIMAL, rateDecimal);\n}\n\n/**\n * `$X / (1 + rate)`, the pre-tax amount inside a tax-inclusive total, kept exact.\n *\n * `tax off $0.09 at 20%` is `$0.09 / 1.2 = $0.075`, which the half-cent rule\n * rounds to `$0.08`, not the `$0.07` a bare double (`0.09 / 1.2 = 0.0749999...`)\n * rounds down to. {@link decimalDivide} carries the quotient exactly where it\n * terminates (the cases that can land on a half-cent, at 20%/25%/50%) and rounds\n * it far below the cent where it does not, so the displayed cent is right either\n * way. Falls back (returns null) only when an operand has no exact value or the\n * divisor is zero, leaving the caller's float path, the same boundary the other\n * MoneyExact helpers draw.\n */\nexport function removeTaxExact(money: Value, unit: string, rate: number): Value | null {\n\tconst base = moneyExactMagnitude(money, unit);\n\tconst divisor = onePlusRateDecimal(rate);\n\tif (base === null || divisor === null || decimalIsZero(divisor)) return null;\n\tconst quotient = decimalDivide(base, divisor);\n\treturn uomValueExact(decimalToNumber(quotient), unit, quotient);\n}\n\n/**\n * `$X - $X / (1 + rate)`, the tax already inside a tax-inclusive total, kept\n * exact. The complement of {@link removeTaxExact}: the two sum back to `$X`.\n *\n * `tax in $0.09 at 20%` is `$0.09 - $0.075 = $0.015`, which rounds to `$0.02`,\n * not the `$0.01` the drifted double rounds down to. The subtraction is done in\n * base ten so the tax and the net a matching `tax off` reports stay consistent.\n */\nexport function taxInExact(money: Value, unit: string, rate: number): Value | null {\n\tconst base = moneyExactMagnitude(money, unit);\n\tconst divisor = onePlusRateDecimal(rate);\n\tif (base === null || divisor === null || decimalIsZero(divisor)) return null;\n\tconst tax = decimalSubtract(base, decimalDivide(base, divisor));\n\treturn uomValueExact(decimalToNumber(tax), unit, tax);\n}\n\n/**\n * Allocate a bill split into whole-cent shares that add back to the exact\n * total. `split $100 between 3` is $33.34 once and $33.33 twice: 2 × $33.33 +\n * 1 × $33.34 is $100.00 to the cent, not the bare $33.33 each that loses a\n * penny. Largest-remainder allocation on the amount's exact decimal cents, so\n * the reconciliation is exact wherever the amount is (a money literal, or a\n * percentage-scaled one like `$120 + 18%`). A non-currency amount (a bare\n * number, or a unit such as km) divides evenly into a single share, carrying\n * its unit for display; money with no exact magnitude (a live-rate conversion)\n * falls back to a float even split, the same boundary the other helpers draw.\n *\n * `n` is assumed a positive integer, the split builtin validates it first.\n * Shares are ordered base-first: the \"each\" amount, then, on an uneven split,\n * the slightly larger amount the odd penny falls on.\n */\nexport function splitEachExact(amount: Value, n: number): SplitData {\n\tconst unit = amount.unit;\n\tconst cents = unit !== undefined && sharedCurrencyExchange.isCurrency(unit)\n\t\t? centsOfMoney(amount, unit)\n\t\t: null;\n\tif (cents === null) {\n\t\treturn { unit, shares: [{ value: amount.toNumber() / n, count: n }] };\n\t}\n\n\tconst divisor = BigInt(n);\n\tconst baseCents = cents / divisor; // truncates toward zero\n\tconst remainder = cents - baseCents * divisor; // sign follows `cents`\n\tconst extraShares = Number(remainder < 0n ? -remainder : remainder);\n\t// A refund (negative total) puts the extra cent on the more-negative share.\n\tconst step = cents < 0n ? -1n : 1n;\n\n\tconst base = centShare(baseCents, n - extraShares);\n\tif (extraShares === 0) return { unit, shares: [base] };\n\treturn { unit, shares: [base, centShare(baseCents + step, extraShares)] };\n}\n\n/** A currency share built from its whole-cent coefficient. */\nfunction centShare(cents: bigint, count: number): SplitShare {\n\tconst exact = makeDecimal(cents, 2);\n\treturn { value: decimalToNumber(exact), exact, count };\n}\n\n/**\n * The exact whole-cent coefficient of a money amount, or null when it has no\n * exact magnitude (a live-rate conversion), so the caller falls back to a float\n * even split. Rounds to two places half-away-from-zero, the till rule the rest\n * of the money arithmetic uses.\n */\nfunction centsOfMoney(amount: Value, unit: string): bigint | null {\n\tconst base = moneyExactMagnitude(amount, unit);\n\treturn base === null ? null : decimalRound(base, 2).coef;\n}\n","/**\n * Partial-fraction decomposition of a rational function.\n *\n * `(3x+5)/(x^2-1)` becomes `4/(x-1) - 1/(x+1)`. Two quite different things want\n * this. A person reading a rational function wants to see what it is made of,\n * and the integrator needs it, because a rational function has no general\n * antiderivative rule but every one of these pieces does.\n *\n * ## How the coefficients are found\n *\n * By undetermined coefficients, solved as an exact linear system. The\n * alternative, the cover-up or residue method, is shorter but only handles\n * distinct linear factors directly and needs separate machinery for repeated\n * factors and irreducible quadratics. One linear solve covers all three, and\n * over exact rationals it is answering a question with a definite answer rather\n * than converging on one.\n *\n * ## The one thing it inherits\n *\n * Decomposition is only as fine as the factorization behind it. `Factor.ts`\n * finds rational roots, so it splits off every linear factor, but it does not\n * split a quartic into two irreducible quadratics. When that happens the\n * quartic stays as one denominator with a cubic numerator over it. The result\n * is still correct, just less decomposed than a textbook would write it, and\n * `Integral.ts` then declines rather than guessing.\n */\n\nimport { type SymbolicNode, constNode, powNode } from \"@solve-js/symbolic/SymbolicNode\";\nimport {\n\ttype Rational,\n\tRATIONAL_ZERO,\n\tRATIONAL_ONE,\n\trationalAdd,\n\trationalSub,\n\trationalMul,\n\trationalDiv,\n\trationalNeg,\n\tisRationalZero,\n} from \"@solve-js/symbolic/Rational\";\nimport { toPolynomial, fromPolynomial, polyCoefficients, polyUnivariateVar } from \"@solve-js/symbolic/Polynomial\";\nimport { polynomialDivide, coefficientGcd, isZeroPolynomial } from \"@solve-js/symbolic/Gcd\";\nimport { factorUnivariate } from \"@solve-js/symbolic/Factor\";\nimport { simplifySymbolic } from \"@solve-js/symbolic/Simplify\";\n\n/**\n * Highest denominator degree {@link partialFractions} will decompose.\n *\n * The linear system is one unknown per degree, so the solve is cubic in this\n * number. Twelve keeps a pathological input from turning into a long exact\n * elimination, and matches the degree ceiling factoring already works under.\n */\nexport const APART_MAX_DEGREE = 12;\n\n/** One `numerator / base^power` piece of a decomposition. */\nexport interface PartialFractionTerm {\n\t/** Ascending coefficients of the numerator, of lower degree than the base. */\n\treadonly numerator: readonly Rational[];\n\t/** Ascending coefficients of the irreducible denominator factor, monic. */\n\treadonly base: readonly Rational[];\n\t/** Which power of the base this piece sits over, counting from one. */\n\treadonly power: number;\n}\n\n/** A rational function written as a polynomial plus a sum of simple fractions. */\nexport interface PartialFractionDecomposition {\n\t/** Ascending coefficients of the polynomial part, empty when the fraction was already proper. */\n\treadonly polynomial: readonly Rational[];\n\t/** The fraction pieces, in the order the denominator's factors were found. */\n\treadonly terms: readonly PartialFractionTerm[];\n}\n\n/** Multiplies two ascending coefficient lists. */\nfunction multiply(a: readonly Rational[], b: readonly Rational[]): Rational[] {\n\tif (a.length === 0 || b.length === 0) return [];\n\tconst product: Rational[] = new Array(a.length + b.length - 1).fill(RATIONAL_ZERO);\n\ta.forEach((left, i) => {\n\t\tb.forEach((right, j) => {\n\t\t\tproduct[i + j] = rationalAdd(product[i + j], rationalMul(left, right));\n\t\t});\n\t});\n\treturn product;\n}\n\n/** Raises an ascending coefficient list to a non-negative integer power. */\nfunction power(base: readonly Rational[], exponent: number): Rational[] {\n\tlet result: Rational[] = [RATIONAL_ONE];\n\tfor (let i = 0; i < exponent; i++) result = multiply(result, base);\n\treturn result;\n}\n\n/** Scales an ascending coefficient list. */\nfunction scale(coefficients: readonly Rational[], factor: Rational): Rational[] {\n\treturn coefficients.map(coefficient => rationalDiv(coefficient, factor));\n}\n\n/**\n * The irreducible factors of a monic denominator, as ascending coefficient\n * lists with multiplicity.\n *\n * Routed through {@link factorUnivariate} rather than repeating its rational\n * root search, at the cost of a round trip through the expression tree.\n *\n * The one thing done here first is pulling out the powers of the variable\n * itself. The rational-root theorem needs a non-zero constant term to have any\n * candidates at all, so `x^3-x` comes back from {@link factorUnivariate}\n * unfactored, and a decomposition over `1/(x^3-x)` would then be no\n * decomposition. `factorSymbolic` extracts the common monomial before calling\n * it for the same reason.\n *\n * @param ascending - Ascending coefficients of the monic denominator.\n * @param variable - The variable it is written in.\n * @returns The factors, or `null` when one cannot be read back as a polynomial.\n */\nfunction denominatorFactors(\n\tascending: readonly Rational[],\n\tvariable: string,\n): { base: Rational[]; power: number }[] | null {\n\tconst factors: { base: Rational[]; power: number }[] = [];\n\n\tlet lowest = 0;\n\twhile (lowest < ascending.length && isRationalZero(ascending[lowest])) lowest++;\n\tif (lowest > 0) factors.push({ base: [RATIONAL_ZERO, RATIONAL_ONE], power: lowest });\n\n\tconst remaining = ascending.slice(lowest);\n\tif (remaining.length > 1) {\n\t\tconst factorization = factorUnivariate([...remaining].reverse(), variable);\n\t\tfor (const factor of factorization.factors) {\n\t\t\tconst polynomial = toPolynomial(factor.base);\n\t\t\tif (polynomial === null) return null;\n\t\t\tfactors.push({ base: [...polyCoefficients(polynomial, variable)], power: factor.power });\n\t\t}\n\t}\n\treturn factors.length > 0 ? factors : null;\n}\n\n/** One unknown in the linear system: which factor, which power of it, and which coefficient of that numerator. */\ninterface Unknown {\n\treadonly factor: number;\n\treadonly power: number;\n\treadonly degree: number;\n}\n\n/**\n * Enumerates the unknowns a decomposition needs.\n *\n * A factor of degree `d` appearing to the power `m` contributes `m` numerators\n * of degree below `d`, so `m*d` unknowns. Summed over the factorization that is\n * exactly the degree of the denominator, which is why the system below is\n * square.\n */\nfunction enumerateUnknowns(factors: readonly { base: Rational[]; power: number }[]): Unknown[] {\n\tconst unknowns: Unknown[] = [];\n\tfactors.forEach((factor, index) => {\n\t\tconst factorDegree = factor.base.length - 1;\n\t\tfor (let p = 1; p <= factor.power; p++) {\n\t\t\tfor (let degree = 0; degree < factorDegree; degree++) {\n\t\t\t\tunknowns.push({ factor: index, power: p, degree });\n\t\t\t}\n\t\t}\n\t});\n\treturn unknowns;\n}\n\n/**\n * The polynomial each unknown multiplies once the identity is cleared of\n * denominators.\n *\n * Multiplying `N/(f^p)` by the whole denominator leaves `N` times everything\n * except `f^p`, so the column for the coefficient of `x^k` in `N` is `x^k`\n * times that cofactor.\n */\nfunction unknownColumn(\n\tunknown: Unknown,\n\tfactors: readonly { base: Rational[]; power: number }[],\n\tdenominator: readonly Rational[],\n): Rational[] | null {\n\tconst divisor = power(factors[unknown.factor].base, unknown.power);\n\tconst { quotient, remainder } = polynomialDivide(denominator, divisor);\n\t// The divisor is a factor of the denominator by construction, so a remainder\n\t// here would mean the factorization did not multiply back and the answer\n\t// would be silently wrong.\n\tif (!isZeroPolynomial(remainder)) return null;\n\n\tconst shift: Rational[] = new Array(unknown.degree).fill(RATIONAL_ZERO);\n\tshift.push(RATIONAL_ONE);\n\treturn multiply(quotient, shift);\n}\n\n/**\n * Solves a square linear system over the rationals by Gaussian elimination.\n *\n * @param matrix - Row-major coefficients, modified in place.\n * @param target - The right-hand side, modified in place.\n * @returns The solution, or `null` when the system is singular.\n */\nfunction solveLinearSystem(matrix: Rational[][], target: Rational[]): Rational[] | null {\n\tconst size = target.length;\n\tfor (let column = 0; column < size; column++) {\n\t\tlet pivot = -1;\n\t\tfor (let row = column; row < size; row++) {\n\t\t\tif (!isRationalZero(matrix[row][column])) {\n\t\t\t\tpivot = row;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (pivot === -1) return null;\n\t\t[matrix[column], matrix[pivot]] = [matrix[pivot], matrix[column]];\n\t\t[target[column], target[pivot]] = [target[pivot], target[column]];\n\n\t\tfor (let row = 0; row < size; row++) {\n\t\t\tif (row === column || isRationalZero(matrix[row][column])) continue;\n\t\t\tconst factor = rationalDiv(matrix[row][column], matrix[column][column]);\n\t\t\tfor (let k = column; k < size; k++) {\n\t\t\t\tmatrix[row][k] = rationalSub(matrix[row][k], rationalMul(factor, matrix[column][k]));\n\t\t\t}\n\t\t\ttarget[row] = rationalSub(target[row], rationalMul(factor, target[column]));\n\t\t}\n\t}\n\treturn target.map((value, index) => rationalDiv(value, matrix[index][index]));\n}\n\n/**\n * Decomposes a rational function into partial fractions.\n *\n * @param numerator - Ascending coefficients of the numerator.\n * @param denominator - Ascending coefficients of the denominator.\n * @param variable - The variable both are written in.\n * @returns The decomposition, or `null` when the denominator is constant, above\n * {@link APART_MAX_DEGREE}, or does not factor into pieces this can solve over.\n */\nexport function partialFractions(\n\tnumerator: readonly Rational[],\n\tdenominator: readonly Rational[],\n\tvariable: string,\n): PartialFractionDecomposition | null {\n\tif (denominator.length < 2 || denominator.length - 1 > APART_MAX_DEGREE) return null;\n\n\t// Cancel first, so a fraction that is secretly a polynomial does not get\n\t// decomposed over a factor that is not really there.\n\tconst shared = coefficientGcd(numerator, denominator);\n\tconst reducedNumerator = shared.length > 1 ? polynomialDivide(numerator, shared).quotient : [...numerator];\n\tconst reducedDenominator = shared.length > 1 ? polynomialDivide(denominator, shared).quotient : [...denominator];\n\t// Cancelling can leave no denominator at all, as it does for\n\t// `(x^2-1)/(x-1)`. That is a polynomial and an answer, not a failure.\n\tif (reducedDenominator.length === 1) {\n\t\treturn { polynomial: scale(reducedNumerator, reducedDenominator[0]), terms: [] };\n\t}\n\tif (reducedDenominator.length === 0) return null;\n\n\t// Made monic, so the factorization carries no content and every factor below\n\t// is monic too.\n\tconst leading = reducedDenominator[reducedDenominator.length - 1];\n\tconst monicDenominator = scale(reducedDenominator, leading);\n\tconst scaledNumerator = scale(reducedNumerator, leading);\n\n\tconst { quotient, remainder } = polynomialDivide(scaledNumerator, monicDenominator);\n\tif (isZeroPolynomial(remainder)) return { polynomial: quotient, terms: [] };\n\n\tconst factors = denominatorFactors(monicDenominator, variable);\n\tif (factors === null) return null;\n\n\tconst terms = solveForNumerators(factors, monicDenominator, remainder);\n\treturn terms === null ? null : { polynomial: quotient, terms };\n}\n\n/**\n * Builds and solves the undetermined-coefficient system, then groups the\n * solution back into one numerator per piece.\n */\nfunction solveForNumerators(\n\tfactors: readonly { base: Rational[]; power: number }[],\n\tdenominator: readonly Rational[],\n\tremainder: readonly Rational[],\n): PartialFractionTerm[] | null {\n\tconst unknowns = enumerateUnknowns(factors);\n\tconst size = denominator.length - 1;\n\tif (unknowns.length !== size) return null;\n\n\tconst columns: Rational[][] = [];\n\tfor (const unknown of unknowns) {\n\t\tconst column = unknownColumn(unknown, factors, denominator);\n\t\tif (column === null) return null;\n\t\tcolumns.push(column);\n\t}\n\n\t// Row `i` is the coefficient of `x^i`, which is what makes the system square.\n\tconst matrix: Rational[][] = [];\n\tfor (let row = 0; row < size; row++) {\n\t\tmatrix.push(columns.map(column => column[row] ?? RATIONAL_ZERO));\n\t}\n\tconst target: Rational[] = [];\n\tfor (let row = 0; row < size; row++) target.push(remainder[row] ?? RATIONAL_ZERO);\n\n\tconst solution = solveLinearSystem(matrix, target);\n\tif (solution === null) return null;\n\treturn groupSolution(unknowns, solution, factors);\n}\n\n/** Collects the solved coefficients back into one numerator per `base^power` piece. */\nfunction groupSolution(\n\tunknowns: readonly Unknown[],\n\tsolution: readonly Rational[],\n\tfactors: readonly { base: Rational[]; power: number }[],\n): PartialFractionTerm[] {\n\tconst grouped = new Map<string, Rational[]>();\n\tunknowns.forEach((unknown, index) => {\n\t\tconst key = `${unknown.factor}:${unknown.power}`;\n\t\tconst existing = grouped.get(key) ?? [];\n\t\texisting[unknown.degree] = solution[index];\n\t\tgrouped.set(key, existing);\n\t});\n\n\tconst terms: PartialFractionTerm[] = [];\n\tfor (const [key, coefficients] of grouped) {\n\t\tconst [factorIndex, termPower] = key.split(\":\").map(Number);\n\t\tconst filled = [...coefficients].map(value => value ?? RATIONAL_ZERO);\n\t\t// A piece whose numerator solved to zero is not part of the answer.\n\t\tif (filled.every(isRationalZero)) continue;\n\t\tterms.push({ numerator: filled, base: factors[factorIndex].base, power: termPower });\n\t}\n\treturn terms;\n}\n\n/** Rebuilds an ascending coefficient list as an expression in one variable. */\nexport function coefficientsToNode(coefficients: readonly Rational[], variable: string): SymbolicNode {\n\tconst terms = new Map<string, Rational>();\n\tcoefficients.forEach((coefficient, exponent) => {\n\t\tif (isRationalZero(coefficient)) return;\n\t\tterms.set(exponent === 0 ? \"\" : exponent === 1 ? variable : `${variable}^${exponent}`, coefficient);\n\t});\n\tif (terms.size === 0) return constNode(RATIONAL_ZERO);\n\treturn fromPolynomial({ terms, vars: coefficients.length > 1 ? [variable] : [] });\n}\n\n/**\n * Decomposes a quotient of polynomials into partial fractions.\n *\n * @param node - The expression to decompose.\n * @returns The decomposed sum, or `node` unchanged when it is not a rational\n * function in one variable or has nothing to decompose.\n */\nexport function apartSymbolic(node: SymbolicNode): SymbolicNode {\n\tconst parts = asRationalFunction(node);\n\tif (parts === null) return node;\n\n\tconst decomposition = partialFractions(parts.numerator, parts.denominator, parts.variable);\n\tif (decomposition === null || decomposition.terms.length === 0) return node;\n\n\tlet result: SymbolicNode | null = decomposition.polynomial.length > 0\n\t\t? coefficientsToNode(decomposition.polynomial, parts.variable)\n\t\t: null;\n\n\tfor (const term of decomposition.terms) {\n\t\tconst base = coefficientsToNode(term.base, parts.variable);\n\t\tconst denominator = term.power === 1 ? base : powNode(base, constNode({ n: BigInt(term.power), d: 1n }));\n\t\t// A wholly negative numerator becomes a subtraction rather than the\n\t\t// addition of a negative, which is how partial fractions are written and\n\t\t// which avoids the literal `+-1/(x+1)`.\n\t\tconst negative = isNegativeNumerator(term.numerator);\n\t\tconst numerator = negative ? term.numerator.map(coefficient => rationalNeg(coefficient)) : term.numerator;\n\t\tconst piece: SymbolicNode = {\n\t\t\tkind: \"div\",\n\t\t\tleft: coefficientsToNode(numerator, parts.variable),\n\t\t\tright: denominator,\n\t\t};\n\t\tif (result === null) result = negative ? { kind: \"neg\", operand: piece } : piece;\n\t\telse result = { kind: negative ? \"sub\" : \"add\", left: result, right: piece };\n\t}\n\treturn result === null ? node : simplifySymbolic(result);\n}\n\n/** Whether every coefficient of a numerator is at most zero, so the whole piece reads better subtracted. */\nfunction isNegativeNumerator(coefficients: readonly Rational[]): boolean {\n\treturn coefficients.some(coefficient => coefficient.n < 0n)\n\t\t&& coefficients.every(coefficient => coefficient.n <= 0n);\n}\n\n/** A quotient split into ascending numerator and denominator coefficients over one variable. */\nexport interface RationalFunctionParts {\n\treadonly numerator: readonly Rational[];\n\treadonly denominator: readonly Rational[];\n\treadonly variable: string;\n}\n\n/**\n * Reads a quotient of univariate polynomials out of an expression.\n *\n * @param node - The expression to read.\n * @returns The two coefficient lists and the variable, or `null` when the\n * expression is not such a quotient.\n */\nexport function asRationalFunction(node: SymbolicNode): RationalFunctionParts | null {\n\tif (node.kind !== \"div\") return null;\n\n\tconst numerator = toPolynomial(node.left);\n\tconst denominator = toPolynomial(node.right);\n\tif (numerator === null || denominator === null) return null;\n\n\t// The variable has to come from the denominator: a numerator can legitimately\n\t// be a constant, and a constant denominator is not a rational function at all.\n\tconst variable = polyUnivariateVar(denominator);\n\tif (variable === null) return null;\n\tif (numerator.vars.some(name => name !== variable)) return null;\n\n\treturn {\n\t\tnumerator: polyCoefficients(numerator, variable),\n\t\tdenominator: polyCoefficients(denominator, variable),\n\t\tvariable,\n\t};\n}\n\n/** Multiplies two ascending coefficient lists, exposed so a caller can rebuild a decomposition and check it. */\nexport function multiplyCoefficients(a: readonly Rational[], b: readonly Rational[]): Rational[] {\n\treturn multiply(a, b);\n}\n\n/** Raises an ascending coefficient list to a power, exposed alongside {@link multiplyCoefficients}. */\nexport function powerCoefficients(base: readonly Rational[], exponent: number): Rational[] {\n\treturn power(base, exponent);\n}\n","/**\n * Symbolic differentiation.\n *\n * Genuinely symbolic, not a finite-difference approximation. Once a `pow` node\n * and a function-application node exist, applying the differentiation rules to\n * the tree is both easier to get right and exact, where a finite difference\n * needs a step size chosen against competing truncation and rounding errors and\n * is wrong in the last digits by construction.\n *\n * An unknown function is left as an unevaluated `der` call rather than guessed\n * at. Returning something plausible for a function whose derivative this module\n * does not know would be the worst available outcome.\n */\n\nimport {\n\ttype SymbolicNode,\n\tconstNode,\n\tvarNode,\n\tpowNode,\n\tcallNode,\n} from \"@solve-js/symbolic/SymbolicNode\";\nimport { RATIONAL_ONE, RATIONAL_ZERO, rationalSub } from \"@solve-js/symbolic/Rational\";\nimport { simplifySymbolic } from \"@solve-js/symbolic/Simplify\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Highest derivative order accepted by {@link differentiate}.\n *\n * Each order re-differentiates the previous result, and the quotient rule in\n * particular grows a tree quickly, so repeated differentiation is the operation\n * most able to run away.\n */\nexport const DERIVATIVE_MAX_ORDER = 16;\n\n/** Shorthand for the constant zero node. */\nfunction zero(): SymbolicNode {\n\treturn constNode(RATIONAL_ZERO);\n}\n\n/** Shorthand for the constant one node. */\nfunction one(): SymbolicNode {\n\treturn constNode(RATIONAL_ONE);\n}\n\n/**\n * The derivative of a known single-argument function, in terms of its own\n * argument, before the chain rule multiplies by the argument's derivative.\n *\n * @param name - The function name.\n * @param argument - The argument expression, substituted into the result.\n * @returns The derivative expression, or `null` when the function is not one\n * this module knows how to differentiate.\n */\nexport function functionDerivative(name: string, argument: SymbolicNode): SymbolicNode | null {\n\tswitch (name) {\n\t\tcase \"sin\":\n\t\t\treturn callNode(\"cos\", [argument]);\n\t\tcase \"cos\":\n\t\t\treturn { kind: \"neg\", operand: callNode(\"sin\", [argument]) };\n\t\tcase \"tan\":\n\t\t\t// 1/cos(u)^2, avoiding a sec() this engine has no name for.\n\t\t\treturn { kind: \"div\", left: one(), right: powNode(callNode(\"cos\", [argument]), constNode(2)) };\n\t\tcase \"exp\":\n\t\t\treturn callNode(\"exp\", [argument]);\n\t\tcase \"log\":\n\t\t\treturn { kind: \"div\", left: one(), right: argument };\n\t\tcase \"sqrt\":\n\t\t\treturn {\n\t\t\t\tkind: \"div\",\n\t\t\t\tleft: one(),\n\t\t\t\tright: { kind: \"mul\", left: constNode(2), right: callNode(\"sqrt\", [argument]) },\n\t\t\t};\n\t\tcase \"asin\":\n\t\t\treturn { kind: \"div\", left: one(), right: callNode(\"sqrt\", [oneMinusSquare(argument)]) };\n\t\tcase \"acos\":\n\t\t\treturn { kind: \"neg\", operand: { kind: \"div\", left: one(), right: callNode(\"sqrt\", [oneMinusSquare(argument)]) } };\n\t\tcase \"atan\":\n\t\t\treturn { kind: \"div\", left: one(), right: onePlusSquare(argument) };\n\t\tcase \"sinh\":\n\t\t\treturn callNode(\"cosh\", [argument]);\n\t\tcase \"cosh\":\n\t\t\treturn callNode(\"sinh\", [argument]);\n\t\tcase \"tanh\":\n\t\t\treturn { kind: \"div\", left: one(), right: powNode(callNode(\"cosh\", [argument]), constNode(2)) };\n\t\tcase \"abs\":\n\t\t\treturn callNode(\"sign\", [argument]);\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/** `1 - u^2`, shared by the inverse trigonometric derivatives. */\nfunction oneMinusSquare(argument: SymbolicNode): SymbolicNode {\n\treturn { kind: \"sub\", left: one(), right: powNode(argument, constNode(2)) };\n}\n\n/** `1 + u^2`, for the arctangent derivative. */\nfunction onePlusSquare(argument: SymbolicNode): SymbolicNode {\n\treturn { kind: \"add\", left: one(), right: powNode(argument, constNode(2)) };\n}\n\n/**\n * Differentiates an expression with respect to one variable.\n *\n * @param node - The expression to differentiate.\n * @param variable - The variable to differentiate with respect to.\n * @param order - How many times, defaulting to once.\n * @returns The simplified derivative.\n * @throws {EngineError} `SYMBOLIC_DERIVATIVE_ORDER_LIMIT` past\n * {@link DERIVATIVE_MAX_ORDER}.\n */\nexport function differentiate(node: SymbolicNode, variable: string, order = 1): SymbolicNode {\n\tif (order < 0 || !Number.isInteger(order)) {\n\t\tthrow ErrorFactory.execution(\"SYMBOLIC_DERIVATIVE_ORDER_LIMIT\", \"A derivative order must be a whole number, at least zero.\");\n\t}\n\tif (order > DERIVATIVE_MAX_ORDER) {\n\t\tthrow ErrorFactory.execution(\n\t\t\t\"SYMBOLIC_DERIVATIVE_ORDER_LIMIT\",\n\t\t\t`A derivative order above ${DERIVATIVE_MAX_ORDER} is not supported.`,\n\t\t\t{ limit: DERIVATIVE_MAX_ORDER },\n\t\t);\n\t}\n\n\tlet result = simplifySymbolic(node);\n\tfor (let i = 0; i < order; i++) result = simplifySymbolic(derive(result, variable));\n\treturn result;\n}\n\n/** One differentiation pass, before simplification. */\nfunction derive(node: SymbolicNode, variable: string): SymbolicNode {\n\tswitch (node.kind) {\n\t\tcase \"const\":\n\t\tcase \"complex\":\n\t\t\treturn zero();\n\t\tcase \"var\":\n\t\t\treturn node.name === variable ? one() : zero();\n\t\tcase \"add\":\n\t\t\treturn { kind: \"add\", left: derive(node.left, variable), right: derive(node.right, variable) };\n\t\tcase \"sub\":\n\t\t\treturn { kind: \"sub\", left: derive(node.left, variable), right: derive(node.right, variable) };\n\t\tcase \"neg\":\n\t\t\treturn { kind: \"neg\", operand: derive(node.operand, variable) };\n\t\tcase \"mul\":\n\t\t\t// Product rule.\n\t\t\treturn {\n\t\t\t\tkind: \"add\",\n\t\t\t\tleft: { kind: \"mul\", left: derive(node.left, variable), right: node.right },\n\t\t\t\tright: { kind: \"mul\", left: node.left, right: derive(node.right, variable) },\n\t\t\t};\n\t\tcase \"div\":\n\t\t\t// Quotient rule.\n\t\t\treturn {\n\t\t\t\tkind: \"div\",\n\t\t\t\tleft: {\n\t\t\t\t\tkind: \"sub\",\n\t\t\t\t\tleft: { kind: \"mul\", left: derive(node.left, variable), right: node.right },\n\t\t\t\t\tright: { kind: \"mul\", left: node.left, right: derive(node.right, variable) },\n\t\t\t\t},\n\t\t\t\tright: powNode(node.right, constNode(2)),\n\t\t\t};\n\t\tcase \"pow\":\n\t\t\treturn derivePow(node, variable);\n\t\tcase \"call\": {\n\t\t\tif (node.args.length !== 1) return unevaluated(node, variable);\n\t\t\tconst outer = functionDerivative(node.name, node.args[0]);\n\t\t\tif (outer === null) return unevaluated(node, variable);\n\t\t\t// Chain rule.\n\t\t\treturn { kind: \"mul\", left: outer, right: derive(node.args[0], variable) };\n\t\t}\n\t}\n}\n\n/**\n * Differentiates a power.\n *\n * The constant-exponent case is the ordinary power rule with the chain rule\n * applied to the base. The general `f^g` case is only attempted when it is\n * sound to do so: with a constant positive base, where it reduces to\n * `f^g * ln(f) * g'`. A general `f^g` would need `ln(f)`, which is undefined\n * for a negative base, so guessing there could produce a formula that is wrong\n * exactly where the original expression was fine.\n */\nfunction derivePow(node: SymbolicNode & { kind: \"pow\" }, variable: string): SymbolicNode {\n\tif (node.exponent.kind === \"const\") {\n\t\tconst reduced = constNode(rationalSub(node.exponent.value, RATIONAL_ONE));\n\t\treturn {\n\t\t\tkind: \"mul\",\n\t\t\tleft: { kind: \"mul\", left: node.exponent, right: powNode(node.base, reduced) },\n\t\t\tright: derive(node.base, variable),\n\t\t};\n\t}\n\tif (node.base.kind === \"const\" && node.base.value.n > 0n) {\n\t\treturn {\n\t\t\tkind: \"mul\",\n\t\t\tleft: { kind: \"mul\", left: node, right: callNode(\"log\", [node.base]) },\n\t\t\tright: derive(node.exponent, variable),\n\t\t};\n\t}\n\treturn unevaluated(node, variable);\n}\n\n/** Leaves an unknown derivative as an explicit `der(expr, variable)` call rather than inventing an answer for it. */\nfunction unevaluated(node: SymbolicNode, variable: string): SymbolicNode {\n\treturn callNode(\"der\", [node, varNode(variable)]);\n}\n","/**\n * Symbolic indefinite integration.\n *\n * ## Failing loudly is the feature\n *\n * Integration, unlike differentiation, has no algorithm that always succeeds:\n * plenty of perfectly ordinary expressions have no elementary antiderivative at\n * all, `exp(x^2)` and `sin(x)/x` among them. So this handles polynomials\n * exactly, plus a small table of standard forms with a linear inner argument,\n * and **reports what it cannot do rather than approximating**.\n *\n * A CAS that quietly returns something wrong for `integral(exp(x^2), x)` is\n * worse than one that says it cannot, because the wrong answer is\n * indistinguishable from a right one at the point of use.\n *\n * The constant of integration is omitted, as is conventional for a calculator.\n */\n\nimport {\n\ttype SymbolicNode,\n\tconstNode,\n\tvarNode,\n\tpowNode,\n\tcallNode,\n\tfreeVariables,\n} from \"@solve-js/symbolic/SymbolicNode\";\nimport {\n\ttype Rational,\n\tRATIONAL_ZERO,\n\trationalSub,\n\trationalMul,\n\trationalDiv,\n\tisRationalZero,\n} from \"@solve-js/symbolic/Rational\";\nimport { toPolynomial, polyCoefficients, polyDegree } from \"@solve-js/symbolic/Polynomial\";\nimport { simplifySymbolic } from \"@solve-js/symbolic/Simplify\";\nimport {\n\ttype PartialFractionTerm,\n\tpartialFractions,\n\tasRationalFunction,\n\tcoefficientsToNode,\n} from \"@solve-js/symbolic/PartialFractions\";\nimport { surdNode } from \"@solve-js/symbolic/Radicals\";\n\n/** The result of an integration attempt, which may legitimately fail. */\nexport type IntegralResult =\n\t/** An antiderivative was found. */\n\t| { readonly ok: true; readonly value: SymbolicNode }\n\t/** None was found, with the reason stated so the caller can pass it on. */\n\t| { readonly ok: false; readonly reason: string };\n\n/** `a*x + b` decomposed, or `null` when the expression is not linear in `variable`. */\ninterface LinearArgument {\n\treadonly slope: Rational;\n\treadonly intercept: Rational;\n}\n\n/** Reads `a*x + b` out of an expression, which is the only inner-argument shape the table below handles. */\nfunction asLinear(node: SymbolicNode, variable: string): LinearArgument | null {\n\tconst polynomial = toPolynomial(node);\n\tif (polynomial === null) return null;\n\tconst others = polynomial.vars.filter(name => name !== variable);\n\tif (others.length > 0) return null;\n\tif (polyDegree(polynomial, variable) > 1) return null;\n\n\tconst ascending = polyCoefficients(polynomial, variable);\n\tconst intercept = ascending[0] ?? { n: 0n, d: 1n };\n\tconst slope = ascending[1] ?? { n: 0n, d: 1n };\n\treturn isRationalZero(slope) ? null : { slope, intercept };\n}\n\n/**\n * Integrates a polynomial term by term with the power rule.\n *\n * `x^-1` is deliberately excluded here and handled by the table instead, since\n * its antiderivative is a logarithm rather than a power. In practice the\n * polynomial form cannot carry a negative exponent anyway, but stating the\n * boundary keeps the two paths from overlapping silently.\n */\nfunction integratePolynomial(node: SymbolicNode, variable: string): IntegralResult | null {\n\tconst polynomial = toPolynomial(node);\n\tif (polynomial === null) return null;\n\tconst others = polynomial.vars.filter(name => name !== variable);\n\tif (others.length > 0) {\n\t\treturn { ok: false, reason: `it involves more than one unknown (${others.join(\", \")})` };\n\t}\n\n\tconst ascending = polyCoefficients(polynomial, variable);\n\tlet result: SymbolicNode = constNode(0);\n\tascending.forEach((coeff, power) => {\n\t\tif (isRationalZero(coeff)) return;\n\t\tconst nextPower = power + 1;\n\t\tconst scaled = rationalDiv(coeff, { n: BigInt(nextPower), d: 1n });\n\t\tconst term: SymbolicNode = {\n\t\t\tkind: \"mul\",\n\t\t\tleft: constNode(scaled),\n\t\t\tright: nextPower === 1 ? varNode(variable) : powNode(varNode(variable), constNode(nextPower)),\n\t\t};\n\t\tresult = { kind: \"add\", left: result, right: term };\n\t});\n\treturn { ok: true, value: simplifySymbolic(result) };\n}\n\n/**\n * The standard-form table, for a function of a linear argument.\n *\n * Every entry divides by the inner slope, which is the linear-substitution rule\n * `integral f(ax+b) dx = F(ax+b)/a`.\n */\nfunction integrateStandardForm(node: SymbolicNode, variable: string): IntegralResult | null {\n\tif (node.kind !== \"call\" || node.args.length !== 1) return null;\n\tconst linear = asLinear(node.args[0], variable);\n\tif (linear === null) return null;\n\n\tconst inner = node.args[0];\n\tconst divideBySlope = (value: SymbolicNode): SymbolicNode =>\n\t\tsimplifySymbolic({ kind: \"div\", left: value, right: constNode(linear.slope) });\n\n\tswitch (node.name) {\n\t\tcase \"exp\":\n\t\t\treturn { ok: true, value: divideBySlope(callNode(\"exp\", [inner])) };\n\t\tcase \"sin\":\n\t\t\treturn { ok: true, value: divideBySlope({ kind: \"neg\", operand: callNode(\"cos\", [inner]) }) };\n\t\tcase \"cos\":\n\t\t\treturn { ok: true, value: divideBySlope(callNode(\"sin\", [inner])) };\n\t\tcase \"log\":\n\t\t\t// integral ln(u) du = u*ln(u) - u, then divided by the inner slope.\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tvalue: divideBySlope({\n\t\t\t\t\tkind: \"sub\",\n\t\t\t\t\tleft: { kind: \"mul\", left: inner, right: callNode(\"log\", [inner]) },\n\t\t\t\t\tright: inner,\n\t\t\t\t}),\n\t\t\t};\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/** `1/x` and `1/(1+x^2)`, whose antiderivatives are a logarithm and an arctangent rather than powers. */\nfunction integrateReciprocalForms(node: SymbolicNode, variable: string): IntegralResult | null {\n\tif (node.kind !== \"div\") return null;\n\tif (node.left.kind !== \"const\" || !isRationalOneNode(node.left.value)) return null;\n\n\tconst linear = asLinear(node.right, variable);\n\tif (linear !== null) {\n\t\t// integral 1/(ax+b) dx = ln(|ax+b|)/a. Written without the absolute value\n\t\t// bars, matching how the rest of this engine treats log's domain.\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: simplifySymbolic({\n\t\t\t\tkind: \"div\",\n\t\t\t\tleft: callNode(\"log\", [node.right]),\n\t\t\t\tright: constNode(linear.slope),\n\t\t\t}),\n\t\t};\n\t}\n\n\t// integral 1/(1+x^2) dx = atan(x), the one non-linear denominator worth a\n\t// table entry because it turns up constantly.\n\tconst denominator = toPolynomial(node.right);\n\tif (denominator !== null && denominator.vars.length === 1 && denominator.vars[0] === variable) {\n\t\tconst ascending = polyCoefficients(denominator, variable);\n\t\tconst isOnePlusSquare =\n\t\t\tascending.length === 3 &&\n\t\t\tisRationalOneNode(ascending[0]) &&\n\t\t\tisRationalZero(ascending[1]) &&\n\t\t\tisRationalOneNode(ascending[2]);\n\t\tif (isOnePlusSquare) return { ok: true, value: callNode(\"atan\", [varNode(variable)]) };\n\t}\n\treturn null;\n}\n\n/** Whether a rational is exactly one. */\nfunction isRationalOneNode(value: Rational): boolean {\n\treturn value.n === 1n && value.d === 1n;\n}\n\n/**\n * Integrates any rational function whose denominator factors into linear pieces\n * and distinct irreducible quadratics.\n *\n * A quotient of polynomials has no single antiderivative rule, but partial\n * fractions turns it into a sum of pieces that each do have one, which is what\n * makes this the general method rather than another table entry. The four\n * shapes are `A/(x-a)` giving a logarithm, `A/(x-a)^k` giving a power,\n * `(Bx+C)/(quadratic)` giving a logarithm plus an arctangent, and the\n * polynomial part left over from the division.\n */\nfunction integrateRationalFunction(node: SymbolicNode, variable: string): IntegralResult | null {\n\tconst parts = asRationalFunction(node);\n\tif (parts === null || parts.variable !== variable) return null;\n\n\tconst decomposition = partialFractions(parts.numerator, parts.denominator, variable);\n\tif (decomposition === null) return null;\n\n\tlet result: SymbolicNode = decomposition.polynomial.length > 0\n\t\t? polynomialAntiderivative(decomposition.polynomial, variable)\n\t\t: constNode(0);\n\n\tfor (const term of decomposition.terms) {\n\t\tconst piece = integrateTerm(term, variable);\n\t\tif (piece === null) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\treason: \"its denominator has a repeated irreducible quadratic factor, which needs a reduction formula this does not have\",\n\t\t\t};\n\t\t}\n\t\tresult = { kind: \"add\", left: result, right: piece };\n\t}\n\treturn { ok: true, value: simplifySymbolic(result) };\n}\n\n/** The antiderivative of one partial-fraction piece, or `null` for a shape with no rule here. */\nfunction integrateTerm(term: PartialFractionTerm, variable: string): SymbolicNode | null {\n\tconst baseDegree = term.base.length - 1;\n\tconst base = coefficientsToNode(term.base, variable);\n\n\tif (baseDegree === 1) {\n\t\tconst coefficient = term.numerator[0] ?? RATIONAL_ZERO;\n\t\t// integral A/(x-a) dx = A ln(x-a), written without absolute-value bars to\n\t\t// match how the rest of this module treats log's domain.\n\t\tif (term.power === 1) {\n\t\t\treturn { kind: \"mul\", left: constNode(coefficient), right: callNode(\"log\", [base]) };\n\t\t}\n\t\t// integral A/(x-a)^k dx = -A / ((k-1)(x-a)^(k-1))\n\t\tconst reduced = term.power - 1;\n\t\tconst scaled = rationalDiv(coefficient, { n: BigInt(-reduced), d: 1n });\n\t\treturn {\n\t\t\tkind: \"div\",\n\t\t\tleft: constNode(scaled),\n\t\t\tright: powNode(base, constNode({ n: BigInt(reduced), d: 1n })),\n\t\t};\n\t}\n\n\t// A repeated quadratic needs the reduction formula, which is a genuinely\n\t// different piece of machinery and is declined rather than approximated.\n\tif (baseDegree !== 2 || term.power !== 1) return null;\n\treturn integrateQuadraticTerm(term, variable, base);\n}\n\n/**\n * The antiderivative of `(Bx+C)/(x^2+px+q)` for an irreducible quadratic.\n *\n * Split as `(B/2)` times the derivative of the denominator over the\n * denominator, which integrates to a logarithm, plus what is left over, which\n * is a constant over a completed square and integrates to an arctangent. The\n * half-width of that square is `sqrt(q - p^2/4)`, real and positive exactly\n * because the quadratic is irreducible.\n */\nfunction integrateQuadraticTerm(term: PartialFractionTerm, variable: string, base: SymbolicNode): SymbolicNode {\n\tconst constant = term.numerator[0] ?? RATIONAL_ZERO;\n\tconst linear = term.numerator[1] ?? RATIONAL_ZERO;\n\tconst [q, p] = term.base;\n\n\tconst half = { n: 1n, d: 2n };\n\tconst halfP = rationalMul(p, half);\n\tconst logarithm: SymbolicNode = {\n\t\tkind: \"mul\",\n\t\tleft: constNode(rationalMul(linear, half)),\n\t\tright: callNode(\"log\", [base]),\n\t};\n\n\t// What the logarithm did not account for: C - B*p/2, over the shifted square.\n\tconst leftover = rationalSub(constant, rationalMul(linear, halfP));\n\tif (isRationalZero(leftover)) return logarithm;\n\n\tconst width = surdNode(rationalSub(q, rationalMul(halfP, halfP)));\n\tconst shifted: SymbolicNode = {\n\t\tkind: \"add\",\n\t\tleft: varNode(variable),\n\t\tright: constNode(halfP),\n\t};\n\tconst arctangent: SymbolicNode = {\n\t\tkind: \"mul\",\n\t\tleft: { kind: \"div\", left: constNode(leftover), right: width },\n\t\tright: callNode(\"atan\", [{ kind: \"div\", left: shifted, right: width }]),\n\t};\n\treturn isRationalZero(linear) ? arctangent : { kind: \"add\", left: logarithm, right: arctangent };\n}\n\n/** The antiderivative of a polynomial given as ascending coefficients. */\nfunction polynomialAntiderivative(ascending: readonly Rational[], variable: string): SymbolicNode {\n\tlet result: SymbolicNode = constNode(0);\n\tascending.forEach((coeff, exponent) => {\n\t\tif (isRationalZero(coeff)) return;\n\t\tconst nextPower = exponent + 1;\n\t\tconst scaled = rationalDiv(coeff, { n: BigInt(nextPower), d: 1n });\n\t\tconst term: SymbolicNode = {\n\t\t\tkind: \"mul\",\n\t\t\tleft: constNode(scaled),\n\t\t\tright: nextPower === 1 ? varNode(variable) : powNode(varNode(variable), constNode(nextPower)),\n\t\t};\n\t\tresult = { kind: \"add\", left: result, right: term };\n\t});\n\treturn result;\n}\n\n/**\n * Finds an indefinite integral, or reports that it could not.\n *\n * @param node - The expression to integrate.\n * @param variable - The variable of integration.\n * @returns The antiderivative, without a constant of integration, or a stated\n * reason for declining.\n */\nexport function integrate(node: SymbolicNode, variable: string): IntegralResult {\n\tconst simplified = simplifySymbolic(node);\n\n\t// A constant integrates to itself times the variable, including the case\n\t// where the expression involves other unknowns but not this one.\n\tif (!freeVariables(simplified).has(variable)) {\n\t\treturn { ok: true, value: simplifySymbolic({ kind: \"mul\", left: simplified, right: varNode(variable) }) };\n\t}\n\n\tconst polynomial = integratePolynomial(simplified, variable);\n\tif (polynomial !== null) return polynomial;\n\n\tconst standard = integrateStandardForm(simplified, variable);\n\tif (standard !== null) return standard;\n\n\tconst reciprocal = integrateReciprocalForms(simplified, variable);\n\tif (reciprocal !== null) return reciprocal;\n\n\t// Tried after the two tables above, which reach the same shapes by a shorter\n\t// route and produce a tidier answer for them: `1/(2x+1)` is better read as\n\t// `log(2x+1)/2` than as the same thing routed through a decomposition.\n\tconst rationalFunction = integrateRationalFunction(simplified, variable);\n\tif (rationalFunction !== null) return rationalFunction;\n\n\t// A sum is integrable term by term whenever each term is, which covers the\n\t// common \"polynomial plus a standard form\" shape.\n\tif (simplified.kind === \"add\" || simplified.kind === \"sub\") {\n\t\tconst left = integrate(simplified.left, variable);\n\t\tif (!left.ok) return left;\n\t\tconst right = integrate(simplified.right, variable);\n\t\tif (!right.ok) return right;\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: simplifySymbolic({ kind: simplified.kind, left: left.value, right: right.value }),\n\t\t};\n\t}\n\n\t// A constant multiple comes out front.\n\tif (simplified.kind === \"mul\" && simplified.left.kind === \"const\") {\n\t\tconst inner = integrate(simplified.right, variable);\n\t\tif (!inner.ok) return inner;\n\t\treturn { ok: true, value: simplifySymbolic({ kind: \"mul\", left: simplified.left, right: inner.value }) };\n\t}\n\n\treturn {\n\t\tok: false,\n\t\treason: \"no elementary antiderivative is known for this expression\",\n\t};\n}\n\n","/**\n * Taylor series expansion, and the Jacobian matrix.\n *\n * Both are built directly on {@link differentiate}, so both are exact wherever\n * differentiation is. A Taylor coefficient is `f^(n)(a) / n!`, which needs the\n * n-th derivative evaluated *at a point*, and that evaluation is the one place\n * this can fail: a derivative that does not reduce to a plain number at the\n * point has no exact rational coefficient, and this reports that rather than\n * approximating one.\n *\n * That is why the exact values of the standard functions at zero (`sin(0)`,\n * `cos(0)`, `exp(0)`, and so on) matter to the simplifier's own folding: they\n * are what makes the familiar series around the origin come out exactly.\n */\n\nimport {\n\ttype SymbolicNode,\n\tconstNode,\n\tvarNode,\n\tpowNode,\n\tsubstitute,\n} from \"@solve-js/symbolic/SymbolicNode\";\nimport { type Rational, RATIONAL_ZERO, rationalDiv, isRationalZero } from \"@solve-js/symbolic/Rational\";\nimport { simplifySymbolic } from \"@solve-js/symbolic/Simplify\";\nimport { differentiate } from \"@solve-js/symbolic/Derivative\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Highest Taylor degree accepted.\n *\n * Each term needs one more derivative than the last, so cost grows with the\n * square of the degree once the expressions themselves start growing.\n */\nexport const TAYLOR_MAX_DEGREE = 16;\n\n/**\n * Expands an expression as a Taylor series about a point.\n *\n * @param node - The expression to expand.\n * @param variable - The variable to expand in.\n * @param point - The point to expand about, `0` giving a Maclaurin series.\n * @param degree - The highest power to include.\n * @returns The series as an expression.\n * @throws {EngineError} `SYMBOLIC_TAYLOR_DEGREE_LIMIT` past\n * {@link TAYLOR_MAX_DEGREE}, or `SYMBOLIC_TAYLOR_INEXACT` when a coefficient\n * does not reduce to an exact number at the point.\n */\nexport function taylorSeries(node: SymbolicNode, variable: string, point: Rational, degree: number): SymbolicNode {\n\tif (degree < 0 || !Number.isInteger(degree) || degree > TAYLOR_MAX_DEGREE) {\n\t\tthrow ErrorFactory.execution(\n\t\t\t\"SYMBOLIC_TAYLOR_DEGREE_LIMIT\",\n\t\t\t`A Taylor degree must be a whole number from 0 to ${TAYLOR_MAX_DEGREE}.`,\n\t\t\t{ limit: TAYLOR_MAX_DEGREE },\n\t\t);\n\t}\n\n\tconst pointNode = constNode(point);\n\tlet factorial = 1n;\n\tlet result: SymbolicNode = constNode(RATIONAL_ZERO);\n\n\tfor (let order = 0; order <= degree; order++) {\n\t\tif (order > 0) factorial *= BigInt(order);\n\n\t\tconst derivative = differentiate(node, variable, order);\n\t\tconst atPoint = simplifySymbolic(substitute(derivative, variable, pointNode));\n\t\tif (atPoint.kind !== \"const\") {\n\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\"SYMBOLIC_TAYLOR_INEXACT\",\n\t\t\t\t`The derivative of order ${order} does not reduce to an exact number at the expansion point, so this series cannot be computed exactly.`,\n\t\t\t\t{ order },\n\t\t\t);\n\t\t}\n\n\t\tconst coefficient = rationalDiv(atPoint.value, { n: factorial, d: 1n });\n\t\tif (isRationalZero(coefficient)) continue;\n\n\t\t// (x - a)^order, collapsing to 1 and to (x - a) at the low orders so the\n\t\t// series reads the way it is written rather than carrying `^1` and `^0`.\n\t\tconst shifted: SymbolicNode = isRationalZero(point)\n\t\t\t? varNode(variable)\n\t\t\t: { kind: \"sub\", left: varNode(variable), right: pointNode };\n\t\tconst power: SymbolicNode =\n\t\t\torder === 0 ? constNode(1) : order === 1 ? shifted : powNode(shifted, constNode(order));\n\n\t\tresult = { kind: \"add\", left: result, right: { kind: \"mul\", left: constNode(coefficient), right: power } };\n\t}\n\n\treturn simplifySymbolic(result);\n}\n\n/**\n * The Jacobian: each row is one function's gradient.\n *\n * @param functions - The functions, in row order.\n * @param variables - The variables, in column order.\n * @returns A row-major grid of partial derivatives, entry `[i][j]` being the\n * derivative of `functions[i]` with respect to `variables[j]`.\n */\nexport function jacobian(functions: readonly SymbolicNode[], variables: readonly string[]): SymbolicNode[][] {\n\treturn functions.map(fn => variables.map(variable => differentiate(fn, variable)));\n}\n","/**\n * Per-engine state that used to live in module-level singletons.\n *\n * Two {@link ExpressionEngine} instances in one process could not be isolated\n * from each other, because the registries they depend on were module globals\n * shared by every instance. Registering a package mutated state that another\n * engine was already reading. Tests worked only because they cleared those\n * globals by hand, and per-document engines were safe only because\n * registration happened to be idempotent.\n *\n * An `EngineContext` is created by the `ExpressionEngine` constructor and owned\n * by that engine. Anything that needs one of these registries receives the\n * context rather than importing a singleton.\n *\n * Runtime imports here are restricted to leaf modules of `vm/`. This file is\n * imported by `vm/`, which `engine/` imports in turn, so pulling in anything\n * that reaches back into `engine/` would close a cycle. `OpRegistry` is safe\n * because it imports only types plus the error factory. Everything else arrives\n * through `import type`, which is erased before the code runs.\n */\n\nimport type { Value } from \"@solve-js/vm/Value\";\nimport type { LineExecutionContext } from \"@solve-js/vm/VM\";\nimport { OpRegistry } from \"@solve-js/vm/OpRegistry\";\n\n/**\n * A function a package contributes to the VM, reachable from bytecode through\n * `CALL_PLUGIN`.\n *\n * Returning a promise puts the line into the pending state rather than\n * blocking: the engine resolves it and re-executes.\n */\nexport type PluginFunctionHandler = (\n\targs: Value[],\n\tcontext?: LineExecutionContext,\n) => Value | Promise<Value>;\n\n/**\n * The registries one engine instance owns.\n *\n * Members are added here as each former singleton is migrated. The migration\n * order is deliberate and recorded in `docs-internal/plans`: plugin functions,\n * then the opcode registry, the variable resolver, the lexer, and finally\n * currency exchange. The lexer comes near the end because package registration\n * writes vocabularies into it, so moving it early would churn every package.\n *\n * Currency exchange is deliberately NOT migrated, which is a departure from\n * that plan. `CurrencyExchangeService` holds a cache of live market rates with\n * a fifteen minute freshness window and no per-engine configuration. Sharing is\n * the correct behaviour there: giving each engine its own would make two\n * engines in one process fetch the same public endpoint independently, and let\n * them disagree about the rate for one currency pair at one moment. The\n * singleton rationale, that one engine's registration should not be visible to\n * another, does not apply to a cache of state that is global in the real world.\n *\n * If a host ever needs per-engine rates, for a what-if scenario against\n * historical figures, the answer is an optional override on the context that\n * falls back to the shared cache, not a private copy per engine.\n */\nexport interface EngineContext {\n\t/**\n\t * Package-contributed VM functions, keyed by the index the bytecode\n\t * carries.\n\t *\n\t * Indices come from `allocatePluginFunctionIndex()`. Two packages picking\n\t * the same number by hand would silently overwrite one another, which is\n\t * why the allocator exists and why nothing should hardcode an index.\n\t */\n\treadonly pluginFunctions: Record<number, PluginFunctionHandler>;\n\n\t/**\n\t * Custom opcode handlers a package registered.\n\t *\n\t * Largely vestigial: packages reach the VM through `CALL_PLUGIN` and\n\t * {@link EngineContext.pluginFunctions} now, and nothing in the built-in\n\t * set registers an opcode. It moves here anyway because the VM interface\n\t * still requires a registry, and one shared instance would put any future\n\t * registration back into every engine at once.\n\t */\n\treadonly opRegistry: OpRegistry;\n\n\t/**\n\t * Which package registered each plugin function index.\n\t *\n\t * The VM emits a pending result when a plugin function returns a promise,\n\t * and that result carries the owning package so diagnostics and the error\n\t * surface can name it. Without this the VM had nothing to report and sent an\n\t * empty string, so every async failure looked as though it came from\n\t * nowhere.\n\t */\n\treadonly pluginFunctionOwners: Record<number, string>;\n}\n\n/**\n * Create a context with empty registries.\n *\n * @returns A context owned by exactly one engine.\n */\nexport function createEngineContext(): EngineContext {\n\treturn {\n\t\tpluginFunctions: {},\n\t\topRegistry: new OpRegistry(),\n\t\tpluginFunctionOwners: {},\n\t};\n}\n\n/**\n * The context backing the deprecated module-level exports.\n *\n * Exists so the `shared*` singletons can keep working, against real state,\n * while callers move across one at a time. It is not a fallback for an engine\n * that forgot to make its own: an engine always creates its own context, and\n * anything reaching for this one is code that has not been migrated yet.\n *\n * @deprecated Take an {@link EngineContext} instead. This is removed once the\n * migration finishes.\n */\nexport const defaultEngineContext: EngineContext = createEngineContext();\n","/**\n * U.S. CPI-U (Consumer Price Index for All Urban Consumers, \"U.S. city\n * average, all items\", 1982-84=100 base) annual average index values.\n *\n * ── DATA VINTAGE / SOURCE / ACCURACY NOTE (read before trusting a number) ──\n * These are APPROXIMATE annual-average CPI-U figures recalled from the\n * assistant's general knowledge (training data through ~January 2026), not\n * a live fetch from the U.S. Bureau of Labor Statistics (bls.gov/cpi). They\n * are representative of the real, published series and good enough for a\n * calculator-notepad's inflation-adjustment feature, but:\n * - Years up to ~2024 are close to BLS-published annual averages but may\n * be off by a small amount (rounding/recall, not a live re-derivation).\n * - 2025 and 2026 are forward-leaning ESTIMATES (2025 not fully finalized,\n * 2026 projected from recent trend), expect these to be the least\n * accurate entries and the first that need replacing with real BLS\n * data as it's published.\n * - This table is NOT authoritative for financial, legal, tax, contract\n * escalation (COLA), or any decision with real money on the line\n * consult bls.gov/cpi directly for that. It exists so `inflationAdjust`\n * and the \"what is/was ... worth\" phrase grammar (see\n * `packages/finance/parselets/InflationQueryParselet.ts`) have a real,\n * working, demonstrably-correct-shaped implementation to run against,\n * matching this session's established honesty principle for bundled\n * approximate data (see `SalesTaxParselet.ts`'s doc comment on never\n * silently faking a rate).\n *\n * Coverage: 1970-2026 inclusive (57 years), additive; extend this table in\n * future years by appending new entries, no other code needs to change.\n * A year outside this range (e.g. \"what was $500 worth in 1920\") produces a\n * clear `INFLATION_YEAR_OUT_OF_RANGE` error rather than a silently wrong\n * extrapolation.\n */\nexport const CPI_TABLE: Readonly<Record<number, number>> = {\n 1970: 38.8, 1971: 40.5, 1972: 41.8, 1973: 44.4, 1974: 49.3,\n 1975: 53.8, 1976: 56.9, 1977: 60.6, 1978: 65.2, 1979: 72.6,\n 1980: 82.4, 1981: 90.9, 1982: 96.5, 1983: 99.6, 1984: 103.9,\n 1985: 107.6, 1986: 109.6, 1987: 113.6, 1988: 118.3, 1989: 124.0,\n 1990: 130.7, 1991: 136.2, 1992: 140.3, 1993: 144.5, 1994: 148.2,\n 1995: 152.4, 1996: 156.9, 1997: 160.5, 1998: 163.0, 1999: 166.6,\n 2000: 172.2, 2001: 177.1, 2002: 179.9, 2003: 184.0, 2004: 188.9,\n 2005: 195.3, 2006: 201.6, 2007: 207.3, 2008: 215.3, 2009: 214.5,\n 2010: 218.1, 2011: 224.9, 2012: 229.6, 2013: 233.0, 2014: 236.7,\n 2015: 237.0, 2016: 240.0, 2017: 245.1, 2018: 251.1, 2019: 255.7,\n 2020: 258.8, 2021: 271.0, 2022: 292.7, 2023: 304.7, 2024: 313.7,\n // 2025-2026 were projected from model knowledge and are now derived from\n // the IMF monthly CPI series (statisticsoftheworld.com,\n // IMF.CPI.YOY.M?geo=USA), chained forward from the published 2024 figure\n // using annual mean year-over-year rates. 2026 covers January to June only,\n // so it remains a partial year and will move.\n //\n // The projections were 320.6 and 327.4, low by 0.49% and 1.63%. Everything\n // from 2021 to 2024 reproduced the same series to within 0.02%, which is\n // what makes those two the only entries worth changing.\n 2025: 322.2, 2026: 332.7,\n} as const;\n\n/** Earliest/latest year this table has data for, used for range-check error messages. */\nexport const CPI_MIN_YEAR = 1970;\n/**\n * Most recent year in {@link CPI_TABLE}.\n *\n * A request beyond this is rejected rather than extrapolated, since inflation\n * past the last published figure is a forecast and not a conversion.\n */\nexport const CPI_MAX_YEAR = 2026;\n\n/** Look up the CPI-U annual average for `year`, or `undefined` if out of range. */\nexport function getCpi(year: number): number | undefined {\n return CPI_TABLE[Math.trunc(year)];\n}\n\n/**\n * Ratio to multiply a `fromYear` dollar amount by to express it in\n * `toYear` dollars: `amount(toYear) = amount(fromYear) * inflationRatio(fromYear, toYear)`.\n *\n * @returns `undefined` if either year is outside the table's range, or if\n * `fromYear`'s CPI is exactly 0 (never true for real data, guarded anyway\n * since it would otherwise divide by zero).\n */\nexport function inflationRatio(fromYear: number, toYear: number): number | undefined {\n const fromCpi = getCpi(fromYear);\n const toCpi = getCpi(toYear);\n if (fromCpi === undefined || toCpi === undefined || fromCpi === 0) return undefined;\n return toCpi / fromCpi;\n}\n\n/**\n * Adjust `amount` from `fromYear` dollars to `toYear` dollars using the CPI\n * table above.\n *\n * @returns `undefined` if either year is out of the table's covered range\n * (caller should surface this as a clear error, not a silently wrong number).\n */\nexport function adjustForInflation(amount: number, fromYear: number, toYear: number): number | undefined {\n const ratio = inflationRatio(fromYear, toYear);\n if (ratio === undefined) return undefined;\n return amount * ratio;\n}\n","import { Value, ValueType, numberValue, hexValue, uomValue, errorValue, matrixValue, percentageValue, stringValue, splitValue, type MatrixData } from \"@solve-js/vm/Value\";\nimport { decimalRound, decimalToNumber, type DecimalData } from \"@solve-js/decimal\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { unifyUom, power, describeMeasureMismatch } from \"@solve-js/vm/VMConversion\";\nimport { scaleMoneyExact, scaleMoneyByPercent, removeTaxExact, taxInExact, splitEachExact } from \"@solve-js/vm/MoneyExact\";\nimport { transpose, determinant, inverse, matrixMultiply, matrixPower, symbolicToEntry, rowMajorToColumnMajor } from \"@solve-js/vm/MatrixOps\";\nimport { symbolicToValue, valueToSymbolic, solveEquationValues } from \"@solve-js/vm/SymbolicOps\";\nimport { expandSymbolic } from \"@solve-js/symbolic/Polynomial\";\nimport { factorSymbolic } from \"@solve-js/symbolic/Factor\";\nimport { cancelSymbolic } from \"@solve-js/symbolic/Gcd\";\nimport { apartSymbolic } from \"@solve-js/symbolic/PartialFractions\";\nimport { differentiate } from \"@solve-js/symbolic/Derivative\";\nimport { integrate } from \"@solve-js/symbolic/Integral\";\nimport { taylorSeries, jacobian } from \"@solve-js/symbolic/Taylor\";\nimport { freeVariables, callNode, constNode, complexNode, complex as complexValue, type SymbolicNode } from \"@solve-js/symbolic\";\nimport { RATIONAL_ZERO, rationalFromNumber } from \"@solve-js/symbolic/Rational\";\n// Type-only, VM.ts imports pluginFunctionRegistry FROM this file, so a\n// runtime import the other direction would be circular; `import type` is\n// erased before compilation and doesn't create that problem.\nimport { defaultEngineContext } from \"@solve-js/engine/EngineContext\";\n// EngineContext is imported for the {@link EngineContext} reference in\n// pluginFunctionRegistry's deprecation note below. Dropping it would leave that\n// link dangling, which is worse than an unused-import warning.\n// eslint-disable-next-line no-unused-vars\nimport type { EngineContext, PluginFunctionHandler } from \"@solve-js/engine/EngineContext\";\nimport { inflationRatio, CPI_MIN_YEAR, CPI_MAX_YEAR } from \"@solve-js/packages/finance/data/CpiTable\";\nimport { UNIT_TABLE } from \"@solve-js/uom/generated/UnitTable.generated\";\n\n/** The angle measure's kind in UNIT_TABLE. Its base unit is the radian. */\nconst ANGLE_KIND = 0;\n\n/**\n * A trig argument in radians.\n *\n * `sin(90 degrees)` used to answer 0.89, because the builtin read the number\n * and discarded the unit, so 90 was taken as 90 radians. The engine already\n * knew the conversion, `90 degrees in radians` has always given 1.5708; the\n * trig functions simply never asked.\n *\n * A plain number is still radians, which is the convention everywhere else and\n * what `sin(pi/2)` relies on.\n */\nfunction angleInRadians(value: Value): number {\n if (value.type === ValueType.Uom && value.unit !== undefined) {\n const entry = UNIT_TABLE[value.unit.toLowerCase()];\n // Every angle entry's ratio converts that spelling to radians.\n if (entry !== undefined && entry[0] === ANGLE_KIND) return value.toNumber() * entry[1];\n }\n return value.toNumber();\n}\n\n/**\n * The plural spelling of a unit, when the count calls for one and the table\n * has it.\n *\n * `$500 at $20/hour` is twenty-five hours, not twenty-five hour. The\n * denominator is written singular in the rate, so a count derived from it\n * inherits the wrong number unless it is adjusted here. Only spellings the\n * unit table already knows are used, so nothing is invented.\n *\n * @param unit - The unit as written.\n * @param count - How many, deciding singular or plural.\n */\nfunction pluraliseUnit(unit: string, count: number): string {\n if (count === 1) return unit;\n const plural = `${unit}s`;\n return UNIT_TABLE[plural.toLowerCase()] === undefined ? unit : plural;\n}\n\n/**\n * The largest or smallest of a list of arguments.\n *\n * A plain loop, replicating Math.min/Math.max's exact semantics for bare\n * numbers (NaN poisons the result wherever it appears; an empty list gives\n * ±Infinity) without the intermediate array a .map()+spread allocates on every\n * call.\n *\n * The two things this does that reading `.toNumber()` off each argument did\n * not:\n *\n * Quantities are compared through unifyUom rather than by their magnitudes, so\n * `max(1 km, 500 m)` is the kilometre. Comparing the bare numbers made 500 the\n * larger of the two, which is the same defect the ordering opcodes in VM.ts\n * had.\n *\n * The winner is returned as it was written rather than as a bare number, so\n * the answer still carries its unit. `max(1 km, 500 m)` returning 500 was\n * wrong twice over: it named the shorter distance AND dropped the unit that\n * would have made the mistake visible. Only a Uom winner is passed through\n * whole; anything else still reduces to a Number, because that is what every\n * other numeric builtin here returns and widening min/max to hand back\n * Datetimes or Percentages is a separate decision from fixing the unit bug.\n *\n * Arguments whose measures do not match cannot be ordered at all, so that is\n * an error rather than an arbitrary pick, matching the ordering opcodes.\n *\n * @param wantLargest - max when true, min when false.\n */\nfunction extremum(args: Value[], wantLargest: boolean): Value {\n let best: Value | undefined;\n let hasNaN = false;\n for (const a of args) {\n if (Number.isNaN(a.toNumber())) { hasNaN = true; continue; }\n if (best === undefined) { best = a; continue; }\n const { lv, rv, sameMeasure } = unifyUom(best, a);\n if (!sameMeasure) {\n const bestUnit = best.type === ValueType.Uom ? best.unit : undefined;\n const otherUnit = a.type === ValueType.Uom ? a.unit : undefined;\n // Same phrasing as the ordering opcodes: name the two dimensions\n // where they differ (\"mass and length cannot be compared\"), keeping\n // the unit-naming fallback for anything with no dimension to name.\n const named = describeMeasureMismatch(bestUnit, otherUnit, \"compared\");\n return errorValue(\n \"INCOMPATIBLE_UNITS\",\n named ?? `Cannot compare incompatible units: ${bestUnit ?? \"?\"} and ${otherUnit ?? \"?\"}`,\n );\n }\n if (wantLargest ? rv > lv : rv < lv) best = a;\n }\n if (hasNaN) return numberValue(NaN);\n if (best === undefined) return numberValue(wantLargest ? -Infinity : Infinity);\n return best.type === ValueType.Uom ? best : numberValue(best.toNumber());\n}\n\n/**\n * Re-wrap a computed magnitude in its operand's unit.\n *\n * The rounding family (round/ceil/floor) and abs change how much of something\n * there is, never what it is, so throwing the unit away is a straight loss of\n * information: `$490 rounded to nearest hundred` answered a bare 500 and\n * `abs(-5 kg)` a bare 5. The first of those is written in\n * `converters/parselets/RoundingParselets.ts`'s own header as `$500`.\n *\n * Only Uom is carried across, matching {@link extremum} above: widening this\n * to Datetime or Percentage is a separate decision from restoring a unit that\n * was already there.\n */\nfunction keepUnit(operand: Value, magnitude: number): Value {\n if (operand.type === ValueType.Uom && operand.unit !== undefined) return uomValue(magnitude, operand.unit);\n return numberValue(magnitude);\n}\n\n/**\n * Round a value to an explicit number of decimal places, recording that place\n * count so the result DISPLAYS at it (see Value's `decimalPlaces`).\n *\n * Backs both spellings of the same idea: the phrase `<x> to N dp` (builtin 97)\n * and the function `round(x, N)` (builtin 8's two-argument form). Rounds from the\n * exact decimal where the value carries one, so `1.005 to 2 dp` and\n * `round(1.005, 2)` are `1.01`, half away from zero, not the `1.00` a double\n * (1.00499...) rounds down to. Without an exact decimal it rounds the double,\n * guarding the point past 2^53 where a double has no fractional digits left to\n * round (scaling further only adds error, so `1e21 to 2 dp` is `1e21`). The\n * unit, if any, rides along.\n */\nfunction roundToPlaces(source: Value, places: number): Value {\n const p = Number.isFinite(places) ? Math.min(100, Math.max(0, Math.trunc(places))) : 0;\n if (source.exact !== undefined) {\n const rounded = decimalRound(source.exact, p);\n return withPlaces(source, decimalToNumber(rounded), p, rounded);\n }\n const value = source.toNumber();\n if (!Number.isFinite(value)) return withPlaces(source, value, p);\n const scale = Math.pow(10, p);\n const scaled = value * scale;\n if (!Number.isFinite(scaled) || Math.abs(scaled) > Number.MAX_SAFE_INTEGER) return withPlaces(source, value, p);\n return withPlaces(source, Math.round(scaled) / scale, p);\n}\n\n/** Carry `source`'s unit onto `magnitude` and stamp its display precision (and exact decimal, when the rounding was exact). */\nfunction withPlaces(source: Value, magnitude: number, places: number, exact?: DecimalData): Value {\n const result = source.type === ValueType.Uom && source.unit !== undefined ? uomValue(magnitude, source.unit) : numberValue(magnitude);\n result.decimalPlaces = places;\n if (exact !== undefined) result.exact = exact;\n return result;\n}\n\n/**\n * Refuses a `gcd`/`lcm` operand that the Euclidean loop cannot terminate on.\n *\n * `while (b !== 0) { [a, b] = [b, a % b] }` relies on the remainder shrinking\n * to zero. A NaN never does, because `NaN !== 0` is true and `NaN % x` is NaN,\n * and an infinity turns into a NaN on the first step and then never does\n * either. So `gcd(4, arccos(2))` spun forever inside ONE opcode, which no\n * ceiling in the engine can see: `maxInstructions` is checked between\n * instructions and the allocation budget counts allocations, and this loop\n * makes neither. The host froze, uninterruptibly, on nine characters of input.\n *\n * Found by the fuzzer as a hang. The same class `DenialOfServiceUnboundedWork.spec.ts`\n * exists for, and the fix is that file's own prescription: bound the loop at\n * the one place that knows the trip count is a number the user typed.\n *\n * @param a - The first operand, already truncated and made positive.\n * @param b - The second, likewise.\n * @param name - Which function to name in the message.\n * @returns An Error Value to return instead, or `null` when the loop is safe.\n */\nfunction nonFiniteEuclidOperand(a: number, b: number, name: string): Value | null {\n if (Number.isFinite(a) && Number.isFinite(b)) return null;\n const culprit = Number.isFinite(a) ? b : a;\n return errorValue(\n \"INVALID_INTEGER_OPERAND\",\n `${name} needs two whole numbers, and ${Number.isNaN(culprit) ? \"one of them has no value\" : \"one of them is infinite\"}`,\n );\n}\n\n/**\n * The Euclidean algorithm, shared by `gcd` and `lcm`.\n *\n * Both had their own inline copy, which is how only one of them would have\n * been fixed. Callers must have refused a non-finite operand first, see\n * {@link nonFiniteEuclidOperand}.\n *\n * @param a - A non-negative, finite integer.\n * @param b - The same.\n * @returns Their greatest common divisor.\n */\nfunction euclidGcd(a: number, b: number): number {\n let x = a;\n let y = b;\n while (y !== 0) {\n const t = y;\n y = x % y;\n x = t;\n }\n return x;\n}\n\n/**\n * Sum of squared deviations from the mean, the numerator both variance forms\n * share. Zero for an empty list.\n */\nfunction sumOfSquares(nums: number[]): number {\n const n = nums.length;\n if (n === 0) return 0;\n const mean = nums.reduce((acc, x) => acc + x, 0) / n;\n return nums.reduce((acc, x) => acc + (x - mean) * (x - mean), 0);\n}\n\n/**\n * Variance in the population form (divide by n) or the sample form (divide by\n * n-1). Returns 0 for an empty list, and for a one-element sample, whose\n * n-1 = 0 has no defined spread, rather than a NaN.\n */\nfunction variance(nums: number[], sample: boolean): number {\n const n = nums.length;\n if (n === 0) return 0;\n const denom = sample ? n - 1 : n;\n if (denom <= 0) return 0;\n return sumOfSquares(nums) / denom;\n}\n\n/**\n * Registry of built-in mathematical functions.\n * Indexed by the number pushed as an operand of OpCode.CALL_BUILTIN.\n */\nexport const builtinFunctions: Record<number, (args: Value[]) => Value> = {\n // ── Populated below ──\n // sqrt: a negative argument has a complex answer now that there is a complex\n // number to give, so this no longer quietly returns NaN. The exact path runs\n // first, so sqrt(-4) is 2i rather than an approximation.\n 0: (args) => {\n const value = args[0].toNumber();\n if (value >= 0) return numberValue(Math.sqrt(value));\n return symbolicToValue(callNode(\"sqrt\", [constNode(value)]));\n },\n // abs(a): for a Matrix, \"|a|\" (Calca's determinant-pipe notation) is a\n // valid alias for det(a) (index 64), reusing the SAME implementation\n // not a separate one. Plain-number abs is unaffected.\n 1: (args) => args[0].type === ValueType.Matrix ? determinant(args[0].value as MatrixData) : keepUnit(args[0], Math.abs(args[0].toNumber())),\n // sin/cos/tan accept an angle with a unit; see angleInRadians().\n 2: (args) => numberValue(Math.sin(angleInRadians(args[0]))),\n 3: (args) => numberValue(Math.cos(angleInRadians(args[0]))),\n 4: (args) => numberValue(Math.tan(angleInRadians(args[0]))),\n 5: (args) => numberValue(Math.log(args[0].toNumber())),\n // round/ceil/floor keep a unit for the same reason abs does; see keepUnit().\n 6: (args) => keepUnit(args[0], Math.ceil(args[0].toNumber())),\n 7: (args) => keepUnit(args[0], Math.floor(args[0].toNumber())),\n 8: (args) =>\n args.length >= 2\n ? // round(x, n): round to n decimal places and display at that precision.\n roundToPlaces(args[0], args[1].toNumber())\n : // round(x): nearest whole number, the way it always was.\n keepUnit(args[0], Math.round(args[0].toNumber())),\n // min/max: see extremum() for why the winner is carried around as a Value\n // rather than as a running number.\n 9: (args) => extremum(args, false),\n 10: (args) => extremum(args, true),\n 11: (args) => numberValue(Math.asin(args[0].toNumber())),\n 12: (args) => numberValue(Math.acos(args[0].toNumber())),\n 13: (args) => numberValue(Math.atan(args[0].toNumber())),\n 14: (args) => numberValue(Math.atan2(args[0].toNumber(), args[1].toNumber())),\n 15: (args) => numberValue(Math.sinh(args[0].toNumber())),\n 16: (args) => numberValue(Math.cosh(args[0].toNumber())),\n 17: (args) => numberValue(Math.tanh(args[0].toNumber())),\n 18: (args) => numberValue(Math.asinh(args[0].toNumber())),\n 19: (args) => numberValue(Math.acosh(args[0].toNumber())),\n 20: (args) => numberValue(Math.atanh(args[0].toNumber())),\n 21: (args) => numberValue(Math.cbrt(args[0].toNumber())),\n 22: (args) => numberValue(Math.clz32(args[0].toNumber())),\n 23: (args) => numberValue(Math.expm1(args[0].toNumber())),\n 24: (args) => numberValue(Math.exp(args[0].toNumber())),\n 25: (args) => numberValue(Math.fround(args[0].toNumber())),\n // hypot: left as .map()+spread (unlike min/max above), Math.hypot uses\n // a numerically-stable scaling algorithm internally to avoid overflow\n // for very large/small inputs; a naive manual reimplementation risks\n // silently changing results at the extremes, so the tiny array\n // allocation here is the safer trade.\n 26: (args) => numberValue(Math.hypot(...args.map(a => a.toNumber()))),\n 27: (args) => numberValue(Math.imul(args[0].toNumber(), args[1].toNumber())),\n 28: (args) => numberValue(Math.log10(args[0].toNumber())),\n 29: (args) => numberValue(Math.log1p(args[0].toNumber())),\n 30: (args) => numberValue(Math.log2(args[0].toNumber())),\n // pow(): the spelled-out form of `^`, so a Matrix base means the same\n // repeated matrix multiplication `^` means. Without this branch\n // `pow([1,2;3,4], 2)` was Math.pow of a value whose toNumber() is 0, and\n // came back as the number 0. See vm/MatrixOps.ts's matrixPower().\n 31: (args) => {\n if (args[0].type === ValueType.Matrix) {\n if (args[1].type !== ValueType.Number) {\n return errorValue(\"MATRIX_POWER_UNSUPPORTED\", `pow: a matrix's exponent must be a whole number, as in \"pow([1,2;3,4], 2)\".`);\n }\n return matrixPower(args[0].value as MatrixData, args[1].value as number);\n }\n if (args[1].type === ValueType.Matrix) {\n return errorValue(\"MATRIX_POWER_UNSUPPORTED\", `pow: a matrix may only be the base, as in \"pow([1,2;3,4], 2)\".`);\n }\n // The spelled-out form of `^` answers what `^` answers, edge cases\n // included. See power() in vm/VMConversion.ts.\n return numberValue(power(args[0].toNumber(), args[1].toNumber()));\n },\n 32: () => numberValue(Math.random()), // takes no arguments, unlike its neighbours\n 33: (args) => numberValue(Math.sign(args[0].toNumber())),\n 34: (args) => numberValue(Math.trunc(args[0].toNumber())),\n 35: (args) => numberValue(args[0].toNumber() * Math.PI / 180),\n 36: (args) => numberValue(args[0].toNumber() * 180 / Math.PI),\n // 37: diceRoll(from, to), random integer in range [from, to] inclusive.\n // A reversed range (from > to) used to silently produce values outside\n // [to, from] via a negative-length Math.random() spread (e.g.\n // \"roll(6, 1)\" returning values like 2-5, never 1 or 6) instead of\n // erroring on the invalid input.\n 37: (args) => {\n const from = args[0].toNumber();\n const to = args[1].toNumber();\n if (from > to) {\n return errorValue(\"INVALID_RANGE\", `roll: invalid range, ${from} is greater than ${to}`);\n }\n return numberValue(Math.floor(Math.random() * (to - from + 1)) + from);\n },\n // gcd(a, b), Euclidean algorithm. Negative inputs are treated by\n // magnitude (gcd is conventionally defined over non-negative integers).\n 38: (args) => {\n const a = Math.trunc(Math.abs(args[0].toNumber()));\n const b = Math.trunc(Math.abs(args[1].toNumber()));\n const nonFinite = nonFiniteEuclidOperand(a, b, \"gcd\");\n if (nonFinite) return nonFinite;\n return numberValue(euclidGcd(a, b));\n },\n // lcm(a, b) = |a*b| / gcd(a, b), via the same Euclidean gcd inline\n // (a standalone gcd() call site, no shared helper needed for two uses).\n 39: (args) => {\n const a = Math.trunc(Math.abs(args[0].toNumber()));\n const b = Math.trunc(Math.abs(args[1].toNumber()));\n const nonFinite = nonFiniteEuclidOperand(a, b, \"lcm\");\n if (nonFinite) return nonFinite;\n if (a === 0 || b === 0) return numberValue(0);\n return numberValue((a / euclidGcd(a, b)) * b);\n },\n // permutation(n, r) = n! / (n-r)!, computed as a running product\n // rather than two full factorials, so it stays exact for n well\n // beyond where n! itself would exceed Number.MAX_SAFE_INTEGER.\n //\n // The loop stops the moment the product stops being a representable\n // double, which is both the answer `fact` (index 62) already gives for\n // the same question and the thing that bounds the loop at all. `r` comes\n // straight off the stack: `permutation(1000000000000, 1000000000000)`\n // used to run a trillion iterations, of which the first ~170 computed\n // something and the rest multiplied Infinity by a number, and it had not\n // returned after thirty seconds. Every factor here is at least 1 and they\n // descend from `n`, so a product that is still finite after 170 steps\n // means the factors are small, which in turn means `r <= n` is small: the\n // early exit bounds the trip count without a separate estimate, and\n // without ever refusing a permutation that does have an answer.\n 40: (args) => {\n const n = Math.trunc(args[0].toNumber());\n const r = Math.trunc(args[1].toNumber());\n if (n < 0 || r < 0 || r > n) {\n return errorValue(\"INVALID_RANGE\", `permutation: invalid n=${n}, r=${r} (require 0 <= r <= n)`);\n }\n let result = 1;\n for (let i = 0; i < r; i++) {\n result *= (n - i);\n if (!Number.isFinite(result)) {\n return errorValue(\n \"PERMUTATION_OVERFLOW\",\n `permutation: P(${n}, ${r}) exceeds the maximum representable double (it passed it after ${i + 1} of ${r} factors)`,\n );\n }\n }\n return numberValue(result);\n },\n // combination(n, r) = n! / (r! * (n-r)!), multiply-then-divide one\n // step at a time (standard technique) keeps every intermediate result\n // an integer, avoiding the overflow a naive factorial-ratio would hit.\n //\n // Same early exit, and needed for the same reason: `k = min(r, n-r)`\n // halves the trip count and bounds nothing, so `combination(1e12, 5e11)`\n // asked for five hundred billion iterations. The running value is C(n, i),\n // which grows monotonically to the middle, so once it is past what a\n // double can hold it never comes back, and the largest run this can now\n // take is the thousand-odd steps C(n, k) needs to cross that line.\n 41: (args) => {\n const n = Math.trunc(args[0].toNumber());\n const r = Math.trunc(args[1].toNumber());\n if (n < 0 || r < 0 || r > n) {\n return errorValue(\"INVALID_RANGE\", `combination: invalid n=${n}, r=${r} (require 0 <= r <= n)`);\n }\n const k = Math.min(r, n - r);\n let result = 1;\n for (let i = 0; i < k; i++) {\n result = (result * (n - i)) / (i + 1);\n if (!Number.isFinite(result)) {\n return errorValue(\n \"COMBINATION_OVERFLOW\",\n `combination: C(${n}, ${r}) exceeds the maximum representable double (it passed it after ${i + 1} of ${k} steps)`,\n );\n }\n }\n return numberValue(Math.round(result));\n },\n // average(...), arithmetic mean of any number of arguments. Backs the\n // MathPhrases package's \"average of X, Y, Z\" (packages/mathphrases/).\n 42: (args) => {\n if (args.length === 0) return numberValue(0);\n const sum = args.reduce((acc, a) => acc + a.toNumber(), 0);\n return numberValue(sum / args.length);\n },\n // median(...), middle value; average of the two middle values for an\n // even argument count.\n 43: (args) => {\n if (args.length === 0) return numberValue(0);\n const sorted = args.map((a) => a.toNumber()).sort((a, b) => a - b);\n const mid = Math.floor(sorted.length / 2);\n return numberValue(\n sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid]\n );\n },\n // total(...), sum of any number of arguments.\n 44: (args) => numberValue(args.reduce((acc, a) => acc + a.toNumber(), 0)),\n // count(...), number of arguments passed.\n 45: (args) => numberValue(args.length),\n // proportion(a, b, c) -> d such that a:b = c:d, i.e. d = c * (b/a)\n // \"A is to B as C is to what\". Unit-aware via unifyUom: \"5 km is to\n // 500m as 5 cm is to what\" unifies 5km/500m to a 10:1 ratio (500m ==\n // 0.5km), so 5cm at the same ratio -> 0.5cm. Falls back to plain\n // toNumber() ratios when the units aren't the same measure (unifyUom's\n // own fallback) rather than guessing at an unsupported conversion.\n 46: (args) => {\n const [a, b, c] = args;\n const { lv: aNum, rv: bNum } = unifyUom(a, b);\n if (aNum === 0) {\n return errorValue(\"PROPORTION_DIVIDE_BY_ZERO\", `Cannot compute proportion: \"${a.value}\" is zero`);\n }\n const result = c.toNumber() * (bNum / aNum);\n return c.type === ValueType.Uom ? uomValue(result, c.unit!) : numberValue(result);\n },\n // clamp(value, lo, hi), restrict value to [lo, hi]. Backs\n // \"clamp X between Y and Z\" / \"clamp X from Y to Z\".\n 47: (args) => {\n const value = args[0].toNumber();\n const lo = args[1].toNumber();\n const hi = args[2].toNumber();\n if (lo > hi) {\n return errorValue(\"INVALID_RANGE\", `clamp: invalid range, ${lo} is greater than ${hi}`);\n }\n return numberValue(Math.min(Math.max(value, lo), hi));\n },\n // hex(n), Python/JS-style call-syntax hex formatting, e.g. hex(255) ->\n // \"0xFF\". Distinct from the Converters package's `255 as hex` (see\n // packages/converters/parselets/AsConverterParselet.ts): \"as hex\"\n // produces a ValueType.Hex (a typed NUMBER that still participates in\n // arithmetic, formatted specially on display), while hex() is a plain\n // function call that returns an ordinary String value, matching\n // Python's hex()/JS convention of a function returning display text,\n // not a numeric type.\n 48: (args) => hexValue(args[0].toNumber()),\n // bin(n). Same call-syntax shape as hex() above, e.g. bin(10) -> \"0b1010\".\n 49: (args) => hexValue(args[0].toNumber(), \"bin\"),\n // int(x), coerce ANY value (Number, Percentage, Uom, String, Hex, ...)\n // to a plain integer Number, truncating any fractional part toward\n // zero (Math.trunc semantics: int(5.7) -> 5, int(-5.7) -> -5). Distinct\n // from the Converters package's `x as number` (TO_NUMBER opcode),\n // which only strips a unit/percentage wrapper and keeps any decimal\n // part (e.g. \"5.7 as number\" -> 5.7), int() additionally truncates.\n 50: (args) => numberValue(Math.trunc(args[0].toNumber())),\n\n // ── Finance (packages/finance/) ──────────────────────────────────────\n // All finance builtins preserve the principal/amount argument's Uom\n // unit (e.g. a currency like \"$\") onto the result, matching\n // ProportionParselet's convention (index 46, above), a plain-number\n // input produces a plain-number result.\n //\n // `rate` arguments are always a decimal fraction (e.g. 0.07 for 7%)\n // this is how \"%\" already normalizes everywhere else in this codebase\n // (see packages/percentage/parselets/PercentParselet.ts: \"7%\" divides\n // by 100 at parse time, producing a plain Number 0.07, not a distinct\n // percentage type). Writing \"at 7\" instead of \"at 7%\" in a phrase form\n // passes 7 as-is (not 0.07), the \"%\" is not implicit.\n\n // compoundFutureValue(principal, rate, years) -> FV = P*(1+r)^years.\n // Backs \"compound interest on $P over Y years at R%\" and the\n // compoundInterest(principal, rate, years) function-call form.\n 51: (args) => {\n const principal = args[0].toNumber();\n const rate = args[1].toNumber();\n const years = args[2].toNumber();\n if (1 + rate <= 0) {\n return errorValue(\"INVALID_RATE\", `compoundInterest: rate ${rate} makes (1 + rate) non-positive`);\n }\n const fv = principal * Math.pow(1 + rate, years);\n return args[0].type === ValueType.Uom ? uomValue(fv, args[0].unit!) : numberValue(fv);\n },\n // compoundInterestEarned(principal, rate, years) -> FV - principal, the\n // interest-only portion. Backs \"interest on $P over Y years at R%\" and\n // the interestEarned(principal, rate, years) function-call form.\n 52: (args) => {\n const principal = args[0].toNumber();\n const rate = args[1].toNumber();\n const years = args[2].toNumber();\n if (1 + rate <= 0) {\n return errorValue(\"INVALID_RATE\", `interestEarned: rate ${rate} makes (1 + rate) non-positive`);\n }\n const interest = principal * (Math.pow(1 + rate, years) - 1);\n return args[0].type === ValueType.Uom ? uomValue(interest, args[0].unit!) : numberValue(interest);\n },\n // compoundInterestRate(principal, futureValue, years) -> the rate (as a\n // decimal fraction) needed to grow principal to futureValue over years.\n // Function-call only, no clean phrase form for a reverse calculation\n // like this without inventing awkward new keywords, so it's scoped to\n // compoundInterestRate(...) rather than a natural-language phrase.\n 53: (args) => {\n const principal = args[0].toNumber();\n const futureValue = args[1].toNumber();\n const years = args[2].toNumber();\n if (principal <= 0 || futureValue <= 0) {\n return errorValue(\"INVALID_RANGE\", `compoundInterestRate: principal and futureValue must both be positive`);\n }\n if (years <= 0) {\n return errorValue(\"INVALID_RANGE\", `compoundInterestRate: years must be greater than 0`);\n }\n return numberValue(Math.pow(futureValue / principal, 1 / years) - 1);\n },\n // compoundInterestYears(principal, futureValue, rate) -> the number of\n // years needed to grow principal to futureValue at a fixed rate.\n // Function-call only, same reasoning as index 53 above.\n 54: (args) => {\n const principal = args[0].toNumber();\n const futureValue = args[1].toNumber();\n const rate = args[2].toNumber();\n if (principal <= 0 || futureValue <= 0) {\n return errorValue(\"INVALID_RANGE\", `compoundInterestYears: principal and futureValue must both be positive`);\n }\n if (1 + rate <= 0 || rate === 0) {\n return errorValue(\"INVALID_RATE\", `compoundInterestYears: rate ${rate} is not usable (must be > -1 and not 0)`);\n }\n return numberValue(Math.log(futureValue / principal) / Math.log(1 + rate));\n },\n // loanRepayment(principal, rate, years, periodsPerYear), standard\n // amortizing-loan repayment (mortgage formula), redistributed evenly\n // across `periodsPerYear` periods/year: 365=daily, 12=monthly, 1=annual,\n // 0=total over the life of the loan. The loan is ALWAYS amortized\n // monthly internally (the standard mortgage convention) regardless of\n // periodsPerYear, \"daily\"/\"annual\"/\"total\" are the same total\n // repayment redistributed, not separately-amortized loans. Verified\n // against real worked numbers (principal=$10,000, rate=6%, years=6):\n // monthly $165.73, annual $1,988.75 (== total/years exactly), daily\n // $5.45 (== total/(years*365)), total $11,932.48.\n // Backs \"daily/monthly/annual/total repayment on $P over Y years at R%\".\n 55: (args) => {\n const principal = args[0].toNumber();\n const rate = args[1].toNumber();\n const years = args[2].toNumber();\n const periodsPerYear = args[3].toNumber();\n if (principal <= 0) return errorValue(\"INVALID_RANGE\", `loanRepayment: principal must be positive`);\n if (years <= 0) return errorValue(\"INVALID_RANGE\", `loanRepayment: years must be positive`);\n if (rate < 0) return errorValue(\"INVALID_RATE\", `loanRepayment: rate must not be negative`);\n if (periodsPerYear < 0) return errorValue(\"INVALID_RANGE\", `loanRepayment: periodsPerYear must not be negative`);\n const { totalRepayment } = amortizeLoan(principal, rate, years);\n const result = periodsPerYear === 0 ? totalRepayment : totalRepayment / (years * periodsPerYear);\n return args[0].type === ValueType.Uom ? uomValue(result, args[0].unit!) : numberValue(result);\n },\n // loanInterest(principal, rate, years, periodsPerYear), the interest\n // portion of index 55's repayment, same periodsPerYear convention.\n // Backs \"daily/monthly/annual/total interest on $P over Y years at R%\".\n 56: (args) => {\n const principal = args[0].toNumber();\n const rate = args[1].toNumber();\n const years = args[2].toNumber();\n const periodsPerYear = args[3].toNumber();\n if (principal <= 0) return errorValue(\"INVALID_RANGE\", `loanInterest: principal must be positive`);\n if (years <= 0) return errorValue(\"INVALID_RANGE\", `loanInterest: years must be positive`);\n if (rate < 0) return errorValue(\"INVALID_RATE\", `loanInterest: rate must not be negative`);\n if (periodsPerYear < 0) return errorValue(\"INVALID_RANGE\", `loanInterest: periodsPerYear must not be negative`);\n const { totalInterest } = amortizeLoan(principal, rate, years);\n const result = periodsPerYear === 0 ? totalInterest : totalInterest / (years * periodsPerYear);\n return args[0].type === ValueType.Uom ? uomValue(result, args[0].unit!) : numberValue(result);\n },\n // monthlyPayment(principal, rate, years), convenience 3-arg wrapper\n // around index 55's monthly case, for direct function-call use without\n // the periodsPerYear parameter (the task's minimum-ask function form).\n 57: (args) => {\n const principal = args[0].toNumber();\n const rate = args[1].toNumber();\n const years = args[2].toNumber();\n if (principal <= 0) return errorValue(\"INVALID_RANGE\", `monthlyPayment: principal must be positive`);\n if (years <= 0) return errorValue(\"INVALID_RANGE\", `monthlyPayment: years must be positive`);\n if (rate < 0) return errorValue(\"INVALID_RATE\", `monthlyPayment: rate must not be negative`);\n const { monthlyPayment } = amortizeLoan(principal, rate, years);\n return args[0].type === ValueType.Uom ? uomValue(monthlyPayment, args[0].unit!) : numberValue(monthlyPayment);\n },\n // taxAdd(amount, rate) -> amount * (1 + rate), the tax-inclusive total.\n // Backs the taxAdd() function-call form, whose name promises exactly this.\n // The \"tax on $X at R%\" PHRASE does NOT use it, see index 86.\n //\n // No default rate is baked in anywhere, the caller always supplies one\n // explicitly, since tax rates vary by region and change over time; this\n // package makes no assumption about which rate applies.\n 58: (args) => {\n const amount = args[0].toNumber();\n const rate = args[1].toNumber();\n // Money stays exact: `$X * (1 + R)` is formed in base ten so the\n // tax-inclusive total does not drift a half-cent (see MoneyExact.ts). A\n // non-currency Uom and a bare number keep their existing float result.\n if (args[0].type === ValueType.Uom) return scaleMoneyByPercent(args[0], args[0].unit!, rate, 1);\n return numberValue(amount * (1 + rate));\n },\n // taxRemove(amount, rate) -> amount / (1 + rate), extracts the\n // pre-tax amount from a tax-INCLUSIVE total. Backs \"tax off $X at R%\" /\n // \"VAT off $X at R%\".\n 59: (args) => {\n const amount = args[0].toNumber();\n const rate = args[1].toNumber();\n if (1 + rate <= 0) {\n return errorValue(\"INVALID_RATE\", `taxRemove: rate ${rate} makes (1 + rate) non-positive`);\n }\n if (args[0].type === ValueType.Uom) {\n // Money stays exact: `$X / (1 + R)` rounds the half-cent like a till\n // (`tax off $0.09 at 20%` is `$0.08`, not the `$0.07` the float lands\n // on). A non-currency Uom passes straight through the same helper to\n // the float path. See MoneyExact.ts.\n return removeTaxExact(args[0], args[0].unit!, rate) ?? uomValue(amount / (1 + rate), args[0].unit!);\n }\n return numberValue(amount / (1 + rate));\n },\n\n // inflationAdjust(amount, fromYear, toYear) -- CPI-based inflation\n // adjustment between two arbitrary years, using the bundled CPI-U\n // table (packages/finance/data/CpiTable.ts -- see its doc comment for\n // vintage/accuracy notes). Backs the function-call form\n // inflationAdjust(...) (FunctionCallParselet's builtinNameToIndex map)\n // and the \"what is $X in fromYear worth in toYear\" phrase form\n // (InflationQueryParselet.ts). The two present-year-relative phrase\n // forms (\"what is $X from year\" / \"what was $X worth in year\" / \"$X\n // in year dollars\") and the flat-rate future-value projection (\"value\n // of $X in year assuming N% inflation\") are collision-safe\n // pluginFunctions instead, not indices here -- see\n // packages/finance/parselets/InflationPluginFunctions.ts.\n 60: (args) => {\n const amount = args[0].toNumber();\n const fromYear = args[1].toNumber();\n const toYear = args[2].toNumber();\n const ratio = inflationRatio(fromYear, toYear);\n if (ratio === undefined) {\n return errorValue(\n \"INFLATION_YEAR_OUT_OF_RANGE\",\n `inflationAdjust: fromYear ${fromYear} or toYear ${toYear} is outside the bundled CPI table's range (${CPI_MIN_YEAR}-${CPI_MAX_YEAR})`,\n );\n }\n const result = amount * ratio;\n return args[0].type === ValueType.Uom ? uomValue(result, args[0].unit!) : numberValue(result);\n },\n\n // root(n, x) -- the n-th root of x (Numi's `root n (x)` phrasing maps\n // to this same call-style form; see FunctionCallParselet's name map).\n // No native Math.root exists (unlike Math.cbrt for n=3 specifically),\n // so this is Math.pow(x, 1/n) directly -- exact for n=2/n=3 modulo the\n // usual floating-point pow() rounding, same precision class as every\n // other builtin here.\n 61: (args) => {\n const n = args[0].toNumber();\n const x = args[1].toNumber();\n return numberValue(power(x, 1 / n));\n },\n\n // fact(n) / factorial(n) -- integer factorial. Deliberately rejects\n // negative or non-integer input (factorial isn't defined for either\n // without a gamma-function generalization this engine doesn't need) and\n // caps at 170 -- Number.MAX_VALUE overflows to Infinity at 171!, so\n // returning a silently-wrong (or silently-infinite) result past that\n // point would be worse than a clear error.\n 62: (args) => {\n const n = args[0].toNumber();\n if (!Number.isInteger(n) || n < 0) {\n return errorValue(\"INVALID_FACTORIAL_INPUT\", `fact: ${n} is not a non-negative integer`);\n }\n if (n > 170) {\n return errorValue(\"FACTORIAL_OVERFLOW\", `fact: ${n}! exceeds the maximum representable double (170! is the largest finite factorial)`);\n }\n let result = 1;\n for (let i = 2; i <= n; i++) result *= i;\n return numberValue(result);\n },\n\n // ── Matrix (packages/matrix/) ────────────────────────────────────────\n // transpose(a)/det(a)/inv(a)/dot(a,b), reachable both via ordinary\n // function-call syntax (this map) and via operator syntax (`^T`, `^-1`\n //. See PrecedenceParser.ts's CARET special-casing, which emits these\n // SAME indices) and `|a|` (abs()'s Matrix branch, index 1 above).\n // Real linear-algebra work lives in vm/MatrixOps.ts, shared by both\n // entry points rather than duplicated.\n\n // transpose(a), for a Matrix, swaps rows/cols. A plain Number is its\n // own transpose (a 1x1 \"matrix\" transposed is itself), matches this\n // engine's existing convention of treating a scalar as a trivial 1x1\n // matrix (see Value.ts's toNumber()/isNaN() 1x1 special case).\n 63: (args) => args[0].type === ValueType.Matrix ? transpose(args[0].value as MatrixData) : args[0],\n // det(a), determinant. A plain Number's \"determinant\" is itself (the\n // determinant of a 1x1 matrix [x] is x).\n 64: (args) => args[0].type === ValueType.Matrix ? determinant(args[0].value as MatrixData) : numberValue(args[0].toNumber()),\n // inv(a), matrix inverse for a Matrix; for a plain Number, `1/x`\n // (byte-identical to `Math.pow(x, -1)`, which is what `x^-1` computed\n // before this feature existed. See PrecedenceParser.ts's `^-1`\n // special-case doc comment for why this must stay exact).\n 65: (args) => {\n if (args[0].type === ValueType.Matrix) return inverse(args[0].value as MatrixData);\n return numberValue(1 / args[0].toNumber());\n },\n // dot(a, b), matrix product / scalar-broadcast, the SAME dispatch as\n // the `*` operator between two matrices (vm/VM.ts's MUL case). Plain\n // Number operands multiply directly; a Number mixed with a Matrix\n // promotes the Number to a 1x1 Matrix first, so it broadcasts exactly\n // like matrixMultiply()'s own 1x1-scalar case.\n 66: (args) => {\n const [a, b] = args;\n if (a.type === ValueType.Number && b.type === ValueType.Number) {\n return numberValue(a.toNumber() * b.toNumber());\n }\n const toMatrix = (v: Value): MatrixData =>\n v.type === ValueType.Matrix ? (v.value as MatrixData) : { rows: 1, cols: 1, data: [v.toNumber()], hasSymbolic: false };\n return matrixMultiply(toMatrix(a), toMatrix(b));\n },\n // ── Symbolic algebra (packages/symbolic/) ──\n // expand(expr), multiplying out every product and power. Reached only\n // through its own parselet, never the builtinNameToIndex name map, so that\n // `expand` keeps working as an ordinary variable name; see\n // packages/symbolic/normalizer/SymbolicCallNormalizerRule.ts.\n //\n // A non-symbolic argument has nothing to expand and is returned unchanged,\n // which is why this does not go through the CALL_BUILTIN symbolic dispatch:\n // `expand(2+3)` is simply 5.\n 67: (args) => {\n const [value] = args;\n if (value.type !== ValueType.Symbolic) return value;\n return symbolicToValue(expandSymbolic(value.value as SymbolicNode));\n },\n // factor(expr), writing a polynomial as a product of irreducible factors\n // over the RATIONALS. x^2-2 and x^2+1 come back unchanged, which is the\n // correct answer over that field rather than a failure; see symbolic/Factor.ts.\n 68: (args) => {\n const [value] = args;\n if (value.type !== ValueType.Symbolic) return value;\n return symbolicToValue(factorSymbolic(value.value as SymbolicNode));\n },\n // solve(equation, variable), emitted by its own parselet as three stack\n // values: the two sides of the equation, then the variable NAME as a\n // String. Reading the name as a string rather than compiling it as a\n // variable read is what lets `solve(x^2-4=0, x)` work without `x` existing.\n 69: (args) => {\n const [lhsValue, rhsValue, variableValue] = args;\n if (variableValue?.type !== ValueType.String) {\n return errorValue(\"SOLVE_REQUIRES_VARIABLE_NAME\", \"solve's second argument must be the name of the unknown.\");\n }\n return solveEquationValues(lhsValue, rhsValue, variableValue.value as string);\n },\n // der(expr, variable, order), the symbolic derivative. Genuinely symbolic\n // rather than a finite difference, so it is exact.\n 70: (args) => {\n const [target, variableValue, orderValue] = args;\n const variable = symbolicVariableName(variableValue, \"der\");\n if (typeof variable !== \"string\") return variable;\n const expression = valueToSymbolic(target);\n if (expression === null) return errorValue(\"SYMBOLIC_NONFINITE_OPERAND\", \"der needs an expression with an exact value.\");\n return symbolicToValue(differentiate(expression, variable, orderValue?.toNumber() ?? 1));\n },\n // integral(expr, variable), the indefinite integral without a constant of\n // integration. Reports what it cannot do rather than approximating; see\n // symbolic/Integral.ts.\n 71: (args) => {\n const [target, variableValue] = args;\n const variable = symbolicVariableName(variableValue, \"integral\");\n if (typeof variable !== \"string\") return variable;\n const expression = valueToSymbolic(target);\n if (expression === null) return errorValue(\"SYMBOLIC_NONFINITE_OPERAND\", \"integral needs an expression with an exact value.\");\n const result = integrate(expression, variable);\n if (!result.ok) return errorValue(\"SYMBOLIC_INTEGRAL_UNSUPPORTED\", `Cannot integrate this: ${result.reason}.`);\n return symbolicToValue(result.value);\n },\n // taylor(expr, variable = point, degree).\n 72: (args) => {\n const [target, variableValue, pointValue, degreeValue] = args;\n const variable = symbolicVariableName(variableValue, \"taylor\");\n if (typeof variable !== \"string\") return variable;\n const expression = valueToSymbolic(target);\n const point = valueToSymbolic(pointValue);\n if (expression === null || point === null || point.kind !== \"const\") {\n return errorValue(\"SYMBOLIC_NONFINITE_OPERAND\", \"taylor needs an expression and an exact expansion point.\");\n }\n return symbolicToValue(taylorSeries(expression, variable, point.value, degreeValue.toNumber()));\n },\n // jacobian(f1, f2, ...), variadic. The variables are not named: they come\n // from the union of the functions' own unknowns, sorted, matching Calca.\n 73: (args) => {\n const functions: SymbolicNode[] = [];\n for (const arg of args) {\n const node = valueToSymbolic(arg);\n if (node === null) return errorValue(\"SYMBOLIC_NONFINITE_OPERAND\", \"jacobian needs expressions with exact values.\");\n functions.push(node);\n }\n const variables = new Set<string>();\n for (const fn of functions) for (const name of freeVariables(fn)) variables.add(name);\n const sorted = [...variables].sort();\n if (sorted.length === 0) return errorValue(\"SYMBOLIC_JACOBIAN_NO_VARIABLES\", \"jacobian needs at least one unknown to differentiate against.\");\n\n const rows = jacobian(functions, sorted);\n // Row-major here, which matrixValue's own helper converts to the\n // column-major storage MatrixData uses.\n const rowMajor: (number | boolean | SymbolicNode)[] = [];\n for (const row of rows) {\n for (const cell of row) rowMajor.push(symbolicToEntry(cell));\n }\n return matrixValue(rows.length, sorted.length, rowMajorToColumnMajor(rows.length, sorted.length, rowMajor));\n },\n // An imaginary literal, 3i. The parselet pushes the numeric part and this\n // turns it into an exact imaginary value.\n 74: (args) => symbolicToValue(complexNode(complexValue(RATIONAL_ZERO, rationalFromNumber(args[0].toNumber())))),\n // conj(z), re(z) and im(z). Each folds immediately for a literal and stays\n // symbolic for anything still carrying an unknown.\n 75: (args) => applyComplexAccessor(\"conj\", args[0]),\n 76: (args) => applyComplexAccessor(\"re\", args[0]),\n 77: (args) => applyComplexAccessor(\"im\", args[0]),\n // cancel(expr), reducing a quotient of polynomials to lowest terms.\n 78: (args) => {\n const value = args[0];\n if (value.type !== ValueType.Symbolic) return value;\n return symbolicToValue(cancelSymbolic(value.value as SymbolicNode));\n },\n // apart(expr), the partial-fraction decomposition of a rational function.\n 79: (args) => {\n const value = args[0];\n if (value.type !== ValueType.Symbolic) return value;\n return symbolicToValue(apartSymbolic(value.value as SymbolicNode));\n },\n // taxIn(amount, rate) -> amount - amount/(1 + rate), the tax already\n // contained in a tax-INCLUSIVE total. Backs \"tax in/of/from $X at R%\".\n // The complement of taxRemove (index 59): the two sum to the gross amount.\n 85: (args) => {\n const amount = args[0].toNumber();\n const rate = args[1].toNumber();\n if (1 + rate <= 0) {\n return errorValue(\"INVALID_RATE\", `taxIn: rate ${rate} makes (1 + rate) non-positive`);\n }\n const tax = amount - amount / (1 + rate);\n if (args[0].type === ValueType.Uom) {\n // Money stays exact: `$X - $X / (1 + R)` rounds the half-cent like a\n // till (`tax in $0.09 at 20%` is `$0.02`, not `$0.01`), and stays the\n // exact complement of `tax off` so the two sum back to the gross. A\n // non-currency Uom keeps the float. See MoneyExact.ts.\n return taxInExact(args[0], args[0].unit!, rate) ?? uomValue(tax, args[0].unit!);\n }\n return numberValue(tax);\n },\n // taxOn(amount, rate) -> amount * rate, the tax itself.\n //\n // The \"tax on $X at R%\" phrase used to compile to taxAdd (index 58) and\n // answer $345.00 for \"tax on $300 at 15%\". Soulver answers $45.00, and\n // \"the tax on $300\" is the tax, not the bill. The total is \"$300 + 15%\",\n // which reads as a relative increase (see PercentParselet.ts), or\n // taxAdd(300, 0.15) for the function form.\n 86: (args) => {\n const amount = args[0].toNumber();\n const rate = args[1].toNumber();\n // Money stays exact: `$X * R` is formed in base ten so the tax rounds\n // like a till (`tax on $10.10 at 15%` is `$1.52`, not the `$1.51` a\n // double lands on). See MoneyExact.ts. A non-currency Uom passes\n // straight through the same helper; a bare number keeps its float.\n if (args[0].type === ValueType.Uom) return scaleMoneyExact(args[0], rate, args[0].unit!);\n return numberValue(amount * rate);\n },\n // ── Degree-taking trig (sind/cosd/tand and the inverses) ──────────────\n // The \"d\" spellings take and return degrees rather than radians, which is\n // the convention every scientific calculator uses. sin(90 degrees) is the\n // other way to say the same thing; both exist because both get typed.\n 87: (args) => numberValue(Math.sin(args[0].toNumber() * Math.PI / 180)),\n 88: (args) => numberValue(Math.cos(args[0].toNumber() * Math.PI / 180)),\n 89: (args) => numberValue(Math.tan(args[0].toNumber() * Math.PI / 180)),\n 90: (args) => numberValue(Math.asin(args[0].toNumber()) * 180 / Math.PI),\n 91: (args) => numberValue(Math.acos(args[0].toNumber()) * 180 / Math.PI),\n 92: (args) => numberValue(Math.atan(args[0].toNumber()) * 180 / Math.PI),\n // daysCount(n) -> n labelled as days. \"days in Q3\" is a count of days\n // and should say so; a bare 92 loses what was being counted.\n 93: (args) => uomValue(args[0].toNumber(), \"days\"),\n // asTwoUnits(value, majorUnit, minorUnit) -> \"12 min 30 s\".\n //\n // \"12.5 minutes in minutes and seconds\" asks for one quantity split\n // across two units, which every other conversion path cannot express:\n // they each produce a single number in a single unit.\n //\n // The whole part goes to the major unit and the remainder to the minor,\n // so nothing is lost. A pair that is not ordered major-then-minor, or\n // that spans two different measures, reports rather than guessing.\n 94: (args) => {\n // Read rather than cast. The parselet always pairs this builtin with two\n // PUSH_STRINGs, but `executeBytecode` is a public export, so a\n // hand-built stream can leave any Value here and the cast is\n // compile-time only: `major.toLowerCase()` on a boolean threw a raw\n // TypeError that reached the host as an unexplained internal error.\n const major = typeof args[1]?.value === \"string\" ? args[1].value : undefined;\n const minor = typeof args[2]?.value === \"string\" ? args[2].value : undefined;\n if (major === undefined || minor === undefined) {\n return errorValue(\"UNKNOWN_UNIT\", \"both units have to be named, as in \\\"12.5 minutes in minutes and seconds\\\"\");\n }\n const majorEntry = UNIT_TABLE[major.toLowerCase()] as readonly [number, number] | undefined;\n const minorEntry = UNIT_TABLE[minor.toLowerCase()] as readonly [number, number] | undefined;\n if (majorEntry === undefined || minorEntry === undefined) {\n return errorValue(\"UNKNOWN_UNIT\", `${major} and ${minor}: one of these is not a unit`);\n }\n if (majorEntry[0] !== minorEntry[0]) {\n return errorValue(\"INCOMPATIBLE_UNITS\", `${major} and ${minor} measure different things`);\n }\n if (minorEntry[1] >= majorEntry[1]) {\n return errorValue(\"INCOMPATIBLE_UNITS\", `${major} and ${minor}: name the larger unit first`);\n }\n const source = args[0];\n const sourceEntry = source.type === ValueType.Uom && source.unit !== undefined\n ? (UNIT_TABLE[source.unit.toLowerCase()] as readonly [number, number] | undefined)\n : undefined;\n const inBase = source.toNumber() * (sourceEntry?.[1] ?? majorEntry[1]);\n const majorCount = Math.floor(inBase / majorEntry[1]);\n const minorCount = Math.round(((inBase - majorCount * majorEntry[1]) / minorEntry[1]) * 1000) / 1000;\n return stringValue(`${majorCount} ${major} ${minorCount} ${minor}`);\n },\n // makeRate(value, denominatorUnit) -> value per that unit.\n //\n // `3 hours / day` is a rate, `3 hours / 3 days` is a division. The\n // difference is whether a number was written in the denominator, which\n // is decided at parse time, so this only ever receives the rate case.\n //\n // Building the rate directly rather than dividing by an implied 1 is the\n // whole point: a division makes same-measure units cancel, which turned\n // `3 hours / day` into 0.125 when that shortcut was tried.\n 95: (args) => {\n const source = args[0];\n const denominator = String(args[1].value);\n const numerator = source.type === ValueType.Uom && source.unit !== undefined\n ? source.unit\n : \"\";\n if (numerator.includes(\"/\")) {\n return errorValue(\"INVALID_RATE_UNIT\", `${numerator}/${denominator}: that is already a rate`);\n }\n // A bare number over a unit is a countless rate, \"30/week\", which the\n // rate machinery already renders without a numerator unit.\n return uomValue(source.toNumber(), `${numerator}/${denominator}`);\n },\n // atRate(quantity, rate) -> whichever of the two the question implies.\n //\n // 30 hours at $30/hour $900 a duration at a price per duration\n // $500 at $20/hour 25 hours money at a price per duration\n //\n // Both are written with the same word and mean opposite operations. Which\n // one applies is decided by which half of the rate the left side matches:\n // match the denominator and you are buying that many, match the numerator\n // and you are asking how many it buys.\n 96: (args) => {\n const left = args[0];\n const rate = args[1];\n if (rate.type !== ValueType.Uom || rate.unit === undefined || !rate.unit.includes(\"/\")) {\n return errorValue(\"INVALID_RATE\", \"at: the right-hand side has to be a rate, as in \\\"$30/hour\\\"\");\n }\n const slash = rate.unit.indexOf(\"/\");\n const numerator = rate.unit.slice(0, slash);\n const denominator = rate.unit.slice(slash + 1);\n const leftUnit = left.type === ValueType.Uom ? left.unit : undefined;\n\n const denominatorEntry = UNIT_TABLE[denominator.toLowerCase()] as readonly [number, number] | undefined;\n const leftEntry = leftUnit === undefined ? undefined : (UNIT_TABLE[leftUnit.toLowerCase()] as readonly [number, number] | undefined);\n\n // \"30 hours at $30/hour\": the left side counts denominators.\n if (leftEntry !== undefined && denominatorEntry !== undefined && leftEntry[0] === denominatorEntry[0]) {\n const inDenominator = left.toNumber() * leftEntry[1] / denominatorEntry[1];\n const total = inDenominator * rate.toNumber();\n return numerator === \"\" ? numberValue(total) : uomValue(total, numerator);\n }\n\n // \"$500 at $20/hour\": the left side is the numerator, so divide.\n if (leftUnit !== undefined && leftUnit === numerator) {\n const count = left.toNumber() / rate.toNumber();\n return uomValue(count, pluraliseUnit(denominator, count));\n }\n\n // A bare number counts denominators too: \"30 at $30/hour\".\n if (leftUnit === undefined) {\n const total = left.toNumber() * rate.toNumber();\n return numerator === \"\" ? numberValue(total) : uomValue(total, numerator);\n }\n\n return errorValue(\"INCOMPATIBLE_UNITS\", `at: ${leftUnit} matches neither side of ${rate.unit}`);\n },\n // ── Investments (packages/finance/) ────────────────────────────────────\n // compoundFutureValueEvery(principal, rate, years, periodsPerYear)\n // FV = P(1 + r/n)^(n·y). Index 51 is the same formula with n fixed at 1;\n // this one backs \"compounding monthly\"/\"quarterly\"/\"daily\"/\"weekly\".\n // Kept separate rather than widening 51, because 51 is also the public\n // compoundInterest(principal, rate, years) call and its arity is part of\n // that contract.\n 80: (args) => {\n const principal = args[0].toNumber();\n const rate = args[1].toNumber();\n const years = args[2].toNumber();\n const perYear = args[3].toNumber();\n if (perYear <= 0) {\n return errorValue(\"INVALID_RATE\", `compounding: ${perYear} periods per year is not a period`);\n }\n if (1 + rate / perYear <= 0) {\n return errorValue(\"INVALID_RATE\", `compounding: rate ${rate} makes each period non-positive`);\n }\n const fv = principal * Math.pow(1 + rate / perYear, perYear * years);\n return args[0].type === ValueType.Uom ? uomValue(fv, args[0].unit!) : numberValue(fv);\n },\n // compoundInterestEarnedEvery(principal, rate, years, periodsPerYear)\n // The interest-only portion of index 80, i.e. FV - P.\n 81: (args) => {\n const principal = args[0].toNumber();\n const rate = args[1].toNumber();\n const years = args[2].toNumber();\n const perYear = args[3].toNumber();\n if (perYear <= 0 || 1 + rate / perYear <= 0) {\n return errorValue(\"INVALID_RATE\", `compounding: rate ${rate} over ${perYear} periods per year is not usable`);\n }\n const interest = principal * (Math.pow(1 + rate / perYear, perYear * years) - 1);\n return args[0].type === ValueType.Uom ? uomValue(interest, args[0].unit!) : numberValue(interest);\n },\n // presentValue(futureValue, rate, years) -> FV / (1 + r)^y, what a sum\n // promised in the future is worth today. The inverse of index 51.\n 82: (args) => {\n const future = args[0].toNumber();\n const rate = args[1].toNumber();\n const years = args[2].toNumber();\n if (1 + rate <= 0) {\n return errorValue(\"INVALID_RATE\", `presentValue: rate ${rate} makes (1 + rate) non-positive`);\n }\n const pv = future / Math.pow(1 + rate, years);\n return args[0].type === ValueType.Uom ? uomValue(pv, args[0].unit!) : numberValue(pv);\n },\n // returnOnInvestment(invested, returned) -> (returned - invested) /\n // invested, the gain as a multiple of what was put in. $500 in and $1,500\n // out is 2x, not 3x: ROI conventionally measures the profit against the\n // cost, so doubling your money is 1x return and tripling it is 2x. The\n // money multiple (3x here) is a different figure; `$1,500 / $500` gives it.\n 83: (args) => {\n const invested = args[0].toNumber();\n const returned = args[1].toNumber();\n if (invested === 0) {\n return errorValue(\"INVALID_RATE\", \"roi: nothing was invested, so there is no return on it\");\n }\n return numberValue((returned - invested) / invested);\n },\n // annualisedReturn(invested, returned, years) -> CAGR, the constant\n // yearly rate that turns `invested` into `returned` over `years`:\n // (returned/invested)^(1/years) - 1. Returned as a Percentage so it\n // renders \"13.99%\" rather than 0.1399.\n 84: (args) => {\n const invested = args[0].toNumber();\n const returned = args[1].toNumber();\n const years = args[2].toNumber();\n if (invested <= 0) {\n return errorValue(\"INVALID_RATE\", \"annual return: the amount invested must be positive\");\n }\n if (years <= 0) {\n return errorValue(\"INVALID_RATE\", \"annual return: the period must be longer than zero\");\n }\n if (returned <= 0) {\n // A total loss has no finite compound rate; -100% a year is the\n // limit, and pretending otherwise would invent a number.\n return errorValue(\"INVALID_RATE\", \"annual return: nothing was returned, so there is no annual rate\");\n }\n return percentageValue(Math.pow(returned / invested, 1 / years) - 1);\n },\n // roundToPlaces(value, places) -> value rounded to that many decimal\n // places, backing `<value> to <n> dp` (converters/parselets/\n // RoundingParselets.ts).\n //\n // It exists because the obvious bytecode for it, \"multiply by 10^p, round,\n // divide by 10^p\", is only safe for values small enough that the multiply\n // is exact. `1e21 to 2 dp` came back as 999999999999999900000: 1e21 has no\n // fractional part to round at all, and the round trip through 1e23 was\n // pure loss. Asking for fewer decimal places than a number has cannot\n // change it, so a value that is already whole is returned untouched.\n 97: (args) => roundToPlaces(args[0], args[1].toNumber()),\n // splitEach(amount, n): a per-person bill split, `split $180 between 4` and\n // `$120 + 18% split 3 ways`. Backs both split spellings (see\n // BillSplitParselets.ts). Money stays exact and the shares add back to the\n // total to the cent (see splitEachExact in MoneyExact.ts). A bare number\n // splits to a bare number; the odd penny is named, not rounded away.\n 98: (args) => {\n const n = args[1].toNumber();\n if (!Number.isInteger(n) || n < 1) {\n return errorValue(\"INVALID_RANGE\", `split: the number of shares must be a whole number of at least 1, not ${args[1].toNumber()}.`);\n }\n return splitValue(splitEachExact(args[0], n));\n },\n // ── Savings goals ──────────────────────────────────────────────\n // savingsGoalPayment(target, duration, annualRate): the level contribution\n // per month that reaches `target` over `duration` (months or years), at an\n // optional annual rate compounded monthly. Backs \"how much per month to\n // save/reach <target> in <duration> [at <rate>]\".\n 99: (args) => {\n const target = args[0].toNumber();\n const months = monthsOfDuration(args[1]);\n const annualRate = args[2].toNumber();\n if (months === null) return errorValue(\"INVALID_RANGE\", `savings goal: the duration must be in months or years, e.g. \"in 2 years\".`);\n if (target <= 0) return errorValue(\"INVALID_RANGE\", `savings goal: the target must be positive.`);\n if (months <= 0) return errorValue(\"INVALID_RANGE\", `savings goal: the duration must be positive.`);\n if (annualRate < 0) return errorValue(\"INVALID_RATE\", `savings goal: the rate must not be negative.`);\n const payment = annuityPayment(target, annualRate / 12, months);\n return args[0].type === ValueType.Uom ? uomValue(payment, args[0].unit!) : numberValue(payment);\n },\n // savingsGoalPeriods(target, contribution, periodsPerYear, annualRate,\n // periodUnit): how many whole periods of `contribution` reach `target`,\n // rounded UP, since a part period has not yet reached the goal. Backs\n // \"how long to save <target> at <amount> <period> [at <rate>]\".\n 100: (args) => {\n const target = args[0].toNumber();\n const contribution = args[1].toNumber();\n const periodsPerYear = args[2].toNumber();\n const annualRate = args[3].toNumber();\n const unit = typeof args[4]?.value === \"string\" ? (args[4].value as string) : \"periods\";\n if (target <= 0) return errorValue(\"INVALID_RANGE\", `savings goal: the target must be positive.`);\n if (contribution <= 0) return errorValue(\"INVALID_RANGE\", `savings goal: the contribution must be positive.`);\n if (annualRate < 0) return errorValue(\"INVALID_RATE\", `savings goal: the rate must not be negative.`);\n const periods = annuityPeriods(target, contribution, annualRate / periodsPerYear);\n return uomValue(periods, unit);\n },\n // ── Spread and shape aggregates (MathPhrases \"standard deviation of X, Y\",\n // \"variance of ...\", \"spread of ...\", \"mode of ...\"). Population form is the\n // default; the sample form is a separate index. See issue #184. ──\n // standard deviation (population): the spread in the same units as the data.\n 101: (args) => numberValue(Math.sqrt(variance(args.map((a) => a.toNumber()), false))),\n // sample standard deviation (divide by n-1).\n 102: (args) => numberValue(Math.sqrt(variance(args.map((a) => a.toNumber()), true))),\n // variance (population): the mean squared deviation.\n 103: (args) => numberValue(variance(args.map((a) => a.toNumber()), false)),\n // sample variance (divide by n-1).\n 104: (args) => numberValue(variance(args.map((a) => a.toNumber()), true)),\n // spread: largest minus smallest. Named \"spread\" because \"range\" already\n // means a start:end interval elsewhere in the engine.\n 105: (args) => {\n if (args.length === 0) return numberValue(0);\n const nums = args.map((a) => a.toNumber());\n return numberValue(Math.max(...nums) - Math.min(...nums));\n },\n // mode: the most frequent value. A tie is broken by first appearance, so the\n // result is deterministic for the same list.\n 106: (args) => {\n if (args.length === 0) return numberValue(0);\n const counts = new Map<number, number>();\n let best = args[0].toNumber();\n let bestCount = 0;\n for (const a of args) {\n const n = a.toNumber();\n const c = (counts.get(n) ?? 0) + 1;\n counts.set(n, c);\n if (c > bestCount) {\n bestCount = c;\n best = n;\n }\n }\n return numberValue(best);\n },\n // weighted average: the arguments arrive interleaved [v1, w1, v2, w2, ...]\n // from WeightedAverageParselet, which has already rejected any value with no\n // weight. Weights are normalised by their own total, so they need not sum to\n // 1 or 100%. See issue #185.\n 107: (args) => {\n let weightedSum = 0;\n let weightTotal = 0;\n for (let i = 0; i + 1 < args.length; i += 2) {\n const value = args[i].toNumber();\n const weight = args[i + 1].toNumber();\n weightedSum += value * weight;\n weightTotal += weight;\n }\n if (weightTotal === 0) {\n return errorValue(\"WEIGHTED_AVERAGE_ZERO_WEIGHT\", \"weighted average: the weights sum to zero, so there is nothing to divide by\");\n }\n return numberValue(weightedSum / weightTotal);\n },\n};\n\n/**\n * The months a savings-goal duration stands for: a Uom in `months` is its own\n * count, a Uom in `years` is twelve to the year. Any other or absent time unit\n * has no clean month count, so the builtin reports it rather than guessing.\n */\nfunction monthsOfDuration(duration: Value): number | null {\n if (duration.type !== ValueType.Uom) return null;\n const unit = duration.unit;\n if (unit === \"months\" || unit === \"month\") return duration.toNumber();\n if (unit === \"years\" || unit === \"year\") return duration.toNumber() * 12;\n return null;\n}\n\n/**\n * The level contribution whose annuity future value reaches `target` after\n * `months` at monthly rate `i`, the sinking-fund payment. A zero rate is the\n * plain `target / months`, avoiding the 0/0 the closed form would produce, the\n * same special case {@link amortizeLoan} draws.\n */\nfunction annuityPayment(target: number, i: number, months: number): number {\n return i === 0 ? target / months : (target * i) / (Math.pow(1 + i, months) - 1);\n}\n\n/**\n * The number of periods of `contribution` whose annuity future value reaches\n * `target` at per-period rate `i`, the inverse of {@link annuityPayment},\n * rounded UP: a part period has not yet reached the goal, the deliberate inverse\n * of the recurring-schedule rule that floors a part period. A tiny snap before\n * the ceiling keeps a clean whole result (a `20.0000001` float) at 20. A zero\n * rate is the plain `target / contribution`.\n */\nfunction annuityPeriods(target: number, contribution: number, i: number): number {\n const raw = i === 0 ? target / contribution : Math.log(1 + (target * i) / contribution) / Math.log(1 + i);\n return Math.ceil(raw - 1e-9);\n}\n\n/**\n * Applies one of the complex accessors to a value.\n *\n * @param name - The accessor name, matching what the simplifier folds.\n * @param value - The argument.\n * @returns The folded result, or the call left symbolic when the argument still\n * contains an unknown.\n */\nfunction applyComplexAccessor(name: string, value: Value): Value {\n const node = valueToSymbolic(value);\n if (node === null) return errorValue(\"SYMBOLIC_NONFINITE_OPERAND\", name + \" needs a value with an exact number.\");\n return symbolicToValue(callNode(name, [node]));\n}\n\n/**\n * Reads the variable-name argument the algebra verbs push as a String.\n *\n * @param value - The argument in the name position.\n * @param verb - The verb's name, for the error message.\n * @returns The name, or an error Value to return directly.\n */\nfunction symbolicVariableName(value: Value | undefined, verb: string): string | Value {\n if (value?.type !== ValueType.String) {\n return errorValue(\"SYMBOLIC_REQUIRES_VARIABLE_NAME\", `${verb} needs the name of an unknown.`);\n }\n return value.value as string;\n}\n\n/**\n * Standard amortizing-loan math shared by the loanRepayment/loanInterest/\n * monthlyPayment builtins (indices 55-57, above). Always amortizes monthly\n * (the standard mortgage convention), `annualRate` is the nominal annual\n * rate as a decimal fraction (e.g. 0.06 for 6%).\n *\n * A zero rate is handled as a special case (plain principal/periods split)\n * since the closed-form annuity formula divides by rate and would\n * otherwise produce a NaN from 0/0.\n */\nfunction amortizeLoan(\n principal: number,\n annualRate: number,\n years: number,\n): { monthlyPayment: number; totalRepayment: number; totalInterest: number } {\n const n = years * 12;\n const rMonthly = annualRate / 12;\n const monthlyPayment = rMonthly === 0\n ? principal / n\n : (principal * rMonthly) / (1 - Math.pow(1 + rMonthly, -n));\n const totalRepayment = monthlyPayment * n;\n const totalInterest = totalRepayment - principal;\n return { monthlyPayment, totalRepayment, totalInterest };\n}\n\n/**\n * Registry of package-registered functions, indexed by the number pushed as an\n * operand of `OpCode.CALL_PLUGIN`.\n *\n * Functions may return a promise. The orchestrator resolves it and re-executes\n * rather than blocking the VM.\n *\n * Populated declaratively via {@link IEnginePackage.pluginFunctions} at\n * package-registration time. Entries are cleared on unregister.\n *\n * @deprecated This is the {@link defaultEngineContext}'s map, kept as a\n * module-level alias so existing callers keep working during the context\n * migration. An engine registers into its own context, so writing here affects\n * only code that has not been migrated. Take an {@link EngineContext} instead.\n */\nexport const pluginFunctionRegistry: Record<number, PluginFunctionHandler> =\n defaultEngineContext.pluginFunctions;\n\n/** Highest index that fits in a single Uint8Array opcode-stream byte. */\nconst MAX_PLUGIN_FUNCTION_INDEX = 255;\nlet nextPluginFunctionIndex = 0;\n\n/**\n * Allocate a unique index into {@link pluginFunctionRegistry} for a package's\n * plugin function.\n *\n * Call once per function, typically at module scope, right where the\n * function is defined, and store the result in a constant. Don't hardcode\n * an index: two packages independently picking the same arbitrary number\n * would silently overwrite each other's handler in the shared registry.\n *\n * @throws If the index pool (0-255, a single opcode-stream byte) is exhausted.\n */\nexport function allocatePluginFunctionIndex(): number {\n if (nextPluginFunctionIndex > MAX_PLUGIN_FUNCTION_INDEX) {\n throw ErrorFactory.config(\n \"PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED\",\n `allocatePluginFunctionIndex: pool exhausted (max ${MAX_PLUGIN_FUNCTION_INDEX + 1} allocations).`\n );\n }\n return nextPluginFunctionIndex++;\n}\n\nconst pluginFunctionIndexByQualifiedName = new Map<string, number>();\n\n/**\n * The stable index for a package's named plugin function, allocated once per\n * `${packageName}:${functionName}` and cached process-wide, so the same function\n * always maps to the same {@link pluginFunctionRegistry} slot no matter which\n * engine registers it or in what order: the property compiled bytecode, and so\n * a snapshot, relies on.\n *\n * The engine calls this at {@link ExpressionEngine.registerPackage} time for each\n * entry of a package's `pluginFunctions` record, so a package author names the\n * function and never sees an index. {@link allocatePluginFunctionIndex} remains\n * for a host that needs a raw index directly.\n */\nexport function pluginFunctionIndexFor(qualifiedName: string): number {\n let index = pluginFunctionIndexByQualifiedName.get(qualifiedName);\n if (index === undefined) {\n index = allocatePluginFunctionIndex();\n pluginFunctionIndexByQualifiedName.set(qualifiedName, index);\n }\n return index;\n}\n\n/**\n * Registry of package-registered `as <name>` converters, the SDK extension\n * point for `IEnginePackage.asConverters` (see ExpressionEngine.registerPackage()).\n *\n * String-keyed rather than index-allocated like {@link pluginFunctionRegistry}:\n * converter names ARE the natural key (there's no bytecode-stream byte-width\n * constraint to economize for, the name is only read at parse time to\n * decide whether it's one of the fixed built-ins with a dedicated fast\n * opcode; anything else falls through to `OpCode.CALL_AS_CONVERTER`, which\n * embeds the name as a string constant and looks it up here at runtime).\n */\nexport const asConverterRegistry = new Map<string, (value: Value) => Value>();\n\n/**\n * Register a custom `as <name>` converter. Called by\n * ExpressionEngine.registerPackage() for each entry in a package's\n * `asConverters`. Warns (does not throw) on a name collision, mirrors\n * ParseletRegistry's collision warning, since two independently-authored\n * packages picking the same converter name is a real possibility with a\n * shared string-keyed registry, and silently overwriting is worse than a\n * visible warning.\n *\n * Skips the warning when `handler` is REFERENCE-IDENTICAL to what's\n * already registered (mirrors `ParseletRegistry.registerPrefix()`'s own\n * `existing !== parselet` guard), a package's `asConverters` object is a\n * module-level constant, so re-constructing an `ExpressionEngine` (which\n * re-registers every built-in package's converters from scratch each\n * time. This is not a per-instance cache) passes the exact same function\n * reference every time, not a genuine second package claiming the name.\n * Without this, every `iso8601` converter registration warned on every\n * single `new ExpressionEngine()` call after the first in a process\n * pure noise, not a real collision signal, surfaced by\n * `DatetimePackage.ts` becoming this registry's first real consumer.\n */\nexport function registerAsConverter(name: string, handler: (value: Value) => Value): void {\n const key = name.toLowerCase();\n const existing = asConverterRegistry.get(key);\n if (existing && existing !== handler) {\n console.warn(`[asConverterRegistry] Converter name \"${key}\" is already registered — overwriting.`);\n }\n asConverterRegistry.set(key, handler);\n}\n\n/** Reverse a {@link registerAsConverter} call, used by unregisterPackage(). */\nexport function unregisterAsConverter(name: string): void {\n asConverterRegistry.delete(name.toLowerCase());\n}\n","import { Value } from \"@solve-js/vm/Value\";\n\n/**\n * Process-wide store for `global :name` variables, distinct from, and\n * unrelated to, the per-document `Map<string, Value>` each VM instance owns\n * for ordinary `:x` variables (see VM.ts's `createVM()`). Every document's\n * VM stays fully isolated for local variables; this is the one deliberate\n * exception, shared across every ExpressionEngine in the same JS realm.\n *\n * Distinct from the package-contributed async data sources (currency rates,\n * OSRS prices) reached through the ResolverRegistry: this store backs a\n * completely separate opcode pair (LOAD_GLOBAL_VAR/\n * STORE_GLOBAL_VAR) and is the synchronous fast-path cache underneath\n * GlobalVariableAsyncResolver, which handles the \"not yet declared by any\n * loaded document\" case via the engine's existing async-resolution pipeline\n * (see that file's doc comment for the full picture).\n */\nexport class GlobalVariableStore {\n\tprivate values = new Map<string, Value>();\n\tprivate listeners = new Set<GlobalVariableListener>();\n\n\t/**\n\t * Guards against runaway cross-document write cycles: doc A's write\n\t * notifies doc B, whose dirty line, once evaluated, writes a global\n\t * that notifies doc C, ... eventually back to A. Same philosophy as the\n\t * VM's own instruction-limit safety net: stop propagating past the\n\t * limit rather than let a genuine cycle recurse unboundedly. The store\n\t * itself is left in a well-defined state either way. This only bounds\n\t * *notification* depth, never the value actually stored.\n\t */\n\tprivate static readonly MAX_NOTIFY_DEPTH = 64;\n\tprivate notifyDepth = 0;\n\n\tget(name: string): Value | undefined {\n\t\treturn this.values.get(name);\n\t}\n\n\thas(name: string): boolean {\n\t\treturn this.values.has(name);\n\t}\n\n\t/**\n\t * Last-write-wins: any document may call this for any name at any time.\n\t * Notifies listeners synchronously, within the same call, before\n\t * returning, so that ThreeTierEvaluator's dirty-marking (a listener)\n\t * and GlobalVariableAsyncResolver's first-write promise (also a\n\t * listener) both observe the new value immediately, no microtask delay.\n\t *\n\t * A write that does not CHANGE the stored value notifies nobody. This\n\t * is not just an optimisation, it is what stops a re-evaluation cycle\n\t * from sustaining itself. Every listener re-runs work in response to a\n\t * write (ThreeTierEvaluator marks dependent lines dirty; the playground\n\t * worker refreshes other documents), and those re-runs re-execute the\n\t * very STORE_GLOBAL_VAR opcode that produced this write. Re-evaluating\n\t * an unchanged `global :x = 5` line therefore used to re-notify, which\n\t * re-triggered the listeners, which re-evaluated... bounded only by\n\t * MAX_NOTIFY_DEPTH below, and only in DEPTH, so with more than one\n\t * writer the work per keystroke grew exponentially. Nothing observable\n\t * changed, so there is nothing for a listener to react to.\n\t */\n\tset(name: string, value: Value): void {\n\t\tconst previous = this.values.get(name);\n\t\tthis.values.set(name, value);\n\t\tif (previous !== undefined && sameValue(previous, value)) return;\n\t\tthis.notify(name, value);\n\t}\n\n\tprivate notify(name: string, value: Value): void {\n\t\tif (this.notifyDepth >= GlobalVariableStore.MAX_NOTIFY_DEPTH) return;\n\t\tthis.notifyDepth++;\n\t\ttry {\n\t\t\tfor (const listener of this.listeners) listener(name, value);\n\t\t} finally {\n\t\t\tthis.notifyDepth--;\n\t\t}\n\t}\n\n\t/**\n\t * Subscribe to every global-variable write (all names, callers filter\n\t * for the name(s) they care about). Returns an unsubscribe function;\n\t * callers MUST invoke it when disposing (e.g. ThreeTierEvaluator's\n\t * terminateWorker()) to avoid leaking listeners for closed documents.\n\t */\n\tsubscribe(listener: GlobalVariableListener): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\t/**\n\t * Full reset, test-only. Never called from production code paths;\n\t * globals must outlive any single engine's own clear()/dispose cycle.\n\t * Tests MUST call this in beforeEach/afterEach since this is a\n\t * module-level singleton whose state and listeners otherwise leak\n\t * across test cases and files.\n\t */\n\tclear(): void {\n\t\tthis.values.clear();\n\t\tthis.listeners.clear();\n\t\tthis.notifyDepth = 0;\n\t}\n}\n\n/**\n * Structural equality for two stored globals, used by `set()` to decide\n * whether a write is worth notifying about. Deliberately NOT identity:\n * VM.ts stores `persistentValue(val)`, a fresh object, on every\n * STORE_GLOBAL_VAR while the arena is active, so two writes of the same\n * literal are never the same object.\n *\n * `Object.is` rather than `===` so a global holding NaN compares equal to\n * itself; otherwise `global :x = 0/0` would re-notify on every\n * re-evaluation, which is exactly the cycle `set()` is trying to break.\n */\nfunction sameValue(a: Value, b: Value): boolean {\n\tif (a.type !== b.type) return false;\n\tif (a.unit !== b.unit) return false;\n\tif ((a.timedOut ?? false) !== (b.timedOut ?? false)) return false;\n\n\tconst av = a.value;\n\tconst bv = b.value;\n\tif (Array.isArray(av) || Array.isArray(bv)) {\n\t\tif (!Array.isArray(av) || !Array.isArray(bv)) return false;\n\t\tif (av.length !== bv.length) return false;\n\t\tfor (let i = 0; i < av.length; i++) {\n\t\t\tif (!Object.is(av[i], bv[i])) return false;\n\t\t}\n\t\treturn true;\n\t}\n\treturn Object.is(av, bv);\n}\n\n/** Called when a cross-document global changes, so dependents can re-evaluate. */\nexport type GlobalVariableListener = (name: string, value: Value) => void;\n\n/** Process-wide singleton, shared across every engine in the same JS realm. */\nexport const sharedGlobalVariableStore = new GlobalVariableStore();\n\n/**\n * DAG bookkeeping key for a `global :name` reference, distinct from the\n * plain `name` key used for a local `:name`, so a single document that\n * reads/writes BOTH a local `:hello` and `global :hello` never collides\n * them in that document's own DependencyGraph reads/writes tracking. This\n * prefix exists ONLY at the DAG-bookkeeping layer (ExpressionEngineSafety's\n * extractReadsAndWrites, and ThreeTierEvaluator's dirty-marking subscriber)\n *, the VM-level storage key in this store, and the LOAD_GLOBAL_VAR/\n * STORE_GLOBAL_VAR bytecode operand, both stay unprefixed.\n */\nexport function globalDagKey(name: string): string {\n\treturn `global:${name}`;\n}\n"]}
|