@invinite-org/chartlang-runtime 1.1.1 → 1.2.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/CHANGELOG.md +236 -0
- package/dist/barPoint.d.ts +20 -0
- package/dist/barPoint.d.ts.map +1 -0
- package/dist/barPoint.js +72 -0
- package/dist/barPoint.js.map +1 -0
- package/dist/bufferSnapshot.d.ts +102 -0
- package/dist/bufferSnapshot.d.ts.map +1 -0
- package/dist/bufferSnapshot.js +119 -0
- package/dist/bufferSnapshot.js.map +1 -0
- package/dist/createScriptRunner.d.ts +6 -3
- package/dist/createScriptRunner.d.ts.map +1 -1
- package/dist/createScriptRunner.js +29 -5
- package/dist/createScriptRunner.js.map +1 -1
- package/dist/dep/DepRunner.d.ts.map +1 -1
- package/dist/dep/DepRunner.js +1 -0
- package/dist/dep/DepRunner.js.map +1 -1
- package/dist/emit/draw/boxes/fillBetween.d.ts +45 -0
- package/dist/emit/draw/boxes/fillBetween.d.ts.map +1 -0
- package/dist/emit/draw/boxes/fillBetween.js +36 -0
- package/dist/emit/draw/boxes/fillBetween.js.map +1 -0
- package/dist/emit/draw/handle.d.ts +9 -0
- package/dist/emit/draw/handle.d.ts.map +1 -1
- package/dist/emit/draw/handle.js +65 -10
- package/dist/emit/draw/handle.js.map +1 -1
- package/dist/emit/draw/namespace.d.ts +4 -3
- package/dist/emit/draw/namespace.d.ts.map +1 -1
- package/dist/emit/draw/namespace.js +6 -3
- package/dist/emit/draw/namespace.js.map +1 -1
- package/dist/emit/plot.d.ts +7 -0
- package/dist/emit/plot.d.ts.map +1 -1
- package/dist/emit/plot.js +13 -0
- package/dist/emit/plot.js.map +1 -1
- package/dist/execution/dispose.d.ts.map +1 -1
- package/dist/execution/dispose.js +16 -0
- package/dist/execution/dispose.js.map +1 -1
- package/dist/execution/runComputeStep.d.ts.map +1 -1
- package/dist/execution/runComputeStep.js +10 -1
- package/dist/execution/runComputeStep.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/persistentStateStore.runtime.d.ts.map +1 -1
- package/dist/persistentStateStore.runtime.js +21 -7
- package/dist/persistentStateStore.runtime.js.map +1 -1
- package/dist/request/index.d.ts +2 -1
- package/dist/request/index.d.ts.map +1 -1
- package/dist/request/index.js +2 -1
- package/dist/request/index.js.map +1 -1
- package/dist/request/requestNamespace.d.ts.map +1 -1
- package/dist/request/requestNamespace.js +16 -3
- package/dist/request/requestNamespace.js.map +1 -1
- package/dist/request/security.d.ts +20 -1
- package/dist/request/security.d.ts.map +1 -1
- package/dist/request/security.js +62 -23
- package/dist/request/security.js.map +1 -1
- package/dist/request/securityExprRunner.d.ts +133 -0
- package/dist/request/securityExprRunner.d.ts.map +1 -0
- package/dist/request/securityExprRunner.js +235 -0
- package/dist/request/securityExprRunner.js.map +1 -0
- package/dist/request/streamBars.d.ts +14 -1
- package/dist/request/streamBars.d.ts.map +1 -1
- package/dist/request/streamBars.js +39 -1
- package/dist/request/streamBars.js.map +1 -1
- package/dist/runtimeContext.d.ts +48 -0
- package/dist/runtimeContext.d.ts.map +1 -1
- package/dist/runtimeContext.js.map +1 -1
- package/dist/seriesView.d.ts +42 -17
- package/dist/seriesView.d.ts.map +1 -1
- package/dist/seriesView.js +65 -42
- package/dist/seriesView.js.map +1 -1
- package/dist/state/index.d.ts +2 -1
- package/dist/state/index.d.ts.map +1 -1
- package/dist/state/index.js +2 -1
- package/dist/state/index.js.map +1 -1
- package/dist/state/lifecycle.d.ts +40 -0
- package/dist/state/lifecycle.d.ts.map +1 -1
- package/dist/state/lifecycle.js +53 -0
- package/dist/state/lifecycle.js.map +1 -1
- package/dist/state/seriesPersistence.d.ts +48 -0
- package/dist/state/seriesPersistence.d.ts.map +1 -0
- package/dist/state/seriesPersistence.js +87 -0
- package/dist/state/seriesPersistence.js.map +1 -0
- package/dist/state/seriesSlot.d.ts +105 -0
- package/dist/state/seriesSlot.d.ts.map +1 -0
- package/dist/state/seriesSlot.js +123 -0
- package/dist/state/seriesSlot.js.map +1 -0
- package/dist/state/stateNamespace.d.ts.map +1 -1
- package/dist/state/stateNamespace.js +28 -0
- package/dist/state/stateNamespace.js.map +1 -1
- package/dist/streamState.d.ts +25 -19
- package/dist/streamState.d.ts.map +1 -1
- package/dist/streamState.js +40 -66
- package/dist/streamState.js.map +1 -1
- package/dist/ta/adx.d.ts +3 -2
- package/dist/ta/adx.d.ts.map +1 -1
- package/dist/ta/adx.js +3 -2
- package/dist/ta/adx.js.map +1 -1
- package/dist/ta/alma.d.ts +6 -4
- package/dist/ta/alma.d.ts.map +1 -1
- package/dist/ta/alma.js +19 -6
- package/dist/ta/alma.js.map +1 -1
- package/dist/ta/atr.d.ts +3 -2
- package/dist/ta/atr.d.ts.map +1 -1
- package/dist/ta/atr.js +3 -2
- package/dist/ta/atr.js.map +1 -1
- package/dist/ta/bb.d.ts +3 -2
- package/dist/ta/bb.d.ts.map +1 -1
- package/dist/ta/bb.js +3 -2
- package/dist/ta/bb.js.map +1 -1
- package/dist/ta/chaikinOsc.d.ts +3 -2
- package/dist/ta/chaikinOsc.d.ts.map +1 -1
- package/dist/ta/chaikinOsc.js +3 -2
- package/dist/ta/chaikinOsc.js.map +1 -1
- package/dist/ta/crossover.d.ts +3 -2
- package/dist/ta/crossover.d.ts.map +1 -1
- package/dist/ta/crossover.js +3 -2
- package/dist/ta/crossover.js.map +1 -1
- package/dist/ta/crossunder.d.ts +3 -2
- package/dist/ta/crossunder.d.ts.map +1 -1
- package/dist/ta/crossunder.js +3 -2
- package/dist/ta/crossunder.js.map +1 -1
- package/dist/ta/dmi.d.ts +4 -3
- package/dist/ta/dmi.d.ts.map +1 -1
- package/dist/ta/dmi.js +4 -3
- package/dist/ta/dmi.js.map +1 -1
- package/dist/ta/ema.d.ts +3 -2
- package/dist/ta/ema.d.ts.map +1 -1
- package/dist/ta/ema.js +3 -2
- package/dist/ta/ema.js.map +1 -1
- package/dist/ta/eom.d.ts +3 -1
- package/dist/ta/eom.d.ts.map +1 -1
- package/dist/ta/eom.js +3 -1
- package/dist/ta/eom.js.map +1 -1
- package/dist/ta/highestbars.d.ts +25 -0
- package/dist/ta/highestbars.d.ts.map +1 -0
- package/dist/ta/highestbars.js +106 -0
- package/dist/ta/highestbars.js.map +1 -0
- package/dist/ta/historicalVolatility.d.ts +3 -2
- package/dist/ta/historicalVolatility.d.ts.map +1 -1
- package/dist/ta/historicalVolatility.js +3 -2
- package/dist/ta/historicalVolatility.js.map +1 -1
- package/dist/ta/ichimoku.d.ts +3 -1
- package/dist/ta/ichimoku.d.ts.map +1 -1
- package/dist/ta/ichimoku.js +3 -1
- package/dist/ta/ichimoku.js.map +1 -1
- package/dist/ta/lowestbars.d.ts +25 -0
- package/dist/ta/lowestbars.d.ts.map +1 -0
- package/dist/ta/lowestbars.js +102 -0
- package/dist/ta/lowestbars.js.map +1 -0
- package/dist/ta/macd.d.ts +3 -2
- package/dist/ta/macd.d.ts.map +1 -1
- package/dist/ta/macd.js +3 -2
- package/dist/ta/macd.js.map +1 -1
- package/dist/ta/massIndex.d.ts +3 -2
- package/dist/ta/massIndex.d.ts.map +1 -1
- package/dist/ta/massIndex.js +3 -2
- package/dist/ta/massIndex.js.map +1 -1
- package/dist/ta/mfi.d.ts +3 -1
- package/dist/ta/mfi.d.ts.map +1 -1
- package/dist/ta/mfi.js +3 -1
- package/dist/ta/mfi.js.map +1 -1
- package/dist/ta/netVolume.d.ts +3 -1
- package/dist/ta/netVolume.d.ts.map +1 -1
- package/dist/ta/netVolume.js +3 -1
- package/dist/ta/netVolume.js.map +1 -1
- package/dist/ta/nvi.d.ts +3 -1
- package/dist/ta/nvi.d.ts.map +1 -1
- package/dist/ta/nvi.js +3 -1
- package/dist/ta/nvi.js.map +1 -1
- package/dist/ta/persistence.d.ts.map +1 -1
- package/dist/ta/persistence.js +1 -40
- package/dist/ta/persistence.js.map +1 -1
- package/dist/ta/ppo.d.ts +3 -2
- package/dist/ta/ppo.d.ts.map +1 -1
- package/dist/ta/ppo.js +3 -2
- package/dist/ta/ppo.js.map +1 -1
- package/dist/ta/pvi.d.ts +3 -1
- package/dist/ta/pvi.d.ts.map +1 -1
- package/dist/ta/pvi.js +3 -1
- package/dist/ta/pvi.js.map +1 -1
- package/dist/ta/pvo.d.ts +3 -1
- package/dist/ta/pvo.d.ts.map +1 -1
- package/dist/ta/pvo.js +3 -1
- package/dist/ta/pvo.js.map +1 -1
- package/dist/ta/pvt.d.ts +3 -1
- package/dist/ta/pvt.d.ts.map +1 -1
- package/dist/ta/pvt.js +3 -1
- package/dist/ta/pvt.js.map +1 -1
- package/dist/ta/registry.d.ts +7 -1
- package/dist/ta/registry.d.ts.map +1 -1
- package/dist/ta/registry.js +4 -0
- package/dist/ta/registry.js.map +1 -1
- package/dist/ta/rsi.d.ts +3 -2
- package/dist/ta/rsi.d.ts.map +1 -1
- package/dist/ta/rsi.js +3 -2
- package/dist/ta/rsi.js.map +1 -1
- package/dist/ta/rvi.d.ts +3 -2
- package/dist/ta/rvi.d.ts.map +1 -1
- package/dist/ta/rvi.js +3 -2
- package/dist/ta/rvi.js.map +1 -1
- package/dist/ta/sma.d.ts +6 -3
- package/dist/ta/sma.d.ts.map +1 -1
- package/dist/ta/sma.js +6 -3
- package/dist/ta/sma.js.map +1 -1
- package/dist/ta/stdev.d.ts +3 -2
- package/dist/ta/stdev.d.ts.map +1 -1
- package/dist/ta/stdev.js +3 -2
- package/dist/ta/stdev.js.map +1 -1
- package/dist/ta/trendStrengthIndex.d.ts +3 -2
- package/dist/ta/trendStrengthIndex.d.ts.map +1 -1
- package/dist/ta/trendStrengthIndex.js +3 -2
- package/dist/ta/trendStrengthIndex.js.map +1 -1
- package/dist/ta/trix.d.ts +4 -3
- package/dist/ta/trix.d.ts.map +1 -1
- package/dist/ta/trix.js +4 -3
- package/dist/ta/trix.js.map +1 -1
- package/dist/ta/vortex.d.ts +3 -2
- package/dist/ta/vortex.d.ts.map +1 -1
- package/dist/ta/vortex.js +3 -2
- package/dist/ta/vortex.js.map +1 -1
- package/package.json +3 -3
- package/dist/ta/lib/applyOffset.d.ts +0 -19
- package/dist/ta/lib/applyOffset.d.ts.map +0 -1
- package/dist/ta/lib/applyOffset.js +0 -38
- package/dist/ta/lib/applyOffset.js.map +0 -1
|
@@ -8,13 +8,20 @@ import { appendSecondaryBar, appendSecondaryHistory, replaceSecondaryHead, } fro
|
|
|
8
8
|
import { resolveInputs } from "./inputs/index.js";
|
|
9
9
|
import { PERSISTENCE_INTERVAL_MS, maybeSaveStateSnapshot, restoreStateSnapshot, saveStateSnapshot, } from "./persistentStateStore.runtime.js";
|
|
10
10
|
import { validateSnapshot } from "./persistentStateStore.validate.js";
|
|
11
|
+
import { buildSecurityExprRunners, driveSecurityExpressions, } from "./request/securityExprRunner.js";
|
|
11
12
|
import { inMemoryStateStore } from "./stateStore.js";
|
|
12
13
|
import { createStreamState } from "./streamState.js";
|
|
13
14
|
import { createRuntimeViews, makeSymInfoView } from "./views/index.js";
|
|
14
15
|
function resolveCapacity(manifest) {
|
|
15
|
-
const
|
|
16
|
+
const { ohlcv, dynamicFallback } = manifest.seriesCapacities;
|
|
16
17
|
const fallback = manifest.maxLookback + 1;
|
|
17
|
-
|
|
18
|
+
// `dynamicFallback` is the compiler's §6.6 safety net: a non-literal
|
|
19
|
+
// series index (e.g. `trend[LOOKBACK]` with `const LOOKBACK = 20`)
|
|
20
|
+
// cannot be sized statically, so `extractMaxLookback` emits a 5000-slot
|
|
21
|
+
// request instead of bumping `maxLookback`. Honour it here — otherwise
|
|
22
|
+
// the buffer collapses to `maxLookback + 1` and every dynamic-index read
|
|
23
|
+
// past slot 0 returns NaN (the "forecast line never drawn" bug).
|
|
24
|
+
return Math.max(1, ohlcv ?? fallback, dynamicFallback ?? 0);
|
|
18
25
|
}
|
|
19
26
|
function createSecondaryStreams(manifest, capacity) {
|
|
20
27
|
const streams = new Map();
|
|
@@ -55,15 +62,24 @@ function pushSecondaryEvent(state, streamKey, event) {
|
|
|
55
62
|
pushUnknownSecondaryDiagnostic(state, streamKey);
|
|
56
63
|
return;
|
|
57
64
|
}
|
|
65
|
+
const ctx = state.runtimeContext;
|
|
58
66
|
switch (event.kind) {
|
|
59
67
|
case "history":
|
|
68
|
+
// History bars are finalised HTF closes: fill the buffer, then
|
|
69
|
+
// drive every registered runner once per bar in source order (a
|
|
70
|
+
// no-op until the main compute captures the callback).
|
|
60
71
|
appendSecondaryHistory(stream, event.bars);
|
|
72
|
+
for (const bar of event.bars) {
|
|
73
|
+
driveSecurityExpressions(ctx, streamKey, "close", bar);
|
|
74
|
+
}
|
|
61
75
|
return;
|
|
62
76
|
case "close":
|
|
63
77
|
appendSecondaryBar(stream, event.bar);
|
|
78
|
+
driveSecurityExpressions(ctx, streamKey, "close", event.bar);
|
|
64
79
|
return;
|
|
65
80
|
case "tick":
|
|
66
81
|
replaceSecondaryHead(stream, event.bar);
|
|
82
|
+
driveSecurityExpressions(ctx, streamKey, "tick", event.bar);
|
|
67
83
|
return;
|
|
68
84
|
}
|
|
69
85
|
}
|
|
@@ -120,6 +136,7 @@ function buildPrimaryState(args, primary) {
|
|
|
120
136
|
},
|
|
121
137
|
scriptMaxDrawings: primary.manifest.maxDrawings ?? null,
|
|
122
138
|
stateSlots: new Map(),
|
|
139
|
+
seriesSlots: new Map(),
|
|
123
140
|
secondaryStreams,
|
|
124
141
|
requestSecurityBars: new Map(),
|
|
125
142
|
requestSecurityAlignments: new Map(),
|
|
@@ -150,6 +167,10 @@ function buildPrimaryState(args, primary) {
|
|
|
150
167
|
args.plotOverrides ??
|
|
151
168
|
args.resolvePlotOverrides?.(primary.manifest.name) ??
|
|
152
169
|
Object.freeze({});
|
|
170
|
+
const exprRunners = buildSecurityExprRunners(primary.manifest, state.runtimeContext, capacity);
|
|
171
|
+
state.runtimeContext.securityExprRunners = exprRunners.bySlot;
|
|
172
|
+
state.runtimeContext.securityExprRunnersByInterval = exprRunners.byInterval;
|
|
173
|
+
state.runtimeContext.requestSecurityExprSeries = new Map();
|
|
153
174
|
return state;
|
|
154
175
|
}
|
|
155
176
|
function attachBundle(primary, bundle, capabilities, now) {
|
|
@@ -205,10 +226,13 @@ function attachBundle(primary, bundle, capabilities, now) {
|
|
|
205
226
|
* `ACTIVE_RUNTIME_CONTEXT`. Phase 1 ships a single-stream model; the
|
|
206
227
|
* `requestedIntervals` field on the manifest is always empty.
|
|
207
228
|
*
|
|
208
|
-
* Capacity sizing follows PLAN §6.6:
|
|
229
|
+
* Capacity sizing follows PLAN §6.6: take the max of
|
|
209
230
|
* `manifest.seriesCapacities.ohlcv` (compiler-emitted per-series
|
|
210
|
-
* lookback)
|
|
211
|
-
*
|
|
231
|
+
* lookback) or the `manifest.maxLookback + 1` floor, and
|
|
232
|
+
* `manifest.seriesCapacities.dynamicFallback` (the 5000-slot safety net the
|
|
233
|
+
* compiler emits when a series is read at a non-literal index it cannot size
|
|
234
|
+
* statically), clamped to a minimum of 1 so an empty-history script still has
|
|
235
|
+
* a valid head slot.
|
|
212
236
|
*
|
|
213
237
|
* @since 0.1 — widened to accept `CompiledScriptBundle` in 0.7.
|
|
214
238
|
* @example
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createScriptRunner.js","sourceRoot":"","sources":["../src/createScriptRunner.ts"],"names":[],"mappings":"AAAA,+DAA+D;AAC/D,+DAA+D;AAe/D,OAAO,EAAE,sBAAsB,EAAE,MAAM,8BAA8B,CAAC;AAEtE,OAAO,EAIH,oBAAoB,EACpB,eAAe,EACf,mBAAmB,EACnB,sBAAsB,GACzB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACxF,OAAO,EACH,OAAO,IAAI,WAAW,EACtB,KAAK,IAAI,SAAS,EAClB,UAAU,IAAI,cAAc,EAC5B,SAAS,IAAI,aAAa,EAC1B,SAAS,IAAI,aAAa,GAC7B,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inite. Licensed under the MIT License.\n// See the LICENSE file in the repo root for full license text.\n\nimport type {\n CandleEvent,\n Capabilities,\n PlotOverride,\n RunnerEmissions,\n} from \"@invinite-org/chartlang-adapter-kit\";\nimport type {\n Bar,\n CompiledScriptBundle,\n CompiledScriptObject,\n ComputeFn,\n ScriptManifest,\n} from \"@invinite-org/chartlang-core\";\nimport { isCompiledScriptBundle } from \"@invinite-org/chartlang-core\";\n\nimport {\n type DepOutputStore,\n type DepRunner,\n type SiblingRunner,\n createDepOutputStore,\n createDepRunner,\n createSiblingRunner,\n installDepOutputGlobal,\n} from \"./dep/index.js\";\nimport { pushDiagnostic, resolveDefaultPane, resolveScriptPane } from \"./emit/index.js\";\nimport {\n dispose as disposeImpl,\n drain as drainImpl,\n onBarClose as onBarCloseImpl,\n onBarTick as onBarTickImpl,\n onHistory as onHistoryImpl,\n} from \"./execution/index.js\";\nimport {\n appendSecondaryBar,\n appendSecondaryHistory,\n replaceSecondaryHead,\n} from \"./execution/secondaryStream.js\";\nimport { resolveInputs } from \"./inputs/index.js\";\nimport type { PersistentStateStore } from \"./persistentStateStore.js\";\nimport {\n PERSISTENCE_INTERVAL_MS,\n maybeSaveStateSnapshot,\n restoreStateSnapshot,\n saveStateSnapshot,\n} from \"./persistentStateStore.runtime.js\";\nimport { validateSnapshot } from \"./persistentStateStore.validate.js\";\nimport type { MutableRunnerEmissions, RuntimeContext } from \"./runtimeContext.js\";\nimport { type StateStore, inMemoryStateStore } from \"./stateStore.js\";\nimport { type StreamState, createStreamState } from \"./streamState.js\";\nimport { type AdapterSymInfo, createRuntimeViews, makeSymInfoView } from \"./views/index.js\";\n\n/**\n * Internal handle the execution functions read and mutate per step. Lives\n * inside `createScriptRunner`'s closure; never exposed on the public\n * barrel. `barIndex` is the only mutable field — `onBarClose` increments\n * it; `onBarTick` does not.\n *\n * @since 0.1\n * @example\n * // RunnerState is internal — execution functions accept it as\n * // their first argument:\n * // await onBarClose(state, rawBar);\n */\nexport type RunnerState = {\n readonly manifest: ScriptManifest;\n readonly compute: ComputeFn;\n readonly capabilities: Capabilities;\n readonly stateStore: StateStore;\n readonly persistenceIntervalMs: number;\n readonly now: () => number;\n readonly mainStream: StreamState;\n readonly runtimeContext: RuntimeContext;\n readonly emissions: MutableRunnerEmissions;\n /**\n * Sub-runners for every private dep entry of a\n * `CompiledScriptBundle`. Empty array for single-script callers.\n * Walked in declaration order before the primary's compute each\n * bar. @since 0.7\n */\n readonly depRunners: ReadonlyArray<DepRunner>;\n /**\n * Sub-runners for every drawn named-export entry of a\n * `CompiledScriptBundle`. Empty for single-script callers.\n * Walked in declaration order after deps, before the primary's\n * compute. @since 0.7\n */\n readonly siblingRunners: ReadonlyArray<SiblingRunner>;\n /**\n * Shared titled-output buffer for the bundle. `null` for\n * single-script callers (no deps to read from). @since 0.7\n */\n readonly depOutputStore: DepOutputStore | null;\n /**\n * Per-bar flag set by `runDepStep` when any dep halts. Read by\n * `onBarClose` / `onBarTick` after the primary's compute returns,\n * clearing the primary's plot/drawing/alert queues. Reset at the\n * top of every bar. @since 0.7\n */\n depErroredThisBar: boolean;\n barIndex: number;\n};\n\n/**\n * The user-facing handle `createScriptRunner` returns. Hosts (Worker,\n * QuickJS, conformance harness) drive a `ScriptRunner` through the\n * standard lifecycle: `load → onHistory → onBarClose × N → onBarTick × M\n * → drain → dispose`. PLAN §6.1 fixes this shape; consumer-repo hosts\n * pin against it.\n *\n * `onHistory` / `onBarClose` / `onBarTick` return `Promise<void>` — the\n * runtime allows compute bodies to `await` (Phase 1 doesn't, but the\n * surface is forward-compatible with Phase-5 `request.security` warmup).\n *\n * @since 0.1\n * @example\n * // import { createScriptRunner }\n * // from \"@invinite-org/chartlang-runtime\";\n * // const runner = createScriptRunner({ compiled, capabilities });\n * // await runner.onHistory(historicalBars);\n * // const emissions = runner.drain();\n * // runner.dispose();\n */\nexport type ScriptRunner = {\n onHistory(bars: ReadonlyArray<Bar>): Promise<void>;\n onBarClose(bar: Bar): Promise<void>;\n onBarTick(bar: Bar): Promise<void>;\n push(event: CandleEvent): Promise<void>;\n warmStart(currentMainBarTime: number): Promise<void>;\n drain(): RunnerEmissions;\n /**\n * Replace the per-slot presentation override map live. Cheap and\n * recompute-free — the swap takes effect on the NEXT push's\n * `compute`; the just-pushed bar's drain returns the pre-swap\n * emissions (already baked during that bar's `compute`). Entries\n * are frozen on assignment; overrides are presentation-only and\n * never feed `compute`.\n *\n * @since 0.8\n * @stable\n * @example\n * // runner.setPlotOverrides({ \"ema.chart.ts:12:5#0\": { visible: false } });\n */\n setPlotOverrides(next: Readonly<Record<string, PlotOverride>>): void;\n dispose(): Promise<void>;\n};\n\n/**\n * Constructor arguments for {@link createScriptRunner}. `stateStore`\n * defaults to {@link inMemoryStateStore} so callers without persistence\n * needs can omit it. `symInfo` defaults to empty sentinels and is gated\n * by `capabilities.symInfoFields` at mount. `resolveInputs` is called\n * once at mount with `manifest.name`; worker-backed callers can pass an\n * already structured-cloned `inputOverrides` record instead.\n * `persistentStateStore` is the PLAN §6.9 cross-mount snapshot store;\n * `persistenceIntervalMs` defaults to 60 seconds.\n *\n * @since 0.1\n * @example\n * // const args: CreateScriptRunnerArgs = {\n * // compiled,\n * // capabilities,\n * // stateStore: inMemoryStateStore(),\n * // };\n */\nexport type CreateScriptRunnerArgs = {\n /**\n * Either a single `CompiledScriptObject` (Phase-1 contract — preserved\n * byte-identically) or a `CompiledScriptBundle` whose primary script\n * is mounted alongside one `DepRunner` per private dep entry and one\n * `SiblingRunner` per drawn named export.\n *\n * @since 0.1 — widened to bundle in 0.7\n */\n readonly compiled: CompiledScriptObject | CompiledScriptBundle;\n readonly capabilities: Capabilities;\n readonly stateStore?: StateStore;\n readonly persistentStateStore?: PersistentStateStore;\n readonly persistenceIntervalMs?: number;\n readonly now?: () => number;\n readonly symInfo?: AdapterSymInfo;\n readonly resolveInputs?: (scriptId: string) => Readonly<Record<string, unknown>>;\n readonly inputOverrides?: Readonly<Record<string, unknown>>;\n readonly resolvePlotOverrides?: (scriptId: string) => Readonly<Record<string, PlotOverride>>;\n readonly plotOverrides?: Readonly<Record<string, PlotOverride>>;\n};\n\nfunction resolveCapacity(manifest: ScriptManifest): number {\n const requested = manifest.seriesCapacities.ohlcv;\n const fallback = manifest.maxLookback + 1;\n return Math.max(1, requested ?? fallback);\n}\n\nfunction createSecondaryStreams(\n manifest: ScriptManifest,\n capacity: number,\n): Map<string, StreamState> {\n const streams = new Map<string, StreamState>();\n for (const interval of manifest.requestedIntervals) {\n if (streams.has(interval)) continue;\n streams.set(interval, createStreamState({ interval, capacity, symbol: \"\" }));\n }\n return streams;\n}\n\nasync function pushMainEvent(state: RunnerState, event: CandleEvent): Promise<void> {\n switch (event.kind) {\n case \"history\":\n await onHistoryImpl(state, event.bars);\n return;\n case \"close\":\n await onBarCloseImpl(state, event.bar);\n await maybeSaveStateSnapshot(state, state.now(), state.persistenceIntervalMs);\n return;\n case \"tick\":\n await onBarTickImpl(state, event.bar);\n return;\n }\n}\n\nfunction pushUnknownSecondaryDiagnostic(state: RunnerState, streamKey: string): void {\n pushDiagnostic(state.emissions, {\n kind: \"diagnostic\",\n severity: \"warning\",\n code: \"unknown-secondary-stream\",\n message: `Secondary stream \"${streamKey}\" was not registered by the script manifest`,\n slotId: null,\n bar: state.barIndex,\n });\n}\n\nfunction pushSecondaryEvent(state: RunnerState, streamKey: string, event: CandleEvent): void {\n const stream = state.runtimeContext.secondaryStreams.get(streamKey);\n if (stream === undefined) {\n pushUnknownSecondaryDiagnostic(state, streamKey);\n return;\n }\n switch (event.kind) {\n case \"history\":\n appendSecondaryHistory(stream, event.bars);\n return;\n case \"close\":\n appendSecondaryBar(stream, event.bar);\n return;\n case \"tick\":\n replaceSecondaryHead(stream, event.bar);\n return;\n }\n}\n\nfunction primaryOf(compiled: CompiledScriptObject | CompiledScriptBundle): CompiledScriptObject {\n return isCompiledScriptBundle(compiled) ? compiled.primary : compiled;\n}\n\nfunction buildPrimaryState(\n args: CreateScriptRunnerArgs,\n primary: CompiledScriptObject,\n): RunnerState {\n const capacity = resolveCapacity(primary.manifest);\n const mainStream = createStreamState({ interval: \"\", capacity, symbol: \"\" });\n const secondaryStreams = createSecondaryStreams(primary.manifest, capacity);\n const stateStore = args.stateStore ?? inMemoryStateStore();\n const now = args.now ?? Date.now;\n const views = createRuntimeViews({\n syminfo: makeSymInfoView(args.symInfo ?? {}, args.capabilities.symInfoFields),\n });\n const emissions: MutableRunnerEmissions = {\n plots: [],\n drawings: [],\n alerts: [],\n alertConditions: [],\n logs: [],\n diagnostics: [],\n fromBar: 0,\n toBar: 0,\n };\n const alertConditions = new Map(\n (primary.manifest.alertConditions ?? []).map((condition) => [condition.id, condition]),\n );\n\n const state: RunnerState = {\n manifest: primary.manifest,\n compute: primary.compute,\n capabilities: args.capabilities,\n stateStore,\n persistenceIntervalMs: args.persistenceIntervalMs ?? PERSISTENCE_INTERVAL_MS,\n now,\n mainStream,\n runtimeContext: {\n stream: mainStream,\n stateStore,\n ...(args.persistentStateStore === undefined\n ? {}\n : { persistentStateStore: args.persistentStateStore }),\n lastPersistTime: 0,\n capabilities: args.capabilities,\n emissions,\n barIndex: () => state.barIndex,\n isTick: false,\n drawingSlots: new Map(),\n drawingSubIdCounters: new Map(),\n drawingBucketCounters: {\n lines: 0,\n labels: 0,\n boxes: 0,\n polylines: 0,\n other: 0,\n },\n scriptMaxDrawings: primary.manifest.maxDrawings ?? null,\n stateSlots: new Map(),\n secondaryStreams,\n requestSecurityBars: new Map(),\n requestSecurityAlignments: new Map(),\n requestSecurityAscendingBars: new Map(),\n requestLowerTfViews: new Map(),\n diagnosedRequestKeys: new Set(),\n alertConditions,\n diagnosedAlertConditionKeys: new Set(),\n logBudget: 0,\n logBudgetExceededDiagnosed: false,\n resolvedInputs: Object.freeze({}),\n defaultPane: resolveDefaultPane(primary.manifest),\n scriptPane: resolveScriptPane(primary.manifest),\n plotOverrides: Object.freeze({}),\n diagnosedInputKeys: new Set(),\n views,\n },\n emissions,\n depRunners: [],\n siblingRunners: [],\n depOutputStore: null,\n depErroredThisBar: false,\n barIndex: 0,\n };\n const overrides =\n args.inputOverrides ?? args.resolveInputs?.(primary.manifest.name) ?? Object.freeze({});\n state.runtimeContext.resolvedInputs = resolveInputs(\n primary.manifest,\n overrides,\n state.runtimeContext,\n );\n state.runtimeContext.plotOverrides =\n args.plotOverrides ??\n args.resolvePlotOverrides?.(primary.manifest.name) ??\n Object.freeze({});\n return state;\n}\n\nfunction attachBundle(\n primary: RunnerState,\n bundle: CompiledScriptBundle,\n capabilities: Capabilities,\n now: () => number,\n): void {\n const consumerLookback = Math.max(\n primary.manifest.maxLookback,\n ...bundle.siblings.map((s) => s.compiled.manifest.maxLookback),\n );\n const storeCapacity = Math.max(1, consumerLookback + 1);\n const producers = [\n ...bundle.dependencies.map((d) => ({\n producerId: d.localId,\n outputs: (d.compiled.manifest.outputs ?? []).map((o) => ({\n title: o.title,\n })),\n })),\n ...bundle.siblings.map((s) => ({\n producerId: s.exportName,\n outputs: (s.compiled.manifest.outputs ?? []).map((o) => ({\n title: o.title,\n })),\n })),\n ];\n const store = createDepOutputStore({ producers, capacity: storeCapacity });\n const depRunners: DepRunner[] = bundle.dependencies.map((entry) =>\n createDepRunner({\n compiled: entry.compiled,\n localId: entry.localId,\n parentCapabilities: capabilities,\n mainStream: primary.mainStream,\n secondaryStreams: primary.runtimeContext.secondaryStreams,\n depOutputStore: store,\n inputOverrides: entry.inputOverrides ?? Object.freeze({}),\n now,\n }),\n );\n const siblingRunners: SiblingRunner[] = bundle.siblings.map((entry) =>\n createSiblingRunner({\n compiled: entry.compiled,\n exportName: entry.exportName,\n parentCapabilities: capabilities,\n mainStream: primary.mainStream,\n secondaryStreams: primary.runtimeContext.secondaryStreams,\n depOutputStore: store,\n inputOverrides: Object.freeze({}),\n now,\n }),\n );\n Object.assign(primary, {\n depRunners,\n siblingRunners,\n depOutputStore: store,\n });\n primary.runtimeContext.depOutputStore = store;\n installDepOutputGlobal();\n}\n\n/**\n * Build a `ScriptRunner` for a compiled chartlang script. The runner\n * owns one `StreamState`, one `MutableRunnerEmissions` queue set, and\n * the `RuntimeContext` Task 7-8 primitives read through\n * `ACTIVE_RUNTIME_CONTEXT`. Phase 1 ships a single-stream model; the\n * `requestedIntervals` field on the manifest is always empty.\n *\n * Capacity sizing follows PLAN §6.6: prefer\n * `manifest.seriesCapacities.ohlcv` (compiler-emitted per-series\n * lookback) and fall back to `manifest.maxLookback + 1`, clamped to a\n * minimum of 1 so an empty-history script still has a valid head slot.\n *\n * @since 0.1 — widened to accept `CompiledScriptBundle` in 0.7.\n * @example\n * // import { createScriptRunner } from \"@invinite-org/chartlang-runtime\";\n * // const runner = createScriptRunner({ compiled, capabilities });\n * // await runner.onHistory([]);\n * // runner.drain();\n * // runner.dispose();\n */\nexport function createScriptRunner(args: CreateScriptRunnerArgs): ScriptRunner {\n const primary = primaryOf(args.compiled);\n const state = buildPrimaryState(args, primary);\n if (isCompiledScriptBundle(args.compiled)) {\n attachBundle(state, args.compiled, args.capabilities, state.now);\n }\n\n return Object.freeze({\n async onHistory(bars) {\n await onHistoryImpl(state, bars);\n },\n async onBarClose(bar) {\n await onBarCloseImpl(state, bar);\n await maybeSaveStateSnapshot(state, state.now(), state.persistenceIntervalMs);\n },\n async onBarTick(bar) {\n await onBarTickImpl(state, bar);\n },\n async push(event) {\n if (event.streamKey === undefined) {\n await pushMainEvent(state, event);\n return;\n }\n pushSecondaryEvent(state, event.streamKey, event);\n },\n async warmStart(currentMainBarTime) {\n const store = state.runtimeContext.persistentStateStore;\n if (store === undefined) return;\n const snap = await store.load();\n if (snap === null) return;\n if (!validateSnapshot(snap)) return;\n if (snap.lastBarTime >= currentMainBarTime) {\n pushDiagnostic(state.emissions, {\n kind: \"diagnostic\",\n severity: \"warning\",\n code: \"state-snapshot-future-dated\",\n message: \"persistent state snapshot is ahead of the current bar cursor\",\n slotId: null,\n bar: state.barIndex,\n });\n try {\n await store.clear();\n } catch (err) {\n pushDiagnostic(state.emissions, {\n kind: \"diagnostic\",\n severity: \"warning\",\n code: \"state-snapshot-save-failed\",\n message: err instanceof Error ? err.message : String(err),\n slotId: null,\n bar: state.barIndex,\n });\n }\n return;\n }\n restoreStateSnapshot(state, snap);\n state.runtimeContext.lastPersistTime = snap.savedAt;\n pushDiagnostic(state.emissions, {\n kind: \"diagnostic\",\n severity: \"info\",\n code: \"state-snapshot-restored\",\n message: `persistent state snapshot restored through bar ${snap.lastBarTime}`,\n slotId: null,\n bar: state.barIndex,\n });\n },\n drain() {\n return drainImpl(state);\n },\n setPlotOverrides(next) {\n state.runtimeContext.plotOverrides = Object.freeze({ ...next });\n },\n async dispose() {\n const finalSave = saveStateSnapshot(state, state.now());\n disposeImpl(state);\n await finalSave;\n },\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"createScriptRunner.js","sourceRoot":"","sources":["../src/createScriptRunner.ts"],"names":[],"mappings":"AAAA,+DAA+D;AAC/D,+DAA+D;AAe/D,OAAO,EAAE,sBAAsB,EAAE,MAAM,8BAA8B,CAAC;AAEtE,OAAO,EAIH,oBAAoB,EACpB,eAAe,EACf,mBAAmB,EACnB,sBAAsB,GACzB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACxF,OAAO,EACH,OAAO,IAAI,WAAW,EACtB,KAAK,IAAI,SAAS,EAClB,UAAU,IAAI,cAAc,EAC5B,SAAS,IAAI,aAAa,EAC1B,SAAS,IAAI,aAAa,GAC7B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACH,kBAAkB,EAClB,sBAAsB,EACtB,oBAAoB,GACvB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAElD,OAAO,EACH,uBAAuB,EACvB,sBAAsB,EACtB,oBAAoB,EACpB,iBAAiB,GACpB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,oCAAoC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E;gBAC5B,IAAI,EAAE,YAAY;gBAClB,QAAQ,EAAE,MAAM;gBAChB,IAAI,EAAE,yBAAyB;gBAC/B,OAAO,EAAE,kDAAkD,IAAI,CAAC,WAAW,EAAE;gBAC7E,MAAM,EAAE,IAAI;gBACZ,GAAG,EAAE,KAAK,CAAC,QAAQ;aACtB,CAAC,CAAC;QACP,CAAC;QACD,KAAK;YACD,OAAO,SAAS,CAAC,KAAK,CAAC,CAAC;QAC5B,CAAC;QACD,gBAAgB,CAAC,IAAI;YACjB,KAAK,CAAC,cAAc,CAAC,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;QACpE,CAAC;QACD,KAAK,CAAC,OAAO;YACT,MAAM,SAAS,GAAG,iBAAiB,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC;YACxD,WAAW,CAAC,KAAK,CAAC,CAAC;YACnB,MAAM,SAAS,CAAC;QACpB,CAAC;KACJ,CAAC,CAAC;AACP,CAAC","sourcesContent":["// Copyright (c) 2026 Invinite. Licensed under the MIT License.\n// See the LICENSE file in the repo root for full license text.\n\nimport type {\n CandleEvent,\n Capabilities,\n PlotOverride,\n RunnerEmissions,\n} from \"@invinite-org/chartlang-adapter-kit\";\nimport type {\n Bar,\n CompiledScriptBundle,\n CompiledScriptObject,\n ComputeFn,\n ScriptManifest,\n} from \"@invinite-org/chartlang-core\";\nimport { isCompiledScriptBundle } from \"@invinite-org/chartlang-core\";\n\nimport {\n type DepOutputStore,\n type DepRunner,\n type SiblingRunner,\n createDepOutputStore,\n createDepRunner,\n createSiblingRunner,\n installDepOutputGlobal,\n} from \"./dep/index.js\";\nimport { pushDiagnostic, resolveDefaultPane, resolveScriptPane } from \"./emit/index.js\";\nimport {\n dispose as disposeImpl,\n drain as drainImpl,\n onBarClose as onBarCloseImpl,\n onBarTick as onBarTickImpl,\n onHistory as onHistoryImpl,\n} from \"./execution/index.js\";\nimport {\n appendSecondaryBar,\n appendSecondaryHistory,\n replaceSecondaryHead,\n} from \"./execution/secondaryStream.js\";\nimport { resolveInputs } from \"./inputs/index.js\";\nimport type { PersistentStateStore } from \"./persistentStateStore.js\";\nimport {\n PERSISTENCE_INTERVAL_MS,\n maybeSaveStateSnapshot,\n restoreStateSnapshot,\n saveStateSnapshot,\n} from \"./persistentStateStore.runtime.js\";\nimport { validateSnapshot } from \"./persistentStateStore.validate.js\";\nimport {\n buildSecurityExprRunners,\n driveSecurityExpressions,\n} from \"./request/securityExprRunner.js\";\nimport type { MutableRunnerEmissions, RuntimeContext } from \"./runtimeContext.js\";\nimport { type StateStore, inMemoryStateStore } from \"./stateStore.js\";\nimport { type StreamState, createStreamState } from \"./streamState.js\";\nimport { type AdapterSymInfo, createRuntimeViews, makeSymInfoView } from \"./views/index.js\";\n\n/**\n * Internal handle the execution functions read and mutate per step. Lives\n * inside `createScriptRunner`'s closure; never exposed on the public\n * barrel. `barIndex` is the only mutable field — `onBarClose` increments\n * it; `onBarTick` does not.\n *\n * @since 0.1\n * @example\n * // RunnerState is internal — execution functions accept it as\n * // their first argument:\n * // await onBarClose(state, rawBar);\n */\nexport type RunnerState = {\n readonly manifest: ScriptManifest;\n readonly compute: ComputeFn;\n readonly capabilities: Capabilities;\n readonly stateStore: StateStore;\n readonly persistenceIntervalMs: number;\n readonly now: () => number;\n readonly mainStream: StreamState;\n readonly runtimeContext: RuntimeContext;\n readonly emissions: MutableRunnerEmissions;\n /**\n * Sub-runners for every private dep entry of a\n * `CompiledScriptBundle`. Empty array for single-script callers.\n * Walked in declaration order before the primary's compute each\n * bar. @since 0.7\n */\n readonly depRunners: ReadonlyArray<DepRunner>;\n /**\n * Sub-runners for every drawn named-export entry of a\n * `CompiledScriptBundle`. Empty for single-script callers.\n * Walked in declaration order after deps, before the primary's\n * compute. @since 0.7\n */\n readonly siblingRunners: ReadonlyArray<SiblingRunner>;\n /**\n * Shared titled-output buffer for the bundle. `null` for\n * single-script callers (no deps to read from). @since 0.7\n */\n readonly depOutputStore: DepOutputStore | null;\n /**\n * Per-bar flag set by `runDepStep` when any dep halts. Read by\n * `onBarClose` / `onBarTick` after the primary's compute returns,\n * clearing the primary's plot/drawing/alert queues. Reset at the\n * top of every bar. @since 0.7\n */\n depErroredThisBar: boolean;\n barIndex: number;\n};\n\n/**\n * The user-facing handle `createScriptRunner` returns. Hosts (Worker,\n * QuickJS, conformance harness) drive a `ScriptRunner` through the\n * standard lifecycle: `load → onHistory → onBarClose × N → onBarTick × M\n * → drain → dispose`. PLAN §6.1 fixes this shape; consumer-repo hosts\n * pin against it.\n *\n * `onHistory` / `onBarClose` / `onBarTick` return `Promise<void>` — the\n * runtime allows compute bodies to `await` (Phase 1 doesn't, but the\n * surface is forward-compatible with Phase-5 `request.security` warmup).\n *\n * @since 0.1\n * @example\n * // import { createScriptRunner }\n * // from \"@invinite-org/chartlang-runtime\";\n * // const runner = createScriptRunner({ compiled, capabilities });\n * // await runner.onHistory(historicalBars);\n * // const emissions = runner.drain();\n * // runner.dispose();\n */\nexport type ScriptRunner = {\n onHistory(bars: ReadonlyArray<Bar>): Promise<void>;\n onBarClose(bar: Bar): Promise<void>;\n onBarTick(bar: Bar): Promise<void>;\n push(event: CandleEvent): Promise<void>;\n warmStart(currentMainBarTime: number): Promise<void>;\n drain(): RunnerEmissions;\n /**\n * Replace the per-slot presentation override map live. Cheap and\n * recompute-free — the swap takes effect on the NEXT push's\n * `compute`; the just-pushed bar's drain returns the pre-swap\n * emissions (already baked during that bar's `compute`). Entries\n * are frozen on assignment; overrides are presentation-only and\n * never feed `compute`.\n *\n * @since 0.8\n * @stable\n * @example\n * // runner.setPlotOverrides({ \"ema.chart.ts:12:5#0\": { visible: false } });\n */\n setPlotOverrides(next: Readonly<Record<string, PlotOverride>>): void;\n dispose(): Promise<void>;\n};\n\n/**\n * Constructor arguments for {@link createScriptRunner}. `stateStore`\n * defaults to {@link inMemoryStateStore} so callers without persistence\n * needs can omit it. `symInfo` defaults to empty sentinels and is gated\n * by `capabilities.symInfoFields` at mount. `resolveInputs` is called\n * once at mount with `manifest.name`; worker-backed callers can pass an\n * already structured-cloned `inputOverrides` record instead.\n * `persistentStateStore` is the PLAN §6.9 cross-mount snapshot store;\n * `persistenceIntervalMs` defaults to 60 seconds.\n *\n * @since 0.1\n * @example\n * // const args: CreateScriptRunnerArgs = {\n * // compiled,\n * // capabilities,\n * // stateStore: inMemoryStateStore(),\n * // };\n */\nexport type CreateScriptRunnerArgs = {\n /**\n * Either a single `CompiledScriptObject` (Phase-1 contract — preserved\n * byte-identically) or a `CompiledScriptBundle` whose primary script\n * is mounted alongside one `DepRunner` per private dep entry and one\n * `SiblingRunner` per drawn named export.\n *\n * @since 0.1 — widened to bundle in 0.7\n */\n readonly compiled: CompiledScriptObject | CompiledScriptBundle;\n readonly capabilities: Capabilities;\n readonly stateStore?: StateStore;\n readonly persistentStateStore?: PersistentStateStore;\n readonly persistenceIntervalMs?: number;\n readonly now?: () => number;\n readonly symInfo?: AdapterSymInfo;\n readonly resolveInputs?: (scriptId: string) => Readonly<Record<string, unknown>>;\n readonly inputOverrides?: Readonly<Record<string, unknown>>;\n readonly resolvePlotOverrides?: (scriptId: string) => Readonly<Record<string, PlotOverride>>;\n readonly plotOverrides?: Readonly<Record<string, PlotOverride>>;\n};\n\nfunction resolveCapacity(manifest: ScriptManifest): number {\n const { ohlcv, dynamicFallback } = manifest.seriesCapacities;\n const fallback = manifest.maxLookback + 1;\n // `dynamicFallback` is the compiler's §6.6 safety net: a non-literal\n // series index (e.g. `trend[LOOKBACK]` with `const LOOKBACK = 20`)\n // cannot be sized statically, so `extractMaxLookback` emits a 5000-slot\n // request instead of bumping `maxLookback`. Honour it here — otherwise\n // the buffer collapses to `maxLookback + 1` and every dynamic-index read\n // past slot 0 returns NaN (the \"forecast line never drawn\" bug).\n return Math.max(1, ohlcv ?? fallback, dynamicFallback ?? 0);\n}\n\nfunction createSecondaryStreams(\n manifest: ScriptManifest,\n capacity: number,\n): Map<string, StreamState> {\n const streams = new Map<string, StreamState>();\n for (const interval of manifest.requestedIntervals) {\n if (streams.has(interval)) continue;\n streams.set(interval, createStreamState({ interval, capacity, symbol: \"\" }));\n }\n return streams;\n}\n\nasync function pushMainEvent(state: RunnerState, event: CandleEvent): Promise<void> {\n switch (event.kind) {\n case \"history\":\n await onHistoryImpl(state, event.bars);\n return;\n case \"close\":\n await onBarCloseImpl(state, event.bar);\n await maybeSaveStateSnapshot(state, state.now(), state.persistenceIntervalMs);\n return;\n case \"tick\":\n await onBarTickImpl(state, event.bar);\n return;\n }\n}\n\nfunction pushUnknownSecondaryDiagnostic(state: RunnerState, streamKey: string): void {\n pushDiagnostic(state.emissions, {\n kind: \"diagnostic\",\n severity: \"warning\",\n code: \"unknown-secondary-stream\",\n message: `Secondary stream \"${streamKey}\" was not registered by the script manifest`,\n slotId: null,\n bar: state.barIndex,\n });\n}\n\nfunction pushSecondaryEvent(state: RunnerState, streamKey: string, event: CandleEvent): void {\n const stream = state.runtimeContext.secondaryStreams.get(streamKey);\n if (stream === undefined) {\n pushUnknownSecondaryDiagnostic(state, streamKey);\n return;\n }\n const ctx = state.runtimeContext;\n switch (event.kind) {\n case \"history\":\n // History bars are finalised HTF closes: fill the buffer, then\n // drive every registered runner once per bar in source order (a\n // no-op until the main compute captures the callback).\n appendSecondaryHistory(stream, event.bars);\n for (const bar of event.bars) {\n driveSecurityExpressions(ctx, streamKey, \"close\", bar);\n }\n return;\n case \"close\":\n appendSecondaryBar(stream, event.bar);\n driveSecurityExpressions(ctx, streamKey, \"close\", event.bar);\n return;\n case \"tick\":\n replaceSecondaryHead(stream, event.bar);\n driveSecurityExpressions(ctx, streamKey, \"tick\", event.bar);\n return;\n }\n}\n\nfunction primaryOf(compiled: CompiledScriptObject | CompiledScriptBundle): CompiledScriptObject {\n return isCompiledScriptBundle(compiled) ? compiled.primary : compiled;\n}\n\nfunction buildPrimaryState(\n args: CreateScriptRunnerArgs,\n primary: CompiledScriptObject,\n): RunnerState {\n const capacity = resolveCapacity(primary.manifest);\n const mainStream = createStreamState({ interval: \"\", capacity, symbol: \"\" });\n const secondaryStreams = createSecondaryStreams(primary.manifest, capacity);\n const stateStore = args.stateStore ?? inMemoryStateStore();\n const now = args.now ?? Date.now;\n const views = createRuntimeViews({\n syminfo: makeSymInfoView(args.symInfo ?? {}, args.capabilities.symInfoFields),\n });\n const emissions: MutableRunnerEmissions = {\n plots: [],\n drawings: [],\n alerts: [],\n alertConditions: [],\n logs: [],\n diagnostics: [],\n fromBar: 0,\n toBar: 0,\n };\n const alertConditions = new Map(\n (primary.manifest.alertConditions ?? []).map((condition) => [condition.id, condition]),\n );\n\n const state: RunnerState = {\n manifest: primary.manifest,\n compute: primary.compute,\n capabilities: args.capabilities,\n stateStore,\n persistenceIntervalMs: args.persistenceIntervalMs ?? PERSISTENCE_INTERVAL_MS,\n now,\n mainStream,\n runtimeContext: {\n stream: mainStream,\n stateStore,\n ...(args.persistentStateStore === undefined\n ? {}\n : { persistentStateStore: args.persistentStateStore }),\n lastPersistTime: 0,\n capabilities: args.capabilities,\n emissions,\n barIndex: () => state.barIndex,\n isTick: false,\n drawingSlots: new Map(),\n drawingSubIdCounters: new Map(),\n drawingBucketCounters: {\n lines: 0,\n labels: 0,\n boxes: 0,\n polylines: 0,\n other: 0,\n },\n scriptMaxDrawings: primary.manifest.maxDrawings ?? null,\n stateSlots: new Map(),\n seriesSlots: new Map(),\n secondaryStreams,\n requestSecurityBars: new Map(),\n requestSecurityAlignments: new Map(),\n requestSecurityAscendingBars: new Map(),\n requestLowerTfViews: new Map(),\n diagnosedRequestKeys: new Set(),\n alertConditions,\n diagnosedAlertConditionKeys: new Set(),\n logBudget: 0,\n logBudgetExceededDiagnosed: false,\n resolvedInputs: Object.freeze({}),\n defaultPane: resolveDefaultPane(primary.manifest),\n scriptPane: resolveScriptPane(primary.manifest),\n plotOverrides: Object.freeze({}),\n diagnosedInputKeys: new Set(),\n views,\n },\n emissions,\n depRunners: [],\n siblingRunners: [],\n depOutputStore: null,\n depErroredThisBar: false,\n barIndex: 0,\n };\n const overrides =\n args.inputOverrides ?? args.resolveInputs?.(primary.manifest.name) ?? Object.freeze({});\n state.runtimeContext.resolvedInputs = resolveInputs(\n primary.manifest,\n overrides,\n state.runtimeContext,\n );\n state.runtimeContext.plotOverrides =\n args.plotOverrides ??\n args.resolvePlotOverrides?.(primary.manifest.name) ??\n Object.freeze({});\n const exprRunners = buildSecurityExprRunners(primary.manifest, state.runtimeContext, capacity);\n state.runtimeContext.securityExprRunners = exprRunners.bySlot;\n state.runtimeContext.securityExprRunnersByInterval = exprRunners.byInterval;\n state.runtimeContext.requestSecurityExprSeries = new Map();\n return state;\n}\n\nfunction attachBundle(\n primary: RunnerState,\n bundle: CompiledScriptBundle,\n capabilities: Capabilities,\n now: () => number,\n): void {\n const consumerLookback = Math.max(\n primary.manifest.maxLookback,\n ...bundle.siblings.map((s) => s.compiled.manifest.maxLookback),\n );\n const storeCapacity = Math.max(1, consumerLookback + 1);\n const producers = [\n ...bundle.dependencies.map((d) => ({\n producerId: d.localId,\n outputs: (d.compiled.manifest.outputs ?? []).map((o) => ({\n title: o.title,\n })),\n })),\n ...bundle.siblings.map((s) => ({\n producerId: s.exportName,\n outputs: (s.compiled.manifest.outputs ?? []).map((o) => ({\n title: o.title,\n })),\n })),\n ];\n const store = createDepOutputStore({ producers, capacity: storeCapacity });\n const depRunners: DepRunner[] = bundle.dependencies.map((entry) =>\n createDepRunner({\n compiled: entry.compiled,\n localId: entry.localId,\n parentCapabilities: capabilities,\n mainStream: primary.mainStream,\n secondaryStreams: primary.runtimeContext.secondaryStreams,\n depOutputStore: store,\n inputOverrides: entry.inputOverrides ?? Object.freeze({}),\n now,\n }),\n );\n const siblingRunners: SiblingRunner[] = bundle.siblings.map((entry) =>\n createSiblingRunner({\n compiled: entry.compiled,\n exportName: entry.exportName,\n parentCapabilities: capabilities,\n mainStream: primary.mainStream,\n secondaryStreams: primary.runtimeContext.secondaryStreams,\n depOutputStore: store,\n inputOverrides: Object.freeze({}),\n now,\n }),\n );\n Object.assign(primary, {\n depRunners,\n siblingRunners,\n depOutputStore: store,\n });\n primary.runtimeContext.depOutputStore = store;\n installDepOutputGlobal();\n}\n\n/**\n * Build a `ScriptRunner` for a compiled chartlang script. The runner\n * owns one `StreamState`, one `MutableRunnerEmissions` queue set, and\n * the `RuntimeContext` Task 7-8 primitives read through\n * `ACTIVE_RUNTIME_CONTEXT`. Phase 1 ships a single-stream model; the\n * `requestedIntervals` field on the manifest is always empty.\n *\n * Capacity sizing follows PLAN §6.6: take the max of\n * `manifest.seriesCapacities.ohlcv` (compiler-emitted per-series\n * lookback) or the `manifest.maxLookback + 1` floor, and\n * `manifest.seriesCapacities.dynamicFallback` (the 5000-slot safety net the\n * compiler emits when a series is read at a non-literal index it cannot size\n * statically), clamped to a minimum of 1 so an empty-history script still has\n * a valid head slot.\n *\n * @since 0.1 — widened to accept `CompiledScriptBundle` in 0.7.\n * @example\n * // import { createScriptRunner } from \"@invinite-org/chartlang-runtime\";\n * // const runner = createScriptRunner({ compiled, capabilities });\n * // await runner.onHistory([]);\n * // runner.drain();\n * // runner.dispose();\n */\nexport function createScriptRunner(args: CreateScriptRunnerArgs): ScriptRunner {\n const primary = primaryOf(args.compiled);\n const state = buildPrimaryState(args, primary);\n if (isCompiledScriptBundle(args.compiled)) {\n attachBundle(state, args.compiled, args.capabilities, state.now);\n }\n\n return Object.freeze({\n async onHistory(bars) {\n await onHistoryImpl(state, bars);\n },\n async onBarClose(bar) {\n await onBarCloseImpl(state, bar);\n await maybeSaveStateSnapshot(state, state.now(), state.persistenceIntervalMs);\n },\n async onBarTick(bar) {\n await onBarTickImpl(state, bar);\n },\n async push(event) {\n if (event.streamKey === undefined) {\n await pushMainEvent(state, event);\n return;\n }\n pushSecondaryEvent(state, event.streamKey, event);\n },\n async warmStart(currentMainBarTime) {\n const store = state.runtimeContext.persistentStateStore;\n if (store === undefined) return;\n const snap = await store.load();\n if (snap === null) return;\n if (!validateSnapshot(snap)) return;\n if (snap.lastBarTime >= currentMainBarTime) {\n pushDiagnostic(state.emissions, {\n kind: \"diagnostic\",\n severity: \"warning\",\n code: \"state-snapshot-future-dated\",\n message: \"persistent state snapshot is ahead of the current bar cursor\",\n slotId: null,\n bar: state.barIndex,\n });\n try {\n await store.clear();\n } catch (err) {\n pushDiagnostic(state.emissions, {\n kind: \"diagnostic\",\n severity: \"warning\",\n code: \"state-snapshot-save-failed\",\n message: err instanceof Error ? err.message : String(err),\n slotId: null,\n bar: state.barIndex,\n });\n }\n return;\n }\n restoreStateSnapshot(state, snap);\n state.runtimeContext.lastPersistTime = snap.savedAt;\n pushDiagnostic(state.emissions, {\n kind: \"diagnostic\",\n severity: \"info\",\n code: \"state-snapshot-restored\",\n message: `persistent state snapshot restored through bar ${snap.lastBarTime}`,\n slotId: null,\n bar: state.barIndex,\n });\n },\n drain() {\n return drainImpl(state);\n },\n setPlotOverrides(next) {\n state.runtimeContext.plotOverrides = Object.freeze({ ...next });\n },\n async dispose() {\n const finalSave = saveStateSnapshot(state, state.now());\n disposeImpl(state);\n await finalSave;\n },\n });\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DepRunner.d.ts","sourceRoot":"","sources":["../../src/dep/DepRunner.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qCAAqC,CAAC;AACxE,OAAO,KAAK,EAAE,GAAG,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAE9E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAO5D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAErD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAO1D;;;;;;;;;;;;;;;GAeG;AACH,MAAM,MAAM,SAAS,GAAG,QAAQ,CA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AAC,CAAC;IACpD,QAAQ,CAAC,cAAc,EAAE,cAAc,CAAC;IACxC,QAAQ,CAAC,cAAc,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAC3D,QAAQ,CAAC,GAAG,EAAE,MAAM,MAAM,CAAC;CAC9B,CAAC,CAAC;AA8FH;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,eAAe,CAC3B,IAAI,EAAE,mBAAmB,GAAG;IAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GACzD,SAAS,CASX;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,mBAAmB,CAC/B,IAAI,EAAE,mBAAmB,GAAG;IAAE,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GAC5D,aAAa,CASf;AAuCD;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,UAAU,CAC5B,GAAG,EAAE,SAAS,EACd,WAAW,EAAE,WAAW,EACxB,MAAM,EAAE,GAAG,EACX,SAAS,EAAE,SAAS,EACpB,MAAM,EAAE,OAAO,GAChB,OAAO,CAAC,IAAI,CAAC,CAwBf;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,cAAc,CAChC,OAAO,EAAE,aAAa,EACtB,WAAW,EAAE,WAAW,EACxB,MAAM,EAAE,GAAG,EACX,SAAS,EAAE,SAAS,EACpB,MAAM,EAAE,OAAO,GAChB,OAAO,CAAC,IAAI,CAAC,CAyBf"}
|
package/dist/dep/DepRunner.js
CHANGED
|
@@ -50,6 +50,7 @@ function buildSubRunnerState(args, slotIdPrefix, isDep) {
|
|
|
50
50
|
},
|
|
51
51
|
scriptMaxDrawings: args.compiled.manifest.maxDrawings ?? null,
|
|
52
52
|
stateSlots: new Map(),
|
|
53
|
+
seriesSlots: new Map(),
|
|
53
54
|
secondaryStreams: args.secondaryStreams,
|
|
54
55
|
requestSecurityBars: new Map(),
|
|
55
56
|
requestSecurityAlignments: new Map(),
|
|
@@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AE,WAAW,CAAC,cAAc,CAAC,CAAC;AAClG,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAChC,OAAsB,EACtB,WAAwB,EACxB,MAAW,EACX,SAAoB,EACpB,MAAe;IAEf,IAAI,WAAW,CAAC,cAAc,KAAK,IAAI,EAAE,CAAC;QACtC,MAAM,IAAI,KAAK,CAAC,4DAA4D,CAAC,CAAC;IAClF,CAAC;IACD,KAAK,MAAM,CAAC;IACZ,MAAM,MAAM,GAAG,MAAM,cAAc,CAAC,OAAO,CAAC,KAAK,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;IACtE,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;QAChB,cAAc,CAAC,OAAO,CAAC,KAAK,CAAC,SAAS,EAAE;YACpC,IAAI,EAAE,YAAY;YAClB,QAAQ,EAAE,OAAO;YACjB,IAAI,EAAE,WAAW;YACjB,OAAO,EAAE,MAAM,CAAC,OAAO;YACvB,MAAM,EAAE,EAAE;YACV,GAAG,EAAE,OAAO,CAAC,KAAK,CAAC,QAAQ;SAC9B,CAAC,CAAC;QACH,2DAA2D;IAC/D,CAAC;IACD,IAAI,CAAC,MAAM,EAAE,CAAC;QACV,OAAO,CAAC,KAAK,CAAC,QAAQ,IAAI,CAAC,CAAC;IAChC,CAAC;IACD,sBAAsB,CAClB,iBAAiB,CAAC,OAAO,CAAC,EAC1B,WAAW,CAAC,SAAS,EACrB,WAAW,CAAC,cAAc,CAC7B,CAAC;AACN,CAAC","sourcesContent":["// Copyright (c) 2026 Invinite. Licensed under the MIT License.\n// See the LICENSE file in the repo root for full license text.\n\nimport type { Capabilities } from \"@invinite-org/chartlang-adapter-kit\";\nimport type { Bar, CompiledScriptObject } from \"@invinite-org/chartlang-core\";\n\nimport type { RunnerState } from \"../createScriptRunner.js\";\nimport { pushDiagnostic } from \"../emit/emissionsQueue.js\";\nimport { resolveDefaultPane, resolveScriptPane } from \"../emit/paneResolver.js\";\nimport { resetBarEmissions, runComputeBody } from \"../execution/runComputeStep.js\";\nimport { resolveInputs } from \"../inputs/resolveInputs.js\";\nimport type { MutableRunnerEmissions } from \"../runtimeContext.js\";\nimport { inMemoryStateStore } from \"../stateStore.js\";\nimport type { StreamState } from \"../streamState.js\";\nimport { createRuntimeViews } from \"../views/index.js\";\nimport type { EventKind } from \"../views/index.js\";\nimport type { DepOutputStore } from \"./DepOutputStore.js\";\nimport {\n type DepRunnerLike,\n type SiblingRunnerLike,\n applyDepEmissionPolicy,\n} from \"./emissionFilter.js\";\n\n/**\n * One mounted private dep — a `const X = defineIndicator(...)` binding\n * that another script in the same compiled bundle references via\n * `X.output(\"title\")`. Owns its own `RunnerState`; shares the parent's\n * `mainStream` + `secondaryStreams`. Plot emissions are dropped from\n * the parent's queue and captured into the shared\n * {@link DepOutputStore}.\n *\n * @since 0.7\n * @stable\n * @example\n * // const dep = createDepRunner({ compiled, localId: \"fast\", ... });\n * // await runDepStep(dep, parent, rawBar, \"close\", false);\n * const x: number = 1;\n * void x;\n */\nexport type DepRunner = Readonly<{\n readonly kind: \"dep\";\n readonly localId: string;\n readonly slotIdPrefix: string;\n readonly declaredOutputs: ReadonlyArray<string>;\n readonly state: RunnerState;\n}>;\n\n/**\n * One mounted drawn sibling — a `export const X = defineIndicator(...)`\n * binding whose emissions ARE forwarded to the parent's queue, with\n * slot ids prefixed by `export:<exportName>/`. Siblings can also expose\n * outputs consumed by the primary or by other siblings.\n *\n * @since 0.7\n * @stable\n * @example\n * // const sib = createSiblingRunner({ compiled, exportName: \"slow\", ... });\n * // await runSiblingStep(sib, parent, rawBar, \"close\", false);\n * const x: number = 1;\n * void x;\n */\nexport type SiblingRunner = Readonly<{\n readonly kind: \"sibling\";\n readonly exportName: string;\n readonly slotIdPrefix: string;\n readonly declaredOutputs: ReadonlyArray<string>;\n readonly state: RunnerState;\n}>;\n\n/**\n * Constructor arguments for {@link createDepRunner} /\n * {@link createSiblingRunner}.\n *\n * `mainStream` + `secondaryStreams` are SHARED with the parent runner\n * (same OHLCV history); `depOutputStore` is also shared so every\n * sibling + dep + primary read from the same store. `inputOverrides`\n * is the merged effective-inputs record the compiler attached to the\n * dep's `DependencyDeclaration`.\n *\n * @since 0.7\n * @stable\n * @example\n * // const args: CreateDepRunnerArgs = {\n * // compiled, localId: \"x\",\n * // parentCapabilities, mainStream, secondaryStreams,\n * // depOutputStore, inputOverrides: {}, now: Date.now,\n * // };\n * const x: number = 1;\n * void x;\n */\nexport type CreateDepRunnerArgs = Readonly<{\n readonly compiled: CompiledScriptObject;\n readonly parentCapabilities: Capabilities;\n readonly mainStream: StreamState;\n readonly secondaryStreams: Map<string, StreamState>;\n readonly depOutputStore: DepOutputStore;\n readonly inputOverrides: Readonly<Record<string, unknown>>;\n readonly now: () => number;\n}>;\n\nfunction freshEmissions(barIndex: number): MutableRunnerEmissions {\n return {\n plots: [],\n drawings: [],\n alerts: [],\n alertConditions: [],\n logs: [],\n diagnostics: [],\n fromBar: barIndex,\n toBar: barIndex,\n };\n}\n\nfunction buildSubRunnerState(\n args: CreateDepRunnerArgs,\n slotIdPrefix: string,\n isDep: boolean,\n): RunnerState {\n const stateStore = inMemoryStateStore();\n const emissions = freshEmissions(0);\n const alertConditions = new Map(\n (args.compiled.manifest.alertConditions ?? []).map((c) => [c.id, c]),\n );\n const state: RunnerState = {\n manifest: args.compiled.manifest,\n compute: args.compiled.compute,\n capabilities: args.parentCapabilities,\n stateStore,\n persistenceIntervalMs: Number.POSITIVE_INFINITY,\n now: args.now,\n mainStream: args.mainStream,\n runtimeContext: {\n stream: args.mainStream,\n stateStore,\n lastPersistTime: 0,\n capabilities: args.parentCapabilities,\n emissions,\n barIndex: () => state.barIndex,\n isTick: false,\n drawingSlots: new Map(),\n drawingSubIdCounters: new Map(),\n drawingBucketCounters: {\n lines: 0,\n labels: 0,\n boxes: 0,\n polylines: 0,\n other: 0,\n },\n scriptMaxDrawings: args.compiled.manifest.maxDrawings ?? null,\n stateSlots: new Map(),\n secondaryStreams: args.secondaryStreams,\n requestSecurityBars: new Map(),\n requestSecurityAlignments: new Map(),\n requestSecurityAscendingBars: new Map(),\n requestLowerTfViews: new Map(),\n diagnosedRequestKeys: new Set(),\n alertConditions,\n diagnosedAlertConditionKeys: new Set(),\n logBudget: 0,\n logBudgetExceededDiagnosed: false,\n resolvedInputs: Object.freeze({}),\n defaultPane: resolveDefaultPane(args.compiled.manifest),\n scriptPane: resolveScriptPane(args.compiled.manifest),\n // Overrides target the primary script's slots only in v1;\n // dep-output plots are not host-overridable.\n plotOverrides: Object.freeze({}),\n diagnosedInputKeys: new Set(),\n views: createRuntimeViews(),\n slotIdPrefix,\n isDep,\n depOutputStore: args.depOutputStore,\n },\n emissions,\n depRunners: [],\n siblingRunners: [],\n depOutputStore: args.depOutputStore,\n depErroredThisBar: false,\n barIndex: 0,\n };\n state.runtimeContext.resolvedInputs = resolveInputs(\n args.compiled.manifest,\n args.inputOverrides,\n state.runtimeContext,\n );\n return state;\n}\n\nfunction declaredOutputTitles(compiled: CompiledScriptObject): ReadonlyArray<string> {\n return (compiled.manifest.outputs ?? []).map((o) => o.title);\n}\n\n/**\n * Construct a {@link DepRunner} for one private dep entry of a\n * `CompiledScriptBundle`. The runner shares the parent's `mainStream`\n * + `secondaryStreams`, owns a fresh `inMemoryStateStore`, and feeds\n * its plot emissions into the shared `DepOutputStore`.\n *\n * @since 0.7\n * @stable\n * @example\n * // const dep = createDepRunner({ compiled, localId: \"fast\",\n * // parentCapabilities, mainStream, secondaryStreams,\n * // depOutputStore, inputOverrides: { length: 20 }, now: Date.now });\n * const x: number = 1;\n * void x;\n */\nexport function createDepRunner(\n args: CreateDepRunnerArgs & { readonly localId: string },\n): DepRunner {\n const slotIdPrefix = `dep:${args.localId}/`;\n return Object.freeze({\n kind: \"dep\" as const,\n localId: args.localId,\n slotIdPrefix,\n declaredOutputs: declaredOutputTitles(args.compiled),\n state: buildSubRunnerState(args, slotIdPrefix, true),\n });\n}\n\n/**\n * Construct a {@link SiblingRunner} for one drawn named-export entry of\n * a `CompiledScriptBundle`. Shares streams + store with the parent;\n * emissions forward to the parent with `export:<exportName>/` slot-id\n * prefixes.\n *\n * @since 0.7\n * @stable\n * @example\n * // const sib = createSiblingRunner({ compiled, exportName: \"slow\", ... });\n * const x: number = 1;\n * void x;\n */\nexport function createSiblingRunner(\n args: CreateDepRunnerArgs & { readonly exportName: string },\n): SiblingRunner {\n const slotIdPrefix = `export:${args.exportName}/`;\n return Object.freeze({\n kind: \"sibling\" as const,\n exportName: args.exportName,\n slotIdPrefix,\n declaredOutputs: declaredOutputTitles(args.compiled),\n state: buildSubRunnerState(args, slotIdPrefix, false),\n });\n}\n\nfunction depRunnerLike(dep: DepRunner): DepRunnerLike {\n return {\n kind: \"dep\",\n localId: dep.localId,\n slotIdPrefix: dep.slotIdPrefix,\n declaredOutputs: dep.declaredOutputs,\n emissions: dep.state.emissions,\n };\n}\n\nfunction siblingRunnerLike(sib: SiblingRunner): SiblingRunnerLike {\n return {\n kind: \"sibling\",\n exportName: sib.exportName,\n slotIdPrefix: sib.slotIdPrefix,\n declaredOutputs: sib.declaredOutputs,\n emissions: sib.state.emissions,\n };\n}\n\nasync function executeSubStep(\n state: RunnerState,\n eventKind: EventKind,\n isTick: boolean,\n): Promise<{ readonly halted: boolean; readonly message: string }> {\n resetBarEmissions(state);\n try {\n const outcome = await runComputeBody({ state, eventKind, isTick });\n return outcome.kind === \"halt\"\n ? { halted: true, message: outcome.message }\n : { halted: false, message: \"\" };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { halted: true, message };\n }\n}\n\n/**\n * Drive one bar of execution for a {@link DepRunner}. Runs the dep's\n * `compute`, captures its titled-plot output into the shared\n * `DepOutputStore` via {@link applyDepEmissionPolicy}, namespaces\n * diagnostics with `dep:<localId>/`, and on halt sets\n * `parentState.depErroredThisBar = true` so the parent's primary\n * step drops its emissions for the bar (per task spec §6).\n *\n * @since 0.7\n * @stable\n * @example\n * // await runDepStep(dep, parent, rawBar, \"close\", false);\n * const x: number = 1;\n * void x;\n */\nexport async function runDepStep(\n dep: DepRunner,\n parentState: RunnerState,\n rawBar: Bar,\n eventKind: EventKind,\n isTick: boolean,\n): Promise<void> {\n if (parentState.depOutputStore === null) {\n throw new Error(\"runDepStep called on a runner with no dep output store\");\n }\n void rawBar;\n const result = await executeSubStep(dep.state, eventKind, isTick);\n if (result.halted) {\n // Use an empty slot id so the filter's prefix call produces the\n // runner's slotIdPrefix (`dep:<localId>/`) — preserves the\n // distinguished slotId in the parent's diagnostic queue.\n pushDiagnostic(dep.state.emissions, {\n kind: \"diagnostic\",\n severity: \"error\",\n code: \"dep-error\",\n message: result.message,\n slotId: \"\",\n bar: dep.state.barIndex,\n });\n parentState.depErroredThisBar = true;\n }\n if (!isTick) {\n dep.state.barIndex += 1;\n }\n applyDepEmissionPolicy(depRunnerLike(dep), parentState.emissions, parentState.depOutputStore);\n}\n\n/**\n * Drive one bar of execution for a {@link SiblingRunner}. Same shape\n * as {@link runDepStep} but the sibling's emissions are forwarded to\n * the parent with `export:<exportName>/` slot-id prefixes, and a\n * sibling halt does NOT clear the primary's emissions — only the\n * sibling's own bar emissions are lost.\n *\n * @since 0.7\n * @stable\n * @example\n * // await runSiblingStep(sibling, parent, rawBar, \"close\", false);\n * const x: number = 1;\n * void x;\n */\nexport async function runSiblingStep(\n sibling: SiblingRunner,\n parentState: RunnerState,\n rawBar: Bar,\n eventKind: EventKind,\n isTick: boolean,\n): Promise<void> {\n if (parentState.depOutputStore === null) {\n throw new Error(\"runSiblingStep called on a runner with no dep output store\");\n }\n void rawBar;\n const result = await executeSubStep(sibling.state, eventKind, isTick);\n if (result.halted) {\n pushDiagnostic(sibling.state.emissions, {\n kind: \"diagnostic\",\n severity: \"error\",\n code: \"dep-error\",\n message: result.message,\n slotId: \"\",\n bar: sibling.state.barIndex,\n });\n // sibling halt does NOT set parentState.depErroredThisBar.\n }\n if (!isTick) {\n sibling.state.barIndex += 1;\n }\n applyDepEmissionPolicy(\n siblingRunnerLike(sibling),\n parentState.emissions,\n parentState.depOutputStore,\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"DepRunner.js","sourceRoot":"","sources":["../../src/dep/DepRunner.ts"],"names":[],"mappings":"AAAA,+DAA+D;AAC/D,+DAA+D;AAM/D,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAChF,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACnF,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAE3D,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAEtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAGvD,OAAO,EAGH,sBAAsB,GACzB,MAAM,qBAAqB,CAAC;AA+E7B,SAAS,cAAc,CAAC,QAAgB;IACpC,OAAO;QACH,KAAK,EAAE,EAAE;QACT,QAAQ,EAAE,EAAE;QACZ,MAAM,EAAE,EAAE;QACV,eAAe,EAAE,EAAE;QACnB,IAAI,EAAE,EAAE;QACR,WAAW,EAAE,EAAE;QACf,OAAO,EAAE,QAAQ;QACjB,KAAK,EAAE,QAAQ;KAClB,CAAC;AACN,CAAC;AAED,SAAS,mBAAmB,CACxB,IAAyB,EACzB,YAAoB,EACpB,KAAc;IAEd,MAAM,UAAU,GAAG,kBAAkB,EAAE,CAAC;IACxC,MAAM,SAAS,GAAG,cAAc,CAAC,CAAC,CAAC,CAAC;IACpC,MAAM,eAAe,GAAG,IAAI,GAAG,CAC3B,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,eAAe,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CACvE,CAAC;IACF,MAAM,KAAK,GAAgB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C;IAC5B,CAAC;IACD,sBAAsB,CAAC,aAAa,CAAC,GAAG,CAAC,EAAE,WAAW,CAAC,SAAS,EAAE,WAAW,CAAC,cAAc,CAAC,CAAC;AAClG,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAChC,OAAsB,EACtB,WAAwB,EACxB,MAAW,EACX,SAAoB,EACpB,MAAe;IAEf,IAAI,WAAW,CAAC,cAAc,KAAK,IAAI,EAAE,CAAC;QACtC,MAAM,IAAI,KAAK,CAAC,4DAA4D,CAAC,CAAC;IAClF,CAAC;IACD,KAAK,MAAM,CAAC;IACZ,MAAM,MAAM,GAAG,MAAM,cAAc,CAAC,OAAO,CAAC,KAAK,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;IACtE,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;QAChB,cAAc,CAAC,OAAO,CAAC,KAAK,CAAC,SAAS,EAAE;YACpC,IAAI,EAAE,YAAY;YAClB,QAAQ,EAAE,OAAO;YACjB,IAAI,EAAE,WAAW;YACjB,OAAO,EAAE,MAAM,CAAC,OAAO;YACvB,MAAM,EAAE,EAAE;YACV,GAAG,EAAE,OAAO,CAAC,KAAK,CAAC,QAAQ;SAC9B,CAAC,CAAC;QACH,2DAA2D;IAC/D,CAAC;IACD,IAAI,CAAC,MAAM,EAAE,CAAC;QACV,OAAO,CAAC,KAAK,CAAC,QAAQ,IAAI,CAAC,CAAC;IAChC,CAAC;IACD,sBAAsB,CAClB,iBAAiB,CAAC,OAAO,CAAC,EAC1B,WAAW,CAAC,SAAS,EACrB,WAAW,CAAC,cAAc,CAC7B,CAAC;AACN,CAAC","sourcesContent":["// Copyright (c) 2026 Invinite. Licensed under the MIT License.\n// See the LICENSE file in the repo root for full license text.\n\nimport type { Capabilities } from \"@invinite-org/chartlang-adapter-kit\";\nimport type { Bar, CompiledScriptObject } from \"@invinite-org/chartlang-core\";\n\nimport type { RunnerState } from \"../createScriptRunner.js\";\nimport { pushDiagnostic } from \"../emit/emissionsQueue.js\";\nimport { resolveDefaultPane, resolveScriptPane } from \"../emit/paneResolver.js\";\nimport { resetBarEmissions, runComputeBody } from \"../execution/runComputeStep.js\";\nimport { resolveInputs } from \"../inputs/resolveInputs.js\";\nimport type { MutableRunnerEmissions } from \"../runtimeContext.js\";\nimport { inMemoryStateStore } from \"../stateStore.js\";\nimport type { StreamState } from \"../streamState.js\";\nimport { createRuntimeViews } from \"../views/index.js\";\nimport type { EventKind } from \"../views/index.js\";\nimport type { DepOutputStore } from \"./DepOutputStore.js\";\nimport {\n type DepRunnerLike,\n type SiblingRunnerLike,\n applyDepEmissionPolicy,\n} from \"./emissionFilter.js\";\n\n/**\n * One mounted private dep — a `const X = defineIndicator(...)` binding\n * that another script in the same compiled bundle references via\n * `X.output(\"title\")`. Owns its own `RunnerState`; shares the parent's\n * `mainStream` + `secondaryStreams`. Plot emissions are dropped from\n * the parent's queue and captured into the shared\n * {@link DepOutputStore}.\n *\n * @since 0.7\n * @stable\n * @example\n * // const dep = createDepRunner({ compiled, localId: \"fast\", ... });\n * // await runDepStep(dep, parent, rawBar, \"close\", false);\n * const x: number = 1;\n * void x;\n */\nexport type DepRunner = Readonly<{\n readonly kind: \"dep\";\n readonly localId: string;\n readonly slotIdPrefix: string;\n readonly declaredOutputs: ReadonlyArray<string>;\n readonly state: RunnerState;\n}>;\n\n/**\n * One mounted drawn sibling — a `export const X = defineIndicator(...)`\n * binding whose emissions ARE forwarded to the parent's queue, with\n * slot ids prefixed by `export:<exportName>/`. Siblings can also expose\n * outputs consumed by the primary or by other siblings.\n *\n * @since 0.7\n * @stable\n * @example\n * // const sib = createSiblingRunner({ compiled, exportName: \"slow\", ... });\n * // await runSiblingStep(sib, parent, rawBar, \"close\", false);\n * const x: number = 1;\n * void x;\n */\nexport type SiblingRunner = Readonly<{\n readonly kind: \"sibling\";\n readonly exportName: string;\n readonly slotIdPrefix: string;\n readonly declaredOutputs: ReadonlyArray<string>;\n readonly state: RunnerState;\n}>;\n\n/**\n * Constructor arguments for {@link createDepRunner} /\n * {@link createSiblingRunner}.\n *\n * `mainStream` + `secondaryStreams` are SHARED with the parent runner\n * (same OHLCV history); `depOutputStore` is also shared so every\n * sibling + dep + primary read from the same store. `inputOverrides`\n * is the merged effective-inputs record the compiler attached to the\n * dep's `DependencyDeclaration`.\n *\n * @since 0.7\n * @stable\n * @example\n * // const args: CreateDepRunnerArgs = {\n * // compiled, localId: \"x\",\n * // parentCapabilities, mainStream, secondaryStreams,\n * // depOutputStore, inputOverrides: {}, now: Date.now,\n * // };\n * const x: number = 1;\n * void x;\n */\nexport type CreateDepRunnerArgs = Readonly<{\n readonly compiled: CompiledScriptObject;\n readonly parentCapabilities: Capabilities;\n readonly mainStream: StreamState;\n readonly secondaryStreams: Map<string, StreamState>;\n readonly depOutputStore: DepOutputStore;\n readonly inputOverrides: Readonly<Record<string, unknown>>;\n readonly now: () => number;\n}>;\n\nfunction freshEmissions(barIndex: number): MutableRunnerEmissions {\n return {\n plots: [],\n drawings: [],\n alerts: [],\n alertConditions: [],\n logs: [],\n diagnostics: [],\n fromBar: barIndex,\n toBar: barIndex,\n };\n}\n\nfunction buildSubRunnerState(\n args: CreateDepRunnerArgs,\n slotIdPrefix: string,\n isDep: boolean,\n): RunnerState {\n const stateStore = inMemoryStateStore();\n const emissions = freshEmissions(0);\n const alertConditions = new Map(\n (args.compiled.manifest.alertConditions ?? []).map((c) => [c.id, c]),\n );\n const state: RunnerState = {\n manifest: args.compiled.manifest,\n compute: args.compiled.compute,\n capabilities: args.parentCapabilities,\n stateStore,\n persistenceIntervalMs: Number.POSITIVE_INFINITY,\n now: args.now,\n mainStream: args.mainStream,\n runtimeContext: {\n stream: args.mainStream,\n stateStore,\n lastPersistTime: 0,\n capabilities: args.parentCapabilities,\n emissions,\n barIndex: () => state.barIndex,\n isTick: false,\n drawingSlots: new Map(),\n drawingSubIdCounters: new Map(),\n drawingBucketCounters: {\n lines: 0,\n labels: 0,\n boxes: 0,\n polylines: 0,\n other: 0,\n },\n scriptMaxDrawings: args.compiled.manifest.maxDrawings ?? null,\n stateSlots: new Map(),\n seriesSlots: new Map(),\n secondaryStreams: args.secondaryStreams,\n requestSecurityBars: new Map(),\n requestSecurityAlignments: new Map(),\n requestSecurityAscendingBars: new Map(),\n requestLowerTfViews: new Map(),\n diagnosedRequestKeys: new Set(),\n alertConditions,\n diagnosedAlertConditionKeys: new Set(),\n logBudget: 0,\n logBudgetExceededDiagnosed: false,\n resolvedInputs: Object.freeze({}),\n defaultPane: resolveDefaultPane(args.compiled.manifest),\n scriptPane: resolveScriptPane(args.compiled.manifest),\n // Overrides target the primary script's slots only in v1;\n // dep-output plots are not host-overridable.\n plotOverrides: Object.freeze({}),\n diagnosedInputKeys: new Set(),\n views: createRuntimeViews(),\n slotIdPrefix,\n isDep,\n depOutputStore: args.depOutputStore,\n },\n emissions,\n depRunners: [],\n siblingRunners: [],\n depOutputStore: args.depOutputStore,\n depErroredThisBar: false,\n barIndex: 0,\n };\n state.runtimeContext.resolvedInputs = resolveInputs(\n args.compiled.manifest,\n args.inputOverrides,\n state.runtimeContext,\n );\n return state;\n}\n\nfunction declaredOutputTitles(compiled: CompiledScriptObject): ReadonlyArray<string> {\n return (compiled.manifest.outputs ?? []).map((o) => o.title);\n}\n\n/**\n * Construct a {@link DepRunner} for one private dep entry of a\n * `CompiledScriptBundle`. The runner shares the parent's `mainStream`\n * + `secondaryStreams`, owns a fresh `inMemoryStateStore`, and feeds\n * its plot emissions into the shared `DepOutputStore`.\n *\n * @since 0.7\n * @stable\n * @example\n * // const dep = createDepRunner({ compiled, localId: \"fast\",\n * // parentCapabilities, mainStream, secondaryStreams,\n * // depOutputStore, inputOverrides: { length: 20 }, now: Date.now });\n * const x: number = 1;\n * void x;\n */\nexport function createDepRunner(\n args: CreateDepRunnerArgs & { readonly localId: string },\n): DepRunner {\n const slotIdPrefix = `dep:${args.localId}/`;\n return Object.freeze({\n kind: \"dep\" as const,\n localId: args.localId,\n slotIdPrefix,\n declaredOutputs: declaredOutputTitles(args.compiled),\n state: buildSubRunnerState(args, slotIdPrefix, true),\n });\n}\n\n/**\n * Construct a {@link SiblingRunner} for one drawn named-export entry of\n * a `CompiledScriptBundle`. Shares streams + store with the parent;\n * emissions forward to the parent with `export:<exportName>/` slot-id\n * prefixes.\n *\n * @since 0.7\n * @stable\n * @example\n * // const sib = createSiblingRunner({ compiled, exportName: \"slow\", ... });\n * const x: number = 1;\n * void x;\n */\nexport function createSiblingRunner(\n args: CreateDepRunnerArgs & { readonly exportName: string },\n): SiblingRunner {\n const slotIdPrefix = `export:${args.exportName}/`;\n return Object.freeze({\n kind: \"sibling\" as const,\n exportName: args.exportName,\n slotIdPrefix,\n declaredOutputs: declaredOutputTitles(args.compiled),\n state: buildSubRunnerState(args, slotIdPrefix, false),\n });\n}\n\nfunction depRunnerLike(dep: DepRunner): DepRunnerLike {\n return {\n kind: \"dep\",\n localId: dep.localId,\n slotIdPrefix: dep.slotIdPrefix,\n declaredOutputs: dep.declaredOutputs,\n emissions: dep.state.emissions,\n };\n}\n\nfunction siblingRunnerLike(sib: SiblingRunner): SiblingRunnerLike {\n return {\n kind: \"sibling\",\n exportName: sib.exportName,\n slotIdPrefix: sib.slotIdPrefix,\n declaredOutputs: sib.declaredOutputs,\n emissions: sib.state.emissions,\n };\n}\n\nasync function executeSubStep(\n state: RunnerState,\n eventKind: EventKind,\n isTick: boolean,\n): Promise<{ readonly halted: boolean; readonly message: string }> {\n resetBarEmissions(state);\n try {\n const outcome = await runComputeBody({ state, eventKind, isTick });\n return outcome.kind === \"halt\"\n ? { halted: true, message: outcome.message }\n : { halted: false, message: \"\" };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n return { halted: true, message };\n }\n}\n\n/**\n * Drive one bar of execution for a {@link DepRunner}. Runs the dep's\n * `compute`, captures its titled-plot output into the shared\n * `DepOutputStore` via {@link applyDepEmissionPolicy}, namespaces\n * diagnostics with `dep:<localId>/`, and on halt sets\n * `parentState.depErroredThisBar = true` so the parent's primary\n * step drops its emissions for the bar (per task spec §6).\n *\n * @since 0.7\n * @stable\n * @example\n * // await runDepStep(dep, parent, rawBar, \"close\", false);\n * const x: number = 1;\n * void x;\n */\nexport async function runDepStep(\n dep: DepRunner,\n parentState: RunnerState,\n rawBar: Bar,\n eventKind: EventKind,\n isTick: boolean,\n): Promise<void> {\n if (parentState.depOutputStore === null) {\n throw new Error(\"runDepStep called on a runner with no dep output store\");\n }\n void rawBar;\n const result = await executeSubStep(dep.state, eventKind, isTick);\n if (result.halted) {\n // Use an empty slot id so the filter's prefix call produces the\n // runner's slotIdPrefix (`dep:<localId>/`) — preserves the\n // distinguished slotId in the parent's diagnostic queue.\n pushDiagnostic(dep.state.emissions, {\n kind: \"diagnostic\",\n severity: \"error\",\n code: \"dep-error\",\n message: result.message,\n slotId: \"\",\n bar: dep.state.barIndex,\n });\n parentState.depErroredThisBar = true;\n }\n if (!isTick) {\n dep.state.barIndex += 1;\n }\n applyDepEmissionPolicy(depRunnerLike(dep), parentState.emissions, parentState.depOutputStore);\n}\n\n/**\n * Drive one bar of execution for a {@link SiblingRunner}. Same shape\n * as {@link runDepStep} but the sibling's emissions are forwarded to\n * the parent with `export:<exportName>/` slot-id prefixes, and a\n * sibling halt does NOT clear the primary's emissions — only the\n * sibling's own bar emissions are lost.\n *\n * @since 0.7\n * @stable\n * @example\n * // await runSiblingStep(sibling, parent, rawBar, \"close\", false);\n * const x: number = 1;\n * void x;\n */\nexport async function runSiblingStep(\n sibling: SiblingRunner,\n parentState: RunnerState,\n rawBar: Bar,\n eventKind: EventKind,\n isTick: boolean,\n): Promise<void> {\n if (parentState.depOutputStore === null) {\n throw new Error(\"runSiblingStep called on a runner with no dep output store\");\n }\n void rawBar;\n const result = await executeSubStep(sibling.state, eventKind, isTick);\n if (result.halted) {\n pushDiagnostic(sibling.state.emissions, {\n kind: \"diagnostic\",\n severity: \"error\",\n code: \"dep-error\",\n message: result.message,\n slotId: \"\",\n bar: sibling.state.barIndex,\n });\n // sibling halt does NOT set parentState.depErroredThisBar.\n }\n if (!isTick) {\n sibling.state.barIndex += 1;\n }\n applyDepEmissionPolicy(\n siblingRunnerLike(sibling),\n parentState.emissions,\n parentState.depOutputStore,\n );\n}\n"]}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { DrawingHandle, FillBetweenStyle, WorldPoint } from "@invinite-org/chartlang-core";
|
|
2
|
+
/**
|
|
3
|
+
* Fill the ribbon between two edges. The native equivalent of Pine
|
|
4
|
+
* `linefill.new(line1, line2, color)` and `fill(plot1, plot2, color)`.
|
|
5
|
+
* The filled region is the closed polygon `edgeA` forward then `edgeB`
|
|
6
|
+
* reversed; the two edges need not share x-coordinates or length.
|
|
7
|
+
*
|
|
8
|
+
* @anchors `edgeA`, `edgeB` — two `WorldPoint` lists (the band edges)
|
|
9
|
+
* @anchorCount variable — each edge needs 2..10000 finite anchors
|
|
10
|
+
* @bucket polylines
|
|
11
|
+
* @warmup none — guard warmup in-script: an edge with fewer than 2 finite
|
|
12
|
+
* anchors (empty, single-point, or a `NaN` coordinate) is dropped with a
|
|
13
|
+
* `malformed-emission` diagnostic, so accumulate then gate on `length >= 2`
|
|
14
|
+
* as the example does.
|
|
15
|
+
* @since 0.4
|
|
16
|
+
* @stable
|
|
17
|
+
* @example
|
|
18
|
+
* import { type WorldPoint, defineIndicator } from "@invinite-org/chartlang-core";
|
|
19
|
+
* const top: WorldPoint[] = [];
|
|
20
|
+
* const bottom: WorldPoint[] = [];
|
|
21
|
+
* export default defineIndicator({
|
|
22
|
+
* name: "draw.fillBetween demo",
|
|
23
|
+
* apiVersion: 1,
|
|
24
|
+
* compute({ bar, draw }) {
|
|
25
|
+
* top.push({ time: bar.time, price: bar.high });
|
|
26
|
+
* bottom.push({ time: bar.time, price: bar.low });
|
|
27
|
+
* if (top.length >= 2) {
|
|
28
|
+
* draw.fillBetween(top, bottom, { fill: "#3b82f6", fillAlpha: 0.2 });
|
|
29
|
+
* }
|
|
30
|
+
* },
|
|
31
|
+
* });
|
|
32
|
+
*/
|
|
33
|
+
export declare function fillBetween(edgeA: ReadonlyArray<WorldPoint>, edgeB: ReadonlyArray<WorldPoint>, opts?: FillBetweenStyle): DrawingHandle;
|
|
34
|
+
/**
|
|
35
|
+
* Compiler-injected overload.
|
|
36
|
+
*
|
|
37
|
+
* @since 0.4
|
|
38
|
+
* @stable
|
|
39
|
+
* @example
|
|
40
|
+
* // Internal — the compiler rewrites every script callsite.
|
|
41
|
+
* // const fn: typeof fillBetween = fillBetween;
|
|
42
|
+
* // void fn;
|
|
43
|
+
*/
|
|
44
|
+
export declare function fillBetween(slotId: string, edgeA: ReadonlyArray<WorldPoint>, edgeB: ReadonlyArray<WorldPoint>, opts?: FillBetweenStyle): DrawingHandle;
|
|
45
|
+
//# sourceMappingURL=fillBetween.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fillBetween.d.ts","sourceRoot":"","sources":["../../../../src/emit/draw/boxes/fillBetween.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACR,aAAa,EAEb,gBAAgB,EAChB,UAAU,EACb,MAAM,8BAA8B,CAAC;AAqBtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,WAAW,CACvB,KAAK,EAAE,aAAa,CAAC,UAAU,CAAC,EAChC,KAAK,EAAE,aAAa,CAAC,UAAU,CAAC,EAChC,IAAI,CAAC,EAAE,gBAAgB,GACxB,aAAa,CAAC;AACjB;;;;;;;;;GASG;AACH,wBAAgB,WAAW,CACvB,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,aAAa,CAAC,UAAU,CAAC,EAChC,KAAK,EAAE,aAAa,CAAC,UAAU,CAAC,EAChC,IAAI,CAAC,EAAE,gBAAgB,GACxB,aAAa,CAAC"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Copyright (c) 2026 Invinite. Licensed under the MIT License.
|
|
2
|
+
// See the LICENSE file in the repo root for full license text.
|
|
3
|
+
import { ACTIVE_RUNTIME_CONTEXT } from "../../../runtimeContext.js";
|
|
4
|
+
import { createDrawingHandle } from "../handle.js";
|
|
5
|
+
import { nextSubId } from "../subIdAllocator.js";
|
|
6
|
+
const OUTSIDE_CTX_MESSAGE = "draw.fillBetween called outside an active script step";
|
|
7
|
+
function fillBetweenImpl(slotId, edgeA, edgeB, opts) {
|
|
8
|
+
const ctx = ACTIVE_RUNTIME_CONTEXT.current;
|
|
9
|
+
if (ctx === null)
|
|
10
|
+
throw new Error(OUTSIDE_CTX_MESSAGE);
|
|
11
|
+
const subId = nextSubId(ctx, slotId);
|
|
12
|
+
const state = { kind: "fill-between", edgeA, edgeB, style: opts };
|
|
13
|
+
return createDrawingHandle(slotId, subId, "fill-between", state);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Implementation signature for {@link fillBetween}. Branches on
|
|
17
|
+
* `typeof arg1 === "string"` to dispatch the script-facing vs
|
|
18
|
+
* compiler-injected overload.
|
|
19
|
+
*
|
|
20
|
+
* @since 0.4
|
|
21
|
+
* @stable
|
|
22
|
+
* @example
|
|
23
|
+
* // const fn: typeof fillBetween = fillBetween;
|
|
24
|
+
* // void fn;
|
|
25
|
+
*/
|
|
26
|
+
export function fillBetween(arg1, arg2, arg3, arg4) {
|
|
27
|
+
if (typeof arg1 !== "string" ||
|
|
28
|
+
arg2 === undefined ||
|
|
29
|
+
!Array.isArray(arg2) ||
|
|
30
|
+
arg3 === undefined ||
|
|
31
|
+
!Array.isArray(arg3)) {
|
|
32
|
+
throw new Error(OUTSIDE_CTX_MESSAGE);
|
|
33
|
+
}
|
|
34
|
+
return fillBetweenImpl(arg1, arg2, arg3, arg4 ?? {});
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=fillBetween.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fillBetween.js","sourceRoot":"","sources":["../../../../src/emit/draw/boxes/fillBetween.ts"],"names":[],"mappings":"AAAA,+DAA+D;AAC/D,+DAA+D;AAS/D,OAAO,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEjD,MAAM,mBAAmB,GAAG,uDAAuD,CAAC;AAEpF,SAAS,eAAe,CACpB,MAAc,EACd,KAAgC,EAChC,KAAgC,EAChC,IAAsB;IAEtB,MAAM,GAAG,GAAG,sBAAsB,CAAC,OAAO,CAAC;IAC3C,IAAI,GAAG,KAAK,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;IACvD,MAAM,KAAK,GAAG,SAAS,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IACrC,MAAM,KAAK,GAAqB,EAAE,IAAI,EAAE,cAAc,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IACpF,OAAO,mBAAmB,CAAC,MAAM,EAAE,KAAK,EAAE,cAAc,EAAE,KAAK,CAAC,CAAC;AACrE,CAAC;AAsDD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,WAAW,CACvB,IAAwC,EACxC,IAAgC,EAChC,IAAmD,EACnD,IAAuB;IAEvB,IACI,OAAO,IAAI,KAAK,QAAQ;QACxB,IAAI,KAAK,SAAS;QAClB,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;QACpB,IAAI,KAAK,SAAS;QAClB,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EACtB,CAAC;QACC,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;IACzC,CAAC;IACD,OAAO,eAAe,CAAC,IAAI,EAAE,IAAI,EAAE,IAAiC,EAAE,IAAI,IAAI,EAAE,CAAC,CAAC;AACtF,CAAC","sourcesContent":["// Copyright (c) 2026 Invinite. Licensed under the MIT License.\n// See the LICENSE file in the repo root for full license text.\n\nimport type {\n DrawingHandle,\n FillBetweenState,\n FillBetweenStyle,\n WorldPoint,\n} from \"@invinite-org/chartlang-core\";\n\nimport { ACTIVE_RUNTIME_CONTEXT } from \"../../../runtimeContext.js\";\nimport { createDrawingHandle } from \"../handle.js\";\nimport { nextSubId } from \"../subIdAllocator.js\";\n\nconst OUTSIDE_CTX_MESSAGE = \"draw.fillBetween called outside an active script step\";\n\nfunction fillBetweenImpl(\n slotId: string,\n edgeA: ReadonlyArray<WorldPoint>,\n edgeB: ReadonlyArray<WorldPoint>,\n opts: FillBetweenStyle,\n): DrawingHandle {\n const ctx = ACTIVE_RUNTIME_CONTEXT.current;\n if (ctx === null) throw new Error(OUTSIDE_CTX_MESSAGE);\n const subId = nextSubId(ctx, slotId);\n const state: FillBetweenState = { kind: \"fill-between\", edgeA, edgeB, style: opts };\n return createDrawingHandle(slotId, subId, \"fill-between\", state);\n}\n\n/**\n * Fill the ribbon between two edges. The native equivalent of Pine\n * `linefill.new(line1, line2, color)` and `fill(plot1, plot2, color)`.\n * The filled region is the closed polygon `edgeA` forward then `edgeB`\n * reversed; the two edges need not share x-coordinates or length.\n *\n * @anchors `edgeA`, `edgeB` — two `WorldPoint` lists (the band edges)\n * @anchorCount variable — each edge needs 2..10000 finite anchors\n * @bucket polylines\n * @warmup none — guard warmup in-script: an edge with fewer than 2 finite\n * anchors (empty, single-point, or a `NaN` coordinate) is dropped with a\n * `malformed-emission` diagnostic, so accumulate then gate on `length >= 2`\n * as the example does.\n * @since 0.4\n * @stable\n * @example\n * import { type WorldPoint, defineIndicator } from \"@invinite-org/chartlang-core\";\n * const top: WorldPoint[] = [];\n * const bottom: WorldPoint[] = [];\n * export default defineIndicator({\n * name: \"draw.fillBetween demo\",\n * apiVersion: 1,\n * compute({ bar, draw }) {\n * top.push({ time: bar.time, price: bar.high });\n * bottom.push({ time: bar.time, price: bar.low });\n * if (top.length >= 2) {\n * draw.fillBetween(top, bottom, { fill: \"#3b82f6\", fillAlpha: 0.2 });\n * }\n * },\n * });\n */\nexport function fillBetween(\n edgeA: ReadonlyArray<WorldPoint>,\n edgeB: ReadonlyArray<WorldPoint>,\n opts?: FillBetweenStyle,\n): DrawingHandle;\n/**\n * Compiler-injected overload.\n *\n * @since 0.4\n * @stable\n * @example\n * // Internal — the compiler rewrites every script callsite.\n * // const fn: typeof fillBetween = fillBetween;\n * // void fn;\n */\nexport function fillBetween(\n slotId: string,\n edgeA: ReadonlyArray<WorldPoint>,\n edgeB: ReadonlyArray<WorldPoint>,\n opts?: FillBetweenStyle,\n): DrawingHandle;\n/**\n * Implementation signature for {@link fillBetween}. Branches on\n * `typeof arg1 === \"string\"` to dispatch the script-facing vs\n * compiler-injected overload.\n *\n * @since 0.4\n * @stable\n * @example\n * // const fn: typeof fillBetween = fillBetween;\n * // void fn;\n */\nexport function fillBetween(\n arg1: string | ReadonlyArray<WorldPoint>,\n arg2?: ReadonlyArray<WorldPoint>,\n arg3?: ReadonlyArray<WorldPoint> | FillBetweenStyle,\n arg4?: FillBetweenStyle,\n): DrawingHandle {\n if (\n typeof arg1 !== \"string\" ||\n arg2 === undefined ||\n !Array.isArray(arg2) ||\n arg3 === undefined ||\n !Array.isArray(arg3)\n ) {\n throw new Error(OUTSIDE_CTX_MESSAGE);\n }\n return fillBetweenImpl(arg1, arg2, arg3 as ReadonlyArray<WorldPoint>, arg4 ?? {});\n}\n"]}
|
|
@@ -14,6 +14,15 @@ import type { DrawingHandle, DrawingKind, DrawingState } from "@invinite-org/cha
|
|
|
14
14
|
*
|
|
15
15
|
* The handle's `id` is `slotId#subId` — stable across bars.
|
|
16
16
|
*
|
|
17
|
+
* `z` is the presentation-only render-order key the `draw.*` opts bag
|
|
18
|
+
* carried (core's `ZOrdered` mixin) folded into `state.style`. It is
|
|
19
|
+
* {@link splitZ | lifted out} of `state.style` so it rides the wire as
|
|
20
|
+
* the top-level {@link DrawingEmission.z} field, **never** inside
|
|
21
|
+
* `DrawingState` (Task 3 forbids `z` in `state`), and is persisted on
|
|
22
|
+
* the slot. An `update` that does not re-specify a non-zero `z` retains
|
|
23
|
+
* the last value; a re-specified non-zero `z` overrides; `remove`
|
|
24
|
+
* carries the last-known `z`.
|
|
25
|
+
*
|
|
17
26
|
* @since 0.3
|
|
18
27
|
* @stable
|
|
19
28
|
* @example
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handle.d.ts","sourceRoot":"","sources":["../../../src/emit/draw/handle.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;
|
|
1
|
+
{"version":3,"file":"handle.d.ts","sourceRoot":"","sources":["../../../src/emit/draw/handle.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAyE7F;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,wBAAgB,mBAAmB,CAC/B,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,WAAW,EACjB,YAAY,EAAE,YAAY,GAC3B,aAAa,CAoEf"}
|
package/dist/emit/draw/handle.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Copyright (c) 2026 Invinite. Licensed under the MIT License.
|
|
2
2
|
// See the LICENSE file in the repo root for full license text.
|
|
3
|
-
import { ACTIVE_RUNTIME_CONTEXT } from "../../runtimeContext.js";
|
|
3
|
+
import { ACTIVE_RUNTIME_CONTEXT, } from "../../runtimeContext.js";
|
|
4
4
|
import { pushDrawing } from "./pushDrawing.js";
|
|
5
5
|
const OUTSIDE_CTX_MESSAGE = "draw called outside an active script step";
|
|
6
6
|
function mergeState(prev, patch) {
|
|
@@ -13,7 +13,34 @@ function mergeState(prev, patch) {
|
|
|
13
13
|
// discriminants stay pinned to `prev.kind`.
|
|
14
14
|
return { ...prev, ...patch, kind: prev.kind };
|
|
15
15
|
}
|
|
16
|
-
|
|
16
|
+
/**
|
|
17
|
+
* Lift the presentation-only `z` (render-order key) **out** of a
|
|
18
|
+
* drawing's `state.style` and hand it back to the caller, returning a
|
|
19
|
+
* state with `z` removed from a **shallow clone** of `style` (the
|
|
20
|
+
* caller's style object is never mutated). Every `draw.*` option bag
|
|
21
|
+
* carries `z` via core's `ZOrdered` mixin, and the per-kind impls fold
|
|
22
|
+
* that bag into `state.style`, so `z` arrives nested at `state.style.z`.
|
|
23
|
+
* `z` is a **top-level** `DrawingEmission` field, not part of
|
|
24
|
+
* `DrawingState`, so it must not ride the wire inside `state` — strip it
|
|
25
|
+
* here. Returns `z: 0` (the omit-when-`0` default) for states with no
|
|
26
|
+
* `style` (e.g. `group`) or no `z`, leaving the state object **untouched**
|
|
27
|
+
* in that case so a no-`z` drawing stays byte-identical to the
|
|
28
|
+
* pre-feature baseline.
|
|
29
|
+
*/
|
|
30
|
+
function splitZ(state) {
|
|
31
|
+
if (!("style" in state) || state.style === undefined) {
|
|
32
|
+
return { state, z: 0 };
|
|
33
|
+
}
|
|
34
|
+
const style = state.style;
|
|
35
|
+
if (style.z === undefined) {
|
|
36
|
+
return { state, z: 0 };
|
|
37
|
+
}
|
|
38
|
+
// Shallow-clone style with `z` removed — never mutate the caller's
|
|
39
|
+
// object. `rest` is z-free, so the wire `state.style` carries no `z`.
|
|
40
|
+
const { z, ...rest } = style;
|
|
41
|
+
return { state: { ...state, style: rest }, z };
|
|
42
|
+
}
|
|
43
|
+
function emit(ctx, handleId, kind, op, state, z) {
|
|
17
44
|
pushDrawing(ctx, {
|
|
18
45
|
kind: "drawing",
|
|
19
46
|
handleId,
|
|
@@ -22,6 +49,10 @@ function emit(ctx, handleId, kind, op, state) {
|
|
|
22
49
|
state,
|
|
23
50
|
bar: ctx.barIndex(),
|
|
24
51
|
time: ctx.stream.bar.time,
|
|
52
|
+
// `z` is presentation-only and top-level (never inside `state`);
|
|
53
|
+
// omit it when `0` so a no-`z` drawing is byte-identical to the
|
|
54
|
+
// pre-feature baseline — mirrors `PlotEmission.xShift` / `.z`.
|
|
55
|
+
...(z === 0 ? {} : { z }),
|
|
25
56
|
});
|
|
26
57
|
}
|
|
27
58
|
/**
|
|
@@ -39,6 +70,15 @@ function emit(ctx, handleId, kind, op, state) {
|
|
|
39
70
|
*
|
|
40
71
|
* The handle's `id` is `slotId#subId` — stable across bars.
|
|
41
72
|
*
|
|
73
|
+
* `z` is the presentation-only render-order key the `draw.*` opts bag
|
|
74
|
+
* carried (core's `ZOrdered` mixin) folded into `state.style`. It is
|
|
75
|
+
* {@link splitZ | lifted out} of `state.style` so it rides the wire as
|
|
76
|
+
* the top-level {@link DrawingEmission.z} field, **never** inside
|
|
77
|
+
* `DrawingState` (Task 3 forbids `z` in `state`), and is persisted on
|
|
78
|
+
* the slot. An `update` that does not re-specify a non-zero `z` retains
|
|
79
|
+
* the last value; a re-specified non-zero `z` overrides; `remove`
|
|
80
|
+
* carries the last-known `z`.
|
|
81
|
+
*
|
|
42
82
|
* @since 0.3
|
|
43
83
|
* @stable
|
|
44
84
|
* @example
|
|
@@ -64,23 +104,30 @@ export function createDrawingHandle(slotId, subId, kind, initialState) {
|
|
|
64
104
|
throw new Error(OUTSIDE_CTX_MESSAGE);
|
|
65
105
|
const handleId = `${slotId}#${subId}`;
|
|
66
106
|
const existing = ctx.drawingSlots.get(handleId);
|
|
107
|
+
// Lift `z` out of `state.style` so it rides the emission top-level,
|
|
108
|
+
// not inside `DrawingState`. The remaining `style` (z removed) is
|
|
109
|
+
// what persists in the slot.
|
|
110
|
+
const initial = splitZ(initialState);
|
|
67
111
|
let slot;
|
|
68
112
|
let op;
|
|
69
113
|
if (existing === undefined) {
|
|
70
|
-
slot = { handleId, kind, state:
|
|
114
|
+
slot = { handleId, kind, state: initial.state, z: initial.z, removed: false };
|
|
71
115
|
ctx.drawingSlots.set(handleId, slot);
|
|
72
116
|
op = "create";
|
|
73
117
|
}
|
|
74
118
|
else {
|
|
75
119
|
// Cross-bar re-entry. Merge initialState into the existing slot
|
|
76
120
|
// (script-author may pass new anchors / style); resurrect if it
|
|
77
|
-
// was previously removed.
|
|
78
|
-
|
|
121
|
+
// was previously removed. A re-specified `z` (non-default)
|
|
122
|
+
// overrides the retained one; an omitted/`0` `z` keeps the last.
|
|
123
|
+
existing.state = mergeState(existing.state, initial.state);
|
|
124
|
+
if (initial.z !== 0)
|
|
125
|
+
existing.z = initial.z;
|
|
79
126
|
existing.removed = false;
|
|
80
127
|
slot = existing;
|
|
81
128
|
op = "update";
|
|
82
129
|
}
|
|
83
|
-
emit(ctx, handleId, kind, op, slot.state);
|
|
130
|
+
emit(ctx, handleId, kind, op, slot.state, slot.z);
|
|
84
131
|
return {
|
|
85
132
|
id: handleId,
|
|
86
133
|
update(patch) {
|
|
@@ -95,8 +142,15 @@ export function createDrawingHandle(slotId, subId, kind, initialState) {
|
|
|
95
142
|
const s = liveCtx.drawingSlots.get(handleId);
|
|
96
143
|
if (s === undefined || s.removed)
|
|
97
144
|
return;
|
|
98
|
-
|
|
99
|
-
|
|
145
|
+
// A patch may re-specify `z` inside `style`; split it out so
|
|
146
|
+
// it never merges into `state.style`. A re-specified
|
|
147
|
+
// non-default `z` overrides; an omitted/`0` `z` retains the
|
|
148
|
+
// slot's last value.
|
|
149
|
+
const split = splitZ(mergeState(s.state, patch));
|
|
150
|
+
s.state = split.state;
|
|
151
|
+
if (split.z !== 0)
|
|
152
|
+
s.z = split.z;
|
|
153
|
+
emit(liveCtx, handleId, kind, "update", s.state, s.z);
|
|
100
154
|
},
|
|
101
155
|
remove() {
|
|
102
156
|
const liveCtx = ACTIVE_RUNTIME_CONTEXT.current;
|
|
@@ -109,9 +163,10 @@ export function createDrawingHandle(slotId, subId, kind, initialState) {
|
|
|
109
163
|
// mid-run, so a previously-created handle's "remove" always
|
|
110
164
|
// reaches `pushDrawing`. The slot stays flagged even if a
|
|
111
165
|
// future drop path swallows the emission — a removed handle
|
|
112
|
-
// must never re-emit.
|
|
166
|
+
// must never re-emit. `remove` carries the last-known `z`
|
|
167
|
+
// (harmless — no render).
|
|
113
168
|
s.removed = true;
|
|
114
|
-
emit(liveCtx, handleId, kind, "remove", s.state);
|
|
169
|
+
emit(liveCtx, handleId, kind, "remove", s.state, s.z);
|
|
115
170
|
},
|
|
116
171
|
};
|
|
117
172
|
}
|