solve-engine 2.5.0 → 2.6.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.
- package/dist/{BytecodeBuilder-DGGeByAP.d.cts → BytecodeBuilder-BGq9ZiO3.d.cts} +2 -1
- package/dist/{BytecodeBuilder-DGGeByAP.d.ts → BytecodeBuilder-BGq9ZiO3.d.ts} +2 -1
- package/dist/{PackageCompatibility-UsSZIfHs.d.ts → PackageCompatibility-4QtIErfx.d.ts} +1 -1
- package/dist/{PackageCompatibility-cEClSSkz.d.cts → PackageCompatibility-CCdud__Q.d.cts} +1 -1
- package/dist/{PackageRegistry-B3yJHSxX.d.ts → PackageRegistry-B7wkfSrY.d.ts} +5 -5
- package/dist/{PackageRegistry-BsLmAVZJ.d.cts → PackageRegistry-Hx85XD01.d.cts} +5 -5
- package/dist/{Parselet-C4Wu055_.d.cts → Parselet-CTNpfuEB.d.cts} +2 -2
- package/dist/{Parselet-B-zoPrTa.d.ts → Parselet-DONNUpur.d.ts} +2 -2
- package/dist/{ScopeManager-DkpnlKuz.d.ts → ScopeManager-BkbDXK_R.d.ts} +3 -3
- package/dist/{ScopeManager-t6SnP6Ce.d.cts → ScopeManager-Cvgypcu4.d.cts} +3 -3
- package/dist/{VMCheckpoints-CsHmQVaD.d.ts → VMCheckpoints-9zBQnTsN.d.ts} +3 -3
- package/dist/{VMCheckpoints-C_jQvABf.d.cts → VMCheckpoints-CBMGiSqw.d.cts} +3 -3
- package/dist/{Value-CCi_Eecs.d.cts → Value-D1XlMwe2.d.cts} +40 -5
- package/dist/{Value-CCi_Eecs.d.ts → Value-D1XlMwe2.d.ts} +40 -5
- package/dist/chunk-3AVWA5IZ.cjs +2 -0
- package/dist/chunk-3AVWA5IZ.cjs.map +1 -0
- package/dist/chunk-3DD2RVBI.cjs +3 -0
- package/dist/chunk-3DD2RVBI.cjs.map +1 -0
- package/dist/{chunk-RDMJNRDO.js → chunk-4XTD4B77.js} +3 -3
- package/dist/{chunk-RDMJNRDO.js.map → chunk-4XTD4B77.js.map} +1 -1
- package/dist/chunk-5FGOIDLS.cjs +2 -0
- package/dist/chunk-5FGOIDLS.cjs.map +1 -0
- package/dist/chunk-5OIXCVB2.js +3 -0
- package/dist/chunk-5OIXCVB2.js.map +1 -0
- package/dist/{chunk-NGJMCVH4.cjs → chunk-B4P4M4ZW.cjs} +3 -3
- package/dist/{chunk-NGJMCVH4.cjs.map → chunk-B4P4M4ZW.cjs.map} +1 -1
- package/dist/{chunk-TWC7K3ZX.js → chunk-GHW2X7PS.js} +2 -2
- package/dist/{chunk-TWC7K3ZX.js.map → chunk-GHW2X7PS.js.map} +1 -1
- package/dist/chunk-GKDZ7TSX.cjs +2 -0
- package/dist/chunk-GKDZ7TSX.cjs.map +1 -0
- package/dist/{chunk-7RTKJMYS.js → chunk-HMEZJXLX.js} +2 -2
- package/dist/{chunk-7RTKJMYS.js.map → chunk-HMEZJXLX.js.map} +1 -1
- package/dist/{chunk-FDE5HWDI.cjs → chunk-HOQU47MF.cjs} +2 -2
- package/dist/{chunk-FDE5HWDI.cjs.map → chunk-HOQU47MF.cjs.map} +1 -1
- package/dist/chunk-IO374J6Z.js +2 -0
- package/dist/chunk-IO374J6Z.js.map +1 -0
- package/dist/{chunk-D5MTMRHS.cjs → chunk-KSDTVFXA.cjs} +4 -4
- package/dist/{chunk-D5MTMRHS.cjs.map → chunk-KSDTVFXA.cjs.map} +1 -1
- package/dist/{chunk-YUJNMUKM.cjs → chunk-OVQ3V4CG.cjs} +2 -2
- package/dist/{chunk-YUJNMUKM.cjs.map → chunk-OVQ3V4CG.cjs.map} +1 -1
- package/dist/{chunk-XNIWQHXY.js → chunk-P6BLASAA.js} +2 -2
- package/dist/{chunk-XNIWQHXY.js.map → chunk-P6BLASAA.js.map} +1 -1
- package/dist/{chunk-AXMQG5TS.cjs → chunk-R7T3NGUE.cjs} +2 -2
- package/dist/{chunk-AXMQG5TS.cjs.map → chunk-R7T3NGUE.cjs.map} +1 -1
- package/dist/{chunk-CT5TC3JX.cjs → chunk-SOSUS2SK.cjs} +3 -3
- package/dist/chunk-SOSUS2SK.cjs.map +1 -0
- package/dist/chunk-SWKYVSMP.js +2 -0
- package/dist/chunk-SWKYVSMP.js.map +1 -0
- package/dist/chunk-T4Y5XOT2.js +3 -0
- package/dist/chunk-T4Y5XOT2.js.map +1 -0
- package/dist/{chunk-LOM3H5ZD.js → chunk-T52Y5G24.js} +4 -4
- package/dist/{chunk-LOM3H5ZD.js.map → chunk-T52Y5G24.js.map} +1 -1
- package/dist/{chunk-JFAJN3C2.cjs → chunk-VBSMA7WJ.cjs} +2 -2
- package/dist/chunk-VBSMA7WJ.cjs.map +1 -0
- package/dist/{chunk-RSF25YSJ.js → chunk-VYWGUMFW.js} +2 -2
- package/dist/{chunk-RSF25YSJ.js.map → chunk-VYWGUMFW.js.map} +1 -1
- package/dist/chunk-XTM4HTRB.js +2 -0
- package/dist/{chunk-LBNX7TXI.js.map → chunk-XTM4HTRB.js.map} +1 -1
- package/dist/{chunk-E6Z4NQAS.js → chunk-YNMMRH44.js} +2 -2
- package/dist/chunk-YNMMRH44.js.map +1 -0
- package/dist/chunk-Z5KBBQOJ.cjs +2 -0
- package/dist/{chunk-YFWAR766.cjs.map → chunk-Z5KBBQOJ.cjs.map} +1 -1
- package/dist/chunk-ZJPAPBP3.js +2 -0
- package/dist/chunk-ZJPAPBP3.js.map +1 -0
- package/dist/{chunk-N7N7MPMK.cjs → chunk-ZOOVGXMK.cjs} +2 -2
- package/dist/{chunk-N7N7MPMK.cjs.map → chunk-ZOOVGXMK.cjs.map} +1 -1
- package/dist/constants.cjs +1 -1
- package/dist/constants.js +1 -1
- package/dist/engine.cjs +1 -1
- package/dist/engine.d.cts +8 -8
- package/dist/engine.d.ts +8 -8
- package/dist/engine.js +1 -1
- package/dist/format.cjs +1 -1
- package/dist/format.d.cts +1 -1
- package/dist/format.d.ts +1 -1
- package/dist/format.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +8 -8
- package/dist/index.d.ts +8 -8
- package/dist/index.js +1 -1
- package/dist/language.d.cts +7 -7
- package/dist/language.d.ts +7 -7
- package/dist/packages.cjs +1 -1
- package/dist/packages.d.cts +7 -7
- package/dist/packages.d.ts +7 -7
- package/dist/packages.js +1 -1
- package/dist/parser.cjs +1 -1
- package/dist/parser.d.cts +4 -4
- package/dist/parser.d.ts +4 -4
- package/dist/parser.js +1 -1
- package/dist/{pipeline-72QmQlGx.d.ts → pipeline-BH7BFOTJ.d.ts} +3 -3
- package/dist/{pipeline-DCQicwWX.d.cts → pipeline-DY0rhgQG.d.cts} +3 -3
- package/dist/resolvers.d.cts +2 -2
- package/dist/resolvers.d.ts +2 -2
- package/dist/testing.cjs +2 -2
- package/dist/testing.d.cts +7 -7
- package/dist/testing.d.ts +7 -7
- package/dist/testing.js +1 -1
- package/dist/uom.cjs +1 -1
- package/dist/uom.d.cts +2 -2
- package/dist/uom.d.ts +2 -2
- package/dist/uom.js +1 -1
- package/dist/vm.cjs +1 -1
- package/dist/vm.d.cts +7 -7
- package/dist/vm.d.ts +7 -7
- package/dist/vm.js +1 -1
- package/dist/worker.cjs +2 -2
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +22 -6
- package/dist/worker.d.ts +22 -6
- package/dist/worker.js +2 -2
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-2HQWM5OB.js +0 -3
- package/dist/chunk-2HQWM5OB.js.map +0 -1
- package/dist/chunk-6G3PMEPA.js +0 -2
- package/dist/chunk-6G3PMEPA.js.map +0 -1
- package/dist/chunk-6INX773F.cjs +0 -2
- package/dist/chunk-6INX773F.cjs.map +0 -1
- package/dist/chunk-6ZNNPXXE.cjs +0 -3
- package/dist/chunk-6ZNNPXXE.cjs.map +0 -1
- package/dist/chunk-ANJPS6FF.cjs +0 -2
- package/dist/chunk-ANJPS6FF.cjs.map +0 -1
- package/dist/chunk-B5NBFGNP.js +0 -3
- package/dist/chunk-B5NBFGNP.js.map +0 -1
- package/dist/chunk-CT5TC3JX.cjs.map +0 -1
- package/dist/chunk-E6Z4NQAS.js.map +0 -1
- package/dist/chunk-EVAOPEO4.js +0 -2
- package/dist/chunk-EVAOPEO4.js.map +0 -1
- package/dist/chunk-JFAJN3C2.cjs.map +0 -1
- package/dist/chunk-LBNX7TXI.js +0 -2
- package/dist/chunk-PS272DZJ.cjs +0 -2
- package/dist/chunk-PS272DZJ.cjs.map +0 -1
- package/dist/chunk-QEYTENAK.js +0 -2
- package/dist/chunk-QEYTENAK.js.map +0 -1
- package/dist/chunk-YFWAR766.cjs +0 -2
|
@@ -92,7 +92,8 @@ declare enum OpCode {
|
|
|
92
92
|
RANGE_NEW = 156,// (min, max already on stack) -> push a Range value `min:max`
|
|
93
93
|
MAP_INVOKE = 157,// map(...) — see parser/BytecodeBuilder.ts's `anonymousBodies` side-table
|
|
94
94
|
REDUCE_INVOKE = 158,// reduce(...) — same anonymousBodies mechanism as MAP_INVOKE
|
|
95
|
-
BIND_UNKNOWN = 159
|
|
95
|
+
BIND_UNKNOWN = 159,
|
|
96
|
+
PLOT_INVOKE = 160
|
|
96
97
|
}
|
|
97
98
|
/**
|
|
98
99
|
* Gets the name of an OpCode as a string.
|
|
@@ -92,7 +92,8 @@ declare enum OpCode {
|
|
|
92
92
|
RANGE_NEW = 156,// (min, max already on stack) -> push a Range value `min:max`
|
|
93
93
|
MAP_INVOKE = 157,// map(...) — see parser/BytecodeBuilder.ts's `anonymousBodies` side-table
|
|
94
94
|
REDUCE_INVOKE = 158,// reduce(...) — same anonymousBodies mechanism as MAP_INVOKE
|
|
95
|
-
BIND_UNKNOWN = 159
|
|
95
|
+
BIND_UNKNOWN = 159,
|
|
96
|
+
PLOT_INVOKE = 160
|
|
96
97
|
}
|
|
97
98
|
/**
|
|
98
99
|
* Gets the name of an OpCode as a string.
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { a as PrecedenceParser, b as PrefixParselet, I as InfixParselet } from './Parselet-
|
|
2
|
-
import { V as Value, b as ValueType } from './Value-
|
|
1
|
+
import { a as PrecedenceParser, b as PrefixParselet, I as InfixParselet } from './Parselet-DONNUpur.js';
|
|
2
|
+
import { V as Value, b as ValueType } from './Value-D1XlMwe2.js';
|
|
3
3
|
import { M as MarkdownLineType, L as Lexer, e as TokenCategory, c as LexerVocabulary } from './Lexer-DKMlj7Sy.js';
|
|
4
4
|
import { IAsyncResolver } from './resolvers.js';
|
|
5
5
|
import { T as TokenFusion, c as TokenNormalizer, a as NormalizerRule } from './TokenNormalizer-DCWdZjGz.js';
|
|
6
|
-
import { D as DependencyGraph, V as VM, a as DagSnapshot, b as EngineContext, S as ScopeManager, P as PluginFunctionHandler } from './ScopeManager-
|
|
7
|
-
import { a as BytecodeProgram } from './BytecodeBuilder-
|
|
6
|
+
import { D as DependencyGraph, V as VM, a as DagSnapshot, b as EngineContext, S as ScopeManager, P as PluginFunctionHandler } from './ScopeManager-BkbDXK_R.js';
|
|
7
|
+
import { a as BytecodeProgram } from './BytecodeBuilder-BGq9ZiO3.js';
|
|
8
8
|
import { QueryClient } from '@tanstack/query-core';
|
|
9
9
|
import { E as EngineError } from './EngineError-Ce1lPkjZ.js';
|
|
10
|
-
import { a as DiagnosticReportJSON, D as DiagnosticPipeline } from './pipeline-
|
|
10
|
+
import { a as DiagnosticReportJSON, D as DiagnosticPipeline } from './pipeline-BH7BFOTJ.js';
|
|
11
11
|
import { T as Token } from './Token-CbP_OutD.js';
|
|
12
12
|
import { E as EngineConfigOverride, a as EngineConfig } from './Configuration-BGQn-cJ8.js';
|
|
13
13
|
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { a as PrecedenceParser, b as PrefixParselet, I as InfixParselet } from './Parselet-
|
|
2
|
-
import { V as Value, b as ValueType } from './Value-
|
|
1
|
+
import { a as PrecedenceParser, b as PrefixParselet, I as InfixParselet } from './Parselet-CTNpfuEB.cjs';
|
|
2
|
+
import { V as Value, b as ValueType } from './Value-D1XlMwe2.cjs';
|
|
3
3
|
import { M as MarkdownLineType, L as Lexer, e as TokenCategory, c as LexerVocabulary } from './Lexer-B4C1qHXu.cjs';
|
|
4
4
|
import { IAsyncResolver } from './resolvers.cjs';
|
|
5
5
|
import { T as TokenFusion, c as TokenNormalizer, a as NormalizerRule } from './TokenNormalizer-DnlL7_8c.cjs';
|
|
6
|
-
import { D as DependencyGraph, V as VM, a as DagSnapshot, b as EngineContext, S as ScopeManager, P as PluginFunctionHandler } from './ScopeManager-
|
|
7
|
-
import { a as BytecodeProgram } from './BytecodeBuilder-
|
|
6
|
+
import { D as DependencyGraph, V as VM, a as DagSnapshot, b as EngineContext, S as ScopeManager, P as PluginFunctionHandler } from './ScopeManager-Cvgypcu4.cjs';
|
|
7
|
+
import { a as BytecodeProgram } from './BytecodeBuilder-BGq9ZiO3.cjs';
|
|
8
8
|
import { QueryClient } from '@tanstack/query-core';
|
|
9
9
|
import { E as EngineError } from './EngineError-Ce1lPkjZ.cjs';
|
|
10
|
-
import { a as DiagnosticReportJSON, D as DiagnosticPipeline } from './pipeline-
|
|
10
|
+
import { a as DiagnosticReportJSON, D as DiagnosticPipeline } from './pipeline-DY0rhgQG.cjs';
|
|
11
11
|
import { T as Token } from './Token-CbP_OutD.cjs';
|
|
12
12
|
import { E as EngineConfigOverride, a as EngineConfig } from './Configuration-BGQn-cJ8.cjs';
|
|
13
13
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { B as BytecodeBuilder } from './BytecodeBuilder-
|
|
1
|
+
import { B as BytecodeBuilder } from './BytecodeBuilder-BGq9ZiO3.cjs';
|
|
2
2
|
import { T as Token } from './Token-CbP_OutD.cjs';
|
|
3
|
-
import { D as DiagnosticPipeline } from './pipeline-
|
|
3
|
+
import { D as DiagnosticPipeline } from './pipeline-DY0rhgQG.cjs';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Dual-keyed ParseletRegistry, accepts both string token types and
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { B as BytecodeBuilder } from './BytecodeBuilder-
|
|
1
|
+
import { B as BytecodeBuilder } from './BytecodeBuilder-BGq9ZiO3.js';
|
|
2
2
|
import { T as Token } from './Token-CbP_OutD.js';
|
|
3
|
-
import { D as DiagnosticPipeline } from './pipeline-
|
|
3
|
+
import { D as DiagnosticPipeline } from './pipeline-BH7BFOTJ.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Dual-keyed ParseletRegistry, accepts both string token types and
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { V as Value } from './Value-
|
|
2
|
-
import { U as UserFunctionDef, A as AnonymousBodyDef, a as BytecodeProgram } from './BytecodeBuilder-
|
|
1
|
+
import { V as Value } from './Value-D1XlMwe2.js';
|
|
2
|
+
import { U as UserFunctionDef, A as AnonymousBodyDef, a as BytecodeProgram } from './BytecodeBuilder-BGq9ZiO3.js';
|
|
3
3
|
import { E as EngineError } from './EngineError-Ce1lPkjZ.js';
|
|
4
|
-
import { D as DiagnosticPipeline } from './pipeline-
|
|
4
|
+
import { D as DiagnosticPipeline } from './pipeline-BH7BFOTJ.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Create a new VM instance with the given opcode registry and configurable limits.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { V as Value } from './Value-
|
|
2
|
-
import { U as UserFunctionDef, A as AnonymousBodyDef, a as BytecodeProgram } from './BytecodeBuilder-
|
|
1
|
+
import { V as Value } from './Value-D1XlMwe2.cjs';
|
|
2
|
+
import { U as UserFunctionDef, A as AnonymousBodyDef, a as BytecodeProgram } from './BytecodeBuilder-BGq9ZiO3.cjs';
|
|
3
3
|
import { E as EngineError } from './EngineError-Ce1lPkjZ.cjs';
|
|
4
|
-
import { D as DiagnosticPipeline } from './pipeline-
|
|
4
|
+
import { D as DiagnosticPipeline } from './pipeline-DY0rhgQG.cjs';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Create a new VM instance with the given opcode registry and configurable limits.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { V as Value } from './Value-
|
|
2
|
-
import { V as VM } from './ScopeManager-
|
|
3
|
-
import { U as UserFunctionDef } from './BytecodeBuilder-
|
|
1
|
+
import { V as Value } from './Value-D1XlMwe2.js';
|
|
2
|
+
import { V as VM } from './ScopeManager-BkbDXK_R.js';
|
|
3
|
+
import { U as UserFunctionDef } from './BytecodeBuilder-BGq9ZiO3.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* A point-in-time snapshot of VM variable state.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { V as Value } from './Value-
|
|
2
|
-
import { V as VM } from './ScopeManager-
|
|
3
|
-
import { U as UserFunctionDef } from './BytecodeBuilder-
|
|
1
|
+
import { V as Value } from './Value-D1XlMwe2.cjs';
|
|
2
|
+
import { V as VM } from './ScopeManager-Cvgypcu4.cjs';
|
|
3
|
+
import { U as UserFunctionDef } from './BytecodeBuilder-BGq9ZiO3.cjs';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* A point-in-time snapshot of VM variable state.
|
|
@@ -243,6 +243,36 @@ interface SplitData {
|
|
|
243
243
|
readonly unit?: string;
|
|
244
244
|
readonly shares: readonly SplitShare[];
|
|
245
245
|
}
|
|
246
|
+
/**
|
|
247
|
+
* What a {@link ChartData} draws, and therefore how a host renders it: a
|
|
248
|
+
* `sparkline` is a tiny inline line with no axes, a `plot` a framed curve over a
|
|
249
|
+
* domain. New kinds (a bar chart, a scatter) are added here, and every host that
|
|
250
|
+
* switches on `kind` keeps working for the ones it already knows.
|
|
251
|
+
*/
|
|
252
|
+
type ChartKind = "sparkline" | "plot";
|
|
253
|
+
/**
|
|
254
|
+
* A chart specification: the DATA to draw, never pixels. One shape holds every
|
|
255
|
+
* visual the engine produces, `[1,2,3] as sparkline` and `plot sin(x) from 0 to
|
|
256
|
+
* 2pi` alike, so a host reads `kind` to choose a renderer and draws `points`
|
|
257
|
+
* scaled to `domain` × `range`. The engine brings the numbers; the developer
|
|
258
|
+
* brings the charting library. `label` is the plain-text answer a reader without
|
|
259
|
+
* a canvas still gets. A sparkline's points are `(index, value)`; a plot's are
|
|
260
|
+
* `(x, y)`. Lives in a {@link Value}'s `value` slot exactly as
|
|
261
|
+
* {@link MatrixData}/{@link ColourData} do (issues #186, #187).
|
|
262
|
+
*/
|
|
263
|
+
interface ChartData {
|
|
264
|
+
readonly kind: ChartKind;
|
|
265
|
+
/** The points to draw, `(x, y)`. A sparkline indexes x from 0. */
|
|
266
|
+
readonly points: readonly (readonly [number, number])[];
|
|
267
|
+
/** The plain-text answer, e.g. `sin(x) over [0, 6.28]` or the series itself. */
|
|
268
|
+
readonly label: string;
|
|
269
|
+
/** The x-axis extent `[min, max]`. */
|
|
270
|
+
readonly domain: readonly [number, number];
|
|
271
|
+
/** The y-axis extent `[min, max]`, for scaling the drawn height. */
|
|
272
|
+
readonly range: readonly [number, number];
|
|
273
|
+
/** The source expression, for a plot; absent for a sparkline. */
|
|
274
|
+
readonly expr?: string;
|
|
275
|
+
}
|
|
246
276
|
/**
|
|
247
277
|
* Discriminated union tag for {@link Value} objects.
|
|
248
278
|
*
|
|
@@ -276,7 +306,9 @@ declare enum ValueType {
|
|
|
276
306
|
/** A colour (hex/rgb/hsl/named). Value is {@link ColourData}. */
|
|
277
307
|
Colour = 14,
|
|
278
308
|
/** A per-person bill split (`split $180 between 4`). Value is {@link SplitData}. */
|
|
279
|
-
Split = 15
|
|
309
|
+
Split = 15,
|
|
310
|
+
/** A chart to draw (`[1,2,3] as sparkline`, `plot sin(x) from 0 to 2pi`). Value is {@link ChartData}. */
|
|
311
|
+
Chart = 16
|
|
280
312
|
}
|
|
281
313
|
/**
|
|
282
314
|
* Universal runtime value for the solve-js VM.
|
|
@@ -292,7 +324,7 @@ declare enum ValueType {
|
|
|
292
324
|
declare class Value {
|
|
293
325
|
private _cachedNumber;
|
|
294
326
|
type: ValueType;
|
|
295
|
-
value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | SymbolicNode;
|
|
327
|
+
value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | ChartData | SymbolicNode;
|
|
296
328
|
unit?: string;
|
|
297
329
|
/** Set by async resolvers when a fetch timed out, the result is a fallback (typically 0). */
|
|
298
330
|
timedOut?: boolean;
|
|
@@ -361,12 +393,12 @@ declare class Value {
|
|
|
361
393
|
* by {@link recycle} alongside the other sidecars.
|
|
362
394
|
*/
|
|
363
395
|
decimalPlaces?: number;
|
|
364
|
-
constructor(type: ValueType, value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | SymbolicNode, unit?: string);
|
|
396
|
+
constructor(type: ValueType, value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | ChartData | SymbolicNode, unit?: string);
|
|
365
397
|
/**
|
|
366
398
|
* Phase 5.3: Reset all fields for arena reuse.
|
|
367
399
|
* Called by ValueArena.acquire(), zero allocation, just field assignment.
|
|
368
400
|
*/
|
|
369
|
-
recycle(type: ValueType, value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | SymbolicNode, unit?: string): void;
|
|
401
|
+
recycle(type: ValueType, value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | ChartData | SymbolicNode, unit?: string): void;
|
|
370
402
|
isNumber(): this is Value & {
|
|
371
403
|
value: number;
|
|
372
404
|
};
|
|
@@ -390,6 +422,9 @@ declare class Value {
|
|
|
390
422
|
isColour(): this is Value & {
|
|
391
423
|
value: ColourData;
|
|
392
424
|
};
|
|
425
|
+
isChart(): this is Value & {
|
|
426
|
+
value: ChartData;
|
|
427
|
+
};
|
|
393
428
|
isSymbolic(): this is Value & {
|
|
394
429
|
value: SymbolicNode;
|
|
395
430
|
};
|
|
@@ -481,4 +516,4 @@ declare function colVectorValue(data: readonly number[]): Value;
|
|
|
481
516
|
/** Create a Range value, a first-class integer range `min:max`, both bounds inclusive. */
|
|
482
517
|
declare function rangeValue(min: number, max: number): Value;
|
|
483
518
|
|
|
484
|
-
export { type ColourData as C, type MatrixData as M, type RangeData as R, type SplitData as S, Value as V, type MatrixEntry as a, ValueType as b, bigIntValue as c, colVectorValue as d, rowVectorValue as e, type
|
|
519
|
+
export { type ColourData as C, type MatrixData as M, type RangeData as R, type SplitData as S, Value as V, type MatrixEntry as a, ValueType as b, bigIntValue as c, colVectorValue as d, rowVectorValue as e, type ChartData as f, type SymbolicNode as g, hexValue as h, type ColourFormat as i, matrixValue as m, numberValue as n, rangeValue as r, stringValue as s, uomValue as u };
|
|
@@ -243,6 +243,36 @@ interface SplitData {
|
|
|
243
243
|
readonly unit?: string;
|
|
244
244
|
readonly shares: readonly SplitShare[];
|
|
245
245
|
}
|
|
246
|
+
/**
|
|
247
|
+
* What a {@link ChartData} draws, and therefore how a host renders it: a
|
|
248
|
+
* `sparkline` is a tiny inline line with no axes, a `plot` a framed curve over a
|
|
249
|
+
* domain. New kinds (a bar chart, a scatter) are added here, and every host that
|
|
250
|
+
* switches on `kind` keeps working for the ones it already knows.
|
|
251
|
+
*/
|
|
252
|
+
type ChartKind = "sparkline" | "plot";
|
|
253
|
+
/**
|
|
254
|
+
* A chart specification: the DATA to draw, never pixels. One shape holds every
|
|
255
|
+
* visual the engine produces, `[1,2,3] as sparkline` and `plot sin(x) from 0 to
|
|
256
|
+
* 2pi` alike, so a host reads `kind` to choose a renderer and draws `points`
|
|
257
|
+
* scaled to `domain` × `range`. The engine brings the numbers; the developer
|
|
258
|
+
* brings the charting library. `label` is the plain-text answer a reader without
|
|
259
|
+
* a canvas still gets. A sparkline's points are `(index, value)`; a plot's are
|
|
260
|
+
* `(x, y)`. Lives in a {@link Value}'s `value` slot exactly as
|
|
261
|
+
* {@link MatrixData}/{@link ColourData} do (issues #186, #187).
|
|
262
|
+
*/
|
|
263
|
+
interface ChartData {
|
|
264
|
+
readonly kind: ChartKind;
|
|
265
|
+
/** The points to draw, `(x, y)`. A sparkline indexes x from 0. */
|
|
266
|
+
readonly points: readonly (readonly [number, number])[];
|
|
267
|
+
/** The plain-text answer, e.g. `sin(x) over [0, 6.28]` or the series itself. */
|
|
268
|
+
readonly label: string;
|
|
269
|
+
/** The x-axis extent `[min, max]`. */
|
|
270
|
+
readonly domain: readonly [number, number];
|
|
271
|
+
/** The y-axis extent `[min, max]`, for scaling the drawn height. */
|
|
272
|
+
readonly range: readonly [number, number];
|
|
273
|
+
/** The source expression, for a plot; absent for a sparkline. */
|
|
274
|
+
readonly expr?: string;
|
|
275
|
+
}
|
|
246
276
|
/**
|
|
247
277
|
* Discriminated union tag for {@link Value} objects.
|
|
248
278
|
*
|
|
@@ -276,7 +306,9 @@ declare enum ValueType {
|
|
|
276
306
|
/** A colour (hex/rgb/hsl/named). Value is {@link ColourData}. */
|
|
277
307
|
Colour = 14,
|
|
278
308
|
/** A per-person bill split (`split $180 between 4`). Value is {@link SplitData}. */
|
|
279
|
-
Split = 15
|
|
309
|
+
Split = 15,
|
|
310
|
+
/** A chart to draw (`[1,2,3] as sparkline`, `plot sin(x) from 0 to 2pi`). Value is {@link ChartData}. */
|
|
311
|
+
Chart = 16
|
|
280
312
|
}
|
|
281
313
|
/**
|
|
282
314
|
* Universal runtime value for the solve-js VM.
|
|
@@ -292,7 +324,7 @@ declare enum ValueType {
|
|
|
292
324
|
declare class Value {
|
|
293
325
|
private _cachedNumber;
|
|
294
326
|
type: ValueType;
|
|
295
|
-
value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | SymbolicNode;
|
|
327
|
+
value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | ChartData | SymbolicNode;
|
|
296
328
|
unit?: string;
|
|
297
329
|
/** Set by async resolvers when a fetch timed out, the result is a fallback (typically 0). */
|
|
298
330
|
timedOut?: boolean;
|
|
@@ -361,12 +393,12 @@ declare class Value {
|
|
|
361
393
|
* by {@link recycle} alongside the other sidecars.
|
|
362
394
|
*/
|
|
363
395
|
decimalPlaces?: number;
|
|
364
|
-
constructor(type: ValueType, value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | SymbolicNode, unit?: string);
|
|
396
|
+
constructor(type: ValueType, value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | ChartData | SymbolicNode, unit?: string);
|
|
365
397
|
/**
|
|
366
398
|
* Phase 5.3: Reset all fields for arena reuse.
|
|
367
399
|
* Called by ValueArena.acquire(), zero allocation, just field assignment.
|
|
368
400
|
*/
|
|
369
|
-
recycle(type: ValueType, value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | SymbolicNode, unit?: string): void;
|
|
401
|
+
recycle(type: ValueType, value: number | bigint | string | boolean | MatrixData | RangeData | ColourData | SplitData | ChartData | SymbolicNode, unit?: string): void;
|
|
370
402
|
isNumber(): this is Value & {
|
|
371
403
|
value: number;
|
|
372
404
|
};
|
|
@@ -390,6 +422,9 @@ declare class Value {
|
|
|
390
422
|
isColour(): this is Value & {
|
|
391
423
|
value: ColourData;
|
|
392
424
|
};
|
|
425
|
+
isChart(): this is Value & {
|
|
426
|
+
value: ChartData;
|
|
427
|
+
};
|
|
393
428
|
isSymbolic(): this is Value & {
|
|
394
429
|
value: SymbolicNode;
|
|
395
430
|
};
|
|
@@ -481,4 +516,4 @@ declare function colVectorValue(data: readonly number[]): Value;
|
|
|
481
516
|
/** Create a Range value, a first-class integer range `min:max`, both bounds inclusive. */
|
|
482
517
|
declare function rangeValue(min: number, max: number): Value;
|
|
483
518
|
|
|
484
|
-
export { type ColourData as C, type MatrixData as M, type RangeData as R, type SplitData as S, Value as V, type MatrixEntry as a, ValueType as b, bigIntValue as c, colVectorValue as d, rowVectorValue as e, type
|
|
519
|
+
export { type ColourData as C, type MatrixData as M, type RangeData as R, type SplitData as S, Value as V, type MatrixEntry as a, ValueType as b, bigIntValue as c, colVectorValue as d, rowVectorValue as e, type ChartData as f, type SymbolicNode as g, hexValue as h, type ColourFormat as i, matrixValue as m, numberValue as n, rangeValue as r, stringValue as s, uomValue as u };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunk4BZIYU7S_cjs=require('./chunk-4BZIYU7S.cjs'),chunk5FGOIDLS_cjs=require('./chunk-5FGOIDLS.cjs');var u=[10,11,12,13,14,16,60,61,62,63,150,159,95,96],E=[50,51,151,152,160],m=[157,158],L=(()=>{let r=new Array(256).fill(0);for(let e of u)r[e]=1;for(let e of E)r[e]=2;for(let e of m)r[e]=3;return r})();[...u,...E,...m];function C(r,e){return e+1+(L[r[e]]??0)}var R="currency",A=class{constructor(e){this.namespace=R;this.exchange=e??chunk4BZIYU7S_cjs.b;}preflight(e,N,U,S,y){let{opcodes:c,strings:l}=N,f=c.length,o=0,i=-1,p=-1;for(;o<f;){let t=c[o];if(t===13&&(p=i,i=c[o+1]),(t===84||t===81||t===20||t===21||t===22||t===23)&&p>=0&&i>=0){let n=l[p],s=l[i];if(this.exchange.isCurrency(n)&&this.exchange.isCurrency(s)&&n.toUpperCase()!==s.toUpperCase()&&this.exchange.getRateSync(n,s)===null){let d=n.toUpperCase(),I=s.toUpperCase(),a=[R,d,I];if(y.getQueryData(a)!==void 0){o++;continue}let g=y.fetchQuery({queryKey:a,queryFn:({signal:h})=>this.exchange.getRate(n,s,h).then(T=>chunk5FGOIDLS_cjs.n(T)),staleTime:300*1e3});return {queryKey:a.join(":"),resolver:g,packageId:U,signal:S,metadata:{fromUnit:n,toUnit:s}}}}o=C(c,o);}return null}destroy(){}};exports.a=C;exports.b=A;//# sourceMappingURL=chunk-3AVWA5IZ.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-3AVWA5IZ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/parser/OperandWidth.ts","../src/uom/CurrencyResolver.ts"],"names":["ONE_OPERAND","TWO_OPERANDS","THREE_OPERANDS","OPERAND_BYTES","widths","op","nextInstruction","opcodes","index","CURRENCY_NS","CurrencyAsyncResolver","exchange","currencyExchangeService","_tokens","bytecode","packageId","signal","queryClient","strings","len","i","lastStrIdx","prevStr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AAAA,CAAWC,CAAO,CAAA,CACjD,GAAIT,CAAAA,CAAY,YAAA,CAAaU,CAAQ,CAAA,GAAM,OAAW,CACrDP,CAAAA,EAAAA,CACA,QACD,CAGA,IAAMQ,CAAAA,CAAWX,CAAAA,CAAY,UAAA,CAAW,CACvC,QAAA,CAAUU,CAAAA,CACV,OAAA,CAAS,CAAC,CAAE,MAAA,CAAQE,CAAQ,IACpB,IAAA,CAAK,QAAA,CAAS,OAAA,CAAQN,CAAAA,CAAUC,CAAAA,CAAQK,CAAO,CAAA,CAAE,IAAA,CAAMC,CAAAA,EAASC,mBAAAA,CAAYD,CAAI,CAAC,CAAA,CAEzF,SAAA,CAAW,GAAA,CAAS,GACrB,CAAC,CAAA,CAED,OAAO,CAAE,QAAA,CAAUH,CAAAA,CAAS,IAAA,CAAK,GAAG,CAAA,CAAG,QAAA,CAAAC,CAAAA,CAAU,SAAA,CAAAb,CAAAA,CAAW,MAAA,CAAAC,CAAAA,CAAQ,QAAA,CAAU,CAAE,SAAAO,CAAAA,CAAU,MAAA,CAAAC,CAAO,CAAE,CACpG,CAEF,CAKDJ,CAAAA,CAAId,EAAgBC,CAAAA,CAASa,CAAC,EAC/B,CAEA,OAAO,IACR,CAEA,OAAA,EAAgB,CAEhB,CACD","file":"chunk-3AVWA5IZ.cjs","sourcesContent":["/**\n * How many operand bytes follow each opcode, and how to step over one.\n *\n * Anything walking a bytecode stream without executing it needs this: the\n * resolver preflight scanners look for specific opcodes and must skip past\n * everything else without mistaking an operand byte for an instruction.\n *\n * It used to be a hand-copied switch in each of those scanners. They had\n * already drifted: two counted `CALL_PLUGIN` as three bytes wide and the third\n * omitted it from that arm, so a stream containing one desynchronised there and\n * every opcode after it was read at the wrong offset. Adding an opcode meant\n * remembering every copy, and nothing checked that you had.\n *\n * `__tests__/parser/OperandWidth.spec.ts` asserts every opcode has a width, so\n * a new one fails a test rather than silently defaulting to zero operands.\n */\n\nimport { OpCode } from \"@solve-js/parser/OpCode\";\n\n/**\n * Opcodes taking one operand byte.\n *\n * A constant-pool index, or a variable-name index.\n */\nconst ONE_OPERAND: readonly OpCode[] = [\n\tOpCode.PUSH_NUMBER,\n\tOpCode.PUSH_BIGINT,\n\tOpCode.PUSH_HEX,\n\tOpCode.PUSH_STRING,\n\tOpCode.PUSH_BOOLEAN,\n\t// Its operand is a string-pool index holding the exact decimal text, so a\n\t// scanner must step over one byte exactly as it does for PUSH_STRING.\n\tOpCode.PUSH_DECIMAL,\n\tOpCode.LOAD_VAR,\n\tOpCode.STORE_VAR,\n\tOpCode.LOAD_GLOBAL_VAR,\n\tOpCode.STORE_GLOBAL_VAR,\n\tOpCode.DEFINE_USER_FUNCTION,\n\tOpCode.BIND_UNKNOWN,\n\t// Its operand is a constant-pool index, like PUSH_NUMBER's: the epoch-ms\n\t// was resolved at parse time and stored in `numbers`. Omitting it made\n\t// every scanner read that index byte as an opcode, so an ordinary date\n\t// literal desynchronised the whole preflight walk.\n\tOpCode.DATE_LITERAL,\n\t// One byte, the offset direction (0 forward, 1 backward) for \"N working\n\t// days after/before/from <date>\". See WorkdayOffsetParselet. DATE_WORKDAYS_BETWEEN\n\t// takes no operand and so is not listed here.\n\tOpCode.DATE_WORKDAY_OFFSET,\n];\n\n/**\n * Opcodes taking two operand bytes.\n *\n * A callable index plus an argument count, or a matrix's row and column counts.\n */\nconst TWO_OPERANDS: readonly OpCode[] = [\n\tOpCode.CALL_PLUGIN,\n\tOpCode.CALL_BUILTIN,\n\tOpCode.CALL_USER_FUNCTION,\n\tOpCode.MAT_NEW,\n\t// A body index plus the pooled source-expression string.\n\tOpCode.PLOT_INVOKE,\n];\n\n/**\n * Opcodes taking three operand bytes.\n *\n * The map and reduce invocations, which carry a body index alongside their\n * other operands.\n */\nconst THREE_OPERANDS: readonly OpCode[] = [OpCode.MAP_INVOKE, OpCode.REDUCE_INVOKE];\n\n/**\n * Operand byte count for every opcode, indexed by opcode value.\n *\n * A dense array rather than a map, because the preflight scanners run on every\n * keystroke and this is read once per instruction.\n */\nexport const OPERAND_BYTES: readonly number[] = (() => {\n\tconst widths = new Array<number>(256).fill(0);\n\tfor (const op of ONE_OPERAND) widths[op] = 1;\n\tfor (const op of TWO_OPERANDS) widths[op] = 2;\n\tfor (const op of THREE_OPERANDS) widths[op] = 3;\n\treturn widths;\n})();\n\n/**\n * Every opcode that takes at least one operand.\n *\n * Exported so a test can assert the table stays complete as opcodes are added.\n */\nexport const OPCODES_WITH_OPERANDS: readonly OpCode[] = [\n\t...ONE_OPERAND,\n\t...TWO_OPERANDS,\n\t...THREE_OPERANDS,\n];\n\n/**\n * Offset of the instruction after the one at `index`.\n *\n * @param opcodes - The bytecode stream.\n * @param index - Offset of an opcode, not of an operand byte. Passing an\n * operand offset yields nonsense, which is the failure mode this exists to\n * prevent: a caller stepping by hand and getting one width wrong reads the rest\n * of the stream misaligned.\n * @returns Offset of the next opcode. May be past the end when the instruction\n * at `index` is the last one, so callers loop while it is under `opcodes.length`.\n */\nexport function nextInstruction(opcodes: Uint8Array, index: number): number {\n\treturn index + 1 + (OPERAND_BYTES[opcodes[index]] ?? 0);\n}\n","/**\n * Currency async resolver, bridges CurrencyExchangeService to the\n * IAsyncResolver interface for the Suspense architecture.\n *\n * Uses TanStack Query (injected via queryClient) as the single cache layer.\n */\nimport type { QueryClient } from \"@tanstack/query-core\";\nimport type { Token } from \"@solve-js/lexer\";\nimport type { BytecodeProgram } from \"@solve-js/parser/BytecodeBuilder\";\nimport { OpCode } from \"@solve-js/parser/OpCode\";\nimport { numberValue } from \"@solve-js/vm/Value\";\nimport {\n\tcurrencyExchangeService,\n\tCurrencyExchangeService,\n} from \"@solve-js/uom/CurrencyExchange\";\nimport type { IAsyncResolver, AsyncCheckResult } from \"@solve-js/resolvers/ResolverRegistry\";\nimport { nextInstruction } from \"@solve-js/parser/OperandWidth\";\n\nconst CURRENCY_NS = \"currency\";\n\n/**\n * Fetches exchange rates before the VM runs, so a conversion has real numbers.\n *\n * Until rates arrive the line evaluates to a pending value rather than a\n * guessed one, and re-evaluates when they land.\n */\nexport class CurrencyAsyncResolver implements IAsyncResolver {\n\treadonly namespace = CURRENCY_NS;\n\n\tprivate exchange: CurrencyExchangeService;\n\n\tconstructor(exchange?: CurrencyExchangeService) {\n\t\tthis.exchange = exchange ?? currencyExchangeService;\n\t}\n\n\tpreflight(_tokens: Token[], bytecode: BytecodeProgram, packageId: string, signal: AbortSignal, queryClient: QueryClient): AsyncCheckResult | null {\n\t\tconst { opcodes, strings } = bytecode;\n\t\tconst len = opcodes.length;\n\t\tlet i = 0;\n\n\t\tlet lastStrIdx = -1;\n\t\tlet prevStrIdx = -1;\n\n\t\twhile (i < len) {\n\t\t\tconst op = opcodes[i] as OpCode;\n\n\t\t\tif (op === OpCode.PUSH_STRING) {\n\t\t\t\tprevStrIdx = lastStrIdx;\n\t\t\t\tlastStrIdx = opcodes[i + 1];\n\t\t\t}\n\n\t\t\t// Explicit \"X to Y\"/\"X in Y\" conversions (UOM_CONVERT_IN/_TO) are\n\t\t\t// the obvious case, but arithmetic directly on two differently-\n\t\t\t// denominated currency literals, \"0.01 BTC + 1 ETH\", needs the\n\t\t\t// exact same preflight fetch and previously never got it: this\n\t\t\t// scanner only looked for the CONVERT opcodes, so ADD/SUB/MUL/DIV\n\t\t\t// between two currency UOMs skipped preflight entirely, ran with\n\t\t\t// no cached rate, and fell through to the VM's silent-wrong-math\n\t\t\t// fallback instead of ever reaching a network fetch.\n\t\t\tconst isCurrencyCombiningOp =\n\t\t\t\top === OpCode.UOM_CONVERT_IN || op === OpCode.UOM_CONVERT_TO ||\n\t\t\t\top === OpCode.ADD || op === OpCode.SUB || op === OpCode.MUL || op === OpCode.DIV;\n\t\t\tif (isCurrencyCombiningOp) {\n\t\t\t\tif (prevStrIdx >= 0 && lastStrIdx >= 0) {\n\t\t\t\t\tconst fromUnit = strings[prevStrIdx];\n\t\t\t\t\tconst toUnit = strings[lastStrIdx];\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tthis.exchange.isCurrency(fromUnit) &&\n\t\t\t\t\t\tthis.exchange.isCurrency(toUnit) &&\n\t\t\t\t\t\tfromUnit.toUpperCase() !== toUnit.toUpperCase()\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst syncRate = this.exchange.getRateSync(fromUnit, toUnit);\n\t\t\t\t\t\tif (syncRate === null) {\n\t\t\t\t\t\t\tconst fromUpper = fromUnit.toUpperCase();\n\t\t\t\t\t\t\tconst toUpper = toUnit.toUpperCase();\n\n\t\t\t\t\t\t\t// Check TanStack Query cache\n\t\t\t\t\t\t\tconst cacheKey = [CURRENCY_NS, fromUpper, toUpper];\n\t\t\t\t\t\t\tif (queryClient.getQueryData(cacheKey) !== undefined) {\n\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Fetch via TanStack Query (dedup + retry automatic)\n\t\t\t\t\t\t\tconst resolver = queryClient.fetchQuery({\n\t\t\t\t\t\t\t\tqueryKey: cacheKey,\n\t\t\t\t\t\t\t\tqueryFn: ({ signal: qSignal }) => {\n\t\t\t\t\t\t\t\t\treturn this.exchange.getRate(fromUnit, toUnit, qSignal).then((rate) => numberValue(rate));\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tstaleTime: 5 * 60 * 1000,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\treturn { queryKey: cacheKey.join(\":\"), resolver, packageId, signal, metadata: { fromUnit, toUnit } };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Step over this instruction and its operands. Shared table, because\n\t\t\t// three hand-copied versions of this had already drifted.\n\t\t\ti = nextInstruction(opcodes, i);\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tdestroy(): void {\n\t\t// Cache cleared by ResolverRegistry.unregister() via removeQueries({ queryKey: [\"currency\"] })\n\t}\n}\n"]}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';var chunkR2SZFJTT_cjs=require('./chunk-R2SZFJTT.cjs'),chunkESUN2THE_cjs=require('./chunk-ESUN2THE.cjs'),chunkZOOVGXMK_cjs=require('./chunk-ZOOVGXMK.cjs'),chunk5FGOIDLS_cjs=require('./chunk-5FGOIDLS.cjs'),chunkMSYX32PF_cjs=require('./chunk-MSYX32PF.cjs');var b={floatResult:{decimalPlaces:2,enableSeperator:true},numberResult:{decimalSeparatorLocale:"en-US"},hexResult:{enablePadding:false,paddingZeros:0},unitOfMeasurementResult:{decimalPlaces:2},percentageResult:{decimalPlaces:2},dateResult:{format:"long"}};function D(t,r,o,n){let e=o.floatResult.enableSeperator,i=o.numberResult.decimalSeparatorLocale;if(n!==void 0&&Number.isFinite(t)){let c=t.toLocaleString(i||"en-US",{minimumFractionDigits:n,maximumFractionDigits:n,useGrouping:e});return `${r.display.resultPrefix}${c}`}let a=o.floatResult.decimalPlaces,s=chunkR2SZFJTT_cjs.a(t,a,e,i);return `${r.display.resultPrefix}${s}`}function F(t,r,o,n){let e=n.floatResult.decimalPlaces,i=n.floatResult.enableSeperator,a=n.numberResult.decimalSeparatorLocale||"en-US",s=Math.max(e,1),c=t.toLocaleString(a,{useGrouping:i,minimumFractionDigits:0,maximumFractionDigits:e}),u=Math.abs(r).toLocaleString(a,{useGrouping:i,minimumFractionDigits:1,maximumFractionDigits:s});return `${o.display.resultPrefix}${c} \xB1 ${u}`}function R(t,r,o){if(typeof t=="number"&&!Number.isFinite(t))return `= ${t}`;let n=typeof t=="bigint"?t<0n:t<0,e=n?"-":"",i=c=>typeof t=="bigint"?(n?-t:t).toString(c):Math.abs(Math.trunc(t)).toString(c);if(o==="bin")return `= ${e}0b${i(2)}`;if(o==="oct")return `= ${e}0o${i(8)}`;let a=r.hexResult.enablePadding?r.hexResult.paddingZeros:0,s=i(16).toUpperCase().padStart(a,"0");return `= ${e}0x${s}`}var L=2e4;function P(t){let r=t<0n?-t:t;if(Number.isFinite(Number(r)))return `= ${t}`;let o=r.toString(16).length*4;if(o*Math.LN2/Math.LN10<=L)return `= ${t}`;let n=o*Math.LN2/Math.LN10,e=Math.floor(n),i=Math.pow(10,n-e);return `= ${t<0n?"-":""}~${i.toFixed(3)}e+${e} (an exact integer of about ${(e+1).toLocaleString("en-US")} digits, too large to print)`}function T(t){return `= ${t}`}function I(t){return `= ${t}`}function w(t,r,o){let n=new Date(t),e=o.dateResult?.format??"long",i=n.getHours()===0&&n.getMinutes()===0&&n.getSeconds()===0&&n.getMilliseconds()===0;if(e==="long"){let g=n.toLocaleDateString(r.code,{weekday:"long",year:"numeric",month:"long",day:"numeric"});return i?`= ${g}`:`= ${g}, ${n.toLocaleTimeString(r.code)}`}let a=g=>String(g).padStart(2,"0"),s=n.getFullYear(),c=a(n.getMonth()+1),u=a(n.getDate()),m;if(e==="iso"?m=`${s}-${c}-${u}`:e==="dmy"?m=`${u}/${c}/${s}`:m=`${c}/${u}/${s}`,i)return `= ${m}`;let l=`${a(n.getHours())}:${a(n.getMinutes())}:${a(n.getSeconds())}`;return e==="iso"?`= ${m}T${l}`:`= ${m} ${l}`}function N(t){let r=t<0?"-":"",o=Math.round(Math.abs(t)/1e3),n=Math.floor(o/3600),e=Math.floor(o%3600/60),i=o%60,a=String(e).padStart(2,"0");if(i===0)return `${r}${n}:${a}`;let s=String(i).padStart(2,"0");return `${r}${n}:${a}:${s}`}function U(t,r,o,n,e){if(r==="ms")return `= ${N(t)}`;let i=n.unitOfMeasurementResult.decimalPlaces,s=r&&["days","weeks","months","years","hours","minutes","seconds","day","week","month","year","hour","minute","second"].includes(r),c;s&&t===Math.floor(t)?c=t.toString():c=t.toFixed(i);let u=r?chunkZOOVGXMK_cjs.ua[r.toUpperCase()]:void 0;if(u){let l=e?chunkZOOVGXMK_cjs.sa(e,i):c,g=u.spaced?" ":"";return `= ${u.position==="prefix"?`${u.symbol}${g}${l}`:`${l}${g}${u.symbol}`}`}return `= ${e?chunkZOOVGXMK_cjs.sa(e,i):c} ${r||""}`.trim()}function M(t,r){if(typeof t=="boolean")return t?"true":"false";if(typeof t=="object"&&t!==null)return chunkZOOVGXMK_cjs.R(t);let o=r.floatResult.decimalPlaces,n=r.floatResult.enableSeperator,e=r.numberResult.decimalSeparatorLocale;return chunkR2SZFJTT_cjs.a(t,o,n,e)}function C(t,r,o){let n=chunkZOOVGXMK_cjs.Z(t),e=[];for(let i=0;i<t.rows;i++){let a=[];for(let s=0;s<t.cols;s++)a.push(M(n[i*t.cols+s],o));e.push(a.join(", "));}return `${r.display.resultPrefix}[${e.join("; ")}]`}function Q(t,r){let o=r||b,n=chunkZOOVGXMK_cjs.Z(t),e=[];for(let a=0;a<t.rows;a++){let s=[];for(let c=0;c<t.cols;c++)s.push(M(n[a*t.cols+c],o));e.push(s);}let i=[];for(let a=0;a<t.cols;a++){let s=0;for(let c=0;c<t.rows;c++)s=Math.max(s,e[c][a].length);i.push(s);}return e.map(a=>`[ ${a.map((s,c)=>s.padStart(i[c])).join(" ")} ]`).join(`
|
|
2
|
+
`)}function E(t,r,o){return `${o.display.resultPrefix}${t}:${r}`}function j(t,r,o){let n=o.percentageResult.decimalPlaces;return `= ${(t*100).toFixed(n)}${r.display.percentageSuffix}`}function A(t,r){return `= ${t} ${r||""}`.trim()}function G(t,r,o){let n=r.display.resultPrefix,e=u=>{let m=t.unit!==void 0?new chunk5FGOIDLS_cjs.m(6,u.value,t.unit):new chunk5FGOIDLS_cjs.m(0,u.value);m.exact=u.exact;let l=O(m,o);return l.startsWith(n)?l.slice(n.length):l},[i,a]=t.shares,s=`${e(i)} each`;if(a===void 0)return `${n}${s}`;let c=a.count===1?"share":"shares";return `${n}${s}, with ${a.count} ${c} paying ${e(a)}`}function O(t,r){let o=r||b,n=o.numberResult.decimalSeparatorLocale||"en",e=chunkMSYX32PF_cjs.a(n);switch(t.type){case 0:return t.uncertainty!==void 0?F(t.value,t.uncertainty,e,o):D(t.value,e,o,t.decimalPlaces);case 1:return R(t.value,o,t.unit);case 2:return P(t.value);case 3:return T(t.value);case 10:return I(t.value);case 4:return w(t.value,e,o);case 6:return U(t.value,t.unit,e,o,t.exact);case 7:return C(t.value,e,o);case 8:{let i=t.value;return E(i.min,i.max,e)}case 14:return `${e.display.resultPrefix}${chunkESUN2THE_cjs.g(t.value)}`;case 15:return G(t.value,e,o);case 16:return `${e.display.resultPrefix}${t.value.label}`;case 9:return chunkZOOVGXMK_cjs.R(t.value);case 5:return j(t.value,e,o);case 11:return A(t.value,t.unit);case 13:return t.unit??String(t.value);default:return `= ${String(t.value)}`}}exports.a=b;exports.b=Q;exports.c=O;//# sourceMappingURL=chunk-3DD2RVBI.cjs.map
|
|
3
|
+
//# sourceMappingURL=chunk-3DD2RVBI.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/format/FormattingSettings.ts","../src/format/FormatEngine.ts"],"names":["DEFAULT_FORMATTING_SETTINGS","formatNumber","value","locale","settings","decimalPlaces","sep","loc","formatted","dp","autoFormatIntegerOrFloat","formatUncertain","center","uncertainty","useGrouping","spreadMax","centerText","spreadText","formatHex","base","negative","sign","digits","radix","padding","hex","MAX_DISPLAYED_BIGINT_DIGITS","formatBigInt","magnitude","bits","log10","exponent","mantissa","formatString","formatBoolean","formatDatetime","d","format","isMidnight","dateStr","p2","n","year","month","day","datePart","time","formatMsDuration","ms","totalSeconds","hours","minutes","seconds","mm","ss","formatUom","unit","exact","isTimeSpan","currencyDisplay","CURRENCY_DISPLAY","moneyText","decimalToFixed","formatMatrixEntry","entry","formatSymbolic","formatMatrix","m","rowMajor","columnMajorToRowMajor","rows","r","cells","c","formatMatrixAligned","us","row","colWidth","width","cell","formatRange","min","max","formatPercentage","formatUnit","formatSplit","data","prefix","render","share","v","Value","text","formatValue","high","each","shareWord","localeCode","getLocale","formatColour"],"mappings":"2QA8CO,IAAMA,CAAAA,CAAkD,CAC7D,WAAA,CAAa,CACX,aAAA,CAAe,CAAA,CACf,eAAA,CAAiB,IACnB,CAAA,CACA,YAAA,CAAc,CACZ,sBAAA,C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CAAKA,CAAAA,CAAE,GAAA,CAAKpE,CAAM,CACzC,CACA,QACE,OAAO,CAAA,EAAGA,EAAO,OAAA,CAAQ,YAAY,CAAA,EAAGgG,mBAAAA,CAAajG,EAAM,KAAmB,CAAC,GACjF,KAAA,EAAA,CACE,OAAOmF,EAAYnF,CAAAA,CAAM,KAAA,CAAoBC,CAAAA,CAAQwE,CAAE,EACzD,KAAA,EAAA,CAGE,OAAO,GAAGxE,CAAAA,CAAO,OAAA,CAAQ,YAAY,CAAA,EAAID,CAAAA,CAAM,KAAA,CAAoB,KAAK,GAC1E,KAAA,CAAA,CACE,OAAO+D,mBAAAA,CAAe/D,CAAAA,CAAM,KAAqB,CAAA,CACnD,KAAA,CAAA,CACE,OAAOiF,CAAAA,CAAiBjF,EAAM,KAAA,CAAiBC,CAAAA,CAAQwE,CAAE,CAAA,CAC3D,KAAA,EAAA,CACE,OAAOS,CAAAA,CAAWlF,CAAAA,CAAM,KAAA,CAAiBA,CAAAA,CAAM,IAAI,CAAA,CACrD,KAAA,EAAA,CAKE,OAAOA,CAAAA,CAAM,IAAA,EAAQ,OAAOA,CAAAA,CAAM,KAAK,CAAA,CACzC,QACE,OAAO,CAAA,EAAA,EAAK,MAAA,CAAOA,EAAM,KAAK,CAAC,EACnC,CACF","file":"chunk-3DD2RVBI.cjs","sourcesContent":["/**\n * How a Datetime value is rendered.\n *\n * - `'long'`: the spelled-out form, \"Tuesday, March 10, 2026\" (the default).\n * - `'iso'`: \"2026-03-10\" (ISO 8601, with a `T`-separated time when present).\n * - `'dmy'`: \"10/03/2026\" (day first).\n * - `'mdy'`: \"03/10/2026\" (month first).\n *\n * The weekday and long month name in `'long'` are localised through the same\n * locale the number separators come from; the numeric forms are locale-neutral.\n */\nexport type DateOutputFormat = \"long\" | \"iso\" | \"dmy\" | \"mdy\";\n\n/**\n * Minimal formatting settings interface for the engine\n * This allows the engine to format values without depending on app-specific settings\n */\nexport interface FormattingSettings {\n floatResult: {\n decimalPlaces: number;\n enableSeperator: boolean;\n };\n numberResult: {\n decimalSeparatorLocale: string;\n };\n hexResult: {\n enablePadding: boolean;\n paddingZeros: number;\n };\n unitOfMeasurementResult: {\n decimalPlaces: number;\n };\n percentageResult: {\n decimalPlaces: number;\n };\n /**\n * Optional so a host that built a `FormattingSettings` before this field\n * existed still compiles; a missing `dateResult` reads as `'long'`, the\n * historic output.\n */\n dateResult?: {\n format: DateOutputFormat;\n };\n}\n\n/** Formatting used when a host supplies none. */\nexport const DEFAULT_FORMATTING_SETTINGS: FormattingSettings = {\n floatResult: {\n decimalPlaces: 2,\n enableSeperator: true,\n },\n numberResult: {\n decimalSeparatorLocale: \"en-US\",\n },\n hexResult: {\n enablePadding: false,\n paddingZeros: 0,\n },\n unitOfMeasurementResult: {\n decimalPlaces: 2,\n },\n percentageResult: {\n decimalPlaces: 2,\n },\n dateResult: {\n format: \"long\",\n },\n};\n","import { Value, ValueType, type MatrixData, type MatrixEntry, type RangeData, type ColourData, type SplitData, type SplitShare, type ChartData } from \"@solve-js/vm/Value\";\nimport { formatColour } from \"@solve-js/packages/colour/ColourMath\";\nimport { decimalToFixed, type DecimalData } from \"@solve-js/decimal\";\nimport { getLocale, type ILocale } from \"@solve-js/constants/locales\";\nimport { autoFormatIntegerOrFloat } from \"@solve-js/utilities/Number\";\nimport { FormattingSettings, DEFAULT_FORMATTING_SETTINGS } from \"./FormattingSettings\";\nimport { CURRENCY_DISPLAY } from \"@solve-js/uom/CurrencyAliases\";\nimport { columnMajorToRowMajor } from \"@solve-js/vm/MatrixOps\";\nimport { formatSymbolic, type SymbolicNode } from \"@solve-js/symbolic\";\n\nfunction formatNumber(value: number, locale: ILocale, settings: FormattingSettings, decimalPlaces?: number): string {\n const sep = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale;\n // An explicit precision (`3.14159 to 4 dp`, `round(1.5, 2)`) shows EXACTLY that\n // many places with trailing zeros kept, where the default trims them and shows\n // an integer with none. The value was already rounded to this precision when\n // it was set (see VMBuiltins' roundToPlaces, exact where an exact decimal was\n // there), so rendering it to the same place count reproduces that rounding.\n if (decimalPlaces !== undefined && Number.isFinite(value)) {\n const formatted = value.toLocaleString(loc || \"en-US\", {\n minimumFractionDigits: decimalPlaces,\n maximumFractionDigits: decimalPlaces,\n useGrouping: sep,\n });\n return `${locale.display.resultPrefix}${formatted}`;\n }\n const dp = settings.floatResult.decimalPlaces;\n const formatted = autoFormatIntegerOrFloat(value, dp, sep, loc);\n return `${locale.display.resultPrefix}${formatted}`;\n}\n\n/**\n * Renders a measurement that carries a one-sigma uncertainty as\n * `center ± spread`, e.g. `49.2 ± 2.0`.\n *\n * The center is shown the way any number is, whole numbers as integers and\n * trailing zeros trimmed, so a tolerance-free-looking center still reads\n * cleanly (\"30 ± 2.24\", not \"30.00 ± 2.24\"). The spread is shown to the same\n * decimal-place budget but always keeps at least one fractional digit, which is\n * what distinguishes it as a tolerance and gives \"± 2.0\" rather than \"± 2\".\n * Both use `Intl` with `maximumFractionDigits`, so the trailing-zero trimming is\n * locale-correct (a comma-decimal locale is not string-sliced on \".\").\n *\n * The symbol is always the `±` glyph on output, even when the input was the\n * ASCII `+/-`, since the glyph is the conventional notation and unambiguous to\n * read back.\n */\nfunction formatUncertain(center: number, uncertainty: number, locale: ILocale, settings: FormattingSettings): string {\n const dp = settings.floatResult.decimalPlaces;\n const useGrouping = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale || \"en-US\";\n // The spread needs room for at least one fractional digit, so a zero-decimal\n // budget cannot leave minimumFractionDigits above maximumFractionDigits.\n const spreadMax = Math.max(dp, 1);\n const centerText = center.toLocaleString(loc, { useGrouping, minimumFractionDigits: 0, maximumFractionDigits: dp });\n const spreadText = Math.abs(uncertainty).toLocaleString(loc, { useGrouping, minimumFractionDigits: 1, maximumFractionDigits: spreadMax });\n return `${locale.display.resultPrefix}${centerText} ± ${spreadText}`;\n}\n\n/**\n * Renders a number in whichever base it is tagged with.\n *\n * The zero padding is a hexadecimal setting and stays one. Applying it to a\n * binary rendering would pad `0b101` out to the same digit count as a hex\n * value, which is a different quantity of zeros and not what the setting asks\n * for.\n */\nfunction formatHex(value: number | bigint, settings: FormattingSettings, base?: string): string {\n // An infinity or a NaN has no digits in any base, and asking for them\n // produced `0xINFINITY`, a literal that reads back as nothing at all. Render\n // the value itself, which is what every other non-finite result shows.\n if (typeof value === \"number\" && !Number.isFinite(value)) return `= ${value}`;\n\n // Truncate and take the sign off before converting. `Number.toString(radix)`\n // does neither: it renders -255 as \"-ff\", which lands the minus inside the\n // literal as `0x-FF`, and it renders 255.7 as \"ff.b3333333333\", inventing\n // fractional hex digits for a notation that has no use for them. Both were\n // visible on `as hex` until the builtins started sharing this path.\n //\n // A bigint needs neither truncation nor a Math call, and must not be routed\n // through one: passing it to Math.trunc() throws, and converting it to a\n // double first is exactly the precision loss it is carried as a bigint to\n // avoid.\n const negative = typeof value === \"bigint\" ? value < 0n : value < 0;\n const sign = negative ? \"-\" : \"\";\n const digits = (radix: number): string =>\n typeof value === \"bigint\"\n ? (negative ? -value : value).toString(radix)\n : Math.abs(Math.trunc(value)).toString(radix);\n\n if (base === \"bin\") return `= ${sign}0b${digits(2)}`;\n if (base === \"oct\") return `= ${sign}0o${digits(8)}`;\n const padding = settings.hexResult.enablePadding ? settings.hexResult.paddingZeros : 0;\n const hex = digits(16).toUpperCase().padStart(padding, \"0\");\n return `= ${sign}0x${hex}`;\n}\n\n/**\n * How many decimal digits of an exact integer this will render in full.\n *\n * A little above the ~19,729 digits of the largest bigint the VM will build\n * (`vm/VM.ts`'s MAX_EXACT_POW_BITS / MAX_EXACT_SHIFT_BITS, 65,536 bits), so\n * every value the engine can produce through `^` or `<<` still prints exactly\n * and this ceiling only ever meets a value that came from somewhere else.\n */\nconst MAX_DISPLAYED_BIGINT_DIGITS = 20000;\n\n/**\n * Renders an exact integer, or describes it when writing it out is itself the\n * expensive operation.\n *\n * This used to be a bare `= ${value}` template, which renders whatever it is\n * handed: `1n << 100000000` took 8.5 seconds here turning a 12.5MB integer\n * into a thirty-million-character string, and a host has no way to opt out,\n * since displaying the answer is what it asked the engine for. The VM's own\n * ceiling on `<<` and `^` now stops that value existing, so this is the\n * backstop for every other way a large bigint can arrive (repeated `x * x`,\n * a Value a host built itself), and it costs one comparison for every value\n * that is not absurd.\n *\n * The digit count is estimated from the bit length rather than measured, since\n * measuring means doing the conversion this exists to avoid. Bit length comes\n * off the hexadecimal form, which is linear in the size of the value where the\n * decimal form is not.\n */\nfunction formatBigInt(value: bigint): string {\n const magnitude = value < 0n ? -value : value;\n // Every bigint a person actually reads takes this line and nothing else:\n // anything a double can hold is at most 309 digits, so it is printable\n // without measuring it at all.\n if (Number.isFinite(Number(magnitude))) return `= ${value}`;\n const bits = magnitude.toString(16).length * 4;\n if (bits * Math.LN2 / Math.LN10 <= MAX_DISPLAYED_BIGINT_DIGITS) return `= ${value}`;\n const log10 = bits * Math.LN2 / Math.LN10;\n const exponent = Math.floor(log10);\n const mantissa = Math.pow(10, log10 - exponent);\n const sign = value < 0n ? \"-\" : \"\";\n return `= ${sign}~${mantissa.toFixed(3)}e+${exponent} (an exact integer of about ${(exponent + 1).toLocaleString(\"en-US\")} digits, too large to print)`;\n}\n\nfunction formatString(value: string): string {\n return `= ${value}`;\n}\n\nfunction formatBoolean(value: boolean): string {\n return `= ${value}`;\n}\n\n/**\n * Renders a Datetime value locale-aware, the previous implementation\n * called `d.toLocaleString()` with no arguments, which always uses the JS\n * runtime's own default locale and never actually consulted `locale.code`\n * despite receiving it as a parameter (both branches of its old\n * `dateFormat === \"default\"` check were byte-for-byte identical, dead\n * groundwork for a distinction that was never implemented). Concretely,\n * this meant every configured locale (including the shipped German one)\n * always displayed weekday/month names in English. See GitHub issue #77.\n *\n * Uses `weekday`/`month`: \"long\" for a spelled-out date (\"Monday,\n * November 17, 2025\" / \"lundi 17 novembre 2025\") since that's what a\n * literal weekday name is for; a bare numeric date doesn't need\n * localizing beyond the decimal/thousands separators `formatNumber()`\n * already handles. The time-of-day portion is only appended when it's\n * not exactly local midnight, bare date literals (\"today\", \"17/11/2025\")\n * always anchor to local midnight, and showing \"00:00:00\" on every one of\n * those would be noise, not information.\n */\nfunction formatDatetime(value: number, locale: ILocale, settings: FormattingSettings): string {\n const d = new Date(value);\n const format = settings.dateResult?.format ?? \"long\";\n const isMidnight = d.getHours() === 0 && d.getMinutes() === 0 && d.getSeconds() === 0 && d.getMilliseconds() === 0;\n\n // The spelled-out default, localised through the locale's own names.\n if (format === \"long\") {\n const dateStr = d.toLocaleDateString(locale.code, { weekday: \"long\", year: \"numeric\", month: \"long\", day: \"numeric\" });\n if (isMidnight) return `= ${dateStr}`;\n return `= ${dateStr}, ${d.toLocaleTimeString(locale.code)}`;\n }\n\n // The numeric forms, built from the local calendar fields so they read the\n // same regardless of the JS runtime's own default locale.\n const p2 = (n: number) => String(n).padStart(2, \"0\");\n const year = d.getFullYear();\n const month = p2(d.getMonth() + 1);\n const day = p2(d.getDate());\n let datePart: string;\n if (format === \"iso\") datePart = `${year}-${month}-${day}`;\n else if (format === \"dmy\") datePart = `${day}/${month}/${year}`;\n else datePart = `${month}/${day}/${year}`; // mdy\n\n if (isMidnight) return `= ${datePart}`;\n const time = `${p2(d.getHours())}:${p2(d.getMinutes())}:${p2(d.getSeconds())}`;\n // ISO joins date and time with `T`; the slash forms with a space.\n return format === \"iso\" ? `= ${datePart}T${time}` : `= ${datePart} ${time}`;\n}\n\n/**\n * Renders a millisecond duration as clock-style `H:MM` (or `H:MM:SS` when\n * there's a non-zero seconds component). `ms` is never a user-typeable\n * unit (confirmed: it appears nowhere in `lexer/units.ts`), it's only\n * ever produced by subtracting two clock times/datetimes (`9:30 - 8:30`,\n * `VM.ts`'s Datetime SUB case), so this is a safe, narrow special case,\n * not a general change to how durations display.\n */\nfunction formatMsDuration(ms: number): string {\n const sign = ms < 0 ? \"-\" : \"\";\n const totalSeconds = Math.round(Math.abs(ms) / 1000);\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n const mm = String(minutes).padStart(2, \"0\");\n if (seconds === 0) return `${sign}${hours}:${mm}`;\n const ss = String(seconds).padStart(2, \"0\");\n return `${sign}${hours}:${mm}:${ss}`;\n}\n\nfunction formatUom(value: number, unit: string | undefined, locale: ILocale, settings: FormattingSettings, exact?: DecimalData): string {\n if (unit === \"ms\") return `= ${formatMsDuration(value)}`;\n\n const dp = settings.unitOfMeasurementResult.decimalPlaces;\n\n // For TimeSpan values (days, weeks, hours, etc.), format as integer if the value is a whole number\n const timeSpanUnits = [\"days\", \"weeks\", \"months\", \"years\", \"hours\", \"minutes\", \"seconds\", \"day\", \"week\", \"month\", \"year\", \"hour\", \"minute\", \"second\"];\n const isTimeSpan = unit && timeSpanUnits.includes(unit);\n\n let formatted: string;\n if (isTimeSpan && value === Math.floor(value)) {\n // For whole number TimeSpan values, format as integer\n formatted = value.toString();\n } else {\n // For other values, use the configured decimal places\n formatted = value.toFixed(dp);\n }\n\n // Currency display: symbol + culturally-conventional placement (e.g.\n // \"$100.00\" prefix vs \"100.00 kr\" suffix) instead of the generic\n // \"amount CODE\" fallback below. See uom/CurrencyAliases.ts's\n // CURRENCY_DISPLAY table for the exact set covered and the reasoning\n // behind each placement choice. Any currency code NOT in that table\n // (most of the ~150 `CurrencyExchange.isCurrency()` recognizes) falls\n // through to the unchanged \"amount CODE\" format below.\n const currencyDisplay = unit ? CURRENCY_DISPLAY[unit.toUpperCase()] : undefined;\n if (currencyDisplay) {\n // An exact money amount rounds from its decimal, not from the double: a\n // half-cent like \"$1.005\" reads as \"$1.01\" here, where \"(1.005).toFixed(2)\"\n // answers \"1.00\" because the double it is handed already sits below the\n // value the user typed. Amounts with no exact decimal (a currency\n // conversion, whose rate is a double) keep the toFixed rendering above.\n const moneyText = exact ? decimalToFixed(exact, dp) : formatted;\n const sep = currencyDisplay.spaced ? \" \" : \"\";\n const withSymbol = currencyDisplay.position === \"prefix\"\n ? `${currencyDisplay.symbol}${sep}${moneyText}`\n : `${moneyText}${sep}${currencyDisplay.symbol}`;\n return `= ${withSymbol}`;\n }\n\n // The unit is written as the symbol the value carries. There used to be a\n // `unitOfMeasurementResult.unitNames` setting here whose two branches were\n // the same expression, so it never changed anything, and it was removed\n // rather than implemented: the engine has no unit-name data to render from.\n // The generated unit table maps a spelling to [measure, ratio] only, and\n // names cannot be recovered from it, because units that differ by an OFFSET\n // share a ratio, so \"20 C\" would come back as \"20 kelvins\". A real\n // implementation needs a hand-authored name per unit plus pluralization and\n // per-locale spelling (metre against meter), which is a feature rather than\n // the repair of a dead ternary.\n //\n // An exact currency with no symbol in the display table above (one of the\n // less common ISO codes) still rounds from its decimal here, so \"1.005 UYW\"\n // reads the same way \"$1.005\" does. Non-currency Uoms never carry an exact,\n // so this leaves \"1.50 kg\" exactly as it was.\n const genericText = exact ? decimalToFixed(exact, dp) : formatted;\n return `= ${genericText} ${unit || \"\"}`.trim();\n}\n\nfunction formatMatrixEntry(entry: MatrixEntry, settings: FormattingSettings): string {\n if (typeof entry === \"boolean\") return entry ? \"true\" : \"false\";\n if (typeof entry === \"object\" && entry !== null) return formatSymbolic(entry);\n const dp = settings.floatResult.decimalPlaces;\n const sep = settings.floatResult.enableSeperator;\n const loc = settings.numberResult.decimalSeparatorLocale;\n return autoFormatIntegerOrFloat(entry, dp, sep, loc);\n}\n\n/**\n * Renders a Matrix matching its own literal syntax: a single row (1xN,\n * including plain vectors) as `[a, b, c]`, a single column (Nx1) as\n * `[a; b; c]`, and a general shape as `[r0c0, r0c1; r1c0, r1c1]`, row-major\n * textual output read back out of the column-major storage\n * (`columnMajorToRowMajor()`), matching how `[1,2;3,4]` is written.\n */\nfunction formatMatrix(m: MatrixData, locale: ILocale, settings: FormattingSettings): string {\n const rowMajor = columnMajorToRowMajor(m);\n const rows: string[] = [];\n for (let r = 0; r < m.rows; r++) {\n const cells: string[] = [];\n for (let c = 0; c < m.cols; c++) {\n cells.push(formatMatrixEntry(rowMajor[r * m.cols + c], settings));\n }\n rows.push(cells.join(\", \"));\n }\n return `${locale.display.resultPrefix}[${rows.join(\"; \")}]`;\n}\n\n/**\n * Render a matrix as a multi-line, column-aligned block: one row per line (the\n * newline is where {@link formatValue}'s compact form writes `;`), each column\n * right-padded to its widest cell, and every row wrapped in `[ ... ]`. For\n * display where a grid reads better than a line, e.g. a docs notepad or a REPL:\n *\n * ```text\n * [ 1 2 ]\n * [ 30 4 ]\n * ```\n *\n * This is deliberately separate from {@link formatValue}, whose single-line\n * matrix form stays the stable, assertable text the API and the worker DTO use.\n * A 1xN row vector is one line; an Nx1 column vector is N lines.\n */\nexport function formatMatrixAligned(m: MatrixData, settings?: FormattingSettings): string {\n const us = settings || DEFAULT_FORMATTING_SETTINGS;\n const rowMajor = columnMajorToRowMajor(m);\n const cells: string[][] = [];\n for (let r = 0; r < m.rows; r++) {\n const row: string[] = [];\n for (let c = 0; c < m.cols; c++) {\n row.push(formatMatrixEntry(rowMajor[r * m.cols + c], us));\n }\n cells.push(row);\n }\n const colWidth: number[] = [];\n for (let c = 0; c < m.cols; c++) {\n let width = 0;\n for (let r = 0; r < m.rows; r++) width = Math.max(width, cells[r][c].length);\n colWidth.push(width);\n }\n return cells\n .map((row) => `[ ${row.map((cell, c) => cell.padStart(colWidth[c])).join(\" \")} ]`)\n .join(\"\\n\");\n}\n\nfunction formatRange(min: number, max: number, locale: ILocale): string {\n return `${locale.display.resultPrefix}${min}:${max}`;\n}\n\nfunction formatPercentage(value: number, locale: ILocale, settings: FormattingSettings): string {\n // ValueType.Percentage stores a fraction (0.25 for 25%). See Value.ts's\n // documented contract and the sole producer, VM.ts's TO_PERCENTAGE opcode\n // (`right/left - 1`, e.g. 0.25 for \"800 to 1000\"). Multiply by 100 before\n // formatting; without this every percentage-change result displayed as\n // e.g. \"0.25%\" instead of \"25.00%\".\n const dp = settings.percentageResult.decimalPlaces;\n const formatted = (value * 100).toFixed(dp);\n return `= ${formatted}${locale.display.percentageSuffix}`;\n}\n\nfunction formatUnit(value: number, unit: string | undefined): string {\n return `= ${value} ${unit || \"\"}`.trim();\n}\n\n/**\n * Renders a per-person bill split: \"= $45.00 each\", or, when the division is\n * uneven, \"= $33.33 each, with 1 share paying $33.34\". Each share's amount is\n * rendered through the ordinary value formatter (a throwaway {@link Value}), so\n * a currency share honours the same symbol placement, decimal places and locale\n * as any other money and a bare share trims trailing zeros the way a plain\n * number does; the \"= \" prefix is added once, around the whole sentence, not\n * per share.\n */\nfunction formatSplit(data: SplitData, locale: ILocale, settings: FormattingSettings): string {\n const prefix = locale.display.resultPrefix;\n const render = (share: SplitShare): string => {\n const v = data.unit !== undefined\n ? new Value(ValueType.Uom, share.value, data.unit)\n : new Value(ValueType.Number, share.value);\n v.exact = share.exact;\n const text = formatValue(v, settings);\n return text.startsWith(prefix) ? text.slice(prefix.length) : text;\n };\n\n const [base, high] = data.shares;\n const each = `${render(base)} each`;\n if (high === undefined) return `${prefix}${each}`;\n const shareWord = high.count === 1 ? \"share\" : \"shares\";\n return `${prefix}${each}, with ${high.count} ${shareWord} paying ${render(high)}`;\n}\n\n/**\n * Render an evaluated {@link Value} as a display string, dispatching on\n * `value.type` to the type-specific formatter (number, hex, datetime, unit\n * of measurement, matrix, range, percentage, ...).\n *\n * Most branches produce a `\"= \"`-prefixed result string (matching the\n * plugin's inline-result convention); `ValueType.Error` is the one\n * exception, it returns the human-readable error message directly\n * (stored in `value.unit`), not an `\"= \"`-prefixed string.\n *\n * @param value - The evaluated value to format.\n * @param settings - Locale/precision/separator options; defaults to\n * {@link DEFAULT_FORMATTING_SETTINGS} when omitted.\n * @example\n * ```typescript\n * const value = engine.evaluateExpression(\"10 USD to GBP\");\n * formatValue(value); // \"= £7.85\" (exact output depends on live exchange rates)\n * ```\n */\nexport function formatValue(value: Value, settings?: FormattingSettings): string {\n const us = settings || DEFAULT_FORMATTING_SETTINGS;\n const localeCode = us.numberResult.decimalSeparatorLocale || \"en\";\n const locale = getLocale(localeCode);\n\n switch (value.type) {\n case ValueType.Number:\n // A measurement with a tolerance renders as \"center ± spread\"; every\n // other number is unchanged, so a plain value is byte-for-byte what it was.\n if (value.uncertainty !== undefined) {\n return formatUncertain(value.value as number, value.uncertainty, locale, us);\n }\n return formatNumber(value.value as number, locale, us, value.decimalPlaces);\n case ValueType.Hex:\n return formatHex(value.value as number | bigint, us, value.unit);\n case ValueType.BigInt:\n return formatBigInt(value.value as bigint);\n case ValueType.String:\n return formatString(value.value as string);\n case ValueType.Boolean:\n return formatBoolean(value.value as boolean);\n case ValueType.Datetime:\n return formatDatetime(value.value as number, locale, us);\n case ValueType.Uom:\n return formatUom(value.value as number, value.unit, locale, us, value.exact);\n case ValueType.Matrix:\n return formatMatrix(value.value as MatrixData, locale, us);\n case ValueType.Range: {\n const r = value.value as RangeData;\n return formatRange(r.min, r.max, locale);\n }\n case ValueType.Colour:\n return `${locale.display.resultPrefix}${formatColour(value.value as ColourData)}`;\n case ValueType.Split:\n return formatSplit(value.value as SplitData, locale, us);\n case ValueType.Chart:\n // A chart is drawn from its data by the host; the text answer is its label\n // (`sin(x) over [0, 6.28]`, or the series a sparkline came from).\n return `${locale.display.resultPrefix}${(value.value as ChartData).label}`;\n case ValueType.Symbolic:\n return formatSymbolic(value.value as SymbolicNode);\n case ValueType.Percentage:\n return formatPercentage(value.value as number, locale, us);\n case ValueType.Unit:\n return formatUnit(value.value as number, value.unit);\n case ValueType.Error:\n // errorValue(code, message) stores the human-readable message in\n // `.unit` (code goes in `.value`), falling through to the default\n // case here previously displayed the raw code (e.g.\n // \"CURRENCY_RATE_UNAVAILABLE\") instead of the actual message.\n return value.unit ?? String(value.value);\n default:\n return `= ${String(value.value)}`;\n }\n}\n"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {a}from'./chunk-RAF57WYO.js';import {l,m,g}from'./chunk-
|
|
2
|
-
`),r=new Array(n.length);for(let s=0;s<n.length;s++){let i=this.nextLineId++;r[s]=i,this.lines.set(i,{lineId:i,textHash:a(n[s]),text:n[s],expressions:[],bytecodes:[],reads:[],writes:[],results:[],result:null,dirty:true,isVariableDef:false,isEmpty:n[s].trim().length===0,inlineSolveCount:0});}this.orderTree.replaceAll(r);for(let s of r)this.dirtyLineIds.add(s);}applyChanges(e){let t=[],n=[],r=[...e].sort((s,i)=>i.startLine-s.startLine);for(let s of r){let i=s.startLine-1,a$1=[];for(let o of s.insertLines){let c=this.nextLineId++;a$1.push(c),t.push(c),this.lines.set(c,{lineId:c,textHash:a(o),text:o,expressions:[],bytecodes:[],reads:[],writes:[],results:[],result:null,dirty:true,isVariableDef:false,isEmpty:o.trim().length===0,inlineSolveCount:0});}for(let o of a$1)this.dirtyLineIds.add(o);let l=this.orderTree.spliceAt(i,s.deleteCount,a$1);for(let o of l)n.push(o),this.lines.delete(o),this.dirtyLineIds.delete(o);}return this._positionCache=null,{inserted:t,removed:n}}insertLines(e,t){let n={startLine:e,deleteCount:0,insertLines:t};return this.applyChanges([n]).inserted}deleteLines(e,t){let n={startLine:e,deleteCount:t-e+1,insertLines:[]};return this.applyChanges([n]).removed}editLine(e,t){let n=this.getLineAt(e);if(!n)return false;let r=a(t);return r===n.textHash?false:(n.text=t,n.textHash=r,n.expressions=[],n.bytecodes=[],n.results=[],n.result=null,n.inlineSolveCount=0,n.dirty=true,this.dirtyLineIds.add(n.lineId),n.isEmpty=t.trim().length===0,true)}getLineAt(e){let t=e-1,n=this.orderTree.getAt(t);if(n!==void 0)return this.lines.get(n)}getLinePosition(e){if(this._positionCache)return this._positionCache.get(e)??-1;this._positionCache=new Map;let t=1;for(let n of this.orderTree)this._positionCache.set(n,t++);return this._positionCache.get(e)??-1}getVisibleLines(e,t){let n=this.orderTree.getRange(e-1,t-1),r=[];for(let s of n){let i=this.lines.get(s);i&&r.push(i);}return r}getAllLines(){return this.getVisibleLines(1,this.lineCount)}getLineById(e){return this.lines.get(e)}getDirtyLines(){let e=[];for(let t of this.lines.values())t.dirty&&e.push(t);return e}hasAnyDirtyLineBefore(e){for(let t of this.dirtyLineIds){let n=this.getLinePosition(t);if(n>=1&&n<e)return true}return false}hasAnyDirtyVariableDefLineBefore(e){for(let t of this.dirtyLineIds){let n=this.lines.get(t);if(!n||!n.isVariableDef)continue;let r=this.getLinePosition(t);if(r>=1&&r<e)return true}return false}get dirtyCount(){return this.dirtyLineIds.size}isBytecodeValid(e,t){let n=this.lines.get(e);return n!==void 0&&n.textHash===t}markClean(e){let t=this.lines.get(e);t&&(t.dirty=false,this.dirtyLineIds.delete(e));}markDirtyByLineNumber(e){let t=this.getLineAt(e);t&&(t.dirty=true,this.dirtyLineIds.add(t.lineId));}markDirty(e){let t=this.lines.get(e);t&&(t.dirty=true,this.dirtyLineIds.add(e));}invalidateAll(){for(let e of this.lines.values())e.dirty=true;this.dirtyLineIds=new Set(this.lines.keys());}updateLineResult(e,t,n,r,s,i,a,l=0){let o=this.lines.get(e);o&&(o.results=t,o.result=t[0]?.[0]??null,o.bytecodes=n,o.expressions=r,o.reads=s,o.writes=i,o.isVariableDef=a,o.inlineSolveCount=l,o.dirty=false,this.dirtyLineIds.delete(e));}updateLineCompiled(e,t,n,r,s,i,a=0){let l=this.lines.get(e);l&&(l.expressions=t,l.bytecodes=n,l.reads=r,l.writes=s,l.isVariableDef=i,l.inlineSolveCount=a);}get lineCount(){return this.orderTree.length}get isEmpty(){return this.orderTree.isEmpty}*[Symbol.iterator](){for(let e of this.orderTree){let t=this.lines.get(e);t&&(yield t);}}clear(){this.lines.clear(),this.orderTree.clear(),this._positionCache=null,this.nextLineId=1;}toJSON(){return {lineCount:this.lineCount,lines:this.getAllLines().map(e=>({lineId:e.lineId,text:e.text.substring(0,80),textHash:e.textHash,dirty:e.dirty,isVariableDef:e.isVariableDef,isEmpty:e.isEmpty,hasBytecode:e.bytecodes.length>0,hasResult:e.results.length>0,inlineSolveCount:e.inlineSolveCount,reads:e.reads,writes:e.writes}))}}};var A=class{constructor(){this.worker=null;this.nextId=1;this.pending=new Map;}ensureWorker(){return this.worker?this.worker:(this.worker=g(),this.worker.onmessage=e=>{let t=e.data;if(!t||t.type!=="COMPILE_RESULT")return;let n=this.pending.get(t.id);if(!n)return;this.pending.delete(t.id);let r=[];for(let s of t.results)r.push(this.reconstructResult(s));n.resolve(r);},this.worker.onerror=e=>{for(let[t,n]of this.pending)n.reject(new Error(`Compilation worker error: ${e.message}`)),this.pending.delete(t);},this.worker)}async compileBatch(e){if(e.length===0)return [];let t=this.ensureWorker(),n=this.nextId++;return new Promise((r,s)=>{this.pending.set(n,{resolve:r,reject:s}),t.postMessage({type:"COMPILE_BATCH",id:n,items:e});})}storeResults(e,t){let n=new Map;for(let i of e){if(i.error)continue;let a=t.getLineById(i.lineId);if(!a||a.textHash!==i.compiledAgainstHash)continue;let l=n.get(i.lineId);l||(l={bytecodes:[],reads:new Set,writes:new Set,isVariableDef:false,expressions:a.expressions.length>0?[...a.expressions]:[],textHash:i.compiledAgainstHash},n.set(i.lineId,l)),l.bytecodes.push(i.program);for(let o of i.reads)l.reads.add(o);for(let o of i.writes)l.writes.add(o);i.isVariableDef&&(l.isVariableDef=true);}let s=0;for(let[i,a]of n){if(a.bytecodes.length===0)continue;let o=t.getLineById(i)?.inlineSolveCount??0;t.updateLineCompiled(i,a.expressions,a.bytecodes,[...a.reads],[...a.writes],a.isVariableDef,o),s+=a.bytecodes.length;}return s}terminate(){this.worker&&(this.worker.terminate(),this.worker=null,this.pending.clear());}get isActive(){return this.worker!==null}reconstructResult(e){if(e.error)return {lineId:e.lineId,compiledAgainstHash:e.compiledAgainstHash,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},reads:[],writes:[],isVariableDef:false,error:e.error};let t=e.opcodesLength>0?new Uint8Array(e.opcodesBuffer,0,e.opcodesLength):new Uint8Array(0),n=e.numbersLength>0?new Float64Array(e.numbersBuffer,0,e.numbersLength):new Float64Array(0),r={opcodes:t,numbers:n,strings:e.strings,hasAsync:false};return {lineId:e.lineId,compiledAgainstHash:e.compiledAgainstHash,program:r,reads:e.reads,writes:e.writes,isVariableDef:e.isVariableDef,error:null}}};var U=128,k=3,Z=6,Q=2,X=k,H=class u{constructor(){this.lastViewportStart=null;this.savedDirection=null;this.pageAccess=new Map;this.accessSeq=0;}static pageForLine(e){return Math.floor((e-1)/U)}static pageRange(e,t){return {startLine:e*U+1,endLine:Math.min((e+1)*U,t)}}detectDirection(e){return this.lastViewportStart===null?null:e.startLine>this.lastViewportStart?"down":e.startLine<this.lastViewportStart?"up":null}maintainAfterEval(e,t){this.savedDirection=this.detectDirection(e),this.lastViewportStart=e.startLine;let n=t.lineCount,r=u.pageForLine(e.startLine),s=u.pageForLine(e.endLine),i=u.pageForLine(n),a=Math.max(0,r-k),l=Math.min(i,s+k),o=Math.max(0,r-Z),c=Math.min(i,s+Z);for(let h=a;h<=l;h++)this.touchPage(h);for(let h=o;h<=c;h++)h>=a&&h<=l||this.evictPageResults(h,t,n);let d=o-1,p=Math.max(0,d-X+1);for(let h=p;h<=d;h++)this.evictPageBytecode(h,t,n);let f=c+1,g=Math.min(i,f+X-1);for(let h=f;h<=g;h++)this.evictPageBytecode(h,t,n);}getPreloadTargets(e,t){let n=this.savedDirection;if(!n)return [];let r=[],s=u.pageForLine(e.endLine),i=u.pageForLine(e.startLine),a=u.pageForLine(t.lineCount),l=[];if(n==="down"){let o=s+k+1,c=Math.min(o+Q-1,a);for(let d=o;d<=c&&d<=a;d++)l.push(d);}else {let o=i-k-1;for(let c=o;c>o-Q&&c>=0;c--)l.push(c);}for(let o of l){let c=u.pageRange(o,t.lineCount);for(let d=c.startLine;d<=c.endLine;d++){let p=t.getLineAt(d);if(p&&p.dirty&&!(p.bytecodes.length>0&&!p.isVariableDef)&&!p.isEmpty)if(p.expressions.length>0)for(let f of p.expressions)f.trim()&&r.push({lineId:p.lineId,expression:f,textHash:p.textHash});else {let f=c$1.findInlineSolves(p.text);if(f.length>0)for(let g of f)g.expression.trim()&&r.push({lineId:p.lineId,expression:g.expression,textHash:p.textHash});else {let g=p.text.trim();g&&r.push({lineId:p.lineId,expression:g,textHash:p.textHash});}}}}return r}clear(){this.pageAccess.clear(),this.accessSeq=0,this.lastViewportStart=null,this.savedDirection=null;}touchPage(e){this.pageAccess.set(e,++this.accessSeq);}evictPageResults(e,t,n){let r=u.pageRange(e,n);for(let s=r.startLine;s<=r.endLine;s++){let i=t.getLineAt(s);i&&!i.isVariableDef&&i.results.length>0&&(i.results=[],i.result=null);}}evictPageBytecode(e,t,n){let r=u.pageRange(e,n);for(let s=r.startLine;s<=r.endLine;s++){let i=t.getLineAt(s);!i||i.isVariableDef||(i.bytecodes.length>0||i.results.length>0)&&(i.bytecodes=[],i.results=[],i.result=null,t.markDirty(i.lineId));}}};var Y=(r=>(r[r.Tier1=1]="Tier1",r[r.Tier2=2]="Tier2",r[r.Tier3=3]="Tier3",r[r.Skipped=0]="Skipped",r))(Y||{}),w=class{constructor(e,t,n){this.compilationWorker=null;this.globalUnsubscribe=null;this.doc=e,this.engine=t,this.dag=t.getDag(),this.checkpointer=n??null,this.pageManager=new H,this.engine.setDocumentModel(this.doc),this.globalUnsubscribe=J.subscribe(r=>{for(let s of this.dag.getAffectedLines(K(r)))this.doc.markDirtyByLineNumber(s);});}evaluate(e,t){this.engine.setKeystrokeSignal(t??null),h();try{this.reseedAccumulators();let n=[],r=new Map,s={tier1:0,tier2:0,tier3:0,skipped:0},i=this.doc.lineCount,a=Math.min(e.endLine,i);for(let l=1;l<=a;l++){let o=this.doc.getLineAt(l);if(!o){s.skipped++;continue}let c=l>=e.startLine&&l<=e.endLine,d=this.evaluateSingleLine(o,l,c);n.push(d),d.tier===1?s.tier1++:d.tier===2?s.tier2++:d.tier===3?s.tier3++:s.skipped++,d.results&&c&&r.set(l,d.results.flat());}return this.pageManager.maintainAfterEval(e,this.doc),{lines:n,resultMap:r,tierCounts:s}}finally{this.engine.setKeystrokeSignal(null),i();}}backgroundCompile(e){let t=[],n=this.doc.lineCount,r=e.endLine+1;for(let s=r;s<=n;s++){let i=this.doc.getLineAt(s);if(!i||!i.dirty||i.bytecodes.length>0&&!i.isVariableDef)continue;let a=this.evaluateSingleLine(i,s,false);t.push(a);}return t}dispatchBackgroundCompiles(e){let t=this.collectInvisibleCompileTargets(e);t.length!==0&&(this.compilationWorker||(this.compilationWorker=new A),this.compilationWorker.compileBatch(t).then(n=>{this.compilationWorker.storeResults(n,this.doc);}).catch(n=>{}));}terminateWorker(){this.compilationWorker&&(this.compilationWorker.terminate(),this.compilationWorker=null),this.globalUnsubscribe&&(this.globalUnsubscribe(),this.globalUnsubscribe=null);}getDoc(){return this.doc}evaluateAll(e){let t={startLine:1,endLine:this.doc.lineCount};return this.evaluate(t,e)}setViewport(e,t){if(this.engine.setKeystrokeSignal(t??null),e.startLine>1&&this.hasDirtyLinesBefore(e.startLine))return this.checkpointer?.clear(),this.evaluate(e,t);this.pageManager.maintainAfterEval(e,this.doc),this.preloadNextPages(e),this.restoreTo(e.startLine-1),h();try{return this.collectEvalResults(e.startLine,e.endLine)}finally{this.engine.setKeystrokeSignal(null),i();}}applyTransaction(e){let t=new Set;for(let s of e)for(let i=0;i<s.deleteCount;i++){let a=s.startLine+i,l=this.dag.getWrites(a);for(let o of l)t.add(o);this.dag.removeLine(a),this.engine.getLineCache().removeAllForLine(a);}let n=new Set;for(let s of t){let i=this.dag.getAffectedLines(s);for(let a of i){let l=this.doc.getLineAt(a);l&&n.add(l.lineId);}}let r=this.doc.applyChanges(e);this.checkpointer?.clear();for(let s of n)this.doc.markDirty(s);return this.dag.clear(),{inserted:r.inserted,removed:r.removed}}reseedAccumulators(){let e=this.engine.resetAccumulators();if(e.size===0)return;let t=this.doc.lineCount;for(let n=1;n<=t;n++){let r=this.dag.getWrites(n);if(r.size!==0){for(let s of r)if(e.has(s)){this.doc.markDirtyByLineNumber(n);break}}}}collectEvalResults(e,t){let n=[],r=new Map,s={tier1:0,tier2:0,tier3:0,skipped:0},i=this.doc.lineCount,a=Math.min(t,i);for(let l=e;l<=a;l++){let o=this.doc.getLineAt(l);if(!o)continue;let c=this.evaluateSingleLine(o,l,true);n.push(c),c.tier===1?s.tier1++:c.tier===2?s.tier2++:c.tier===3?s.tier3++:s.skipped++,c.results&&r.set(l,c.results.flat());}return {lines:n,resultMap:r,tierCounts:s}}hasDirtyLinesBefore(e){return this.doc.hasAnyDirtyVariableDefLineBefore(e)}evaluateSingleLine(e,t,n){let r={lineId:e.lineId,lineNumber:t};if(e.isEmpty||l(e.text))return e.isEmpty=true,this.doc.markClean(e.lineId),{...r,tier:0,result:null,error:null};let{expressions:s,inlineSolveCount:i}=this.extractExpressions(e);return s.length===0?(e.isEmpty=true,this.doc.markClean(e.lineId),{...r,tier:0,result:null,error:null}):e.dirty?n?this.evaluateTier1(e,t,s,i,r):e.bytecodes.length>0&&e.bytecodes.length===s.length&&!e.isVariableDef?{...r,tier:0,result:null,error:null}:this.evaluateTier3(e,t,s,i,r):n&&e.bytecodes.length>0?this.evaluateTier2(e,t,r):{...r,tier:0,result:null,error:null}}evaluateTier1(e,t,n,r,s){let i=[],a=[],l=new Set,o=new Set,c=false,d=null,p=null,f=false,g=false;for(let y of n){if(!y.trim())continue;let b=null,L;try{let m=this.engine.evaluateLine(t,y);b=[m],d=m,L=this.engine.getLineCache().get(t,y);}catch(m){let x=m instanceof Error?m.message:String(m);p||(p=x),f=true,b=null;}if(b&&b.some(m=>m.type===12)&&(g=true),b?i.push(b):i.push([N("eval_failed",p??"unknown error")]),L){a.push(L.bytecode);for(let m of L.readVariables)l.add(m);L.writeVariable&&(o.add(L.writeVariable),c=true);}else try{let{program:m,reads:x,writes:E}=this.engine.compileExpression(y);a.push(m);for(let S of x)l.add(S);for(let S of E)o.add(S);E.length>0&&(c=!0);}catch(m){if(a.push({opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false}),m instanceof b$2&&m.context){let x=m.context.reads,E=m.context.writes;if(Array.isArray(x))for(let S of x)l.add(S);if(Array.isArray(E))for(let S of E)o.add(S);}}}let h=[...l],v=[...o];return f||g?(this.doc.updateLineCompiled(e.lineId,n,a,h,v,c,r),e.results=i,e.result=i[0]?.[0]??null,e.inlineSolveCount=r,e.expressions=n):this.doc.updateLineResult(e.lineId,i,a,n,h,v,c,r),this.dag.registerLine(t,h,v),this.checkpointer&&v.length>0&&!f&&!g&&this.checkpointer.snapshot(t,e.lineId,v),{...s,tier:1,result:d,results:i,error:p}}evaluateTier2(e,t,n){if(e.bytecodes.length===0)return {...n,tier:0,result:null,error:null};let r=[],s=null,i=null,a=false;for(let l of e.bytecodes)if(l.opcodes.length!==0)try{let o=this.engine.executeCached(l,t);s=o,r.push([o]);}catch(o){let c=o instanceof Error?o.message:String(o);i||(i=c),a=true,r.push([N("exec_failed",c)]);}return this.dag.registerLine(t,e.reads,e.writes),e.results=r,e.result=r[0]?.[0]??null,a&&this.doc.markDirty(e.lineId),{...n,tier:2,result:s,results:r,error:i}}evaluateTier3(e,t,n,r,s){let i=[],a=new Set,l=new Set,o=false,c=null,d=null,p=false,f=false;for(let v of n)if(v.trim())try{let{program:y,reads:b,writes:L}=this.engine.compileExpression(v);i.push(y);for(let m of b)a.add(m);for(let m of L)l.add(m);L.length>0&&(o=!0),L.length>0&&y.opcodes.length>0&&(c=this.engine.executeCached(y,t),c&&c.type===12&&(f=!0));}catch(y){let b=y instanceof Error?y.message:String(y);d||(d=b),p=true,i.push({opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false});}let g=[...a],h=[...l];return this.doc.updateLineCompiled(e.lineId,n,i,g,h,o,r),this.dag.registerLine(t,g,h),o&&c&&!p&&!f&&(e.results=[[c]],e.result=c,this.doc.markClean(e.lineId),this.checkpointer&&this.checkpointer.snapshot(t,e.lineId,h)),{...s,tier:3,result:c,results:o&&c&&!p&&!f?[[c]]:void 0,error:d}}restoreTo(e){this.checkpointer&&this.checkpointer.restoreTo(e);}getCheckpointer(){return this.checkpointer}getPageManager(){return this.pageManager}preloadNextPages(e){let t=this.pageManager.getPreloadTargets(e,this.doc);t.length!==0&&(this.compilationWorker||(this.compilationWorker=new A),this.compilationWorker.compileBatch(t).then(n=>{this.compilationWorker.storeResults(n,this.doc);}).catch(n=>{}));}collectInvisibleCompileTargets(e){let t=[],n=this.doc.lineCount,r=e.endLine+1;for(let s=r;s<=n;s++){let i=this.doc.getLineAt(s);if(!i||!i.dirty||i.bytecodes.length>0&&!i.isVariableDef||i.isEmpty||l(i.text))continue;let{expressions:a}=this.extractExpressions(i);if(a.length!==0)for(let l of a)l.trim()&&t.push({lineId:i.lineId,expression:l,textHash:i.textHash});}return t}extractExpressions(e){if(e.expressions.length>0)return {expressions:e.expressions,inlineSolveCount:e.inlineSolveCount};let t=e.text.trim();if(t.length===0)return {expressions:[],inlineSolveCount:0};let n=c$1.findInlineSolves(e.text);return n.length>0?{expressions:n.map(r=>r.expression),inlineSolveCount:n.length}:{expressions:[t],inlineSolveCount:0}}};function ee(u){return typeof u.unit=="string"?u.unit:String(u.value)}function ie(u,e,t={inputType:"markdown"}){let n=u.getDocumentModel(),r=new R;r.setDocument(e);let s=new w(r,u);try{let i=r.lineCount;s.evaluate({startLine:1,endLine:i});let a=[],l=[],o=0;for(let c=1;c<=i;c++){let d=r.getLineAt(c),p=d.text,f=o,g=o+p.length;o=g+1;let h=d.inlineSolveCount>0,v=[],y=null,b=null;d.isEmpty||(h?v=m(p,c).map((L,m)=>{let x=d.results[m]?.[0]??null;if(x&&x.type===13){let E=ee(x);return l.push(`Line ${c}: ${E}`),{...L,result:null,error:E}}return {...L,result:x,error:null}}):(y=d.expressions[0]??null,b=d.result??null,b&&b.type===13&&l.push(`Line ${c}: ${ee(b)}`))),a.push({lineNumber:c,text:p,startPosition:f,endPosition:g,isEmpty:d.isEmpty,hasInlineSolves:h,inlineSolves:v,expression:y,error:null,result:b});}return {lines:a,totalLines:i,errors:l}}finally{s.terminateWorker(),u.setDocumentModel(n);}}export{R as a,Y as b,w as c,ie as d};//# sourceMappingURL=chunk-RDMJNRDO.js.map
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a}from'./chunk-RAF57WYO.js';import {l,m,g}from'./chunk-T52Y5G24.js';import {b as b$1}from'./chunk-76F3LCIL.js';import {J,K}from'./chunk-XTM4HTRB.js';import {h,i,O}from'./chunk-IO374J6Z.js';import {b}from'./chunk-HMEZJXLX.js';import {c as c$1}from'./chunk-YAHGSBMC.js';import {c,b as b$2}from'./chunk-MPB7KUN5.js';var P=class{constructor(){this.root=null;}get length(){return this.root?this.root.size:0}get isEmpty(){return this.root===null}getAt(e){if(!(e<0||e>=(this.root?.size??0)))return this.nodeAt(this.root,e).lineId}insertAt(e,t){let[n,r]=I(this.root,e);this.root=C(C(n,te(t)),r);}deleteAt(e){if(e<0||e>=(this.root?.size??0))return;let[t,n]=I(this.root,e),[r,s]=I(n,1),i=r?r.lineId:void 0;return this.root=C(t,s),i}spliceAt(e,t,n){let r=Math.max(0,e),s=Math.min(Math.max(0,t),(this.root?.size??0)-r),[i,a]=I(this.root,r),[l,o]=I(a,s),c=ne(l),d=B(n,0,n.length);return this.root=C(C(i,d),o),c}replaceAll(e){this.root=B(e,0,e.length);}getRange(e,t){let n=Math.max(0,e),r=Math.min((this.root?.size??0)-1,t);if(n>r)return [];let s=[];return this.collectRange(this.root,n,r,0,s),s}clear(){this.root=null;}*[Symbol.iterator](){yield*this.inOrder(this.root);}*inOrder(e){e&&(yield*this.inOrder(e.left),yield e.lineId,yield*this.inOrder(e.right));}nodeAt(e,t){let n=e.left?e.left.size:0;return t<n?this.nodeAt(e.left,t):t===n?e:this.nodeAt(e.right,t-n-1)}collectRange(e,t,n,r,s){if(!e)return;let i=e.left?e.left.size:0,a=r+i;a>t&&e.left&&this.collectRange(e.left,t,n,r,s),a>=t&&a<=n&&s.push(e.lineId),a<n&&e.right&&this.collectRange(e.right,t,n,a+1,s);}};function te(u){return {lineId:u,size:1,priority:Math.random(),left:null,right:null}}function T(u){u.size=1+(u.left?u.left.size:0)+(u.right?u.right.size:0);}function C(u,e){return u?e?u.priority>e.priority?(u.right=C(u.right,e),T(u),u):(e.left=C(u,e.left),T(e),e):u:e}function I(u,e){if(!u)return [null,null];let t=u.left?u.left.size:0;if(e<=t){let[n,r]=I(u.left,e);return u.left=r,T(u),[n,u]}else {let[n,r]=I(u.right,e-t-1);return u.right=n,T(u),[u,r]}}function ne(u){let e=[];return F(u,e),e}function F(u,e){u&&(F(u.left,e),e.push(u.lineId),F(u.right,e));}function B(u,e,t){if(e>=t)return null;let n=Math.floor((e+t)/2),r=re(n);return {lineId:u[n],size:t-e,priority:r,left:B(u,e,n),right:B(u,n+1,t)}}function re(u){let e=u;return e=(e>>16^e)*73244475,e=(e>>16^e)*73244475,e=e>>16^e,e/4294967295}var R=class{constructor(e=b.performance.maxDocumentLines){this.lines=new Map;this.orderTree=new P;this.nextLineId=1;this._positionCache=null;this.dirtyLineIds=new Set;this.maxLines=e;}setDocument(e){if(b$1(e,this.maxLines)>this.maxLines)throw c.execution("DOCUMENT_TOO_LARGE",`This document has more than ${this.maxLines.toLocaleString("en-US")} lines, which is the most the engine will hold at once`,{maxLines:this.maxLines});this.lines.clear(),this.orderTree.clear(),this._positionCache=null,this.dirtyLineIds.clear(),this.nextLineId=1;let n=e.split(`
|
|
2
|
+
`),r=new Array(n.length);for(let s=0;s<n.length;s++){let i=this.nextLineId++;r[s]=i,this.lines.set(i,{lineId:i,textHash:a(n[s]),text:n[s],expressions:[],bytecodes:[],reads:[],writes:[],results:[],result:null,dirty:true,isVariableDef:false,isEmpty:n[s].trim().length===0,inlineSolveCount:0});}this.orderTree.replaceAll(r);for(let s of r)this.dirtyLineIds.add(s);}applyChanges(e){let t=[],n=[],r=[...e].sort((s,i)=>i.startLine-s.startLine);for(let s of r){let i=s.startLine-1,a$1=[];for(let o of s.insertLines){let c=this.nextLineId++;a$1.push(c),t.push(c),this.lines.set(c,{lineId:c,textHash:a(o),text:o,expressions:[],bytecodes:[],reads:[],writes:[],results:[],result:null,dirty:true,isVariableDef:false,isEmpty:o.trim().length===0,inlineSolveCount:0});}for(let o of a$1)this.dirtyLineIds.add(o);let l=this.orderTree.spliceAt(i,s.deleteCount,a$1);for(let o of l)n.push(o),this.lines.delete(o),this.dirtyLineIds.delete(o);}return this._positionCache=null,{inserted:t,removed:n}}insertLines(e,t){let n={startLine:e,deleteCount:0,insertLines:t};return this.applyChanges([n]).inserted}deleteLines(e,t){let n={startLine:e,deleteCount:t-e+1,insertLines:[]};return this.applyChanges([n]).removed}editLine(e,t){let n=this.getLineAt(e);if(!n)return false;let r=a(t);return r===n.textHash?false:(n.text=t,n.textHash=r,n.expressions=[],n.bytecodes=[],n.results=[],n.result=null,n.inlineSolveCount=0,n.dirty=true,this.dirtyLineIds.add(n.lineId),n.isEmpty=t.trim().length===0,true)}getLineAt(e){let t=e-1,n=this.orderTree.getAt(t);if(n!==void 0)return this.lines.get(n)}getLinePosition(e){if(this._positionCache)return this._positionCache.get(e)??-1;this._positionCache=new Map;let t=1;for(let n of this.orderTree)this._positionCache.set(n,t++);return this._positionCache.get(e)??-1}getVisibleLines(e,t){let n=this.orderTree.getRange(e-1,t-1),r=[];for(let s of n){let i=this.lines.get(s);i&&r.push(i);}return r}getAllLines(){return this.getVisibleLines(1,this.lineCount)}getLineById(e){return this.lines.get(e)}getDirtyLines(){let e=[];for(let t of this.lines.values())t.dirty&&e.push(t);return e}hasAnyDirtyLineBefore(e){for(let t of this.dirtyLineIds){let n=this.getLinePosition(t);if(n>=1&&n<e)return true}return false}hasAnyDirtyVariableDefLineBefore(e){for(let t of this.dirtyLineIds){let n=this.lines.get(t);if(!n||!n.isVariableDef)continue;let r=this.getLinePosition(t);if(r>=1&&r<e)return true}return false}get dirtyCount(){return this.dirtyLineIds.size}isBytecodeValid(e,t){let n=this.lines.get(e);return n!==void 0&&n.textHash===t}markClean(e){let t=this.lines.get(e);t&&(t.dirty=false,this.dirtyLineIds.delete(e));}markDirtyByLineNumber(e){let t=this.getLineAt(e);t&&(t.dirty=true,this.dirtyLineIds.add(t.lineId));}markDirty(e){let t=this.lines.get(e);t&&(t.dirty=true,this.dirtyLineIds.add(e));}invalidateAll(){for(let e of this.lines.values())e.dirty=true;this.dirtyLineIds=new Set(this.lines.keys());}updateLineResult(e,t,n,r,s,i,a,l=0){let o=this.lines.get(e);o&&(o.results=t,o.result=t[0]?.[0]??null,o.bytecodes=n,o.expressions=r,o.reads=s,o.writes=i,o.isVariableDef=a,o.inlineSolveCount=l,o.dirty=false,this.dirtyLineIds.delete(e));}updateLineCompiled(e,t,n,r,s,i,a=0){let l=this.lines.get(e);l&&(l.expressions=t,l.bytecodes=n,l.reads=r,l.writes=s,l.isVariableDef=i,l.inlineSolveCount=a);}get lineCount(){return this.orderTree.length}get isEmpty(){return this.orderTree.isEmpty}*[Symbol.iterator](){for(let e of this.orderTree){let t=this.lines.get(e);t&&(yield t);}}clear(){this.lines.clear(),this.orderTree.clear(),this._positionCache=null,this.nextLineId=1;}toJSON(){return {lineCount:this.lineCount,lines:this.getAllLines().map(e=>({lineId:e.lineId,text:e.text.substring(0,80),textHash:e.textHash,dirty:e.dirty,isVariableDef:e.isVariableDef,isEmpty:e.isEmpty,hasBytecode:e.bytecodes.length>0,hasResult:e.results.length>0,inlineSolveCount:e.inlineSolveCount,reads:e.reads,writes:e.writes}))}}};var A=class{constructor(){this.worker=null;this.nextId=1;this.pending=new Map;}ensureWorker(){return this.worker?this.worker:(this.worker=g(),this.worker.onmessage=e=>{let t=e.data;if(!t||t.type!=="COMPILE_RESULT")return;let n=this.pending.get(t.id);if(!n)return;this.pending.delete(t.id);let r=[];for(let s of t.results)r.push(this.reconstructResult(s));n.resolve(r);},this.worker.onerror=e=>{for(let[t,n]of this.pending)n.reject(new Error(`Compilation worker error: ${e.message}`)),this.pending.delete(t);},this.worker)}async compileBatch(e){if(e.length===0)return [];let t=this.ensureWorker(),n=this.nextId++;return new Promise((r,s)=>{this.pending.set(n,{resolve:r,reject:s}),t.postMessage({type:"COMPILE_BATCH",id:n,items:e});})}storeResults(e,t){let n=new Map;for(let i of e){if(i.error)continue;let a=t.getLineById(i.lineId);if(!a||a.textHash!==i.compiledAgainstHash)continue;let l=n.get(i.lineId);l||(l={bytecodes:[],reads:new Set,writes:new Set,isVariableDef:false,expressions:a.expressions.length>0?[...a.expressions]:[],textHash:i.compiledAgainstHash},n.set(i.lineId,l)),l.bytecodes.push(i.program);for(let o of i.reads)l.reads.add(o);for(let o of i.writes)l.writes.add(o);i.isVariableDef&&(l.isVariableDef=true);}let s=0;for(let[i,a]of n){if(a.bytecodes.length===0)continue;let o=t.getLineById(i)?.inlineSolveCount??0;t.updateLineCompiled(i,a.expressions,a.bytecodes,[...a.reads],[...a.writes],a.isVariableDef,o),s+=a.bytecodes.length;}return s}terminate(){this.worker&&(this.worker.terminate(),this.worker=null,this.pending.clear());}get isActive(){return this.worker!==null}reconstructResult(e){if(e.error)return {lineId:e.lineId,compiledAgainstHash:e.compiledAgainstHash,program:{opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false},reads:[],writes:[],isVariableDef:false,error:e.error};let t=e.opcodesLength>0?new Uint8Array(e.opcodesBuffer,0,e.opcodesLength):new Uint8Array(0),n=e.numbersLength>0?new Float64Array(e.numbersBuffer,0,e.numbersLength):new Float64Array(0),r={opcodes:t,numbers:n,strings:e.strings,hasAsync:false};return {lineId:e.lineId,compiledAgainstHash:e.compiledAgainstHash,program:r,reads:e.reads,writes:e.writes,isVariableDef:e.isVariableDef,error:null}}};var U=128,k=3,Z=6,Q=2,X=k,H=class u{constructor(){this.lastViewportStart=null;this.savedDirection=null;this.pageAccess=new Map;this.accessSeq=0;}static pageForLine(e){return Math.floor((e-1)/U)}static pageRange(e,t){return {startLine:e*U+1,endLine:Math.min((e+1)*U,t)}}detectDirection(e){return this.lastViewportStart===null?null:e.startLine>this.lastViewportStart?"down":e.startLine<this.lastViewportStart?"up":null}maintainAfterEval(e,t){this.savedDirection=this.detectDirection(e),this.lastViewportStart=e.startLine;let n=t.lineCount,r=u.pageForLine(e.startLine),s=u.pageForLine(e.endLine),i=u.pageForLine(n),a=Math.max(0,r-k),l=Math.min(i,s+k),o=Math.max(0,r-Z),c=Math.min(i,s+Z);for(let h=a;h<=l;h++)this.touchPage(h);for(let h=o;h<=c;h++)h>=a&&h<=l||this.evictPageResults(h,t,n);let d=o-1,p=Math.max(0,d-X+1);for(let h=p;h<=d;h++)this.evictPageBytecode(h,t,n);let f=c+1,g=Math.min(i,f+X-1);for(let h=f;h<=g;h++)this.evictPageBytecode(h,t,n);}getPreloadTargets(e,t){let n=this.savedDirection;if(!n)return [];let r=[],s=u.pageForLine(e.endLine),i=u.pageForLine(e.startLine),a=u.pageForLine(t.lineCount),l=[];if(n==="down"){let o=s+k+1,c=Math.min(o+Q-1,a);for(let d=o;d<=c&&d<=a;d++)l.push(d);}else {let o=i-k-1;for(let c=o;c>o-Q&&c>=0;c--)l.push(c);}for(let o of l){let c=u.pageRange(o,t.lineCount);for(let d=c.startLine;d<=c.endLine;d++){let p=t.getLineAt(d);if(p&&p.dirty&&!(p.bytecodes.length>0&&!p.isVariableDef)&&!p.isEmpty)if(p.expressions.length>0)for(let f of p.expressions)f.trim()&&r.push({lineId:p.lineId,expression:f,textHash:p.textHash});else {let f=c$1.findInlineSolves(p.text);if(f.length>0)for(let g of f)g.expression.trim()&&r.push({lineId:p.lineId,expression:g.expression,textHash:p.textHash});else {let g=p.text.trim();g&&r.push({lineId:p.lineId,expression:g,textHash:p.textHash});}}}}return r}clear(){this.pageAccess.clear(),this.accessSeq=0,this.lastViewportStart=null,this.savedDirection=null;}touchPage(e){this.pageAccess.set(e,++this.accessSeq);}evictPageResults(e,t,n){let r=u.pageRange(e,n);for(let s=r.startLine;s<=r.endLine;s++){let i=t.getLineAt(s);i&&!i.isVariableDef&&i.results.length>0&&(i.results=[],i.result=null);}}evictPageBytecode(e,t,n){let r=u.pageRange(e,n);for(let s=r.startLine;s<=r.endLine;s++){let i=t.getLineAt(s);!i||i.isVariableDef||(i.bytecodes.length>0||i.results.length>0)&&(i.bytecodes=[],i.results=[],i.result=null,t.markDirty(i.lineId));}}};var Y=(r=>(r[r.Tier1=1]="Tier1",r[r.Tier2=2]="Tier2",r[r.Tier3=3]="Tier3",r[r.Skipped=0]="Skipped",r))(Y||{}),w=class{constructor(e,t,n){this.compilationWorker=null;this.globalUnsubscribe=null;this.doc=e,this.engine=t,this.dag=t.getDag(),this.checkpointer=n??null,this.pageManager=new H,this.engine.setDocumentModel(this.doc),this.globalUnsubscribe=J.subscribe(r=>{for(let s of this.dag.getAffectedLines(K(r)))this.doc.markDirtyByLineNumber(s);});}evaluate(e,t){this.engine.setKeystrokeSignal(t??null),h();try{this.reseedAccumulators();let n=[],r=new Map,s={tier1:0,tier2:0,tier3:0,skipped:0},i=this.doc.lineCount,a=Math.min(e.endLine,i);for(let l=1;l<=a;l++){let o=this.doc.getLineAt(l);if(!o){s.skipped++;continue}let c=l>=e.startLine&&l<=e.endLine,d=this.evaluateSingleLine(o,l,c);n.push(d),d.tier===1?s.tier1++:d.tier===2?s.tier2++:d.tier===3?s.tier3++:s.skipped++,d.results&&c&&r.set(l,d.results.flat());}return this.pageManager.maintainAfterEval(e,this.doc),{lines:n,resultMap:r,tierCounts:s}}finally{this.engine.setKeystrokeSignal(null),i();}}backgroundCompile(e){let t=[],n=this.doc.lineCount,r=e.endLine+1;for(let s=r;s<=n;s++){let i=this.doc.getLineAt(s);if(!i||!i.dirty||i.bytecodes.length>0&&!i.isVariableDef)continue;let a=this.evaluateSingleLine(i,s,false);t.push(a);}return t}dispatchBackgroundCompiles(e){let t=this.collectInvisibleCompileTargets(e);t.length!==0&&(this.compilationWorker||(this.compilationWorker=new A),this.compilationWorker.compileBatch(t).then(n=>{this.compilationWorker.storeResults(n,this.doc);}).catch(n=>{}));}terminateWorker(){this.compilationWorker&&(this.compilationWorker.terminate(),this.compilationWorker=null),this.globalUnsubscribe&&(this.globalUnsubscribe(),this.globalUnsubscribe=null);}getDoc(){return this.doc}evaluateAll(e){let t={startLine:1,endLine:this.doc.lineCount};return this.evaluate(t,e)}setViewport(e,t){if(this.engine.setKeystrokeSignal(t??null),e.startLine>1&&this.hasDirtyLinesBefore(e.startLine))return this.checkpointer?.clear(),this.evaluate(e,t);this.pageManager.maintainAfterEval(e,this.doc),this.preloadNextPages(e),this.restoreTo(e.startLine-1),h();try{return this.collectEvalResults(e.startLine,e.endLine)}finally{this.engine.setKeystrokeSignal(null),i();}}applyTransaction(e){let t=new Set;for(let s of e)for(let i=0;i<s.deleteCount;i++){let a=s.startLine+i,l=this.dag.getWrites(a);for(let o of l)t.add(o);this.dag.removeLine(a),this.engine.getLineCache().removeAllForLine(a);}let n=new Set;for(let s of t){let i=this.dag.getAffectedLines(s);for(let a of i){let l=this.doc.getLineAt(a);l&&n.add(l.lineId);}}let r=this.doc.applyChanges(e);this.checkpointer?.clear();for(let s of n)this.doc.markDirty(s);return this.dag.clear(),{inserted:r.inserted,removed:r.removed}}reseedAccumulators(){let e=this.engine.resetAccumulators();if(e.size===0)return;let t=this.doc.lineCount;for(let n=1;n<=t;n++){let r=this.dag.getWrites(n);if(r.size!==0){for(let s of r)if(e.has(s)){this.doc.markDirtyByLineNumber(n);break}}}}collectEvalResults(e,t){let n=[],r=new Map,s={tier1:0,tier2:0,tier3:0,skipped:0},i=this.doc.lineCount,a=Math.min(t,i);for(let l=e;l<=a;l++){let o=this.doc.getLineAt(l);if(!o)continue;let c=this.evaluateSingleLine(o,l,true);n.push(c),c.tier===1?s.tier1++:c.tier===2?s.tier2++:c.tier===3?s.tier3++:s.skipped++,c.results&&r.set(l,c.results.flat());}return {lines:n,resultMap:r,tierCounts:s}}hasDirtyLinesBefore(e){return this.doc.hasAnyDirtyVariableDefLineBefore(e)}evaluateSingleLine(e,t,n){let r={lineId:e.lineId,lineNumber:t};if(e.isEmpty||l(e.text))return e.isEmpty=true,this.doc.markClean(e.lineId),{...r,tier:0,result:null,error:null};let{expressions:s,inlineSolveCount:i}=this.extractExpressions(e);return s.length===0?(e.isEmpty=true,this.doc.markClean(e.lineId),{...r,tier:0,result:null,error:null}):e.dirty?n?this.evaluateTier1(e,t,s,i,r):e.bytecodes.length>0&&e.bytecodes.length===s.length&&!e.isVariableDef?{...r,tier:0,result:null,error:null}:this.evaluateTier3(e,t,s,i,r):n&&e.bytecodes.length>0?this.evaluateTier2(e,t,r):{...r,tier:0,result:null,error:null}}evaluateTier1(e,t,n,r,s){let i=[],a=[],l=new Set,o=new Set,c=false,d=null,p=null,f=false,g=false;for(let y of n){if(!y.trim())continue;let b=null,L;try{let m=this.engine.evaluateLine(t,y);b=[m],d=m,L=this.engine.getLineCache().get(t,y);}catch(m){let x=m instanceof Error?m.message:String(m);p||(p=x),f=true,b=null;}if(b&&b.some(m=>m.type===12)&&(g=true),b?i.push(b):i.push([O("eval_failed",p??"unknown error")]),L){a.push(L.bytecode);for(let m of L.readVariables)l.add(m);L.writeVariable&&(o.add(L.writeVariable),c=true);}else try{let{program:m,reads:x,writes:E}=this.engine.compileExpression(y);a.push(m);for(let S of x)l.add(S);for(let S of E)o.add(S);E.length>0&&(c=!0);}catch(m){if(a.push({opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false}),m instanceof b$2&&m.context){let x=m.context.reads,E=m.context.writes;if(Array.isArray(x))for(let S of x)l.add(S);if(Array.isArray(E))for(let S of E)o.add(S);}}}let h=[...l],v=[...o];return f||g?(this.doc.updateLineCompiled(e.lineId,n,a,h,v,c,r),e.results=i,e.result=i[0]?.[0]??null,e.inlineSolveCount=r,e.expressions=n):this.doc.updateLineResult(e.lineId,i,a,n,h,v,c,r),this.dag.registerLine(t,h,v),this.checkpointer&&v.length>0&&!f&&!g&&this.checkpointer.snapshot(t,e.lineId,v),{...s,tier:1,result:d,results:i,error:p}}evaluateTier2(e,t,n){if(e.bytecodes.length===0)return {...n,tier:0,result:null,error:null};let r=[],s=null,i=null,a=false;for(let l of e.bytecodes)if(l.opcodes.length!==0)try{let o=this.engine.executeCached(l,t);s=o,r.push([o]);}catch(o){let c=o instanceof Error?o.message:String(o);i||(i=c),a=true,r.push([O("exec_failed",c)]);}return this.dag.registerLine(t,e.reads,e.writes),e.results=r,e.result=r[0]?.[0]??null,a&&this.doc.markDirty(e.lineId),{...n,tier:2,result:s,results:r,error:i}}evaluateTier3(e,t,n,r,s){let i=[],a=new Set,l=new Set,o=false,c=null,d=null,p=false,f=false;for(let v of n)if(v.trim())try{let{program:y,reads:b,writes:L}=this.engine.compileExpression(v);i.push(y);for(let m of b)a.add(m);for(let m of L)l.add(m);L.length>0&&(o=!0),L.length>0&&y.opcodes.length>0&&(c=this.engine.executeCached(y,t),c&&c.type===12&&(f=!0));}catch(y){let b=y instanceof Error?y.message:String(y);d||(d=b),p=true,i.push({opcodes:new Uint8Array(0),numbers:new Float64Array(0),strings:[],hasAsync:false});}let g=[...a],h=[...l];return this.doc.updateLineCompiled(e.lineId,n,i,g,h,o,r),this.dag.registerLine(t,g,h),o&&c&&!p&&!f&&(e.results=[[c]],e.result=c,this.doc.markClean(e.lineId),this.checkpointer&&this.checkpointer.snapshot(t,e.lineId,h)),{...s,tier:3,result:c,results:o&&c&&!p&&!f?[[c]]:void 0,error:d}}restoreTo(e){this.checkpointer&&this.checkpointer.restoreTo(e);}getCheckpointer(){return this.checkpointer}getPageManager(){return this.pageManager}preloadNextPages(e){let t=this.pageManager.getPreloadTargets(e,this.doc);t.length!==0&&(this.compilationWorker||(this.compilationWorker=new A),this.compilationWorker.compileBatch(t).then(n=>{this.compilationWorker.storeResults(n,this.doc);}).catch(n=>{}));}collectInvisibleCompileTargets(e){let t=[],n=this.doc.lineCount,r=e.endLine+1;for(let s=r;s<=n;s++){let i=this.doc.getLineAt(s);if(!i||!i.dirty||i.bytecodes.length>0&&!i.isVariableDef||i.isEmpty||l(i.text))continue;let{expressions:a}=this.extractExpressions(i);if(a.length!==0)for(let l of a)l.trim()&&t.push({lineId:i.lineId,expression:l,textHash:i.textHash});}return t}extractExpressions(e){if(e.expressions.length>0)return {expressions:e.expressions,inlineSolveCount:e.inlineSolveCount};let t=e.text.trim();if(t.length===0)return {expressions:[],inlineSolveCount:0};let n=c$1.findInlineSolves(e.text);return n.length>0?{expressions:n.map(r=>r.expression),inlineSolveCount:n.length}:{expressions:[t],inlineSolveCount:0}}};function ee(u){return typeof u.unit=="string"?u.unit:String(u.value)}function ie(u,e,t={inputType:"markdown"}){let n=u.getDocumentModel(),r=new R;r.setDocument(e);let s=new w(r,u);try{let i=r.lineCount;s.evaluate({startLine:1,endLine:i});let a=[],l=[],o=0;for(let c=1;c<=i;c++){let d=r.getLineAt(c),p=d.text,f=o,g=o+p.length;o=g+1;let h=d.inlineSolveCount>0,v=[],y=null,b=null;d.isEmpty||(h?v=m(p,c).map((L,m)=>{let x=d.results[m]?.[0]??null;if(x&&x.type===13){let E=ee(x);return l.push(`Line ${c}: ${E}`),{...L,result:null,error:E}}return {...L,result:x,error:null}}):(y=d.expressions[0]??null,b=d.result??null,b&&b.type===13&&l.push(`Line ${c}: ${ee(b)}`))),a.push({lineNumber:c,text:p,startPosition:f,endPosition:g,isEmpty:d.isEmpty,hasInlineSolves:h,inlineSolves:v,expression:y,error:null,result:b});}return {lines:a,totalLines:i,errors:l}}finally{s.terminateWorker(),u.setDocumentModel(n);}}export{R as a,Y as b,w as c,ie as d};//# sourceMappingURL=chunk-4XTD4B77.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-4XTD4B77.js.map
|