solve-engine 2.38.27 → 2.38.28

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 (122) hide show
  1. package/dist/{PackageCompatibility-DwcUeOGJ.d.ts → PackageCompatibility-BfRpqwmD.d.ts} +1 -1
  2. package/dist/{PackageCompatibility-BJja2o8r.d.cts → PackageCompatibility-CcfNMlWN.d.cts} +1 -1
  3. package/dist/{PackageRegistry-Cj73Whk9.d.ts → PackageRegistry-ClAKDDOP.d.ts} +4 -4
  4. package/dist/{PackageRegistry-DqzsjxGQ.d.cts → PackageRegistry-DLLVZW0S.d.cts} +4 -4
  5. package/dist/{Parselet-DmMY2s9Y.d.cts → Parselet-ClR3Blwp.d.cts} +1 -1
  6. package/dist/{Parselet-Br1tHash.d.ts → Parselet-DkAFnfU2.d.ts} +1 -1
  7. package/dist/{VMBuiltins-BqkoJtHt.d.ts → VMBuiltins-Bk8TQNF1.d.ts} +2 -2
  8. package/dist/{VMBuiltins-Baa90D2v.d.cts → VMBuiltins-ClXnXk9K.d.cts} +2 -2
  9. package/dist/{Value-B55Hvn3e.d.cts → Value-wMuCzPn0.d.cts} +18 -2
  10. package/dist/{Value-B55Hvn3e.d.ts → Value-wMuCzPn0.d.ts} +18 -2
  11. package/dist/{chunk-SFCLGBCD.js → chunk-34RTVUU3.js} +3 -3
  12. package/dist/{chunk-SFCLGBCD.js.map → chunk-34RTVUU3.js.map} +1 -1
  13. package/dist/{chunk-QP4VIEXZ.js → chunk-36JGHDZR.js} +2 -2
  14. package/dist/chunk-36JGHDZR.js.map +1 -0
  15. package/dist/chunk-3ZFJLH4W.cjs +2 -0
  16. package/dist/chunk-3ZFJLH4W.cjs.map +1 -0
  17. package/dist/{chunk-EZ7R3ZHM.cjs → chunk-4AX7GIZY.cjs} +3 -3
  18. package/dist/{chunk-EZ7R3ZHM.cjs.map → chunk-4AX7GIZY.cjs.map} +1 -1
  19. package/dist/chunk-4H27GUVY.js +2 -0
  20. package/dist/chunk-4H27GUVY.js.map +1 -0
  21. package/dist/{chunk-JVDNK45F.cjs → chunk-5BRJQREI.cjs} +4 -4
  22. package/dist/{chunk-JVDNK45F.cjs.map → chunk-5BRJQREI.cjs.map} +1 -1
  23. package/dist/{chunk-AWGSR2GZ.js → chunk-BNVE6I22.js} +2 -2
  24. package/dist/{chunk-AWGSR2GZ.js.map → chunk-BNVE6I22.js.map} +1 -1
  25. package/dist/chunk-CAJKB4WQ.js +2 -0
  26. package/dist/chunk-CAJKB4WQ.js.map +1 -0
  27. package/dist/{chunk-ZSFOIBIH.js → chunk-CUH3FEWI.js} +2 -2
  28. package/dist/chunk-CUH3FEWI.js.map +1 -0
  29. package/dist/{chunk-NMZRAJLJ.cjs → chunk-FZTGWNVU.cjs} +2 -2
  30. package/dist/{chunk-NMZRAJLJ.cjs.map → chunk-FZTGWNVU.cjs.map} +1 -1
  31. package/dist/{chunk-RMBUP4XA.js → chunk-GMHYWVOG.js} +2 -2
  32. package/dist/{chunk-RMBUP4XA.js.map → chunk-GMHYWVOG.js.map} +1 -1
  33. package/dist/{chunk-OGD4YTZW.js → chunk-HPJ5SQEL.js} +3 -3
  34. package/dist/{chunk-OGD4YTZW.js.map → chunk-HPJ5SQEL.js.map} +1 -1
  35. package/dist/{chunk-FKNZ3VFB.cjs → chunk-HTB3D3FU.cjs} +3 -3
  36. package/dist/{chunk-FKNZ3VFB.cjs.map → chunk-HTB3D3FU.cjs.map} +1 -1
  37. package/dist/chunk-KVHLLR67.cjs +3 -0
  38. package/dist/chunk-KVHLLR67.cjs.map +1 -0
  39. package/dist/{chunk-Z4MIX43O.cjs → chunk-NIDVZMKV.cjs} +2 -2
  40. package/dist/chunk-NIDVZMKV.cjs.map +1 -0
  41. package/dist/chunk-NW5MM3Q6.js +3 -0
  42. package/dist/chunk-NW5MM3Q6.js.map +1 -0
  43. package/dist/{chunk-T24WU3LV.js → chunk-QXZVDT54.js} +2 -2
  44. package/dist/{chunk-T24WU3LV.js.map → chunk-QXZVDT54.js.map} +1 -1
  45. package/dist/chunk-SXLHFK7M.cjs +2 -0
  46. package/dist/{chunk-NH74IT7B.cjs.map → chunk-SXLHFK7M.cjs.map} +1 -1
  47. package/dist/{chunk-OBQC7KDY.cjs → chunk-TIWNKFSD.cjs} +2 -2
  48. package/dist/{chunk-OBQC7KDY.cjs.map → chunk-TIWNKFSD.cjs.map} +1 -1
  49. package/dist/chunk-TSVKHY5E.js +2 -0
  50. package/dist/{chunk-A34R65WT.js.map → chunk-TSVKHY5E.js.map} +1 -1
  51. package/dist/chunk-U5PPRJ3B.cjs +2 -0
  52. package/dist/chunk-U5PPRJ3B.cjs.map +1 -0
  53. package/dist/chunk-VOWMVLVV.cjs +2 -0
  54. package/dist/chunk-VOWMVLVV.cjs.map +1 -0
  55. package/dist/{chunk-F3UM5JNL.cjs → chunk-VZ4FEVWA.cjs} +2 -2
  56. package/dist/{chunk-F3UM5JNL.cjs.map → chunk-VZ4FEVWA.cjs.map} +1 -1
  57. package/dist/{chunk-TFZNEEJR.js → chunk-XAKFFIMQ.js} +3 -3
  58. package/dist/{chunk-TFZNEEJR.js.map → chunk-XAKFFIMQ.js.map} +1 -1
  59. package/dist/constants.cjs +1 -1
  60. package/dist/constants.js +1 -1
  61. package/dist/engine.cjs +1 -1
  62. package/dist/engine.d.cts +7 -7
  63. package/dist/engine.d.ts +7 -7
  64. package/dist/engine.js +1 -1
  65. package/dist/engine.worker.cjs +1 -1
  66. package/dist/engine.worker.js +1 -1
  67. package/dist/format.cjs +1 -1
  68. package/dist/format.d.cts +1 -1
  69. package/dist/format.d.ts +1 -1
  70. package/dist/format.js +1 -1
  71. package/dist/index.cjs +1 -1
  72. package/dist/index.d.cts +7 -7
  73. package/dist/index.d.ts +7 -7
  74. package/dist/index.js +1 -1
  75. package/dist/language.d.cts +6 -6
  76. package/dist/language.d.ts +6 -6
  77. package/dist/packages.cjs +1 -1
  78. package/dist/packages.d.cts +5 -5
  79. package/dist/packages.d.ts +5 -5
  80. package/dist/packages.js +1 -1
  81. package/dist/parser.d.cts +3 -3
  82. package/dist/parser.d.ts +3 -3
  83. package/dist/{pipeline-CADMN2D1.d.ts → pipeline-CLegjVrf.d.ts} +1 -1
  84. package/dist/{pipeline-C1-CJnFJ.d.cts → pipeline-DKNPr6s8.d.cts} +1 -1
  85. package/dist/resolvers.d.cts +1 -1
  86. package/dist/resolvers.d.ts +1 -1
  87. package/dist/testing.cjs +2 -2
  88. package/dist/testing.d.cts +6 -6
  89. package/dist/testing.d.ts +6 -6
  90. package/dist/testing.js +1 -1
  91. package/dist/uom.cjs +1 -1
  92. package/dist/uom.d.cts +1 -1
  93. package/dist/uom.d.ts +1 -1
  94. package/dist/uom.js +1 -1
  95. package/dist/vm.cjs +1 -1
  96. package/dist/vm.d.cts +4 -4
  97. package/dist/vm.d.ts +4 -4
  98. package/dist/vm.js +1 -1
  99. package/dist/worker.cjs +2 -2
  100. package/dist/worker.d.cts +5 -5
  101. package/dist/worker.d.ts +5 -5
  102. package/dist/worker.js +1 -1
  103. package/package.json +1 -1
  104. package/dist/chunk-54QMY2VL.cjs +0 -2
  105. package/dist/chunk-54QMY2VL.cjs.map +0 -1
  106. package/dist/chunk-5TCSFTZD.js +0 -2
  107. package/dist/chunk-5TCSFTZD.js.map +0 -1
  108. package/dist/chunk-5TVI2UPZ.cjs +0 -2
  109. package/dist/chunk-5TVI2UPZ.cjs.map +0 -1
  110. package/dist/chunk-6FBXJYWO.cjs +0 -3
  111. package/dist/chunk-6FBXJYWO.cjs.map +0 -1
  112. package/dist/chunk-A34R65WT.js +0 -2
  113. package/dist/chunk-KSOB5FCI.js +0 -3
  114. package/dist/chunk-KSOB5FCI.js.map +0 -1
  115. package/dist/chunk-NH74IT7B.cjs +0 -2
  116. package/dist/chunk-QP4VIEXZ.js.map +0 -1
  117. package/dist/chunk-Y5ZY6DPX.cjs +0 -2
  118. package/dist/chunk-Y5ZY6DPX.cjs.map +0 -1
  119. package/dist/chunk-Z4MIX43O.cjs.map +0 -1
  120. package/dist/chunk-ZISAN7NW.js +0 -2
  121. package/dist/chunk-ZISAN7NW.js.map +0 -1
  122. package/dist/chunk-ZSFOIBIH.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { I as IEnginePackage } from './PackageRegistry-Cj73Whk9.js';
1
+ import { I as IEnginePackage } from './PackageRegistry-ClAKDDOP.js';
2
2
 
3
3
  /**
4
4
  * Package load-time compatibility checking, the "detect overlapping
@@ -1,4 +1,4 @@
1
- import { I as IEnginePackage } from './PackageRegistry-DqzsjxGQ.cjs';
1
+ import { I as IEnginePackage } from './PackageRegistry-DLLVZW0S.cjs';
2
2
 
3
3
  /**
4
4
  * Package load-time compatibility checking, the "detect overlapping
@@ -1,14 +1,14 @@
1
- import { a as PrecedenceParser, b as PrefixParselet, I as InfixParselet } from './Parselet-Br1tHash.js';
1
+ import { a as PrecedenceParser, b as PrefixParselet, I as InfixParselet } from './Parselet-DkAFnfU2.js';
2
2
  import { M as MarkdownLineType, L as Lexer, e as TokenCategory, c as LexerVocabulary } from './Lexer-DPn5dfCH.js';
3
3
  import { IAsyncResolver } from './resolvers.js';
4
4
  import { T as TokenFusion, c as TokenNormalizer, a as NormalizerRule } from './TokenNormalizer-DAzPp-j1.js';
5
- import { b as VMCheckpointer, D as DependencyGraph, V as VM, h as DagSnapshot, i as EngineContext, S as ScopeManager, P as PluginFunctionHandler, A as AsConverter } from './VMBuiltins-BqkoJtHt.js';
6
- import { V as Value, b as ValueType, D as DatetimeGrain } from './Value-B55Hvn3e.js';
5
+ import { b as VMCheckpointer, D as DependencyGraph, V as VM, h as DagSnapshot, i as EngineContext, S as ScopeManager, P as PluginFunctionHandler, A as AsConverter } from './VMBuiltins-Bk8TQNF1.js';
6
+ import { V as Value, b as ValueType, D as DatetimeGrain } from './Value-wMuCzPn0.js';
7
7
  import { a as BytecodeProgram } from './BytecodeBuilder-DSWKZi4f.js';
8
8
  import { C as CalendarBackend } from './CalendarBackend-MdS3Bb4P.js';
9
9
  import { QueryClient } from '@tanstack/query-core';
10
10
  import { E as EngineError } from './EngineError-Bm4OYmw8.js';
11
- import { a as DiagnosticReportJSON, D as DiagnosticPipeline } from './pipeline-CADMN2D1.js';
11
+ import { a as DiagnosticReportJSON, D as DiagnosticPipeline } from './pipeline-CLegjVrf.js';
12
12
  import { T as Token } from './Token-D8f7yaz1.js';
13
13
  import { D as DateAmbiguity, E as EngineConfigOverride, a as EngineConfig } from './Configuration-BxriK9Kw.js';
14
14
 
@@ -1,14 +1,14 @@
1
- import { a as PrecedenceParser, b as PrefixParselet, I as InfixParselet } from './Parselet-DmMY2s9Y.cjs';
1
+ import { a as PrecedenceParser, b as PrefixParselet, I as InfixParselet } from './Parselet-ClR3Blwp.cjs';
2
2
  import { M as MarkdownLineType, L as Lexer, e as TokenCategory, c as LexerVocabulary } from './Lexer-DaWkCu84.cjs';
3
3
  import { IAsyncResolver } from './resolvers.cjs';
4
4
  import { T as TokenFusion, c as TokenNormalizer, a as NormalizerRule } from './TokenNormalizer-D382VSYh.cjs';
5
- import { b as VMCheckpointer, D as DependencyGraph, V as VM, h as DagSnapshot, i as EngineContext, S as ScopeManager, P as PluginFunctionHandler, A as AsConverter } from './VMBuiltins-Baa90D2v.cjs';
6
- import { V as Value, b as ValueType, D as DatetimeGrain } from './Value-B55Hvn3e.cjs';
5
+ import { b as VMCheckpointer, D as DependencyGraph, V as VM, h as DagSnapshot, i as EngineContext, S as ScopeManager, P as PluginFunctionHandler, A as AsConverter } from './VMBuiltins-ClXnXk9K.cjs';
6
+ import { V as Value, b as ValueType, D as DatetimeGrain } from './Value-wMuCzPn0.cjs';
7
7
  import { a as BytecodeProgram } from './BytecodeBuilder-DSWKZi4f.cjs';
8
8
  import { C as CalendarBackend } from './CalendarBackend-MdS3Bb4P.cjs';
9
9
  import { QueryClient } from '@tanstack/query-core';
10
10
  import { E as EngineError } from './EngineError-Bm4OYmw8.cjs';
11
- import { a as DiagnosticReportJSON, D as DiagnosticPipeline } from './pipeline-C1-CJnFJ.cjs';
11
+ import { a as DiagnosticReportJSON, D as DiagnosticPipeline } from './pipeline-DKNPr6s8.cjs';
12
12
  import { T as Token } from './Token-D8f7yaz1.cjs';
13
13
  import { D as DateAmbiguity, E as EngineConfigOverride, a as EngineConfig } from './Configuration-BxriK9Kw.cjs';
14
14
 
@@ -1,6 +1,6 @@
1
1
  import { B as BytecodeBuilder } from './BytecodeBuilder-DSWKZi4f.cjs';
2
2
  import { T as Token } from './Token-D8f7yaz1.cjs';
3
- import { D as DiagnosticPipeline } from './pipeline-C1-CJnFJ.cjs';
3
+ import { D as DiagnosticPipeline } from './pipeline-DKNPr6s8.cjs';
4
4
  import { C as CalendarBackend } from './CalendarBackend-MdS3Bb4P.cjs';
5
5
 
6
6
  /**
@@ -1,6 +1,6 @@
1
1
  import { B as BytecodeBuilder } from './BytecodeBuilder-DSWKZi4f.js';
2
2
  import { T as Token } from './Token-D8f7yaz1.js';
3
- import { D as DiagnosticPipeline } from './pipeline-CADMN2D1.js';
3
+ import { D as DiagnosticPipeline } from './pipeline-CLegjVrf.js';
4
4
  import { C as CalendarBackend } from './CalendarBackend-MdS3Bb4P.js';
5
5
 
6
6
  /**
@@ -1,8 +1,8 @@
1
- import { V as Value } from './Value-B55Hvn3e.js';
1
+ import { V as Value } from './Value-wMuCzPn0.js';
2
2
  import { U as UserFunctionDef, A as AnonymousBodyDef, a as BytecodeProgram } from './BytecodeBuilder-DSWKZi4f.js';
3
3
  import { C as CalendarBackend } from './CalendarBackend-MdS3Bb4P.js';
4
4
  import { E as EngineError } from './EngineError-Bm4OYmw8.js';
5
- import { D as DiagnosticPipeline } from './pipeline-CADMN2D1.js';
5
+ import { D as DiagnosticPipeline } from './pipeline-CLegjVrf.js';
6
6
 
7
7
  /**
8
8
  * Create a new VM instance with the given opcode registry and configurable limits.
@@ -1,8 +1,8 @@
1
- import { V as Value } from './Value-B55Hvn3e.cjs';
1
+ import { V as Value } from './Value-wMuCzPn0.cjs';
2
2
  import { U as UserFunctionDef, A as AnonymousBodyDef, a as BytecodeProgram } from './BytecodeBuilder-DSWKZi4f.cjs';
3
3
  import { C as CalendarBackend } from './CalendarBackend-MdS3Bb4P.cjs';
4
4
  import { E as EngineError } from './EngineError-Bm4OYmw8.cjs';
5
- import { D as DiagnosticPipeline } from './pipeline-C1-CJnFJ.cjs';
5
+ import { D as DiagnosticPipeline } from './pipeline-DKNPr6s8.cjs';
6
6
 
7
7
  /**
8
8
  * Create a new VM instance with the given opcode registry and configurable limits.
@@ -606,9 +606,25 @@ type DisplayBase = "hex" | "bin" | "oct";
606
606
  * `unit` slot, which is free for this type.
607
607
  */
608
608
  declare function hexValue(n: number | bigint, base?: DisplayBase): Value;
609
- /** Create a BigInt-typed Value (arbitrary-precision integer). */
609
+ /**
610
+ * Create a BigInt-typed Value (arbitrary-precision integer).
611
+ *
612
+ * Charged on birth by its byte size, so a doubling chain like `b(n) = n * n`
613
+ * nested deep trips the allocation budget (the running tally accumulates each
614
+ * product) rather than building a multi-megabyte integer. The `^` and `<<`
615
+ * operators refuse past their own bit ceiling before they reach here; multiply,
616
+ * which has no such ceiling, is bounded by this charge.
617
+ */
610
618
  declare function bigIntValue(n: bigint): Value;
611
- /** Create a String-typed Value. */
619
+ /**
620
+ * Create a String-typed Value.
621
+ *
622
+ * Charged on birth by its length, the one place every string is born, so a
623
+ * doubling chain like `d(s) = s + s` nested deep trips the allocation budget
624
+ * rather than building a near-gigabyte string. The charge is a no-op outside an
625
+ * evaluation (the formatter, snapshot restore and host callers), exactly like
626
+ * {@link matrixValue}.
627
+ */
612
628
  declare function stringValue(s: string): Value;
613
629
  /** Create a Unit-of-Measurement Value (typed number with unit annotation). */
614
630
  declare function uomValue(n: number, unit: string): Value;
@@ -606,9 +606,25 @@ type DisplayBase = "hex" | "bin" | "oct";
606
606
  * `unit` slot, which is free for this type.
607
607
  */
608
608
  declare function hexValue(n: number | bigint, base?: DisplayBase): Value;
609
- /** Create a BigInt-typed Value (arbitrary-precision integer). */
609
+ /**
610
+ * Create a BigInt-typed Value (arbitrary-precision integer).
611
+ *
612
+ * Charged on birth by its byte size, so a doubling chain like `b(n) = n * n`
613
+ * nested deep trips the allocation budget (the running tally accumulates each
614
+ * product) rather than building a multi-megabyte integer. The `^` and `<<`
615
+ * operators refuse past their own bit ceiling before they reach here; multiply,
616
+ * which has no such ceiling, is bounded by this charge.
617
+ */
610
618
  declare function bigIntValue(n: bigint): Value;
611
- /** Create a String-typed Value. */
619
+ /**
620
+ * Create a String-typed Value.
621
+ *
622
+ * Charged on birth by its length, the one place every string is born, so a
623
+ * doubling chain like `d(s) = s + s` nested deep trips the allocation budget
624
+ * rather than building a near-gigabyte string. The charge is a no-op outside an
625
+ * evaluation (the formatter, snapshot restore and host callers), exactly like
626
+ * {@link matrixValue}.
627
+ */
612
628
  declare function stringValue(s: string): Value;
613
629
  /** Create a Unit-of-Measurement Value (typed number with unit annotation). */
614
630
  declare function uomValue(n: number, unit: string): Value;
@@ -1,5 +1,5 @@
1
- import {b as b$2,a as a$5}from'./chunk-RU3KGJRA.js';import {a as a$3}from'./chunk-RMDCGYZM.js';import {a as a$6}from'./chunk-MIQBJGGR.js';import {c as c$1,a as a$2,b as b$5}from'./chunk-RMBUP4XA.js';import {a as a$4,b as b$3,c as c$9}from'./chunk-JP4JMQOG.js';import {c as c$b,a as a$b}from'./chunk-TFZNEEJR.js';import {k,w,s,r,q as q$1,o,l,p,n as n$1,a as a$7,b as b$9,e,t as t$1,v,j as j$2,u as u$1,m as m$1}from'./chunk-ZISAN7NW.js';import {d as d$1}from'./chunk-U5MESNRT.js';import {c as c$5,d as d$2,b as b$a}from'./chunk-DB5ISONG.js';import {b as b$8}from'./chunk-76F3LCIL.js';import {c as c$7,a as a$8,b as b$c}from'./chunk-TCZSPH4A.js';import {O,c as c$3,B as B$1,J,L,M,b as b$7,l as l$1}from'./chunk-QP4VIEXZ.js';import {_ as _$1,da}from'./chunk-ZSFOIBIH.js';import {b as b$4}from'./chunk-EOO6M65F.js';import {P,n,O as O$1,l as l$2,L as L$1,u,N,M as M$1,t,s as s$1,r as r$1,j as j$1,k as k$1,m,g}from'./chunk-A34R65WT.js';import {a as a$1,c as c$4,b}from'./chunk-T24WU3LV.js';import {c as c$2,b as b$1}from'./chunk-6NL7RBAG.js';import {b as b$6,c as c$8}from'./chunk-JPFCXLJV.js';import {c as c$6,a as a$9}from'./chunk-APYRNAU2.js';import {a,c as c$a}from'./chunk-FAO6DQ74.js';import {a as a$a}from'./chunk-LHLW7JLS.js';import {c,d,b as b$b}from'./chunk-6G2NES2I.js';function Xt(n,e,t,r,i){let s=t[e],o=r[e];if(!s||!o)return;let l=new Set(Object.keys(s));for(let a of Object.keys(o))l.has(a)&&i.push({kind:n,severity:"warning",detail:`Both "${t.name}" and "${r.name}" register a ${e==="prefixParselets"?"prefix":"infix"} parselet for token type "${a}" \u2014 the later-registered one silently wins.`,packages:[t.name,r.name]});}function Jt(n,e){let t=[];if(Xt("prefixParseletTokenType","prefixParselets",n,e,t),Xt("infixParseletTokenType","infixParselets",n,e,t),n.phrases&&e.phrases)for(let[s,o]of Object.entries(e.phrases)){let l=n.phrases[s];l!==void 0&&l!==o&&t.push({kind:"phrase",severity:"warning",detail:`Both "${n.name}" (-> "${l}") 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(l=>l.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 l=r.keywords[s];l!==void 0&&l!==o&&t.push({kind:"lexerKeyword",severity:"error",detail:`Both "${n.name}" (-> "${l}") 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 l=r.operators[s];l!==void 0&&l!==o&&t.push({kind:"lexerOperator",severity:"error",detail:`Both "${n.name}" (-> "${l}") 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 l=n.tokenCategories[s];l!==void 0&&l!==o&&t.push({kind:"tokenCategory",severity:"info",detail:`Both "${n.name}" (-> "${l}") 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 or(n,e){let t=[];for(let r of e)r===n||r.name===n.name||t.push(...Jt(r,n));return {compatible:!t.some(r=>r.severity==="error"),conflicts:t}}var Ee=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 l=s.get(o);l&&l!==e&&l.name!==e.name&&t.add(l);};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(...Jt(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 Ln=/(\d+)\.(\d+)\.(\d+)/,On=/^\d+$/;function Zt(n){let e=Ln.exec(n.trim());return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function In(n,e){return n[0]-e[0]||n[1]-e[1]||n[2]-e[2]}function Me(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(!On.test(e[r]))return null;t[r]=Number(e[r]);}return [t[0],t[1],t[2]]}function Dn([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 Mn([n,e,t]){return [{op:">=",v:[n,e,t]},{op:"<",v:[n,e+1,0]}]}function Vn(n){if(n===""||n==="*"||n==="x"||n==="X")return [];if(n[0]==="^"){let i=Me(n.slice(1));return i&&Dn(i)}if(n[0]==="~"){let i=Me(n.slice(1));return i&&Mn(i)}let e=/^(>=|<=|>|<|=)/.exec(n),t=e?e[1]:"=",r=Me(e?n.slice(e[1].length):n);return r&&[{op:t,v:r}]}function en(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=Vn(s);if(o===null)return null;i.push(...o);}e.push(i);}return e}function tn(n){return en(n.trim())!==null}function Bn(n,e){let t=In(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 nn(n,e){let t=en(e.trim());return t===null?false:t.some(r=>r.every(i=>Bn(n,i)))}function Fn(n,e=a$1){if(!n.engineVersion)return {compatible:true};if(!tn(n.engineVersion))return {compatible:false,reason:"invalid-range",declaredRange:n.engineVersion,engineVersion:e};let t=Zt(e);return t===null||!nn(t,n.engineVersion)?{compatible:false,reason:"range-not-satisfied",declaredRange:n.engineVersion,engineVersion:e}:{compatible:true}}function rn(n,e=a$1){let t=Fn(n,e);if(!t.compatible)throw t.reason==="invalid-range"?c.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.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 ee="solve-engine/snapshot",Q=1;function W(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.validation({code:V.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 V={SNAPSHOT_VERSION_MISMATCH:"SNAPSHOT_VERSION_MISMATCH",SNAPSHOT_MALFORMED:"SNAPSHOT_MALFORMED",SNAPSHOT_UNSUPPORTED_VALUE:"SNAPSHOT_UNSUPPORTED_VALUE"};function sn(n){return {coef:n.coef.toString(),scale:n.scale}}function on(n){return {coef:BigInt(n.coef),scale:n.scale}}function Un(n){return {n:n.n.toString(),d:n.d.toString()}}function _n(n){return {n:BigInt(n.n),d:BigInt(n.d)}}function an(n){return g[n]??String(n)}function Ve(n,e){throw c.validation({code:V.SNAPSHOT_UNSUPPORTED_VALUE,message:`A ${an(n)} value (${e}) cannot be included in a snapshot yet.`,expected:"a concrete number, string, boolean, unit, range, matrix, bigint, or money value",found:`${an(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 Be(n,e){switch(n.type){case 0:{let t={t:0,v:W(n.value)};return n.exact!==void 0&&(t.exact=sn(n.exact)),n.rational!==void 0&&(t.rational=Un(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:W(t),base:n.unit}}case 2:return {t:2,v:n.value.toString()};case 3:return {t:3,v:n.value};case 4:{let t={t:4,v:W(n.value)};return n.grain!==void 0&&(t.g=n.grain),n.zone!==void 0&&(t.z=n.zone),t}case 5:return {t:5,v:W(n.value)};case 6:{let t={t:6,v:W(n.value),unit:n.unit??""};return n.exact!==void 0&&(t.exact=sn(n.exact)),t}case 7:{let t=n.value;t.hasSymbolic&&Ve(9,`${e} (symbolic matrix cell)`);let r=t.data.map(i=>zn(i,e));return {t:7,rows:t.rows,cols:t.cols,data:r}}case 8:{let t=n.value;return {t:8,min:W(t.min),max:W(t.max)}}case 10:return {t:10,v:n.value};case 13:return {t:13,code:n.value,message:n.unit??""};default:return Ve(n.type,e)}}function zn(n,e){return typeof n=="boolean"?n:typeof n=="number"?W(n):Ve(9,`${e} (symbolic matrix cell)`)}function Fe(n){switch(n.t){case 0:{let e=new m(0,$(n.v));return n.exact!==void 0&&(e.exact=on(n.exact)),n.rational!==void 0&&(e.rational=_n(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:{let e=new m(4,$(n.v));return n.g!==void 0&&(e.grain=n.g),n.z!==void 0&&(e.zone=n.z),e}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=on(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.validation({code:V.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 pe(n){let e={opcodes:Array.from(n.opcodes),numbers:Array.from(n.numbers,W),strings:n.strings.slice(),hasAsync:n.hasAsync};return n.constants&&(e.constants=Array.from(n.constants.entries())),n.userFunctionBodies&&(e.userFunctionBodies=n.userFunctionBodies.map(Ue)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:pe(t.program)}))),e}function fe(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(_e)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:fe(t.program)}))),e}function Ue(n){return {name:n.name,params:n.params.slice(),program:pe(n.program)}}function _e(n){return {name:n.name,params:n.params.slice(),program:fe(n.program)}}function dn(n){if(typeof n!="object"||n===null)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:"fromJSON was given something that is not a snapshot object.",expected:`an object produced by ExpressionEngine.toJSON() with format "${ee}"`,found:n===null?"null":typeof n});let e=n;if(e.format!==ee)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:`This object is not a solve-engine snapshot (its "format" is ${JSON.stringify(e.format)}).`,expected:`format "${ee}"`,found:JSON.stringify(e.format)});if(e.version!==Q)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:`This snapshot was written for format version ${e.version}, but this engine restores version ${Q}.`,expected:`snapshot version ${Q}`,found:`version ${e.version}`,suggestion:"Regenerate the snapshot with a matching engine version, or re-evaluate the document from source.",context:{snapshotVersion:e.version,readerVersion:Q,engineVersion:e.engineVersion}});Wn(n);}var ln=32;function $n(n){return n===null?"null":Array.isArray(n)?`an array of ${n.length}`:typeof n=="object"?"an object":`${typeof n} ${JSON.stringify(n)}`.slice(0,80)}function h(n,e,t){throw c.validation({code:V.SNAPSHOT_MALFORMED,message:`Snapshot is malformed at ${n}: expected ${e}.`,expected:e,found:$n(t),suggestion:"Regenerate the snapshot with ExpressionEngine.toJSON(), or re-evaluate the document from source.",context:{location:n}})}function H(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function j(n){return typeof n=="number"||n==="NaN"||n==="Infinity"||n==="-Infinity"}function de(n){return typeof n=="string"&&/^-?\d+$/.test(n)}function xe(n,e){(!Array.isArray(n)||!n.every(t=>typeof t=="string"))&&h(e,"an array of strings",n);}function cn(n,e){(!H(n)||!de(n.coef)||typeof n.scale!="number")&&h(e,"a decimal as { coef: digits, scale: number }",n);}function jn(n,e){(!H(n)||!de(n.n)||!de(n.d))&&h(e,"a rational as { n: digits, d: digits }",n);}function un(n,e){switch(H(n)||h(e,"a serialised value object",n),n.t){case 0:j(n.v)||h(`${e}.v`,"a number",n.v),n.exact!==void 0&&cn(n.exact,`${e}.exact`),n.rational!==void 0&&jn(n.rational,`${e}.rational`);return;case 1:(n.big?!de(n.v):!j(n.v))&&h(`${e}.v`,n.big?"an integer string":"a number",n.v),n.base!==void 0&&typeof n.base!="string"&&h(`${e}.base`,"a base name",n.base);return;case 2:de(n.v)||h(`${e}.v`,"an integer string",n.v);return;case 3:typeof n.v!="string"&&h(`${e}.v`,"a string",n.v);return;case 4:j(n.v)||h(`${e}.v`,"a number",n.v),n.g!==void 0&&n.g!=="date"&&n.g!=="datetime"&&n.g!=="instant"&&h(`${e}.g`,'one of "date", "datetime" or "instant"',n.g),n.z!==void 0&&typeof n.z!="string"&&h(`${e}.z`,"a zone reference",n.z);return;case 5:j(n.v)||h(`${e}.v`,"a number",n.v);return;case 6:j(n.v)||h(`${e}.v`,"a number",n.v),typeof n.unit!="string"&&h(`${e}.unit`,"a unit name",n.unit),n.exact!==void 0&&cn(n.exact,`${e}.exact`);return;case 7:{let{rows:t,cols:r,data:i}=n;(!Number.isInteger(t)||t<0)&&h(`${e}.rows`,"a non-negative integer",t),(!Number.isInteger(r)||r<0)&&h(`${e}.cols`,"a non-negative integer",r),(!Array.isArray(i)||i.length!==t*r)&&h(`${e}.data`,`an array of ${t} \xD7 ${r} cells`,i),i.every(s=>typeof s=="boolean"||j(s))||h(`${e}.data`,"numeric or boolean cells",i);return}case 8:(!j(n.min)||!j(n.max))&&h(e,"a range with numeric min and max",n);return;case 10:typeof n.v!="boolean"&&h(`${e}.v`,"a boolean",n.v);return;case 13:(typeof n.code!="string"||typeof n.message!="string")&&h(e,"an error with a string code and message",n);return;default:return}}function Se(n,e,t){if(t>ln&&h(e,`function bodies nested at most ${ln} deep`,"deeper nesting"),H(n)||h(e,"a serialised program object",n),(!Array.isArray(n.opcodes)||!n.opcodes.every(r=>Number.isInteger(r)&&r>=0&&r<=255))&&h(`${e}.opcodes`,"an array of bytes (integers 0 to 255)",n.opcodes),(!Array.isArray(n.numbers)||!n.numbers.every(j))&&h(`${e}.numbers`,"an array of numbers",n.numbers),xe(n.strings,`${e}.strings`),typeof n.hasAsync!="boolean"&&h(`${e}.hasAsync`,"a boolean",n.hasAsync),n.constants!==void 0){let r=i=>Array.isArray(i)&&i.length===2&&typeof i[0]=="number"&&typeof i[1]=="number";(!Array.isArray(n.constants)||!n.constants.every(r))&&h(`${e}.constants`,"an array of [number, number] pairs",n.constants);}n.userFunctionBodies!==void 0&&(Array.isArray(n.userFunctionBodies)||h(`${e}.userFunctionBodies`,"an array of functions",n.userFunctionBodies),n.userFunctionBodies.forEach((r,i)=>pn(r,`${e}.userFunctionBodies[${i}]`,t+1))),n.anonymousBodies!==void 0&&(Array.isArray(n.anonymousBodies)||h(`${e}.anonymousBodies`,"an array of bodies",n.anonymousBodies),n.anonymousBodies.forEach((r,i)=>{let s=`${e}.anonymousBodies[${i}]`;H(r)||h(s,"a body object",r),xe(r.params,`${s}.params`),Se(r.program,`${s}.program`,t+1);}));}function pn(n,e,t){H(n)||h(e,"a function object",n),typeof n.name!="string"&&h(`${e}.name`,"a function name",n.name),xe(n.params,`${e}.params`),Se(n.program,`${e}.program`,t);}function Wn(n){n.locale!==void 0&&typeof n.locale!="string"&&h("locale","a locale code",n.locale),H(n.variables)||h("variables","an object of values by name",n.variables);for(let[e,t]of Object.entries(n.variables))un(t,`variables.${e}`);Array.isArray(n.userFunctions)||h("userFunctions","an array of functions",n.userFunctions),n.userFunctions.forEach((e,t)=>pn(e,`userFunctions[${t}]`,1)),Array.isArray(n.lineCache)||h("lineCache","an array of cached lines",n.lineCache),n.lineCache.forEach((e,t)=>{let r=`lineCache[${t}]`;H(e)||h(r,"a cached line",e),Number.isInteger(e.line)||h(`${r}.line`,"a line number",e.line),typeof e.expression!="string"&&h(`${r}.expression`,"the line's expression text",e.expression),un(e.result,`${r}.result`),Se(e.bytecode,`${r}.bytecode`,1),xe(e.reads,`${r}.reads`),e.writeVar!==null&&typeof e.writeVar!="string"&&h(`${r}.writeVar`,"a variable name or null",e.writeVar);}),Array.isArray(n.bytecodeCache)||h("bytecodeCache","an array of compiled expressions",n.bytecodeCache),n.bytecodeCache.forEach((e,t)=>{let r=`bytecodeCache[${t}]`;(!H(e)||typeof e.expression!="string")&&h(r,"an { expression, program } pair",e),Se(e.program,`${r}.program`,1);});}var fn=null;function mr(n){fn=n;}function ze(){return fn}var hn=3e4,gn=50,ke=class{constructor(e){this.workers=[];this.nextWorker=0;this.nextId=1;this.pendingBatches=new Map;this.terminated=false;this._available=null;this.poolSize=Math.min(e??this.defaultPoolSize(),4);}defaultPoolSize(){return typeof navigator<"u"&&navigator.hardwareConcurrency?Math.min(navigator.hardwareConcurrency,4):2}isAvailable(){if(this.terminated)return false;if(this._available!==null)return this._available;if(typeof Worker>"u")return this._available=false,false;try{let e=ze();return e===null?(this._available=!1,!1):(e().terminate(),this._available=!0,!0)}catch{return this._available=false,false}}executeBatch(e,t){if(!this.isAvailable())return;if(e.length===0)return Promise.resolve([]);this.ensureWorkers();let r=[];for(let a of e){let c=t.get(a);if(!c||c.bytecode.opcodes.length===0)continue;let u=c.bytecode.opcodes,d=c.bytecode.numbers,g=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength),y=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);r.push({lineNumber:a,opcodesBuffer:g,numbersBuffer:y,opcodesLength:u.length,numbersLength:d.length,strings:[...c.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.nextWorkerIndex(),l=this.workers[o];return new Promise(a=>{let c=setTimeout(()=>{this.pendingBatches.has(s)&&this.failWorker(o,"WORKER_TIMEOUT",`Evaluation did not finish within ${hn/1e3} seconds; the worker was replaced`);},hn);this.pendingBatches.set(s,{id:s,lineNumbers:r.map(u=>u.lineNumber),workerIndex:o,resolve:u=>{clearTimeout(c),a(u);}}),l.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++)this.spawnWorker(e);}spawnWorker(e){let t=ze();if(t===null)return;let r=t();r.onmessage=i=>{this.handleWorkerMessage(i.data);},r.onerror=i=>{console.error(`[ExecutionPool] Worker ${e} error:`,i.message),this.failWorker(e,"WORKER_EXECUTION_ERROR",`Worker failed: ${i.message}`);},this.workers[e]=r;}failWorker(e,t,r){if(this.workers.length!==0){this.workers[e]?.terminate(),this.terminated||this.spawnWorker(e);for(let[i,s]of this.pendingBatches)s.workerIndex===e&&(this.pendingBatches.delete(i),s.resolve(Hn(s.lineNumbers,t,r)));}}nextWorkerIndex(){let e=this.nextWorker;return this.nextWorker=(this.nextWorker+1)%this.workers.length,e}handleWorkerMessage(e){if(e.type!=="EXECUTE_RESULT")return;let t=this.pendingBatches.get(e.id);t&&(this.pendingBatches.delete(e.id),t.resolve(e.results));}};function Hn(n,e,t){return n.map(r=>({lineNumber:r,valueType:13,value:0,unit:t,isPending:false,errorCode:e}))}function mn(n$1){switch(n$1.valueType){case 0:return n(n$1.value);case 1:return r$1(n$1.value);case 2:return s$1(BigInt(n$1.value));case 3:return t(String(n$1.value));case 4:return M$1(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$1(n$1.value!==0);case 12:return O$1(n$1.queryKey??"");case 13:return P(n$1.errorCode??"WORKER_EXECUTION_ERROR",n$1.unit??"Unknown worker error");default:return n(n$1.value)}}var te=class te{constructor(e,t,r,i=te.DEFAULT_HIGH_WATER_MARK){this.pending=new Map;this.collapsed=0;this.scheduled=false;this.cleared=false;this.executionPool=null;this.workerOffloadDispatchCount=0;this._eventStream=null;this._streamController=null;this._testCaptures=null;this.onLineResult=null;this.checkpointer=null;this.warnedAboutMissingHook=false;this.flushesWithoutYielding=0;this.yieldProbeArmed=false;this.dag=e,this.lineCache=t,this.vm=r,this.highWaterMark=i;}warnIfUnwired(){this.onLineResult||this.listenerCount>0||this.warnedAboutMissingHook||(this.warnedAboutMissingHook=true,console.warn("[solve-engine] An async result resolved, but nothing is listening for it: no reader is attached to engine.getEventStream() and AsyncResolutionBatcher.onLineResult is not set. The value is in the cache; without one of those the line keeps showing as pending. Read the event stream and re-evaluate the lines it names (see the async guide), or set onLineResult to mirror resolved values into your own state. This warning appears once per batcher."));}createEventStream(){return new ReadableStream({start:e=>{this._streamController=e;},cancel:()=>{this._streamController=null;}},new CountQueuingStrategy({highWaterMark:this.highWaterMark}))}eventStream(){return this._eventStream??(this._eventStream=this.createEventStream()),this._eventStream}add(e){this.cleared=false;let t=`${e.packageId}:${e.queryKey}`;if(this.pending.has(t)){this.collapsed++;return}if(this.pending.set(t,e),!this.scheduled){this.scheduled=true;let r=this.flushesWithoutYielding>=te.MAX_CHAINED_FLUSHES,i=()=>{try{this.flush();}catch(s){let o=d(s);console.error(`[AsyncResolutionBatcher] flush() failed unexpectedly \u2014 this should never happen; please report: ${o.format()}`);}};r?setTimeout(i,0):queueMicrotask(i);}}getEventStream(){return this.eventStream()}get pendingCount(){return this.pending.size}get dedupCount(){return this.collapsed}get listenerCount(){return this._eventStream?.locked?1:0}get workerOffloadCount(){return this.workerOffloadDispatchCount}clearAll(){this.pending=new Map,this.collapsed=0,this.scheduled=false,this.cleared=true,this._testCaptures=null,this.onLineResult=null;try{this._streamController?.close();}catch{}this._streamController=null,this._eventStream=null,this.executionPool&&(this.executionPool.clear(),this.executionPool=null),this.workerOffloadDispatchCount=0;}flush(){if(this.scheduled=false,this.cleared||this.pending.size===0)return;this.flushesWithoutYielding++,this.yieldProbeArmed||(this.yieldProbeArmed=true,setTimeout(()=>{this.flushesWithoutYielding=0,this.yieldProbeArmed=false;},0));let e=this.pending;this.pending=new Map,this.collapsed=0;let t=[],r=[];for(let a of e.values())a.isError?t.push(a):r.push(a);for(let a of t)a.signal.aborted||this.notifyListeners({type:"error",queryKey:a.queryKey,packageId:a.packageId,error:a.error??new Error("Unknown async resolution error")});let i=new Set,s=[],o=[...r,...t];for(let a of o){if(a.signal.aborted)continue;s.push(a.queryKey);let c=this.dag.getAffectedLinesByDataSource(a.packageId,[a.queryKey]);for(let u of c)i.add(u);}{let a=[...i],c=u=>{i.has(u)||(i.add(u),a.push(u));};for(let u=0;u<a.length;u++){let d=a[u];for(let g of this.dag.getWrites(d))for(let y of this.dag.getAffectedLines(g))c(y);for(let g of this.dag.getAffectedLinesByPosition(d))c(g);}}if(i.size===0){this.notifyListeners({type:"lines-updated",lineNumbers:[],affectedQueryKeys:s});return}let l=this.topologicalSort(Array.from(i));if(l.length>gn){let a=new Map;for(let c of l)a.set(c,this.lineCache.getEntryForLine(c));this.reExecuteViaWorkerPool(l,a,s).catch(c=>{let u=d(c);console.error(`[AsyncResolutionBatcher] reExecuteViaWorkerPool() failed unexpectedly: ${u.format()}`);});return}this.reExecuteMainThread(l,s);}topologicalSort(e){if(e.length<=1)return e;let t=new Map,r=new Map,i=new Map;for(let l of e)t.set(l,0),r.set(l,[]);for(let l of e){let a=this.dag.getWrites(l);for(let c of a)i.set(c,l);}for(let l of e){let a=this.dag.getReads(l);for(let c of a){let u=i.get(c);u!==void 0&&u!==l&&(r.get(u).push(l),t.set(l,(t.get(l)??0)+1));}}let s=[];for(let[l,a]of t)a===0&&s.push(l);if(s.length===0&&e.length>0)return [...e].sort((l,a)=>l-a);let o=[];for(let l=0;l<s.length;l++){let a=s[l];o.push(a);for(let c of r.get(a)??[]){let u=(t.get(c)??1)-1;t.set(c,u),u===0&&s.push(c);}}if(o.length<e.length){let l=new Set(o),a=e.filter(c=>!l.has(c)).sort((c,u)=>c-u);o.push(...a);}return o}async reExecuteViaWorkerPool(e,t,r){this.executionPool||(this.executionPool=new ke);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 l of s){let a=t.get(l.lineNumber);if(!a||l.isPending)continue;let c=mn(l);a.result=c,this.warnIfUnwired(),this.onLineResult?.(l.lineNumber,c),o.push(l.lineNumber);}this.cleared||(o.length>0||r.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:o,affectedQueryKeys:r});}prepareSweep(e){if(e.length===0)return null;let t=e[0];for(let r=1;r<e.length;r++)e[r]<t&&(t=e[r]);return this.checkpointer.restoreTo(t-1),{at:t-1}}sweepTo(e,t){for(let r=e.at+1;r<t;r++)this.checkpointer.applyCheckpointAt(r);t>e.at&&(e.at=t);}reExecuteMainThread(e,t,r){let i=[],s=this.checkpointer!==null?this.prepareSweep(e):null;for(let o of e){s!==null&&this.sweepTo(s,o);let l=r?r.get(o):this.lineCache.getEntryForLine(o);if(!l||l.bytecode.opcodes.length===0)continue;let a=this.vm.getStack().length;try{let c=c$1(l.bytecode,this.vm,void 0,void 0,{lineIndex:o,networkEnabled:this.vm.context.networkEnabled,calendar:this.vm.context.calendar});for(;this.vm.getStack().length>a;)this.vm.pop();if(c.type==="value")s!==null&&l.writeVariable!==null&&this.checkpointer.updateCheckpointAt(o,[l.writeVariable]),l.result=c.value,this.warnIfUnwired(),this.onLineResult?.(o,c.value),i.push(o);else if(c.type==="error"){let u=P(c.error.code,c.error.message);l.result=u,this.warnIfUnwired(),this.warnIfUnwired(),this.onLineResult?.(o,u),i.push(o);}}catch(c){for(;this.vm.getStack().length>a;)this.vm.pop();let u=d(c),d$1=P(u.code,u.message);l.result=d$1,this.warnIfUnwired(),this.onLineResult?.(o,d$1),i.push(o);}}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.eventStream(),this._streamController)try{this._streamController.enqueue(e);}catch{}}};te.DEFAULT_HIGH_WATER_MARK=64,te.MAX_CHAINED_FLUSHES=4;var Ce=te;function $e(n$1,e){if(n$1.length>e.maxExpressionLength){let t=c.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 je(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.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 he(n){return n.type==="IDENT"||n.type==="UNIT"}function Kn(n){return n.type==="NUMBER"||n.type==="TO"||n.type==="IN"||n.type==="RPAREN"}function yn(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 Gn(n){let e=new Set;for(let t=0;t<n.length;t++){if(!he(n[t])||t>0&&n[t-1].type==="COLON"||n[t+1]?.type!=="LPAREN")continue;let r=yn(n,t+1);if(r!==null&&n[r+1]?.type==="EQUALS")for(let i=t+2;i<r;i++)he(n[i])&&e.add(n[i].value);}return e}function qn(n,e){if(n[e+1]?.type!=="LINE_REF")return -1;let t=n[e+2];if(!(t!==void 0&&(t.type==="FOR_DURATION"||t.type==="IDENT"&&t.value.toLowerCase()==="for")))return -1;let i=n[e+3];return i===void 0||i.type!=="IDENT"&&i.type!=="UNIT"?-1:e+3}function Te(n){let e=[],t=[],r=Gn(n),i=null;for(let s=0;s<n.length;s++){let o=n[s];if(o.type==="GOAL_SEEK"){let l=qn(n,s);l!==-1&&(i??(i=new Set)).add(l);continue}if(o.type==="GLOBAL"){if(s+2<n.length&&n[s+1].type==="COLON"&&he(n[s+2])){let l=O(n[s+2].value);e.push(l),s+3<n.length&&n[s+3].type==="EQUALS"&&t.push(l);}continue}if(o.type==="COLON"){if(s>0&&n[s-1].type==="GLOBAL")continue;if(s+1<n.length&&he(n[s+1])){let l=n[s+1].value;e.push(l),s+2<n.length&&n[s+2].type==="EQUALS"&&t.push(l);}}if(he(o)){if(s>0&&n[s-1].type==="COLON"||i!==null&&i.has(s)||o.type==="UNIT"&&s>0&&Kn(n[s-1])||r.has(o.value))continue;if(n[s+1]?.type==="LPAREN"){let a=yn(n,s+1);if(a!==null&&n[a+1]?.type==="EQUALS"){e.push(o.value),t.push(o.value);continue}}e.push(o.value);let l=n[s+1]?.type;(l==="EQUALS"||l==="PLUS_EQUALS"||l==="MINUS_EQUALS")&&t.push(o.value);}}return {reads:e,writes:t}}function Lr(n){return c$2.classifyLine(n).skip}function Or(n,e){return c$2.findInlineSolves(n).map(r=>({start:r.start,end:r.end,expression:r.expression,lineNumber:e,columnNumber:r.columnNumber}))}var q=class{constructor(e,t,r,i){this.result=e;this.bytecode=t;this.readVariables=r;this.writeVariable=i;}},we=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 We(n,e){let t=e.fields(n),r=String(t.month0+1).padStart(2,"0"),i=String(t.day).padStart(2,"0");return `${t.year}-${r}-${i}`}function Yn(n,e){if(n instanceof Date)return We(n.getTime(),e);if(typeof n=="number")return Number.isFinite(n)?We(n,e):null;let t=/^(\d{4})-(\d{2})-(\d{2})/.exec(n.trim());return t?`${t[1]}-${t[2]}-${t[3]}`:null}function vn(n,e){if(n===void 0)return;if(typeof n=="function")return r=>n(new Date(r));let t=new Set;for(let r of n){let i=Yn(r,e);i!==null&&t.add(i);}return r=>t.has(We(r,e))}function Qn(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 Re=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&&Qn(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 B=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(),l=typeof process<"u"&&process.hrtime?process.hrtime(s):void 0,a=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,c=l?l[0]*1e9+l[1]:(performance.now()-s)*1e6,u=i&&a?a.heapUsed-i.heapUsed:0,d={stage:e,allocCount:0,allocBytes:u,objectCounts:{},wallTimeNs:c,...r};return {result:o,alloc:d}}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(`
1
+ import {b as b$2,a as a$5}from'./chunk-RU3KGJRA.js';import {a as a$3}from'./chunk-RMDCGYZM.js';import {a as a$6}from'./chunk-MIQBJGGR.js';import {c as c$1,a as a$2,b as b$5}from'./chunk-GMHYWVOG.js';import {a as a$4,b as b$3,c as c$9}from'./chunk-JP4JMQOG.js';import {c as c$b,a as a$b}from'./chunk-XAKFFIMQ.js';import {k,w,s,r,q as q$1,o,l,p,n as n$1,a as a$7,b as b$9,e,t as t$1,v,j as j$2,u as u$1,m as m$1}from'./chunk-4H27GUVY.js';import {d as d$1}from'./chunk-U5MESNRT.js';import {c as c$5,d as d$2,b as b$a}from'./chunk-DB5ISONG.js';import {b as b$8}from'./chunk-76F3LCIL.js';import {c as c$7,a as a$8,b as b$c}from'./chunk-TCZSPH4A.js';import {O,c as c$3,B as B$1,J,L,M,b as b$7,l as l$1}from'./chunk-36JGHDZR.js';import {_ as _$1,da}from'./chunk-CUH3FEWI.js';import {b as b$4}from'./chunk-EOO6M65F.js';import {P,n,O as O$1,l as l$2,L as L$1,u,N,M as M$1,t,s as s$1,r as r$1,j as j$1,k as k$1,m,g}from'./chunk-TSVKHY5E.js';import {a as a$1,c as c$4,b}from'./chunk-QXZVDT54.js';import {c as c$2,b as b$1}from'./chunk-6NL7RBAG.js';import {b as b$6,c as c$8}from'./chunk-JPFCXLJV.js';import {c as c$6,a as a$9}from'./chunk-APYRNAU2.js';import {a,c as c$a}from'./chunk-FAO6DQ74.js';import {a as a$a}from'./chunk-LHLW7JLS.js';import {c,d,b as b$b}from'./chunk-6G2NES2I.js';function Xt(n,e,t,r,i){let s=t[e],o=r[e];if(!s||!o)return;let l=new Set(Object.keys(s));for(let a of Object.keys(o))l.has(a)&&i.push({kind:n,severity:"warning",detail:`Both "${t.name}" and "${r.name}" register a ${e==="prefixParselets"?"prefix":"infix"} parselet for token type "${a}" \u2014 the later-registered one silently wins.`,packages:[t.name,r.name]});}function Jt(n,e){let t=[];if(Xt("prefixParseletTokenType","prefixParselets",n,e,t),Xt("infixParseletTokenType","infixParselets",n,e,t),n.phrases&&e.phrases)for(let[s,o]of Object.entries(e.phrases)){let l=n.phrases[s];l!==void 0&&l!==o&&t.push({kind:"phrase",severity:"warning",detail:`Both "${n.name}" (-> "${l}") 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(l=>l.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 l=r.keywords[s];l!==void 0&&l!==o&&t.push({kind:"lexerKeyword",severity:"error",detail:`Both "${n.name}" (-> "${l}") 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 l=r.operators[s];l!==void 0&&l!==o&&t.push({kind:"lexerOperator",severity:"error",detail:`Both "${n.name}" (-> "${l}") 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 l=n.tokenCategories[s];l!==void 0&&l!==o&&t.push({kind:"tokenCategory",severity:"info",detail:`Both "${n.name}" (-> "${l}") 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 or(n,e){let t=[];for(let r of e)r===n||r.name===n.name||t.push(...Jt(r,n));return {compatible:!t.some(r=>r.severity==="error"),conflicts:t}}var Ee=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 l=s.get(o);l&&l!==e&&l.name!==e.name&&t.add(l);};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(...Jt(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 Ln=/(\d+)\.(\d+)\.(\d+)/,On=/^\d+$/;function Zt(n){let e=Ln.exec(n.trim());return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function In(n,e){return n[0]-e[0]||n[1]-e[1]||n[2]-e[2]}function Me(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(!On.test(e[r]))return null;t[r]=Number(e[r]);}return [t[0],t[1],t[2]]}function Dn([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 Mn([n,e,t]){return [{op:">=",v:[n,e,t]},{op:"<",v:[n,e+1,0]}]}function Vn(n){if(n===""||n==="*"||n==="x"||n==="X")return [];if(n[0]==="^"){let i=Me(n.slice(1));return i&&Dn(i)}if(n[0]==="~"){let i=Me(n.slice(1));return i&&Mn(i)}let e=/^(>=|<=|>|<|=)/.exec(n),t=e?e[1]:"=",r=Me(e?n.slice(e[1].length):n);return r&&[{op:t,v:r}]}function en(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=Vn(s);if(o===null)return null;i.push(...o);}e.push(i);}return e}function tn(n){return en(n.trim())!==null}function Bn(n,e){let t=In(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 nn(n,e){let t=en(e.trim());return t===null?false:t.some(r=>r.every(i=>Bn(n,i)))}function Fn(n,e=a$1){if(!n.engineVersion)return {compatible:true};if(!tn(n.engineVersion))return {compatible:false,reason:"invalid-range",declaredRange:n.engineVersion,engineVersion:e};let t=Zt(e);return t===null||!nn(t,n.engineVersion)?{compatible:false,reason:"range-not-satisfied",declaredRange:n.engineVersion,engineVersion:e}:{compatible:true}}function rn(n,e=a$1){let t=Fn(n,e);if(!t.compatible)throw t.reason==="invalid-range"?c.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.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 ee="solve-engine/snapshot",Q=1;function W(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.validation({code:V.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 V={SNAPSHOT_VERSION_MISMATCH:"SNAPSHOT_VERSION_MISMATCH",SNAPSHOT_MALFORMED:"SNAPSHOT_MALFORMED",SNAPSHOT_UNSUPPORTED_VALUE:"SNAPSHOT_UNSUPPORTED_VALUE"};function sn(n){return {coef:n.coef.toString(),scale:n.scale}}function on(n){return {coef:BigInt(n.coef),scale:n.scale}}function Un(n){return {n:n.n.toString(),d:n.d.toString()}}function _n(n){return {n:BigInt(n.n),d:BigInt(n.d)}}function an(n){return g[n]??String(n)}function Ve(n,e){throw c.validation({code:V.SNAPSHOT_UNSUPPORTED_VALUE,message:`A ${an(n)} value (${e}) cannot be included in a snapshot yet.`,expected:"a concrete number, string, boolean, unit, range, matrix, bigint, or money value",found:`${an(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 Be(n,e){switch(n.type){case 0:{let t={t:0,v:W(n.value)};return n.exact!==void 0&&(t.exact=sn(n.exact)),n.rational!==void 0&&(t.rational=Un(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:W(t),base:n.unit}}case 2:return {t:2,v:n.value.toString()};case 3:return {t:3,v:n.value};case 4:{let t={t:4,v:W(n.value)};return n.grain!==void 0&&(t.g=n.grain),n.zone!==void 0&&(t.z=n.zone),t}case 5:return {t:5,v:W(n.value)};case 6:{let t={t:6,v:W(n.value),unit:n.unit??""};return n.exact!==void 0&&(t.exact=sn(n.exact)),t}case 7:{let t=n.value;t.hasSymbolic&&Ve(9,`${e} (symbolic matrix cell)`);let r=t.data.map(i=>zn(i,e));return {t:7,rows:t.rows,cols:t.cols,data:r}}case 8:{let t=n.value;return {t:8,min:W(t.min),max:W(t.max)}}case 10:return {t:10,v:n.value};case 13:return {t:13,code:n.value,message:n.unit??""};default:return Ve(n.type,e)}}function zn(n,e){return typeof n=="boolean"?n:typeof n=="number"?W(n):Ve(9,`${e} (symbolic matrix cell)`)}function Fe(n){switch(n.t){case 0:{let e=new m(0,$(n.v));return n.exact!==void 0&&(e.exact=on(n.exact)),n.rational!==void 0&&(e.rational=_n(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:{let e=new m(4,$(n.v));return n.g!==void 0&&(e.grain=n.g),n.z!==void 0&&(e.zone=n.z),e}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=on(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.validation({code:V.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 pe(n){let e={opcodes:Array.from(n.opcodes),numbers:Array.from(n.numbers,W),strings:n.strings.slice(),hasAsync:n.hasAsync};return n.constants&&(e.constants=Array.from(n.constants.entries())),n.userFunctionBodies&&(e.userFunctionBodies=n.userFunctionBodies.map(Ue)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:pe(t.program)}))),e}function fe(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(_e)),n.anonymousBodies&&(e.anonymousBodies=n.anonymousBodies.map(t=>({params:t.params.slice(),program:fe(t.program)}))),e}function Ue(n){return {name:n.name,params:n.params.slice(),program:pe(n.program)}}function _e(n){return {name:n.name,params:n.params.slice(),program:fe(n.program)}}function dn(n){if(typeof n!="object"||n===null)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:"fromJSON was given something that is not a snapshot object.",expected:`an object produced by ExpressionEngine.toJSON() with format "${ee}"`,found:n===null?"null":typeof n});let e=n;if(e.format!==ee)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:`This object is not a solve-engine snapshot (its "format" is ${JSON.stringify(e.format)}).`,expected:`format "${ee}"`,found:JSON.stringify(e.format)});if(e.version!==Q)throw c.validation({code:V.SNAPSHOT_VERSION_MISMATCH,message:`This snapshot was written for format version ${e.version}, but this engine restores version ${Q}.`,expected:`snapshot version ${Q}`,found:`version ${e.version}`,suggestion:"Regenerate the snapshot with a matching engine version, or re-evaluate the document from source.",context:{snapshotVersion:e.version,readerVersion:Q,engineVersion:e.engineVersion}});Wn(n);}var ln=32;function $n(n){return n===null?"null":Array.isArray(n)?`an array of ${n.length}`:typeof n=="object"?"an object":`${typeof n} ${JSON.stringify(n)}`.slice(0,80)}function h(n,e,t){throw c.validation({code:V.SNAPSHOT_MALFORMED,message:`Snapshot is malformed at ${n}: expected ${e}.`,expected:e,found:$n(t),suggestion:"Regenerate the snapshot with ExpressionEngine.toJSON(), or re-evaluate the document from source.",context:{location:n}})}function H(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function j(n){return typeof n=="number"||n==="NaN"||n==="Infinity"||n==="-Infinity"}function de(n){return typeof n=="string"&&/^-?\d+$/.test(n)}function xe(n,e){(!Array.isArray(n)||!n.every(t=>typeof t=="string"))&&h(e,"an array of strings",n);}function cn(n,e){(!H(n)||!de(n.coef)||typeof n.scale!="number")&&h(e,"a decimal as { coef: digits, scale: number }",n);}function jn(n,e){(!H(n)||!de(n.n)||!de(n.d))&&h(e,"a rational as { n: digits, d: digits }",n);}function un(n,e){switch(H(n)||h(e,"a serialised value object",n),n.t){case 0:j(n.v)||h(`${e}.v`,"a number",n.v),n.exact!==void 0&&cn(n.exact,`${e}.exact`),n.rational!==void 0&&jn(n.rational,`${e}.rational`);return;case 1:(n.big?!de(n.v):!j(n.v))&&h(`${e}.v`,n.big?"an integer string":"a number",n.v),n.base!==void 0&&typeof n.base!="string"&&h(`${e}.base`,"a base name",n.base);return;case 2:de(n.v)||h(`${e}.v`,"an integer string",n.v);return;case 3:typeof n.v!="string"&&h(`${e}.v`,"a string",n.v);return;case 4:j(n.v)||h(`${e}.v`,"a number",n.v),n.g!==void 0&&n.g!=="date"&&n.g!=="datetime"&&n.g!=="instant"&&h(`${e}.g`,'one of "date", "datetime" or "instant"',n.g),n.z!==void 0&&typeof n.z!="string"&&h(`${e}.z`,"a zone reference",n.z);return;case 5:j(n.v)||h(`${e}.v`,"a number",n.v);return;case 6:j(n.v)||h(`${e}.v`,"a number",n.v),typeof n.unit!="string"&&h(`${e}.unit`,"a unit name",n.unit),n.exact!==void 0&&cn(n.exact,`${e}.exact`);return;case 7:{let{rows:t,cols:r,data:i}=n;(!Number.isInteger(t)||t<0)&&h(`${e}.rows`,"a non-negative integer",t),(!Number.isInteger(r)||r<0)&&h(`${e}.cols`,"a non-negative integer",r),(!Array.isArray(i)||i.length!==t*r)&&h(`${e}.data`,`an array of ${t} \xD7 ${r} cells`,i),i.every(s=>typeof s=="boolean"||j(s))||h(`${e}.data`,"numeric or boolean cells",i);return}case 8:(!j(n.min)||!j(n.max))&&h(e,"a range with numeric min and max",n);return;case 10:typeof n.v!="boolean"&&h(`${e}.v`,"a boolean",n.v);return;case 13:(typeof n.code!="string"||typeof n.message!="string")&&h(e,"an error with a string code and message",n);return;default:return}}function Se(n,e,t){if(t>ln&&h(e,`function bodies nested at most ${ln} deep`,"deeper nesting"),H(n)||h(e,"a serialised program object",n),(!Array.isArray(n.opcodes)||!n.opcodes.every(r=>Number.isInteger(r)&&r>=0&&r<=255))&&h(`${e}.opcodes`,"an array of bytes (integers 0 to 255)",n.opcodes),(!Array.isArray(n.numbers)||!n.numbers.every(j))&&h(`${e}.numbers`,"an array of numbers",n.numbers),xe(n.strings,`${e}.strings`),typeof n.hasAsync!="boolean"&&h(`${e}.hasAsync`,"a boolean",n.hasAsync),n.constants!==void 0){let r=i=>Array.isArray(i)&&i.length===2&&typeof i[0]=="number"&&typeof i[1]=="number";(!Array.isArray(n.constants)||!n.constants.every(r))&&h(`${e}.constants`,"an array of [number, number] pairs",n.constants);}n.userFunctionBodies!==void 0&&(Array.isArray(n.userFunctionBodies)||h(`${e}.userFunctionBodies`,"an array of functions",n.userFunctionBodies),n.userFunctionBodies.forEach((r,i)=>pn(r,`${e}.userFunctionBodies[${i}]`,t+1))),n.anonymousBodies!==void 0&&(Array.isArray(n.anonymousBodies)||h(`${e}.anonymousBodies`,"an array of bodies",n.anonymousBodies),n.anonymousBodies.forEach((r,i)=>{let s=`${e}.anonymousBodies[${i}]`;H(r)||h(s,"a body object",r),xe(r.params,`${s}.params`),Se(r.program,`${s}.program`,t+1);}));}function pn(n,e,t){H(n)||h(e,"a function object",n),typeof n.name!="string"&&h(`${e}.name`,"a function name",n.name),xe(n.params,`${e}.params`),Se(n.program,`${e}.program`,t);}function Wn(n){n.locale!==void 0&&typeof n.locale!="string"&&h("locale","a locale code",n.locale),H(n.variables)||h("variables","an object of values by name",n.variables);for(let[e,t]of Object.entries(n.variables))un(t,`variables.${e}`);Array.isArray(n.userFunctions)||h("userFunctions","an array of functions",n.userFunctions),n.userFunctions.forEach((e,t)=>pn(e,`userFunctions[${t}]`,1)),Array.isArray(n.lineCache)||h("lineCache","an array of cached lines",n.lineCache),n.lineCache.forEach((e,t)=>{let r=`lineCache[${t}]`;H(e)||h(r,"a cached line",e),Number.isInteger(e.line)||h(`${r}.line`,"a line number",e.line),typeof e.expression!="string"&&h(`${r}.expression`,"the line's expression text",e.expression),un(e.result,`${r}.result`),Se(e.bytecode,`${r}.bytecode`,1),xe(e.reads,`${r}.reads`),e.writeVar!==null&&typeof e.writeVar!="string"&&h(`${r}.writeVar`,"a variable name or null",e.writeVar);}),Array.isArray(n.bytecodeCache)||h("bytecodeCache","an array of compiled expressions",n.bytecodeCache),n.bytecodeCache.forEach((e,t)=>{let r=`bytecodeCache[${t}]`;(!H(e)||typeof e.expression!="string")&&h(r,"an { expression, program } pair",e),Se(e.program,`${r}.program`,1);});}var fn=null;function mr(n){fn=n;}function ze(){return fn}var hn=3e4,gn=50,ke=class{constructor(e){this.workers=[];this.nextWorker=0;this.nextId=1;this.pendingBatches=new Map;this.terminated=false;this._available=null;this.poolSize=Math.min(e??this.defaultPoolSize(),4);}defaultPoolSize(){return typeof navigator<"u"&&navigator.hardwareConcurrency?Math.min(navigator.hardwareConcurrency,4):2}isAvailable(){if(this.terminated)return false;if(this._available!==null)return this._available;if(typeof Worker>"u")return this._available=false,false;try{let e=ze();return e===null?(this._available=!1,!1):(e().terminate(),this._available=!0,!0)}catch{return this._available=false,false}}executeBatch(e,t){if(!this.isAvailable())return;if(e.length===0)return Promise.resolve([]);this.ensureWorkers();let r=[];for(let a of e){let c=t.get(a);if(!c||c.bytecode.opcodes.length===0)continue;let u=c.bytecode.opcodes,d=c.bytecode.numbers,g=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength),y=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);r.push({lineNumber:a,opcodesBuffer:g,numbersBuffer:y,opcodesLength:u.length,numbersLength:d.length,strings:[...c.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.nextWorkerIndex(),l=this.workers[o];return new Promise(a=>{let c=setTimeout(()=>{this.pendingBatches.has(s)&&this.failWorker(o,"WORKER_TIMEOUT",`Evaluation did not finish within ${hn/1e3} seconds; the worker was replaced`);},hn);this.pendingBatches.set(s,{id:s,lineNumbers:r.map(u=>u.lineNumber),workerIndex:o,resolve:u=>{clearTimeout(c),a(u);}}),l.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++)this.spawnWorker(e);}spawnWorker(e){let t=ze();if(t===null)return;let r=t();r.onmessage=i=>{this.handleWorkerMessage(i.data);},r.onerror=i=>{console.error(`[ExecutionPool] Worker ${e} error:`,i.message),this.failWorker(e,"WORKER_EXECUTION_ERROR",`Worker failed: ${i.message}`);},this.workers[e]=r;}failWorker(e,t,r){if(this.workers.length!==0){this.workers[e]?.terminate(),this.terminated||this.spawnWorker(e);for(let[i,s]of this.pendingBatches)s.workerIndex===e&&(this.pendingBatches.delete(i),s.resolve(Hn(s.lineNumbers,t,r)));}}nextWorkerIndex(){let e=this.nextWorker;return this.nextWorker=(this.nextWorker+1)%this.workers.length,e}handleWorkerMessage(e){if(e.type!=="EXECUTE_RESULT")return;let t=this.pendingBatches.get(e.id);t&&(this.pendingBatches.delete(e.id),t.resolve(e.results));}};function Hn(n,e,t){return n.map(r=>({lineNumber:r,valueType:13,value:0,unit:t,isPending:false,errorCode:e}))}function mn(n$1){switch(n$1.valueType){case 0:return n(n$1.value);case 1:return r$1(n$1.value);case 2:return s$1(BigInt(n$1.value));case 3:return t(String(n$1.value));case 4:return M$1(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$1(n$1.value!==0);case 12:return O$1(n$1.queryKey??"");case 13:return P(n$1.errorCode??"WORKER_EXECUTION_ERROR",n$1.unit??"Unknown worker error");default:return n(n$1.value)}}var te=class te{constructor(e,t,r,i=te.DEFAULT_HIGH_WATER_MARK){this.pending=new Map;this.collapsed=0;this.scheduled=false;this.cleared=false;this.executionPool=null;this.workerOffloadDispatchCount=0;this._eventStream=null;this._streamController=null;this._testCaptures=null;this.onLineResult=null;this.checkpointer=null;this.warnedAboutMissingHook=false;this.flushesWithoutYielding=0;this.yieldProbeArmed=false;this.dag=e,this.lineCache=t,this.vm=r,this.highWaterMark=i;}warnIfUnwired(){this.onLineResult||this.listenerCount>0||this.warnedAboutMissingHook||(this.warnedAboutMissingHook=true,console.warn("[solve-engine] An async result resolved, but nothing is listening for it: no reader is attached to engine.getEventStream() and AsyncResolutionBatcher.onLineResult is not set. The value is in the cache; without one of those the line keeps showing as pending. Read the event stream and re-evaluate the lines it names (see the async guide), or set onLineResult to mirror resolved values into your own state. This warning appears once per batcher."));}createEventStream(){return new ReadableStream({start:e=>{this._streamController=e;},cancel:()=>{this._streamController=null;}},new CountQueuingStrategy({highWaterMark:this.highWaterMark}))}eventStream(){return this._eventStream??(this._eventStream=this.createEventStream()),this._eventStream}add(e){this.cleared=false;let t=`${e.packageId}:${e.queryKey}`;if(this.pending.has(t)){this.collapsed++;return}if(this.pending.set(t,e),!this.scheduled){this.scheduled=true;let r=this.flushesWithoutYielding>=te.MAX_CHAINED_FLUSHES,i=()=>{try{this.flush();}catch(s){let o=d(s);console.error(`[AsyncResolutionBatcher] flush() failed unexpectedly \u2014 this should never happen; please report: ${o.format()}`);}};r?setTimeout(i,0):queueMicrotask(i);}}getEventStream(){return this.eventStream()}get pendingCount(){return this.pending.size}get dedupCount(){return this.collapsed}get listenerCount(){return this._eventStream?.locked?1:0}get workerOffloadCount(){return this.workerOffloadDispatchCount}clearAll(){this.pending=new Map,this.collapsed=0,this.scheduled=false,this.cleared=true,this._testCaptures=null,this.onLineResult=null;try{this._streamController?.close();}catch{}this._streamController=null,this._eventStream=null,this.executionPool&&(this.executionPool.clear(),this.executionPool=null),this.workerOffloadDispatchCount=0;}flush(){if(this.scheduled=false,this.cleared||this.pending.size===0)return;this.flushesWithoutYielding++,this.yieldProbeArmed||(this.yieldProbeArmed=true,setTimeout(()=>{this.flushesWithoutYielding=0,this.yieldProbeArmed=false;},0));let e=this.pending;this.pending=new Map,this.collapsed=0;let t=[],r=[];for(let a of e.values())a.isError?t.push(a):r.push(a);for(let a of t)a.signal.aborted||this.notifyListeners({type:"error",queryKey:a.queryKey,packageId:a.packageId,error:a.error??new Error("Unknown async resolution error")});let i=new Set,s=[],o=[...r,...t];for(let a of o){if(a.signal.aborted)continue;s.push(a.queryKey);let c=this.dag.getAffectedLinesByDataSource(a.packageId,[a.queryKey]);for(let u of c)i.add(u);}{let a=[...i],c=u=>{i.has(u)||(i.add(u),a.push(u));};for(let u=0;u<a.length;u++){let d=a[u];for(let g of this.dag.getWrites(d))for(let y of this.dag.getAffectedLines(g))c(y);for(let g of this.dag.getAffectedLinesByPosition(d))c(g);}}if(i.size===0){this.notifyListeners({type:"lines-updated",lineNumbers:[],affectedQueryKeys:s});return}let l=this.topologicalSort(Array.from(i));if(l.length>gn){let a=new Map;for(let c of l)a.set(c,this.lineCache.getEntryForLine(c));this.reExecuteViaWorkerPool(l,a,s).catch(c=>{let u=d(c);console.error(`[AsyncResolutionBatcher] reExecuteViaWorkerPool() failed unexpectedly: ${u.format()}`);});return}this.reExecuteMainThread(l,s);}topologicalSort(e){if(e.length<=1)return e;let t=new Map,r=new Map,i=new Map;for(let l of e)t.set(l,0),r.set(l,[]);for(let l of e){let a=this.dag.getWrites(l);for(let c of a)i.set(c,l);}for(let l of e){let a=this.dag.getReads(l);for(let c of a){let u=i.get(c);u!==void 0&&u!==l&&(r.get(u).push(l),t.set(l,(t.get(l)??0)+1));}}let s=[];for(let[l,a]of t)a===0&&s.push(l);if(s.length===0&&e.length>0)return [...e].sort((l,a)=>l-a);let o=[];for(let l=0;l<s.length;l++){let a=s[l];o.push(a);for(let c of r.get(a)??[]){let u=(t.get(c)??1)-1;t.set(c,u),u===0&&s.push(c);}}if(o.length<e.length){let l=new Set(o),a=e.filter(c=>!l.has(c)).sort((c,u)=>c-u);o.push(...a);}return o}async reExecuteViaWorkerPool(e,t,r){this.executionPool||(this.executionPool=new ke);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 l of s){let a=t.get(l.lineNumber);if(!a||l.isPending)continue;let c=mn(l);a.result=c,this.warnIfUnwired(),this.onLineResult?.(l.lineNumber,c),o.push(l.lineNumber);}this.cleared||(o.length>0||r.length>0)&&this.notifyListeners({type:"lines-updated",lineNumbers:o,affectedQueryKeys:r});}prepareSweep(e){if(e.length===0)return null;let t=e[0];for(let r=1;r<e.length;r++)e[r]<t&&(t=e[r]);return this.checkpointer.restoreTo(t-1),{at:t-1}}sweepTo(e,t){for(let r=e.at+1;r<t;r++)this.checkpointer.applyCheckpointAt(r);t>e.at&&(e.at=t);}reExecuteMainThread(e,t,r){let i=[],s=this.checkpointer!==null?this.prepareSweep(e):null;for(let o of e){s!==null&&this.sweepTo(s,o);let l=r?r.get(o):this.lineCache.getEntryForLine(o);if(!l||l.bytecode.opcodes.length===0)continue;let a=this.vm.getStack().length;try{let c=c$1(l.bytecode,this.vm,void 0,void 0,{lineIndex:o,networkEnabled:this.vm.context.networkEnabled,calendar:this.vm.context.calendar});for(;this.vm.getStack().length>a;)this.vm.pop();if(c.type==="value")s!==null&&l.writeVariable!==null&&this.checkpointer.updateCheckpointAt(o,[l.writeVariable]),l.result=c.value,this.warnIfUnwired(),this.onLineResult?.(o,c.value),i.push(o);else if(c.type==="error"){let u=P(c.error.code,c.error.message);l.result=u,this.warnIfUnwired(),this.warnIfUnwired(),this.onLineResult?.(o,u),i.push(o);}}catch(c){for(;this.vm.getStack().length>a;)this.vm.pop();let u=d(c),d$1=P(u.code,u.message);l.result=d$1,this.warnIfUnwired(),this.onLineResult?.(o,d$1),i.push(o);}}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.eventStream(),this._streamController)try{this._streamController.enqueue(e);}catch{}}};te.DEFAULT_HIGH_WATER_MARK=64,te.MAX_CHAINED_FLUSHES=4;var Ce=te;function $e(n$1,e){if(n$1.length>e.maxExpressionLength){let t=c.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 je(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.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 he(n){return n.type==="IDENT"||n.type==="UNIT"}function Kn(n){return n.type==="NUMBER"||n.type==="TO"||n.type==="IN"||n.type==="RPAREN"}function yn(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 Gn(n){let e=new Set;for(let t=0;t<n.length;t++){if(!he(n[t])||t>0&&n[t-1].type==="COLON"||n[t+1]?.type!=="LPAREN")continue;let r=yn(n,t+1);if(r!==null&&n[r+1]?.type==="EQUALS")for(let i=t+2;i<r;i++)he(n[i])&&e.add(n[i].value);}return e}function qn(n,e){if(n[e+1]?.type!=="LINE_REF")return -1;let t=n[e+2];if(!(t!==void 0&&(t.type==="FOR_DURATION"||t.type==="IDENT"&&t.value.toLowerCase()==="for")))return -1;let i=n[e+3];return i===void 0||i.type!=="IDENT"&&i.type!=="UNIT"?-1:e+3}function Te(n){let e=[],t=[],r=Gn(n),i=null;for(let s=0;s<n.length;s++){let o=n[s];if(o.type==="GOAL_SEEK"){let l=qn(n,s);l!==-1&&(i??(i=new Set)).add(l);continue}if(o.type==="GLOBAL"){if(s+2<n.length&&n[s+1].type==="COLON"&&he(n[s+2])){let l=O(n[s+2].value);e.push(l),s+3<n.length&&n[s+3].type==="EQUALS"&&t.push(l);}continue}if(o.type==="COLON"){if(s>0&&n[s-1].type==="GLOBAL")continue;if(s+1<n.length&&he(n[s+1])){let l=n[s+1].value;e.push(l),s+2<n.length&&n[s+2].type==="EQUALS"&&t.push(l);}}if(he(o)){if(s>0&&n[s-1].type==="COLON"||i!==null&&i.has(s)||o.type==="UNIT"&&s>0&&Kn(n[s-1])||r.has(o.value))continue;if(n[s+1]?.type==="LPAREN"){let a=yn(n,s+1);if(a!==null&&n[a+1]?.type==="EQUALS"){e.push(o.value),t.push(o.value);continue}}e.push(o.value);let l=n[s+1]?.type;(l==="EQUALS"||l==="PLUS_EQUALS"||l==="MINUS_EQUALS")&&t.push(o.value);}}return {reads:e,writes:t}}function Lr(n){return c$2.classifyLine(n).skip}function Or(n,e){return c$2.findInlineSolves(n).map(r=>({start:r.start,end:r.end,expression:r.expression,lineNumber:e,columnNumber:r.columnNumber}))}var q=class{constructor(e,t,r,i){this.result=e;this.bytecode=t;this.readVariables=r;this.writeVariable=i;}},we=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 We(n,e){let t=e.fields(n),r=String(t.month0+1).padStart(2,"0"),i=String(t.day).padStart(2,"0");return `${t.year}-${r}-${i}`}function Yn(n,e){if(n instanceof Date)return We(n.getTime(),e);if(typeof n=="number")return Number.isFinite(n)?We(n,e):null;let t=/^(\d{4})-(\d{2})-(\d{2})/.exec(n.trim());return t?`${t[1]}-${t[2]}-${t[3]}`:null}function vn(n,e){if(n===void 0)return;if(typeof n=="function")return r=>n(new Date(r));let t=new Set;for(let r of n){let i=Yn(r,e);i!==null&&t.add(i);}return r=>t.has(We(r,e))}function Qn(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 Re=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&&Qn(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 B=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(),l=typeof process<"u"&&process.hrtime?process.hrtime(s):void 0,a=typeof process<"u"&&process.memoryUsage?process.memoryUsage():null,c=l?l[0]*1e9+l[1]:(performance.now()-s)*1e6,u=i&&a?a.heapUsed-i.heapUsed:0,d={stage:e,allocCount:0,allocBytes:u,objectCounts:{},wallTimeNs:c,...r};return {result:o,alloc:d}}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
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 a of i)r.push(`| ${a.stage} | ${a.count} | ${(a.meanWallTimeNs/1e3).toFixed(2)} | ${a.meanAllocBytes.toFixed(0)} | ${(a.minWallTimeNs/1e3).toFixed(2)} | ${(a.maxWallTimeNs/1e3).toFixed(2)} | ${(a.p50WallTimeNs/1e3).toFixed(2)} | ${(a.p95WallTimeNs/1e3).toFixed(2)} | ${(a.p99WallTimeNs/1e3).toFixed(2)} |`);let s=e.reduce((a,c)=>a+c.totalAllocBytes,0),o=e.reduce((a,c)=>a+c.totalWallTimeNs,0),l=e.filter(a=>a.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:** ${l}/${e.length} (${(l/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
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),l=s.map(c=>c.allocBytes),a=s.length;r.push({stage:i,count:a,meanAllocBytes:l.reduce((c,u)=>c+u,0)/a,meanWallTimeNs:o.reduce((c,u)=>c+u,0)/a,minWallTimeNs:o[0],maxWallTimeNs:o[o.length-1],p50WallTimeNs:He(o,50),p95WallTimeNs:He(o,95),p99WallTimeNs:He(o,99)});}return r.sort((i,s)=>i.stage.localeCompare(s.stage)),r}static createTelemetry(e,t,r=false){let i=t.reduce((o,l)=>o+l.allocBytes,0),s=t.reduce((o,l)=>o+l.wallTimeNs,0);return {expression:e,stages:t,totalAllocBytes:i,totalWallTimeNs:s,fastPath:r}}};B.enabled=false;function He(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 bn(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 Ne=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,i=-1){let s=bn(e),o=this.byKey.get(s),l=o===void 0||o.ratioText!==t||o.baseUnit!==r;return this.byKey.set(s,{displayName:e.join(" "),ratioText:t,baseUnit:r,definedByLineId:i}),e.length>this.longestName&&(this.longestName=e.length),l}match(e){let t=Math.min(e.length,this.longestName);for(let r=t;r>=1;r--){let i=this.byKey.get(bn(e.slice(0,r)));if(i!==void 0)return {definition:i,wordCount:r}}return null}undefineFrom(e){if(e<0)return false;let t=false;for(let[r,i]of this.byKey)i.definedByLineId===e&&(this.byKey.delete(r),t=true);return t}get names(){return [...this.byKey.keys()]}clear(){this.byKey.clear(),this.longestName=0;}};function En(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 p=r+1;p<t.length&&s.length<o&&t[p].type==="IDENT";p++)s.push(t[p].value);if(s.length===0)return null;let l=n.match(s);if(l===null||t[r+1+l.wordCount]?.type==="EQUALS")return null;let{ratioText:c,baseUnit:u}=l.definition,d=new a$9("STAR",c$a("STAR"),"*","*",i.offset,0,i.line,i.col),g=new a$9("NUMBER",c$a("NUMBER"),c,c,i.offset,0,i.line,i.col),y=new a$9("UNIT",c$a("UNIT"),u,u,i.offset,0,i.line,i.col);return {consumed:1+l.wordCount,replacement:[i,d,g,y],ruleName:"uom:user-unit"}}}}var xn="engine:call-fusion";function Sn(n,e=80){return {name:xn,priority:e,shape:[{types:["IDENT"]},{types:["LPAREN"]}],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$9(o,c$a(o),s,i.value,i.offset,0,i.line,i.col)],ruleName:xn}}}}var Xn={january:1,jan:1,february:2,feb:2,march:3,mar:3,april:4,apr:4,may:5,june:6,jun:6,july:7,jul:7,august:8,aug:8,september:9,sep:9,sept:9,october:10,oct:10,november:11,nov:11,december:12,dec:12};function kn(n){return n===void 0||n.type!=="IDENT"&&n.type!=="UNIT"?0:Xn[(n.text??n.value??"").toLowerCase()]??0}var ge=/^\d+$/;function Ae(n){return n.length===4}function ne(n,e,t,r,i,s){let o="datetime:month-name-date",l=t$1(n,e,t,r,o,i);return l!==null?l:s==="arithmetic"||e<1||e>12||n<1||n>31?null:v(j$2.DATE_NOT_A_CALENDAR_DAY,`"${u$1(r)}" is not a real date: ${m$1(n,e,t)}.`,r,`${o}:unreadable`)}function Cn(n){return n.fields(n.now()).year}function Tn(n=64,e=()=>b$4,t=()=>"refuse"){return {name:"datetime:month-name-date",priority:n,startTokenTypes:["NUMBER","IDENT","UNIT"],match(r,i){let s=e(),o=t(),l=r[i];if(l?.type==="NUMBER"&&ge.test(l.text??"")){let y=kn(r[i+1]);if(y===0)return null;let p=Number(l.text);if(p<1||p>31)return null;let S=r[i+2];return S?.type==="NUMBER"&&ge.test(S.text??"")&&Ae(S.text??"")?ne(p,y,Number(S.text),r.slice(i,i+3),s,o):ne(p,y,Cn(s),r.slice(i,i+2),s,o)}let a=kn(l);if(a===0)return null;let c=r[i+1];if(c?.type!=="NUMBER"||!ge.test(c.text??""))return null;if(Ae(c.text??""))return ne(1,a,Number(c.text),r.slice(i,i+2),s,o);let u=Number(c.text),d=r[i+2],g=r[i+3];return d?.type==="COMMA"&&g?.type==="NUMBER"&&ge.test(g.text??"")&&Ae(g.text??"")?ne(u,a,Number(g.text),r.slice(i,i+4),s,o):d?.type==="NUMBER"&&ge.test(d.text??"")&&Ae(d.text??"")?ne(u,a,Number(d.text),r.slice(i,i+3),s,o):ne(u,a,Cn(s),r.slice(i,i+2),s,o)}}}var Jn=30,Zn=40,er=50,tr=24;function nr(n){switch(n){case a.PLUS:case a.MINUS:return Jn;case a.STAR:case a.SLASH:case a.MOD:case a.OF:return Zn;case a.CARET:return er;case a.PCT_ON:case a.PCT_OFF:return tr;default:return 0}}function rr(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 wn(n){return n.sourceEnd??n.offset+n.value.length}var ir=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 sr(n){return !ir.has(n)}var Ke=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=nr(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()&&!sr(this.peek().type);)i=wn(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:wn(r)}}},Ge=class{constructor(e,t,r){this.source=e;this.evaluate=t;this.steps=[];this.cache=new Map;this.resultPrefix=a$a(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=rr(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$b(e,a$b);return t.startsWith(this.resultPrefix)?t.slice(this.resultPrefix.length):t}};function qe(n){let{expression:e,tokens:t,evaluate:r,locale:i,readings:s=[]}=n,o=c=>s.filter(u=>u.needsNote).map(u=>({description:u.note,value:c})),l=()=>{let c=r(e);return {expression:e,steps:o(c),result:c}},a;try{a=new Ke(t).parseAll();}catch{return l()}try{let{steps:c,result:u}=new Ge(e,r,i).build(a);return {expression:e,steps:[...o(u),...c],result:u}}catch{return l()}}function Ye(n){let e=t(n);return j$1()?k$1(e):e}var _=class _{constructor(e={}){this.dag=new c$3;this.asyncFailures=new Map;this.lineCache=new we;this.accumulatorNames=new Set;this.scopeManager=new a$2;this.resolverRegistry=new a$3;this.packageContributions=new Map;this.registeredPackages=new Map;this.callFusions=new Map;this.callFusionOwners=new Map;this.compatIndex=new Ee;this.documentModel=null;this.goalSeekDepth=0;this.batchScanResults=null;this.batchParsedLines=null;this.batchTagIndex=null;this.lineContext=null;this.lineContextDoc=null;this.lineContextScan=null;this.lineContextParsed=null;this.packageCompletionItems=new Map;this.keystrokeSignal=null;this.orphanCandidates=null;this.backgroundRefreshSignal=new AbortController().signal;this.inertSignal=new AbortController().signal;this.userUnits=new Ne;this.bytecodeCache=new Map;this.compiledFrontHalf=new Map;this.failedParses=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;this.lineOnCycle=false;let{locale:t="en",diagnostics:r=false,config:i,packages:s,calendar:o}=e;this.localeCode=t,this.config=c$4(b,i??{}),this.dateReading=k(this.config.date),this.lexer=new b$1(t),this.registry=new b$2,this.context=B$1({networkEnabled:this.config.network.enabled,calendar:o}),r?(this.diagnosticPipeline=new a$4,this.timelineCollector=new b$3,this.diagnosticPipeline.register(this.timelineCollector)):this.diagnosticPipeline=new a$4,this.normalizer=new c$5;for(let[a,c]of Object.entries(c$6))this.normalizer.addPhrase(a,c);this.normalizer.register(d$2(50,a=>this.normalizer.canStartPhrase(a))),this.normalizer.register(En(this.userUnits)),this.normalizer.register(Sn(this.callFusions));let l=s??[];for(let a of l)try{this.registerPackage(a);}catch(c){let u=d(c);console.error(`[ExpressionEngine] Failed to register package "${a.name}" \u2014 skipping it and continuing construction with the remaining packages: ${u.format()}`);}if(this.registry.hasPrefix("DATETIME_LITERAL")&&this.registry.hasPrefix("DATETIME_LITERAL_UNREADABLE")){let a=()=>this.context.calendar;this.normalizer.register(w(()=>this.dateReading.order,a,()=>this.config.date.onAmbiguous)),this.normalizer.register(Tn(void 0,a,()=>this.config.date.onAmbiguous));}this.parser=new a$5(this.registry,this.config.validation.maxNestingDepth,t,this.pluginFunctionIndexByName,this.context.calendar),this.vm=b$5(this.context.opRegistry,this.config.vm.maxStackDepth,this.config.vm.maxInstructions,void 0,this.config.vm.maxCollectionSize,this.config.vm.maxAllocatedElements,this.config.vm.maxFunctionCalls,this.config.date.maxOffsetYears,this.config.date.minOffsetYears,this.context,vn(this.config.date.holidays,this.context.calendar)),this.queryClient=c$7(),this.batcher=new Ce(this.dag,this.lineCache,this.vm),this.backgroundRefresh=this.config.backgroundRefresh.enabled?new Re(this.dag,(a,c)=>this.batcher.add({queryKey:c,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 _.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(),c$1(s,this.vm);}catch{}this.vm.reset();}makeLineContext(e){let t=this.documentModel,r=t?null:this.batchScanResults,i=t?null:this.batchParsedLines,s=this.lineContext;return (s===null||this.lineContextDoc!==t||this.lineContextScan!==r||this.lineContextParsed!==i)&&(s=this.buildLineContext(t,r,i,e),this.lineContext=s,this.lineContextDoc=t,this.lineContextScan=r,this.lineContextParsed=i),s.lineIndex=e,s}buildLineContext(e,t,r,i){let s=this.dag,o;return o={lineIndex:i,getLineCount:e?()=>e.lineCount:void 0,getLineResult:e?a=>{if(a!==o.lineIndex&&(s.registerLinePositionDependency(o.lineIndex,a),!(a>o.lineIndex&&this.lineOnCycle)))return e.getLineAt(a)?.result??void 0}:r?a=>a===o.lineIndex?void 0:r[a-1]?.result??void 0:void 0,noteLineRead:e?a=>{a!==o.lineIndex&&s.registerLinePositionDependency(o.lineIndex,a);}:void 0,isLineBoundary:e?a=>{let c=e.getLineAt(a);return c?c.isEmpty||/^\s*#/.test(c.text):true}:t?a=>{let c=t[a-1];return c?c.classification.skip||/^\s*#/.test(c.text):true}:void 0,getLineReads:e?a=>{if(a!==o.lineIndex&&s.registerLinePositionDependency(o.lineIndex,a),a>o.lineIndex&&this.lineOnCycle)return;let c=e.getLineAt(a);if(!(!c||c.bytecodes.length===0))return c.reads}:void 0,evaluateLineWithBinding:e?(a,c,u,d)=>(a!==o.lineIndex&&s.registerLinePositionDependency(o.lineIndex,a),this.evaluateLineWithBinding(a,c,u,d)):void 0,goalSeekMaxIterations:this.config.vm.maxGoalSeekIterations,networkEnabled:this.config.network.enabled,calendar:this.context.calendar,getLineText:e?a=>e.getLineAt(a)?.text:t?a=>t[a-1]?.text:void 0,getTaggedLines:e?a=>e.linesCarryingTag(a):t?a=>this.batchLinesCarryingTag(t,a):void 0},o}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>=_.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 l=o.bytecodes[0];this.goalSeekDepth++;try{let a=new Map([[t,r]]),c=this.vm.getStack().length;this.vm.pushCallFrame(a);try{let u=c$1(l,this.vm,void 0,void 0,this.buildLineContext(s,null,null,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(a){return P("GOAL_SEEK_TARGET_ERROR",d(a).message)}finally{this.goalSeekDepth--;}}frontHalfCached(e){return this.compiledFrontHalf.has(e)&&this.bytecodeCache.has(e)||this.failedParses.has(e)}clearCompiledCache(){this.bytecodeCache.clear(),this.compiledFrontHalf.clear(),this.failedParses.clear();}cacheBytecode(e,t,r){let i=this.config.performance.defaultCacheSize;if(this.bytecodeCache.size>=i){let s=this.bytecodeCache.keys().next().value;s!==void 0&&(this.bytecodeCache.delete(s),this.compiledFrontHalf.delete(s));}this.bytecodeCache.set(e,t),this.compiledFrontHalf.set(e,r);}touchCompiled(e,t){this.bytecodeCache.size<this.config.performance.defaultCacheSize||(this.bytecodeCache.delete(e),this.bytecodeCache.set(e,t));}rememberFailedParse(e,t){if(this.failedParses.size>=this.config.performance.defaultCacheSize){let r=this.failedParses.keys().next().value;r!==void 0&&this.failedParses.delete(r);}this.failedParses.set(e,t);}touchFailedParse(e,t){this.failedParses.size<this.config.performance.defaultCacheSize||(this.failedParses.delete(e),this.failedParses.set(e,t));}getEventStream(){return this.batcher.getEventStream()}restoreToPrefix(e,t){if(this.accumulatorNames.has(e))return;let r=this.batcher.checkpointer,i=r?.lookupFunctionBefore(e,t);i!==void 0?this.vm.defineUserFunction(i.name,i.params,i.program):this.vm.hasUserFunction(e)&&this.vm.deleteUserFunction(e);let s=r?.lookupVariableBefore(e,t);s===void 0?this.vm.deleteVar(e):this.vm.setVar(e,s);}setLineOnCycle(e){this.lineOnCycle=e;}isAccumulatorName(e){return this.accumulatorNames.has(e)}userUnitNames(){return this.userUnits.names}undefineUserUnitsFrom(e){return this.userUnits.undefineFrom(e)}invalidateForRemovedUserUnits(){this.clearCompiledCache(),this.documentModel?.invalidateAll();}getBatcher(){return this.batcher}registerPackage(e){rn(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=J(`${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(),l=this.callFusionOwners.get(o);l?l.push({pkg:e.name,tokenType:s}):this.callFusionOwners.set(o,[{pkg:e.name,tokenType:s}]),this.callFusions.set(o,s),r.callFusionNames.push(o);}if(e.tokenCategories)for(let[i,s]of Object.entries(e.tokenCategories))b$6(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))L(i,s),r.asConverterNames.push(i);this.packageContributions.set(e.name,r),this.registeredPackages.set(e.name,e),this.compatIndex.add(e),this.clearCompiledCache();}unregisterPackage(e){let t=this.packageContributions.get(e);if(!t)return false;for(let 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$8(r);t.lexerVocabulary&&this.lexer.unregisterVocabulary(t.lexerVocabulary);for(let r of t.asConverterNames)M(r);for(let r of t.normalizerRuleNames)this.normalizer.unregister(r);for(let r of t.callFusionNames){let i=(this.callFusionOwners.get(r)??[]).filter(s=>s.pkg!==e);i.length===0?(this.callFusionOwners.delete(r),this.callFusions.delete(r)):(this.callFusionOwners.set(r,i),this.callFusions.set(r,i[i.length-1].tokenType));}return this.packageCompletionItems.delete(e),this.packageContributions.delete(e),this.registeredPackages.delete(e),this.compatIndex.rebuild(this.registeredPackages.values()),this.clearCompiledCache(),true}getConfig(){return {...this.config}}getDateReading(){return this.dateReading}readDates(e){let{tokens:t}=this.lexToTokens(e,void 0,false),r$1=this.normalizer.normalize(t.filter(s=>s.type!=="COMMENT")),i=[];for(let s$1 of r$1){let o=s$1.type===s;if(!o&&s$1.type!==r)continue;let l=s$1.offset,a=s$1.sourceEnd??s$1.offset+s$1.text.length;i.push(this.describeDateLiteral(e.slice(l,a),l,a,s$1,o));}return i}describeDateLiteral(e,t,r,i,s){let o$1=q$1(e);if(o$1!==null){let c=o(o$1,this.dateReading.order,this.config.date.onAmbiguous,this.context.calendar),u=l(o$1.groups[0],o$1.groups[1],o$1.groups[2],o$1.separator)==="iso",d=this.dateReading.order==="auto"?o$1.separator==="hyphen"?"MDY":"DMY":this.dateReading.order,g=u?{order:"ISO",orderSource:"iso",locale:void 0}:{order:d,orderSource:this.dateReading.orderSource,locale:this.dateReading.locale};return c.kind==="date"?p({text:e,start:t,end:r,iso:n$1(c.day,c.month,c.year),...g,contested:c.alternative!==void 0,shortYear:c.shortYear,alternative:c.alternative},o$1.separator):p({text:e,start:t,end:r,iso:null,...g,contested:false,shortYear:false,problem:c.kind==="refuse"?c.code:void 0},o$1.separator,c.kind==="refuse"?c.message:void 0)}if(s){let c=i.fault??{code:"DATE_NOT_A_CALENDAR_DAY",message:`"${i.value}" is not a date this engine can read.`};return p({text:e,start:t,end:r,iso:null,order:null,orderSource:"spelled",contested:false,shortYear:false,problem:c.code},"slash",c.message)}let l$1=this.context.calendar.fields(Number(i.value)),a=/^\d{4}-/.test(e)?"iso":"spelled";return p({text:e,start:t,end:r,iso:n$1(l$1.day,l$1.month0+1,l$1.year),order:a==="iso"?"ISO":"spelled",orderSource:a,contested:false,shortYear:false},"slash")}getDiagnosticPipeline(){return this.diagnosticPipeline}storeLineResult(e,t,r,i,s,o){this.lineCache.set(e,new q(t,r,i,s.length>0?s[0]:null),o);}mayResolve(e){return e.hasAsync||this.resolverRegistry.mayIntercept(e)}armCancellation(e,t){if(!this.mayResolve(e))return this.vm.activeSignal=this.inertSignal,this.vm.abortCurrent=void 0,null;let r=new AbortController,i=()=>r.abort(),s=this.keystrokeSignal;s?.addEventListener("abort",i,{once:true}),a$6.localControllerCreated(t),s&&a$6.signalLinked(t);let o=()=>s?.removeEventListener("abort",i);return this.vm.activeSignal=r.signal,this.vm.abortCurrent=()=>{a$6.signalUnlinked(t),o(),r.abort();},o}forgetOrphanedNames(e){if(e.length!==0)for(let t of e)b$7(t)||(this.orphanCandidates??(this.orphanCandidates=new Set)).add(t);}settleOrphanedNames(){let e=this.orphanCandidates;if(e===null||e.size===0)return;this.orphanCandidates=null;let t=this.documentModel;if(t===null)return;let r=new Set,i=t.lineCount;for(let o=1;o<=i;o++){let l=t.getLineAt(o);if(l!==void 0)for(let a of l.writes)e.has(a)&&r.add(a);}let s=[];for(let o of e)r.has(o)||(s.push(o),this.vm.deleteVar(o),this.vm.hasUserFunction(o)&&this.vm.deleteUserFunction(o));this.batcher.checkpointer?.forget(s);}registerLineWithTags(e,t,r,i){if(e===-1)return;let s=a$7(t,r,i);this.forgetOrphanedNames(this.dag.registerLine(e,s.reads,s.writes));}executeAndStore(e,t,r,i,s,o,l,a){let c=this.vm.getStack().length,u=this.armCancellation(e,"executeAndStore");a$8(this.queryClient);let d=c$1(e,this.vm,l,a,this.makeLineContext(t));for(;this.vm.getStack().length>c;)this.vm.pop();if(d.type==="pending"){let g=`${d.packageId||o}:${d.queryKey}`,y=this.asyncFailures.get(g)??0;if(y>=_.MAX_ASYNC_FAILURES){u?.();let S=P("ASYNC_RESOLVER_FAILED",`This value could not be fetched after ${y} attempts, so it is reported rather than retried. Edit the line to try again.`);return this.storeLineResult(t,S,e,i,s,r),S}this.resolveAsync(d),this.dag.registerLineDataSourceDependency(t,d.packageId||o,[d.queryKey]);let p=O$1(d.queryKey);return this.storeLineResult(t,p,e,i,s,r),p}if(d.type==="error")throw u?.(),d.error;return u?.(),this.registerLineWithTags(t,r,i,s),this.storeLineResult(t,d.value,e,i,s,r),d.value}executeRaw(e,t=-1){let r=this.vm.getStack().length,i=this.armCancellation(e,"executeRaw");a$8(this.queryClient);let s=c$1(e,this.vm,void 0,void 0,this.makeLineContext(t));for(;this.vm.getStack().length>r;)this.vm.pop();return s.type!=="pending"&&i?.(),s}async resolveAsync(e){let{queryKey:t,resolver:r,packageId:i,signal:s}=e,o=i||"_engine",l=`${o}:${t}`;try{if(await r,this.asyncFailures.delete(l),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 c=a instanceof Error?a:new Error(String(a)),u=(this.asyncFailures.get(l)??0)+1;if(this.asyncFailures.set(l,u),u>_.MAX_ASYNC_FAILURES)return;this.batcher.add({queryKey:t,packageId:o,signal:s,isError:true,error:c});}}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$8(e,r)>r)throw c.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.clearCompiledCache(),this.userUnits.clear(),this.resetAccumulators();let i=this.lexer.scanDocument(e),s=this.processScanResults(i),o={lines:s,totalLines:s.length,errors:[]};for(let a of s){a.error&&o.errors.push(`Line ${a.lineNumber}: ${a.error}`);for(let c of a.inlineSolves)c.error&&o.errors.push(`Line ${a.lineNumber}: ${c.error}`);}if(t.includeDiagnostics??false){let a=this.diagnosticPipeline.collectReports();a.length>0&&(o.diagnostics=a[0].toJSON());}return o}evaluateLines(e){this.userUnits.isEmpty||this.clearCompiledCache(),this.userUnits.clear(),this.resetAccumulators();let t=e.join(`
4
- `),r=this.lexer.scanDocument(t);return this.processScanResults(r)}batchLinesCarryingTag(e,t){let r=this.batchTagIndex;if(r===null){r=new Map;for(let i=0;i<e.length;i++){let s=e[i].text;if(!(s.indexOf("#")<0))for(let o of b$9(s)){let l=r.get(o);l===void 0?r.set(o,[i+1]):l.push(i+1);}}this.batchTagIndex=r;}return r.get(t.toLowerCase())??[]}processScanResults(e){let t=[],r=this.batchScanResults,i=this.batchParsedLines;this.batchScanResults=e,this.batchParsedLines=t;let s=this.batchTagIndex;this.batchTagIndex=null;try{for(let o of e){let l=o.text,a=o.lineNumber,c=o.startOffset,u=o.endOffset,d=o.classification.skip,g=o.inlineSolves.map(S=>({start:S.start,end:S.end,expression:S.expression,lineNumber:a,columnNumber:S.columnNumber})),y=g.length>0,p={lineNumber:a,text:l,startPosition:c,endPosition:u,isEmpty:d,hasInlineSolves:y,inlineSolves:g,expression:null,result:null,error:null};if(o.error)p.error=o.error.message;else if(!d){let S=l.trim().startsWith(":");if(y&&!S)for(let b of g)try{b.result=this.evaluateLine(a,b.expression);}catch(k){let L=k instanceof Error?k.message:String(k);b.error=L;}else {let b=o.classification.contentOffset,L=(b===void 0?l:l.slice(b-c)).trim();if(L)try{let O=this.evaluateLineWithPreTokenized(a,L,o.tokens);p.expression=L,p.result=O[0];}catch(O){let re=O instanceof Error?O.message:String(O);p.error=re;}}}t.push(p);}}finally{this.batchScanResults=r,this.batchParsedLines=i,this.batchTagIndex=s,this.lineContext=null;}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 l=true;for(let a=0;a<o;a++){let c=t[a].type;if(c!=="NUMBER"&&c!=="COLON"){l=false;break}}if(l){let a=t.slice(0,o+2).map(c=>c.value).join("");throw c.parsing("INVALID_TIME_LITERAL",`"${a}" is not a valid time`,{tokenType:t[o].type,tokenValue:a})}e.reset();try{this.parseExpression(e,t.slice(o+1),r,!1);return}catch{}}throw c.parsing({code:"UNEXPECTED_TRAILING_TOKEN",message:`Unexpected token after expression: "${s.value}"`,context:{tokenType:s.type,tokenValue:s.value},span:{start:s.offset,end:s.sourceEnd??s.offset+s.text.length,line:s.line,col:s.col}})}}compileAdHoc(e){let t=new d$1(this.pluginFunctionIndexByName);return this.parseExpression(t,e),t.build()}executeSymbolicTolerant(e,t=-1){let r=c$1(e,this.vm,void 0,void 0,this.makeLineContext(t),true);if(r.type==="error")throw r.error;if(r.type==="pending")throw c.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 l of e.factorNames){let a=this.vm.getVar(l);if(a===void 0)return P("EQUATION_FACTOR_UNDEFINED",`Cannot solve for "${e.variable}": "${l}" is not yet defined.`);if(a.type!==7)return P("EQUATION_FACTOR_NOT_MATRIX",`Cannot solve for "${e.variable}": "${l}" must be a Matrix (got a different value type).`);r.push(a);}let i=r[0].value;for(let l=1;l<r.length;l++){let a=_$1(i,r[l].value);if(a.type===13)return a;i=a.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,t){if(e.length<5||e[0].type!=="NUMBER"||Number(e[0].value)!==1)return null;let r=1;e[r].type==="STAR"&&r++;let i=[];for(;r<e.length&&e[r].type==="IDENT";)i.push(e[r].value),r++;if(i.length===0||e[r]?.type!=="EQUALS"||(r++,e[r]?.type!=="NUMBER"))return null;let s=e[r];if(r++,e[r]?.type!=="UNIT")return null;let o=e[r];return r++,r!==e.length?null:(this.userUnits.define(i,s.value,o.value,t)&&(this.clearCompiledCache(),this.documentModel?.invalidateAll()),Ye(`${i.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 l=e.slice(2);if(l.length===0)throw c.parsing("COMPOUND_ASSIGN_REQUIRES_EXPRESSION",`"${r.value} ${i.value}" needs an expression on the right, e.g. "${r.value} ${i.value} 10".`);let a=r.value;this.accumulatorNames.add(a),this.vm.getVar(a)===void 0&&this.vm.setVar(a,n(0));let c$2=i.type==="PLUS_EQUALS"?{type:"PLUS",text:"+"}:{type:"MINUS",text:"-"},u=[b$a("IDENT",a,[r]),b$a(c$2.type,c$2.text,[i]),b$a("LPAREN","(",[i]),...l,b$a("RPAREN",")",[i])],d=c$1(this.compileAdHoc(u),this.vm,void 0,void 0,this.makeLineContext(t),false);if(d.type==="error")throw d.error;if(d.type==="pending")throw c.execution("COMPOUND_ASSIGN_ASYNC_UNSUPPORTED","A running total (+= / -=) cannot use an async operation (weather/stocks/currency) on its right-hand side.");return this.vm.setVar(a,d.value),d.value}resetAccumulators(){for(let e of this.accumulatorNames)this.vm.deleteVar(e);return this.accumulatorNames}trySymbolicGrammar(e$1,t=-1){if(e$1.length===0)return null;if(e$1[e$1.length-1].type==="THEREFORE"){let c$1=e$1.slice(0,-1);if(c$1.length===0)throw c.parsing("THEREFORE_REQUIRES_EXPRESSION",'"=>" needs an expression or variable name before it.');if(c$1.length===1&&(c$1[0].type==="IDENT"||c$1[0].type==="UNIT")){let u=c$1[0].value,d=this.vm.getEquation(u),g=this.vm.getScalarEquation(u);if(d){let y=this.solveEquation(d,t);if(!(y.type===13&&y.value==="EQUATION_FACTOR_NOT_MATRIX")||!g)return y}if(g)return this.solveScalarEquation(g,t)}return this.simplifySymbolically(c$1,t)}if(e(e$1))return this.simplifySymbolically(e$1,t);if(e$1[0].type==="COLON"||e$1[0].type==="GLOBAL"||e$1[0].type==="GOAL_SEEK")return null;let i=e$1.findIndex(c=>c.type==="EQUALS");if(i===-1)return null;let s=this.parseFactorChain(e$1.slice(0,i));if(s===null)return this.tryStoreScalarEquation(e$1,i);let o=e$1.slice(i+1);if(s.length===1){let c=this.simplifySymbolically(o,t);return this.vm.setVar(s[0],c),c}let l=s[s.length-1],a=s.slice(0,-1);return this.vm.defineEquation(l,a,this.compileAdHoc(o)),this.vm.defineScalarEquation(l,this.compileAdHoc(e$1.slice(0,i)),this.compileAdHoc(o)),Ye(`${l} stored as an equation \u2014 solve with "${l} =>"`)}tryStoreScalarEquation(e,t){if(e[1]?.type==="LPAREN"||t===0||t===e.length-1)return null;let r=e.slice(0,t),i=e.slice(t+1);if(i.some(l=>l.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)),Ye(`${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=this.executeSymbolicTolerant(e.rhsProgram,t);return l$1(r,i,e.variable)}lexToTokens(e,t,r=true){let i=[],s=false;if(r&&!t&&this.frontHalfCached(e))return {tokens:i,hasParens:s,compiled:true};this.lexer.resetExpression(e);for(let o of this.lexer)o.type!=="COMMENT"&&((o.type==="LPAREN"||o.type==="RPAREN")&&(s=true),i.push(o),t?.(o));return {tokens:i,hasParens:s,compiled:false}}prepareExpression(e,t,r,i,s=-1){let o=this.bytecodeCache.get(e);if(o&&!i){let b=this.compiledFrontHalf.get(e);if(b)return this.touchCompiled(e,o),{kind:"ready",normalizedTokens:b.normalizedTokens,reads:b.reads,writes:b.writes,program:o,cached:true}}let l=i?void 0:this.failedParses.get(e),a;if(l)this.touchFailedParse(e,l),a=l.normalizedTokens;else {let b=$e(e,this.config.validation);if(!b.passed)return {kind:"error",stage:"length",error:b.error.engineError};let k=t;for(let O=0;O<t.length;O++)if(t[O].type==="COMMENT"){k=t.filter(re=>re.type!=="COMMENT");break}if(k.length===0)return {kind:"empty"};a=this.normalizer.normalize(k,i);let L=je(a,this.config.validation);if(!L.passed)return {kind:"error",stage:"complexity",error:L.engineError,normalizedTokens:a}}let c,u=null;try{let b=this.documentModel?.getLineAt(s)?.lineId??-1;if(c=this.tryDefineUserUnit(a,b),c===null){let k=this.tryCompoundAssignment(a,s);k!==null&&(c=k,u=Te(a));}c===null&&(c=this.trySymbolicGrammar(a,s));}catch(b){let{reads:k,writes:L}=Te(a);return {kind:"error",stage:"parse",error:d(b),reads:k,writes:L,normalizedTokens:a}}if(c!==null)return {kind:"symbolic-solve",normalizedTokens:a,value:c,reads:u?.reads,writes:u?.writes};if(l)return {kind:"error",stage:"parse",error:l.error,reads:l.reads,writes:l.writes,normalizedTokens:a};let{reads:d$1,writes:g}=Te(a);if(o)return this.compiledFrontHalf.set(e,{normalizedTokens:a,reads:d$1,writes:g}),this.touchCompiled(e,o),{kind:"ready",normalizedTokens:a,reads:d$1,writes:g,program:o,cached:true};let y=this.builderPool[this.builderPoolIndex++%this.builderPool.length];y.reset();let p,S=null;try{if(B.isEnabled()){let b=B.track("parser",()=>(this.parseExpression(y,a,r),y.build()));p=b.result,S=b.alloc;}else this.parseExpression(y,a,r),p=y.build();}catch(b){let k=d(b);return this.rememberFailedParse(e,{error:k,normalizedTokens:a,reads:d$1,writes:g}),{kind:"error",stage:"parse",error:k,reads:d$1,writes:g,normalizedTokens:a}}return this.cacheBytecode(e,p,{normalizedTokens:a,reads:d$1,writes:g}),{kind:"ready",normalizedTokens:a,reads:d$1,writes:g,program:p,cached:false,parserAlloc:S}}preflightAsync(e,t,r,i,s,o){if(!this.mayResolve(t))return {kind:"proceed"};let l=new AbortController,a=()=>l.abort();this.keystrokeSignal?.addEventListener("abort",a,{once:true}),a$6.localControllerCreated("preflightAsync"),this.keystrokeSignal&&a$6.signalLinked("preflightAsync");let c=l.signal,u=this.resolverRegistry.preflightAll(e,t,"_engine",c,this.queryClient,this.config.network.enabled);if(u){this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.dag.registerLineDataSourceDependency(r,u.packageId||"_engine",[u.queryKey]),this.registerBackgroundRefresh(u);let d=O$1(u.queryKey);return this.storeLineResult(r,d,t,s,o,i),{kind:"pending",value:d}}return this.keystrokeSignal?.removeEventListener("abort",a),{kind:"proceed"}}evaluateWithTokens(e,t,r,i){let s=this.prepareExpression(t,r,i,void 0,e);if(s.kind==="empty"){let d=n(0);return this.lineCache.set(e,new q(d,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),t),d}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:l,writes:a,program:c}=s,u=this.preflightAsync(o,c,e,t,l,a);return u.kind==="pending"?u.value:this.executeAndStore(c,e,t,l,a,"_engine")}evaluateLine(e,t){let r=this.evaluateLineWithDebug(e,t);if(r.error)throw r.engineError?r.engineError:c.execution("EVALUATION_ERROR",r.error,{lineNumber:e});return l$2(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,l,a,c){e.push({stage:t,label:r,icon:i,colorClass:s,stepNumber:o,elapsedNs:l,skipped:a,output:c});}evaluateExpressionWithDiagnostic(e,t,r="expression"){let i=this.diagnosticPipeline,s=i.hasCollectors,o=this.timelineCollector?.parseletMatchCount??0,l=B.isEnabled(),a=[],c$1=[],u=0,d$1=$e(e,this.config.validation);if(!d$1.passed)return s&&this.addDiagnosticStage(c$1,"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:d$1.error.error}),{...d$1.error,debug:void 0,diagnostic:void 0};s&&(i.firePipelineStart({type:c$9.PipelineStart,elapsedNs:0,expression:e,inputType:r}),this.addDiagnosticStage(c$1,"pipeline_start","Pipeline Start","\u25B6","pipeline",1,u,false,{type:"pipeline_start",expression:e,inputType:r}),this.addDiagnosticStage(c$1,"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 g=s?m=>{i.fireTokenEmitted({type:c$9.TokenEmitted,elapsedNs:0,expression:e,token:{type:m.type,value:m.value,offset:m.offset||0,line:m.line||t,col:m.col||0}});}:void 0,y;if(l){let m=B.track("lexer",()=>this.lexToTokens(e,g));y=m.result,m.alloc&&a.push(m.alloc);}else y=this.lexToTokens(e,g);let p=y.tokens,S=y.hasParens,b=y.compiled;if(s){let m={};for(let P of p)m[P.type]=(m[P.type]||0)+1;this.addDiagnosticStage(c$1,"lexer","Lexer","\u{1F524}","lexer",3,u,false,{type:"lexer",tokenCount:p.length,tokenTypes:m,hasParens:S,locale:this.localeCode,tokens:[...p]});let A=[];for(let P=0;P<p.length;P++){let ae=p[P];if(ae.type==="INLINE_SOLVE_START"){let F=-1;for(let K=P+1;K<p.length;K++)if(p[K].type==="BACKTICK_OPEN"){F=K;break}if(F>P){let An=p.slice(P+1,F).map(Pn=>Pn.value).join("");A.push({startTokenIndex:P,endTokenIndex:F,expression:An,columnNumber:ae.col||1}),P=F;}}}this.addDiagnosticStage(c$1,"line_classification","Line Classification","\u{1F4CB}","classify",3.5,u,false,{type:"line_classification",classification:"expression",skip:false,hasInlineSolve:A.length>0,inlineSolveSpans:A});}if(!b&&p.length===0){let m=n(0);return this.lineCache.set(t,new q(m,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),s&&i.firePipelineEnd({type:c$9.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:0,totalOpcodes:0}),{value:m,tokens:p,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}let k=0,L=[],O=new Map,re=s?m=>{k++,L.push(m),O.set(m.rule,(O.get(m.rule)||0)+1),i.fireTokenFused({type:c$9.TokenFused,elapsedNs:0,expression:e,ruleName:m.rule,sourceTokenCount:m.sourceTokens.length,fusedTokenType:m.fusedToken.type,fusedTokenValue:m.fusedToken.value});}:void 0;s&&this.normalizer.ruleCount>0&&i.fireNormalizerStart({type:c$9.NormalizerStart,elapsedNs:0,expression:e,inputTokenCount:p.length});let M=this.bytecodeCache.get(e);s&&!M&&this.parser.setDiagnosticPipeline(i,e);let v=this.prepareExpression(e,p,S,re,t);b&&v.kind==="ready"&&(p=v.normalizedTokens),l&&v.kind==="ready"&&v.parserAlloc&&a.push(v.parserAlloc),s&&!M&&this.parser.setDiagnosticPipeline(void 0,"");let C=v.kind==="empty"?p:v.normalizedTokens??p;if(s&&(this.normalizer.ruleCount>0?(i.fireNormalizerEnd({type:c$9.NormalizerEnd,elapsedNs:0,expression:e,outputTokenCount:C.length,fusionsCount:k}),this.addDiagnosticStage(c$1,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,false,{type:"normalizer",inputTokenCount:p.length,outputTokenCount:C.length,fusions:L,rulesApplied:[...O.entries()].map(([m,A])=>({rule:m,count:A})),tokens:[...C],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(C)})):this.addDiagnosticStage(c$1,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,true,{type:"normalizer",inputTokenCount:p.length,outputTokenCount:p.length,fusions:[],rulesApplied:[],tokens:[...p],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(p)})),v.kind==="empty"||v.kind==="error"&&v.stage==="length"){if(s&&i.firePipelineEnd({type:c$9.PipelineEnd,elapsedNs:0,expression:e,success:v.kind==="empty",totalTokens:p.length,totalOpcodes:0}),v.kind==="empty"){let m=n(0);return this.lineCache.set(t,new q(m,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),{value:m,tokens:p,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}return {value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:v.error.message,engineError:v.error,debug:void 0,diagnostic:void 0}}let ie=je(C,this.config.validation);if(v.kind==="error"&&v.stage==="complexity")return s&&(this.addDiagnosticStage(c$1,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:false,complexityScore:ie.complexityScore??0,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:C.length,functionCalls:0,nestingDepth:0},errorMessage:ie.errorMessage}),i.firePipelineEnd({type:c$9.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:p.length,totalOpcodes:0})),{value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:ie.errorMessage,engineError:ie.engineError,debug:void 0,diagnostic:void 0};if(s&&this.addDiagnosticStage(c$1,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:true,complexityScore:ie.complexityScore??C.length,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:C.length,functionCalls:0,nestingDepth:0}}),v.kind==="symbolic-solve"){s&&i.firePipelineEnd({type:c$9.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:p.length,totalOpcodes:0});let m={opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false};return this.storeLineResult(t,v.value,m,v.reads??[],v.writes??[],e),{value:v.value,tokens:C,program:m,debug:void 0,diagnostic:void 0}}let se=v.reads??[],X=v.writes??[];if(s&&(this.addDiagnosticStage(c$1,"readwrite","Read/Write","\u{1F4CB}","readwrite",6,u,false,{type:"readwrite",reads:se,writes:X,isAssignment:X.length>0}),this.addDiagnosticStage(c$1,"cache_check","Cache Check","\u{1F4BE}","cache",7,u,false,{type:"cache_check",hit:!!M,cacheSize:this.bytecodeCache.size,cacheKey:e}),M?i.fireCacheHit({type:c$9.CacheHit,elapsedNs:0,expression:e,cache:"bytecode",key:e}):i.fireCacheMiss({type:c$9.CacheMiss,elapsedNs:0,expression:e,cache:"bytecode",key:e})),v.kind==="error"&&v.stage==="parse")return s&&i.firePipelineEnd({type:c$9.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:p.length,totalOpcodes:0}),{value:n(0),tokens:C,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:v.error.message,engineError:v.error,debug:void 0,diagnostic:void 0};if(v.kind!=="ready")throw c.internal({code:"UNEXPECTED_ERROR",message:"Internal error: prepareExpression() returned an unexpected variant after all other cases were handled"});let E=v.program;s&&(this.addDiagnosticStage(c$1,"parser","Parser","\u{1F333}","parser",8,u,!!M,{type:"parser",parselets:[],uniqueParseletTypes:[],astDepth:0}),this.addDiagnosticStage(c$1,"compiler","Compiler","\u2699\uFE0F","compiler",9,u,!!M,{type:"compiler",opcodeCount:E.opcodes.length,numberConstants:E.numbers.length,stringConstants:E.strings.length,hasAsync:E.hasAsync,cached:!!M}),i.fireBytecodeBuilt({type:c$9.BytecodeBuilt,elapsedNs:0,expression:e,opcodesLength:E.opcodes.length,numbersLength:E.numbers.length,stringsLength:E.strings.length,isCached:!!M}));let Nn=this.mayResolve(E),oe=this.preflightAsync(C,E,t,e,se,X);if(s&&(oe.kind==="pending"?this.addDiagnosticStage(c$1,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"pending",pendingQueryKey:oe.value.value,resolverCount:this.resolverRegistry.size,skippedGuard:true}):Nn?this.addDiagnosticStage(c$1,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"sync",resolverCount:this.resolverRegistry.size,skippedGuard:false}):this.addDiagnosticStage(c$1,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,true,{type:"async_preflight",path:"sync",resolverCount:this.resolverRegistry.size,skippedGuard:true})),oe.kind==="pending")return s&&i.firePipelineEnd({type:c$9.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:p.length,totalOpcodes:E.opcodes.length}),{value:oe.value,tokens:C,program:E,debug:void 0,diagnostic:s?this.buildDiagnosticResult(c$1,oe.value,C,E,null):void 0};let Qe=s&&this.config.diagnostic.vmTraceEnabled===true,w;try{if(l){let m=B.track("vm",()=>this.executeAndStore(E,t,e,se,X,"_engine",Qe?i:void 0,e),{cacheHit:!!M});w=m.result,m.alloc&&a.push(m.alloc);}else w=this.executeAndStore(E,t,e,se,X,"_engine",Qe?i:void 0,e);}catch(m){let A=d(m);return s&&i.firePipelineEnd({type:c$9.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:p.length,totalOpcodes:E.opcodes.length}),{value:n(0),tokens:C,program:E,error:A.message,engineError:A,debug:void 0,diagnostic:void 0}}let me=w.type===12;if(s){let m=me?"pending":String(w.value??""),A=me?"Pending":w.unit?"Uom":"Number";this.addDiagnosticStage(c$1,"vm_execute","VM Execute","\u26A1","vm",11,u,false,{type:"vm_execute",totalInstructions:E.opcodes.length,stackDepth:this.vm.getStack().length,resultType:A,resultValue:m,isPending:me});}if(me)return s&&i.firePipelineEnd({type:c$9.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:p.length,totalOpcodes:E.opcodes.length}),{value:w,tokens:C,program:E,debug:void 0,diagnostic:s?this.buildDiagnosticResult(c$1,w,C,E,null):void 0};if(l&&a.length>0&&(this.lastTelemetry=B.createTelemetry(e,a,!!M)),s&&(this.addDiagnosticStage(c$1,"dag_registration","DAG Registration","\u{1F517}","dag",12,u,false,{type:"dag_registration",readsRegistered:se,writesRegistered:X,dataSourcesRegistered:[]}),this.addDiagnosticStage(c$1,"linecache","Line Cache","\u{1F4E6}","cache",13,u,false,{type:"linecache",lineNumber:t,expression:e,stored:true}),this.addDiagnosticStage(c$1,"result","Result","\u2713","result",14,u,false,{type:"result",rawValue:String(w.value),formattedValue:String(w.value),valueType:w.type===0?"Number":"Value",unit:w.unit}),i.fireVmHalt({type:c$9.VmHalt,elapsedNs:0,expression:e,result:w?{type:w.type,value:w.value,unit:w.unit}:void 0}),this.addDiagnosticStage(c$1,"pipeline_end","Pipeline End","\u23F9","pipeline",15,u,false,{type:"pipeline_end",success:true,totalTokens:p.length,totalOpcodes:E.opcodes.length,cacheHit:!!M}),i.firePipelineEnd({type:c$9.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:p.length,totalOpcodes:E.opcodes.length})),s){let A=i.collectReports()[0]?.toJSON(),P=A;if(A){let ae=A.parselets.slice(o),F={};for(let K of ae)F[K.parseletCategory]=(F[K.parseletCategory]??0)+1;P={...A,parselets:ae,summary:{...A.summary,totalParselets:Object.keys(F).length,parseCategories:F}};}return {value:w,tokens:C,program:E,debug:P,diagnostic:this.buildDiagnosticResult(c$1,w,C,E,null)}}return {value:w,tokens:C,program:E}}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(this.touchCompiled(t,i),this.mayResolve(r.bytecode)){let l=new AbortController,a=()=>l.abort();this.keystrokeSignal?.addEventListener("abort",a,{once:true}),a$6.localControllerCreated("reEvaluateLine preflight"),this.keystrokeSignal&&a$6.signalLinked("reEvaluateLine preflight");let c=l.signal,u=this.resolverRegistry.preflightAll([],r.bytecode,"_engine",c,this.queryClient,this.config.network.enabled);if(u)return this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.registerBackgroundRefresh(u),O$1(u.queryKey);this.keystrokeSignal?.removeEventListener("abort",a);}let s=this.executeRaw(i,e);if(s.type==="pending")return this.resolveAsync(s),O$1(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,l]of this.bytecodeCache)e.push({expression:o,opcodesLength:l.opcodes.length,numbersLength:l.numbers.length,stringsLength:l.strings.length,hasAsync:l.hasAsync});let t=[];for(let o of this.lineCache.keys()){let l=o.indexOf(":"),a=l>0?parseInt(o.slice(0,l),10)||0:parseInt(o,10)||0,c=l>0?o.slice(l+1):void 0,u=c!==void 0?this.lineCache.get(a,c):this.lineCache.getEntryForLine(a);u&&t.push({key:o,lineNumber:a,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 l=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:l}]}});return {bytecode:e,lineCache:t,asyncCache:s}}getBatcherMetrics(){return {pendingCount:this.batcher.pendingCount,dedupCount:this.batcher.dedupCount,workerOffloadCount:this.batcher.workerOffloadCount,listenerCount:this.batcher.listenerCount}}getCheckpoints(){let t=this.vm.checkpointer;return t?t.getAllCheckpoints().map(i=>({lineNumber:i.lineNumber,variables:Object.keys(i.variables),variableCount:Object.keys(i.variables).length})):[]}getLastTelemetry(){return this.lastTelemetry}evaluateExpression(e){return this.evaluateLine(-1,e)}explainLine(e){let{tokens:t}=this.lexToTokens(e,void 0,false),r=t.filter(s=>s.type!=="COMMENT"),i=this.normalizer.normalize(r);return qe({expression:e,tokens:i,evaluate:s=>this.evaluateIsolated(s),locale:this.localeCode,readings:this.readDates(e)})}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.execution("EXPLAIN_ASYNC_UNSUPPORTED",`A derivation cannot be built for a line that resolves data asynchronously: "${e}"`,{expression:e});return s.value}compileExpression(e){let t=this.lexToTokens(e),{hasParens:r}=t,i=this.prepareExpression(e,t.tokens,r),s=t.compiled&&i.kind==="ready"?i.normalizedTokens:t.tokens;if(i.kind==="empty")return {program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:[],reads:[],writes:[]};if(i.kind==="error")throw i.stage==="parse"&&(i.reads?.length||i.writes?.length)?new b$b(i.error.category,{code:i.error.code,message:i.error.message,expected:i.error.expected,found:i.error.found,suggestion:i.error.suggestion,recoverable:i.error.recoverable,span:i.error.span,cause:i.error.cause,context:{...i.error.context,reads:i.reads??[],writes:i.writes??[]}}):i.error;return i.kind==="symbolic-solve"?{program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:i.normalizedTokens,reads:i.reads??[],writes:i.writes??[]}:{program:i.program,tokens:s,reads:i.reads,writes:i.writes}}tryCompileExpression(e){try{return this.tryCompileExpressionUnguarded(e)}catch{return false}}tryCompileExpressionUnguarded(e){let{tokens:t,hasParens: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$1(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.asyncFailures.clear(),this.backgroundRefresh?.clearAll(),this.queryClient.clear(),b$c()===this.queryClient&&a$8(null),this.dag.clear(),this.lineCache.clear(),this.scopeManager.clear(),this.clearCompiledCache(),this.vm.reset(),this.userUnits.clear(),this.accumulatorNames.clear(),this.lastTelemetry=null,this.lineContext=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 d=t.has(c)||u.bytecode.hasAsync;d&&t.add(c);let g=u.writeVariable;if(g){let y=i.get(g);(!y||c>=y.line)&&i.set(g,{line:c,async:d});}}let s={};for(let[c,u]of this.vm.getVariableEntries())if(u.type!==12&&!i.get(c)?.async)try{s[c]=Be(u,`variable "${c}"`);}catch(d){if(d instanceof b$b&&d.code===V.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw d}let o=this.vm.getUserFunctionDefs().map(Ue),l=[];for(let{line:c,expression:u,entry:d}of r){if(t.has(c)||d.result.type===12)continue;let g;try{g=Be(d.result,`line ${c}`);}catch(y){if(y instanceof b$b&&y.code===V.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw y}l.push({line:c,expression:u,result:g,bytecode:pe(d.bytecode),reads:d.readVariables.slice(),writeVar:d.writeVariable});}let a=Array.from(this.bytecodeCache.entries()).map(([c,u])=>({expression:c,program:pe(u)}));return {format:ee,version:Q,engineVersion:a$1,locale:this.localeCode,variables:s,userFunctions:o,lineCache:l,bytecodeCache:a}}static fromJSON(e,t={}){dn(e);let r=t.locale??e.locale??"en",i=new _({locale:r,diagnostics:t.diagnostics??false,config:t.config,packages:t.packages,calendar:t.calendar});return i.restoreSnapshot(e),i}restoreSnapshot(e){for(let[t,r]of Object.entries(e.variables))this.vm.setVar(t,Fe(r));for(let t of e.userFunctions){let r=_e(t);this.vm.defineUserFunction(r.name,r.params,r.program);}for(let t of e.lineCache){let r=new q(Fe(t.result),fe(t.bytecode),t.reads.slice(),t.writeVar);this.lineCache.set(t.line,r,t.expression),this.registerLineWithTags(t.line,t.expression,t.reads,t.writeVar?[t.writeVar]:[]);}for(let{expression:t,program:r}of e.bytecodeCache)this.bytecodeCache.set(t,fe(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 l=this.executeRaw(o.bytecode,s);if(l.type==="pending"){this.resolveAsync(l);continue}if(l.type==="error"){let c=P(l.error.code,l.error.message);i.set(s,c),o.result=c;continue}let a=l.value;i.set(s,a),o.result=a;}return i}};_.MAX_ASYNC_FAILURES=3,_.GOAL_SEEK_MAX_NESTING_DEPTH=1,_.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 Rn=_;export{or as a,Fn as b,rn as c,ee as d,Q as e,V as f,mr as g,ze as h,Ce as i,$e as j,je as k,Te as l,Lr as m,Or as n,Rn as o};//# sourceMappingURL=chunk-SFCLGBCD.js.map
5
- //# sourceMappingURL=chunk-SFCLGBCD.js.map
4
+ `),r=this.lexer.scanDocument(t);return this.processScanResults(r)}batchLinesCarryingTag(e,t){let r=this.batchTagIndex;if(r===null){r=new Map;for(let i=0;i<e.length;i++){let s=e[i].text;if(!(s.indexOf("#")<0))for(let o of b$9(s)){let l=r.get(o);l===void 0?r.set(o,[i+1]):l.push(i+1);}}this.batchTagIndex=r;}return r.get(t.toLowerCase())??[]}processScanResults(e){let t=[],r=this.batchScanResults,i=this.batchParsedLines;this.batchScanResults=e,this.batchParsedLines=t;let s=this.batchTagIndex;this.batchTagIndex=null;try{for(let o of e){let l=o.text,a=o.lineNumber,c=o.startOffset,u=o.endOffset,d=o.classification.skip,g=o.inlineSolves.map(S=>({start:S.start,end:S.end,expression:S.expression,lineNumber:a,columnNumber:S.columnNumber})),y=g.length>0,p={lineNumber:a,text:l,startPosition:c,endPosition:u,isEmpty:d,hasInlineSolves:y,inlineSolves:g,expression:null,result:null,error:null};if(o.error)p.error=o.error.message;else if(!d){let S=l.trim().startsWith(":");if(y&&!S)for(let b of g)try{b.result=this.evaluateLine(a,b.expression);}catch(k){let L=k instanceof Error?k.message:String(k);b.error=L;}else {let b=o.classification.contentOffset,L=(b===void 0?l:l.slice(b-c)).trim();if(L)try{let O=this.evaluateLineWithPreTokenized(a,L,o.tokens);p.expression=L,p.result=O[0];}catch(O){let re=O instanceof Error?O.message:String(O);p.error=re;}}}t.push(p);}}finally{this.batchScanResults=r,this.batchParsedLines=i,this.batchTagIndex=s,this.lineContext=null;}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 l=true;for(let a=0;a<o;a++){let c=t[a].type;if(c!=="NUMBER"&&c!=="COLON"){l=false;break}}if(l){let a=t.slice(0,o+2).map(c=>c.value).join("");throw c.parsing("INVALID_TIME_LITERAL",`"${a}" is not a valid time`,{tokenType:t[o].type,tokenValue:a})}e.reset();try{this.parseExpression(e,t.slice(o+1),r,!1);return}catch{}}throw c.parsing({code:"UNEXPECTED_TRAILING_TOKEN",message:`Unexpected token after expression: "${s.value}"`,context:{tokenType:s.type,tokenValue:s.value},span:{start:s.offset,end:s.sourceEnd??s.offset+s.text.length,line:s.line,col:s.col}})}}compileAdHoc(e){let t=new d$1(this.pluginFunctionIndexByName);return this.parseExpression(t,e),t.build()}executeSymbolicTolerant(e,t=-1){let r=c$1(e,this.vm,void 0,void 0,this.makeLineContext(t),true);if(r.type==="error")throw r.error;if(r.type==="pending")throw c.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 l of e.factorNames){let a=this.vm.getVar(l);if(a===void 0)return P("EQUATION_FACTOR_UNDEFINED",`Cannot solve for "${e.variable}": "${l}" is not yet defined.`);if(a.type!==7)return P("EQUATION_FACTOR_NOT_MATRIX",`Cannot solve for "${e.variable}": "${l}" must be a Matrix (got a different value type).`);r.push(a);}let i=r[0].value;for(let l=1;l<r.length;l++){let a=_$1(i,r[l].value);if(a.type===13)return a;i=a.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,t){if(e.length<5||e[0].type!=="NUMBER"||Number(e[0].value)!==1)return null;let r=1;e[r].type==="STAR"&&r++;let i=[];for(;r<e.length&&e[r].type==="IDENT";)i.push(e[r].value),r++;if(i.length===0||e[r]?.type!=="EQUALS"||(r++,e[r]?.type!=="NUMBER"))return null;let s=e[r];if(r++,e[r]?.type!=="UNIT")return null;let o=e[r];return r++,r!==e.length?null:(this.userUnits.define(i,s.value,o.value,t)&&(this.clearCompiledCache(),this.documentModel?.invalidateAll()),Ye(`${i.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 l=e.slice(2);if(l.length===0)throw c.parsing("COMPOUND_ASSIGN_REQUIRES_EXPRESSION",`"${r.value} ${i.value}" needs an expression on the right, e.g. "${r.value} ${i.value} 10".`);let a=r.value;this.accumulatorNames.add(a),this.vm.getVar(a)===void 0&&this.vm.setVar(a,n(0));let c$2=i.type==="PLUS_EQUALS"?{type:"PLUS",text:"+"}:{type:"MINUS",text:"-"},u=[b$a("IDENT",a,[r]),b$a(c$2.type,c$2.text,[i]),b$a("LPAREN","(",[i]),...l,b$a("RPAREN",")",[i])],d=c$1(this.compileAdHoc(u),this.vm,void 0,void 0,this.makeLineContext(t),false);if(d.type==="error")throw d.error;if(d.type==="pending")throw c.execution("COMPOUND_ASSIGN_ASYNC_UNSUPPORTED","A running total (+= / -=) cannot use an async operation (weather/stocks/currency) on its right-hand side.");return this.vm.setVar(a,d.value),d.value}resetAccumulators(){for(let e of this.accumulatorNames)this.vm.deleteVar(e);return this.accumulatorNames}trySymbolicGrammar(e$1,t=-1){if(e$1.length===0)return null;if(e$1[e$1.length-1].type==="THEREFORE"){let c$1=e$1.slice(0,-1);if(c$1.length===0)throw c.parsing("THEREFORE_REQUIRES_EXPRESSION",'"=>" needs an expression or variable name before it.');if(c$1.length===1&&(c$1[0].type==="IDENT"||c$1[0].type==="UNIT")){let u=c$1[0].value,d=this.vm.getEquation(u),g=this.vm.getScalarEquation(u);if(d){let y=this.solveEquation(d,t);if(!(y.type===13&&y.value==="EQUATION_FACTOR_NOT_MATRIX")||!g)return y}if(g)return this.solveScalarEquation(g,t)}return this.simplifySymbolically(c$1,t)}if(e(e$1))return this.simplifySymbolically(e$1,t);if(e$1[0].type==="COLON"||e$1[0].type==="GLOBAL"||e$1[0].type==="GOAL_SEEK")return null;let i=e$1.findIndex(c=>c.type==="EQUALS");if(i===-1)return null;let s=this.parseFactorChain(e$1.slice(0,i));if(s===null)return this.tryStoreScalarEquation(e$1,i);let o=e$1.slice(i+1);if(s.length===1){let c=this.simplifySymbolically(o,t);return this.vm.setVar(s[0],c),c}let l=s[s.length-1],a=s.slice(0,-1);return this.vm.defineEquation(l,a,this.compileAdHoc(o)),this.vm.defineScalarEquation(l,this.compileAdHoc(e$1.slice(0,i)),this.compileAdHoc(o)),Ye(`${l} stored as an equation \u2014 solve with "${l} =>"`)}tryStoreScalarEquation(e,t){if(e[1]?.type==="LPAREN"||t===0||t===e.length-1)return null;let r=e.slice(0,t),i=e.slice(t+1);if(i.some(l=>l.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)),Ye(`${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=this.executeSymbolicTolerant(e.rhsProgram,t);return l$1(r,i,e.variable)}lexToTokens(e,t,r=true){let i=[],s=false;if(r&&!t&&this.frontHalfCached(e))return {tokens:i,hasParens:s,compiled:true};this.lexer.resetExpression(e);for(let o of this.lexer)o.type!=="COMMENT"&&((o.type==="LPAREN"||o.type==="RPAREN")&&(s=true),i.push(o),t?.(o));return {tokens:i,hasParens:s,compiled:false}}prepareExpression(e,t,r,i,s=-1){let o=this.bytecodeCache.get(e);if(o&&!i){let b=this.compiledFrontHalf.get(e);if(b)return this.touchCompiled(e,o),{kind:"ready",normalizedTokens:b.normalizedTokens,reads:b.reads,writes:b.writes,program:o,cached:true}}let l=i?void 0:this.failedParses.get(e),a;if(l)this.touchFailedParse(e,l),a=l.normalizedTokens;else {let b=$e(e,this.config.validation);if(!b.passed)return {kind:"error",stage:"length",error:b.error.engineError};let k=t;for(let O=0;O<t.length;O++)if(t[O].type==="COMMENT"){k=t.filter(re=>re.type!=="COMMENT");break}if(k.length===0)return {kind:"empty"};a=this.normalizer.normalize(k,i);let L=je(a,this.config.validation);if(!L.passed)return {kind:"error",stage:"complexity",error:L.engineError,normalizedTokens:a}}let c,u=null;try{let b=this.documentModel?.getLineAt(s)?.lineId??-1;if(c=this.tryDefineUserUnit(a,b),c===null){let k=this.tryCompoundAssignment(a,s);k!==null&&(c=k,u=Te(a));}c===null&&(c=this.trySymbolicGrammar(a,s));}catch(b){let{reads:k,writes:L}=Te(a);return {kind:"error",stage:"parse",error:d(b),reads:k,writes:L,normalizedTokens:a}}if(c!==null)return {kind:"symbolic-solve",normalizedTokens:a,value:c,reads:u?.reads,writes:u?.writes};if(l)return {kind:"error",stage:"parse",error:l.error,reads:l.reads,writes:l.writes,normalizedTokens:a};let{reads:d$1,writes:g}=Te(a);if(o)return this.compiledFrontHalf.set(e,{normalizedTokens:a,reads:d$1,writes:g}),this.touchCompiled(e,o),{kind:"ready",normalizedTokens:a,reads:d$1,writes:g,program:o,cached:true};let y=this.builderPool[this.builderPoolIndex++%this.builderPool.length];y.reset();let p,S=null;try{if(B.isEnabled()){let b=B.track("parser",()=>(this.parseExpression(y,a,r),y.build()));p=b.result,S=b.alloc;}else this.parseExpression(y,a,r),p=y.build();}catch(b){let k=d(b);return this.rememberFailedParse(e,{error:k,normalizedTokens:a,reads:d$1,writes:g}),{kind:"error",stage:"parse",error:k,reads:d$1,writes:g,normalizedTokens:a}}return this.cacheBytecode(e,p,{normalizedTokens:a,reads:d$1,writes:g}),{kind:"ready",normalizedTokens:a,reads:d$1,writes:g,program:p,cached:false,parserAlloc:S}}preflightAsync(e,t,r,i,s,o){if(!this.mayResolve(t))return {kind:"proceed"};let l=new AbortController,a=()=>l.abort();this.keystrokeSignal?.addEventListener("abort",a,{once:true}),a$6.localControllerCreated("preflightAsync"),this.keystrokeSignal&&a$6.signalLinked("preflightAsync");let c=l.signal,u=this.resolverRegistry.preflightAll(e,t,"_engine",c,this.queryClient,this.config.network.enabled);if(u){this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.dag.registerLineDataSourceDependency(r,u.packageId||"_engine",[u.queryKey]),this.registerBackgroundRefresh(u);let d=O$1(u.queryKey);return this.storeLineResult(r,d,t,s,o,i),{kind:"pending",value:d}}return this.keystrokeSignal?.removeEventListener("abort",a),{kind:"proceed"}}evaluateWithTokens(e,t,r,i){let s=this.prepareExpression(t,r,i,void 0,e);if(s.kind==="empty"){let d=n(0);return this.lineCache.set(e,new q(d,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),t),d}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:l,writes:a,program:c}=s,u=this.preflightAsync(o,c,e,t,l,a);return u.kind==="pending"?u.value:this.executeAndStore(c,e,t,l,a,"_engine")}evaluateLine(e,t){let r=this.evaluateLineWithDebug(e,t);if(r.error)throw r.engineError?r.engineError:c.execution("EVALUATION_ERROR",r.error,{lineNumber:e});return l$2(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,l,a,c){e.push({stage:t,label:r,icon:i,colorClass:s,stepNumber:o,elapsedNs:l,skipped:a,output:c});}evaluateExpressionWithDiagnostic(e,t,r="expression"){let i=this.diagnosticPipeline,s=i.hasCollectors,o=this.timelineCollector?.parseletMatchCount??0,l=B.isEnabled(),a=[],c$1=[],u=0,d$1=$e(e,this.config.validation);if(!d$1.passed)return s&&this.addDiagnosticStage(c$1,"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:d$1.error.error}),{...d$1.error,debug:void 0,diagnostic:void 0};s&&(i.firePipelineStart({type:c$9.PipelineStart,elapsedNs:0,expression:e,inputType:r}),this.addDiagnosticStage(c$1,"pipeline_start","Pipeline Start","\u25B6","pipeline",1,u,false,{type:"pipeline_start",expression:e,inputType:r}),this.addDiagnosticStage(c$1,"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 g=s?m=>{i.fireTokenEmitted({type:c$9.TokenEmitted,elapsedNs:0,expression:e,token:{type:m.type,value:m.value,offset:m.offset||0,line:m.line||t,col:m.col||0}});}:void 0,y;if(l){let m=B.track("lexer",()=>this.lexToTokens(e,g));y=m.result,m.alloc&&a.push(m.alloc);}else y=this.lexToTokens(e,g);let p=y.tokens,S=y.hasParens,b=y.compiled;if(s){let m={};for(let P of p)m[P.type]=(m[P.type]||0)+1;this.addDiagnosticStage(c$1,"lexer","Lexer","\u{1F524}","lexer",3,u,false,{type:"lexer",tokenCount:p.length,tokenTypes:m,hasParens:S,locale:this.localeCode,tokens:[...p]});let A=[];for(let P=0;P<p.length;P++){let ae=p[P];if(ae.type==="INLINE_SOLVE_START"){let F=-1;for(let K=P+1;K<p.length;K++)if(p[K].type==="BACKTICK_OPEN"){F=K;break}if(F>P){let An=p.slice(P+1,F).map(Pn=>Pn.value).join("");A.push({startTokenIndex:P,endTokenIndex:F,expression:An,columnNumber:ae.col||1}),P=F;}}}this.addDiagnosticStage(c$1,"line_classification","Line Classification","\u{1F4CB}","classify",3.5,u,false,{type:"line_classification",classification:"expression",skip:false,hasInlineSolve:A.length>0,inlineSolveSpans:A});}if(!b&&p.length===0){let m=n(0);return this.lineCache.set(t,new q(m,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),s&&i.firePipelineEnd({type:c$9.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:0,totalOpcodes:0}),{value:m,tokens:p,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}let k=0,L=[],O=new Map,re=s?m=>{k++,L.push(m),O.set(m.rule,(O.get(m.rule)||0)+1),i.fireTokenFused({type:c$9.TokenFused,elapsedNs:0,expression:e,ruleName:m.rule,sourceTokenCount:m.sourceTokens.length,fusedTokenType:m.fusedToken.type,fusedTokenValue:m.fusedToken.value});}:void 0;s&&this.normalizer.ruleCount>0&&i.fireNormalizerStart({type:c$9.NormalizerStart,elapsedNs:0,expression:e,inputTokenCount:p.length});let M=this.bytecodeCache.get(e);s&&!M&&this.parser.setDiagnosticPipeline(i,e);let v=this.prepareExpression(e,p,S,re,t);b&&v.kind==="ready"&&(p=v.normalizedTokens),l&&v.kind==="ready"&&v.parserAlloc&&a.push(v.parserAlloc),s&&!M&&this.parser.setDiagnosticPipeline(void 0,"");let C=v.kind==="empty"?p:v.normalizedTokens??p;if(s&&(this.normalizer.ruleCount>0?(i.fireNormalizerEnd({type:c$9.NormalizerEnd,elapsedNs:0,expression:e,outputTokenCount:C.length,fusionsCount:k}),this.addDiagnosticStage(c$1,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,false,{type:"normalizer",inputTokenCount:p.length,outputTokenCount:C.length,fusions:L,rulesApplied:[...O.entries()].map(([m,A])=>({rule:m,count:A})),tokens:[...C],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(C)})):this.addDiagnosticStage(c$1,"normalizer","Normalizer","\u{1F504}","normalizer",4,u,true,{type:"normalizer",inputTokenCount:p.length,outputTokenCount:p.length,fusions:[],rulesApplied:[],tokens:[...p],phrases:this.normalizer.getPhrases(),ruleShapes:this.normalizer.getRuleShapes(),candidatesPerPosition:this.normalizer.getCandidateCounts(p)})),v.kind==="empty"||v.kind==="error"&&v.stage==="length"){if(s&&i.firePipelineEnd({type:c$9.PipelineEnd,elapsedNs:0,expression:e,success:v.kind==="empty",totalTokens:p.length,totalOpcodes:0}),v.kind==="empty"){let m=n(0);return this.lineCache.set(t,new q(m,{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},[],null),e),{value:m,tokens:p,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},debug:void 0,diagnostic:void 0}}return {value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:v.error.message,engineError:v.error,debug:void 0,diagnostic:void 0}}let ie=je(C,this.config.validation);if(v.kind==="error"&&v.stage==="complexity")return s&&(this.addDiagnosticStage(c$1,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:false,complexityScore:ie.complexityScore??0,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:C.length,functionCalls:0,nestingDepth:0},errorMessage:ie.errorMessage}),i.firePipelineEnd({type:c$9.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:p.length,totalOpcodes:0})),{value:n(0),tokens:[],program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:ie.errorMessage,engineError:ie.engineError,debug:void 0,diagnostic:void 0};if(s&&this.addDiagnosticStage(c$1,"safety_complexity","Safety: Complexity","\u{1F6E1}\uFE0F","validate",5,u,false,{type:"safety_complexity",passed:true,complexityScore:ie.complexityScore??C.length,maxComplexity:this.config.validation.maxComplexity,breakdown:{tokenCount:C.length,functionCalls:0,nestingDepth:0}}),v.kind==="symbolic-solve"){s&&i.firePipelineEnd({type:c$9.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:p.length,totalOpcodes:0});let m={opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false};return this.storeLineResult(t,v.value,m,v.reads??[],v.writes??[],e),{value:v.value,tokens:C,program:m,debug:void 0,diagnostic:void 0}}let se=v.reads??[],X=v.writes??[];if(s&&(this.addDiagnosticStage(c$1,"readwrite","Read/Write","\u{1F4CB}","readwrite",6,u,false,{type:"readwrite",reads:se,writes:X,isAssignment:X.length>0}),this.addDiagnosticStage(c$1,"cache_check","Cache Check","\u{1F4BE}","cache",7,u,false,{type:"cache_check",hit:!!M,cacheSize:this.bytecodeCache.size,cacheKey:e}),M?i.fireCacheHit({type:c$9.CacheHit,elapsedNs:0,expression:e,cache:"bytecode",key:e}):i.fireCacheMiss({type:c$9.CacheMiss,elapsedNs:0,expression:e,cache:"bytecode",key:e})),v.kind==="error"&&v.stage==="parse")return s&&i.firePipelineEnd({type:c$9.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:p.length,totalOpcodes:0}),{value:n(0),tokens:C,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},error:v.error.message,engineError:v.error,debug:void 0,diagnostic:void 0};if(v.kind!=="ready")throw c.internal({code:"UNEXPECTED_ERROR",message:"Internal error: prepareExpression() returned an unexpected variant after all other cases were handled"});let E=v.program;s&&(this.addDiagnosticStage(c$1,"parser","Parser","\u{1F333}","parser",8,u,!!M,{type:"parser",parselets:[],uniqueParseletTypes:[],astDepth:0}),this.addDiagnosticStage(c$1,"compiler","Compiler","\u2699\uFE0F","compiler",9,u,!!M,{type:"compiler",opcodeCount:E.opcodes.length,numberConstants:E.numbers.length,stringConstants:E.strings.length,hasAsync:E.hasAsync,cached:!!M}),i.fireBytecodeBuilt({type:c$9.BytecodeBuilt,elapsedNs:0,expression:e,opcodesLength:E.opcodes.length,numbersLength:E.numbers.length,stringsLength:E.strings.length,isCached:!!M}));let Nn=this.mayResolve(E),oe=this.preflightAsync(C,E,t,e,se,X);if(s&&(oe.kind==="pending"?this.addDiagnosticStage(c$1,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"pending",pendingQueryKey:oe.value.value,resolverCount:this.resolverRegistry.size,skippedGuard:true}):Nn?this.addDiagnosticStage(c$1,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,false,{type:"async_preflight",path:"sync",resolverCount:this.resolverRegistry.size,skippedGuard:false}):this.addDiagnosticStage(c$1,"async_preflight","Async Preflight","\u{1F52E}","async",10,u,true,{type:"async_preflight",path:"sync",resolverCount:this.resolverRegistry.size,skippedGuard:true})),oe.kind==="pending")return s&&i.firePipelineEnd({type:c$9.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:p.length,totalOpcodes:E.opcodes.length}),{value:oe.value,tokens:C,program:E,debug:void 0,diagnostic:s?this.buildDiagnosticResult(c$1,oe.value,C,E,null):void 0};let Qe=s&&this.config.diagnostic.vmTraceEnabled===true,w;try{if(l){let m=B.track("vm",()=>this.executeAndStore(E,t,e,se,X,"_engine",Qe?i:void 0,e),{cacheHit:!!M});w=m.result,m.alloc&&a.push(m.alloc);}else w=this.executeAndStore(E,t,e,se,X,"_engine",Qe?i:void 0,e);}catch(m){let A=d(m);return s&&i.firePipelineEnd({type:c$9.PipelineEnd,elapsedNs:0,expression:e,success:false,totalTokens:p.length,totalOpcodes:E.opcodes.length}),{value:n(0),tokens:C,program:E,error:A.message,engineError:A,debug:void 0,diagnostic:void 0}}let me=w.type===12;if(s){let m=me?"pending":String(w.value??""),A=me?"Pending":w.unit?"Uom":"Number";this.addDiagnosticStage(c$1,"vm_execute","VM Execute","\u26A1","vm",11,u,false,{type:"vm_execute",totalInstructions:E.opcodes.length,stackDepth:this.vm.getStack().length,resultType:A,resultValue:m,isPending:me});}if(me)return s&&i.firePipelineEnd({type:c$9.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:p.length,totalOpcodes:E.opcodes.length}),{value:w,tokens:C,program:E,debug:void 0,diagnostic:s?this.buildDiagnosticResult(c$1,w,C,E,null):void 0};if(l&&a.length>0&&(this.lastTelemetry=B.createTelemetry(e,a,!!M)),s&&(this.addDiagnosticStage(c$1,"dag_registration","DAG Registration","\u{1F517}","dag",12,u,false,{type:"dag_registration",readsRegistered:se,writesRegistered:X,dataSourcesRegistered:[]}),this.addDiagnosticStage(c$1,"linecache","Line Cache","\u{1F4E6}","cache",13,u,false,{type:"linecache",lineNumber:t,expression:e,stored:true}),this.addDiagnosticStage(c$1,"result","Result","\u2713","result",14,u,false,{type:"result",rawValue:String(w.value),formattedValue:String(w.value),valueType:w.type===0?"Number":"Value",unit:w.unit}),i.fireVmHalt({type:c$9.VmHalt,elapsedNs:0,expression:e,result:w?{type:w.type,value:w.value,unit:w.unit}:void 0}),this.addDiagnosticStage(c$1,"pipeline_end","Pipeline End","\u23F9","pipeline",15,u,false,{type:"pipeline_end",success:true,totalTokens:p.length,totalOpcodes:E.opcodes.length,cacheHit:!!M}),i.firePipelineEnd({type:c$9.PipelineEnd,elapsedNs:0,expression:e,success:true,totalTokens:p.length,totalOpcodes:E.opcodes.length})),s){let A=i.collectReports()[0]?.toJSON(),P=A;if(A){let ae=A.parselets.slice(o),F={};for(let K of ae)F[K.parseletCategory]=(F[K.parseletCategory]??0)+1;P={...A,parselets:ae,summary:{...A.summary,totalParselets:Object.keys(F).length,parseCategories:F}};}return {value:w,tokens:C,program:E,debug:P,diagnostic:this.buildDiagnosticResult(c$1,w,C,E,null)}}return {value:w,tokens:C,program:E}}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(this.touchCompiled(t,i),this.mayResolve(r.bytecode)){let l=new AbortController,a=()=>l.abort();this.keystrokeSignal?.addEventListener("abort",a,{once:true}),a$6.localControllerCreated("reEvaluateLine preflight"),this.keystrokeSignal&&a$6.signalLinked("reEvaluateLine preflight");let c=l.signal,u=this.resolverRegistry.preflightAll([],r.bytecode,"_engine",c,this.queryClient,this.config.network.enabled);if(u)return this.resolveAsync({type:"pending",queryKey:u.queryKey,resolver:u.resolver,packageId:u.packageId||"_engine",signal:u.signal}),this.registerBackgroundRefresh(u),O$1(u.queryKey);this.keystrokeSignal?.removeEventListener("abort",a);}let s=this.executeRaw(i,e);if(s.type==="pending")return this.resolveAsync(s),O$1(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,l]of this.bytecodeCache)e.push({expression:o,opcodesLength:l.opcodes.length,numbersLength:l.numbers.length,stringsLength:l.strings.length,hasAsync:l.hasAsync});let t=[];for(let o of this.lineCache.keys()){let l=o.indexOf(":"),a=l>0?parseInt(o.slice(0,l),10)||0:parseInt(o,10)||0,c=l>0?o.slice(l+1):void 0,u=c!==void 0?this.lineCache.get(a,c):this.lineCache.getEntryForLine(a);u&&t.push({key:o,lineNumber:a,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 l=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:l}]}});return {bytecode:e,lineCache:t,asyncCache:s}}getBatcherMetrics(){return {pendingCount:this.batcher.pendingCount,dedupCount:this.batcher.dedupCount,workerOffloadCount:this.batcher.workerOffloadCount,listenerCount:this.batcher.listenerCount}}getCheckpoints(){let t=this.vm.checkpointer;return t?t.getAllCheckpoints().map(i=>({lineNumber:i.lineNumber,variables:Object.keys(i.variables),variableCount:Object.keys(i.variables).length})):[]}getLastTelemetry(){return this.lastTelemetry}evaluateExpression(e){return this.evaluateLine(-1,e)}explainLine(e){let{tokens:t}=this.lexToTokens(e,void 0,false),r=t.filter(s=>s.type!=="COMMENT"),i=this.normalizer.normalize(r);return qe({expression:e,tokens:i,evaluate:s=>this.evaluateIsolated(s),locale:this.localeCode,readings:this.readDates(e)})}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.execution("EXPLAIN_ASYNC_UNSUPPORTED",`A derivation cannot be built for a line that resolves data asynchronously: "${e}"`,{expression:e});return s.value}compileExpression(e){let t=this.lexToTokens(e),{hasParens:r}=t,i=this.prepareExpression(e,t.tokens,r),s=t.compiled&&i.kind==="ready"?i.normalizedTokens:t.tokens;if(i.kind==="empty")return {program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:[],reads:[],writes:[]};if(i.kind==="error")throw i.stage==="parse"&&(i.reads?.length||i.writes?.length)?new b$b(i.error.category,{code:i.error.code,message:i.error.message,expected:i.error.expected,found:i.error.found,suggestion:i.error.suggestion,recoverable:i.error.recoverable,span:i.error.span,cause:i.error.cause,context:{...i.error.context,reads:i.reads??[],writes:i.writes??[]}}):i.error;return i.kind==="symbolic-solve"?{program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},tokens:i.normalizedTokens,reads:i.reads??[],writes:i.writes??[]}:{program:i.program,tokens:s,reads:i.reads,writes:i.writes}}tryCompileExpression(e){try{return this.tryCompileExpressionUnguarded(e)}catch{return false}}tryCompileExpressionUnguarded(e){let{tokens:t,hasParens: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$1(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.asyncFailures.clear(),this.backgroundRefresh?.clearAll(),this.queryClient.clear(),b$c()===this.queryClient&&a$8(null),this.dag.clear(),this.lineCache.clear(),this.scopeManager.clear(),this.clearCompiledCache(),this.vm.reset(),this.userUnits.clear(),this.accumulatorNames.clear(),this.lastTelemetry=null,this.lineContext=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 d=t.has(c)||u.bytecode.hasAsync;d&&t.add(c);let g=u.writeVariable;if(g){let y=i.get(g);(!y||c>=y.line)&&i.set(g,{line:c,async:d});}}let s={};for(let[c,u]of this.vm.getVariableEntries())if(u.type!==12&&!i.get(c)?.async)try{s[c]=Be(u,`variable "${c}"`);}catch(d){if(d instanceof b$b&&d.code===V.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw d}let o=this.vm.getUserFunctionDefs().map(Ue),l=[];for(let{line:c,expression:u,entry:d}of r){if(t.has(c)||d.result.type===12)continue;let g;try{g=Be(d.result,`line ${c}`);}catch(y){if(y instanceof b$b&&y.code===V.SNAPSHOT_UNSUPPORTED_VALUE)continue;throw y}l.push({line:c,expression:u,result:g,bytecode:pe(d.bytecode),reads:d.readVariables.slice(),writeVar:d.writeVariable});}let a=Array.from(this.bytecodeCache.entries()).map(([c,u])=>({expression:c,program:pe(u)}));return {format:ee,version:Q,engineVersion:a$1,locale:this.localeCode,variables:s,userFunctions:o,lineCache:l,bytecodeCache:a}}static fromJSON(e,t={}){dn(e);let r=t.locale??e.locale??"en",i=new _({locale:r,diagnostics:t.diagnostics??false,config:t.config,packages:t.packages,calendar:t.calendar});return i.restoreSnapshot(e),i}restoreSnapshot(e){for(let[t,r]of Object.entries(e.variables))this.vm.setVar(t,Fe(r));for(let t of e.userFunctions){let r=_e(t);this.vm.defineUserFunction(r.name,r.params,r.program);}for(let t of e.lineCache){let r=new q(Fe(t.result),fe(t.bytecode),t.reads.slice(),t.writeVar);this.lineCache.set(t.line,r,t.expression),this.registerLineWithTags(t.line,t.expression,t.reads,t.writeVar?[t.writeVar]:[]);}for(let{expression:t,program:r}of e.bytecodeCache)this.bytecodeCache.set(t,fe(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 l=this.executeRaw(o.bytecode,s);if(l.type==="pending"){this.resolveAsync(l);continue}if(l.type==="error"){let c=P(l.error.code,l.error.message);i.set(s,c),o.result=c;continue}let a=l.value;i.set(s,a),o.result=a;}return i}};_.MAX_ASYNC_FAILURES=3,_.GOAL_SEEK_MAX_NESTING_DEPTH=1,_.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 Rn=_;export{or as a,Fn as b,rn as c,ee as d,Q as e,V as f,mr as g,ze as h,Ce as i,$e as j,je as k,Te as l,Lr as m,Or as n,Rn as o};//# sourceMappingURL=chunk-34RTVUU3.js.map
5
+ //# sourceMappingURL=chunk-34RTVUU3.js.map