solve-engine 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/{Configuration-B6W0-T67.d.cts → Configuration-Culg8H_o.d.cts} +17 -0
  2. package/dist/{Configuration-B6W0-T67.d.ts → Configuration-Culg8H_o.d.ts} +17 -0
  3. package/dist/{PackageCompatibility-Cv7zjqSV.d.cts → PackageCompatibility-CN-2CVhu.d.cts} +1 -1
  4. package/dist/{PackageCompatibility-DBsZ0l2a.d.ts → PackageCompatibility-DbpyKYOe.d.ts} +1 -1
  5. package/dist/{PackageRegistry-BSGQ6saH.d.cts → PackageRegistry-DXsvmpQN.d.cts} +24 -1
  6. package/dist/{PackageRegistry-DRbqNJfI.d.ts → PackageRegistry-jqdAsm6U.d.ts} +24 -1
  7. package/dist/{chunk-7GK3XEZF.js → chunk-7E7NXKQ5.js} +2 -2
  8. package/dist/chunk-7E7NXKQ5.js.map +1 -0
  9. package/dist/chunk-AIIPKVKO.js +3 -0
  10. package/dist/chunk-AIIPKVKO.js.map +1 -0
  11. package/dist/chunk-BAVZMGTZ.cjs +2 -0
  12. package/dist/chunk-BAVZMGTZ.cjs.map +1 -0
  13. package/dist/chunk-ESXQDRP7.js +2 -0
  14. package/dist/chunk-ESXQDRP7.js.map +1 -0
  15. package/dist/chunk-JFREB45J.cjs +3 -0
  16. package/dist/chunk-JFREB45J.cjs.map +1 -0
  17. package/dist/chunk-L7ZQQ773.cjs +5 -0
  18. package/dist/chunk-L7ZQQ773.cjs.map +1 -0
  19. package/dist/{chunk-ZCNBT44X.cjs → chunk-LNZNJSRW.cjs} +2 -2
  20. package/dist/chunk-LNZNJSRW.cjs.map +1 -0
  21. package/dist/chunk-NNYMXK6H.js +5 -0
  22. package/dist/chunk-NNYMXK6H.js.map +1 -0
  23. package/dist/{chunk-6C6IPUBH.cjs → chunk-PBGPQM3X.cjs} +3 -3
  24. package/dist/{chunk-6C6IPUBH.cjs.map → chunk-PBGPQM3X.cjs.map} +1 -1
  25. package/dist/{chunk-7NXAZJDB.js → chunk-PXWOATTF.js} +3 -3
  26. package/dist/{chunk-7NXAZJDB.js.map → chunk-PXWOATTF.js.map} +1 -1
  27. package/dist/constants.cjs +1 -1
  28. package/dist/constants.d.cts +1 -1
  29. package/dist/constants.d.ts +1 -1
  30. package/dist/constants.js +1 -1
  31. package/dist/engine.cjs +1 -1
  32. package/dist/engine.d.cts +5 -5
  33. package/dist/engine.d.ts +5 -5
  34. package/dist/engine.js +1 -1
  35. package/dist/index.cjs +1 -1
  36. package/dist/index.d.cts +4 -4
  37. package/dist/index.d.ts +4 -4
  38. package/dist/index.js +1 -1
  39. package/dist/language.d.cts +3 -3
  40. package/dist/language.d.ts +3 -3
  41. package/dist/packages.cjs +1 -1
  42. package/dist/packages.d.cts +11 -2
  43. package/dist/packages.d.ts +11 -2
  44. package/dist/packages.js +1 -1
  45. package/dist/resolvers.cjs +1 -1
  46. package/dist/resolvers.d.cts +14 -0
  47. package/dist/resolvers.d.ts +14 -0
  48. package/dist/resolvers.js +1 -1
  49. package/dist/testing.cjs +2 -2
  50. package/dist/testing.d.cts +3 -3
  51. package/dist/testing.d.ts +3 -3
  52. package/dist/testing.js +1 -1
  53. package/dist/worker.cjs +2 -2
  54. package/dist/worker.d.cts +2 -2
  55. package/dist/worker.d.ts +2 -2
  56. package/dist/worker.js +1 -1
  57. package/package.json +1 -1
  58. package/dist/chunk-7GK3XEZF.js.map +0 -1
  59. package/dist/chunk-E2Q3PQ2G.js +0 -3
  60. package/dist/chunk-E2Q3PQ2G.js.map +0 -1
  61. package/dist/chunk-KVTOV3TZ.js +0 -2
  62. package/dist/chunk-KVTOV3TZ.js.map +0 -1
  63. package/dist/chunk-OVKDDTXO.cjs +0 -3
  64. package/dist/chunk-OVKDDTXO.cjs.map +0 -1
  65. package/dist/chunk-U2UZJX5W.cjs +0 -5
  66. package/dist/chunk-U2UZJX5W.cjs.map +0 -1
  67. package/dist/chunk-X3R7B7XM.cjs +0 -2
  68. package/dist/chunk-X3R7B7XM.cjs.map +0 -1
  69. package/dist/chunk-YU3PACLE.js +0 -5
  70. package/dist/chunk-YU3PACLE.js.map +0 -1
  71. package/dist/chunk-ZCNBT44X.cjs.map +0 -1
@@ -171,6 +171,21 @@ interface DiagnosticConfig {
171
171
  /** Enable VM trace mode, emits per-opcode execution events (very verbose; disables some optimizations) */
172
172
  readonly vmTraceEnabled: boolean;
173
173
  }
174
+ /**
175
+ * Proactive background refresh of live async values.
176
+ *
177
+ * Off by default. When a live value (a stock quote, an FX rate) has gone
178
+ * stale, today it only refetches on the next re-evaluation (a keystroke), so a
179
+ * note left open silently ages. With this enabled, the engine drives a refetch
180
+ * on each such value's own cadence (the resolver's `refetchIntervalMs`) for the
181
+ * values currently on screen, and pushes the fresh result to the host through
182
+ * the same event stream the pull path uses. It needs timers and a live editor
183
+ * consuming that stream, so a headless or batch host leaves it off.
184
+ */
185
+ interface BackgroundRefreshConfig {
186
+ /** Master switch. When false, no timers run and every value refreshes only on re-evaluation. */
187
+ readonly enabled: boolean;
188
+ }
174
189
  /**
175
190
  * Virtual Machine configuration.
176
191
  * Controls the internal bytecode VM that executes compiled expressions.
@@ -283,6 +298,8 @@ interface EngineConfig {
283
298
  readonly worker: WorkerConfig;
284
299
  /** Diagnostic pipeline configuration */
285
300
  readonly diagnostic: DiagnosticConfig;
301
+ /** Proactive background refresh of live async values */
302
+ readonly backgroundRefresh: BackgroundRefreshConfig;
286
303
  }
287
304
  /**
288
305
  * A partial {@link EngineConfig} override, one section at a time.
@@ -171,6 +171,21 @@ interface DiagnosticConfig {
171
171
  /** Enable VM trace mode, emits per-opcode execution events (very verbose; disables some optimizations) */
172
172
  readonly vmTraceEnabled: boolean;
173
173
  }
174
+ /**
175
+ * Proactive background refresh of live async values.
176
+ *
177
+ * Off by default. When a live value (a stock quote, an FX rate) has gone
178
+ * stale, today it only refetches on the next re-evaluation (a keystroke), so a
179
+ * note left open silently ages. With this enabled, the engine drives a refetch
180
+ * on each such value's own cadence (the resolver's `refetchIntervalMs`) for the
181
+ * values currently on screen, and pushes the fresh result to the host through
182
+ * the same event stream the pull path uses. It needs timers and a live editor
183
+ * consuming that stream, so a headless or batch host leaves it off.
184
+ */
185
+ interface BackgroundRefreshConfig {
186
+ /** Master switch. When false, no timers run and every value refreshes only on re-evaluation. */
187
+ readonly enabled: boolean;
188
+ }
174
189
  /**
175
190
  * Virtual Machine configuration.
176
191
  * Controls the internal bytecode VM that executes compiled expressions.
@@ -283,6 +298,8 @@ interface EngineConfig {
283
298
  readonly worker: WorkerConfig;
284
299
  /** Diagnostic pipeline configuration */
285
300
  readonly diagnostic: DiagnosticConfig;
301
+ /** Proactive background refresh of live async values */
302
+ readonly backgroundRefresh: BackgroundRefreshConfig;
286
303
  }
287
304
  /**
288
305
  * A partial {@link EngineConfig} override, one section at a time.
@@ -1,4 +1,4 @@
1
- import { I as IEnginePackage } from './PackageRegistry-BSGQ6saH.cjs';
1
+ import { I as IEnginePackage } from './PackageRegistry-DXsvmpQN.cjs';
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-DRbqNJfI.js';
1
+ import { I as IEnginePackage } from './PackageRegistry-jqdAsm6U.js';
2
2
 
3
3
  /**
4
4
  * Package load-time compatibility checking, the "detect overlapping
@@ -9,7 +9,7 @@ import { QueryClient } from '@tanstack/query-core';
9
9
  import { E as EngineError } from './EngineError-Ce1lPkjZ.cjs';
10
10
  import { a as DiagnosticReportJSON, D as DiagnosticPipeline } from './pipeline-DCQicwWX.cjs';
11
11
  import { T as Token } from './Token-CbP_OutD.cjs';
12
- import { E as EngineConfigOverride, a as EngineConfig } from './Configuration-B6W0-T67.cjs';
12
+ import { E as EngineConfigOverride, a as EngineConfig } from './Configuration-Culg8H_o.cjs';
13
13
 
14
14
  /**
15
15
  * One line's compiled bytecode, plus the variables it reads and writes.
@@ -1690,6 +1690,17 @@ declare class ExpressionEngine {
1690
1690
  * DAG walk + re-evaluation pass. Replaces the old single-callback pattern.
1691
1691
  */
1692
1692
  private batcher;
1693
+ /**
1694
+ * Drives proactive background refresh of live values, or `null` when the
1695
+ * host has not enabled it (the default). See {@link BackgroundRefreshManager}.
1696
+ */
1697
+ private readonly backgroundRefresh;
1698
+ /**
1699
+ * The signal a background re-evaluation is dispatched under. Never aborted
1700
+ * (a background refetch is not tied to a keystroke), so the batcher treats
1701
+ * its results as current; the manager's own timers are what stop the work.
1702
+ */
1703
+ private readonly backgroundRefreshSignal;
1693
1704
  /** Post-lexer token normalizer for phrase fusion, implicit multiply, etc. */
1694
1705
  private normalizer;
1695
1706
  /**
@@ -1848,6 +1859,18 @@ declare class ExpressionEngine {
1848
1859
  * and fires typed events to all listeners.
1849
1860
  */
1850
1861
  private resolveAsync;
1862
+ /**
1863
+ * Start refreshing a value in the background if it declared a cadence and the
1864
+ * host enabled background refresh. A no-op otherwise, so the pull path is
1865
+ * unchanged for a headless host or a value that never wants it.
1866
+ */
1867
+ private registerBackgroundRefresh;
1868
+ /**
1869
+ * How many live values are currently being refreshed in the background.
1870
+ * Zero when the host has not enabled background refresh. For hosts that want
1871
+ * to surface it, and for tests.
1872
+ */
1873
+ getBackgroundRefreshCount(): number;
1851
1874
  /**
1852
1875
  * Unified parsing method that handles different input types and returns comprehensive results
1853
1876
  * with precise coordinate mapping for inline solves.
@@ -9,7 +9,7 @@ import { QueryClient } from '@tanstack/query-core';
9
9
  import { E as EngineError } from './EngineError-Ce1lPkjZ.js';
10
10
  import { a as DiagnosticReportJSON, D as DiagnosticPipeline } from './pipeline-72QmQlGx.js';
11
11
  import { T as Token } from './Token-CbP_OutD.js';
12
- import { E as EngineConfigOverride, a as EngineConfig } from './Configuration-B6W0-T67.js';
12
+ import { E as EngineConfigOverride, a as EngineConfig } from './Configuration-Culg8H_o.js';
13
13
 
14
14
  /**
15
15
  * One line's compiled bytecode, plus the variables it reads and writes.
@@ -1690,6 +1690,17 @@ declare class ExpressionEngine {
1690
1690
  * DAG walk + re-evaluation pass. Replaces the old single-callback pattern.
1691
1691
  */
1692
1692
  private batcher;
1693
+ /**
1694
+ * Drives proactive background refresh of live values, or `null` when the
1695
+ * host has not enabled it (the default). See {@link BackgroundRefreshManager}.
1696
+ */
1697
+ private readonly backgroundRefresh;
1698
+ /**
1699
+ * The signal a background re-evaluation is dispatched under. Never aborted
1700
+ * (a background refetch is not tied to a keystroke), so the batcher treats
1701
+ * its results as current; the manager's own timers are what stop the work.
1702
+ */
1703
+ private readonly backgroundRefreshSignal;
1693
1704
  /** Post-lexer token normalizer for phrase fusion, implicit multiply, etc. */
1694
1705
  private normalizer;
1695
1706
  /**
@@ -1848,6 +1859,18 @@ declare class ExpressionEngine {
1848
1859
  * and fires typed events to all listeners.
1849
1860
  */
1850
1861
  private resolveAsync;
1862
+ /**
1863
+ * Start refreshing a value in the background if it declared a cadence and the
1864
+ * host enabled background refresh. A no-op otherwise, so the pull path is
1865
+ * unchanged for a headless host or a value that never wants it.
1866
+ */
1867
+ private registerBackgroundRefresh;
1868
+ /**
1869
+ * How many live values are currently being refreshed in the background.
1870
+ * Zero when the host has not enabled background refresh. For hosts that want
1871
+ * to surface it, and for tests.
1872
+ */
1873
+ getBackgroundRefreshCount(): number;
1851
1874
  /**
1852
1875
  * Unified parsing method that handles different input types and returns comprehensive results
1853
1876
  * with precise coordinate mapping for inline solves.
@@ -1,2 +1,2 @@
1
- var n=class{constructor(){this.resolvers=new Map;}register(e){this.resolvers.has(e.namespace)&&(console.warn(`[ResolverRegistry] Namespace "${e.namespace}" already registered. Destroying old resolver and overwriting. Use distinct namespaces (e.g., "${e.namespace}:sub1", "${e.namespace}:sub2") to avoid collisions when a package needs multiple async resolvers.`),this.resolvers.get(e.namespace).destroy()),this.resolvers.set(e.namespace,e);}unregister(e,r){let s=this.resolvers.get(e);s&&(s.destroy(),this.resolvers.delete(e)),r&&r.removeQueries({queryKey:[e]});}preflightAll(e,r,s,i,l){for(let t of this.resolvers.values()){if(!t.preflight)continue;let o=t.preflight(e,r,s,i,l);if(o)return o}return null}get(e){return this.resolvers.get(e)}get size(){return this.resolvers.size}has(e){return this.resolvers.has(e)}clear(){for(let e of this.resolvers.values())e.destroy();this.resolvers.clear();}};export{n as a};//# sourceMappingURL=chunk-7GK3XEZF.js.map
2
- //# sourceMappingURL=chunk-7GK3XEZF.js.map
1
+ var n=class{constructor(){this.resolvers=new Map;}register(e){this.resolvers.has(e.namespace)&&(console.warn(`[ResolverRegistry] Namespace "${e.namespace}" already registered. Destroying old resolver and overwriting. Use distinct namespaces (e.g., "${e.namespace}:sub1", "${e.namespace}:sub2") to avoid collisions when a package needs multiple async resolvers.`),this.resolvers.get(e.namespace).destroy()),this.resolvers.set(e.namespace,e);}unregister(e,r){let s=this.resolvers.get(e);s&&(s.destroy(),this.resolvers.delete(e)),r&&r.removeQueries({queryKey:[e]});}preflightAll(e,r,s,i,l){for(let t of this.resolvers.values()){if(!t.preflight)continue;let o=t.preflight(e,r,s,i,l);if(o)return o}return null}get(e){return this.resolvers.get(e)}get size(){return this.resolvers.size}has(e){return this.resolvers.has(e)}clear(){for(let e of this.resolvers.values())e.destroy();this.resolvers.clear();}};export{n as a};//# sourceMappingURL=chunk-7E7NXKQ5.js.map
2
+ //# sourceMappingURL=chunk-7E7NXKQ5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/resolvers/ResolverRegistry.ts"],"names":["ResolverRegistry","resolver","namespace","queryClient","tokens","bytecode","packageId","signal","result"],"mappings":"AAqFO,IAAMA,EAAN,KAAuB,CAAvB,WAAA,EAAA,CACN,IAAA,CAAQ,UAAY,IAAI,IAAA,CAWxB,QAAA,CAASC,CAAAA,CAAgC,CAEpC,IAAA,CAAK,SAAA,CAAU,GAAA,CAAIA,CAAAA,CAAS,SAAS,CAAA,GACxC,OAAA,CAAQ,IAAA,CACP,CAAA,8BAAA,EAAiCA,EAAS,SAAS,CAAA,+FAAA,EAExCA,CAAAA,CAAS,SAAS,YAAYA,CAAAA,CAAS,SAAS,CAAA,0EAAA,CAE5D,CAAA,CACA,KAAK,SAAA,CAAU,GAAA,CAAIA,CAAAA,CAAS,SAAS,EAAG,OAAA,EAAQ,CAAA,CAEjD,IAAA,CAAK,SAAA,CAAU,IAAIA,CAAAA,CAAS,SAAA,CAAWA,CAAQ,EAChD,CAMA,UAAA,CAAWC,CAAAA,CAAmBC,CAAAA,CAAiC,CAC9D,IAAMF,CAAAA,CAAW,IAAA,CAAK,SAAA,CAAU,GAAA,CAAIC,CAAS,CAAA,CACzCD,CAAAA,GACHA,CAAAA,CAAS,OAAA,GACT,IAAA,CAAK,SAAA,CAAU,MAAA,CAAOC,CAAS,GAI5BC,CAAAA,EACHA,CAAAA,CAAY,aAAA,CAAc,CAAE,SAAU,CAACD,CAAS,CAAE,CAAC,EAErD,CASA,YAAA,CAAaE,CAAAA,CAAiBC,CAAAA,CAA2BC,EAAmBC,CAAAA,CAAqBJ,CAAAA,CAAmD,CACnJ,IAAA,IAAWF,KAAY,IAAA,CAAK,SAAA,CAAU,MAAA,EAAO,CAAG,CAC/C,GAAI,CAACA,CAAAA,CAAS,SAAA,CAAW,SACzB,IAAMO,CAAAA,CAASP,CAAAA,CAAS,SAAA,CAAUG,EAAQC,CAAAA,CAAUC,CAAAA,CAAWC,CAAAA,CAAQJ,CAAW,EAClF,GAAIK,CAAAA,CAAQ,OAAOA,CACpB,CACA,OAAO,IACR,CAMA,GAAA,CAAIN,EAA+C,CAClD,OAAO,IAAA,CAAK,SAAA,CAAU,IAAIA,CAAS,CACpC,CAGA,IAAI,MAAe,CAClB,OAAO,IAAA,CAAK,SAAA,CAAU,IACvB,CAKA,GAAA,CAAIA,CAAAA,CAA4B,CAC/B,OAAO,IAAA,CAAK,SAAA,CAAU,GAAA,CAAIA,CAAS,CACpC,CAMA,KAAA,EAAc,CACb,IAAA,IAAWD,KAAY,IAAA,CAAK,SAAA,CAAU,MAAA,EAAO,CAC5CA,EAAS,OAAA,EAAQ,CAElB,KAAK,SAAA,CAAU,KAAA,GAChB,CACD","file":"chunk-7E7NXKQ5.js","sourcesContent":["import type { QueryClient } from \"@tanstack/query-core\";\nimport type { Token } from \"@solve-js/lexer\";\nimport type { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport type { Value } from \"@solve-js/vm/Value\";\n\n/**\n * Result from a resolver's preflight() check.\n * Returned when async data is needed, the orchestrator uses this\n * to subscribe to the resolver and return a Pending value immediately.\n */\nexport interface AsyncCheckResult {\n\t/** Unique cache key for deduplication (e.g., \"{packageId}:rates:USD:GBP\") */\n\tqueryKey: string;\n\t/** Promise that resolves to the final Value */\n\tresolver: Promise<Value>;\n\t/** Package owning this resolver */\n\tpackageId: string;\n\t/** AbortSignal for stale-data prevention */\n\tsignal: AbortSignal;\n\t/** Optional metadata for diagnostics */\n\tmetadata?: Record<string, unknown>;\n\t/**\n\t * Cadence, in ms, at which this value wants proactive background refresh\n\t * (a live quote every minute, an FX rate every few minutes). Absent, or\n\t * paired with no {@link refetch}, means pull-only: the value refreshes on\n\t * re-evaluation, never on its own. Only acted on when the host has enabled\n\t * background refresh; see {@link BackgroundRefreshConfig}.\n\t */\n\trefetchIntervalMs?: number;\n\t/**\n\t * Force a fresh fetch of this exact query, bypassing `staleTime`, and return\n\t * the new value. Supplied alongside {@link refetchIntervalMs} so the engine\n\t * can drive the background refresh without re-scanning bytecode.\n\t */\n\trefetch?: () => Promise<Value>;\n}\n\n/**\n * Interface for async resolvers registered by packages/plugins.\n *\n * Each resolver handles a domain of async data (currency rates,\n * weather, stock prices, etc.). The preflight() method is called\n * BEFORE VM execution to check if all data is cached. If not,\n * it returns an AsyncCheckResult and the engine skips the VM,\n * returning a Pending value instead.\n */\nexport interface IAsyncResolver {\n\t/** Unique namespace for cache key scoping (e.g., \"currency\", \"weather\") */\n\treadonly namespace: string;\n\n\t/**\n\t * Pre-flight check: called BEFORE VM execution.\n\t *\n\t * Returns null if all data for this expression is cached and ready.\n\t * Returns an AsyncCheckResult if async work is needed.\n\t *\n\t * This method is synchronous, it only checks caches, never fetches.\n\t * If data is missing, it creates a Promise and returns immediately.\n\t *\n\t * @param tokens - The lexed tokens for the expression\n\t * @param bytecode - The compiled bytecode program\n\t * @param pluginId - The plugin ID (for cache key scoping)\n\t * @param signal - AbortSignal for the current evaluation\n\t */\n\tpreflight?(tokens: Token[], bytecode: BytecodeProgram, packageId: string, signal: AbortSignal, queryClient: QueryClient): AsyncCheckResult | null;\n\n\t/**\n\t * Called when the resolver's namespace is being unregistered.\n\t * Clean up any in-flight promises, clear caches, unsubscribe.\n\t */\n\tdestroy(): void;\n}\n\n/**\n * Registry of async resolvers, keyed by namespace.\n *\n * Plugins/packages register resolvers alongside their parselets\n * and opcode handlers. The engine calls preflightAll() before\n * VM execution to short-circuit async expressions.\n *\n * Lifecycle:\n * - register(), when a package is loaded\n * - unregister(), when a package is unloaded (clears cache entries)\n * - clear(), on document switch (clears all resolvers)\n */\nexport class ResolverRegistry {\n\tprivate resolvers = new Map<string, IAsyncResolver>();\n\n\t/**\n\t * Register an async resolver.\n\t *\n\t * Each resolver must have a unique `namespace`. If a resolver with the\n\t * same namespace is already registered, the old one is destroyed and\n\t * replaced (with a console warning). Packages that need multiple async\n\t * operations should use `asyncResolvers: [...]` with distinct namespaces\n\t * (e.g., `\"weather:current\"`, `\"weather:forecast\"`).\n\t */\n\tregister(resolver: IAsyncResolver): void {\n\t\t// Clean up previous resolver with same namespace if any\n\t\tif (this.resolvers.has(resolver.namespace)) {\n\t\t\tconsole.warn(\n\t\t\t\t`[ResolverRegistry] Namespace \"${resolver.namespace}\" already registered. ` +\n\t\t\t\t`Destroying old resolver and overwriting. Use distinct namespaces ` +\n\t\t\t\t`(e.g., \"${resolver.namespace}:sub1\", \"${resolver.namespace}:sub2\") ` +\n\t\t\t\t`to avoid collisions when a package needs multiple async resolvers.`,\n\t\t\t);\n\t\t\tthis.resolvers.get(resolver.namespace)!.destroy();\n\t\t}\n\t\tthis.resolvers.set(resolver.namespace, resolver);\n\t}\n\n\t/**\n\t * Unregister a resolver by namespace.\n\t * Calls destroy() and clears all cache entries with that namespace prefix.\n\t */\n\tunregister(namespace: string, queryClient?: QueryClient): void {\n\t\tconst resolver = this.resolvers.get(namespace);\n\t\tif (resolver) {\n\t\t\tresolver.destroy();\n\t\t\tthis.resolvers.delete(namespace);\n\t\t}\n\t\t// Clear all cache entries for this namespace via TanStack Query\n\t\t// Hierarchical keys: [\"osrs\"] clears all [\"osrs\", ...] queries\n\t\tif (queryClient) {\n\t\t\tqueryClient.removeQueries({ queryKey: [namespace] });\n\t\t}\n\t}\n\n\t/**\n\t * Run all registered resolvers' preflight checks against compiled bytecode.\n\t *\n\t * Returns the first AsyncCheckResult found, or null if all data is ready.\n\t * Short-circuits on first pending, subsequent pending ops will be\n\t * discovered on re-evaluation when the first resolves.\n\t */\n\tpreflightAll(tokens: Token[], bytecode: BytecodeProgram, packageId: string, signal: AbortSignal, queryClient: QueryClient): AsyncCheckResult | null {\n\t\tfor (const resolver of this.resolvers.values()) {\n\t\t\tif (!resolver.preflight) continue;\n\t\t\tconst result = resolver.preflight(tokens, bytecode, packageId, signal, queryClient);\n\t\t\tif (result) return result;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Get a resolver by namespace.\n\t * Returns undefined if no resolver is registered for that namespace.\n\t */\n\tget(namespace: string): IAsyncResolver | undefined {\n\t\treturn this.resolvers.get(namespace);\n\t}\n\n\t/** Number of registered resolvers. */\n\tget size(): number {\n\t\treturn this.resolvers.size;\n\t}\n\n\t/**\n\t * Check if a resolver is registered for the given namespace.\n\t */\n\thas(namespace: string): boolean {\n\t\treturn this.resolvers.has(namespace);\n\t}\n\n\t/**\n\t * Clear all resolvers (document switch, engine reset).\n\t * Calls destroy() on each resolver and clears the map.\n\t */\n\tclear(): void {\n\t\tfor (const resolver of this.resolvers.values()) {\n\t\t\tresolver.destroy();\n\t\t}\n\t\tthis.resolvers.clear();\n\t}\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import {b as b$1,a as a$2}from'./chunk-6G3PMEPA.js';import {a as a$4}from'./chunk-TN5E6JU6.js';import {a,d,e as e$2}from'./chunk-YVKHEAFT.js';import {b as b$4,e as e$4}from'./chunk-5FO4PDIG.js';import {a as a$8}from'./chunk-76F3LCIL.js';import {b as b$3}from'./chunk-TCZSPH4A.js';import {F,J as J$2,B as B$2,d as d$2,z as z$3,A as A$2}from'./chunk-W2JAR233.js';import {c as c$3}from'./chunk-YAYBVVG2.js';import {a as a$3}from'./chunk-HFKDWQUL.js';import {B as B$1,i,z as z$1,y,q as q$1,u,t as t$1,b as b$2,h as h$1,s,r,p,o,n as n$1,e,a as a$1,c as c$2,A as A$1,j as j$1,k as k$1,l,m,d as d$3,v,w,x}from'./chunk-R2ENWQ76.js';import {ta as ta$1,q as q$2,p as p$1,d as d$1,Q,e as e$3}from'./chunk-RSF25YSJ.js';import {N,t,J as J$1,G as G$1,n,O,u as u$1,K,z as z$2,I as I$1,g}from'./chunk-EVAOPEO4.js';import {c as c$4,e as e$1}from'./chunk-WGZ3FNHI.js';import {a as a$7}from'./chunk-G7TBEQRQ.js';import {c}from'./chunk-IJMNVBIS.js';import {a as a$5}from'./chunk-62LMTO4F.js';import {b}from'./chunk-TRBXW6HW.js';import {a as a$6}from'./chunk-2JMFUQZH.js';import {c as c$1}from'./chunk-MPB7KUN5.js';var Sm=/^\d{1,3}(\.\d{3}){2,}$/,Lm=/^\d*\.\d*$/,tr=class{constructor(){this.category="Arithmetic";}parse(e,o,t){let n,i=null,a=o.value;if(a.startsWith("0x")||a.startsWith("0X")){if(n=parseInt(a,16),Number.isNaN(n))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid hex literal: "${a}"`,{raw:a})}else if(a.startsWith("0b")||a.startsWith("0B")){if(n=parseInt(a.slice(2),2),Number.isNaN(n))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid binary literal: "${a}"`,{raw:a})}else if(a.startsWith("0o")||a.startsWith("0O")){if(n=parseInt(a.slice(2),8),Number.isNaN(n))throw c$1.parsing("INVALID_NUMBER_LITERAL",`Invalid octal literal: "${a}"`,{raw:a})}else if(Sm.test(a))n=parseFloat(a.split(".").join(""));else {let m=a$5(e.getLocaleCode()),s=m.display.decimalSeparator,u=m.display.thousandsSeparator,c=a;u&&(c=c.split(u).join("")),s&&s!=="."&&(c=c.replace(s,".")),n=parseFloat(c),Lm.test(c)&&(i=c);}if(i!==null){t.emitOpcode(16),t.emitString(i);return}t.emitOpcode(10),t.emitNumber(n);}};var ce=class{constructor(e){this.opcode=e;this.category="Arithmetic";}parse(e,o,t){e.parseExpression(60,t),t.emitOpcode(this.opcode);}};var A=class{constructor(e,o,t=false){this.opcode=o;this.category="Arithmetic";this.bindingPower=e,this.rightBindingPower=t?e-1:e;}parse(e,o,t,n){e.parseExpression(this.rightBindingPower,n),n.emitOpcode(this.opcode);}};var or=class{constructor(){this.category="Arithmetic";}parse(e,o,t){e.parseExpression(0,t);let n=1;for(;e.match("COMMA");)e.parseExpression(0,t),n++;e.consume("RPAREN"),n>1&&(t.emitOpcode(152),t.emitIndex(1),t.emitIndex(n));}};var he=class{constructor(){this.category="Arithmetic";}parse(e,o,t){let n=o.type==="PI"?Math.PI:Math.E;t.emitOpcode(10),t.emitNumber(n);}};var wm={k:3,M:6,G:9,B:9,T:12},km={thousand:3,thousands:3,million:6,millions:6,mn:6,billion:9,billions:9,bn:9,trillion:12,trillions:12,tn:12},Bm=/^\d+(\.\d+)?$/;function Um(r,e){let o=r.indexOf("."),t=o===-1?r:r.slice(0,o),n=o===-1?"":r.slice(o+1);n.length<e&&(n=n.padEnd(e,"0"));let i=t+n.slice(0,e),a=n.slice(e);return a?`${i}.${a}`:i}function Bn(r=65){return {name:"arithmetic:large-number-suffix",priority:r,match(e,o){let t=e[o];if(t.type!=="NUMBER"||!Bm.test(t.text))return null;let n=e[o+1];if(!n||n.type!=="IDENT"&&n.type!=="UNIT")return null;let i=t.offset+t.text.length===n.offset,a=n.type==="UNIT"?void 0:km[n.value.toLowerCase()],m=i?wm[n.value]??a:a;if(m===void 0)return null;let s=Um(t.text,m);return {consumed:2,replacement:[b$4("NUMBER",s,e.slice(o,o+2))],ruleName:"arithmetic:large-number-suffix"}}}}var Xt={name:"solve-arithmetic",prefixParselets:{NUMBER:new tr,LPAREN:new or,PI:new he,E:new he,PLUS:new ce(27),MINUS:new ce(26),BIT_NOT:new ce(36)},infixParselets:{PLUS:new A(a.Sum,20),AND_CONJ:new A(a.Conjunction,20),MINUS:new A(a.Sum,21),STAR:new A(a.Product,22),SLASH:new A(a.Product,23),MOD:new A(a.Product,24),CARET:new A(a.Exponent,25,true),TIMES_BY:new A(a.Product,22),MULTIPLY_BY:new A(a.Product,22),DIVIDE_BY:new A(a.Product,23),LSHIFT:new A(a.Shift,30),RSHIFT:new A(a.Shift,31),URSHIFT:new A(a.Shift,32),BIT_AND:new A(a.BitwiseAnd,33),BIT_OR:new A(a.BitwiseOr,34),BIT_XOR:new A(a.BitwiseXor,35)},normalizerRules:[Bn()]};var nr=class{constructor(){this.category="Percentage";this.bindingPower=a.Prefix;}parse(e,o,t,n){n.emitOpcode(10),n.emitNumber(100),n.emitOpcode(23),n.emitOpcode(74);}};var ir=class{constructor(){this.category="Percentage";this.bindingPower=a.Conditional;}parse(e,o,t,n){if(Dn(e,"what")){e.consume(),this.parseWhatRate(e,n);return}this.parseWhatBase(e,n);}parseWhatRate(e,o){if(!e.match("PERCENT"))throw c$1.parsing("IS_WHAT_EXPECTED_PERCENT",'Expected "%" after "is what", as in "20 is what % of 200"');let t=Mm(e);if(t===null){o.emitOpcode(74);return}e.parseExpression(a.Conditional,o),o.emitOpcode(23),t==="off"?(o.emitOpcode(10),o.emitNumber(1),o.emitOpcode(2),o.emitOpcode(21)):t==="on"&&(o.emitOpcode(10),o.emitNumber(1),o.emitOpcode(21)),o.emitOpcode(74);}parseWhatBase(e,o){if(e.parseExpression(a.Conditional,o),e.match("TO")){Mn(e,"what",'"81 is 9 to what power"'),Mn(e,"power",'"81 is 9 to what power"'),o.emitOpcode(51),o.emitIndex(Un),o.emitIndex(1),o.emitOpcode(2),o.emitOpcode(51),o.emitIndex(Un),o.emitIndex(1),o.emitOpcode(2),o.emitOpcode(23);return}let t=e.match("OF_WHAT")?"of":e.match("OFF_WHAT")?"off":e.match("ON_WHAT")?"on":null;if(t===null)throw c$1.parsing("IS_WHAT_EXPECTED_PREPOSITION",'Expected "of what", "off what" or "on what", as in "20 is 10% of what"');if(t==="of"){o.emitOpcode(23);return}o.emitOpcode(10),o.emitNumber(1),t==="off"?(o.emitOpcode(2),o.emitOpcode(21)):o.emitOpcode(20),o.emitOpcode(23);}},Un=5;function Dn(r,e){return (r.peek()?.text??"").toLowerCase()===e}function Mn(r,e,o){if(!Dn(r,e))throw c$1.parsing("IS_WHAT_EXPECTED_WORD",`Expected "${e}" here, as in ${o}`);r.consume();}function Mm(r){if(r.match("OF"))return "of";let e=(r.peek()?.text??"").toLowerCase();return e==="off"||e==="on"?(r.consume(),e):null}var xe=class{constructor(e){this.sign=e;this.category="Percentage";this.bindingPower=a.Conditional;}parse(e,o,t,n){e.parseExpression(a.Conditional,n),n.emitOpcode(2),n.emitOpcode(10),n.emitNumber(1),this.sign===1?n.emitOpcode(20):(n.emitOpcode(2),n.emitOpcode(21)),n.emitOpcode(22);}};function Fn(r=68){return {name:"percentage:on-off",priority:r,match(e,o){if(e[o]?.type!=="PERCENT")return null;let t=e[o+1];if(t?.type!=="IDENT")return null;let n=(t.text??t.value??"").toLowerCase();return n!=="on"&&n!=="off"||(e[o+2]?.text??"").toLowerCase()==="what"?null:{consumed:2,replacement:[e[o],b$4(n==="on"?"PCT_ON":"PCT_OFF",n,[t])],ruleName:"percentage:on-off"}}}}var ar=class{constructor(){this.category="Percentage";this.bindingPower=a.Product;}parse(e,o,t,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(22);}};var mr=class{constructor(){this.category="Percentage";this.bindingPower=a.Product;}parse(e,o,t,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(2),n.emitOpcode(23);}};var ve=class{constructor(e){this.sign=e;this.category="Percentage";this.bindingPower=a.Product;}parse(e,o,t,n){n.emitOpcode(10),n.emitNumber(1),this.sign===1?n.emitOpcode(20):(n.emitOpcode(2),n.emitOpcode(21)),e.parseExpression(this.bindingPower,n),n.emitOpcode(2),n.emitOpcode(23);}};var Se=class{constructor(e){this.multiplier=e;this.category="Percentage";}parse(e,o,t){e.parseExpression(0,t);let n=e.peek();n&&(n.type==="IDENT"||n.type==="BY")&&e.consume(),t.emitOpcode(10),t.emitNumber(1),e.parseExpression(0,t),e.peek()?.type==="PERCENT"&&e.consume(),t.emitOpcode(this.multiplier>0?20:21),t.emitOpcode(22);}};var Le=class{constructor(e){this.multiplier=e;this.category="Percentage";this.bindingPower=a.Conditional;}parse(e,o,t,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(10),n.emitNumber(1),n.emitOpcode(2),n.emitOpcode(this.multiplier>0?20:21),n.emitOpcode(22);}};var sr=class{constructor(){this.category="Percentage";this.bindingPower=a.Conditional;}parse(e,o,t,n){if(o.type==="UNIT")return;let i=e.peek();if(i&&((i.type==="UNIT"||i.type==="IDENT")&&b(i.value)||i.type==="IN")){e.consume(),n.emitOpcode(13),n.emitString(i.value),n.emitOpcode(84);return}e.parseExpression(this.bindingPower,n),n.emitOpcode(2),n.emitOpcode(23),n.emitOpcode(10),n.emitNumber(1),n.emitOpcode(21),n.emitOpcode(74);}};var Dm={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12};function Fm(r){if(r.type==="NUMBER"){let e=Number(r.value);return Number.isInteger(e)&&e>=0?e:null}return r.type==="IDENT"?Dm[r.value.toLowerCase()]??null:null}var we=class{constructor(e){this.sign=e;this.category="Percentage";this.bindingPower=a.Conditional;}parse(e,o,t,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(10),n.emitNumber(1),n.emitOpcode(2),n.emitOpcode(this.sign>0?20:21);let i=this.tryConsumeRepeat(e);i!==null&&(n.emitOpcode(10),n.emitNumber(i),n.emitOpcode(25)),n.emitOpcode(22),this.consumeChainThen(e);}tryConsumeRepeat(e){let o=e.peek(),t=e.peekAt(1);if(!o||!t||t.type!=="STAR"||t.value.toLowerCase()!=="times")return null;let n=Fm(o);return n===null?null:(e.consume(),e.consume(),n)}consumeChainThen(e){if(e.peek()?.type!=="THEN")return;let o=e.peekAt(1)?.type;(o==="PCT_UP"||o==="PCT_DOWN")&&e.consume();}};function bn(r,e){let o=r[e];if(o?.type!=="IDENT")return null;let t=(o.text??o.value??"").toLowerCase();return t!=="up"&&t!=="down"||r[e+1]?.type!=="NUMBER"||r[e+2]?.type!=="PERCENT"?null:b$4(t==="up"?"PCT_UP":"PCT_DOWN",t,[o])}function Vn(r=68){return {name:"percentage:up-down",priority:r,match(e,o){let t=e[o];if(t&&(t.type==="NUMBER"||t.type==="RPAREN")){let i=bn(e,o+1);if(i)return {consumed:2,replacement:[t,i],ruleName:"percentage:up-down"}}let n=bn(e,o);return n?{consumed:1,replacement:[n],ruleName:"percentage:up-down"}:null}}}var Qt={name:"solve-percentage",phrases:{"of what is":"OF_WHAT_IS","of what":"OF_WHAT","off what":"OFF_WHAT","on what":"ON_WHAT","on what is":"ON_WHAT_IS","off what is":"OFF_WHAT_IS"},infixParselets:{PERCENT:new nr,IS:new ir,PCT_ON:new xe(1),PCT_OFF:new xe(-1),OF:new ar,OF_WHAT_IS:new mr,ON_WHAT_IS:new ve(1),OFF_WHAT_IS:new ve(-1),TO:new sr,INCREASE_BY:new Le(1),DECREASE_BY:new Le(-1),PCT_UP:new we(1),PCT_DOWN:new we(-1)},prefixParselets:{INCREASE:new Se(1),DECREASE:new Se(-1)},normalizerRules:[Fn(),Vn()]};var Zt={sqrt:0,abs:1,sin:2,cos:3,tan:4,log:5,ceil:6,floor:7,round:8,min:9,max:10,asin:11,acos:12,atan:13,atan2:14,arcsin:11,arccos:12,arctan:13,sind:87,cosd:88,tand:89,asind:90,acosd:91,atand:92,sinh:15,cosh:16,tanh:17,asinh:18,acosh:19,atanh:20,cbrt:21,clz32:22,expm1:23,exp:24,fround:25,hypot:26,imul:27,log10:28,log1p:29,log2:30,pow:31,random:32,sign:33,trunc:34,degtorad:35,radtodeg:36,gcd:38,lcm:39,permutation:40,combination:41,hex:48,bin:49,int:50,compoundinterest:51,interestearned:52,compoundinterestrate:53,compoundinterestyears:54,loanrepayment:55,loaninterest:56,monthlypayment:57,taxadd:58,taxremove:59,inflationadjust:60,root:61,fact:62,factorial:62,transpose:63,det:64,inv:65,dot:66},lr=class{constructor(){this.category="Function";}parse(e,o,t){let n=o.value.toLowerCase(),i=Zt[n];if(i===void 0)throw c$1.execution("UNKNOWN_FUNCTION",`Unknown function: ${n}`,{functionName:n});e.consume("LPAREN");let a$1=0;if(e.peek()?.type!=="RPAREN")for(e.parseExpression(a.Lowest,t),a$1++;e.match("COMMA");)e.parseExpression(a.Lowest,t),a$1++;e.consume("RPAREN"),t.emitOpcode(51),t.emitIndex(i),t.emitIndex(a$1);}};var qt={name:"solve-function",prefixParselets:{FUNC:new lr}};var Z=class{constructor(e=0){this.category="Date/Time";this.dayOffset=e;}parse(e,o,t){t.emitOpcode(90),this.dayOffset!==0&&(t.emitOpcode(10),t.emitNumber(this.dayOffset),t.emitOpcode(13),t.emitString("days"),t.emitOpcode(80),t.emitOpcode(20));}};var bm={SUNDAY:0,MONDAY:1,TUESDAY:2,WEDNESDAY:3,THURSDAY:4,FRIDAY:5,SATURDAY:6},ke=class{constructor(e){this.direction=e;this.category="Date/Time";}parse(e,o,t){let n=e.peek(),i=n?bm[n.type]:void 0;if(i===void 0)throw c$1.parsing("MISSING_WEEKDAY",`"${o.value}" must be followed by a day of the week (e.g. "${o.value} Saturday")`,{keyword:o.value,actualType:n?.type,actualValue:n?.value});e.consume(),t.emitOpcode(90),t.emitOpcode(10),t.emitNumber(i),t.emitOpcode(this.direction==="next"?93:94);}};var Be=class{constructor(e){this.direction=e;this.category="Date/Time";}parse(e,o,t){let n=o.value;this.direction==="until"?(e.parseExpression(0,t),t.emitOpcode(90)):(t.emitOpcode(90),e.parseExpression(0,t)),t.emitOpcode(21),t.emitOpcode(13),t.emitString(n),t.emitOpcode(84);}};var ur=class{constructor(){this.category="Date/Time";}parse(e,o,t){e.parseExpression(0,t),t.emitPluginCall("workdaysInDuration",1);}};var Ue=class{constructor(e){this.direction=e;this.category="Date/Time";this.bindingPower=a.Conditional;}parse(e,o,t,n){e.parseExpression(a.Sum,n),n.emitOpcode(96),n.emitByte(this.direction==="backward"?1:0);}};var cr=class{constructor(){this.category="Date/Time";}parse(e,o,t){e.parseExpression(a.Product,t),e.consume("AND_CONJ"),e.parseExpression(a.Lowest,t),t.emitOpcode(97);}};var V=class{constructor(e,o){this.functionName=e;this.mode=o;this.category="Date/Time";}parse(e,o,t){this.mode==="in"?(t.emitOpcode(90),e.parseExpression(0,t),t.emitOpcode(20)):e.peek()?e.parseExpression(0,t):t.emitOpcode(90),t.emitPluginCall(this.functionName,1);}};var pr=class{constructor(){this.category="Date/Time";}parse(e,o,t){let n=o.value;e.parseExpression(a.Product,t),e.consume("AND_CONJ"),e.parseExpression(a.Lowest,t),t.emitPluginCall("spanBetweenDates",2),t.emitOpcode(13),t.emitString(n),t.emitOpcode(84);}};var Me=class{constructor(e){this.functionName=e;this.category="Date/Time";this.bindingPower=a.Conditional;}parse(e,o,t,n){n.emitPluginCall(this.functionName,1);}};var fr=class{constructor(){this.category="Date/Time";}parse(e,o,t){t.emitOpcode(90),t.emitPluginCall("toTimestampFromAny",1);}};var dr=class{constructor(){this.category="Date/Time";this.bindingPower=a.Conditional;}parse(e,o,t,n){n.emitPluginCall("toDateFromAny",1);}};var Er=class{constructor(){this.category="Date/Time";this.bindingPower=a.Conditional;}parse(e,o,t,n){n.emitPluginCall("toTimestampFromAny",1);}};var Nr=class{constructor(){this.category="Date/Time";}parse(e,o,t){t.emitOpcode(95),t.emitNumber(Number(o.value));}};var Vm=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function De(r){let e=r.trim();if(e.length>=2&&e.startsWith('"')&&e.endsWith('"')&&(e=e.slice(1,-1)),!Vm.test(e))return null;let o=new Date(e).getTime();return Number.isNaN(o)?null:o}function zn(r){let e=new Date(r),o=y=>String(y).padStart(2,"0"),t=e.getFullYear(),n=o(e.getMonth()+1),i=o(e.getDate()),a=o(e.getHours()),m=o(e.getMinutes()),s=o(e.getSeconds()),u=-e.getTimezoneOffset(),c=u>=0?"+":"-",p=Math.abs(u),E=o(Math.floor(p/60)),T=o(p%60);return `${t}-${n}-${i}T${a}:${m}:${s}${c}${E}:${T}`}var zm=1e12;function Hn(r){return Math.abs(r)>=zm?r:r*1e3}function Hm(r){let e=r[0],o;if(e.type===6&&e.unit){if(c$4(e.unit)!=="time")return N("WORKDAYS_IN_EXPECTED_DURATION",`"workdays in" expects a time duration, got unit "${e.unit}"`);o=e$1(e.toNumber(),e.unit,"day");}else o=e.toNumber();let t=o<0?-1:1,n$1=Math.abs(o),i=Math.floor(n$1/7),a=n$1-i*7,m=t*(i*5+Math.min(a,5));return n(m)}var Gm=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function Fe(r,e){return r.type===4?r.toNumber():N("DATE_FIELD_EXPECTED_DATE",`"${e}" expects a date, got ${g[r.type]??"an unsupported value"}`)}function $m(r){let e=Fe(r[0],"weekday");return typeof e!="number"?e:t(Gm[new Date(e).getDay()])}var Km=["January","February","March","April","May","June","July","August","September","October","November","December"];function Wm(r){let e=Fe(r[0],"month");return typeof e!="number"?e:t(Km[new Date(e).getMonth()])}function Ym(r){let e=Fe(r[0],"week");if(typeof e!="number")return e;let o=new Date(e),t=new Date(Date.UTC(o.getFullYear(),o.getMonth(),o.getDate())),n$1=t.getUTCDay()===0?7:t.getUTCDay();t.setUTCDate(t.getUTCDate()+4-n$1);let i=Date.UTC(t.getUTCFullYear(),0,1),a=Math.floor((t.getTime()-i)/864e5);return n(Math.floor(a/7)+1)}function Gn(r){let e=new Date(r).getDay();return e===0||e===6}function jm(r){let e=Fe(r[0],"is a weekend");return typeof e!="number"?e:J$1(Gn(e))}function Xm(r){let e=Fe(r[0],"is a workday");return typeof e!="number"?e:J$1(!Gn(e))}function Qm(r){return u$1(Math.abs(r[0].toNumber()-r[1].toNumber()),"ms")}function Zm(r){let e=r[0];if(e.type===4)return e;if(e.type===3){let o=De(e.value);return o===null?N("INVALID_ISO8601_STRING",`"${e.value}" is not a recognizable ISO8601 date/time string`):K(o)}return K(Hn(e.toNumber()))}function qm(r){let e=r[0];if(e.type===3){let o=De(e.value);return o===null?N("INVALID_ISO8601_STRING",`"${e.value}" is not a recognizable ISO8601 date/time string`):n(Math.floor(o/1e3))}return n(Math.floor(e.toNumber()/1e3))}var $n=Hm,Jt=$m,eo=Wm,ro=Ym,Kn=jm,Wn=Xm,Yn=Qm,jn=Zm,Xn=qm;function Qn(r=60){return {name:"datetime:until-since",priority:r,match(e,o){if(o+1>=e.length)return null;let t=e[o],n=e[o+1];if(t.type!=="UNIT"||n.type!=="UNTIL"&&n.type!=="SINCE")return null;let i=n.type==="UNTIL"?"UNTIL_UNIT":"SINCE_UNIT";return {consumed:2,replacement:[b$4(i,t.value,[t,n])],ruleName:`datetime:${n.type.toLowerCase()}`}}}}function Zn(r=60){return {name:"datetime:between-unit",priority:r,match(e,o){let t=o,n=0;e[o]?.value?.toLowerCase()==="how"&&e[o+1]?.value?.toLowerCase()==="many"&&(t=o+2,n=2);let i=e[t],a=e[t+1];if(!i||!a||i.type!=="UNIT")return null;let m=a.type==="BETWEEN",s=a.type==="UNTIL"||a.type==="SINCE";if(!m&&!s||s&&n===0)return null;let u=e.slice(o,t+2);return s?{consumed:n+2,replacement:[i,a],ruleName:"datetime:how-many"}:{consumed:n+2,replacement:[b$4("BETWEEN_UNIT",i.value,u)],ruleName:"datetime:between"}}}}function qn(r=70){return {name:"datetime:workday-rate-denominator",priority:r,match(e,o){let t=e[o];if(t.type!=="SLASH")return null;let n=e[o+1];if(!n||n.type!=="UNIT"||n.value!=="workday"&&n.value!=="workdays")return null;let i={...n,type:"NUMBER",typeId:c("NUMBER"),value:"1",text:"1"};return {consumed:2,replacement:[t,i,n],ruleName:"datetime:workday-rate-denominator"}}}}var be="DATETIME_LITERAL",Jn=c(be),Tr=/^\d+$/,Jm=/^\d{1,2}\.\d{1,2}$/,es=/^\.(\d{2}|\d{4})$/,pe=/^\d{1,2}$/;function rs(r){for(let e=0;e<r.length-1;e++){let o=r[e];if((o.sourceEnd??o.offset+o.text.length)!==r[e+1].offset)return false}return true}function to(r){if(r.length===4)return Number(r);if(r.length===2){let e=Number(r);return e<=68?2e3+e:1900+e}return null}function k(r,e,o,t,n){if(e<1||e>12||r<1||r>31)return null;let i=new Date(o,e-1,r);if(i.getFullYear()!==o||i.getMonth()!==e-1||i.getDate()!==r)return null;let a=t[0],m=t.map(u=>u.value).join(""),s=new a$7(be,Jn,String(i.getTime()),m,a.offset,0,a.line,a.col);return {consumed:t.length,replacement:[s],ruleName:n}}var ts=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?/,os=new Set(["NUMBER","MINUS","PLUS","COLON","IDENT"]),ns=16;function is(r,e,o){let t=r[e];if(t.sourceEnd!==void 0)return null;let n=t.text,i=t.offset+t.text.length,a=[t];for(let E=e+1;E<r.length&&a.length<ns;E++){let T=r[E];if(T.sourceEnd!==void 0||T.offset!==i||!os.has(T.type))break;n+=T.text,i=T.offset+T.text.length,a.push(T);}let m=ts.exec(n);if(m===null)return null;let s=0,u=0;for(let E of a)if(u+=E.text.length,s++,u>=m[0].length)break;if(u!==m[0].length)return null;let c=De(m[0]);if(c===null)return null;let p=new a$7(be,Jn,String(c),m[0],t.offset,0,t.line,t.col,t.offset+m[0].length);return {consumed:s,replacement:[p],ruleName:o}}function ei(){return {name:"datetime:date-literal",priority:70,match(r,e){let o=r[e];if(o.type!=="NUMBER")return null;if(Jm.test(o.value)){let u=r[e+1];if(u&&u.type==="NUMBER"&&es.test(u.value)){let[c,p]=o.value.split("."),E=to(u.value.slice(1));if(E!==null){let T=k(Number(c),Number(p),E,[o,u],"datetime:date-literal:dot");if(T)return T}}return null}if(o.value.length===4&&Tr.test(o.value)){let u=is(r,e,"datetime:date-literal:iso-timestamp");if(u)return u}if(!Tr.test(o.value))return null;let t=r[e+1];if(!t||t.type!=="SLASH"&&t.type!=="MINUS")return null;let n=r[e+2],i=r[e+3],a=r[e+4];if(!n||n.type!=="NUMBER"||!Tr.test(n.value)||!i||i.type!==t.type||!a||a.type!=="NUMBER"||!Tr.test(a.value))return null;let m=[o,t,n,i,a];if(!rs(m))return null;if(t.type==="SLASH"){if(!pe.test(o.value)||!pe.test(n.value))return null;let u=to(a.value);return u===null?null:k(Number(o.value),Number(n.value),u,m,"datetime:date-literal:european")}if(o.value.length===4)return !pe.test(n.value)||!pe.test(a.value)?null:k(Number(a.value),Number(n.value),Number(o.value),m,"datetime:date-literal:iso");if(!pe.test(o.value)||!pe.test(n.value))return null;let s=to(a.value);return s===null?null:k(Number(n.value),Number(o.value),s,m,"datetime:date-literal:us")}}}var as={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 ri(r){return r===void 0||r.type!=="IDENT"&&r.type!=="UNIT"?0:as[(r.text??r.value??"").toLowerCase()]??0}var Ve=/^\d+$/;function yr(r){return r.length===4}function ti(r=64){return {name:"datetime:month-name-date",priority:r,match(e,o){let t="datetime:month-name-date",n=e[o];if(n?.type==="NUMBER"&&Ve.test(n.text??"")){let c=ri(e[o+1]);if(c===0)return null;let p=Number(n.text);if(p<1||p>31)return null;let E=e[o+2];return E?.type==="NUMBER"&&Ve.test(E.text??"")&&yr(E.text??"")?k(p,c,Number(E.text),e.slice(o,o+3),t):k(p,c,new Date().getFullYear(),e.slice(o,o+2),t)}let i=ri(n);if(i===0)return null;let a=e[o+1];if(a?.type!=="NUMBER"||!Ve.test(a.text??""))return null;if(yr(a.text??""))return k(1,i,Number(a.text),e.slice(o,o+2),t);let m=Number(a.text),s=e[o+2],u=e[o+3];return s?.type==="COMMA"&&u?.type==="NUMBER"&&Ve.test(u.text??"")&&yr(u.text??"")?k(m,i,Number(u.text),e.slice(o,o+4),t):s?.type==="NUMBER"&&Ve.test(s.text??"")&&yr(s.text??"")?k(m,i,Number(s.text),e.slice(o,o+3),t):k(m,i,new Date().getFullYear(),e.slice(o,o+2),t)}}}var ms=93,ss={q1:[1,3],q2:[4,6],q3:[7,9],q4:[10,12]};function oo(r,e){return new Date(r,e,0).getDate()}function ls(r){return oo(r,2)===29?366:365}var gr=class{constructor(){this.category="Datetime";}parse(e,o,t){let n=this.readPeriodDays(e);t.emitOpcode(10),t.emitNumber(n),t.emitOpcode(51),t.emitIndex(ms),t.emitIndex(1);}readPeriodDays(e){let o=e.peek(),t=(o?.text??o?.value??"").toLowerCase(),n=ss[t];if(n!==void 0){e.consume();let a=this.readOptionalYear(e)??new Date().getFullYear(),m=0;for(let s=n[0];s<=n[1];s++)m+=oo(a,s);return m}if(o?.type==="DATETIME_LITERAL"){e.consume();let a=new Date(Number(o.value));return oo(a.getFullYear(),a.getMonth()+1)}let i=this.readOptionalYear(e);if(i!==null)return ls(i);throw c$1.parsing("DAYS_IN_EXPECTED_PERIOD",'Expected a month, quarter or year, as in "days in February 2020" or "days in Q3"')}readOptionalYear(e){let o=e.peek();if(o?.type!=="NUMBER")return null;let t=o.text??o.value??"";return /^\d{4}$/.test(t)?(e.consume(),Number(t)):null}};var us=new Set(["q1","q2","q3","q4"]),cs=new Set(["january","jan","february","feb","march","mar","april","apr","may","june","jun","july","jul","august","aug","september","sep","sept","october","oct","november","nov","december","dec"]);function ps(r){if(r===void 0)return false;if(r.type==="DATETIME_LITERAL")return true;let e=(r.text??r.value??"").toLowerCase();return r.type==="IDENT"||r.type==="UNIT"?us.has(e)||cs.has(e):r.type==="NUMBER"&&/^\d{4}$/.test(r.text??"")}function oi(r=60){return {name:"datetime:days-in-period",priority:r,match(e,o){let t=e[o];return t===void 0||(t.text??t.value??"").toLowerCase()!=="days"||t.type!=="UNIT"&&t.type!=="IDENT"||e[o+1]?.type!=="IN"||!ps(e[o+2])?null:{consumed:2,replacement:[b$4("DAYS_IN_PERIOD","days in",[t,e[o+1]])],ruleName:"datetime:days-in-period"}}}}function ni(){return {name:"datetime:daily-note-link",priority:80,match(r,e){return r[e]?.type!=="LBRACKET"||r[e+1]?.type!=="LBRACKET"||r[e+2]?.type!==be||r[e+3]?.type!=="RBRACKET"||r[e+4]?.type!=="RBRACKET"?null:{consumed:5,replacement:[r[e+2]],ruleName:"datetime:daily-note-link"}}}}var no={name:"solve-datetime",phrases:{"workdays in":"WORKDAYS_IN","working days after":"WORKDAYS_AFTER","business days after":"WORKDAYS_AFTER","working day after":"WORKDAYS_AFTER","business day after":"WORKDAYS_AFTER","working days from":"WORKDAYS_AFTER","business days from":"WORKDAYS_AFTER","working day from":"WORKDAYS_AFTER","business day from":"WORKDAYS_AFTER","working days before":"WORKDAYS_BEFORE","business days before":"WORKDAYS_BEFORE","working day before":"WORKDAYS_BEFORE","business day before":"WORKDAYS_BEFORE","working days between":"WORKDAYS_BETWEEN","business days between":"WORKDAYS_BETWEEN","day of the week on":"WEEKDAY_ON","weekday on":"WEEKDAY_ON","current timestamp":"CURRENT_TIMESTAMP","to date":"TO_DATE","to timestamp":"TO_TIMESTAMP","what day is it":"WEEKDAY_ON","what day is it on":"WEEKDAY_ON","what day will it be on":"WEEKDAY_ON","what day is it in":"WEEKDAY_IN","what day will it be in":"WEEKDAY_IN","what month is it":"MONTH_ON","what month is it on":"MONTH_ON","month of":"MONTH_ON","what month is it in":"MONTH_IN","what month will it be in":"MONTH_IN","what week is it":"WEEK_ON","what week is it on":"WEEK_ON","week of":"WEEK_ON","week number on":"WEEK_ON","week number of":"WEEK_ON","week number":"WEEK_ON","what week is it in":"WEEK_IN","what week will it be in":"WEEK_IN","is a weekend":"IS_WEEKEND","is on a weekend":"IS_WEEKEND","is a workday":"IS_WORKDAY","is a weekday":"IS_WORKDAY","is a business day":"IS_WORKDAY"},prefixParselets:{DAYS_IN_PERIOD:new gr,NOW:new Z(0),TODAY:new Z(0),TOMORROW:new Z(1),YESTERDAY:new Z(-1),NEXT:new ke("next"),LAST:new ke("last"),UNTIL_UNIT:new Be("until"),SINCE_UNIT:new Be("since"),WORKDAYS_IN:new ur,WORKDAYS_BETWEEN:new cr,WEEKDAY_ON:new V("weekdayOnDate","on"),WEEKDAY_IN:new V("weekdayOnDate","in"),MONTH_ON:new V("monthOnDate","on"),MONTH_IN:new V("monthOnDate","in"),WEEK_ON:new V("weekOnDate","on"),WEEK_IN:new V("weekOnDate","in"),BETWEEN_UNIT:new pr,CURRENT_TIMESTAMP:new fr,DATETIME_LITERAL:new Nr},infixParselets:{WORKDAYS_AFTER:new Ue("forward"),WORKDAYS_BEFORE:new Ue("backward"),TO_DATE:new dr,TO_TIMESTAMP:new Er,IS_WEEKEND:new Me("isWeekendOnDate"),IS_WORKDAY:new Me("isWorkdayOnDate")},normalizerRules:[Qn(),Zn(),qn(),ei(),ti(),oi(),ni()],pluginFunctions:{workdaysInDuration:$n,weekdayOnDate:Jt,toDateFromAny:jn,toTimestampFromAny:Xn,monthOnDate:eo,weekOnDate:ro,isWeekendOnDate:Kn,isWorkdayOnDate:Wn,spanBetweenDates:Yn},asConverters:{iso8601:r=>t(zn(r.toNumber())),weekday:r=>Jt([r]),month:r=>eo([r]),week:r=>ro([r])}};var fs={sydney:"Australia/Sydney",melbourne:"Australia/Melbourne",brisbane:"Australia/Brisbane",perth:"Australia/Perth",adelaide:"Australia/Adelaide",canberra:"Australia/Sydney",auckland:"Pacific/Auckland",wellington:"Pacific/Auckland",fiji:"Pacific/Fiji",chicago:"America/Chicago",seattle:"America/Los_Angeles",denver:"America/Denver",phoenix:"America/Phoenix",toronto:"America/Toronto",montreal:"America/Toronto",vancouver:"America/Vancouver",ottawa:"America/Toronto",honolulu:"Pacific/Honolulu",anchorage:"America/Anchorage",miami:"America/New_York",boston:"America/New_York",atlanta:"America/New_York",dallas:"America/Chicago",houston:"America/Chicago",lima:"America/Lima",bogota:"America/Bogota",caracas:"America/Caracas",santiago:"America/Santiago",montevideo:"America/Montevideo",quito:"America/Guayaquil",london:"Europe/London",paris:"Europe/Paris",berlin:"Europe/Berlin",madrid:"Europe/Madrid",rome:"Europe/Rome",amsterdam:"Europe/Amsterdam",dublin:"Europe/Dublin",lisbon:"Europe/Lisbon",vienna:"Europe/Vienna",zurich:"Europe/Zurich",geneva:"Europe/Zurich",moscow:"Europe/Moscow",istanbul:"Europe/Istanbul",athens:"Europe/Athens",stockholm:"Europe/Stockholm",oslo:"Europe/Oslo",helsinki:"Europe/Helsinki",warsaw:"Europe/Warsaw",prague:"Europe/Prague",budapest:"Europe/Budapest",brussels:"Europe/Brussels",copenhagen:"Europe/Copenhagen",reykjavik:"Atlantic/Reykjavik",kiev:"Europe/Kyiv",kyiv:"Europe/Kyiv",tokyo:"Asia/Tokyo",osaka:"Asia/Tokyo",beijing:"Asia/Shanghai",shanghai:"Asia/Shanghai",seoul:"Asia/Seoul",singapore:"Asia/Singapore",bangkok:"Asia/Bangkok",jakarta:"Asia/Jakarta",manila:"Asia/Manila",mumbai:"Asia/Kolkata",delhi:"Asia/Kolkata",bangalore:"Asia/Kolkata",dubai:"Asia/Dubai",abudhabi:"Asia/Dubai",karachi:"Asia/Karachi",dhaka:"Asia/Dhaka",hanoi:"Asia/Ho_Chi_Minh",taipei:"Asia/Taipei",islamabad:"Asia/Karachi",riyadh:"Asia/Riyadh",telaviv:"Asia/Jerusalem",jerusalem:"Asia/Jerusalem",cairo:"Africa/Cairo",lagos:"Africa/Lagos",nairobi:"Africa/Nairobi",johannesburg:"Africa/Johannesburg",casablanca:"Africa/Casablanca",accra:"Africa/Accra",tunis:"Africa/Tunis",addisababa:"Africa/Addis_Ababa",france:"Europe/Paris",germany:"Europe/Berlin",spain:"Europe/Madrid",italy:"Europe/Rome",japan:"Asia/Tokyo",china:"Asia/Shanghai",india:"Asia/Kolkata",brazil:"America/Sao_Paulo",russia:"Europe/Moscow",australia:"Australia/Sydney",canada:"America/Toronto",mexico:"America/Mexico_City",uk:"Europe/London",usa:"America/New_York",ireland:"Europe/Dublin",netherlands:"Europe/Amsterdam",sweden:"Europe/Stockholm",norway:"Europe/Oslo",poland:"Europe/Warsaw",turkey:"Europe/Istanbul",egypt:"Africa/Cairo",nigeria:"Africa/Lagos"},io={"new york":"America/New_York","los angeles":"America/Los_Angeles","san francisco":"America/Los_Angeles","las vegas":"America/Los_Angeles","mexico city":"America/Mexico_City","hong kong":"Asia/Hong_Kong","kuala lumpur":"Asia/Kuala_Lumpur","sao paulo":"America/Sao_Paulo","buenos aires":"America/Argentina/Buenos_Aires","rio de janeiro":"America/Sao_Paulo","cape town":"Africa/Johannesburg","new delhi":"Asia/Kolkata","united kingdom":"Europe/London","united states":"America/New_York","south africa":"Africa/Johannesburg"},ds={pst:"America/Los_Angeles",pdt:"America/Los_Angeles",est:"America/New_York",edt:"America/New_York",cst:"America/Chicago",cdt:"America/Chicago",mst:"America/Denver",mdt:"America/Denver",hst:"Pacific/Honolulu",bst:"Europe/London",cet:"Europe/Paris",cest:"Europe/Paris",jst:"Asia/Tokyo",ist:"Asia/Kolkata",aest:"Australia/Sydney",aedt:"Australia/Sydney"},ii={...fs,...io,...ds};var ao="UTCOFFSET:";function mo(r){return `${ao}${r}`}function ze(r){return r.startsWith(ao)}function He(r){return parseInt(r.slice(ao.length),10)}function Pr(r,e){if(ze(r))return He(r);let o=new Intl.DateTimeFormat("en-US",{timeZone:r,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),t={};for(let i of o.formatToParts(new Date(e)))t[i.type]=i.value;let n=Date.UTC(+t.year,+t.month-1,+t.day,+t.hour,+t.minute,+t.second);return Math.round((n-e)/6e4)}function mi(r,e,o,t,n,i){let a=Date.UTC(r,e,o,t,n,0),m=Pr(i,a);return a-m*6e4}function so(r,e){if(ze(e)){let t=He(e)*6e4;return Es(new Date(r+t))}return new Intl.DateTimeFormat("en-US",{timeZone:e,hour:"numeric",minute:"2-digit",hour12:true}).format(new Date(r))}function si(r,e){if(ze(e)){let t=He(e)*6e4;return Ns(new Date(r+t))}return new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"long",day:"numeric"}).format(new Date(r))}function ai(r,e){if(ze(e)){let n=new Date(r+He(e)*6e4);return {year:n.getUTCFullYear(),month0:n.getUTCMonth(),day:n.getUTCDate()}}let o=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit"}),t={};for(let n of o.formatToParts(new Date(r)))t[n.type]=n.value;return {year:+t.year,month0:+t.month-1,day:+t.day}}function li(r,e,o){let t=ai(r,e),n=ai(r,o),i=Date.UTC(t.year,t.month0,t.day),a=Date.UTC(n.year,n.month0,n.day);return Math.round((i-a)/864e5)}function Es(r){return new Intl.DateTimeFormat("en-US",{timeZone:"UTC",hour:"numeric",minute:"2-digit",hour12:true}).format(r)}function Ns(r){return new Intl.DateTimeFormat("en-US",{timeZone:"UTC",year:"numeric",month:"long",day:"numeric"}).format(r)}function lo(r){if(ze(r)){let o=He(r),t=o>=0?"+":"-",n=Math.abs(o),i=Math.floor(n/60),a=n%60;return a===0?`UTC${t}${i}`:`UTC${t}${i}:${String(a).padStart(2,"0")}`}return (r.split("/").pop()??r).replace(/_/g," ")}function Y(r){let e=r.peek();if(!e)return null;let o=e.value,t=o.toLowerCase();if(t==="gmt"||t==="utc"){r.consume();let i=r.peek();if(i?.type==="PLUS"||i?.type==="MINUS"){let m=i.type==="MINUS";r.consume();let s=r.peek(),u;if(s?.type==="CLOCK_TIME")r.consume(),u=parseInt(s.value,10);else {let p=r.consume("NUMBER");if(u=parseInt(p.value,10)*60,r.peek()?.type==="COLON"){r.consume();let E=r.consume("NUMBER");u+=parseInt(E.value,10);}}let c=mo(m?-u:u);return {zoneRef:c,displayName:lo(c)}}let a=mo(0);return {zoneRef:a,displayName:lo(a)}}let n=ii[t];if(n){r.consume();let i=o.replace(/\b\w/g,a=>a.toUpperCase());return {zoneRef:n,displayName:i}}return null}var _r="zoneConvert",uo="timeInZone",co="dateInZone",Or="timeDifference";function ui(r){let e=r[0].toNumber(),o=r[1].value,t$1=r[2].value,n=new Date,i=mi(n.getFullYear(),n.getMonth(),n.getDate(),Math.floor(e/60),e%60,o),a=so(i,t$1),m=li(i,t$1,o);if(m===0)return t(a);let s=m>0?"+":"";return t(`${a} (${s}${m} day${Math.abs(m)===1?"":"s"})`)}function ci(r){let e=r[0].value;return t(so(Date.now(),e))}function pi(r){let e=r[0].value;return t(si(Date.now(),e))}function fi(r){let e=r[0].value,o=r[1].value,t$1=r[2].value,n=r[3].value,i=Date.now(),a=Pr(e,i),s=Pr(o,i)-a;if(s===0)return t(`${n} and ${t$1} currently share the same UTC offset`);let u=s>0?n:t$1,c=s>0?t$1:n,p=Math.abs(s),E=Math.floor(p/60),T=p%60,y=[];return E>0&&y.push(`${E} hour${E===1?"":"s"}`),T>0&&y.push(`${T} minute${T===1?"":"s"}`),t(`${u} is ${y.join(" ")} ahead of ${c}`)}var Rr=class{constructor(){this.category="Time";}parse(e,o,t){let n=parseInt(o.value,10),i=Y(e);if(i!==null){if(e.peek()?.type!=="IN")throw c$1.parsing("TIME_ZONE_EXPECTED_IN",`Expected "in <city>" after the zone name (e.g. "6pm Sydney in Chicago") but got ${e.peek()?`"${e.peek().value}"`:"end of input"}`);e.consume();let a=Y(e);if(a===null)throw c$1.parsing("TIME_ZONE_EXPECTED_TARGET",'Expected a city or zone name after "in" (e.g. "6pm Sydney in Chicago")');t.emitOpcode(10),t.emitNumber(n),t.emitOpcode(13),t.emitString(i.zoneRef),t.emitOpcode(13),t.emitString(a.zoneRef),t.emitPluginCall(_r,3);return}t.emitOpcode(10),t.emitNumber(n),t.emitOpcode(120);}};var Ar=class{constructor(){this.category="Time";}parse(e,o,t){let[n,i]=o.value.split(":"),a=parseInt(n,10),m=parseInt(i,10),s=m>=a?m-a:1440-a+m;t.emitOpcode(10),t.emitNumber(s),t.emitOpcode(13),t.emitString("minutes"),t.emitOpcode(80);}};var Ir=class{constructor(){this.category="Time";}parse(e,o,t){t.emitOpcode(10),t.emitNumber(parseFloat(o.value)),t.emitOpcode(13),t.emitString("frames/s"),t.emitOpcode(80);}};var Cr=class{constructor(){this.category="Time";}parse(e,o,t){t.emitOpcode(10),t.emitNumber(parseFloat(o.value)),t.emitOpcode(13),t.emitString("s"),t.emitOpcode(80);}};function po(r){return {category:"Time",parse(e,o,t){let n=Y(e);if(n===null)throw c$1.parsing("TIME_ZONE_EXPECTED_CITY",`Expected a city or zone name after "${o.value}" (e.g. "time in Paris")`);t.emitOpcode(13),t.emitString(n.zoneRef),t.emitPluginCall(r,1);}}}var hr=class{constructor(){this.category="Time";}parse(e,o,t){let n=Y(e);if(n===null)throw c$1.parsing("TIME_DIFFERENCE_EXPECTED_CITY",'Expected a city or zone name after "time difference between" (e.g. "time difference between Seattle and Moscow")');e.consume("AND_CONJ");let i=Y(e);if(i===null)throw c$1.parsing("TIME_DIFFERENCE_EXPECTED_SECOND_CITY",'Expected a second city or zone name after "and" (e.g. "time difference between Seattle and Moscow")');t.emitOpcode(13),t.emitString(n.zoneRef),t.emitOpcode(13),t.emitString(i.zoneRef),t.emitOpcode(13),t.emitString(n.displayName),t.emitOpcode(13),t.emitString(i.displayName),t.emitPluginCall(Or,4);}};var xr=class{constructor(){this.category="Time";}parse(e,o,t){let[n,i,a,m]=o.value.split(",").map(Number),s=e.peek();if(!s||s.type!=="RATE_AT"&&s.type!=="AT")throw c$1.parsing("TIMECODE_EXPECTED_FPS",`A video timecode must specify a frame rate, e.g. "${o.value.split(",").join(":")} at 30 fps" or "... @ 30 fps"`);e.consume();let u=e.peek();if(!u||u.type!=="FPS_RATE")throw c$1.parsing("TIMECODE_EXPECTED_FPS",`Expected "<number> fps" after "${s.value}" (e.g. "at 30 fps")`);e.consume();let c=parseFloat(u.value),p=Math.round(c);if(m>=p)throw c$1.parsing("TIMECODE_FRAME_OUT_OF_RANGE",`Frame number ${m} is out of range for ${c} fps (must be 0-${p-1})`);let E=(n*3600+i*60+a)*p+m,T=z$2(c);if(e.peek()?.type==="IN"){e.consume();let y=e.peek();if(!y||y.type!=="IDENT"||y.value.toLowerCase()!=="frames")throw c$1.parsing("TIMECODE_EXPECTED_FRAMES",`Expected "frames" after "in" (e.g. "... in frames") but got ${y?`"${y.value}"`:"end of input"}`);e.consume(),T="frames";}t.emitOpcode(10),t.emitNumber(E),t.emitOpcode(13),t.emitString(T),t.emitOpcode(80);}};function di(r,e){let o=Math.max(1,Math.round(e)),t=c=>String(c).padStart(2,"0"),n=Math.trunc(r),i=(n%o+o)%o,a=Math.floor(n/o),m=Math.floor(a/3600),s=Math.floor(a%3600/60),u=a%60;return `${t(m)}:${t(s)}:${t(u)}:${t(i)}`}var vr=class{constructor(){this.category="Time";}parse(e,o,t){let n=parseFloat(o.value),i=e.peek();if(i&&(i.type==="RATE_AT"||i.type==="AT")){e.consume();let a=e.peek();if(!a||a.type!=="FPS_RATE")throw c$1.parsing("TIMECODE_EXPECTED_FPS",`Expected "<number> fps" after "${i.value}" (e.g. "@ 30 fps")`);e.consume();let m=parseFloat(a.value);t.emitOpcode(13),t.emitString(di(n,m));return}t.emitOpcode(10),t.emitNumber(n),t.emitOpcode(13),t.emitString("frames"),t.emitOpcode(80);}};function Ei(r,e,o){if(e<0||e>59)return null;if(o){if(r<1||r>12)return null;let t=o.toLowerCase()==="pm";return (r%12+(t?12:0))*60+e}return r<0||r>23?null:r*60+e}function Ni(r){return !!r&&r.type==="IDENT"&&/^(am|pm)$/i.test(r.value)}function Ti(r=65){return {name:"time:clock-time",priority:r,match(e,o){if(e$4(e,o))return null;let t=e[o];if(t.type!=="NUMBER")return null;let n=parseInt(t.value,10);if(isNaN(n)||n<0||n>23)return null;let i=e[o+1],a=e[o+2];if(i?.type==="COLON"&&a?.type==="NUMBER"){let s=parseInt(a.value,10),u=e[o+3],c=Ni(u),p=Ei(n,s,c?u.value:void 0);if(p===null)return null;let E=c?4:3;return {consumed:E,replacement:[b$4("CLOCK_TIME",String(p),e.slice(o,o+E))],ruleName:"time:clock-time"}}let m=e[o+1];if(Ni(m)){let s=Ei(n,0,m.value);return s===null?null:{consumed:2,replacement:[b$4("CLOCK_TIME",String(s),e.slice(o,o+2))],ruleName:"time:clock-time"}}return null}}}function yi(r=66){return {name:"time:clock-time-interval",priority:r,match(e,o){let t=e[o],n=e[o+1],i=e[o+2];return t.type!=="CLOCK_TIME"||n?.type!=="TO"||i?.type!=="CLOCK_TIME"?null:{consumed:3,replacement:[b$4("CLOCK_TIME_INTERVAL",`${t.value}:${i.value}`,e.slice(o,o+3))],ruleName:"time:clock-time-interval"}}}}function gi(r=65){return {name:"time:fps-rate",priority:r,match(e,o){let t=e[o],n=e[o+1];return t.type!=="NUMBER"||n?.type!=="IDENT"||n.value.toLowerCase()!=="fps"?null:{consumed:2,replacement:[b$4("FPS_RATE",t.value,e.slice(o,o+2))],ruleName:"time:fps-rate"}}}}function Pi(r=70){return {name:"time:laptime",priority:r,match(e,o){if(e$4(e,o))return null;let t=e[o],n=e[o+1],i=e[o+2],a=e[o+3],m=e[o+4];if(t.type!=="NUMBER"||n?.type!=="COLON"||i?.type!=="NUMBER"||a?.type!=="COLON"||m?.type!=="NUMBER")return null;let s=parseInt(t.value,10),u=parseInt(i.value,10),c=parseFloat(m.value);if(isNaN(s)||isNaN(u)||isNaN(c)||u<0||u>59||c<0||c>=60)return null;let p=s*3600+u*60+c;return {consumed:5,replacement:[b$4("LAPTIME",String(p),e.slice(o,o+5))],ruleName:"time:laptime"}}}}function _i(r=75){return {name:"time:video-timecode",priority:r,match(e,o){if(e$4(e,o))return null;let t=e[o],n=e[o+1],i=e[o+2],a=e[o+3],m=e[o+4],s=e[o+5],u=e[o+6];if(t?.type!=="NUMBER"||n?.type!=="COLON"||i?.type!=="NUMBER"||a?.type!=="COLON"||m?.type!=="NUMBER"||s?.type!=="COLON"||u?.type!=="NUMBER")return null;let c=parseInt(t.value,10),p=parseInt(i.value,10),E=parseInt(m.value,10),T=parseInt(u.value,10);return [c,p,E,T].some(y=>isNaN(y))||p<0||p>59||E<0||E>59||c<0||T<0?null:{consumed:7,replacement:[b$4("VIDEO_TIMECODE",`${c},${p},${E},${T}`,e.slice(o,o+7))],ruleName:"time:video-timecode"}}}}function Oi(r=65){return {name:"time:frame-count",priority:r,match(e,o){let t=e[o],n=e[o+1];return t.type!=="NUMBER"||n?.type!=="IDENT"||n.value.toLowerCase()!=="frames"?null:{consumed:2,replacement:[b$4("FRAME_COUNT",t.value,e.slice(o,o+2))],ruleName:"time:frame-count"}}}}var Ts=14,ys=[["week","weeks",604800],["day","days",86400],["hour","hours",3600],["minute","minutes",60],["second","seconds",1]];function Ri(r){if(r.type===0)return r.toNumber();if(r.type!==6||r.unit===void 0)return null;let e=a$6[r.unit.toLowerCase()];return e===void 0||e[0]!==Ts?null:r.toNumber()*e[1]}function Ai(r){let e=Ri(r);if(e===null)return t(`"as timespan" needs a duration, got ${r.unit??"a non-duration"}`);let o=e<0,t$1=Math.abs(e),n=[];for(let[a,m,s]of ys){if(s===1)break;let u=Math.floor(t$1/s);u>0&&(n.push(`${u} ${u===1?a:m}`),t$1-=u*s);}let i=Math.round(t$1*1e3)/1e3;return (i>0||n.length===0)&&n.push(`${i} ${i===1?"second":"seconds"}`),t((o?"-":"")+n.join(" "))}function Eo(r){let e=Ri(r);if(e===null)return t(`"as laptime" needs a duration, got ${r.unit??"a non-duration"}`);let o=e<0,t$1=Math.round(Math.abs(e)*1e3)/1e3,n=Math.floor(t$1/3600),i=Math.floor(t$1%3600/60),a=t$1%60,m=Math.floor(a),s=Math.round((a-m)*1e3),u=`${fo(n)}:${fo(i)}:${fo(m)}`;return t((o?"-":"")+(s>0?`${u}.${String(s).padStart(3,"0")}`:u))}function fo(r){return r<10?`0${r}`:String(r)}var No={name:"solve-time",asConverters:{timespan:Ai,laptime:Eo,lap:Eo},phrases:{"time in":"TIME_IN","date in":"DATE_IN","time difference between":"TIME_DIFFERENCE_BETWEEN",...Object.fromEntries(Object.keys(io).map(r=>[r,"CITY_NAME"]))},prefixParselets:{CLOCK_TIME:new Rr,CLOCK_TIME_INTERVAL:new Ar,FPS_RATE:new Ir,LAPTIME:new Cr,TIME_IN:po(uo),DATE_IN:po(co),TIME_DIFFERENCE_BETWEEN:new hr,VIDEO_TIMECODE:new xr,FRAME_COUNT:new vr},normalizerRules:[Ti(),yi(),gi(),Pi(),_i(),Oi()],pluginFunctions:{[_r]:ui,[uo]:ci,[co]:pi,[Or]:fi}};function Sr(r){for(let e of r.alternatives){let o=e.slots[0];if(!o||o.kind!=="keyword")throw c$1.config("INVALID_PHRASE_PATTERN","Every PhraseAlternative's first slot must be a `keyword` slot \u2014 alternatives are chosen by peeking the next token, which only works if the choice is decidable from one leading keyword.",{category:r.category})}return {category:r.category,parse(e,o,t){let n=e.peek(),i=r.alternatives.find(m=>{let s=m.slots[0];return n!==void 0&&s.tokenTypes.includes(n.type)});if(!i){let m=r.alternatives.map(s=>s.slots[0].tokenTypes.join("|")).join(", ");throw c$1.parsing("NO_MATCHING_PHRASE_ALTERNATIVE",`Expected one of [${m}] but got "${n?.type??"end of input"}" ("${n?.value??""}")`,{category:r.category,expected:m,actualType:n?.type,actualValue:n?.value})}let a=[];for(let m of i.slots)if(m.kind==="keyword"){let s=e.peek();if(!s||!m.tokenTypes.includes(s.type))throw c$1.parsing("PHRASE_KEYWORD_MISMATCH",`Expected one of [${m.tokenTypes.join("|")}] but got "${s?.type??"end of input"}" ("${s?.value??""}")`,{category:r.category,expected:m.tokenTypes,actualType:s?.type,actualValue:s?.value});e.consume(),a.push({type:s.type,value:s.value});}else e.parseExpression(m.bindingPower??0,t);i.emit(t,a);}}}var gs=37;function Lr(r){r.emitOpcode(51),r.emitIndex(gs),r.emitIndex(2);}var Ps=Sr({category:"Dice",alternatives:[{slots:[{kind:"keyword",tokenTypes:["BETWEEN"]},{kind:"expr",bindingPower:a.Product},{kind:"keyword",tokenTypes:["AND_CONJ"]},{kind:"expr"}],emit:Lr},{slots:[{kind:"keyword",tokenTypes:["FROM"]},{kind:"expr",bindingPower:a.Product},{kind:"keyword",tokenTypes:["TO"]},{kind:"expr"}],emit:Lr},{slots:[{kind:"keyword",tokenTypes:["LPAREN"]},{kind:"expr"},{kind:"keyword",tokenTypes:["COMMA"]},{kind:"expr"},{kind:"keyword",tokenTypes:["RPAREN"]}],emit:Lr}]}),wr=class{constructor(){this.category="Dice";}parse(e,o,t){let n=e.peek();if(n&&n.type==="NUMBER"){let i=e.consume();t.emitOpcode(10),t.emitNumber(parseFloat(i.value)),e.consume("MINUS");let a=e.consume();t.emitOpcode(10),t.emitNumber(parseFloat(a.value)),Lr(t);return}Ps.parse(e,o,t);}};var To={name:"solve-dice",prefixParselets:{ROLL:new wr}};var kr=class{constructor(){this.category="Variable";}parse(e,o,t){let n=e.consume();if(n.type!=="IDENT"&&n.type!=="UNIT")throw c$1.parsing("EXPECTED_IDENTIFIER",`Expected identifier or unit after colon, got ${n.type}`,{tokenType:n.type});let i=n.value;e.peek()?.type==="EQUALS"?(e.consume("EQUALS"),e.parseExpression(0,t),t.emitOpcode(61),t.emitString(i)):(t.emitOpcode(60),t.emitString(i));}};var Ge=class{constructor(){this.category="Variable";}parse(e,o,t){t.emitOpcode(60),t.emitString(o.value);}};var Br=class{constructor(){this.category="Variable";}parse(e,o,t){e.consume("COLON");let n=e.consume();if(n.type!=="IDENT"&&n.type!=="UNIT")throw c$1.parsing("EXPECTED_IDENTIFIER",`Expected identifier after 'global :', got ${n.type}`,{tokenType:n.type});let i=n.value;e.peek()?.type==="EQUALS"?(e.consume("EQUALS"),e.parseExpression(0,t),t.emitOpcode(63),t.emitString(i)):(t.emitOpcode(62),t.emitString(i));}};var Ur=class{constructor(){this.namespace="global-variables";this.pending=new Map;}preflight(e,o,t,n,i){let{opcodes:a,strings:m}=o,s=a.length,u=0;for(;u<s;){if(a[u]===62){let p=m[a[u+1]];if(!J$2.has(p))return this.pendingResultFor(p,t,n)}u=a$2(a,u);}return null}pendingResultFor(e,o,t){let n=this.pending.get(e);return n||(n=new Promise(i=>{let a=J$2.subscribe((m,s)=>{m===e&&(a(),this.pending.delete(e),i(s));});}),this.pending.set(e,n)),{queryKey:`global:${e}`,resolver:n,packageId:o,signal:t,metadata:{varName:e}}}destroy(){this.pending.clear();}};var yo={name:"solve-variables",asyncResolvers:[new Ur],prefixParselets:{COLON:new kr,IDENT:new Ge,UNIT:new Ge,GLOBAL:new Br}};var Ci="currency-historical",q="historicalCurrency",_s=`solve-currency:${q}`,Mr={NOT_CONFIGURED:"HISTORICAL_RATES_NOT_CONFIGURED",QUERY_FAILED:"HISTORICAL_RATE_QUERY_FAILED",NOT_PREFLIGHTED:"HISTORICAL_RATE_NOT_PREFLIGHTED",INVALID_OPERAND:"HISTORICAL_CURRENCY_INVALID_OPERAND"},Os=3e4,hi=1/0,Rs=1e4;function go(r,e,o){return [Ci,`${r.toUpperCase()}:${e.toUpperCase()}:${o}`]}function Ii(r){return r<10?`0${r}`:String(r)}function Dr(r,e,o){if(!c$3.isCurrency(e)||o!==void 0&&!c$3.isCurrency(o))return null;let t=r.peek();if(!t||t.type!=="IDENT"||t.value.toLowerCase()!=="on")return null;let n=r.peekAt(1);if(!n||n.type!=="DATETIME_LITERAL")return null;r.consume(),r.consume();let i=new Date(Number(n.value));return `${i.getFullYear()}-${Ii(i.getMonth()+1)}-${Ii(i.getDate())}`}async function xi(r,e,o,t,n$1,i){let a=e.toUpperCase(),m=o.toUpperCase();if(!r)return N(Mr.NOT_CONFIGURED,`Historical exchange rates are not configured. Supply historicalRateProvider via createCurrencyPackage({ ... }) to convert ${a} to ${m} on ${t}.`);let{signal:s,cleanup:u}=a$3(n$1,Rs,"Historical currency rate fetch");try{let c=await r(a,m,t,s);return n(c)}catch(c){let p=N(Mr.QUERY_FAILED,`Failed to resolve the historical rate for ${a} to ${m} on ${t}: ${c instanceof Error?c.message:String(c)}`),E=go(e,o,t);return setTimeout(()=>{i.getQueryData(E)===p&&i.removeQueries({queryKey:E,exact:true});},Os).unref?.(),p}finally{u();}}function Po(r){return e=>{let o=e[0],t=e[1],n=e[2],i=O(o);if(i)return i;if(o.type!==6||o.unit===void 0||!c$3.isCurrency(o.unit))return N(Mr.INVALID_OPERAND,'Historical conversion needs an amount in a currency, for example "100 USD in GBP on 2024-01-15".');let a=o.unit,m=String(t.value),s=String(n.value);if(a.toUpperCase()===m.toUpperCase())return u$1(o.toNumber(),m);let u=b$3(),c=go(a,m,s),p=u?.getQueryData(c);if(p===void 0)return u?u.fetchQuery({queryKey:c,queryFn:({signal:T})=>xi(r,a,m,s,T,u),staleTime:hi}):N(Mr.NOT_PREFLIGHTED,`No historical rate resolved for ${a.toUpperCase()} to ${m.toUpperCase()} on ${s}.`);if(p.type===13)return p;let E=p.value;return u$1(o.toNumber()*E,m)}}function vi(r){return {namespace:Ci,preflight(e,o,t,n,i){let{opcodes:a,strings:m}=o,s=a.length,u=F(_s),c=0,p=[];for(;c<s;){let E=a[c];if(E===13)p.push(a[c+1]);else if(E===50){let T=a[c+1],y=a[c+2];if(T===u&&y===3&&p.length>=3){let O=m[p[p.length-1]],L=m[p[p.length-2]],x=new Set;for(let F=0;F<p.length-2;F++){let $=m[p[F]];c$3.isCurrency($)&&x.add($.toUpperCase());}if(x.size===1){let F=x.values().next().value;if(F!==L.toUpperCase()){let $=go(F,L,O);if(i.getQueryData($)===void 0){let bt=i.fetchQuery({queryKey:$,queryFn:({signal:ie})=>xi(r,F,L,O,ie,i),staleTime:hi});return {queryKey:$.join(":"),resolver:bt,packageId:t,signal:n,metadata:{from:F,to:L,isoDate:O}}}}}}p=[];}c=a$2(a,c);}return null},destroy(){}}}function Si(r){return ta$1(r)??r}var Fr=class{constructor(){this.category="UoM";this.bindingPower=a.Postfix;}parse(e,o,t,n){let i=Si(t.value);if(n.emitOpcode(13),n.emitString(i),!(e.infixMinBindingPower>=a.Product)&&(e.peek()?.type==="TO"||e.peek()?.type==="IN")){e.consume();let m=e.peek();if(m?.type==="UNIT"||m?.type==="IN"){e.consume();let s=Si(m.value),u=Dr(e,s,i);if(u!==null){n.emitOpcode(80),n.emitOpcode(13),n.emitString(s),n.emitOpcode(13),n.emitString(u),n.emitPluginCall(q,3);return}n.emitOpcode(13),n.emitString(s),n.emitOpcode(81);return}if(m?.type==="QUESTION"){e.consume(),n.emitOpcode(85);return}}if(e.peek()?.type==="BEST"){e.consume(),n.emitOpcode(83);return}n.emitOpcode(80);}};function _o(r){return ta$1(r)??r}var br=class{constructor(){this.category="UoM";}parse(e,o,t){e.parseExpression(a.Postfix,t);let n=e.peek();if(n&&n.type==="UNIT"){if(e.consume(),t.emitOpcode(13),t.emitString(_o(n.value)),e.peek()?.type==="TO"){e.consume("TO");let i=e.consume();i?.type==="UNIT"?(t.emitOpcode(13),t.emitString(_o(i.value)),t.emitOpcode(81)):i?.type==="BEST"&&t.emitOpcode(83);}else t.emitOpcode(80);return}if(n&&(n.type==="TO"||n.type==="IN")){e.consume();let i=e.peek();i?.type==="UNIT"||i?.type==="IN"||i?.type==="DOLLAR"||i?.type==="POUND"||i?.type==="EURO"||i?.type==="YEN"||i?.type==="RUBLE"||i?.type==="WON"||i?.type==="CURRENCY_SYMBOL"||i?.type==="IDENT"?(e.consume(),t.emitOpcode(13),t.emitString(_o(i.value)),t.emitOpcode(84)):i?.type==="BEST"&&(e.consume(),t.emitOpcode(83));return}}};var Vr=class{constructor(){this.category="UoM";}parse(e,o,t){t.emitOpcode(13),t.emitString(o.value),t.emitOpcode(85);}};function Li(r=60){return {name:"uom:possibilities",priority:r,match(e,o){if(o+2>=e.length)return null;let t=e[o],n=e[o+1],i=e[o+2];return t.type!=="UNIT"||n.type!=="TO"||i.type!=="QUESTION"?null:{consumed:3,replacement:[b$4("UOM_POSSIBILITIES_QUERY",t.value,[t,n,i])],ruleName:"uom:possibilities"}}}}var wi=14;function ki(r,e){if(r===void 0||r.type!=="UNIT")return;let o=(r.value??"").toLowerCase();if(o==="m"&&e===wi)return {kind:wi,ratio:60,spelling:"minutes"};let t=a$6[o];return t===void 0?void 0:{kind:t[0],ratio:t[1],spelling:o}}var Bi=/^\d+(\.\d+)?$/;function Ui(r=63){return {name:"uom:compound-quantity",priority:r,match(e,o){let t=e[o];if(t?.type!=="NUMBER"||!Bi.test(t.text??""))return null;let n=ki(e[o+1]);if(n===void 0)return null;let i=n.kind,a=n.ratio,m=Number(t.text)*a,s=n.spelling,u=e[o+1],c=2;for(;;){let T=e[o+c];if(T?.type!=="NUMBER"||!Bi.test(T.text??""))break;let y=ki(e[o+c+1],i);if(y===void 0||y.kind!==i||y.ratio>=a)break;m+=Number(T.text)*y.ratio,a=y.ratio,s=y.spelling,u=e[o+c+1],c+=2;}if(c===2)return null;let p=e.slice(o,o+c),E=m/a;return {consumed:c,replacement:[b$4("NUMBER",String(E),p),b$4("UNIT",s,[u])],ruleName:"uom:compound-quantity"}}}}function Mi(r){return r===void 0||r.type!=="UNIT"?false:a$6[(r.value??"").toLowerCase()]!==void 0}function Di(r=59){return {name:"uom:two-unit-conversion",priority:r,match(e,o){let t=e[o];if(t?.type!=="IN"&&t?.type!=="TO"||!Mi(e[o+1])||e[o+2]?.type!=="AND_CONJ"||!Mi(e[o+3]))return null;let n=e[o+1].value,i=e[o+3].value;return {consumed:4,replacement:[b$4("IN_TWO_UNITS",`${n} ${i}`,e.slice(o,o+4))],ruleName:"uom:two-unit-conversion"}}}}function Fi(r=74){return {name:"uom:degree-symbol",priority:r,match(e,o){let t=e[o];if(t?.type!=="NUMBER")return null;let n=e[o+1];return n===void 0||n.type!=="IDENT"||(n.text??n.value??"")!=="\xB0"?null:{consumed:2,replacement:[t,b$4("UNIT","degrees",[n])],ruleName:"uom:degree-symbol"}}}}var zr=class{constructor(e){this.builtinIndex=e;this.category="Uom";this.bindingPower=a.Conditional;}parse(e,o,t,n){let[i,a]=String(t.value).split(" ");n.emitOpcode(13),n.emitString(i),n.emitOpcode(13),n.emitString(a),n.emitOpcode(51),n.emitIndex(this.builtinIndex),n.emitIndex(3);}};function bi(r){return r===void 0||r.type!=="UNIT"?false:a$6[(r.value??"").toLowerCase()]!==void 0}var Oo=new Set(["per","a","an","each","every"]);function As(r){if(r===void 0||r.type!=="IDENT")return false;let e=(r.text??r.value??"").toLowerCase();return Oo.has(e)?false:/^[a-z][a-z_]{2,}$/.test(e)&&a$6[e]===void 0}function Vi(r=75){return {name:"uom:bare-rate-denominator",priority:r,match(e,o){let t=e[o];if(t===void 0)return null;if(t.type==="NUMBER"&&As(e[o+1])){let s=e[o+1],u=e[o+2];if((u?.type==="SLASH"||u?.type==="IDENT"&&Oo.has((u.text??u.value??"").toLowerCase()))&&bi(e[o+3]))return {consumed:2,replacement:[t,b$4("UNIT",s.value,[s])],ruleName:"uom:bare-rate-denominator"}}if(!bi(e[o+1]))return null;let n=t.type==="SLASH",i=(t.text??t.value??"").toLowerCase(),a=t.type==="IDENT"&&Oo.has(i);if(!n&&!a)return null;let m=e[o+1];return {consumed:2,replacement:[b$4("PER_UNIT",m.value,[t,m])],ruleName:"uom:bare-rate-denominator"}}}}var Hr=class{constructor(e){this.builtinIndex=e;this.category="Uom";this.bindingPower=a.Product;}parse(e,o,t,n){n.emitOpcode(13),n.emitString(String(t.value)),n.emitOpcode(51),n.emitIndex(this.builtinIndex),n.emitIndex(2);}};var Gr=class{constructor(e){this.builtinIndex=e;this.category="Uom";this.bindingPower=a.Product;}parse(e,o,t,n){e.parseExpression(a.Conditional,n),n.emitOpcode(51),n.emitIndex(this.builtinIndex),n.emitIndex(2);}};function Is(r){return r===void 0||r.type!=="UNIT"?false:a$6[(r.value??"").toLowerCase()]!==void 0}var Cs=new Set(["per","a","an","each","every"]);function hs(r,e){for(let o=e;o<r.length&&o<e+5;o++){let t=r[o];if(t.type==="PER_UNIT")return true;if(t.type==="EOF"||t.type==="COMMA"||t.type==="RATE_AT")return false;let n=(t.text??t.value??"").toLowerCase();if((t.type==="SLASH"||t.type==="IDENT"&&Cs.has(n))&&Is(r[o+1]))return true}return false}function zi(r=73){return {name:"uom:at-rate",priority:r,match(e,o){return e[o]?.type!=="RATE_AT"||!hs(e,o+1)?null:{consumed:1,replacement:[b$4("AT_RATE","at",[e[o]])],ruleName:"uom:at-rate"}}}}function xs(r){return r===void 0||r.type!=="UNIT"?false:a$6[(r.value??"").toLowerCase()]!==void 0}var vs=new Set(["a","an"]);function Hi(r=76){return {name:"uom:for-duration",priority:r,match(e,o){let t=e[o];if(t?.type!=="FOR_DURATION")return null;let n=e[o+1];return n?.type!=="IDENT"||!vs.has((n.text??n.value??"").toLowerCase())||!xs(e[o+2])?null:{consumed:3,replacement:[b$4("STAR","*",[t]),b$4("NUMBER","1",[n]),e[o+2]],ruleName:"uom:for-duration"}}}}function Ro(r){return r===void 0||r.type!=="UNIT"?false:a$6[(r.value??"").toLowerCase()]!==void 0}var Ss=new Set(["a","an"]);function Gi(r=61){return {name:"uom:reversed-conversion",priority:r,match(e,o){if(o!==0||!Ro(e[o])||e[o+1]?.type!=="IN")return null;let t=e[o],n=e[o+2];if(n===void 0)return null;if(n.type==="NUMBER"&&Ro(e[o+3]))return {consumed:4,replacement:[n,e[o+3],e[o+1],t],ruleName:"uom:reversed-conversion"};let i=(n.text??n.value??"").toLowerCase();return n.type==="IDENT"&&Ss.has(i)&&Ro(e[o+3])?{consumed:4,replacement:[b$4("NUMBER","1",[n]),e[o+3],e[o+1],t],ruleName:"uom:reversed-conversion"}:null}}}var Ls={water:1,milk:1.03,"whole milk":1.03,"skim milk":1.035,buttermilk:1.03,"heavy cream":1,"whipping cream":1,"sour cream":.96,yogurt:1.03,"greek yogurt":1.05,"cream cheese":1.01,"condensed milk":1.3,"evaporated milk":1.06,"coconut milk":.97,"almond milk":1.03,"soy milk":1.03,butter:.9595,margarine:.96,"vegetable oil":.92,"olive oil":.913,"canola oil":.92,"coconut oil":.92,"sunflower oil":.92,"sesame oil":.92,mayonnaise:.91,sugar:.845,"granulated sugar":.845,"brown sugar":.93,"powdered sugar":.51,"icing sugar":.51,honey:1.42,"maple syrup":1.32,"corn syrup":1.38,molasses:1.4,nutella:1.14,"peanut butter":1.09,flour:.53,"all-purpose flour":.53,"all purpose flour":.53,"bread flour":.54,"cake flour":.47,"whole wheat flour":.55,cornstarch:.53,cornmeal:.65,semolina:.6,rice:.79,"white rice":.79,"brown rice":.8,oats:.34,"rolled oats":.38,breadcrumbs:.43,yeast:.68,"dry yeast":.68,salt:1.2,"table salt":1.2,"kosher salt":.96,"baking powder":.9,"baking soda":.99,"cream of tartar":.68,cinnamon:.56,ginger:.5,"vanilla extract":.88,"lemon juice":1.03,"lime juice":1.02,"orange juice":1.04,vinegar:1.01,cocoa:.41,"cocoa powder":.41,"chocolate chips":.72,"chocolate chunks":.72,coconut:.35,"shredded coconut":.35,raisins:.68,almonds:.55,walnuts:.5,pecans:.5,pistachios:.55,peanuts:.6,"shredded cheese":.4,parmesan:.44,"tomato paste":1.06,"tomato sauce":1.02,ketchup:1.14,broth:1,stock:1,wine:.99,beer:1.01},$i=2;function Ki(r){return Ls[r.toLowerCase().trim()]}var $r="cookingConvert";function Wi(r){let e=r[0],o=r[1].value,t=r[2].value;if(e.type!==6||!e.unit)return N("COOKING_CONVERSION_REQUIRES_UNIT",'Expected a value with a mass or volume unit (e.g. "300g", "10 cups"), got a plain number');let n=e.unit,i=e.toNumber(),a=c$4(n),m=c$4(t),s=T=>T==="mass"||T==="volume";if(!s(a))return N("COOKING_CONVERSION_UNSUPPORTED_UNIT",`"${n}" is not a recognized mass or volume unit`);if(!s(m))return N("COOKING_CONVERSION_UNSUPPORTED_UNIT",`"${t}" is not a recognized mass or volume unit`);if(a===m)return u$1(e$1(i,n,t),t);let u=Ki(o);if(u===void 0)return N("COOKING_UNKNOWN_INGREDIENT",`No density data for "${o}" \u2014 cannot convert between mass and volume for this ingredient`);if(a==="mass"){let y=e$1(i,n,"g")/u,O=e$1(y,"ml",t);return u$1(O,t)}let p=e$1(i,n,"ml")*u,E=e$1(p,"g",t);return u$1(E,t)}var Kr=class{constructor(){this.category="UoM";this.bindingPower=35;}parse(e,o,t,n){let i=t.value;e.consume("IN");let a=e.consume();n.emitOpcode(13),n.emitString(i),n.emitOpcode(13),n.emitString(a.value),n.emitPluginCall($r,3);}};function Yi(r=68){return {name:"uom-cooking:ingredient-name",priority:r,match(e,o){let t=e[o-1];if(!t||t.type!=="UNIT")return null;for(let n=$i;n>=1;n--){if(o+n>e.length)continue;let i=e.slice(o,o+n);if(!i.every(c=>c.type==="IDENT"))continue;let a=o+n,m=e[a];if(!m||m.type!=="IN")continue;let s=e[a+1];if(!s||s.type!=="UNIT"&&s.type!=="IDENT")continue;let u=i.map(c=>c.value.toLowerCase()).join(" ");return {consumed:n,replacement:[b$4("INGREDIENT_NAME",u,i)],ruleName:"uom-cooking:ingredient-name"}}return null}}}function ji(r=78){return {name:"uom:multi-word-unit",priority:r,match(e,o){let t=e[o],n=e[o+1];if(t?.type!=="UNIT"||n?.type!=="UNIT"||t.offset+t.text.length+1!==n.offset)return null;let i=`${t.value} ${n.value}`;return a$6[i]===void 0?null:{consumed:2,replacement:[b$4("UNIT",i,e.slice(o,o+2))],ruleName:"uom:multi-word-unit"}}}}function Xi(r=77){return {name:"uom:compound-unit",priority:r,match(e,o){let t=e[o],n=e[o+1],i=e[o+2];if(t?.type!=="UNIT"||n?.type!=="SLASH"||i?.type!=="UNIT")return null;let a=`${t.value}/${i.value}`;return {consumed:3,replacement:[b$4("UNIT",a,[t,n,i])],ruleName:"uom:compound-unit"}}}}var Ao={name:"solve-uom",prefixParselets:{CONVERT:new br,UOM_POSSIBILITIES_QUERY:new Vr},infixParselets:{IN_TWO_UNITS:new zr(94),PER_UNIT:new Hr(95),AT_RATE:new Gr(96),UNIT:new Fr,INGREDIENT_NAME:new Kr},normalizerRules:[ji(),Xi(),Li(),Ui(),Di(),Fi(),zi(),Hi(),Vi(),Gi(),Yi()],pluginFunctions:{[$r]:Wi}};var M=class{constructor(){this.category="UoM";}parse(e,o,t){let n=ta$1(o.value)??o.value.toUpperCase();e.parseExpression(a.Prefix,t),e.peek()?.type==="UNIT"&&e.consume(),t.emitOpcode(13),t.emitString(n),t.emitOpcode(80);}};var Wr=class{constructor(){this.category="UoM";this.bindingPower=35;}parse(e,o,t,n){let i=e.peek();if(i&&(i.type==="UNIT"||i.type==="DOLLAR"||i.type==="POUND"||i.type==="EURO"||i.type==="YEN"||i.type==="RUBLE"||i.type==="WON"||i.type==="CURRENCY_SYMBOL"||i.type==="IDENT"||i.type==="IN")){e.consume();let a=ta$1(i.value)??i.value,m=Dr(e,a);if(m!==null){n.emitOpcode(13),n.emitString(a),n.emitOpcode(13),n.emitString(m),n.emitPluginCall(q,3);return}n.emitOpcode(13),n.emitString(a),n.emitOpcode(84);}}};function Io(r={}){return {name:"solve-currency",asyncResolvers:[new b$1,vi(r.historicalRateProvider)],prefixParselets:{DOLLAR:new M,POUND:new M,EURO:new M,YEN:new M,RUBLE:new M,WON:new M,CURRENCY_SYMBOL:new M},infixParselets:{IN:new Wr},pluginFunctions:{[q]:Po(r.historicalRateProvider)}}}var Co=Io();var fe=class{constructor(e=0){this.category="Vector";this.dimension=e;}parse(e,o,t){e.consume("LPAREN");let n=0;if(e.peek()?.type!=="RPAREN")for(e.parseExpression(0,t),n++;e.match("COMMA");)e.parseExpression(0,t),n++;e.consume("RPAREN"),t.emitOpcode(152),t.emitIndex(1),t.emitIndex(this.dimension>0?this.dimension:n);}};var Yr=class{constructor(){this.category="Float";}parse(e,o,t){e.consume("LPAREN"),e.parseExpression(0,t),e.consume("RPAREN"),t.emitOpcode(152),t.emitIndex(1),t.emitIndex(1);}};var ho={name:"solve-vector",prefixParselets:{VEC2:new fe(2),VEC3:new fe(3),VEC4:new fe(4),FLOAT:new Yr}};var jr=class{constructor(){this.category="Matrix";}parse(e,o,t){let n=0,i=-1;if(e.peek()?.type==="RBRACKET")throw c$1.parsing("EMPTY_MATRIX_LITERAL","A matrix literal cannot be empty \u2014 `[]` has no valid shape.",{});for(;;){let a=0;for(e.parseExpression(0,t),a++;e.match("COMMA");)e.parseExpression(0,t),a++;if(i===-1)i=a;else if(a!==i)throw c$1.parsing("RAGGED_MATRIX_LITERAL",`Matrix literal rows must all have the same number of columns \u2014 row ${n+1} has ${a}, but a previous row has ${i}.`,{expectedCols:i,actualCols:a,row:n+1});if(n++,!e.match("SEMICOLON"))break}e.consume("RBRACKET"),t.emitOpcode(152),t.emitIndex(n),t.emitIndex(i);}};var Xr=class{constructor(){this.category="Matrix";this.bindingPower=a.Postfix;}parse(e,o,t,n){let i=this.hasTopLevelColon(e);this.parseIndexArg(e,n,i);let a=1;if(e.match("COMMA")&&(this.parseIndexArg(e,n,i),a=2),e.consume("RBRACKET"),!i){a===1?n.emitOpcode(153):n.emitOpcode(154);return}if(a!==2)throw c$1.parsing("INVALID_MATRIX_SLICE_ARITY",`Range-based matrix slicing needs exactly 2 arguments ("a[rowRange, colRange]"), got ${a}.`,{argCount:a});n.emitOpcode(155);}hasTopLevelColon(e){let o=0;for(let t=0;;t++){let n=e.peekAt(t);if(!n)return false;if(n.type==="LBRACKET"||n.type==="LPAREN")o++;else if(n.type==="RBRACKET"||n.type==="RPAREN"){if(o===0)return false;o--;}else if(n.type==="COLON"&&o===0)return true}}parseIndexArg(e,o,t){e.parseExpression(0,o);let n=false;e.match("COLON")&&(e.parseExpression(0,o),n=true),t&&(n||o.emitOpcode(3),o.emitOpcode(156));}};var xo={name:"solve-matrix",prefixParselets:{LBRACKET:new jr},infixParselets:{LBRACKET:new Xr}};function Qr(r,e){let o=r.peek(),t=r.peekAt(1);if(o&&(o.type==="IDENT"||o.type==="UNIT"||o.type==="FUNC")&&t?.type==="COMMA"){r.consume();let a=o.value,m=Zt[a.toLowerCase()];return m!==void 0?{kind:1,builtinIdx:m}:{kind:2,name:a}}let n=new d(e.pluginIndexMap);r.parseExpression(a.Lowest,n),r.setBuilder(e);let i=n.build();if(i.hasAsync)throw c$1.parsing("MAP_REDUCE_TRANSFORM_MUST_BE_SYNCHRONOUS","map/reduce transform expressions must be synchronous (no weather/stocks/currency calls).");return {kind:0,program:i}}function Qi(r){let e=r.peek(),o=r.peekAt(1);return !!e&&(e.type==="IDENT"||e.type==="UNIT")&&o?.type==="EQUALS"}function Zi(r){let e=r.peek();if(e&&(e.type==="IDENT"||e.type==="UNIT"))return r.consume(),e.value;throw c$1.parsing("MAP_REDUCE_EXPECTED_COLLECTION_NAME",`Expected a collection name (e.g. "x" in "x=[1,2,3]") but got ${e?`"${e.value}"`:"end of input"}.`)}function z(r,e){r.parseExpression(0,e),r.match("COLON")&&(r.parseExpression(0,e),e.emitOpcode(156));}function j(r,e,o,t,n){if(r.emitOpcode(e),r.emitIndex(o.kind),o.kind===0){let i=r.emitAnonymousBody(t,o.program);r.emitIndex(i);}else o.kind===1?r.emitIndex(o.builtinIdx):r.emitString(o.name);r.emitIndex(n);}var Zr=class{constructor(){this.category="MapReduce";}parse(e,o,t){e.consume("LPAREN");let n=Qr(e,t);e.consume("COMMA");let i=[];if(Qi(e))do{let a=Zi(e);e.consume("EQUALS"),z(e,t),i.push(a);}while(e.match("COMMA"));else z(e,t),i.push("x");e.consume("RPAREN"),j(t,157,n,i,i.length);}};var qr=class{constructor(){this.category="MapReduce";}parse(e,o,t){e.consume("LPAREN");let n=Qr(e,t);e.consume("COMMA"),z(e,t);let i=0;e.match("COMMA")&&(e.parseExpression(a.Lowest,t),i=1),e.consume("RPAREN"),j(t,158,n,["acc","x"],i);}};var Jr=class{constructor(){this.category="MapReduce";}parse(e,o,t){e.consume("LPAREN");let n=new d(t.pluginIndexMap);n.emitOpcode(60),n.emitString("acc"),e.parseExpression(a.Lowest,n),e.setBuilder(t),n.emitOpcode(20);let i=n.build();if(i.hasAsync)throw c$1.parsing("MAP_REDUCE_TRANSFORM_MUST_BE_SYNCHRONOUS","sum's element expression must be synchronous (no weather/stocks/currency calls).");e.consume("COMMA"),z(e,t),e.consume("RPAREN"),t.emitOpcode(10),t.emitNumber(0),j(t,158,{kind:0,program:i},["acc","x"],1);}};var et=class{constructor(){this.category="MapReduce";}parse(e,o,t){e.consume("LPAREN");let n=new d(t.pluginIndexMap);n.emitOpcode(60),n.emitString("acc"),e.parseExpression(a.Lowest,n),e.setBuilder(t),n.emitOpcode(22);let i=n.build();if(i.hasAsync)throw c$1.parsing("MAP_REDUCE_TRANSFORM_MUST_BE_SYNCHRONOUS","prod's element expression must be synchronous (no weather/stocks/currency calls).");e.consume("COMMA"),z(e,t),e.consume("RPAREN"),t.emitOpcode(10),t.emitNumber(1),j(t,158,{kind:0,program:i},["acc","x"],1);}};var ws={map:"MAP",reduce:"REDUCE",sum:"SUM_FN",prod:"PROD_FN"};function ks(r,e){return r?!!(r.type==="LINE_REF"||r.type==="IDENT"&&(/^line\d+$/i.test(r.value)||/^line$/i.test(r.value)&&e?.type==="NUMBER"&&/^\d+$/.test(e.value))):false}function qi(r=80){return {name:"mapreduce:call",priority:r,match(e,o){let t=e[o];if(!t||t.type!=="IDENT")return null;let n=t.value.toLowerCase(),i=ws[n];return !i||e[o+1]?.type!=="LPAREN"||n==="sum"&&ks(e[o+2],e[o+3])?null:{consumed:1,replacement:[new a$7(i,c(i),t.value,t.value,t.offset,0,t.line,t.col)],ruleName:"mapreduce:call"}}}}var vo={name:"solve-mapreduce",normalizerRules:[qi()],prefixParselets:{MAP:new Zr,REDUCE:new qr,SUM_FN:new Jr,PROD_FN:new et}};var rt=class{constructor(){this.category="BigInt";}parse(e,o,t){t.emitOpcode(11),t.emitString(e$2(o.value,e.getLocaleCode()));}};var So={name:"solve-bigint",prefixParselets:{BIGINT:new rt}};var H=class{constructor(e){this.opcode=e;this.category="Conditionals";this.bindingPower=a.Conditional;}parse(e,o,t,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(this.opcode);}};var de=class{constructor(e,o){this.opcode=e;this.bindingPower=o;this.category="Conditionals";}parse(e,o,t,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(this.opcode);}};var $e=class{constructor(e){this.value=e;this.category="Conditionals";}parse(e,o,t){t.emitOpcode(14),t.emitByte(this.value?1:0);}};var tt=class{constructor(){this.category="Conditionals";}parse(e,o,t){e.parseExpression(0,t),e.consume("THEN"),e.parseExpression(0,t),e.consume("ELSE"),e.parseExpression(0,t),t.emitOpcode(132);}};var Lo={name:"solve-conditionals",prefixParselets:{TRUE:new $e(true),FALSE:new $e(false),IF:new tt},infixParselets:{EQUALITY:new H(40),NEQ:new H(41),LT:new H(42),GT:new H(44),LTE:new H(43),GTE:new H(45),OR:new de(131,a.LogicalOr),LOGICAL_AND:new de(130,a.LogicalAnd),LOGICAL_OR:new de(131,a.LogicalOr)}};var Bs={percent:74,percentage:74,decimal:70,dec:70,number:70,hex:71,fraction:140,multiplier:141,x:141,sci:142,scientific:142,binary:143,bin:143,octal:144,oct:144},Ji={2:143,8:144,16:71},ot=class{constructor(){this.category="Converters";this.bindingPower=a.Conditional;}parse(e,o,t,n){let i=e.peek();if(i?.type==="PERCENT"){e.consume(),n.emitOpcode(74);return}if(!i||i.type!=="CONVERTER_NAME"&&i.type!=="IDENT"&&i.type!=="FUNC"&&i.type!=="UNIT")throw c$1.parsing("AS_CONVERTER_EXPECTED_NAME",`Expected a converter name after "as" (e.g. "as hex", "as decimal") but got ${i?`"${i.value}"`:"end of input"}`);e.consume();let a$1=i.value.toLowerCase();if(a$1==="base"){let s=e.peek(),u=s?.type==="NUMBER"?Number(s.value):NaN,c=Ji[u];if(c===void 0)throw c$1.parsing("AS_CONVERTER_UNSUPPORTED_BASE",`"as base ${s?.value??"?"}": only bases ${Object.keys(Ji).join(", ")} can be written out`);e.consume(),n.emitOpcode(c);return}let m=Bs[a$1];if(m!==void 0){m===141&&e.match("OF")&&(e.parseExpression(a.Conditional,n),n.emitOpcode(23)),n.emitOpcode(m);return}n.emitOpcode(13),n.emitString(a$1),n.emitOpcode(145);}};var ea={ten:10,hundred:100,thousand:1e3,million:1e6,billion:1e9};function ra(r,e,o){r.emitOpcode(10),r.emitNumber(e),r.emitOpcode(23),ta(r,o),r.emitOpcode(10),r.emitNumber(e),r.emitOpcode(22);}function ta(r,e){let o=e==="up"?Ms:e==="down"?Ds:Us;r.emitOpcode(51),r.emitIndex(o),r.emitIndex(1);}var Us=8,Ms=6,Ds=7,Fs=97;function bs(r){let o=(r.peek()?.text??"").toLowerCase();return o==="up"?(r.consume(),"up"):o==="down"?(r.consume(),"down"):"nearest"}var nt=class{constructor(){this.category="Converters";this.bindingPower=a.Conditional;}parse(e,o,t,n){let i=bs(e);if(e.match("TO_NEAREST")){ra(n,oa(e),i);return}ta(n,i);}},it=class{constructor(){this.category="Converters";this.bindingPower=a.Conditional;}parse(e,o,t,n){ra(n,oa(e),"nearest");}};function oa(r){let e=r.peek(),o=(e?.text??"").toLowerCase(),t=ea[o];if(t!==void 0)return r.consume(),t;if(e?.type==="NUMBER"){r.consume();let n=Number(e.value);if(Number.isFinite(n)&&n>0)return n}throw c$1.parsing("INVALID_ROUNDING_INCREMENT",`"to nearest ${e?.value??"?"}": expected a positive number or one of ${Object.keys(ea).join(", ")}`)}var at=class{constructor(){this.category="Converters";this.bindingPower=a.Conditional;}parse(e,o,t,n){let i=Number(t.value);if(!Number.isFinite(i)||i<0||i>100)throw c$1.parsing("INVALID_DECIMAL_PLACES",`"to ${t.value} dp": expected a place count between 0 and 100`);n.emitOpcode(10),n.emitNumber(i),n.emitOpcode(51),n.emitIndex(Fs),n.emitIndex(2);}};var Vs=new Set(["dp","dps","decimals","digits","digit"]),zs=new Set(["decimal"]);function na(r=66){return {name:"converters:decimal-places",priority:r,match(e,o){if(e[o]?.type!=="TO")return null;let t=e[o+1];if(t?.type!=="NUMBER")return null;let n=e[o+2];if(!n)return null;let i=(n.text??n.value??"").toLowerCase(),a=3;if(zs.has(i)){let s=(e[o+3]?.text??"").toLowerCase();if(s!=="place"&&s!=="places")return null;a=4;}else if(!Vs.has(i))return null;return {consumed:a,replacement:[b$4("DECIMAL_PLACES",t.value,e.slice(o,o+a))],ruleName:"converters:decimal-places"}}}}var Hs=new Set(["hex","bin"]);function ia(r=67){return {name:"converters:preposition",priority:r,match(e,o){let t=e[o];if(t?.type!=="IN"&&t?.type!=="TO")return null;let n=e[o+1];return n?.type==="CONVERTER_NAME"||n?.type==="FUNC"&&Hs.has(n.value.toLowerCase())?{consumed:1,replacement:[b$4("AS","as",[t])],ruleName:"converters:preposition"}:null}}}var wo={name:"solve-converters",phrases:{"to nearest":"TO_NEAREST","to the nearest":"TO_NEAREST"},infixParselets:{AS:new ot,ROUNDED:new nt,TO_NEAREST:new it,DECIMAL_PLACES:new at},normalizerRules:[na(),ia()]};var J=class{constructor(e){this.builtinIndex=e;this.category="MathPhrases";}parse(e,o,t){let n=0;for(e.parseExpression(a.Conjunction,t),n++;e.match("COMMA")||e.match("AND_CONJ");)e.parseExpression(a.Conjunction,t),n++;t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.emitIndex(n);}};function ko(r){return {category:"MathPhrases",parse(e,o,t){e.parseExpression(a.Lowest,t),t.emitOpcode(51),t.emitIndex(r),t.emitIndex(1);}}}var ma={category:"MathPhrases",parse(r,e,o){if(r.parseExpression(a.Product,o),!r.match("DIVIDE_BY")&&!r.match("SLASH"))throw c$1.parsing("REMAINDER_EXPECTED_DIVIDED_BY",'Expected "divided by" or "/", as in "remainder of 21 divided by 5"');r.parseExpression(a.Product,o),o.emitOpcode(24);}},sa={category:"MathPhrases",parse(r,e,o){if(r.parseExpression(a.Product,o),!r.match("OF"))throw c$1.parsing("ROOT_EXPECTED_OF",'Expected "of", as in "root 5 of 100"');r.parseExpression(a.Conditional,o),o.emitOpcode(2),o.emitOpcode(10),o.emitNumber(1),o.emitOpcode(2),o.emitOpcode(23),o.emitOpcode(25);}},la={category:"MathPhrases",parse(r,e,o){if(r.parseExpression(a.Conditional,o),aa(o),!r.match("LOG_BASE"))throw c$1.parsing("LOG_EXPECTED_BASE",'Expected "base", as in "log 20 base 4"');r.parseExpression(a.Conditional,o),aa(o),o.emitOpcode(23);}},Gs=5;function aa(r){r.emitOpcode(51),r.emitIndex(Gs),r.emitIndex(1);}function ua(r=69){return {name:"mathphrases:function-phrase",priority:r,match(e,o){let t=e[o];if(t?.type!=="FUNC")return null;let n=(t.value??"").toLowerCase();if(n!=="root"&&n!=="log"||e[o+1]?.type==="LPAREN")return null;if(n==="root")return {consumed:1,replacement:[b$4("NTH_ROOT","root",[t])],ruleName:"mathphrases:function-phrase"};let i=$s(e,o+1);if(i===-1)return null;let a=e.slice(o,i+1).map((m,s)=>s===0?b$4("LOG_PHRASE","log",[m]):s===i-o?b$4("LOG_BASE","base",[m]):m);return {consumed:i-o+1,replacement:a,ruleName:"mathphrases:function-phrase"}}}}function $s(r,e){for(let o=e;o<r.length&&o<e+8;o++){let t=r[o];if(t.type==="EOF"||t.type==="COMMA"||t.type==="RPAREN")return -1;if((t.text??t.value??"").toLowerCase()==="base")return o}return -1}function Ke(r){return {category:"MathPhrases",parse(e,o,t){e.parseExpression(a.Conjunction,t),e.consume("AND_CONJ"),e.parseExpression(a.Lowest,t),t.emitOpcode(51),t.emitIndex(r),t.emitIndex(2);}}}var ca={category:"MathPhrases",parse(r,e,o){r.parseExpression(a.Lowest,o),o.emitOpcode(10),o.emitNumber(2),o.emitOpcode(23);}};var pa={category:"MathPhrases",parse(r,e,o){r.parseExpression(a.Conjunction,o),r.consume("AND_CONJ"),r.parseExpression(a.Lowest,o),o.emitOpcode(20),o.emitOpcode(10),o.emitNumber(2),o.emitOpcode(23);}};var fa=Sr({category:"MathPhrases",alternatives:[{slots:[{kind:"keyword",tokenTypes:["BETWEEN"]},{kind:"expr",bindingPower:a.Product},{kind:"keyword",tokenTypes:["AND_CONJ"]},{kind:"expr"}],emit:r=>{r.emitOpcode(51),r.emitIndex(37),r.emitIndex(2);}}]});var Ks=47,mt=class{constructor(){this.category="MathPhrases";}parse(e,o,t){e.parseExpression(a.Lowest,t);let n=e.peek();if(n?.type==="BETWEEN")e.consume(),e.parseExpression(a.Product,t),e.consume("AND_CONJ"),e.parseExpression(a.Lowest,t);else if(n?.type==="FROM")e.consume(),e.parseExpression(a.Lowest,t),e.consume("TO"),e.parseExpression(a.Lowest,t);else throw c$1.parsing("CLAMP_EXPECTED_BETWEEN_OR_FROM",`Expected "between" or "from" after "clamp <value>" but got ${n?`"${n.value}"`:"end of input"}`);t.emitOpcode(51),t.emitIndex(Ks),t.emitIndex(3);}};var Ws=46,st=class{constructor(){this.category="MathPhrases";this.bindingPower=a.Conditional;}parse(e,o,t,n){e.parseExpression(this.bindingPower,n),e.consume("AS"),e.parseExpression(this.bindingPower,n),e.consume("IS_TO");let i=e.consume();if(!i||i.value.toLowerCase()!=="what")throw c$1.parsing("PROPORTION_EXPECTED_WHAT",`Expected "what" but got ${i?`"${i.value}"`:"end of input"}`);n.emitOpcode(51),n.emitIndex(Ws),n.emitIndex(3);}};var Ys=42,js=43,Xs=44,Qs=45,Zs=9,qs=10,Js=38,el=39,rl=0,tl=21,Bo={name:"solve-mathphrases",phrases:{"average of":"AVERAGE_OF","median of":"MEDIAN_OF","total of":"TOTAL_OF","count of":"COUNT_OF","larger of":"LARGER_OF","greater of":"LARGER_OF","smaller of":"SMALLER_OF","lesser of":"SMALLER_OF","half of":"HALF_OF","midpoint between":"MIDPOINT_BETWEEN","random number":"RANDOM_NUMBER","is to":"IS_TO","remainder of":"REMAINDER_OF","gcd of":"GCD_OF","lcm of":"LCM_OF","square root of":"SQUARE_ROOT_OF","cube root of":"CUBE_ROOT_OF"},prefixParselets:{AVERAGE_OF:new J(Ys),MEDIAN_OF:new J(js),TOTAL_OF:new J(Xs),COUNT_OF:new J(Qs),LARGER_OF:Ke(qs),SMALLER_OF:Ke(Zs),HALF_OF:ca,MIDPOINT_BETWEEN:pa,RANDOM_NUMBER:fa,REMAINDER_OF:ma,NTH_ROOT:sa,LOG_PHRASE:la,GCD_OF:Ke(Js),LCM_OF:Ke(el),SQUARE_ROOT_OF:ko(rl),CUBE_ROOT_OF:ko(tl),CLAMP:new mt},infixParselets:{IS_TO:new st},normalizerRules:[ua()]};var da={annually:1,yearly:1,"semi-annually":2,quarterly:4,monthly:12,fortnightly:26,weekly:52,daily:365};function Uo(r){if(!r.match("COMPOUNDING"))return 1;let e=r.peek(),o=(e?.text??e?.value??"").toLowerCase(),t=da[o];if(t===void 0)throw c$1.parsing("UNKNOWN_COMPOUNDING_INTERVAL",`compounding ${o||"?"}: expected one of ${Object.keys(da).join(", ")}`);return r.consume(),t}var We=class{constructor(e,o){this.annualIndex=e;this.intervalIndex=o;this.category="Finance";this.bindingPower=a.Conditional;}parse(e,o,t,n){e.parseExpression(a.Conditional,n),e.match("RATE_AT")||e.consume("AT"),e.parseExpression(a.Conditional,n);let i=Uo(e);if(n.emitOpcode(2),i===1){n.emitOpcode(51),n.emitIndex(this.annualIndex),n.emitIndex(3);return}n.emitOpcode(10),n.emitNumber(i),n.emitOpcode(51),n.emitIndex(this.intervalIndex),n.emitIndex(4);}},lt=class{constructor(e){this.builtinIndex=e;this.category="Finance";}parse(e,o,t){e.parseExpression(a.Conditional,t),!e.match("AFTER")&&!e.match("OVER")&&!e.match("IN")&&e.consume("AFTER"),e.parseExpression(a.Conditional,t),e.match("RATE_AT")||e.consume("AT"),e.parseExpression(a.Conditional,t),t.emitOpcode(2),t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.emitIndex(3);}},ut=class{constructor(e){this.builtinIndex=e;this.category="Finance";this.bindingPower=a.Conditional;}parse(e,o,t,n){e.parseExpression(a.Conditional,n),e.consume("RETURNED"),n.emitOpcode(51),n.emitIndex(this.builtinIndex),n.emitIndex(2);}},ct=class{constructor(e){this.builtinIndex=e;this.category="Finance";}parse(e,o,t){e.parseExpression(a.Conditional,t),e.consume("INVESTED"),e.parseExpression(a.Conditional,t),e.consume("RETURNED"),!e.match("AFTER")&&!e.match("OVER")&&!e.match("IN")&&e.consume("AFTER"),e.parseExpression(a.Conditional,t),t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.emitIndex(3);}};function pt(r,e,o){return Na(r,o)?(r.parseExpression(a.Lowest,e),Ea(r),r.parseExpression(a.Lowest,e),{swap:true}):(Ea(r),r.parseExpression(a.Lowest,e),ol(r,o),r.parseExpression(a.Lowest,e),{swap:false})}function Na(r,e){for(let o of e)if(r.match(o))return true;return false}function ol(r,e){Na(r,e)||r.consume(e[0]);}function Ea(r){r.match("RATE_AT")||r.consume("AT");}var Ye=class{constructor(e,o){this.builtinIndex=e;this.intervalIndex=o;this.category="Finance";}parse(e,o,t){e.parseExpression(a.Conditional,t);let{swap:n}=pt(e,t,["AFTER","FOR_DURATION","OVER"]),i=Uo(e);if(n&&t.emitOpcode(2),i===1){t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.emitIndex(3);return}t.emitOpcode(10),t.emitNumber(i),t.emitOpcode(51),t.emitIndex(this.intervalIndex),t.emitIndex(4);}};var B=class{constructor(e,o){this.builtinIndex=e;this.periodsPerYear=o;this.category="Finance";}parse(e,o,t){e.parseExpression(a.Lowest,t);let{swap:n}=pt(e,t,["OVER"]);n&&t.emitOpcode(2),t.emitOpcode(10),t.emitNumber(this.periodsPerYear),t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.emitIndex(4);}};var ft=class{constructor(e){this.builtinIndex=e;this.category="Finance";}parse(e,o,t){e.parseExpression(a.Lowest,t),e.consume("BETWEEN"),e.parseExpression(a.Lowest,t),e.match("PEOPLE"),t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.emitIndex(2);}},dt=class{constructor(e){this.builtinIndex=e;this.category="Finance";this.bindingPower=a.Conditional;}parse(e,o,t,n){e.parseExpression(a.Conditional,n),e.consume("WAYS"),n.emitOpcode(51),n.emitIndex(this.builtinIndex),n.emitIndex(2);}};var Ta={daily:{perYear:365,unit:"days"},weekly:{perYear:52,unit:"weeks"},monthly:{perYear:12,unit:"months"},yearly:{perYear:1,unit:"years"},annually:{perYear:1,unit:"years"}};function nl(r){let e=r.peek(),o=(e?.text??e?.value??"").toLowerCase(),t=Ta[o];if(t===void 0)throw c$1.parsing("UNKNOWN_SAVINGS_PERIOD",`savings goal: expected a contribution period, one of ${Object.keys(Ta).join(", ")}, not "${o||"?"}".`);return r.consume(),t}var Et=class{constructor(e){this.builtinIndex=e;this.category="Finance";}parse(e,o,t){e.parseExpression(a.Conditional,t),e.match("RATE_AT")||e.consume("AT"),e.parseExpression(a.Product,t),e.match("STAR");let n=nl(e);t.emitOpcode(10),t.emitNumber(n.perYear),e.match("RATE_AT")||e.match("AT")?e.parseExpression(a.Conditional,t):(t.emitOpcode(10),t.emitNumber(0)),t.emitOpcode(13),t.emitString(n.unit),t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.emitIndex(5);}},Nt=class{constructor(e){this.builtinIndex=e;this.category="Finance";}parse(e,o,t){e.parseExpression(a.Product,t),e.consume("IN"),e.parseExpression(a.Conditional,t),e.match("RATE_AT")||e.match("AT")?e.parseExpression(a.Conditional,t):(t.emitOpcode(10),t.emitNumber(0)),t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.emitIndex(3);}};var Ee=class{constructor(e){this.builtinIndex=e;this.category="Finance";}parse(e,o,t){e.parseExpression(a.Lowest,t),e.consume("RATE_AT"),e.parseExpression(a.Lowest,t),t.emitOpcode(51),t.emitIndex(this.builtinIndex),t.emitIndex(2);}};var il=60;function al(r){for(let e=0;;e++){let o=r.peekAt(e);if(!o)return false;if(o.type==="FROM"||o.type==="WORTH_IN")return true}}var je=class{constructor(e){this.variant=e;this.category="Finance";}parse(e,o,t){if(!al(e)){e.parseExpression(a.Lowest,t);return}if(e.parseExpression(a.Product,t),this.variant==="what-was"){e.consume("WORTH_IN"),e.parseExpression(a.Lowest,t),t.emitPluginCall("inflationToYearFromPresent",2);return}let n=e.peek();if(n?.type==="FROM"){e.consume(),e.parseExpression(a.Lowest,t),t.emitPluginCall("inflationFromYearToPresent",2);return}if(n?.type==="IN"){e.consume(),e.parseExpression(a.Lowest,t),e.consume("WORTH_IN"),e.parseExpression(a.Lowest,t),t.emitOpcode(51),t.emitIndex(il),t.emitIndex(3);return}let i=n?n.type:"end of input";throw c$1.parsing("INFLATION_EXPECTED_FROM_OR_IN",`Expected "from <year>" or "in <year> worth in <year>" after "what is <amount>", got ${i}`)}};var Tt=class{constructor(){this.category="Finance";}parse(e,o,t){e.parseExpression(a.Product,t),e.consume("IN"),e.parseExpression(a.Lowest,t),e.consume("ASSUMING"),e.parseExpression(a.Lowest,t);let n=e.peek();if((n&&n.type==="IDENT"?n.value.toLowerCase():void 0)!=="inflation"){let a=n?n.value:"end of input";throw c$1.parsing("INFLATION_EXPECTED_INFLATION_WORD",`Expected the word "inflation" after "assuming <rate>%", got "${a}"`)}e.consume(),t.emitPluginCall("inflationFutureValue",3);}};var yt=class{constructor(){this.category="Finance";this.bindingPower=35;}parse(e,o,t,n){let i=Number(t.value);n.emitOpcode(10),n.emitNumber(i),n.emitPluginCall("inflationToYearFromPresent",2);}};function ya(r,e){return N(r,`Year ${e} is outside the bundled CPI table's range (${z$3}-${A$2})`)}function ga(r){let e=r[0],o=r[1].toNumber(),t=new Date().getFullYear(),n$1=B$2(e.toNumber(),o,t);return n$1===void 0?ya("INFLATION_YEAR_OUT_OF_RANGE",o):e.type===6?u$1(n$1,e.unit):n(n$1)}function Pa(r){let e=r[0],o=new Date().getFullYear(),t=r[1].toNumber(),n$1=B$2(e.toNumber(),o,t);return n$1===void 0?ya("INFLATION_YEAR_OUT_OF_RANGE",t):e.type===6?u$1(n$1,e.unit):n(n$1)}function _a(r){let e=r[0],o=r[1].toNumber(),t=r[2].toNumber(),n$1=o-new Date().getFullYear();if(1+t<=0)return N("INVALID_RATE",`inflationFutureValue: rate ${t} makes (1 + rate) non-positive`);let a=e.toNumber()/Math.pow(1+t,n$1);return e.type===6?u$1(a,e.unit):n(a)}function Oa(r=70){return {name:"finance:in-year-dollars",priority:r,match(e,o){let t=e[o],n=e[o+1],i=e[o+2];if(t.type!=="IN"||n?.type!=="NUMBER"||i?.type!=="IDENT"&&i?.type!=="UNIT")return null;let a=i.value.toLowerCase();return a!=="dollars"&&a!=="dollar"?null:{consumed:3,replacement:[b$4("IN_YEAR_DOLLARS",n.value,e.slice(o,o+3))],ruleName:"finance:in-year-dollars"}}}}var ml={RECURRING_INTERVAL_NOT_POSITIVE:"RECURRING_INTERVAL_NOT_POSITIVE"},sl={daily:365,weekly:52,monthly:12,yearly:1,annually:1},ll={day:365,days:365,week:52,weeks:52,month:12,months:12,year:1,years:1},ul=new Set(["a","an"]),cl=new Set(["NUMBER","FLOAT","HEX","BIGINT","RPAREN","RBRACKET","IDENT","PERCENT","STRING"]);function Xe(r){return r===void 0?"":(r.text??r.value??"").toLowerCase()}function Ra(r){if(!(r===void 0||r.type!=="UNIT"))return ll[Xe(r)]}function pl(r,e){let o=r[e];if(o===void 0)return null;if(o.type==="IDENT"){let t=sl[Xe(o)];if(t!==void 0)return {perYear:t,consumed:1};if(Xe(o)==="every"){let n=r[e+1];if(n?.type!=="NUMBER")return null;let i=Ra(r[e+2]);if(i===void 0)return null;let a=Number((n.value??"").replace(/,/g,""));if(!(a>0))throw c$1.parsing({code:ml.RECURRING_INTERVAL_NOT_POSITIVE,message:`A recurring interval must be a positive number, not "${n.value}".`,expected:"a positive interval, e.g. every 2 weeks",found:`every ${n.value} ${Xe(r[e+2])}`});return {perYear:i/a,consumed:3}}}return null}function fl(r,e){let o=r[e];if(o===void 0)return null;let t,n;if(o.type==="NUMBER")t=Number((o.value??"").replace(/,/g,"")),n=e+1;else if(o.type==="IDENT"&&ul.has(Xe(o)))t=1,n=e+1;else return null;let i=Ra(r[n]);return i===void 0||!Number.isFinite(t)||t<0?null:{years:t/i,consumed:n-e+1}}function dl(r,e){let o=r*e,t=Math.round(o);return Math.abs(o-t)<1e-9?t:Math.floor(o)}function Aa(r=78){return {name:"finance:recurring-schedule",priority:r,match(e,o){let t=e[o];if(t===void 0||!cl.has(t.type))return null;let n=pl(e,o+1);if(n===null)return null;let i=o+1+n.consumed;if(e[i]?.type!=="FOR_DURATION")return null;let a=fl(e,i+1);if(a===null)return null;let m=dl(n.perYear,a.years),s=i+1+a.consumed-o,u=e.slice(o,o+s);return {replacement:[t,b$4("STAR","*",u),b$4("NUMBER",String(m),u)],consumed:s,ruleName:"finance:recurring-schedule"}}}}function gt(r){return r===void 0?"":(r.text??r.value??"").toLowerCase()}var Ia=new Set(["NUMBER","FLOAT","HEX","BIGINT","RPAREN","RBRACKET","IDENT","PERCENT","STRING"]),Ca=new Set(["NUMBER","FLOAT"]);function ha(r=77){return {name:"finance:bill-split",priority:r,match(e,o){let t=e[o];if(t===void 0)return null;if(Ia.has(t.type)){let p=e[o+1],E=e[o+2],T=e[o+3];if(p?.type==="IDENT"&&gt(p)==="split"&&E!==void 0&&Ca.has(E.type)&&T?.type==="IDENT"&&gt(T)==="ways")return {consumed:4,replacement:[t,b$4("SPLIT_WAYS","split",[p]),E,b$4("WAYS","ways",[T])],ruleName:"finance:bill-split"}}if(t.type!=="IDENT"||gt(t)!=="split")return null;let n=e[o-1];if(n!==void 0&&Ia.has(n.type))return null;let i=-1;for(let p=o+1;p<e.length;p++)if(e[p].type==="BETWEEN"){i=p;break}if(i===-1)return null;let a=e[i+1];if(a===void 0||!Ca.has(a.type))return null;let m=i+2,s=e[m]?.type==="IDENT"&&gt(e[m])==="people",u=s?m:i+1,c=[b$4("SPLIT","split",[t]),...e.slice(o+1,i+2)];return s&&c.push(b$4("PEOPLE","people",[e[m]])),{consumed:u-o+1,replacement:c,ruleName:"finance:bill-split"}}}}var Mo=51,El=52,Pt=55,_t=56,Do=80,Nl=81,Tl=82,yl=83,gl=84,Pl=59,_l=85,Ol=86,xa=98,Rl=99,Al=100,Fo={name:"solve-finance",phrases:{"compound interest on":"COMPOUND_INTEREST_ON","interest on":"INTEREST_ON","daily repayment on":"DAILY_REPAYMENT_ON","monthly repayment on":"MONTHLY_REPAYMENT_ON","annual repayment on":"ANNUAL_REPAYMENT_ON","total repayment on":"TOTAL_REPAYMENT_ON","daily interest on":"DAILY_LOAN_INTEREST_ON","monthly interest on":"MONTHLY_LOAN_INTEREST_ON","annual interest on":"ANNUAL_LOAN_INTEREST_ON","total interest on":"TOTAL_LOAN_INTEREST_ON","tax on":"TAX_ON","tax off":"TAX_OFF","tax in":"TAX_IN_PHRASE","tax of":"TAX_IN_PHRASE","tax from":"TAX_IN_PHRASE","vat in":"TAX_IN_PHRASE","vat of":"TAX_IN_PHRASE","vat from":"TAX_IN_PHRASE","vat on":"TAX_ON","vat off":"TAX_OFF","what is":"WHAT_IS","what was":"WHAT_WAS","present value of":"PRESENT_VALUE_OF","annual return on":"ANNUAL_RETURN_ON","value of":"VALUE_OF","worth in":"WORTH_IN","how long to save":"SAVINGS_HOW_LONG","how much per month to save":"SAVINGS_HOW_MUCH","how much per month to reach":"SAVINGS_HOW_MUCH",assuming:"ASSUMING"},prefixParselets:{PRESENT_VALUE_OF:new lt(Tl),ANNUAL_RETURN_ON:new ct(gl),COMPOUND_INTEREST_ON:new Ye(Mo,Do),INTEREST_ON:new Ye(El,Nl),DAILY_REPAYMENT_ON:new B(Pt,365),MONTHLY_REPAYMENT_ON:new B(Pt,12),ANNUAL_REPAYMENT_ON:new B(Pt,1),TOTAL_REPAYMENT_ON:new B(Pt,0),DAILY_LOAN_INTEREST_ON:new B(_t,365),MONTHLY_LOAN_INTEREST_ON:new B(_t,12),ANNUAL_LOAN_INTEREST_ON:new B(_t,1),TOTAL_LOAN_INTEREST_ON:new B(_t,0),TAX_ON:new Ee(Ol),TAX_OFF:new Ee(Pl),TAX_IN_PHRASE:new Ee(_l),SPLIT:new ft(xa),WHAT_IS:new je("what-is"),WHAT_WAS:new je("what-was"),VALUE_OF:new Tt,SAVINGS_HOW_LONG:new Et(Al),SAVINGS_HOW_MUCH:new Nt(Rl)},infixParselets:{AFTER:new We(Mo,Do),FOR_DURATION:new We(Mo,Do),INVESTED:new ut(yl),IN_YEAR_DOLLARS:new yt,SPLIT_WAYS:new dt(xa)},normalizerRules:[Oa(),Aa(),ha()],pluginFunctions:{inflationFromYearToPresent:ga,inflationToYearFromPresent:Pa,inflationFutureValue:_a}};function Il(r){return (e,o)=>N(`${r.toUpperCase()}_QUERY_FAILED`,`Failed to resolve "${e}": ${o instanceof Error?o.message:String(o)}`)}function ee(r){let e=r.staleTimeMs??3e5,o=r.timeoutMs??1e4,t=r.failureCooldownMs??3e4,n=r.onError??Il(r.namespace),i=u=>[r.namespace,u];async function a(u,c,p){let{signal:E,cleanup:T}=a$3(c,o,`${r.namespace} query`);try{return await r.fetchQuery(u,E)}catch(y){let O=n(u,y);return setTimeout(()=>{p.getQueryData(i(u))===O&&p.removeQueries({queryKey:i(u),exact:true});},t).unref?.(),O}finally{T();}}return {resolver:{namespace:r.namespace,preflight(u,c,p,E,T){let{opcodes:y,strings:O}=c,L=y.length,x=0;for(;x<L;){if(y[x]===50&&x+2<L){let $=y[x+1],bt=y[x+2];if($===r.pluginFunctionIndex&&bt>=1&&x>=2&&y[x-2]===13){let ie=O[y[x-1]],qe=i(ie);if(T.getQueryData(qe)===void 0){let vm=T.fetchQuery({queryKey:qe,queryFn:({signal:zt})=>a(ie,zt,T),staleTime:e}),Vt={queryKey:qe.join(":"),resolver:vm,packageId:p,signal:E,metadata:{query:ie}};return r.refetchIntervalMs!==void 0&&(Vt.refetchIntervalMs=r.refetchIntervalMs,Vt.refetch=()=>T.fetchQuery({queryKey:qe,queryFn:({signal:zt})=>a(ie,zt,T),staleTime:0})),Vt}}x+=3;continue}x=a$2(y,x);}return null},destroy(){}},pluginFunction:u=>{let c=u[0]?.value,p=b$3()?.getQueryData(i(c));return p!==void 0?p:N(`${r.namespace.toUpperCase()}_NOT_PREFLIGHTED`,`No cached result for "${c}"`)}}}function Cl(r,e){let o=[];for(;r.peek()?.type==="IDENT";)o.push(r.consume().value);if(o.length===0)throw c$1.parsing("WEATHER_EXPECTED_CITY",`Expected a city name after "${e}" (e.g. "${e} London")`);return o.join(" ")}function Ne(r,e){return {category:"Weather",parse(o,t,n){let i=Cl(o,t.value);n.emitOpcode(13),n.emitString(`${r}:${i}`),n.emitPluginCall(e,1);}}}var hl={0:"clear sky",1:"mainly clear",2:"partly cloudy",3:"overcast",45:"fog",48:"depositing rime fog",51:"light drizzle",53:"moderate drizzle",55:"dense drizzle",56:"light freezing drizzle",57:"dense freezing drizzle",61:"slight rain",63:"moderate rain",65:"heavy rain",66:"light freezing rain",67:"heavy freezing rain",71:"slight snow fall",73:"moderate snow fall",75:"heavy snow fall",77:"snow grains",80:"slight rain showers",81:"moderate rain showers",82:"violent rain showers",85:"slight snow showers",86:"heavy snow showers",95:"thunderstorm",96:"thunderstorm with slight hail",99:"thunderstorm with heavy hail"};function va(r){return hl[r]??`weather code ${r}`}var Te={GEOCODING_API_ERROR:"WEATHER_GEOCODING_API_ERROR",CITY_NOT_FOUND:"WEATHER_CITY_NOT_FOUND",FORECAST_API_ERROR:"WEATHER_FORECAST_API_ERROR",FORECAST_RESPONSE_MALFORMED:"WEATHER_FORECAST_RESPONSE_MALFORMED",UNKNOWN_QUERY_KIND:"WEATHER_UNKNOWN_QUERY_KIND"},xl="https://geocoding-api.open-meteo.com/v1/search",vl="https://api.open-meteo.com/v1/forecast",Sl=1e4;async function Ll(r,e){let o=`${xl}?name=${encodeURIComponent(r)}&count=1&language=en&format=json`,t=await fetch(o,{signal:e});if(!t.ok)throw c$1.external(Te.GEOCODING_API_ERROR,`Open-Meteo geocoding API returned ${t.status} for "${r}"`,{city:r,status:t.status});let i=(await t.json())?.results?.[0];if(!i)throw c$1.validation(Te.CITY_NOT_FOUND,`No location found for "${r}"`,{city:r});return {latitude:i.latitude,longitude:i.longitude,name:i.name}}async function wl(r,e,o){let t=new URLSearchParams({latitude:String(r),longitude:String(e),current:"temperature_2m,apparent_temperature,weather_code",daily:"temperature_2m_max,temperature_2m_min",timezone:"auto",forecast_days:"1"}),n=await fetch(`${vl}?${t.toString()}`,{signal:o});if(!n.ok)throw c$1.external(Te.FORECAST_API_ERROR,`Open-Meteo forecast API returned ${n.status}`,{status:n.status});let i=await n.json(),a=i?.current,m=i?.daily;if(!a||!m)throw c$1.external(Te.FORECAST_RESPONSE_MALFORMED,"Open-Meteo forecast response missing current/daily blocks");return {weatherCode:a.weather_code,temperature:a.temperature_2m,apparentTemperature:a.apparent_temperature,high:m.temperature_2m_max?.[0],low:m.temperature_2m_min?.[0]}}var Ot=new Map,kl=6e4;function Sa(r,e){let o=r.trim().toLowerCase(),t=Date.now(),n=Ot.get(o);if(n&&n.expiresAt>t)return n.promise;let{signal:i,cleanup:a}=a$3(e,Sl,"Open-Meteo weather query"),m=(async()=>{try{let s=await Ll(r,i),u=await wl(s.latitude,s.longitude,i);return {resolvedName:s.name,weatherCode:u.weatherCode,description:va(u.weatherCode),temperature:u.temperature,apparentTemperature:u.apparentTemperature,high:u.high,low:u.low}}finally{a();}})();return Ot.set(o,{promise:m,expiresAt:t+kl}),m.catch(()=>{Ot.get(o)?.promise===m&&Ot.delete(o);}),m}var La="solve-weather",re="weather",Bl=F(`${La}:${re}`),{resolver:Ul,pluginFunction:Ml}=ee({namespace:"weather",pluginFunctionIndex:Bl,staleTimeMs:600*1e3,fetchQuery:async(r,e)=>{let o=r.indexOf(":"),t$1=o===-1?r:r.slice(0,o),n=o===-1?"":r.slice(o+1),i=await Sa(n,e);switch(t$1){case "current":return t(`${Math.round(i.temperature)}\xB0C, ${i.description}`);case "temperature":return u$1(i.temperature,"C");case "feelslike":return u$1(i.apparentTemperature,"C");case "high":return u$1(i.high,"C");case "low":return u$1(i.low,"C");default:throw c$1.internal(Te.UNKNOWN_QUERY_KIND,`Unknown weather query kind "${t$1}"`,{kind:t$1})}}}),bo={name:La,phrases:{"weather in":"WEATHER_IN","temperature in":"TEMPERATURE_IN","feels like in":"FEELS_LIKE_IN","high in":"HIGH_IN","low in":"LOW_IN"},prefixParselets:{WEATHER_IN:Ne("current",re),TEMPERATURE_IN:Ne("temperature",re),FEELS_LIKE_IN:Ne("feelslike",re),HIGH_IN:Ne("high",re),LOW_IN:Ne("low",re)},pluginFunctions:{[re]:Ml},asyncResolvers:[Ul]};var Rt={jan:0,january:0,feb:1,february:1,mar:2,march:2,apr:3,april:3,may:4,jun:5,june:5,jul:6,july:6,aug:7,august:7,sep:8,sept:8,september:8,oct:9,october:9,nov:10,november:10,dec:11,december:11};function It(r){return r<10?`0${r}`:String(r)}function Qe(r,e,o,t){let n=new Date(r,e,o);if(n.getFullYear()!==r||n.getMonth()!==e||n.getDate()!==o)throw c$1.parsing("STOCKS_INVALID_DATE",`"${t}" is not a valid calendar date`);return {isoDate:`${r}-${It(e+1)}-${It(o)}`,raw:t}}function At(r,e){if(!/^\d{4}$/.test(r))throw c$1.parsing("STOCKS_INVALID_DATE",`Expected a 4-digit year in "${e}", got "${r}"`);return parseInt(r,10)}function wa(r){let e=r.peek();if(!e)return null;if(e.type==="DATETIME_LITERAL"){r.consume();let o=new Date(Number(e.value));return Number.isNaN(o.getTime())?null:{isoDate:`${o.getFullYear()}-${It(o.getMonth()+1)}-${It(o.getDate())}`,raw:e.text??e.value}}if(e.type==="NUMBER"){let o=r.consume(),t=r.peek();if(t&&(t.type==="SLASH"||t.type==="MINUS")){let i=t.type;r.consume();let a=r.consume("NUMBER");r.consume(i);let m=r.consume("NUMBER"),s=`${o.value}${i==="SLASH"?"/":"-"}${a.value}${i==="SLASH"?"/":"-"}${m.value}`;if(i==="SLASH"){let u=parseInt(o.value,10),c=parseInt(a.value,10),p=At(m.value,s);return Qe(p,u-1,c,s)}else {if(/^\d{4}$/.test(o.value)){let E=parseInt(o.value,10),T=parseInt(a.value,10),y=parseInt(m.value,10);return Qe(E,T-1,y,s)}let u=parseInt(o.value,10),c=parseInt(a.value,10),p=At(m.value,s);return Qe(p,u-1,c,s)}}let n=r.peek();if(n&&n.type==="IDENT"&&Rt[n.value.toLowerCase()]!==void 0){let i=Rt[n.value.toLowerCase()];r.consume(),r.peek()?.type==="COMMA"&&r.consume();let a=r.consume("NUMBER"),m=`${o.value} ${n.value} ${a.value}`,s=At(a.value,m);return Qe(s,i,parseInt(o.value,10),m)}throw c$1.parsing("STOCKS_INVALID_DATE",`Expected a date after "on" (e.g. "April 12, 2005" or "4/12/2005"), got "${o.value}"`)}if(e.type==="IDENT"&&Rt[e.value.toLowerCase()]!==void 0){let o=Rt[e.value.toLowerCase()];r.consume();let t=r.consume("NUMBER");r.peek()?.type==="COMMA"&&r.consume();let n=r.consume("NUMBER"),i=`${e.value} ${t.value}, ${n.value}`,a=At(n.value,i);return Qe(a,o,parseInt(t.value,10),i)}return null}var ka=new Set(["AAPL","MSFT","GOOGL","GOOG","AMZN","META","NVDA","TSLA","NFLX","ADBE","CRM","ORCL","IBM","INTC","AMD","CSCO","PYPL","UBER","ABNB","SPOT","SHOP","SQ","COIN","PLTR","SNOW","ZM","JPM","V","MA","BAC","WFC","GS","MS","AXP","WMT","COST","HD","NKE","SBUX","MCD","KO","PEP","DIS","TGT","BA","GE","F","GM","XOM","CVX","PFE","JNJ","UNH","MRNA","TSM","ASML","BABA"]);var ye="STOCK_TICKER",Dl=c(ye);function Ba(){return {name:"stocks:bare-ticker",priority:20,match(r,e){let o=r[e];return !o||o.type!=="IDENT"||!ka.has(o.value)||e>0&&r[e-1].type==="COLON"?null:{consumed:1,replacement:[new a$7(ye,Dl,o.value,o.value,o.offset,0,o.line,o.col)],ruleName:"stocks:bare-ticker"}}}}function Fl(r){let e=r.peek();if(!e||e.type!=="IDENT")return null;let o=e.value.toLowerCase(),t="close";if(o==="close"||o==="volume"){t=o,r.consume();let i=r.peek();if(!i||i.type!=="IDENT"||i.value.toLowerCase()!=="on")throw c$1.parsing("STOCKS_EXPECTED_ON",`Expected "on <date>" after "${o}" (e.g. "AAPL ${o} on April 12, 2005")`);r.consume();}else if(o==="on")r.consume();else return null;let n=wa(r);if(!n)throw c$1.parsing("STOCKS_EXPECTED_DATE",'Expected a date after "on" (e.g. "April 12, 2005" or "4/12/2005")');return {field:t,date:n}}function Ua(r,e,o,t,n){r.emitOpcode(13),o?(r.emitString(`${o.field}:${e}:${o.date.isoDate}`),r.emitPluginCall(n,1)):(r.emitString(e),r.emitPluginCall(t,1));}function Ma(r,e,o,t,n){let i=false;r.peek()?.type==="STAR"&&(r.consume(),i=true);let a$1=Fl(r);if(i&&!a$1){Ua(e,o,null,t,n),r.parseExpression(a.Product,e),e.emitOpcode(22);return}Ua(e,o,a$1,t,n);}function Da(r,e){return {category:"Stocks",parse(o,t,n){o.consume("LPAREN");let i=o.consume(),a;if(i.type==="STRING")a=a$8(i.value).toUpperCase();else if(i.type==="IDENT"||i.type===ye)a=i.value.toUpperCase();else throw c$1.parsing("STOCKS_INVALID_TICKER",`Expected a ticker symbol inside stock(...), got "${i.value}" (${i.type})`);o.consume("RPAREN"),Ma(o,n,a,r,e);}}}function Fa(r,e){return {category:"Stocks",parse(o,t,n){let i=t.value.toUpperCase();Ma(o,n,i,r,e);}}}var Vo="solve-stocks",Ct="stock",ht="stockhistorical";function ba(r={}){function e(m){return N("STOCKS_NOT_CONFIGURED",`Stock data provider not configured. Supply ${m} via createStocksPackage({ ... }); see the StocksPackage doc comment.`)}let{resolver:o,pluginFunction:t}=ee({namespace:"stocks-current",pluginFunctionIndex:F(`${Vo}:${Ct}`),staleTimeMs:r.staleTimeMs??6e4,refetchIntervalMs:r.refetchIntervalMs,fetchQuery:async(m,s)=>{if(!r.fetchQuote)return e("fetchQuote");let u=await r.fetchQuote(m,s);return u$1(u.price,u.currency??"USD")}}),{resolver:n$1,pluginFunction:i}=ee({namespace:"stocks-historical",pluginFunctionIndex:F(`${Vo}:${ht}`),staleTimeMs:r.historicalStaleTimeMs??720*60*60*1e3,fetchQuery:async(m,s)=>{let[u,c,p]=m.split(":");if(!r.fetchHistoricalQuote)return e("fetchHistoricalQuote");let E=await r.fetchHistoricalQuote(c,p,s);return u==="volume"?n(E.volume??0):u$1(E.close,E.currency??"USD")}});return {name:Vo,lexerVocabulary:{keywords:{stock:"STOCK_FN"}},prefixParselets:{STOCK_FN:Da(Ct,ht),...r.enableBareTickerRecognition?{[ye]:Fa(Ct,ht)}:{}},normalizerRules:r.enableBareTickerRecognition?[Ba()]:[],pluginFunctions:{[Ct]:t,[ht]:i},asyncResolvers:[o,n$1]}}function Va(r){return {category:"Knowledge",parse(e,o,t){t.emitOpcode(13),t.emitString(o.value),t.emitPluginCall(r,1);}}}function za(r={}){let e="solve-knowledge",o="knowledge",t$1=F(`${e}:${o}`),{resolver:n,pluginFunction:i}=ee({namespace:"knowledge",pluginFunctionIndex:t$1,staleTimeMs:r.staleTimeMs??300*1e3,fetchQuery:async(a,m)=>{if(!r.answerQuery)return N("KNOWLEDGE_NOT_CONFIGURED","Knowledge answer provider not configured. Supply answerQuery via createKnowledgePackage({ ... }); see the KnowledgePackage doc comment.");let s=await r.answerQuery(a,m);return t(s)}});return {name:e,lexerVocabulary:{rawLinePatterns:[{pattern:/^(?:search|ask|google)\s*:\s*(.+)$/i,tokenType:"KNOWLEDGE_QUERY"},{pattern:/^(.+?)=\s*\?\s*$/,tokenType:"KNOWLEDGE_QUERY"}]},prefixParselets:{KNOWLEDGE_QUERY:Va(o)},pluginFunctions:{[o]:i},asyncResolvers:[n]}}var xt=class{constructor(){this.category="Lines";}parse(e,o,t){t.emitPluginCall("prev",0);}};var vt=class{constructor(){this.category="Lines";}parse(e,o,t){let n=parseInt(o.value,10);t.emitOpcode(10),t.emitNumber(n),t.emitPluginCall("lineRef",1);}};var Ze=class{constructor(e){this.isAverage=e;this.category="Lines";}parse(e,o,t){e.consume("LPAREN");let n=e.consume("LINE_REF");e.consume("COLON");let i=e.consume("LINE_REF");e.consume("RPAREN");let a=parseInt(n.value,10),m=parseInt(i.value,10);t.emitOpcode(10),t.emitNumber(a),t.emitOpcode(10),t.emitNumber(m),t.emitPluginCall(this.isAverage?"averageRange":"sumRange",2);}};var ge=class{constructor(e){this.isAverage=e;this.category="Lines";}parse(e,o,t){t.emitPluginCall(this.isAverage?"averageAbove":"totalAbove",0);}};var bl=c("LINE_REF"),Vl=c("SUM_RANGE_CALL"),zl=c("AVERAGE_RANGE_CALL");function Ga(){return {name:"lines:line-ref",priority:80,match(r,e){if(e>0&&r[e-1].type==="COLON"&&!(e>1&&r[e-2].type==="LINE_REF"))return null;let o=r[e];if(!o)return null;if(o.type==="IDENT"){let t=/^line(\d+)$/i.exec(o.value);if(t)return {consumed:1,replacement:[Ha(t[1],o)],ruleName:"lines:line-ref"}}if(o.type==="IDENT"&&/^line$/i.test(o.value)){let t=r[e+1];if(t&&t.type==="NUMBER"&&/^\d+$/.test(t.value))return {consumed:2,replacement:[Ha(t.value,o)],ruleName:"lines:line-ref"}}return null}}}function Ha(r,e){return new a$7("LINE_REF",bl,r,r,e.offset,0,e.line,e.col)}function $a(){return {name:"lines:range-call",priority:80,match(r,e){let o=r[e];if(!o||o.type!=="IDENT")return null;let t=o.value.toLowerCase();if(t!=="sum"&&t!=="total"&&t!=="average"||r[e+1]?.type!=="LPAREN")return null;let n=t==="average"?"AVERAGE_RANGE_CALL":"SUM_RANGE_CALL",i=t==="average"?zl:Vl;return {consumed:1,replacement:[new a$7(n,i,o.value,o.value,o.offset,0,o.line,o.col)],ruleName:"lines:range-call"}}}}function St(r,e){return r===void 0?N("LINE_NOT_YET_EVALUATED",`Line ${e} has not been evaluated yet (forward reference, or out of range)`):r.type===12?N("LINE_RESULT_PENDING",`Line ${e}'s result is still resolving`):r.type===13?N("LINE_RESULT_ERROR",`Line ${e} has an error`):null}function Pe(r){return r?.getLineResult?null:N("LINE_REF_NO_DOCUMENT","Cross-line references require a real document \u2014 not available outside one (e.g. evaluateExpression()'s single-expression path)")}function Ka(r,e){let o=Pe(e);if(o)return o;let t=e.lineIndex-1,n=e.getLineResult(t);return St(n,t)??n}function Wa(r,e){let o=Pe(e);if(o)return o;let t=r[0].toNumber(),n=e.getLineResult(t);return St(n,t)??n}function Ya(r,e,o,t){let n$1=0,i=0,a,m=false,s=r<=e?1:-1;for(let c=r;s>0?c<=e:c>=e;c+=s){let p=o.getLineResult(c),E=St(p,c);if(E)return E;if(p.type!==0&&p.type!==6)return N("LINE_RANGE_NON_NUMERIC",`Line ${c} is not a plain number or unit value \u2014 cannot include it in a sum/total/average range`);if(p.type===6){if(m=true,a===void 0)a=p.unit;else if(p.unit!==a)return N("LINE_RANGE_MIXED_UNITS",`Line ${c}'s unit (${p.unit}) doesn't match the range's first unit (${a}) \u2014 aggregating mixed units would silently misrepresent the result`)}n$1+=p.toNumber(),i++;}let u=t?n$1/i:n$1;return m?u$1(u,a):n(u)}function ja(r,e){let o=Pe(e);return o||Ya(r[0].toNumber(),r[1].toNumber(),e,false)}function Xa(r,e){let o=Pe(e);return o||Ya(r[0].toNumber(),r[1].toNumber(),e,true)}function Qa(r,e){let o=r.isLineBoundary;if(!o)return N("LINE_REF_NO_DOCUMENT",'"above" aggregation requires a real document');let t=0,n$1=0,i,a=false;for(let s=r.lineIndex-1;s>=1&&!o(s);s--){let u=r.getLineResult(s),c=St(u,s);if(c)return c;if(u.type!==0&&u.type!==6)return N("LINE_RANGE_NON_NUMERIC",`Line ${s} is not a plain number or unit value \u2014 cannot include it in "above" aggregation`);if(u.type===6){if(a=true,i===void 0)i=u.unit;else if(u.unit!==i)return N("LINE_RANGE_MIXED_UNITS",`Line ${s}'s unit (${u.unit}) doesn't match the range's unit (${i})`)}t+=u.toNumber(),n$1++;}if(n$1===0)return N("LINE_RANGE_EMPTY","No lines above to aggregate (hit the top of the document, a blank line, or a heading immediately)");let m=e?t/n$1:t;return a?u$1(m,i):n(m)}function Za(r,e){let o=Pe(e);return o||Qa(e,false)}function qa(r,e){let o=Pe(e);return o||Qa(e,true)}var zo={name:"solve-lines",lexerVocabulary:{keywords:{prev:"PREV"}},phrases:{"total above":"TOTAL_ABOVE","sum above":"SUM_ABOVE","average above":"AVERAGE_ABOVE"},normalizerRules:[Ga(),$a()],prefixParselets:{PREV:new xt,LINE_REF:new vt,SUM_RANGE_CALL:new Ze(false),AVERAGE_RANGE_CALL:new Ze(true),TOTAL_ABOVE:new ge(false),SUM_ABOVE:new ge(false),AVERAGE_ABOVE:new ge(true)},pluginFunctions:{prev:Ka,lineRef:Wa,sumRange:ja,averageRange:Xa,totalAbove:Za,averageAbove:qa}};var G=class{constructor(e){this.pluginFnName=e;this.category="Tables";}parse(e,o,t){let n=e.peek();if(!n||n.type!=="STRING")throw c$1.parsing("TABLE_COLUMN_NAME_EXPECTED",`Expected a quoted column name after "... of column" but got ${n?`"${n.value}"`:"end of input"}`);let i=e.consume("STRING");for(;;){let a=e.peek();if(!a)break;if(a.type==="IN"){e.consume();continue}if(a.type==="IDENT"&&Hl.has(a.value.toLowerCase())){e.consume();continue}break}t.emitOpcode(13),t.emitString(i.value),t.emitPluginCall(this.pluginFnName,1);}},Hl=new Set(["the","table","above"]);function Ja(r){return r.trimStart().startsWith("|")}function Gl(r){let e=r.trim();return e.length===0||!e.includes("-")||!e.includes("|")?false:/^[|\s:-]+$/.test(e)}function em(r){let e=r.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&!e.endsWith("\\|")&&(e=e.slice(0,-1));let o=[],t="";for(let n=0;n<e.length;n++){let i=e[n];if(i==="\\"&&n+1<e.length&&e[n+1]==="|"){t+="|",n++;continue}if(i==="|"){o.push(t.trim()),t="";continue}t+=i;}return o.push(t.trim()),o}function $l(r){if(r===void 0)return null;let e=r.trim();if(e.length===0)return null;let o=e.replace(/,/g,"");if(!/^[+-]?(\d+(\.\d+)?|\.\d+)$/.test(o))return null;let t=Number.parseFloat(o);return Number.isFinite(t)?t:null}function rm(r,e){let o=-1;for(let m=e-1;m>=1;m--){let s=r(m);if(s===void 0)break;if(Ja(s)){o=m;break}}if(o===-1)return null;let t=o;for(;t-1>=1;){let m=r(t-1);if(m===void 0||!Ja(m))break;t--;}let n=-1;for(let m=t;m<=o;m++)if(Gl(r(m))){n=m;break}if(n===-1||n===t)return null;let i=em(r(n-1)),a=[];for(let m=n+1;m<=o;m++)a.push(em(r(m)));return {header:i,rows:a}}function tm(r,e){let o=e.trim().toLowerCase();for(let t=0;t<r.length;t++)if(r[t].trim().toLowerCase()===o)return t;return -1}function om(r,e){let o=[];for(let t of r.rows){let n=$l(t[e]);n!==null&&o.push(n);}return o}var Lt={TABLE_NO_DOCUMENT:"TABLE_NO_DOCUMENT",TABLE_NOT_FOUND:"TABLE_NOT_FOUND",TABLE_COLUMN_NOT_FOUND:"TABLE_COLUMN_NOT_FOUND",TABLE_COLUMN_NO_NUMERIC_CELLS:"TABLE_COLUMN_NO_NUMERIC_CELLS"};function Kl(r,e){switch(r){case "sum":return e.reduce((o,t)=>o+t,0);case "average":return e.reduce((o,t)=>o+t,0)/e.length;case "min":return Math.min(...e);case "max":return Math.max(...e);case "count":return e.length;case "median":{let o=[...e].sort((n,i)=>n-i),t=Math.floor(o.length/2);return o.length%2===0?(o[t-1]+o[t])/2:o[t]}}}function _e(r,e,o){let t=o?.getLineText;if(!t||o.lineIndex<1)return N(Lt.TABLE_NO_DOCUMENT,"Reading a table column needs a real document, which the single-expression path (evaluateExpression) does not have");let n$1=rm(t,o.lineIndex);if(!n$1)return N(Lt.TABLE_NOT_FOUND,'No markdown table found above this line (a table row starts with "|", and needs a "|---|" separator under its header)');let i=tm(n$1.header,e);if(i===-1){let m=n$1.header.map(s=>`"${s}"`).join(", ");return N(Lt.TABLE_COLUMN_NOT_FOUND,`The table above has no column named "${e}". Its columns are: ${m}`)}let a=om(n$1,i);return r==="count"?n(a.length):a.length===0?N(Lt.TABLE_COLUMN_NO_NUMERIC_CELLS,`Column "${e}" has no plain-number cells to aggregate (currency and unit cells are not read yet)`):n(Kl(r,a))}function Oe(r){let e=r[0];return e&&e.type===3&&typeof e.value=="string"?e.value:String(e?.value??"")}function nm(r,e){return _e("sum",Oe(r),e)}function im(r,e){return _e("average",Oe(r),e)}function am(r,e){return _e("min",Oe(r),e)}function mm(r,e){return _e("max",Oe(r),e)}function sm(r,e){return _e("count",Oe(r),e)}function lm(r,e){return _e("median",Oe(r),e)}var Ho={name:"solve-tables",phrases:{"sum of column":"TABLE_COLUMN_SUM","total of column":"TABLE_COLUMN_SUM","average of column":"TABLE_COLUMN_AVERAGE","mean of column":"TABLE_COLUMN_AVERAGE","min of column":"TABLE_COLUMN_MIN","minimum of column":"TABLE_COLUMN_MIN","max of column":"TABLE_COLUMN_MAX","maximum of column":"TABLE_COLUMN_MAX","count of column":"TABLE_COLUMN_COUNT","median of column":"TABLE_COLUMN_MEDIAN"},prefixParselets:{TABLE_COLUMN_SUM:new G("TABLE_COLUMN_SUM"),TABLE_COLUMN_AVERAGE:new G("TABLE_COLUMN_AVERAGE"),TABLE_COLUMN_MIN:new G("TABLE_COLUMN_MIN"),TABLE_COLUMN_MAX:new G("TABLE_COLUMN_MAX"),TABLE_COLUMN_COUNT:new G("TABLE_COLUMN_COUNT"),TABLE_COLUMN_MEDIAN:new G("TABLE_COLUMN_MEDIAN")},pluginFunctions:{TABLE_COLUMN_SUM:nm,TABLE_COLUMN_AVERAGE:im,TABLE_COLUMN_MIN:am,TABLE_COLUMN_MAX:mm,TABLE_COLUMN_COUNT:sm,TABLE_COLUMN_MEDIAN:lm}};var Re=class{constructor(e){this.pluginFnName=e;this.category="Tags";}parse(e,o,t){t.emitOpcode(13),t.emitString(o.value),t.emitPluginCall(this.pluginFnName,1);}};function wt(r){return r===void 0?"":(r.text??r.value??"").toLowerCase()}var um={TOTAL_OF:"TAG_SUM",COUNT_OF:"TAG_COUNT",AVERAGE_OF:"TAG_AVERAGE"},Wl=new Set(["total","sum","count","average"]);function cm(r=80){return {name:"tags:aggregate",priority:r,match(e,o){let t=e[o];if(t===void 0)return null;let n=um[t.type];if(n!==void 0){let i=e[o+1];return i?.type!=="TAG"?null:{consumed:2,replacement:[b$4(n,i.value??"",[t,i])],ruleName:"tags:aggregate"}}if(t.type==="IDENT"&&wt(t)==="sum"){let i=e[o+1],a=e[o+2];return wt(i)!=="of"||a?.type!=="TAG"?null:{consumed:3,replacement:[b$4("TAG_SUM",a.value??"",[t,i,a])],ruleName:"tags:aggregate"}}return null}}}function pm(r=40){return {name:"tags:strip",priority:r,match(e,o){if(e[o]?.type!=="TAG")return null;let t=e[o-1];return t!==void 0&&(um[t.type]!==void 0||wt(t)==="of"&&Wl.has(wt(e[o-2])))?null:{consumed:1,replacement:[],ruleName:"tags:strip"}}}}function Yl(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fm(r,e){if(e==="")return false;let t=new RegExp(`(?:^|[^0-9A-Za-z_])#${Yl(e)}(?![0-9A-Za-z_-])`,"i").exec(r);if(t===null)return false;let n=t.index+t[0].indexOf("#");return r.slice(0,n).trim().length>0}function jl(r,e){return r===void 0?N("LINE_NOT_YET_EVALUATED",`Line ${e} has not been evaluated yet`):r.type===12?N("LINE_RESULT_PENDING",`Line ${e}'s result is still resolving`):r.type===13?N("LINE_RESULT_ERROR",`Line ${e} has an error`):null}function Go(r){return !r?.getLineResult||!r.getLineText?N("TAG_NO_DOCUMENT","Category tag sums require a real document, not available outside one (e.g. evaluateExpression()'s single-expression path)"):null}function $o(r,e,o){let t=r.getLineText,n$1=r.getLineResult,i=r.isLineBoundary,a=e.toLowerCase(),m=0,s=0,u,c=false;for(let E=1;;E++){let T=t(E);if(T===void 0)break;if(E===r.lineIndex||i&&i(E)||!fm(T,a))continue;let y=n$1(E),O=jl(y,E);if(O)return O;if(o!=="count"){if(y.type!==0&&y.type!==6)return N("TAG_NON_NUMERIC",`Line ${E}, tagged #${e}, is not a plain number or unit value.`);if(y.type===6){if(c=true,u===void 0)u=y.unit;else if(y.unit!==u)return N("TAG_MIXED_UNITS",`Line ${E}'s unit (${y.unit}) doesn't match #${e}'s first unit (${u}), aggregating mixed units would misrepresent the result.`)}m+=y.toNumber();}s++;}if(o==="count")return n(s);if(s===0)return N("TAG_EMPTY",`No lines are tagged #${e}.`);let p=o==="average"?m/s:m;return c?u$1(p,u):n(p)}function dm(r,e){let o=Go(e);return o||$o(e,String(r[0].value),"sum")}function Em(r,e){let o=Go(e);return o||$o(e,String(r[0].value),"average")}function Nm(r,e){let o=Go(e);return o||$o(e,String(r[0].value),"count")}var Ko={name:"solve-tags",normalizerRules:[cm(),pm()],prefixParselets:{TAG_SUM:new Re("sum"),TAG_AVERAGE:new Re("average"),TAG_COUNT:new Re("count")},pluginFunctions:{sum:dm,average:Em,count:Nm}};var kt=class{constructor(){this.category="operator";this.bindingPower=a.Uncertainty;}parse(e,o,t,n){e.parseExpression(this.bindingPower,n),n.emitOpcode(28);}};function Tm(r=90){return {name:"uncertainty:ascii-plus-minus",priority:r,match(e,o){let t=e[o];if(t?.type!=="PLUS")return null;let n=e[o+1];if(n?.type!=="SLASH")return null;let i=e[o+2];return i?.type!=="MINUS"?null:{consumed:3,replacement:[b$4("PLUS_MINUS","\xB1",[t,n,i])],ruleName:"uncertainty:ascii-plus-minus"}}}}var Wo={name:"solve-uncertainty",infixParselets:{PLUS_MINUS:new kt},normalizerRules:[Tm()]};var ym=1e-9,gm=1e9,Xl=100,Ql=1e-9,Zl=1e-9,ql=1e-12,Jl=1e-9,Bt="goalseek";function Pm(r,e){let o=e?.evaluateLineWithBinding,t=e?.getLineReads;if(!o||!t)return N("GOAL_SEEK_NO_DOCUMENT","Goal seek only works inside a document, since it re-runs another line. The single-expression entry point has no document to solve against.");let n$1=r[0].toNumber(),i=typeof r[1].value=="string"?r[1].value:String(r[1].value),a=r[2];if(a.type!==0&&a.type!==6)return N("GOAL_SEEK_TARGET_NOT_NUMERIC",`Goal seek's target must be a number, as in "solve line ${n$1} for ${i} = 900".`);let m=a.toNumber();if(!Number.isFinite(m))return N("GOAL_SEEK_TARGET_NOT_NUMERIC","Goal seek's target is not a finite number.");let s=t(n$1);if(s===void 0)return N("GOAL_SEEK_LINE_NOT_READY",`Line ${n$1} has no evaluated expression to solve (forward reference, out of range, or not an expression).`);if(!s.includes(i))return N("GOAL_SEEK_VARIABLE_NOT_USED",`Line ${n$1} does not use ${i}, so changing ${i} cannot move its result toward ${m}.`);let u=o(n$1,i,I$1(q$2(i)),true);if(u.type===9){let p=eu(u.value,m,i);if(p!==null)return n(p)}let c=e.goalSeekMaxIterations??Xl;return ru(o,n$1,i,m,c)}function eu(r,e,o){let t=p$1(d$1(e)),n;try{n=d$2(r,t,o);}catch{return null}if(n.kind!=="roots")return null;let i=[];for(let s of n.exact){let u=Q(s);if(u.kind==="const"){let c=e$3(u.value);Number.isFinite(c)&&i.push(c);}}for(let s of n.approximate)Math.abs(s.im)<=Jl&&Number.isFinite(s.re)&&i.push(s.re);if(i.length===0)return null;let a=i.filter(s=>s>=ym&&s<=gm),m=a.length>0?a:i;return m.sort((s,u)=>Math.abs(s)-Math.abs(u)),m[0]}function ru(r,e,o,t,n$1){let i=T=>{let y=r(e,o,n(T),false);if(y.type===13)return {error:y};if(y.type!==0&&y.type!==6)return {error:N("GOAL_SEEK_TARGET_NOT_NUMERIC",`Line ${e} did not produce a number when ${o} was set to ${T}, so goal seek cannot compare it to the target.`)};let O=y.toNumber();return Number.isFinite(O)?{value:O}:{error:N("GOAL_SEEK_NON_FINITE",`Line ${e}'s result is not finite when ${o} is ${T}.`)}},a=ym,m=gm,s=i(a);if("error"in s)return s.error;let u=i(m);if("error"in u)return u.error;let c=Math.max(Ql,Math.abs(t)*Zl),p=s.value-t,E=u.value-t;if(Math.abs(p)<=c)return n(a);if(Math.abs(E)<=c)return n(m);if(Math.sign(p)===Math.sign(E))return N("GOAL_SEEK_NO_SOLUTION",`No value of ${o} between ${a} and ${m} makes line ${e} equal ${t}: across that whole range its result stays on one side of the target.`);for(let T=0;T<n$1;T++){let y=(a+m)/2,O=i(y);if("error"in O)return O.error;let L=O.value-t;if(Math.abs(L)<=c)return n(y);if(m-a<=ql)return N("GOAL_SEEK_DID_NOT_CONVERGE",`Goal seek narrowed ${o} to a single point near ${y} without line ${e} reaching ${t}: the relationship jumps across the target rather than passing through it.`);Math.sign(L)===Math.sign(p)?(a=y,p=L):m=y;}return N("GOAL_SEEK_DID_NOT_CONVERGE",`Goal seek did not bring line ${e} within tolerance of ${t} by varying ${o} in ${n$1} steps.`)}var Ut=class{constructor(){this.category="GoalSeek";}parse(e,o,t){let n=e.peek();if(!n||n.type!=="LINE_REF")throw c$1.parsing("GOAL_SEEK_SYNTAX",'Goal seek reads "solve line N for <var> = <target>", for example "solve line 4 for rate = 900".',{found:n?.type??"end of input"});e.consume();let i=parseInt(n.value,10),a$1=e.peek();if(!(!!a$1&&(a$1.type==="FOR_DURATION"||a$1.type==="IDENT"&&a$1.value.toLowerCase()==="for")))throw c$1.parsing("GOAL_SEEK_SYNTAX",'Goal seek reads "solve line N for <var> = <target>". Expected "for" after the line reference.',{found:a$1?.type??"end of input"});e.consume();let s=e.peek();if(!s||s.type!=="IDENT"&&s.type!=="UNIT")throw c$1.parsing("GOAL_SEEK_REQUIRES_VARIABLE_NAME",'Goal seek needs the name of the variable to vary here, as in "solve line 4 for rate = 900".',{found:s?.type??"end of input"});e.consume(),e.consume("EQUALS"),t.emitOpcode(10),t.emitNumber(i),t.emitOpcode(13),t.emitString(s.value),e.parseExpression(a.Lowest,t),t.emitPluginCall(Bt,3);}};var tu=c("GOAL_SEEK");function _m(r=75){return {name:"goalseek:solve-line",priority:r,match(e,o){if(o>0&&e[o-1].type==="COLON")return null;let t=e[o];return !t||t.type!=="IDENT"||t.value.toLowerCase()!=="solve"||e[o+1]?.type!=="LINE_REF"?null:{consumed:1,replacement:[new a$7("GOAL_SEEK",tu,t.value,t.value,t.offset,0,t.line,t.col)],ruleName:"goalseek:solve-line"}}}}var Yo={name:"solve-goalseek",normalizerRules:[_m()],prefixParselets:{GOAL_SEEK:new Ut},pluginFunctions:{[Bt]:Pm}};var Mt=class{constructor(){this.category="Colour";}parse(e,o,t){t.emitOpcode(13),t.emitString(o.value),t.emitPluginCall("colour",1);}};var te={COLOUR_INVALID:"COLOUR_INVALID",COLOUR_EXPECTED_COLOUR:"COLOUR_EXPECTED_COLOUR",COLOUR_BAD_ARGUMENTS:"COLOUR_BAD_ARGUMENTS"};function I(r){return r&&r.type===14?r.value:null}function h(r){if(!r)return 0;let e=r.toNumber();return r.type===5?e:e>1?e/100:e}function D(r,e){return N(te.COLOUR_BAD_ARGUMENTS,`${r}(...) expects ${e}`)}function U(r){return N(te.COLOUR_EXPECTED_COLOUR,`${r}(...) expects a colour as its first argument`)}function Om(r){let e=r[0];if(!e||e.type!==3||typeof e.value!="string")return D("color",'a string, e.g. color("#ff0000") or color("red")');let o=c$2(e.value);return o?G$1(o):N(te.COLOUR_INVALID,`"${e.value}" is not a hex colour (#rgb, #rgba, #rrggbb, #rrggbbaa) or a CSS colour name`)}function ou(r){return r.length!==3?D("rgb","three numbers: rgb(red, green, blue)"):G$1({r:a$1(r[0].toNumber()),g:a$1(r[1].toNumber()),b:a$1(r[2].toNumber()),a:1,format:"rgb"})}function nu(r){return r.length!==4?D("rgba","four numbers: rgba(red, green, blue, alpha)"):G$1({r:a$1(r[0].toNumber()),g:a$1(r[1].toNumber()),b:a$1(r[2].toNumber()),a:b$2(h(r[3])),format:"rgba"})}function iu(r){if(r.length!==3)return D("hsl","three values: hsl(hue, saturation%, lightness%)");let{r:e$1,g:o,b:t}=e(r[0].toNumber(),h(r[1]),h(r[2]));return G$1({r:e$1,g:o,b:t,a:1,format:"hsl"})}function au(r){if(r.length!==4)return D("hsla","four values: hsla(hue, saturation%, lightness%, alpha)");let{r:e$1,g:o,b:t}=e(r[0].toNumber(),h(r[1]),h(r[2]));return G$1({r:e$1,g:o,b:t,a:b$2(h(r[3])),format:"hsla"})}function oe(r,e){return o=>{let t=I(o[0]);return t?o.length<2?D(r,`a colour and an amount, e.g. ${r}(#3366cc, 20%)`):G$1(e(t,h(o[1]))):U(r)}}var mu=oe("lighten",j$1),su=oe("darken",k$1),lu=oe("saturate",l),Rm=oe("desaturate",m);function jo(r){let e=I(r[0]);return e?r.length<2?D("rotate","a colour and a hue angle in degrees, e.g. rotate(#ff0000, 90)"):G$1(n$1(e,r[1].toNumber())):U("rotate")}function uu(r){let e=I(r[0]);return e?G$1(o(e)):U("complement")}function Am(r){let e=I(r[0]);return e?G$1(p(e)):U("grayscale")}function Im(r){let e=I(r[0]);return e?G$1(q$1(e,r.length>1?h(r[1]):1)):U("invert")}function cu(r$1){let e=I(r$1[0]),o=I(r$1[1]);return !e||!o?N(te.COLOUR_EXPECTED_COLOUR,"mix(...) expects two colours to blend"):G$1(r(e,o,r$1.length>2?h(r$1[2]):.5))}function Xo(r){let e=I(r[0]);return e?r.length<2?n(e.a):G$1(s(e,h(r[1]))):U("alpha")}function pu(r){let e=I(r[0]),o=I(r[1]);return !e||!o?N(te.COLOUR_EXPECTED_COLOUR,"contrast(...) expects two colours"):n(i(e,o))}function fu(r){let e=I(r[0]);return e?n(h$1(e)):U("luminance")}function Ae(r,e){return o=>{let t=I(o[0]);return t?n(e(t)):U(r)}}var du=Ae("red",r=>r.r),Eu=Ae("green",r=>r.g),Nu=Ae("blue",r=>r.b),Tu=Ae("hue",r=>d$3(r.r,r.g,r.b).h),yu=Ae("saturation",r=>d$3(r.r,r.g,r.b).s*100),gu=Ae("lightness",r=>d$3(r.r,r.g,r.b).l*100);function Cm(r){if(r.length!==3)return D("hsv","three values: hsv(hue, saturation%, value%)");let{r:e,g:o,b:t}=t$1(r[0].toNumber(),h(r[1]),h(r[2]));return G$1({r:e,g:o,b:t,a:1,format:"hex"})}function Pu(r){if(r.length!==4)return D("hsva","four values: hsva(hue, saturation%, value%, alpha)");let{r:e,g:o,b:t}=t$1(r[0].toNumber(),h(r[1]),h(r[2]));return G$1({r:e,g:o,b:t,a:b$2(h(r[3])),format:"hex"})}function _u(r){if(r.length!==3)return D("hwb","three values: hwb(hue, whiteness%, blackness%)");let{r:e,g:o,b:t}=u(r[0].toNumber(),h(r[1]),h(r[2]));return G$1({r:e,g:o,b:t,a:1,format:"hex"})}var Ou=oe("tint",v),Ru=oe("shade",w),Au=oe("tone",x);function Iu(r){let e=I(r[0]);return e?J$1(y(e)):U("isdark")}function Cu(r){let e=I(r[0]);return e?J$1(!y(e)):U("islight")}function Qo(r){let e=I(r[0]);return e?G$1(z$1(e)):U("readable")}function hu(r){if(!r)return A$1.aa;if(r.type===0)return r.toNumber();if(r.type===3){let e=r.value.trim().toLowerCase();if(e==="aaa")return A$1.aaa;if(e==="aa large"||e==="aa-large"||e==="large")return A$1.aaLarge;if(e==="aaa large"||e==="aaa-large")return A$1.aaaLarge}return A$1.aa}function xu(r){let e=I(r[0]),o=I(r[1]);return !e||!o?N(te.COLOUR_EXPECTED_COLOUR,"iscontrastcompliant(...) expects two colours"):J$1(i(e,o)>=hu(r[2]))}function hm(r){let e=I(r[0]),o=I(r[1]);return !e||!o?N(te.COLOUR_EXPECTED_COLOUR,"wcaglevel(...) expects two colours"):t(B$1(e,o))}var ne={color:Om,colour:Om,rgb:ou,rgba:nu,hsl:iu,hsla:au,lighten:mu,darken:su,saturate:lu,desaturate:Rm,desat:Rm,rotate:jo,spin:jo,adjusthue:jo,complement:uu,grayscale:Am,greyscale:Am,invert:Im,mix:cu,alpha:Xo,opacity:Xo,fade:Xo,contrast:pu,luminance:fu,red:du,green:Eu,blue:Nu,hue:Tu,saturation:yu,lightness:gu,hsv:Cm,hsb:Cm,hsva:Pu,hwb:_u,tint:Ou,shade:Ru,tone:Au,negate:Im,isdark:Iu,islight:Cu,readable:Qo,contrastcolor:Qo,contrastcolour:Qo,iscontrastcompliant:xu,wcaglevel:hm,wcag:hm};var Dt=class{constructor(){this.category="Colour";}parse(e,o,t){let n=o.value.toLowerCase();if(ne[n]===void 0)throw c$1.execution("UNKNOWN_COLOUR_FUNCTION",`Unknown colour function: ${n}`,{functionName:n});e.consume("LPAREN");let i=0;if(e.peek()?.type!=="RPAREN")for(e.parseExpression(a.Lowest,t),i++;e.match("COMMA");)e.parseExpression(a.Lowest,t),i++;e.consume("RPAREN"),t.emitPluginCall(n,i);}};var vu=new Set(Object.keys(ne));function xm(r=80){return {name:"colour:call",priority:r,match(e,o){let t=e[o];if(!t||t.type!=="IDENT")return null;let n=t.value.toLowerCase();return !vu.has(n)||e[o+1]?.type!=="LPAREN"?null:{consumed:1,replacement:[new a$7("COLOUR_CALL",c("COLOUR_CALL"),t.value,t.value,t.offset,0,t.line,t.col)],ruleName:"colour:call"}}}}var Ft=r=>e=>{if(e.type!==14)return e;let o=e.value;return G$1({r:o.r,g:o.g,b:o.b,a:o.a,format:r})},Su=Object.keys(ne).map(r=>({label:r,category:"function",detail:"colour"})),Zo={name:"solve-colour",prefixParselets:{HEX_COLOUR:new Mt,COLOUR_CALL:new Dt},normalizerRules:[xm()],pluginFunctions:ne,asConverters:{rgb:Ft("rgb"),rgba:Ft("rgba"),hsl:Ft("hsl"),hsla:Ft("hsla")},completionItems:Su};var eR=[Xt,Qt,qt,no,No,To,yo,Ao,Co,ho,xo,vo,a$4,So,Lo,wo,Bo,Fo,Wo,bo,zo,Yo,Ho,Zo,Ko];
2
+ export{Xt as a,Qt as b,qt as c,no as d,No as e,To as f,yo as g,Ao as h,Io as i,Co as j,ho as k,xo as l,vo as m,So as n,Lo as o,wo as p,Bo as q,Fo as r,bo as s,ba as t,za as u,zo as v,Ho as w,Ko as x,eR as y};//# sourceMappingURL=chunk-AIIPKVKO.js.map
3
+ //# sourceMappingURL=chunk-AIIPKVKO.js.map