solve-engine 1.0.0-beta.0 → 1.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (253) hide show
  1. package/dist/BytecodeBuilder-3egMyuDi.d.cts +274 -0
  2. package/dist/BytecodeBuilder-3egMyuDi.d.ts +274 -0
  3. package/dist/Configuration-fVpd-HC-.d.cts +228 -0
  4. package/dist/Configuration-fVpd-HC-.d.ts +228 -0
  5. package/dist/EngineError-DvPSnhZi.d.cts +304 -0
  6. package/dist/EngineError-DvPSnhZi.d.ts +304 -0
  7. package/dist/Lexer-BJdhlnej.d.cts +531 -0
  8. package/dist/Lexer-D9l4Yrk2.d.ts +531 -0
  9. package/dist/NormalizerRule-BrVoVjmP.d.cts +163 -0
  10. package/dist/NormalizerRule-CEjf1FyD.d.ts +163 -0
  11. package/dist/PackageRegistry-D-Tv_7ca.d.cts +2572 -0
  12. package/dist/PackageRegistry-DaH4aIKP.d.ts +2572 -0
  13. package/dist/Parselet-CK8cQu2a.d.cts +299 -0
  14. package/dist/Parselet-ConOIdRO.d.ts +299 -0
  15. package/dist/ScopeManager-B5k0nk05.d.ts +559 -0
  16. package/dist/ScopeManager-CKfQtl7l.d.cts +559 -0
  17. package/dist/Token-0jpvUdPY.d.cts +245 -0
  18. package/dist/Token-0jpvUdPY.d.ts +245 -0
  19. package/dist/VMCheckpoints-BmDwIXgK.d.ts +171 -0
  20. package/dist/VMCheckpoints-CqFuLwrT.d.cts +171 -0
  21. package/dist/Value-KtAQNHur.d.cts +295 -0
  22. package/dist/Value-KtAQNHur.d.ts +295 -0
  23. package/dist/chunk-2RWAXT6O.js +3 -0
  24. package/dist/chunk-2RWAXT6O.js.map +1 -0
  25. package/dist/chunk-34RRD7PC.js +1492 -0
  26. package/dist/chunk-34RRD7PC.js.map +1 -0
  27. package/dist/chunk-3PPFLFH4.js +5097 -0
  28. package/dist/chunk-3PPFLFH4.js.map +1 -0
  29. package/dist/chunk-3VGDNEE3.js +84 -0
  30. package/dist/chunk-3VGDNEE3.js.map +1 -0
  31. package/dist/chunk-3YNVWKR2.cjs +370 -0
  32. package/dist/chunk-3YNVWKR2.cjs.map +1 -0
  33. package/dist/chunk-47LRVGOT.cjs +316 -0
  34. package/dist/chunk-47LRVGOT.cjs.map +1 -0
  35. package/dist/chunk-4MG4XKO2.js +1644 -0
  36. package/dist/chunk-4MG4XKO2.js.map +1 -0
  37. package/dist/chunk-4QADQTWS.js +2392 -0
  38. package/dist/chunk-4QADQTWS.js.map +1 -0
  39. package/dist/chunk-53B6KDDJ.cjs +1651 -0
  40. package/dist/chunk-53B6KDDJ.cjs.map +1 -0
  41. package/dist/chunk-5X2PTP6F.cjs +104 -0
  42. package/dist/chunk-5X2PTP6F.cjs.map +1 -0
  43. package/dist/chunk-5YEMOYSE.js +264 -0
  44. package/dist/chunk-5YEMOYSE.js.map +1 -0
  45. package/dist/chunk-64W6GLLZ.js +481 -0
  46. package/dist/chunk-64W6GLLZ.js.map +1 -0
  47. package/dist/chunk-6BKTCEUP.cjs +233 -0
  48. package/dist/chunk-6BKTCEUP.cjs.map +1 -0
  49. package/dist/chunk-6NTVRDQV.cjs +1642 -0
  50. package/dist/chunk-6NTVRDQV.cjs.map +1 -0
  51. package/dist/chunk-6RDSQURE.js +290 -0
  52. package/dist/chunk-6RDSQURE.js.map +1 -0
  53. package/dist/chunk-75JP4BZX.js +93 -0
  54. package/dist/chunk-75JP4BZX.js.map +1 -0
  55. package/dist/chunk-B7LXJ6LC.cjs +36 -0
  56. package/dist/chunk-B7LXJ6LC.cjs.map +1 -0
  57. package/dist/chunk-BVAR5J2F.js +257 -0
  58. package/dist/chunk-BVAR5J2F.js.map +1 -0
  59. package/dist/chunk-C4XZV6E7.cjs +269 -0
  60. package/dist/chunk-C4XZV6E7.cjs.map +1 -0
  61. package/dist/chunk-CCJPSHGI.cjs +40 -0
  62. package/dist/chunk-CCJPSHGI.cjs.map +1 -0
  63. package/dist/chunk-CLL7RUQV.cjs +316 -0
  64. package/dist/chunk-CLL7RUQV.cjs.map +1 -0
  65. package/dist/chunk-DM3LMRBC.js +329 -0
  66. package/dist/chunk-DM3LMRBC.js.map +1 -0
  67. package/dist/chunk-DUEZFTK2.js +38 -0
  68. package/dist/chunk-DUEZFTK2.js.map +1 -0
  69. package/dist/chunk-EBSPLUW4.cjs +489 -0
  70. package/dist/chunk-EBSPLUW4.cjs.map +1 -0
  71. package/dist/chunk-EHAHVROS.cjs +261 -0
  72. package/dist/chunk-EHAHVROS.cjs.map +1 -0
  73. package/dist/chunk-EIGTWK5N.js +167 -0
  74. package/dist/chunk-EIGTWK5N.js.map +1 -0
  75. package/dist/chunk-EPOXXJBK.js +96 -0
  76. package/dist/chunk-EPOXXJBK.js.map +1 -0
  77. package/dist/chunk-FEAIOR7N.cjs +91 -0
  78. package/dist/chunk-FEAIOR7N.cjs.map +1 -0
  79. package/dist/chunk-G535KJEG.js +312 -0
  80. package/dist/chunk-G535KJEG.js.map +1 -0
  81. package/dist/chunk-GCM5JHMX.js +88 -0
  82. package/dist/chunk-GCM5JHMX.js.map +1 -0
  83. package/dist/chunk-GOLDJNMZ.js +368 -0
  84. package/dist/chunk-GOLDJNMZ.js.map +1 -0
  85. package/dist/chunk-GW32KPCU.cjs +360 -0
  86. package/dist/chunk-GW32KPCU.cjs.map +1 -0
  87. package/dist/chunk-HTXVVJRA.cjs +1549 -0
  88. package/dist/chunk-HTXVVJRA.cjs.map +1 -0
  89. package/dist/chunk-HWSZJQCI.js +311 -0
  90. package/dist/chunk-HWSZJQCI.js.map +1 -0
  91. package/dist/chunk-IF532O7C.js +101 -0
  92. package/dist/chunk-IF532O7C.js.map +1 -0
  93. package/dist/chunk-J73SJHR3.cjs +2415 -0
  94. package/dist/chunk-J73SJHR3.cjs.map +1 -0
  95. package/dist/chunk-JBSYC7BB.cjs +7473 -0
  96. package/dist/chunk-JBSYC7BB.cjs.map +1 -0
  97. package/dist/chunk-KVILKGMS.js +228 -0
  98. package/dist/chunk-KVILKGMS.js.map +1 -0
  99. package/dist/chunk-LIPPNDBE.js +258 -0
  100. package/dist/chunk-LIPPNDBE.js.map +1 -0
  101. package/dist/chunk-LR7YASZF.cjs +172 -0
  102. package/dist/chunk-LR7YASZF.cjs.map +1 -0
  103. package/dist/chunk-M4N5GA5Z.cjs +309 -0
  104. package/dist/chunk-M4N5GA5Z.cjs.map +1 -0
  105. package/dist/chunk-M5LX5AOO.js +7459 -0
  106. package/dist/chunk-M5LX5AOO.js.map +1 -0
  107. package/dist/chunk-MZOVP3WI.cjs +96 -0
  108. package/dist/chunk-MZOVP3WI.cjs.map +1 -0
  109. package/dist/chunk-N5YFR4UP.cjs +10 -0
  110. package/dist/chunk-N5YFR4UP.cjs.map +1 -0
  111. package/dist/chunk-NGBBNL4K.cjs +4 -0
  112. package/dist/chunk-NGBBNL4K.cjs.map +1 -0
  113. package/dist/chunk-NH2O2AUR.js +146 -0
  114. package/dist/chunk-NH2O2AUR.js.map +1 -0
  115. package/dist/chunk-NLNDMWZC.js +31 -0
  116. package/dist/chunk-NLNDMWZC.js.map +1 -0
  117. package/dist/chunk-NMCRQP3Z.cjs +778 -0
  118. package/dist/chunk-NMCRQP3Z.cjs.map +1 -0
  119. package/dist/chunk-NMD5VRN4.cjs +1327 -0
  120. package/dist/chunk-NMD5VRN4.cjs.map +1 -0
  121. package/dist/chunk-OC6LTXYS.cjs +286 -0
  122. package/dist/chunk-OC6LTXYS.cjs.map +1 -0
  123. package/dist/chunk-OT6OJY7C.cjs +114 -0
  124. package/dist/chunk-OT6OJY7C.cjs.map +1 -0
  125. package/dist/chunk-PFSDGGYL.js +8 -0
  126. package/dist/chunk-PFSDGGYL.js.map +1 -0
  127. package/dist/chunk-QNJ4ACRT.cjs +155 -0
  128. package/dist/chunk-QNJ4ACRT.cjs.map +1 -0
  129. package/dist/chunk-QWY3VEZN.js +1637 -0
  130. package/dist/chunk-QWY3VEZN.js.map +1 -0
  131. package/dist/chunk-RFYD5TJE.js +111 -0
  132. package/dist/chunk-RFYD5TJE.js.map +1 -0
  133. package/dist/chunk-RIN643A3.js +354 -0
  134. package/dist/chunk-RIN643A3.js.map +1 -0
  135. package/dist/chunk-RZCWSXTA.cjs +5122 -0
  136. package/dist/chunk-RZCWSXTA.cjs.map +1 -0
  137. package/dist/chunk-SDGRK7EP.js +774 -0
  138. package/dist/chunk-SDGRK7EP.js.map +1 -0
  139. package/dist/chunk-VEKIWQ3F.cjs +39 -0
  140. package/dist/chunk-VEKIWQ3F.cjs.map +1 -0
  141. package/dist/chunk-WQTTOGXC.cjs +99 -0
  142. package/dist/chunk-WQTTOGXC.cjs.map +1 -0
  143. package/dist/chunk-X6K3HUOY.cjs +86 -0
  144. package/dist/chunk-X6K3HUOY.cjs.map +1 -0
  145. package/dist/chunk-XJCMXB2E.cjs +333 -0
  146. package/dist/chunk-XJCMXB2E.cjs.map +1 -0
  147. package/dist/chunk-XVWCOTR6.js +1324 -0
  148. package/dist/chunk-XVWCOTR6.js.map +1 -0
  149. package/dist/chunk-YLJ4XMA6.js +33 -0
  150. package/dist/chunk-YLJ4XMA6.js.map +1 -0
  151. package/dist/chunk-Z2XP767T.cjs +35 -0
  152. package/dist/chunk-Z2XP767T.cjs.map +1 -0
  153. package/dist/chunk-Z4X2RWOF.js +37 -0
  154. package/dist/chunk-Z4X2RWOF.js.map +1 -0
  155. package/dist/constants.cjs +22 -0
  156. package/dist/constants.cjs.map +1 -0
  157. package/dist/constants.d.cts +12 -0
  158. package/dist/constants.d.ts +12 -0
  159. package/dist/constants.js +5 -0
  160. package/dist/constants.js.map +1 -0
  161. package/dist/engine.cjs +79 -0
  162. package/dist/engine.cjs.map +1 -0
  163. package/dist/engine.d.cts +587 -0
  164. package/dist/engine.d.ts +587 -0
  165. package/dist/engine.js +34 -0
  166. package/dist/engine.js.map +1 -0
  167. package/dist/errors.cjs +81 -0
  168. package/dist/errors.cjs.map +1 -0
  169. package/dist/errors.d.cts +95 -0
  170. package/dist/errors.d.ts +95 -0
  171. package/dist/errors.js +4 -0
  172. package/dist/errors.js.map +1 -0
  173. package/dist/format.cjs +171 -0
  174. package/dist/format.cjs.map +1 -0
  175. package/dist/format.d.cts +51 -0
  176. package/dist/format.d.ts +51 -0
  177. package/dist/format.js +168 -0
  178. package/dist/format.js.map +1 -0
  179. package/dist/index.cjs +97 -0
  180. package/dist/index.cjs.map +1 -0
  181. package/dist/index.d.cts +152 -0
  182. package/dist/index.d.ts +152 -0
  183. package/dist/index.js +75 -0
  184. package/dist/index.js.map +1 -0
  185. package/dist/language.cjs +308 -0
  186. package/dist/language.cjs.map +1 -0
  187. package/dist/language.d.cts +110 -0
  188. package/dist/language.d.ts +110 -0
  189. package/dist/language.js +287 -0
  190. package/dist/language.js.map +1 -0
  191. package/dist/lexer.cjs +64 -0
  192. package/dist/lexer.cjs.map +1 -0
  193. package/dist/lexer.d.cts +56 -0
  194. package/dist/lexer.d.ts +56 -0
  195. package/dist/lexer.js +11 -0
  196. package/dist/lexer.js.map +1 -0
  197. package/dist/normalizer.cjs +40 -0
  198. package/dist/normalizer.cjs.map +1 -0
  199. package/dist/normalizer.d.cts +364 -0
  200. package/dist/normalizer.d.ts +364 -0
  201. package/dist/normalizer.js +11 -0
  202. package/dist/normalizer.js.map +1 -0
  203. package/dist/packages.cjs +121 -0
  204. package/dist/packages.cjs.map +1 -0
  205. package/dist/packages.d.cts +691 -0
  206. package/dist/packages.d.ts +691 -0
  207. package/dist/packages.js +24 -0
  208. package/dist/packages.js.map +1 -0
  209. package/dist/parser.cjs +55 -0
  210. package/dist/parser.cjs.map +1 -0
  211. package/dist/parser.d.cts +46 -0
  212. package/dist/parser.d.ts +46 -0
  213. package/dist/parser.js +10 -0
  214. package/dist/parser.js.map +1 -0
  215. package/dist/pipeline-CrsRPmsv.d.ts +285 -0
  216. package/dist/pipeline-DPUQt7yL.d.cts +285 -0
  217. package/dist/resolvers.cjs +13 -0
  218. package/dist/resolvers.cjs.map +1 -0
  219. package/dist/resolvers.d.cts +111 -0
  220. package/dist/resolvers.d.ts +111 -0
  221. package/dist/resolvers.js +4 -0
  222. package/dist/resolvers.js.map +1 -0
  223. package/dist/services.cjs +21 -0
  224. package/dist/services.cjs.map +1 -0
  225. package/dist/services.d.cts +30 -0
  226. package/dist/services.d.ts +30 -0
  227. package/dist/services.js +4 -0
  228. package/dist/services.js.map +1 -0
  229. package/dist/uom.cjs +56 -0
  230. package/dist/uom.cjs.map +1 -0
  231. package/dist/uom.d.cts +224 -0
  232. package/dist/uom.d.ts +224 -0
  233. package/dist/uom.js +11 -0
  234. package/dist/uom.js.map +1 -0
  235. package/dist/utilities.cjs +32 -0
  236. package/dist/utilities.cjs.map +1 -0
  237. package/dist/utilities.d.cts +113 -0
  238. package/dist/utilities.d.ts +113 -0
  239. package/dist/utilities.js +7 -0
  240. package/dist/utilities.js.map +1 -0
  241. package/dist/variables.cjs +17 -0
  242. package/dist/variables.cjs.map +1 -0
  243. package/dist/variables.d.cts +87 -0
  244. package/dist/variables.d.ts +87 -0
  245. package/dist/variables.js +4 -0
  246. package/dist/variables.js.map +1 -0
  247. package/dist/vm.cjs +284 -0
  248. package/dist/vm.cjs.map +1 -0
  249. package/dist/vm.d.cts +68 -0
  250. package/dist/vm.d.ts +68 -0
  251. package/dist/vm.js +194 -0
  252. package/dist/vm.js.map +1 -0
  253. package/package.json +4 -4
@@ -0,0 +1,2392 @@
1
+ import { VariableResolver } from './chunk-GCM5JHMX.js';
2
+ import { sharedCurrencyExchange } from './chunk-DM3LMRBC.js';
3
+ import { powNode, callNode, simplifySymbolic, sameShape, cancelSymbolic, complexNode, complex, RATIONAL_ZERO, rationalFromNumber, freeVariables, symbolicToEntry, rowMajorToColumnMajor, expandSymbolic, matrixMultiply, inverse, determinant, transpose, constNode, rationalToNumber, toPolynomial, polyDegree, polyCoefficients, rationalNeg, substitute, rationalDiv, isRationalZero, varNode, isRationalOne, RATIONAL_ONE, polyUnivariateVar, rationalMul, fromPolynomial, rationalCompare, coefficientGcd, polynomialDivide, isZeroPolynomial, rationalAdd, rationalSub, exactIntegerSqrt, surdNode, compareMonomials, COMPLEX_I, exactRationalSqrt, symbolicKey, monomialFromKey, monomialToKey, signedSurdNode, exactIntegerCbrt } from './chunk-34RRD7PC.js';
4
+ import { errorValue, symbolicValue, numberValue, bigIntValue, uomValue, matrixValue, hexValue, stringValue } from './chunk-BVAR5J2F.js';
5
+ import { getMeasure, convertUnit } from './chunk-NH2O2AUR.js';
6
+ import { ErrorFactory } from './chunk-6RDSQURE.js';
7
+
8
+ // src/symbolic/MultivariateFactor.ts
9
+ function exactRoot(value, degree) {
10
+ const rootOf = degree === 2 ? exactIntegerSqrt : exactIntegerCbrt;
11
+ const numerator = rootOf(value.n);
12
+ const denominator = rootOf(value.d);
13
+ return numerator === null || denominator === null ? null : { n: numerator, d: denominator };
14
+ }
15
+ function monomialRoot(key, degree) {
16
+ const monomial = monomialFromKey(key);
17
+ const root = /* @__PURE__ */ new Map();
18
+ for (const [name, exponent] of monomial) {
19
+ if (exponent % degree !== 0) return null;
20
+ root.set(name, exponent / degree);
21
+ }
22
+ return monomialToKey(root);
23
+ }
24
+ function monomialMul(a, b) {
25
+ const product2 = monomialFromKey(a);
26
+ for (const [name, exponent] of monomialFromKey(b)) {
27
+ product2.set(name, (product2.get(name) ?? 0) + exponent);
28
+ }
29
+ return monomialToKey(product2);
30
+ }
31
+ function monomialDiv(a, b) {
32
+ const quotient = monomialFromKey(a);
33
+ for (const [name, exponent] of monomialFromKey(b)) {
34
+ const remaining = (quotient.get(name) ?? 0) - exponent;
35
+ if (remaining <= 0) quotient.delete(name);
36
+ else quotient.set(name, remaining);
37
+ }
38
+ return monomialToKey(quotient);
39
+ }
40
+ function monomialGcd(a, b) {
41
+ const left = monomialFromKey(a);
42
+ const shared = /* @__PURE__ */ new Map();
43
+ for (const [name, exponent] of monomialFromKey(b)) {
44
+ const other = left.get(name);
45
+ if (other !== void 0) shared.set(name, Math.min(other, exponent));
46
+ }
47
+ return monomialToKey(shared);
48
+ }
49
+ function namesOf(keys) {
50
+ const names = /* @__PURE__ */ new Set();
51
+ for (const key of keys) for (const name of monomialFromKey(key).keys()) names.add(name);
52
+ return [...names].sort();
53
+ }
54
+ function termsToNode(terms) {
55
+ const map = /* @__PURE__ */ new Map();
56
+ for (const term of terms) map.set(term.key, term.coefficient);
57
+ return fromPolynomial({ terms: map, vars: namesOf(terms.map((term) => term.key)) });
58
+ }
59
+ function product(factors) {
60
+ let result = factors[0];
61
+ for (let i = 1; i < factors.length; i++) result = { kind: "mul", left: result, right: factors[i] };
62
+ return result;
63
+ }
64
+ function orderedTerms(p) {
65
+ const terms = [...p.terms].map(([key, coefficient]) => ({ key, coefficient }));
66
+ return terms.sort((a, b) => compareMonomials(a.key, b.key, p.vars));
67
+ }
68
+ function factorMultivariate(p) {
69
+ if (p.vars.length < 2) return null;
70
+ const terms = orderedTerms(p);
71
+ if (terms.length === 2) return factorBinomial(terms[0], terms[1]);
72
+ if (terms.length === 3) return factorPerfectSquare(terms);
73
+ if (terms.length === 4) return factorByGrouping(terms);
74
+ return null;
75
+ }
76
+ function factorBinomial(first, second) {
77
+ const firstPositive = first.coefficient.n > 0n;
78
+ const secondPositive = second.coefficient.n > 0n;
79
+ if (!firstPositive) return null;
80
+ const squares = asPowerPair(first, second, 2);
81
+ if (squares !== null && !secondPositive) {
82
+ return product([
83
+ termsToNode([squares.a, negated(squares.b)]),
84
+ termsToNode([squares.a, squares.b])
85
+ ]);
86
+ }
87
+ const cubes = asPowerPair(first, second, 3);
88
+ if (cubes === null) return null;
89
+ const linear = secondPositive ? termsToNode([cubes.a, cubes.b]) : termsToNode([cubes.a, negated(cubes.b)]);
90
+ const middle = secondPositive ? negated(multiplyTerms(cubes.a, cubes.b)) : multiplyTerms(cubes.a, cubes.b);
91
+ return product([linear, termsToNode([squareOf(cubes.a), middle, squareOf(cubes.b)])]);
92
+ }
93
+ function asPowerPair(first, second, degree) {
94
+ const magnitude = second.coefficient.n < 0n ? rationalNeg(second.coefficient) : second.coefficient;
95
+ const firstRoot = exactRoot(first.coefficient, degree);
96
+ const secondRoot = exactRoot(magnitude, degree);
97
+ if (firstRoot === null || secondRoot === null) return null;
98
+ const firstKey = monomialRoot(first.key, degree);
99
+ const secondKey = monomialRoot(second.key, degree);
100
+ if (firstKey === null || secondKey === null) return null;
101
+ return { a: { key: firstKey, coefficient: firstRoot }, b: { key: secondKey, coefficient: secondRoot } };
102
+ }
103
+ function negated(term) {
104
+ return { key: term.key, coefficient: rationalNeg(term.coefficient) };
105
+ }
106
+ function multiplyTerms(a, b) {
107
+ return { key: monomialMul(a.key, b.key), coefficient: rationalMul(a.coefficient, b.coefficient) };
108
+ }
109
+ function squareOf(term) {
110
+ return multiplyTerms(term, term);
111
+ }
112
+ function factorPerfectSquare(terms) {
113
+ const [first, middle, last] = terms;
114
+ if (first.coefficient.n < 0n || last.coefficient.n < 0n) return null;
115
+ const roots = asPowerPair(first, last, 2);
116
+ if (roots === null) return null;
117
+ const cross = multiplyTerms(roots.a, roots.b);
118
+ if (cross.key !== middle.key) return null;
119
+ const twice = rationalMul(cross.coefficient, { n: 2n, d: 1n });
120
+ const negative = middle.coefficient.n < 0n;
121
+ const magnitude = negative ? rationalNeg(middle.coefficient) : middle.coefficient;
122
+ if (!isRationalOne(rationalDiv(magnitude, twice))) return null;
123
+ const base = termsToNode([roots.a, negative ? negated(roots.b) : roots.b]);
124
+ return { kind: "pow", base, exponent: constNode(2) };
125
+ }
126
+ function factorByGrouping(terms) {
127
+ const pairings = [
128
+ [[0, 1], [2, 3]],
129
+ [[0, 2], [1, 3]],
130
+ [[0, 3], [1, 2]]
131
+ ];
132
+ for (const pairing of pairings) {
133
+ const first = splitPair(terms[pairing[0][0]], terms[pairing[0][1]]);
134
+ const second = splitPair(terms[pairing[1][0]], terms[pairing[1][1]]);
135
+ if (first === null || second === null) continue;
136
+ if (!cofactorsAgree(first.cofactor, second.cofactor)) continue;
137
+ return product([
138
+ termsToNode([first.common, second.common]),
139
+ termsToNode(first.cofactor)
140
+ ]);
141
+ }
142
+ return null;
143
+ }
144
+ function splitPair(first, second) {
145
+ const shared = monomialGcd(first.key, second.key);
146
+ const common = { key: shared, coefficient: first.coefficient };
147
+ const cofactor = [
148
+ { key: monomialDiv(first.key, shared), coefficient: { n: 1n, d: 1n } },
149
+ { key: monomialDiv(second.key, shared), coefficient: rationalDiv(second.coefficient, first.coefficient) }
150
+ ];
151
+ return cofactor[0].key === cofactor[1].key ? null : { common, cofactor };
152
+ }
153
+ function cofactorsAgree(a, b) {
154
+ if (a.length !== b.length) return false;
155
+ return a.every((term, index) => term.key === b[index].key && term.coefficient.n === b[index].coefficient.n && term.coefficient.d === b[index].coefficient.d);
156
+ }
157
+
158
+ // src/symbolic/Factor.ts
159
+ var FACTOR_MAX_DEGREE = 12;
160
+ var FACTOR_MAX_ROOT_CANDIDATES = 4096;
161
+ function gcd(a, b) {
162
+ let x = a < 0n ? -a : a;
163
+ let y = b < 0n ? -b : b;
164
+ while (y !== 0n) {
165
+ const remainder = x % y;
166
+ x = y;
167
+ y = remainder;
168
+ }
169
+ return x;
170
+ }
171
+ function lcm(a, b) {
172
+ if (a === 0n || b === 0n) return 0n;
173
+ return a / gcd(a, b) * b;
174
+ }
175
+ function divisors(value) {
176
+ const magnitude = value < 0n ? -value : value;
177
+ if (magnitude === 0n) return null;
178
+ const found = [];
179
+ for (let candidate = 1n; candidate * candidate <= magnitude; candidate++) {
180
+ if (magnitude % candidate !== 0n) continue;
181
+ found.push(candidate);
182
+ const paired = magnitude / candidate;
183
+ if (paired !== candidate) found.push(paired);
184
+ if (found.length > FACTOR_MAX_ROOT_CANDIDATES) return null;
185
+ }
186
+ return found;
187
+ }
188
+ function evaluateAt(descending, x) {
189
+ let total = RATIONAL_ZERO;
190
+ for (const coeff of descending) total = rationalAdd(rationalMul(total, x), coeff);
191
+ return total;
192
+ }
193
+ function divideByRoot(descending, root) {
194
+ const quotient = [descending[0]];
195
+ for (let i = 1; i < descending.length - 1; i++) {
196
+ quotient.push(rationalAdd(descending[i], rationalMul(quotient[i - 1], root)));
197
+ }
198
+ return quotient;
199
+ }
200
+ function rationalRoots(descending) {
201
+ if (descending.length < 2) return [];
202
+ let multiplier = 1n;
203
+ for (const coeff of descending) multiplier = lcm(multiplier, coeff.d);
204
+ const integers = descending.map((coeff) => coeff.n * multiplier / coeff.d);
205
+ const leading = integers[0];
206
+ const trailing = integers[integers.length - 1];
207
+ if (trailing === 0n) return [];
208
+ const numeratorDivisors = divisors(trailing);
209
+ const denominatorDivisors = divisors(leading);
210
+ if (numeratorDivisors === null || denominatorDivisors === null) {
211
+ throw ErrorFactory.execution(
212
+ "SYMBOLIC_FACTOR_LIMIT_EXCEEDED",
213
+ "This polynomial's coefficients have too many divisors to search for rational roots.",
214
+ { limit: FACTOR_MAX_ROOT_CANDIDATES }
215
+ );
216
+ }
217
+ if (numeratorDivisors.length * denominatorDivisors.length > FACTOR_MAX_ROOT_CANDIDATES) {
218
+ throw ErrorFactory.execution(
219
+ "SYMBOLIC_FACTOR_LIMIT_EXCEEDED",
220
+ "This polynomial has too many candidate rational roots to test.",
221
+ { limit: FACTOR_MAX_ROOT_CANDIDATES }
222
+ );
223
+ }
224
+ const roots = [];
225
+ const seen = /* @__PURE__ */ new Set();
226
+ for (const p of numeratorDivisors) {
227
+ for (const q of denominatorDivisors) {
228
+ for (const sign of [1n, -1n]) {
229
+ const candidate = { n: sign * p / gcd(p, q), d: q / gcd(p, q) };
230
+ const key = `${candidate.n}/${candidate.d}`;
231
+ if (seen.has(key)) continue;
232
+ seen.add(key);
233
+ if (isRationalZero(evaluateAt(descending, candidate))) roots.push(candidate);
234
+ }
235
+ }
236
+ }
237
+ return roots;
238
+ }
239
+ function linearFactorNode(variable, root) {
240
+ if (isRationalZero(root)) return varNode(variable);
241
+ return root.n > 0n ? { kind: "sub", left: varNode(variable), right: constNode(root) } : { kind: "add", left: varNode(variable), right: constNode(rationalNeg(root)) };
242
+ }
243
+ function coefficientsToNode(descending, variable) {
244
+ const degree = descending.length - 1;
245
+ const terms = /* @__PURE__ */ new Map();
246
+ descending.forEach((coeff, index) => {
247
+ if (isRationalZero(coeff)) return;
248
+ const power2 = degree - index;
249
+ terms.set(power2 === 0 ? "" : power2 === 1 ? variable : `${variable}^${power2}`, coeff);
250
+ });
251
+ return fromPolynomial({ terms, vars: terms.size > 0 ? [variable] : [] });
252
+ }
253
+ function factorUnivariate(descending, variable) {
254
+ const factors = [];
255
+ let remaining = [...descending];
256
+ let roots = rationalRoots(remaining);
257
+ while (roots.length > 0 && remaining.length > 2) {
258
+ for (const root of roots) {
259
+ let multiplicity = 0;
260
+ while (remaining.length > 1 && isRationalZero(evaluateAt(remaining, root))) {
261
+ remaining = divideByRoot(remaining, root);
262
+ multiplicity++;
263
+ }
264
+ if (multiplicity > 0) factors.push({ base: linearFactorNode(variable, root), power: multiplicity });
265
+ }
266
+ roots = remaining.length > 2 ? rationalRoots(remaining) : [];
267
+ }
268
+ const leftoverDegree = remaining.length - 1;
269
+ if (leftoverDegree >= 1) {
270
+ factors.push({ base: coefficientsToNode(remaining, variable), power: 1 });
271
+ return { content: RATIONAL_ONE, factors };
272
+ }
273
+ return { content: remaining.length === 1 ? remaining[0] : RATIONAL_ONE, factors };
274
+ }
275
+ function factorizationToNode(factorization) {
276
+ const pieces = [];
277
+ if (!isRationalOne(factorization.content)) pieces.push(constNode(factorization.content));
278
+ for (const factor of factorization.factors) {
279
+ pieces.push(factor.power === 1 ? factor.base : powNode(factor.base, constNode({ n: BigInt(factor.power), d: 1n })));
280
+ }
281
+ if (pieces.length === 0) return constNode(RATIONAL_ONE);
282
+ let result = pieces[0];
283
+ for (let i = 1; i < pieces.length; i++) result = { kind: "mul", left: result, right: pieces[i] };
284
+ return result;
285
+ }
286
+ function contentOf(p) {
287
+ let numeratorGcd = 0n;
288
+ let denominatorLcm = 1n;
289
+ for (const coeff of p.terms.values()) {
290
+ numeratorGcd = gcd(numeratorGcd, coeff.n);
291
+ denominatorLcm = lcm(denominatorLcm, coeff.d);
292
+ }
293
+ if (numeratorGcd === 0n) return RATIONAL_ONE;
294
+ return { n: numeratorGcd, d: denominatorLcm };
295
+ }
296
+ function extractCommonMonomial(p) {
297
+ const common = /* @__PURE__ */ new Map();
298
+ for (const name of p.vars) {
299
+ let lowest = Infinity;
300
+ for (const key of p.terms.keys()) {
301
+ const exponent = exponentOf(key, name);
302
+ if (exponent < lowest) lowest = exponent;
303
+ }
304
+ if (lowest > 0 && lowest !== Infinity) common.set(name, lowest);
305
+ }
306
+ if (common.size === 0) return { monomial: common, reduced: p };
307
+ const terms = /* @__PURE__ */ new Map();
308
+ for (const [key, coeff] of p.terms) {
309
+ const exponents = parseKey(key);
310
+ for (const [name, shared] of common) exponents.set(name, (exponents.get(name) ?? 0) - shared);
311
+ terms.set(buildKey(exponents), coeff);
312
+ }
313
+ const names = /* @__PURE__ */ new Set();
314
+ for (const key of terms.keys()) for (const name of parseKey(key).keys()) names.add(name);
315
+ return { monomial: common, reduced: { terms, vars: [...names].sort() } };
316
+ }
317
+ function exponentOf(key, name) {
318
+ return parseKey(key).get(name) ?? 0;
319
+ }
320
+ function parseKey(key) {
321
+ const exponents = /* @__PURE__ */ new Map();
322
+ if (key === "") return exponents;
323
+ for (const factor of key.split("*")) {
324
+ const caret = factor.indexOf("^");
325
+ if (caret === -1) exponents.set(factor, 1);
326
+ else exponents.set(factor.slice(0, caret), Number(factor.slice(caret + 1)));
327
+ }
328
+ return exponents;
329
+ }
330
+ function buildKey(exponents) {
331
+ const names = [...exponents.keys()].filter((name) => (exponents.get(name) ?? 0) > 0).sort();
332
+ return names.map((name) => exponents.get(name) === 1 ? name : `${name}^${exponents.get(name)}`).join("*");
333
+ }
334
+ function monomialNode(monomial) {
335
+ const names = [...monomial.keys()].sort();
336
+ let result = null;
337
+ for (const name of names) {
338
+ const exponent = monomial.get(name);
339
+ const factor = exponent === 1 ? varNode(name) : powNode(varNode(name), constNode({ n: BigInt(exponent), d: 1n }));
340
+ result = result === null ? factor : { kind: "mul", left: result, right: factor };
341
+ }
342
+ return result;
343
+ }
344
+ function factorSymbolic(node) {
345
+ const polynomial = toPolynomial(node);
346
+ if (polynomial === null || polynomial.terms.size === 0) return node;
347
+ if (polyDegree(polynomial) > FACTOR_MAX_DEGREE) return node;
348
+ if (polynomial.vars.length === 0) return node;
349
+ const content = contentOf(polynomial);
350
+ const primitive = isRationalOne(content) ? polynomial : scaleTerms(polynomial, rationalDiv(RATIONAL_ONE, content));
351
+ const { monomial, reduced } = extractCommonMonomial(primitive);
352
+ const monomialFactor = monomialNode(monomial);
353
+ const variable = polyUnivariateVar(reduced);
354
+ if (variable === null) {
355
+ const patterned = factorMultivariate(reduced);
356
+ if (patterned !== null) return assemble(content, monomialFactor, patterned);
357
+ const pieces2 = buildPieces(content, monomialFactor, reduced);
358
+ return pieces2 ?? node;
359
+ }
360
+ const descending = [...polyCoefficients(reduced, variable)].reverse();
361
+ const factorization = factorUnivariate(descending, variable);
362
+ const combinedContent = rationalMul(content, factorization.content);
363
+ const isUnchanged = factorization.factors.length <= 1 && (factorization.factors[0]?.power ?? 1) === 1 && monomialFactor === null && isRationalOne(combinedContent);
364
+ if (isUnchanged) return node;
365
+ const pieces = [];
366
+ if (!isRationalOne(combinedContent)) pieces.push(constNode(combinedContent));
367
+ if (monomialFactor !== null) pieces.push(monomialFactor);
368
+ pieces.push(factorizationToNode({ content: RATIONAL_ONE, factors: factorization.factors }));
369
+ let result = pieces[0];
370
+ for (let i = 1; i < pieces.length; i++) result = { kind: "mul", left: result, right: pieces[i] };
371
+ return result;
372
+ }
373
+ function scaleTerms(p, k) {
374
+ const terms = /* @__PURE__ */ new Map();
375
+ for (const [key, coeff] of p.terms) terms.set(key, rationalMul(coeff, k));
376
+ return { terms, vars: p.vars };
377
+ }
378
+ function assemble(content, monomialFactor, factored) {
379
+ const pieces = [];
380
+ if (!isRationalOne(content)) pieces.push(constNode(content));
381
+ if (monomialFactor !== null) pieces.push(monomialFactor);
382
+ pieces.push(factored);
383
+ let result = pieces[0];
384
+ for (let i = 1; i < pieces.length; i++) result = { kind: "mul", left: result, right: pieces[i] };
385
+ return result;
386
+ }
387
+ function buildPieces(content, monomialFactor, reduced) {
388
+ if (monomialFactor === null && isRationalOne(content)) return null;
389
+ const pieces = [];
390
+ if (!isRationalOne(content)) pieces.push(constNode(content));
391
+ if (monomialFactor !== null) pieces.push(monomialFactor);
392
+ pieces.push(fromPolynomial(reduced));
393
+ let result = pieces[0];
394
+ for (let i = 1; i < pieces.length; i++) result = { kind: "mul", left: result, right: pieces[i] };
395
+ return result;
396
+ }
397
+
398
+ // src/symbolic/CubicQuartic.ts
399
+ var TWO = { n: 2n, d: 1n };
400
+ var THREE = { n: 3n, d: 1n };
401
+ var FOUR = { n: 4n, d: 1n };
402
+ function depressCubic(a, b, c, d) {
403
+ const shift = rationalNeg(rationalDiv(b, rationalMul(THREE, a)));
404
+ const p = rationalDiv(
405
+ rationalSub(rationalMul(THREE, rationalMul(a, c)), rationalMul(b, b)),
406
+ rationalMul(THREE, rationalMul(a, a))
407
+ );
408
+ const twoBCubed = rationalMul(TWO, rationalMul(b, rationalMul(b, b)));
409
+ const nineABC = rationalMul({ n: 9n, d: 1n }, rationalMul(a, rationalMul(b, c)));
410
+ const twentySevenAAD = rationalMul({ n: 27n, d: 1n }, rationalMul(rationalMul(a, a), d));
411
+ const q = rationalDiv(
412
+ rationalAdd(rationalSub(twoBCubed, nineABC), twentySevenAAD),
413
+ rationalMul({ n: 27n, d: 1n }, rationalMul(a, rationalMul(a, a)))
414
+ );
415
+ return { p, q, shift };
416
+ }
417
+ function solveCubic(a, b, c, d) {
418
+ const { p, q, shift } = depressCubic(a, b, c, d);
419
+ const discriminant = rationalNeg(
420
+ rationalAdd(
421
+ rationalMul(FOUR, rationalMul(p, rationalMul(p, p))),
422
+ rationalMul({ n: 27n, d: 1n }, rationalMul(q, q))
423
+ )
424
+ );
425
+ if (rationalCompare(discriminant, RATIONAL_ZERO) > 0) {
426
+ return { exact: [], approximate: trigonometricRoots(p, q, shift) };
427
+ }
428
+ if (isRationalZero(discriminant)) return { exact: repeatedCubicRoots(p, q, shift), approximate: [] };
429
+ return { exact: cardanoRoots(p, q, shift), approximate: [] };
430
+ }
431
+ function repeatedCubicRoots(p, q, shift) {
432
+ if (isRationalZero(p)) return [constNode(shift)];
433
+ const simple = rationalAdd(rationalDiv(rationalMul(THREE, q), p), shift);
434
+ const repeated = rationalAdd(rationalNeg(rationalDiv(rationalMul(THREE, q), rationalMul(TWO, p))), shift);
435
+ const ordered = [simple, repeated].sort(rationalCompare);
436
+ return ordered.map(constNode);
437
+ }
438
+ function cardanoRoots(p, q, shift) {
439
+ const half = rationalNeg(rationalDiv(q, TWO));
440
+ const radicand = rationalAdd(
441
+ rationalMul(rationalDiv(q, TWO), rationalDiv(q, TWO)),
442
+ rationalMul(rationalDiv(p, THREE), rationalMul(rationalDiv(p, THREE), rationalDiv(p, THREE)))
443
+ );
444
+ const inner = surdNode(radicand);
445
+ const u = { kind: "call", name: "cbrt", args: [{ kind: "add", left: constNode(half), right: inner }] };
446
+ const v = { kind: "call", name: "cbrt", args: [{ kind: "sub", left: constNode(half), right: inner }] };
447
+ const sum = { kind: "add", left: u, right: v };
448
+ const difference = { kind: "sub", left: u, right: v };
449
+ const real = { kind: "add", left: constNode(shift), right: { kind: "div", left: { kind: "neg", operand: sum }, right: constNode(TWO) } };
450
+ const imaginary = {
451
+ kind: "mul",
452
+ left: { kind: "div", left: { kind: "mul", left: difference, right: surdNode(THREE) }, right: constNode(TWO) },
453
+ right: complexNode(COMPLEX_I)
454
+ };
455
+ return [
456
+ { kind: "add", left: constNode(shift), right: sum },
457
+ { kind: "sub", left: real, right: imaginary },
458
+ { kind: "add", left: real, right: imaginary }
459
+ ];
460
+ }
461
+ function trigonometricRoots(p, q, shift) {
462
+ const pNumber = rationalToNumber(p);
463
+ const qNumber = rationalToNumber(q);
464
+ const shiftNumber = rationalToNumber(shift);
465
+ const magnitude = 2 * Math.sqrt(-pNumber / 3);
466
+ const ratio = 3 * qNumber / (2 * pNumber) * Math.sqrt(-3 / pNumber);
467
+ const angle = Math.acos(Math.min(1, Math.max(-1, ratio))) / 3;
468
+ return [0, 1, 2].map((k) => magnitude * Math.cos(angle - 2 * Math.PI * k / 3) + shiftNumber).sort((left, right) => left - right);
469
+ }
470
+ function depressQuartic(b, c, d, e) {
471
+ const shift = rationalNeg(rationalDiv(b, FOUR));
472
+ const bb = rationalMul(b, b);
473
+ const p = rationalSub(c, rationalDiv(rationalMul(THREE, bb), { n: 8n, d: 1n }));
474
+ const q = rationalAdd(
475
+ rationalSub(d, rationalDiv(rationalMul(b, c), TWO)),
476
+ rationalDiv(rationalMul(bb, b), { n: 8n, d: 1n })
477
+ );
478
+ const r = rationalSub(
479
+ rationalAdd(
480
+ rationalSub(e, rationalDiv(rationalMul(b, d), FOUR)),
481
+ rationalDiv(rationalMul(bb, c), { n: 16n, d: 1n })
482
+ ),
483
+ rationalDiv(rationalMul(THREE, rationalMul(bb, bb)), { n: 256n, d: 1n })
484
+ );
485
+ return { p, q, r, shift };
486
+ }
487
+ function solveQuartic(a, b, c, d, e, solveQuadratic2) {
488
+ const monic = (value) => rationalDiv(value, a);
489
+ const { p, q, r, shift } = depressQuartic(monic(b), monic(c), monic(d), monic(e));
490
+ const roots = isRationalZero(q) ? biquadraticRoots(p, r) : splitQuarticRoots(p, q, r, solveQuadratic2);
491
+ if (roots === null) return null;
492
+ const shifted = isRationalZero(shift) ? roots : roots.map((root) => ({ kind: "add", left: constNode(shift), right: root }));
493
+ return { exact: distinct(shifted), approximate: [] };
494
+ }
495
+ function distinct(roots) {
496
+ const seen = /* @__PURE__ */ new Set();
497
+ const unique = [];
498
+ for (const root of roots) {
499
+ const key = symbolicKey(simplifySymbolic(root));
500
+ if (seen.has(key)) continue;
501
+ seen.add(key);
502
+ unique.push(root);
503
+ }
504
+ return unique;
505
+ }
506
+ function biquadraticRoots(p, r) {
507
+ const discriminant = rationalSub(rationalMul(p, p), rationalMul(FOUR, r));
508
+ if (rationalCompare(discriminant, RATIONAL_ZERO) < 0) return complexBiquadraticRoots(p, r);
509
+ const root = exactRationalSqrt(discriminant);
510
+ if (root !== null) return rationalSquareRoots(rationalNeg(p), root, isRationalZero(discriminant));
511
+ return nestedSquareRoots(p, r, discriminant);
512
+ }
513
+ function rationalSquareRoots(negatedP, root, repeated) {
514
+ const values = repeated ? [rationalDiv(negatedP, TWO)] : [rationalDiv(rationalAdd(negatedP, root), TWO), rationalDiv(rationalSub(negatedP, root), TWO)];
515
+ const roots = [];
516
+ for (const value of values) {
517
+ if (isRationalZero(value)) {
518
+ roots.push(constNode(RATIONAL_ZERO));
519
+ continue;
520
+ }
521
+ const square = signedSurdNode(value);
522
+ roots.push({ kind: "neg", operand: square }, square);
523
+ }
524
+ return roots;
525
+ }
526
+ function nestedSquareRoots(p, r, discriminant) {
527
+ const negatedP = constNode(rationalNeg(p));
528
+ const surd = surdNode(discriminant);
529
+ const negativeP = rationalCompare(p, RATIONAL_ZERO) <= 0;
530
+ const solutions = [
531
+ { node: halved({ kind: "add", left: negatedP, right: surd }), positive: negativeP || rationalCompare(r, RATIONAL_ZERO) <= 0 },
532
+ { node: halved({ kind: "sub", left: negatedP, right: surd }), positive: negativeP && rationalCompare(r, RATIONAL_ZERO) >= 0 }
533
+ ];
534
+ const roots = [];
535
+ for (const { node, positive } of solutions) {
536
+ const radicand = positive ? node : { kind: "neg", operand: node };
537
+ const magnitude = { kind: "call", name: "sqrt", args: [radicand] };
538
+ const square = positive ? magnitude : { kind: "mul", left: magnitude, right: complexNode(COMPLEX_I) };
539
+ roots.push({ kind: "neg", operand: square }, square);
540
+ }
541
+ return roots;
542
+ }
543
+ function halved(node) {
544
+ return { kind: "div", left: node, right: constNode(TWO) };
545
+ }
546
+ function complexBiquadraticRoots(p, r) {
547
+ const modulus = exactRationalSqrt(r);
548
+ if (modulus === null) return null;
549
+ const realPart = rationalDiv(rationalAdd(modulus, rationalDiv(rationalNeg(p), TWO)), TWO);
550
+ const imaginaryPart = rationalDiv(rationalSub(modulus, rationalDiv(rationalNeg(p), TWO)), TWO);
551
+ if (rationalCompare(realPart, RATIONAL_ZERO) < 0 || rationalCompare(imaginaryPart, RATIONAL_ZERO) < 0) return null;
552
+ const re = surdNode(realPart);
553
+ const im = { kind: "mul", left: surdNode(imaginaryPart), right: complexNode(COMPLEX_I) };
554
+ const first = { kind: "add", left: re, right: im };
555
+ const second = { kind: "sub", left: re, right: im };
556
+ return [
557
+ { kind: "neg", operand: first },
558
+ { kind: "neg", operand: second },
559
+ second,
560
+ first
561
+ ];
562
+ }
563
+ function splitQuarticRoots(p, q, r, solveQuadratic2) {
564
+ const resolvent = [
565
+ { n: 1n, d: 1n },
566
+ rationalMul(TWO, p),
567
+ rationalSub(rationalMul(p, p), rationalMul(FOUR, r)),
568
+ rationalNeg(rationalMul(q, q))
569
+ ];
570
+ for (const z of rationalRoots(resolvent)) {
571
+ if (rationalCompare(z, RATIONAL_ZERO) <= 0) continue;
572
+ const alpha = exactRationalSqrt(z);
573
+ if (alpha === null) continue;
574
+ const sum = rationalAdd(p, z);
575
+ const difference = rationalDiv(q, alpha);
576
+ const beta = rationalDiv(rationalSub(sum, difference), TWO);
577
+ const gamma = rationalDiv(rationalAdd(sum, difference), TWO);
578
+ const one2 = { n: 1n, d: 1n };
579
+ return [
580
+ ...solveQuadratic2(one2, alpha, beta),
581
+ ...solveQuadratic2(one2, rationalNeg(alpha), gamma)
582
+ ];
583
+ }
584
+ return null;
585
+ }
586
+
587
+ // src/symbolic/Solve.ts
588
+ var SOLVE_MAX_DEGREE = 8;
589
+ var NEWTON_MAX_ITERATIONS = 100;
590
+ var NEWTON_TOLERANCE = 1e-12;
591
+ var NUMERIC_SCAN_STEPS = 2e3;
592
+ function evaluateRational(descending, x) {
593
+ let total = RATIONAL_ZERO;
594
+ for (const coeff of descending) total = rationalAdd(rationalMul(total, x), coeff);
595
+ return total;
596
+ }
597
+ function evaluateNumeric(descending, x) {
598
+ let total = 0;
599
+ for (const coeff of descending) total = total * x + rationalToNumber(coeff);
600
+ return total;
601
+ }
602
+ function divideByRoot2(descending, root) {
603
+ const quotient = [descending[0]];
604
+ for (let i = 1; i < descending.length - 1; i++) {
605
+ quotient.push(rationalAdd(descending[i], rationalMul(quotient[i - 1], root)));
606
+ }
607
+ return quotient;
608
+ }
609
+ function solveQuadratic(a, b, c) {
610
+ const discriminant = rationalSub(rationalMul(b, b), rationalMul(rational4(), rationalMul(a, c)));
611
+ const twoA = rationalMul(rational2(), a);
612
+ if (rationalCompare(discriminant, RATIONAL_ZERO) < 0) {
613
+ return complexQuadraticRoots(rationalNeg(b), discriminant, twoA);
614
+ }
615
+ if (isRationalZero(discriminant)) return [constNode(rationalDiv(rationalNeg(b), twoA))];
616
+ const rootN = exactIntegerSqrt(discriminant.n);
617
+ const rootD = exactIntegerSqrt(discriminant.d);
618
+ if (rootN !== null && rootD !== null) {
619
+ const root = { n: rootN, d: rootD };
620
+ const plus = rationalDiv(rationalAdd(rationalNeg(b), root), twoA);
621
+ const minus = rationalDiv(rationalSub(rationalNeg(b), root), twoA);
622
+ return rationalCompare(minus, plus) <= 0 ? [constNode(minus), constNode(plus)] : [constNode(plus), constNode(minus)];
623
+ }
624
+ const surd = surdNode(discriminant);
625
+ const ascending = rationalCompare(twoA, RATIONAL_ZERO) > 0;
626
+ const lower = { kind: "div", left: { kind: "sub", left: constNode(rationalNeg(b)), right: surd }, right: constNode(twoA) };
627
+ const upper = { kind: "div", left: { kind: "add", left: constNode(rationalNeg(b)), right: surd }, right: constNode(twoA) };
628
+ return ascending ? [lower, upper] : [upper, lower];
629
+ }
630
+ function complexQuadraticRoots(negatedB, discriminant, twoA) {
631
+ const magnitude = rationalNeg(discriminant);
632
+ const rootN = exactIntegerSqrt(magnitude.n);
633
+ const rootD = exactIntegerSqrt(magnitude.d);
634
+ if (rootN !== null && rootD !== null) {
635
+ const imaginary2 = rationalDiv({ n: rootN, d: rootD }, twoA);
636
+ const real2 = rationalDiv(negatedB, twoA);
637
+ return [
638
+ complexNode(complex(real2, rationalNeg(imaginary2))),
639
+ complexNode(complex(real2, imaginary2))
640
+ ];
641
+ }
642
+ const real = rationalDiv(negatedB, twoA);
643
+ const scaledRadicand = rationalDiv(magnitude, rationalMul(twoA, twoA));
644
+ const imaginary = { kind: "mul", left: surdNode(scaledRadicand), right: complexNode(COMPLEX_I) };
645
+ if (isRationalZero(real)) {
646
+ return [{ kind: "neg", operand: imaginary }, imaginary];
647
+ }
648
+ return [
649
+ { kind: "sub", left: constNode(real), right: imaginary },
650
+ { kind: "add", left: constNode(real), right: imaginary }
651
+ ];
652
+ }
653
+ function rational2() {
654
+ return { n: 2n, d: 1n };
655
+ }
656
+ function rational4() {
657
+ return { n: 4n, d: 1n };
658
+ }
659
+ function numericRoots(descending) {
660
+ const leading = rationalToNumber(descending[0]);
661
+ if (leading === 0) return [];
662
+ let bound = 0;
663
+ for (let i = 1; i < descending.length; i++) {
664
+ const ratio = Math.abs(rationalToNumber(descending[i]) / leading);
665
+ if (ratio > bound) bound = ratio;
666
+ }
667
+ bound += 1;
668
+ const roots = [];
669
+ const step = 2 * bound / NUMERIC_SCAN_STEPS;
670
+ let previousX = -bound;
671
+ let previousY = evaluateNumeric(descending, previousX);
672
+ for (let i = 1; i <= NUMERIC_SCAN_STEPS; i++) {
673
+ const x = -bound + i * step;
674
+ const y = evaluateNumeric(descending, x);
675
+ if (previousY === 0) roots.push(previousX);
676
+ else if (previousY < 0 !== y < 0) roots.push(bisect(descending, previousX, x));
677
+ previousX = x;
678
+ previousY = y;
679
+ }
680
+ return roots;
681
+ }
682
+ function bisect(descending, low, high) {
683
+ let left = low;
684
+ let right = high;
685
+ let leftValue = evaluateNumeric(descending, left);
686
+ for (let i = 0; i < NEWTON_MAX_ITERATIONS && right - left > NEWTON_TOLERANCE; i++) {
687
+ const middle = (left + right) / 2;
688
+ const middleValue = evaluateNumeric(descending, middle);
689
+ if (leftValue < 0 === middleValue < 0) {
690
+ left = middle;
691
+ leftValue = middleValue;
692
+ } else {
693
+ right = middle;
694
+ }
695
+ }
696
+ return (left + right) / 2;
697
+ }
698
+ function solveForVariable(lhs, rhs, variable) {
699
+ const polynomial = toPolynomial({ kind: "sub", left: lhs, right: rhs });
700
+ if (polynomial === null) {
701
+ return {
702
+ kind: "unsupported",
703
+ reason: "this is not a polynomial equation (it divides by an unknown, or calls a function of one)"
704
+ };
705
+ }
706
+ const others = polynomial.vars.filter((name) => name !== variable);
707
+ const degree = polyDegree(polynomial, variable);
708
+ if (others.length > 0) {
709
+ if (degree !== 1) {
710
+ return {
711
+ kind: "unsupported",
712
+ reason: `solving for "${variable}" needs the equation to be linear in it when other unknowns (${others.join(", ")}) are present`
713
+ };
714
+ }
715
+ return solveLinearWithOtherUnknowns(polynomial, variable);
716
+ }
717
+ if (degree === 0) {
718
+ return polynomial.terms.size === 0 ? { kind: "identity" } : { kind: "contradiction" };
719
+ }
720
+ if (degree > SOLVE_MAX_DEGREE) {
721
+ return { kind: "unsupported", reason: `degree ${degree} is above the supported maximum of ${SOLVE_MAX_DEGREE}` };
722
+ }
723
+ const descending = [...polyCoefficients(polynomial, variable)].reverse();
724
+ return solveUnivariate(descending);
725
+ }
726
+ function solveLinearWithOtherUnknowns(polynomial, variable) {
727
+ const coefficientTerms = /* @__PURE__ */ new Map();
728
+ const constantTerms = /* @__PURE__ */ new Map();
729
+ for (const [key, coeff] of polynomial.terms) {
730
+ const factors = key.split("*").filter((part) => part.length > 0);
731
+ const index = factors.indexOf(variable);
732
+ if (index === -1) {
733
+ constantTerms.set(key, coeff);
734
+ } else {
735
+ factors.splice(index, 1);
736
+ coefficientTerms.set(factors.join("*"), coeff);
737
+ }
738
+ }
739
+ const namesOf2 = (terms) => {
740
+ const names = /* @__PURE__ */ new Set();
741
+ for (const key of terms.keys()) {
742
+ for (const part of key.split("*")) {
743
+ if (part.length > 0) names.add(part.split("^")[0]);
744
+ }
745
+ }
746
+ return [...names].sort();
747
+ };
748
+ const coefficient = fromPolynomial({ terms: coefficientTerms, vars: namesOf2(coefficientTerms) });
749
+ const constant = fromPolynomial({ terms: constantTerms, vars: namesOf2(constantTerms) });
750
+ return {
751
+ kind: "roots",
752
+ exact: [{ kind: "div", left: { kind: "neg", operand: constant }, right: coefficient }],
753
+ approximate: []
754
+ };
755
+ }
756
+ function closedFormRoots(descending) {
757
+ if (descending.length === 4) {
758
+ return solveCubic(descending[0], descending[1], descending[2], descending[3]);
759
+ }
760
+ if (descending.length === 5) {
761
+ return solveQuartic(descending[0], descending[1], descending[2], descending[3], descending[4], solveQuadratic);
762
+ }
763
+ return null;
764
+ }
765
+ function solveUnivariate(descending) {
766
+ const exact = [];
767
+ let remaining = [...descending];
768
+ let roots = [...rationalRoots(remaining)].sort(rationalCompare);
769
+ while (roots.length > 0 && remaining.length > 1) {
770
+ for (const root of roots) {
771
+ while (remaining.length > 1 && isRationalZero(evaluateRational(remaining, root))) {
772
+ remaining = divideByRoot2(remaining, root);
773
+ }
774
+ exact.push(constNode(root));
775
+ }
776
+ roots = remaining.length > 1 ? [...rationalRoots(remaining)].sort(rationalCompare) : [];
777
+ }
778
+ const leftoverDegree = remaining.length - 1;
779
+ if (leftoverDegree === 1) {
780
+ exact.push(constNode(rationalDiv(rationalNeg(remaining[1]), remaining[0])));
781
+ return { kind: "roots", exact, approximate: [] };
782
+ }
783
+ if (leftoverDegree === 2) {
784
+ const quadratic = solveQuadratic(remaining[0], remaining[1], remaining[2]);
785
+ return { kind: "roots", exact: [...exact, ...quadratic], approximate: [] };
786
+ }
787
+ if (leftoverDegree <= 0) {
788
+ return exact.length > 0 ? { kind: "roots", exact, approximate: [] } : { kind: "no-real-solutions", reason: "there is no value that satisfies this equation" };
789
+ }
790
+ const closedForm = closedFormRoots(remaining);
791
+ if (closedForm !== null) {
792
+ return { kind: "roots", exact: [...exact, ...closedForm.exact], approximate: closedForm.approximate };
793
+ }
794
+ const approximate = numericRoots(remaining);
795
+ if (exact.length === 0 && approximate.length === 0) {
796
+ return { kind: "no-real-solutions", reason: "no real root was found within the polynomial's root bound" };
797
+ }
798
+ return { kind: "roots", exact, approximate };
799
+ }
800
+
801
+ // src/vm/SymbolicOps.ts
802
+ var SYMBOLIC_BUILTIN_NAMES = {
803
+ 0: "sqrt",
804
+ 1: "abs",
805
+ 2: "sin",
806
+ 3: "cos",
807
+ 4: "tan",
808
+ 5: "log",
809
+ 6: "ceil",
810
+ 7: "floor",
811
+ 8: "round",
812
+ 11: "asin",
813
+ 12: "acos",
814
+ 13: "atan",
815
+ 14: "atan2",
816
+ 15: "sinh",
817
+ 16: "cosh",
818
+ 17: "tanh",
819
+ 18: "asinh",
820
+ 19: "acosh",
821
+ 20: "atanh",
822
+ 21: "cbrt",
823
+ 23: "expm1",
824
+ 24: "exp",
825
+ 26: "hypot",
826
+ 28: "log10",
827
+ 29: "log1p",
828
+ 30: "log2",
829
+ 33: "sign",
830
+ 34: "trunc",
831
+ // Spelled exactly as `builtinNameToIndex` accepts them, all lower case. A
832
+ // `call` node's name is what gets displayed, so a name the parser would not
833
+ // accept back would render an expression the user cannot retype.
834
+ 35: "degtorad",
835
+ 36: "radtodeg",
836
+ 61: "root",
837
+ 62: "fact"
838
+ };
839
+ var POW_BUILTIN_INDEX = 31;
840
+ var SYMBOLIC_NATIVE_BUILTINS = /* @__PURE__ */ new Set([67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79]);
841
+ function valueToSymbolic(v) {
842
+ if (v.type === 9 /* Symbolic */) return v.value;
843
+ if (v.type === 13 /* Error */ || v.type === 12 /* Pending */) return null;
844
+ const numeric = v.toNumber();
845
+ if (!Number.isFinite(numeric)) return null;
846
+ return constNode(rationalFromNumber(numeric));
847
+ }
848
+ function symbolicToValue(node) {
849
+ const simplified = simplifySymbolic(node);
850
+ if (simplified.kind === "const") return numberValue(rationalToNumber(simplified.value));
851
+ return symbolicValue(simplified);
852
+ }
853
+ function unsupported(what) {
854
+ return errorValue(
855
+ "SYMBOLIC_UNSUPPORTED_FUNCTION",
856
+ `"${what}" cannot be applied to an expression that still contains an unknown.`
857
+ );
858
+ }
859
+ function symbolicPow(l, r) {
860
+ const base = valueToSymbolic(l);
861
+ const exponent = valueToSymbolic(r);
862
+ if (base === null || exponent === null) return unsupported("^");
863
+ return symbolicToValue(powNode(base, exponent));
864
+ }
865
+ function symbolicNeg(v) {
866
+ const operand = valueToSymbolic(v);
867
+ if (operand === null) return unsupported("-");
868
+ return symbolicToValue({ kind: "neg", operand });
869
+ }
870
+ function symbolicBuiltin(index, args) {
871
+ const nodes = [];
872
+ for (const arg of args) {
873
+ if (arg.type === 13 /* Error */) return arg;
874
+ const node = valueToSymbolic(arg);
875
+ if (node === null) return unsupported(SYMBOLIC_BUILTIN_NAMES[index] ?? `builtin ${index}`);
876
+ nodes.push(node);
877
+ }
878
+ if (index === POW_BUILTIN_INDEX && nodes.length === 2) {
879
+ return symbolicToValue(powNode(nodes[0], nodes[1]));
880
+ }
881
+ const name = SYMBOLIC_BUILTIN_NAMES[index];
882
+ if (name === void 0) return unsupported(`builtin ${index}`);
883
+ return symbolicToValue(callNode(name, nodes));
884
+ }
885
+ function rootToValue(root) {
886
+ const value = symbolicToValue(root);
887
+ if (value.type === 0 /* Number */ && !Number.isInteger(value.toNumber())) return symbolicValue(root);
888
+ return value;
889
+ }
890
+ function solveOutcomeToValue(outcome) {
891
+ switch (outcome.kind) {
892
+ case "identity":
893
+ return stringValue("true for every value");
894
+ case "contradiction":
895
+ return stringValue("no solution");
896
+ case "no-real-solutions":
897
+ return stringValue(`no real solutions (${outcome.reason})`);
898
+ case "unsupported":
899
+ return errorValue("SYMBOLIC_SOLVE_UNSUPPORTED", `Cannot solve this equation: ${outcome.reason}.`);
900
+ case "roots": {
901
+ const values = outcome.exact.map(rootToValue);
902
+ for (const approximate of outcome.approximate) values.push(numberValue(approximate));
903
+ if (values.length === 0) return stringValue("no solution");
904
+ if (values.length === 1) return values[0];
905
+ return matrixValue(1, values.length, values.map((v) => v.type === 9 /* Symbolic */ ? v.value : v.toNumber()));
906
+ }
907
+ }
908
+ }
909
+ function solveEquationValues(lhsValue, rhsValue, variable) {
910
+ const lhs = valueToSymbolic(lhsValue);
911
+ const rhs = valueToSymbolic(rhsValue);
912
+ if (lhs === null || rhs === null) {
913
+ return errorValue("SYMBOLIC_NONFINITE_OPERAND", "An equation side has no exact value to solve with.");
914
+ }
915
+ return solveOutcomeToValue(solveForVariable(lhs, rhs, variable));
916
+ }
917
+
918
+ // src/vm/VMConversion.ts
919
+ function unifyUom(l, r) {
920
+ if (l.type === 6 /* Uom */ && r.type === 6 /* Uom */) {
921
+ if (l.unit === r.unit) {
922
+ return { lv: l.toNumber(), rv: r.toNumber(), unit: l.unit, sameMeasure: true };
923
+ }
924
+ const lMeasure = getMeasure(l.unit);
925
+ const rMeasure = getMeasure(r.unit);
926
+ const isCurrency = sharedCurrencyExchange.isCurrency(l.unit) && sharedCurrencyExchange.isCurrency(r.unit);
927
+ if (lMeasure && lMeasure === rMeasure) {
928
+ const rvConverted = convertUnit(r.toNumber(), r.unit, l.unit);
929
+ return { lv: l.toNumber(), rv: rvConverted, unit: l.unit, sameMeasure: true };
930
+ }
931
+ if (isCurrency) {
932
+ const rvConverted = sharedCurrencyExchange.convertSync(r.toNumber(), r.unit, l.unit);
933
+ if (rvConverted !== null) {
934
+ return { lv: l.toNumber(), rv: rvConverted, unit: l.unit, sameMeasure: true };
935
+ }
936
+ }
937
+ return { lv: l.toNumber(), rv: r.toNumber(), unit: void 0, sameMeasure: false };
938
+ }
939
+ if (l.type === 6 /* Uom */) {
940
+ return { lv: l.toNumber(), rv: r.toNumber(), unit: l.unit, sameMeasure: true };
941
+ }
942
+ if (r.type === 6 /* Uom */) {
943
+ return { lv: l.toNumber(), rv: r.toNumber(), unit: r.unit, sameMeasure: true };
944
+ }
945
+ return { lv: l.toNumber(), rv: r.toNumber(), unit: void 0, sameMeasure: true };
946
+ }
947
+ function binaryOp(l, r, op, bigOp, symbolicOp) {
948
+ if (l.type === 13 /* Error */) return l;
949
+ if (r.type === 13 /* Error */) return r;
950
+ if (l.type === 12 /* Pending */) return l;
951
+ if (r.type === 12 /* Pending */) return r;
952
+ if (symbolicOp && (l.type === 9 /* Symbolic */ || r.type === 9 /* Symbolic */)) {
953
+ const left = valueToSymbolic(l);
954
+ const right = valueToSymbolic(r);
955
+ if (left === null || right === null) {
956
+ return errorValue(
957
+ "SYMBOLIC_NONFINITE_OPERAND",
958
+ "A symbolic expression cannot combine with a value that has no exact number (NaN or infinity)."
959
+ );
960
+ }
961
+ const node = { kind: symbolicOp, left, right };
962
+ return symbolicValue(simplifySymbolic(node));
963
+ }
964
+ if (l.type === 0 /* Number */ && r.type === 0 /* Number */) {
965
+ return numberValue(op(l.value, r.value));
966
+ }
967
+ if (l.type === 2 /* BigInt */ || r.type === 2 /* BigInt */) {
968
+ const lb = l.type === 2 /* BigInt */ ? l.value : BigInt(l.toNumber());
969
+ const rb = r.type === 2 /* BigInt */ ? r.value : BigInt(r.toNumber());
970
+ if (bigOp) return bigIntValue(bigOp(lb, rb));
971
+ return bigIntValue(lb + rb);
972
+ }
973
+ if (l.type === 6 /* Uom */ || r.type === 6 /* Uom */) {
974
+ const { lv, rv, unit, sameMeasure } = unifyUom(l, r);
975
+ if (isNaN(lv) || isNaN(rv)) return numberValue(0);
976
+ if (!sameMeasure) {
977
+ const lUnit = l.type === 6 /* Uom */ ? l.unit : void 0;
978
+ const rUnit = r.type === 6 /* Uom */ ? r.unit : void 0;
979
+ return errorValue("INCOMPATIBLE_UNITS", `Cannot combine incompatible units: ${lUnit ?? "?"} and ${rUnit ?? "?"}`);
980
+ }
981
+ return uomValue(op(lv, rv), unit);
982
+ }
983
+ if (l.type === 7 /* Matrix */ && r.type === 7 /* Matrix */) {
984
+ const lm = l.value;
985
+ const rm = r.value;
986
+ if (!sameShape(lm, rm)) {
987
+ return errorValue("DIMENSION_MISMATCH", `Cannot combine matrices of different shapes: ${lm.rows}x${lm.cols} and ${rm.rows}x${rm.cols}`);
988
+ }
989
+ const result = new Array(lm.data.length);
990
+ for (let i = 0; i < lm.data.length; i++) result[i] = op(lm.data[i], rm.data[i]);
991
+ return matrixValue(lm.rows, lm.cols, result);
992
+ }
993
+ if (l.type === 7 /* Matrix */) {
994
+ const lm = l.value;
995
+ const scalar = r.toNumber();
996
+ const result = lm.data.map((v) => op(v, scalar));
997
+ return matrixValue(lm.rows, lm.cols, result);
998
+ }
999
+ if (r.type === 7 /* Matrix */) {
1000
+ const rm = r.value;
1001
+ const scalar = l.toNumber();
1002
+ const result = rm.data.map((v) => op(scalar, v));
1003
+ return matrixValue(rm.rows, rm.cols, result);
1004
+ }
1005
+ const lNum = l.toNumber();
1006
+ const rNum = r.toNumber();
1007
+ if (isNaN(lNum) || isNaN(rNum)) return numberValue(0);
1008
+ return numberValue(op(lNum, rNum));
1009
+ }
1010
+
1011
+ // src/vm/OpRegistry.ts
1012
+ var MAX_OPCODE = 254;
1013
+ var DYNAMIC_OPCODE_START = 200;
1014
+ var OpRegistry = class {
1015
+ constructor() {
1016
+ this.handlers = /* @__PURE__ */ new Map();
1017
+ this.nextOpcode = DYNAMIC_OPCODE_START + 1;
1018
+ }
1019
+ register(registration) {
1020
+ this.handlers.set(registration.opcode, registration.handler);
1021
+ }
1022
+ /**
1023
+ * Remove a previously registered opcode handler.
1024
+ * Used by package unregistration to reverse shared-registry contributions.
1025
+ */
1026
+ unregister(opcode) {
1027
+ this.handlers.delete(opcode);
1028
+ }
1029
+ get(opcode) {
1030
+ return this.handlers.get(opcode);
1031
+ }
1032
+ has(opcode) {
1033
+ return this.handlers.has(opcode);
1034
+ }
1035
+ /**
1036
+ * Allocate a unique opcode for a plugin's custom bytecode handler.
1037
+ *
1038
+ * Returns the next available opcode (starting at 201). Each call
1039
+ * returns a distinct value. Plugins should call this once during
1040
+ * registration and store the result.
1041
+ *
1042
+ * @throws If the dynamic opcode pool is exhausted.
1043
+ * @returns A unique opcode number for the calling plugin.
1044
+ */
1045
+ allocateOpcode() {
1046
+ if (this.nextOpcode > MAX_OPCODE) {
1047
+ throw ErrorFactory.config(
1048
+ "OPCODE_POOL_EXHAUSTED",
1049
+ `OpRegistry: dynamic opcode pool exhausted (max ${MAX_OPCODE - DYNAMIC_OPCODE_START} allocations).`
1050
+ );
1051
+ }
1052
+ return this.nextOpcode++;
1053
+ }
1054
+ };
1055
+ var sharedOpRegistry = new OpRegistry();
1056
+
1057
+ // src/symbolic/PartialFractions.ts
1058
+ var APART_MAX_DEGREE = 12;
1059
+ function multiply(a, b) {
1060
+ if (a.length === 0 || b.length === 0) return [];
1061
+ const product2 = new Array(a.length + b.length - 1).fill(RATIONAL_ZERO);
1062
+ a.forEach((left, i) => {
1063
+ b.forEach((right, j) => {
1064
+ product2[i + j] = rationalAdd(product2[i + j], rationalMul(left, right));
1065
+ });
1066
+ });
1067
+ return product2;
1068
+ }
1069
+ function power(base, exponent) {
1070
+ let result = [RATIONAL_ONE];
1071
+ for (let i = 0; i < exponent; i++) result = multiply(result, base);
1072
+ return result;
1073
+ }
1074
+ function scale(coefficients, factor) {
1075
+ return coefficients.map((coefficient) => rationalDiv(coefficient, factor));
1076
+ }
1077
+ function denominatorFactors(ascending, variable) {
1078
+ const factors = [];
1079
+ let lowest = 0;
1080
+ while (lowest < ascending.length && isRationalZero(ascending[lowest])) lowest++;
1081
+ if (lowest > 0) factors.push({ base: [RATIONAL_ZERO, RATIONAL_ONE], power: lowest });
1082
+ const remaining = ascending.slice(lowest);
1083
+ if (remaining.length > 1) {
1084
+ const factorization = factorUnivariate([...remaining].reverse(), variable);
1085
+ for (const factor of factorization.factors) {
1086
+ const polynomial = toPolynomial(factor.base);
1087
+ if (polynomial === null) return null;
1088
+ factors.push({ base: [...polyCoefficients(polynomial, variable)], power: factor.power });
1089
+ }
1090
+ }
1091
+ return factors.length > 0 ? factors : null;
1092
+ }
1093
+ function enumerateUnknowns(factors) {
1094
+ const unknowns = [];
1095
+ factors.forEach((factor, index) => {
1096
+ const factorDegree = factor.base.length - 1;
1097
+ for (let p = 1; p <= factor.power; p++) {
1098
+ for (let degree = 0; degree < factorDegree; degree++) {
1099
+ unknowns.push({ factor: index, power: p, degree });
1100
+ }
1101
+ }
1102
+ });
1103
+ return unknowns;
1104
+ }
1105
+ function unknownColumn(unknown, factors, denominator) {
1106
+ const divisor = power(factors[unknown.factor].base, unknown.power);
1107
+ const { quotient, remainder } = polynomialDivide(denominator, divisor);
1108
+ if (!isZeroPolynomial(remainder)) return null;
1109
+ const shift = new Array(unknown.degree).fill(RATIONAL_ZERO);
1110
+ shift.push(RATIONAL_ONE);
1111
+ return multiply(quotient, shift);
1112
+ }
1113
+ function solveLinearSystem(matrix, target) {
1114
+ const size = target.length;
1115
+ for (let column = 0; column < size; column++) {
1116
+ let pivot = -1;
1117
+ for (let row = column; row < size; row++) {
1118
+ if (!isRationalZero(matrix[row][column])) {
1119
+ pivot = row;
1120
+ break;
1121
+ }
1122
+ }
1123
+ if (pivot === -1) return null;
1124
+ [matrix[column], matrix[pivot]] = [matrix[pivot], matrix[column]];
1125
+ [target[column], target[pivot]] = [target[pivot], target[column]];
1126
+ for (let row = 0; row < size; row++) {
1127
+ if (row === column || isRationalZero(matrix[row][column])) continue;
1128
+ const factor = rationalDiv(matrix[row][column], matrix[column][column]);
1129
+ for (let k = column; k < size; k++) {
1130
+ matrix[row][k] = rationalSub(matrix[row][k], rationalMul(factor, matrix[column][k]));
1131
+ }
1132
+ target[row] = rationalSub(target[row], rationalMul(factor, target[column]));
1133
+ }
1134
+ }
1135
+ return target.map((value, index) => rationalDiv(value, matrix[index][index]));
1136
+ }
1137
+ function partialFractions(numerator, denominator, variable) {
1138
+ if (denominator.length < 2 || denominator.length - 1 > APART_MAX_DEGREE) return null;
1139
+ const shared = coefficientGcd(numerator, denominator);
1140
+ const reducedNumerator = shared.length > 1 ? polynomialDivide(numerator, shared).quotient : [...numerator];
1141
+ const reducedDenominator = shared.length > 1 ? polynomialDivide(denominator, shared).quotient : [...denominator];
1142
+ if (reducedDenominator.length === 1) {
1143
+ return { polynomial: scale(reducedNumerator, reducedDenominator[0]), terms: [] };
1144
+ }
1145
+ if (reducedDenominator.length === 0) return null;
1146
+ const leading = reducedDenominator[reducedDenominator.length - 1];
1147
+ const monicDenominator = scale(reducedDenominator, leading);
1148
+ const scaledNumerator = scale(reducedNumerator, leading);
1149
+ const { quotient, remainder } = polynomialDivide(scaledNumerator, monicDenominator);
1150
+ if (isZeroPolynomial(remainder)) return { polynomial: quotient, terms: [] };
1151
+ const factors = denominatorFactors(monicDenominator, variable);
1152
+ if (factors === null) return null;
1153
+ const terms = solveForNumerators(factors, monicDenominator, remainder);
1154
+ return terms === null ? null : { polynomial: quotient, terms };
1155
+ }
1156
+ function solveForNumerators(factors, denominator, remainder) {
1157
+ const unknowns = enumerateUnknowns(factors);
1158
+ const size = denominator.length - 1;
1159
+ if (unknowns.length !== size) return null;
1160
+ const columns = [];
1161
+ for (const unknown of unknowns) {
1162
+ const column = unknownColumn(unknown, factors, denominator);
1163
+ if (column === null) return null;
1164
+ columns.push(column);
1165
+ }
1166
+ const matrix = [];
1167
+ for (let row = 0; row < size; row++) {
1168
+ matrix.push(columns.map((column) => column[row] ?? RATIONAL_ZERO));
1169
+ }
1170
+ const target = [];
1171
+ for (let row = 0; row < size; row++) target.push(remainder[row] ?? RATIONAL_ZERO);
1172
+ const solution = solveLinearSystem(matrix, target);
1173
+ if (solution === null) return null;
1174
+ return groupSolution(unknowns, solution, factors);
1175
+ }
1176
+ function groupSolution(unknowns, solution, factors) {
1177
+ const grouped = /* @__PURE__ */ new Map();
1178
+ unknowns.forEach((unknown, index) => {
1179
+ const key = `${unknown.factor}:${unknown.power}`;
1180
+ const existing = grouped.get(key) ?? [];
1181
+ existing[unknown.degree] = solution[index];
1182
+ grouped.set(key, existing);
1183
+ });
1184
+ const terms = [];
1185
+ for (const [key, coefficients] of grouped) {
1186
+ const [factorIndex, termPower] = key.split(":").map(Number);
1187
+ const filled = [...coefficients].map((value) => value ?? RATIONAL_ZERO);
1188
+ if (filled.every(isRationalZero)) continue;
1189
+ terms.push({ numerator: filled, base: factors[factorIndex].base, power: termPower });
1190
+ }
1191
+ return terms;
1192
+ }
1193
+ function coefficientsToNode2(coefficients, variable) {
1194
+ const terms = /* @__PURE__ */ new Map();
1195
+ coefficients.forEach((coefficient, exponent) => {
1196
+ if (isRationalZero(coefficient)) return;
1197
+ terms.set(exponent === 0 ? "" : exponent === 1 ? variable : `${variable}^${exponent}`, coefficient);
1198
+ });
1199
+ if (terms.size === 0) return constNode(RATIONAL_ZERO);
1200
+ return fromPolynomial({ terms, vars: coefficients.length > 1 ? [variable] : [] });
1201
+ }
1202
+ function apartSymbolic(node) {
1203
+ const parts = asRationalFunction(node);
1204
+ if (parts === null) return node;
1205
+ const decomposition = partialFractions(parts.numerator, parts.denominator, parts.variable);
1206
+ if (decomposition === null || decomposition.terms.length === 0) return node;
1207
+ let result = decomposition.polynomial.length > 0 ? coefficientsToNode2(decomposition.polynomial, parts.variable) : null;
1208
+ for (const term of decomposition.terms) {
1209
+ const base = coefficientsToNode2(term.base, parts.variable);
1210
+ const denominator = term.power === 1 ? base : powNode(base, constNode({ n: BigInt(term.power), d: 1n }));
1211
+ const negative = isNegativeNumerator(term.numerator);
1212
+ const numerator = negative ? term.numerator.map((coefficient) => rationalNeg(coefficient)) : term.numerator;
1213
+ const piece = {
1214
+ kind: "div",
1215
+ left: coefficientsToNode2(numerator, parts.variable),
1216
+ right: denominator
1217
+ };
1218
+ if (result === null) result = negative ? { kind: "neg", operand: piece } : piece;
1219
+ else result = { kind: negative ? "sub" : "add", left: result, right: piece };
1220
+ }
1221
+ return result === null ? node : simplifySymbolic(result);
1222
+ }
1223
+ function isNegativeNumerator(coefficients) {
1224
+ return coefficients.some((coefficient) => coefficient.n < 0n) && coefficients.every((coefficient) => coefficient.n <= 0n);
1225
+ }
1226
+ function asRationalFunction(node) {
1227
+ if (node.kind !== "div") return null;
1228
+ const numerator = toPolynomial(node.left);
1229
+ const denominator = toPolynomial(node.right);
1230
+ if (numerator === null || denominator === null) return null;
1231
+ const variable = polyUnivariateVar(denominator);
1232
+ if (variable === null) return null;
1233
+ if (numerator.vars.some((name) => name !== variable)) return null;
1234
+ return {
1235
+ numerator: polyCoefficients(numerator, variable),
1236
+ denominator: polyCoefficients(denominator, variable),
1237
+ variable
1238
+ };
1239
+ }
1240
+
1241
+ // src/symbolic/Derivative.ts
1242
+ var DERIVATIVE_MAX_ORDER = 16;
1243
+ function zero() {
1244
+ return constNode(RATIONAL_ZERO);
1245
+ }
1246
+ function one() {
1247
+ return constNode(RATIONAL_ONE);
1248
+ }
1249
+ function functionDerivative(name, argument) {
1250
+ switch (name) {
1251
+ case "sin":
1252
+ return callNode("cos", [argument]);
1253
+ case "cos":
1254
+ return { kind: "neg", operand: callNode("sin", [argument]) };
1255
+ case "tan":
1256
+ return { kind: "div", left: one(), right: powNode(callNode("cos", [argument]), constNode(2)) };
1257
+ case "exp":
1258
+ return callNode("exp", [argument]);
1259
+ case "log":
1260
+ return { kind: "div", left: one(), right: argument };
1261
+ case "sqrt":
1262
+ return {
1263
+ kind: "div",
1264
+ left: one(),
1265
+ right: { kind: "mul", left: constNode(2), right: callNode("sqrt", [argument]) }
1266
+ };
1267
+ case "asin":
1268
+ return { kind: "div", left: one(), right: callNode("sqrt", [oneMinusSquare(argument)]) };
1269
+ case "acos":
1270
+ return { kind: "neg", operand: { kind: "div", left: one(), right: callNode("sqrt", [oneMinusSquare(argument)]) } };
1271
+ case "atan":
1272
+ return { kind: "div", left: one(), right: onePlusSquare(argument) };
1273
+ case "sinh":
1274
+ return callNode("cosh", [argument]);
1275
+ case "cosh":
1276
+ return callNode("sinh", [argument]);
1277
+ case "tanh":
1278
+ return { kind: "div", left: one(), right: powNode(callNode("cosh", [argument]), constNode(2)) };
1279
+ case "abs":
1280
+ return callNode("sign", [argument]);
1281
+ default:
1282
+ return null;
1283
+ }
1284
+ }
1285
+ function oneMinusSquare(argument) {
1286
+ return { kind: "sub", left: one(), right: powNode(argument, constNode(2)) };
1287
+ }
1288
+ function onePlusSquare(argument) {
1289
+ return { kind: "add", left: one(), right: powNode(argument, constNode(2)) };
1290
+ }
1291
+ function differentiate(node, variable, order = 1) {
1292
+ if (order < 0 || !Number.isInteger(order)) {
1293
+ throw ErrorFactory.execution("SYMBOLIC_DERIVATIVE_ORDER_LIMIT", "A derivative order must be a whole number, at least zero.");
1294
+ }
1295
+ if (order > DERIVATIVE_MAX_ORDER) {
1296
+ throw ErrorFactory.execution(
1297
+ "SYMBOLIC_DERIVATIVE_ORDER_LIMIT",
1298
+ `A derivative order above ${DERIVATIVE_MAX_ORDER} is not supported.`,
1299
+ { limit: DERIVATIVE_MAX_ORDER }
1300
+ );
1301
+ }
1302
+ let result = simplifySymbolic(node);
1303
+ for (let i = 0; i < order; i++) result = simplifySymbolic(derive(result, variable));
1304
+ return result;
1305
+ }
1306
+ function derive(node, variable) {
1307
+ switch (node.kind) {
1308
+ case "const":
1309
+ case "complex":
1310
+ return zero();
1311
+ case "var":
1312
+ return node.name === variable ? one() : zero();
1313
+ case "add":
1314
+ return { kind: "add", left: derive(node.left, variable), right: derive(node.right, variable) };
1315
+ case "sub":
1316
+ return { kind: "sub", left: derive(node.left, variable), right: derive(node.right, variable) };
1317
+ case "neg":
1318
+ return { kind: "neg", operand: derive(node.operand, variable) };
1319
+ case "mul":
1320
+ return {
1321
+ kind: "add",
1322
+ left: { kind: "mul", left: derive(node.left, variable), right: node.right },
1323
+ right: { kind: "mul", left: node.left, right: derive(node.right, variable) }
1324
+ };
1325
+ case "div":
1326
+ return {
1327
+ kind: "div",
1328
+ left: {
1329
+ kind: "sub",
1330
+ left: { kind: "mul", left: derive(node.left, variable), right: node.right },
1331
+ right: { kind: "mul", left: node.left, right: derive(node.right, variable) }
1332
+ },
1333
+ right: powNode(node.right, constNode(2))
1334
+ };
1335
+ case "pow":
1336
+ return derivePow(node, variable);
1337
+ case "call": {
1338
+ if (node.args.length !== 1) return unevaluated(node, variable);
1339
+ const outer = functionDerivative(node.name, node.args[0]);
1340
+ if (outer === null) return unevaluated(node, variable);
1341
+ return { kind: "mul", left: outer, right: derive(node.args[0], variable) };
1342
+ }
1343
+ }
1344
+ }
1345
+ function derivePow(node, variable) {
1346
+ if (node.exponent.kind === "const") {
1347
+ const reduced = constNode(rationalSub(node.exponent.value, RATIONAL_ONE));
1348
+ return {
1349
+ kind: "mul",
1350
+ left: { kind: "mul", left: node.exponent, right: powNode(node.base, reduced) },
1351
+ right: derive(node.base, variable)
1352
+ };
1353
+ }
1354
+ if (node.base.kind === "const" && node.base.value.n > 0n) {
1355
+ return {
1356
+ kind: "mul",
1357
+ left: { kind: "mul", left: node, right: callNode("log", [node.base]) },
1358
+ right: derive(node.exponent, variable)
1359
+ };
1360
+ }
1361
+ return unevaluated(node, variable);
1362
+ }
1363
+ function unevaluated(node, variable) {
1364
+ return callNode("der", [node, varNode(variable)]);
1365
+ }
1366
+
1367
+ // src/symbolic/Integral.ts
1368
+ function asLinear(node, variable) {
1369
+ const polynomial = toPolynomial(node);
1370
+ if (polynomial === null) return null;
1371
+ const others = polynomial.vars.filter((name) => name !== variable);
1372
+ if (others.length > 0) return null;
1373
+ if (polyDegree(polynomial, variable) > 1) return null;
1374
+ const ascending = polyCoefficients(polynomial, variable);
1375
+ const intercept = ascending[0] ?? { n: 0n, d: 1n };
1376
+ const slope = ascending[1] ?? { n: 0n, d: 1n };
1377
+ return isRationalZero(slope) ? null : { slope, intercept };
1378
+ }
1379
+ function integratePolynomial(node, variable) {
1380
+ const polynomial = toPolynomial(node);
1381
+ if (polynomial === null) return null;
1382
+ const others = polynomial.vars.filter((name) => name !== variable);
1383
+ if (others.length > 0) {
1384
+ return { ok: false, reason: `it involves more than one unknown (${others.join(", ")})` };
1385
+ }
1386
+ const ascending = polyCoefficients(polynomial, variable);
1387
+ let result = constNode(0);
1388
+ ascending.forEach((coeff, power2) => {
1389
+ if (isRationalZero(coeff)) return;
1390
+ const nextPower = power2 + 1;
1391
+ const scaled = rationalDiv(coeff, { n: BigInt(nextPower), d: 1n });
1392
+ const term = {
1393
+ kind: "mul",
1394
+ left: constNode(scaled),
1395
+ right: nextPower === 1 ? varNode(variable) : powNode(varNode(variable), constNode(nextPower))
1396
+ };
1397
+ result = { kind: "add", left: result, right: term };
1398
+ });
1399
+ return { ok: true, value: simplifySymbolic(result) };
1400
+ }
1401
+ function integrateStandardForm(node, variable) {
1402
+ if (node.kind !== "call" || node.args.length !== 1) return null;
1403
+ const linear = asLinear(node.args[0], variable);
1404
+ if (linear === null) return null;
1405
+ const inner = node.args[0];
1406
+ const divideBySlope = (value) => simplifySymbolic({ kind: "div", left: value, right: constNode(linear.slope) });
1407
+ switch (node.name) {
1408
+ case "exp":
1409
+ return { ok: true, value: divideBySlope(callNode("exp", [inner])) };
1410
+ case "sin":
1411
+ return { ok: true, value: divideBySlope({ kind: "neg", operand: callNode("cos", [inner]) }) };
1412
+ case "cos":
1413
+ return { ok: true, value: divideBySlope(callNode("sin", [inner])) };
1414
+ case "log":
1415
+ return {
1416
+ ok: true,
1417
+ value: divideBySlope({
1418
+ kind: "sub",
1419
+ left: { kind: "mul", left: inner, right: callNode("log", [inner]) },
1420
+ right: inner
1421
+ })
1422
+ };
1423
+ default:
1424
+ return null;
1425
+ }
1426
+ }
1427
+ function integrateReciprocalForms(node, variable) {
1428
+ if (node.kind !== "div") return null;
1429
+ if (node.left.kind !== "const" || !isRationalOneNode(node.left.value)) return null;
1430
+ const linear = asLinear(node.right, variable);
1431
+ if (linear !== null) {
1432
+ return {
1433
+ ok: true,
1434
+ value: simplifySymbolic({
1435
+ kind: "div",
1436
+ left: callNode("log", [node.right]),
1437
+ right: constNode(linear.slope)
1438
+ })
1439
+ };
1440
+ }
1441
+ const denominator = toPolynomial(node.right);
1442
+ if (denominator !== null && denominator.vars.length === 1 && denominator.vars[0] === variable) {
1443
+ const ascending = polyCoefficients(denominator, variable);
1444
+ const isOnePlusSquare = ascending.length === 3 && isRationalOneNode(ascending[0]) && isRationalZero(ascending[1]) && isRationalOneNode(ascending[2]);
1445
+ if (isOnePlusSquare) return { ok: true, value: callNode("atan", [varNode(variable)]) };
1446
+ }
1447
+ return null;
1448
+ }
1449
+ function isRationalOneNode(value) {
1450
+ return value.n === 1n && value.d === 1n;
1451
+ }
1452
+ function integrateRationalFunction(node, variable) {
1453
+ const parts = asRationalFunction(node);
1454
+ if (parts === null || parts.variable !== variable) return null;
1455
+ const decomposition = partialFractions(parts.numerator, parts.denominator, variable);
1456
+ if (decomposition === null) return null;
1457
+ let result = decomposition.polynomial.length > 0 ? polynomialAntiderivative(decomposition.polynomial, variable) : constNode(0);
1458
+ for (const term of decomposition.terms) {
1459
+ const piece = integrateTerm(term, variable);
1460
+ if (piece === null) {
1461
+ return {
1462
+ ok: false,
1463
+ reason: "its denominator has a repeated irreducible quadratic factor, which needs a reduction formula this does not have"
1464
+ };
1465
+ }
1466
+ result = { kind: "add", left: result, right: piece };
1467
+ }
1468
+ return { ok: true, value: simplifySymbolic(result) };
1469
+ }
1470
+ function integrateTerm(term, variable) {
1471
+ const baseDegree = term.base.length - 1;
1472
+ const base = coefficientsToNode2(term.base, variable);
1473
+ if (baseDegree === 1) {
1474
+ const coefficient = term.numerator[0] ?? RATIONAL_ZERO;
1475
+ if (term.power === 1) {
1476
+ return { kind: "mul", left: constNode(coefficient), right: callNode("log", [base]) };
1477
+ }
1478
+ const reduced = term.power - 1;
1479
+ const scaled = rationalDiv(coefficient, { n: BigInt(-reduced), d: 1n });
1480
+ return {
1481
+ kind: "div",
1482
+ left: constNode(scaled),
1483
+ right: powNode(base, constNode({ n: BigInt(reduced), d: 1n }))
1484
+ };
1485
+ }
1486
+ if (baseDegree !== 2 || term.power !== 1) return null;
1487
+ return integrateQuadraticTerm(term, variable, base);
1488
+ }
1489
+ function integrateQuadraticTerm(term, variable, base) {
1490
+ const constant = term.numerator[0] ?? RATIONAL_ZERO;
1491
+ const linear = term.numerator[1] ?? RATIONAL_ZERO;
1492
+ const [q, p] = term.base;
1493
+ const half = { n: 1n, d: 2n };
1494
+ const halfP = rationalMul(p, half);
1495
+ const logarithm = {
1496
+ kind: "mul",
1497
+ left: constNode(rationalMul(linear, half)),
1498
+ right: callNode("log", [base])
1499
+ };
1500
+ const leftover = rationalSub(constant, rationalMul(linear, halfP));
1501
+ if (isRationalZero(leftover)) return logarithm;
1502
+ const width = surdNode(rationalSub(q, rationalMul(halfP, halfP)));
1503
+ const shifted = {
1504
+ kind: "add",
1505
+ left: varNode(variable),
1506
+ right: constNode(halfP)
1507
+ };
1508
+ const arctangent = {
1509
+ kind: "mul",
1510
+ left: { kind: "div", left: constNode(leftover), right: width },
1511
+ right: callNode("atan", [{ kind: "div", left: shifted, right: width }])
1512
+ };
1513
+ return isRationalZero(linear) ? arctangent : { kind: "add", left: logarithm, right: arctangent };
1514
+ }
1515
+ function polynomialAntiderivative(ascending, variable) {
1516
+ let result = constNode(0);
1517
+ ascending.forEach((coeff, exponent) => {
1518
+ if (isRationalZero(coeff)) return;
1519
+ const nextPower = exponent + 1;
1520
+ const scaled = rationalDiv(coeff, { n: BigInt(nextPower), d: 1n });
1521
+ const term = {
1522
+ kind: "mul",
1523
+ left: constNode(scaled),
1524
+ right: nextPower === 1 ? varNode(variable) : powNode(varNode(variable), constNode(nextPower))
1525
+ };
1526
+ result = { kind: "add", left: result, right: term };
1527
+ });
1528
+ return result;
1529
+ }
1530
+ function integrate(node, variable) {
1531
+ const simplified = simplifySymbolic(node);
1532
+ if (!freeVariables(simplified).has(variable)) {
1533
+ return { ok: true, value: simplifySymbolic({ kind: "mul", left: simplified, right: varNode(variable) }) };
1534
+ }
1535
+ const polynomial = integratePolynomial(simplified, variable);
1536
+ if (polynomial !== null) return polynomial;
1537
+ const standard = integrateStandardForm(simplified, variable);
1538
+ if (standard !== null) return standard;
1539
+ const reciprocal = integrateReciprocalForms(simplified, variable);
1540
+ if (reciprocal !== null) return reciprocal;
1541
+ const rationalFunction = integrateRationalFunction(simplified, variable);
1542
+ if (rationalFunction !== null) return rationalFunction;
1543
+ if (simplified.kind === "add" || simplified.kind === "sub") {
1544
+ const left = integrate(simplified.left, variable);
1545
+ if (!left.ok) return left;
1546
+ const right = integrate(simplified.right, variable);
1547
+ if (!right.ok) return right;
1548
+ return {
1549
+ ok: true,
1550
+ value: simplifySymbolic({ kind: simplified.kind, left: left.value, right: right.value })
1551
+ };
1552
+ }
1553
+ if (simplified.kind === "mul" && simplified.left.kind === "const") {
1554
+ const inner = integrate(simplified.right, variable);
1555
+ if (!inner.ok) return inner;
1556
+ return { ok: true, value: simplifySymbolic({ kind: "mul", left: simplified.left, right: inner.value }) };
1557
+ }
1558
+ return {
1559
+ ok: false,
1560
+ reason: "no elementary antiderivative is known for this expression"
1561
+ };
1562
+ }
1563
+
1564
+ // src/symbolic/Taylor.ts
1565
+ var TAYLOR_MAX_DEGREE = 16;
1566
+ function taylorSeries(node, variable, point, degree) {
1567
+ if (degree < 0 || !Number.isInteger(degree) || degree > TAYLOR_MAX_DEGREE) {
1568
+ throw ErrorFactory.execution(
1569
+ "SYMBOLIC_TAYLOR_DEGREE_LIMIT",
1570
+ `A Taylor degree must be a whole number from 0 to ${TAYLOR_MAX_DEGREE}.`,
1571
+ { limit: TAYLOR_MAX_DEGREE }
1572
+ );
1573
+ }
1574
+ const pointNode = constNode(point);
1575
+ let factorial = 1n;
1576
+ let result = constNode(RATIONAL_ZERO);
1577
+ for (let order = 0; order <= degree; order++) {
1578
+ if (order > 0) factorial *= BigInt(order);
1579
+ const derivative = differentiate(node, variable, order);
1580
+ const atPoint = simplifySymbolic(substitute(derivative, variable, pointNode));
1581
+ if (atPoint.kind !== "const") {
1582
+ throw ErrorFactory.execution(
1583
+ "SYMBOLIC_TAYLOR_INEXACT",
1584
+ `The derivative of order ${order} does not reduce to an exact number at the expansion point, so this series cannot be computed exactly.`,
1585
+ { order }
1586
+ );
1587
+ }
1588
+ const coefficient = rationalDiv(atPoint.value, { n: factorial, d: 1n });
1589
+ if (isRationalZero(coefficient)) continue;
1590
+ const shifted = isRationalZero(point) ? varNode(variable) : { kind: "sub", left: varNode(variable), right: pointNode };
1591
+ const power2 = order === 0 ? constNode(1) : order === 1 ? shifted : powNode(shifted, constNode(order));
1592
+ result = { kind: "add", left: result, right: { kind: "mul", left: constNode(coefficient), right: power2 } };
1593
+ }
1594
+ return simplifySymbolic(result);
1595
+ }
1596
+ function jacobian(functions, variables) {
1597
+ return functions.map((fn) => variables.map((variable) => differentiate(fn, variable)));
1598
+ }
1599
+
1600
+ // src/engine/EngineContext.ts
1601
+ function createEngineContext() {
1602
+ return {
1603
+ pluginFunctions: {},
1604
+ opRegistry: new OpRegistry(),
1605
+ variableResolver: new VariableResolver(),
1606
+ pluginFunctionOwners: {}
1607
+ };
1608
+ }
1609
+ var defaultEngineContext = createEngineContext();
1610
+
1611
+ // src/packages/finance/data/CpiTable.ts
1612
+ var CPI_TABLE = {
1613
+ 1970: 38.8,
1614
+ 1971: 40.5,
1615
+ 1972: 41.8,
1616
+ 1973: 44.4,
1617
+ 1974: 49.3,
1618
+ 1975: 53.8,
1619
+ 1976: 56.9,
1620
+ 1977: 60.6,
1621
+ 1978: 65.2,
1622
+ 1979: 72.6,
1623
+ 1980: 82.4,
1624
+ 1981: 90.9,
1625
+ 1982: 96.5,
1626
+ 1983: 99.6,
1627
+ 1984: 103.9,
1628
+ 1985: 107.6,
1629
+ 1986: 109.6,
1630
+ 1987: 113.6,
1631
+ 1988: 118.3,
1632
+ 1989: 124,
1633
+ 1990: 130.7,
1634
+ 1991: 136.2,
1635
+ 1992: 140.3,
1636
+ 1993: 144.5,
1637
+ 1994: 148.2,
1638
+ 1995: 152.4,
1639
+ 1996: 156.9,
1640
+ 1997: 160.5,
1641
+ 1998: 163,
1642
+ 1999: 166.6,
1643
+ 2e3: 172.2,
1644
+ 2001: 177.1,
1645
+ 2002: 179.9,
1646
+ 2003: 184,
1647
+ 2004: 188.9,
1648
+ 2005: 195.3,
1649
+ 2006: 201.6,
1650
+ 2007: 207.3,
1651
+ 2008: 215.3,
1652
+ 2009: 214.5,
1653
+ 2010: 218.1,
1654
+ 2011: 224.9,
1655
+ 2012: 229.6,
1656
+ 2013: 233,
1657
+ 2014: 236.7,
1658
+ 2015: 237,
1659
+ 2016: 240,
1660
+ 2017: 245.1,
1661
+ 2018: 251.1,
1662
+ 2019: 255.7,
1663
+ 2020: 258.8,
1664
+ 2021: 271,
1665
+ 2022: 292.7,
1666
+ 2023: 304.7,
1667
+ 2024: 313.7,
1668
+ // 2025-2026: preliminary/projected estimates. See doc comment above.
1669
+ 2025: 320.6,
1670
+ 2026: 327.4
1671
+ };
1672
+ var CPI_MIN_YEAR = 1970;
1673
+ var CPI_MAX_YEAR = 2026;
1674
+ function getCpi(year) {
1675
+ return CPI_TABLE[Math.trunc(year)];
1676
+ }
1677
+ function inflationRatio(fromYear, toYear) {
1678
+ const fromCpi = getCpi(fromYear);
1679
+ const toCpi = getCpi(toYear);
1680
+ if (fromCpi === void 0 || toCpi === void 0 || fromCpi === 0) return void 0;
1681
+ return toCpi / fromCpi;
1682
+ }
1683
+ function adjustForInflation(amount, fromYear, toYear) {
1684
+ const ratio = inflationRatio(fromYear, toYear);
1685
+ if (ratio === void 0) return void 0;
1686
+ return amount * ratio;
1687
+ }
1688
+
1689
+ // src/vm/VMBuiltins.ts
1690
+ var builtinFunctions = {
1691
+ // ── Populated below ──
1692
+ // sqrt: a negative argument has a complex answer now that there is a complex
1693
+ // number to give, so this no longer quietly returns NaN. The exact path runs
1694
+ // first, so sqrt(-4) is 2i rather than an approximation.
1695
+ 0: (args) => {
1696
+ const value = args[0].toNumber();
1697
+ if (value >= 0) return numberValue(Math.sqrt(value));
1698
+ return symbolicToValue(callNode("sqrt", [constNode(value)]));
1699
+ },
1700
+ // abs(a): for a Matrix, "|a|" (Calca's determinant-pipe notation) is a
1701
+ // valid alias for det(a) (index 64), reusing the SAME implementation
1702
+ // not a separate one. Plain-number abs is unaffected.
1703
+ 1: (args) => args[0].type === 7 /* Matrix */ ? determinant(args[0].value) : numberValue(Math.abs(args[0].toNumber())),
1704
+ 2: (args) => numberValue(Math.sin(args[0].toNumber())),
1705
+ 3: (args) => numberValue(Math.cos(args[0].toNumber())),
1706
+ 4: (args) => numberValue(Math.tan(args[0].toNumber())),
1707
+ 5: (args) => numberValue(Math.log(args[0].toNumber())),
1708
+ 6: (args) => numberValue(Math.ceil(args[0].toNumber())),
1709
+ 7: (args) => numberValue(Math.floor(args[0].toNumber())),
1710
+ 8: (args) => numberValue(Math.round(args[0].toNumber())),
1711
+ // min/max: a plain loop replicating Math.min/Math.max's exact semantics
1712
+ // (NaN poisons the result regardless of position; empty args -> ±Infinity)
1713
+ // avoids the intermediate array .map()+spread allocates on every call.
1714
+ 9: (args) => {
1715
+ let result = Infinity;
1716
+ let hasNaN = false;
1717
+ for (const a of args) {
1718
+ const n = a.toNumber();
1719
+ if (Number.isNaN(n)) hasNaN = true;
1720
+ else if (n < result) result = n;
1721
+ }
1722
+ return numberValue(hasNaN ? NaN : result);
1723
+ },
1724
+ 10: (args) => {
1725
+ let result = -Infinity;
1726
+ let hasNaN = false;
1727
+ for (const a of args) {
1728
+ const n = a.toNumber();
1729
+ if (Number.isNaN(n)) hasNaN = true;
1730
+ else if (n > result) result = n;
1731
+ }
1732
+ return numberValue(hasNaN ? NaN : result);
1733
+ },
1734
+ 11: (args) => numberValue(Math.asin(args[0].toNumber())),
1735
+ 12: (args) => numberValue(Math.acos(args[0].toNumber())),
1736
+ 13: (args) => numberValue(Math.atan(args[0].toNumber())),
1737
+ 14: (args) => numberValue(Math.atan2(args[0].toNumber(), args[1].toNumber())),
1738
+ 15: (args) => numberValue(Math.sinh(args[0].toNumber())),
1739
+ 16: (args) => numberValue(Math.cosh(args[0].toNumber())),
1740
+ 17: (args) => numberValue(Math.tanh(args[0].toNumber())),
1741
+ 18: (args) => numberValue(Math.asinh(args[0].toNumber())),
1742
+ 19: (args) => numberValue(Math.acosh(args[0].toNumber())),
1743
+ 20: (args) => numberValue(Math.atanh(args[0].toNumber())),
1744
+ 21: (args) => numberValue(Math.cbrt(args[0].toNumber())),
1745
+ 22: (args) => numberValue(Math.clz32(args[0].toNumber())),
1746
+ 23: (args) => numberValue(Math.expm1(args[0].toNumber())),
1747
+ 24: (args) => numberValue(Math.exp(args[0].toNumber())),
1748
+ 25: (args) => numberValue(Math.fround(args[0].toNumber())),
1749
+ // hypot: left as .map()+spread (unlike min/max above), Math.hypot uses
1750
+ // a numerically-stable scaling algorithm internally to avoid overflow
1751
+ // for very large/small inputs; a naive manual reimplementation risks
1752
+ // silently changing results at the extremes, so the tiny array
1753
+ // allocation here is the safer trade.
1754
+ 26: (args) => numberValue(Math.hypot(...args.map((a) => a.toNumber()))),
1755
+ 27: (args) => numberValue(Math.imul(args[0].toNumber(), args[1].toNumber())),
1756
+ 28: (args) => numberValue(Math.log10(args[0].toNumber())),
1757
+ 29: (args) => numberValue(Math.log1p(args[0].toNumber())),
1758
+ 30: (args) => numberValue(Math.log2(args[0].toNumber())),
1759
+ 31: (args) => numberValue(Math.pow(args[0].toNumber(), args[1].toNumber())),
1760
+ 32: () => numberValue(Math.random()),
1761
+ // takes no arguments, unlike its neighbours
1762
+ 33: (args) => numberValue(Math.sign(args[0].toNumber())),
1763
+ 34: (args) => numberValue(Math.trunc(args[0].toNumber())),
1764
+ 35: (args) => numberValue(args[0].toNumber() * Math.PI / 180),
1765
+ 36: (args) => numberValue(args[0].toNumber() * 180 / Math.PI),
1766
+ // 37: diceRoll(from, to), random integer in range [from, to] inclusive.
1767
+ // A reversed range (from > to) used to silently produce values outside
1768
+ // [to, from] via a negative-length Math.random() spread (e.g.
1769
+ // "roll(6, 1)" returning values like 2-5, never 1 or 6) instead of
1770
+ // erroring on the invalid input.
1771
+ 37: (args) => {
1772
+ const from = args[0].toNumber();
1773
+ const to = args[1].toNumber();
1774
+ if (from > to) {
1775
+ return errorValue("INVALID_RANGE", `roll: invalid range, ${from} is greater than ${to}`);
1776
+ }
1777
+ return numberValue(Math.floor(Math.random() * (to - from + 1)) + from);
1778
+ },
1779
+ // gcd(a, b), Euclidean algorithm. Negative inputs are treated by
1780
+ // magnitude (gcd is conventionally defined over non-negative integers).
1781
+ 38: (args) => {
1782
+ let a = Math.trunc(Math.abs(args[0].toNumber()));
1783
+ let b = Math.trunc(Math.abs(args[1].toNumber()));
1784
+ while (b !== 0) {
1785
+ const t = b;
1786
+ b = a % b;
1787
+ a = t;
1788
+ }
1789
+ return numberValue(a);
1790
+ },
1791
+ // lcm(a, b) = |a*b| / gcd(a, b), via the same Euclidean gcd inline
1792
+ // (a standalone gcd() call site, no shared helper needed for two uses).
1793
+ 39: (args) => {
1794
+ const a = Math.trunc(Math.abs(args[0].toNumber()));
1795
+ const b = Math.trunc(Math.abs(args[1].toNumber()));
1796
+ if (a === 0 || b === 0) return numberValue(0);
1797
+ let x = a, y = b;
1798
+ while (y !== 0) {
1799
+ const t = y;
1800
+ y = x % y;
1801
+ x = t;
1802
+ }
1803
+ return numberValue(a / x * b);
1804
+ },
1805
+ // permutation(n, r) = n! / (n-r)!, computed as a running product
1806
+ // rather than two full factorials, so it stays exact for n well
1807
+ // beyond where n! itself would exceed Number.MAX_SAFE_INTEGER.
1808
+ 40: (args) => {
1809
+ const n = Math.trunc(args[0].toNumber());
1810
+ const r = Math.trunc(args[1].toNumber());
1811
+ if (n < 0 || r < 0 || r > n) {
1812
+ return errorValue("INVALID_RANGE", `permutation: invalid n=${n}, r=${r} (require 0 <= r <= n)`);
1813
+ }
1814
+ let result = 1;
1815
+ for (let i = 0; i < r; i++) result *= n - i;
1816
+ return numberValue(result);
1817
+ },
1818
+ // combination(n, r) = n! / (r! * (n-r)!), multiply-then-divide one
1819
+ // step at a time (standard technique) keeps every intermediate result
1820
+ // an integer, avoiding the overflow a naive factorial-ratio would hit.
1821
+ 41: (args) => {
1822
+ const n = Math.trunc(args[0].toNumber());
1823
+ const r = Math.trunc(args[1].toNumber());
1824
+ if (n < 0 || r < 0 || r > n) {
1825
+ return errorValue("INVALID_RANGE", `combination: invalid n=${n}, r=${r} (require 0 <= r <= n)`);
1826
+ }
1827
+ const k = Math.min(r, n - r);
1828
+ let result = 1;
1829
+ for (let i = 0; i < k; i++) result = result * (n - i) / (i + 1);
1830
+ return numberValue(Math.round(result));
1831
+ },
1832
+ // average(...), arithmetic mean of any number of arguments. Backs the
1833
+ // MathPhrases package's "average of X, Y, Z" (packages/mathphrases/).
1834
+ 42: (args) => {
1835
+ if (args.length === 0) return numberValue(0);
1836
+ const sum = args.reduce((acc, a) => acc + a.toNumber(), 0);
1837
+ return numberValue(sum / args.length);
1838
+ },
1839
+ // median(...), middle value; average of the two middle values for an
1840
+ // even argument count.
1841
+ 43: (args) => {
1842
+ if (args.length === 0) return numberValue(0);
1843
+ const sorted = args.map((a) => a.toNumber()).sort((a, b) => a - b);
1844
+ const mid = Math.floor(sorted.length / 2);
1845
+ return numberValue(
1846
+ sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid]
1847
+ );
1848
+ },
1849
+ // total(...), sum of any number of arguments.
1850
+ 44: (args) => numberValue(args.reduce((acc, a) => acc + a.toNumber(), 0)),
1851
+ // count(...), number of arguments passed.
1852
+ 45: (args) => numberValue(args.length),
1853
+ // proportion(a, b, c) -> d such that a:b = c:d, i.e. d = c * (b/a)
1854
+ // "A is to B as C is to what". Unit-aware via unifyUom: "5 km is to
1855
+ // 500m as 5 cm is to what" unifies 5km/500m to a 10:1 ratio (500m ==
1856
+ // 0.5km), so 5cm at the same ratio -> 0.5cm. Falls back to plain
1857
+ // toNumber() ratios when the units aren't the same measure (unifyUom's
1858
+ // own fallback) rather than guessing at an unsupported conversion.
1859
+ 46: (args) => {
1860
+ const [a, b, c] = args;
1861
+ const { lv: aNum, rv: bNum } = unifyUom(a, b);
1862
+ if (aNum === 0) {
1863
+ return errorValue("PROPORTION_DIVIDE_BY_ZERO", `Cannot compute proportion: "${a.value}" is zero`);
1864
+ }
1865
+ const result = c.toNumber() * (bNum / aNum);
1866
+ return c.type === 6 /* Uom */ ? uomValue(result, c.unit) : numberValue(result);
1867
+ },
1868
+ // clamp(value, lo, hi), restrict value to [lo, hi]. Backs
1869
+ // "clamp X between Y and Z" / "clamp X from Y to Z".
1870
+ 47: (args) => {
1871
+ const value = args[0].toNumber();
1872
+ const lo = args[1].toNumber();
1873
+ const hi = args[2].toNumber();
1874
+ if (lo > hi) {
1875
+ return errorValue("INVALID_RANGE", `clamp: invalid range, ${lo} is greater than ${hi}`);
1876
+ }
1877
+ return numberValue(Math.min(Math.max(value, lo), hi));
1878
+ },
1879
+ // hex(n), Python/JS-style call-syntax hex formatting, e.g. hex(255) ->
1880
+ // "0xFF". Distinct from the Converters package's `255 as hex` (see
1881
+ // packages/converters/parselets/AsConverterParselet.ts): "as hex"
1882
+ // produces a ValueType.Hex (a typed NUMBER that still participates in
1883
+ // arithmetic, formatted specially on display), while hex() is a plain
1884
+ // function call that returns an ordinary String value, matching
1885
+ // Python's hex()/JS convention of a function returning display text,
1886
+ // not a numeric type.
1887
+ 48: (args) => hexValue(args[0].toNumber()),
1888
+ // bin(n). Same call-syntax shape as hex() above, e.g. bin(10) -> "0b1010".
1889
+ 49: (args) => hexValue(args[0].toNumber(), "bin"),
1890
+ // int(x), coerce ANY value (Number, Percentage, Uom, String, Hex, ...)
1891
+ // to a plain integer Number, truncating any fractional part toward
1892
+ // zero (Math.trunc semantics: int(5.7) -> 5, int(-5.7) -> -5). Distinct
1893
+ // from the Converters package's `x as number` (TO_NUMBER opcode),
1894
+ // which only strips a unit/percentage wrapper and keeps any decimal
1895
+ // part (e.g. "5.7 as number" -> 5.7), int() additionally truncates.
1896
+ 50: (args) => numberValue(Math.trunc(args[0].toNumber())),
1897
+ // ── Finance (packages/finance/) ──────────────────────────────────────
1898
+ // All finance builtins preserve the principal/amount argument's Uom
1899
+ // unit (e.g. a currency like "$") onto the result, matching
1900
+ // ProportionParselet's convention (index 46, above), a plain-number
1901
+ // input produces a plain-number result.
1902
+ //
1903
+ // `rate` arguments are always a decimal fraction (e.g. 0.07 for 7%)
1904
+ // this is how "%" already normalizes everywhere else in this codebase
1905
+ // (see packages/percentage/parselets/PercentParselet.ts: "7%" divides
1906
+ // by 100 at parse time, producing a plain Number 0.07, not a distinct
1907
+ // percentage type). Writing "at 7" instead of "at 7%" in a phrase form
1908
+ // passes 7 as-is (not 0.07), the "%" is not implicit.
1909
+ // compoundFutureValue(principal, rate, years) -> FV = P*(1+r)^years.
1910
+ // Backs "compound interest on $P over Y years at R%" and the
1911
+ // compoundInterest(principal, rate, years) function-call form.
1912
+ 51: (args) => {
1913
+ const principal = args[0].toNumber();
1914
+ const rate = args[1].toNumber();
1915
+ const years = args[2].toNumber();
1916
+ if (1 + rate <= 0) {
1917
+ return errorValue("INVALID_RATE", `compoundInterest: rate ${rate} makes (1 + rate) non-positive`);
1918
+ }
1919
+ const fv = principal * Math.pow(1 + rate, years);
1920
+ return args[0].type === 6 /* Uom */ ? uomValue(fv, args[0].unit) : numberValue(fv);
1921
+ },
1922
+ // compoundInterestEarned(principal, rate, years) -> FV - principal, the
1923
+ // interest-only portion. Backs "interest on $P over Y years at R%" and
1924
+ // the interestEarned(principal, rate, years) function-call form.
1925
+ 52: (args) => {
1926
+ const principal = args[0].toNumber();
1927
+ const rate = args[1].toNumber();
1928
+ const years = args[2].toNumber();
1929
+ if (1 + rate <= 0) {
1930
+ return errorValue("INVALID_RATE", `interestEarned: rate ${rate} makes (1 + rate) non-positive`);
1931
+ }
1932
+ const interest = principal * (Math.pow(1 + rate, years) - 1);
1933
+ return args[0].type === 6 /* Uom */ ? uomValue(interest, args[0].unit) : numberValue(interest);
1934
+ },
1935
+ // compoundInterestRate(principal, futureValue, years) -> the rate (as a
1936
+ // decimal fraction) needed to grow principal to futureValue over years.
1937
+ // Function-call only, no clean phrase form for a reverse calculation
1938
+ // like this without inventing awkward new keywords, so it's scoped to
1939
+ // compoundInterestRate(...) rather than a natural-language phrase.
1940
+ 53: (args) => {
1941
+ const principal = args[0].toNumber();
1942
+ const futureValue = args[1].toNumber();
1943
+ const years = args[2].toNumber();
1944
+ if (principal <= 0 || futureValue <= 0) {
1945
+ return errorValue("INVALID_RANGE", `compoundInterestRate: principal and futureValue must both be positive`);
1946
+ }
1947
+ if (years <= 0) {
1948
+ return errorValue("INVALID_RANGE", `compoundInterestRate: years must be greater than 0`);
1949
+ }
1950
+ return numberValue(Math.pow(futureValue / principal, 1 / years) - 1);
1951
+ },
1952
+ // compoundInterestYears(principal, futureValue, rate) -> the number of
1953
+ // years needed to grow principal to futureValue at a fixed rate.
1954
+ // Function-call only, same reasoning as index 53 above.
1955
+ 54: (args) => {
1956
+ const principal = args[0].toNumber();
1957
+ const futureValue = args[1].toNumber();
1958
+ const rate = args[2].toNumber();
1959
+ if (principal <= 0 || futureValue <= 0) {
1960
+ return errorValue("INVALID_RANGE", `compoundInterestYears: principal and futureValue must both be positive`);
1961
+ }
1962
+ if (1 + rate <= 0 || rate === 0) {
1963
+ return errorValue("INVALID_RATE", `compoundInterestYears: rate ${rate} is not usable (must be > -1 and not 0)`);
1964
+ }
1965
+ return numberValue(Math.log(futureValue / principal) / Math.log(1 + rate));
1966
+ },
1967
+ // loanRepayment(principal, rate, years, periodsPerYear), standard
1968
+ // amortizing-loan repayment (mortgage formula), redistributed evenly
1969
+ // across `periodsPerYear` periods/year: 365=daily, 12=monthly, 1=annual,
1970
+ // 0=total over the life of the loan. The loan is ALWAYS amortized
1971
+ // monthly internally (the standard mortgage convention) regardless of
1972
+ // periodsPerYear, "daily"/"annual"/"total" are the same total
1973
+ // repayment redistributed, not separately-amortized loans. Verified
1974
+ // against real worked numbers (principal=$10,000, rate=6%, years=6):
1975
+ // monthly $165.73, annual $1,988.75 (== total/years exactly), daily
1976
+ // $5.45 (== total/(years*365)), total $11,932.48.
1977
+ // Backs "daily/monthly/annual/total repayment on $P over Y years at R%".
1978
+ 55: (args) => {
1979
+ const principal = args[0].toNumber();
1980
+ const rate = args[1].toNumber();
1981
+ const years = args[2].toNumber();
1982
+ const periodsPerYear = args[3].toNumber();
1983
+ if (principal <= 0) return errorValue("INVALID_RANGE", `loanRepayment: principal must be positive`);
1984
+ if (years <= 0) return errorValue("INVALID_RANGE", `loanRepayment: years must be positive`);
1985
+ if (rate < 0) return errorValue("INVALID_RATE", `loanRepayment: rate must not be negative`);
1986
+ if (periodsPerYear < 0) return errorValue("INVALID_RANGE", `loanRepayment: periodsPerYear must not be negative`);
1987
+ const { totalRepayment } = amortizeLoan(principal, rate, years);
1988
+ const result = periodsPerYear === 0 ? totalRepayment : totalRepayment / (years * periodsPerYear);
1989
+ return args[0].type === 6 /* Uom */ ? uomValue(result, args[0].unit) : numberValue(result);
1990
+ },
1991
+ // loanInterest(principal, rate, years, periodsPerYear), the interest
1992
+ // portion of index 55's repayment, same periodsPerYear convention.
1993
+ // Backs "daily/monthly/annual/total interest on $P over Y years at R%".
1994
+ 56: (args) => {
1995
+ const principal = args[0].toNumber();
1996
+ const rate = args[1].toNumber();
1997
+ const years = args[2].toNumber();
1998
+ const periodsPerYear = args[3].toNumber();
1999
+ if (principal <= 0) return errorValue("INVALID_RANGE", `loanInterest: principal must be positive`);
2000
+ if (years <= 0) return errorValue("INVALID_RANGE", `loanInterest: years must be positive`);
2001
+ if (rate < 0) return errorValue("INVALID_RATE", `loanInterest: rate must not be negative`);
2002
+ if (periodsPerYear < 0) return errorValue("INVALID_RANGE", `loanInterest: periodsPerYear must not be negative`);
2003
+ const { totalInterest } = amortizeLoan(principal, rate, years);
2004
+ const result = periodsPerYear === 0 ? totalInterest : totalInterest / (years * periodsPerYear);
2005
+ return args[0].type === 6 /* Uom */ ? uomValue(result, args[0].unit) : numberValue(result);
2006
+ },
2007
+ // monthlyPayment(principal, rate, years), convenience 3-arg wrapper
2008
+ // around index 55's monthly case, for direct function-call use without
2009
+ // the periodsPerYear parameter (the task's minimum-ask function form).
2010
+ 57: (args) => {
2011
+ const principal = args[0].toNumber();
2012
+ const rate = args[1].toNumber();
2013
+ const years = args[2].toNumber();
2014
+ if (principal <= 0) return errorValue("INVALID_RANGE", `monthlyPayment: principal must be positive`);
2015
+ if (years <= 0) return errorValue("INVALID_RANGE", `monthlyPayment: years must be positive`);
2016
+ if (rate < 0) return errorValue("INVALID_RATE", `monthlyPayment: rate must not be negative`);
2017
+ const { monthlyPayment } = amortizeLoan(principal, rate, years);
2018
+ return args[0].type === 6 /* Uom */ ? uomValue(monthlyPayment, args[0].unit) : numberValue(monthlyPayment);
2019
+ },
2020
+ // taxAdd(amount, rate) -> amount * (1 + rate). Backs "tax on $X at R%" /
2021
+ // "VAT on $X at R%". No default rate is baked in anywhere, the caller
2022
+ // always supplies one explicitly, since tax rates vary by region and
2023
+ // change over time; this package makes no assumption about which rate
2024
+ // applies.
2025
+ 58: (args) => {
2026
+ const amount = args[0].toNumber();
2027
+ const rate = args[1].toNumber();
2028
+ const result = amount * (1 + rate);
2029
+ return args[0].type === 6 /* Uom */ ? uomValue(result, args[0].unit) : numberValue(result);
2030
+ },
2031
+ // taxRemove(amount, rate) -> amount / (1 + rate), extracts the
2032
+ // pre-tax amount from a tax-INCLUSIVE total. Backs "tax off $X at R%" /
2033
+ // "VAT off $X at R%".
2034
+ 59: (args) => {
2035
+ const amount = args[0].toNumber();
2036
+ const rate = args[1].toNumber();
2037
+ if (1 + rate <= 0) {
2038
+ return errorValue("INVALID_RATE", `taxRemove: rate ${rate} makes (1 + rate) non-positive`);
2039
+ }
2040
+ return args[0].type === 6 /* Uom */ ? uomValue(amount / (1 + rate), args[0].unit) : numberValue(amount / (1 + rate));
2041
+ },
2042
+ // inflationAdjust(amount, fromYear, toYear) -- CPI-based inflation
2043
+ // adjustment between two arbitrary years, using the bundled CPI-U
2044
+ // table (packages/finance/data/CpiTable.ts -- see its doc comment for
2045
+ // vintage/accuracy notes). Backs the function-call form
2046
+ // inflationAdjust(...) (FunctionCallParselet's builtinNameToIndex map)
2047
+ // and the "what is $X in fromYear worth in toYear" phrase form
2048
+ // (InflationQueryParselet.ts). The two present-year-relative phrase
2049
+ // forms ("what is $X from year" / "what was $X worth in year" / "$X
2050
+ // in year dollars") and the flat-rate future-value projection ("value
2051
+ // of $X in year assuming N% inflation") are collision-safe
2052
+ // pluginFunctions instead, not indices here -- see
2053
+ // packages/finance/parselets/InflationPluginFunctions.ts.
2054
+ 60: (args) => {
2055
+ const amount = args[0].toNumber();
2056
+ const fromYear = args[1].toNumber();
2057
+ const toYear = args[2].toNumber();
2058
+ const ratio = inflationRatio(fromYear, toYear);
2059
+ if (ratio === void 0) {
2060
+ return errorValue(
2061
+ "INFLATION_YEAR_OUT_OF_RANGE",
2062
+ `inflationAdjust: fromYear ${fromYear} or toYear ${toYear} is outside the bundled CPI table's range (${CPI_MIN_YEAR}-${CPI_MAX_YEAR})`
2063
+ );
2064
+ }
2065
+ const result = amount * ratio;
2066
+ return args[0].type === 6 /* Uom */ ? uomValue(result, args[0].unit) : numberValue(result);
2067
+ },
2068
+ // root(n, x) -- the n-th root of x (Numi's `root n (x)` phrasing maps
2069
+ // to this same call-style form; see FunctionCallParselet's name map).
2070
+ // No native Math.root exists (unlike Math.cbrt for n=3 specifically),
2071
+ // so this is Math.pow(x, 1/n) directly -- exact for n=2/n=3 modulo the
2072
+ // usual floating-point pow() rounding, same precision class as every
2073
+ // other builtin here.
2074
+ 61: (args) => {
2075
+ const n = args[0].toNumber();
2076
+ const x = args[1].toNumber();
2077
+ return numberValue(Math.pow(x, 1 / n));
2078
+ },
2079
+ // fact(n) / factorial(n) -- integer factorial. Deliberately rejects
2080
+ // negative or non-integer input (factorial isn't defined for either
2081
+ // without a gamma-function generalization this engine doesn't need) and
2082
+ // caps at 170 -- Number.MAX_VALUE overflows to Infinity at 171!, so
2083
+ // returning a silently-wrong (or silently-infinite) result past that
2084
+ // point would be worse than a clear error.
2085
+ 62: (args) => {
2086
+ const n = args[0].toNumber();
2087
+ if (!Number.isInteger(n) || n < 0) {
2088
+ return errorValue("INVALID_FACTORIAL_INPUT", `fact: ${n} is not a non-negative integer`);
2089
+ }
2090
+ if (n > 170) {
2091
+ return errorValue("FACTORIAL_OVERFLOW", `fact: ${n}! exceeds the maximum representable double (170! is the largest finite factorial)`);
2092
+ }
2093
+ let result = 1;
2094
+ for (let i = 2; i <= n; i++) result *= i;
2095
+ return numberValue(result);
2096
+ },
2097
+ // ── Matrix (packages/matrix/) ────────────────────────────────────────
2098
+ // transpose(a)/det(a)/inv(a)/dot(a,b), reachable both via ordinary
2099
+ // function-call syntax (this map) and via operator syntax (`^T`, `^-1`
2100
+ //. See PrecedenceParser.ts's CARET special-casing, which emits these
2101
+ // SAME indices) and `|a|` (abs()'s Matrix branch, index 1 above).
2102
+ // Real linear-algebra work lives in vm/MatrixOps.ts, shared by both
2103
+ // entry points rather than duplicated.
2104
+ // transpose(a), for a Matrix, swaps rows/cols. A plain Number is its
2105
+ // own transpose (a 1x1 "matrix" transposed is itself), matches this
2106
+ // engine's existing convention of treating a scalar as a trivial 1x1
2107
+ // matrix (see Value.ts's toNumber()/isNaN() 1x1 special case).
2108
+ 63: (args) => args[0].type === 7 /* Matrix */ ? transpose(args[0].value) : args[0],
2109
+ // det(a), determinant. A plain Number's "determinant" is itself (the
2110
+ // determinant of a 1x1 matrix [x] is x).
2111
+ 64: (args) => args[0].type === 7 /* Matrix */ ? determinant(args[0].value) : numberValue(args[0].toNumber()),
2112
+ // inv(a), matrix inverse for a Matrix; for a plain Number, `1/x`
2113
+ // (byte-identical to `Math.pow(x, -1)`, which is what `x^-1` computed
2114
+ // before this feature existed. See PrecedenceParser.ts's `^-1`
2115
+ // special-case doc comment for why this must stay exact).
2116
+ 65: (args) => {
2117
+ if (args[0].type === 7 /* Matrix */) return inverse(args[0].value);
2118
+ return numberValue(1 / args[0].toNumber());
2119
+ },
2120
+ // dot(a, b), matrix product / scalar-broadcast, the SAME dispatch as
2121
+ // the `*` operator between two matrices (vm/VM.ts's MUL case). Plain
2122
+ // Number operands multiply directly; a Number mixed with a Matrix
2123
+ // promotes the Number to a 1x1 Matrix first, so it broadcasts exactly
2124
+ // like matrixMultiply()'s own 1x1-scalar case.
2125
+ 66: (args) => {
2126
+ const [a, b] = args;
2127
+ if (a.type === 0 /* Number */ && b.type === 0 /* Number */) {
2128
+ return numberValue(a.toNumber() * b.toNumber());
2129
+ }
2130
+ const toMatrix = (v) => v.type === 7 /* Matrix */ ? v.value : { rows: 1, cols: 1, data: [v.toNumber()], hasSymbolic: false };
2131
+ return matrixMultiply(toMatrix(a), toMatrix(b));
2132
+ },
2133
+ // ── Symbolic algebra (packages/symbolic/) ──
2134
+ // expand(expr), multiplying out every product and power. Reached only
2135
+ // through its own parselet, never the builtinNameToIndex name map, so that
2136
+ // `expand` keeps working as an ordinary variable name; see
2137
+ // packages/symbolic/normalizer/SymbolicCallNormalizerRule.ts.
2138
+ //
2139
+ // A non-symbolic argument has nothing to expand and is returned unchanged,
2140
+ // which is why this does not go through the CALL_BUILTIN symbolic dispatch:
2141
+ // `expand(2+3)` is simply 5.
2142
+ 67: (args) => {
2143
+ const [value] = args;
2144
+ if (value.type !== 9 /* Symbolic */) return value;
2145
+ return symbolicToValue(expandSymbolic(value.value));
2146
+ },
2147
+ // factor(expr), writing a polynomial as a product of irreducible factors
2148
+ // over the RATIONALS. x^2-2 and x^2+1 come back unchanged, which is the
2149
+ // correct answer over that field rather than a failure; see symbolic/Factor.ts.
2150
+ 68: (args) => {
2151
+ const [value] = args;
2152
+ if (value.type !== 9 /* Symbolic */) return value;
2153
+ return symbolicToValue(factorSymbolic(value.value));
2154
+ },
2155
+ // solve(equation, variable), emitted by its own parselet as three stack
2156
+ // values: the two sides of the equation, then the variable NAME as a
2157
+ // String. Reading the name as a string rather than compiling it as a
2158
+ // variable read is what lets `solve(x^2-4=0, x)` work without `x` existing.
2159
+ 69: (args) => {
2160
+ const [lhsValue, rhsValue, variableValue] = args;
2161
+ if (variableValue?.type !== 3 /* String */) {
2162
+ return errorValue("SOLVE_REQUIRES_VARIABLE_NAME", "solve's second argument must be the name of the unknown.");
2163
+ }
2164
+ return solveEquationValues(lhsValue, rhsValue, variableValue.value);
2165
+ },
2166
+ // der(expr, variable, order), the symbolic derivative. Genuinely symbolic
2167
+ // rather than a finite difference, so it is exact.
2168
+ 70: (args) => {
2169
+ const [target, variableValue, orderValue] = args;
2170
+ const variable = symbolicVariableName(variableValue, "der");
2171
+ if (typeof variable !== "string") return variable;
2172
+ const expression = valueToSymbolic(target);
2173
+ if (expression === null) return errorValue("SYMBOLIC_NONFINITE_OPERAND", "der needs an expression with an exact value.");
2174
+ return symbolicToValue(differentiate(expression, variable, orderValue?.toNumber() ?? 1));
2175
+ },
2176
+ // integral(expr, variable), the indefinite integral without a constant of
2177
+ // integration. Reports what it cannot do rather than approximating; see
2178
+ // symbolic/Integral.ts.
2179
+ 71: (args) => {
2180
+ const [target, variableValue] = args;
2181
+ const variable = symbolicVariableName(variableValue, "integral");
2182
+ if (typeof variable !== "string") return variable;
2183
+ const expression = valueToSymbolic(target);
2184
+ if (expression === null) return errorValue("SYMBOLIC_NONFINITE_OPERAND", "integral needs an expression with an exact value.");
2185
+ const result = integrate(expression, variable);
2186
+ if (!result.ok) return errorValue("SYMBOLIC_INTEGRAL_UNSUPPORTED", `Cannot integrate this: ${result.reason}.`);
2187
+ return symbolicToValue(result.value);
2188
+ },
2189
+ // taylor(expr, variable = point, degree).
2190
+ 72: (args) => {
2191
+ const [target, variableValue, pointValue, degreeValue] = args;
2192
+ const variable = symbolicVariableName(variableValue, "taylor");
2193
+ if (typeof variable !== "string") return variable;
2194
+ const expression = valueToSymbolic(target);
2195
+ const point = valueToSymbolic(pointValue);
2196
+ if (expression === null || point === null || point.kind !== "const") {
2197
+ return errorValue("SYMBOLIC_NONFINITE_OPERAND", "taylor needs an expression and an exact expansion point.");
2198
+ }
2199
+ return symbolicToValue(taylorSeries(expression, variable, point.value, degreeValue.toNumber()));
2200
+ },
2201
+ // jacobian(f1, f2, ...), variadic. The variables are not named: they come
2202
+ // from the union of the functions' own unknowns, sorted, matching Calca.
2203
+ 73: (args) => {
2204
+ const functions = [];
2205
+ for (const arg of args) {
2206
+ const node = valueToSymbolic(arg);
2207
+ if (node === null) return errorValue("SYMBOLIC_NONFINITE_OPERAND", "jacobian needs expressions with exact values.");
2208
+ functions.push(node);
2209
+ }
2210
+ const variables = /* @__PURE__ */ new Set();
2211
+ for (const fn of functions) for (const name of freeVariables(fn)) variables.add(name);
2212
+ const sorted = [...variables].sort();
2213
+ if (sorted.length === 0) return errorValue("SYMBOLIC_JACOBIAN_NO_VARIABLES", "jacobian needs at least one unknown to differentiate against.");
2214
+ const rows = jacobian(functions, sorted);
2215
+ const rowMajor = [];
2216
+ for (const row of rows) {
2217
+ for (const cell of row) rowMajor.push(symbolicToEntry(cell));
2218
+ }
2219
+ return matrixValue(rows.length, sorted.length, rowMajorToColumnMajor(rows.length, sorted.length, rowMajor));
2220
+ },
2221
+ // An imaginary literal, 3i. The parselet pushes the numeric part and this
2222
+ // turns it into an exact imaginary value.
2223
+ 74: (args) => symbolicToValue(complexNode(complex(RATIONAL_ZERO, rationalFromNumber(args[0].toNumber())))),
2224
+ // conj(z), re(z) and im(z). Each folds immediately for a literal and stays
2225
+ // symbolic for anything still carrying an unknown.
2226
+ 75: (args) => applyComplexAccessor("conj", args[0]),
2227
+ 76: (args) => applyComplexAccessor("re", args[0]),
2228
+ 77: (args) => applyComplexAccessor("im", args[0]),
2229
+ // cancel(expr), reducing a quotient of polynomials to lowest terms.
2230
+ 78: (args) => {
2231
+ const value = args[0];
2232
+ if (value.type !== 9 /* Symbolic */) return value;
2233
+ return symbolicToValue(cancelSymbolic(value.value));
2234
+ },
2235
+ // apart(expr), the partial-fraction decomposition of a rational function.
2236
+ 79: (args) => {
2237
+ const value = args[0];
2238
+ if (value.type !== 9 /* Symbolic */) return value;
2239
+ return symbolicToValue(apartSymbolic(value.value));
2240
+ }
2241
+ };
2242
+ function applyComplexAccessor(name, value) {
2243
+ const node = valueToSymbolic(value);
2244
+ if (node === null) return errorValue("SYMBOLIC_NONFINITE_OPERAND", name + " needs a value with an exact number.");
2245
+ return symbolicToValue(callNode(name, [node]));
2246
+ }
2247
+ function symbolicVariableName(value, verb) {
2248
+ if (value?.type !== 3 /* String */) {
2249
+ return errorValue("SYMBOLIC_REQUIRES_VARIABLE_NAME", `${verb} needs the name of an unknown.`);
2250
+ }
2251
+ return value.value;
2252
+ }
2253
+ function amortizeLoan(principal, annualRate, years) {
2254
+ const n = years * 12;
2255
+ const rMonthly = annualRate / 12;
2256
+ const monthlyPayment = rMonthly === 0 ? principal / n : principal * rMonthly / (1 - Math.pow(1 + rMonthly, -n));
2257
+ const totalRepayment = monthlyPayment * n;
2258
+ const totalInterest = totalRepayment - principal;
2259
+ return { monthlyPayment, totalRepayment, totalInterest };
2260
+ }
2261
+ var pluginFunctionRegistry = defaultEngineContext.pluginFunctions;
2262
+ var MAX_PLUGIN_FUNCTION_INDEX = 255;
2263
+ var nextPluginFunctionIndex = 0;
2264
+ function allocatePluginFunctionIndex() {
2265
+ if (nextPluginFunctionIndex > MAX_PLUGIN_FUNCTION_INDEX) {
2266
+ throw ErrorFactory.config(
2267
+ "PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED",
2268
+ `allocatePluginFunctionIndex: pool exhausted (max ${MAX_PLUGIN_FUNCTION_INDEX + 1} allocations).`
2269
+ );
2270
+ }
2271
+ return nextPluginFunctionIndex++;
2272
+ }
2273
+ var asConverterRegistry = /* @__PURE__ */ new Map();
2274
+ function registerAsConverter(name, handler) {
2275
+ const key = name.toLowerCase();
2276
+ const existing = asConverterRegistry.get(key);
2277
+ if (existing && existing !== handler) {
2278
+ console.warn(`[asConverterRegistry] Converter name "${key}" is already registered \u2014 overwriting.`);
2279
+ }
2280
+ asConverterRegistry.set(key, handler);
2281
+ }
2282
+ function unregisterAsConverter(name) {
2283
+ asConverterRegistry.delete(name.toLowerCase());
2284
+ }
2285
+
2286
+ // src/vm/GlobalVariableStore.ts
2287
+ var _GlobalVariableStore = class _GlobalVariableStore {
2288
+ constructor() {
2289
+ this.values = /* @__PURE__ */ new Map();
2290
+ this.listeners = /* @__PURE__ */ new Set();
2291
+ this.notifyDepth = 0;
2292
+ }
2293
+ get(name) {
2294
+ return this.values.get(name);
2295
+ }
2296
+ has(name) {
2297
+ return this.values.has(name);
2298
+ }
2299
+ /**
2300
+ * Last-write-wins: any document may call this for any name at any time.
2301
+ * Notifies listeners synchronously, within the same call, before
2302
+ * returning, so that ThreeTierEvaluator's dirty-marking (a listener)
2303
+ * and GlobalVariableAsyncResolver's first-write promise (also a
2304
+ * listener) both observe the new value immediately, no microtask delay.
2305
+ *
2306
+ * A write that does not CHANGE the stored value notifies nobody. This
2307
+ * is not just an optimisation, it is what stops a re-evaluation cycle
2308
+ * from sustaining itself. Every listener re-runs work in response to a
2309
+ * write (ThreeTierEvaluator marks dependent lines dirty; the playground
2310
+ * worker refreshes other documents), and those re-runs re-execute the
2311
+ * very STORE_GLOBAL_VAR opcode that produced this write. Re-evaluating
2312
+ * an unchanged `global :x = 5` line therefore used to re-notify, which
2313
+ * re-triggered the listeners, which re-evaluated... bounded only by
2314
+ * MAX_NOTIFY_DEPTH below, and only in DEPTH, so with more than one
2315
+ * writer the work per keystroke grew exponentially. Nothing observable
2316
+ * changed, so there is nothing for a listener to react to.
2317
+ */
2318
+ set(name, value) {
2319
+ const previous = this.values.get(name);
2320
+ this.values.set(name, value);
2321
+ if (previous !== void 0 && sameValue(previous, value)) return;
2322
+ this.notify(name, value);
2323
+ }
2324
+ notify(name, value) {
2325
+ if (this.notifyDepth >= _GlobalVariableStore.MAX_NOTIFY_DEPTH) return;
2326
+ this.notifyDepth++;
2327
+ try {
2328
+ for (const listener of this.listeners) listener(name, value);
2329
+ } finally {
2330
+ this.notifyDepth--;
2331
+ }
2332
+ }
2333
+ /**
2334
+ * Subscribe to every global-variable write (all names, callers filter
2335
+ * for the name(s) they care about). Returns an unsubscribe function;
2336
+ * callers MUST invoke it when disposing (e.g. ThreeTierEvaluator's
2337
+ * terminateWorker()) to avoid leaking listeners for closed documents.
2338
+ */
2339
+ subscribe(listener) {
2340
+ this.listeners.add(listener);
2341
+ return () => {
2342
+ this.listeners.delete(listener);
2343
+ };
2344
+ }
2345
+ /**
2346
+ * Full reset, test-only. Never called from production code paths;
2347
+ * globals must outlive any single engine's own clear()/dispose cycle.
2348
+ * Tests MUST call this in beforeEach/afterEach since this is a
2349
+ * module-level singleton whose state and listeners otherwise leak
2350
+ * across test cases and files.
2351
+ */
2352
+ clear() {
2353
+ this.values.clear();
2354
+ this.listeners.clear();
2355
+ this.notifyDepth = 0;
2356
+ }
2357
+ };
2358
+ /**
2359
+ * Guards against runaway cross-document write cycles: doc A's write
2360
+ * notifies doc B, whose dirty line, once evaluated, writes a global
2361
+ * that notifies doc C, ... eventually back to A. Same philosophy as the
2362
+ * VM's own instruction-limit safety net: stop propagating past the
2363
+ * limit rather than let a genuine cycle recurse unboundedly. The store
2364
+ * itself is left in a well-defined state either way. This only bounds
2365
+ * *notification* depth, never the value actually stored.
2366
+ */
2367
+ _GlobalVariableStore.MAX_NOTIFY_DEPTH = 64;
2368
+ var GlobalVariableStore = _GlobalVariableStore;
2369
+ function sameValue(a, b) {
2370
+ if (a.type !== b.type) return false;
2371
+ if (a.unit !== b.unit) return false;
2372
+ if ((a.timedOut ?? false) !== (b.timedOut ?? false)) return false;
2373
+ const av = a.value;
2374
+ const bv = b.value;
2375
+ if (Array.isArray(av) || Array.isArray(bv)) {
2376
+ if (!Array.isArray(av) || !Array.isArray(bv)) return false;
2377
+ if (av.length !== bv.length) return false;
2378
+ for (let i = 0; i < av.length; i++) {
2379
+ if (!Object.is(av[i], bv[i])) return false;
2380
+ }
2381
+ return true;
2382
+ }
2383
+ return Object.is(av, bv);
2384
+ }
2385
+ var sharedGlobalVariableStore = new GlobalVariableStore();
2386
+ function globalDagKey(name) {
2387
+ return `global:${name}`;
2388
+ }
2389
+
2390
+ export { CPI_MAX_YEAR, CPI_MIN_YEAR, OpRegistry, SYMBOLIC_NATIVE_BUILTINS, adjustForInflation, allocatePluginFunctionIndex, asConverterRegistry, binaryOp, builtinFunctions, createEngineContext, defaultEngineContext, globalDagKey, pluginFunctionRegistry, registerAsConverter, sharedGlobalVariableStore, sharedOpRegistry, solveEquationValues, symbolicBuiltin, symbolicNeg, symbolicPow, unifyUom, unregisterAsConverter };
2391
+ //# sourceMappingURL=chunk-4QADQTWS.js.map
2392
+ //# sourceMappingURL=chunk-4QADQTWS.js.map