solve-engine 2.24.0 → 2.26.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 (258) hide show
  1. package/dist/{BytecodeBuilder-aqVa7Plx.d.cts → BytecodeBuilder-DSWKZi4f.d.cts} +11 -9
  2. package/dist/{BytecodeBuilder-aqVa7Plx.d.ts → BytecodeBuilder-DSWKZi4f.d.ts} +11 -9
  3. package/dist/CalendarBackend-MdS3Bb4P.d.cts +181 -0
  4. package/dist/CalendarBackend-MdS3Bb4P.d.ts +181 -0
  5. package/dist/{Configuration-DnzYPmoK.d.cts → Configuration-BxriK9Kw.d.cts} +63 -4
  6. package/dist/{Configuration-DnzYPmoK.d.ts → Configuration-BxriK9Kw.d.ts} +63 -4
  7. package/dist/DateCalendar-B85t6Vk6.d.ts +90 -0
  8. package/dist/DateCalendar-CUGI1fT4.d.cts +90 -0
  9. package/dist/{EngineError-D1kXsjIj.d.cts → EngineError-C-kBwYlN.d.cts} +33 -4
  10. package/dist/{EngineError-D1kXsjIj.d.ts → EngineError-C-kBwYlN.d.ts} +33 -4
  11. package/dist/{FormattingSettings-bRKjU7wI.d.ts → FormattingSettings-ByO-4wiM.d.cts} +14 -0
  12. package/dist/{FormattingSettings-bRKjU7wI.d.cts → FormattingSettings-CvCzAfsz.d.ts} +14 -0
  13. package/dist/{Lexer-CqagTewQ.d.ts → Lexer-DhGhoAa2.d.cts} +96 -37
  14. package/dist/{Lexer-CCHFDcgP.d.cts → Lexer-DqtnZMC5.d.ts} +96 -37
  15. package/dist/{PackageCompatibility-CeAPVHZr.d.cts → PackageCompatibility-CNiTtC6S.d.cts} +1 -1
  16. package/dist/{PackageCompatibility-Bq82y0ZN.d.ts → PackageCompatibility-fj_f7uqC.d.ts} +1 -1
  17. package/dist/{PackageRegistry-B9-7fJGH.d.cts → PackageRegistry-BHBCFswo.d.cts} +377 -15
  18. package/dist/{PackageRegistry-CDEgfhT_.d.ts → PackageRegistry-CNZUwWHJ.d.ts} +377 -15
  19. package/dist/{Parselet-4oH5OuRt.d.cts → Parselet-DF3864la.d.cts} +26 -4
  20. package/dist/{Parselet-BwDqKFfK.d.ts → Parselet-Dgymjxzd.d.ts} +26 -4
  21. package/dist/{Token-CbP_OutD.d.cts → Token-D8f7yaz1.d.cts} +17 -0
  22. package/dist/{Token-CbP_OutD.d.ts → Token-D8f7yaz1.d.ts} +17 -0
  23. package/dist/{TokenNormalizer-OTPS0Otq.d.ts → TokenNormalizer-IF7nPRMp.d.ts} +46 -27
  24. package/dist/{TokenNormalizer-MXaKLJ_m.d.cts → TokenNormalizer-Pe3_390t.d.cts} +46 -27
  25. package/dist/{ScopeManager-BQBhlDAu.d.ts → VMBuiltins-CZiZRKn-.d.ts} +92 -10
  26. package/dist/{ScopeManager-DrXB3Nvm.d.cts → VMBuiltins-kv4rr0y5.d.cts} +92 -10
  27. package/dist/{VMCheckpoints-C5jC92o3.d.ts → VMCheckpoints-DXze6ypg.d.ts} +3 -3
  28. package/dist/{VMCheckpoints-BK32PTl2.d.cts → VMCheckpoints-yun4ocSv.d.cts} +3 -3
  29. package/dist/{Value-Ds3Gy07C.d.cts → Value-BYHw-x7q.d.cts} +57 -1
  30. package/dist/{Value-Ds3Gy07C.d.ts → Value-BYHw-x7q.d.ts} +57 -1
  31. package/dist/{WorkerError-DaNWQFp1.d.cts → WorkerError-BLZyNq6M.d.cts} +1 -1
  32. package/dist/{WorkerError-CVQbs6_D.d.ts → WorkerError-CfBJYueR.d.ts} +1 -1
  33. package/dist/chunk-2SYYKQ4Q.cjs +2 -0
  34. package/dist/chunk-2SYYKQ4Q.cjs.map +1 -0
  35. package/dist/chunk-6EYKVQT3.cjs +2 -0
  36. package/dist/chunk-6EYKVQT3.cjs.map +1 -0
  37. package/dist/chunk-7RC6RBS6.cjs +2 -0
  38. package/dist/chunk-7RC6RBS6.cjs.map +1 -0
  39. package/dist/chunk-AZX4NTYN.cjs +3 -0
  40. package/dist/chunk-AZX4NTYN.cjs.map +1 -0
  41. package/dist/{chunk-PTQCHMYA.js → chunk-BCR53EIL.js} +2 -2
  42. package/dist/{chunk-PTQCHMYA.js.map → chunk-BCR53EIL.js.map} +1 -1
  43. package/dist/chunk-BLJ6E577.js +2 -0
  44. package/dist/chunk-BLJ6E577.js.map +1 -0
  45. package/dist/{chunk-CMZSK6FY.cjs → chunk-C5GEMKUY.cjs} +3 -3
  46. package/dist/{chunk-CMZSK6FY.cjs.map → chunk-C5GEMKUY.cjs.map} +1 -1
  47. package/dist/chunk-CL7DM2FX.js +2 -0
  48. package/dist/chunk-CL7DM2FX.js.map +1 -0
  49. package/dist/chunk-CQLCTKMX.cjs +2 -0
  50. package/dist/chunk-CQLCTKMX.cjs.map +1 -0
  51. package/dist/chunk-CQY23OF5.cjs +5 -0
  52. package/dist/chunk-CQY23OF5.cjs.map +1 -0
  53. package/dist/chunk-D4VBWPWN.js +2 -0
  54. package/dist/chunk-D4VBWPWN.js.map +1 -0
  55. package/dist/chunk-E4HAKNBQ.cjs +2 -0
  56. package/dist/chunk-E4HAKNBQ.cjs.map +1 -0
  57. package/dist/{chunk-GP4H5OIT.js → chunk-ESZNJQ2C.js} +3 -3
  58. package/dist/{chunk-GP4H5OIT.js.map → chunk-ESZNJQ2C.js.map} +1 -1
  59. package/dist/{chunk-IJMNVBIS.js → chunk-FAO6DQ74.js} +2 -2
  60. package/dist/chunk-FAO6DQ74.js.map +1 -0
  61. package/dist/{chunk-2VE4OW4A.cjs → chunk-FDKTESBC.cjs} +2 -2
  62. package/dist/{chunk-2VE4OW4A.cjs.map → chunk-FDKTESBC.cjs.map} +1 -1
  63. package/dist/{chunk-RN3ISTM3.cjs → chunk-G2V33LFM.cjs} +2 -2
  64. package/dist/{chunk-RN3ISTM3.cjs.map → chunk-G2V33LFM.cjs.map} +1 -1
  65. package/dist/chunk-GJZIJK2Q.cjs +2 -0
  66. package/dist/chunk-GJZIJK2Q.cjs.map +1 -0
  67. package/dist/chunk-GQM6ICDM.js +2 -0
  68. package/dist/chunk-GQM6ICDM.js.map +1 -0
  69. package/dist/chunk-GVL3ZMS7.cjs +2 -0
  70. package/dist/chunk-GVL3ZMS7.cjs.map +1 -0
  71. package/dist/chunk-GXO7TSXQ.cjs +3 -0
  72. package/dist/chunk-GXO7TSXQ.cjs.map +1 -0
  73. package/dist/{chunk-OMHRBKAT.js → chunk-HANGBVEE.js} +2 -2
  74. package/dist/{chunk-OMHRBKAT.js.map → chunk-HANGBVEE.js.map} +1 -1
  75. package/dist/chunk-J4K72CQN.js +2 -0
  76. package/dist/chunk-J4K72CQN.js.map +1 -0
  77. package/dist/chunk-LE6WZLJ4.js +2 -0
  78. package/dist/chunk-LE6WZLJ4.js.map +1 -0
  79. package/dist/chunk-LMZDTQS5.js +3 -0
  80. package/dist/chunk-LMZDTQS5.js.map +1 -0
  81. package/dist/chunk-LQIRBP4Q.js +2 -0
  82. package/dist/chunk-LQIRBP4Q.js.map +1 -0
  83. package/dist/{chunk-UXR7JIPX.js → chunk-LTUYWJGO.js} +2 -2
  84. package/dist/{chunk-UXR7JIPX.js.map → chunk-LTUYWJGO.js.map} +1 -1
  85. package/dist/chunk-MCU7UYKG.js +3 -0
  86. package/dist/{chunk-7EP36NXE.js.map → chunk-MCU7UYKG.js.map} +1 -1
  87. package/dist/chunk-MTN53APQ.js +5 -0
  88. package/dist/chunk-MTN53APQ.js.map +1 -0
  89. package/dist/chunk-OPKJ2WWB.cjs +3 -0
  90. package/dist/chunk-OPKJ2WWB.cjs.map +1 -0
  91. package/dist/chunk-QQHHZPEW.cjs +2 -0
  92. package/dist/chunk-QQHHZPEW.cjs.map +1 -0
  93. package/dist/chunk-RRUGQ6DM.js +2 -0
  94. package/dist/chunk-RRUGQ6DM.js.map +1 -0
  95. package/dist/chunk-S3ODNMJS.js +2 -0
  96. package/dist/chunk-S3ODNMJS.js.map +1 -0
  97. package/dist/{chunk-CDNJZBM3.cjs → chunk-SE6ZCGZ5.cjs} +2 -2
  98. package/dist/{chunk-CDNJZBM3.cjs.map → chunk-SE6ZCGZ5.cjs.map} +1 -1
  99. package/dist/chunk-TC23XEAV.js +2 -0
  100. package/dist/chunk-TC23XEAV.js.map +1 -0
  101. package/dist/{chunk-MWWAKZOD.cjs → chunk-TMQ37JQY.cjs} +3 -3
  102. package/dist/{chunk-MWWAKZOD.cjs.map → chunk-TMQ37JQY.cjs.map} +1 -1
  103. package/dist/chunk-TPPM4QSS.cjs +2 -0
  104. package/dist/chunk-TPPM4QSS.cjs.map +1 -0
  105. package/dist/chunk-VB6QMU2W.js +3 -0
  106. package/dist/chunk-VB6QMU2W.js.map +1 -0
  107. package/dist/chunk-VQO54ZMA.js +2 -0
  108. package/dist/chunk-VQO54ZMA.js.map +1 -0
  109. package/dist/chunk-Y7XRA2EV.js +2 -0
  110. package/dist/chunk-Y7XRA2EV.js.map +1 -0
  111. package/dist/{chunk-5IJD5L3O.cjs → chunk-YBQOQTVL.cjs} +2 -2
  112. package/dist/chunk-YBQOQTVL.cjs.map +1 -0
  113. package/dist/chunk-YG7UWQFV.js +2 -0
  114. package/dist/chunk-YG7UWQFV.js.map +1 -0
  115. package/dist/chunk-YS2OW75C.cjs +2 -0
  116. package/dist/chunk-YS2OW75C.cjs.map +1 -0
  117. package/dist/chunk-ZC2NPRLO.js +3 -0
  118. package/dist/chunk-ZC2NPRLO.js.map +1 -0
  119. package/dist/chunk-ZDJTDFTR.cjs +2 -0
  120. package/dist/chunk-ZDJTDFTR.cjs.map +1 -0
  121. package/dist/chunk-ZE5KKMBV.cjs +2 -0
  122. package/dist/chunk-ZE5KKMBV.cjs.map +1 -0
  123. package/dist/chunk-ZSLVLMO5.cjs +2 -0
  124. package/dist/chunk-ZSLVLMO5.cjs.map +1 -0
  125. package/dist/constants.cjs +1 -1
  126. package/dist/constants.d.cts +1 -1
  127. package/dist/constants.d.ts +1 -1
  128. package/dist/constants.js +1 -1
  129. package/dist/engine.cjs +1 -1
  130. package/dist/engine.d.cts +15 -13
  131. package/dist/engine.d.ts +15 -13
  132. package/dist/engine.js +1 -1
  133. package/dist/errors.cjs +1 -1
  134. package/dist/errors.d.cts +3 -3
  135. package/dist/errors.d.ts +3 -3
  136. package/dist/errors.js +1 -1
  137. package/dist/format.cjs +1 -1
  138. package/dist/format.d.cts +4 -3
  139. package/dist/format.d.ts +4 -3
  140. package/dist/format.js +1 -1
  141. package/dist/index.cjs +1 -1
  142. package/dist/index.cjs.map +1 -1
  143. package/dist/index.d.cts +16 -14
  144. package/dist/index.d.ts +16 -14
  145. package/dist/index.js +1 -1
  146. package/dist/index.js.map +1 -1
  147. package/dist/language.d.cts +13 -12
  148. package/dist/language.d.ts +13 -12
  149. package/dist/lexer.cjs +1 -1
  150. package/dist/lexer.cjs.map +1 -1
  151. package/dist/lexer.d.cts +9 -8
  152. package/dist/lexer.d.ts +9 -8
  153. package/dist/lexer.js +1 -1
  154. package/dist/lexer.js.map +1 -1
  155. package/dist/normalizer.cjs +1 -1
  156. package/dist/normalizer.d.cts +3 -3
  157. package/dist/normalizer.d.ts +3 -3
  158. package/dist/normalizer.js +1 -1
  159. package/dist/packages.cjs +1 -1
  160. package/dist/packages.d.cts +12 -11
  161. package/dist/packages.d.ts +12 -11
  162. package/dist/packages.js +1 -1
  163. package/dist/parser.cjs +1 -1
  164. package/dist/parser.d.cts +6 -5
  165. package/dist/parser.d.ts +6 -5
  166. package/dist/parser.js +1 -1
  167. package/dist/{pipeline-69q2tsLE.d.cts → pipeline-BYkKNpql.d.cts} +1 -1
  168. package/dist/{pipeline-DTqGLPsV.d.ts → pipeline-Cl7KW8CB.d.ts} +1 -1
  169. package/dist/resolvers.d.cts +3 -3
  170. package/dist/resolvers.d.ts +3 -3
  171. package/dist/temporal.cjs +2 -0
  172. package/dist/temporal.cjs.map +1 -0
  173. package/dist/temporal.d.cts +201 -0
  174. package/dist/temporal.d.ts +201 -0
  175. package/dist/temporal.js +2 -0
  176. package/dist/temporal.js.map +1 -0
  177. package/dist/testing.cjs +2 -2
  178. package/dist/testing.cjs.map +1 -1
  179. package/dist/testing.d.cts +13 -12
  180. package/dist/testing.d.ts +13 -12
  181. package/dist/testing.js +1 -1
  182. package/dist/testing.js.map +1 -1
  183. package/dist/uom.cjs +1 -1
  184. package/dist/uom.d.cts +3 -3
  185. package/dist/uom.d.ts +3 -3
  186. package/dist/uom.js +1 -1
  187. package/dist/vm.cjs +1 -1
  188. package/dist/vm.cjs.map +1 -1
  189. package/dist/vm.d.cts +9 -57
  190. package/dist/vm.d.ts +9 -57
  191. package/dist/vm.js +1 -1
  192. package/dist/vm.js.map +1 -1
  193. package/dist/worker.cjs +2 -2
  194. package/dist/worker.cjs.map +1 -1
  195. package/dist/worker.d.cts +36 -14
  196. package/dist/worker.d.ts +36 -14
  197. package/dist/worker.js +2 -2
  198. package/dist/worker.js.map +1 -1
  199. package/package.json +16 -5
  200. package/dist/chunk-2BXNZM3G.js +0 -2
  201. package/dist/chunk-2BXNZM3G.js.map +0 -1
  202. package/dist/chunk-2JSNWYYA.cjs +0 -3
  203. package/dist/chunk-2JSNWYYA.cjs.map +0 -1
  204. package/dist/chunk-3SHWTGTP.js +0 -2
  205. package/dist/chunk-3SHWTGTP.js.map +0 -1
  206. package/dist/chunk-5GL4SAVH.cjs +0 -2
  207. package/dist/chunk-5GL4SAVH.cjs.map +0 -1
  208. package/dist/chunk-5IJD5L3O.cjs.map +0 -1
  209. package/dist/chunk-72N3ZRVE.cjs +0 -2
  210. package/dist/chunk-72N3ZRVE.cjs.map +0 -1
  211. package/dist/chunk-7EP36NXE.js +0 -3
  212. package/dist/chunk-A4JV7HRB.js +0 -3
  213. package/dist/chunk-A4JV7HRB.js.map +0 -1
  214. package/dist/chunk-AUOE7MFI.cjs +0 -2
  215. package/dist/chunk-AUOE7MFI.cjs.map +0 -1
  216. package/dist/chunk-BDF4VCQX.js +0 -3
  217. package/dist/chunk-BDF4VCQX.js.map +0 -1
  218. package/dist/chunk-D2Q2VFJ6.js +0 -2
  219. package/dist/chunk-D2Q2VFJ6.js.map +0 -1
  220. package/dist/chunk-DA7M6H63.cjs +0 -2
  221. package/dist/chunk-DA7M6H63.cjs.map +0 -1
  222. package/dist/chunk-ELQQKZN3.cjs +0 -3
  223. package/dist/chunk-ELQQKZN3.cjs.map +0 -1
  224. package/dist/chunk-F7QIBC4B.cjs +0 -3
  225. package/dist/chunk-F7QIBC4B.cjs.map +0 -1
  226. package/dist/chunk-HQ7BKXG7.js +0 -2
  227. package/dist/chunk-HQ7BKXG7.js.map +0 -1
  228. package/dist/chunk-IHAZL4EF.cjs +0 -2
  229. package/dist/chunk-IHAZL4EF.cjs.map +0 -1
  230. package/dist/chunk-IJMNVBIS.js.map +0 -1
  231. package/dist/chunk-IPSOWFCA.js +0 -2
  232. package/dist/chunk-IPSOWFCA.js.map +0 -1
  233. package/dist/chunk-LM6ZQUEU.js +0 -2
  234. package/dist/chunk-LM6ZQUEU.js.map +0 -1
  235. package/dist/chunk-LTJV3VJE.cjs +0 -2
  236. package/dist/chunk-LTJV3VJE.cjs.map +0 -1
  237. package/dist/chunk-NUF66H57.js +0 -5
  238. package/dist/chunk-NUF66H57.js.map +0 -1
  239. package/dist/chunk-PWWQZFAE.js +0 -2
  240. package/dist/chunk-PWWQZFAE.js.map +0 -1
  241. package/dist/chunk-RE6AIU6Y.js +0 -3
  242. package/dist/chunk-RE6AIU6Y.js.map +0 -1
  243. package/dist/chunk-RECRD45C.cjs +0 -5
  244. package/dist/chunk-RECRD45C.cjs.map +0 -1
  245. package/dist/chunk-RENO2AWO.js +0 -2
  246. package/dist/chunk-RENO2AWO.js.map +0 -1
  247. package/dist/chunk-RMCN5WFO.cjs +0 -2
  248. package/dist/chunk-RMCN5WFO.cjs.map +0 -1
  249. package/dist/chunk-S46R5QZP.cjs +0 -2
  250. package/dist/chunk-S46R5QZP.cjs.map +0 -1
  251. package/dist/chunk-UPH22K2T.cjs +0 -2
  252. package/dist/chunk-UPH22K2T.cjs.map +0 -1
  253. package/dist/chunk-UY3ID6JF.cjs +0 -2
  254. package/dist/chunk-UY3ID6JF.cjs.map +0 -1
  255. package/dist/chunk-WFOQRPA6.js +0 -2
  256. package/dist/chunk-WFOQRPA6.js.map +0 -1
  257. package/dist/chunk-XFJABR3B.js +0 -2
  258. package/dist/chunk-XFJABR3B.js.map +0 -1
@@ -1,3 +1,3 @@
1
- 'use strict';var chunkTLG7VZRX_cjs=require('./chunk-TLG7VZRX.cjs'),chunkELQQKZN3_cjs=require('./chunk-ELQQKZN3.cjs');var b=new Set(["AED","AFN","ALL","AMD","ANG","AOA","ARS","AUD","AWG","AZN","BAM","BBD","BDT","BGN","BHD","BIF","BMD","BND","BOB","BOV","BRL","BSD","BTN","BWP","BYN","BZD","CAD","CDF","CHE","CHF","CHW","CLF","CLP","CNY","COP","COU","CRC","CUP","CVE","CZK","DJF","DKK","DOP","DZD","EGP","ERN","ETB","EUR","FJD","FKP","GBP","GEL","GHS","GIP","GMD","GNF","GTQ","GYD","HKD","HNL","HTG","HUF","IDR","ILS","INR","IQD","IRR","ISK","JMD","JOD","JPY","KES","KGS","KHR","KMF","KPW","KRW","KWD","KYD","KZT","LAK","LBP","LKR","LRD","LSL","LYD","MAD","MDL","MGA","MKD","MMK","MNT","MOP","MRU","MUR","MVR","MWK","MXN","MXV","MYR","MZN","NAD","NGN","NIO","NOK","NPR","NZD","OMR","PAB","PEN","PGK","PHP","PKR","PLN","PYG","QAR","RON","RSD","RUB","RWF","SAR","SBD","SCR","SDG","SEK","SGD","SHP","SLE","SOS","SRD","SSP","STN","SVC","SYP","SZL","THB","TJS","TMT","TND","TOP","TRY","TTD","TWD","TZS","UAH","UGX","USD","USN","UYI","UYU","UYW","UZS","VED","VES","VND","VUV","WST","XAF","XCD","XCG","XOF","XPF","YER","ZAR","ZMW","ZWG"]);function O(N){return b.has(N.toUpperCase())}var D={API_ERROR:"CURRENCY_API_ERROR",UNKNOWN_CODE:"UNKNOWN_CURRENCY_CODE",CRYPTO_API_ERROR:"CRYPTO_PRICE_API_ERROR"},a=class a{constructor(){this.baseTables=new Map;}isCryptoCode(t){return Object.prototype.hasOwnProperty.call(a.CRYPTO_IDS,t.toUpperCase())}async getRate(t,e,r){let n=t.toUpperCase(),s=e.toUpperCase();if(this.isCryptoCode(n)||this.isCryptoCode(s))return this.getCryptoRate(n,s,r);let{signal:R,cleanup:l}=chunkTLG7VZRX_cjs.a(r,a.FETCH_TIMEOUT_MS,"Currency API fetch");try{let u=new URLSearchParams({base:n}),i=await fetch(`https://api.frankfurter.dev/v2/rates?${u.toString()}`,{signal:R});if(!i.ok)throw chunkELQQKZN3_cjs.c.external(D.API_ERROR,`Currency API returned ${i.status}`,{status:i.status});let c=await i.json(),C=Array.isArray(c)?Object.fromEntries(c.filter(o=>{if(typeof o!="object"||o===null)return !1;let d=o;return typeof d.quote=="string"&&typeof d.rate=="number"}).map(o=>[o.quote.toUpperCase(),o.rate])):c.rates??{};if(C[s]===void 0)throw chunkELQQKZN3_cjs.c.validation(D.UNKNOWN_CODE,`Unknown currency: ${s}`,{code:s});return this.baseTables.set(n,{fetchedAt:Date.now(),rates:{...C,[n]:1}}),C[s]}finally{l();}}async getCryptoRate(t,e,r){let{signal:n,cleanup:s}=chunkTLG7VZRX_cjs.a(r,a.FETCH_TIMEOUT_MS,"Crypto price API fetch");try{let R=this.isCryptoCode(t),l=this.isCryptoCode(e),u;if(R&&l){let i=a.CRYPTO_IDS[t],c=a.CRYPTO_IDS[e],C=await this.fetchCoinGeckoPrices([i,c],"usd",n),o=C[i]?.usd,d=C[c]?.usd;if(typeof o!="number")throw chunkELQQKZN3_cjs.c.validation(D.UNKNOWN_CODE,`Unknown currency: ${t}`,{code:t});if(typeof d!="number")throw chunkELQQKZN3_cjs.c.validation(D.UNKNOWN_CODE,`Unknown currency: ${e}`,{code:e});u=o/d;}else if(R){let i=a.CRYPTO_IDS[t],c=e.toLowerCase(),o=(await this.fetchCoinGeckoPrices([i],c,n))[i]?.[c];if(typeof o!="number")throw chunkELQQKZN3_cjs.c.validation(D.UNKNOWN_CODE,`Unknown currency: ${e}`,{code:e});u=o;}else {let i=a.CRYPTO_IDS[e],c=t.toLowerCase(),o=(await this.fetchCoinGeckoPrices([i],c,n))[i]?.[c];if(typeof o!="number")throw chunkELQQKZN3_cjs.c.validation(D.UNKNOWN_CODE,`Unknown currency: ${t}`,{code:t});u=1/o;}return this.baseTables.set(t,{fetchedAt:Date.now(),rates:{[t]:1,[e]:u}}),u}finally{s();}}async fetchCoinGeckoPrices(t,e,r){let n=new URLSearchParams({ids:t.join(","),vs_currencies:e}),s=await fetch(`https://api.coingecko.com/api/v3/simple/price?${n.toString()}`,{signal:r});if(!s.ok)throw chunkELQQKZN3_cjs.c.external(D.CRYPTO_API_ERROR,`Crypto price API returned ${s.status}`,{status:s.status});return s.json()}primeRates(t,e){let r=t.toUpperCase();this.baseTables.set(r,{fetchedAt:Date.now(),rates:{...e,[r]:1}});}clearRates(){this.baseTables.clear();}getRateSync(t,e){let r=t.toUpperCase(),n=e.toUpperCase();if(r===n)return 1;let s=Date.now();for(let R of this.baseTables.values()){if(s-R.fetchedAt>a.RATE_FRESHNESS_MS)continue;let l=R.rates[r],u=R.rates[n];if(l&&u)return u/l}return null}async convert(t,e,r){let n=await this.getRate(e,r);return t*n}getAllRates(){let t=Date.now(),e={},r=false;for(let[n,s]of this.baseTables)if(!(t-s.fetchedAt>a.RATE_FRESHNESS_MS))for(let[R,l]of Object.entries(s.rates))e[`${n}:${R}`]=l,r=true;return r?e:null}hasRates(){return this.getAllRates()!==null}convertSync(t,e,r){let n=this.getRateSync(e,r);return n===null?null:t*n}isCurrency(t){return O(t)||this.isCryptoCode(t)}};a.RATE_FRESHNESS_MS=900*1e3,a.CRYPTO_IDS={BTC:"bitcoin",ETH:"ethereum",SOL:"solana",XRP:"ripple",ADA:"cardano",DOGE:"dogecoin",DOT:"polkadot"},a.FETCH_TIMEOUT_MS=1e4;var f=a,p=new f,g=p;
2
- exports.a=f;exports.b=p;exports.c=g;//# sourceMappingURL=chunk-MWWAKZOD.cjs.map
3
- //# sourceMappingURL=chunk-MWWAKZOD.cjs.map
1
+ 'use strict';var chunkTLG7VZRX_cjs=require('./chunk-TLG7VZRX.cjs'),chunkGXO7TSXQ_cjs=require('./chunk-GXO7TSXQ.cjs');var b=new Set(["AED","AFN","ALL","AMD","ANG","AOA","ARS","AUD","AWG","AZN","BAM","BBD","BDT","BGN","BHD","BIF","BMD","BND","BOB","BOV","BRL","BSD","BTN","BWP","BYN","BZD","CAD","CDF","CHE","CHF","CHW","CLF","CLP","CNY","COP","COU","CRC","CUP","CVE","CZK","DJF","DKK","DOP","DZD","EGP","ERN","ETB","EUR","FJD","FKP","GBP","GEL","GHS","GIP","GMD","GNF","GTQ","GYD","HKD","HNL","HTG","HUF","IDR","ILS","INR","IQD","IRR","ISK","JMD","JOD","JPY","KES","KGS","KHR","KMF","KPW","KRW","KWD","KYD","KZT","LAK","LBP","LKR","LRD","LSL","LYD","MAD","MDL","MGA","MKD","MMK","MNT","MOP","MRU","MUR","MVR","MWK","MXN","MXV","MYR","MZN","NAD","NGN","NIO","NOK","NPR","NZD","OMR","PAB","PEN","PGK","PHP","PKR","PLN","PYG","QAR","RON","RSD","RUB","RWF","SAR","SBD","SCR","SDG","SEK","SGD","SHP","SLE","SOS","SRD","SSP","STN","SVC","SYP","SZL","THB","TJS","TMT","TND","TOP","TRY","TTD","TWD","TZS","UAH","UGX","USD","USN","UYI","UYU","UYW","UZS","VED","VES","VND","VUV","WST","XAF","XCD","XCG","XOF","XPF","YER","ZAR","ZMW","ZWG"]);function O(N){return b.has(N.toUpperCase())}var D={API_ERROR:"CURRENCY_API_ERROR",UNKNOWN_CODE:"UNKNOWN_CURRENCY_CODE",CRYPTO_API_ERROR:"CRYPTO_PRICE_API_ERROR"},a=class a{constructor(){this.baseTables=new Map;}isCryptoCode(t){return Object.prototype.hasOwnProperty.call(a.CRYPTO_IDS,t.toUpperCase())}async getRate(t,e,r){let n=t.toUpperCase(),s=e.toUpperCase();if(this.isCryptoCode(n)||this.isCryptoCode(s))return this.getCryptoRate(n,s,r);let{signal:R,cleanup:l}=chunkTLG7VZRX_cjs.a(r,a.FETCH_TIMEOUT_MS,"Currency API fetch");try{let u=new URLSearchParams({base:n}),i=await fetch(`https://api.frankfurter.dev/v2/rates?${u.toString()}`,{signal:R});if(!i.ok)throw chunkGXO7TSXQ_cjs.c.external(D.API_ERROR,`Currency API returned ${i.status}`,{status:i.status});let c=await i.json(),C=Array.isArray(c)?Object.fromEntries(c.filter(o=>{if(typeof o!="object"||o===null)return !1;let d=o;return typeof d.quote=="string"&&typeof d.rate=="number"}).map(o=>[o.quote.toUpperCase(),o.rate])):c.rates??{};if(C[s]===void 0)throw chunkGXO7TSXQ_cjs.c.validation(D.UNKNOWN_CODE,`Unknown currency: ${s}`,{code:s});return this.baseTables.set(n,{fetchedAt:Date.now(),rates:{...C,[n]:1}}),C[s]}finally{l();}}async getCryptoRate(t,e,r){let{signal:n,cleanup:s}=chunkTLG7VZRX_cjs.a(r,a.FETCH_TIMEOUT_MS,"Crypto price API fetch");try{let R=this.isCryptoCode(t),l=this.isCryptoCode(e),u;if(R&&l){let i=a.CRYPTO_IDS[t],c=a.CRYPTO_IDS[e],C=await this.fetchCoinGeckoPrices([i,c],"usd",n),o=C[i]?.usd,d=C[c]?.usd;if(typeof o!="number")throw chunkGXO7TSXQ_cjs.c.validation(D.UNKNOWN_CODE,`Unknown currency: ${t}`,{code:t});if(typeof d!="number")throw chunkGXO7TSXQ_cjs.c.validation(D.UNKNOWN_CODE,`Unknown currency: ${e}`,{code:e});u=o/d;}else if(R){let i=a.CRYPTO_IDS[t],c=e.toLowerCase(),o=(await this.fetchCoinGeckoPrices([i],c,n))[i]?.[c];if(typeof o!="number")throw chunkGXO7TSXQ_cjs.c.validation(D.UNKNOWN_CODE,`Unknown currency: ${e}`,{code:e});u=o;}else {let i=a.CRYPTO_IDS[e],c=t.toLowerCase(),o=(await this.fetchCoinGeckoPrices([i],c,n))[i]?.[c];if(typeof o!="number")throw chunkGXO7TSXQ_cjs.c.validation(D.UNKNOWN_CODE,`Unknown currency: ${t}`,{code:t});u=1/o;}return this.baseTables.set(t,{fetchedAt:Date.now(),rates:{[t]:1,[e]:u}}),u}finally{s();}}async fetchCoinGeckoPrices(t,e,r){let n=new URLSearchParams({ids:t.join(","),vs_currencies:e}),s=await fetch(`https://api.coingecko.com/api/v3/simple/price?${n.toString()}`,{signal:r});if(!s.ok)throw chunkGXO7TSXQ_cjs.c.external(D.CRYPTO_API_ERROR,`Crypto price API returned ${s.status}`,{status:s.status});return s.json()}primeRates(t,e){let r=t.toUpperCase();this.baseTables.set(r,{fetchedAt:Date.now(),rates:{...e,[r]:1}});}clearRates(){this.baseTables.clear();}getRateSync(t,e){let r=t.toUpperCase(),n=e.toUpperCase();if(r===n)return 1;let s=Date.now();for(let R of this.baseTables.values()){if(s-R.fetchedAt>a.RATE_FRESHNESS_MS)continue;let l=R.rates[r],u=R.rates[n];if(l&&u)return u/l}return null}async convert(t,e,r){let n=await this.getRate(e,r);return t*n}getAllRates(){let t=Date.now(),e={},r=false;for(let[n,s]of this.baseTables)if(!(t-s.fetchedAt>a.RATE_FRESHNESS_MS))for(let[R,l]of Object.entries(s.rates))e[`${n}:${R}`]=l,r=true;return r?e:null}hasRates(){return this.getAllRates()!==null}convertSync(t,e,r){let n=this.getRateSync(e,r);return n===null?null:t*n}isCurrency(t){return O(t)||this.isCryptoCode(t)}};a.RATE_FRESHNESS_MS=900*1e3,a.CRYPTO_IDS={BTC:"bitcoin",ETH:"ethereum",SOL:"solana",XRP:"ripple",ADA:"cardano",DOGE:"dogecoin",DOT:"polkadot"},a.FETCH_TIMEOUT_MS=1e4;var f=a,p=new f,g=p;
2
+ exports.a=f;exports.b=p;exports.c=g;//# sourceMappingURL=chunk-TMQ37JQY.cjs.map
3
+ //# sourceMappingURL=chunk-TMQ37JQY.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/uom/Iso4217.ts","../src/uom/CurrencyExchange.ts"],"names":["ISO_4217_CODES","isIso4217","code","CurrencyErrorCodes","_CurrencyExchangeService","from","to","signal","fromUpper","toUpper","fetchSignal","cleanup","createTimeoutSignal","query","response","ErrorFactory","data","rates","entry","candidate","fromIsCrypto","toIsCrypto","rate","fromId","toId","fromUsd","toUsd","vs","value","priceOfToInFrom","ids","vsCurrency","base","baseUpper","now","table","fromRate","toRate","snapshot","any","CurrencyExchangeService","currencyExchangeService","sharedCurrencyExchange"],"mappings":"qHAyBO,IAAMA,CAAAA,CAAsC,IAAI,GAAA,CAAI,CAC1D,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAC/D,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAC/D,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CACnC,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAC/D,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CACrB,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CACrB,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CACrB,KAAA,CAAO,KAAA,CACP,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CACjD,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CACrB,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CACnC,KAAA,CAAO,KAAA,CAAO,KAAA,CACd,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAA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AAA,CAAW,IAAA,CAAM,WAAY,GAAA,CAAK,UACzC,CAAA,CA/BWA,CAAAA,CAoDa,gBAAA,CAAmB,GAAA,CApDtC,IAAMoC,CAAAA,CAANpC,CAAAA,CA4TMqC,CAAAA,CAA0B,IAAID,CAAAA,CAI9BE,CAAAA,CAAyBD","file":"chunk-MWWAKZOD.cjs","sourcesContent":["/**\n * Every active ISO 4217 currency code.\n *\n * This exists because `CurrencyExchange.isCurrency()` used to hold a\n * hand-written list of forty-six codes, and a code missing from it did not\n * error: `$100 in UAH` returned the original hundred dollars, unconverted, as\n * though the rate were 1. A wrong answer, not a missing feature.\n *\n * The list is the ISO 4217 active set, so \"is this a currency\" is answered by\n * the standard rather than by whichever codes happened to get added. Whether a\n * *rate* is available for one is a separate question, answered at resolution\n * time by whatever the exchange provider supports; conflating the two is what\n * produced the silent failure.\n *\n * Deliberately excluded:\n * - The historical/withdrawn codes (DEM, FRF, and the rest). They are not\n * active, no provider quotes them, and recognising them would only move the\n * failure later.\n * - The X-series non-currencies: XAU/XAG/XPT/XPD (metals), XDR (IMF special\n * drawing rights), XTS (reserved for testing) and XXX (explicitly \"no\n * currency\"). XXX in particular must never resolve.\n *\n * Cryptocurrencies are not here either. They are not ISO 4217 and are tracked\n * separately in `CurrencyExchangeService.CRYPTO_IDS`.\n */\nexport const ISO_4217_CODES: ReadonlySet<string> = new Set([\n\t\"AED\", \"AFN\", \"ALL\", \"AMD\", \"ANG\", \"AOA\", \"ARS\", \"AUD\", \"AWG\", \"AZN\",\n\t\"BAM\", \"BBD\", \"BDT\", \"BGN\", \"BHD\", \"BIF\", \"BMD\", \"BND\", \"BOB\", \"BOV\",\n\t\"BRL\", \"BSD\", \"BTN\", \"BWP\", \"BYN\", \"BZD\",\n\t\"CAD\", \"CDF\", \"CHE\", \"CHF\", \"CHW\", \"CLF\", \"CLP\", \"CNY\", \"COP\", \"COU\",\n\t\"CRC\", \"CUP\", \"CVE\", \"CZK\",\n\t\"DJF\", \"DKK\", \"DOP\", \"DZD\",\n\t\"EGP\", \"ERN\", \"ETB\", \"EUR\",\n\t\"FJD\", \"FKP\",\n\t\"GBP\", \"GEL\", \"GHS\", \"GIP\", \"GMD\", \"GNF\", \"GTQ\", \"GYD\",\n\t\"HKD\", \"HNL\", \"HTG\", \"HUF\",\n\t\"IDR\", \"ILS\", \"INR\", \"IQD\", \"IRR\", \"ISK\",\n\t\"JMD\", \"JOD\", \"JPY\",\n\t\"KES\", \"KGS\", \"KHR\", \"KMF\", \"KPW\", \"KRW\", \"KWD\", \"KYD\", \"KZT\",\n\t\"LAK\", \"LBP\", \"LKR\", \"LRD\", \"LSL\", \"LYD\",\n\t\"MAD\", \"MDL\", \"MGA\", \"MKD\", \"MMK\", \"MNT\", \"MOP\", \"MRU\", \"MUR\", \"MVR\",\n\t\"MWK\", \"MXN\", \"MXV\", \"MYR\", \"MZN\",\n\t\"NAD\", \"NGN\", \"NIO\", \"NOK\", \"NPR\", \"NZD\",\n\t\"OMR\",\n\t\"PAB\", \"PEN\", \"PGK\", \"PHP\", \"PKR\", \"PLN\", \"PYG\",\n\t\"QAR\",\n\t\"RON\", \"RSD\", \"RUB\", \"RWF\",\n\t\"SAR\", \"SBD\", \"SCR\", \"SDG\", \"SEK\", \"SGD\", \"SHP\", \"SLE\", \"SOS\", \"SRD\",\n\t\"SSP\", \"STN\", \"SVC\", \"SYP\", \"SZL\",\n\t\"THB\", \"TJS\", \"TMT\", \"TND\", \"TOP\", \"TRY\", \"TTD\", \"TWD\", \"TZS\",\n\t\"UAH\", \"UGX\", \"USD\", \"USN\", \"UYI\", \"UYU\", \"UYW\", \"UZS\",\n\t\"VED\", \"VES\", \"VND\", \"VUV\",\n\t\"WST\",\n\t\"XAF\", \"XCD\", \"XCG\", \"XOF\", \"XPF\",\n\t\"YER\",\n\t\"ZAR\", \"ZMW\", \"ZWG\",\n]);\n\n/**\n * Whether `code` is an active ISO 4217 currency code.\n *\n * @param code - A three-letter code, in any case.\n */\nexport function isIso4217(code: string): boolean {\n\treturn ISO_4217_CODES.has(code.toUpperCase());\n}\n","/**\n * Production-grade currency exchange service with scalable architecture\n * Integrates with DataQueryService for worker-based execution\n */\n\nimport { isIso4217 } from \"@solve-js/uom/Iso4217\";\nimport { createTimeoutSignal } from \"@solve-js/utilities/TimeoutSignal\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Error codes for this service. Co-located rather than unioned into\n * `errors/ErrorCode.ts`'s core catalog (that catalog is scoped to the\n * parser/VM/engine/errors/config/lexer layers, not yet the ~17 domain\n * packages. See that file's module doc for the intended per-package\n * pattern this follows).\n */\nexport const CurrencyErrorCodes = {\n /** Frankfurter's rates endpoint returned a non-OK HTTP status. */\n API_ERROR: \"CURRENCY_API_ERROR\",\n /** A requested currency/crypto code isn't in the fetched rate table, an unrecognized code, not an API failure. */\n UNKNOWN_CODE: \"UNKNOWN_CURRENCY_CODE\",\n /** CoinGecko's simple-price endpoint returned a non-OK HTTP status. */\n CRYPTO_API_ERROR: \"CRYPTO_PRICE_API_ERROR\",\n} as const;\n\n// ============================================================================\n// CURRENCY EXCHANGE SERVICE\n// ============================================================================\n\n/**\n * Caches exchange rates fetched from an external source.\n *\n * Rates are global market data rather than per-engine configuration, which is\n * why one instance is shared. Two engines with private copies would fetch the\n * same endpoint twice and could disagree about one pair at one moment. See\n * `engine/EngineContext.ts`.\n */\nexport class CurrencyExchangeService {\n /**\n * Live rate tables cached from successful getRate() fetches, keyed by\n * uppercase base currency. Each table holds every rate the API returned\n * for that base (plus the base itself at 1), so any pair whose two codes\n * appear in one fresh table can be served synchronously, including\n * cross pairs via triangulation (EUR→GBP through a USD-base table).\n * Stale tables are ignored, not evicted; the next successful fetch for\n * the same base overwrites them.\n */\n private baseTables: Map<string, { fetchedAt: number; rates: Record<string, number> }> = new Map();\n\n /**\n * How long a fetched rate may be served synchronously by getRateSync().\n * Beyond this window callers fall through to the async path (expression\n * shows Pending until the fetch lands).\n */\n private static readonly RATE_FRESHNESS_MS = 15 * 60 * 1000;\n\n /**\n * Ticker → CoinGecko coin id, for the cryptocurrencies `isCurrency()`\n * recognizes. Frankfurter (the fiat rate source below) is ECB reference\n * rates only and has no concept of BTC/ETH/etc, routing a crypto code\n * through it as `base=BTC` fails outright, which is why crypto pairs\n * previously never resolved (see CurrencyAsyncResolver/VM.ts's ADD\n * handling for the two bugs that let that failure pass silently instead\n * of surfacing as a real fetch).\n */\n private static readonly CRYPTO_IDS: Record<string, string> = {\n BTC: \"bitcoin\", ETH: \"ethereum\", SOL: \"solana\", XRP: \"ripple\",\n ADA: \"cardano\", DOGE: \"dogecoin\", DOT: \"polkadot\",\n };\n\n private isCryptoCode(code: string): boolean {\n // An own-property check, not `in`: `in` also answers for everything on\n // Object.prototype, so a code spelt like an inherited name would pass.\n return Object.prototype.hasOwnProperty.call(CurrencyExchangeService.CRYPTO_IDS, code.toUpperCase());\n }\n\n constructor() {}\n\n // ------------------------------------------------------------------------\n // RATE FETCHING\n // ------------------------------------------------------------------------\n\n /**\n * Timeout (ms) for currency exchange rate fetches.\n *\n * If the frankfurter API doesn't respond within this window, the fetch\n * is aborted, preventing indefinite \"Pending\" states in the playground\n * and Obsidian plugin when the exchange rate API is unreachable.\n */\n private static readonly FETCH_TIMEOUT_MS = 10_000;\n\n /**\n * Fetch the live exchange rate for converting 1 unit of `from` into `to`.\n *\n * Routes cryptocurrency codes (see {@link CRYPTO_IDS}) to CoinGecko and\n * everything else to Frankfurter (ECB reference rates, fiat-only). On\n * success, caches the whole returned rate table for `from` so subsequent\n * lookups, including cross-pairs via triangulation, can be served\n * synchronously by {@link getRateSync} within the freshness window.\n *\n * @throws If the currency code is unrecognized or the fetch fails/times out.\n */\n async getRate(from: string, to: string, signal?: AbortSignal): Promise<number> {\n const fromUpper = from.toUpperCase();\n const toUpper = to.toUpperCase();\n\n if (this.isCryptoCode(fromUpper) || this.isCryptoCode(toUpper)) {\n return this.getCryptoRate(fromUpper, toUpper, signal);\n }\n\n // Combine the caller's optional abort signal with a hard timeout so a\n // hanging currency API never blocks re-evaluation indefinitely.\n const { signal: fetchSignal, cleanup } = createTimeoutSignal(\n signal,\n CurrencyExchangeService.FETCH_TIMEOUT_MS,\n \"Currency API fetch\",\n );\n\n try {\n // Built with URLSearchParams rather than interpolated. The code is\n // ISO-4217 by the time it gets here, but the query should be safe on\n // its own terms rather than by relying on a check that lives elsewhere.\n const query = new URLSearchParams({ base: fromUpper });\n const response = await fetch(`https://api.frankfurter.dev/v2/rates?${query.toString()}`, { signal: fetchSignal });\n if (!response.ok) throw ErrorFactory.external(CurrencyErrorCodes.API_ERROR, `Currency API returned ${response.status}`, { status: response.status });\n const data = await response.json();\n // The v2 endpoint returns a flat array of { date, base, quote, rate }\n // entries (one per target currency) rather than the classic v1 shape\n // { base, date, rates: { CODE: rate } }. Reading data.rates against\n // the real response is always undefined, so every conversion used to\n // throw \"Unknown currency\" no matter which currencies were requested.\n // Accept both shapes so a future API revision back to the object form\n // doesn't silently break this again.\n const rates: Record<string, number> = Array.isArray(data)\n ? Object.fromEntries(\n data\n .filter((entry: unknown): entry is { quote: string; rate: number } => {\n if (typeof entry !== \"object\" || entry === null) return false;\n const candidate = entry as { quote?: unknown; rate?: unknown };\n return typeof candidate.quote === \"string\" && typeof candidate.rate === \"number\";\n })\n .map((entry: { quote: string; rate: number }) => [entry.quote.toUpperCase(), entry.rate])\n )\n : (data.rates ?? {});\n if (rates[toUpper] === undefined) throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n\n // The API returns ALL rates for the base currency, cache the whole\n // table so subsequent conversions (including cross pairs via\n // triangulation) resolve synchronously within the freshness window\n // instead of going Pending again.\n this.baseTables.set(fromUpper, {\n fetchedAt: Date.now(),\n rates: { ...rates, [fromUpper]: 1 },\n });\n\n return rates[toUpper];\n } finally {\n cleanup();\n }\n }\n\n /**\n * Crypto rate fetch, routed through CoinGecko's no-auth simple-price\n * endpoint instead of Frankfurter (fiat-only, has no BTC/ETH concept).\n * Handles all three combinations, crypto→crypto, crypto→fiat\n * fiat→crypto, via prices denominated in USD (or the target fiat\n * directly, which CoinGecko's `vs_currencies` also accepts), then\n * caches the result as a same-shaped base table so getRateSync /\n * convertSync keep working unchanged for crypto pairs too.\n */\n private async getCryptoRate(fromUpper: string, toUpper: string, signal?: AbortSignal): Promise<number> {\n const { signal: fetchSignal, cleanup } = createTimeoutSignal(\n signal,\n CurrencyExchangeService.FETCH_TIMEOUT_MS,\n \"Crypto price API fetch\",\n );\n\n try {\n const fromIsCrypto = this.isCryptoCode(fromUpper);\n const toIsCrypto = this.isCryptoCode(toUpper);\n let rate: number;\n\n if (fromIsCrypto && toIsCrypto) {\n const fromId = CurrencyExchangeService.CRYPTO_IDS[fromUpper];\n const toId = CurrencyExchangeService.CRYPTO_IDS[toUpper];\n const data = await this.fetchCoinGeckoPrices([fromId, toId], \"usd\", fetchSignal);\n const fromUsd = data[fromId]?.usd;\n const toUsd = data[toId]?.usd;\n if (typeof fromUsd !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${fromUpper}`, { code: fromUpper });\n if (typeof toUsd !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n rate = fromUsd / toUsd;\n } else if (fromIsCrypto) {\n const fromId = CurrencyExchangeService.CRYPTO_IDS[fromUpper];\n const vs = toUpper.toLowerCase();\n const data = await this.fetchCoinGeckoPrices([fromId], vs, fetchSignal);\n const value = data[fromId]?.[vs];\n if (typeof value !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n rate = value;\n } else {\n const toId = CurrencyExchangeService.CRYPTO_IDS[toUpper];\n const vs = fromUpper.toLowerCase();\n const data = await this.fetchCoinGeckoPrices([toId], vs, fetchSignal);\n const priceOfToInFrom = data[toId]?.[vs];\n if (typeof priceOfToInFrom !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${fromUpper}`, { code: fromUpper });\n rate = 1 / priceOfToInFrom;\n }\n\n // Cache as a single-pair base table, same shape Frankfurter fetches\n // produce, so getRateSync/convertSync's triangulation logic doesn't\n // need to know or care which source a rate came from.\n this.baseTables.set(fromUpper, {\n fetchedAt: Date.now(),\n rates: { [fromUpper]: 1, [toUpper]: rate },\n });\n\n return rate;\n } finally {\n cleanup();\n }\n }\n\n private async fetchCoinGeckoPrices(ids: string[], vsCurrency: string, signal: AbortSignal): Promise<Record<string, Record<string, number>>> {\n const query = new URLSearchParams({ ids: ids.join(\",\"), vs_currencies: vsCurrency });\n const response = await fetch(`https://api.coingecko.com/api/v3/simple/price?${query.toString()}`, { signal });\n if (!response.ok) throw ErrorFactory.external(CurrencyErrorCodes.CRYPTO_API_ERROR, `Crypto price API returned ${response.status}`, { status: response.status });\n return response.json();\n }\n\n /**\n * Seed a base rate table without a network fetch.\n *\n * Intended for tests and for future user-provided offline rates\n * production live data always comes from {@link getRate}. Seeded rates\n * obey the same freshness window as fetched ones.\n *\n * @param base - Base currency code (e.g. \"USD\").\n * @param rates - Map of currency code → rate relative to the base.\n */\n primeRates(base: string, rates: Record<string, number>): void {\n const baseUpper = base.toUpperCase();\n this.baseTables.set(baseUpper, {\n fetchedAt: Date.now(),\n rates: { ...rates, [baseUpper]: 1 },\n });\n }\n\n /**\n * Drop every cached/primed rate table.\n *\n * Mainly for test isolation: {@link sharedCurrencyExchange} is a\n * module-level singleton, so a rate primed or fetched by one test can\n * silently leak into a later test in the same file. Also usable in\n * production if a caller ever wants to force a full re-fetch.\n */\n clearRates(): void {\n this.baseTables.clear();\n }\n\n /**\n * Synchronous rate lookup: `1` for same-currency pairs, a cached LIVE\n * rate if one was fetched within {@link RATE_FRESHNESS_MS}, otherwise\n * `null`, callers fall through to the async fetch path and the\n * expression shows Pending until real data arrives.\n *\n * There is deliberately no hardcoded fallback table: a stale made-up\n * rate presented as a real conversion is worse than a Pending state.\n */\n getRateSync(from: string, to: string): number | null {\n const fromUpper = from.toUpperCase();\n const toUpper = to.toUpperCase();\n if (fromUpper === toUpper) {\n return 1;\n }\n const now = Date.now();\n for (const table of this.baseTables.values()) {\n if (now - table.fetchedAt > CurrencyExchangeService.RATE_FRESHNESS_MS) continue;\n const fromRate = table.rates[fromUpper];\n const toRate = table.rates[toUpper];\n if (fromRate && toRate) {\n return toRate / fromRate;\n }\n }\n return null;\n }\n\n /** Convert `value` from `from` to `to` using a freshly-fetched live rate (see {@link getRate}). */\n async convert(value: number, from: string, to: string): Promise<number> {\n const rate = await this.getRate(from, to);\n return value * rate;\n }\n\n /**\n * Get all currently cached fresh rates, keyed \"FROM:TO\".\n * @returns Snapshot of fresh live rates, or null when none are cached.\n */\n getAllRates(): Record<string, number> | null {\n const now = Date.now();\n const snapshot: Record<string, number> = {};\n let any = false;\n for (const [base, table] of this.baseTables) {\n if (now - table.fetchedAt > CurrencyExchangeService.RATE_FRESHNESS_MS) continue;\n for (const [code, rate] of Object.entries(table.rates)) {\n snapshot[`${base}:${code}`] = rate;\n any = true;\n }\n }\n return any ? snapshot : null;\n }\n\n /**\n * Check whether any fresh live rates are currently cached.\n */\n hasRates(): boolean {\n return this.getAllRates() !== null;\n }\n\n /**\n * Synchronous conversion using cached rates only\n * Returns null if rate not in cache\n */\n convertSync(value: number, from: string, to: string): number | null {\n const rate = this.getRateSync(from, to);\n if (rate === null) return null;\n return value * rate;\n }\n\n // ------------------------------------------------------------------------\n // CURRENCY VALIDATION\n // ------------------------------------------------------------------------\n\n /**\n * Check whether `code` is a recognized currency code: any active ISO 4217\n * code, or one of the cryptocurrencies in {@link CRYPTO_IDS}.\n *\n * This used to be a hand-written list of forty-six codes, which meant\n * `$100 in UAH` returned an unconverted hundred dollars rather than saying\n * it could not convert. Answering from the standard rather than from\n * whichever codes happened to get added is what stops that class of bug.\n *\n * Recognising a code is not the same as having a rate for it. That is\n * answered later, by the exchange provider; conflating the two is what\n * produced the silent failure.\n */\n isCurrency(code: string): boolean {\n return isIso4217(code) || this.isCryptoCode(code);\n }\n}\n\n// ============================================================================\n// SINGLETON INSTANCE\n// ============================================================================\n\n/** The shared rate cache. See {@link CurrencyExchangeService} for why it is shared. */\nexport const currencyExchangeService = new CurrencyExchangeService();\n\n// Export for backward compatibility\n/** Alias for {@link currencyExchangeService}, kept for older imports. */\nexport const sharedCurrencyExchange = currencyExchangeService;\n\n// Default export\nexport default currencyExchangeService;\n"]}
1
+ {"version":3,"sources":["../src/uom/Iso4217.ts","../src/uom/CurrencyExchange.ts"],"names":["ISO_4217_CODES","isIso4217","code","CurrencyErrorCodes","_CurrencyExchangeService","from","to","signal","fromUpper","toUpper","fetchSignal","cleanup","createTimeoutSignal","query","response","ErrorFactory","data","rates","entry","candidate","fromIsCrypto","toIsCrypto","rate","fromId","toId","fromUsd","toUsd","vs","value","priceOfToInFrom","ids","vsCurrency","base","baseUpper","now","table","fromRate","toRate","snapshot","any","CurrencyExchangeService","currencyExchangeService","sharedCurrencyExchange"],"mappings":"qHAyBO,IAAMA,CAAAA,CAAsC,IAAI,GAAA,CAAI,CAC1D,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAC/D,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAC/D,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CACnC,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CAC/D,KAAA,CAAO,MAAO,KAAA,CAAO,KAAA,CACrB,KAAA,CAAO,KAAA,CAAO,KAAA,CAAO,KAAA,CACr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C,CAAE,CAAA,CACtC,OAAIgB,IAAS,IAAA,CAAa,IAAA,CACnBM,CAAAA,CAAQN,CACjB,CAmBA,UAAA,CAAWpB,EAAuB,CAChC,OAAOD,CAAAA,CAAUC,CAAI,CAAA,EAAK,IAAA,CAAK,YAAA,CAAaA,CAAI,CAClD,CACF,CAAA,CArTaE,CAAAA,CAiBa,iBAAA,CAAoB,GAAA,CAAU,IAjB3CA,CAAAA,CA4Ba,UAAA,CAAqC,CAC3D,GAAA,CAAK,SAAA,CAAW,GAAA,CAAK,UAAA,CAAY,GAAA,CAAK,QAAA,CAAU,GAAA,CAAK,QAAA,CACrD,GAAA,CAAK,SAAA,CAAW,IAAA,CAAM,WAAY,GAAA,CAAK,UACzC,CAAA,CA/BWA,CAAAA,CAoDa,gBAAA,CAAmB,GAAA,CApDtC,IAAMoC,CAAAA,CAANpC,CAAAA,CA4TMqC,CAAAA,CAA0B,IAAID,CAAAA,CAI9BE,CAAAA,CAAyBD","file":"chunk-TMQ37JQY.cjs","sourcesContent":["/**\n * Every active ISO 4217 currency code.\n *\n * This exists because `CurrencyExchange.isCurrency()` used to hold a\n * hand-written list of forty-six codes, and a code missing from it did not\n * error: `$100 in UAH` returned the original hundred dollars, unconverted, as\n * though the rate were 1. A wrong answer, not a missing feature.\n *\n * The list is the ISO 4217 active set, so \"is this a currency\" is answered by\n * the standard rather than by whichever codes happened to get added. Whether a\n * *rate* is available for one is a separate question, answered at resolution\n * time by whatever the exchange provider supports; conflating the two is what\n * produced the silent failure.\n *\n * Deliberately excluded:\n * - The historical/withdrawn codes (DEM, FRF, and the rest). They are not\n * active, no provider quotes them, and recognising them would only move the\n * failure later.\n * - The X-series non-currencies: XAU/XAG/XPT/XPD (metals), XDR (IMF special\n * drawing rights), XTS (reserved for testing) and XXX (explicitly \"no\n * currency\"). XXX in particular must never resolve.\n *\n * Cryptocurrencies are not here either. They are not ISO 4217 and are tracked\n * separately in `CurrencyExchangeService.CRYPTO_IDS`.\n */\nexport const ISO_4217_CODES: ReadonlySet<string> = new Set([\n\t\"AED\", \"AFN\", \"ALL\", \"AMD\", \"ANG\", \"AOA\", \"ARS\", \"AUD\", \"AWG\", \"AZN\",\n\t\"BAM\", \"BBD\", \"BDT\", \"BGN\", \"BHD\", \"BIF\", \"BMD\", \"BND\", \"BOB\", \"BOV\",\n\t\"BRL\", \"BSD\", \"BTN\", \"BWP\", \"BYN\", \"BZD\",\n\t\"CAD\", \"CDF\", \"CHE\", \"CHF\", \"CHW\", \"CLF\", \"CLP\", \"CNY\", \"COP\", \"COU\",\n\t\"CRC\", \"CUP\", \"CVE\", \"CZK\",\n\t\"DJF\", \"DKK\", \"DOP\", \"DZD\",\n\t\"EGP\", \"ERN\", \"ETB\", \"EUR\",\n\t\"FJD\", \"FKP\",\n\t\"GBP\", \"GEL\", \"GHS\", \"GIP\", \"GMD\", \"GNF\", \"GTQ\", \"GYD\",\n\t\"HKD\", \"HNL\", \"HTG\", \"HUF\",\n\t\"IDR\", \"ILS\", \"INR\", \"IQD\", \"IRR\", \"ISK\",\n\t\"JMD\", \"JOD\", \"JPY\",\n\t\"KES\", \"KGS\", \"KHR\", \"KMF\", \"KPW\", \"KRW\", \"KWD\", \"KYD\", \"KZT\",\n\t\"LAK\", \"LBP\", \"LKR\", \"LRD\", \"LSL\", \"LYD\",\n\t\"MAD\", \"MDL\", \"MGA\", \"MKD\", \"MMK\", \"MNT\", \"MOP\", \"MRU\", \"MUR\", \"MVR\",\n\t\"MWK\", \"MXN\", \"MXV\", \"MYR\", \"MZN\",\n\t\"NAD\", \"NGN\", \"NIO\", \"NOK\", \"NPR\", \"NZD\",\n\t\"OMR\",\n\t\"PAB\", \"PEN\", \"PGK\", \"PHP\", \"PKR\", \"PLN\", \"PYG\",\n\t\"QAR\",\n\t\"RON\", \"RSD\", \"RUB\", \"RWF\",\n\t\"SAR\", \"SBD\", \"SCR\", \"SDG\", \"SEK\", \"SGD\", \"SHP\", \"SLE\", \"SOS\", \"SRD\",\n\t\"SSP\", \"STN\", \"SVC\", \"SYP\", \"SZL\",\n\t\"THB\", \"TJS\", \"TMT\", \"TND\", \"TOP\", \"TRY\", \"TTD\", \"TWD\", \"TZS\",\n\t\"UAH\", \"UGX\", \"USD\", \"USN\", \"UYI\", \"UYU\", \"UYW\", \"UZS\",\n\t\"VED\", \"VES\", \"VND\", \"VUV\",\n\t\"WST\",\n\t\"XAF\", \"XCD\", \"XCG\", \"XOF\", \"XPF\",\n\t\"YER\",\n\t\"ZAR\", \"ZMW\", \"ZWG\",\n]);\n\n/**\n * Whether `code` is an active ISO 4217 currency code.\n *\n * @param code - A three-letter code, in any case.\n */\nexport function isIso4217(code: string): boolean {\n\treturn ISO_4217_CODES.has(code.toUpperCase());\n}\n","/**\n * Production-grade currency exchange service with scalable architecture\n * Integrates with DataQueryService for worker-based execution\n */\n\nimport { isIso4217 } from \"@solve-js/uom/Iso4217\";\nimport { createTimeoutSignal } from \"@solve-js/utilities/TimeoutSignal\";\nimport { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\n\n/**\n * Error codes for this service. Co-located rather than unioned into\n * `errors/ErrorCode.ts`'s core catalog (that catalog is scoped to the\n * parser/VM/engine/errors/config/lexer layers, not yet the ~17 domain\n * packages. See that file's module doc for the intended per-package\n * pattern this follows).\n */\nexport const CurrencyErrorCodes = {\n /** Frankfurter's rates endpoint returned a non-OK HTTP status. */\n API_ERROR: \"CURRENCY_API_ERROR\",\n /** A requested currency/crypto code isn't in the fetched rate table, an unrecognized code, not an API failure. */\n UNKNOWN_CODE: \"UNKNOWN_CURRENCY_CODE\",\n /** CoinGecko's simple-price endpoint returned a non-OK HTTP status. */\n CRYPTO_API_ERROR: \"CRYPTO_PRICE_API_ERROR\",\n} as const;\n\n// ============================================================================\n// CURRENCY EXCHANGE SERVICE\n// ============================================================================\n\n/**\n * Caches exchange rates fetched from an external source.\n *\n * Rates are global market data rather than per-engine configuration, which is\n * why one instance is shared. Two engines with private copies would fetch the\n * same endpoint twice and could disagree about one pair at one moment. See\n * `engine/EngineContext.ts`.\n */\nexport class CurrencyExchangeService {\n /**\n * Live rate tables cached from successful getRate() fetches, keyed by\n * uppercase base currency. Each table holds every rate the API returned\n * for that base (plus the base itself at 1), so any pair whose two codes\n * appear in one fresh table can be served synchronously, including\n * cross pairs via triangulation (EUR→GBP through a USD-base table).\n * Stale tables are ignored, not evicted; the next successful fetch for\n * the same base overwrites them.\n */\n private baseTables: Map<string, { fetchedAt: number; rates: Record<string, number> }> = new Map();\n\n /**\n * How long a fetched rate may be served synchronously by getRateSync().\n * Beyond this window callers fall through to the async path (expression\n * shows Pending until the fetch lands).\n */\n private static readonly RATE_FRESHNESS_MS = 15 * 60 * 1000;\n\n /**\n * Ticker → CoinGecko coin id, for the cryptocurrencies `isCurrency()`\n * recognizes. Frankfurter (the fiat rate source below) is ECB reference\n * rates only and has no concept of BTC/ETH/etc, routing a crypto code\n * through it as `base=BTC` fails outright, which is why crypto pairs\n * previously never resolved (see CurrencyAsyncResolver/VM.ts's ADD\n * handling for the two bugs that let that failure pass silently instead\n * of surfacing as a real fetch).\n */\n private static readonly CRYPTO_IDS: Record<string, string> = {\n BTC: \"bitcoin\", ETH: \"ethereum\", SOL: \"solana\", XRP: \"ripple\",\n ADA: \"cardano\", DOGE: \"dogecoin\", DOT: \"polkadot\",\n };\n\n private isCryptoCode(code: string): boolean {\n // An own-property check, not `in`: `in` also answers for everything on\n // Object.prototype, so a code spelt like an inherited name would pass.\n return Object.prototype.hasOwnProperty.call(CurrencyExchangeService.CRYPTO_IDS, code.toUpperCase());\n }\n\n constructor() {}\n\n // ------------------------------------------------------------------------\n // RATE FETCHING\n // ------------------------------------------------------------------------\n\n /**\n * Timeout (ms) for currency exchange rate fetches.\n *\n * If the frankfurter API doesn't respond within this window, the fetch\n * is aborted, preventing indefinite \"Pending\" states in the playground\n * and Obsidian plugin when the exchange rate API is unreachable.\n */\n private static readonly FETCH_TIMEOUT_MS = 10_000;\n\n /**\n * Fetch the live exchange rate for converting 1 unit of `from` into `to`.\n *\n * Routes cryptocurrency codes (see {@link CRYPTO_IDS}) to CoinGecko and\n * everything else to Frankfurter (ECB reference rates, fiat-only). On\n * success, caches the whole returned rate table for `from` so subsequent\n * lookups, including cross-pairs via triangulation, can be served\n * synchronously by {@link getRateSync} within the freshness window.\n *\n * @throws If the currency code is unrecognized or the fetch fails/times out.\n */\n async getRate(from: string, to: string, signal?: AbortSignal): Promise<number> {\n const fromUpper = from.toUpperCase();\n const toUpper = to.toUpperCase();\n\n if (this.isCryptoCode(fromUpper) || this.isCryptoCode(toUpper)) {\n return this.getCryptoRate(fromUpper, toUpper, signal);\n }\n\n // Combine the caller's optional abort signal with a hard timeout so a\n // hanging currency API never blocks re-evaluation indefinitely.\n const { signal: fetchSignal, cleanup } = createTimeoutSignal(\n signal,\n CurrencyExchangeService.FETCH_TIMEOUT_MS,\n \"Currency API fetch\",\n );\n\n try {\n // Built with URLSearchParams rather than interpolated. The code is\n // ISO-4217 by the time it gets here, but the query should be safe on\n // its own terms rather than by relying on a check that lives elsewhere.\n const query = new URLSearchParams({ base: fromUpper });\n const response = await fetch(`https://api.frankfurter.dev/v2/rates?${query.toString()}`, { signal: fetchSignal });\n if (!response.ok) throw ErrorFactory.external(CurrencyErrorCodes.API_ERROR, `Currency API returned ${response.status}`, { status: response.status });\n const data = await response.json();\n // The v2 endpoint returns a flat array of { date, base, quote, rate }\n // entries (one per target currency) rather than the classic v1 shape\n // { base, date, rates: { CODE: rate } }. Reading data.rates against\n // the real response is always undefined, so every conversion used to\n // throw \"Unknown currency\" no matter which currencies were requested.\n // Accept both shapes so a future API revision back to the object form\n // doesn't silently break this again.\n const rates: Record<string, number> = Array.isArray(data)\n ? Object.fromEntries(\n data\n .filter((entry: unknown): entry is { quote: string; rate: number } => {\n if (typeof entry !== \"object\" || entry === null) return false;\n const candidate = entry as { quote?: unknown; rate?: unknown };\n return typeof candidate.quote === \"string\" && typeof candidate.rate === \"number\";\n })\n .map((entry: { quote: string; rate: number }) => [entry.quote.toUpperCase(), entry.rate])\n )\n : (data.rates ?? {});\n if (rates[toUpper] === undefined) throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n\n // The API returns ALL rates for the base currency, cache the whole\n // table so subsequent conversions (including cross pairs via\n // triangulation) resolve synchronously within the freshness window\n // instead of going Pending again.\n this.baseTables.set(fromUpper, {\n fetchedAt: Date.now(),\n rates: { ...rates, [fromUpper]: 1 },\n });\n\n return rates[toUpper];\n } finally {\n cleanup();\n }\n }\n\n /**\n * Crypto rate fetch, routed through CoinGecko's no-auth simple-price\n * endpoint instead of Frankfurter (fiat-only, has no BTC/ETH concept).\n * Handles all three combinations, crypto→crypto, crypto→fiat\n * fiat→crypto, via prices denominated in USD (or the target fiat\n * directly, which CoinGecko's `vs_currencies` also accepts), then\n * caches the result as a same-shaped base table so getRateSync /\n * convertSync keep working unchanged for crypto pairs too.\n */\n private async getCryptoRate(fromUpper: string, toUpper: string, signal?: AbortSignal): Promise<number> {\n const { signal: fetchSignal, cleanup } = createTimeoutSignal(\n signal,\n CurrencyExchangeService.FETCH_TIMEOUT_MS,\n \"Crypto price API fetch\",\n );\n\n try {\n const fromIsCrypto = this.isCryptoCode(fromUpper);\n const toIsCrypto = this.isCryptoCode(toUpper);\n let rate: number;\n\n if (fromIsCrypto && toIsCrypto) {\n const fromId = CurrencyExchangeService.CRYPTO_IDS[fromUpper];\n const toId = CurrencyExchangeService.CRYPTO_IDS[toUpper];\n const data = await this.fetchCoinGeckoPrices([fromId, toId], \"usd\", fetchSignal);\n const fromUsd = data[fromId]?.usd;\n const toUsd = data[toId]?.usd;\n if (typeof fromUsd !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${fromUpper}`, { code: fromUpper });\n if (typeof toUsd !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n rate = fromUsd / toUsd;\n } else if (fromIsCrypto) {\n const fromId = CurrencyExchangeService.CRYPTO_IDS[fromUpper];\n const vs = toUpper.toLowerCase();\n const data = await this.fetchCoinGeckoPrices([fromId], vs, fetchSignal);\n const value = data[fromId]?.[vs];\n if (typeof value !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${toUpper}`, { code: toUpper });\n rate = value;\n } else {\n const toId = CurrencyExchangeService.CRYPTO_IDS[toUpper];\n const vs = fromUpper.toLowerCase();\n const data = await this.fetchCoinGeckoPrices([toId], vs, fetchSignal);\n const priceOfToInFrom = data[toId]?.[vs];\n if (typeof priceOfToInFrom !== \"number\") throw ErrorFactory.validation(CurrencyErrorCodes.UNKNOWN_CODE, `Unknown currency: ${fromUpper}`, { code: fromUpper });\n rate = 1 / priceOfToInFrom;\n }\n\n // Cache as a single-pair base table, same shape Frankfurter fetches\n // produce, so getRateSync/convertSync's triangulation logic doesn't\n // need to know or care which source a rate came from.\n this.baseTables.set(fromUpper, {\n fetchedAt: Date.now(),\n rates: { [fromUpper]: 1, [toUpper]: rate },\n });\n\n return rate;\n } finally {\n cleanup();\n }\n }\n\n private async fetchCoinGeckoPrices(ids: string[], vsCurrency: string, signal: AbortSignal): Promise<Record<string, Record<string, number>>> {\n const query = new URLSearchParams({ ids: ids.join(\",\"), vs_currencies: vsCurrency });\n const response = await fetch(`https://api.coingecko.com/api/v3/simple/price?${query.toString()}`, { signal });\n if (!response.ok) throw ErrorFactory.external(CurrencyErrorCodes.CRYPTO_API_ERROR, `Crypto price API returned ${response.status}`, { status: response.status });\n return response.json();\n }\n\n /**\n * Seed a base rate table without a network fetch.\n *\n * Intended for tests and for future user-provided offline rates\n * production live data always comes from {@link getRate}. Seeded rates\n * obey the same freshness window as fetched ones.\n *\n * @param base - Base currency code (e.g. \"USD\").\n * @param rates - Map of currency code → rate relative to the base.\n */\n primeRates(base: string, rates: Record<string, number>): void {\n const baseUpper = base.toUpperCase();\n this.baseTables.set(baseUpper, {\n fetchedAt: Date.now(),\n rates: { ...rates, [baseUpper]: 1 },\n });\n }\n\n /**\n * Drop every cached/primed rate table.\n *\n * Mainly for test isolation: {@link sharedCurrencyExchange} is a\n * module-level singleton, so a rate primed or fetched by one test can\n * silently leak into a later test in the same file. Also usable in\n * production if a caller ever wants to force a full re-fetch.\n */\n clearRates(): void {\n this.baseTables.clear();\n }\n\n /**\n * Synchronous rate lookup: `1` for same-currency pairs, a cached LIVE\n * rate if one was fetched within {@link RATE_FRESHNESS_MS}, otherwise\n * `null`, callers fall through to the async fetch path and the\n * expression shows Pending until real data arrives.\n *\n * There is deliberately no hardcoded fallback table: a stale made-up\n * rate presented as a real conversion is worse than a Pending state.\n */\n getRateSync(from: string, to: string): number | null {\n const fromUpper = from.toUpperCase();\n const toUpper = to.toUpperCase();\n if (fromUpper === toUpper) {\n return 1;\n }\n const now = Date.now();\n for (const table of this.baseTables.values()) {\n if (now - table.fetchedAt > CurrencyExchangeService.RATE_FRESHNESS_MS) continue;\n const fromRate = table.rates[fromUpper];\n const toRate = table.rates[toUpper];\n if (fromRate && toRate) {\n return toRate / fromRate;\n }\n }\n return null;\n }\n\n /** Convert `value` from `from` to `to` using a freshly-fetched live rate (see {@link getRate}). */\n async convert(value: number, from: string, to: string): Promise<number> {\n const rate = await this.getRate(from, to);\n return value * rate;\n }\n\n /**\n * Get all currently cached fresh rates, keyed \"FROM:TO\".\n * @returns Snapshot of fresh live rates, or null when none are cached.\n */\n getAllRates(): Record<string, number> | null {\n const now = Date.now();\n const snapshot: Record<string, number> = {};\n let any = false;\n for (const [base, table] of this.baseTables) {\n if (now - table.fetchedAt > CurrencyExchangeService.RATE_FRESHNESS_MS) continue;\n for (const [code, rate] of Object.entries(table.rates)) {\n snapshot[`${base}:${code}`] = rate;\n any = true;\n }\n }\n return any ? snapshot : null;\n }\n\n /**\n * Check whether any fresh live rates are currently cached.\n */\n hasRates(): boolean {\n return this.getAllRates() !== null;\n }\n\n /**\n * Synchronous conversion using cached rates only\n * Returns null if rate not in cache\n */\n convertSync(value: number, from: string, to: string): number | null {\n const rate = this.getRateSync(from, to);\n if (rate === null) return null;\n return value * rate;\n }\n\n // ------------------------------------------------------------------------\n // CURRENCY VALIDATION\n // ------------------------------------------------------------------------\n\n /**\n * Check whether `code` is a recognized currency code: any active ISO 4217\n * code, or one of the cryptocurrencies in {@link CRYPTO_IDS}.\n *\n * This used to be a hand-written list of forty-six codes, which meant\n * `$100 in UAH` returned an unconverted hundred dollars rather than saying\n * it could not convert. Answering from the standard rather than from\n * whichever codes happened to get added is what stops that class of bug.\n *\n * Recognising a code is not the same as having a rate for it. That is\n * answered later, by the exchange provider; conflating the two is what\n * produced the silent failure.\n */\n isCurrency(code: string): boolean {\n return isIso4217(code) || this.isCryptoCode(code);\n }\n}\n\n// ============================================================================\n// SINGLETON INSTANCE\n// ============================================================================\n\n/** The shared rate cache. See {@link CurrencyExchangeService} for why it is shared. */\nexport const currencyExchangeService = new CurrencyExchangeService();\n\n// Export for backward compatibility\n/** Alias for {@link currencyExchangeService}, kept for older imports. */\nexport const sharedCurrencyExchange = currencyExchangeService;\n\n// Default export\nexport default currencyExchangeService;\n"]}
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunkE4HAKNBQ_cjs=require('./chunk-E4HAKNBQ.cjs'),chunkGXO7TSXQ_cjs=require('./chunk-GXO7TSXQ.cjs');var s=class{now(){return Date.now()}fields(t){let e=new Date(t);return {year:e.getFullYear(),month0:e.getMonth(),day:e.getDate(),weekday:e.getDay(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),millisecond:e.getMilliseconds()}}localMidnight(t,e,n){return new Date(t,e,n).getTime()}localWallClock(t,e,n,r){let a=new Date(t,e,n,0,0,0,0);return a.setMinutes(r),a.getTime()}addDays(t,e){let n=new Date(t);return n.setDate(n.getDate()+e),n.getTime()}addMonths(t,e){let n=new Date(t),r=n.getDate();return n.setDate(1),n.setMonth(n.getMonth()+e),n.setDate(Math.min(r,chunkE4HAKNBQ_cjs.b(n.getFullYear(),n.getMonth()))),n.getTime()}utcOffsetMinutes(t){return 0-new Date(t).getTimezoneOffset()}parseIso8601(t){return new Date(t).getTime()}formatLongDate(t,e){return new Date(t).toLocaleDateString(e,{weekday:"long",year:"numeric",month:"long",day:"numeric"})}formatTimeOfDay(t,e){return new Date(t).toLocaleTimeString(e)}zoneOffsetMinutes(t,e){let n=chunkE4HAKNBQ_cjs.l(t,e);return Math.round((chunkE4HAKNBQ_cjs.a(n.year,n.month0,n.day,n.hour,n.minute,n.second)-e)/6e4)||0}fieldsInZone(t,e){return chunkE4HAKNBQ_cjs.l(t,e)}formatTimeInZone(t,e){return chunkE4HAKNBQ_cjs.m(t,e)}formatDateInZone(t,e){return chunkE4HAKNBQ_cjs.n(t,e)}},k=new s;function L(o){return o?.calendar??k}var O=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?$/,l=class extends s{constructor(e){super();this.namedZone=e;}zone(){return this.namedZone}fields(e){let n=chunkE4HAKNBQ_cjs.l(this.namedZone,e),r=((chunkE4HAKNBQ_cjs.c(n.year,n.month0,n.day)+4)%7+7)%7;return {year:n.year,month0:n.month0,day:n.day,weekday:r,hour:n.hour,minute:n.minute,second:n.second,millisecond:(e%1e3+1e3)%1e3}}localMidnight(e,n,r){return chunkE4HAKNBQ_cjs.j(e,n,r,0,0,this.namedZone,this)}localWallClock(e,n,r,a){return chunkE4HAKNBQ_cjs.j(e,n,r,0,a,this.namedZone,this)}addDays(e,n){let r=chunkE4HAKNBQ_cjs.l(this.namedZone,e);return this.reanchor(r,r.day+n,e)}addMonths(e,n){let r=chunkE4HAKNBQ_cjs.l(this.namedZone,e),a=new Date(Date.UTC(r.year,r.month0+n,1)),i=Math.min(r.day,chunkE4HAKNBQ_cjs.b(a.getUTCFullYear(),a.getUTCMonth()));return chunkE4HAKNBQ_cjs.j(a.getUTCFullYear(),a.getUTCMonth(),i,r.hour,r.minute,this.namedZone,this)+r.second*1e3+(e%1e3+1e3)%1e3}utcOffsetMinutes(e){return this.zoneOffsetMinutes(this.namedZone,e)}parseIso8601(e){let n=O.exec(e.trim());if(n===null)return super.parseIso8601(e);let[,r,a,i,w,p,c,b]=n,I=b===void 0?0:Number(b.slice(0,3).padEnd(3,"0"));return chunkE4HAKNBQ_cjs.j(Number(r),Number(a)-1,Number(i),Number(w),Number(p),this.namedZone,this)+(c===void 0?0:Number(c))*1e3+I}formatLongDate(e,n){return chunkE4HAKNBQ_cjs.o(this.namedZone,e,n)}formatTimeOfDay(e,n){return chunkE4HAKNBQ_cjs.p(this.namedZone,e,n)}reanchor(e,n,r){return chunkE4HAKNBQ_cjs.j(e.year,e.month0,n,e.hour,e.minute,this.namedZone,this)+e.second*1e3+(r%1e3+1e3)%1e3}};function U(o){if(!chunkE4HAKNBQ_cjs.k(o))throw chunkGXO7TSXQ_cjs.c.config(chunkGXO7TSXQ_cjs.s.DATE_ZONE_UNKNOWN,`dateCalendarInZone("${o}") is not a time zone this runtime knows.`);return new l(o)}exports.a=s;exports.b=k;exports.c=L;exports.d=U;//# sourceMappingURL=chunk-TPPM4QSS.cjs.map
2
+ //# sourceMappingURL=chunk-TPPM4QSS.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/calendar/DateCalendar.ts"],"names":["DateCalendar","epochMs","d","year","month0","day","minutesPastMidnight","anchored","days","date","months","dayOfMonth","daysInMonth","text","locale","zone","f","zonedFields","utcMs","timeInZone","dateInZone","DATE_CALENDAR","calendarOf","context","ISO_LOCAL_DATE_TIME","ZonedDateCalendar","namedZone","weekday","dayNumber","zonedWallClockToUtcMs","target","clampedDay","matched","month","hour","minute","second","fraction","millisecond","longDateInZone","timeOfDayInZone","dateCalendarInZone","isSupportedZone","ErrorFactory","DatetimeErrorCodes"],"mappings":"qHA0BO,IAAMA,EAAN,KAA8C,CACpD,GAAA,EAAc,CACb,OAAO,IAAA,CAAK,GAAA,EACb,CAEA,OAAOC,CA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AAA,CAAS,GAAA,CAAA,CAAUf,EAAU,GAAA,CAAQ,GAAA,EAAQ,GACnD,CACD,CAAA,CA6BO,SAASwC,CAAAA,CAAmB1B,CAAAA,CAA+B,CACjE,GAAI,CAAC2B,mBAAAA,CAAgB3B,CAAI,CAAA,CACxB,MAAM4B,oBAAa,MAAA,CAClBC,mBAAAA,CAAmB,iBAAA,CACnB,CAAA,oBAAA,EAAuB7B,CAAI,CAAA,yCAAA,CAC5B,CAAA,CAED,OAAO,IAAIU,CAAAA,CAAkBV,CAAI,CAClC","file":"chunk-TPPM4QSS.cjs","sourcesContent":["import { ErrorFactory } from \"@solve-js/errors/UnifiedErrorFramework\";\nimport { DatetimeErrorCodes } from \"@solve-js/errors/ErrorCode\";\nimport type { CalendarBackend, CalendarFields, ZonedFields } from \"./CalendarBackend\";\nimport { dayNumber, daysInMonth, utcMs } from \"./Gregorian\";\nimport { dateInZone, isSupportedZone, longDateInZone, timeInZone, timeOfDayInZone, zonedFields, zonedWallClockToUtcMs } from \"./IntlZone\";\n\n/**\n * The default {@link CalendarBackend}: the JavaScript `Date` object, read in\n * the host process's time zone, with `Intl.DateTimeFormat` for named zones.\n *\n * This is the calendar code the engine has always run, moved behind the\n * interface method by method rather than rewritten, so a host that configures\n * nothing sees the same instants and the same strings it did before the\n * backend existed. Where `Date` has a quirk (a two-digit year in a\n * constructor maps to the 1900s, an out-of-range instant answers `NaN`), the\n * quirk is kept here deliberately: the point of this backend is to be the\n * behaviour the `Temporal` backend is measured against, not to improve on it.\n *\n * It stays the default because it is the one calendar every supported runtime\n * has. `Temporal` ships unflagged in Node 26 and in current Chrome, Firefox\n * and Deno, but not in Safari or in the Node 22 and 24 the engine supports,\n * and the smallest polyfill adds about twenty kilobytes gzipped to a bundle\n * that a host doing plain arithmetic never needs. A host that wants\n * `Temporal` opts in through the engine's `calendar` option with the backend\n * from `solve-engine/temporal`, and pays for it only then.\n */\nexport class DateCalendar implements CalendarBackend {\n\tnow(): number {\n\t\treturn Date.now();\n\t}\n\n\tfields(epochMs: number): CalendarFields {\n\t\tconst d = new Date(epochMs);\n\t\treturn {\n\t\t\tyear: d.getFullYear(),\n\t\t\tmonth0: d.getMonth(),\n\t\t\tday: d.getDate(),\n\t\t\tweekday: d.getDay(),\n\t\t\thour: d.getHours(),\n\t\t\tminute: d.getMinutes(),\n\t\t\tsecond: d.getSeconds(),\n\t\t\tmillisecond: d.getMilliseconds(),\n\t\t};\n\t}\n\n\tlocalMidnight(year: number, month0: number, day: number): number {\n\t\treturn new Date(year, month0, day).getTime();\n\t}\n\n\tlocalWallClock(year: number, month0: number, day: number, minutesPastMidnight: number): number {\n\t\t// Anchored at midnight and then moved by the minutes FIELD, so the\n\t\t// result is the wall-clock reading asked for whatever the day's length.\n\t\tconst anchored = new Date(year, month0, day, 0, 0, 0, 0);\n\t\tanchored.setMinutes(minutesPastMidnight);\n\t\treturn anchored.getTime();\n\t}\n\n\taddDays(epochMs: number, days: number): number {\n\t\tconst date = new Date(epochMs);\n\t\tdate.setDate(date.getDate() + days);\n\t\treturn date.getTime();\n\t}\n\n\taddMonths(epochMs: number, months: number): number {\n\t\tconst date = new Date(epochMs);\n\t\tconst dayOfMonth = date.getDate();\n\t\t// Parked on the 1st before the month field moves: `setMonth()` keeps\n\t\t// the day number, so a 31st aimed at a 30-day month would overflow\n\t\t// into the month after it. Clamping afterwards is what keeps the month\n\t\t// the caller asked for.\n\t\tdate.setDate(1);\n\t\tdate.setMonth(date.getMonth() + months);\n\t\tdate.setDate(Math.min(dayOfMonth, daysInMonth(date.getFullYear(), date.getMonth())));\n\t\treturn date.getTime();\n\t}\n\n\tutcOffsetMinutes(epochMs: number): number {\n\t\t// `getTimezoneOffset()` is (UTC minus local), so its sign is inverted\n\t\t// relative to the \"+HH:MM ahead of UTC\" reading every caller wants.\n\t\t// Subtracted from zero rather than negated, so a zero offset is 0 and\n\t\t// not -0, which a second backend could not be expected to reproduce.\n\t\treturn 0 - new Date(epochMs).getTimezoneOffset();\n\t}\n\n\tparseIso8601(text: string): number {\n\t\treturn new Date(text).getTime();\n\t}\n\n\tformatLongDate(epochMs: number, locale: string): string {\n\t\treturn new Date(epochMs).toLocaleDateString(locale, { weekday: \"long\", year: \"numeric\", month: \"long\", day: \"numeric\" });\n\t}\n\n\tformatTimeOfDay(epochMs: number, locale: string): string {\n\t\treturn new Date(epochMs).toLocaleTimeString(locale);\n\t}\n\n\tzoneOffsetMinutes(zone: string, epochMs: number): number {\n\t\t// The `Intl` round trip: read the instant as the zone's wall-clock\n\t\t// fields, re-read those fields as if they were UTC, and the difference\n\t\t// from the instant is the zone's offset then, daylight saving included.\n\t\tconst f = zonedFields(zone, epochMs);\n\t\t// `|| 0` folds the -0 a negative sub-minute difference rounds to.\n\t\treturn Math.round((utcMs(f.year, f.month0, f.day, f.hour, f.minute, f.second) - epochMs) / 60000) || 0;\n\t}\n\n\tfieldsInZone(zone: string, epochMs: number): ZonedFields {\n\t\treturn zonedFields(zone, epochMs);\n\t}\n\n\tformatTimeInZone(zone: string, epochMs: number): string {\n\t\treturn timeInZone(zone, epochMs);\n\t}\n\n\tformatDateInZone(zone: string, epochMs: number): string {\n\t\treturn dateInZone(zone, epochMs);\n\t}\n}\n\n/**\n * The one `Date` backend, shared by every engine that configures no other.\n *\n * Stateless, so sharing is safe: it holds no zone of its own and reads the\n * process's. It is also what the sites with no engine in hand use (the\n * normaliser rules that fuse a literal, `days in <period>`, the stocks and\n * historical-currency date phrases, and `formatValue`), which is why an\n * engine's own backend is the default here rather than a second copy.\n */\nexport const DATE_CALENDAR: CalendarBackend = new DateCalendar();\n\n/**\n * The backend a plugin function or converter should compute with: the one\n * on its execution context, or the `Date` backend when the handler was\n * called with no context (a direct call from a test, or an `as` converter\n * invoked outside the VM).\n *\n * @param context - The execution context the handler received, if any.\n * @returns The engine's backend when the context carries one, else {@link DATE_CALENDAR}.\n */\nexport function calendarOf(context?: { readonly calendar?: CalendarBackend }): CalendarBackend {\n\treturn context?.calendar ?? DATE_CALENDAR;\n}\n\n/**\n * The `Date` backend, computing in a named IANA zone instead of the host\n * process's.\n *\n * Every zone-free answer is inherited unchanged from {@link DateCalendar}:\n * `now()` is still the clock, `parseIso8601` still reads the two ECMAScript\n * spellings, and the four named-zone methods already took the zone as an\n * argument. What changes is what \"local\" means, which is exactly the set of\n * questions {@link CalendarBackend} says depends on a zone: which day an\n * instant falls on, what a wall-clock reading names, what a day or a month\n * later is, and what the offset from UTC is.\n *\n * Those are answered through `Intl`, the same data the base class already\n * reads named zones with, so the accuracy is the same and nothing new is\n * bundled. The one place it is a simplification is a wall clock that a\n * daylight-saving transition made ambiguous or non-existent (01:30 on a\n * spring-forward morning): {@link zonedWallClockToUtcMs} resolves it one way,\n * and a `Temporal` backend's `disambiguation: 'compatible'` may resolve it an\n * hour differently.\n */\n/**\n * An ISO 8601 date-time with a time of day and NO offset and no `Z`: the one\n * spelling whose instant depends on which zone reads it. Anchored at both\n * ends, so a date-only string and anything carrying an offset fall through to\n * the base class untouched.\n */\nconst ISO_LOCAL_DATE_TIME = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d+))?)?$/;\n\nclass ZonedDateCalendar extends DateCalendar {\n\t/**\n\t * @param namedZone - An IANA zone name `Intl` accepts.\n\t */\n\tconstructor(private readonly namedZone: string) {\n\t\tsuper();\n\t}\n\n\tzone(): string {\n\t\treturn this.namedZone;\n\t}\n\n\tfields(epochMs: number): CalendarFields {\n\t\tconst f = zonedFields(this.namedZone, epochMs);\n\t\t// `zonedFields` answers no weekday and no millisecond: the weekday is a\n\t\t// pure function of the zoned date (`Gregorian.dayNumber`, counting from a\n\t\t// Thursday), and the millisecond is the instant's own, which no zone\n\t\t// offset in use is fractional enough to move.\n\t\tconst weekday = (((dayNumber(f.year, f.month0, f.day) + 4) % 7) + 7) % 7;\n\t\treturn {\n\t\t\tyear: f.year, month0: f.month0, day: f.day, weekday,\n\t\t\thour: f.hour, minute: f.minute, second: f.second,\n\t\t\tmillisecond: ((epochMs % 1000) + 1000) % 1000,\n\t\t};\n\t}\n\n\tlocalMidnight(year: number, month0: number, day: number): number {\n\t\treturn zonedWallClockToUtcMs(year, month0, day, 0, 0, this.namedZone, this);\n\t}\n\n\tlocalWallClock(year: number, month0: number, day: number, minutesPastMidnight: number): number {\n\t\t// The minutes go in as the MINUTE field, not as elapsed time, so a\n\t\t// reading of 540 is 09:00 on that date even on a 23-hour day. `Date.UTC`\n\t\t// rolls a minute field past 59 into the hour, which is what makes one\n\t\t// argument enough.\n\t\treturn zonedWallClockToUtcMs(year, month0, day, 0, minutesPastMidnight, this.namedZone, this);\n\t}\n\n\taddDays(epochMs: number, days: number): number {\n\t\tconst f = zonedFields(this.namedZone, epochMs);\n\t\treturn this.reanchor(f, f.day + days, epochMs);\n\t}\n\n\taddMonths(epochMs: number, months: number): number {\n\t\tconst f = zonedFields(this.namedZone, epochMs);\n\t\tconst target = new Date(Date.UTC(f.year, f.month0 + months, 1));\n\t\tconst clampedDay = Math.min(f.day, daysInMonth(target.getUTCFullYear(), target.getUTCMonth()));\n\t\treturn zonedWallClockToUtcMs(\n\t\t\ttarget.getUTCFullYear(), target.getUTCMonth(), clampedDay,\n\t\t\tf.hour, f.minute, this.namedZone, this,\n\t\t) + f.second * 1000 + (((epochMs % 1000) + 1000) % 1000);\n\t}\n\n\tutcOffsetMinutes(epochMs: number): number {\n\t\treturn this.zoneOffsetMinutes(this.namedZone, epochMs);\n\t}\n\n\tparseIso8601(text: string): number {\n\t\t// The one reading in that contract that depends on a zone: a date-time\n\t\t// with no offset and no `Z` is LOCAL time, and local here is the named\n\t\t// zone. Without this the backend contradicted itself, computing\n\t\t// `2026-04-03` at New York midnight while reading `2026-04-03T09:30` as\n\t\t// half past nine in the host process's zone. It is also what the\n\t\t// `Temporal` backend already does (`TemporalCalendar.parseIso8601`\n\t\t// resolves a bare wall clock in its own zone), so the two agree.\n\t\t//\n\t\t// Everything else is the base class byte for byte: a date-only string is\n\t\t// still UTC midnight and an explicit offset is still subtracted, both\n\t\t// frozen by the interface's contract.\n\t\tconst matched = ISO_LOCAL_DATE_TIME.exec(text.trim());\n\t\tif (matched === null) return super.parseIso8601(text);\n\t\tconst [, year, month, day, hour, minute, second, fraction] = matched;\n\t\tconst millisecond = fraction === undefined ? 0 : Number(fraction.slice(0, 3).padEnd(3, \"0\"));\n\t\treturn zonedWallClockToUtcMs(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute), this.namedZone, this)\n\t\t\t+ (second === undefined ? 0 : Number(second)) * 1000 + millisecond;\n\t}\n\n\tformatLongDate(epochMs: number, locale: string): string {\n\t\treturn longDateInZone(this.namedZone, epochMs, locale);\n\t}\n\n\tformatTimeOfDay(epochMs: number, locale: string): string {\n\t\treturn timeOfDayInZone(this.namedZone, epochMs, locale);\n\t}\n\n\t/** Rebuild an instant on a (possibly overflowed) day, holding its wall clock down to the millisecond. */\n\tprivate reanchor(f: ZonedFields, day: number, epochMs: number): number {\n\t\treturn zonedWallClockToUtcMs(f.year, f.month0, day, f.hour, f.minute, this.namedZone, this)\n\t\t\t+ f.second * 1000 + (((epochMs % 1000) + 1000) % 1000);\n\t}\n}\n\n/**\n * A `Date` backend that computes in a named time zone rather than the host\n * process's.\n *\n * This is how a host pins the zone the engine reads dates in, and it is the\n * only knob for it: the zone belongs to the calendar backend, which already\n * owns what \"local\" means, so there is deliberately no `date.zone` config\n * field to drift against it.\n *\n * ```ts\n * import { createEngine, dateCalendarInZone } from \"solve-engine\";\n * const engine = createEngine({ calendar: dateCalendarInZone(\"Asia/Tokyo\") });\n * ```\n *\n * It ships on the `Date` backend on purpose. `Temporal` is undefined on Node\n * 24 and in Safari, so \"pass a `Temporal` backend\" would put the zone out of\n * reach for most hosts today; `Temporal` stays an accuracy upgrade for the\n * ambiguous wall clocks around a daylight-saving transition, never a\n * prerequisite for naming a zone at all.\n *\n * @param zone - An IANA zone name, e.g. `\"Asia/Tokyo\"`.\n * @returns A backend whose local zone is that one.\n * @throws A `DATE_ZONE_UNKNOWN` config error when this runtime's `Intl` does\n * not know the zone. Refused here rather than per line, because a backend\n * that cannot compute in the zone it was asked for must not quietly answer\n * in another one.\n */\nexport function dateCalendarInZone(zone: string): CalendarBackend {\n\tif (!isSupportedZone(zone)) {\n\t\tthrow ErrorFactory.config(\n\t\t\tDatetimeErrorCodes.DATE_ZONE_UNKNOWN,\n\t\t\t`dateCalendarInZone(\"${zone}\") is not a time zone this runtime knows.`,\n\t\t);\n\t}\n\treturn new ZonedDateCalendar(zone);\n}\n"]}
@@ -0,0 +1,3 @@
1
+ var i=(e=>(e.PARSING="PARSING",e.EXECUTION="EXECUTION",e.VALIDATION="VALIDATION",e.EXTERNAL="EXTERNAL",e.INTERNAL="INTERNAL",e.CONFIG="CONFIG",e))(i||{}),O=class O extends Error{constructor(r,N){let _=N.recoverable??true,n=_&&!O.captureRecoverableStacks,I=Error,e=I.stackTraceLimit;n&&(I.stackTraceLimit=0),super(N.message),n&&(I.stackTraceLimit=e),this.name="EngineError",this.category=r,this.code=N.code,this.expected=N.expected,this.found=N.found,this.suggestion=N.suggestion,this.recoverable=_,this.span=N.span,this.context=N.context,this.cause=N.cause,this.timestamp=new Date,!n&&Error.captureStackTrace&&Error.captureStackTrace(this,O);}isFatal(){return !this.recoverable}causeChain(){let r=[this],N=this.cause;for(;N!=null;)r.push(N),N=N instanceof Error?N.cause:void 0;return r}format(){let r=[`error[${this.code}]: ${this.message}`];return this.expected&&r.push(` expected: ${this.expected}`),this.found&&r.push(` found: ${this.found}`),this.suggestion&&r.push(` suggestion: ${this.suggestion}`),r.join(`
2
+ `)}toJSON(){return {name:this.name,category:this.category,code:this.code,message:this.message,expected:this.expected,found:this.found,suggestion:this.suggestion,recoverable:this.recoverable,span:this.span,context:this.context,timestamp:this.timestamp.toISOString()}}};O.captureRecoverableStacks=false;var t=O,T=class E{static build(r,N,_,n,I){let e=typeof _=="string"?{code:_,message:n,context:I}:_;return new t(r,{recoverable:N,...e})}static validation(r,N,_){return E.build("VALIDATION",true,r,N,_)}static parsing(r,N,_){return E.build("PARSING",true,r,N,_)}static execution(r,N,_){return E.build("EXECUTION",true,r,N,_)}static external(r,N,_){return E.build("EXTERNAL",true,r,N,_)}static internal(r,N,_){return E.build("INTERNAL",true,r,N,_)}static config(r,N,_){return E.build("CONFIG",false,r,N,_)}};function R(E){return E instanceof t?E:E instanceof Error?T.internal({code:"UNEXPECTED_ERROR",message:E.message,context:{originalErrorName:E.name},cause:E,recoverable:true}):T.internal({code:"UNKNOWN_ERROR",message:"An unknown error occurred",context:{error:String(E)},recoverable:true})}function o(E){return {ok:true,value:E}}function A(E){return {ok:false,error:E}}function s(E){return E.ok}function D(E){return !E.ok}function C(E,r){return E.ok?o(r(E.value)):E}function S(E,r){return E.ok?E:A(r(E.error))}function L(E,r){return E.ok?r(E.value):E}function U(E,r){return E.ok?E.value:r}function a(E,r){return E.ok?r.ok(E.value):r.err(E.error)}function u(E){let r=[];for(let N of E){if(!N.ok)return N;r.push(N.value);}return o(r)}function c(E){if(E.ok)return E.value;throw E.error}function M(E,r=R){try{return o(E())}catch(N){return A(r(N))}}async function P(E,r=R){try{return o(await E())}catch(N){return A(r(N))}}var g={INVALID_NUMBER_LITERAL:"INVALID_NUMBER_LITERAL",UNTERMINATED_STRING:"UNTERMINATED_STRING",NO_PREFIX_PARSELET:"NO_PREFIX_PARSELET",UNEXPECTED_END_OF_INPUT:"UNEXPECTED_END_OF_INPUT",UNEXPECTED_TOKEN_TYPE:"UNEXPECTED_TOKEN_TYPE",NESTING_DEPTH_EXCEEDED:"NESTING_DEPTH_EXCEEDED",UNEXPECTED_END:"UNEXPECTED_END",UNEXPECTED_TRAILING_TOKEN:"UNEXPECTED_TRAILING_TOKEN",PARSE_ERROR:"PARSE_ERROR",TOO_MANY_NUMERIC_CONSTANTS:"TOO_MANY_NUMERIC_CONSTANTS",BYTECODE_OPERAND_OUT_OF_RANGE:"BYTECODE_OPERAND_OUT_OF_RANGE",TOO_MANY_STRING_CONSTANTS:"TOO_MANY_STRING_CONSTANTS",NO_MATCHING_PHRASE_ALTERNATIVE:"NO_MATCHING_PHRASE_ALTERNATIVE",INVALID_PHRASE_PATTERN:"INVALID_PHRASE_PATTERN",PHRASE_KEYWORD_MISMATCH:"PHRASE_KEYWORD_MISMATCH",USER_FUNCTION_INVALID_PARAM_NAME:"USER_FUNCTION_INVALID_PARAM_NAME",USER_FUNCTION_NO_PARAMS:"USER_FUNCTION_NO_PARAMS",FUNCTION_BODY_MUST_BE_SYNCHRONOUS:"FUNCTION_BODY_MUST_BE_SYNCHRONOUS",TOO_MANY_FUNCTION_DEFINITIONS:"TOO_MANY_FUNCTION_DEFINITIONS",TOO_MANY_ANONYMOUS_BODIES:"TOO_MANY_ANONYMOUS_BODIES",UNKNOWN_PLUGIN_FUNCTION:"UNKNOWN_PLUGIN_FUNCTION",EVALUATION_ERROR:"EVALUATION_ERROR",INSTRUCTION_LIMIT_EXCEEDED:"INSTRUCTION_LIMIT_EXCEEDED",STACK_LIMIT_EXCEEDED:"STACK_LIMIT_EXCEEDED",ALLOCATION_LIMIT_EXCEEDED:"ALLOCATION_LIMIT_EXCEEDED",STACK_UNDERFLOW:"STACK_UNDERFLOW",UNDEFINED_VARIABLE:"UNDEFINED_VARIABLE",GLOBAL_VARIABLE_NOT_RESOLVED:"GLOBAL_VARIABLE_NOT_RESOLVED",UNKNOWN_FUNCTION:"UNKNOWN_FUNCTION",UNEXPECTED_PENDING_RESULT:"UNEXPECTED_PENDING_RESULT",UNDEFINED_FUNCTION:"UNDEFINED_FUNCTION",FUNCTION_ARITY_MISMATCH:"FUNCTION_ARITY_MISMATCH",BUILTIN_ARITY_MISMATCH:"BUILTIN_ARITY_MISMATCH",USER_FUNCTION_ASYNC_UNSUPPORTED:"USER_FUNCTION_ASYNC_UNSUPPORTED",MAP_REDUCE_ASYNC_UNSUPPORTED:"MAP_REDUCE_ASYNC_UNSUPPORTED",SYMBOLIC_ASYNC_UNSUPPORTED:"SYMBOLIC_ASYNC_UNSUPPORTED",EXPLAIN_ASYNC_UNSUPPORTED:"EXPLAIN_ASYNC_UNSUPPORTED",FUNCTION_RECURSION_LIMIT_EXCEEDED:"FUNCTION_RECURSION_LIMIT_EXCEEDED",FUNCTION_CALL_LIMIT_EXCEEDED:"FUNCTION_CALL_LIMIT_EXCEEDED",DATE_OFFSET_LIMIT_EXCEEDED:"DATE_OFFSET_LIMIT_EXCEEDED",WORKDAY_OFFSET_EXPECTED_DATE:"WORKDAY_OFFSET_EXPECTED_DATE",WORKDAYS_BETWEEN_EXPECTED_DATES:"WORKDAYS_BETWEEN_EXPECTED_DATES",WORKDAYS_BETWEEN_RANGE_TOO_LARGE:"WORKDAYS_BETWEEN_RANGE_TOO_LARGE",BIGINT_SHIFT_LIMIT_EXCEEDED:"BIGINT_SHIFT_LIMIT_EXCEEDED",BIGINT_POW_LIMIT_EXCEEDED:"BIGINT_POW_LIMIT_EXCEEDED",BIGINT_INEXACT_OPERAND:"BIGINT_INEXACT_OPERAND",BIGINT_DIVISION_BY_ZERO:"BIGINT_DIVISION_BY_ZERO",INTERNAL_MISSING_FUNCTION_BODY:"INTERNAL_MISSING_FUNCTION_BODY",INTERNAL_MISSING_ANONYMOUS_BODY:"INTERNAL_MISSING_ANONYMOUS_BODY",UNKNOWN_BUILTIN_FUNCTION:"UNKNOWN_BUILTIN_FUNCTION",MALFORMED_BYTECODE_TRUNCATED:"MALFORMED_BYTECODE_TRUNCATED",MALFORMED_BYTECODE_CONSTANT_INDEX:"MALFORMED_BYTECODE_CONSTANT_INDEX",MALFORMED_BYTECODE_OPERAND_TYPE:"MALFORMED_BYTECODE_OPERAND_TYPE",MALFORMED_BYTECODE_BODY_KIND:"MALFORMED_BYTECODE_BODY_KIND",MALFORMED_BYTECODE_BIGINT_LITERAL:"MALFORMED_BYTECODE_BIGINT_LITERAL",MALFORMED_BYTECODE_PROGRAM:"MALFORMED_BYTECODE_PROGRAM",SYMBOLIC_RATIONAL_OVERFLOW:"SYMBOLIC_RATIONAL_OVERFLOW",SYMBOLIC_NONFINITE_OPERAND:"SYMBOLIC_NONFINITE_OPERAND",SYMBOLIC_DIVISION_BY_ZERO:"SYMBOLIC_DIVISION_BY_ZERO",SYMBOLIC_NODE_LIMIT_EXCEEDED:"SYMBOLIC_NODE_LIMIT_EXCEEDED",SYMBOLIC_UNSUPPORTED_FUNCTION:"SYMBOLIC_UNSUPPORTED_FUNCTION",SYMBOLIC_FACTOR_LIMIT_EXCEEDED:"SYMBOLIC_FACTOR_LIMIT_EXCEEDED",SYMBOLIC_SOLVE_UNSUPPORTED:"SYMBOLIC_SOLVE_UNSUPPORTED",SYMBOLIC_SOLVE_INCOMPLETE:"SYMBOLIC_SOLVE_INCOMPLETE",SOLVE_REQUIRES_VARIABLE_NAME:"SOLVE_REQUIRES_VARIABLE_NAME",SYMBOLIC_DERIVATIVE_ORDER_LIMIT:"SYMBOLIC_DERIVATIVE_ORDER_LIMIT",SYMBOLIC_INTEGRAL_UNSUPPORTED:"SYMBOLIC_INTEGRAL_UNSUPPORTED",SYMBOLIC_TAYLOR_DEGREE_LIMIT:"SYMBOLIC_TAYLOR_DEGREE_LIMIT",SYMBOLIC_TAYLOR_INEXACT:"SYMBOLIC_TAYLOR_INEXACT",SYMBOLIC_REQUIRES_VARIABLE_NAME:"SYMBOLIC_REQUIRES_VARIABLE_NAME",SYMBOLIC_JACOBIAN_NO_VARIABLES:"SYMBOLIC_JACOBIAN_NO_VARIABLES",INTERNAL_RATIONAL_PARSE:"INTERNAL_RATIONAL_PARSE",EXPRESSION_TOO_LONG:"EXPRESSION_TOO_LONG",EXPRESSION_TOO_COMPLEX:"EXPRESSION_TOO_COMPLEX",DOCUMENT_TOO_LARGE:"DOCUMENT_TOO_LARGE",NORMALIZED_TOKEN_LIMIT_EXCEEDED:"NORMALIZED_TOKEN_LIMIT_EXCEEDED",THEREFORE_REQUIRES_EXPRESSION:"THEREFORE_REQUIRES_EXPRESSION",THEREFORE_ASYNC_UNSUPPORTED:"THEREFORE_ASYNC_UNSUPPORTED",COMPOUND_ASSIGN_REQUIRES_EXPRESSION:"COMPOUND_ASSIGN_REQUIRES_EXPRESSION",COMPOUND_ASSIGN_ASYNC_UNSUPPORTED:"COMPOUND_ASSIGN_ASYNC_UNSUPPORTED",UNKNOWN_SAVINGS_PERIOD:"UNKNOWN_SAVINGS_PERIOD",INVALID_TIME_LITERAL:"INVALID_TIME_LITERAL",NETWORK_DISABLED:"NETWORK_DISABLED",TEMPORAL_IMPLEMENTATION_INVALID:"TEMPORAL_IMPLEMENTATION_INVALID",TEMPORAL_TIME_ZONE_UNKNOWN:"TEMPORAL_TIME_ZONE_UNKNOWN",SNAPSHOT_VERSION_MISMATCH:"SNAPSHOT_VERSION_MISMATCH",SNAPSHOT_MALFORMED:"SNAPSHOT_MALFORMED",SNAPSHOT_UNSUPPORTED_VALUE:"SNAPSHOT_UNSUPPORTED_VALUE",CONFIG_PATH_NOT_FOUND:"CONFIG_PATH_NOT_FOUND",INVALID_CONFIG_PATH:"INVALID_CONFIG_PATH",CONFIG_SECTION_NOT_FOUND:"CONFIG_SECTION_NOT_FOUND",CONFIG_PROPERTY_NOT_FOUND:"CONFIG_PROPERTY_NOT_FOUND",CALENDAR_TEMPORAL_UNAVAILABLE:"CALENDAR_TEMPORAL_UNAVAILABLE",PLUGIN_OPERATOR_COLLISION:"PLUGIN_OPERATOR_COLLISION",PLUGIN_KEYWORD_COLLISION:"PLUGIN_KEYWORD_COLLISION",PLUGIN_UNIT_COLLISION:"PLUGIN_UNIT_COLLISION",PACKAGE_ENGINE_VERSION_MISMATCH:"PACKAGE_ENGINE_VERSION_MISMATCH",PACKAGE_ENGINE_VERSION_INVALID_RANGE:"PACKAGE_ENGINE_VERSION_INVALID_RANGE",OPCODE_POOL_EXHAUSTED:"OPCODE_POOL_EXHAUSTED",PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED:"PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED",PLUGIN_FUNCTION_INDEX_TOO_LARGE:"PLUGIN_FUNCTION_INDEX_TOO_LARGE",INVALID_RATE_UNIT:"INVALID_RATE_UNIT",INVALID_TIMECODE_UNIT:"INVALID_TIMECODE_UNIT",UNEXPECTED_ERROR:"UNEXPECTED_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR"},B={DATETIME_ZONE_UNKNOWN:"DATETIME_ZONE_UNKNOWN",DATETIME_NOT_CONVERTIBLE:"DATETIME_NOT_CONVERTIBLE",DATE_ZONE_UNKNOWN:"DATE_ZONE_UNKNOWN"};export{i as a,t as b,T as c,R as d,o as e,A as f,s as g,D as h,C as i,S as j,L as k,U as l,a as m,u as n,c as o,M as p,P as q,g as r,B as s};//# sourceMappingURL=chunk-VB6QMU2W.js.map
3
+ //# sourceMappingURL=chunk-VB6QMU2W.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors/EngineError.ts","../src/errors/Result.ts","../src/errors/ErrorCode.ts"],"names":["ErrorCategory","_EngineError","category","init","recoverable","skipStack","errorCtor","previousLimit","chain","current","lines","EngineError","ErrorFactory","_ErrorFactory","defaultRecoverable","codeOrInit","message","context","normalizeUnknownError","error","ok","value","err","isOk","r","isErr","map","fn","mapErr","andThen","unwrapOr","fallback","match","arms","combine","results","values","throwIfErr","tryCatch","normalize","e","tryCatchAsync","CoreErrorCodes","DatetimeErrorCodes"],"mappings":"AA6BO,IAAKA,OAEVA,CAAAA,CAAA,OAAA,CAAU,UAEVA,CAAAA,CAAA,SAAA,CAAY,YAEZA,CAAAA,CAAA,UAAA,CAAa,aAEbA,CAAAA,CAAA,QAAA,CAAW,WAEXA,CAAAA,CAAA,QAAA,CAAW,WAEXA,CAAAA,CAAA,MAAA,CAAS,SAZCA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAAA,CAAA,CAmECC,CAAAA,CAAN,MAAMA,UAAoB,KAAM,CA+CrC,YAAYC,CAAAA,CAAyBC,CAAAA,CAAuB,CAK1D,IAAMC,CAAAA,CAAcD,EAAK,WAAA,EA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the error-handling redesign (the other half is\n * `Result.ts`).\n *\n * Historical note: an earlier version of this class (`UnifiedErrorFramework.ts`,\n * still the import path most of the codebase uses. See that file, now a\n * pure re-export barrel) had a much larger field set (`severity`,\n * `recovery`, a 5-value enum, `ErrorRecoveryManager`) that was almost\n * entirely dead: nothing downstream ever read `.severity`/`.recovery`,\n * only `.message` reliably survived to a caller. This version is smaller\n * and deliberately keeps only fields something actually consumes.\n */\n\nimport type { ErrorCode } from \"@solve-js/errors/ErrorCode\";\n\n/** A character-offset (and optional line/col) span into the original expression text, for a future \"underline the offending token\" UI, not yet wired to one. */\nexport interface SourceSpan {\n start: number;\n end: number;\n line?: number;\n col?: number;\n}\n\n/**\n * Error classification, kept from the original framework, now actually\n * consulted: it's the `format()` header and lets host code group errors\n * by pipeline stage without string-matching `.code`.\n */\nexport enum ErrorCategory {\n /** Errors during expression parsing. */\n PARSING = \"PARSING\",\n /** Errors during bytecode execution. */\n EXECUTION = \"EXECUTION\",\n /** Errors from input validation (safety limits, config). */\n VALIDATION = \"VALIDATION\",\n /** Errors from external services/APIs (currency rates, weather, stocks). */\n EXTERNAL = \"EXTERNAL\",\n /** Internal engine invariant violations. See `recoverable`'s doc comment. */\n INTERNAL = \"INTERNAL\",\n /** Configuration errors. */\n CONFIG = \"CONFIG\",\n}\n\n/** Fields accepted when constructing an {@link EngineError}. */\nexport interface EngineErrorInit {\n /** Catalog code. See `errors/ErrorCode.ts`. Not a free string: every code used by a BUILT-IN package should be registered there so `ErrorCodeCatalog.spec.ts` can catch collisions/typos. Third-party packages may still use any string here, `EngineError.code`'s runtime type is `string`. */\n code: ErrorCode | (string & {});\n /** Short, single-line, `Error.message`-compatible. Existing `.toThrow(/pattern/)`/`.message` assertions keep working against this field, richer detail goes in `expected`/`found`/`suggestion`, not crammed into this string. */\n message: string;\n /** What the parser/validator/VM expected to see, in plain words, e.g. \"a city name\", \"a 4-digit year\", \"end of expression\". */\n expected?: string;\n /** What was actually found instead, e.g. \"end of expression\", `NUMBER \"5\"`, the offending token's literal text. */\n found?: string;\n /** An actionable, worked-example fix, e.g. `e.g. \"weather in London\"`. Mirrors this codebase's best existing messages (`WEATHER_EXPECTED_CITY`, `AS_CONVERTER_EXPECTED_NAME`). */\n suggestion?: string;\n /**\n * Whether this engine instance is still usable. `true` for everything that\n * went wrong on ONE line, whether the line's fault (bad syntax, an unknown\n * variable, a safety limit exceeded), the environment's (an external API\n * down), or the engine's own (corrupted bytecode, a stack underflow from a\n * buggy plugin). `false` is for the far rarer case where there is no working\n * engine to go on with: a configuration or package-registration failure,\n * which is what `ErrorFactory.config()` is for and the only factory method\n * that still defaults to it.\n *\n * The category answers a different question, and the two used to be answered\n * as one. Category INTERNAL says whose fault this is, the engine's, worth\n * reporting as a bug. `recoverable` says whether the host may carry on, and\n * after an internal slip on one line it may:\n * `__tests__/hardening/RobustnessEngineLifecycle.spec.ts` alternates a\n * throwing line with a good one five hundred times and every answer stays\n * correct. Reporting that as `isFatal()` told a host the opposite, and a host\n * that honours the name would tear a document down over one bad line.\n *\n * This has never gated \"does evaluation of the rest of the document\n * continue\"; with this engine's per-line containment it always does, even for\n * a `recoverable: false` error (see `ARCHITECTURE.md`'s async-batcher/Tier-2\n * hardening notes). It gates what a host is TOLD. See\n * {@link EngineError.isFatal}.\n */\n recoverable?: boolean;\n /** Character-offset span into the source expression, when available. Not yet threaded through every call site, populate opportunistically, don't block on retrofitting every existing throw site. */\n span?: SourceSpan;\n /** Free-form structured context. The one field the pre-existing framework's real consumer (`ThreeTierEvaluator.ts`'s DAG-preservation-on-compile-error path) actually reads, kept name- and shape-compatible on purpose. */\n context?: Record<string, unknown>;\n /** The underlying error this one wraps, if any, passed straight through to native `Error.cause` (ES2022), so Node's default printer, most loggers, and `instanceof Error` tooling understand the chain for free. */\n cause?: unknown;\n}\n\n/**\n * The engine's structured error type. Still a real `Error` subclass (so\n * `throw`/`catch`/`instanceof Error` all keep working exactly as before),\n * but now every field except the removed `severity`/`recovery` pair is\n * something real code reads.\n */\nexport class EngineError extends Error {\n readonly category: ErrorCategory;\n readonly code: string;\n readonly expected?: string;\n readonly found?: string;\n readonly suggestion?: string;\n readonly recoverable: boolean;\n readonly span?: SourceSpan;\n readonly context?: Record<string, unknown>;\n readonly timestamp: Date;\n /**\n * Set explicitly (not via `super(message, {cause})`). This repo's\n * `tsconfig.json` targets ES6/ES5-ES7 lib, which predates TypeScript's\n * ES2022 `Error` constructor `cause`-option overload. `Error.prototype.cause`\n * is still a real runtime feature in every target this engine actually\n * runs in (Node 16.9+, all evergreen browsers, Electron/Obsidian's\n * bundled Chromium) regardless of the TS lib target used to type-check\n * against it, assigning it directly gets the same Node-printer/logger\n * interop with no build-config change needed.\n */\n readonly cause?: unknown;\n\n /**\n * Whether a recoverable error captures a JavaScript stack trace.\n *\n * Off, because a recoverable EngineError is a value rather than a fault. A\n * line of prose in a notepad is not an expression, so parsing it fails, and\n * that failure is the answer for that line rather than a bug to debug. The\n * engine builds one such error per non-expression line.\n *\n * Capturing a stack is not cheap, and its cost grows with how deep the stack\n * is when it happens. Measured through `parseDocument`, where the throw site\n * sits about a dozen frames down, each capture cost around 62 microseconds\n * and a 250-line document built 74 of them: a CPU profile put the\n * constructor at 46% of the whole pipeline, more than lexing, normalising,\n * parsing and executing put together.\n *\n * Turn it on to debug where a recoverable error is raised from. Errors that\n * are NOT recoverable always capture, since those are the genuine faults.\n *\n * @example\n * ```ts\n * EngineError.captureRecoverableStacks = true;\n * ```\n */\n static captureRecoverableStacks = false;\n\n constructor(category: ErrorCategory, init: EngineErrorInit) {\n // Before super(), which is legal as long as `this` is untouched. V8 reads\n // `Error.stackTraceLimit` while constructing the Error, so zeroing it\n // across the super() call is what actually skips the capture; there is no\n // per-instance switch for it.\n const recoverable = init.recoverable ?? true;\n const skipStack = recoverable && !EngineError.captureRecoverableStacks;\n // `stackTraceLimit` is a V8 extension, present in Node and every\n // Chromium-based browser but absent from the DOM lib, so it is reached\n // through a narrow local view rather than by widening the global type.\n // Where it does not exist, reading and writing it are both harmless and\n // the stack is captured as before.\n const errorCtor = Error as unknown as { stackTraceLimit?: number };\n const previousLimit = errorCtor.stackTraceLimit;\n if (skipStack) errorCtor.stackTraceLimit = 0;\n super(init.message);\n if (skipStack) errorCtor.stackTraceLimit = previousLimit;\n\n this.name = \"EngineError\";\n this.category = category;\n this.code = init.code;\n this.expected = init.expected;\n this.found = init.found;\n this.suggestion = init.suggestion;\n this.recoverable = recoverable;\n this.span = init.span;\n this.context = init.context;\n this.cause = init.cause;\n this.timestamp = new Date();\n // Only for the faults. super() has already captured a stack for those, and\n // this second call recaptures it purely to drop this constructor's own\n // frame; doing that for every error meant paying the whole cost twice.\n if (!skipStack && Error.captureStackTrace) {\n Error.captureStackTrace(this, EngineError);\n }\n }\n\n /** `!recoverable`. See `EngineErrorInit.recoverable`'s doc comment for what this actually gates (message framing/telemetry, not whether evaluation continues). */\n isFatal(): boolean {\n return !this.recoverable;\n }\n\n /** Walk `.cause` repeatedly, collecting the full chain (this error first). */\n causeChain(): unknown[] {\n const chain: unknown[] = [this];\n let current: unknown = this.cause;\n while (current !== undefined && current !== null) {\n chain.push(current);\n current = current instanceof Error ? (current as Error & { cause?: unknown }).cause : undefined;\n }\n return chain;\n }\n\n /**\n * Rust/Go-style multi-line renderer, the NEW thing a host/CLI/test\n * reaches for when it wants the full, verbose picture, as distinct from\n * `.message` (kept short and stable for existing assertions). Example:\n *\n * ```\n * error[WEATHER_EXPECTED_CITY]: Expected a city name after \"weather in\"\n * expected: a city name\n * found: end of expression\n * suggestion: e.g. \"weather in London\"\n * ```\n */\n format(): string {\n const lines = [`error[${this.code}]: ${this.message}`];\n if (this.expected) lines.push(` expected: ${this.expected}`);\n if (this.found) lines.push(` found: ${this.found}`);\n if (this.suggestion) lines.push(` suggestion: ${this.suggestion}`);\n return lines.join(\"\\n\");\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n category: this.category,\n code: this.code,\n message: this.message,\n expected: this.expected,\n found: this.found,\n suggestion: this.suggestion,\n recoverable: this.recoverable,\n span: this.span,\n context: this.context,\n timestamp: this.timestamp.toISOString(),\n };\n }\n}\n\n/**\n * Factory for creating classified `EngineError`s. Every method accepts\n * EITHER the original, minimal 3-arg shape (`code, message, context?`\n * every existing call site across the codebase keeps compiling unchanged)\n * OR the richer `EngineErrorInit` object (for `expected`/`found`/\n * `suggestion`/`recoverable`/`span`/`cause`), upgrade a call site to the\n * richer form only when you're already touching it, no separate churn\n * pass required.\n */\nexport class ErrorFactory {\n private static build(\n category: ErrorCategory,\n defaultRecoverable: boolean,\n codeOrInit: string | EngineErrorInit,\n message?: string,\n context?: Record<string, unknown>,\n ): EngineError {\n const init: EngineErrorInit =\n typeof codeOrInit === \"string\"\n ? { code: codeOrInit, message: message!, context }\n : codeOrInit;\n return new EngineError(category, { recoverable: defaultRecoverable, ...init });\n }\n\n static validation(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static validation(init: EngineErrorInit): EngineError;\n static validation(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.VALIDATION, true, codeOrInit, message, context);\n }\n\n static parsing(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static parsing(init: EngineErrorInit): EngineError;\n static parsing(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.PARSING, true, codeOrInit, message, context);\n }\n\n static execution(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static execution(init: EngineErrorInit): EngineError;\n static execution(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.EXECUTION, true, codeOrInit, message, context);\n }\n\n static external(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static external(init: EngineErrorInit): EngineError;\n static external(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.EXTERNAL, true, codeOrInit, message, context);\n }\n\n /**\n * Reserve for genuine engine-internal invariant violations (corrupted\n * bytecode, a stack underflow from a buggy plugin, an \"impossible\" state),\n * not for user-input errors: the category is a bug report.\n *\n * Defaults `recoverable: true` all the same, because every one of these sites\n * is an invariant that failed on ONE line and none of them leaves the engine\n * unusable. This used to default to `false`, which conflated \"the engine's\n * fault\" with \"the engine is finished\" and told a host to tear a document\n * down over a line it could simply have shown an error against. A site that\n * has looked at its own case and concluded the instance really is gone can\n * still pass `recoverable: false` explicitly. See {@link\n * EngineErrorInit.recoverable}.\n */\n static internal(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static internal(init: EngineErrorInit): EngineError;\n static internal(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.INTERNAL, true, codeOrInit, message, context);\n }\n\n /** Defaults `recoverable: false`, and is now the only method that does: a configuration or package-registration failure is the one class that leaves no working engine to carry on with, rather than one bad line in a document. */\n static config(code: string, message: string, context?: Record<string, unknown>): EngineError;\n static config(init: EngineErrorInit): EngineError;\n static config(codeOrInit: string | EngineErrorInit, message?: string, context?: Record<string, unknown>): EngineError {\n return ErrorFactory.build(ErrorCategory.CONFIG, false, codeOrInit, message, context);\n }\n}\n\n/**\n * Normalize any thrown value into an `EngineError`, an `EngineError`\n * passes through as-is; a plain `Error` gets wrapped (message preserved,\n * original attached via `cause`); anything else becomes a generic\n * \"unknown error\" wrapping the stringified value. Used at every\n * throw-space/Result-space boundary (`Result.tryCatch`'s default\n * `normalize`, the VM's outer execution try/catch, `AsyncResolutionBatcher`'s\n * per-line containment) so a raw `TypeError` from a genuine engine bug\n * still surfaces as a structured, catalogued error instead of an opaque\n * uncaught exception.\n *\n * Both branches state RECOVERABLE explicitly, while keeping the INTERNAL\n * category. The two fields answer different questions and were previously\n * answering the same one:\n *\n * category INTERNAL whose fault is this? The engine's. Worth reporting.\n * recoverable is this engine instance still usable? Yes.\n *\n * Everything reaching here is by definition something the engine did not\n * anticipate on ONE line, and per-line containment means the next line\n * evaluates normally, which `__tests__/hardening/RobustnessEngineLifecycle`\n * demonstrates over hundreds of alternating failure/success pairs. Reporting\n * that as `isFatal()` told a host the opposite, and a host that honours the\n * name would tear a document down over a single bad line. The \"this is an\n * engine bug rather than your syntax\" signal a caller wants for telemetry is\n * the CATEGORY, which is unchanged.\n *\n * The flag is written out here rather than inherited from\n * `ErrorFactory.internal()`, which now defaults the same way, so that this\n * function's contract survives a future change to that default.\n */\nexport function normalizeUnknownError(error: unknown): EngineError {\n if (error instanceof EngineError) return error;\n if (error instanceof Error) {\n return ErrorFactory.internal({\n code: \"UNEXPECTED_ERROR\",\n message: error.message,\n context: { originalErrorName: error.name },\n cause: error,\n recoverable: true,\n });\n }\n return ErrorFactory.internal({\n code: \"UNKNOWN_ERROR\",\n message: \"An unknown error occurred\",\n context: { error: String(error) },\n recoverable: true,\n });\n}\n","import { type EngineError, normalizeUnknownError } from \"@solve-js/errors/EngineError\";\n\n/**\n * A Rust-style `Result<T, E>`, the value half of this engine's error-handling\n * redesign. `E` defaults to `EngineError` (this engine's structured error\n * type) but every combinator here is generic over `E`, so `Result` works\n * equally well for a domain that isn't `EngineError`-shaped.\n *\n * This exact shape used to live in `errors/UnifiedErrorFramework.ts` (kept\n * there as a barrel re-export for backward compatibility), moved here as\n * its own module because it's genuinely generic (no dependency on\n * `EngineError` beyond the default type parameter) and because the engine\n * is migrating callers to it incrementally: parsing/VM/package code that\n * expects \"a failure is a possibility, not an exception\" returns\n * `Result<T, EngineError>` instead of throwing; two explicit adapters\n * {@link throwIfErr} and {@link tryCatch}, are the sanctioned way to cross\n * the boundary between Result-based code and still-throw-based code during\n * the migration (and permanently, at the public API boundary. See\n * `ExpressionEngine.evaluateExpression()`'s documented throw contract).\n */\nexport type Result<T, E = EngineError> =\n | { ok: true; value: T }\n | { ok: false; error: E };\n\n/** Wrap a successful value. */\nexport function ok<T>(value: T): Result<T, never> {\n return { ok: true, value };\n}\n\n/** Wrap a failure. */\nexport function err<E>(error: E): Result<never, E> {\n return { ok: false, error };\n}\n\n/**\n * Narrow a {@link Result} to its success arm.\n *\n * @param r - The result to test.\n * @returns True when it succeeded, narrowing `r` so `r.value` is reachable.\n */\nexport function isOk<T, E>(r: Result<T, E>): r is { ok: true; value: T } {\n return r.ok;\n}\n\n/**\n * Narrow a {@link Result} to its failure arm.\n *\n * @param r - The result to test.\n * @returns True when it failed, narrowing `r` so `r.error` is reachable.\n */\nexport function isErr<T, E>(r: Result<T, E>): r is { ok: false; error: E } {\n return !r.ok;\n}\n\n/** Transform the success value; a failure passes through untouched. */\nexport function map<T, U, E>(r: Result<T, E>, fn: (value: T) => U): Result<U, E> {\n return r.ok ? ok(fn(r.value)) : r;\n}\n\n/** Transform the error; a success passes through untouched. */\nexport function mapErr<T, E, F>(r: Result<T, E>, fn: (error: E) => F): Result<T, F> {\n return r.ok ? r : err(fn(r.error));\n}\n\n/** Chain a Result-returning operation onto a success (a.k.a. flatMap/bind). */\nexport function andThen<T, U, E>(r: Result<T, E>, fn: (value: T) => Result<U, E>): Result<U, E> {\n return r.ok ? fn(r.value) : r;\n}\n\n/** Unwrap a success, or return `fallback` for a failure. Never throws. */\nexport function unwrapOr<T, E>(r: Result<T, E>, fallback: T): T {\n return r.ok ? r.value : fallback;\n}\n\n/** Exhaustive pattern-match, the `match`/`switch` a Rust enum gets for free. */\nexport function match<T, E, R>(r: Result<T, E>, arms: { ok: (value: T) => R; err: (error: E) => R }): R {\n return r.ok ? arms.ok(r.value) : arms.err(r.error);\n}\n\n/**\n * Combine several Results into one, succeeds with a tuple of all values\n * iff every input succeeded; otherwise fails with the FIRST error\n * encountered (left-to-right), matching this codebase's existing\n * fail-fast convention elsewhere (e.g. `BytecodeBuilder`'s constant-pool\n * limit checks).\n */\nexport function combine<T extends readonly unknown[], E>(\n results: { [K in keyof T]: Result<T[K], E> },\n): Result<T, E> {\n const values: unknown[] = [];\n for (const r of results as readonly Result<unknown, E>[]) {\n if (!r.ok) return r;\n values.push(r.value);\n }\n return ok(values as unknown as T);\n}\n\n/**\n * Cross from Result-space back to throw-space, the sanctioned boundary\n * adapter for callers (public API surface, older not-yet-migrated code,\n * tests) that still want exception-based control flow. Throws `r.error`\n * as-is (an `EngineError` is already a real `Error` subclass, so this\n * needs no wrapping).\n */\nexport function throwIfErr<T, E>(r: Result<T, E>): T {\n if (r.ok) return r.value;\n throw r.error;\n}\n\n/**\n * Cross from throw-space into Result-space, runs `fn`, converting any\n * thrown value into a Result via `normalize` (defaults to\n * {@link normalizeUnknownError}). The inverse of {@link throwIfErr}; the\n * pairing that lets Result-based and throw-based code interoperate during\n * an incremental migration instead of requiring a single flag-day rewrite.\n */\nexport function tryCatch<T>(\n fn: () => T,\n normalize: (e: unknown) => EngineError = normalizeUnknownError,\n): Result<T, EngineError> {\n try {\n return ok(fn());\n } catch (e) {\n return err(normalize(e));\n }\n}\n\n/** Async sibling of {@link tryCatch}. */\nexport async function tryCatchAsync<T>(\n fn: () => Promise<T>,\n normalize: (e: unknown) => EngineError = normalizeUnknownError,\n): Promise<Result<T, EngineError>> {\n try {\n return ok(await fn());\n } catch (e) {\n return err(normalize(e));\n }\n}\n","/**\n * The built-in error-code catalog, one typed const object per domain\n * unioned together here for autocomplete/exhaustiveness in core engine\n * code. Deliberately NOT one central enum: `IEnginePackage` is documented\n * public SDK surface for third-party packages (see `api/PackageRegistry.ts`),\n * and a closed enum would block an external package author from defining\n * their own codes without editing this file. `EngineError.code`'s runtime\n * type stays `string` for exactly that reason. This catalog is for the\n * codes THIS repo owns and wants collision/typo checking on (see\n * `__tests__/errors/ErrorCodeCatalog.spec.ts`), not a hard runtime\n * whitelist.\n *\n * As each package migrates to `Result<void, EngineError>` (see this\n * session's error-handling-refactor plan, Phase 5), it should export its\n * own small `XxxErrorCodes` const object co-located with its parselets\n * exactly like `CoreErrorCodes` below, just scoped to one domain, and get\n * unioned into `ErrorCode` here. Until a package migrates, its existing\n * free-string codes keep working (ErrorFactory accepts any string); they\n * just aren't caught by the catalog's uniqueness/orphan checks yet.\n */\n\n/**\n * Codes used directly by the parser/VM/engine/errors layers themselves\n * confirmed against the current source, not aspirational. Grouped by\n * pipeline stage via the comments, not a naming prefix (these predate any\n * naming convention and renaming them is out of scope for introducing the\n * catalog, only NEW codes need to follow a scoped/prefixed style, see\n * `STACK_UNDERFLOW` etc. below).\n */\nexport const CoreErrorCodes = {\n // ── Parser (parser/PrecedenceParser.ts, parser/BytecodeBuilder.ts, parser/PhrasePattern.ts) ──\n INVALID_NUMBER_LITERAL: \"INVALID_NUMBER_LITERAL\",\n /** A `\"` that never meets its closing partner (`lexer/ExpressionLexer.ts`'s `tokenizeString()`). Previously the tokenizer ran off the end of the input and returned what it had, so `\"abc` lexed to an ordinary String and an unterminated literal was indistinguishable from a terminated one. */\n UNTERMINATED_STRING: \"UNTERMINATED_STRING\",\n NO_PREFIX_PARSELET: \"NO_PREFIX_PARSELET\",\n UNEXPECTED_END_OF_INPUT: \"UNEXPECTED_END_OF_INPUT\",\n UNEXPECTED_TOKEN_TYPE: \"UNEXPECTED_TOKEN_TYPE\",\n NESTING_DEPTH_EXCEEDED: \"NESTING_DEPTH_EXCEEDED\",\n UNEXPECTED_END: \"UNEXPECTED_END\",\n UNEXPECTED_TRAILING_TOKEN: \"UNEXPECTED_TRAILING_TOKEN\",\n PARSE_ERROR: \"PARSE_ERROR\",\n TOO_MANY_NUMERIC_CONSTANTS: \"TOO_MANY_NUMERIC_CONSTANTS\",\n /** A raw bytecode operand outside 0 to 255, or a jump patch outside the emitted stream (`parser/BytecodeBuilder.ts`'s `emitIndex`, `emitByte`, `patchJump`). `build()` keeps one byte per operand, so 300 used to become 44 with no error and the program read the wrong constant or plugin function. A package-authoring fault, reported at compile time. */\n BYTECODE_OPERAND_OUT_OF_RANGE: \"BYTECODE_OPERAND_OUT_OF_RANGE\",\n TOO_MANY_STRING_CONSTANTS: \"TOO_MANY_STRING_CONSTANTS\",\n NO_MATCHING_PHRASE_ALTERNATIVE: \"NO_MATCHING_PHRASE_ALTERNATIVE\",\n INVALID_PHRASE_PATTERN: \"INVALID_PHRASE_PATTERN\",\n PHRASE_KEYWORD_MISMATCH: \"PHRASE_KEYWORD_MISMATCH\",\n /** User-defined-function definition parsing (`f(x, y) = ...`), an invalid token where a parameter name was expected. */\n USER_FUNCTION_INVALID_PARAM_NAME: \"USER_FUNCTION_INVALID_PARAM_NAME\",\n /** `f() = ...` with zero parameters, indistinguishable from a plain no-arg function call, so rejected at definition time. */\n USER_FUNCTION_NO_PARAMS: \"USER_FUNCTION_NO_PARAMS\",\n /** A user-defined function body calling an async plugin (weather/stocks/currency/...), rejected at definition time; v1 scope excludes async function bodies. */\n FUNCTION_BODY_MUST_BE_SYNCHRONOUS: \"FUNCTION_BODY_MUST_BE_SYNCHRONOUS\",\n /** `BytecodeBuilder`'s `userFunctionBodies` side-table exceeding its capacity. Same class as `TOO_MANY_NUMERIC_CONSTANTS`/`TOO_MANY_STRING_CONSTANTS` below. */\n TOO_MANY_FUNCTION_DEFINITIONS: \"TOO_MANY_FUNCTION_DEFINITIONS\",\n /** `BytecodeBuilder`'s `anonymousBodies` side-table (map/reduce inline transform bodies) exceeding its capacity. Same class as `TOO_MANY_FUNCTION_DEFINITIONS` above. */\n TOO_MANY_ANONYMOUS_BODIES: \"TOO_MANY_ANONYMOUS_BODIES\",\n /** New with the 2.0 descriptor redesign: a parselet emits a plugin call by NAME (`BytecodeBuilder.emitPluginCall(name, argCount)`) and the engine resolves that name to the index it assigned at registration. This fires when the name is absent from the builder's name->index map: the package used a `pluginFunctions` name it never declared, or the expression was parsed before that package registered. Not a user-input error; a package-authoring/registration fault. See `parser/BytecodeBuilder.ts`'s `emitPluginCall()`. */\n UNKNOWN_PLUGIN_FUNCTION: \"UNKNOWN_PLUGIN_FUNCTION\",\n\n // ── VM (vm/VM.ts, vm/OpRegistry.ts, vm/VMBuiltins.ts) ──\n EVALUATION_ERROR: \"EVALUATION_ERROR\",\n INSTRUCTION_LIMIT_EXCEEDED: \"INSTRUCTION_LIMIT_EXCEEDED\",\n STACK_LIMIT_EXCEEDED: \"STACK_LIMIT_EXCEEDED\",\n /** One evaluation asking for more elements (collection Values, matrix cells) than `vm.maxAllocatedElements` allows. The counter the two limits above cannot be: both are checked between opcodes, so neither can see what a single opcode allocates inside a loop of its own. See `vm/AllocationBudget.ts`. Recoverable, since it describes this expression rather than the engine. */\n ALLOCATION_LIMIT_EXCEEDED: \"ALLOCATION_LIMIT_EXCEEDED\",\n /** New this phase. See `VM.ts`'s `safePop()`: a stack-underflow (corrupted bytecode, a buggy plugin) is now a controlled EngineError instead of a raw TypeError. Category INTERNAL, since it is an engine or plugin fault rather than a typed line, but recoverable: it happened on one line and the engine is still usable. */\n STACK_UNDERFLOW: \"STACK_UNDERFLOW\",\n UNDEFINED_VARIABLE: \"UNDEFINED_VARIABLE\",\n /** New this phase, the Tier-2/`LOAD_GLOBAL_VAR` hardening: a global variable read before its async preflight resolved, surfaced as a controlled error instead of pushing `undefined`. */\n GLOBAL_VARIABLE_NOT_RESOLVED: \"GLOBAL_VARIABLE_NOT_RESOLVED\",\n UNKNOWN_FUNCTION: \"UNKNOWN_FUNCTION\",\n /** `unwrapEvalResult()`'s pending-when-expecting-value case, a caller-contract violation, not user-input. */\n UNEXPECTED_PENDING_RESULT: \"UNEXPECTED_PENDING_RESULT\",\n /** User-defined-function call/definition errors (`CALL_USER_FUNCTION`/`DEFINE_USER_FUNCTION` opcodes), calling a name with no matching definition, calling with the wrong argument count, and the deliberate v1 restriction that a function body can't itself contain async work. */\n UNDEFINED_FUNCTION: \"UNDEFINED_FUNCTION\",\n FUNCTION_ARITY_MISMATCH: \"FUNCTION_ARITY_MISMATCH\",\n /** The same mistake against a BUILT-IN rather than a user-defined function (`sqrt()`, `atan2(1)`, `sqrt(1,2,3)`). Separate from `FUNCTION_ARITY_MISMATCH` above because the two are raised by different opcodes and a host may want to word them differently. Checked at the `CALL_BUILTIN` dispatch against `vm/VMBuiltinArity.ts`; recoverable, since it is a typo in the line, not an engine fault. */\n BUILTIN_ARITY_MISMATCH: \"BUILTIN_ARITY_MISMATCH\",\n USER_FUNCTION_ASYNC_UNSUPPORTED: \"USER_FUNCTION_ASYNC_UNSUPPORTED\",\n /** A map/reduce transform body (inline expression or user-defined function) calling an async plugin. Same v1 scope restriction as `USER_FUNCTION_ASYNC_UNSUPPORTED` above, enforced both at parse time (`MAP_REDUCE_TRANSFORM_MUST_BE_SYNCHRONOUS`, packages/mapreduce/) and as a defense-in-depth runtime backstop here. */\n MAP_REDUCE_ASYNC_UNSUPPORTED: \"MAP_REDUCE_ASYNC_UNSUPPORTED\",\n /** An algebra verb's expression argument (`BIND_UNKNOWN`'s body) calling an async plugin. Same v1 scope restriction as the two above, and likewise refused at parse time first (`SYMBOLIC_ARGUMENT_MUST_BE_SYNCHRONOUS`, packages/symbolic/). */\n SYMBOLIC_ASYNC_UNSUPPORTED: \"SYMBOLIC_ASYNC_UNSUPPORTED\",\n /** `explainLine()` asked to derive a line that resolves data asynchronously (a live-data or async-plugin line). A derivation is a sequence of settled intermediate values, which a pending result has none of, so the line is refused rather than explained with a hole in it. */\n EXPLAIN_ASYNC_UNSUPPORTED: \"EXPLAIN_ASYNC_UNSUPPORTED\",\n /** `pushCallFrame()`'s recursion guard, a nested `CALL_USER_FUNCTION` re-enters `executeBytecode()`, so `maxInstructions` alone can't catch e.g. `f(x) = f(x)`; this is the dedicated backstop. `recoverable: true` (the default for `.execution()`), ordinary user-written infinite recursion, not an engine bug; the guard exists precisely so it surfaces as a clear error instead of overflowing the native call stack uncatchably. */\n FUNCTION_RECURSION_LIMIT_EXCEEDED: \"FUNCTION_RECURSION_LIMIT_EXCEEDED\",\n /** The companion to the code above, and the half it could never see: how MANY user-defined-function calls one evaluation makes, rather than how deeply they nest. A twenty-two-line doubling chain nests twenty-two deep (legal) and makes two million calls (a fatal heap abort). Counted in `vm/AllocationBudget.ts`, because the tally has to survive `executeBytecode()` re-entering itself. Recoverable. */\n FUNCTION_CALL_LIMIT_EXCEEDED: \"FUNCTION_CALL_LIMIT_EXCEEDED\",\n /** A `<date> + N workdays` offset outside `date.maxOffsetYears`/`minOffsetYears`. Workdays are the one date offset that walks the calendar a day at a time, so the one whose cost is the offset; every other one moves a Date field once. Recoverable. */\n DATE_OFFSET_LIMIT_EXCEEDED: \"DATE_OFFSET_LIMIT_EXCEEDED\",\n /** The anchor of `N working days after/before/from <expr>` was not a date (e.g. `5 working days after 3`). The grammar guarantees the count is a number, so this only fires on the anchor. Emitted as a recoverable Error value, not thrown, matching the datetime package's other type guards. See `vm/VM.ts`'s `DATE_WORKDAY_OFFSET` case. */\n WORKDAY_OFFSET_EXPECTED_DATE: \"WORKDAY_OFFSET_EXPECTED_DATE\",\n /** An endpoint of `working days between <expr> and <expr>` was not a date. Recoverable Error value. See `vm/VM.ts`'s `DATE_WORKDAYS_BETWEEN` case. */\n WORKDAYS_BETWEEN_EXPECTED_DATES: \"WORKDAYS_BETWEEN_EXPECTED_DATES\",\n /** The two endpoints of `working days between <expr> and <expr>` are further apart than `date.maxOffsetYears`/`minOffsetYears` allow the count's calendar walk to run. Recoverable Error value, the between-count's equivalent of `DATE_OFFSET_LIMIT_EXCEEDED`. See `vm/VM.ts`'s `DATE_WORKDAYS_BETWEEN` case. */\n WORKDAYS_BETWEEN_RANGE_TOO_LARGE: \"WORKDAYS_BETWEEN_RANGE_TOO_LARGE\",\n /** A `<<`/`>>` with a bigint operand whose exact result would pass `MAX_EXACT_SHIFT_BITS`, whichever operand is the bigint. Both spellings refuse as of 1.0.0: a bigint on the left used to fall through to `x * 2^n` in doubles and report a 19,870-digit integer as Infinity. See `vm/VM.ts`'s `bigIntShift()`. Recoverable. */\n BIGINT_SHIFT_LIMIT_EXCEEDED: \"BIGINT_SHIFT_LIMIT_EXCEEDED\",\n /** The same ceiling for `^`, the operator it was written for: `2n ^ 100000` asks for the same 100,001-bit integer `1n << 100000` does, so the two spellings answer the same way. Also new in 1.0.0, and for the same reason: this used to fall through to the double path and answer Infinity. A fractional or negative exponent (`4n ^ 0.5`, `2n ^ -1`) has no exact answer to bound and still uses the double path. See `vm/VM.ts`'s `MAX_EXACT_POW_BITS`. Recoverable. */\n BIGINT_POW_LIMIT_EXCEEDED: \"BIGINT_POW_LIMIT_EXCEEDED\",\n /** An operand with no whole-number form (a fraction, an infinity, a NaN) meeting a bigint: `1n + 0.5`, `1n & 1.5`, `5n/pi`. `BigInt()` answers those with a raw RangeError, which the VM relabelled UNEXPECTED_ERROR, so a typo in the line was reported as an engine fault. Recoverable; see `vm/VMConversion.ts`'s `toBigIntOperand()`. */\n BIGINT_INEXACT_OPERAND: \"BIGINT_INEXACT_OPERAND\",\n /** `10n / 0n` and `10n mod 0n`. Deliberately NOT what `1 / 0` does, which is Infinity: a bigint division is exact integer division (`7n / 2n` is 3n), and integer division by zero has no answer, exactly as it has none in C, Java, Python or JavaScript's own BigInt. Previously V8's own RangeError, relabelled UNEXPECTED_ERROR. Recoverable; see `vm/VMConversion.ts`'s `bigIntDivisionByZero()`. */\n BIGINT_DIVISION_BY_ZERO: \"BIGINT_DIVISION_BY_ZERO\",\n /** `DEFINE_USER_FUNCTION`'s body-index lookup failing, a compiler/VM invariant violation (the opcode stream referenced a `userFunctionBodies` slot that doesn't exist), never a user-input error. */\n INTERNAL_MISSING_FUNCTION_BODY: \"INTERNAL_MISSING_FUNCTION_BODY\",\n /** `MAP_INVOKE`/`REDUCE_INVOKE`'s anonymous-body-index lookup failing. Same class as `INTERNAL_MISSING_FUNCTION_BODY` above, for the `anonymousBodies` side-table instead of `userFunctionBodies`. */\n INTERNAL_MISSING_ANONYMOUS_BODY: \"INTERNAL_MISSING_ANONYMOUS_BODY\",\n /** `CALL_BUILTIN` naming an index no builtin is registered at. It used to pop its arguments and push nothing, so the opcode after it read a neighbour's operand as its own; now an Error value on the stack, the shape `map`/`reduce` already used for the same fault. Bytecode-level, so unreachable from source without a compiler or snapshot fault. */\n UNKNOWN_BUILTIN_FUNCTION: \"UNKNOWN_BUILTIN_FUNCTION\",\n\n // ── Malformed bytecode on the public `./vm` surface (vm/VM.ts) ──\n //\n // `executeBytecode` is exported, so a bytecode program is caller input in\n // the same sense an expression string is, and these five say so. They are\n // VALIDATION rather than INTERNAL for exactly that reason: before they\n // existed, every one of these cases reached a raw TypeError (`BigInt(undefined)`,\n // `code.toUpperCase()` on a boolean, destructuring a program that was not\n // there), which normalised to UNEXPECTED_ERROR and told the caller the\n // engine was broken when their eleven bytes were. Reachable from ordinary\n // source only through a compiler bug, which is why the messages name the\n // opcode and the operand rather than the user's line.\n /** An operand byte read past the end of the stream: the program ends in the middle of an instruction. */\n MALFORMED_BYTECODE_TRUNCATED: \"MALFORMED_BYTECODE_TRUNCATED\",\n /** A constant-pool operand indexing a `numbers`/`strings` entry that does not exist, or that is not of the pool's type. */\n MALFORMED_BYTECODE_CONSTANT_INDEX: \"MALFORMED_BYTECODE_CONSTANT_INDEX\",\n /** A unit or converter name read off the value stack that is not a string. Distinct from the pool case above: the operand is a Value another opcode pushed, not a pool entry. */\n MALFORMED_BYTECODE_OPERAND_TYPE: \"MALFORMED_BYTECODE_OPERAND_TYPE\",\n /** `MAP_INVOKE`/`REDUCE_INVOKE` carrying a body kind other than 0/1/2. Used to fall through every arm with no body and recurse into `executeBytecode(undefined)`. */\n MALFORMED_BYTECODE_BODY_KIND: \"MALFORMED_BYTECODE_BODY_KIND\",\n /** A `PUSH_BIGINT` pool entry that is not a whole number, e.g. `\"1.000\"`. `BigInt()` answers that with a raw SyntaxError. */\n MALFORMED_BYTECODE_BIGINT_LITERAL: \"MALFORMED_BYTECODE_BIGINT_LITERAL\",\n /** `executeBytecode()` called with something that is not a runnable program at all. Checked before the destructure that used to throw outside the function's own try/catch. */\n MALFORMED_BYTECODE_PROGRAM: \"MALFORMED_BYTECODE_PROGRAM\",\n\n // ── Symbolic algebra (symbolic/, vm/SymbolicOps.ts) ──\n /** A coefficient grew past `RATIONAL_MAX_BITS`, e.g. repeated exact elimination multiplying denominators together. */\n SYMBOLIC_RATIONAL_OVERFLOW: \"SYMBOLIC_RATIONAL_OVERFLOW\",\n /** `NaN` or `±Infinity` reaching a symbolic expression, neither of which has an exact rational value. */\n SYMBOLIC_NONFINITE_OPERAND: \"SYMBOLIC_NONFINITE_OPERAND\",\n /** Division by an exactly-zero rational. Exact, unlike the double comparison it replaced, which could not distinguish a true zero from `5.551e-17`. */\n SYMBOLIC_DIVISION_BY_ZERO: \"SYMBOLIC_DIVISION_BY_ZERO\",\n /** A tree exceeding `SYMBOLIC_MAX_NODES` entering the simplifier. */\n SYMBOLIC_NODE_LIMIT_EXCEEDED: \"SYMBOLIC_NODE_LIMIT_EXCEEDED\",\n /** A builtin with no symbolic reading (`min`, `random`, the finance block, ...) applied to an expression still containing an unknown. Returned rather than computing against `toNumber()`'s placeholder zero. */\n SYMBOLIC_UNSUPPORTED_FUNCTION: \"SYMBOLIC_UNSUPPORTED_FUNCTION\",\n /** The rational-root search exceeding `FACTOR_MAX_ROOT_CANDIDATES`. The candidate set is the product of two divisor sets, so a highly-composite coefficient escapes quickly. */\n SYMBOLIC_FACTOR_LIMIT_EXCEEDED: \"SYMBOLIC_FACTOR_LIMIT_EXCEEDED\",\n /** An equation outside what the solver attempts: not a polynomial, above the degree ceiling, or non-linear in the unknown while another unknown is present. */\n SYMBOLIC_SOLVE_UNSUPPORTED: \"SYMBOLIC_SOLVE_UNSUPPORTED\",\n /** Some but not all of an equation's roots were found. Reported rather than returned, because a partial list of roots looks exactly like a complete one. */\n SYMBOLIC_SOLVE_INCOMPLETE: \"SYMBOLIC_SOLVE_INCOMPLETE\",\n /** `solve`'s second argument not being a bare name. */\n SOLVE_REQUIRES_VARIABLE_NAME: \"SOLVE_REQUIRES_VARIABLE_NAME\",\n /** A derivative order outside 0..`DERIVATIVE_MAX_ORDER`. */\n SYMBOLIC_DERIVATIVE_ORDER_LIMIT: \"SYMBOLIC_DERIVATIVE_ORDER_LIMIT\",\n /** An expression with no known elementary antiderivative. Reported rather than approximated, since a wrong integral is indistinguishable from a right one at the point of use. */\n SYMBOLIC_INTEGRAL_UNSUPPORTED: \"SYMBOLIC_INTEGRAL_UNSUPPORTED\",\n /** A Taylor degree outside 0..`TAYLOR_MAX_DEGREE`. */\n SYMBOLIC_TAYLOR_DEGREE_LIMIT: \"SYMBOLIC_TAYLOR_DEGREE_LIMIT\",\n /** A Taylor coefficient that does not reduce to an exact number at the expansion point. */\n SYMBOLIC_TAYLOR_INEXACT: \"SYMBOLIC_TAYLOR_INEXACT\",\n /** An algebra verb's variable-name argument not being a bare name. */\n SYMBOLIC_REQUIRES_VARIABLE_NAME: \"SYMBOLIC_REQUIRES_VARIABLE_NAME\",\n /** `jacobian` called with expressions containing no unknown to differentiate against. */\n SYMBOLIC_JACOBIAN_NO_VARIABLES: \"SYMBOLIC_JACOBIAN_NO_VARIABLES\",\n /** A finite number whose decimal form could not be read back, which the regex covering every `Number.prototype.toString` output should make unreachable. */\n INTERNAL_RATIONAL_PARSE: \"INTERNAL_RATIONAL_PARSE\",\n\n // ── Engine (engine/ExpressionEngine.ts, engine/ExpressionEngineSafety.ts, engine/AsyncResolutionBatcher.ts) ──\n EXPRESSION_TOO_LONG: \"EXPRESSION_TOO_LONG\",\n EXPRESSION_TOO_COMPLEX: \"EXPRESSION_TOO_COMPLEX\",\n /** A document with more lines than `performance.maxDocumentLines`. The per-line limits above bound what one line may ask for and say nothing about how many lines there are; two hundred thousand of `1 + 1` exhausted the heap on the line records alone. Recoverable. */\n DOCUMENT_TOO_LARGE: \"DOCUMENT_TOO_LARGE\",\n NORMALIZED_TOKEN_LIMIT_EXCEEDED: \"NORMALIZED_TOKEN_LIMIT_EXCEEDED\",\n /** `\"=>\"` with nothing before it, needs an expression or variable name to solve/simplify. */\n THEREFORE_REQUIRES_EXPRESSION: \"THEREFORE_REQUIRES_EXPRESSION\",\n /** A `\"=>\"`-triggered expression called an async plugin (weather/stocks/currency). Same v1 scope restriction as user-function/map-reduce bodies. */\n THEREFORE_ASYNC_UNSUPPORTED: \"THEREFORE_ASYNC_UNSUPPORTED\",\n /** A compound assignment (`name += expr` / `name -= expr`) with nothing on the right, a line half-typed on the way to `total += 5`. */\n COMPOUND_ASSIGN_REQUIRES_EXPRESSION: \"COMPOUND_ASSIGN_REQUIRES_EXPRESSION\",\n /** A running total (`+= / -=`) whose right-hand side calls an async plugin (weather/stocks/currency). The same v1 scope restriction as the `\"=>\"` and user-function bodies. */\n COMPOUND_ASSIGN_ASYNC_UNSUPPORTED: \"COMPOUND_ASSIGN_ASYNC_UNSUPPORTED\",\n /** A savings-goal contribution period that is not one of daily/weekly/monthly/yearly (`how long to save $X at $Y <period>`). Names the accepted set. */\n UNKNOWN_SAVINGS_PERIOD: \"UNKNOWN_SAVINGS_PERIOD\",\n /** Colon-separated numbers that are not a time any clock can show (\"24:00\", \"9:60\", \"100:5\"). Raised by the labeled-line fallback, which used to answer them with whatever stood after the colon. */\n INVALID_TIME_LITERAL: \"INVALID_TIME_LITERAL\",\n /** A live-data form evaluated on an engine whose host switched the network off (`network.enabled: false`, see `constants/Configuration.ts`'s `NetworkConfig`). A recoverable Error value, raised by the VM for a currency conversion with no primed rate and for a plugin function that returned a promise, and by `createQueryResolver`'s plugin function when its preflight was skipped. Names the setting, so the reader knows it is policy rather than an outage. */\n NETWORK_DISABLED: \"NETWORK_DISABLED\",\n\n // ── Temporal calendar backend (temporal/TemporalCalendar.ts) ──\n /** `createTemporalCalendar()` was handed something that is not a usable `Temporal` implementation: no `Now.instant`, `Now.timeZoneId`, `Instant.fromEpochMilliseconds` or `PlainDateTime.from`. Raised at construction, naming the missing member, rather than letting the first date computation fail on it obscurely. */\n TEMPORAL_IMPLEMENTATION_INVALID: \"TEMPORAL_IMPLEMENTATION_INVALID\",\n /** The `timeZone` given to `createTemporalCalendar()` is not one the `Temporal` implementation knows. Raised at construction, so a misspelt zone is a configuration error the host sees once, not a `RangeError` from inside every date the engine computes. */\n TEMPORAL_TIME_ZONE_UNKNOWN: \"TEMPORAL_TIME_ZONE_UNKNOWN\",\n\n // ── Snapshot / restore (engine/EngineSnapshot.ts, engine/ExpressionEngine.ts) ──\n /** `fromJSON()` handed an object that is not a snapshot at all, or whose serialised-shape version does not match this engine's reader. The versioning gate that refuses an incompatible snapshot clearly rather than restoring it wrongly. See `engine/EngineSnapshot.ts`'s `assertRestorable()`. */\n SNAPSHOT_VERSION_MISMATCH: \"SNAPSHOT_VERSION_MISMATCH\",\n /** A snapshot with the right envelope but internally inconsistent contents (an unrecognised number sentinel, an unknown value tag). Distinct from a version mismatch: the format is right, the payload is not. */\n SNAPSHOT_MALFORMED: \"SNAPSHOT_MALFORMED\",\n /** A value the v1 snapshot format cannot yet represent (a symbolic/algebra value, a symbolic matrix cell). Deferred to a follow-up; refused by name rather than dropped silently. */\n SNAPSHOT_UNSUPPORTED_VALUE: \"SNAPSHOT_UNSUPPORTED_VALUE\",\n\n // ── Config (constants/Configuration.ts) ──\n CONFIG_PATH_NOT_FOUND: \"CONFIG_PATH_NOT_FOUND\",\n INVALID_CONFIG_PATH: \"INVALID_CONFIG_PATH\",\n CONFIG_SECTION_NOT_FOUND: \"CONFIG_SECTION_NOT_FOUND\",\n CONFIG_PROPERTY_NOT_FOUND: \"CONFIG_PROPERTY_NOT_FOUND\",\n\n // ── Package/lexer registration-time collisions (lexer/ExpressionLexer.ts) ──\n /** `calendar: \"temporal\"` was asked for on a runtime with no `Temporal`. Refused rather than silently computing on `Date`, because a host that named Temporal did so to be sure what it was computing on. Recoverable. */\n CALENDAR_TEMPORAL_UNAVAILABLE: \"CALENDAR_TEMPORAL_UNAVAILABLE\",\n PLUGIN_OPERATOR_COLLISION: \"PLUGIN_OPERATOR_COLLISION\",\n PLUGIN_KEYWORD_COLLISION: \"PLUGIN_KEYWORD_COLLISION\",\n PLUGIN_UNIT_COLLISION: \"PLUGIN_UNIT_COLLISION\",\n /** A package's declared `IEnginePackage.engineVersion` semver range doesn't satisfy the running engine's ENGINE_VERSION. See api/EngineVersionCompatibility.ts. */\n PACKAGE_ENGINE_VERSION_MISMATCH: \"PACKAGE_ENGINE_VERSION_MISMATCH\",\n /** A package's declared `IEnginePackage.engineVersion` isn't a parseable semver range at all (a typo in the package's own descriptor). */\n PACKAGE_ENGINE_VERSION_INVALID_RANGE: \"PACKAGE_ENGINE_VERSION_INVALID_RANGE\",\n /** `OpRegistry.allocateOpcode()`'s dynamic opcode pool (started at 201) exhausted, too many packages calling it. */\n OPCODE_POOL_EXHAUSTED: \"OPCODE_POOL_EXHAUSTED\",\n /** `VMBuiltins.allocatePluginFunctionIndex()`'s index pool (up to 65536, two opcode-stream bytes) exhausted. */\n PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED: \"PLUGIN_FUNCTION_INDEX_POOL_EXHAUSTED\",\n /** A plugin-function index exceeds the two-byte (65535) `CALL_PLUGIN_WIDE` bytecode operand. */\n PLUGIN_FUNCTION_INDEX_TOO_LARGE: \"PLUGIN_FUNCTION_INDEX_TOO_LARGE\",\n\n // ── vm/Value.ts caller-contract violations (check isRateUnit()/isTimecodeUnit() first) ──\n INVALID_RATE_UNIT: \"INVALID_RATE_UNIT\",\n INVALID_TIMECODE_UNIT: \"INVALID_TIMECODE_UNIT\",\n\n // ── errors/EngineError.ts's own fallback normalization ──\n UNEXPECTED_ERROR: \"UNEXPECTED_ERROR\",\n UNKNOWN_ERROR: \"UNKNOWN_ERROR\",\n} as const;\n\n/** Every error code the engine's own layers can produce, from {@link CoreErrorCodes}. */\nexport type CoreErrorCode = (typeof CoreErrorCodes)[keyof typeof CoreErrorCodes];\n\n/**\n * Codes for the datetime forms whose failure is raised OUTSIDE the datetime\n * package.\n *\n * These sit here rather than beside the datetime parselets, which is where a\n * package's own code object belongs, because the two sites that raise them are\n * `vm/VM.ts` (the `in <zone>` branch of the unit-conversion opcode) and\n * `calendar/DateCalendar.ts` (the zone-bound backend factory), and neither may\n * import from `packages/`. A code object in the datetime package would put the\n * name a core file needs on the wrong side of that line.\n */\nexport const DatetimeErrorCodes = {\n /** `2026-04-03 in Atlantis`: a Datetime met `in <name>` and the name is neither a zone this engine knows nor a unit. Before this code the epoch-millisecond payload was simply labelled with the name, and the line answered a fourteen-digit quantity in a unit called Atlantis. */\n DATETIME_ZONE_UNKNOWN: \"DATETIME_ZONE_UNKNOWN\",\n /** `2026-04-03 in furlongs`: the same handler, where the name IS a real unit. Separate from `DATETIME_ZONE_UNKNOWN` because the two mistakes have different fixes: one is a misspelt zone, the other is a category error, and a message that suggests checking the spelling of `furlongs` would be no help at all. */\n DATETIME_NOT_CONVERTIBLE: \"DATETIME_NOT_CONVERTIBLE\",\n /** `dateCalendarInZone(\"Europe/Atlantis\")`: the zone-bound `Date` backend factory, given a zone this runtime's `Intl` cannot format with. Raised at construction rather than per line, because a backend that cannot compute in the zone it was asked for must not silently answer in another one. */\n DATE_ZONE_UNKNOWN: \"DATE_ZONE_UNKNOWN\",\n} as const;\n\n/** Every code from {@link DatetimeErrorCodes}. */\nexport type DatetimeErrorCode = (typeof DatetimeErrorCodes)[keyof typeof DatetimeErrorCodes];\n\n/**\n * The aggregated catalog type. Currently `CoreErrorCode` and\n * `DatetimeErrorCode`, union in each package's own code-object type here as\n * Phase 5 converts it, e.g. `CoreErrorCode | WeatherErrorCode | ...`.\n */\nexport type ErrorCode = CoreErrorCode | DatetimeErrorCode;\n"]}
@@ -0,0 +1,2 @@
1
+ import {c as c$2}from'./chunk-JP4JMQOG.js';import {b,a as a$2,e,d}from'./chunk-YG7UWQFV.js';import {b as b$1}from'./chunk-BLJ6E577.js';import {c,a}from'./chunk-FAO6DQ74.js';import {a as a$1}from'./chunk-LHLW7JLS.js';import {c as c$1}from'./chunk-VB6QMU2W.js';var D=/^\d{1,3}(\.\d{3}){2,}$/,T=/^\d*\.\d*$/,n=class n{constructor(e,t=50,r="en",l,a=b$1){this.tokens=[];this.current=0;this.depth=0;this.currentExpression="";this.infixMinBindingPower=0;this.registry=e,this.maxDepth=t,this.localeCode=r;let p=a$1(r).display;this.decimalSeparator=p.decimalSeparator,this.thousandsSeparator=p.thousandsSeparator,this.pluginFunctionIndex=l,this.calendar=a;}getLocaleCode(){return this.localeCode}getCalendar(){return this.calendar}setDiagnosticPipeline(e,t){this.diagnosticPipeline=e,this.currentExpression=t??"";}load(e,t){if(t===false){this.tokens=e,this.current=0,this.depth=0;return}let r=c(a.LPAREN),l=c(a.RPAREN),a$1=0;for(let p=0;p<e.length;p++)e[p].typeId===r?a$1++:e[p].typeId===l&&a$1--;this.tokens=a$1===0?e:this.balanceParens(e,a$1),this.current=0,this.depth=0;}balanceParens(e,t){let r=e.slice();if(t>0){let l=c(a.RPAREN);for(let a$1=0;a$1<t;a$1++){let p=e[e.length-1];r.push({type:a.RPAREN,typeId:l,value:")",text:")",offset:p?p.offset+p.text.length:0,lineBreaks:0,line:p?p.line:1,col:p?p.col+p.text.length:1});}}else if(t<0){let l=c(a.LPAREN);for(let a$1=0;a$1<-t;a$1++)r.unshift({type:a.LPAREN,typeId:l,value:"(",text:"(",offset:0,lineBreaks:0,line:1,col:1});}return r}parseExpression(e=0,t){let r=this.builder;t&&(this.builder=t),this.depth++;try{if(this.depth>this.maxDepth)throw c$1.parsing("NESTING_DEPTH_EXCEEDED",`Parse nesting depth ${this.depth} exceeds maximum of ${this.maxDepth}`,{maxDepth:this.maxDepth,currentDepth:this.depth});this.parseExpressionBody(e);}finally{this.depth--,t&&(this.builder=r);}}parseExpressionBody(e){let t=this.consume();if(!t)throw c$1.parsing({code:"UNEXPECTED_END",message:"Unexpected end of expression",span:this.spanAtEnd()});this.parsePrefix(t);let r=this.tokens,l=r.length,a=n.BP_TABLE,p=this.registry,o=this.builder,h=this.current;for(;h<l;){let d=r[h];if(!d)break;let c=a[d.typeId];if(c>0){if(c<=e)break;if(this.diagnosticPipeline){let I=p.getInfix(d.typeId);I&&this.fireParseletMatched(I,d,false,c);}this.current=++h;let f=d.typeId;if(f===n.PERCENT_ID)o.emitOpcode(10),o.emitNumber(100),o.emitOpcode(23),o.emitOpcode(74);else if(!(f===n.CARET_ID&&this.tryEmitMatrixCaretOp(o))){let I=f===n.CARET_ID?c-1:c+1;this.parseExpression(I,o),o.emitOpcode(n.INFIX_OPCODE[f]);}}else {let f=p.getInfix(d.typeId);if(!f||f.bindingPower<=e)break;this.current=++h,this.diagnosticPipeline&&this.fireParseletMatched(f,d,false,f.bindingPower);let I=this.infixMinBindingPower;this.infixMinBindingPower=e;try{f.parse(this,t,d,o);}finally{this.infixMinBindingPower=I;}}h=this.current;}this.current=h;}parsePrefix(e$1){let t=this.builder,r=e$1.typeId;if(this.diagnosticPipeline){let a=this.registry.getPrefix(r);a&&this.fireParseletMatched(a,e$1,true);}switch(r){case n.NUMBER_ID:{let a,p=null,o=e$1.value;if(this.decimalSeparator==="."){let h=0,d=o.length>0;for(let c=0;c<o.length;c++){let f=o.charCodeAt(c);if(!(f>=48&&f<=57)){if(f===46&&h===0){h=1;continue}d=false;break}}if(d){if(h===1){t.emitOpcode(16),t.emitString(o);return}t.emitOpcode(10),t.emitNumber(+o);return}}if(o.startsWith("0x")||o.startsWith("0X")){if(a=parseInt(o,16),Number.isNaN(a))throw c$1.parsing({code:"INVALID_NUMBER_LITERAL",message:`Invalid hex literal: "${o}"`,context:{raw:o},span:this.spanOf(e$1)})}else if(o.startsWith("0b")||o.startsWith("0B")){if(a=parseInt(o.slice(2),2),Number.isNaN(a))throw c$1.parsing({code:"INVALID_NUMBER_LITERAL",message:`Invalid binary literal: "${o}"`,context:{raw:o},span:this.spanOf(e$1)})}else if(o.startsWith("0o")||o.startsWith("0O")){if(a=parseInt(o.slice(2),8),Number.isNaN(a))throw c$1.parsing({code:"INVALID_NUMBER_LITERAL",message:`Invalid octal literal: "${o}"`,context:{raw:o},span:this.spanOf(e$1)})}else if(D.test(o))a=parseFloat(o.split(".").join(""));else {let h=this.decimalSeparator,d=this.thousandsSeparator,c=o;d&&c.indexOf(d)!==-1&&(c=c.split(d).join("")),h&&h!=="."&&(c=c.replace(h,".")),a=parseFloat(c),T.test(c)&&(p=c);}if(p!==null){t.emitOpcode(16),t.emitString(p);return}t.emitOpcode(10),t.emitNumber(a);return}case n.BIGINT_ID:{t.emitOpcode(11),t.emitString(e(e$1.value,this.localeCode));return}case n.STRING_ID:{t.emitOpcode(13),t.emitString(e$1.value);return}case n.IDENT_ID:{if(this.peek()?.typeId===n.LPAREN_ID){this.parseUserFunctionDefOrCall(e$1,t);return}t.emitOpcode(60),t.emitString(e$1.value);return}case n.LPAREN_ID:{this.parseExpression(0,t);let a$1=1;for(;this.match(a.COMMA);)this.parseExpression(0,t),a$1++;this.consume(a.RPAREN),a$1>1&&(t.emitOpcode(152),t.emitIndex(1),t.emitIndex(a$1));return}case n.MINUS_ID:{this.parseExpression(a$2.Prefix,t),t.emitOpcode(26);return}case n.PLUS_ID:{this.parseExpression(a$2.Prefix,t),t.emitOpcode(27);return}case n.KEYWORD_ID:}let l=this.registry.getPrefix(r);if(!l)throw c$1.parsing({code:"NO_PREFIX_PARSELET",message:`No prefix parselet found for token: ${e$1.type} ("${e$1.value}")`,context:{tokenType:e$1.type,tokenValue:e$1.value},span:this.spanOf(e$1)});l.parse(this,e$1,t);}tryEmitMatrixCaretOp(e){for(let t of n.CARET_SUFFIX_RULES)if(t.matches(this))return t.emit(this,e),true;return false}findMatchingRParen(e){let t=0;for(let r=e;r<this.tokens.length;r++){let l=this.tokens[r];if(l.typeId===n.LPAREN_ID)t++;else if(l.typeId===n.RPAREN_ID&&(t--,t===0))return r}return null}parseUserFunctionDefOrCall(e,t){let r=this.findMatchingRParen(this.current);if(r===null){t.emitOpcode(60),t.emitString(e.value);return}this.tokens[r+1]?.type===a.EQUALS?this.parseUserFunctionDefinition(e,t):this.parseUserFunctionCall(e,t);}consumeParamName(){let e=this.peek();if(e?.type===a.IDENT||e?.type===a.UNIT)return this.consume(),e.value;throw c$1.parsing({code:"USER_FUNCTION_INVALID_PARAM_NAME",message:`Expected a parameter name but got "${e?.type??"end of input"}"${e?` ("${e.value}")`:""}`,context:{actualType:e?.type},span:e?this.spanOf(e):this.spanAtEnd()})}parseUserFunctionDefinition(e,t){this.consume(a.LPAREN);let r=[];if(this.peek()?.type!==a.RPAREN)for(r.push(this.consumeParamName());this.match(a.COMMA);)r.push(this.consumeParamName());if(this.consume(a.RPAREN),this.consume(a.EQUALS),r.length===0)throw c$1.parsing({code:"USER_FUNCTION_NO_PARAMS",message:`"${e.value}()" has no parameters -- user-defined functions need at least one (a zero-argument definition is indistinguishable from a plain function CALL with no args, which this grammar doesn't otherwise support)`,context:{name:e.value},span:this.spanOf(e)});let l=new d(this.pluginFunctionIndex);this.parseExpression(a$2.Lowest,l),this.setBuilder(t);let a$1=l.build();if(a$1.hasAsync)throw c$1.parsing({code:"FUNCTION_BODY_MUST_BE_SYNCHRONOUS",message:`"${e.value}(...)"'s body calls an async operation (weather, stocks, currency, ...) \u2014 user-defined function bodies must be synchronous`,context:{name:e.value},span:this.spanOf(e)});let p=t.emitUserFunctionBody(e.value,r,a$1);t.emitOpcode(150),t.emitIndex(p),t.emitOpcode(13),t.emitString(`${e.value}(${r.join(", ")}) defined`);}parseUserFunctionCall(e,t){this.consume(a.LPAREN);let r=0;if(this.peek()?.type!==a.RPAREN)for(this.parseExpression(a$2.Lowest,t),r++;this.match(a.COMMA);)this.parseExpression(a$2.Lowest,t),r++;this.consume(a.RPAREN),t.emitOpcode(151),t.emitString(e.value),t.emitByte(r);}spanOf(e){return {start:e.offset,end:e.sourceEnd??e.offset+e.text.length,line:e.line,col:e.col}}spanAtEnd(){let e=this.tokens[this.tokens.length-1];if(!e)return {start:0,end:0};let t=e.sourceEnd??e.offset+e.text.length;return {start:t,end:t,line:e.line,col:e.col+(t-e.offset)}}consume(e){let t=this.tokens[this.current];if(!t)throw c$1.parsing({code:"UNEXPECTED_END_OF_INPUT",message:"Unexpected end of input",span:this.spanAtEnd()});if(e!==void 0){let r=c(e);if(t.typeId!==r)throw c$1.parsing({code:"UNEXPECTED_TOKEN_TYPE",message:`Expected token type "${e}" but got "${t.type}" ("${t.value}")`,context:{expectedType:e,actualType:t.type,actualValue:t.value},span:this.spanOf(t)})}return this.current++,t}match(e){let t=this.peek();return t&&t.typeId===c(e)?(this.advance(),true):false}peek(){return this.tokens[this.current]}peekAt(e){return this.tokens[this.current+e]}previous(){return this.current>0?this.tokens[this.current-1]:void 0}advance(){this.current++;}setBuilder(e){this.builder=e;}fireParseletMatched(e,t,r,l){let a=this.diagnosticPipeline,p={type:c$2.ParseletMatched,elapsedNs:0,expression:this.currentExpression,tokenType:t.type,tokenValue:t.value,parseletCategory:e.category,parseletType:e.constructor?.name??"unknown",isPrefix:r,bindingPower:l,tokenOffset:t.offset||0};a.fireParseletMatched(p);}};n.BP_TABLE=b(),n.NUMBER_ID=c(a.NUMBER),n.BIGINT_ID=c(a.BIGINT),n.STRING_ID=c(a.STRING),n.IDENT_ID=c(a.IDENT),n.LPAREN_ID=c(a.LPAREN),n.RPAREN_ID=c(a.RPAREN),n.MINUS_ID=c(a.MINUS),n.PLUS_ID=c(a.PLUS),n.KEYWORD_ID=c(a.KEYWORD),n.STAR_ID=c(a.STAR),n.SLASH_ID=c(a.SLASH),n.MOD_ID=c(a.MOD),n.CARET_ID=c(a.CARET),n.LSHIFT_ID=c(a.LSHIFT),n.RSHIFT_ID=c(a.RSHIFT),n.URSHIFT_ID=c(a.URSHIFT),n.BIT_AND_ID=c(a.BIT_AND),n.BIT_OR_ID=c(a.BIT_OR),n.BIT_XOR_ID=c(a.BIT_XOR),n.PERCENT_ID=c(a.PERCENT),n.OF_ID=c(a.OF),n.INFIX_OPCODE={[c(a.PLUS)]:20,[c(a.MINUS)]:21,[c(a.STAR)]:22,[c(a.SLASH)]:23,[c(a.MOD)]:24,[c(a.CARET)]:25,[c(a.LSHIFT)]:30,[c(a.RSHIFT)]:31,[c(a.URSHIFT)]:32,[c(a.BIT_AND)]:33,[c(a.BIT_OR)]:34,[c(a.BIT_XOR)]:35,[c(a.OF)]:22},n.CARET_SUFFIX_RULES=[{name:"transpose (^T)",matches:e=>{let t=e.peek();return t?.type===a.IDENT&&t.value==="T"},emit:(e,t)=>{e.advance(),t.emitOpcode(51),t.emitIndex(63),t.emitIndex(1);}},{name:"inverse (^-1)",matches:e=>{if(e.peek()?.typeId!==n.MINUS_ID)return false;let r=e.peekAt(1);return r?.type===a.NUMBER&&r.value==="1"},emit:(e,t)=>{e.advance(),e.advance(),t.emitOpcode(51),t.emitIndex(65),t.emitIndex(1);}}];var v=n;var m=class{constructor(){this.prefixParselets=new Map;this.infixParselets=new Map;this.prefixById=new Map;this.infixById=new Map;}registerPrefix(e,t){let r=this.prefixParselets.get(e);r&&r!==t&&console.warn(`[ParseletRegistry] Prefix parselet for token "${e}" is already registered (category: "${r.category??"unknown"}"). Overwriting with a new parselet (category: "${t.category??"unknown"}") \u2014 the previous parselet is now unreachable. Two packages may be claiming the same token type.`),this.prefixParselets.set(e,t),this.prefixById.set(c(e),t);}registerInfix(e,t){let r=this.infixParselets.get(e);r&&r!==t&&console.warn(`[ParseletRegistry] Infix parselet for token "${e}" is already registered (category: "${r.category??"unknown"}"). Overwriting with a new parselet (category: "${t.category??"unknown"}") \u2014 the previous parselet is now unreachable. Two packages may be claiming the same token type.`),this.infixParselets.set(e,t),this.infixById.set(c(e),t);}getAllPrefix(){let e=[];for(let[t,r]of this.prefixParselets)e.push({tokenType:t,bindingPower:r.bindingPower??a$2.Prefix,category:r.category});return e}getAllInfix(){let e=[];for(let[t,r]of this.infixParselets){let l=r.bindingPower??0;e.push({tokenType:t,leftBindingPower:l,rightBindingPower:l+1,category:r.category});}return e}get prefixCount(){return this.prefixParselets.size}get infixCount(){return this.infixParselets.size}getPrefix(e){return typeof e=="number"?this.prefixById.get(e):this.prefixParselets.get(e)}getInfix(e){return typeof e=="number"?this.infixById.get(e):this.infixParselets.get(e)}hasPrefix(e){return this.prefixParselets.has(e)}hasInfix(e){return this.infixParselets.has(e)}clear(){this.prefixParselets.clear(),this.infixParselets.clear(),this.prefixById.clear(),this.infixById.clear();}},$=new m;export{v as a,m as b,$ as c};//# sourceMappingURL=chunk-VQO54ZMA.js.map
2
+ //# sourceMappingURL=chunk-VQO54ZMA.js.map