solve-engine 2.23.0 → 2.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/README.md +82 -32
  2. package/dist/{BytecodeBuilder-aqVa7Plx.d.cts → BytecodeBuilder-DSWKZi4f.d.cts} +11 -9
  3. package/dist/{BytecodeBuilder-aqVa7Plx.d.ts → BytecodeBuilder-DSWKZi4f.d.ts} +11 -9
  4. package/dist/{Configuration-BGQn-cJ8.d.cts → Configuration-DnzYPmoK.d.cts} +33 -0
  5. package/dist/{Configuration-BGQn-cJ8.d.ts → Configuration-DnzYPmoK.d.ts} +33 -0
  6. package/dist/{EngineError-DTk7I7hZ.d.cts → EngineError-fR1K1rvx.d.cts} +6 -0
  7. package/dist/{EngineError-DTk7I7hZ.d.ts → EngineError-fR1K1rvx.d.ts} +6 -0
  8. package/dist/{Lexer-CqagTewQ.d.ts → Lexer-Bmctxl0n.d.ts} +84 -35
  9. package/dist/{Lexer-CCHFDcgP.d.cts → Lexer-aB95pjoX.d.cts} +84 -35
  10. package/dist/{PackageCompatibility-BGXSFuL9.d.ts → PackageCompatibility-BludTs7v.d.ts} +1 -1
  11. package/dist/{PackageCompatibility-BZCqaTOO.d.cts → PackageCompatibility-CUVg8tmt.d.cts} +1 -1
  12. package/dist/{PackageRegistry-BRoVOYzg.d.ts → PackageRegistry-DT-x32OM.d.ts} +67 -14
  13. package/dist/{PackageRegistry-rMGnTh7W.d.cts → PackageRegistry-Dvn4i2QK.d.cts} +67 -14
  14. package/dist/{Parselet-Bkbp9CKD.d.cts → Parselet-BawfGuTF.d.cts} +8 -2
  15. package/dist/{Parselet-B-WyUtX4.d.ts → Parselet-DqTbbtWA.d.ts} +8 -2
  16. package/dist/{ScopeManager-gB9UengK.d.ts → ScopeManager-B636am7Y.d.ts} +39 -8
  17. package/dist/{ScopeManager-bCYewWVt.d.cts → ScopeManager-CdwX0VTw.d.cts} +39 -8
  18. package/dist/{TokenNormalizer-OTPS0Otq.d.ts → TokenNormalizer-CLBtiE8M.d.ts} +45 -26
  19. package/dist/{TokenNormalizer-MXaKLJ_m.d.cts → TokenNormalizer-CjTDmHgB.d.cts} +45 -26
  20. package/dist/{VMCheckpoints-DGar9Yg8.d.cts → VMCheckpoints-CYqeq8IV.d.cts} +3 -3
  21. package/dist/{VMCheckpoints-BDRY1Kx8.d.ts → VMCheckpoints-DDlxNssY.d.ts} +3 -3
  22. package/dist/{Value-DCTqTSeP.d.cts → Value-Ds3Gy07C.d.cts} +1 -1
  23. package/dist/{Value-DCTqTSeP.d.ts → Value-Ds3Gy07C.d.ts} +1 -1
  24. package/dist/{WorkerError-DGBNM3gA.d.cts → WorkerError-B1dF3VYT.d.cts} +1 -1
  25. package/dist/{WorkerError-DpZgKRks.d.ts → WorkerError-dneODN-u.d.ts} +1 -1
  26. package/dist/{chunk-YAONCEAW.cjs → chunk-4BAUQE6A.cjs} +3 -3
  27. package/dist/{chunk-YAONCEAW.cjs.map → chunk-4BAUQE6A.cjs.map} +1 -1
  28. package/dist/chunk-4BRTUFTH.js +2 -0
  29. package/dist/chunk-4BRTUFTH.js.map +1 -0
  30. package/dist/chunk-4NZXCHQL.cjs +2 -0
  31. package/dist/chunk-4NZXCHQL.cjs.map +1 -0
  32. package/dist/chunk-57PSJQQW.js +3 -0
  33. package/dist/chunk-57PSJQQW.js.map +1 -0
  34. package/dist/chunk-634ILVMP.cjs +2 -0
  35. package/dist/chunk-634ILVMP.cjs.map +1 -0
  36. package/dist/{chunk-HMC7FJO7.js → chunk-63ZOOUOL.js} +2 -2
  37. package/dist/{chunk-HMC7FJO7.js.map → chunk-63ZOOUOL.js.map} +1 -1
  38. package/dist/chunk-72PYPENZ.js +2 -0
  39. package/dist/chunk-72PYPENZ.js.map +1 -0
  40. package/dist/chunk-77KI7AKJ.cjs +2 -0
  41. package/dist/chunk-77KI7AKJ.cjs.map +1 -0
  42. package/dist/chunk-7DP57BA7.js +2 -0
  43. package/dist/chunk-7DP57BA7.js.map +1 -0
  44. package/dist/chunk-7N3IJSWF.js +5 -0
  45. package/dist/chunk-7N3IJSWF.js.map +1 -0
  46. package/dist/chunk-BMXYR5LI.cjs +2 -0
  47. package/dist/chunk-BMXYR5LI.cjs.map +1 -0
  48. package/dist/chunk-DUYTXLO2.js +2 -0
  49. package/dist/chunk-DUYTXLO2.js.map +1 -0
  50. package/dist/chunk-EL2XUOWX.js +2 -0
  51. package/dist/chunk-EL2XUOWX.js.map +1 -0
  52. package/dist/chunk-FYAMQFZZ.cjs +3 -0
  53. package/dist/chunk-FYAMQFZZ.cjs.map +1 -0
  54. package/dist/chunk-FYTB7SDP.cjs +2 -0
  55. package/dist/chunk-FYTB7SDP.cjs.map +1 -0
  56. package/dist/chunk-GBCN7FNV.cjs +2 -0
  57. package/dist/chunk-GBCN7FNV.cjs.map +1 -0
  58. package/dist/{chunk-7E7NXKQ5.js → chunk-IJHL3LMH.js} +2 -2
  59. package/dist/chunk-IJHL3LMH.js.map +1 -0
  60. package/dist/{chunk-4ETS224G.js → chunk-JFZ5SLF7.js} +2 -2
  61. package/dist/{chunk-4ETS224G.js.map → chunk-JFZ5SLF7.js.map} +1 -1
  62. package/dist/chunk-JSM3O7EM.cjs +2 -0
  63. package/dist/chunk-JSM3O7EM.cjs.map +1 -0
  64. package/dist/chunk-MZMA32NE.js +3 -0
  65. package/dist/chunk-MZMA32NE.js.map +1 -0
  66. package/dist/chunk-N4SSR7Q6.js +2 -0
  67. package/dist/chunk-N4SSR7Q6.js.map +1 -0
  68. package/dist/{chunk-TL545PXW.cjs → chunk-NEGZZB7F.cjs} +2 -2
  69. package/dist/{chunk-TL545PXW.cjs.map → chunk-NEGZZB7F.cjs.map} +1 -1
  70. package/dist/{chunk-3GR46UOX.js → chunk-NMU5E7W7.js} +2 -2
  71. package/dist/{chunk-3GR46UOX.js.map → chunk-NMU5E7W7.js.map} +1 -1
  72. package/dist/chunk-OB2VX4IL.js +2 -0
  73. package/dist/chunk-OB2VX4IL.js.map +1 -0
  74. package/dist/{chunk-MRRMIBHE.js → chunk-OONQ3V3I.js} +2 -2
  75. package/dist/{chunk-MRRMIBHE.js.map → chunk-OONQ3V3I.js.map} +1 -1
  76. package/dist/{chunk-N37PUZJR.cjs → chunk-RAPEZR5L.cjs} +2 -2
  77. package/dist/{chunk-N37PUZJR.cjs.map → chunk-RAPEZR5L.cjs.map} +1 -1
  78. package/dist/{chunk-KEA5HRL3.js → chunk-RDYXH7ML.js} +2 -2
  79. package/dist/{chunk-KEA5HRL3.js.map → chunk-RDYXH7ML.js.map} +1 -1
  80. package/dist/{chunk-3SSMOVWB.cjs → chunk-SAF3B3AX.cjs} +2 -2
  81. package/dist/{chunk-3SSMOVWB.cjs.map → chunk-SAF3B3AX.cjs.map} +1 -1
  82. package/dist/chunk-SPOVFRZO.cjs +5 -0
  83. package/dist/chunk-SPOVFRZO.cjs.map +1 -0
  84. package/dist/{chunk-75JLWK4L.cjs → chunk-SQHBOWES.cjs} +2 -2
  85. package/dist/{chunk-75JLWK4L.cjs.map → chunk-SQHBOWES.cjs.map} +1 -1
  86. package/dist/chunk-UF5XMZTT.js +2 -0
  87. package/dist/chunk-UF5XMZTT.js.map +1 -0
  88. package/dist/chunk-UV3EUIBT.cjs +3 -0
  89. package/dist/chunk-UV3EUIBT.cjs.map +1 -0
  90. package/dist/chunk-VMSCRVNX.cjs +2 -0
  91. package/dist/chunk-VMSCRVNX.cjs.map +1 -0
  92. package/dist/{chunk-J7ABVGZH.cjs → chunk-WGP4UUO5.cjs} +2 -2
  93. package/dist/{chunk-J7ABVGZH.cjs.map → chunk-WGP4UUO5.cjs.map} +1 -1
  94. package/dist/chunk-XBGK3TTU.cjs +3 -0
  95. package/dist/chunk-XBGK3TTU.cjs.map +1 -0
  96. package/dist/chunk-XHQYHXRE.js +3 -0
  97. package/dist/chunk-XHQYHXRE.js.map +1 -0
  98. package/dist/chunk-XX55RR4Q.js +3 -0
  99. package/dist/chunk-XX55RR4Q.js.map +1 -0
  100. package/dist/chunk-YBQPEWT7.cjs +3 -0
  101. package/dist/chunk-YBQPEWT7.cjs.map +1 -0
  102. package/dist/{chunk-CHSO3DCS.js → chunk-ZDCZ5IDD.js} +3 -3
  103. package/dist/{chunk-CHSO3DCS.js.map → chunk-ZDCZ5IDD.js.map} +1 -1
  104. package/dist/{chunk-LNZNJSRW.cjs → chunk-ZVPZQ66D.cjs} +2 -2
  105. package/dist/chunk-ZVPZQ66D.cjs.map +1 -0
  106. package/dist/constants.cjs +1 -1
  107. package/dist/constants.d.cts +1 -1
  108. package/dist/constants.d.ts +1 -1
  109. package/dist/constants.js +1 -1
  110. package/dist/engine.cjs +1 -1
  111. package/dist/engine.d.cts +12 -12
  112. package/dist/engine.d.ts +12 -12
  113. package/dist/engine.js +1 -1
  114. package/dist/errors.cjs +1 -1
  115. package/dist/errors.d.cts +3 -3
  116. package/dist/errors.d.ts +3 -3
  117. package/dist/errors.js +1 -1
  118. package/dist/format.cjs +1 -1
  119. package/dist/format.d.cts +1 -1
  120. package/dist/format.d.ts +1 -1
  121. package/dist/format.js +1 -1
  122. package/dist/index.cjs +1 -1
  123. package/dist/index.cjs.map +1 -1
  124. package/dist/index.d.cts +14 -12
  125. package/dist/index.d.ts +14 -12
  126. package/dist/index.js +1 -1
  127. package/dist/index.js.map +1 -1
  128. package/dist/language.d.cts +11 -11
  129. package/dist/language.d.ts +11 -11
  130. package/dist/lexer.cjs +1 -1
  131. package/dist/lexer.cjs.map +1 -1
  132. package/dist/lexer.d.cts +8 -7
  133. package/dist/lexer.d.ts +8 -7
  134. package/dist/lexer.js +1 -1
  135. package/dist/lexer.js.map +1 -1
  136. package/dist/normalizer.cjs +1 -1
  137. package/dist/normalizer.d.cts +16 -10
  138. package/dist/normalizer.d.ts +16 -10
  139. package/dist/normalizer.js +1 -1
  140. package/dist/packages.cjs +1 -1
  141. package/dist/packages.d.cts +10 -10
  142. package/dist/packages.d.ts +10 -10
  143. package/dist/packages.js +1 -1
  144. package/dist/parser.cjs +1 -1
  145. package/dist/parser.d.cts +4 -4
  146. package/dist/parser.d.ts +4 -4
  147. package/dist/parser.js +1 -1
  148. package/dist/{pipeline-B4wf3M1h.d.cts → pipeline-69q2tsLE.d.cts} +1 -1
  149. package/dist/{pipeline-QIT4iD8f.d.ts → pipeline-DTqGLPsV.d.ts} +1 -1
  150. package/dist/resolvers.cjs +1 -1
  151. package/dist/resolvers.d.cts +19 -3
  152. package/dist/resolvers.d.ts +19 -3
  153. package/dist/resolvers.js +1 -1
  154. package/dist/testing.cjs +2 -2
  155. package/dist/testing.d.cts +11 -11
  156. package/dist/testing.d.ts +11 -11
  157. package/dist/testing.js +1 -1
  158. package/dist/uom.cjs +1 -1
  159. package/dist/uom.d.cts +2 -2
  160. package/dist/uom.d.ts +2 -2
  161. package/dist/uom.js +1 -1
  162. package/dist/vm.cjs +1 -1
  163. package/dist/vm.d.cts +8 -8
  164. package/dist/vm.d.ts +8 -8
  165. package/dist/vm.js +1 -1
  166. package/dist/worker.cjs +2 -2
  167. package/dist/worker.cjs.map +1 -1
  168. package/dist/worker.d.cts +34 -25
  169. package/dist/worker.d.ts +34 -25
  170. package/dist/worker.js +1 -1
  171. package/dist/worker.js.map +1 -1
  172. package/package.json +5 -5
  173. package/dist/chunk-42JXN3BH.js +0 -5
  174. package/dist/chunk-42JXN3BH.js.map +0 -1
  175. package/dist/chunk-4DJJIUQF.js +0 -2
  176. package/dist/chunk-4DJJIUQF.js.map +0 -1
  177. package/dist/chunk-6YM67DWH.cjs +0 -3
  178. package/dist/chunk-6YM67DWH.cjs.map +0 -1
  179. package/dist/chunk-7E7NXKQ5.js.map +0 -1
  180. package/dist/chunk-7SZBEE5R.cjs +0 -2
  181. package/dist/chunk-7SZBEE5R.cjs.map +0 -1
  182. package/dist/chunk-A5M4QZIK.js +0 -2
  183. package/dist/chunk-A5M4QZIK.js.map +0 -1
  184. package/dist/chunk-AF7HQN6I.js +0 -2
  185. package/dist/chunk-AF7HQN6I.js.map +0 -1
  186. package/dist/chunk-ALY4ZMYO.js +0 -2
  187. package/dist/chunk-ALY4ZMYO.js.map +0 -1
  188. package/dist/chunk-BRJ4RT5U.js +0 -2
  189. package/dist/chunk-BRJ4RT5U.js.map +0 -1
  190. package/dist/chunk-CO2BI6WL.cjs +0 -3
  191. package/dist/chunk-CO2BI6WL.cjs.map +0 -1
  192. package/dist/chunk-EN3CDYOS.cjs +0 -2
  193. package/dist/chunk-EN3CDYOS.cjs.map +0 -1
  194. package/dist/chunk-EQDT42JG.js +0 -3
  195. package/dist/chunk-EQDT42JG.js.map +0 -1
  196. package/dist/chunk-FMMT5C5H.cjs +0 -3
  197. package/dist/chunk-FMMT5C5H.cjs.map +0 -1
  198. package/dist/chunk-FP6Z6PYR.js +0 -2
  199. package/dist/chunk-FP6Z6PYR.js.map +0 -1
  200. package/dist/chunk-H3JXNH7X.cjs +0 -3
  201. package/dist/chunk-H3JXNH7X.cjs.map +0 -1
  202. package/dist/chunk-HZOLIL5T.js +0 -3
  203. package/dist/chunk-HZOLIL5T.js.map +0 -1
  204. package/dist/chunk-JVMINMAB.js +0 -2
  205. package/dist/chunk-JVMINMAB.js.map +0 -1
  206. package/dist/chunk-JYLNQOPU.cjs +0 -2
  207. package/dist/chunk-JYLNQOPU.cjs.map +0 -1
  208. package/dist/chunk-KRXO3MOW.cjs +0 -2
  209. package/dist/chunk-KRXO3MOW.cjs.map +0 -1
  210. package/dist/chunk-KVLJDOZ7.cjs +0 -5
  211. package/dist/chunk-KVLJDOZ7.cjs.map +0 -1
  212. package/dist/chunk-LNZNJSRW.cjs.map +0 -1
  213. package/dist/chunk-O3BDXOQJ.js +0 -2
  214. package/dist/chunk-O3BDXOQJ.js.map +0 -1
  215. package/dist/chunk-PIZQIQVM.js +0 -3
  216. package/dist/chunk-PIZQIQVM.js.map +0 -1
  217. package/dist/chunk-QTSDIDAS.js +0 -3
  218. package/dist/chunk-QTSDIDAS.js.map +0 -1
  219. package/dist/chunk-SGIDBZ4T.cjs +0 -2
  220. package/dist/chunk-SGIDBZ4T.cjs.map +0 -1
  221. package/dist/chunk-UNKSCVIL.cjs +0 -2
  222. package/dist/chunk-UNKSCVIL.cjs.map +0 -1
  223. package/dist/chunk-USQ4KL6S.cjs +0 -2
  224. package/dist/chunk-USQ4KL6S.cjs.map +0 -1
  225. package/dist/chunk-XDXIPVZB.cjs +0 -2
  226. package/dist/chunk-XDXIPVZB.cjs.map +0 -1
package/dist/worker.js CHANGED
@@ -1,3 +1,3 @@
1
- import {a,e,d,c as c$2,b}from'./chunk-4ETS224G.js';import {n}from'./chunk-42JXN3BH.js';import'./chunk-JVMINMAB.js';import'./chunk-2RWAXT6O.js';import'./chunk-7E7NXKQ5.js';import'./chunk-MIQBJGGR.js';import'./chunk-ALY4ZMYO.js';import'./chunk-JP4JMQOG.js';import {c}from'./chunk-QTSDIDAS.js';import'./chunk-XEIDV5JP.js';import {z}from'./chunk-HZOLIL5T.js';import'./chunk-MRRMIBHE.js';import'./chunk-HMC7FJO7.js';import'./chunk-O3BDXOQJ.js';import'./chunk-4DJJIUQF.js';import'./chunk-76F3LCIL.js';import'./chunk-TCZSPH4A.js';import'./chunk-A5M4QZIK.js';import'./chunk-EQDT42JG.js';import'./chunk-TZYMXNIB.js';import'./chunk-HFKDWQUL.js';import {g,f}from'./chunk-5TCSFTZD.js';import {R as R$1}from'./chunk-KEA5HRL3.js';import'./chunk-3GR46UOX.js';import'./chunk-4CNYGIND.js';import'./chunk-BRJ4RT5U.js';import'./chunk-FP6Z6PYR.js';import'./chunk-JPFCXLJV.js';import'./chunk-AF7HQN6I.js';import'./chunk-IJMNVBIS.js';import'./chunk-LHLW7JLS.js';import'./chunk-CHVGFTO3.js';import'./chunk-PRSXXDTA.js';import {c as c$1,d as d$1}from'./chunk-PIZQIQVM.js';var W=class{constructor(r){this.nextId=1;this.pending=new Map;this.resolvedListeners=new Set;this.asyncErrorListeners=new Set;this.terminated=false;this.transport=r,this.transport.onMessage(n=>this.onMessage(n));}init(r){let n=this.nextId++;return new Promise((t,s)=>{this.pending.set(n,{resolve:()=>t(),reject:s}),this.transport.postMessage({kind:"init",id:n,localeCode:r.localeCode,diagnostics:r.diagnostics,config:r.config,packages:r.packages,formatting:r.formatting});})}parseDocument(r,n){let{signal:t,...s}=n??{},i=Object.keys(s).length>0?s:void 0;return this.call("parseDocument",[r,i],t)}evaluateLines(r,n){return this.call("evaluateLines",[r],n?.signal)}evaluateExpression(r,n){return this.call("evaluateExpression",[r],n?.signal)}onResolved(r){return this.resolvedListeners.add(r),()=>this.resolvedListeners.delete(r)}onAsyncError(r){return this.asyncErrorListeners.add(r),()=>this.asyncErrorListeners.delete(r)}terminate(){if(this.terminated)return;this.terminated=true;let r=e();for(let n of this.pending.values())this.unhook(n),n.reject(r);this.pending.clear(),this.resolvedListeners.clear(),this.asyncErrorListeners.clear(),this.transport.terminate();}call(r,n,t){if(this.terminated)return Promise.reject(e());if(t?.aborted)return Promise.reject(d(r));let s=this.nextId++;return new Promise((i,l)=>{let p={resolve:i,reject:l};if(t){let c=()=>{this.pending.has(s)&&(this.pending.delete(s),this.transport.postMessage({kind:"cancel",id:s}),l(d(r)));};p.signal=t,p.onAbort=c,t.addEventListener("abort",c,{once:true});}this.pending.set(s,p),this.transport.postMessage({kind:"request",id:s,method:r,args:n});})}onMessage(r){let n=r;switch(n.kind){case "ready":case "result":{let t=n.kind==="result"?n.value:void 0;this.settle(n.id,s=>s.resolve(t));break}case "error":this.settle(n.id,t=>t.reject(c$2(n.error)));break;case "async-update":for(let t of [...this.resolvedListeners])t(n.lines);break;case "async-error":for(let t of [...this.asyncErrorListeners])t({queryKey:n.queryKey,packageId:n.packageId,error:c$2(n.error)});break}}settle(r,n){let t=this.pending.get(r);t&&(this.pending.delete(r),this.unhook(t),n(t));}unhook(r){r.signal&&r.onAbort&&r.signal.removeEventListener("abort",r.onAbort);}};async function K(e){let r=new W(e.transport);return await r.init(e),r}function C(e){return e>0?"Infinity":e<0?"-Infinity":"NaN"}function U(e){let r=e.data.map(n=>typeof n=="object"&&n!==null?R$1(n):typeof n=="number"&&!Number.isFinite(n)?C(n):n);return {rows:e.rows,cols:e.cols,cells:r,hasSymbolic:e.hasSymbolic}}function m(e,r){let n=e.toNumber(),t={type:e.type,text:c(e,r),number:Number.isFinite(n)?n:0};Number.isFinite(n)||(t.nonFinite=C(n)),e.unit!==void 0&&(t.unit=e.unit),e.timedOut!==void 0&&(t.timedOut=e.timedOut);let s=e.value;if(typeof s=="bigint")t.bigint=s.toString();else if(e.type===7)t.matrix=U(s);else if(e.type===8){let i=s;t.range={min:i.min,max:i.max};}else if(e.type===14){let i=s;t.colour={hex:f(i),r:i.r,g:i.g,b:i.b,a:i.a,format:i.format,css:g(i)};}else if(e.type===16){let i=s;t.chart={kind:i.kind,points:i.points.map(l=>[l[0],l[1]]),label:i.label,domain:[i.domain[0],i.domain[1]],range:[i.range[0],i.range[1]],...i.expr!==void 0?{expr:i.expr}:{}};}else if(e.type===17){let i=s;t.ipCidr={...i.addr!==void 0?{addr:i.addr}:{},...i.prefix!==void 0?{prefix:i.prefix}:{},text:c(e).replace(/^=\s*/,"")};}return t}function O(e,r){return e?m(e,r):null}function _(e,r){return {start:e.start,end:e.end,expression:e.expression,lineNumber:e.lineNumber,columnNumber:e.columnNumber,result:O(e.result,r),error:e.error??null}}function y(e,r){return {lineNumber:e.lineNumber,text:e.text,startPosition:e.startPosition,endPosition:e.endPosition,isEmpty:e.isEmpty,hasInlineSolves:e.hasInlineSolves,inlineSolves:e.inlineSolves.map(n=>_(n,r)),expression:e.expression,result:O(e.result,r),error:e.error}}function R(e,r){let n={lines:e.lines.map(t=>y(t,r)),totalLines:e.totalLines,errors:[...e.errors]};return e.diagnostics!==void 0&&(n.diagnostics=e.diagnostics),n}function H(e,r){if(r===void 0)return e;let n=new Map(e.map(s=>[s.name,s])),t=[];for(let s of r){let i=n.get(s);if(!i)throw c$1.config(a.WORKER_UNKNOWN_PACKAGE,`No package named "${s}" is available in this worker runtime`,{name:s,available:[...n.keys()]});t.push(i);}return t}function B(e,r={}){let n$1=r.packages??z,t=null,s,i=new Map,l=new Map,p=null,c=null,g=o=>e.postMessage(o),h=(o,a)=>{g({kind:"error",id:o,error:b(d$1(a))});},N=o=>{let a=new Map;return o.method==="parseDocument"?o.args[0].split(`
1
+ import {a,e,d,c as c$2,b}from'./chunk-JFZ5SLF7.js';import {n}from'./chunk-7N3IJSWF.js';import'./chunk-4BRTUFTH.js';import'./chunk-2RWAXT6O.js';import'./chunk-IJHL3LMH.js';import'./chunk-MIQBJGGR.js';import'./chunk-N4SSR7Q6.js';import'./chunk-JP4JMQOG.js';import {c}from'./chunk-XX55RR4Q.js';import'./chunk-XEIDV5JP.js';import {z}from'./chunk-MZMA32NE.js';import'./chunk-OONQ3V3I.js';import'./chunk-63ZOOUOL.js';import'./chunk-EL2XUOWX.js';import'./chunk-72PYPENZ.js';import'./chunk-76F3LCIL.js';import'./chunk-TCZSPH4A.js';import'./chunk-UF5XMZTT.js';import'./chunk-XHQYHXRE.js';import'./chunk-TZYMXNIB.js';import'./chunk-HFKDWQUL.js';import {g,f}from'./chunk-5TCSFTZD.js';import {R as R$1}from'./chunk-RDYXH7ML.js';import'./chunk-NMU5E7W7.js';import'./chunk-4CNYGIND.js';import'./chunk-DUYTXLO2.js';import'./chunk-7DP57BA7.js';import'./chunk-JPFCXLJV.js';import'./chunk-OB2VX4IL.js';import'./chunk-IJMNVBIS.js';import'./chunk-LHLW7JLS.js';import'./chunk-CHVGFTO3.js';import'./chunk-PRSXXDTA.js';import {c as c$1,d as d$1}from'./chunk-57PSJQQW.js';var P=class{constructor(r){this.nextId=1;this.pending=new Map;this.resolvedListeners=new Set;this.asyncErrorListeners=new Set;this.terminated=false;this.transport=r,this.transport.onMessage(n=>this.onMessage(n));}init(r){let n=this.nextId++;return new Promise((t,s)=>{this.pending.set(n,{resolve:()=>t(),reject:s}),this.transport.postMessage({kind:"init",id:n,localeCode:r.localeCode,diagnostics:r.diagnostics,config:r.config,packages:r.packages,formatting:r.formatting});})}parseDocument(r,n){let{signal:t,...s}=n??{},i=Object.keys(s).length>0?s:void 0;return this.call("parseDocument",[r,i],t)}evaluateLines(r,n){return this.call("evaluateLines",[r],n?.signal)}evaluateExpression(r,n){return this.call("evaluateExpression",[r],n?.signal)}onResolved(r){return this.resolvedListeners.add(r),()=>this.resolvedListeners.delete(r)}onAsyncError(r){return this.asyncErrorListeners.add(r),()=>this.asyncErrorListeners.delete(r)}terminate(){if(this.terminated)return;this.terminated=true;let r=e();for(let n of this.pending.values())this.unhook(n),n.reject(r);this.pending.clear(),this.resolvedListeners.clear(),this.asyncErrorListeners.clear(),this.transport.terminate();}call(r,n,t){if(this.terminated)return Promise.reject(e());if(t?.aborted)return Promise.reject(d(r));let s=this.nextId++;return new Promise((i,l)=>{let p={resolve:i,reject:l};if(t){let c=()=>{this.pending.has(s)&&(this.pending.delete(s),this.transport.postMessage({kind:"cancel",id:s}),l(d(r)));};p.signal=t,p.onAbort=c,t.addEventListener("abort",c,{once:true});}this.pending.set(s,p),this.transport.postMessage({kind:"request",id:s,method:r,args:n});})}onMessage(r){let n=r;switch(n.kind){case "ready":case "result":{let t=n.kind==="result"?n.value:void 0;this.settle(n.id,s=>s.resolve(t));break}case "error":this.settle(n.id,t=>t.reject(c$2(n.error)));break;case "async-update":for(let t of [...this.resolvedListeners])t(n.lines);break;case "async-error":for(let t of [...this.asyncErrorListeners])t({queryKey:n.queryKey,packageId:n.packageId,error:c$2(n.error)});break}}settle(r,n){let t=this.pending.get(r);t&&(this.pending.delete(r),this.unhook(t),n(t));}unhook(r){r.signal&&r.onAbort&&r.signal.removeEventListener("abort",r.onAbort);}};async function K(e){let r=new P(e.transport);return await r.init(e),r}function C(e){return e>0?"Infinity":e<0?"-Infinity":"NaN"}function U(e){let r=e.data.map(n=>typeof n=="object"&&n!==null?R$1(n):typeof n=="number"&&!Number.isFinite(n)?C(n):n);return {rows:e.rows,cols:e.cols,cells:r,hasSymbolic:e.hasSymbolic}}function m(e,r){let n=e.toNumber(),t={type:e.type,text:c(e,r),number:Number.isFinite(n)?n:0};Number.isFinite(n)||(t.nonFinite=C(n)),e.unit!==void 0&&(t.unit=e.unit),e.timedOut!==void 0&&(t.timedOut=e.timedOut);let s=e.value;if(typeof s=="bigint")t.bigint=s.toString();else if(e.type===7)t.matrix=U(s);else if(e.type===8){let i=s;t.range={min:i.min,max:i.max};}else if(e.type===14){let i=s;t.colour={hex:f(i),r:i.r,g:i.g,b:i.b,a:i.a,format:i.format,css:g(i)};}else if(e.type===16){let i=s;t.chart={kind:i.kind,points:i.points.map(l=>[l[0],l[1]]),label:i.label,domain:[i.domain[0],i.domain[1]],range:[i.range[0],i.range[1]],...i.expr!==void 0?{expr:i.expr}:{}};}else if(e.type===17){let i=s;t.ipCidr={...i.addr!==void 0?{addr:i.addr}:{},...i.prefix!==void 0?{prefix:i.prefix}:{},text:c(e).replace(/^=\s*/,"")};}return t}function O(e,r){return e?m(e,r):null}function _(e,r){return {start:e.start,end:e.end,expression:e.expression,lineNumber:e.lineNumber,columnNumber:e.columnNumber,result:O(e.result,r),error:e.error??null}}function y(e,r){return {lineNumber:e.lineNumber,text:e.text,startPosition:e.startPosition,endPosition:e.endPosition,isEmpty:e.isEmpty,hasInlineSolves:e.hasInlineSolves,inlineSolves:e.inlineSolves.map(n=>_(n,r)),expression:e.expression,result:O(e.result,r),error:e.error}}function R(e,r){let n={lines:e.lines.map(t=>y(t,r)),totalLines:e.totalLines,errors:[...e.errors]};return e.diagnostics!==void 0&&(n.diagnostics=e.diagnostics),n}function H(e,r){if(r===void 0)return e;let n=new Map(e.map(s=>[s.name,s])),t=[];for(let s of r){let i=n.get(s);if(!i)throw c$1.config(a.WORKER_UNKNOWN_PACKAGE,`No package named "${s}" is available in this worker runtime`,{name:s,available:[...n.keys()]});t.push(i);}return t}function B(e,r={}){let n$1=r.packages??z,t=null,s,i=new Map,l=new Map,p=null,c=null,g=o=>e.postMessage(o),h=(o,a)=>{g({kind:"error",id:o,error:b(d$1(a))});},N=o=>{let a=new Map;return o.method==="parseDocument"?o.args[0].split(`
2
2
  `).forEach((u,d)=>a.set(d+1,u)):o.method==="evaluateLines"?o.args[0].forEach((u,d)=>a.set(d+1,u)):a.set(-1,o.args[0]),a},q=(o,a)=>{if(a.type==="error"){g({kind:"async-error",queryKey:a.queryKey,packageId:a.packageId,error:b(d$1(a.error))});return}let u=[];for(let d of a.lineNumbers){let f=l.get(d);if(f!==void 0)try{let L=o.evaluateLine(d,f);L&&u.push({lineNumber:d,value:m(L,s)});}catch{}}u.length>0&&g({kind:"async-update",lines:u});},F=o=>{c?.();let a=o.getEventStream().getReader();c=()=>{a.cancel();},(async()=>{try{for(;;){let{done:u,value:d}=await a.read();if(u)return;q(o,d);}}catch{}})();},D=o=>{try{let a=H(n$1,o.packages);t=new n({locale:o.localeCode??"en",diagnostics:o.diagnostics??!1,config:o.config,packages:a}),s=o.formatting,F(t),g({kind:"ready",id:o.id});}catch(a){h(o.id,a);}},V=(o,a$1)=>{let{method:u,args:d}=a$1;switch(u){case "parseDocument":return R(o.parseDocument(d[0],d[1]),s);case "evaluateLines":return o.evaluateLines(d[0]).map(f=>y(f,s));case "evaluateExpression":return m(o.evaluateExpression(d[0]),s);default:throw c$1.execution(a.WORKER_UNKNOWN_METHOD,`The worker runtime has no method named "${String(u)}"`,{method:u})}},j=o=>{let a$1=t;if(!a$1){h(o.id,c$1.execution(a.WORKER_NOT_INITIALISED,"The worker received a request before its engine finished initialising"));return}p?.abort();let u=new AbortController;p=u,l=N(o),i.set(o.id,u),a$1.setKeystrokeSignal(u.signal);try{let d=V(a$1,o);g({kind:"result",id:o.id,value:d});}catch(d){h(o.id,d);}finally{i.delete(o.id),a$1.setKeystrokeSignal(null);}};return e.onMessage(o=>{let a=o;switch(a.kind){case "init":D(a);break;case "request":j(a);break;case "cancel":i.get(a.id)?.abort();break}}),()=>{c?.(),c=null,p?.abort(),p=null,l=new Map;for(let o of i.values())o.abort();i.clear(),t?.clear(),t=null,e.terminate();}}function G(e){return typeof globalThis.structuredClone=="function"?globalThis.structuredClone(e):JSON.parse(JSON.stringify(e))}function J(){let e=null,r=null,n=true,t=(l,p)=>{let c=G(p);queueMicrotask(()=>{n&&l()?.(c);});};return {client:{postMessage:l=>t(()=>r,l),onMessage:l=>{e=l;},terminate:()=>{n=false;}},host:{postMessage:l=>t(()=>e,l),onMessage:l=>{r=l;},terminate:()=>{n=false;}}}}function $(e){return {postMessage:r=>e.postMessage(r),onMessage:r=>{let n=t=>r(t.data);typeof e.addEventListener=="function"?e.addEventListener("message",n):e.onmessage=n,e.start?.();},terminate:()=>{e.terminate?.(),e.close?.();}}}function Q(e){return {postMessage:r=>e.postMessage(r),onMessage:r=>{e.on("message",n=>r(n));},terminate:()=>{e.terminate?.(),e.close?.();}}}export{J as createLinkedTransports,K as createWorkerEngine,$ as eventTargetTransport,Q as messagePortTransport,y as serializeParsedLine,R as serializeParsingResult,m as serializeValue,B as startWorkerRuntime};//# sourceMappingURL=worker.js.map
3
3
  //# sourceMappingURL=worker.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/worker/client.ts","../src/worker/serialize.ts","../src/worker/runtime.ts","../src/worker/transport.ts"],"names":["WorkerEngineClient","transport","raw","options","id","resolve","reject","input","signal","parsing","parseOptions","lines","expression","listener","error","workerTerminatedError","entry","method","args","workerCancelledError","onAbort","message","value","deserializeEngineError","apply","createWorkerEngine","client","nonFiniteTag","n","serializeMatrix","m","cells","cell","formatSymbolic","serializeValue","settings","reading","dto","formatValue","r","c","toHexString","formatColour","pt","ip","serializeMaybe","serializeInlineSolve","solve","serializeParsedLine","line","serializeParsingResult","result","resolvePackages","available","names","byName","pkg","resolved","name","ErrorFactory","WorkerErrorCodes","startWorkerRuntime","BUILTIN_PACKAGES","engine","formatting","inFlight","retainedLines","documentController","stopEventPump","post","fail","serializeEngineError","normalizeUnknownError","retainLines","map","text","index","handleAsyncEvent","eng","event","lineNumber","startEventPump","reader","done","handleInit","packages","ExpressionEngine","runMethod","handleRequest","controller","cloneMessage","createLinkedTransports","clientHandler","hostHandler","alive","deliver","target","cloned","handler","eventTargetTransport","messagePortTransport","port"],"mappings":"whCA8HA,IAAMA,CAAAA,CAAN,KAAiD,CAWhD,WAAA,CAAYC,CAAAA,CAA4B,CATxC,IAAA,CAAQ,MAAA,CAAS,CAAA,CACjB,IAAA,CAAiB,OAAA,CAAU,IAAI,GAAA,CAI/B,IAAA,CAAiB,iBAAA,CAAoB,IAAI,GAAA,CACzC,IAAA,CAAiB,mBAAA,CAAsB,IAAI,GAAA,CAC3C,IAAA,CAAQ,UAAA,CAAa,KAAA,CAGpB,IAAA,CAAK,SAAA,CAAYA,CAAAA,CACjB,IAAA,CAAK,UAAU,SAAA,CAAWC,CAAAA,EAAQ,IAAA,CAAK,SAAA,CAAUA,CAAG,CAAC,EACtD,CAGA,IAAA,CAAKC,CAAAA,CAA6C,CACjD,IAAMC,CAAAA,CAAK,IAAA,CAAK,MAAA,EAAA,CAChB,OAAO,IAAI,OAAA,CAAc,CAACC,CAAAA,CAASC,CAAAA,GAAW,CAC7C,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAIF,CAAAA,CAAI,CAAE,OAAA,CAAS,IAAMC,CAAAA,EAAQ,CAAG,MAAA,CAAAC,CAAO,CAAC,CAAA,CACzD,IAAA,CAAK,SAAA,CAAU,WAAA,CAAY,CAC1B,IAAA,CAAM,MAAA,CACN,EAAA,CAAAF,CAAAA,CACA,UAAA,CAAYD,CAAAA,CAAQ,UAAA,CACpB,WAAA,CAAaA,CAAAA,CAAQ,WAAA,CACrB,MAAA,CAAQA,CAAAA,CAAQ,MAAA,CAChB,QAAA,CAAUA,CAAAA,CAAQ,QAAA,CAClB,UAAA,CAAYA,CAAAA,CAAQ,UACrB,CAAC,EACF,CAAC,CACF,CAEA,aAAA,CACCI,CAAAA,CACAJ,EACmC,CAGnC,GAAM,CAAE,MAAA,CAAAK,CAAAA,CAAQ,GAAGC,CAAQ,CAAA,CAAIN,CAAAA,EAAW,EAA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ACD,CAEsB,CACvB,CAqBO,SAASK,EAAqBH,CAAAA,CAA0C,CAC9E,OAAO,CACN,YAAc3E,CAAAA,EAAY2E,CAAAA,CAAO,WAAA,CAAY3E,CAAO,EACpD,SAAA,CAAY6E,CAAAA,EAAY,CACvB,IAAMrF,EAAYkE,CAAAA,EAAmCmB,CAAAA,CAAQnB,CAAAA,CAAM,IAAI,EACnE,OAAOiB,CAAAA,CAAO,gBAAA,EAAqB,UAAA,CACtCA,EAAO,gBAAA,CAAiB,SAAA,CAAWnF,CAAQ,CAAA,CAE3CmF,EAAO,SAAA,CAAYnF,CAAAA,CAEpBmF,CAAAA,CAAO,KAAA,KACR,CAAA,CAGA,SAAA,CAAW,IAAM,CAChBA,CAAAA,CAAO,aAAY,CACnBA,CAAAA,CAAO,KAAA,KACR,CACD,CACD,CAmBO,SAASI,CAAAA,CAAqBC,EAAwC,CAC5E,OAAO,CACN,WAAA,CAAchF,GAAYgF,CAAAA,CAAK,WAAA,CAAYhF,CAAO,CAAA,CAClD,UAAY6E,CAAAA,EAAY,CACvBG,CAAAA,CAAK,EAAA,CAAG,UAAYhF,CAAAA,EAAY6E,CAAAA,CAAQ7E,CAAO,CAAC,EACjD,CAAA,CACA,SAAA,CAAW,IAAM,CAChBgF,EAAK,SAAA,IAAY,CACjBA,EAAK,KAAA,KACN,CACD,CACD","file":"worker.js","sourcesContent":["/**\n * The main-side half of the harness: an async proxy of the core evaluate\n * methods.\n *\n * {@link createWorkerEngine} performs the init handshake and resolves once the\n * worker's engine is built, so the returned {@link WorkerEngine} is ready to\n * call. Each call stamps a request id, tracks the pending promise, and settles\n * it when the matching answer arrives, so several requests can be outstanding at\n * once. An `AbortSignal` rejects the local promise and posts a `cancel` for the\n * same id, mapping keystroke-level cancellation onto the boundary rather than\n * re-inventing it.\n */\n\nimport type { EngineConfigOverride } from \"@solve-js/constants/Configuration\";\nimport type { UnifiedParsingOptions } from \"@solve-js/types/ParsingResult\";\nimport type { FormattingSettings } from \"@solve-js/format/FormattingSettings\";\nimport type { EngineError } from \"@solve-js/errors\";\nimport {\n\tdeserializeEngineError,\n\tworkerCancelledError,\n\tworkerTerminatedError,\n} from \"@solve-js/errors\";\nimport type { WorkerTransport } from \"./transport\";\nimport type {\n\tWorkerMethod,\n\tWorkerRequestArgs,\n\tWorkerToMainMessage,\n} from \"./protocol\";\nimport type {\n\tSerializedValue,\n\tSerializedParsedLine,\n\tSerializedParsingResult,\n} from \"./dto\";\n\n/** Configuration for {@link createWorkerEngine}. */\nexport interface WorkerEngineOptions {\n\t/** The channel to the worker runtime. See `worker/transport.ts` for adapters. */\n\ttransport: WorkerTransport;\n\t/** Locale for keywords and number formatting; defaults to English worker-side. */\n\tlocaleCode?: string;\n\t/** Whether the worker builds its engine with diagnostics enabled. */\n\tdiagnostics?: boolean;\n\t/** Config overrides, merged per section over the defaults worker-side. */\n\tconfig?: EngineConfigOverride;\n\t/**\n\t * Names of built-in packages the worker should register. Omitted registers\n\t * them all. Names rather than the packages themselves, since a package\n\t * carries functions that cannot cross a `postMessage` boundary; a host with\n\t * a custom package bakes it into its own worker entry and selects it here by\n\t * name.\n\t */\n\tpackages?: string[];\n\t/** Formatting settings the worker uses when it renders a DTO's display text. */\n\tformatting?: FormattingSettings;\n}\n\n/** Per-call options common to every proxied method. */\nexport interface WorkerCallOptions {\n\t/** Abort the request. Rejects the returned promise and cancels the work worker-side. */\n\tsignal?: AbortSignal;\n}\n\n/**\n * One line whose result changed after a live value resolved worker-side, carried\n * as its freshly re-evaluated {@link SerializedValue}. The value the host renders\n * against `lineNumber`, recovered worker-side so the main thread needs no further\n * round-trip to display it.\n */\nexport interface WorkerAsyncUpdate {\n\tlineNumber: number;\n\tvalue: SerializedValue;\n}\n\n/**\n * A live-data resolution that failed worker-side. `error` is the same structured\n * {@link EngineError} an in-process resolver failure would surface, rebuilt from\n * its transported form, so a host branches on `code`/`category` as it always has.\n */\nexport interface WorkerAsyncError {\n\tqueryKey: string;\n\tpackageId: string;\n\terror: EngineError;\n}\n\n/**\n * An async proxy of {@link ExpressionEngine}'s core evaluate methods.\n *\n * Each method mirrors its synchronous counterpart but returns a Promise of the\n * serialisable DTO rather than a live `Value`, and accepts an `AbortSignal`.\n */\nexport interface WorkerEngine {\n\t/** Parse a whole document off-thread. Mirrors `ExpressionEngine.parseDocument`. */\n\tparseDocument(input: string, options?: UnifiedParsingOptions & WorkerCallOptions): Promise<SerializedParsingResult>;\n\t/** Evaluate an array of lines off-thread. Mirrors `ExpressionEngine.evaluateLines`. */\n\tevaluateLines(lines: string[], options?: WorkerCallOptions): Promise<SerializedParsedLine[]>;\n\t/** Evaluate a single expression off-thread. Mirrors `ExpressionEngine.evaluateExpression`. */\n\tevaluateExpression(expression: string, options?: WorkerCallOptions): Promise<SerializedValue>;\n\t/**\n\t * Subscribe to live-data resolutions that land after a request already\n\t * answered.\n\t *\n\t * A currency, weather or historical-rate value resolves inside the worker some\n\t * time after `parseDocument` returned its pending result. When it does, the\n\t * affected lines are re-evaluated worker-side and their fresh values arrive\n\t * here as one batch. This is a subscription rather than a per-request promise\n\t * because a resolution is tied to no single request: it belongs to whichever\n\t * document is current when the value lands. Returns an unsubscribe function.\n\t */\n\tonResolved(listener: (lines: WorkerAsyncUpdate[]) => void): () => void;\n\t/**\n\t * Subscribe to live-data resolutions that failed. Returns an unsubscribe\n\t * function. See {@link onResolved}; this is its failure channel.\n\t */\n\tonAsyncError(listener: (error: WorkerAsyncError) => void): () => void;\n\t/** Reject every in-flight request and tear the transport down. Idempotent. */\n\tterminate(): void;\n}\n\n/** A promise awaiting one worker answer, plus the abort wiring to unhook when it settles. */\ninterface PendingRequest {\n\tresolve: (value: unknown) => void;\n\treject: (error: unknown) => void;\n\tsignal?: AbortSignal;\n\tonAbort?: () => void;\n}\n\nclass WorkerEngineClient implements WorkerEngine {\n\tprivate readonly transport: WorkerTransport;\n\tprivate nextId = 1;\n\tprivate readonly pending = new Map<number, PendingRequest>();\n\t// Broadcast subscribers for async resolutions. Sets, not one callback each, so\n\t// several views can watch the same worker; a resolution is not tied to a\n\t// request id, so these live outside `pending`.\n\tprivate readonly resolvedListeners = new Set<(lines: WorkerAsyncUpdate[]) => void>();\n\tprivate readonly asyncErrorListeners = new Set<(error: WorkerAsyncError) => void>();\n\tprivate terminated = false;\n\n\tconstructor(transport: WorkerTransport) {\n\t\tthis.transport = transport;\n\t\tthis.transport.onMessage((raw) => this.onMessage(raw));\n\t}\n\n\t/** Perform the init handshake, resolving once the worker posts `ready`. */\n\tinit(options: WorkerEngineOptions): Promise<void> {\n\t\tconst id = this.nextId++;\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tthis.pending.set(id, { resolve: () => resolve(), reject });\n\t\t\tthis.transport.postMessage({\n\t\t\t\tkind: \"init\",\n\t\t\t\tid,\n\t\t\t\tlocaleCode: options.localeCode,\n\t\t\t\tdiagnostics: options.diagnostics,\n\t\t\t\tconfig: options.config,\n\t\t\t\tpackages: options.packages,\n\t\t\t\tformatting: options.formatting,\n\t\t\t});\n\t\t});\n\t}\n\n\tparseDocument(\n\t\tinput: string,\n\t\toptions?: UnifiedParsingOptions & WorkerCallOptions,\n\t): Promise<SerializedParsingResult> {\n\t\t// The signal stays main-side and drives a `cancel`; only the parsing\n\t\t// options cross, so an AbortSignal never reaches `postMessage`.\n\t\tconst { signal, ...parsing } = options ?? {};\n\t\tconst parseOptions = Object.keys(parsing).length > 0 ? (parsing as UnifiedParsingOptions) : undefined;\n\t\treturn this.call<SerializedParsingResult>(\"parseDocument\", [input, parseOptions], signal);\n\t}\n\n\tevaluateLines(lines: string[], options?: WorkerCallOptions): Promise<SerializedParsedLine[]> {\n\t\treturn this.call<SerializedParsedLine[]>(\"evaluateLines\", [lines], options?.signal);\n\t}\n\n\tevaluateExpression(expression: string, options?: WorkerCallOptions): Promise<SerializedValue> {\n\t\treturn this.call<SerializedValue>(\"evaluateExpression\", [expression], options?.signal);\n\t}\n\n\tonResolved(listener: (lines: WorkerAsyncUpdate[]) => void): () => void {\n\t\tthis.resolvedListeners.add(listener);\n\t\treturn () => this.resolvedListeners.delete(listener);\n\t}\n\n\tonAsyncError(listener: (error: WorkerAsyncError) => void): () => void {\n\t\tthis.asyncErrorListeners.add(listener);\n\t\treturn () => this.asyncErrorListeners.delete(listener);\n\t}\n\n\tterminate(): void {\n\t\tif (this.terminated) return;\n\t\tthis.terminated = true;\n\t\tconst error = workerTerminatedError();\n\t\tfor (const entry of this.pending.values()) {\n\t\t\tthis.unhook(entry);\n\t\t\tentry.reject(error);\n\t\t}\n\t\tthis.pending.clear();\n\t\t// No more resolutions can arrive across a torn-down transport, so drop the\n\t\t// subscribers rather than leaving them referenced for the client's lifetime.\n\t\tthis.resolvedListeners.clear();\n\t\tthis.asyncErrorListeners.clear();\n\t\tthis.transport.terminate();\n\t}\n\n\t/** Dispatch one request and return the promise that settles on its answer. */\n\tprivate call<T>(method: WorkerMethod, args: WorkerRequestArgs, signal?: AbortSignal): Promise<T> {\n\t\tif (this.terminated) return Promise.reject(workerTerminatedError());\n\t\tif (signal?.aborted) return Promise.reject(workerCancelledError(method));\n\n\t\tconst id = this.nextId++;\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tconst entry: PendingRequest = { resolve: resolve as (value: unknown) => void, reject };\n\n\t\t\tif (signal) {\n\t\t\t\tconst onAbort = (): void => {\n\t\t\t\t\t// Nothing to do if the answer already arrived and settled this id.\n\t\t\t\t\tif (!this.pending.has(id)) return;\n\t\t\t\t\tthis.pending.delete(id);\n\t\t\t\t\tthis.transport.postMessage({ kind: \"cancel\", id });\n\t\t\t\t\treject(workerCancelledError(method));\n\t\t\t\t};\n\t\t\t\tentry.signal = signal;\n\t\t\t\tentry.onAbort = onAbort;\n\t\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t}\n\n\t\t\tthis.pending.set(id, entry);\n\t\t\tthis.transport.postMessage({ kind: \"request\", id, method, args });\n\t\t});\n\t}\n\n\t/** Route one incoming message to the request that is waiting on its id. */\n\tprivate onMessage(raw: unknown): void {\n\t\tconst message = raw as WorkerToMainMessage;\n\t\tswitch (message.kind) {\n\t\t\tcase \"ready\":\n\t\t\tcase \"result\": {\n\t\t\t\tconst value = message.kind === \"result\" ? message.value : undefined;\n\t\t\t\tthis.settle(message.id, (entry) => entry.resolve(value));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"error\":\n\t\t\t\tthis.settle(message.id, (entry) => entry.reject(deserializeEngineError(message.error)));\n\t\t\t\tbreak;\n\t\t\tcase \"async-update\":\n\t\t\t\t// A broadcast, not an answer to a request: fan it out to every\n\t\t\t\t// subscriber. A copy of the listener set is iterated so a listener\n\t\t\t\t// that unsubscribes itself mid-callback cannot disturb the walk.\n\t\t\t\tfor (const listener of [...this.resolvedListeners]) listener(message.lines);\n\t\t\t\tbreak;\n\t\t\tcase \"async-error\":\n\t\t\t\tfor (const listener of [...this.asyncErrorListeners]) {\n\t\t\t\t\tlistener({\n\t\t\t\t\t\tqueryKey: message.queryKey,\n\t\t\t\t\t\tpackageId: message.packageId,\n\t\t\t\t\t\terror: deserializeEngineError(message.error),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t/** Remove a pending request by id and run the settle callback, if it is still pending. */\n\tprivate settle(id: number, apply: (entry: PendingRequest) => void): void {\n\t\tconst entry = this.pending.get(id);\n\t\tif (!entry) return;\n\t\tthis.pending.delete(id);\n\t\tthis.unhook(entry);\n\t\tapply(entry);\n\t}\n\n\t/** Detach an entry's abort listener so a settled request leaves nothing on the signal. */\n\tprivate unhook(entry: PendingRequest): void {\n\t\tif (entry.signal && entry.onAbort) entry.signal.removeEventListener(\"abort\", entry.onAbort);\n\t}\n}\n\n/**\n * Build a worker-backed engine and wait for it to be ready.\n *\n * ```ts\n * const { client, host } = createLinkedTransports();\n * startWorkerRuntime(host);\n * const engine = await createWorkerEngine({ transport: client });\n * const result = await engine.parseDocument(text);\n * ```\n *\n * In production `client` wraps a real `Worker` (see `eventTargetTransport` /\n * `messagePortTransport`), and `startWorkerRuntime` runs inside that worker.\n */\nexport async function createWorkerEngine(options: WorkerEngineOptions): Promise<WorkerEngine> {\n\tconst client = new WorkerEngineClient(options.transport);\n\tawait client.init(options);\n\treturn client;\n}\n","/**\n * Turn live engine results into the clone-safe DTOs the worker harness posts.\n *\n * These functions run on the worker side, just before a result crosses the\n * boundary, and are also what the main side re-runs on a synchronous result to\n * compare the two paths in tests. They are pure and deterministic given the\n * same {@link FormattingSettings}, so a value serialised on either side is\n * byte-for-byte the same DTO.\n */\n\nimport { Value, ValueType, type MatrixData, type MatrixEntry, type RangeData, type ColourData, type ChartData, type IpCidrData } from \"@solve-js/vm/Value\";\nimport { formatValue } from \"@solve-js/format/FormatEngine\";\nimport { toHexString, formatColour } from \"@solve-js/packages/colour/ColourMath\";\nimport type { FormattingSettings } from \"@solve-js/format/FormattingSettings\";\nimport { formatSymbolic } from \"@solve-js/symbolic\";\nimport type { ParsedLine, InlineSolvePosition, ParsingResult } from \"@solve-js/types/ParsingResult\";\nimport type {\n\tSerializedValue,\n\tSerializedMatrix,\n\tSerializedParsedLine,\n\tSerializedInlineSolve,\n\tSerializedParsingResult,\n} from \"./dto\";\n\n/**\n * The JSON-safe string tag for a non-finite reading. `Infinity`/`-Infinity`/`NaN`\n * cannot cross `JSON` (which turns each into `null`), so this one string form is\n * what survives both `structuredClone` and `JSON`, and a host recovers the value\n * with `Number(tag)`. Shared by the scalar `nonFinite` field and matrix cells.\n */\nfunction nonFiniteTag(n: number): \"Infinity\" | \"-Infinity\" | \"NaN\" {\n\treturn n > 0 ? \"Infinity\" : n < 0 ? \"-Infinity\" : \"NaN\";\n}\n\n/** Project a matrix onto clone-safe cells: finite primitives pass through, symbolic cells and non-finite numbers become strings. */\nfunction serializeMatrix(m: MatrixData): SerializedMatrix {\n\tconst cells = m.data.map((cell: MatrixEntry): number | boolean | string => {\n\t\t// A `SymbolicNode` (the object-typed cell variant) flattens to its display\n\t\t// string. A non-finite number (a `[1/0, 2]` cell) cannot cross JSON any\n\t\t// more than a scalar reading can, so it takes the same string tag rather\n\t\t// than being passed through raw and turned into `null` by `JSON.stringify`\n\t\t// (which would diverge from the `structuredClone` path). A finite number\n\t\t// or a boolean is already clone-safe and passes through.\n\t\tif (typeof cell === \"object\" && cell !== null) return formatSymbolic(cell);\n\t\tif (typeof cell === \"number\" && !Number.isFinite(cell)) return nonFiniteTag(cell);\n\t\treturn cell;\n\t});\n\treturn { rows: m.rows, cols: m.cols, cells, hasSymbolic: m.hasSymbolic };\n}\n\n/**\n * Project a {@link Value} onto a {@link SerializedValue}.\n *\n * `text` and `number` are set for every value; the type-specific fields are\n * added only where the payload needs them, so the DTO stays minimal and a\n * deep-equal between the two evaluation paths does not trip on a property one\n * side left `undefined`.\n */\nexport function serializeValue(value: Value, settings?: FormattingSettings): SerializedValue {\n\tconst reading = value.toNumber();\n\tconst dto: SerializedValue = {\n\t\ttype: value.type,\n\t\ttext: formatValue(value, settings),\n\t\t// A non-finite reading (1/0, 0/0, an overflow) cannot cross JSON, which\n\t\t// turns it into null and breaks the round-trip the DTO guarantees. Keep\n\t\t// `number` finite and name the real value in `nonFinite` instead.\n\t\tnumber: Number.isFinite(reading) ? reading : 0,\n\t};\n\tif (!Number.isFinite(reading)) {\n\t\tdto.nonFinite = nonFiniteTag(reading);\n\t}\n\n\tif (value.unit !== undefined) dto.unit = value.unit;\n\tif (value.timedOut !== undefined) dto.timedOut = value.timedOut;\n\n\tconst raw = value.value;\n\tif (typeof raw === \"bigint\") {\n\t\t// Covers BigInt values and a Hex value that carries a bigint magnitude:\n\t\t// a base-ten string is the one representation that neither loses\n\t\t// precision nor breaks JSON.\n\t\tdto.bigint = raw.toString();\n\t} else if (value.type === ValueType.Matrix) {\n\t\tdto.matrix = serializeMatrix(raw as MatrixData);\n\t} else if (value.type === ValueType.Range) {\n\t\tconst r = raw as RangeData;\n\t\tdto.range = { min: r.min, max: r.max };\n\t} else if (value.type === ValueType.Colour) {\n\t\tconst c = raw as ColourData;\n\t\tdto.colour = { hex: toHexString(c), r: c.r, g: c.g, b: c.b, a: c.a, format: c.format, css: formatColour(c) };\n\t} else if (value.type === ValueType.Chart) {\n\t\tconst c = raw as ChartData;\n\t\tdto.chart = {\n\t\t\tkind: c.kind,\n\t\t\tpoints: c.points.map((pt) => [pt[0], pt[1]]),\n\t\t\tlabel: c.label,\n\t\t\tdomain: [c.domain[0], c.domain[1]],\n\t\t\trange: [c.range[0], c.range[1]],\n\t\t\t...(c.expr !== undefined ? { expr: c.expr } : {}),\n\t\t};\n\t} else if (value.type === ValueType.IpCidr) {\n\t\tconst ip = raw as IpCidrData;\n\t\tdto.ipCidr = {\n\t\t\t...(ip.addr !== undefined ? { addr: ip.addr } : {}),\n\t\t\t...(ip.prefix !== undefined ? { prefix: ip.prefix } : {}),\n\t\t\ttext: formatValue(value).replace(/^=\\s*/, \"\"),\n\t\t};\n\t}\n\n\treturn dto;\n}\n\n/** Serialise a nullable value, the shape both `result` fields carry. */\nfunction serializeMaybe(value: Value | null | undefined, settings?: FormattingSettings): SerializedValue | null {\n\treturn value ? serializeValue(value, settings) : null;\n}\n\n/** Project an inline solve onto its DTO, serialising its result. */\nfunction serializeInlineSolve(solve: InlineSolvePosition, settings?: FormattingSettings): SerializedInlineSolve {\n\treturn {\n\t\tstart: solve.start,\n\t\tend: solve.end,\n\t\texpression: solve.expression,\n\t\tlineNumber: solve.lineNumber,\n\t\tcolumnNumber: solve.columnNumber,\n\t\tresult: serializeMaybe(solve.result, settings),\n\t\terror: solve.error ?? null,\n\t};\n}\n\n/** Project a parsed line onto its DTO, serialising its result and every inline solve. */\nexport function serializeParsedLine(line: ParsedLine, settings?: FormattingSettings): SerializedParsedLine {\n\treturn {\n\t\tlineNumber: line.lineNumber,\n\t\ttext: line.text,\n\t\tstartPosition: line.startPosition,\n\t\tendPosition: line.endPosition,\n\t\tisEmpty: line.isEmpty,\n\t\thasInlineSolves: line.hasInlineSolves,\n\t\tinlineSolves: line.inlineSolves.map((solve) => serializeInlineSolve(solve, settings)),\n\t\texpression: line.expression,\n\t\tresult: serializeMaybe(line.result, settings),\n\t\terror: line.error,\n\t};\n}\n\n/** Project a whole parsing result onto its DTO. */\nexport function serializeParsingResult(result: ParsingResult, settings?: FormattingSettings): SerializedParsingResult {\n\tconst dto: SerializedParsingResult = {\n\t\tlines: result.lines.map((line) => serializeParsedLine(line, settings)),\n\t\ttotalLines: result.totalLines,\n\t\terrors: [...result.errors],\n\t};\n\t// The diagnostics report is already the engine's own JSON form, so it\n\t// crosses unchanged; present only when the host asked for it.\n\tif (result.diagnostics !== undefined) dto.diagnostics = result.diagnostics;\n\treturn dto;\n}\n","/**\n * The worker-side half of the harness: it owns an {@link ExpressionEngine} and\n * answers the protocol.\n *\n * {@link startWorkerRuntime} is transport-agnostic, so the same function runs\n * behind a browser `Worker`, a Node `worker_threads` port, or an in-process\n * link. A host's worker entry file is two lines: adapt the environment onto a\n * {@link WorkerTransport} and call this.\n *\n * The runtime never posts a raw {@link Value}. Every result is projected onto a\n * DTO first (`worker/serialize.ts`), and every failure is caught and flattened\n * into a structured error, so a worker-side throw reaches the caller as an\n * `EngineError` rather than a lost promise.\n */\n\nimport { ExpressionEngine } from \"@solve-js/engine/ExpressionEngine\";\nimport type { AsyncResolutionEvent } from \"@solve-js/engine/AsyncResolutionBatcher\";\nimport type { IEnginePackage } from \"@solve-js/api/PackageRegistry\";\nimport { BUILTIN_PACKAGES } from \"@solve-js/packages/builtins\";\nimport type { FormattingSettings } from \"@solve-js/format/FormattingSettings\";\nimport {\n\tErrorFactory,\n\tnormalizeUnknownError,\n\tserializeEngineError,\n\tWorkerErrorCodes,\n} from \"@solve-js/errors\";\nimport { serializeParsingResult, serializeParsedLine, serializeValue } from \"./serialize\";\nimport type { WorkerTransport } from \"./transport\";\nimport type {\n\tMainToWorkerMessage,\n\tInitMessage,\n\tRequestMessage,\n\tWorkerToMainMessage,\n\tAsyncResolvedLine,\n} from \"./protocol\";\n\n/** Options a host bakes into its own worker entry, chiefly its custom packages. */\nexport interface WorkerRuntimeOptions {\n\t/**\n\t * The packages available to register, defaulting to {@link BUILTIN_PACKAGES}.\n\t * A host with its own package authors a worker entry that passes them here,\n\t * then selects among them by name from the main side. This is how a\n\t * function-carrying package reaches the worker: baked into its bundle, never\n\t * posted across the boundary.\n\t */\n\tpackages?: IEnginePackage[];\n}\n\n/**\n * Resolve the requested package names against the available set.\n *\n * Undefined names means \"all of them\". A name with no match is a configuration\n * failure the caller must see, not a silent omission that would leave a feature\n * quietly missing from every result.\n */\nfunction resolvePackages(available: IEnginePackage[], names: string[] | undefined): IEnginePackage[] {\n\tif (names === undefined) return available;\n\tconst byName = new Map(available.map((pkg) => [pkg.name, pkg]));\n\tconst resolved: IEnginePackage[] = [];\n\tfor (const name of names) {\n\t\tconst pkg = byName.get(name);\n\t\tif (!pkg) {\n\t\t\tthrow ErrorFactory.config(\n\t\t\t\tWorkerErrorCodes.WORKER_UNKNOWN_PACKAGE,\n\t\t\t\t`No package named \"${name}\" is available in this worker runtime`,\n\t\t\t\t{ name, available: [...byName.keys()] },\n\t\t\t);\n\t\t}\n\t\tresolved.push(pkg);\n\t}\n\treturn resolved;\n}\n\n/**\n * Attach the runtime to a transport and start serving.\n *\n * Returns a teardown function that clears the engine and detaches, for a host\n * that reuses a transport or shuts a worker down cleanly.\n */\nexport function startWorkerRuntime(transport: WorkerTransport, options: WorkerRuntimeOptions = {}): () => void {\n\tconst available = options.packages ?? BUILTIN_PACKAGES;\n\n\tlet engine: ExpressionEngine | null = null;\n\tlet formatting: FormattingSettings | undefined;\n\t// One AbortController per in-flight request, so a `cancel` can map onto the\n\t// engine's keystroke signal for exactly the request the caller aborted.\n\tconst inFlight = new Map<number, AbortController>();\n\n\t// The line texts of the current document, keyed by the line number the engine\n\t// evaluates them under (1-based for a document, -1 for a lone expression). An\n\t// async resolution names the lines whose result changed but not the new value,\n\t// so this is what the event pump re-reads a line from to recover it.\n\tlet retainedLines = new Map<number, string>();\n\n\t// The current document's abort controller, kept alive past the request that\n\t// created it so this document's async resolutions can still land. Aborted when\n\t// a new document supersedes it: aborting drops the old document's in-flight\n\t// resolutions at the engine's own staleness guard (an aborted signal is\n\t// discarded before it reaches the batcher), so a stale value never reaches the\n\t// host as if it were current. See {@link handleRequest}.\n\tlet documentController: AbortController | null = null;\n\n\t// Cancels the event-stream reader on teardown. Null until the pump starts.\n\tlet stopEventPump: (() => void) | null = null;\n\n\tconst post = (message: WorkerToMainMessage): void => transport.postMessage(message);\n\n\tconst fail = (id: number, error: unknown): void => {\n\t\tpost({ kind: \"error\", id, error: serializeEngineError(normalizeUnknownError(error)) });\n\t};\n\n\t/**\n\t * Record the line texts a request evaluates, so a later async resolution can\n\t * re-read exactly the lines it names. A whole document splits into 1-based\n\t * lines; a lone `evaluateExpression` maps onto the engine's `-1` sentinel, the\n\t * same line number the engine registers and later reports for it.\n\t */\n\tconst retainLines = (message: RequestMessage): Map<number, string> => {\n\t\tconst map = new Map<number, string>();\n\t\tif (message.method === \"parseDocument\") {\n\t\t\t(message.args[0] as string).split(\"\\n\").forEach((text, index) => map.set(index + 1, text));\n\t\t} else if (message.method === \"evaluateLines\") {\n\t\t\t(message.args[0] as string[]).forEach((text, index) => map.set(index + 1, text));\n\t\t} else {\n\t\t\tmap.set(-1, message.args[0] as string);\n\t\t}\n\t\treturn map;\n\t};\n\n\t/**\n\t * Turn one async resolution event into a message home.\n\t *\n\t * A `lines-updated` event names the lines whose result changed; the resolved\n\t * value lives in the engine's cache, so each named line is re-evaluated (which\n\t * now reads the settled value from that cache rather than starting a fresh\n\t * fetch) and serialised. A line the current document no longer retains belongs\n\t * to a superseded document and is skipped. An `error` event carries the failed\n\t * query straight across as a structured error.\n\t */\n\tconst handleAsyncEvent = (eng: ExpressionEngine, event: AsyncResolutionEvent): void => {\n\t\tif (event.type === \"error\") {\n\t\t\tpost({\n\t\t\t\tkind: \"async-error\",\n\t\t\t\tqueryKey: event.queryKey,\n\t\t\t\tpackageId: event.packageId,\n\t\t\t\terror: serializeEngineError(normalizeUnknownError(event.error)),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst lines: AsyncResolvedLine[] = [];\n\t\tfor (const lineNumber of event.lineNumbers) {\n\t\t\tconst text = retainedLines.get(lineNumber);\n\t\t\tif (text === undefined) continue;\n\t\t\ttry {\n\t\t\t\tconst value = eng.evaluateLine(lineNumber, text);\n\t\t\t\tif (value) lines.push({ lineNumber, value: serializeValue(value, formatting) });\n\t\t\t} catch {\n\t\t\t\t// A line that resolved into an error re-throws on re-evaluation; the\n\t\t\t\t// batcher's own `error` event is the channel for that, so this keeps\n\t\t\t\t// the update to the lines that produced a value rather than posting a\n\t\t\t\t// second, half-formed failure here.\n\t\t\t}\n\t\t}\n\t\tif (lines.length > 0) post({ kind: \"async-update\", lines });\n\t};\n\n\t/**\n\t * Drain the engine's async-resolution event stream for the life of the\n\t * runtime, posting each event home. Started once the engine exists; the reader\n\t * loop ends when the stream closes (engine cleared) or the returned canceller\n\t * runs at teardown.\n\t */\n\tconst startEventPump = (eng: ExpressionEngine): void => {\n\t\tstopEventPump?.();\n\t\tconst reader = eng.getEventStream().getReader();\n\t\tstopEventPump = () => void reader.cancel();\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tfor (;;) {\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) return;\n\t\t\t\t\thandleAsyncEvent(eng, value);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// The stream errored or was cancelled (teardown); the loop is done.\n\t\t\t}\n\t\t})();\n\t};\n\n\tconst handleInit = (message: InitMessage): void => {\n\t\ttry {\n\t\t\tconst packages = resolvePackages(available, message.packages);\n\t\t\tengine = new ExpressionEngine({\n\t\t\t\tlocale: message.localeCode ?? \"en\",\n\t\t\t\tdiagnostics: message.diagnostics ?? false,\n\t\t\t\tconfig: message.config,\n\t\t\t\tpackages,\n\t\t\t});\n\t\t\tformatting = message.formatting;\n\t\t\t// Drain live-data resolutions for the engine's whole lifetime, so a\n\t\t\t// value that settles after a request already answered still reaches the\n\t\t\t// host. Started here, after the engine exists, and torn down with it.\n\t\t\tstartEventPump(engine);\n\t\t\tpost({ kind: \"ready\", id: message.id });\n\t\t} catch (error) {\n\t\t\t// A build failure leaves no engine; the caller's `createWorkerEngine`\n\t\t\t// promise rejects with this rather than hanging on a `ready` that\n\t\t\t// never comes.\n\t\t\tfail(message.id, error);\n\t\t}\n\t};\n\n\tconst runMethod = (eng: ExpressionEngine, message: RequestMessage): unknown => {\n\t\tconst { method, args } = message;\n\t\tswitch (method) {\n\t\t\tcase \"parseDocument\":\n\t\t\t\treturn serializeParsingResult(eng.parseDocument(args[0] as string, args[1] as never), formatting);\n\t\t\tcase \"evaluateLines\":\n\t\t\t\treturn eng.evaluateLines(args[0] as string[]).map((line) => serializeParsedLine(line, formatting));\n\t\t\tcase \"evaluateExpression\":\n\t\t\t\t// Mirrors ExpressionEngine.evaluateExpression: a single Value in,\n\t\t\t\t// a single serialized Value out.\n\t\t\t\treturn serializeValue(eng.evaluateExpression(args[0] as string), formatting);\n\t\t\tdefault:\n\t\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\tWorkerErrorCodes.WORKER_UNKNOWN_METHOD,\n\t\t\t\t\t`The worker runtime has no method named \"${String(method)}\"`,\n\t\t\t\t\t{ method },\n\t\t\t\t);\n\t\t}\n\t};\n\n\tconst handleRequest = (message: RequestMessage): void => {\n\t\tconst eng = engine;\n\t\tif (!eng) {\n\t\t\tfail(\n\t\t\t\tmessage.id,\n\t\t\t\tErrorFactory.execution(\n\t\t\t\t\tWorkerErrorCodes.WORKER_NOT_INITIALISED,\n\t\t\t\t\t\"The worker received a request before its engine finished initialising\",\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\t// Supersede the previous document: abort its controller so any resolution\n\t\t// still in flight for it is dropped at the engine's staleness guard rather\n\t\t// than posted home as if it belonged to this request's document. The old\n\t\t// retained lines go with it. Every evaluate call shares one engine and one\n\t\t// document context, so the most recent call is the live one.\n\t\tdocumentController?.abort();\n\n\t\t// This request's controller doubles as the document controller: wired in as\n\t\t// the keystroke signal so a later `cancel` (or the next supersede) aborts\n\t\t// the async work this evaluation fires, the same mechanism a host uses on\n\t\t// the main thread. It is deliberately NOT aborted when the request settles,\n\t\t// so this document's live values can still resolve and stream back.\n\t\tconst controller = new AbortController();\n\t\tdocumentController = controller;\n\t\tretainedLines = retainLines(message);\n\t\tinFlight.set(message.id, controller);\n\t\teng.setKeystrokeSignal(controller.signal);\n\n\t\ttry {\n\t\t\tconst value = runMethod(eng, message);\n\t\t\tpost({ kind: \"result\", id: message.id, value });\n\t\t} catch (error) {\n\t\t\tfail(message.id, error);\n\t\t} finally {\n\t\t\tinFlight.delete(message.id);\n\t\t\teng.setKeystrokeSignal(null);\n\t\t}\n\t};\n\n\ttransport.onMessage((raw) => {\n\t\tconst message = raw as MainToWorkerMessage;\n\t\tswitch (message.kind) {\n\t\t\tcase \"init\":\n\t\t\t\thandleInit(message);\n\t\t\t\tbreak;\n\t\t\tcase \"request\":\n\t\t\t\thandleRequest(message);\n\t\t\t\tbreak;\n\t\t\tcase \"cancel\":\n\t\t\t\t// Abort maps onto the keystroke signal for the named request; a\n\t\t\t\t// cancel that arrives after the request already settled finds no\n\t\t\t\t// controller and is a harmless no-op.\n\t\t\t\tinFlight.get(message.id)?.abort();\n\t\t\t\tbreak;\n\t\t}\n\t});\n\n\treturn () => {\n\t\tstopEventPump?.();\n\t\tstopEventPump = null;\n\t\tdocumentController?.abort();\n\t\tdocumentController = null;\n\t\tretainedLines = new Map();\n\t\tfor (const controller of inFlight.values()) controller.abort();\n\t\tinFlight.clear();\n\t\tengine?.clear();\n\t\tengine = null;\n\t\ttransport.terminate();\n\t};\n}\n","/**\n * The seam between the harness and whatever actually carries messages.\n *\n * Both the client (`worker/client.ts`) and the runtime (`worker/runtime.ts`)\n * talk to a {@link WorkerTransport} and nothing more, so the same code drives a\n * browser `Worker`, a Node `worker_threads` port, or an in-process pair. The\n * three factory functions below adapt each of those onto the interface; a host\n * with a transport this file does not cover can implement the three methods\n * directly.\n */\n\n/**\n * A bidirectional message channel with a single receive handler.\n *\n * `onMessage` registers the one handler the harness needs; calling it again\n * replaces the previous handler. `terminate` tears the channel down and is safe\n * to call more than once.\n */\nexport interface WorkerTransport {\n\t/** Send one message to the other end. The message must be clone-safe. */\n\tpostMessage(message: unknown): void;\n\t/** Register the handler that receives messages from the other end. */\n\tonMessage(handler: (message: unknown) => void): void;\n\t/** Tear the channel down. Idempotent. */\n\tterminate(): void;\n}\n\n/**\n * Clone a message the way `postMessage` would, so an in-process transport has\n * the same value semantics as a real one.\n *\n * The harness protocol is clone-safe by construction, so the `JSON` fallback\n * (for a runtime without a global `structuredClone`) is lossless here; the\n * structured-clone path is preferred because it is what a real worker uses and\n * because it throws loudly if a non-clone-safe value ever reaches it, which is\n * exactly the mistake the DTO layer exists to prevent.\n *\n * A function, not a module-level const, so this module does no work at load\n * time and stays deletable under the package's `sideEffects: false` claim; the\n * `typeof` probe runs once per message, which is free next to the clone itself.\n */\nfunction cloneMessage<T>(value: T): T {\n\treturn typeof globalThis.structuredClone === \"function\"\n\t\t? globalThis.structuredClone(value)\n\t\t: JSON.parse(JSON.stringify(value));\n}\n\n/**\n * A pair of linked in-process transports.\n *\n * `client` and `host` are two ends of one channel: a message posted on either\n * is cloned at post time and delivered to the other on a microtask, so delivery\n * is asynchronous (as a real worker's is) but deterministic (no timers, no I/O).\n * Wire `client` into {@link createWorkerEngine} and `host` into\n * {@link startWorkerRuntime} to run the whole protocol, DTO serialisation and\n * cancellation included, without a second thread. This is the transport tests\n * use, and a fit for a host that wants the message-passing shape on one thread.\n */\nexport function createLinkedTransports(): { client: WorkerTransport; host: WorkerTransport } {\n\tlet clientHandler: ((message: unknown) => void) | null = null;\n\tlet hostHandler: ((message: unknown) => void) | null = null;\n\tlet alive = true;\n\n\t// The handler is read at delivery time rather than post time so setup order\n\t// (post before the other end has registered) cannot drop a message.\n\tconst deliver = (target: () => ((message: unknown) => void) | null, message: unknown): void => {\n\t\tconst cloned = cloneMessage(message);\n\t\tqueueMicrotask(() => {\n\t\t\tif (!alive) return;\n\t\t\ttarget()?.(cloned);\n\t\t});\n\t};\n\n\tconst client: WorkerTransport = {\n\t\tpostMessage: (message) => deliver(() => hostHandler, message),\n\t\tonMessage: (handler) => {\n\t\t\tclientHandler = handler;\n\t\t},\n\t\tterminate: () => {\n\t\t\talive = false;\n\t\t},\n\t};\n\n\tconst host: WorkerTransport = {\n\t\tpostMessage: (message) => deliver(() => clientHandler, message),\n\t\tonMessage: (handler) => {\n\t\t\thostHandler = handler;\n\t\t},\n\t\tterminate: () => {\n\t\t\talive = false;\n\t\t},\n\t};\n\n\treturn { client, host };\n}\n\n/** The `postMessage`/`onmessage`/event-listener shape a browser `Worker`, a worker's `self`, or a DOM `MessagePort` presents. */\ninterface EventTargetLike {\n\tpostMessage(message: unknown): void;\n\taddEventListener?(type: \"message\", handler: (event: { data: unknown }) => void): void;\n\tonmessage?: ((event: { data: unknown }) => void) | null;\n\tterminate?(): void;\n\tclose?(): void;\n\tstart?(): void;\n}\n\n/**\n * Adapt a browser-style message target onto a {@link WorkerTransport}.\n *\n * Covers the main-side `Worker`, the worker global `self`, and a DOM\n * `MessagePort`: each posts with `postMessage` and receives a `MessageEvent`\n * whose `data` is the payload. A `MessagePort` is `start`ed here so it begins\n * dispatching. On the main side pass a `Worker`; inside a browser worker pass\n * `self`.\n */\nexport function eventTargetTransport(target: EventTargetLike): WorkerTransport {\n\treturn {\n\t\tpostMessage: (message) => target.postMessage(message),\n\t\tonMessage: (handler) => {\n\t\t\tconst listener = (event: { data: unknown }): void => handler(event.data);\n\t\t\tif (typeof target.addEventListener === \"function\") {\n\t\t\t\ttarget.addEventListener(\"message\", listener);\n\t\t\t} else {\n\t\t\t\ttarget.onmessage = listener;\n\t\t\t}\n\t\t\ttarget.start?.();\n\t\t},\n\t\t// A main-side Worker terminates; a worker's own `self` closes. Calling\n\t\t// whichever exists keeps one adapter usable from both ends.\n\t\tterminate: () => {\n\t\t\ttarget.terminate?.();\n\t\t\ttarget.close?.();\n\t\t},\n\t};\n}\n\n/** The `postMessage`/`on(\"message\")` shape a Node `worker_threads` `Worker`, `parentPort`, or `MessagePort` presents. */\ninterface MessagePortLike {\n\tpostMessage(message: unknown): void;\n\ton(event: \"message\", handler: (message: unknown) => void): void;\n\tterminate?(): void;\n\tclose?(): void;\n}\n\n/**\n * Adapt a Node `worker_threads` port onto a {@link WorkerTransport}.\n *\n * Covers the main-side `Worker`, the worker's `parentPort`, and a\n * `worker_threads` `MessagePort`: each posts with `postMessage` and emits a\n * `\"message\"` event whose argument IS the payload (no `.data` wrapper, unlike\n * the DOM). On the main side pass the `Worker`; inside the worker pass\n * `parentPort`.\n */\nexport function messagePortTransport(port: MessagePortLike): WorkerTransport {\n\treturn {\n\t\tpostMessage: (message) => port.postMessage(message),\n\t\tonMessage: (handler) => {\n\t\t\tport.on(\"message\", (message) => handler(message));\n\t\t},\n\t\tterminate: () => {\n\t\t\tport.terminate?.();\n\t\t\tport.close?.();\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"sources":["../src/worker/client.ts","../src/worker/serialize.ts","../src/worker/runtime.ts","../src/worker/transport.ts"],"names":["WorkerEngineClient","transport","raw","options","id","resolve","reject","input","signal","parsing","parseOptions","lines","expression","listener","error","workerTerminatedError","entry","method","args","workerCancelledError","onAbort","message","value","deserializeEngineError","apply","createWorkerEngine","client","nonFiniteTag","n","serializeMatrix","m","cells","cell","formatSymbolic","serializeValue","settings","reading","dto","formatValue","r","c","toHexString","formatColour","pt","ip","serializeMaybe","serializeInlineSolve","solve","serializeParsedLine","line","serializeParsingResult","result","resolvePackages","available","names","byName","pkg","resolved","name","ErrorFactory","WorkerErrorCodes","startWorkerRuntime","BUILTIN_PACKAGES","engine","formatting","inFlight","retainedLines","documentController","stopEventPump","post","fail","serializeEngineError","normalizeUnknownError","retainLines","map","text","index","handleAsyncEvent","eng","event","lineNumber","startEventPump","reader","done","handleInit","packages","ExpressionEngine","runMethod","handleRequest","controller","cloneMessage","createLinkedTransports","clientHandler","hostHandler","alive","deliver","target","cloned","handler","eventTargetTransport","messagePortTransport","port"],"mappings":"whCA8HA,IAAMA,CAAAA,CAAN,KAAiD,CAWhD,WAAA,CAAYC,CAAAA,CAA4B,CATxC,IAAA,CAAQ,MAAA,CAAS,CAAA,CACjB,IAAA,CAAiB,OAAA,CAAU,IAAI,GAAA,CAI/B,IAAA,CAAiB,iBAAA,CAAoB,IAAI,GAAA,CACzC,IAAA,CAAiB,mBAAA,CAAsB,IAAI,GAAA,CAC3C,IAAA,CAAQ,UAAA,CAAa,KAAA,CAGpB,IAAA,CAAK,SAAA,CAAYA,CAAAA,CACjB,IAAA,CAAK,UAAU,SAAA,CAAWC,CAAAA,EAAQ,IAAA,CAAK,SAAA,CAAUA,CAAG,CAAC,EACtD,CAGA,IAAA,CAAKC,CAAAA,CAA6C,CACjD,IAAMC,CAAAA,CAAK,IAAA,CAAK,MAAA,EAAA,CAChB,OAAO,IAAI,OAAA,CAAc,CAACC,CAAAA,CAASC,CAAAA,GAAW,CAC7C,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAIF,CAAAA,CAAI,CAAE,OAAA,CAAS,IAAMC,CAAAA,EAAQ,CAAG,MAAA,CAAAC,CAAO,CAAC,CAAA,CACzD,IAAA,CAAK,SAAA,CAAU,WAAA,CAAY,CAC1B,IAAA,CAAM,MAAA,CACN,EAAA,CAAAF,CAAAA,CACA,UAAA,CAAYD,CAAAA,CAAQ,UAAA,CACpB,WAAA,CAAaA,CAAAA,CAAQ,WAAA,CACrB,MAAA,CAAQA,CAAAA,CAAQ,MAAA,CAChB,QAAA,CAAUA,CAAAA,CAAQ,QAAA,CAClB,UAAA,CAAYA,CAAAA,CAAQ,UACrB,CAAC,EACF,CAAC,CACF,CAEA,aAAA,CACCI,CAAAA,CACAJ,EACmC,CAGnC,GAAM,CAAE,MAAA,C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AcK,EACf,EACA,SAAA,CAAW,IAAM,CAChBJ,CAAAA,CAAQ,MACT,CACD,CAEsB,CACvB,CAqBO,SAASK,EAAqBH,CAAAA,CAA0C,CAC9E,OAAO,CACN,YAAc3E,CAAAA,EAAY2E,CAAAA,CAAO,WAAA,CAAY3E,CAAO,EACpD,SAAA,CAAY6E,CAAAA,EAAY,CACvB,IAAMrF,EAAYkE,CAAAA,EAAmCmB,CAAAA,CAAQnB,CAAAA,CAAM,IAAI,EACnE,OAAOiB,CAAAA,CAAO,gBAAA,EAAqB,UAAA,CACtCA,EAAO,gBAAA,CAAiB,SAAA,CAAWnF,CAAQ,CAAA,CAE3CmF,EAAO,SAAA,CAAYnF,CAAAA,CAEpBmF,CAAAA,CAAO,KAAA,KACR,CAAA,CAGA,SAAA,CAAW,IAAM,CAChBA,CAAAA,CAAO,aAAY,CACnBA,CAAAA,CAAO,KAAA,KACR,CACD,CACD,CAmBO,SAASI,CAAAA,CAAqBC,EAAwC,CAC5E,OAAO,CACN,WAAA,CAAchF,GAAYgF,CAAAA,CAAK,WAAA,CAAYhF,CAAO,CAAA,CAClD,UAAY6E,CAAAA,EAAY,CACvBG,CAAAA,CAAK,EAAA,CAAG,UAAYhF,CAAAA,EAAY6E,CAAAA,CAAQ7E,CAAO,CAAC,EACjD,CAAA,CACA,SAAA,CAAW,IAAM,CAChBgF,EAAK,SAAA,IAAY,CACjBA,EAAK,KAAA,KACN,CACD,CACD","file":"worker.js","sourcesContent":["/**\n * The main-side half of the harness: an async proxy of the core evaluate\n * methods.\n *\n * {@link createWorkerEngine} performs the init handshake and resolves once the\n * worker's engine is built, so the returned {@link WorkerEngine} is ready to\n * call. Each call stamps a request id, tracks the pending promise, and settles\n * it when the matching answer arrives, so several requests can be outstanding at\n * once. An `AbortSignal` rejects the local promise and posts a `cancel` for the\n * same id, mapping keystroke-level cancellation onto the boundary rather than\n * re-inventing it.\n */\n\nimport type { EngineConfigOverride } from \"@solve-js/constants/Configuration\";\nimport type { UnifiedParsingOptions } from \"@solve-js/types/ParsingResult\";\nimport type { FormattingSettings } from \"@solve-js/format/FormattingSettings\";\nimport type { EngineError } from \"@solve-js/errors\";\nimport {\n\tdeserializeEngineError,\n\tworkerCancelledError,\n\tworkerTerminatedError,\n} from \"@solve-js/errors\";\nimport type { WorkerTransport } from \"./transport\";\nimport type {\n\tWorkerMethod,\n\tWorkerRequestArgs,\n\tWorkerToMainMessage,\n} from \"./protocol\";\nimport type {\n\tSerializedWorkerValue,\n\tSerializedParsedLine,\n\tSerializedParsingResult,\n} from \"./dto\";\n\n/** Configuration for {@link createWorkerEngine}. */\nexport interface WorkerEngineOptions {\n\t/** The channel to the worker runtime. See `worker/transport.ts` for adapters. */\n\ttransport: WorkerTransport;\n\t/** Locale for keywords and number formatting; defaults to English worker-side. */\n\tlocaleCode?: string;\n\t/** Whether the worker builds its engine with diagnostics enabled. */\n\tdiagnostics?: boolean;\n\t/** Config overrides, merged per section over the defaults worker-side. */\n\tconfig?: EngineConfigOverride;\n\t/**\n\t * Names of built-in packages the worker should register. Omitted registers\n\t * them all. Names rather than the packages themselves, since a package\n\t * carries functions that cannot cross a `postMessage` boundary; a host with\n\t * a custom package bakes it into its own worker entry and selects it here by\n\t * name.\n\t */\n\tpackages?: string[];\n\t/** Formatting settings the worker uses when it renders a DTO's display text. */\n\tformatting?: FormattingSettings;\n}\n\n/** Per-call options common to every proxied method. */\nexport interface WorkerCallOptions {\n\t/** Abort the request. Rejects the returned promise and cancels the work worker-side. */\n\tsignal?: AbortSignal;\n}\n\n/**\n * One line whose result changed after a live value resolved worker-side, carried\n * as its freshly re-evaluated {@link SerializedWorkerValue}. The value the host renders\n * against `lineNumber`, recovered worker-side so the main thread needs no further\n * round-trip to display it.\n */\nexport interface WorkerAsyncUpdate {\n\tlineNumber: number;\n\tvalue: SerializedWorkerValue;\n}\n\n/**\n * A live-data resolution that failed worker-side. `error` is the same structured\n * {@link EngineError} an in-process resolver failure would surface, rebuilt from\n * its transported form, so a host branches on `code`/`category` as it always has.\n */\nexport interface WorkerAsyncError {\n\tqueryKey: string;\n\tpackageId: string;\n\terror: EngineError;\n}\n\n/**\n * An async proxy of {@link ExpressionEngine}'s core evaluate methods.\n *\n * Each method mirrors its synchronous counterpart but returns a Promise of the\n * serialisable DTO rather than a live `Value`, and accepts an `AbortSignal`.\n */\nexport interface WorkerEngine {\n\t/** Parse a whole document off-thread. Mirrors `ExpressionEngine.parseDocument`. */\n\tparseDocument(input: string, options?: UnifiedParsingOptions & WorkerCallOptions): Promise<SerializedParsingResult>;\n\t/** Evaluate an array of lines off-thread. Mirrors `ExpressionEngine.evaluateLines`. */\n\tevaluateLines(lines: string[], options?: WorkerCallOptions): Promise<SerializedParsedLine[]>;\n\t/** Evaluate a single expression off-thread. Mirrors `ExpressionEngine.evaluateExpression`. */\n\tevaluateExpression(expression: string, options?: WorkerCallOptions): Promise<SerializedWorkerValue>;\n\t/**\n\t * Subscribe to live-data resolutions that land after a request already\n\t * answered.\n\t *\n\t * A currency, weather or historical-rate value resolves inside the worker some\n\t * time after `parseDocument` returned its pending result. When it does, the\n\t * affected lines are re-evaluated worker-side and their fresh values arrive\n\t * here as one batch. This is a subscription rather than a per-request promise\n\t * because a resolution is tied to no single request: it belongs to whichever\n\t * document is current when the value lands. Returns an unsubscribe function.\n\t */\n\tonResolved(listener: (lines: WorkerAsyncUpdate[]) => void): () => void;\n\t/**\n\t * Subscribe to live-data resolutions that failed. Returns an unsubscribe\n\t * function. See {@link onResolved}; this is its failure channel.\n\t */\n\tonAsyncError(listener: (error: WorkerAsyncError) => void): () => void;\n\t/** Reject every in-flight request and tear the transport down. Idempotent. */\n\tterminate(): void;\n}\n\n/** A promise awaiting one worker answer, plus the abort wiring to unhook when it settles. */\ninterface PendingRequest {\n\tresolve: (value: unknown) => void;\n\treject: (error: unknown) => void;\n\tsignal?: AbortSignal;\n\tonAbort?: () => void;\n}\n\nclass WorkerEngineClient implements WorkerEngine {\n\tprivate readonly transport: WorkerTransport;\n\tprivate nextId = 1;\n\tprivate readonly pending = new Map<number, PendingRequest>();\n\t// Broadcast subscribers for async resolutions. Sets, not one callback each, so\n\t// several views can watch the same worker; a resolution is not tied to a\n\t// request id, so these live outside `pending`.\n\tprivate readonly resolvedListeners = new Set<(lines: WorkerAsyncUpdate[]) => void>();\n\tprivate readonly asyncErrorListeners = new Set<(error: WorkerAsyncError) => void>();\n\tprivate terminated = false;\n\n\tconstructor(transport: WorkerTransport) {\n\t\tthis.transport = transport;\n\t\tthis.transport.onMessage((raw) => this.onMessage(raw));\n\t}\n\n\t/** Perform the init handshake, resolving once the worker posts `ready`. */\n\tinit(options: WorkerEngineOptions): Promise<void> {\n\t\tconst id = this.nextId++;\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tthis.pending.set(id, { resolve: () => resolve(), reject });\n\t\t\tthis.transport.postMessage({\n\t\t\t\tkind: \"init\",\n\t\t\t\tid,\n\t\t\t\tlocaleCode: options.localeCode,\n\t\t\t\tdiagnostics: options.diagnostics,\n\t\t\t\tconfig: options.config,\n\t\t\t\tpackages: options.packages,\n\t\t\t\tformatting: options.formatting,\n\t\t\t});\n\t\t});\n\t}\n\n\tparseDocument(\n\t\tinput: string,\n\t\toptions?: UnifiedParsingOptions & WorkerCallOptions,\n\t): Promise<SerializedParsingResult> {\n\t\t// The signal stays main-side and drives a `cancel`; only the parsing\n\t\t// options cross, so an AbortSignal never reaches `postMessage`.\n\t\tconst { signal, ...parsing } = options ?? {};\n\t\tconst parseOptions = Object.keys(parsing).length > 0 ? (parsing as UnifiedParsingOptions) : undefined;\n\t\treturn this.call<SerializedParsingResult>(\"parseDocument\", [input, parseOptions], signal);\n\t}\n\n\tevaluateLines(lines: string[], options?: WorkerCallOptions): Promise<SerializedParsedLine[]> {\n\t\treturn this.call<SerializedParsedLine[]>(\"evaluateLines\", [lines], options?.signal);\n\t}\n\n\tevaluateExpression(expression: string, options?: WorkerCallOptions): Promise<SerializedWorkerValue> {\n\t\treturn this.call<SerializedWorkerValue>(\"evaluateExpression\", [expression], options?.signal);\n\t}\n\n\tonResolved(listener: (lines: WorkerAsyncUpdate[]) => void): () => void {\n\t\tthis.resolvedListeners.add(listener);\n\t\treturn () => this.resolvedListeners.delete(listener);\n\t}\n\n\tonAsyncError(listener: (error: WorkerAsyncError) => void): () => void {\n\t\tthis.asyncErrorListeners.add(listener);\n\t\treturn () => this.asyncErrorListeners.delete(listener);\n\t}\n\n\tterminate(): void {\n\t\tif (this.terminated) return;\n\t\tthis.terminated = true;\n\t\tconst error = workerTerminatedError();\n\t\tfor (const entry of this.pending.values()) {\n\t\t\tthis.unhook(entry);\n\t\t\tentry.reject(error);\n\t\t}\n\t\tthis.pending.clear();\n\t\t// No more resolutions can arrive across a torn-down transport, so drop the\n\t\t// subscribers rather than leaving them referenced for the client's lifetime.\n\t\tthis.resolvedListeners.clear();\n\t\tthis.asyncErrorListeners.clear();\n\t\tthis.transport.terminate();\n\t}\n\n\t/** Dispatch one request and return the promise that settles on its answer. */\n\tprivate call<T>(method: WorkerMethod, args: WorkerRequestArgs, signal?: AbortSignal): Promise<T> {\n\t\tif (this.terminated) return Promise.reject(workerTerminatedError());\n\t\tif (signal?.aborted) return Promise.reject(workerCancelledError(method));\n\n\t\tconst id = this.nextId++;\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tconst entry: PendingRequest = { resolve: resolve as (value: unknown) => void, reject };\n\n\t\t\tif (signal) {\n\t\t\t\tconst onAbort = (): void => {\n\t\t\t\t\t// Nothing to do if the answer already arrived and settled this id.\n\t\t\t\t\tif (!this.pending.has(id)) return;\n\t\t\t\t\tthis.pending.delete(id);\n\t\t\t\t\tthis.transport.postMessage({ kind: \"cancel\", id });\n\t\t\t\t\treject(workerCancelledError(method));\n\t\t\t\t};\n\t\t\t\tentry.signal = signal;\n\t\t\t\tentry.onAbort = onAbort;\n\t\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t}\n\n\t\t\tthis.pending.set(id, entry);\n\t\t\tthis.transport.postMessage({ kind: \"request\", id, method, args });\n\t\t});\n\t}\n\n\t/** Route one incoming message to the request that is waiting on its id. */\n\tprivate onMessage(raw: unknown): void {\n\t\tconst message = raw as WorkerToMainMessage;\n\t\tswitch (message.kind) {\n\t\t\tcase \"ready\":\n\t\t\tcase \"result\": {\n\t\t\t\tconst value = message.kind === \"result\" ? message.value : undefined;\n\t\t\t\tthis.settle(message.id, (entry) => entry.resolve(value));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"error\":\n\t\t\t\tthis.settle(message.id, (entry) => entry.reject(deserializeEngineError(message.error)));\n\t\t\t\tbreak;\n\t\t\tcase \"async-update\":\n\t\t\t\t// A broadcast, not an answer to a request: fan it out to every\n\t\t\t\t// subscriber. A copy of the listener set is iterated so a listener\n\t\t\t\t// that unsubscribes itself mid-callback cannot disturb the walk.\n\t\t\t\tfor (const listener of [...this.resolvedListeners]) listener(message.lines);\n\t\t\t\tbreak;\n\t\t\tcase \"async-error\":\n\t\t\t\tfor (const listener of [...this.asyncErrorListeners]) {\n\t\t\t\t\tlistener({\n\t\t\t\t\t\tqueryKey: message.queryKey,\n\t\t\t\t\t\tpackageId: message.packageId,\n\t\t\t\t\t\terror: deserializeEngineError(message.error),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t/** Remove a pending request by id and run the settle callback, if it is still pending. */\n\tprivate settle(id: number, apply: (entry: PendingRequest) => void): void {\n\t\tconst entry = this.pending.get(id);\n\t\tif (!entry) return;\n\t\tthis.pending.delete(id);\n\t\tthis.unhook(entry);\n\t\tapply(entry);\n\t}\n\n\t/** Detach an entry's abort listener so a settled request leaves nothing on the signal. */\n\tprivate unhook(entry: PendingRequest): void {\n\t\tif (entry.signal && entry.onAbort) entry.signal.removeEventListener(\"abort\", entry.onAbort);\n\t}\n}\n\n/**\n * Build a worker-backed engine and wait for it to be ready.\n *\n * ```ts\n * const { client, host } = createLinkedTransports();\n * startWorkerRuntime(host);\n * const engine = await createWorkerEngine({ transport: client });\n * const result = await engine.parseDocument(text);\n * ```\n *\n * In production `client` wraps a real `Worker` (see `eventTargetTransport` /\n * `messagePortTransport`), and `startWorkerRuntime` runs inside that worker.\n */\nexport async function createWorkerEngine(options: WorkerEngineOptions): Promise<WorkerEngine> {\n\tconst client = new WorkerEngineClient(options.transport);\n\tawait client.init(options);\n\treturn client;\n}\n","/**\n * Turn live engine results into the clone-safe DTOs the worker harness posts.\n *\n * These functions run on the worker side, just before a result crosses the\n * boundary, and are also what the main side re-runs on a synchronous result to\n * compare the two paths in tests. They are pure and deterministic given the\n * same {@link FormattingSettings}, so a value serialised on either side is\n * byte-for-byte the same DTO.\n */\n\nimport { Value, ValueType, type MatrixData, type MatrixEntry, type RangeData, type ColourData, type ChartData, type IpCidrData } from \"@solve-js/vm/Value\";\nimport { formatValue } from \"@solve-js/format/FormatEngine\";\nimport { toHexString, formatColour } from \"@solve-js/packages/colour/ColourMath\";\nimport type { FormattingSettings } from \"@solve-js/format/FormattingSettings\";\nimport { formatSymbolic } from \"@solve-js/symbolic\";\nimport type { ParsedLine, InlineSolvePosition, ParsingResult } from \"@solve-js/types/ParsingResult\";\nimport type {\n\tSerializedWorkerValue,\n\tSerializedMatrix,\n\tSerializedParsedLine,\n\tSerializedInlineSolve,\n\tSerializedParsingResult,\n} from \"./dto\";\n\n/**\n * The JSON-safe string tag for a non-finite reading. `Infinity`/`-Infinity`/`NaN`\n * cannot cross `JSON` (which turns each into `null`), so this one string form is\n * what survives both `structuredClone` and `JSON`, and a host recovers the value\n * with `Number(tag)`. Shared by the scalar `nonFinite` field and matrix cells.\n */\nfunction nonFiniteTag(n: number): \"Infinity\" | \"-Infinity\" | \"NaN\" {\n\treturn n > 0 ? \"Infinity\" : n < 0 ? \"-Infinity\" : \"NaN\";\n}\n\n/** Project a matrix onto clone-safe cells: finite primitives pass through, symbolic cells and non-finite numbers become strings. */\nfunction serializeMatrix(m: MatrixData): SerializedMatrix {\n\tconst cells = m.data.map((cell: MatrixEntry): number | boolean | string => {\n\t\t// A `SymbolicNode` (the object-typed cell variant) flattens to its display\n\t\t// string. A non-finite number (a `[1/0, 2]` cell) cannot cross JSON any\n\t\t// more than a scalar reading can, so it takes the same string tag rather\n\t\t// than being passed through raw and turned into `null` by `JSON.stringify`\n\t\t// (which would diverge from the `structuredClone` path). A finite number\n\t\t// or a boolean is already clone-safe and passes through.\n\t\tif (typeof cell === \"object\" && cell !== null) return formatSymbolic(cell);\n\t\tif (typeof cell === \"number\" && !Number.isFinite(cell)) return nonFiniteTag(cell);\n\t\treturn cell;\n\t});\n\treturn { rows: m.rows, cols: m.cols, cells, hasSymbolic: m.hasSymbolic };\n}\n\n/**\n * Project a {@link Value} onto a {@link SerializedWorkerValue}.\n *\n * `text` and `number` are set for every value; the type-specific fields are\n * added only where the payload needs them, so the DTO stays minimal and a\n * deep-equal between the two evaluation paths does not trip on a property one\n * side left `undefined`.\n */\nexport function serializeValue(value: Value, settings?: FormattingSettings): SerializedWorkerValue {\n\tconst reading = value.toNumber();\n\tconst dto: SerializedWorkerValue = {\n\t\ttype: value.type,\n\t\ttext: formatValue(value, settings),\n\t\t// A non-finite reading (1/0, 0/0, an overflow) cannot cross JSON, which\n\t\t// turns it into null and breaks the round-trip the DTO guarantees. Keep\n\t\t// `number` finite and name the real value in `nonFinite` instead.\n\t\tnumber: Number.isFinite(reading) ? reading : 0,\n\t};\n\tif (!Number.isFinite(reading)) {\n\t\tdto.nonFinite = nonFiniteTag(reading);\n\t}\n\n\tif (value.unit !== undefined) dto.unit = value.unit;\n\tif (value.timedOut !== undefined) dto.timedOut = value.timedOut;\n\n\tconst raw = value.value;\n\tif (typeof raw === \"bigint\") {\n\t\t// Covers BigInt values and a Hex value that carries a bigint magnitude:\n\t\t// a base-ten string is the one representation that neither loses\n\t\t// precision nor breaks JSON.\n\t\tdto.bigint = raw.toString();\n\t} else if (value.type === ValueType.Matrix) {\n\t\tdto.matrix = serializeMatrix(raw as MatrixData);\n\t} else if (value.type === ValueType.Range) {\n\t\tconst r = raw as RangeData;\n\t\tdto.range = { min: r.min, max: r.max };\n\t} else if (value.type === ValueType.Colour) {\n\t\tconst c = raw as ColourData;\n\t\tdto.colour = { hex: toHexString(c), r: c.r, g: c.g, b: c.b, a: c.a, format: c.format, css: formatColour(c) };\n\t} else if (value.type === ValueType.Chart) {\n\t\tconst c = raw as ChartData;\n\t\tdto.chart = {\n\t\t\tkind: c.kind,\n\t\t\tpoints: c.points.map((pt) => [pt[0], pt[1]]),\n\t\t\tlabel: c.label,\n\t\t\tdomain: [c.domain[0], c.domain[1]],\n\t\t\trange: [c.range[0], c.range[1]],\n\t\t\t...(c.expr !== undefined ? { expr: c.expr } : {}),\n\t\t};\n\t} else if (value.type === ValueType.IpCidr) {\n\t\tconst ip = raw as IpCidrData;\n\t\tdto.ipCidr = {\n\t\t\t...(ip.addr !== undefined ? { addr: ip.addr } : {}),\n\t\t\t...(ip.prefix !== undefined ? { prefix: ip.prefix } : {}),\n\t\t\ttext: formatValue(value).replace(/^=\\s*/, \"\"),\n\t\t};\n\t}\n\n\treturn dto;\n}\n\n/** Serialise a nullable value, the shape both `result` fields carry. */\nfunction serializeMaybe(value: Value | null | undefined, settings?: FormattingSettings): SerializedWorkerValue | null {\n\treturn value ? serializeValue(value, settings) : null;\n}\n\n/** Project an inline solve onto its DTO, serialising its result. */\nfunction serializeInlineSolve(solve: InlineSolvePosition, settings?: FormattingSettings): SerializedInlineSolve {\n\treturn {\n\t\tstart: solve.start,\n\t\tend: solve.end,\n\t\texpression: solve.expression,\n\t\tlineNumber: solve.lineNumber,\n\t\tcolumnNumber: solve.columnNumber,\n\t\tresult: serializeMaybe(solve.result, settings),\n\t\terror: solve.error ?? null,\n\t};\n}\n\n/** Project a parsed line onto its DTO, serialising its result and every inline solve. */\nexport function serializeParsedLine(line: ParsedLine, settings?: FormattingSettings): SerializedParsedLine {\n\treturn {\n\t\tlineNumber: line.lineNumber,\n\t\ttext: line.text,\n\t\tstartPosition: line.startPosition,\n\t\tendPosition: line.endPosition,\n\t\tisEmpty: line.isEmpty,\n\t\thasInlineSolves: line.hasInlineSolves,\n\t\tinlineSolves: line.inlineSolves.map((solve) => serializeInlineSolve(solve, settings)),\n\t\texpression: line.expression,\n\t\tresult: serializeMaybe(line.result, settings),\n\t\terror: line.error,\n\t};\n}\n\n/** Project a whole parsing result onto its DTO. */\nexport function serializeParsingResult(result: ParsingResult, settings?: FormattingSettings): SerializedParsingResult {\n\tconst dto: SerializedParsingResult = {\n\t\tlines: result.lines.map((line) => serializeParsedLine(line, settings)),\n\t\ttotalLines: result.totalLines,\n\t\terrors: [...result.errors],\n\t};\n\t// The diagnostics report is already the engine's own JSON form, so it\n\t// crosses unchanged; present only when the host asked for it.\n\tif (result.diagnostics !== undefined) dto.diagnostics = result.diagnostics;\n\treturn dto;\n}\n","/**\n * The worker-side half of the harness: it owns an {@link ExpressionEngine} and\n * answers the protocol.\n *\n * {@link startWorkerRuntime} is transport-agnostic, so the same function runs\n * behind a browser `Worker`, a Node `worker_threads` port, or an in-process\n * link. A host's worker entry file is two lines: adapt the environment onto a\n * {@link WorkerTransport} and call this.\n *\n * The runtime never posts a raw {@link Value}. Every result is projected onto a\n * DTO first (`worker/serialize.ts`), and every failure is caught and flattened\n * into a structured error, so a worker-side throw reaches the caller as an\n * `EngineError` rather than a lost promise.\n */\n\nimport { ExpressionEngine } from \"@solve-js/engine/ExpressionEngine\";\nimport type { AsyncResolutionEvent } from \"@solve-js/engine/AsyncResolutionBatcher\";\nimport type { IEnginePackage } from \"@solve-js/api/PackageRegistry\";\nimport { BUILTIN_PACKAGES } from \"@solve-js/packages/builtins\";\nimport type { FormattingSettings } from \"@solve-js/format/FormattingSettings\";\nimport {\n\tErrorFactory,\n\tnormalizeUnknownError,\n\tserializeEngineError,\n\tWorkerErrorCodes,\n} from \"@solve-js/errors\";\nimport { serializeParsingResult, serializeParsedLine, serializeValue } from \"./serialize\";\nimport type { WorkerTransport } from \"./transport\";\nimport type {\n\tMainToWorkerMessage,\n\tInitMessage,\n\tRequestMessage,\n\tWorkerToMainMessage,\n\tAsyncResolvedLine,\n} from \"./protocol\";\n\n/** Options a host bakes into its own worker entry, chiefly its custom packages. */\nexport interface WorkerRuntimeOptions {\n\t/**\n\t * The packages available to register, defaulting to {@link BUILTIN_PACKAGES}.\n\t * A host with its own package authors a worker entry that passes them here,\n\t * then selects among them by name from the main side. This is how a\n\t * function-carrying package reaches the worker: baked into its bundle, never\n\t * posted across the boundary.\n\t */\n\tpackages?: IEnginePackage[];\n}\n\n/**\n * Resolve the requested package names against the available set.\n *\n * Undefined names means \"all of them\". A name with no match is a configuration\n * failure the caller must see, not a silent omission that would leave a feature\n * quietly missing from every result.\n */\nfunction resolvePackages(available: IEnginePackage[], names: string[] | undefined): IEnginePackage[] {\n\tif (names === undefined) return available;\n\tconst byName = new Map(available.map((pkg) => [pkg.name, pkg]));\n\tconst resolved: IEnginePackage[] = [];\n\tfor (const name of names) {\n\t\tconst pkg = byName.get(name);\n\t\tif (!pkg) {\n\t\t\tthrow ErrorFactory.config(\n\t\t\t\tWorkerErrorCodes.WORKER_UNKNOWN_PACKAGE,\n\t\t\t\t`No package named \"${name}\" is available in this worker runtime`,\n\t\t\t\t{ name, available: [...byName.keys()] },\n\t\t\t);\n\t\t}\n\t\tresolved.push(pkg);\n\t}\n\treturn resolved;\n}\n\n/**\n * Attach the runtime to a transport and start serving.\n *\n * Returns a teardown function that clears the engine and detaches, for a host\n * that reuses a transport or shuts a worker down cleanly.\n */\nexport function startWorkerRuntime(transport: WorkerTransport, options: WorkerRuntimeOptions = {}): () => void {\n\tconst available = options.packages ?? BUILTIN_PACKAGES;\n\n\tlet engine: ExpressionEngine | null = null;\n\tlet formatting: FormattingSettings | undefined;\n\t// One AbortController per in-flight request, so a `cancel` can map onto the\n\t// engine's keystroke signal for exactly the request the caller aborted.\n\tconst inFlight = new Map<number, AbortController>();\n\n\t// The line texts of the current document, keyed by the line number the engine\n\t// evaluates them under (1-based for a document, -1 for a lone expression). An\n\t// async resolution names the lines whose result changed but not the new value,\n\t// so this is what the event pump re-reads a line from to recover it.\n\tlet retainedLines = new Map<number, string>();\n\n\t// The current document's abort controller, kept alive past the request that\n\t// created it so this document's async resolutions can still land. Aborted when\n\t// a new document supersedes it: aborting drops the old document's in-flight\n\t// resolutions at the engine's own staleness guard (an aborted signal is\n\t// discarded before it reaches the batcher), so a stale value never reaches the\n\t// host as if it were current. See {@link handleRequest}.\n\tlet documentController: AbortController | null = null;\n\n\t// Cancels the event-stream reader on teardown. Null until the pump starts.\n\tlet stopEventPump: (() => void) | null = null;\n\n\tconst post = (message: WorkerToMainMessage): void => transport.postMessage(message);\n\n\tconst fail = (id: number, error: unknown): void => {\n\t\tpost({ kind: \"error\", id, error: serializeEngineError(normalizeUnknownError(error)) });\n\t};\n\n\t/**\n\t * Record the line texts a request evaluates, so a later async resolution can\n\t * re-read exactly the lines it names. A whole document splits into 1-based\n\t * lines; a lone `evaluateExpression` maps onto the engine's `-1` sentinel, the\n\t * same line number the engine registers and later reports for it.\n\t */\n\tconst retainLines = (message: RequestMessage): Map<number, string> => {\n\t\tconst map = new Map<number, string>();\n\t\tif (message.method === \"parseDocument\") {\n\t\t\t(message.args[0] as string).split(\"\\n\").forEach((text, index) => map.set(index + 1, text));\n\t\t} else if (message.method === \"evaluateLines\") {\n\t\t\t(message.args[0] as string[]).forEach((text, index) => map.set(index + 1, text));\n\t\t} else {\n\t\t\tmap.set(-1, message.args[0] as string);\n\t\t}\n\t\treturn map;\n\t};\n\n\t/**\n\t * Turn one async resolution event into a message home.\n\t *\n\t * A `lines-updated` event names the lines whose result changed; the resolved\n\t * value lives in the engine's cache, so each named line is re-evaluated (which\n\t * now reads the settled value from that cache rather than starting a fresh\n\t * fetch) and serialised. A line the current document no longer retains belongs\n\t * to a superseded document and is skipped. An `error` event carries the failed\n\t * query straight across as a structured error.\n\t */\n\tconst handleAsyncEvent = (eng: ExpressionEngine, event: AsyncResolutionEvent): void => {\n\t\tif (event.type === \"error\") {\n\t\t\tpost({\n\t\t\t\tkind: \"async-error\",\n\t\t\t\tqueryKey: event.queryKey,\n\t\t\t\tpackageId: event.packageId,\n\t\t\t\terror: serializeEngineError(normalizeUnknownError(event.error)),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tconst lines: AsyncResolvedLine[] = [];\n\t\tfor (const lineNumber of event.lineNumbers) {\n\t\t\tconst text = retainedLines.get(lineNumber);\n\t\t\tif (text === undefined) continue;\n\t\t\ttry {\n\t\t\t\tconst value = eng.evaluateLine(lineNumber, text);\n\t\t\t\tif (value) lines.push({ lineNumber, value: serializeValue(value, formatting) });\n\t\t\t} catch {\n\t\t\t\t// A line that resolved into an error re-throws on re-evaluation; the\n\t\t\t\t// batcher's own `error` event is the channel for that, so this keeps\n\t\t\t\t// the update to the lines that produced a value rather than posting a\n\t\t\t\t// second, half-formed failure here.\n\t\t\t}\n\t\t}\n\t\tif (lines.length > 0) post({ kind: \"async-update\", lines });\n\t};\n\n\t/**\n\t * Drain the engine's async-resolution event stream for the life of the\n\t * runtime, posting each event home. Started once the engine exists; the reader\n\t * loop ends when the stream closes (engine cleared) or the returned canceller\n\t * runs at teardown.\n\t */\n\tconst startEventPump = (eng: ExpressionEngine): void => {\n\t\tstopEventPump?.();\n\t\tconst reader = eng.getEventStream().getReader();\n\t\tstopEventPump = () => void reader.cancel();\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tfor (;;) {\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) return;\n\t\t\t\t\thandleAsyncEvent(eng, value);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// The stream errored or was cancelled (teardown); the loop is done.\n\t\t\t}\n\t\t})();\n\t};\n\n\tconst handleInit = (message: InitMessage): void => {\n\t\ttry {\n\t\t\tconst packages = resolvePackages(available, message.packages);\n\t\t\tengine = new ExpressionEngine({\n\t\t\t\tlocale: message.localeCode ?? \"en\",\n\t\t\t\tdiagnostics: message.diagnostics ?? false,\n\t\t\t\tconfig: message.config,\n\t\t\t\tpackages,\n\t\t\t});\n\t\t\tformatting = message.formatting;\n\t\t\t// Drain live-data resolutions for the engine's whole lifetime, so a\n\t\t\t// value that settles after a request already answered still reaches the\n\t\t\t// host. Started here, after the engine exists, and torn down with it.\n\t\t\tstartEventPump(engine);\n\t\t\tpost({ kind: \"ready\", id: message.id });\n\t\t} catch (error) {\n\t\t\t// A build failure leaves no engine; the caller's `createWorkerEngine`\n\t\t\t// promise rejects with this rather than hanging on a `ready` that\n\t\t\t// never comes.\n\t\t\tfail(message.id, error);\n\t\t}\n\t};\n\n\tconst runMethod = (eng: ExpressionEngine, message: RequestMessage): unknown => {\n\t\tconst { method, args } = message;\n\t\tswitch (method) {\n\t\t\tcase \"parseDocument\":\n\t\t\t\treturn serializeParsingResult(eng.parseDocument(args[0] as string, args[1] as never), formatting);\n\t\t\tcase \"evaluateLines\":\n\t\t\t\treturn eng.evaluateLines(args[0] as string[]).map((line) => serializeParsedLine(line, formatting));\n\t\t\tcase \"evaluateExpression\":\n\t\t\t\t// Mirrors ExpressionEngine.evaluateExpression: a single Value in,\n\t\t\t\t// a single serialized Value out.\n\t\t\t\treturn serializeValue(eng.evaluateExpression(args[0] as string), formatting);\n\t\t\tdefault:\n\t\t\t\tthrow ErrorFactory.execution(\n\t\t\t\t\tWorkerErrorCodes.WORKER_UNKNOWN_METHOD,\n\t\t\t\t\t`The worker runtime has no method named \"${String(method)}\"`,\n\t\t\t\t\t{ method },\n\t\t\t\t);\n\t\t}\n\t};\n\n\tconst handleRequest = (message: RequestMessage): void => {\n\t\tconst eng = engine;\n\t\tif (!eng) {\n\t\t\tfail(\n\t\t\t\tmessage.id,\n\t\t\t\tErrorFactory.execution(\n\t\t\t\t\tWorkerErrorCodes.WORKER_NOT_INITIALISED,\n\t\t\t\t\t\"The worker received a request before its engine finished initialising\",\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\t// Supersede the previous document: abort its controller so any resolution\n\t\t// still in flight for it is dropped at the engine's staleness guard rather\n\t\t// than posted home as if it belonged to this request's document. The old\n\t\t// retained lines go with it. Every evaluate call shares one engine and one\n\t\t// document context, so the most recent call is the live one.\n\t\tdocumentController?.abort();\n\n\t\t// This request's controller doubles as the document controller: wired in as\n\t\t// the keystroke signal so a later `cancel` (or the next supersede) aborts\n\t\t// the async work this evaluation fires, the same mechanism a host uses on\n\t\t// the main thread. It is deliberately NOT aborted when the request settles,\n\t\t// so this document's live values can still resolve and stream back.\n\t\tconst controller = new AbortController();\n\t\tdocumentController = controller;\n\t\tretainedLines = retainLines(message);\n\t\tinFlight.set(message.id, controller);\n\t\teng.setKeystrokeSignal(controller.signal);\n\n\t\ttry {\n\t\t\tconst value = runMethod(eng, message);\n\t\t\tpost({ kind: \"result\", id: message.id, value });\n\t\t} catch (error) {\n\t\t\tfail(message.id, error);\n\t\t} finally {\n\t\t\tinFlight.delete(message.id);\n\t\t\teng.setKeystrokeSignal(null);\n\t\t}\n\t};\n\n\ttransport.onMessage((raw) => {\n\t\tconst message = raw as MainToWorkerMessage;\n\t\tswitch (message.kind) {\n\t\t\tcase \"init\":\n\t\t\t\thandleInit(message);\n\t\t\t\tbreak;\n\t\t\tcase \"request\":\n\t\t\t\thandleRequest(message);\n\t\t\t\tbreak;\n\t\t\tcase \"cancel\":\n\t\t\t\t// Abort maps onto the keystroke signal for the named request; a\n\t\t\t\t// cancel that arrives after the request already settled finds no\n\t\t\t\t// controller and is a harmless no-op.\n\t\t\t\tinFlight.get(message.id)?.abort();\n\t\t\t\tbreak;\n\t\t}\n\t});\n\n\treturn () => {\n\t\tstopEventPump?.();\n\t\tstopEventPump = null;\n\t\tdocumentController?.abort();\n\t\tdocumentController = null;\n\t\tretainedLines = new Map();\n\t\tfor (const controller of inFlight.values()) controller.abort();\n\t\tinFlight.clear();\n\t\tengine?.clear();\n\t\tengine = null;\n\t\ttransport.terminate();\n\t};\n}\n","/**\n * The seam between the harness and whatever actually carries messages.\n *\n * Both the client (`worker/client.ts`) and the runtime (`worker/runtime.ts`)\n * talk to a {@link WorkerTransport} and nothing more, so the same code drives a\n * browser `Worker`, a Node `worker_threads` port, or an in-process pair. The\n * three factory functions below adapt each of those onto the interface; a host\n * with a transport this file does not cover can implement the three methods\n * directly.\n */\n\n/**\n * A bidirectional message channel with a single receive handler.\n *\n * `onMessage` registers the one handler the harness needs; calling it again\n * replaces the previous handler. `terminate` tears the channel down and is safe\n * to call more than once.\n */\nexport interface WorkerTransport {\n\t/** Send one message to the other end. The message must be clone-safe. */\n\tpostMessage(message: unknown): void;\n\t/** Register the handler that receives messages from the other end. */\n\tonMessage(handler: (message: unknown) => void): void;\n\t/** Tear the channel down. Idempotent. */\n\tterminate(): void;\n}\n\n/**\n * Clone a message the way `postMessage` would, so an in-process transport has\n * the same value semantics as a real one.\n *\n * The harness protocol is clone-safe by construction, so the `JSON` fallback\n * (for a runtime without a global `structuredClone`) is lossless here; the\n * structured-clone path is preferred because it is what a real worker uses and\n * because it throws loudly if a non-clone-safe value ever reaches it, which is\n * exactly the mistake the DTO layer exists to prevent.\n *\n * A function, not a module-level const, so this module does no work at load\n * time and stays deletable under the package's `sideEffects: false` claim; the\n * `typeof` probe runs once per message, which is free next to the clone itself.\n */\nfunction cloneMessage<T>(value: T): T {\n\treturn typeof globalThis.structuredClone === \"function\"\n\t\t? globalThis.structuredClone(value)\n\t\t: JSON.parse(JSON.stringify(value));\n}\n\n/**\n * A pair of linked in-process transports.\n *\n * `client` and `host` are two ends of one channel: a message posted on either\n * is cloned at post time and delivered to the other on a microtask, so delivery\n * is asynchronous (as a real worker's is) but deterministic (no timers, no I/O).\n * Wire `client` into {@link createWorkerEngine} and `host` into\n * {@link startWorkerRuntime} to run the whole protocol, DTO serialisation and\n * cancellation included, without a second thread. This is the transport tests\n * use, and a fit for a host that wants the message-passing shape on one thread.\n */\nexport function createLinkedTransports(): { client: WorkerTransport; host: WorkerTransport } {\n\tlet clientHandler: ((message: unknown) => void) | null = null;\n\tlet hostHandler: ((message: unknown) => void) | null = null;\n\tlet alive = true;\n\n\t// The handler is read at delivery time rather than post time so setup order\n\t// (post before the other end has registered) cannot drop a message.\n\tconst deliver = (target: () => ((message: unknown) => void) | null, message: unknown): void => {\n\t\tconst cloned = cloneMessage(message);\n\t\tqueueMicrotask(() => {\n\t\t\tif (!alive) return;\n\t\t\ttarget()?.(cloned);\n\t\t});\n\t};\n\n\tconst client: WorkerTransport = {\n\t\tpostMessage: (message) => deliver(() => hostHandler, message),\n\t\tonMessage: (handler) => {\n\t\t\tclientHandler = handler;\n\t\t},\n\t\tterminate: () => {\n\t\t\talive = false;\n\t\t},\n\t};\n\n\tconst host: WorkerTransport = {\n\t\tpostMessage: (message) => deliver(() => clientHandler, message),\n\t\tonMessage: (handler) => {\n\t\t\thostHandler = handler;\n\t\t},\n\t\tterminate: () => {\n\t\t\talive = false;\n\t\t},\n\t};\n\n\treturn { client, host };\n}\n\n/** The `postMessage`/`onmessage`/event-listener shape a browser `Worker`, a worker's `self`, or a DOM `MessagePort` presents. */\ninterface EventTargetLike {\n\tpostMessage(message: unknown): void;\n\taddEventListener?(type: \"message\", handler: (event: { data: unknown }) => void): void;\n\tonmessage?: ((event: { data: unknown }) => void) | null;\n\tterminate?(): void;\n\tclose?(): void;\n\tstart?(): void;\n}\n\n/**\n * Adapt a browser-style message target onto a {@link WorkerTransport}.\n *\n * Covers the main-side `Worker`, the worker global `self`, and a DOM\n * `MessagePort`: each posts with `postMessage` and receives a `MessageEvent`\n * whose `data` is the payload. A `MessagePort` is `start`ed here so it begins\n * dispatching. On the main side pass a `Worker`; inside a browser worker pass\n * `self`.\n */\nexport function eventTargetTransport(target: EventTargetLike): WorkerTransport {\n\treturn {\n\t\tpostMessage: (message) => target.postMessage(message),\n\t\tonMessage: (handler) => {\n\t\t\tconst listener = (event: { data: unknown }): void => handler(event.data);\n\t\t\tif (typeof target.addEventListener === \"function\") {\n\t\t\t\ttarget.addEventListener(\"message\", listener);\n\t\t\t} else {\n\t\t\t\ttarget.onmessage = listener;\n\t\t\t}\n\t\t\ttarget.start?.();\n\t\t},\n\t\t// A main-side Worker terminates; a worker's own `self` closes. Calling\n\t\t// whichever exists keeps one adapter usable from both ends.\n\t\tterminate: () => {\n\t\t\ttarget.terminate?.();\n\t\t\ttarget.close?.();\n\t\t},\n\t};\n}\n\n/** The `postMessage`/`on(\"message\")` shape a Node `worker_threads` `Worker`, `parentPort`, or `MessagePort` presents. */\ninterface MessagePortLike {\n\tpostMessage(message: unknown): void;\n\ton(event: \"message\", handler: (message: unknown) => void): void;\n\tterminate?(): void;\n\tclose?(): void;\n}\n\n/**\n * Adapt a Node `worker_threads` port onto a {@link WorkerTransport}.\n *\n * Covers the main-side `Worker`, the worker's `parentPort`, and a\n * `worker_threads` `MessagePort`: each posts with `postMessage` and emits a\n * `\"message\"` event whose argument IS the payload (no `.data` wrapper, unlike\n * the DOM). On the main side pass the `Worker`; inside the worker pass\n * `parentPort`.\n */\nexport function messagePortTransport(port: MessagePortLike): WorkerTransport {\n\treturn {\n\t\tpostMessage: (message) => port.postMessage(message),\n\t\tonMessage: (handler) => {\n\t\t\tport.on(\"message\", (message) => handler(message));\n\t\t},\n\t\tterminate: () => {\n\t\t\tport.terminate?.();\n\t\t\tport.close?.();\n\t\t},\n\t};\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "solve-engine",
3
- "version": "2.23.0",
3
+ "version": "2.25.0",
4
4
  "description": "An embeddable expression engine for natural-language calculations: units, currencies, percentages, dates and matrices, with the parsing and evaluation plumbing already built.",
5
5
  "keywords": [
6
6
  "expression-evaluator",
@@ -218,13 +218,13 @@
218
218
  "typecheck:tsc": "tsc --noEmit --skipLibCheck"
219
219
  },
220
220
  "dependencies": {
221
- "@tanstack/query-core": "^5.100.10"
221
+ "@tanstack/query-core": "^5.102.8"
222
222
  },
223
223
  "devDependencies": {
224
- "@jest/globals": "^30.4.1",
225
- "@types/node": "^26.2.0",
224
+ "@jest/globals": "^30.5.0",
225
+ "@types/node": "^26.4.0",
226
226
  "convert": "^7.0.0",
227
- "jest": "^30.4.2",
227
+ "jest": "^30.5.0",
228
228
  "ts-jest": "^29.4.12",
229
229
  "tsup": "8.5.1",
230
230
  "typescript": "5.9.3"
@@ -1,5 +0,0 @@
1
- import {b as b$3,a as a$4}from'./chunk-JVMINMAB.js';import {a as a$2}from'./chunk-7E7NXKQ5.js';import {a as a$6}from'./chunk-MIQBJGGR.js';import {d,c,a as a$1,b}from'./chunk-ALY4ZMYO.js';import {a as a$3,b as b$4,c as c$6}from'./chunk-JP4JMQOG.js';import {c as c$8,a as a$a}from'./chunk-QTSDIDAS.js';import {h,b as b$8}from'./chunk-HMC7FJO7.js';import {d as d$1}from'./chunk-O3BDXOQJ.js';import {c as c$2,g,d as d$3,b as b$7}from'./chunk-4DJJIUQF.js';import {b as b$6}from'./chunk-76F3LCIL.js';import {c as c$3,a as a$7,b as b$a}from'./chunk-TCZSPH4A.js';import {w,x,F as F$1,H as H$1,I,i,K as K$1}from'./chunk-A5M4QZIK.js';import {_ as _$1,da}from'./chunk-KEA5HRL3.js';import {P,O,t,n,l,m,L,u,N,M,s,r,g as g$1}from'./chunk-3GR46UOX.js';import {c as c$1,b as b$1,a as a$5}from'./chunk-BRJ4RT5U.js';import {b as b$2,d as d$2,c as c$9}from'./chunk-FP6Z6PYR.js';import {b as b$5,c as c$4}from'./chunk-JPFCXLJV.js';import {a as a$8}from'./chunk-AF7HQN6I.js';import {a,c as c$7}from'./chunk-IJMNVBIS.js';import {a as a$9}from'./chunk-LHLW7JLS.js';import {d as d$4,c as c$5,b as b$9}from'./chunk-PIZQIQVM.js';function wt(n,e,t,r,i){let s=t[e],o=r[e];if(!s||!o)return;let a=new Set(Object.keys(s));for(let l of Object.keys(o))a.has(l)&&i.push({kind:n,severity:"warning",detail:`Both "${t.name}" and "${r.name}" register a ${e==="prefixParselets"?"prefix":"infix"} parselet for token type "${l}" \u2014 the later-registered one silently wins.`,packages:[t.name,r.name]});}function Tt(n,e){let t=[];if(wt("prefixParseletTokenType","prefixParselets",n,e,t),wt("infixParseletTokenType","infixParselets",n,e,t),n.phrases&&e.phrases)for(let[s,o]of Object.entries(e.phrases)){let a=n.phrases[s];a!==void 0&&a!==o&&t.push({kind:"phrase",severity:"warning",detail:`Both "${n.name}" (-> "${a}") and "${e.name}" (-> "${o}") fuse the phrase "${s}" to DIFFERENT token types \u2014 PhraseTrie has no collision detection of its own, so the later-registered mapping silently wins with no other signal.`,packages:[n.name,e.name]});}if(n.asConverters&&e.asConverters)for(let s of Object.keys(e.asConverters)){let o=s.toLowerCase();Object.keys(n.asConverters).some(a=>a.toLowerCase()===o)&&t.push({kind:"converterName",severity:"warning",detail:`Both "${n.name}" and "${e.name}" register an "as ${s}" converter \u2014 the later-registered handler silently wins.`,packages:[n.name,e.name]});}if(n.pluginFunctions&&e.pluginFunctions){let s=new Set(Object.keys(n.pluginFunctions));for(let o of Object.keys(e.pluginFunctions))s.has(o)&&t.push({kind:"pluginFunctionName",severity:"warning",detail:`Both "${n.name}" and "${e.name}" register a plugin function named "${o}" \u2014 the later registration wins in the engine's name-to-index map. Give each package's functions package-unique names.`,packages:[n.name,e.name]});}if(n.normalizerRules&&e.normalizerRules){let s=new Set(n.normalizerRules.map(o=>o.name));for(let o of e.normalizerRules)s.has(o.name)&&t.push({kind:"normalizerRuleName",severity:"warning",detail:`Both "${n.name}" and "${e.name}" register a normalizer rule named "${o.name}" \u2014 the normalizer unregisters rules by name, so removing either package would drop both rules. Give each package's rules a package-unique name.`,packages:[n.name,e.name]});}let r=n.lexerVocabulary,i=e.lexerVocabulary;if(r?.keywords&&i?.keywords)for(let[s,o]of Object.entries(i.keywords)){let a=r.keywords[s];a!==void 0&&a!==o&&t.push({kind:"lexerKeyword",severity:"error",detail:`Both "${n.name}" (-> "${a}") and "${e.name}" (-> "${o}") register the lexer keyword "${s}" for DIFFERENT token types \u2014 whichever package registers second wins, and the loser's grammar becomes silently unreachable for that word.`,packages:[n.name,e.name]});}if(r?.operators&&i?.operators)for(let[s,o]of Object.entries(i.operators)){let a=r.operators[s];a!==void 0&&a!==o&&t.push({kind:"lexerOperator",severity:"error",detail:`Both "${n.name}" (-> "${a}") and "${e.name}" (-> "${o}") register the lexer operator "${s}" for DIFFERENT token types.`,packages:[n.name,e.name]});}if(n.asyncResolvers&&e.asyncResolvers){let s=new Set(n.asyncResolvers.map(o=>o.namespace));for(let o of e.asyncResolvers)s.has(o.namespace)&&t.push({kind:"asyncResolverNamespace",severity:"error",detail:`Both "${n.name}" and "${e.name}" register an async resolver under the namespace "${o.namespace}" \u2014 ResolverRegistry is keyed by namespace, so one resolver's cache/preflight state will silently clobber the other's.`,packages:[n.name,e.name]});}if(n.tokenCategories&&e.tokenCategories)for(let[s,o]of Object.entries(e.tokenCategories)){let a=n.tokenCategories[s];a!==void 0&&a!==o&&t.push({kind:"tokenCategory",severity:"info",detail:`Both "${n.name}" (-> "${a}") and "${e.name}" (-> "${o}") declare a highlight category for token type "${s}" \u2014 cosmetic only, but the later registration wins.`,packages:[n.name,e.name]});}return t}function Nr(n,e){let t=[];for(let r of e)r===n||r.name===n.name||t.push(...Tt(r,n));return {compatible:!t.some(r=>r.severity==="error"),conflicts:t}}var he=class{constructor(){this.prefixOwners=new Map;this.infixOwners=new Map;this.phraseOwners=new Map;this.converterOwners=new Map;this.pluginFnOwners=new Map;this.ruleOwners=new Map;this.keywordOwners=new Map;this.operatorOwners=new Map;this.resolverOwners=new Map;this.categoryOwners=new Map;}check(e){let t=new Set,r=(s,o)=>{let a=s.get(o);a&&a!==e&&a.name!==e.name&&t.add(a);};if(e.prefixParselets)for(let s of Object.keys(e.prefixParselets))r(this.prefixOwners,s);if(e.infixParselets)for(let s of Object.keys(e.infixParselets))r(this.infixOwners,s);if(e.phrases)for(let s of Object.keys(e.phrases))r(this.phraseOwners,s);if(e.asConverters)for(let s of Object.keys(e.asConverters))r(this.converterOwners,s.toLowerCase());if(e.pluginFunctions)for(let s of Object.keys(e.pluginFunctions))r(this.pluginFnOwners,s);if(e.normalizerRules)for(let s of e.normalizerRules)r(this.ruleOwners,s.name);if(e.lexerVocabulary?.keywords)for(let s of Object.keys(e.lexerVocabulary.keywords))r(this.keywordOwners,s);if(e.lexerVocabulary?.operators)for(let s of Object.keys(e.lexerVocabulary.operators))r(this.operatorOwners,s);if(e.asyncResolvers)for(let s of e.asyncResolvers)r(this.resolverOwners,s.namespace);if(e.tokenCategories)for(let s of Object.keys(e.tokenCategories))r(this.categoryOwners,s);let i=[];for(let s of t)i.push(...Tt(s,e));return i}add(e){let t=(r,i)=>{r.has(i)||r.set(i,e);};if(e.prefixParselets)for(let r of Object.keys(e.prefixParselets))t(this.prefixOwners,r);if(e.infixParselets)for(let r of Object.keys(e.infixParselets))t(this.infixOwners,r);if(e.phrases)for(let r of Object.keys(e.phrases))t(this.phraseOwners,r);if(e.asConverters)for(let r of Object.keys(e.asConverters))t(this.converterOwners,r.toLowerCase());if(e.pluginFunctions)for(let r of Object.keys(e.pluginFunctions))t(this.pluginFnOwners,r);if(e.normalizerRules)for(let r of e.normalizerRules)t(this.ruleOwners,r.name);if(e.lexerVocabulary?.keywords)for(let r of Object.keys(e.lexerVocabulary.keywords))t(this.keywordOwners,r);if(e.lexerVocabulary?.operators)for(let r of Object.keys(e.lexerVocabulary.operators))t(this.operatorOwners,r);if(e.asyncResolvers)for(let r of e.asyncResolvers)t(this.resolverOwners,r.namespace);if(e.tokenCategories)for(let r of Object.keys(e.tokenCategories))t(this.categoryOwners,r);}rebuild(e){for(let t of [this.prefixOwners,this.infixOwners,this.phraseOwners,this.converterOwners,this.pluginFnOwners,this.ruleOwners,this.keywordOwners,this.operatorOwners,this.resolverOwners,this.categoryOwners])t.clear();for(let t of e)this.add(t);}};var Qt=/(\d+)\.(\d+)\.(\d+)/,Xt=/^\d+$/;function Nt(n){let e=Qt.exec(n.trim());return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function Jt(n,e){return n[0]-e[0]||n[1]-e[1]||n[2]-e[2]}function Ne(n){let e=n.split(".");if(e.length===0||e.length>3)return null;let t=[0,0,0];for(let r=0;r<e.length;r++){if(!Xt.test(e[r]))return null;t[r]=Number(e[r]);}return [t[0],t[1],t[2]]}function Yt([n,e,t]){let r=n>0?[n+1,0,0]:e>0?[0,e+1,0]:[0,0,t+1];return [{op:">=",v:[n,e,t]},{op:"<",v:r}]}function Zt([n,e,t]){return [{op:">=",v:[n,e,t]},{op:"<",v:[n,e+1,0]}]}function er(n){if(n===""||n==="*"||n==="x"||n==="X")return [];if(n[0]==="^"){let i=Ne(n.slice(1));return i&&Yt(i)}if(n[0]==="~"){let i=Ne(n.slice(1));return i&&Zt(i)}let e=/^(>=|<=|>|<|=)/.exec(n),t=e?e[1]:"=",r=Ne(e?n.slice(e[1].length):n);return r&&[{op:t,v:r}]}function Rt(n){let e=[];for(let t of n.split("||")){let r=t.trim().split(/\s+/).filter(s=>s!==""),i=[];for(let s of r){let o=er(s);if(o===null)return null;i.push(...o);}e.push(i);}return e}function At(n){return Rt(n.trim())!==null}function tr(n,e){let t=Jt(n,e.v);switch(e.op){case "<":return t<0;case "<=":return t<=0;case ">":return t>0;case ">=":return t>=0;case "=":return t===0}}function Pt(n,e){let t=Rt(e.trim());return t===null?false:t.some(r=>r.every(i=>tr(n,i)))}function rr(n,e=a$5){if(!n.engineVersion)return {compatible:true};if(!At(n.engineVersion))return {compatible:false,reason:"invalid-range",declaredRange:n.engineVersion,engineVersion:e};let t=Nt(e);return t===null||!Pt(t,n.engineVersion)?{compatible:false,reason:"range-not-satisfied",declaredRange:n.engineVersion,engineVersion:e}:{compatible:true}}function Lt(n,e=a$5){let t=rr(n,e);if(!t.compatible)throw t.reason==="invalid-range"?c$5.config({code:"PACKAGE_ENGINE_VERSION_INVALID_RANGE",message:`Package "${n.name}" declares an invalid engineVersion range: "${t.declaredRange}" is not a valid semver range.`,expected:'a valid semver range string (e.g. "^0.1.0", ">=0.2.0 <1.0.0")',found:`"${t.declaredRange}"`,suggestion:`This is a range-syntax typo in "${n.name}"'s own descriptor, not a version mismatch with the running engine \u2014 check for a stray character.`,context:{packageName:n.name,declaredRange:t.declaredRange}}):c$5.config({code:"PACKAGE_ENGINE_VERSION_MISMATCH",message:`Package "${n.name}" declares engineVersion "${t.declaredRange}", which is not satisfied by the running engine version "${t.engineVersion}".`,expected:`an engine version satisfying "${t.declaredRange}"`,found:`engine version "${t.engineVersion}"`,suggestion:`Update "${n.name}" to a version built against solve-engine ${t.engineVersion}, or pin solve-engine to a version satisfying "${t.declaredRange}".`,context:{packageName:n.name,declaredRange:t.declaredRange,engineVersion:t.engineVersion}})}var X="solve-engine/snapshot",K=1;function F(n){return Number.isFinite(n)?n:Number.isNaN(n)?"NaN":n>0?"Infinity":"-Infinity"}function _(n){if(typeof n=="number")return n;if(n==="NaN")return NaN;if(n==="Infinity")return 1/0;if(n==="-Infinity")return -1/0;throw c$5.validation({code:D.SNAPSHOT_MALFORMED,message:`Snapshot holds an unrecognised number sentinel: ${JSON.stringify(n)}`,expected:'a JSON number, or one of "NaN", "Infinity", "-Infinity"',found:JSON.stringify(n)})}var D={SNAPSHOT_VERSION_MISMATCH:"SNAPSHOT_VERSION_MISMATCH",SNAPSHOT_MALFORMED:"SNAPSHOT_MALFORMED",SNAPSHOT_UNSUPPORTED_VALUE:"SNAPSHOT_UNSUPPORTED_VALUE"};function Ot(n){return {coef:n.coef.toString(),scale:n.scale}}function It(n){return {coef:BigInt(n.coef),scale:n.scale}}function nr(n){return {n:n.n.toString(),d:n.d.toString()}}function ir(n){return {n:BigInt(n.n),d:BigInt(n.d)}}function Vt(n){return g$1[n]??String(n)}function Re(n,e){throw c$5.validation({code:D.SNAPSHOT_UNSUPPORTED_VALUE,message:`A ${Vt(n)} value (${e}) cannot be included in a snapshot yet.`,expected:"a concrete number, string, boolean, unit, range, matrix, bigint, or money value",found:`${Vt(n)} value`,suggestion:"Symbolic (algebra) values are deferred to a follow-up. Evaluate the document without the symbolic line, or re-derive it after restoring.",context:{valueType:n,location:e}})}function Ae(n,e){switch(n.type){case 0:{let t={t:0,v:F(n.value)};return n.exact!==void 0&&(t.exact=Ot(n.exact)),n.rational!==void 0&&(t.rational=nr(n.rational)),t}case 1:{let t=n.value;return typeof t=="bigint"?{t:1,v:t.toString(),big:true,base:n.unit}:{t:1,v:F(t),base:n.unit}}case 2:return {t:2,v:n.value.toString()};case 3:return {t:3,v:n.value};case 4:return {t:4,v:F(n.value)};case 5:return {t:5,v:F(n.value)};case 6:{let t={t:6,v:F(n.value),unit:n.unit??""};return n.exact!==void 0&&(t.exact=Ot(n.exact)),t}case 7:{let t=n.value;t.hasSymbolic&&Re(9,`${e} (symbolic matrix cell)`);let r=t.data.map(i=>sr(i,e));return {t:7,rows:t.rows,cols:t.cols,data:r}}case 8:{let t=n.value;return {t:8,min:F(t.min),max:F(t.max)}}case 10:return {t:10,v:n.value};case 13:return {t:13,code:n.value,message:n.unit??""};default:return Re(n.type,e)}}function sr(n,e){return typeof n=="boolean"?n:typeof n=="number"?F(n):Re(9,`${e} (symbolic matrix cell)`)}function Pe(n){switch(n.t){case 0:{let e=new m(0,_(n.v));return n.exact!==void 0&&(e.exact=It(n.exact)),n.rational!==void 0&&(e.rational=ir(n.rational)),e}case 1:{let e=n.big?BigInt(n.v):_(n.v);return new m(1,e,n.base)}case 2:return new m(2,BigInt(n.v));case 3:return new m(3,n.v);case 4:return new m(4,_(n.v));case 5:return new m(5,_(n.v));case 6:{let e=new m(6,_(n.v),n.unit);return n.exact!==void 0&&(e.exact=It(n.exact)),e}case 7:{let e=n.data.map(r=>typeof r=="boolean"?r:_(r)),t={rows:n.rows,cols:n.cols,data:e,hasSymbolic:false};return new m(7,t)}case 8:return new m(8,{min:_(n.min),max:_(n.max)});case 10:return new m(10,n.v);case 13:return new m(13,n.code,n.message);default:throw c$5.validation({code:D.SNAPSHOT_MALFORMED,message:`Snapshot holds a value with an unknown type tag: ${JSON.stringify(n.t)}`,expected:"a known SerializedValue type tag",found:JSON.stringify(n.t)})}}function oe(n){let e={opcodes:Array.from(n.opcodes),numbers:Array.from(n.numbers,F),strings:n.strings.slice(),hasAsync:n.hasAsync};return n.constants&&(e.constants=Array.from(n.constants.entries())),n.userFunctionBodies&&(e.userFunctionBodies=n.userFunctionBodies.map(Le)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:oe(t.program)}))),e}function ae(n){let e={opcodes:Uint8Array.from(n.opcodes),numbers:Float64Array.from(n.numbers,_),strings:n.strings.slice(),hasAsync:n.hasAsync};return n.constants&&(e.constants=new Map(n.constants)),n.userFunctionBodies&&(e.userFunctionBodies=n.userFunctionBodies.map(Oe)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:ae(t.program)}))),e}function Le(n){return {name:n.name,params:n.params.slice(),program:oe(n.program)}}function Oe(n){return {name:n.name,params:n.params.slice(),program:ae(n.program)}}function Mt(n){if(typeof n!="object"||n===null)throw c$5.validation({code:D.SNAPSHOT_VERSION_MISMATCH,message:"fromJSON was given something that is not a snapshot object.",expected:`an object produced by ExpressionEngine.toJSON() with format "${X}"`,found:n===null?"null":typeof n});let e=n;if(e.format!==X)throw c$5.validation({code:D.SNAPSHOT_VERSION_MISMATCH,message:`This object is not a solve-engine snapshot (its "format" is ${JSON.stringify(e.format)}).`,expected:`format "${X}"`,found:JSON.stringify(e.format)});if(e.version!==K)throw c$5.validation({code:D.SNAPSHOT_VERSION_MISMATCH,message:`This snapshot was written for format version ${e.version}, but this engine restores version ${K}.`,expected:`snapshot version ${K}`,found:`version ${e.version}`,suggestion:"Regenerate the snapshot with a matching engine version, or re-evaluate the document from source.",context:{snapshotVersion:e.version,readerVersion:K,engineVersion:e.engineVersion}})}var j=class{constructor(e,t,r,i){this.result=e;this.bytecode=t;this.readVariables=r;this.writeVariable=i;}},de=class n{constructor(){this.byLine=new Map;this.count=0;}static exprKey(e){return e??""}static displayKey(e,t){return t===""?`${e}`:`${e}:${t}`}get(e,t){return this.byLine.get(e)?.get(n.exprKey(t))}getEntryForLine(e){let t=this.byLine.get(e);if(t)for(let r of t.values())return r}set(e,t,r){let i=this.byLine.get(e);i||(i=new Map,this.byLine.set(e,i));let s=n.exprKey(r);i.size>0&&!i.has(s)&&(this.count-=i.size,i.clear()),i.has(s)||this.count++,i.set(s,t);}has(e,t){return this.byLine.get(e)?.has(n.exprKey(t))??false}remove(e,t){let r=this.byLine.get(e);r&&r.delete(n.exprKey(t))&&(this.count--,r.size===0&&this.byLine.delete(e));}removeAllForLine(e){let t=this.byLine.get(e);t&&(this.count-=t.size,this.byLine.delete(e));}clearLine(e){this.removeAllForLine(e);}get size(){return this.count}clear(){this.byLine.clear(),this.count=0;}forEach(e){for(let[t,r]of this.byLine)for(let[i,s]of r)e(n.displayKey(t,i),s);}snapshotEntries(){let e=[];for(let[t,r]of this.byLine)for(let[i,s]of r)e.push({line:t,expression:i,entry:s});return e}keys(){let e=[];for(let[t,r]of this.byLine)for(let i of r.keys())e.push(n.displayKey(t,i));return e}};function Ie(n){let e=new Date(n),t=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return `${e.getFullYear()}-${t}-${r}`}function or(n){if(n instanceof Date)return Ie(n.getTime());if(typeof n=="number")return Number.isFinite(n)?Ie(n):null;let e=/^(\d{4})-(\d{2})-(\d{2})/.exec(n.trim());return e?`${e[1]}-${e[2]}-${e[3]}`:null}function Bt(n){if(n===void 0)return;if(typeof n=="function")return t=>n(new Date(t));let e=new Set;for(let t of n){let r=or(t);r!==null&&e.add(r);}return t=>e.has(Ie(t))}function ar(n,e){if(!n||n.type!==e.type||n.value!==e.value)return true;let t=n.unit,r=e.unit;return t!==r}var me=class n{constructor(e,t){this.dag=e;this.enqueue=t;this.entries=new Map;}get size(){return this.entries.size}static idOf(e,t){return JSON.stringify([e,t])}register(e){if(!(e.intervalMs>0))return;let t=n.idOf(e.packageId,e.queryKey);if(this.entries.has(t))return;let r=setInterval(()=>{this.tick(t);},e.intervalMs);r.unref?.(),this.entries.set(t,{...e,timer:r,lastValue:null,inFlight:false});}async tick(e){let t=this.entries.get(e);if(t&&!t.inFlight){if(this.isDead(t)){this.stop(e);return}t.inFlight=true;try{let r=await t.refetch(),i=this.entries.get(e);if(!i)return;r&&ar(i.lastValue,r)&&(i.lastValue=r,this.enqueue(i.packageId,i.queryKey));}catch{}finally{let r=this.entries.get(e);r&&(r.inFlight=false);}}}isDead(e){return this.dag.getAffectedLinesByDataSource(e.packageId,[e.queryKey]).size===0}reconcile(){for(let[e,t]of this.entries)this.isDead(t)&&this.stop(e);}stop(e){let t=this.entries.get(e);t&&(clearInterval(t.timer),this.entries.delete(e));}clearAll(){for(let e of this.entries.values())clearInterval(e.timer);this.entries.clear();}};var U=class{static enable(){this.enabled=true;}static disable(){this.enabled=false;}static isEnabled(){return this.enabled}static track(e,t,r){if(!this.enabled)return {result:t(),alloc:null};let i=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,s=typeof process<"u"&&process.hrtime?process.hrtime():performance.now(),o=t(),a=typeof process<"u"&&process.hrtime?process.hrtime(s):void 0,l=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,c=a?a[0]*1e9+a[1]:(performance.now()-s)*1e6,u=i&&l?l.heapUsed-i.heapUsed:0,p={stage:e,allocCount:0,allocBytes:u,objectCounts:{},wallTimeNs:c,...r};return {result:o,alloc:p}}static generateReport(e,t){let r=[];r.push(t?`## ${t}`:"## Pipeline Allocation Report"),r.push(""),r.push(`**Runs:** ${e.length} | **Generated:** ${new Date().toISOString()}`),r.push("");let i=this.aggregate(e);if(i.length===0)return r.push("_No telemetry data._"),r.join(`
2
- `);r.push("### Per-Stage Breakdown"),r.push(""),r.push("| Stage | Count | Mean Wall (\xB5s) | Mean Alloc (bytes) | Min (\xB5s) | Max (\xB5s) | p50 (\xB5s) | p95 (\xB5s) | p99 (\xB5s) |"),r.push("|-------|:-----:|:--------------:|:------------------:|:--------:|:--------:|:--------:|:--------:|:--------:|");for(let l of i)r.push(`| ${l.stage} | ${l.count} | ${(l.meanWallTimeNs/1e3).toFixed(2)} | ${l.meanAllocBytes.toFixed(0)} | ${(l.minWallTimeNs/1e3).toFixed(2)} | ${(l.maxWallTimeNs/1e3).toFixed(2)} | ${(l.p50WallTimeNs/1e3).toFixed(2)} | ${(l.p95WallTimeNs/1e3).toFixed(2)} | ${(l.p99WallTimeNs/1e3).toFixed(2)} |`);let s=e.reduce((l,c)=>l+c.totalAllocBytes,0),o=e.reduce((l,c)=>l+c.totalWallTimeNs,0),a=e.filter(l=>l.fastPath).length;return r.push(""),r.push("### Totals"),r.push(""),r.push(`- **Total wall time:** ${(o/1e6).toFixed(2)} ms (${e.length} runs)`),r.push(`- **Total heap allocated:** ${s.toLocaleString()} bytes`),r.push(`- **Fast-path runs:** ${a}/${e.length} (${(a/e.length*100).toFixed(0)}%)`),r.push(`- **Mean per-run:** ${(o/e.length/1e3).toFixed(2)} \xB5s, ${(s/e.length).toFixed(0)} bytes`),r.join(`
3
- `)}static aggregate(e){let t=new Map;for(let i of e)for(let s of i.stages)t.has(s.stage)||t.set(s.stage,[]),t.get(s.stage).push(s);let r=[];for(let[i,s]of t){let o=s.map(c=>c.wallTimeNs).sort((c,u)=>c-u),a=s.map(c=>c.allocBytes),l=s.length;r.push({stage:i,count:l,meanAllocBytes:a.reduce((c,u)=>c+u,0)/l,meanWallTimeNs:o.reduce((c,u)=>c+u,0)/l,minWallTimeNs:o[0],maxWallTimeNs:o[o.length-1],p50WallTimeNs:Ve(o,50),p95WallTimeNs:Ve(o,95),p99WallTimeNs:Ve(o,99)});}return r.sort((i,s)=>i.stage.localeCompare(s.stage)),r}static createTelemetry(e,t,r=false){let i=t.reduce((o,a)=>o+a.allocBytes,0),s=t.reduce((o,a)=>o+a.wallTimeNs,0);return {expression:e,stages:t,totalAllocBytes:i,totalWallTimeNs:s,fastPath:r}}};U.enabled=false;function Ve(n,e){if(n.length===0)return 0;if(n.length===1)return n[0];let t=e/100*(n.length-1),r=Math.floor(t),i=Math.ceil(t);if(r===i)return n[r];let s=t-r;return n[r]*(1-s)+n[i]*s}function Me(n$1,e){if(n$1.length>e.maxExpressionLength){let t=c$5.validation("EXPRESSION_TOO_LONG",`Expression exceeds max length of ${e.maxExpressionLength} characters (got ${n$1.length})`,{expressionLength:n$1.length,maxLength:e.maxExpressionLength});return {passed:false,error:{value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:t.message,engineError:t}}}return {passed:true}}function Be(n,e){let t=0,r=0,i=0;for(let o of n)o.type==="FUNC"&&t++,(o.value==="("||o.type==="LPAREN")&&(r++,i=Math.max(i,r)),(o.value===")"||o.type==="RPAREN")&&r--;let s=n.length+t*5+i*10;if(s>e.maxComplexity){let o=c$5.validation("EXPRESSION_TOO_COMPLEX",`Expression complexity score ${s} exceeds maximum of ${e.maxComplexity}`,{complexity:s,maxComplexity:e.maxComplexity});return {passed:false,complexityScore:s,errorMessage:o.message,engineError:o}}return {passed:true,complexityScore:s}}function le(n){return n.type==="IDENT"||n.type==="UNIT"}function lr(n){return n.type==="NUMBER"||n.type==="TO"||n.type==="IN"||n.type==="RPAREN"}function Dt(n,e){let t=0;for(let r=e;r<n.length;r++)if(n[r].type==="LPAREN")t++;else if(n[r].type==="RPAREN"&&(t--,t===0))return r;return null}function cr(n){let e=new Set;for(let t=0;t<n.length;t++){if(!le(n[t])||t>0&&n[t-1].type==="COLON"||n[t+1]?.type!=="LPAREN")continue;let r=Dt(n,t+1);if(r!==null&&n[r+1]?.type==="EQUALS")for(let i=t+2;i<r;i++)le(n[i])&&e.add(n[i].value);}return e}function ye(n){let e=[],t=[],r=cr(n);for(let i=0;i<n.length;i++){let s=n[i];if(s.type==="GLOBAL"){if(i+2<n.length&&n[i+1].type==="COLON"&&le(n[i+2])){let o=K$1(n[i+2].value);e.push(o),i+3<n.length&&n[i+3].type==="EQUALS"&&t.push(o);}continue}if(s.type==="COLON"){if(i>0&&n[i-1].type==="GLOBAL")continue;if(i+1<n.length&&le(n[i+1])){let o=n[i+1].value;e.push(o),i+2<n.length&&n[i+2].type==="EQUALS"&&t.push(o);}}if(le(s)){if(i>0&&n[i-1].type==="COLON"||s.type==="UNIT"&&i>0&&lr(n[i-1])||r.has(s.value))continue;if(n[i+1]?.type==="LPAREN"){let a=Dt(n,i+1);if(a!==null&&n[a+1]?.type==="EQUALS"){e.push(s.value),t.push(s.value);continue}}e.push(s.value);let o=n[i+1]?.type;(o==="EQUALS"||o==="PLUS_EQUALS"||o==="MINUS_EQUALS")&&t.push(s.value);}}return {reads:e,writes:t}}function Gr(n){return c$9.classifyLine(n).skip}function Qr(n,e){return c$9.findInlineSolves(n).map(r=>({start:r.start,end:r.end,expression:r.expression,lineNumber:e,columnNumber:r.columnNumber}))}function Ut(n){let e=n[n.length-1],t=e.length>1&&e.endsWith("s")?e.slice(0,-1):e;return [...n.slice(0,-1),t].join(" ")}var ve=class{constructor(){this.byKey=new Map;this.longestName=0;}get isEmpty(){return this.byKey.size===0}get maxWordCount(){return this.longestName}define(e,t,r){let i=Ut(e);this.byKey.set(i,{displayName:e.join(" "),ratioText:t,baseUnit:r}),e.length>this.longestName&&(this.longestName=e.length);}match(e){let t=Math.min(e.length,this.longestName);for(let r=t;r>=1;r--){let i=this.byKey.get(Ut(e.slice(0,r)));if(i!==void 0)return {definition:i,wordCount:r}}return null}clear(){this.byKey.clear(),this.longestName=0;}};function _t(n,e=82){return {name:"uom:user-unit",priority:e,shape:[{types:["NUMBER","RPAREN"]},{types:["IDENT"]}],match(t,r){if(n.isEmpty)return null;let i=t[r];if(i.type!=="NUMBER"&&i.type!=="RPAREN")return null;let s=[],o=n.maxWordCount;for(let g=r+1;g<t.length&&s.length<o&&t[g].type==="IDENT";g++)s.push(t[g].value);if(s.length===0)return null;let a=n.match(s);if(a===null||t[r+1+a.wordCount]?.type==="EQUALS")return null;let{ratioText:c,baseUnit:u}=a.definition,p=new a$8("STAR",c$7("STAR"),"*","*",i.offset,0,i.line,i.col),d=new a$8("NUMBER",c$7("NUMBER"),c,c,i.offset,0,i.line,i.col),m=new a$8("UNIT",c$7("UNIT"),u,u,i.offset,0,i.line,i.col);return {consumed:1+a.wordCount,replacement:[i,p,d,m],ruleName:"uom:user-unit"}}}}var Ft="engine:call-fusion";function zt(n,e=80){return {name:Ft,priority:e,startTokenTypes:["IDENT"],match(t,r){let i=t[r];if(!i||i.type!=="IDENT"||t[r+1]?.type!=="LPAREN"||t[r-1]?.type==="COLON")return null;let s=(i.value??"").toLowerCase(),o=n.get(s);return o===void 0?null:{consumed:1,replacement:[new a$8(o,c$7(o),s,i.value,i.offset,0,i.line,i.col)],ruleName:Ft}}}}var ur=30,pr=40,gr=50,fr=24;function hr(n){switch(n){case a.PLUS:case a.MINUS:return ur;case a.STAR:case a.SLASH:case a.MOD:case a.OF:return pr;case a.CARET:return gr;case a.PCT_ON:case a.PCT_OFF:return fr;default:return 0}}function dr(n){switch(n){case a.PLUS:return "plus";case a.MINUS:return "minus";case a.STAR:return "times";case a.SLASH:return "divided by";case a.MOD:return "mod";case a.CARET:return "to the power of";case a.OF:return "of";case a.PCT_ON:return "plus";case a.PCT_OFF:return "less";default:return n.toLowerCase()}}function $t(n){return n.sourceEnd??n.offset+n.value.length}var mr=new Set([a.NUMBER,a.BIGINT,a.IDENT,a.UNIT,a.PERCENT,a.PI,a.E,a.TRUE,a.FALSE,a.DOLLAR,a.POUND,a.EURO,a.YEN,a.RUBLE,a.WON,a.CURRENCY_SYMBOL]);function yr(n){return !mr.has(n)}var De=class{constructor(e){this.tokens=e;this.pos=0;}peek(){return this.tokens[this.pos]}next(){return this.tokens[this.pos++]}parseAll(){let e=this.parseExpression(0);if(this.pos!==this.tokens.length)throw new Error("explain: unconsumed tokens");return e}parseExpression(e){let t=this.parseOperand();for(;;){let r=this.peek();if(!r)break;let i=hr(r.type);if(i===0||i<=e)break;this.next();let s=r.type===a.CARET?i-1:i,o=this.parseExpression(s);t={kind:"binary",op:r.type,left:t,right:o,start:t.start,end:o.end};}return t}parseOperand(){let e=this.peek();if(!e)throw new Error("explain: expected an operand");if(e.type===a.LPAREN)return this.parseGroup();let t=e.offset,r=false;for(;this.peek()&&(this.peek().type===a.PLUS||this.peek().type===a.MINUS);)this.next(),r=true;if(r&&this.peek()&&this.peek().type===a.LPAREN){let s=this.parseGroup();return {kind:"wrap",child:s,start:t,end:s.end}}let i=-1;for(;this.peek()&&!yr(this.peek().type);)i=$t(this.next());if(i===-1)throw new Error("explain: expected an operand");return {kind:"leaf",start:t,end:i}}parseGroup(){let e=this.next(),t=this.parseExpression(0),r=this.peek();if(!r||r.type!==a.RPAREN)throw new Error("explain: unbalanced parentheses");return this.next(),{kind:"wrap",child:t,start:e.offset,end:$t(r)}}},Ue=class{constructor(e,t,r){this.source=e;this.evaluate=t;this.steps=[];this.cache=new Map;this.resultPrefix=a$9(r).display.resultPrefix;}build(e){return this.emit(e),{steps:this.steps,result:this.valueOf(e)}}emit(e){if(e.kind!=="leaf"){if(e.kind==="wrap"){this.emit(e.child);return}this.emit(e.left),this.emit(e.right),this.steps.push({description:this.describe(e),value:this.valueOf(e)});}}describe(e){let t=dr(e.op);return e.op===a.PCT_ON||e.op===a.PCT_OFF?`${this.operand(e.right)} ${t} ${this.operand(e.left)}`:`${this.operand(e.left)} ${t} ${this.operand(e.right)}`}operand(e){return e.kind==="leaf"?this.source.slice(e.start,e.end).trim():this.render(this.valueOf(e))}valueOf(e){let t=this.cache.get(e);if(t)return t;let r=this.evaluate(this.source.slice(e.start,e.end));return this.cache.set(e,r),r}render(e){let t=c$8(e,a$a);return t.startsWith(this.resultPrefix)?t.slice(this.resultPrefix.length):t}};function _e(n){let{expression:e,tokens:t,evaluate:r,locale:i}=n,s=()=>({expression:e,steps:[],result:r(e)}),o;try{o=new De(t).parseAll();}catch{return s()}try{let{steps:a,result:l}=new Ue(e,r,i).build(o);return {expression:e,steps:a,result:l}}catch{return s()}}var H=class H{constructor(e={}){this.dag=new a$1;this.lineCache=new de;this.accumulatorNames=new Set;this.scopeManager=new b;this.resolverRegistry=new a$2;this.packageContributions=new Map;this.registeredPackages=new Map;this.callFusions=new Map;this.compatIndex=new he;this.documentModel=null;this.goalSeekDepth=0;this.batchScanResults=null;this.batchParsedLines=null;this.packageCompletionItems=new Map;this.keystrokeSignal=null;this.backgroundRefreshSignal=new AbortController().signal;this.userUnits=new ve;this.bytecodeCache=new Map;this.pluginFunctionIndexByName=new Map;this.builderPool=[new d$1(this.pluginFunctionIndexByName),new d$1(this.pluginFunctionIndexByName),new d$1(this.pluginFunctionIndexByName),new d$1(this.pluginFunctionIndexByName)];this.builderPoolIndex=0;this.lastTelemetry=null;let{locale:t="en",diagnostics:r=false,config:i,packages:s}=e;this.localeCode=t,this.config=c$1(b$1,i??{}),this.lexer=new b$2(t,d$2(t)),this.registry=new b$3,this.context=x(),r?(this.diagnosticPipeline=new a$3,this.timelineCollector=new b$4,this.diagnosticPipeline.register(this.timelineCollector)):this.diagnosticPipeline=new a$3,this.normalizer=new c$2;for(let[a,l]of Object.entries(g))this.normalizer.addPhrase(a,l);this.normalizer.register(d$3(50,a=>this.normalizer.canStartPhrase(a))),this.normalizer.register(_t(this.userUnits)),this.normalizer.register(zt(this.callFusions));let o=s??[];for(let a of o)try{this.registerPackage(a);}catch(l){let c=d$4(l);console.error(`[ExpressionEngine] Failed to register package "${a.name}" \u2014 skipping it and continuing construction with the remaining packages: ${c.format()}`);}this.registry.hasPrefix("DATETIME_LITERAL")&&this.normalizer.register(h(()=>this.config.date.inputOrder)),this.parser=new a$4(this.registry,this.config.validation.maxNestingDepth,t,this.pluginFunctionIndexByName),this.vm=c(this.context.opRegistry,this.config.vm.maxStackDepth,this.config.vm.maxInstructions,void 0,this.config.vm.maxCollectionSize,this.config.vm.maxAllocatedElements,this.config.vm.maxFunctionCalls,this.config.date.maxOffsetYears,this.config.date.minOffsetYears,this.context,Bt(this.config.date.holidays)),this.queryClient=c$3(),this.batcher=new Ee(this.dag,this.lineCache,this.vm),this.backgroundRefresh=this.config.backgroundRefresh.enabled?new me(this.dag,(a,l)=>this.batcher.add({queryKey:l,packageId:a,signal:this.backgroundRefreshSignal,isError:false})):null,e.warmup===true&&this.warmUp();}setDocumentModel(e){this.documentModel=e;}getDocumentModel(){return this.documentModel}warmUp(){let e=new d$1(this.pluginFunctionIndexByName);for(let t of H.WARMUP_EXPRESSIONS)try{this.lexer.resetExpression(t);let r=[];for(let o of this.lexer)o.type!=="COMMENT"&&r.push(o);let i=this.normalizer.normalize(r);e.reset(),this.parser.load(i),this.parser.parseExpression(0,e);let s=e.build();this.vm.reset(),d(s,this.vm);}catch{}this.vm.reset();}makeLineContext(e){let t=this.documentModel,r=t?null:this.batchScanResults,i=t?null:this.batchParsedLines;return {lineIndex:e,getLineResult:t?s=>t.getLineAt(s)?.result??void 0:i?s=>i[s-1]?.result??void 0:void 0,isLineBoundary:t?s=>{let o=t.getLineAt(s);return o?o.isEmpty||/^\s*#/.test(o.text):true}:r?s=>{let o=r[s-1];return o?o.classification.skip||/^\s*#/.test(o.text):true}:void 0,getLineReads:t?s=>{let o=t.getLineAt(s);if(!(!o||o.bytecodes.length===0))return o.reads}:void 0,evaluateLineWithBinding:t?(s,o,a,l)=>this.evaluateLineWithBinding(s,o,a,l):void 0,goalSeekMaxIterations:this.config.vm.maxGoalSeekIterations,getLineText:t?s=>t.getLineAt(s)?.text:r?s=>r[s-1]?.text:void 0}}evaluateLineWithBinding(e,t,r,i){let s=this.documentModel;if(!s)return P("GOAL_SEEK_NO_DOCUMENT","Goal seek needs a document to solve against, which the single-expression entry point does not have.");if(this.goalSeekDepth>=H.GOAL_SEEK_MAX_NESTING_DEPTH)return P("GOAL_SEEK_NESTED","A goal-seek line cannot target another goal-seek line, since each already re-runs its target many times.");let o=s.getLineAt(e);if(!o||o.bytecodes.length===0)return P("GOAL_SEEK_LINE_NOT_READY",`Line ${e} has no evaluated expression to solve (forward reference, out of range, or not an expression).`);if(o.isVariableDef)return P("GOAL_SEEK_TARGET_IS_DEFINITION",`Line ${e} defines a variable, so re-running it would overwrite that variable. Target the line that uses ${t}, not the one that sets a value.`);let a=o.bytecodes[0];this.goalSeekDepth++;try{let l=new Map([[t,r]]),c=this.vm.getStack().length;this.vm.pushCallFrame(l);try{let u=d(a,this.vm,void 0,void 0,this.makeLineContext(e),i);return u.type==="pending"?P("GOAL_SEEK_ASYNC_UNSUPPORTED",`Line ${e} depends on an async value (weather, stocks, currency, ...), which goal seek cannot re-run.`):u.type==="error"?P(u.error.code??"GOAL_SEEK_TARGET_ERROR",u.error.message):u.value}finally{for(this.vm.popCallFrame();this.vm.getStack().length>c;)this.vm.pop();}}catch(l){return P("GOAL_SEEK_TARGET_ERROR",d$4(l).message)}finally{this.goalSeekDepth--;}}cacheBytecode(e,t){let r=this.config.performance.defaultCacheSize;if(this.bytecodeCache.size>=r){let i=this.bytecodeCache.keys().next().value;i!==void 0&&this.bytecodeCache.delete(i);}this.bytecodeCache.set(e,t);}getEventStream(){return this.batcher.getEventStream()}getBatcher(){return this.batcher}registerPackage(e){Lt(e),this.packageContributions.has(e.name)&&(console.warn(`[ExpressionEngine] Package "${e.name}" is already registered. Unregistering the previous registration before re-registering.`),this.unregisterPackage(e.name));let t=this.compatIndex.check(e);for(let i of t)(i.severity==="error"?console.error:console.warn)(`[ExpressionEngine] Package compatibility ${i.severity} (${i.kind}): ${i.detail}`);let r={pluginFunctionIndices:[],pluginFunctionNames:[],resolverNamespaces:[],tokenCategories:[],lexerVocabulary:e.lexerVocabulary,asConverterNames:[],normalizerRuleNames:[],callFusionNames:[]};if(e.lexerVocabulary&&this.lexer.registerVocabulary(e.lexerVocabulary),e.prefixParselets)for(let[i,s]of Object.entries(e.prefixParselets))this.registry.registerPrefix(i,s);if(e.infixParselets)for(let[i,s]of Object.entries(e.infixParselets))this.registry.registerInfix(i,s);if(e.pluginFunctions)for(let[i,s]of Object.entries(e.pluginFunctions)){let o=F$1(`${e.name}:${i}`);this.context.pluginFunctions[o]=s,this.context.pluginFunctionOwners[o]=e.name,this.pluginFunctionIndexByName.set(i,o),r.pluginFunctionIndices.push(o),r.pluginFunctionNames.push(i);}if(e.asyncResolvers)for(let i of e.asyncResolvers)this.resolverRegistry.register(i),r.resolverNamespaces.push(i.namespace);if(e.phrases)for(let[i,s]of Object.entries(e.phrases))this.normalizer.addPhrase(i,s);if(e.normalizerRules)for(let i of e.normalizerRules)this.normalizer.register(i),r.normalizerRuleNames.push(i.name);if(e.callFusions)for(let[i,s]of Object.entries(e.callFusions)){let o=i.toLowerCase();this.callFusions.set(o,s),r.callFusionNames.push(o);}if(e.tokenCategories)for(let[i,s]of Object.entries(e.tokenCategories))b$5(i,s),r.tokenCategories.push(i);if(e.completionItems&&this.packageCompletionItems.set(e.name,e.completionItems),e.asConverters)for(let[i,s]of Object.entries(e.asConverters))H$1(i,s),r.asConverterNames.push(i);this.packageContributions.set(e.name,r),this.registeredPackages.set(e.name,e),this.compatIndex.add(e);}unregisterPackage(e){let t=this.packageContributions.get(e);if(!t)return false;for(let r of t.pluginFunctionIndices)delete this.context.pluginFunctions[r],delete this.context.pluginFunctionOwners[r];for(let r of t.pluginFunctionNames)this.pluginFunctionIndexByName.delete(r);for(let r of t.resolverNamespaces)this.resolverRegistry.unregister(r);for(let r of t.tokenCategories)c$4(r);t.lexerVocabulary&&this.lexer.unregisterVocabulary(t.lexerVocabulary);for(let r of t.asConverterNames)I(r);for(let r of t.normalizerRuleNames)this.normalizer.unregister(r);for(let r of t.callFusionNames)this.callFusions.delete(r);return this.packageCompletionItems.delete(e),this.packageContributions.delete(e),this.registeredPackages.delete(e),this.compatIndex.rebuild(this.registeredPackages.values()),this.bytecodeCache.clear(),true}getConfig(){return {...this.config}}getDiagnosticPipeline(){return this.diagnosticPipeline}storeLineResult(e,t,r,i,s,o){this.lineCache.set(e,new j(t,r,i,s.length>0?s[0]:null),o);}executeAndStore(e,t,r,i,s,o,a,l){let c=this.vm.getStack().length,u=new AbortController,p=()=>u.abort();this.keystrokeSignal?.addEventListener("abort",p,{once:true}),a$6.localControllerCreated("executeAndStore"),this.keystrokeSignal&&a$6.signalLinked("executeAndStore"),this.vm.activeSignal=u.signal,this.vm.abortCurrent=()=>{a$6.signalUnlinked("executeAndStore"),this.keystrokeSignal?.removeEventListener("abort",p),u.abort();},a$7(this.queryClient);let d$1=d(e,this.vm,a,l,this.makeLineContext(t));for(;this.vm.getStack().length>c;)this.vm.pop();if(d$1.type==="pending"){this.resolveAsync(d$1),this.dag.registerLineDataSourceDependency(t,d$1.packageId||o,[d$1.queryKey]);let m=O(d$1.queryKey);return this.storeLineResult(t,m,e,i,s,r),m}if(d$1.type==="error")throw this.keystrokeSignal?.removeEventListener("abort",p),d$1.error;return this.keystrokeSignal?.removeEventListener("abort",p),this.dag.registerLine(t,i,s),this.storeLineResult(t,d$1.value,e,i,s,r),d$1.value}executeRaw(e,t=-1){let r=this.vm.getStack().length,i=new AbortController,s=()=>i.abort();this.keystrokeSignal?.addEventListener("abort",s,{once:true}),a$6.localControllerCreated("executeRaw"),this.keystrokeSignal&&a$6.signalLinked("executeRaw"),this.vm.activeSignal=i.signal,this.vm.abortCurrent=()=>{a$6.signalUnlinked("executeRaw"),this.keystrokeSignal?.removeEventListener("abort",s),i.abort();},a$7(this.queryClient);let o=d(e,this.vm,void 0,void 0,this.makeLineContext(t));for(;this.vm.getStack().length>r;)this.vm.pop();return o.type!=="pending"&&this.keystrokeSignal?.removeEventListener("abort",s),o}async resolveAsync(e){let{queryKey:t,resolver:r,packageId:i,signal:s}=e,o=i||"_engine";try{if(await r,s.aborted){a$6.staleDataDiscarded(t,"signal aborted after resolve");return}this.batcher.add({queryKey:t,packageId:o,signal:s,isError:!1});}catch(a){if(s.aborted){a$6.staleDataDiscarded(t,"signal aborted after error");return}let l=a instanceof Error?a:new Error(String(a));this.batcher.add({queryKey:t,packageId:o,signal:s,isError:true,error:l});}}registerBackgroundRefresh(e){this.backgroundRefresh&&(e.refetchIntervalMs===void 0||!e.refetch||this.backgroundRefresh.register({packageId:e.packageId||"_engine",queryKey:e.queryKey,intervalMs:e.refetchIntervalMs,refetch:e.refetch}));}getBackgroundRefreshCount(){return this.backgroundRefresh?.size??0}parseDocument(e,t={inputType:"markdown"}){let r=this.config.performance.maxDocumentLines;if(b$6(e,r)>r)throw c$5.execution("DOCUMENT_TOO_LARGE",`This document has more than ${r.toLocaleString("en-US")} lines, which is the most the engine will process in one pass`,{maxLines:r});this.userUnits.isEmpty||this.bytecodeCache.clear(),this.userUnits.clear(),this.resetAccumulators();let i=this.lexer.scanDocument(e),s=this.processScanResults(i),o={lines:s,totalLines:s.length,errors:[]};for(let l of s){l.error&&o.errors.push(`Line ${l.lineNumber}: ${l.error}`);for(let c of l.inlineSolves)c.error&&o.errors.push(`Line ${l.lineNumber}: ${c.error}`);}if(t.includeDiagnostics??false){let l=this.diagnosticPipeline.collectReports();l.length>0&&(o.diagnostics=l[0].toJSON());}return o}evaluateLines(e){this.userUnits.isEmpty||this.bytecodeCache.clear(),this.userUnits.clear(),this.resetAccumulators();let t=e.join(`
4
- `),r=this.lexer.scanDocument(t);return this.processScanResults(r)}processScanResults(e){let t=[],r=this.batchScanResults,i=this.batchParsedLines;this.batchScanResults=e,this.batchParsedLines=t;try{for(let s of e){let o=s.text,a=s.lineNumber,l=s.startOffset,c=s.endOffset,u=s.classification.skip,p=s.inlineSolves.map(g=>({start:g.start,end:g.end,expression:g.expression,lineNumber:a,columnNumber:g.columnNumber})),d=p.length>0,m={lineNumber:a,text:o,startPosition:l,endPosition:c,isEmpty:u,hasInlineSolves:d,inlineSolves:p,expression:null,result:null,error:null};if(!u){let g=o.trim().startsWith(":");if(d&&!g)for(let A of p)try{A.result=this.evaluateLine(a,A.expression);}catch(O){let I=O instanceof Error?O.message:String(O);A.error=I;}else {let A=s.classification.contentOffset,I=(A===void 0?o:o.slice(A-l)).trim();if(I)try{let E=this.evaluateLineWithPreTokenized(a,I,s.tokens);m.expression=I,m.result=E[0];}catch(E){let Z=E instanceof Error?E.message:String(E);m.error=Z;}}}t.push(m);}}finally{this.batchScanResults=r,this.batchParsedLines=i;}return t}evaluateLineWithPreTokenized(e,t,r){let i=[],s=false;for(let o of r)(o.type==="LPAREN"||o.type==="RPAREN")&&(s=true),i.push(o);return [this.evaluateWithTokens(e,t,i,s)]}parseExpression(e,t,r,i=true){this.parser.setBuilder(e),this.parser.load(t,this.config.validation.autoBalanceParens?r:false),this.parser.parseExpression(0);let s=this.parser.peek();if(s){if(s.type==="EQUALS"&&!this.parser.peekAt(1))return;for(let o=i?t.length-1:0;o>=1;o--){if(t[o].type!=="COLON"||o+1>=t.length)continue;let a=true;for(let l=0;l<o;l++){let c=t[l].type;if(c!=="NUMBER"&&c!=="COLON"){a=false;break}}if(a){let l=t.slice(0,o+2).map(c=>c.value).join("");throw c$5.parsing("INVALID_TIME_LITERAL",`"${l}" is not a valid time`,{tokenType:t[o].type,tokenValue:l})}e.reset();try{this.parseExpression(e,t.slice(o+1),r,!1);return}catch{}}throw c$5.parsing("UNEXPECTED_TRAILING_TOKEN",`Unexpected token after expression: "${s.value}"`,{tokenType:s.type,tokenValue:s.value})}}compileAdHoc(e){let t=new d$1(this.pluginFunctionIndexByName);return this.parseExpression(t,e),t.build()}executeSymbolicTolerant(e,t=-1){let r=d(e,this.vm,void 0,void 0,this.makeLineContext(t),true);if(r.type==="error")throw r.error;if(r.type==="pending")throw c$5.execution("THEREFORE_ASYNC_UNSUPPORTED",`"=>" doesn't support expressions that call an async operation (weather/stocks/currency).`);return r.value}simplifySymbolically(e,t=-1){return this.executeSymbolicTolerant(this.compileAdHoc(e),t)}parseFactorChain(e){if(e.length===0||e.length%2===0)return null;let t=[];for(let r=0;r<e.length;r++)if(r%2===0){if(e[r].type!=="IDENT"&&e[r].type!=="UNIT")return null;t.push(e[r].value);}else if(e[r].type!=="STAR")return null;return t}solveEquation(e,t=-1){let r=[];for(let a of e.factorNames){let l=this.vm.getVar(a);if(l===void 0)return P("EQUATION_FACTOR_UNDEFINED",`Cannot solve for "${e.variable}": "${a}" is not yet defined.`);if(l.type!==7)return P("EQUATION_FACTOR_NOT_MATRIX",`Cannot solve for "${e.variable}": "${a}" must be a Matrix (got a different value type).`);r.push(l);}let i=r[0].value;for(let a=1;a<r.length;a++){let l=_$1(i,r[a].value);if(l.type===13)return l;i=l.value;}let s=da(i);if(s.type===13)return s;let o=this.executeSymbolicTolerant(e.rhsProgram,t);return o.type!==7?P("EQUATION_RHS_NOT_MATRIX",`Cannot solve for "${e.variable}": the right-hand side must be a Matrix.`):_$1(s.value,o.value)}tryDefineUserUnit(e){if(e.length<5||e[0].type!=="NUMBER"||Number(e[0].value)!==1)return null;let t$1=1;e[t$1].type==="STAR"&&t$1++;let r=[];for(;t$1<e.length&&e[t$1].type==="IDENT";)r.push(e[t$1].value),t$1++;if(r.length===0||e[t$1]?.type!=="EQUALS"||(t$1++,e[t$1]?.type!=="NUMBER"))return null;let i=e[t$1];if(t$1++,e[t$1]?.type!=="UNIT")return null;let s=e[t$1];return t$1++,t$1!==e.length?null:(this.userUnits.define(r,i.value,s.value),this.bytecodeCache.clear(),t(`${r.join(" ")} defined`))}tryCompoundAssignment(e,t=-1){if(e.length<2)return null;let r=e[0],i=e[1],s=r.type==="IDENT"||r.type==="UNIT",o=i.type==="PLUS_EQUALS"||i.type==="MINUS_EQUALS";if(!s||!o)return null;let a=e.slice(2);if(a.length===0)throw c$5.parsing("COMPOUND_ASSIGN_REQUIRES_EXPRESSION",`"${r.value} ${i.value}" needs an expression on the right, e.g. "${r.value} ${i.value} 10".`);let l=r.value;this.accumulatorNames.add(l),this.vm.getVar(l)===void 0&&this.vm.setVar(l,n(0));let c=i.type==="PLUS_EQUALS"?{type:"PLUS",text:"+"}:{type:"MINUS",text:"-"},u=[b$7("IDENT",l,[r]),b$7(c.type,c.text,[i]),b$7("LPAREN","(",[i]),...a,b$7("RPAREN",")",[i])],p=d(this.compileAdHoc(u),this.vm,void 0,void 0,this.makeLineContext(t),false);if(p.type==="error")throw p.error;if(p.type==="pending")throw c$5.execution("COMPOUND_ASSIGN_ASYNC_UNSUPPORTED","A running total (+= / -=) cannot use an async operation (weather/stocks/currency) on its right-hand side.");return this.vm.setVar(l,p.value),p.value}resetAccumulators(){for(let e of this.accumulatorNames)this.vm.deleteVar(e);return this.accumulatorNames}trySymbolicGrammar(e,t$1=-1){if(e.length===0)return null;if(e[e.length-1].type==="THEREFORE"){let c=e.slice(0,-1);if(c.length===0)throw c$5.parsing("THEREFORE_REQUIRES_EXPRESSION",'"=>" needs an expression or variable name before it.');if(c.length===1&&(c[0].type==="IDENT"||c[0].type==="UNIT")){let u=c[0].value,p=this.vm.getEquation(u),d=this.vm.getScalarEquation(u);if(p){let m=this.solveEquation(p,t$1);if(!(m.type===13&&m.value==="EQUATION_FACTOR_NOT_MATRIX")||!d)return m}if(d)return this.solveScalarEquation(d,t$1)}return this.simplifySymbolically(c,t$1)}if(b$8(e))return this.simplifySymbolically(e,t$1);if(e[0].type==="COLON"||e[0].type==="GLOBAL"||e[0].type==="GOAL_SEEK")return null;let i=e.findIndex(c=>c.type==="EQUALS");if(i===-1)return null;let s=this.parseFactorChain(e.slice(0,i));if(s===null)return this.tryStoreScalarEquation(e,i);let o=e.slice(i+1);if(s.length===1){let c=this.simplifySymbolically(o,t$1);return this.vm.setVar(s[0],c),c}let a=s[s.length-1],l=s.slice(0,-1);return this.vm.defineEquation(a,l,this.compileAdHoc(o)),this.vm.defineScalarEquation(a,this.compileAdHoc(e.slice(0,i)),this.compileAdHoc(o)),t(`${a} stored as an equation \u2014 solve with "${a} =>"`)}tryStoreScalarEquation(e,t$1){if(e[1]?.type==="LPAREN"||t$1===0||t$1===e.length-1)return null;let r=e.slice(0,t$1),i=e.slice(t$1+1);if(i.some(a=>a.type==="EQUALS"))return null;let s=this.equationUnknowns(r,i);if(s.length!==1)return null;let o=s[0];return this.vm.defineScalarEquation(o,this.compileAdHoc(r),this.compileAdHoc(i)),t(`${o} stored as an equation \u2014 solve with "${o} =>"`)}equationUnknowns(e,t){let r=[];for(let i of [...e,...t])i.type!=="IDENT"&&i.type!=="UNIT"||this.vm.getVar(i.value)===void 0&&(this.vm.hasUserFunction(i.value)||r.includes(i.value)||r.push(i.value));return r}solveScalarEquation(e,t=-1){let r=this.executeSymbolicTolerant(e.lhsProgram,t),i$1=this.executeSymbolicTolerant(e.rhsProgram,t);return i(r,i$1,e.variable)}lexToTokens(e,t){let r=[],i=false;this.lexer.resetExpression(e);for(let s of this.lexer)s.type!=="COMMENT"&&((s.type==="LPAREN"||s.type==="RPAREN")&&(i=true),r.push(s),t?.(s));return {tokens:r,hasParens:i}}prepareExpression(e,t,r,i,s=-1){let o=Me(e,this.config.validation);if(!o.passed)return {kind:"error",stage:"length",error:o.error.engineError};let a=t.filter(E=>E.type!=="COMMENT");if(a.length===0)return {kind:"empty"};let l=this.normalizer.normalize(a,i),c=Be(l,this.config.validation);if(!c.passed)return {kind:"error",stage:"complexity",error:c.engineError,normalizedTokens:l};let u,p=null;try{if(u=this.tryDefineUserUnit(l),u===null){let E=this.tryCompoundAssignment(l,s);E!==null&&(u=E,p=ye(l));}u===null&&(u=this.trySymbolicGrammar(l,s));}catch(E){let{reads:Z,writes:P}=ye(l);return {kind:"error",stage:"parse",error:d$4(E),reads:Z,writes:P,normalizedTokens:l}}if(u!==null)return {kind:"symbolic-solve",normalizedTokens:l,value:u,reads:p?.reads,writes:p?.writes};let{reads:d,writes:m}=ye(l),g=this.bytecodeCache.get(e);if(g)return {kind:"ready",normalizedTokens:l,reads:d,writes:m,program:g,cached:true};let A=this.builderPool[this.builderPoolIndex++%this.builderPool.length];A.reset();let O,I=null;try{let E=U.track("parser",()=>(this.parseExpression(A,l,r),A.build()));O=E.result,I=E.alloc;}catch(E){return {kind:"error",stage:"parse",error:d$4(E),reads:d,writes:m,normalizedTokens:l}}return this.cacheBytecode(e,O),{kind:"ready",normalizedTokens:l,reads:d,writes:m,program:O,cached:false,parserAlloc:I}}preflightAsync(e,t,r,i,s,o){if(!(t.hasAsync||this.resolverRegistry.size>0))return {kind:"proceed"};let a=new AbortController,l=()=>a.abort();this.keystrokeSignal?.addEventListener("abort",l,{once:true}),a$6.localControllerCreated("preflightAsync"),this.keystrokeSignal&&a$6.signalLinked("preflightAsync");let c=a.signal,u=this.resolverRegistry.preflightAll(e,t,"_engine",c,this.queryClient);if(u){this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.dag.registerLineDataSourceDependency(r,u.packageId||"_engine",[u.queryKey]),this.registerBackgroundRefresh(u);let p=O(u.queryKey);return this.storeLineResult(r,p,t,s,o,i),{kind:"pending",value:p}}return this.keystrokeSignal?.removeEventListener("abort",l),{kind:"proceed"}}evaluateWithTokens(e,t,r,i){let s=this.prepareExpression(t,r,i,void 0,e);if(s.kind==="empty"){let p=n(0);return this.lineCache.set(e,new j(p,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),t),p}if(s.kind==="error")throw s.error;if(s.kind==="symbolic-solve")return this.storeLineResult(e,s.value,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},s.reads??[],s.writes??[],t),s.value;let{normalizedTokens:o,reads:a,writes:l,program:c}=s,u=this.preflightAsync(o,c,e,t,a,l);return u.kind==="pending"?u.value:this.executeAndStore(c,e,t,a,l,"_engine")}evaluateLine(e,t){let r=this.evaluateLineWithDebug(e,t);if(r.error)throw r.engineError?r.engineError:c$5.execution("EVALUATION_ERROR",r.error,{lineNumber:e});return l(r.value)}evaluateLineWithDebug(e,t,r="expression"){let i=t.match(/^s`([^`]*)`$/);if(i){let s=i[1];return {...this.evaluateExpressionWithDiagnostic(s,e,r),inlineSolve:{start:0,end:t.length,expression:s,lineNumber:e,columnNumber:1}}}return this.evaluateExpressionWithDiagnostic(t,e,r)}addDiagnosticStage(e,t,r,i,s,o,a,l,c){e.push({stage:t,label:r,icon:i,colorClass:s,stepNumber:o,elapsedNs:a,skipped:l,output:c});}evaluateExpressionWithDiagnostic(e,t,r="expression"){let i=this.diagnosticPipeline,s=i.hasCollectors,o=this.timelineCollector?.parseletMatchCount??0,a=U.isEnabled(),l=[],c=[],u=0,p=Me(e,this.config.validation);if(!p.passed)return s&&this.addDiagnosticStage(c,"safety_length","Safety: Length","\u{1F6E1}\uFE0F","validate",2,u,false,{type:"safety_length",passed:false,expressionLength:e.length,maxLength:this.config.validation.maxExpressionLength,errorMessage:p.error.error}),{...p.error,debug:void 0,diagnostic:void 0};s&&(i.firePipelineStart({type:c$6.PipelineStart,elapsedNs:0,expression:e,inputType:r}),this.addDiagnosticStage(c,"pipeline_start","Pipeline Start","\u25B6","pipeline",1,u,false,{type:"pipeline_start",expression:e,inputType:r}),this.addDiagnosticStage(c,"safety_length","Safety: Length","\u{1F6E1}\uFE0F","validate",2,u,false,{type:"safety_length",passed:true,expressionLength:e.length,maxLength:this.config.validation.maxExpressionLength}));let d=s?h=>{i.fireTokenEmitted({type:c$6.TokenEmitted,elapsedNs:0,expression:e,token:{type:h.type,value:h.value,offset:h.offset||0,line:h.line||t,col:h.col||0}});}:void 0,m=U.track("lexer",()=>this.lexToTokens(e,d)),g=m.result.tokens,A=m.result.hasParens;if(a&&m.alloc&&l.push(m.alloc),s){let h={};for(let R of g)h[R.type]=(h[R.type]||0)+1;this.addDiagnosticStage(c,"lexer","Lexer","\u{1F524}","lexer",3,u,false,{type:"lexer",tokenCount:g.length,tokenTypes:h,hasParens:A,locale:this.localeCode,tokens:[...g]});let T=[];for(let R=0;R<g.length;R++){let ne=g[R];if(ne.type==="INLINE_SOLVE_START"){let M=-1;for(let z=R+1;z<g.length;z++)if(g[z].type==="BACKTICK_OPEN"){M=z;break}if(M>R){let qt=g.slice(R+1,M).map(Gt=>Gt.value).join("");T.push({startTokenIndex:R,endTokenIndex:M,expression:qt,columnNumber:ne.col||1}),R=M;}}}this.addDiagnosticStage(c,"line_classification","Line Classification","\u{1F4CB}","classify",3.5,u,false,{type:"line_classification",classification:"expression",skip:false,hasInlineSolve:T.length>0,inlineSolveSpans:T});}if(g.length===0){let h=n(0);return this.lineCache.set(t,new j(h,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),s&&i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:0,totalOpcodes:0}),{value:h,tokens:g,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}let O=0,I=[],E=new Map,Z=s?h=>{O++,I.push(h),E.set(h.rule,(E.get(h.rule)||0)+1),i.fireTokenFused({type:c$6.TokenFused,elapsedNs:0,expression:e,ruleName:h.rule,sourceTokenCount:h.sourceTokens.length,fusedTokenType:h.fusedToken.type,fusedTokenValue:h.fusedToken.value});}:void 0;s&&this.normalizer.ruleCount>0&&i.fireNormalizerStart({type:c$6.NormalizerStart,elapsedNs:0,expression:e,inputTokenCount:g.length});let P=this.bytecodeCache.get(e);s&&!P&&this.parser.setDiagnosticPipeline(i,e);let y=this.prepareExpression(e,g,A,Z,t);a&&y.kind==="ready"&&y.parserAlloc&&l.push(y.parserAlloc),s&&!P&&this.parser.setDiagnosticPipeline(void 0,"");let x=y.kind==="empty"?g:y.normalizedTokens??g;if(s&&(this.normalizer.ruleCount>0?(i.fireNormalizerEnd({type:c$6.NormalizerEnd,elapsedNs:0,expression:e,outputTokenCount:x.length,fusionsCount:O}),this.addDiagnosticStage(c,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,false,{type:"normalizer",inputTokenCount:g.length,outputTokenCount:x.length,fusions:I,rulesApplied:[...E.entries()].map(([h,T])=>({rule:h,count:T})),tokens:[...x],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(x)})):this.addDiagnosticStage(c,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,true,{type:"normalizer",inputTokenCount:g.length,outputTokenCount:g.length,fusions:[],rulesApplied:[],tokens:[...g],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(g)})),y.kind==="empty"||y.kind==="error"&&y.stage==="length"){if(s&&i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:y.kind==="empty",totalTokens:g.length,totalOpcodes:0}),y.kind==="empty"){let h=n(0);return this.lineCache.set(t,new j(h,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),{value:h,tokens:g,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}return {value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:y.error.message,engineError:y.error,debug:void 0,diagnostic:void 0}}let ee=Be(x,this.config.validation);if(y.kind==="error"&&y.stage==="complexity")return s&&(this.addDiagnosticStage(c,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:false,complexityScore:ee.complexityScore??0,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:x.length,functionCalls:0,nestingDepth:0},errorMessage:ee.errorMessage}),i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:g.length,totalOpcodes:0})),{value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:ee.errorMessage,engineError:ee.engineError,debug:void 0,diagnostic:void 0};if(s&&this.addDiagnosticStage(c,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:true,complexityScore:ee.complexityScore??x.length,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:x.length,functionCalls:0,nestingDepth:0}}),y.kind==="symbolic-solve"){s&&i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:g.length,totalOpcodes:0});let h={opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false};return this.storeLineResult(t,y.value,h,y.reads??[],y.writes??[],e),{value:y.value,tokens:x,program:h,debug:void 0,diagnostic:void 0}}let ce=y.reads??[],te=y.writes??[];if(s&&(this.addDiagnosticStage(c,"readwrite","Read/Write","\u{1F4CB}","readwrite",6,u,false,{type:"readwrite",reads:ce,writes:te,isAssignment:te.length>0}),this.addDiagnosticStage(c,"cache_check","Cache Check","\u{1F4BE}","cache",7,u,false,{type:"cache_check",hit:!!P,cacheSize:this.bytecodeCache.size,cacheKey:e}),P?i.fireCacheHit({type:c$6.CacheHit,elapsedNs:0,expression:e,cache:"bytecode",key:e}):i.fireCacheMiss({type:c$6.CacheMiss,elapsedNs:0,expression:e,cache:"bytecode",key:e})),y.kind==="error"&&y.stage==="parse")return s&&i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:g.length,totalOpcodes:0}),{value:n(0),tokens:x,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:y.error.message,engineError:y.error,debug:void 0,diagnostic:void 0};if(y.kind!=="ready")throw c$5.internal({code:"UNEXPECTED_ERROR",message:"Internal error: prepareExpression() returned an unexpected variant after all other cases were handled"});let v=y.program;s&&(this.addDiagnosticStage(c,"parser","Parser","\u{1F333}","parser",8,u,!!P,{type:"parser",parselets:[],uniqueParseletTypes:[],astDepth:0}),this.addDiagnosticStage(c,"compiler","Compiler","\u2699\uFE0F","compiler",9,u,!!P,{type:"compiler",opcodeCount:v.opcodes.length,numberConstants:v.numbers.length,stringConstants:v.strings.length,hasAsync:v.hasAsync,cached:!!P}),i.fireBytecodeBuilt({type:c$6.BytecodeBuilt,elapsedNs:0,expression:e,opcodesLength:v.opcodes.length,numbersLength:v.numbers.length,stringsLength:v.strings.length,isCached:!!P}));let Kt=v.hasAsync||this.resolverRegistry.size>0,re=this.preflightAsync(x,v,t,e,ce,te);if(s&&(re.kind==="pending"?this.addDiagnosticStage(c,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"pending",pendingQueryKey:re.value.value,resolverCount:this.resolverRegistry.size,skippedGuard:true}):Kt?this.addDiagnosticStage(c,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"sync",resolverCount:this.resolverRegistry.size,skippedGuard:false}):this.addDiagnosticStage(c,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,true,{type:"async_preflight",path:"sync",resolverCount:0,skippedGuard:true})),re.kind==="pending")return s&&i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:g.length,totalOpcodes:v.opcodes.length}),{value:re.value,tokens:x,program:v,debug:void 0,diagnostic:s?this.buildDiagnosticResult(c,re.value,x,v,null):void 0};let Ht=s&&this.config.diagnostic.vmTraceEnabled===true,C;try{let h=U.track("vm",()=>this.executeAndStore(v,t,e,ce,te,"_engine",Ht?i:void 0,e),{cacheHit:!!P});C=h.result,a&&h.alloc&&l.push(h.alloc);}catch(h){let T=d$4(h);return s&&i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:g.length,totalOpcodes:v.opcodes.length}),{value:n(0),tokens:x,program:v,error:T.message,engineError:T,debug:void 0,diagnostic:void 0}}let ue=C.type===12;if(s){let h=ue?"pending":String(C.value??""),T=ue?"Pending":C.unit?"Uom":"Number";this.addDiagnosticStage(c,"vm_execute","VM Execute","\u26A1","vm",11,u,false,{type:"vm_execute",totalInstructions:v.opcodes.length,stackDepth:this.vm.getStack().length,resultType:T,resultValue:h,isPending:ue});}if(ue)return s&&i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:g.length,totalOpcodes:v.opcodes.length}),{value:C,tokens:x,program:v,debug:void 0,diagnostic:s?this.buildDiagnosticResult(c,C,x,v,null):void 0};if(a&&l.length>0&&(this.lastTelemetry=U.createTelemetry(e,l,!!P)),s&&(this.addDiagnosticStage(c,"dag_registration","DAG Registration","\u{1F517}","dag",12,u,false,{type:"dag_registration",readsRegistered:ce,writesRegistered:te,dataSourcesRegistered:[]}),this.addDiagnosticStage(c,"linecache","Line Cache","\u{1F4E6}","cache",13,u,false,{type:"linecache",lineNumber:t,expression:e,stored:true}),this.addDiagnosticStage(c,"result","Result","\u2713","result",14,u,false,{type:"result",rawValue:String(C.value),formattedValue:String(C.value),valueType:C.type===0?"Number":"Value",unit:C.unit}),i.fireVmHalt({type:c$6.VmHalt,elapsedNs:0,expression:e,result:C?{type:C.type,value:C.value,unit:C.unit}:void 0}),this.addDiagnosticStage(c,"pipeline_end","Pipeline End","\u23F9","pipeline",15,u,false,{type:"pipeline_end",success:true,totalTokens:g.length,totalOpcodes:v.opcodes.length,cacheHit:!!P}),i.firePipelineEnd({type:c$6.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:g.length,totalOpcodes:v.opcodes.length})),s){let T=i.collectReports()[0]?.toJSON(),R=T;if(T){let ne=T.parselets.slice(o),M={};for(let z of ne)M[z.parseletCategory]=(M[z.parseletCategory]??0)+1;R={...T,parselets:ne,summary:{...T.summary,totalParselets:Object.keys(M).length,parseCategories:M}};}return {value:C,tokens:x,program:v,debug:R,diagnostic:this.buildDiagnosticResult(c,C,x,v,null)}}return {value:C,tokens:x,program:v}}buildDiagnosticResult(e,t,r,i,s){return {stages:e,value:t,tokens:r,program:i,error:s,dagSnapshot:this.dag.getSnapshot(),cacheSnapshot:this.getCacheSnapshot(),batcherMetrics:this.getBatcherMetrics(),checkpoints:this.getCheckpoints()}}reEvaluateLine(e,t){let r=this.lineCache.get(e,t);if(!r)return;let i=this.bytecodeCache.get(t);if(!i)return;if(r.bytecode.hasAsync||this.resolverRegistry.size>0){let a=new AbortController,l=()=>a.abort();this.keystrokeSignal?.addEventListener("abort",l,{once:true}),a$6.localControllerCreated("reEvaluateLine preflight"),this.keystrokeSignal&&a$6.signalLinked("reEvaluateLine preflight");let c=a.signal,u=this.resolverRegistry.preflightAll([],r.bytecode,"_engine",c,this.queryClient);if(u)return this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.registerBackgroundRefresh(u),O(u.queryKey);this.keystrokeSignal?.removeEventListener("abort",l);}let s=this.executeRaw(i,e);if(s.type==="pending")return this.resolveAsync(s),O(s.queryKey);if(s.type==="error")throw s.error;let o=s.value;return r.result=o,o}getDag(){return this.dag}getLineCache(){return this.lineCache}getBytecodeCache(){return this.bytecodeCache}getVM(){return this.vm}getContext(){return this.context}getScopeManager(){return this.scopeManager}getLexer(){return this.lexer}getNormalizer(){return this.normalizer}getPackageCompletionItems(){let e=[];for(let t of this.packageCompletionItems.values())e.push(...t);return e}getParseletRegistry(){return {prefix:this.registry.getAllPrefix(),infix:this.registry.getAllInfix()}}tokenizeForClassification(e){this.lexer.resetExpression(e);let r=Array.from(this.lexer).filter(i=>i.type!=="COMMENT");return r.length===0?[]:this.normalizer.normalize(r)}getParser(){return this.parser}isDiagnosticMode(){return this.diagnosticPipeline.hasCollectors}setKeystrokeSignal(e){e?a$6.keystrokeSignalSet(e.aborted):a$6.keystrokeSignalCleared(),this.keystrokeSignal=e;}getCacheSnapshot(){let e=[];for(let[o,a]of this.bytecodeCache)e.push({expression:o,opcodesLength:a.opcodes.length,numbersLength:a.numbers.length,stringsLength:a.strings.length,hasAsync:a.hasAsync});let t=[];for(let o of this.lineCache.keys()){let a=o.indexOf(":"),l=a>0?parseInt(o.slice(0,a),10)||0:parseInt(o,10)||0,c=a>0?o.slice(a+1):void 0,u=c!==void 0?this.lineCache.get(l,c):this.lineCache.getEntryForLine(l);u&&t.push({key:o,lineNumber:l,resultType:String(u.result?.type??""),resultValue:String(u.result?.value??""),reads:u.readVariables??[],writeVar:u.writeVariable??null});}let s=this.queryClient.getQueryCache().getAll().map(o=>{let a=o.state.status==="success"?"resolved":o.state.status==="error"?"error":"in_flight";return {packageId:o.queryKey[0]??"unknown",resolvedCount:o.state.status==="success"?1:0,inFlightCount:o.state.status!=="success"&&o.state.status!=="error"?1:0,errorCount:o.state.status==="error"?1:0,entries:[{key:o.queryKey.join(":"),status:a}]}});return {bytecode:e,lineCache:t,asyncCache:s}}getBatcherMetrics(){return {pendingCount:this.batcher.pendingCount,dedupCount:this.batcher.dedupCount,workerOffloadCount:this.batcher.workerOffloadCount,listenerCount:this.batcher.listenerCount}}getCheckpoints(){let t=this.vm.checkpointer;return t?t.getAllCheckpoints().map(i=>({lineNumber:i.lineNumber,variables:Object.keys(i.variables),variableCount:Object.keys(i.variables).length})):[]}getLastTelemetry(){return this.lastTelemetry}evaluateExpression(e){return this.evaluateLine(-1,e)}explainLine(e){let{tokens:t}=this.lexToTokens(e),r=t.filter(s=>s.type!=="COMMENT"),i=this.normalizer.normalize(r);return _e({expression:e,tokens:i,evaluate:s=>this.evaluateIsolated(s),locale:this.localeCode})}evaluateIsolated(e){let{tokens:t,hasParens:r}=this.lexToTokens(e),i=this.prepareExpression(e,t,r,void 0,-1);if(i.kind==="empty")return n(0);if(i.kind==="error")throw i.error;if(i.kind==="symbolic-solve")return i.value;let s=this.executeRaw(i.program,-1);if(s.type==="error")throw s.error;if(s.type==="pending")throw c$5.execution("EXPLAIN_ASYNC_UNSUPPORTED",`A derivation cannot be built for a line that resolves data asynchronously: "${e}"`,{expression:e});return s.value}compileExpression(e){let{tokens:t,hasParens:r}=this.lexToTokens(e),i=this.prepareExpression(e,t,r);if(i.kind==="empty")return {program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:[],reads:[],writes:[]};if(i.kind==="error")throw i.stage==="parse"&&(i.reads?.length||i.writes?.length)?new b$9(i.error.category,{code:i.error.code,message:i.error.message,expected:i.error.expected,found:i.error.found,suggestion:i.error.suggestion,recoverable:i.error.recoverable,span:i.error.span,cause:i.error.cause,context:{...i.error.context,reads:i.reads??[],writes:i.writes??[]}}):i.error;return i.kind==="symbolic-solve"?{program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:i.normalizedTokens,reads:i.reads??[],writes:i.writes??[]}:{program:i.program,tokens:t,reads:i.reads,writes:i.writes}}tryCompileExpression(e){try{return this.tryCompileExpressionUnguarded(e)}catch{return false}}tryCompileExpressionUnguarded(e){let{tokens:t,hasParens:r}=this.lexToTokens(e);return this.prepareExpression(e,t,r).kind!=="error"}executeCached(e,t=-1){if(e.opcodes.length===0)return n(0);let r=this.executeRaw(e,t);if(r.type==="pending")return this.resolveAsync(r),O(r.queryKey);if(r.type==="error")throw r.error;return r.value}evaluateNumber(e){let t=e.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)&&this.vm.getVar(t)===void 0)return NaN;try{let r=this.evaluateLine(-1,e);return r.isFault()?NaN:r.toNumber()}catch{return NaN}}clear(){this.batcher.clearAll(),this.backgroundRefresh?.clearAll(),this.queryClient.clear(),b$a()===this.queryClient&&a$7(null),this.dag.clear(),this.lineCache.clear(),this.scopeManager.clear(),this.bytecodeCache.clear(),this.vm.reset(),this.userUnits.clear(),this.accumulatorNames.clear(),this.lastTelemetry=null;}toJSON(){let e=this.dag.getSnapshot(),t=new Set;for(let c of Object.keys(e.dataSourceDeps)){let u=Number(c);Number.isNaN(u)||t.add(u);}let r=this.lineCache.snapshotEntries(),i=new Map;for(let{line:c,entry:u}of r){let p=t.has(c)||u.bytecode.hasAsync;p&&t.add(c);let d=u.writeVariable;if(d){let m=i.get(d);(!m||c>=m.line)&&i.set(d,{line:c,async:p});}}let s={};for(let[c,u]of this.vm.getVariableEntries())if(u.type!==12&&!i.get(c)?.async)try{s[c]=Ae(u,`variable "${c}"`);}catch(p){if(p instanceof b$9&&p.code===D.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw p}let o=this.vm.getUserFunctionDefs().map(Le),a=[];for(let{line:c,expression:u,entry:p}of r){if(t.has(c)||p.result.type===12)continue;let d;try{d=Ae(p.result,`line ${c}`);}catch(m){if(m instanceof b$9&&m.code===D.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw m}a.push({line:c,expression:u,result:d,bytecode:oe(p.bytecode),reads:p.readVariables.slice(),writeVar:p.writeVariable});}let l=Array.from(this.bytecodeCache.entries()).map(([c,u])=>({expression:c,program:oe(u)}));return {format:X,version:K,engineVersion:a$5,locale:this.localeCode,variables:s,userFunctions:o,lineCache:a,bytecodeCache:l}}static fromJSON(e,t={}){Mt(e);let r=t.locale??e.locale??"en",i=new H({locale:r,diagnostics:t.diagnostics??false,config:t.config,packages:t.packages});return i.restoreSnapshot(e),i}restoreSnapshot(e){for(let[t,r]of Object.entries(e.variables))this.vm.setVar(t,Pe(r));for(let t of e.userFunctions){let r=Oe(t);this.vm.defineUserFunction(r.name,r.params,r.program);}for(let t of e.lineCache){let r=new j(Pe(t.result),ae(t.bytecode),t.reads.slice(),t.writeVar);this.lineCache.set(t.line,r,t.expression),this.dag.registerLine(t.line,t.reads,t.writeVar?[t.writeVar]:[]);}for(let{expression:t,program:r}of e.bytecodeCache)this.bytecodeCache.set(t,ae(r));}evaluateIncremental(e,t){let r=this.dag.getAffectedLinesInOrder(e);this.vm.setVar(e,n(t));let i=new Map;for(let s of r){let o=this.lineCache.getEntryForLine(s);if(!o||o.bytecode.opcodes.length===0)continue;let a=this.executeRaw(o.bytecode,s);if(a.type==="pending"){this.resolveAsync(a);continue}if(a.type==="error"){let c=P(a.error.code,a.error.message);i.set(s,c),o.result=c;continue}let l=a.value;i.set(s,l),o.result=l;}return i}};H.GOAL_SEEK_MAX_NESTING_DEPTH=1,H.WARMUP_EXPRESSIONS=["1 + 2 * 3","10.5 / 2 - 0.25","50% of 200","3 kg + 400 g","sqrt(144) + max(1, 2)","1 < 2 && 3 >= 3","half of 250",'"text" + "joined"'];var be=H;var Fe=(()=>{throw new Error("engine.worker.ts was not processed by esbuild-plugin-inline-worker, so worker offload is unavailable")}),J=null;function vr(){return J||(J=new be),J}var Y=null;function br(){return Y||(Y=c(w,200,5e4)),Y}function Er(n){let e={lineId:n.lineId,expression:n.expression,compiledAgainstHash:n.textHash,strings:[],reads:[],writes:[],isVariableDef:false,error:null};try{let t=vr(),{program:r,reads:i,writes:s}=t.compileExpression(n.expression),o=s.length>0,a=r.opcodes,l=r.numbers,c=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),u=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);return {...e,opcodesBuffer:c,numbersBuffer:u,opcodesLength:a.length,numbersLength:l.length,strings:[...r.strings],reads:i,writes:s,isVariableDef:o}}catch(t){return {...e,opcodesBuffer:new ArrayBuffer(0),numbersBuffer:new ArrayBuffer(0),opcodesLength:0,numbersLength:0,error:t instanceof Error?t.message:String(t)}}}function xr(n){let e=[],t=[];for(let r of n.items){let i=Er(r);e.push(i),i.opcodesBuffer.byteLength>0&&t.push(i.opcodesBuffer),i.numbersBuffer.byteLength>0&&t.push(i.numbersBuffer);}self.postMessage({id:n.id,type:"COMPILE_RESULT",results:e},t);}function Sr(n){let e=br();e.reset();let t=new Uint8Array(n.opcodesBuffer,0,n.opcodesLength),r=new Float64Array(n.numbersBuffer,0,n.numbersLength),i={opcodes:t,numbers:r,strings:n.strings};try{let s=d(i,e);if(s.type==="pending")return {lineNumber:n.lineNumber,valueType:12,value:0,isPending:!0,queryKey:s.queryKey};if(s.type==="error")return {lineNumber:n.lineNumber,valueType:13,value:0,isPending:!1,unit:s.error.message};let o=s.value;return {lineNumber:n.lineNumber,valueType:o.type,value:typeof o.value=="number"?o.value:typeof o.value=="bigint"?Number(o.value):0,unit:o.unit,isPending:!1}}catch{return {lineNumber:n.lineNumber,valueType:13,value:0,isPending:false,unit:"Worker execution failed"}}}function kr(n){let e=[];for(let t of n.items)e.push(Sr(t));self.postMessage({id:n.id,type:"EXECUTE_RESULT",results:e});}var Cr=typeof self<"u"&&typeof window>"u",wr=n=>{if(n.origin&&self.location&&n.origin!==self.location.origin)return;let e=n.data;switch(e.type){case "COMPILE_BATCH":xr(e);break;case "EXECUTE_BATCH":kr(e);break;case "TERMINATE":{J&&(J.clear(),J=null),Y&&(Y.reset(),Y=null),self.postMessage({id:e.id,type:"COMPILE_RESULT",results:[]});break}default:self.postMessage({id:-1,type:"COMPILE_RESULT",results:[],error:`Unknown message type: ${e.type}`});}};Cr&&(self.onmessage=wr);var Tr=3e4,jt=50,xe=class{constructor(e){this.workers=[];this.nextWorker=0;this.nextId=1;this.pendingBatches=new Map;this.terminated=false;this._available=null;this.poolSize=Math.min(e??this.defaultPoolSize(),4);}defaultPoolSize(){return typeof navigator<"u"&&navigator.hardwareConcurrency?Math.min(navigator.hardwareConcurrency,4):2}isAvailable(){if(this.terminated)return false;if(this._available!==null)return this._available;if(typeof Worker>"u")return this._available=false,false;try{return Fe().terminate(),this._available=!0,!0}catch{return this._available=false,false}}executeBatch(e,t){if(!this.isAvailable())return;if(e.length===0)return Promise.resolve([]);this.ensureWorkers();let r=[];for(let a of e){let l=t.get(a);if(!l||l.bytecode.opcodes.length===0)continue;let c=l.bytecode.opcodes,u=l.bytecode.numbers,p=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength),d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);r.push({lineNumber:a,opcodesBuffer:p,numbersBuffer:d,opcodesLength:c.length,numbersLength:u.length,strings:[...l.bytecode.strings]});}if(r.length===0)return Promise.resolve([]);let i=[];for(let a of r)a.opcodesBuffer.byteLength>0&&i.push(a.opcodesBuffer),a.numbersBuffer.byteLength>0&&i.push(a.numbersBuffer);let s=this.nextId++,o=this.getNextWorker();return new Promise(a=>{let l=setTimeout(()=>{this.pendingBatches.delete(s),a([]);},Tr);this.pendingBatches.set(s,{id:s,lineNumbers:e,resolve:c=>{clearTimeout(l),a(c);}}),o.postMessage({type:"EXECUTE_BATCH",id:s,items:r},i);})}clear(){for(let[,e]of this.pendingBatches)e.resolve([]);this.pendingBatches.clear();for(let e of this.workers)e.terminate();this.workers=[],this.nextWorker=0;}destroy(){this.terminated=true,this.clear();}ensureWorkers(){if(!(this.workers.length>0))for(let e=0;e<this.poolSize;e++){let t=Fe();t.onmessage=r=>{this.handleWorkerMessage(r.data);},t.onerror=r=>{console.error(`[ExecutionPool] Worker ${e} error:`,r.message);for(let[i,s]of this.pendingBatches)s.resolve([]),this.pendingBatches.delete(i);},this.workers.push(t);}}getNextWorker(){let e=this.workers[this.nextWorker];return this.nextWorker=(this.nextWorker+1)%this.workers.length,e}handleWorkerMessage(e){if(e.type!=="EXECUTE_RESULT")return;let t=this.pendingBatches.get(e.id);t&&(this.pendingBatches.delete(e.id),t.resolve(e.results));}};function Wt(n$1){switch(n$1.valueType){case 0:return n(n$1.value);case 1:return r(n$1.value);case 2:return s(BigInt(n$1.value));case 3:return t(String(n$1.value));case 4:return M(n$1.value);case 5:return N(n$1.value);case 6:return u(n$1.value,n$1.unit??"");case 7:return n(n$1.value);case 10:return L(n$1.value!==0);case 12:return O(n$1.queryKey??"");case 13:return P("WORKER_EXECUTION_ERROR",n$1.unit??"Unknown worker error");default:return n(n$1.value)}}var Se=class Se{constructor(e,t,r,i=Se.DEFAULT_HIGH_WATER_MARK){this.pending=[];this.scheduled=false;this.cleared=false;this.executionPool=null;this.workerOffloadDispatchCount=0;this._streamController=null;this._testCaptures=null;this.onLineResult=null;this.warnedAboutMissingHook=false;this.dag=e,this.lineCache=t,this.vm=r,this.highWaterMark=i,this._eventStream=this.createEventStream();}warnIfUnwired(){this.onLineResult||this.warnedAboutMissingHook||(this.warnedAboutMissingHook=true,console.warn("[solve-engine] An async result resolved but AsyncResolutionBatcher.onLineResult is not set, so the value cannot reach your document and the line will keep showing as pending. Set it to mirror resolved values into your own state. This warning appears once per batcher."));}createEventStream(){return new ReadableStream({start:e=>{this._streamController=e;},cancel:()=>{this._streamController=null;}},new CountQueuingStrategy({highWaterMark:this.highWaterMark}))}add(e){this.cleared=false;for(let t of this.pending)if(t.packageId===e.packageId&&t.queryKey===e.queryKey)return;this.pending.push(e),this.scheduled||(this.scheduled=true,queueMicrotask(()=>{try{this.flush();}catch(t){let r=d$4(t);console.error(`[AsyncResolutionBatcher] flush() failed unexpectedly \u2014 this should never happen; please report: ${r.format()}`);}}));}getEventStream(){return this._eventStream}get pendingCount(){return this.pending.length}get dedupCount(){let e=new Set;for(let t of this.pending)e.add(`${t.packageId}:${t.queryKey}`);return Math.max(0,this.pending.length-e.size)}get listenerCount(){return this._eventStream.locked?1:0}get workerOffloadCount(){return this.workerOffloadDispatchCount}clearAll(){this.pending=[],this.scheduled=false,this.cleared=true,this._testCaptures=null,this.onLineResult=null;try{this._streamController?.close();}catch{}this._streamController=null,this._eventStream=this.createEventStream(),this.executionPool&&(this.executionPool.clear(),this.executionPool=null),this.workerOffloadDispatchCount=0;}flush(){if(this.scheduled=false,this.cleared||this.pending.length===0)return;let e=this.pending;this.pending=[];let t=new Map;for(let c of e){let u=`${c.packageId}:${c.queryKey}`;t.set(u,c);}let r=[],i=[];for(let c of t.values())c.isError?r.push(c):i.push(c);for(let c of r)c.signal.aborted||this.notifyListeners({type:"error",queryKey:c.queryKey,packageId:c.packageId,error:c.error??new Error("Unknown async resolution error")});let s=new Set,o=[],a=[...i,...r];for(let c of a){if(c.signal.aborted)continue;o.push(c.queryKey);let u=this.dag.getAffectedLinesByDataSource(c.packageId,[c.queryKey]);for(let p of u)s.add(p);}if(s.size===0){this.notifyListeners({type:"lines-updated",lineNumbers:[],affectedQueryKeys:o});return}let l=this.topologicalSort(Array.from(s));if(l.length>jt){let c=new Map;for(let u of l)c.set(u,this.lineCache.getEntryForLine(u));this.reExecuteViaWorkerPool(l,c,o).catch(u=>{let p=d$4(u);console.error(`[AsyncResolutionBatcher] reExecuteViaWorkerPool() failed unexpectedly: ${p.format()}`);});return}this.reExecuteMainThread(l,o);}topologicalSort(e){if(e.length<=1)return e;let t=new Map,r=new Map,i=new Map;for(let a of e)t.set(a,0),r.set(a,[]);for(let a of e){let l=this.dag.getWrites(a);for(let c of l)i.set(c,a);}for(let a of e){let l=this.dag.getDependencies(a);for(let c of l){let u=i.get(c);u!==void 0&&u!==a&&(r.get(u).push(a),t.set(a,(t.get(a)??0)+1));}}let s=[];for(let[a,l]of t)l===0&&s.push(a);if(s.length===0&&e.length>0)return [...e].sort((a,l)=>a-l);let o=[];for(;s.length>0;){let a=s.shift();o.push(a);for(let l of r.get(a)??[]){let c=(t.get(l)??1)-1;t.set(l,c),c===0&&s.push(l);}}if(o.length<e.length){let a=e.filter(l=>!o.includes(l)).sort((l,c)=>l-c);o.push(...a);}return o}async reExecuteViaWorkerPool(e,t,r){this.executionPool||(this.executionPool=new xe);let i=this.executionPool.executeBatch(e,t);if(!i){this.reExecuteMainThread(e,r,t);return}this.workerOffloadDispatchCount++;let s=await i;if(this.cleared)return;let o=[];for(let a of s){let l=t.get(a.lineNumber);if(!l||a.isPending)continue;let c=Wt(a);l.result=c,this.warnIfUnwired(),this.onLineResult?.(a.lineNumber,c),o.push(a.lineNumber);}this.cleared||(o.length>0||r.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:o,affectedQueryKeys:r});}reExecuteMainThread(e,t,r){let i=[];for(let s of e){let o=r?r.get(s):this.lineCache.getEntryForLine(s);if(!o||o.bytecode.opcodes.length===0)continue;let a=this.vm.getStack().length;try{let l=d(o.bytecode,this.vm);for(;this.vm.getStack().length>a;)this.vm.pop();if(l.type==="value")o.result=l.value,this.warnIfUnwired(),this.onLineResult?.(s,l.value),i.push(s);else if(l.type==="error"){let c=P(l.error.code,l.error.message);o.result=c,this.warnIfUnwired(),this.warnIfUnwired(),this.onLineResult?.(s,c),i.push(s);}}catch(l){for(;this.vm.getStack().length>a;)this.vm.pop();let c=d$4(l),u=P(c.code,c.message);o.result=u,this.warnIfUnwired(),this.onLineResult?.(s,u),i.push(s);}}return (i.length>0||t.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:i,affectedQueryKeys:t}),i}notifyListeners(e){if(this._testCaptures&&this._testCaptures.push(e),this._streamController)try{this._streamController.enqueue(e);}catch{}}};Se.DEFAULT_HIGH_WATER_MARK=64;var Ee=Se;export{Nr as a,rr as b,Lt as c,X as d,K as e,D as f,Fe as g,Ee as h,Me as i,Be as j,ye as k,Gr as l,Qr as m,be as n};//# sourceMappingURL=chunk-42JXN3BH.js.map
5
- //# sourceMappingURL=chunk-42JXN3BH.js.map