solve-engine 2.32.0 → 2.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/dist/{EngineError-CqGtaT_v.d.cts → EngineError-Bm4OYmw8.d.cts} +6 -0
  2. package/dist/{EngineError-CqGtaT_v.d.ts → EngineError-Bm4OYmw8.d.ts} +6 -0
  3. package/dist/{Lexer-CqFjYoRA.d.ts → Lexer-DPn5dfCH.d.ts} +1 -13
  4. package/dist/{Lexer-sCI05tqO.d.cts → Lexer-DaWkCu84.d.cts} +1 -13
  5. package/dist/{PackageCompatibility-phvSFP4f.d.ts → PackageCompatibility-CkzZfoJ3.d.ts} +1 -1
  6. package/dist/{PackageCompatibility-Bn-T_xKW.d.cts → PackageCompatibility-E_5GtcQW.d.cts} +1 -1
  7. package/dist/{PackageRegistry-C78jVkI9.d.ts → PackageRegistry-DSqic8kz.d.ts} +132 -23
  8. package/dist/{PackageRegistry-B-C1duZw.d.cts → PackageRegistry-js47hr28.d.cts} +132 -23
  9. package/dist/{Parselet-Dgymjxzd.d.ts → Parselet-CQjcHOKw.d.ts} +13 -6
  10. package/dist/{Parselet-DF3864la.d.cts → Parselet-s1sRRn8H.d.cts} +13 -6
  11. package/dist/{TokenNormalizer-Pe3_390t.d.cts → TokenNormalizer-D382VSYh.d.cts} +4 -1
  12. package/dist/{TokenNormalizer-IF7nPRMp.d.ts → TokenNormalizer-DAzPp-j1.d.ts} +4 -1
  13. package/dist/{VMBuiltins-BkKzhj6C.d.cts → VMBuiltins-JCavlQUj.d.cts} +53 -18
  14. package/dist/{VMBuiltins-Du9y8sEo.d.ts → VMBuiltins-qgzA6qGi.d.ts} +53 -18
  15. package/dist/{VMCheckpoints-WdUQrdc9.d.cts → VMCheckpoints-BxPzmdu0.d.cts} +2 -2
  16. package/dist/{VMCheckpoints-gvy_yxYh.d.ts → VMCheckpoints-DjjE92mf.d.ts} +2 -2
  17. package/dist/{Value-BYHw-x7q.d.cts → Value-2TIKi-YL.d.cts} +19 -0
  18. package/dist/{Value-BYHw-x7q.d.ts → Value-2TIKi-YL.d.ts} +19 -0
  19. package/dist/{WorkerError-DTrl3Jag.d.ts → WorkerError-BaN8_eok.d.ts} +1 -1
  20. package/dist/{WorkerError-CRoM8Ju1.d.cts → WorkerError-CexHHmbb.d.cts} +1 -1
  21. package/dist/{chunk-IJE4AEDX.js → chunk-24OW3AAU.js} +3 -3
  22. package/dist/{chunk-IJE4AEDX.js.map → chunk-24OW3AAU.js.map} +1 -1
  23. package/dist/{chunk-CAJTDZ5B.cjs → chunk-2XOLAHW6.cjs} +2 -2
  24. package/dist/{chunk-CAJTDZ5B.cjs.map → chunk-2XOLAHW6.cjs.map} +1 -1
  25. package/dist/{chunk-AGCNMEP2.cjs → chunk-3MG7VIPL.cjs} +2 -2
  26. package/dist/{chunk-AGCNMEP2.cjs.map → chunk-3MG7VIPL.cjs.map} +1 -1
  27. package/dist/chunk-4ASM522I.js +2 -0
  28. package/dist/chunk-4ASM522I.js.map +1 -0
  29. package/dist/{chunk-KH4QXKLT.js → chunk-4MD5L23F.js} +2 -2
  30. package/dist/{chunk-KH4QXKLT.js.map → chunk-4MD5L23F.js.map} +1 -1
  31. package/dist/{chunk-IQVSCL2R.js → chunk-4XWZXP6I.js} +3 -3
  32. package/dist/{chunk-IQVSCL2R.js.map → chunk-4XWZXP6I.js.map} +1 -1
  33. package/dist/{chunk-RELMEWY6.js → chunk-6G2NES2I.js} +2 -2
  34. package/dist/chunk-6G2NES2I.js.map +1 -0
  35. package/dist/{chunk-CDE2ZUGG.js → chunk-6NL7RBAG.js} +2 -2
  36. package/dist/{chunk-CDE2ZUGG.js.map → chunk-6NL7RBAG.js.map} +1 -1
  37. package/dist/{chunk-SUAGBRQ7.cjs → chunk-6SYU4MH7.cjs} +2 -2
  38. package/dist/chunk-6SYU4MH7.cjs.map +1 -0
  39. package/dist/chunk-72J5V7SN.cjs +2 -0
  40. package/dist/chunk-72J5V7SN.cjs.map +1 -0
  41. package/dist/{chunk-TSJ4RQLZ.js → chunk-AENL3Z66.js} +2 -2
  42. package/dist/{chunk-TSJ4RQLZ.js.map → chunk-AENL3Z66.js.map} +1 -1
  43. package/dist/chunk-APYRNAU2.js +2 -0
  44. package/dist/chunk-APYRNAU2.js.map +1 -0
  45. package/dist/{chunk-AXTYQFIV.cjs → chunk-D7URPV5Z.cjs} +3 -3
  46. package/dist/{chunk-AXTYQFIV.cjs.map → chunk-D7URPV5Z.cjs.map} +1 -1
  47. package/dist/chunk-DB5ISONG.js +2 -0
  48. package/dist/chunk-DB5ISONG.js.map +1 -0
  49. package/dist/chunk-DGDVY6XI.js +3 -0
  50. package/dist/chunk-DGDVY6XI.js.map +1 -0
  51. package/dist/chunk-EOKHRS2T.js +2 -0
  52. package/dist/chunk-EOKHRS2T.js.map +1 -0
  53. package/dist/{chunk-NQFCXLEF.js → chunk-EOO6M65F.js} +2 -2
  54. package/dist/{chunk-NQFCXLEF.js.map → chunk-EOO6M65F.js.map} +1 -1
  55. package/dist/{chunk-A764BY7L.cjs → chunk-EQNKDTMX.cjs} +2 -2
  56. package/dist/{chunk-A764BY7L.cjs.map → chunk-EQNKDTMX.cjs.map} +1 -1
  57. package/dist/chunk-FESR6PZI.cjs +2 -0
  58. package/dist/chunk-FESR6PZI.cjs.map +1 -0
  59. package/dist/chunk-G2LCDR52.cjs +3 -0
  60. package/dist/chunk-G2LCDR52.cjs.map +1 -0
  61. package/dist/chunk-G5TZ6TDA.js +2 -0
  62. package/dist/chunk-G5TZ6TDA.js.map +1 -0
  63. package/dist/chunk-GDLYXRMA.cjs +2 -0
  64. package/dist/chunk-GDLYXRMA.cjs.map +1 -0
  65. package/dist/{chunk-7DJYS5PO.cjs → chunk-HSTGWWU2.cjs} +2 -2
  66. package/dist/{chunk-7DJYS5PO.cjs.map → chunk-HSTGWWU2.cjs.map} +1 -1
  67. package/dist/{chunk-OE2DBN4K.js → chunk-INMJ7ZXL.js} +2 -2
  68. package/dist/chunk-INMJ7ZXL.js.map +1 -0
  69. package/dist/chunk-ITH2RLRG.js +5 -0
  70. package/dist/chunk-ITH2RLRG.js.map +1 -0
  71. package/dist/{chunk-5AKT36UK.cjs → chunk-K3PZ66XR.cjs} +2 -2
  72. package/dist/{chunk-5AKT36UK.cjs.map → chunk-K3PZ66XR.cjs.map} +1 -1
  73. package/dist/chunk-LI6LYJDA.cjs +2 -0
  74. package/dist/chunk-LI6LYJDA.cjs.map +1 -0
  75. package/dist/{chunk-WQGHJAW2.cjs → chunk-M4UC2PB6.cjs} +2 -2
  76. package/dist/{chunk-WQGHJAW2.cjs.map → chunk-M4UC2PB6.cjs.map} +1 -1
  77. package/dist/chunk-O7HF345B.js +2 -0
  78. package/dist/chunk-O7HF345B.js.map +1 -0
  79. package/dist/{chunk-CM2WM5CM.cjs → chunk-OBZJKZ2F.cjs} +2 -2
  80. package/dist/{chunk-CM2WM5CM.cjs.map → chunk-OBZJKZ2F.cjs.map} +1 -1
  81. package/dist/{chunk-Q7TBBV62.cjs → chunk-P5YWBIIU.cjs} +2 -2
  82. package/dist/chunk-P5YWBIIU.cjs.map +1 -0
  83. package/dist/chunk-PICFFFJV.js +3 -0
  84. package/dist/chunk-PICFFFJV.js.map +1 -0
  85. package/dist/{chunk-P43SV4NJ.cjs → chunk-QOOTRUY7.cjs} +3 -3
  86. package/dist/{chunk-P43SV4NJ.cjs.map → chunk-QOOTRUY7.cjs.map} +1 -1
  87. package/dist/chunk-R3W53ZMP.cjs +2 -0
  88. package/dist/chunk-R3W53ZMP.cjs.map +1 -0
  89. package/dist/chunk-RMDCGYZM.js +2 -0
  90. package/dist/chunk-RMDCGYZM.js.map +1 -0
  91. package/dist/{chunk-CB3EXUM2.js → chunk-RU3KGJRA.js} +2 -2
  92. package/dist/chunk-RU3KGJRA.js.map +1 -0
  93. package/dist/chunk-S3SPDK6N.cjs +2 -0
  94. package/dist/chunk-S3SPDK6N.cjs.map +1 -0
  95. package/dist/chunk-SF5QVUEI.cjs +3 -0
  96. package/dist/chunk-SF5QVUEI.cjs.map +1 -0
  97. package/dist/{chunk-FXB5GCBT.js → chunk-TJKN466F.js} +2 -2
  98. package/dist/{chunk-FXB5GCBT.js.map → chunk-TJKN466F.js.map} +1 -1
  99. package/dist/{chunk-VLX7ZVK4.js → chunk-U5MESNRT.js} +2 -2
  100. package/dist/{chunk-VLX7ZVK4.js.map → chunk-U5MESNRT.js.map} +1 -1
  101. package/dist/chunk-WCVPXBCW.cjs +5 -0
  102. package/dist/chunk-WCVPXBCW.cjs.map +1 -0
  103. package/dist/{chunk-YWF6C2IO.cjs → chunk-WFT3XUSH.cjs} +2 -2
  104. package/dist/{chunk-YWF6C2IO.cjs.map → chunk-WFT3XUSH.cjs.map} +1 -1
  105. package/dist/{chunk-3ZGFAE3Q.js → chunk-X2GQAKL2.js} +2 -2
  106. package/dist/{chunk-3ZGFAE3Q.js.map → chunk-X2GQAKL2.js.map} +1 -1
  107. package/dist/{chunk-G3POUURF.js → chunk-YID47OPR.js} +2 -2
  108. package/dist/{chunk-G3POUURF.js.map → chunk-YID47OPR.js.map} +1 -1
  109. package/dist/chunk-YV4GDW5A.cjs +2 -0
  110. package/dist/chunk-YV4GDW5A.cjs.map +1 -0
  111. package/dist/chunk-ZSXQP7PD.cjs +2 -0
  112. package/dist/chunk-ZSXQP7PD.cjs.map +1 -0
  113. package/dist/constants.cjs +1 -1
  114. package/dist/constants.js +1 -1
  115. package/dist/engine.cjs +1 -1
  116. package/dist/engine.d.cts +10 -10
  117. package/dist/engine.d.ts +10 -10
  118. package/dist/engine.js +1 -1
  119. package/dist/engine.worker.cjs +1 -1
  120. package/dist/engine.worker.cjs.map +1 -1
  121. package/dist/engine.worker.js +1 -1
  122. package/dist/engine.worker.js.map +1 -1
  123. package/dist/errors.cjs +1 -1
  124. package/dist/errors.d.cts +3 -3
  125. package/dist/errors.d.ts +3 -3
  126. package/dist/errors.js +1 -1
  127. package/dist/format.cjs +1 -1
  128. package/dist/format.d.cts +1 -1
  129. package/dist/format.d.ts +1 -1
  130. package/dist/format.js +1 -1
  131. package/dist/index.cjs +1 -1
  132. package/dist/index.cjs.map +1 -1
  133. package/dist/index.d.cts +10 -10
  134. package/dist/index.d.ts +10 -10
  135. package/dist/index.js +1 -1
  136. package/dist/index.js.map +1 -1
  137. package/dist/language.d.cts +9 -9
  138. package/dist/language.d.ts +9 -9
  139. package/dist/lexer.cjs +1 -1
  140. package/dist/lexer.d.cts +3 -3
  141. package/dist/lexer.d.ts +3 -3
  142. package/dist/lexer.js +1 -1
  143. package/dist/normalizer.cjs +1 -1
  144. package/dist/normalizer.d.cts +2 -2
  145. package/dist/normalizer.d.ts +2 -2
  146. package/dist/normalizer.js +1 -1
  147. package/dist/packages.cjs +1 -1
  148. package/dist/packages.d.cts +8 -8
  149. package/dist/packages.d.ts +8 -8
  150. package/dist/packages.js +1 -1
  151. package/dist/parser.cjs +1 -1
  152. package/dist/parser.d.cts +3 -3
  153. package/dist/parser.d.ts +3 -3
  154. package/dist/parser.js +1 -1
  155. package/dist/{pipeline-BYkKNpql.d.cts → pipeline-Bum6y1B9.d.cts} +1 -1
  156. package/dist/{pipeline-Cl7KW8CB.d.ts → pipeline-DOo3KHaq.d.ts} +1 -1
  157. package/dist/resolvers.cjs +1 -1
  158. package/dist/resolvers.d.cts +69 -3
  159. package/dist/resolvers.d.ts +69 -3
  160. package/dist/resolvers.js +1 -1
  161. package/dist/temporal.cjs +1 -1
  162. package/dist/temporal.js +1 -1
  163. package/dist/testing.cjs +2 -2
  164. package/dist/testing.cjs.map +1 -1
  165. package/dist/testing.d.cts +9 -9
  166. package/dist/testing.d.ts +9 -9
  167. package/dist/testing.js +1 -1
  168. package/dist/testing.js.map +1 -1
  169. package/dist/uom.cjs +1 -1
  170. package/dist/uom.d.cts +35 -2
  171. package/dist/uom.d.ts +35 -2
  172. package/dist/uom.js +1 -1
  173. package/dist/vm.cjs +1 -1
  174. package/dist/vm.d.cts +6 -6
  175. package/dist/vm.d.ts +6 -6
  176. package/dist/vm.js +1 -1
  177. package/dist/worker.cjs +2 -2
  178. package/dist/worker.cjs.map +1 -1
  179. package/dist/worker.d.cts +9 -9
  180. package/dist/worker.d.ts +9 -9
  181. package/dist/worker.js +1 -1
  182. package/dist/worker.js.map +1 -1
  183. package/package.json +1 -1
  184. package/dist/chunk-4DR5RBHQ.cjs +0 -2
  185. package/dist/chunk-4DR5RBHQ.cjs.map +0 -1
  186. package/dist/chunk-4IC5OARK.js +0 -3
  187. package/dist/chunk-4IC5OARK.js.map +0 -1
  188. package/dist/chunk-7ODHPWQC.js +0 -5
  189. package/dist/chunk-7ODHPWQC.js.map +0 -1
  190. package/dist/chunk-A755LVPT.cjs +0 -2
  191. package/dist/chunk-A755LVPT.cjs.map +0 -1
  192. package/dist/chunk-AF6NDOIE.js +0 -2
  193. package/dist/chunk-AF6NDOIE.js.map +0 -1
  194. package/dist/chunk-B2NL65FI.js +0 -2
  195. package/dist/chunk-B2NL65FI.js.map +0 -1
  196. package/dist/chunk-CB3EXUM2.js.map +0 -1
  197. package/dist/chunk-DUFEONVN.cjs +0 -3
  198. package/dist/chunk-DUFEONVN.cjs.map +0 -1
  199. package/dist/chunk-IJHL3LMH.js +0 -2
  200. package/dist/chunk-IJHL3LMH.js.map +0 -1
  201. package/dist/chunk-LCYQQFUH.cjs +0 -2
  202. package/dist/chunk-LCYQQFUH.cjs.map +0 -1
  203. package/dist/chunk-LP3JYC3A.js +0 -2
  204. package/dist/chunk-LP3JYC3A.js.map +0 -1
  205. package/dist/chunk-OE2DBN4K.js.map +0 -1
  206. package/dist/chunk-OKKGPINQ.cjs +0 -5
  207. package/dist/chunk-OKKGPINQ.cjs.map +0 -1
  208. package/dist/chunk-OM7NOHJF.cjs +0 -2
  209. package/dist/chunk-OM7NOHJF.cjs.map +0 -1
  210. package/dist/chunk-PTXUWGRR.js +0 -3
  211. package/dist/chunk-PTXUWGRR.js.map +0 -1
  212. package/dist/chunk-Q7TBBV62.cjs.map +0 -1
  213. package/dist/chunk-RELMEWY6.js.map +0 -1
  214. package/dist/chunk-SFM4XFGJ.js +0 -2
  215. package/dist/chunk-SFM4XFGJ.js.map +0 -1
  216. package/dist/chunk-SRAU3BLV.cjs +0 -3
  217. package/dist/chunk-SRAU3BLV.cjs.map +0 -1
  218. package/dist/chunk-SUAGBRQ7.cjs.map +0 -1
  219. package/dist/chunk-UNKZ5XRC.cjs +0 -2
  220. package/dist/chunk-UNKZ5XRC.cjs.map +0 -1
  221. package/dist/chunk-WU7SBKVU.cjs +0 -2
  222. package/dist/chunk-WU7SBKVU.cjs.map +0 -1
  223. package/dist/chunk-X5K72MBV.js +0 -2
  224. package/dist/chunk-X5K72MBV.js.map +0 -1
  225. package/dist/chunk-ZVPZQ66D.cjs +0 -2
  226. package/dist/chunk-ZVPZQ66D.cjs.map +0 -1
@@ -1,5 +0,0 @@
1
- import {b as b$3,a as a$5}from'./chunk-CB3EXUM2.js';import {a as a$3}from'./chunk-IJHL3LMH.js';import {a as a$6}from'./chunk-MIQBJGGR.js';import {d as d$1,a as a$2,b,c as c$5}from'./chunk-AF6NDOIE.js';import {a as a$4,b as b$4,c as c$8}from'./chunk-JP4JMQOG.js';import {c as c$a,a as a$a}from'./chunk-IQVSCL2R.js';import {h as h$1,t,p,o,n as n$1,l,i,m,k,b as b$9,q,s as s$1,g,r as r$1,j as j$1}from'./chunk-FXB5GCBT.js';import {d as d$2}from'./chunk-VLX7ZVK4.js';import {c as c$3,d as d$3,b as b$8}from'./chunk-B2NL65FI.js';import {b as b$7}from'./chunk-76F3LCIL.js';import {c as c$6,a as a$7,b as b$b}from'./chunk-TCZSPH4A.js';import {K as K$1,x,F as F$1,H,I,i as i$1}from'./chunk-OE2DBN4K.js';import {_,da}from'./chunk-KH4QXKLT.js';import {b as b$5}from'./chunk-NQFCXLEF.js';import {P,n,O,t as t$1,l as l$1,L,u,N,M,s,r,m as m$1,g as g$1}from'./chunk-X5K72MBV.js';import {a as a$1,c as c$2,b as b$1}from'./chunk-TSJ4RQLZ.js';import {c as c$1,b as b$2}from'./chunk-CDE2ZUGG.js';import {b as b$6,c as c$7}from'./chunk-JPFCXLJV.js';import {c as c$4,a as a$8}from'./chunk-LP3JYC3A.js';import {a,c as c$9}from'./chunk-FAO6DQ74.js';import {a as a$9}from'./chunk-LHLW7JLS.js';import {c,d,b as b$a}from'./chunk-RELMEWY6.js';function jt(r,e,t,n,i){let s=t[e],o=n[e];if(!s||!o)return;let c=new Set(Object.keys(s));for(let l of Object.keys(o))c.has(l)&&i.push({kind:r,severity:"warning",detail:`Both "${t.name}" and "${n.name}" register a ${e==="prefixParselets"?"prefix":"infix"} parselet for token type "${l}" \u2014 the later-registered one silently wins.`,packages:[t.name,n.name]});}function Wt(r,e){let t=[];if(jt("prefixParseletTokenType","prefixParselets",r,e,t),jt("infixParseletTokenType","infixParselets",r,e,t),r.phrases&&e.phrases)for(let[s,o]of Object.entries(e.phrases)){let c=r.phrases[s];c!==void 0&&c!==o&&t.push({kind:"phrase",severity:"warning",detail:`Both "${r.name}" (-> "${c}") and "${e.name}" (-> "${o}") fuse the phrase "${s}" to DIFFERENT token types \u2014 PhraseTrie has no collision detection of its own, so the later-registered mapping silently wins with no other signal.`,packages:[r.name,e.name]});}if(r.asConverters&&e.asConverters)for(let s of Object.keys(e.asConverters)){let o=s.toLowerCase();Object.keys(r.asConverters).some(c=>c.toLowerCase()===o)&&t.push({kind:"converterName",severity:"warning",detail:`Both "${r.name}" and "${e.name}" register an "as ${s}" converter \u2014 the later-registered handler silently wins.`,packages:[r.name,e.name]});}if(r.pluginFunctions&&e.pluginFunctions){let s=new Set(Object.keys(r.pluginFunctions));for(let o of Object.keys(e.pluginFunctions))s.has(o)&&t.push({kind:"pluginFunctionName",severity:"warning",detail:`Both "${r.name}" and "${e.name}" register a plugin function named "${o}" \u2014 the later registration wins in the engine's name-to-index map. Give each package's functions package-unique names.`,packages:[r.name,e.name]});}if(r.normalizerRules&&e.normalizerRules){let s=new Set(r.normalizerRules.map(o=>o.name));for(let o of e.normalizerRules)s.has(o.name)&&t.push({kind:"normalizerRuleName",severity:"warning",detail:`Both "${r.name}" and "${e.name}" register a normalizer rule named "${o.name}" \u2014 the normalizer unregisters rules by name, so removing either package would drop both rules. Give each package's rules a package-unique name.`,packages:[r.name,e.name]});}let n=r.lexerVocabulary,i=e.lexerVocabulary;if(n?.keywords&&i?.keywords)for(let[s,o]of Object.entries(i.keywords)){let c=n.keywords[s];c!==void 0&&c!==o&&t.push({kind:"lexerKeyword",severity:"error",detail:`Both "${r.name}" (-> "${c}") and "${e.name}" (-> "${o}") register the lexer keyword "${s}" for DIFFERENT token types \u2014 whichever package registers second wins, and the loser's grammar becomes silently unreachable for that word.`,packages:[r.name,e.name]});}if(n?.operators&&i?.operators)for(let[s,o]of Object.entries(i.operators)){let c=n.operators[s];c!==void 0&&c!==o&&t.push({kind:"lexerOperator",severity:"error",detail:`Both "${r.name}" (-> "${c}") and "${e.name}" (-> "${o}") register the lexer operator "${s}" for DIFFERENT token types.`,packages:[r.name,e.name]});}if(r.asyncResolvers&&e.asyncResolvers){let s=new Set(r.asyncResolvers.map(o=>o.namespace));for(let o of e.asyncResolvers)s.has(o.namespace)&&t.push({kind:"asyncResolverNamespace",severity:"error",detail:`Both "${r.name}" and "${e.name}" register an async resolver under the namespace "${o.namespace}" \u2014 ResolverRegistry is keyed by namespace, so one resolver's cache/preflight state will silently clobber the other's.`,packages:[r.name,e.name]});}if(r.tokenCategories&&e.tokenCategories)for(let[s,o]of Object.entries(e.tokenCategories)){let c=r.tokenCategories[s];c!==void 0&&c!==o&&t.push({kind:"tokenCategory",severity:"info",detail:`Both "${r.name}" (-> "${c}") and "${e.name}" (-> "${o}") declare a highlight category for token type "${s}" \u2014 cosmetic only, but the later registration wins.`,packages:[r.name,e.name]});}return t}function Jr(r,e){let t=[];for(let n of e)n===r||n.name===r.name||t.push(...Wt(n,r));return {compatible:!t.some(n=>n.severity==="error"),conflicts:t}}var ve=class{constructor(){this.prefixOwners=new Map;this.infixOwners=new Map;this.phraseOwners=new Map;this.converterOwners=new Map;this.pluginFnOwners=new Map;this.ruleOwners=new Map;this.keywordOwners=new Map;this.operatorOwners=new Map;this.resolverOwners=new Map;this.categoryOwners=new Map;}check(e){let t=new Set,n=(s,o)=>{let c=s.get(o);c&&c!==e&&c.name!==e.name&&t.add(c);};if(e.prefixParselets)for(let s of Object.keys(e.prefixParselets))n(this.prefixOwners,s);if(e.infixParselets)for(let s of Object.keys(e.infixParselets))n(this.infixOwners,s);if(e.phrases)for(let s of Object.keys(e.phrases))n(this.phraseOwners,s);if(e.asConverters)for(let s of Object.keys(e.asConverters))n(this.converterOwners,s.toLowerCase());if(e.pluginFunctions)for(let s of Object.keys(e.pluginFunctions))n(this.pluginFnOwners,s);if(e.normalizerRules)for(let s of e.normalizerRules)n(this.ruleOwners,s.name);if(e.lexerVocabulary?.keywords)for(let s of Object.keys(e.lexerVocabulary.keywords))n(this.keywordOwners,s);if(e.lexerVocabulary?.operators)for(let s of Object.keys(e.lexerVocabulary.operators))n(this.operatorOwners,s);if(e.asyncResolvers)for(let s of e.asyncResolvers)n(this.resolverOwners,s.namespace);if(e.tokenCategories)for(let s of Object.keys(e.tokenCategories))n(this.categoryOwners,s);let i=[];for(let s of t)i.push(...Wt(s,e));return i}add(e){let t=(n,i)=>{n.has(i)||n.set(i,e);};if(e.prefixParselets)for(let n of Object.keys(e.prefixParselets))t(this.prefixOwners,n);if(e.infixParselets)for(let n of Object.keys(e.infixParselets))t(this.infixOwners,n);if(e.phrases)for(let n of Object.keys(e.phrases))t(this.phraseOwners,n);if(e.asConverters)for(let n of Object.keys(e.asConverters))t(this.converterOwners,n.toLowerCase());if(e.pluginFunctions)for(let n of Object.keys(e.pluginFunctions))t(this.pluginFnOwners,n);if(e.normalizerRules)for(let n of e.normalizerRules)t(this.ruleOwners,n.name);if(e.lexerVocabulary?.keywords)for(let n of Object.keys(e.lexerVocabulary.keywords))t(this.keywordOwners,n);if(e.lexerVocabulary?.operators)for(let n of Object.keys(e.lexerVocabulary.operators))t(this.operatorOwners,n);if(e.asyncResolvers)for(let n of e.asyncResolvers)t(this.resolverOwners,n.namespace);if(e.tokenCategories)for(let n of Object.keys(e.tokenCategories))t(this.categoryOwners,n);}rebuild(e){for(let t of [this.prefixOwners,this.infixOwners,this.phraseOwners,this.converterOwners,this.pluginFnOwners,this.ruleOwners,this.keywordOwners,this.operatorOwners,this.resolverOwners,this.categoryOwners])t.clear();for(let t of e)this.add(t);}};var Cr=/(\d+)\.(\d+)\.(\d+)/,Tr=/^\d+$/;function Ht(r){let e=Cr.exec(r.trim());return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function Nr(r,e){return r[0]-e[0]||r[1]-e[1]||r[2]-e[2]}function De(r){let e=r.split(".");if(e.length===0||e.length>3)return null;let t=[0,0,0];for(let n=0;n<e.length;n++){if(!Tr.test(e[n]))return null;t[n]=Number(e[n]);}return [t[0],t[1],t[2]]}function wr([r,e,t]){let n=r>0?[r+1,0,0]:e>0?[0,e+1,0]:[0,0,t+1];return [{op:">=",v:[r,e,t]},{op:"<",v:n}]}function Rr([r,e,t]){return [{op:">=",v:[r,e,t]},{op:"<",v:[r,e+1,0]}]}function Ar(r){if(r===""||r==="*"||r==="x"||r==="X")return [];if(r[0]==="^"){let i=De(r.slice(1));return i&&wr(i)}if(r[0]==="~"){let i=De(r.slice(1));return i&&Rr(i)}let e=/^(>=|<=|>|<|=)/.exec(r),t=e?e[1]:"=",n=De(e?r.slice(e[1].length):r);return n&&[{op:t,v:n}]}function Kt(r){let e=[];for(let t of r.split("||")){let n=t.trim().split(/\s+/).filter(s=>s!==""),i=[];for(let s of n){let o=Ar(s);if(o===null)return null;i.push(...o);}e.push(i);}return e}function Gt(r){return Kt(r.trim())!==null}function Pr(r,e){let t=Nr(r,e.v);switch(e.op){case "<":return t<0;case "<=":return t<=0;case ">":return t>0;case ">=":return t>=0;case "=":return t===0}}function qt(r,e){let t=Kt(e.trim());return t===null?false:t.some(n=>n.every(i=>Pr(r,i)))}function Or(r,e=a$1){if(!r.engineVersion)return {compatible:true};if(!Gt(r.engineVersion))return {compatible:false,reason:"invalid-range",declaredRange:r.engineVersion,engineVersion:e};let t=Ht(e);return t===null||!qt(t,r.engineVersion)?{compatible:false,reason:"range-not-satisfied",declaredRange:r.engineVersion,engineVersion:e}:{compatible:true}}function Qt(r,e=a$1){let t=Or(r,e);if(!t.compatible)throw t.reason==="invalid-range"?c.config({code:"PACKAGE_ENGINE_VERSION_INVALID_RANGE",message:`Package "${r.name}" declares an invalid engineVersion range: "${t.declaredRange}" is not a valid semver range.`,expected:'a valid semver range string (e.g. "^0.1.0", ">=0.2.0 <1.0.0")',found:`"${t.declaredRange}"`,suggestion:`This is a range-syntax typo in "${r.name}"'s own descriptor, not a version mismatch with the running engine \u2014 check for a stray character.`,context:{packageName:r.name,declaredRange:t.declaredRange}}):c.config({code:"PACKAGE_ENGINE_VERSION_MISMATCH",message:`Package "${r.name}" declares engineVersion "${t.declaredRange}", which is not satisfied by the running engine version "${t.engineVersion}".`,expected:`an engine version satisfying "${t.declaredRange}"`,found:`engine version "${t.engineVersion}"`,suggestion:`Update "${r.name}" to a version built against solve-engine ${t.engineVersion}, or pin solve-engine to a version satisfying "${t.declaredRange}".`,context:{packageName:r.name,declaredRange:t.declaredRange,engineVersion:t.engineVersion}})}var ee="solve-engine/snapshot",Q=1;function $(r){return Number.isFinite(r)?r:Number.isNaN(r)?"NaN":r>0?"Infinity":"-Infinity"}function F(r){if(typeof r=="number")return r;if(r==="NaN")return NaN;if(r==="Infinity")return 1/0;if(r==="-Infinity")return -1/0;throw c.validation({code:V.SNAPSHOT_MALFORMED,message:`Snapshot holds an unrecognised number sentinel: ${JSON.stringify(r)}`,expected:'a JSON number, or one of "NaN", "Infinity", "-Infinity"',found:JSON.stringify(r)})}var V={SNAPSHOT_VERSION_MISMATCH:"SNAPSHOT_VERSION_MISMATCH",SNAPSHOT_MALFORMED:"SNAPSHOT_MALFORMED",SNAPSHOT_UNSUPPORTED_VALUE:"SNAPSHOT_UNSUPPORTED_VALUE"};function Yt(r){return {coef:r.coef.toString(),scale:r.scale}}function Xt(r){return {coef:BigInt(r.coef),scale:r.scale}}function Lr(r){return {n:r.n.toString(),d:r.d.toString()}}function Ir(r){return {n:BigInt(r.n),d:BigInt(r.d)}}function Jt(r){return g$1[r]??String(r)}function Ve(r,e){throw c.validation({code:V.SNAPSHOT_UNSUPPORTED_VALUE,message:`A ${Jt(r)} value (${e}) cannot be included in a snapshot yet.`,expected:"a concrete number, string, boolean, unit, range, matrix, bigint, or money value",found:`${Jt(r)} value`,suggestion:"Symbolic (algebra) values are deferred to a follow-up. Evaluate the document without the symbolic line, or re-derive it after restoring.",context:{valueType:r,location:e}})}function Me(r,e){switch(r.type){case 0:{let t={t:0,v:$(r.value)};return r.exact!==void 0&&(t.exact=Yt(r.exact)),r.rational!==void 0&&(t.rational=Lr(r.rational)),t}case 1:{let t=r.value;return typeof t=="bigint"?{t:1,v:t.toString(),big:true,base:r.unit}:{t:1,v:$(t),base:r.unit}}case 2:return {t:2,v:r.value.toString()};case 3:return {t:3,v:r.value};case 4:{let t={t:4,v:$(r.value)};return r.grain!==void 0&&(t.g=r.grain),r.zone!==void 0&&(t.z=r.zone),t}case 5:return {t:5,v:$(r.value)};case 6:{let t={t:6,v:$(r.value),unit:r.unit??""};return r.exact!==void 0&&(t.exact=Yt(r.exact)),t}case 7:{let t=r.value;t.hasSymbolic&&Ve(9,`${e} (symbolic matrix cell)`);let n=t.data.map(i=>Dr(i,e));return {t:7,rows:t.rows,cols:t.cols,data:n}}case 8:{let t=r.value;return {t:8,min:$(t.min),max:$(t.max)}}case 10:return {t:10,v:r.value};case 13:return {t:13,code:r.value,message:r.unit??""};default:return Ve(r.type,e)}}function Dr(r,e){return typeof r=="boolean"?r:typeof r=="number"?$(r):Ve(9,`${e} (symbolic matrix cell)`)}function Be(r){switch(r.t){case 0:{let e=new m$1(0,F(r.v));return r.exact!==void 0&&(e.exact=Xt(r.exact)),r.rational!==void 0&&(e.rational=Ir(r.rational)),e}case 1:{let e=r.big?BigInt(r.v):F(r.v);return new m$1(1,e,r.base)}case 2:return new m$1(2,BigInt(r.v));case 3:return new m$1(3,r.v);case 4:{let e=new m$1(4,F(r.v));return r.g!==void 0&&(e.grain=r.g),r.z!==void 0&&(e.zone=r.z),e}case 5:return new m$1(5,F(r.v));case 6:{let e=new m$1(6,F(r.v),r.unit);return r.exact!==void 0&&(e.exact=Xt(r.exact)),e}case 7:{let e=r.data.map(n=>typeof n=="boolean"?n:F(n)),t={rows:r.rows,cols:r.cols,data:e,hasSymbolic:false};return new m$1(7,t)}case 8:return new m$1(8,{min:F(r.min),max:F(r.max)});case 10:return new m$1(10,r.v);case 13:return new m$1(13,r.code,r.message);default:throw c.validation({code:V.SNAPSHOT_MALFORMED,message:`Snapshot holds a value with an unknown type tag: ${JSON.stringify(r.t)}`,expected:"a known SerializedValue type tag",found:JSON.stringify(r.t)})}}function ue(r){let e={opcodes:Array.from(r.opcodes),numbers:Array.from(r.numbers,$),strings:r.strings.slice(),hasAsync:r.hasAsync};return r.constants&&(e.constants=Array.from(r.constants.entries())),r.userFunctionBodies&&(e.userFunctionBodies=r.userFunctionBodies.map(Ue)),r.anonymousBodies&&(e.anonymousBodies=r.anonymousBodies.map(t=>({params:t.params.slice(),program:ue(t.program)}))),e}function pe(r){let e={opcodes:Uint8Array.from(r.opcodes),numbers:Float64Array.from(r.numbers,F),strings:r.strings.slice(),hasAsync:r.hasAsync};return r.constants&&(e.constants=new Map(r.constants)),r.userFunctionBodies&&(e.userFunctionBodies=r.userFunctionBodies.map(_e)),r.anonymousBodies&&(e.anonymousBodies=r.anonymousBodies.map(t=>({params:t.params.slice(),program:pe(t.program)}))),e}function Ue(r){return {name:r.name,params:r.params.slice(),program:ue(r.program)}}function _e(r){return {name:r.name,params:r.params.slice(),program:pe(r.program)}}function rr(r){if(typeof r!="object"||r===null)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:"fromJSON was given something that is not a snapshot object.",expected:`an object produced by ExpressionEngine.toJSON() with format "${ee}"`,found:r===null?"null":typeof r});let e=r;if(e.format!==ee)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:`This object is not a solve-engine snapshot (its "format" is ${JSON.stringify(e.format)}).`,expected:`format "${ee}"`,found:JSON.stringify(e.format)});if(e.version!==Q)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:`This snapshot was written for format version ${e.version}, but this engine restores version ${Q}.`,expected:`snapshot version ${Q}`,found:`version ${e.version}`,suggestion:"Regenerate the snapshot with a matching engine version, or re-evaluate the document from source.",context:{snapshotVersion:e.version,readerVersion:Q,engineVersion:e.engineVersion}});Br(r);}var Zt=32;function Vr(r){return r===null?"null":Array.isArray(r)?`an array of ${r.length}`:typeof r=="object"?"an object":`${typeof r} ${JSON.stringify(r)}`.slice(0,80)}function h(r,e,t){throw c.validation({code:V.SNAPSHOT_MALFORMED,message:`Snapshot is malformed at ${r}: expected ${e}.`,expected:e,found:Vr(t),suggestion:"Regenerate the snapshot with ExpressionEngine.toJSON(), or re-evaluate the document from source.",context:{location:r}})}function j(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function z(r){return typeof r=="number"||r==="NaN"||r==="Infinity"||r==="-Infinity"}function ce(r){return typeof r=="string"&&/^-?\d+$/.test(r)}function be(r,e){(!Array.isArray(r)||!r.every(t=>typeof t=="string"))&&h(e,"an array of strings",r);}function er(r,e){(!j(r)||!ce(r.coef)||typeof r.scale!="number")&&h(e,"a decimal as { coef: digits, scale: number }",r);}function Mr(r,e){(!j(r)||!ce(r.n)||!ce(r.d))&&h(e,"a rational as { n: digits, d: digits }",r);}function tr(r,e){switch(j(r)||h(e,"a serialised value object",r),r.t){case 0:z(r.v)||h(`${e}.v`,"a number",r.v),r.exact!==void 0&&er(r.exact,`${e}.exact`),r.rational!==void 0&&Mr(r.rational,`${e}.rational`);return;case 1:(r.big?!ce(r.v):!z(r.v))&&h(`${e}.v`,r.big?"an integer string":"a number",r.v),r.base!==void 0&&typeof r.base!="string"&&h(`${e}.base`,"a base name",r.base);return;case 2:ce(r.v)||h(`${e}.v`,"an integer string",r.v);return;case 3:typeof r.v!="string"&&h(`${e}.v`,"a string",r.v);return;case 4:z(r.v)||h(`${e}.v`,"a number",r.v),r.g!==void 0&&r.g!=="date"&&r.g!=="datetime"&&r.g!=="instant"&&h(`${e}.g`,'one of "date", "datetime" or "instant"',r.g),r.z!==void 0&&typeof r.z!="string"&&h(`${e}.z`,"a zone reference",r.z);return;case 5:z(r.v)||h(`${e}.v`,"a number",r.v);return;case 6:z(r.v)||h(`${e}.v`,"a number",r.v),typeof r.unit!="string"&&h(`${e}.unit`,"a unit name",r.unit),r.exact!==void 0&&er(r.exact,`${e}.exact`);return;case 7:{let{rows:t,cols:n,data:i}=r;(!Number.isInteger(t)||t<0)&&h(`${e}.rows`,"a non-negative integer",t),(!Number.isInteger(n)||n<0)&&h(`${e}.cols`,"a non-negative integer",n),(!Array.isArray(i)||i.length!==t*n)&&h(`${e}.data`,`an array of ${t} \xD7 ${n} cells`,i),i.every(s=>typeof s=="boolean"||z(s))||h(`${e}.data`,"numeric or boolean cells",i);return}case 8:(!z(r.min)||!z(r.max))&&h(e,"a range with numeric min and max",r);return;case 10:typeof r.v!="boolean"&&h(`${e}.v`,"a boolean",r.v);return;case 13:(typeof r.code!="string"||typeof r.message!="string")&&h(e,"an error with a string code and message",r);return;default:return}}function Ee(r,e,t){if(t>Zt&&h(e,`function bodies nested at most ${Zt} deep`,"deeper nesting"),j(r)||h(e,"a serialised program object",r),(!Array.isArray(r.opcodes)||!r.opcodes.every(n=>Number.isInteger(n)&&n>=0&&n<=255))&&h(`${e}.opcodes`,"an array of bytes (integers 0 to 255)",r.opcodes),(!Array.isArray(r.numbers)||!r.numbers.every(z))&&h(`${e}.numbers`,"an array of numbers",r.numbers),be(r.strings,`${e}.strings`),typeof r.hasAsync!="boolean"&&h(`${e}.hasAsync`,"a boolean",r.hasAsync),r.constants!==void 0){let n=i=>Array.isArray(i)&&i.length===2&&typeof i[0]=="number"&&typeof i[1]=="number";(!Array.isArray(r.constants)||!r.constants.every(n))&&h(`${e}.constants`,"an array of [number, number] pairs",r.constants);}r.userFunctionBodies!==void 0&&(Array.isArray(r.userFunctionBodies)||h(`${e}.userFunctionBodies`,"an array of functions",r.userFunctionBodies),r.userFunctionBodies.forEach((n,i)=>nr(n,`${e}.userFunctionBodies[${i}]`,t+1))),r.anonymousBodies!==void 0&&(Array.isArray(r.anonymousBodies)||h(`${e}.anonymousBodies`,"an array of bodies",r.anonymousBodies),r.anonymousBodies.forEach((n,i)=>{let s=`${e}.anonymousBodies[${i}]`;j(n)||h(s,"a body object",n),be(n.params,`${s}.params`),Ee(n.program,`${s}.program`,t+1);}));}function nr(r,e,t){j(r)||h(e,"a function object",r),typeof r.name!="string"&&h(`${e}.name`,"a function name",r.name),be(r.params,`${e}.params`),Ee(r.program,`${e}.program`,t);}function Br(r){r.locale!==void 0&&typeof r.locale!="string"&&h("locale","a locale code",r.locale),j(r.variables)||h("variables","an object of values by name",r.variables);for(let[e,t]of Object.entries(r.variables))tr(t,`variables.${e}`);Array.isArray(r.userFunctions)||h("userFunctions","an array of functions",r.userFunctions),r.userFunctions.forEach((e,t)=>nr(e,`userFunctions[${t}]`,1)),Array.isArray(r.lineCache)||h("lineCache","an array of cached lines",r.lineCache),r.lineCache.forEach((e,t)=>{let n=`lineCache[${t}]`;j(e)||h(n,"a cached line",e),Number.isInteger(e.line)||h(`${n}.line`,"a line number",e.line),typeof e.expression!="string"&&h(`${n}.expression`,"the line's expression text",e.expression),tr(e.result,`${n}.result`),Ee(e.bytecode,`${n}.bytecode`,1),be(e.reads,`${n}.reads`),e.writeVar!==null&&typeof e.writeVar!="string"&&h(`${n}.writeVar`,"a variable name or null",e.writeVar);}),Array.isArray(r.bytecodeCache)||h("bytecodeCache","an array of compiled expressions",r.bytecodeCache),r.bytecodeCache.forEach((e,t)=>{let n=`bytecodeCache[${t}]`;(!j(e)||typeof e.expression!="string")&&h(n,"an { expression, program } pair",e),Ee(e.program,`${n}.program`,1);});}var ir=null;function cn(r){ir=r;}function Fe(){return ir}var sr=3e4,or=50,xe=class{constructor(e){this.workers=[];this.nextWorker=0;this.nextId=1;this.pendingBatches=new Map;this.terminated=false;this._available=null;this.poolSize=Math.min(e??this.defaultPoolSize(),4);}defaultPoolSize(){return typeof navigator<"u"&&navigator.hardwareConcurrency?Math.min(navigator.hardwareConcurrency,4):2}isAvailable(){if(this.terminated)return false;if(this._available!==null)return this._available;if(typeof Worker>"u")return this._available=false,false;try{let e=Fe();return e===null?(this._available=!1,!1):(e().terminate(),this._available=!0,!0)}catch{return this._available=false,false}}executeBatch(e,t){if(!this.isAvailable())return;if(e.length===0)return Promise.resolve([]);this.ensureWorkers();let n=[];for(let l of e){let a=t.get(l);if(!a||a.bytecode.opcodes.length===0)continue;let u=a.bytecode.opcodes,p=a.bytecode.numbers,f=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength),m=p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength);n.push({lineNumber:l,opcodesBuffer:f,numbersBuffer:m,opcodesLength:u.length,numbersLength:p.length,strings:[...a.bytecode.strings]});}if(n.length===0)return Promise.resolve([]);let i=[];for(let l of n)l.opcodesBuffer.byteLength>0&&i.push(l.opcodesBuffer),l.numbersBuffer.byteLength>0&&i.push(l.numbersBuffer);let s=this.nextId++,o=this.nextWorkerIndex(),c=this.workers[o];return new Promise(l=>{let a=setTimeout(()=>{this.pendingBatches.has(s)&&this.failWorker(o,"WORKER_TIMEOUT",`Evaluation did not finish within ${sr/1e3} seconds; the worker was replaced`);},sr);this.pendingBatches.set(s,{id:s,lineNumbers:n.map(u=>u.lineNumber),workerIndex:o,resolve:u=>{clearTimeout(a),l(u);}}),c.postMessage({type:"EXECUTE_BATCH",id:s,items:n},i);})}clear(){for(let[,e]of this.pendingBatches)e.resolve([]);this.pendingBatches.clear();for(let e of this.workers)e.terminate();this.workers=[],this.nextWorker=0;}destroy(){this.terminated=true,this.clear();}ensureWorkers(){if(!(this.workers.length>0))for(let e=0;e<this.poolSize;e++)this.spawnWorker(e);}spawnWorker(e){let t=Fe();if(t===null)return;let n=t();n.onmessage=i=>{this.handleWorkerMessage(i.data);},n.onerror=i=>{console.error(`[ExecutionPool] Worker ${e} error:`,i.message),this.failWorker(e,"WORKER_EXECUTION_ERROR",`Worker failed: ${i.message}`);},this.workers[e]=n;}failWorker(e,t,n){if(this.workers.length!==0){this.workers[e]?.terminate(),this.terminated||this.spawnWorker(e);for(let[i,s]of this.pendingBatches)s.workerIndex===e&&(this.pendingBatches.delete(i),s.resolve(Ur(s.lineNumbers,t,n)));}}nextWorkerIndex(){let e=this.nextWorker;return this.nextWorker=(this.nextWorker+1)%this.workers.length,e}handleWorkerMessage(e){if(e.type!=="EXECUTE_RESULT")return;let t=this.pendingBatches.get(e.id);t&&(this.pendingBatches.delete(e.id),t.resolve(e.results));}};function Ur(r,e,t){return r.map(n=>({lineNumber:n,valueType:13,value:0,unit:t,isPending:false,errorCode:e}))}function ar(r$1){switch(r$1.valueType){case 0:return n(r$1.value);case 1:return r(r$1.value);case 2:return s(BigInt(r$1.value));case 3:return t$1(String(r$1.value));case 4:return M(r$1.value);case 5:return N(r$1.value);case 6:return u(r$1.value,r$1.unit??"");case 7:return n(r$1.value);case 10:return L(r$1.value!==0);case 12:return O(r$1.queryKey??"");case 13:return P(r$1.errorCode??"WORKER_EXECUTION_ERROR",r$1.unit??"Unknown worker error");default:return n(r$1.value)}}var Se=class Se{constructor(e,t,n,i=Se.DEFAULT_HIGH_WATER_MARK){this.pending=[];this.scheduled=false;this.cleared=false;this.executionPool=null;this.workerOffloadDispatchCount=0;this._streamController=null;this._testCaptures=null;this.onLineResult=null;this.warnedAboutMissingHook=false;this.dag=e,this.lineCache=t,this.vm=n,this.highWaterMark=i,this._eventStream=this.createEventStream();}warnIfUnwired(){this.onLineResult||this.listenerCount>0||this.warnedAboutMissingHook||(this.warnedAboutMissingHook=true,console.warn("[solve-engine] An async result resolved, but nothing is listening for it: no reader is attached to engine.getEventStream() and AsyncResolutionBatcher.onLineResult is not set. The value is in the cache; without one of those the line keeps showing as pending. Read the event stream and re-evaluate the lines it names (see the async guide), or set onLineResult to mirror resolved values into your own state. This warning appears once per batcher."));}createEventStream(){return new ReadableStream({start:e=>{this._streamController=e;},cancel:()=>{this._streamController=null;}},new CountQueuingStrategy({highWaterMark:this.highWaterMark}))}add(e){this.cleared=false;for(let t of this.pending)if(t.packageId===e.packageId&&t.queryKey===e.queryKey)return;this.pending.push(e),this.scheduled||(this.scheduled=true,queueMicrotask(()=>{try{this.flush();}catch(t){let n=d(t);console.error(`[AsyncResolutionBatcher] flush() failed unexpectedly \u2014 this should never happen; please report: ${n.format()}`);}}));}getEventStream(){return this._eventStream}get pendingCount(){return this.pending.length}get dedupCount(){let e=new Set;for(let t of this.pending)e.add(`${t.packageId}:${t.queryKey}`);return Math.max(0,this.pending.length-e.size)}get listenerCount(){return this._eventStream.locked?1:0}get workerOffloadCount(){return this.workerOffloadDispatchCount}clearAll(){this.pending=[],this.scheduled=false,this.cleared=true,this._testCaptures=null,this.onLineResult=null;try{this._streamController?.close();}catch{}this._streamController=null,this._eventStream=this.createEventStream(),this.executionPool&&(this.executionPool.clear(),this.executionPool=null),this.workerOffloadDispatchCount=0;}flush(){if(this.scheduled=false,this.cleared||this.pending.length===0)return;let e=this.pending;this.pending=[];let t=new Map;for(let a of e){let u=`${a.packageId}:${a.queryKey}`;t.set(u,a);}let n=[],i=[];for(let a of t.values())a.isError?n.push(a):i.push(a);for(let a of n)a.signal.aborted||this.notifyListeners({type:"error",queryKey:a.queryKey,packageId:a.packageId,error:a.error??new Error("Unknown async resolution error")});let s=new Set,o=[],c=[...i,...n];for(let a of c){if(a.signal.aborted)continue;o.push(a.queryKey);let u=this.dag.getAffectedLinesByDataSource(a.packageId,[a.queryKey]);for(let p of u)s.add(p);}if(s.size===0){this.notifyListeners({type:"lines-updated",lineNumbers:[],affectedQueryKeys:o});return}let l=this.topologicalSort(Array.from(s));if(l.length>or){let a=new Map;for(let u of l)a.set(u,this.lineCache.getEntryForLine(u));this.reExecuteViaWorkerPool(l,a,o).catch(u=>{let p=d(u);console.error(`[AsyncResolutionBatcher] reExecuteViaWorkerPool() failed unexpectedly: ${p.format()}`);});return}this.reExecuteMainThread(l,o);}topologicalSort(e){if(e.length<=1)return e;let t=new Map,n=new Map,i=new Map;for(let c of e)t.set(c,0),n.set(c,[]);for(let c of e){let l=this.dag.getWrites(c);for(let a of l)i.set(a,c);}for(let c of e){let l=this.dag.getDependencies(c);for(let a of l){let u=i.get(a);u!==void 0&&u!==c&&(n.get(u).push(c),t.set(c,(t.get(c)??0)+1));}}let s=[];for(let[c,l]of t)l===0&&s.push(c);if(s.length===0&&e.length>0)return [...e].sort((c,l)=>c-l);let o=[];for(;s.length>0;){let c=s.shift();o.push(c);for(let l of n.get(c)??[]){let a=(t.get(l)??1)-1;t.set(l,a),a===0&&s.push(l);}}if(o.length<e.length){let c=e.filter(l=>!o.includes(l)).sort((l,a)=>l-a);o.push(...c);}return o}async reExecuteViaWorkerPool(e,t,n){this.executionPool||(this.executionPool=new xe);let i=this.executionPool.executeBatch(e,t);if(!i){this.reExecuteMainThread(e,n,t);return}this.workerOffloadDispatchCount++;let s=await i;if(this.cleared)return;let o=[];for(let c of s){let l=t.get(c.lineNumber);if(!l||c.isPending)continue;let a=ar(c);l.result=a,this.warnIfUnwired(),this.onLineResult?.(c.lineNumber,a),o.push(c.lineNumber);}this.cleared||(o.length>0||n.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:o,affectedQueryKeys:n});}reExecuteMainThread(e,t,n){let i=[];for(let s of e){let o=n?n.get(s):this.lineCache.getEntryForLine(s);if(!o||o.bytecode.opcodes.length===0)continue;let c=this.vm.getStack().length;try{let l=d$1(o.bytecode,this.vm,void 0,void 0,{lineIndex:s,networkEnabled:this.vm.context.networkEnabled,calendar:this.vm.context.calendar});for(;this.vm.getStack().length>c;)this.vm.pop();if(l.type==="value")o.result=l.value,this.warnIfUnwired(),this.onLineResult?.(s,l.value),i.push(s);else if(l.type==="error"){let a=P(l.error.code,l.error.message);o.result=a,this.warnIfUnwired(),this.warnIfUnwired(),this.onLineResult?.(s,a),i.push(s);}}catch(l){for(;this.vm.getStack().length>c;)this.vm.pop();let a=d(l),u=P(a.code,a.message);o.result=u,this.warnIfUnwired(),this.onLineResult?.(s,u),i.push(s);}}return (i.length>0||t.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:i,affectedQueryKeys:t}),i}notifyListeners(e){if(this._testCaptures&&this._testCaptures.push(e),this._streamController)try{this._streamController.enqueue(e);}catch{}}};Se.DEFAULT_HIGH_WATER_MARK=64;var ke=Se;function ze(r,e){if(r.length>e.maxExpressionLength){let t=c.validation("EXPRESSION_TOO_LONG",`Expression exceeds max length of ${e.maxExpressionLength} characters (got ${r.length})`,{expressionLength:r.length,maxLength:e.maxExpressionLength});return {passed:false,error:{value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:t.message,engineError:t}}}return {passed:true}}function $e(r,e){let t=0,n=0,i=0;for(let o of r)o.type==="FUNC"&&t++,(o.value==="("||o.type==="LPAREN")&&(n++,i=Math.max(i,n)),(o.value===")"||o.type==="RPAREN")&&n--;let s=r.length+t*5+i*10;if(s>e.maxComplexity){let o=c.validation("EXPRESSION_TOO_COMPLEX",`Expression complexity score ${s} exceeds maximum of ${e.maxComplexity}`,{complexity:s,maxComplexity:e.maxComplexity});return {passed:false,complexityScore:s,errorMessage:o.message,engineError:o}}return {passed:true,complexityScore:s}}function de(r){return r.type==="IDENT"||r.type==="UNIT"}function _r(r){return r.type==="NUMBER"||r.type==="TO"||r.type==="IN"||r.type==="RPAREN"}function lr(r,e){let t=0;for(let n=e;n<r.length;n++)if(r[n].type==="LPAREN")t++;else if(r[n].type==="RPAREN"&&(t--,t===0))return n;return null}function Fr(r){let e=new Set;for(let t=0;t<r.length;t++){if(!de(r[t])||t>0&&r[t-1].type==="COLON"||r[t+1]?.type!=="LPAREN")continue;let n=lr(r,t+1);if(n!==null&&r[n+1]?.type==="EQUALS")for(let i=t+2;i<n;i++)de(r[i])&&e.add(r[i].value);}return e}function Ce(r){let e=[],t=[],n=Fr(r);for(let i=0;i<r.length;i++){let s=r[i];if(s.type==="GLOBAL"){if(i+2<r.length&&r[i+1].type==="COLON"&&de(r[i+2])){let o=K$1(r[i+2].value);e.push(o),i+3<r.length&&r[i+3].type==="EQUALS"&&t.push(o);}continue}if(s.type==="COLON"){if(i>0&&r[i-1].type==="GLOBAL")continue;if(i+1<r.length&&de(r[i+1])){let o=r[i+1].value;e.push(o),i+2<r.length&&r[i+2].type==="EQUALS"&&t.push(o);}}if(de(s)){if(i>0&&r[i-1].type==="COLON"||s.type==="UNIT"&&i>0&&_r(r[i-1])||n.has(s.value))continue;if(r[i+1]?.type==="LPAREN"){let c=lr(r,i+1);if(c!==null&&r[c+1]?.type==="EQUALS"){e.push(s.value),t.push(s.value);continue}}e.push(s.value);let o=r[i+1]?.type;(o==="EQUALS"||o==="PLUS_EQUALS"||o==="MINUS_EQUALS")&&t.push(s.value);}}return {reads:e,writes:t}}function Cn(r){return c$1.classifyLine(r).skip}function Tn(r,e){return c$1.findInlineSolves(r).map(n=>({start:n.start,end:n.end,expression:n.expression,lineNumber:e,columnNumber:n.columnNumber}))}var K=class{constructor(e,t,n,i){this.result=e;this.bytecode=t;this.readVariables=n;this.writeVariable=i;}},Te=class r{constructor(){this.byLine=new Map;this.count=0;}static exprKey(e){return e??""}static displayKey(e,t){return t===""?`${e}`:`${e}:${t}`}get(e,t){return this.byLine.get(e)?.get(r.exprKey(t))}getEntryForLine(e){let t=this.byLine.get(e);if(t)for(let n of t.values())return n}set(e,t,n){let i=this.byLine.get(e);i||(i=new Map,this.byLine.set(e,i));let s=r.exprKey(n);i.size>0&&!i.has(s)&&(this.count-=i.size,i.clear()),i.has(s)||this.count++,i.set(s,t);}has(e,t){return this.byLine.get(e)?.has(r.exprKey(t))??false}remove(e,t){let n=this.byLine.get(e);n&&n.delete(r.exprKey(t))&&(this.count--,n.size===0&&this.byLine.delete(e));}removeAllForLine(e){let t=this.byLine.get(e);t&&(this.count-=t.size,this.byLine.delete(e));}clearLine(e){this.removeAllForLine(e);}get size(){return this.count}clear(){this.byLine.clear(),this.count=0;}forEach(e){for(let[t,n]of this.byLine)for(let[i,s]of n)e(r.displayKey(t,i),s);}snapshotEntries(){let e=[];for(let[t,n]of this.byLine)for(let[i,s]of n)e.push({line:t,expression:i,entry:s});return e}keys(){let e=[];for(let[t,n]of this.byLine)for(let i of n.keys())e.push(r.displayKey(t,i));return e}};function je(r,e){let t=e.fields(r),n=String(t.month0+1).padStart(2,"0"),i=String(t.day).padStart(2,"0");return `${t.year}-${n}-${i}`}function zr(r,e){if(r instanceof Date)return je(r.getTime(),e);if(typeof r=="number")return Number.isFinite(r)?je(r,e):null;let t=/^(\d{4})-(\d{2})-(\d{2})/.exec(r.trim());return t?`${t[1]}-${t[2]}-${t[3]}`:null}function cr(r,e){if(r===void 0)return;if(typeof r=="function")return n=>r(new Date(n));let t=new Set;for(let n of r){let i=zr(n,e);i!==null&&t.add(i);}return n=>t.has(je(n,e))}function $r(r,e){if(!r||r.type!==e.type||r.value!==e.value)return true;let t=r.unit,n=e.unit;return t!==n}var Ne=class r{constructor(e,t){this.dag=e;this.enqueue=t;this.entries=new Map;}get size(){return this.entries.size}static idOf(e,t){return JSON.stringify([e,t])}register(e){if(!(e.intervalMs>0))return;let t=r.idOf(e.packageId,e.queryKey);if(this.entries.has(t))return;let n=setInterval(()=>{this.tick(t);},e.intervalMs);n.unref?.(),this.entries.set(t,{...e,timer:n,lastValue:null,inFlight:false});}async tick(e){let t=this.entries.get(e);if(t&&!t.inFlight){if(this.isDead(t)){this.stop(e);return}t.inFlight=true;try{let n=await t.refetch(),i=this.entries.get(e);if(!i)return;n&&$r(i.lastValue,n)&&(i.lastValue=n,this.enqueue(i.packageId,i.queryKey));}catch{}finally{let n=this.entries.get(e);n&&(n.inFlight=false);}}}isDead(e){return this.dag.getAffectedLinesByDataSource(e.packageId,[e.queryKey]).size===0}reconcile(){for(let[e,t]of this.entries)this.isDead(t)&&this.stop(e);}stop(e){let t=this.entries.get(e);t&&(clearInterval(t.timer),this.entries.delete(e));}clearAll(){for(let e of this.entries.values())clearInterval(e.timer);this.entries.clear();}};var U=class{static enable(){this.enabled=true;}static disable(){this.enabled=false;}static isEnabled(){return this.enabled}static track(e,t,n){if(!this.enabled)return {result:t(),alloc:null};let i=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,s=typeof process<"u"&&process.hrtime?process.hrtime():performance.now(),o=t(),c=typeof process<"u"&&process.hrtime?process.hrtime(s):void 0,l=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,a=c?c[0]*1e9+c[1]:(performance.now()-s)*1e6,u=i&&l?l.heapUsed-i.heapUsed:0,p={stage:e,allocCount:0,allocBytes:u,objectCounts:{},wallTimeNs:a,...n};return {result:o,alloc:p}}static generateReport(e,t){let n=[];n.push(t?`## ${t}`:"## Pipeline Allocation Report"),n.push(""),n.push(`**Runs:** ${e.length} | **Generated:** ${new Date().toISOString()}`),n.push("");let i=this.aggregate(e);if(i.length===0)return n.push("_No telemetry data._"),n.join(`
2
- `);n.push("### Per-Stage Breakdown"),n.push(""),n.push("| Stage | Count | Mean Wall (\xB5s) | Mean Alloc (bytes) | Min (\xB5s) | Max (\xB5s) | p50 (\xB5s) | p95 (\xB5s) | p99 (\xB5s) |"),n.push("|-------|:-----:|:--------------:|:------------------:|:--------:|:--------:|:--------:|:--------:|:--------:|");for(let l of i)n.push(`| ${l.stage} | ${l.count} | ${(l.meanWallTimeNs/1e3).toFixed(2)} | ${l.meanAllocBytes.toFixed(0)} | ${(l.minWallTimeNs/1e3).toFixed(2)} | ${(l.maxWallTimeNs/1e3).toFixed(2)} | ${(l.p50WallTimeNs/1e3).toFixed(2)} | ${(l.p95WallTimeNs/1e3).toFixed(2)} | ${(l.p99WallTimeNs/1e3).toFixed(2)} |`);let s=e.reduce((l,a)=>l+a.totalAllocBytes,0),o=e.reduce((l,a)=>l+a.totalWallTimeNs,0),c=e.filter(l=>l.fastPath).length;return n.push(""),n.push("### Totals"),n.push(""),n.push(`- **Total wall time:** ${(o/1e6).toFixed(2)} ms (${e.length} runs)`),n.push(`- **Total heap allocated:** ${s.toLocaleString()} bytes`),n.push(`- **Fast-path runs:** ${c}/${e.length} (${(c/e.length*100).toFixed(0)}%)`),n.push(`- **Mean per-run:** ${(o/e.length/1e3).toFixed(2)} \xB5s, ${(s/e.length).toFixed(0)} bytes`),n.join(`
3
- `)}static aggregate(e){let t=new Map;for(let i of e)for(let s of i.stages)t.has(s.stage)||t.set(s.stage,[]),t.get(s.stage).push(s);let n=[];for(let[i,s]of t){let o=s.map(a=>a.wallTimeNs).sort((a,u)=>a-u),c=s.map(a=>a.allocBytes),l=s.length;n.push({stage:i,count:l,meanAllocBytes:c.reduce((a,u)=>a+u,0)/l,meanWallTimeNs:o.reduce((a,u)=>a+u,0)/l,minWallTimeNs:o[0],maxWallTimeNs:o[o.length-1],p50WallTimeNs:We(o,50),p95WallTimeNs:We(o,95),p99WallTimeNs:We(o,99)});}return n.sort((i,s)=>i.stage.localeCompare(s.stage)),n}static createTelemetry(e,t,n=false){let i=t.reduce((o,c)=>o+c.allocBytes,0),s=t.reduce((o,c)=>o+c.wallTimeNs,0);return {expression:e,stages:t,totalAllocBytes:i,totalWallTimeNs:s,fastPath:n}}};U.enabled=false;function We(r,e){if(r.length===0)return 0;if(r.length===1)return r[0];let t=e/100*(r.length-1),n=Math.floor(t),i=Math.ceil(t);if(n===i)return r[n];let s=t-n;return r[n]*(1-s)+r[i]*s}function ur(r){let e=r[r.length-1],t=e.length>1&&e.endsWith("s")?e.slice(0,-1):e;return [...r.slice(0,-1),t].join(" ")}var we=class{constructor(){this.byKey=new Map;this.longestName=0;}get isEmpty(){return this.byKey.size===0}get maxWordCount(){return this.longestName}define(e,t,n){let i=ur(e);this.byKey.set(i,{displayName:e.join(" "),ratioText:t,baseUnit:n}),e.length>this.longestName&&(this.longestName=e.length);}match(e){let t=Math.min(e.length,this.longestName);for(let n=t;n>=1;n--){let i=this.byKey.get(ur(e.slice(0,n)));if(i!==void 0)return {definition:i,wordCount:n}}return null}clear(){this.byKey.clear(),this.longestName=0;}};function pr(r,e=82){return {name:"uom:user-unit",priority:e,shape:[{types:["NUMBER","RPAREN"]},{types:["IDENT"]}],match(t,n){if(r.isEmpty)return null;let i=t[n];if(i.type!=="NUMBER"&&i.type!=="RPAREN")return null;let s=[],o=r.maxWordCount;for(let d=n+1;d<t.length&&s.length<o&&t[d].type==="IDENT";d++)s.push(t[d].value);if(s.length===0)return null;let c=r.match(s);if(c===null||t[n+1+c.wordCount]?.type==="EQUALS")return null;let{ratioText:a,baseUnit:u}=c.definition,p=new a$8("STAR",c$9("STAR"),"*","*",i.offset,0,i.line,i.col),f=new a$8("NUMBER",c$9("NUMBER"),a,a,i.offset,0,i.line,i.col),m=new a$8("UNIT",c$9("UNIT"),u,u,i.offset,0,i.line,i.col);return {consumed:1+c.wordCount,replacement:[i,p,f,m],ruleName:"uom:user-unit"}}}}var dr="engine:call-fusion";function fr(r,e=80){return {name:dr,priority:e,shape:[{types:["IDENT"]},{types:["LPAREN"]}],match(t,n){let i=t[n];if(!i||i.type!=="IDENT"||t[n+1]?.type!=="LPAREN"||t[n-1]?.type==="COLON")return null;let s=(i.value??"").toLowerCase(),o=r.get(s);return o===void 0?null:{consumed:1,replacement:[new a$8(o,c$9(o),s,i.value,i.offset,0,i.line,i.col)],ruleName:dr}}}}var jr={january:1,jan:1,february:2,feb:2,march:3,mar:3,april:4,apr:4,may:5,june:6,jun:6,july:7,jul:7,august:8,aug:8,september:9,sep:9,sept:9,october:10,oct:10,november:11,nov:11,december:12,dec:12};function gr(r){return r===void 0||r.type!=="IDENT"&&r.type!=="UNIT"?0:jr[(r.text??r.value??"").toLowerCase()]??0}var fe=/^\d+$/;function Re(r){return r.length===4}function te(r,e,t,n,i,s){let o="datetime:month-name-date",c=q(r,e,t,n,o,i);return c!==null?c:s==="arithmetic"||e<1||e>12||r<1||r>31?null:s$1(g.DATE_NOT_A_CALENDAR_DAY,`"${r$1(n)}" is not a real date: ${j$1(r,e,t)}.`,n,`${o}:unreadable`)}function hr(r){return r.fields(r.now()).year}function mr(r=64,e=()=>b$5,t=()=>"refuse"){return {name:"datetime:month-name-date",priority:r,startTokenTypes:["NUMBER","IDENT","UNIT"],match(n,i){let s=e(),o=t(),c=n[i];if(c?.type==="NUMBER"&&fe.test(c.text??"")){let m=gr(n[i+1]);if(m===0)return null;let d=Number(c.text);if(d<1||d>31)return null;let T=n[i+2];return T?.type==="NUMBER"&&fe.test(T.text??"")&&Re(T.text??"")?te(d,m,Number(T.text),n.slice(i,i+3),s,o):te(d,m,hr(s),n.slice(i,i+2),s,o)}let l=gr(c);if(l===0)return null;let a=n[i+1];if(a?.type!=="NUMBER"||!fe.test(a.text??""))return null;if(Re(a.text??""))return te(1,l,Number(a.text),n.slice(i,i+2),s,o);let u=Number(a.text),p=n[i+2],f=n[i+3];return p?.type==="COMMA"&&f?.type==="NUMBER"&&fe.test(f.text??"")&&Re(f.text??"")?te(u,l,Number(f.text),n.slice(i,i+4),s,o):p?.type==="NUMBER"&&fe.test(p.text??"")&&Re(p.text??"")?te(u,l,Number(p.text),n.slice(i,i+3),s,o):te(u,l,hr(s),n.slice(i,i+2),s,o)}}}var Wr=30,Hr=40,Kr=50,Gr=24;function qr(r){switch(r){case a.PLUS:case a.MINUS:return Wr;case a.STAR:case a.SLASH:case a.MOD:case a.OF:return Hr;case a.CARET:return Kr;case a.PCT_ON:case a.PCT_OFF:return Gr;default:return 0}}function Qr(r){switch(r){case a.PLUS:return "plus";case a.MINUS:return "minus";case a.STAR:return "times";case a.SLASH:return "divided by";case a.MOD:return "mod";case a.CARET:return "to the power of";case a.OF:return "of";case a.PCT_ON:return "plus";case a.PCT_OFF:return "less";default:return r.toLowerCase()}}function yr(r){return r.sourceEnd??r.offset+r.value.length}var Yr=new Set([a.NUMBER,a.BIGINT,a.IDENT,a.UNIT,a.PERCENT,a.PI,a.E,a.TRUE,a.FALSE,a.DOLLAR,a.POUND,a.EURO,a.YEN,a.RUBLE,a.WON,a.CURRENCY_SYMBOL]);function Xr(r){return !Yr.has(r)}var He=class{constructor(e){this.tokens=e;this.pos=0;}peek(){return this.tokens[this.pos]}next(){return this.tokens[this.pos++]}parseAll(){let e=this.parseExpression(0);if(this.pos!==this.tokens.length)throw new Error("explain: unconsumed tokens");return e}parseExpression(e){let t=this.parseOperand();for(;;){let n=this.peek();if(!n)break;let i=qr(n.type);if(i===0||i<=e)break;this.next();let s=n.type===a.CARET?i-1:i,o=this.parseExpression(s);t={kind:"binary",op:n.type,left:t,right:o,start:t.start,end:o.end};}return t}parseOperand(){let e=this.peek();if(!e)throw new Error("explain: expected an operand");if(e.type===a.LPAREN)return this.parseGroup();let t=e.offset,n=false;for(;this.peek()&&(this.peek().type===a.PLUS||this.peek().type===a.MINUS);)this.next(),n=true;if(n&&this.peek()&&this.peek().type===a.LPAREN){let s=this.parseGroup();return {kind:"wrap",child:s,start:t,end:s.end}}let i=-1;for(;this.peek()&&!Xr(this.peek().type);)i=yr(this.next());if(i===-1)throw new Error("explain: expected an operand");return {kind:"leaf",start:t,end:i}}parseGroup(){let e=this.next(),t=this.parseExpression(0),n=this.peek();if(!n||n.type!==a.RPAREN)throw new Error("explain: unbalanced parentheses");return this.next(),{kind:"wrap",child:t,start:e.offset,end:yr(n)}}},Ke=class{constructor(e,t,n){this.source=e;this.evaluate=t;this.steps=[];this.cache=new Map;this.resultPrefix=a$9(n).display.resultPrefix;}build(e){return this.emit(e),{steps:this.steps,result:this.valueOf(e)}}emit(e){if(e.kind!=="leaf"){if(e.kind==="wrap"){this.emit(e.child);return}this.emit(e.left),this.emit(e.right),this.steps.push({description:this.describe(e),value:this.valueOf(e)});}}describe(e){let t=Qr(e.op);return e.op===a.PCT_ON||e.op===a.PCT_OFF?`${this.operand(e.right)} ${t} ${this.operand(e.left)}`:`${this.operand(e.left)} ${t} ${this.operand(e.right)}`}operand(e){return e.kind==="leaf"?this.source.slice(e.start,e.end).trim():this.render(this.valueOf(e))}valueOf(e){let t=this.cache.get(e);if(t)return t;let n=this.evaluate(this.source.slice(e.start,e.end));return this.cache.set(e,n),n}render(e){let t=c$a(e,a$a);return t.startsWith(this.resultPrefix)?t.slice(this.resultPrefix.length):t}};function Ge(r){let{expression:e,tokens:t,evaluate:n,locale:i,readings:s=[]}=r,o=a=>s.filter(u=>u.needsNote).map(u=>({description:u.note,value:a})),c=()=>{let a=n(e);return {expression:e,steps:o(a),result:a}},l;try{l=new He(t).parseAll();}catch{return c()}try{let{steps:a,result:u}=new Ke(e,n,i).build(l);return {expression:e,steps:[...o(u),...a],result:u}}catch{return c()}}var Y=class Y{constructor(e={}){this.dag=new a$2;this.lineCache=new Te;this.accumulatorNames=new Set;this.scopeManager=new b;this.resolverRegistry=new a$3;this.packageContributions=new Map;this.registeredPackages=new Map;this.callFusions=new Map;this.callFusionOwners=new Map;this.compatIndex=new ve;this.documentModel=null;this.goalSeekDepth=0;this.batchScanResults=null;this.batchParsedLines=null;this.packageCompletionItems=new Map;this.keystrokeSignal=null;this.backgroundRefreshSignal=new AbortController().signal;this.userUnits=new we;this.bytecodeCache=new Map;this.compiledFrontHalf=new Map;this.failedParses=new Map;this.pluginFunctionIndexByName=new Map;this.builderPool=[new d$2(this.pluginFunctionIndexByName),new d$2(this.pluginFunctionIndexByName),new d$2(this.pluginFunctionIndexByName),new d$2(this.pluginFunctionIndexByName)];this.builderPoolIndex=0;this.lastTelemetry=null;let{locale:t$1="en",diagnostics:n=false,config:i,packages:s,calendar:o}=e;this.localeCode=t$1,this.config=c$2(b$1,i??{}),this.dateReading=h$1(this.config.date),this.lexer=new b$2(t$1),this.registry=new b$3,this.context=x({networkEnabled:this.config.network.enabled,calendar:o}),n?(this.diagnosticPipeline=new a$4,this.timelineCollector=new b$4,this.diagnosticPipeline.register(this.timelineCollector)):this.diagnosticPipeline=new a$4,this.normalizer=new c$3;for(let[l,a]of Object.entries(c$4))this.normalizer.addPhrase(l,a);this.normalizer.register(d$3(50,l=>this.normalizer.canStartPhrase(l))),this.normalizer.register(pr(this.userUnits)),this.normalizer.register(fr(this.callFusions));let c=s??[];for(let l of c)try{this.registerPackage(l);}catch(a){let u=d(a);console.error(`[ExpressionEngine] Failed to register package "${l.name}" \u2014 skipping it and continuing construction with the remaining packages: ${u.format()}`);}if(this.registry.hasPrefix("DATETIME_LITERAL")&&this.registry.hasPrefix("DATETIME_LITERAL_UNREADABLE")){let l=()=>this.context.calendar;this.normalizer.register(t(()=>this.dateReading.order,l,()=>this.config.date.onAmbiguous)),this.normalizer.register(mr(void 0,l,()=>this.config.date.onAmbiguous));}this.parser=new a$5(this.registry,this.config.validation.maxNestingDepth,t$1,this.pluginFunctionIndexByName,this.context.calendar),this.vm=c$5(this.context.opRegistry,this.config.vm.maxStackDepth,this.config.vm.maxInstructions,void 0,this.config.vm.maxCollectionSize,this.config.vm.maxAllocatedElements,this.config.vm.maxFunctionCalls,this.config.date.maxOffsetYears,this.config.date.minOffsetYears,this.context,cr(this.config.date.holidays,this.context.calendar)),this.queryClient=c$6(),this.batcher=new ke(this.dag,this.lineCache,this.vm),this.backgroundRefresh=this.config.backgroundRefresh.enabled?new Ne(this.dag,(l,a)=>this.batcher.add({queryKey:a,packageId:l,signal:this.backgroundRefreshSignal,isError:false})):null,e.warmup===true&&this.warmUp();}setDocumentModel(e){this.documentModel=e;}getDocumentModel(){return this.documentModel}warmUp(){let e=new d$2(this.pluginFunctionIndexByName);for(let t of Y.WARMUP_EXPRESSIONS)try{this.lexer.resetExpression(t);let n=[];for(let o of this.lexer)o.type!=="COMMENT"&&n.push(o);let i=this.normalizer.normalize(n);e.reset(),this.parser.load(i),this.parser.parseExpression(0,e);let s=e.build();this.vm.reset(),d$1(s,this.vm);}catch{}this.vm.reset();}makeLineContext(e){let t=this.documentModel,n=t?null:this.batchScanResults,i=t?null:this.batchParsedLines;return {lineIndex:e,getLineResult:t?s=>t.getLineAt(s)?.result??void 0:i?s=>i[s-1]?.result??void 0:void 0,isLineBoundary:t?s=>{let o=t.getLineAt(s);return o?o.isEmpty||/^\s*#/.test(o.text):true}:n?s=>{let o=n[s-1];return o?o.classification.skip||/^\s*#/.test(o.text):true}:void 0,getLineReads:t?s=>{let o=t.getLineAt(s);if(!(!o||o.bytecodes.length===0))return o.reads}:void 0,evaluateLineWithBinding:t?(s,o,c,l)=>this.evaluateLineWithBinding(s,o,c,l):void 0,goalSeekMaxIterations:this.config.vm.maxGoalSeekIterations,networkEnabled:this.config.network.enabled,calendar:this.context.calendar,getLineText:t?s=>t.getLineAt(s)?.text:n?s=>n[s-1]?.text:void 0}}evaluateLineWithBinding(e,t,n,i){let s=this.documentModel;if(!s)return P("GOAL_SEEK_NO_DOCUMENT","Goal seek needs a document to solve against, which the single-expression entry point does not have.");if(this.goalSeekDepth>=Y.GOAL_SEEK_MAX_NESTING_DEPTH)return P("GOAL_SEEK_NESTED","A goal-seek line cannot target another goal-seek line, since each already re-runs its target many times.");let o=s.getLineAt(e);if(!o||o.bytecodes.length===0)return P("GOAL_SEEK_LINE_NOT_READY",`Line ${e} has no evaluated expression to solve (forward reference, out of range, or not an expression).`);if(o.isVariableDef)return P("GOAL_SEEK_TARGET_IS_DEFINITION",`Line ${e} defines a variable, so re-running it would overwrite that variable. Target the line that uses ${t}, not the one that sets a value.`);let c=o.bytecodes[0];this.goalSeekDepth++;try{let l=new Map([[t,n]]),a=this.vm.getStack().length;this.vm.pushCallFrame(l);try{let u=d$1(c,this.vm,void 0,void 0,this.makeLineContext(e),i);return u.type==="pending"?P("GOAL_SEEK_ASYNC_UNSUPPORTED",`Line ${e} depends on an async value (weather, stocks, currency, ...), which goal seek cannot re-run.`):u.type==="error"?P(u.error.code??"GOAL_SEEK_TARGET_ERROR",u.error.message):u.value}finally{for(this.vm.popCallFrame();this.vm.getStack().length>a;)this.vm.pop();}}catch(l){return P("GOAL_SEEK_TARGET_ERROR",d(l).message)}finally{this.goalSeekDepth--;}}frontHalfCached(e){return this.compiledFrontHalf.has(e)&&this.bytecodeCache.has(e)||this.failedParses.has(e)}clearCompiledCache(){this.bytecodeCache.clear(),this.compiledFrontHalf.clear(),this.failedParses.clear();}cacheBytecode(e,t,n){let i=this.config.performance.defaultCacheSize;if(this.bytecodeCache.size>=i){let s=this.bytecodeCache.keys().next().value;s!==void 0&&(this.bytecodeCache.delete(s),this.compiledFrontHalf.delete(s));}this.bytecodeCache.set(e,t),this.compiledFrontHalf.set(e,n);}rememberFailedParse(e,t){if(this.failedParses.size>=this.config.performance.defaultCacheSize){let n=this.failedParses.keys().next().value;n!==void 0&&this.failedParses.delete(n);}this.failedParses.set(e,t);}getEventStream(){return this.batcher.getEventStream()}getBatcher(){return this.batcher}registerPackage(e){Qt(e),this.packageContributions.has(e.name)&&(console.warn(`[ExpressionEngine] Package "${e.name}" is already registered. Unregistering the previous registration before re-registering.`),this.unregisterPackage(e.name));let t=this.compatIndex.check(e);for(let i of t)(i.severity==="error"?console.error:console.warn)(`[ExpressionEngine] Package compatibility ${i.severity} (${i.kind}): ${i.detail}`);let n={pluginFunctionIndices:[],pluginFunctionNames:[],resolverNamespaces:[],tokenCategories:[],lexerVocabulary:e.lexerVocabulary,asConverterNames:[],normalizerRuleNames:[],callFusionNames:[]};if(e.lexerVocabulary&&this.lexer.registerVocabulary(e.lexerVocabulary),e.prefixParselets)for(let[i,s]of Object.entries(e.prefixParselets))this.registry.registerPrefix(i,s);if(e.infixParselets)for(let[i,s]of Object.entries(e.infixParselets))this.registry.registerInfix(i,s);if(e.pluginFunctions)for(let[i,s]of Object.entries(e.pluginFunctions)){let o=F$1(`${e.name}:${i}`);this.context.pluginFunctions[o]=s,this.context.pluginFunctionOwners[o]=e.name,this.pluginFunctionIndexByName.set(i,o),n.pluginFunctionIndices.push(o),n.pluginFunctionNames.push(i);}if(e.asyncResolvers)for(let i of e.asyncResolvers)this.resolverRegistry.register(i),n.resolverNamespaces.push(i.namespace);if(e.phrases)for(let[i,s]of Object.entries(e.phrases))this.normalizer.addPhrase(i,s);if(e.normalizerRules)for(let i of e.normalizerRules)this.normalizer.register(i),n.normalizerRuleNames.push(i.name);if(e.callFusions)for(let[i,s]of Object.entries(e.callFusions)){let o=i.toLowerCase(),c=this.callFusionOwners.get(o);c?c.push({pkg:e.name,tokenType:s}):this.callFusionOwners.set(o,[{pkg:e.name,tokenType:s}]),this.callFusions.set(o,s),n.callFusionNames.push(o);}if(e.tokenCategories)for(let[i,s]of Object.entries(e.tokenCategories))b$6(i,s),n.tokenCategories.push(i);if(e.completionItems&&this.packageCompletionItems.set(e.name,e.completionItems),e.asConverters)for(let[i,s]of Object.entries(e.asConverters))H(i,s),n.asConverterNames.push(i);this.packageContributions.set(e.name,n),this.registeredPackages.set(e.name,e),this.compatIndex.add(e),this.clearCompiledCache();}unregisterPackage(e){let t=this.packageContributions.get(e);if(!t)return false;for(let n of t.pluginFunctionIndices)delete this.context.pluginFunctions[n],delete this.context.pluginFunctionOwners[n];for(let n of t.pluginFunctionNames)this.pluginFunctionIndexByName.delete(n);for(let n of t.resolverNamespaces)this.resolverRegistry.unregister(n);for(let n of t.tokenCategories)c$7(n);t.lexerVocabulary&&this.lexer.unregisterVocabulary(t.lexerVocabulary);for(let n of t.asConverterNames)I(n);for(let n of t.normalizerRuleNames)this.normalizer.unregister(n);for(let n of t.callFusionNames){let i=(this.callFusionOwners.get(n)??[]).filter(s=>s.pkg!==e);i.length===0?(this.callFusionOwners.delete(n),this.callFusions.delete(n)):(this.callFusionOwners.set(n,i),this.callFusions.set(n,i[i.length-1].tokenType));}return this.packageCompletionItems.delete(e),this.packageContributions.delete(e),this.registeredPackages.delete(e),this.compatIndex.rebuild(this.registeredPackages.values()),this.clearCompiledCache(),true}getConfig(){return {...this.config}}getDateReading(){return this.dateReading}readDates(e){let{tokens:t}=this.lexToTokens(e,void 0,false),n=this.normalizer.normalize(t.filter(s=>s.type!=="COMMENT")),i=[];for(let s of n){let o$1=s.type===p;if(!o$1&&s.type!==o)continue;let c=s.offset,l=s.sourceEnd??s.offset+s.text.length;i.push(this.describeDateLiteral(e.slice(c,l),c,l,s,o$1));}return i}describeDateLiteral(e,t,n,i$1,s){let o=n$1(e);if(o!==null){let a=l(o,this.dateReading.order,this.config.date.onAmbiguous,this.context.calendar),u=i(o.groups[0],o.groups[1],o.groups[2],o.separator)==="iso",p=this.dateReading.order==="auto"?o.separator==="hyphen"?"MDY":"DMY":this.dateReading.order,f=u?{order:"ISO",orderSource:"iso",locale:void 0}:{order:p,orderSource:this.dateReading.orderSource,locale:this.dateReading.locale};return a.kind==="date"?m({text:e,start:t,end:n,iso:k(a.day,a.month,a.year),...f,contested:a.alternative!==void 0,shortYear:a.shortYear,alternative:a.alternative},o.separator):m({text:e,start:t,end:n,iso:null,...f,contested:false,shortYear:false,problem:a.kind==="refuse"?a.code:void 0},o.separator,a.kind==="refuse"?a.message:void 0)}if(s){let a=i$1.fault??{code:"DATE_NOT_A_CALENDAR_DAY",message:`"${i$1.value}" is not a date this engine can read.`};return m({text:e,start:t,end:n,iso:null,order:null,orderSource:"spelled",contested:false,shortYear:false,problem:a.code},"slash",a.message)}let c=this.context.calendar.fields(Number(i$1.value)),l$1=/^\d{4}-/.test(e)?"iso":"spelled";return m({text:e,start:t,end:n,iso:k(c.day,c.month0+1,c.year),order:l$1==="iso"?"ISO":"spelled",orderSource:l$1,contested:false,shortYear:false},"slash")}getDiagnosticPipeline(){return this.diagnosticPipeline}storeLineResult(e,t,n,i,s,o){this.lineCache.set(e,new K(t,n,i,s.length>0?s[0]:null),o);}executeAndStore(e,t,n,i,s,o,c,l){let a=this.vm.getStack().length,u=new AbortController,p=()=>u.abort();this.keystrokeSignal?.addEventListener("abort",p,{once:true}),a$6.localControllerCreated("executeAndStore"),this.keystrokeSignal&&a$6.signalLinked("executeAndStore"),this.vm.activeSignal=u.signal,this.vm.abortCurrent=()=>{a$6.signalUnlinked("executeAndStore"),this.keystrokeSignal?.removeEventListener("abort",p),u.abort();},a$7(this.queryClient);let f=d$1(e,this.vm,c,l,this.makeLineContext(t));for(;this.vm.getStack().length>a;)this.vm.pop();if(f.type==="pending"){this.resolveAsync(f),this.dag.registerLineDataSourceDependency(t,f.packageId||o,[f.queryKey]);let m=O(f.queryKey);return this.storeLineResult(t,m,e,i,s,n),m}if(f.type==="error")throw this.keystrokeSignal?.removeEventListener("abort",p),f.error;return this.keystrokeSignal?.removeEventListener("abort",p),this.dag.registerLine(t,i,s),this.storeLineResult(t,f.value,e,i,s,n),f.value}executeRaw(e,t=-1){let n=this.vm.getStack().length,i=new AbortController,s=()=>i.abort();this.keystrokeSignal?.addEventListener("abort",s,{once:true}),a$6.localControllerCreated("executeRaw"),this.keystrokeSignal&&a$6.signalLinked("executeRaw"),this.vm.activeSignal=i.signal,this.vm.abortCurrent=()=>{a$6.signalUnlinked("executeRaw"),this.keystrokeSignal?.removeEventListener("abort",s),i.abort();},a$7(this.queryClient);let o=d$1(e,this.vm,void 0,void 0,this.makeLineContext(t));for(;this.vm.getStack().length>n;)this.vm.pop();return o.type!=="pending"&&this.keystrokeSignal?.removeEventListener("abort",s),o}async resolveAsync(e){let{queryKey:t,resolver:n,packageId:i,signal:s}=e,o=i||"_engine";try{if(await n,s.aborted){a$6.staleDataDiscarded(t,"signal aborted after resolve");return}this.batcher.add({queryKey:t,packageId:o,signal:s,isError:!1});}catch(c){if(s.aborted){a$6.staleDataDiscarded(t,"signal aborted after error");return}let l=c instanceof Error?c:new Error(String(c));this.batcher.add({queryKey:t,packageId:o,signal:s,isError:true,error:l});}}registerBackgroundRefresh(e){this.backgroundRefresh&&(e.refetchIntervalMs===void 0||!e.refetch||this.backgroundRefresh.register({packageId:e.packageId||"_engine",queryKey:e.queryKey,intervalMs:e.refetchIntervalMs,refetch:e.refetch}));}getBackgroundRefreshCount(){return this.backgroundRefresh?.size??0}parseDocument(e,t={inputType:"markdown"}){let n=this.config.performance.maxDocumentLines;if(b$7(e,n)>n)throw c.execution("DOCUMENT_TOO_LARGE",`This document has more than ${n.toLocaleString("en-US")} lines, which is the most the engine will process in one pass`,{maxLines:n});this.userUnits.isEmpty||this.clearCompiledCache(),this.userUnits.clear(),this.resetAccumulators();let i=this.lexer.scanDocument(e),s=this.processScanResults(i),o={lines:s,totalLines:s.length,errors:[]};for(let l of s){l.error&&o.errors.push(`Line ${l.lineNumber}: ${l.error}`);for(let a of l.inlineSolves)a.error&&o.errors.push(`Line ${l.lineNumber}: ${a.error}`);}if(t.includeDiagnostics??false){let l=this.diagnosticPipeline.collectReports();l.length>0&&(o.diagnostics=l[0].toJSON());}return o}evaluateLines(e){this.userUnits.isEmpty||this.clearCompiledCache(),this.userUnits.clear(),this.resetAccumulators();let t=e.join(`
4
- `),n=this.lexer.scanDocument(t);return this.processScanResults(n)}processScanResults(e){let t=[],n=this.batchScanResults,i=this.batchParsedLines;this.batchScanResults=e,this.batchParsedLines=t;try{for(let s of e){let o=s.text,c=s.lineNumber,l=s.startOffset,a=s.endOffset,u=s.classification.skip,p=s.inlineSolves.map(d=>({start:d.start,end:d.end,expression:d.expression,lineNumber:c,columnNumber:d.columnNumber})),f=p.length>0,m={lineNumber:c,text:o,startPosition:l,endPosition:a,isEmpty:u,hasInlineSolves:f,inlineSolves:p,expression:null,result:null,error:null};if(s.error)m.error=s.error.message;else if(!u){let d=o.trim().startsWith(":");if(f&&!d)for(let T of p)try{T.result=this.evaluateLine(c,T.expression);}catch(b){let R=b instanceof Error?b.message:String(b);T.error=R;}else {let T=s.classification.contentOffset,R=(T===void 0?o:o.slice(T-l)).trim();if(R)try{let L=this.evaluateLineWithPreTokenized(c,R,s.tokens);m.expression=R,m.result=L[0];}catch(L){let G=L instanceof Error?L.message:String(L);m.error=G;}}}t.push(m);}}finally{this.batchScanResults=n,this.batchParsedLines=i;}return t}evaluateLineWithPreTokenized(e,t,n){let i=[],s=false;for(let o of n)(o.type==="LPAREN"||o.type==="RPAREN")&&(s=true),i.push(o);return [this.evaluateWithTokens(e,t,i,s)]}parseExpression(e,t,n,i=true){this.parser.setBuilder(e),this.parser.load(t,this.config.validation.autoBalanceParens?n:false),this.parser.parseExpression(0);let s=this.parser.peek();if(s){if(s.type==="EQUALS"&&!this.parser.peekAt(1))return;for(let o=i?t.length-1:0;o>=1;o--){if(t[o].type!=="COLON"||o+1>=t.length)continue;let c$1=true;for(let l=0;l<o;l++){let a=t[l].type;if(a!=="NUMBER"&&a!=="COLON"){c$1=false;break}}if(c$1){let l=t.slice(0,o+2).map(a=>a.value).join("");throw c.parsing("INVALID_TIME_LITERAL",`"${l}" is not a valid time`,{tokenType:t[o].type,tokenValue:l})}e.reset();try{this.parseExpression(e,t.slice(o+1),n,!1);return}catch{}}throw c.parsing({code:"UNEXPECTED_TRAILING_TOKEN",message:`Unexpected token after expression: "${s.value}"`,context:{tokenType:s.type,tokenValue:s.value},span:{start:s.offset,end:s.sourceEnd??s.offset+s.text.length,line:s.line,col:s.col}})}}compileAdHoc(e){let t=new d$2(this.pluginFunctionIndexByName);return this.parseExpression(t,e),t.build()}executeSymbolicTolerant(e,t=-1){let n=d$1(e,this.vm,void 0,void 0,this.makeLineContext(t),true);if(n.type==="error")throw n.error;if(n.type==="pending")throw c.execution("THEREFORE_ASYNC_UNSUPPORTED",`"=>" doesn't support expressions that call an async operation (weather/stocks/currency).`);return n.value}simplifySymbolically(e,t=-1){return this.executeSymbolicTolerant(this.compileAdHoc(e),t)}parseFactorChain(e){if(e.length===0||e.length%2===0)return null;let t=[];for(let n=0;n<e.length;n++)if(n%2===0){if(e[n].type!=="IDENT"&&e[n].type!=="UNIT")return null;t.push(e[n].value);}else if(e[n].type!=="STAR")return null;return t}solveEquation(e,t=-1){let n=[];for(let c of e.factorNames){let l=this.vm.getVar(c);if(l===void 0)return P("EQUATION_FACTOR_UNDEFINED",`Cannot solve for "${e.variable}": "${c}" is not yet defined.`);if(l.type!==7)return P("EQUATION_FACTOR_NOT_MATRIX",`Cannot solve for "${e.variable}": "${c}" must be a Matrix (got a different value type).`);n.push(l);}let i=n[0].value;for(let c=1;c<n.length;c++){let l=_(i,n[c].value);if(l.type===13)return l;i=l.value;}let s=da(i);if(s.type===13)return s;let o=this.executeSymbolicTolerant(e.rhsProgram,t);return o.type!==7?P("EQUATION_RHS_NOT_MATRIX",`Cannot solve for "${e.variable}": the right-hand side must be a Matrix.`):_(s.value,o.value)}tryDefineUserUnit(e){if(e.length<5||e[0].type!=="NUMBER"||Number(e[0].value)!==1)return null;let t=1;e[t].type==="STAR"&&t++;let n=[];for(;t<e.length&&e[t].type==="IDENT";)n.push(e[t].value),t++;if(n.length===0||e[t]?.type!=="EQUALS"||(t++,e[t]?.type!=="NUMBER"))return null;let i=e[t];if(t++,e[t]?.type!=="UNIT")return null;let s=e[t];return t++,t!==e.length?null:(this.userUnits.define(n,i.value,s.value),this.clearCompiledCache(),t$1(`${n.join(" ")} defined`))}tryCompoundAssignment(e,t=-1){if(e.length<2)return null;let n$1=e[0],i=e[1],s=n$1.type==="IDENT"||n$1.type==="UNIT",o=i.type==="PLUS_EQUALS"||i.type==="MINUS_EQUALS";if(!s||!o)return null;let c$1=e.slice(2);if(c$1.length===0)throw c.parsing("COMPOUND_ASSIGN_REQUIRES_EXPRESSION",`"${n$1.value} ${i.value}" needs an expression on the right, e.g. "${n$1.value} ${i.value} 10".`);let l=n$1.value;this.accumulatorNames.add(l),this.vm.getVar(l)===void 0&&this.vm.setVar(l,n(0));let a=i.type==="PLUS_EQUALS"?{type:"PLUS",text:"+"}:{type:"MINUS",text:"-"},u=[b$8("IDENT",l,[n$1]),b$8(a.type,a.text,[i]),b$8("LPAREN","(",[i]),...c$1,b$8("RPAREN",")",[i])],p=d$1(this.compileAdHoc(u),this.vm,void 0,void 0,this.makeLineContext(t),false);if(p.type==="error")throw p.error;if(p.type==="pending")throw c.execution("COMPOUND_ASSIGN_ASYNC_UNSUPPORTED","A running total (+= / -=) cannot use an async operation (weather/stocks/currency) on its right-hand side.");return this.vm.setVar(l,p.value),p.value}resetAccumulators(){for(let e of this.accumulatorNames)this.vm.deleteVar(e);return this.accumulatorNames}trySymbolicGrammar(e,t=-1){if(e.length===0)return null;if(e[e.length-1].type==="THEREFORE"){let a=e.slice(0,-1);if(a.length===0)throw c.parsing("THEREFORE_REQUIRES_EXPRESSION",'"=>" needs an expression or variable name before it.');if(a.length===1&&(a[0].type==="IDENT"||a[0].type==="UNIT")){let u=a[0].value,p=this.vm.getEquation(u),f=this.vm.getScalarEquation(u);if(p){let m=this.solveEquation(p,t);if(!(m.type===13&&m.value==="EQUATION_FACTOR_NOT_MATRIX")||!f)return m}if(f)return this.solveScalarEquation(f,t)}return this.simplifySymbolically(a,t)}if(b$9(e))return this.simplifySymbolically(e,t);if(e[0].type==="COLON"||e[0].type==="GLOBAL"||e[0].type==="GOAL_SEEK")return null;let i=e.findIndex(a=>a.type==="EQUALS");if(i===-1)return null;let s=this.parseFactorChain(e.slice(0,i));if(s===null)return this.tryStoreScalarEquation(e,i);let o=e.slice(i+1);if(s.length===1){let a=this.simplifySymbolically(o,t);return this.vm.setVar(s[0],a),a}let c$1=s[s.length-1],l=s.slice(0,-1);return this.vm.defineEquation(c$1,l,this.compileAdHoc(o)),this.vm.defineScalarEquation(c$1,this.compileAdHoc(e.slice(0,i)),this.compileAdHoc(o)),t$1(`${c$1} stored as an equation \u2014 solve with "${c$1} =>"`)}tryStoreScalarEquation(e,t){if(e[1]?.type==="LPAREN"||t===0||t===e.length-1)return null;let n=e.slice(0,t),i=e.slice(t+1);if(i.some(c=>c.type==="EQUALS"))return null;let s=this.equationUnknowns(n,i);if(s.length!==1)return null;let o=s[0];return this.vm.defineScalarEquation(o,this.compileAdHoc(n),this.compileAdHoc(i)),t$1(`${o} stored as an equation \u2014 solve with "${o} =>"`)}equationUnknowns(e,t){let n=[];for(let i of [...e,...t])i.type!=="IDENT"&&i.type!=="UNIT"||this.vm.getVar(i.value)===void 0&&(this.vm.hasUserFunction(i.value)||n.includes(i.value)||n.push(i.value));return n}solveScalarEquation(e,t=-1){let n=this.executeSymbolicTolerant(e.lhsProgram,t),i=this.executeSymbolicTolerant(e.rhsProgram,t);return i$1(n,i,e.variable)}lexToTokens(e,t,n=true){let i=[],s=false;if(n&&!t&&this.frontHalfCached(e))return {tokens:i,hasParens:s,compiled:true};this.lexer.resetExpression(e);for(let o of this.lexer)o.type!=="COMMENT"&&((o.type==="LPAREN"||o.type==="RPAREN")&&(s=true),i.push(o),t?.(o));return {tokens:i,hasParens:s,compiled:false}}prepareExpression(e,t,n,i,s=-1){let o=this.bytecodeCache.get(e);if(o&&!i){let b=this.compiledFrontHalf.get(e);if(b)return {kind:"ready",normalizedTokens:b.normalizedTokens,reads:b.reads,writes:b.writes,program:o,cached:true}}let c=i?void 0:this.failedParses.get(e),l;if(c)l=c.normalizedTokens;else {let b=ze(e,this.config.validation);if(!b.passed)return {kind:"error",stage:"length",error:b.error.engineError};let R=t.filter(G=>G.type!=="COMMENT");if(R.length===0)return {kind:"empty"};l=this.normalizer.normalize(R,i);let L=$e(l,this.config.validation);if(!L.passed)return {kind:"error",stage:"complexity",error:L.engineError,normalizedTokens:l}}let a,u=null;try{if(a=this.tryDefineUserUnit(l),a===null){let b=this.tryCompoundAssignment(l,s);b!==null&&(a=b,u=Ce(l));}a===null&&(a=this.trySymbolicGrammar(l,s));}catch(b){let{reads:R,writes:L}=Ce(l);return {kind:"error",stage:"parse",error:d(b),reads:R,writes:L,normalizedTokens:l}}if(a!==null)return {kind:"symbolic-solve",normalizedTokens:l,value:a,reads:u?.reads,writes:u?.writes};if(c)return {kind:"error",stage:"parse",error:c.error,reads:c.reads,writes:c.writes,normalizedTokens:l};let{reads:p,writes:f}=Ce(l);if(o)return this.compiledFrontHalf.set(e,{normalizedTokens:l,reads:p,writes:f}),{kind:"ready",normalizedTokens:l,reads:p,writes:f,program:o,cached:true};let m=this.builderPool[this.builderPoolIndex++%this.builderPool.length];m.reset();let d$1,T=null;try{let b=U.track("parser",()=>(this.parseExpression(m,l,n),m.build()));d$1=b.result,T=b.alloc;}catch(b){let R=d(b);return this.rememberFailedParse(e,{error:R,normalizedTokens:l,reads:p,writes:f}),{kind:"error",stage:"parse",error:R,reads:p,writes:f,normalizedTokens:l}}return this.cacheBytecode(e,d$1,{normalizedTokens:l,reads:p,writes:f}),{kind:"ready",normalizedTokens:l,reads:p,writes:f,program:d$1,cached:false,parserAlloc:T}}preflightAsync(e,t,n,i,s,o){if(!(t.hasAsync||this.resolverRegistry.size>0))return {kind:"proceed"};let c=new AbortController,l=()=>c.abort();this.keystrokeSignal?.addEventListener("abort",l,{once:true}),a$6.localControllerCreated("preflightAsync"),this.keystrokeSignal&&a$6.signalLinked("preflightAsync");let a=c.signal,u=this.resolverRegistry.preflightAll(e,t,"_engine",a,this.queryClient,this.config.network.enabled);if(u){this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.dag.registerLineDataSourceDependency(n,u.packageId||"_engine",[u.queryKey]),this.registerBackgroundRefresh(u);let p=O(u.queryKey);return this.storeLineResult(n,p,t,s,o,i),{kind:"pending",value:p}}return this.keystrokeSignal?.removeEventListener("abort",l),{kind:"proceed"}}evaluateWithTokens(e,t,n$1,i){let s=this.prepareExpression(t,n$1,i,void 0,e);if(s.kind==="empty"){let p=n(0);return this.lineCache.set(e,new K(p,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),t),p}if(s.kind==="error")throw s.error;if(s.kind==="symbolic-solve")return this.storeLineResult(e,s.value,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},s.reads??[],s.writes??[],t),s.value;let{normalizedTokens:o,reads:c,writes:l,program:a}=s,u=this.preflightAsync(o,a,e,t,c,l);return u.kind==="pending"?u.value:this.executeAndStore(a,e,t,c,l,"_engine")}evaluateLine(e,t){let n=this.evaluateLineWithDebug(e,t);if(n.error)throw n.engineError?n.engineError:c.execution("EVALUATION_ERROR",n.error,{lineNumber:e});return l$1(n.value)}evaluateLineWithDebug(e,t,n="expression"){let i=t.match(/^s`([^`]*)`$/);if(i){let s=i[1];return {...this.evaluateExpressionWithDiagnostic(s,e,n),inlineSolve:{start:0,end:t.length,expression:s,lineNumber:e,columnNumber:1}}}return this.evaluateExpressionWithDiagnostic(t,e,n)}addDiagnosticStage(e,t,n,i,s,o,c,l,a){e.push({stage:t,label:n,icon:i,colorClass:s,stepNumber:o,elapsedNs:c,skipped:l,output:a});}evaluateExpressionWithDiagnostic(e,t,n$1="expression"){let i=this.diagnosticPipeline,s=i.hasCollectors,o=this.timelineCollector?.parseletMatchCount??0,c$1=U.isEnabled(),l=[],a=[],u=0,p=ze(e,this.config.validation);if(!p.passed)return s&&this.addDiagnosticStage(a,"safety_length","Safety: Length","\u{1F6E1}\uFE0F","validate",2,u,false,{type:"safety_length",passed:false,expressionLength:e.length,maxLength:this.config.validation.maxExpressionLength,errorMessage:p.error.error}),{...p.error,debug:void 0,diagnostic:void 0};s&&(i.firePipelineStart({type:c$8.PipelineStart,elapsedNs:0,expression:e,inputType:n$1}),this.addDiagnosticStage(a,"pipeline_start","Pipeline Start","\u25B6","pipeline",1,u,false,{type:"pipeline_start",expression:e,inputType:n$1}),this.addDiagnosticStage(a,"safety_length","Safety: Length","\u{1F6E1}\uFE0F","validate",2,u,false,{type:"safety_length",passed:true,expressionLength:e.length,maxLength:this.config.validation.maxExpressionLength}));let f=s?y=>{i.fireTokenEmitted({type:c$8.TokenEmitted,elapsedNs:0,expression:e,token:{type:y.type,value:y.value,offset:y.offset||0,line:y.line||t,col:y.col||0}});}:void 0,m=U.track("lexer",()=>this.lexToTokens(e,f)),d$1=m.result.tokens,T=m.result.hasParens,b=m.result.compiled;if(c$1&&m.alloc&&l.push(m.alloc),s){let y={};for(let O of d$1)y[O.type]=(y[O.type]||0)+1;this.addDiagnosticStage(a,"lexer","Lexer","\u{1F524}","lexer",3,u,false,{type:"lexer",tokenCount:d$1.length,tokenTypes:y,hasParens:T,locale:this.localeCode,tokens:[...d$1]});let A=[];for(let O=0;O<d$1.length;O++){let se=d$1[O];if(se.type==="INLINE_SOLVE_START"){let M=-1;for(let W=O+1;W<d$1.length;W++)if(d$1[W].type==="BACKTICK_OPEN"){M=W;break}if(M>O){let kr=d$1.slice(O+1,M).map(Sr=>Sr.value).join("");A.push({startTokenIndex:O,endTokenIndex:M,expression:kr,columnNumber:se.col||1}),O=M;}}}this.addDiagnosticStage(a,"line_classification","Line Classification","\u{1F4CB}","classify",3.5,u,false,{type:"line_classification",classification:"expression",skip:false,hasInlineSolve:A.length>0,inlineSolveSpans:A});}if(!b&&d$1.length===0){let y=n(0);return this.lineCache.set(t,new K(y,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:0,totalOpcodes:0}),{value:y,tokens:d$1,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}let R=0,L=[],G=new Map,br=s?y=>{R++,L.push(y),G.set(y.rule,(G.get(y.rule)||0)+1),i.fireTokenFused({type:c$8.TokenFused,elapsedNs:0,expression:e,ruleName:y.rule,sourceTokenCount:y.sourceTokens.length,fusedTokenType:y.fusedToken.type,fusedTokenValue:y.fusedToken.value});}:void 0;s&&this.normalizer.ruleCount>0&&i.fireNormalizerStart({type:c$8.NormalizerStart,elapsedNs:0,expression:e,inputTokenCount:d$1.length});let D=this.bytecodeCache.get(e);s&&!D&&this.parser.setDiagnosticPipeline(i,e);let v=this.prepareExpression(e,d$1,T,br,t);b&&v.kind==="ready"&&(d$1=v.normalizedTokens),c$1&&v.kind==="ready"&&v.parserAlloc&&l.push(v.parserAlloc),s&&!D&&this.parser.setDiagnosticPipeline(void 0,"");let k=v.kind==="empty"?d$1:v.normalizedTokens??d$1;if(s&&(this.normalizer.ruleCount>0?(i.fireNormalizerEnd({type:c$8.NormalizerEnd,elapsedNs:0,expression:e,outputTokenCount:k.length,fusionsCount:R}),this.addDiagnosticStage(a,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,false,{type:"normalizer",inputTokenCount:d$1.length,outputTokenCount:k.length,fusions:L,rulesApplied:[...G.entries()].map(([y,A])=>({rule:y,count:A})),tokens:[...k],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(k)})):this.addDiagnosticStage(a,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,true,{type:"normalizer",inputTokenCount:d$1.length,outputTokenCount:d$1.length,fusions:[],rulesApplied:[],tokens:[...d$1],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(d$1)})),v.kind==="empty"||v.kind==="error"&&v.stage==="length"){if(s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:v.kind==="empty",totalTokens:d$1.length,totalOpcodes:0}),v.kind==="empty"){let y=n(0);return this.lineCache.set(t,new K(y,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),{value:y,tokens:d$1,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}return {value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:v.error.message,engineError:v.error,debug:void 0,diagnostic:void 0}}let re=$e(k,this.config.validation);if(v.kind==="error"&&v.stage==="complexity")return s&&(this.addDiagnosticStage(a,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:false,complexityScore:re.complexityScore??0,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:k.length,functionCalls:0,nestingDepth:0},errorMessage:re.errorMessage}),i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d$1.length,totalOpcodes:0})),{value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:re.errorMessage,engineError:re.engineError,debug:void 0,diagnostic:void 0};if(s&&this.addDiagnosticStage(a,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:true,complexityScore:re.complexityScore??k.length,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:k.length,functionCalls:0,nestingDepth:0}}),v.kind==="symbolic-solve"){s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:0});let y={opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false};return this.storeLineResult(t,v.value,y,v.reads??[],v.writes??[],e),{value:v.value,tokens:k,program:y,debug:void 0,diagnostic:void 0}}let ge=v.reads??[],ne=v.writes??[];if(s&&(this.addDiagnosticStage(a,"readwrite","Read/Write","\u{1F4CB}","readwrite",6,u,false,{type:"readwrite",reads:ge,writes:ne,isAssignment:ne.length>0}),this.addDiagnosticStage(a,"cache_check","Cache Check","\u{1F4BE}","cache",7,u,false,{type:"cache_check",hit:!!D,cacheSize:this.bytecodeCache.size,cacheKey:e}),D?i.fireCacheHit({type:c$8.CacheHit,elapsedNs:0,expression:e,cache:"bytecode",key:e}):i.fireCacheMiss({type:c$8.CacheMiss,elapsedNs:0,expression:e,cache:"bytecode",key:e})),v.kind==="error"&&v.stage==="parse")return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d$1.length,totalOpcodes:0}),{value:n(0),tokens:k,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:v.error.message,engineError:v.error,debug:void 0,diagnostic:void 0};if(v.kind!=="ready")throw c.internal({code:"UNEXPECTED_ERROR",message:"Internal error: prepareExpression() returned an unexpected variant after all other cases were handled"});let x=v.program;s&&(this.addDiagnosticStage(a,"parser","Parser","\u{1F333}","parser",8,u,!!D,{type:"parser",parselets:[],uniqueParseletTypes:[],astDepth:0}),this.addDiagnosticStage(a,"compiler","Compiler","\u2699\uFE0F","compiler",9,u,!!D,{type:"compiler",opcodeCount:x.opcodes.length,numberConstants:x.numbers.length,stringConstants:x.strings.length,hasAsync:x.hasAsync,cached:!!D}),i.fireBytecodeBuilt({type:c$8.BytecodeBuilt,elapsedNs:0,expression:e,opcodesLength:x.opcodes.length,numbersLength:x.numbers.length,stringsLength:x.strings.length,isCached:!!D}));let Er=x.hasAsync||this.resolverRegistry.size>0,ie=this.preflightAsync(k,x,t,e,ge,ne);if(s&&(ie.kind==="pending"?this.addDiagnosticStage(a,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"pending",pendingQueryKey:ie.value.value,resolverCount:this.resolverRegistry.size,skippedGuard:true}):Er?this.addDiagnosticStage(a,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"sync",resolverCount:this.resolverRegistry.size,skippedGuard:false}):this.addDiagnosticStage(a,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,true,{type:"async_preflight",path:"sync",resolverCount:0,skippedGuard:true})),ie.kind==="pending")return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length}),{value:ie.value,tokens:k,program:x,debug:void 0,diagnostic:s?this.buildDiagnosticResult(a,ie.value,k,x,null):void 0};let xr=s&&this.config.diagnostic.vmTraceEnabled===true,N;try{let y=U.track("vm",()=>this.executeAndStore(x,t,e,ge,ne,"_engine",xr?i:void 0,e),{cacheHit:!!D});N=y.result,c$1&&y.alloc&&l.push(y.alloc);}catch(y){let A=d(y);return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:d$1.length,totalOpcodes:x.opcodes.length}),{value:n(0),tokens:k,program:x,error:A.message,engineError:A,debug:void 0,diagnostic:void 0}}let he=N.type===12;if(s){let y=he?"pending":String(N.value??""),A=he?"Pending":N.unit?"Uom":"Number";this.addDiagnosticStage(a,"vm_execute","VM Execute","\u26A1","vm",11,u,false,{type:"vm_execute",totalInstructions:x.opcodes.length,stackDepth:this.vm.getStack().length,resultType:A,resultValue:y,isPending:he});}if(he)return s&&i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length}),{value:N,tokens:k,program:x,debug:void 0,diagnostic:s?this.buildDiagnosticResult(a,N,k,x,null):void 0};if(c$1&&l.length>0&&(this.lastTelemetry=U.createTelemetry(e,l,!!D)),s&&(this.addDiagnosticStage(a,"dag_registration","DAG Registration","\u{1F517}","dag",12,u,false,{type:"dag_registration",readsRegistered:ge,writesRegistered:ne,dataSourcesRegistered:[]}),this.addDiagnosticStage(a,"linecache","Line Cache","\u{1F4E6}","cache",13,u,false,{type:"linecache",lineNumber:t,expression:e,stored:true}),this.addDiagnosticStage(a,"result","Result","\u2713","result",14,u,false,{type:"result",rawValue:String(N.value),formattedValue:String(N.value),valueType:N.type===0?"Number":"Value",unit:N.unit}),i.fireVmHalt({type:c$8.VmHalt,elapsedNs:0,expression:e,result:N?{type:N.type,value:N.value,unit:N.unit}:void 0}),this.addDiagnosticStage(a,"pipeline_end","Pipeline End","\u23F9","pipeline",15,u,false,{type:"pipeline_end",success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length,cacheHit:!!D}),i.firePipelineEnd({type:c$8.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:d$1.length,totalOpcodes:x.opcodes.length})),s){let A=i.collectReports()[0]?.toJSON(),O=A;if(A){let se=A.parselets.slice(o),M={};for(let W of se)M[W.parseletCategory]=(M[W.parseletCategory]??0)+1;O={...A,parselets:se,summary:{...A.summary,totalParselets:Object.keys(M).length,parseCategories:M}};}return {value:N,tokens:k,program:x,debug:O,diagnostic:this.buildDiagnosticResult(a,N,k,x,null)}}return {value:N,tokens:k,program:x}}buildDiagnosticResult(e,t,n,i,s){return {stages:e,value:t,tokens:n,program:i,error:s,dagSnapshot:this.dag.getSnapshot(),cacheSnapshot:this.getCacheSnapshot(),batcherMetrics:this.getBatcherMetrics(),checkpoints:this.getCheckpoints()}}reEvaluateLine(e,t){let n=this.lineCache.get(e,t);if(!n)return;let i=this.bytecodeCache.get(t);if(!i)return;if(n.bytecode.hasAsync||this.resolverRegistry.size>0){let c=new AbortController,l=()=>c.abort();this.keystrokeSignal?.addEventListener("abort",l,{once:true}),a$6.localControllerCreated("reEvaluateLine preflight"),this.keystrokeSignal&&a$6.signalLinked("reEvaluateLine preflight");let a=c.signal,u=this.resolverRegistry.preflightAll([],n.bytecode,"_engine",a,this.queryClient,this.config.network.enabled);if(u)return this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.registerBackgroundRefresh(u),O(u.queryKey);this.keystrokeSignal?.removeEventListener("abort",l);}let s=this.executeRaw(i,e);if(s.type==="pending")return this.resolveAsync(s),O(s.queryKey);if(s.type==="error")throw s.error;let o=s.value;return n.result=o,o}getDag(){return this.dag}getLineCache(){return this.lineCache}getBytecodeCache(){return this.bytecodeCache}getVM(){return this.vm}getContext(){return this.context}getScopeManager(){return this.scopeManager}getLexer(){return this.lexer}getNormalizer(){return this.normalizer}getPackageCompletionItems(){let e=[];for(let t of this.packageCompletionItems.values())e.push(...t);return e}getParseletRegistry(){return {prefix:this.registry.getAllPrefix(),infix:this.registry.getAllInfix()}}tokenizeForClassification(e){this.lexer.resetExpression(e);let n=Array.from(this.lexer).filter(i=>i.type!=="COMMENT");return n.length===0?[]:this.normalizer.normalize(n)}getParser(){return this.parser}isDiagnosticMode(){return this.diagnosticPipeline.hasCollectors}setKeystrokeSignal(e){e?a$6.keystrokeSignalSet(e.aborted):a$6.keystrokeSignalCleared(),this.keystrokeSignal=e;}getCacheSnapshot(){let e=[];for(let[o,c]of this.bytecodeCache)e.push({expression:o,opcodesLength:c.opcodes.length,numbersLength:c.numbers.length,stringsLength:c.strings.length,hasAsync:c.hasAsync});let t=[];for(let o of this.lineCache.keys()){let c=o.indexOf(":"),l=c>0?parseInt(o.slice(0,c),10)||0:parseInt(o,10)||0,a=c>0?o.slice(c+1):void 0,u=a!==void 0?this.lineCache.get(l,a):this.lineCache.getEntryForLine(l);u&&t.push({key:o,lineNumber:l,resultType:String(u.result?.type??""),resultValue:String(u.result?.value??""),reads:u.readVariables??[],writeVar:u.writeVariable??null});}let s=this.queryClient.getQueryCache().getAll().map(o=>{let c=o.state.status==="success"?"resolved":o.state.status==="error"?"error":"in_flight";return {packageId:o.queryKey[0]??"unknown",resolvedCount:o.state.status==="success"?1:0,inFlightCount:o.state.status!=="success"&&o.state.status!=="error"?1:0,errorCount:o.state.status==="error"?1:0,entries:[{key:o.queryKey.join(":"),status:c}]}});return {bytecode:e,lineCache:t,asyncCache:s}}getBatcherMetrics(){return {pendingCount:this.batcher.pendingCount,dedupCount:this.batcher.dedupCount,workerOffloadCount:this.batcher.workerOffloadCount,listenerCount:this.batcher.listenerCount}}getCheckpoints(){let t=this.vm.checkpointer;return t?t.getAllCheckpoints().map(i=>({lineNumber:i.lineNumber,variables:Object.keys(i.variables),variableCount:Object.keys(i.variables).length})):[]}getLastTelemetry(){return this.lastTelemetry}evaluateExpression(e){return this.evaluateLine(-1,e)}explainLine(e){let{tokens:t}=this.lexToTokens(e,void 0,false),n=t.filter(s=>s.type!=="COMMENT"),i=this.normalizer.normalize(n);return Ge({expression:e,tokens:i,evaluate:s=>this.evaluateIsolated(s),locale:this.localeCode,readings:this.readDates(e)})}evaluateIsolated(e){let{tokens:t,hasParens:n$1}=this.lexToTokens(e),i=this.prepareExpression(e,t,n$1,void 0,-1);if(i.kind==="empty")return n(0);if(i.kind==="error")throw i.error;if(i.kind==="symbolic-solve")return i.value;let s=this.executeRaw(i.program,-1);if(s.type==="error")throw s.error;if(s.type==="pending")throw c.execution("EXPLAIN_ASYNC_UNSUPPORTED",`A derivation cannot be built for a line that resolves data asynchronously: "${e}"`,{expression:e});return s.value}compileExpression(e){let t=this.lexToTokens(e),{hasParens:n}=t,i=this.prepareExpression(e,t.tokens,n),s=t.compiled&&i.kind==="ready"?i.normalizedTokens:t.tokens;if(i.kind==="empty")return {program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:[],reads:[],writes:[]};if(i.kind==="error")throw i.stage==="parse"&&(i.reads?.length||i.writes?.length)?new b$a(i.error.category,{code:i.error.code,message:i.error.message,expected:i.error.expected,found:i.error.found,suggestion:i.error.suggestion,recoverable:i.error.recoverable,span:i.error.span,cause:i.error.cause,context:{...i.error.context,reads:i.reads??[],writes:i.writes??[]}}):i.error;return i.kind==="symbolic-solve"?{program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:i.normalizedTokens,reads:i.reads??[],writes:i.writes??[]}:{program:i.program,tokens:s,reads:i.reads,writes:i.writes}}tryCompileExpression(e){try{return this.tryCompileExpressionUnguarded(e)}catch{return false}}tryCompileExpressionUnguarded(e){let{tokens:t,hasParens:n}=this.lexToTokens(e);return this.prepareExpression(e,t,n).kind!=="error"}executeCached(e,t=-1){if(e.opcodes.length===0)return n(0);let n$1=this.executeRaw(e,t);if(n$1.type==="pending")return this.resolveAsync(n$1),O(n$1.queryKey);if(n$1.type==="error")throw n$1.error;return n$1.value}evaluateNumber(e){let t=e.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&this.vm.getVar(t)===void 0)return NaN;try{let n=this.evaluateLine(-1,e);return n.isFault()?NaN:n.toNumber()}catch{return NaN}}clear(){this.batcher.clearAll(),this.backgroundRefresh?.clearAll(),this.queryClient.clear(),b$b()===this.queryClient&&a$7(null),this.dag.clear(),this.lineCache.clear(),this.scopeManager.clear(),this.clearCompiledCache(),this.vm.reset(),this.userUnits.clear(),this.accumulatorNames.clear(),this.lastTelemetry=null;}toJSON(){let e=this.dag.getSnapshot(),t=new Set;for(let a of Object.keys(e.dataSourceDeps)){let u=Number(a);Number.isNaN(u)||t.add(u);}let n=this.lineCache.snapshotEntries(),i=new Map;for(let{line:a,entry:u}of n){let p=t.has(a)||u.bytecode.hasAsync;p&&t.add(a);let f=u.writeVariable;if(f){let m=i.get(f);(!m||a>=m.line)&&i.set(f,{line:a,async:p});}}let s={};for(let[a,u]of this.vm.getVariableEntries())if(u.type!==12&&!i.get(a)?.async)try{s[a]=Me(u,`variable "${a}"`);}catch(p){if(p instanceof b$a&&p.code===V.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw p}let o=this.vm.getUserFunctionDefs().map(Ue),c=[];for(let{line:a,expression:u,entry:p}of n){if(t.has(a)||p.result.type===12)continue;let f;try{f=Me(p.result,`line ${a}`);}catch(m){if(m instanceof b$a&&m.code===V.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw m}c.push({line:a,expression:u,result:f,bytecode:ue(p.bytecode),reads:p.readVariables.slice(),writeVar:p.writeVariable});}let l=Array.from(this.bytecodeCache.entries()).map(([a,u])=>({expression:a,program:ue(u)}));return {format:ee,version:Q,engineVersion:a$1,locale:this.localeCode,variables:s,userFunctions:o,lineCache:c,bytecodeCache:l}}static fromJSON(e,t={}){rr(e);let n=t.locale??e.locale??"en",i=new Y({locale:n,diagnostics:t.diagnostics??false,config:t.config,packages:t.packages,calendar:t.calendar});return i.restoreSnapshot(e),i}restoreSnapshot(e){for(let[t,n]of Object.entries(e.variables))this.vm.setVar(t,Be(n));for(let t of e.userFunctions){let n=_e(t);this.vm.defineUserFunction(n.name,n.params,n.program);}for(let t of e.lineCache){let n=new K(Be(t.result),pe(t.bytecode),t.reads.slice(),t.writeVar);this.lineCache.set(t.line,n,t.expression),this.dag.registerLine(t.line,t.reads,t.writeVar?[t.writeVar]:[]);}for(let{expression:t,program:n}of e.bytecodeCache)this.bytecodeCache.set(t,pe(n));}evaluateIncremental(e,t){let n$1=this.dag.getAffectedLinesInOrder(e);this.vm.setVar(e,n(t));let i=new Map;for(let s of n$1){let o=this.lineCache.getEntryForLine(s);if(!o||o.bytecode.opcodes.length===0)continue;let c=this.executeRaw(o.bytecode,s);if(c.type==="pending"){this.resolveAsync(c);continue}if(c.type==="error"){let a=P(c.error.code,c.error.message);i.set(s,a),o.result=a;continue}let l=c.value;i.set(s,l),o.result=l;}return i}};Y.GOAL_SEEK_MAX_NESTING_DEPTH=1,Y.WARMUP_EXPRESSIONS=["1 + 2 * 3","10.5 / 2 - 0.25","50% of 200","3 kg + 400 g","sqrt(144) + max(1, 2)","1 < 2 && 3 >= 3","half of 250",'"text" + "joined"'];var vr=Y;export{Jr as a,Or as b,Qt as c,ee as d,Q as e,V as f,cn as g,Fe as h,ke as i,ze as j,$e as k,Ce as l,Cn as m,Tn as n,vr as o};//# sourceMappingURL=chunk-7ODHPWQC.js.map
5
- //# sourceMappingURL=chunk-7ODHPWQC.js.map