@orangecharts/wrun-chart-host 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +72 -0
  2. package/dist/constants/governed-exchanges.constants.d.ts +11 -0
  3. package/dist/constants/governed-exchanges.constants.js +11 -0
  4. package/dist/constants/indicator-sets.constants.d.ts +8 -0
  5. package/dist/constants/indicator-sets.constants.js +8 -0
  6. package/dist/constants/interval.constants.d.ts +34 -0
  7. package/dist/constants/interval.constants.js +121 -0
  8. package/dist/constants/scriptEditor/technicalIndicatorScriptKeys.constants.d.ts +28 -0
  9. package/dist/constants/scriptEditor/technicalIndicatorScriptKeys.constants.js +65 -0
  10. package/dist/constants/tpo-color-schemes.constants.d.ts +30 -0
  11. package/dist/constants/tpo-color-schemes.constants.js +32 -0
  12. package/dist/host-env.d.ts +102 -0
  13. package/dist/host-env.js +26 -0
  14. package/dist/index.d.ts +93 -0
  15. package/dist/index.js +96 -0
  16. package/dist/indicators/controls/tpo-letter.util.d.ts +2 -0
  17. package/dist/indicators/controls/tpo-letter.util.js +13 -0
  18. package/dist/indicators/controls/tpo-session.util.d.ts +99 -0
  19. package/dist/indicators/controls/tpo-session.util.js +389 -0
  20. package/dist/interfaces/kscript-diagnostics.interface.d.ts +64 -0
  21. package/dist/interfaces/kscript-diagnostics.interface.js +1 -0
  22. package/dist/interfaces/om-panel-data.interface.d.ts +103 -0
  23. package/dist/interfaces/om-panel-data.interface.js +7 -0
  24. package/dist/interfaces/wrun-runtime.interface.d.ts +2659 -0
  25. package/dist/interfaces/wrun-runtime.interface.js +55 -0
  26. package/dist/utility/chart/calendar-interval.util.d.ts +24 -0
  27. package/dist/utility/chart/calendar-interval.util.js +81 -0
  28. package/dist/utility/chart/candle-bar-end.util.d.ts +15 -0
  29. package/dist/utility/chart/candle-bar-end.util.js +23 -0
  30. package/dist/utility/chart/cme-realtime.util.d.ts +24 -0
  31. package/dist/utility/chart/cme-realtime.util.js +53 -0
  32. package/dist/utility/chart/interval-ladder.util.d.ts +27 -0
  33. package/dist/utility/chart/interval-ladder.util.js +92 -0
  34. package/dist/utility/chart/kscript-drawing-prep.util.d.ts +40 -0
  35. package/dist/utility/chart/kscript-drawing-prep.util.js +184 -0
  36. package/dist/utility/chart/kscript-drawing-safe-area.util.d.ts +95 -0
  37. package/dist/utility/chart/kscript-drawing-safe-area.util.js +805 -0
  38. package/dist/utility/chart/kscript-legend-entries.util.d.ts +166 -0
  39. package/dist/utility/chart/kscript-legend-entries.util.js +538 -0
  40. package/dist/utility/chart/kscript-output-role.util.d.ts +32 -0
  41. package/dist/utility/chart/kscript-output-role.util.js +215 -0
  42. package/dist/utility/chart/kscript-provenance-keys.util.d.ts +22 -0
  43. package/dist/utility/chart/kscript-provenance-keys.util.js +56 -0
  44. package/dist/utility/chart/kscript-run-result-normalize.util.d.ts +53 -0
  45. package/dist/utility/chart/kscript-run-result-normalize.util.js +476 -0
  46. package/dist/utility/chart/kscript-run-result-shape.util.d.ts +14 -0
  47. package/dist/utility/chart/kscript-run-result-shape.util.js +66 -0
  48. package/dist/utility/chart/kscript-titancharts-container.util.d.ts +29 -0
  49. package/dist/utility/chart/kscript-titancharts-container.util.js +151 -0
  50. package/dist/utility/chart/kscript-viewport-overlays.util.d.ts +83 -0
  51. package/dist/utility/chart/kscript-viewport-overlays.util.js +443 -0
  52. package/dist/utility/chart/om-panel-push-style.util.d.ts +78 -0
  53. package/dist/utility/chart/om-panel-push-style.util.js +301 -0
  54. package/dist/utility/chart/om-panel.util.d.ts +166 -0
  55. package/dist/utility/chart/om-panel.util.js +815 -0
  56. package/dist/utility/chart/om-series.util.d.ts +42 -0
  57. package/dist/utility/chart/om-series.util.js +330 -0
  58. package/dist/utility/chart/om-target.util.d.ts +11 -0
  59. package/dist/utility/chart/om-target.util.js +24 -0
  60. package/dist/utility/chart/om-widget.util.d.ts +148 -0
  61. package/dist/utility/chart/om-widget.util.js +413 -0
  62. package/dist/utility/chart/overlay-output-budget.util.d.ts +16 -0
  63. package/dist/utility/chart/overlay-output-budget.util.js +109 -0
  64. package/dist/utility/chart/overlay-paint-flags.util.d.ts +24 -0
  65. package/dist/utility/chart/overlay-paint-flags.util.js +55 -0
  66. package/dist/utility/chart/profile-row-height.util.d.ts +21 -0
  67. package/dist/utility/chart/profile-row-height.util.js +110 -0
  68. package/dist/utility/chart/session-interval.util.d.ts +1 -0
  69. package/dist/utility/chart/session-interval.util.js +35 -0
  70. package/dist/utility/chart/technical-script-legend-value.util.d.ts +18 -0
  71. package/dist/utility/chart/technical-script-legend-value.util.js +53 -0
  72. package/dist/utility/chart/trading-day.util.d.ts +70 -0
  73. package/dist/utility/chart/trading-day.util.js +238 -0
  74. package/dist/utility/chart/wrun-legend-name.util.d.ts +25 -0
  75. package/dist/utility/chart/wrun-legend-name.util.js +87 -0
  76. package/dist/utility/chart/wrun-run-result.util.d.ts +977 -0
  77. package/dist/utility/chart/wrun-run-result.util.js +5179 -0
  78. package/dist/utility/chart/wrun-visibility-chart.util.d.ts +25 -0
  79. package/dist/utility/chart/wrun-visibility-chart.util.js +22 -0
  80. package/dist/utility/indicators/heatmap-sensitivity.util.d.ts +62 -0
  81. package/dist/utility/indicators/heatmap-sensitivity.util.js +82 -0
  82. package/dist/utility/number-format.util.d.ts +68 -0
  83. package/dist/utility/number-format.util.js +188 -0
  84. package/dist/utility/v2/opra-governed.util.d.ts +1 -0
  85. package/dist/utility/v2/opra-governed.util.js +13 -0
  86. package/dist/utility/wrun/wrun-auto-row.util.d.ts +54 -0
  87. package/dist/utility/wrun/wrun-auto-row.util.js +96 -0
  88. package/dist/utility/wrun/wrun-batched-marks.util.d.ts +341 -0
  89. package/dist/utility/wrun/wrun-batched-marks.util.js +938 -0
  90. package/dist/utility/wrun/wrun-batched-readout.util.d.ts +75 -0
  91. package/dist/utility/wrun/wrun-batched-readout.util.js +171 -0
  92. package/dist/utility/wrun/wrun-box-segment.util.d.ts +185 -0
  93. package/dist/utility/wrun/wrun-box-segment.util.js +570 -0
  94. package/dist/utility/wrun/wrun-build-memo.util.d.ts +133 -0
  95. package/dist/utility/wrun/wrun-build-memo.util.js +301 -0
  96. package/dist/utility/wrun/wrun-builtin-twin-ports.util.d.ts +25 -0
  97. package/dist/utility/wrun/wrun-builtin-twin-ports.util.js +75 -0
  98. package/dist/utility/wrun/wrun-builtin-twin.util.d.ts +9 -0
  99. package/dist/utility/wrun/wrun-builtin-twin.util.js +40 -0
  100. package/dist/utility/wrun/wrun-canvas-cache.util.d.ts +28 -0
  101. package/dist/utility/wrun/wrun-canvas-cache.util.js +56 -0
  102. package/dist/utility/wrun/wrun-canvas-readout.util.d.ts +69 -0
  103. package/dist/utility/wrun/wrun-canvas-readout.util.js +53 -0
  104. package/dist/utility/wrun/wrun-canvases.util.d.ts +295 -0
  105. package/dist/utility/wrun/wrun-canvases.util.js +1432 -0
  106. package/dist/utility/wrun/wrun-cap-notice.util.d.ts +77 -0
  107. package/dist/utility/wrun/wrun-cap-notice.util.js +296 -0
  108. package/dist/utility/wrun/wrun-card-style.util.d.ts +154 -0
  109. package/dist/utility/wrun/wrun-card-style.util.js +539 -0
  110. package/dist/utility/wrun/wrun-chart-context.util.d.ts +89 -0
  111. package/dist/utility/wrun/wrun-chart-context.util.js +213 -0
  112. package/dist/utility/wrun/wrun-chart-names.util.d.ts +23 -0
  113. package/dist/utility/wrun/wrun-chart-names.util.js +33 -0
  114. package/dist/utility/wrun/wrun-chart-time.util.d.ts +12 -0
  115. package/dist/utility/wrun/wrun-chart-time.util.js +23 -0
  116. package/dist/utility/wrun/wrun-child-overlay-id.util.d.ts +13 -0
  117. package/dist/utility/wrun/wrun-child-overlay-id.util.js +44 -0
  118. package/dist/utility/wrun/wrun-color-facts.util.d.ts +40 -0
  119. package/dist/utility/wrun/wrun-color-facts.util.js +88 -0
  120. package/dist/utility/wrun/wrun-color-settings.lazy.d.ts +26 -0
  121. package/dist/utility/wrun/wrun-color-settings.lazy.js +9 -0
  122. package/dist/utility/wrun/wrun-color-settings.util.d.ts +351 -0
  123. package/dist/utility/wrun/wrun-color-settings.util.js +1363 -0
  124. package/dist/utility/wrun/wrun-footprint-modes.util.d.ts +23 -0
  125. package/dist/utility/wrun/wrun-footprint-modes.util.js +24 -0
  126. package/dist/utility/wrun/wrun-frames.d.ts +217 -0
  127. package/dist/utility/wrun/wrun-frames.js +1021 -0
  128. package/dist/utility/wrun/wrun-handles.util.d.ts +792 -0
  129. package/dist/utility/wrun/wrun-handles.util.js +2050 -0
  130. package/dist/utility/wrun/wrun-heatmap-cell-budget.util.d.ts +156 -0
  131. package/dist/utility/wrun/wrun-heatmap-cell-budget.util.js +342 -0
  132. package/dist/utility/wrun/wrun-hosted-wire-caps.d.ts +218 -0
  133. package/dist/utility/wrun/wrun-hosted-wire-caps.js +667 -0
  134. package/dist/utility/wrun/wrun-hosted-wire.util.d.ts +40 -0
  135. package/dist/utility/wrun/wrun-hosted-wire.util.js +27 -0
  136. package/dist/utility/wrun/wrun-hover.util.d.ts +182 -0
  137. package/dist/utility/wrun/wrun-hover.util.js +534 -0
  138. package/dist/utility/wrun/wrun-hud-looks.util.d.ts +246 -0
  139. package/dist/utility/wrun/wrun-hud-looks.util.js +587 -0
  140. package/dist/utility/wrun/wrun-integration-budget.util.d.ts +47 -0
  141. package/dist/utility/wrun/wrun-integration-budget.util.js +122 -0
  142. package/dist/utility/wrun/wrun-latest-snapshot.d.ts +19 -0
  143. package/dist/utility/wrun/wrun-latest-snapshot.js +7 -0
  144. package/dist/utility/wrun/wrun-levels-child.util.d.ts +131 -0
  145. package/dist/utility/wrun/wrun-levels-child.util.js +514 -0
  146. package/dist/utility/wrun/wrun-lifecycle.contract.d.ts +75 -0
  147. package/dist/utility/wrun/wrun-lifecycle.contract.js +9 -0
  148. package/dist/utility/wrun/wrun-market-facts.util.d.ts +116 -0
  149. package/dist/utility/wrun/wrun-market-facts.util.js +238 -0
  150. package/dist/utility/wrun/wrun-output-style.util.d.ts +344 -0
  151. package/dist/utility/wrun/wrun-output-style.util.js +1239 -0
  152. package/dist/utility/wrun/wrun-overlay-identity.util.d.ts +84 -0
  153. package/dist/utility/wrun/wrun-overlay-identity.util.js +142 -0
  154. package/dist/utility/wrun/wrun-overlay-result.util.d.ts +120 -0
  155. package/dist/utility/wrun/wrun-overlay-result.util.js +219 -0
  156. package/dist/utility/wrun/wrun-pack.util.d.ts +70 -0
  157. package/dist/utility/wrun/wrun-pack.util.js +301 -0
  158. package/dist/utility/wrun/wrun-pane-format.util.d.ts +180 -0
  159. package/dist/utility/wrun/wrun-pane-format.util.js +299 -0
  160. package/dist/utility/wrun/wrun-panel-style.lazy.d.ts +25 -0
  161. package/dist/utility/wrun/wrun-panel-style.lazy.js +15 -0
  162. package/dist/utility/wrun/wrun-panel-style.util.d.ts +174 -0
  163. package/dist/utility/wrun/wrun-panel-style.util.js +726 -0
  164. package/dist/utility/wrun/wrun-param-values.util.d.ts +69 -0
  165. package/dist/utility/wrun/wrun-param-values.util.js +230 -0
  166. package/dist/utility/wrun/wrun-refusal.util.d.ts +263 -0
  167. package/dist/utility/wrun/wrun-refusal.util.js +1259 -0
  168. package/dist/utility/wrun/wrun-registry-errors.util.d.ts +199 -0
  169. package/dist/utility/wrun/wrun-registry-errors.util.js +257 -0
  170. package/dist/utility/wrun/wrun-render-select.util.d.ts +336 -0
  171. package/dist/utility/wrun/wrun-render-select.util.js +1157 -0
  172. package/dist/utility/wrun/wrun-script-inputs.util.d.ts +434 -0
  173. package/dist/utility/wrun/wrun-script-inputs.util.js +1971 -0
  174. package/dist/utility/wrun/wrun-setting-words.lazy.d.ts +20 -0
  175. package/dist/utility/wrun/wrun-setting-words.lazy.js +9 -0
  176. package/dist/utility/wrun/wrun-setting-words.util.d.ts +79 -0
  177. package/dist/utility/wrun/wrun-setting-words.util.js +176 -0
  178. package/dist/utility/wrun/wrun-socket-row-store.d.ts +98 -0
  179. package/dist/utility/wrun/wrun-socket-row-store.js +417 -0
  180. package/dist/utility/wrun/wrun-style-flags.util.d.ts +18 -0
  181. package/dist/utility/wrun/wrun-style-flags.util.js +21 -0
  182. package/dist/utility/wrun/wrun-style-words.util.d.ts +148 -0
  183. package/dist/utility/wrun/wrun-style-words.util.js +439 -0
  184. package/dist/utility/wrun/wrun-table-look.util.d.ts +125 -0
  185. package/dist/utility/wrun/wrun-table-look.util.js +225 -0
  186. package/dist/utility/wrun/wrun-text-look.util.d.ts +51 -0
  187. package/dist/utility/wrun/wrun-text-look.util.js +227 -0
  188. package/dist/utility/wrun/wrun-text-params.util.d.ts +106 -0
  189. package/dist/utility/wrun/wrun-text-params.util.js +171 -0
  190. package/dist/utility/wrun/wrun-tpo-rows.util.d.ts +71 -0
  191. package/dist/utility/wrun/wrun-tpo-rows.util.js +438 -0
  192. package/dist/utility/wrun/wrun-twin-compute-inputs.util.d.ts +14 -0
  193. package/dist/utility/wrun/wrun-twin-compute-inputs.util.js +58 -0
  194. package/dist/utility/wrun/wrun-visibility-table.d.ts +437 -0
  195. package/dist/utility/wrun/wrun-visibility-table.js +237 -0
  196. package/dist/utility/wrun/wrun-volume-profile.util.d.ts +37 -0
  197. package/dist/utility/wrun/wrun-volume-profile.util.js +278 -0
  198. package/package.json +38 -0
@@ -0,0 +1,1363 @@
1
+ /**
2
+ * Colour settings for browser-run Indicators (frozen sheet contract, round 6):
3
+ * how a colour param's packed default, the overlay's picked colour string and
4
+ * the sheet locations it paints fit together, and the ONE seam that repaints
5
+ * a sheet with the overlay's current settings.
6
+ *
7
+ * - A compute colour param (`type: 'color'`, no om `style`) defaults to the
8
+ * packed colour `((r * 256 + g) * 256 + b) * 1024 + round(alpha * 1000)`
9
+ * (the `color_packed_by` wire). The settings dialog shows and stores a
10
+ * colour STRING; init() receives the packed number of the stored string
11
+ * (an unparsable setting falls back to the default).
12
+ * - `color_array: '<kScript input name>'` groups N consecutive colour params
13
+ * into one colour-array row stored under that key (member i = element i),
14
+ * the kScript `color[]` input's own shape.
15
+ * - An om `style` knob never reaches init() (its slot holds 0, the om
16
+ * runtime's rule) and sets its bound output's property.
17
+ * - `style_targets` lists every sheet location a colour param, a number /
18
+ * int / select param (round 7: widths, line styles; a select writes
19
+ * `style_values[value]` when it declares them), a boolean param (its state
20
+ * in the kind the location holds: true / false or 1 / 0, e.g. a Smooth
21
+ * toggle on each line's `smooth`, a stats row's switch at
22
+ * `renderers.<name>.visible`, which a legacy 0..1 switch param paints the
23
+ * same way, or an output's `visible`, which makes the param OWN that
24
+ * output's visibility, wrunVisibilityOwners) or a style knob sets;
25
+ * `wrunSheetWithSettings` writes them into a copy of the sheet
26
+ * before anything reads it (run request, run result, live ticks), so every
27
+ * reader downstream (ladders, ranges, renderers, tables, handle defaults,
28
+ * legend, price tags) sees the chosen colours. A target's `alpha`
29
+ * REPLACES the pick's own alpha (the kScript engine's opacity() rule, see
30
+ * WrunStyleTarget).
31
+ *
32
+ * Typed inputs (WRUN-INPUTS-PLAN 1.1, 1.5, 1.7) ride the same seam:
33
+ * - A host-applied param (`host: 'source' | 'interval' | 'symbol'`) stays an
34
+ * ordinary numeric init arg (its index, 0 for a symbol) and, on the browser
35
+ * host only, rewrites the pins of every input bound to it (`field_param`,
36
+ * `interval_param`, `symbol_param` on the input): the frozen field word at
37
+ * the setting index (the blends hl2 / hlc3 / ohlc4 / hlcc4 included, the
38
+ * row builder derives them), the frozen interval word (index 0 = follow the chart = the pin
39
+ * key removed), the `EXCHANGE:SYMBOL` text split into both pins. A setting
40
+ * at the declared default writes nothing: the extractor baked the default
41
+ * pins into the sheet.
42
+ * - A volume-profile bucket size bound to a setting (frozen authoring
43
+ * contract C1.3, the in-source `ticks_per_bar: "@<int param>"`): an input
44
+ * bound to a declared param (`ticks_per_bar_param` beside a numeric
45
+ * default, or the reference verbatim in `ticks_per_bar`) takes that
46
+ * param's current value (the setting, else its default) as its
47
+ * `ticks_per_bar`, so the lane request, the live fold and a settings
48
+ * change follow it, the way a timeframe or symbol param rewrites its pins.
49
+ * A value equal to the baked `ticks_per_bar` writes nothing; the lane util
50
+ * clamps it to 1..500 (`wrunVolumeProfileLaneExtras`).
51
+ * - The lane words (kit 0.77.0, `laneWordWrites`): `currency_param` and `when`.
52
+ * - A Style page row (`__style__<output>__<property>`, an FE-only declared
53
+ * input that never reaches any host) writes the output's `width`,
54
+ * `line_style`, `color` or `opacity` (created when the sheet left the key
55
+ * to the adapter's default), and `colors` recolours a two-tone histogram's
56
+ * declared `colors` swatch by swatch. An output's `visible` row is no
57
+ * sheet write: the run applies it through `applyWrunOutputVisibility`
58
+ * after integration. An output a boolean param owns has no such row: the
59
+ * param's flag is the sheet's `visible`, which that apply reads.
60
+ * - The targets past the outputs are the visibility table's
61
+ * (wrun-visibility-table.ts, frozen identities): a renderer of any kind
62
+ * (`text:<name>`), a heatmap (`heatmap:<name>`), a profile
63
+ * (`profile:<name>`), a docked level (`levels:<name>`), a batched section
64
+ * (`marks:<name>`, `spans:<name>`, `rays:<name>`), a band
65
+ * (`fill:<first>/<second>#<n>`, `range:<upper>/<lower>#<n>`), a box
66
+ * (`box:<name>`), a segment (`segment:<name>`), a sheet drawing
67
+ * (`drawing:<kind>:<name>`), a draw-API handle kind (`handles:<kind>`), a
68
+ * matrix (`matrix:<name>`) and a panel (`panel:<name>`). A Visible row is a
69
+ * sheet write on the declaration only for the table's `skip` group
70
+ * (wrunStyleTargetWrites: `visible: false` mounts nothing,
71
+ * isWrunStyleTargetHidden); the colour rows land on the keys the builders
72
+ * already read. A change to any of them, or to an output's `colors`,
73
+ * reruns: the in-place patch (wrun-style-patch.util) reaches an output's
74
+ * color, width, line_style and opacity, and the Visible rows of the
75
+ * table's `nested` group, only.
76
+ * - A colour lands in the kind its location holds: a colour word into a
77
+ * string location, the packed number (the colour param's own form) into a
78
+ * batched section's `colors` slot holding a number (packed by the build;
79
+ * any other number, a width or an opacity, is no colour and stays), so a
80
+ * colour param bound through `style_targets` and a `colors` row paint either.
81
+ */
82
+ import { isEqual } from 'lodash-es';
83
+ import { HEATMAP_SENSITIVITY_MAX, HEATMAP_SENSITIVITY_MIN } from '../indicators/heatmap-sensitivity.util.js';
84
+ import { WRUN_SOURCE_FIELD_WORDS, wrunInputGateOn } from './wrun-market-facts.util.js';
85
+ import { wrunParamValuesFromSettings } from './wrun-param-values.util.js';
86
+ import { bindWrunColorSettings } from './wrun-color-settings.lazy.js';
87
+ import { WRUN_LEVELS_COLOR_PICKED_KEY } from './wrun-style-flags.util.js';
88
+ import { findWrunVisibilityTarget, wrunVisibilitySectionOfPrefix, wrunVisibilityTargetAt, } from './wrun-visibility-table.js';
89
+ import { isWrunHudViewerRowKey, packWrunColor, parseWrunColor, WRUN_HEATMAP_SENSITIVITY_ROW_RE, WRUN_HUD_LOOK_ROW_PREFIX, WRUN_HUD_LOOK_ROW_RE, } from './wrun-color-facts.util.js';
90
+ // The key predicates and the colour parse are thin facts boot-path readers take without this
91
+ // module (wrun-color-facts.util); every name stays exported here for this module's readers.
92
+ export { isWrunHeatmapSensitivityRowKey, isWrunHudLookRowKey, isWrunHudPlaceRowKey, isWrunHudViewerRowKey, isWrunStyleRowKey, isWrunViewerRowKey, packWrunColor, parseWrunColor, WRUN_HUD_LOOK_ROW_PREFIX, WRUN_STYLE_ROW_PREFIX, } from './wrun-color-facts.util.js';
93
+ /** The largest packed colour (rgb 0xffffff, alpha 1000 thousandths), below
94
+ * 2^34 and so exact in f64. */
95
+ const WRUN_PACKED_COLOR_MAX = 0xffffff * 1024 + 1000;
96
+ const WRUN_LINE_STYLES = ['solid', 'dashed', 'dotted'];
97
+ const STYLE_PROPERTIES = ['color', 'width', 'opacity', 'lineStyle'];
98
+ /** The output key a style binding's property sets (the sheet's spelling). */
99
+ const STYLE_PROPERTY_KEYS = {
100
+ color: 'color',
101
+ width: 'width',
102
+ opacity: 'opacity',
103
+ lineStyle: 'line_style',
104
+ };
105
+ /** The frozen `param.source` field list (plan 1.7, the kit's
106
+ * WRUN_SOURCE_FIELD_WORDS): a `_field` select's value is the index into this
107
+ * list (hlcc4 is 8). The blends (hl2 / hlc3 / ohlc4 / hlcc4) are derived by
108
+ * the row builder from the candle's open / high / low / close
109
+ * (wrunSourceBlend). */
110
+ export const WRUN_SOURCE_FIELDS = WRUN_SOURCE_FIELD_WORDS;
111
+ /** The frozen `param.timeframe` word list (plan 1.7): a timeframe select's
112
+ * value is the index into this list; index 0 follows the chart (no pin). */
113
+ export const WRUN_TIMEFRAME_WORDS = Object.freeze([
114
+ 'chart',
115
+ '1m',
116
+ '5m',
117
+ '15m',
118
+ '30m',
119
+ '1h',
120
+ '4h',
121
+ '1d',
122
+ '1w',
123
+ ]);
124
+ // ---------------------------------------------------------------------------
125
+ // Select settings: the choice set and the ONE select read, for every lane.
126
+ // ---------------------------------------------------------------------------
127
+ /** A select without `options` takes its values from min..max: a range this
128
+ * long or longer stays a number field instead of a menu. */
129
+ const WRUN_SELECT_RANGE_LIMIT = 256;
130
+ function nonEmptyString(value) {
131
+ return typeof value === 'string' && value.trim() !== '' ? value : undefined;
132
+ }
133
+ /** A select param's choices: its `options` or, without them, the integers
134
+ * min..max, each labelled by `option_labels` at the same position (else by
135
+ * its value). Undefined when the param declares no usable choice set. */
136
+ export function wrunParamChoices(param) {
137
+ let values = Array.isArray(param.options)
138
+ ? param.options.filter((value) => typeof value === 'number' && Number.isFinite(value))
139
+ : [];
140
+ if (values.length === 0) {
141
+ const { min, max } = param;
142
+ if (typeof min !== 'number' || typeof max !== 'number' || !Number.isInteger(min) || !Number.isInteger(max)) {
143
+ return undefined;
144
+ }
145
+ if (max < min || max - min >= WRUN_SELECT_RANGE_LIMIT)
146
+ return undefined;
147
+ values = Array.from({ length: max - min + 1 }, (_, at) => min + at);
148
+ }
149
+ const labels = Array.isArray(param.option_labels) ? param.option_labels : [];
150
+ return values.map((value, at) => ({ value, label: nonEmptyString(labels[at]) ?? String(value) }));
151
+ }
152
+ /**
153
+ * A select setting resolved against the row's option strings and their
154
+ * labels: the ONE select read. The dialog's row codec, the run values, the
155
+ * cloud param map, the sheet's host pins and its style targets all read a
156
+ * persisted choice through it, so every lane agrees. A string that is an
157
+ * option is itself; an option label is its option; a number, or a numeric
158
+ * string, is the option whose string it is, else (an integer that names no
159
+ * option) the option at that index; anything else, an index past the
160
+ * options included (a choice persisted before the author dropped one), is
161
+ * undefined, and the reader keeps its declared default. A row without
162
+ * options passes the value through.
163
+ */
164
+ export function wrunSelectOptionValue(options, labels, raw) {
165
+ if (typeof raw === 'string') {
166
+ if (options.length === 0 || options.includes(raw))
167
+ return raw;
168
+ const at = labels.indexOf(raw);
169
+ if (at >= 0 && options[at] !== undefined)
170
+ return options[at];
171
+ const numeric = raw.trim() === '' ? Number.NaN : Number(raw);
172
+ return Number.isFinite(numeric) ? wrunSelectOptionValue(options, labels, numeric) : undefined;
173
+ }
174
+ if (typeof raw !== 'number' || !Number.isFinite(raw))
175
+ return undefined;
176
+ const text = String(raw);
177
+ if (options.length === 0 || options.includes(text))
178
+ return text;
179
+ return Number.isInteger(raw) && options[raw] !== undefined ? options[raw] : undefined;
180
+ }
181
+ /** A select PARAM's setting as its option value (the number init() and the
182
+ * sheet writes take), through the one select read over the param's choice
183
+ * set; undefined when the param declares no usable choice set (the number
184
+ * field's read applies) or the setting names no option. */
185
+ export function wrunSelectParamValue(param, raw) {
186
+ const choices = wrunParamChoices(param);
187
+ if (choices === undefined)
188
+ return undefined;
189
+ const picked = wrunSelectOptionValue(choices.map((choice) => String(choice.value)), choices.map((choice) => choice.label), raw);
190
+ return picked === undefined ? undefined : Number(picked);
191
+ }
192
+ /** A Style page row key (`WRUN_STYLE_ROW_PREFIX`, wrun-color-facts.util) read apart. */
193
+ const WRUN_STYLE_ROW_RE = /^__style__(.+)__(visible|width|lineStyle|color|opacity|colors)$/;
194
+ /** A Style page row key read back: the target it styles (an output name, or
195
+ * a prefixed declaration, parseWrunStyleTarget) and the property. */
196
+ export function parseWrunStyleRowKey(key) {
197
+ const match = WRUN_STYLE_ROW_RE.exec(key);
198
+ return match ? { output: match[1], property: match[2] } : undefined;
199
+ }
200
+ /** A Style row target read back: a prefix the visibility table lists and the identity after it,
201
+ * else an output name as written (an output name never carries a colon, the kit's output grammar),
202
+ * else `unknown`: a target with a colon the table does not list is refused, never read as an output
203
+ * name (a write for it paints nothing). */
204
+ export function parseWrunStyleTarget(target) {
205
+ const colon = target.indexOf(':');
206
+ if (colon === -1)
207
+ return { kind: 'output', name: target };
208
+ const prefix = target.slice(0, colon);
209
+ const name = target.slice(colon + 1);
210
+ return wrunVisibilitySectionOfPrefix(prefix) !== undefined && name !== ''
211
+ ? { kind: prefix, name }
212
+ : { kind: 'unknown', name: target };
213
+ }
214
+ /** True for a declaration a Style row's Visible switched off (C1: a text
215
+ * renderer, heatmap, profile or levels declaration the seam painted
216
+ * `visible: false`): it mounts nothing, the stats-row rule. Absent or true
217
+ * draws. */
218
+ export function isWrunStyleTargetHidden(declaration) {
219
+ return isRecord(declaration) && declaration.visible === false;
220
+ }
221
+ /** A HUD's Look row (`hud:<name>:look`, the prefix and the reader in wrun-color-facts.util). */
222
+ const WRUN_HUD_LOOK_ROW_SUFFIX = ':look';
223
+ export function wrunHudLookRowKey(name) {
224
+ return `${WRUN_HUD_LOOK_ROW_PREFIX}${name}${WRUN_HUD_LOOK_ROW_SUFFIX}`;
225
+ }
226
+ /** A HUD Look row key read back: the HUD it belongs to. */
227
+ export function parseWrunHudLookRowKey(key) {
228
+ const match = WRUN_HUD_LOOK_ROW_RE.exec(key);
229
+ return match ? { name: match[1] } : undefined;
230
+ }
231
+ /** The viewer's Look pick for one HUD under the overlay's settings: the
232
+ * stored word, or undefined for "As made" (absent, empty, not a string).
233
+ * The resolver checks the word against the look list. */
234
+ export function wrunHudLookSetting(settings, name) {
235
+ const raw = flatSettings(settings)?.[wrunHudLookRowKey(name)];
236
+ return typeof raw === 'string' && raw.trim() !== '' ? raw.trim() : undefined;
237
+ }
238
+ /** The viewer's own place for one HUD (the card moved by its title on the
239
+ * chart): `hud:<name>:place`, stored on the overlay beside the Look pick and
240
+ * never written into the sheet. The value is `<anchor>@<at>` for a card
241
+ * snapped into one of the nine places, or `<anchor>@<at>:<dx>,<dy>` for a
242
+ * card dropped free: its nearest place plus the nudge inward from it (DW22's
243
+ * offset convention). `at` is when the move was made, so in a place shared
244
+ * with other cards the latest move sits outermost. Absent = where the script
245
+ * puts it. */
246
+ const WRUN_HUD_PLACE_ROW_SUFFIX = ':place';
247
+ const WRUN_HUD_PLACE_VALUE_RE = /^([a-z_]+)@(\d{1,16})(?::(-?\d{1,6}),(-?\d{1,6}))?$/;
248
+ const WRUN_HUD_PLACE_ANCHORS = [
249
+ 'top_left',
250
+ 'top_center',
251
+ 'top_right',
252
+ 'middle_left',
253
+ 'middle_center',
254
+ 'middle_right',
255
+ 'bottom_left',
256
+ 'bottom_center',
257
+ 'bottom_right',
258
+ ];
259
+ export function wrunHudPlaceRowKey(name) {
260
+ return `${WRUN_HUD_LOOK_ROW_PREFIX}${name}${WRUN_HUD_PLACE_ROW_SUFFIX}`;
261
+ }
262
+ /** The viewer's Sensitivity for one heatmap (`heatmap:<name>:sensitivity`):
263
+ * a 0..100 slider position on the options heatmap's Subtle..Vivid map
264
+ * (options-heatmap-encoding.util), stored on the overlay beside the HUD rows
265
+ * and never written into the sheet: the run keeps the author's bounds and
266
+ * the mount re-picks them (wrun-canvases.util). Absent or null is the
267
+ * author's `auto_quantile`, exactly. */
268
+ export function wrunHeatmapSensitivityRowKey(name) {
269
+ return `heatmap:${name}:sensitivity`;
270
+ }
271
+ /** A Sensitivity value read as a position: a finite number clamped into
272
+ * 0..100; undefined (draw the author's bounds) for anything else. */
273
+ export function wrunHeatmapSensitivityValue(raw) {
274
+ if (typeof raw !== 'number' || !Number.isFinite(raw))
275
+ return undefined;
276
+ return Math.min(HEATMAP_SENSITIVITY_MAX, Math.max(HEATMAP_SENSITIVITY_MIN, raw));
277
+ }
278
+ /** The viewer's Sensitivity for one heatmap under the overlay's settings: a
279
+ * finite stored position, clamped into 0..100; undefined (draw the author's
280
+ * bounds) for anything else, null and absent included. */
281
+ export function wrunHeatmapSensitivitySetting(settings, name) {
282
+ return wrunHeatmapSensitivityValue(flatSettings(settings)?.[wrunHeatmapSensitivityRowKey(name)]);
283
+ }
284
+ /** True when a save moves the Sensitivity any heatmap draws with (a value set,
285
+ * changed or cleared, read as wrunHeatmapSensitivitySetting reads it). */
286
+ export function wrunHeatmapSensitivityChanged(prev, next) {
287
+ const before = flatSettings(prev) ?? {};
288
+ const after = flatSettings(next) ?? {};
289
+ for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {
290
+ const name = WRUN_HEATMAP_SENSITIVITY_ROW_RE.exec(key)?.[1];
291
+ if (name === undefined)
292
+ continue;
293
+ if (wrunHeatmapSensitivitySetting(before, name) !== wrunHeatmapSensitivitySetting(after, name))
294
+ return true;
295
+ }
296
+ return false;
297
+ }
298
+ /** A save whose every change is a HUD's viewer row (its Look pick, its place): rows only the FE-drawn
299
+ * card reads, so no run, canvas paint or legend row depends on them. `patch` is what the save
300
+ * sends; its keys are compared with the overlay's current settings (`current`). */
301
+ export function onlyWrunHudViewerRowsChanged(current, patch) {
302
+ const before = flatSettings(current) ?? {};
303
+ const sent = flatSettings(patch) ?? {};
304
+ let changed = false;
305
+ for (const [key, value] of Object.entries(sent)) {
306
+ if (isEqual(before[key], value))
307
+ continue;
308
+ if (!isWrunHudViewerRowKey(key))
309
+ return false;
310
+ changed = true;
311
+ }
312
+ return changed;
313
+ }
314
+ /** A stored place read back; anything malformed reads as "where the script puts it". */
315
+ export function parseWrunHudPlace(raw) {
316
+ if (typeof raw !== 'string')
317
+ return undefined;
318
+ const match = WRUN_HUD_PLACE_VALUE_RE.exec(raw.trim());
319
+ if (!match || !WRUN_HUD_PLACE_ANCHORS.includes(match[1]))
320
+ return undefined;
321
+ const at = Number(match[2]);
322
+ if (!Number.isSafeInteger(at))
323
+ return undefined;
324
+ const place = { anchor: match[1], at };
325
+ if (match[3] !== undefined && match[4] !== undefined)
326
+ place.nudge = [Number(match[3]), Number(match[4])];
327
+ return place;
328
+ }
329
+ export function formatWrunHudPlace(place) {
330
+ const head = `${place.anchor}@${Math.max(0, Math.round(place.at))}`;
331
+ return place.nudge ? `${head}:${Math.round(place.nudge[0])},${Math.round(place.nudge[1])}` : head;
332
+ }
333
+ /** The viewer's place for one HUD under the overlay's settings, or undefined (the script's place). */
334
+ export function wrunHudPlaceSetting(settings, name) {
335
+ return parseWrunHudPlace(flatSettings(settings)?.[wrunHudPlaceRowKey(name)]);
336
+ }
337
+ function isRecord(value) {
338
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
339
+ }
340
+ function unpackWrunColor(value) {
341
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 0 || value > WRUN_PACKED_COLOR_MAX) {
342
+ return undefined;
343
+ }
344
+ const thousandths = value % 1024;
345
+ if (thousandths > 1000)
346
+ return undefined;
347
+ const rgb = Math.floor(value / 1024);
348
+ return { r: Math.floor(rgb / 65536), g: Math.floor(rgb / 256) % 256, b: rgb % 256, a: thousandths / 1000 };
349
+ }
350
+ /** A packed colour (the `color_packed_by` wire) as the engine's own
351
+ * `rgba(r, g, b, a)` spelling. A non-finite, negative, fractional or
352
+ * out-of-range value (alpha thousandths past 1000) decodes to no colour. */
353
+ export function decodeWrunPackedColor(value) {
354
+ const rgba = unpackWrunColor(value);
355
+ return rgba === undefined ? undefined : `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`;
356
+ }
357
+ function byteHex(value) {
358
+ return value.toString(16).padStart(2, '0');
359
+ }
360
+ /** A colour as a settings string: `#rrggbb` when opaque, else the engine's
361
+ * `rgba(r, g, b, a)` spelling (an 8-digit hex cannot hold every
362
+ * thousandth). */
363
+ export function wrunColorString(rgba) {
364
+ if (rgba.a >= 1)
365
+ return `#${byteHex(rgba.r)}${byteHex(rgba.g)}${byteHex(rgba.b)}`;
366
+ return `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`;
367
+ }
368
+ /** An om style knob (a param with `style`): never reaches init(). The om
369
+ * runtime's own test is the key's presence. */
370
+ export function isWrunStyleParam(param) {
371
+ return !!param.style;
372
+ }
373
+ function styleBinding(param) {
374
+ const style = param.style;
375
+ if (!isRecord(style) || typeof style.output !== 'string')
376
+ return undefined;
377
+ const property = style.property;
378
+ return STYLE_PROPERTIES.includes(property) ? { output: style.output, property } : undefined;
379
+ }
380
+ /** A compute colour param: `type: 'color'`, no om `style`, and a packed
381
+ * default the FE decodes (one it cannot decode keeps the number field the
382
+ * param rendered as before the key). */
383
+ export function isWrunColorParam(param) {
384
+ return param.type === 'color' && !isWrunStyleParam(param) && unpackWrunColor(param.default) !== undefined;
385
+ }
386
+ /** The colour-array key of a compute colour param, when it declares one. */
387
+ export function wrunColorArrayKey(param) {
388
+ const key = param.color_array;
389
+ return isWrunColorParam(param) && typeof key === 'string' && key.trim() !== '' ? key : undefined;
390
+ }
391
+ /** A colour param's default as a settings string (`#rrggbb` or rgba). */
392
+ export function wrunColorParamDefault(param) {
393
+ const rgba = unpackWrunColor(param.default);
394
+ return rgba === undefined ? '#000000' : wrunColorString(rgba);
395
+ }
396
+ /** A colour setting as the string the chart paints, or undefined when it is
397
+ * no colour: a parsable string verbatim (the kScript engine hands a colour
398
+ * input's value through as written), a packed number decoded. */
399
+ export function wrunColorSettingString(value) {
400
+ if (typeof value === 'string')
401
+ return parseWrunColor(value) === undefined ? undefined : value.trim();
402
+ const rgba = unpackWrunColor(value);
403
+ return rgba === undefined ? undefined : wrunColorString(rgba);
404
+ }
405
+ /** Two colour words name the same colour: the same word (a theme token, which
406
+ * only the mount door resolves), or the same rgba once parsed, alpha at the
407
+ * parser's own three decimals on both sides (a hex alpha is rounded there,
408
+ * an rgba() alpha rides as written). */
409
+ function sameWrunColorWord(a, b) {
410
+ if (a.trim().toLowerCase() === b.trim().toLowerCase())
411
+ return true;
412
+ const left = parseWrunColor(a);
413
+ const right = parseWrunColor(b);
414
+ return (left !== undefined &&
415
+ right !== undefined &&
416
+ left.r === right.r &&
417
+ left.g === right.g &&
418
+ left.b === right.b &&
419
+ Math.round(left.a * 1000) === Math.round(right.a * 1000));
420
+ }
421
+ /**
422
+ * The docked levels whose colour the settings moved away from the published
423
+ * declaration, decided ONCE over the painted sheet (so a Style row and a
424
+ * colour param bound through `style_targets` read the same rule): such a
425
+ * level gets the FE-only `color_picked` flag, and the levels child then
426
+ * paints every row with the pick instead of the frame's per-row colours (a
427
+ * GEX ladder: sky where calls carry the strike, violet where puts do) and
428
+ * leaves out the `gradient` stops with their `gradient_direction` and an
429
+ * outline's `border_color`: each would otherwise paint over the pick and
430
+ * leave the colour row with nothing to paint. A level at its
431
+ * declared colour, in any spelling, carries no flag, and a flag a published
432
+ * sheet brings along is dropped here: only this comparison ever sets it.
433
+ */
434
+ function levelColorPickedWrites(published, painted) {
435
+ const declaredLevels = Array.isArray(published.levels) ? published.levels : [];
436
+ const paintedLevels = Array.isArray(painted.levels) ? painted.levels : [];
437
+ const writes = [];
438
+ paintedLevels.forEach((level, at) => {
439
+ if (!isRecord(level))
440
+ return;
441
+ const declared = declaredLevels[at];
442
+ const declaredColor = isRecord(declared) && typeof declared.color === 'string' ? declared.color : undefined;
443
+ const color = typeof level.color === 'string' ? level.color : undefined;
444
+ const picked = declaredColor !== undefined && color !== undefined && !sameWrunColorWord(declaredColor, color);
445
+ const path = ['levels', at, WRUN_LEVELS_COLOR_PICKED_KEY];
446
+ if (picked)
447
+ writes.push({ path, kind: 'flag', on: true, create: true });
448
+ else if (WRUN_LEVELS_COLOR_PICKED_KEY in level)
449
+ writes.push({ path, kind: 'delete' });
450
+ });
451
+ return writes;
452
+ }
453
+ /** Each colour-array member's key and position (member i = element i of
454
+ * the row stored under the key), in param order. */
455
+ export function wrunColorArrayMembers(params) {
456
+ const members = new Map();
457
+ const counts = new Map();
458
+ for (const param of params) {
459
+ const key = wrunColorArrayKey(param);
460
+ if (key === undefined)
461
+ continue;
462
+ const index = counts.get(key) ?? 0;
463
+ counts.set(key, index + 1);
464
+ members.set(param.name, { key, index });
465
+ }
466
+ return members;
467
+ }
468
+ /** The raw setting a colour param reads: its own flat key, or element i of
469
+ * its colour-array row. */
470
+ function rawColorSetting(param, flat, members) {
471
+ const member = members.get(param.name);
472
+ if (member === undefined)
473
+ return flat?.[param.name];
474
+ const row = flat?.[member.key];
475
+ return Array.isArray(row) ? row[member.index] : undefined;
476
+ }
477
+ function flatSettings(settings) {
478
+ return isRecord(settings) ? settings : undefined;
479
+ }
480
+ /** The colour a colour param paints under the overlay's settings: the
481
+ * setting when it is a colour, else the declared default. */
482
+ export function wrunColorParamSetting(param, settings, members = new Map()) {
483
+ return (wrunColorSettingString(rawColorSetting(param, flatSettings(settings), members)) ?? wrunColorParamDefault(param));
484
+ }
485
+ /** The packed colour init() receives for a colour param: the setting's
486
+ * colour packed, else (no setting, or no colour) the declared default. */
487
+ export function wrunColorParamPacked(param, settings, members = new Map()) {
488
+ const raw = rawColorSetting(param, flatSettings(settings), members);
489
+ const rgba = typeof raw === 'string' ? parseWrunColor(raw) : unpackWrunColor(raw);
490
+ return rgba === undefined ? param.default : packWrunColor(rgba);
491
+ }
492
+ /** An om style knob's current value under the overlay's settings (the
493
+ * setting when it fits the property, else the declared default), or
494
+ * undefined when neither fits. */
495
+ export function wrunStyleParamValue(param, settings) {
496
+ const binding = styleBinding(param);
497
+ if (binding === undefined)
498
+ return undefined;
499
+ const raw = flatSettings(settings)?.[param.name];
500
+ switch (binding.property) {
501
+ case 'color':
502
+ return wrunColorSettingString(raw) ?? wrunColorSettingString(param.default);
503
+ case 'lineStyle': {
504
+ const fits = (value) => typeof value === 'string' && WRUN_LINE_STYLES.includes(value);
505
+ return fits(raw) ? raw : fits(param.default) ? param.default : undefined;
506
+ }
507
+ default: {
508
+ const value = typeof raw === 'number' || typeof raw === 'string' ? Number(raw) : Number.NaN;
509
+ if (raw !== '' && Number.isFinite(value))
510
+ return value;
511
+ return typeof param.default === 'number' && Number.isFinite(param.default) ? param.default : undefined;
512
+ }
513
+ }
514
+ }
515
+ /** The line styles a lineStyle knob offers (the dialog's select values). */
516
+ export function wrunLineStyles() {
517
+ return [...WRUN_LINE_STYLES];
518
+ }
519
+ /** The binding a style knob renders by (undefined when malformed). */
520
+ export function wrunStyleBinding(param) {
521
+ return styleBinding(param);
522
+ }
523
+ /** Sheet keys the frozen contract reads as off when absent: an output's and
524
+ * a range's `smooth` ("absent, 0 or false keeps straight segments"). A
525
+ * boolean target may create one (false there changes nothing, and true is
526
+ * the only way a toggle turns it on); any other absent location stays as
527
+ * baked, since its absence may mean something a toggle's off does not (a
528
+ * default the adapter picks). */
529
+ const ABSENT_MEANS_OFF_KEYS = new Set(['smooth']);
530
+ /** A stats row's switch (scaffold 42): the location `["renderers", <name or index>, "visible"]`.
531
+ * The om schema admits a switch param there (`type: "boolean"`, or the legacy spelling: an
532
+ * untyped or int param from 0 to 1, whose 0 paints false and 1 true) and requires the sheet to
533
+ * hold the key, so the write never creates it. */
534
+ function isStatsRowSwitchTarget(path) {
535
+ return path.length === 3 && path[0] === 'renderers' && path[2] === 'visible';
536
+ }
537
+ /** The legacy spelling of a switch param: untyped or int, from 0 to 1. */
538
+ function isLegacySwitchParam(param) {
539
+ return (param.type === undefined || param.type === 'int') && param.min === 0 && param.max === 1;
540
+ }
541
+ /** A colour at a target: the pick verbatim, or its RGB at the target's
542
+ * alpha (REPLACE, the engine's opacity() rule). */
543
+ function colorAtTarget(color, alpha) {
544
+ if (alpha === undefined)
545
+ return color;
546
+ const rgba = parseWrunColor(color);
547
+ return rgba === undefined ? undefined : `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${alpha})`;
548
+ }
549
+ function targetAlpha(target) {
550
+ if (target.alpha === undefined)
551
+ return undefined;
552
+ return typeof target.alpha === 'number' && target.alpha >= 0 && target.alpha <= 1 ? target.alpha : null;
553
+ }
554
+ function validPath(path) {
555
+ return (Array.isArray(path) &&
556
+ path.length > 0 &&
557
+ path.every((segment) => typeof segment === 'string' || (typeof segment === 'number' && Number.isInteger(segment))));
558
+ }
559
+ function childKey(container, segment) {
560
+ if (Array.isArray(container)) {
561
+ if (typeof segment === 'number')
562
+ return segment >= 0 && segment < container.length ? segment : undefined;
563
+ const at = container.findIndex((entry) => isRecord(entry) && entry.name === segment);
564
+ return at === -1 ? undefined : at;
565
+ }
566
+ if (isRecord(container) && typeof segment === 'string')
567
+ return segment;
568
+ return undefined;
569
+ }
570
+ function readChild(container, key) {
571
+ return Array.isArray(container) ? container[key] : container[key];
572
+ }
573
+ function writeChild(container, key, value) {
574
+ if (Array.isArray(container))
575
+ container[key] = value;
576
+ else
577
+ container[key] = value;
578
+ }
579
+ /** The sheet sections whose `colors` lists may hold packed colours (WRUN-BATCHED-MARKS: the build packs a
580
+ * section's colours, the value a bound colour param writes there as it is). */
581
+ const PACKED_COLOR_SECTIONS = new Set(['marks', 'spans', 'rays']);
582
+ /** True for one slot of a batched section's `colors` list (`[section, entry, 'colors', slot]`): the only sheet
583
+ * location where a number IS a colour, so a colour write lands there packed. */
584
+ function isPackedColorSlot(path) {
585
+ return path.length === 4 && PACKED_COLOR_SECTIONS.has(path[0]) && path[2] === 'colors' && typeof path[3] === 'number';
586
+ }
587
+ /** Each painted copy's first original: the layout gate judges the declaration (WRUN-MARKS-CONTRACT F2). */
588
+ const paintedFrom = new WeakMap();
589
+ /** The declaration a painted container was copied from, or the container itself. */
590
+ export function wrunPaintedDeclarationOf(value) {
591
+ return paintedFrom.get(value) ?? value;
592
+ }
593
+ /** Apply one write into `root` (already a copy), copying each container on
594
+ * the path the first time it is touched. A location that does not resolve,
595
+ * or holds a value of another kind, is left as the package bakes it; a flag
596
+ * (a boolean param) is written in the kind its location holds, true / false
597
+ * into a boolean and 1 / 0 into a number; a colour likewise, a colour string
598
+ * into a string and the packed colour into a batched `colors` slot holding a
599
+ * number (isPackedColorSlot). */
600
+ function applyWrite(root, write, owned) {
601
+ let container = root;
602
+ for (let at = 0; at < write.path.length - 1; at += 1) {
603
+ const key = childKey(container, write.path[at]);
604
+ if (key === undefined)
605
+ return;
606
+ let next = readChild(container, key);
607
+ if (typeof next !== 'object' || next === null)
608
+ return;
609
+ if (!owned.has(next)) {
610
+ const declared = next;
611
+ next = Array.isArray(next) ? [...next] : { ...next };
612
+ owned.add(next);
613
+ paintedFrom.set(next, paintedFrom.get(declared) ?? declared);
614
+ writeChild(container, key, next);
615
+ }
616
+ container = next;
617
+ }
618
+ // A string on an object always names its key (present or not): `create`
619
+ // decides below whether an absent one is written.
620
+ const key = childKey(container, write.path[write.path.length - 1]);
621
+ if (key === undefined)
622
+ return;
623
+ if (write.kind === 'delete') {
624
+ if (isRecord(container))
625
+ delete container[key];
626
+ return;
627
+ }
628
+ const current = readChild(container, key);
629
+ if (write.kind === 'color') {
630
+ const color = colorAtTarget(write.color, write.alpha);
631
+ if (color === undefined)
632
+ return;
633
+ if (typeof current === 'string') {
634
+ writeChild(container, key, color);
635
+ return;
636
+ }
637
+ // A packed colour slot (a batched section's `colors`, packed by the build): the pick packed, its alpha
638
+ // the target's when the target names one (colorAtTarget). Any other number (a width, an opacity) is no
639
+ // colour and stays as baked; a pick that does not parse writes nothing.
640
+ if (typeof current === 'number' && Number.isFinite(current) && isPackedColorSlot(write.path)) {
641
+ const rgba = parseWrunColor(color);
642
+ if (rgba !== undefined)
643
+ writeChild(container, key, packWrunColor(rgba));
644
+ }
645
+ return;
646
+ }
647
+ if (write.kind === 'flag') {
648
+ if (typeof current === 'number')
649
+ writeChild(container, key, write.on ? 1 : 0);
650
+ else if (typeof current === 'boolean' || (current === undefined && write.create)) {
651
+ writeChild(container, key, write.on);
652
+ }
653
+ return;
654
+ }
655
+ if (!write.create && typeof current !== typeof write.value)
656
+ return;
657
+ writeChild(container, key, write.value);
658
+ }
659
+ /**
660
+ * What a number / int / select / boolean param with `style_targets` writes
661
+ * (frozen sheet contract, round 7): its current value (the flat setting when
662
+ * Number() reads it as finite, a select's through the one select read, else
663
+ * the declared default: the value init() receives), or `style_values[value]`
664
+ * for a select that declares them (a
665
+ * line-style select writes "dashed", never 1). A boolean reads as 1 or 0 here,
666
+ * the module's own form; at a target it is written in the kind the location
667
+ * holds (applyWrite). Undefined when neither fits.
668
+ */
669
+ export function wrunValueParamSetting(param, settings) {
670
+ if (param.type === 'color' || isWrunStyleParam(param))
671
+ return undefined;
672
+ if (param.type === 'boolean') {
673
+ const on = wrunBooleanParamOn(param, settings);
674
+ return on === undefined ? undefined : on ? 1 : 0;
675
+ }
676
+ const stored = flatSettings(settings)?.[param.name];
677
+ // A select reads through the one select read (a label or an index resolves,
678
+ // an index past the options is no value); the rest is Number() of the setting.
679
+ const own = param.type === 'select' && wrunParamChoices(param) !== undefined
680
+ ? (wrunSelectParamValue(param, stored) ?? Number.NaN)
681
+ : Number(stored);
682
+ const value = Number.isFinite(own) ? own : typeof param.default === 'number' ? param.default : undefined;
683
+ if (value === undefined)
684
+ return undefined;
685
+ const styleValues = param.type === 'select' && Array.isArray(param.style_values) ? param.style_values : undefined;
686
+ if (styleValues === undefined)
687
+ return value;
688
+ const styled = Number.isInteger(value) ? styleValues[value] : undefined;
689
+ if (typeof styled === 'string' && styled.trim() !== '')
690
+ return styled;
691
+ const fallback = typeof param.default === 'number' && Number.isInteger(param.default) ? styleValues[param.default] : undefined;
692
+ return typeof fallback === 'string' && fallback.trim() !== '' ? fallback : undefined;
693
+ }
694
+ /** A boolean param's state: the flat setting when it reads as on or off, else
695
+ * the declared default; undefined when neither does. */
696
+ function wrunBooleanParamOn(param, settings) {
697
+ const raw = flatSettings(settings)?.[param.name];
698
+ if (raw === true || raw === 1 || raw === '1' || raw === 'true')
699
+ return true;
700
+ if (raw === false || raw === 0 || raw === '0' || raw === 'false')
701
+ return false;
702
+ const fallback = param.default;
703
+ if (typeof fallback === 'boolean')
704
+ return fallback;
705
+ if (typeof fallback === 'number' && Number.isFinite(fallback))
706
+ return fallback !== 0;
707
+ return undefined;
708
+ }
709
+ /** A `style_targets` entry read in either frozen spelling: the FE's own
710
+ * `{ path, alpha? }` (a sheet location), or the kit's `{ output, property }`
711
+ * (plan 1.3: a string reference like `{ color: "@fast" }` on an output
712
+ * lands as the output's name and the property it binds), normalized to the
713
+ * location the property lives at. Anything else is dropped. */
714
+ function normalizeStyleTarget(target) {
715
+ // `alpha` rides through as declared: targetAlpha validates it (a malformed
716
+ // one drops the write, never paints the plain pick).
717
+ const alpha = {
718
+ ...(target.alpha === undefined ? {} : { alpha: target.alpha }),
719
+ ...(target.unset_at_default === true ? { unset_at_default: true } : {}),
720
+ };
721
+ if (validPath(target.path))
722
+ return { path: target.path, ...alpha };
723
+ if (typeof target.output !== 'string' || target.output === '')
724
+ return undefined;
725
+ const property = target.property;
726
+ const key = typeof property === 'string'
727
+ ? (STYLE_PROPERTY_KEYS[property] ??
728
+ (Object.values(STYLE_PROPERTY_KEYS).includes(property) ? property : undefined))
729
+ : undefined;
730
+ return key === undefined ? undefined : { path: ['outputs', target.output, key], ...alpha };
731
+ }
732
+ /**
733
+ * THE param-owned visibility reader: the boolean params that own a drawn
734
+ * target's visibility, each with the Style targets it owns in its
735
+ * `style_targets` order, over every section the visibility table lists
736
+ * (wrun-visibility-table.ts, the same targets the Style page offers): a
737
+ * `type: 'boolean'` param (no om `style`) with a target `{ path: [<section>,
738
+ * <name or index>, 'visible'] }` on a drawn entry whose declaration holds
739
+ * `visible` as a boolean (the ports harness requires the key, so the param's
740
+ * flag always lands, paramWrites; a stats row's switch is one). Such a param
741
+ * IS the target's Visible control: the Style page builds no Visible row for
742
+ * it and places the param in that row's slot (wrun-script-inputs.util
743
+ * stylePlacements), and the visibility apply reads the painted sheet's
744
+ * `visible` over any `__style__<target>__visible` setting saved under an
745
+ * earlier package version (wrunOutputVisibleState). The kit's `{ output,
746
+ * property }` spelling and a `paints` word never reach `visible`.
747
+ */
748
+ export function wrunVisibilityTargetOwners(metadata) {
749
+ const owners = new Map();
750
+ if (metadata === undefined)
751
+ return owners;
752
+ for (const param of Array.isArray(metadata.params) ? metadata.params : []) {
753
+ if (!isRecord(param) || param.type !== 'boolean' || isWrunStyleParam(param))
754
+ continue;
755
+ const owned = [];
756
+ for (const { path } of paramTargets(param).targets) {
757
+ if (path.length !== 3 || path[2] !== 'visible' || typeof path[0] !== 'string')
758
+ continue;
759
+ const target = wrunVisibilityTargetAt(metadata, path[0], path[1]);
760
+ if (target === undefined || typeof target.entry.visible !== 'boolean' || owned.includes(target.target))
761
+ continue;
762
+ owned.push(target.target);
763
+ }
764
+ if (owned.length > 0)
765
+ owners.set(param.name, owned);
766
+ }
767
+ return owners;
768
+ }
769
+ /** The outputs' half of the param-owned visibility (wrunVisibilityTargetOwners): each boolean
770
+ * param with the drawn OUTPUTS it owns, by name (an output's target is its name). */
771
+ export function wrunVisibilityOwners(metadata) {
772
+ const owners = new Map();
773
+ if (metadata === undefined)
774
+ return owners;
775
+ const outputs = new Set((Array.isArray(metadata.outputs) ? metadata.outputs : []).flatMap((output) => isRecord(output) && typeof output.name === 'string' ? [output.name] : []));
776
+ for (const [param, targets] of wrunVisibilityTargetOwners(metadata)) {
777
+ const owned = targets.filter((target) => outputs.has(target) && !target.includes(':'));
778
+ if (owned.length > 0)
779
+ owners.set(param, owned);
780
+ }
781
+ return owners;
782
+ }
783
+ /** The output entries whose whole `key` a param writes, by the locations the
784
+ * seam writes it to (paramWrites: its targets, paramTargets, else an om
785
+ * style knob's own binding), `["outputs", <name or index>, key]`, each once,
786
+ * in target order. */
787
+ export function wrunParamOutputTargets(param, outputs, key) {
788
+ const entries = Array.isArray(outputs) ? outputs : [];
789
+ const written = [];
790
+ const { targets, declared } = paramTargets(param);
791
+ const binding = styleBinding(param);
792
+ const paths = !declared && binding !== undefined
793
+ ? [{ path: ['outputs', binding.output, STYLE_PROPERTY_KEYS[binding.property]] }]
794
+ : targets;
795
+ for (const { path } of paths) {
796
+ if (path.length !== 3 || path[0] !== 'outputs' || path[2] !== key)
797
+ continue;
798
+ const at = childKey(entries, path[1]);
799
+ const output = at === undefined ? undefined : entries[at];
800
+ if (!isRecord(output) || typeof output.name !== 'string')
801
+ continue;
802
+ if (!written.some((entry) => entry.name === output.name))
803
+ written.push(output);
804
+ }
805
+ return written;
806
+ }
807
+ /** Every Style target whose visibility a boolean param owns (wrunVisibilityTargetOwners): an
808
+ * output by its name, any other drawn kind by its prefixed target. Such a target shows by the
809
+ * painted sheet alone and offers no Visible row. */
810
+ export function wrunVisibilityOwnedOutputs(metadata) {
811
+ return new Set([...wrunVisibilityTargetOwners(metadata).values()].flat());
812
+ }
813
+ /** The sheet locations a param paints: its `style_targets` (either
814
+ * spelling), else its `paints` word (`"<output>"` = the colour,
815
+ * `"<output>.width" | ".line_style" | ".opacity"`), else none. `declared`
816
+ * tells a style knob apart from one that declared no target at all. */
817
+ function paramTargets(param) {
818
+ const raw = param.style_targets;
819
+ if (Array.isArray(raw)) {
820
+ return {
821
+ targets: raw.filter(isRecord).flatMap((target) => {
822
+ const normalized = normalizeStyleTarget(target);
823
+ return normalized === undefined ? [] : [normalized];
824
+ }),
825
+ declared: true,
826
+ };
827
+ }
828
+ const paints = param.paints;
829
+ if (typeof paints === 'string' && paints !== '') {
830
+ const dot = paints.indexOf('.');
831
+ const output = dot === -1 ? paints : paints.slice(0, dot);
832
+ const property = dot === -1 ? 'color' : paints.slice(dot + 1);
833
+ if (output !== '' && Object.values(STYLE_PROPERTY_KEYS).includes(property)) {
834
+ return { targets: [{ path: ['outputs', output, property] }], declared: true };
835
+ }
836
+ }
837
+ return { targets: [], declared: false };
838
+ }
839
+ /** A select without `style_values` that paints a `line_style` location: its
840
+ * option label at the value, when that label is a line style (the kit's
841
+ * `param.choice` bound by `{ line_style: "@style" }` labels its options
842
+ * with the style words). */
843
+ function lineStyleLabel(param, value) {
844
+ if (param.type !== 'select' || typeof value !== 'number' || !Number.isInteger(value))
845
+ return undefined;
846
+ const labels = Array.isArray(param.option_labels) ? param.option_labels : [];
847
+ const at = Array.isArray(param.options) ? param.options.indexOf(value) : value;
848
+ const label = labels[at];
849
+ return typeof label === 'string' && WRUN_LINE_STYLES.includes(label) ? label : undefined;
850
+ }
851
+ /** The writes one param makes: a colour param to each of its targets, a
852
+ * number / int / select param its value (or style value) to each of its
853
+ * targets, a boolean param its state to each of its targets (in the kind the
854
+ * location holds; an absent `smooth` is created), a style knob to its
855
+ * targets or, without any, to its bound output's property. A target whose
856
+ * location holds another kind of value is left as the package bakes it. */
857
+ function paramWrites(param, settings, members) {
858
+ const { targets: explicit, declared } = paramTargets(param);
859
+ if (isWrunColorParam(param)) {
860
+ const color = wrunColorParamSetting(param, settings, members);
861
+ // A target marked unset_at_default yields while the pick is the declared
862
+ // default colour (compared as the packed colour init() receives, so any
863
+ // spelling of it counts): its key leaves the sheet and the surface's own
864
+ // colour shows, the Bar Statistics template's elision of a colour left
865
+ // at its input's default.
866
+ const atDefault = wrunColorParamPacked(param, settings, members) === param.default;
867
+ return explicit.flatMap((target) => {
868
+ if (target.unset_at_default === true && atDefault)
869
+ return [{ path: target.path, kind: 'delete' }];
870
+ const alpha = targetAlpha(target);
871
+ return alpha === null ? [] : [{ path: target.path, kind: 'color', color, alpha, create: false }];
872
+ });
873
+ }
874
+ const binding = styleBinding(param);
875
+ if (binding === undefined && param.type === 'boolean') {
876
+ const on = wrunBooleanParamOn(param, settings);
877
+ if (on === undefined)
878
+ return [];
879
+ return explicit.map((target) => ({
880
+ path: target.path,
881
+ kind: 'flag',
882
+ on,
883
+ create: ABSENT_MEANS_OFF_KEYS.has(target.path[target.path.length - 1]),
884
+ }));
885
+ }
886
+ if (binding === undefined) {
887
+ const value = wrunValueParamSetting(param, settings);
888
+ if (value === undefined)
889
+ return [];
890
+ return explicit.map((target) => {
891
+ // A legacy switch param paints a stats row's switch as a flag (0 false, 1 true), the way a
892
+ // boolean param does above: the location holds a boolean, never the param's number.
893
+ if (isStatsRowSwitchTarget(target.path) && isLegacySwitchParam(param) && typeof value === 'number') {
894
+ return { path: target.path, kind: 'flag', on: value !== 0, create: false };
895
+ }
896
+ const last = target.path[target.path.length - 1];
897
+ const styled = last === 'line_style' ? lineStyleLabel(param, value) : undefined;
898
+ return { path: target.path, kind: 'value', value: styled ?? value, create: false };
899
+ });
900
+ }
901
+ const value = wrunStyleParamValue(param, settings);
902
+ if (value === undefined)
903
+ return [];
904
+ const implicit = !declared;
905
+ const paths = implicit
906
+ ? [{ path: ['outputs', binding.output, STYLE_PROPERTY_KEYS[binding.property]] }]
907
+ : explicit;
908
+ return paths.flatMap((target) => {
909
+ if (binding.property === 'color') {
910
+ const alpha = targetAlpha(target);
911
+ if (alpha === null || typeof value !== 'string')
912
+ return [];
913
+ // The implicit binding target sets the output's colour even when the
914
+ // sheet leaves it to the adapter's default.
915
+ return implicit
916
+ ? [{ path: target.path, kind: 'value', value: colorAtTarget(value, alpha) ?? value, create: true }]
917
+ : [{ path: target.path, kind: 'color', color: value, alpha, create: false }];
918
+ }
919
+ return [{ path: target.path, kind: 'value', value, create: implicit }];
920
+ });
921
+ }
922
+ /** A finite whole number read off a setting (a number, or a select's
923
+ * numeric string), else undefined. */
924
+ function settingIndex(raw) {
925
+ if (typeof raw !== 'number' && (typeof raw !== 'string' || raw.trim() === ''))
926
+ return undefined;
927
+ const value = Number(raw);
928
+ return Number.isInteger(value) ? value : undefined;
929
+ }
930
+ /** `EXCHANGE:SYMBOL` split at the first colon (an exchange-less text keeps
931
+ * the sheet's exchange pin); empty parts are absent. */
932
+ function splitMarketText(text) {
933
+ const at = text.indexOf(':');
934
+ const exchange = at === -1 ? '' : text.slice(0, at).trim();
935
+ const symbol = (at === -1 ? text : text.slice(at + 1)).trim();
936
+ return { ...(exchange !== '' ? { exchange } : {}), ...(symbol !== '' ? { symbol } : {}) };
937
+ }
938
+ /** A host-applied select's setting as its index into the frozen list: the
939
+ * one select read over the param's choice set (an option value, a label, an
940
+ * index; an index past the options is no pick), else the declared default's
941
+ * index. A param without a choice set reads the bare number, as before the
942
+ * typed key. The dialog resolves the same setting the same way, so the pins
943
+ * bind what the dialog shows. */
944
+ function hostParamIndex(param, raw) {
945
+ const picked = wrunParamChoices(param) === undefined ? settingIndex(raw) : wrunSelectParamValue(param, raw);
946
+ return picked ?? settingIndex(param.default);
947
+ }
948
+ /**
949
+ * A host-applied param's CURRENT setting resolved (plan 1.1, 1.7): a source
950
+ * param's field word and a timeframe param's interval word at the setting's
951
+ * index (a label resolves to it; an index past the options, or no setting,
952
+ * reads the declared default's), a symbol param's `EXCHANGE:SYMBOL` text
953
+ * split into its pins. Undefined for a param that is not host-applied, an
954
+ * index outside the frozen list, or a symbol setting that is empty / 0 (the
955
+ * sheet's own pins stand).
956
+ */
957
+ export function wrunHostParamSetting(param, settings) {
958
+ const raw = flatSettings(settings)?.[param.name];
959
+ switch (param.host) {
960
+ case 'source': {
961
+ const index = hostParamIndex(param, raw);
962
+ const field = index === undefined ? undefined : WRUN_SOURCE_FIELDS[index];
963
+ return index !== undefined && field !== undefined ? { host: 'source', index, field } : undefined;
964
+ }
965
+ case 'interval': {
966
+ const index = hostParamIndex(param, raw);
967
+ const word = index === undefined ? undefined : WRUN_TIMEFRAME_WORDS[index];
968
+ return index !== undefined && word !== undefined ? { host: 'interval', index, word } : undefined;
969
+ }
970
+ case 'symbol': {
971
+ const text = typeof raw === 'string' ? raw.trim() : '';
972
+ if (text === '' || text === '0')
973
+ return undefined;
974
+ return { host: 'symbol', text, ...splitMarketText(text) };
975
+ }
976
+ default:
977
+ return undefined;
978
+ }
979
+ }
980
+ /** True when a host-applied param's setting is its declared default (absent,
981
+ * the default index, or for a symbol: empty, 0, or the declared
982
+ * `symbol_default` market). The browser and the cloud both compute on a
983
+ * moved pick (the hosted map rides a timeframe pick as its index and a
984
+ * symbol pick as its `EXCHANGE:SYMBOL` text, lane parity contract C1); the
985
+ * alerts host still computes on the sheet's own pins, so the alert arm
986
+ * refuses a non-default pick on this. */
987
+ export function wrunHostParamAtDefault(param, settings) {
988
+ const resolved = wrunHostParamSetting(param, settings);
989
+ if (resolved === undefined)
990
+ return true;
991
+ if (resolved.host === 'symbol') {
992
+ const declared = typeof param.symbol_default === 'string' ? param.symbol_default.trim().toUpperCase() : '';
993
+ return declared !== '' && resolved.text.toUpperCase() === declared;
994
+ }
995
+ return resolved.index === (settingIndex(param.default) ?? 0);
996
+ }
997
+ /** The inputs bound to a host-applied param (plan 1.9 delta a: one param may
998
+ * bind several inputs; the input references the param, never the reverse). */
999
+ function boundInputNames(metadata, param) {
1000
+ const sources = isRecord(metadata.inputSources) ? metadata.inputSources : {};
1001
+ const key = param.host === 'source'
1002
+ ? 'field_param'
1003
+ : param.host === 'interval'
1004
+ ? 'interval_param'
1005
+ : param.host === 'symbol'
1006
+ ? 'symbol_param'
1007
+ : undefined;
1008
+ if (key === undefined)
1009
+ return [];
1010
+ return Object.entries(sources)
1011
+ .filter(([, source]) => isRecord(source) && source[key] === param.name)
1012
+ .map(([name]) => name);
1013
+ }
1014
+ /** The pin writes of every host-applied param whose setting left its
1015
+ * declared default (the default pins are baked into the sheet). */
1016
+ function hostWrites(metadata, param, settings) {
1017
+ if (param.host === undefined || wrunHostParamAtDefault(param, settings))
1018
+ return [];
1019
+ const resolved = wrunHostParamSetting(param, settings);
1020
+ if (resolved === undefined)
1021
+ return [];
1022
+ return boundInputNames(metadata, param).flatMap((name) => {
1023
+ const at = (key) => ['inputSources', name, key];
1024
+ switch (resolved.host) {
1025
+ case 'source':
1026
+ return [{ path: at('field'), kind: 'value', value: resolved.field, create: true }];
1027
+ case 'interval':
1028
+ return resolved.index === 0
1029
+ ? [{ path: at('interval'), kind: 'delete' }]
1030
+ : [{ path: at('interval'), kind: 'value', value: resolved.word, create: true }];
1031
+ case 'symbol':
1032
+ return [
1033
+ ...(resolved.exchange !== undefined
1034
+ ? [{ path: at('exchange'), kind: 'value', value: resolved.exchange, create: true }]
1035
+ : []),
1036
+ ...(resolved.symbol !== undefined
1037
+ ? [{ path: at('symbol'), kind: 'value', value: resolved.symbol, create: true }]
1038
+ : []),
1039
+ ];
1040
+ default:
1041
+ return [];
1042
+ }
1043
+ });
1044
+ }
1045
+ /** The param a volume-profile input's bucket size is bound to (C1.3), in
1046
+ * either sheet spelling: `ticks_per_bar_param` beside a numeric default, or
1047
+ * the in-source reference verbatim, `ticks_per_bar: "@<param>"`. */
1048
+ function ticksPerBarParamName(source) {
1049
+ if (typeof source.ticks_per_bar_param === 'string')
1050
+ return source.ticks_per_bar_param;
1051
+ const reference = source.ticks_per_bar;
1052
+ return typeof reference === 'string' && reference.startsWith('@') && reference.length > 1
1053
+ ? reference.slice(1)
1054
+ : undefined;
1055
+ }
1056
+ /** The volume-profile bucket-size bindings (C1.3): every input bound to a
1057
+ * declared param takes the param's current value (`wrunValueParamSetting`:
1058
+ * the setting, else the declared default) as its `ticks_per_bar`. A value
1059
+ * equal to the baked one writes nothing; an unknown param or a value that is
1060
+ * not a finite number writes nothing either, so a verbatim reference that
1061
+ * resolves to nothing reaches the lane util, which refuses it by name. */
1062
+ function ticksPerBarWrites(metadata, settings) {
1063
+ const sources = isRecord(metadata.inputSources) ? metadata.inputSources : {};
1064
+ const params = Array.isArray(metadata.params) ? metadata.params : [];
1065
+ const writes = [];
1066
+ for (const [name, source] of Object.entries(sources)) {
1067
+ if (!isRecord(source))
1068
+ continue;
1069
+ const bound = ticksPerBarParamName(source);
1070
+ const param = bound === undefined ? undefined : params.find((candidate) => candidate.name === bound);
1071
+ const value = param === undefined ? undefined : wrunValueParamSetting(param, settings);
1072
+ if (typeof value !== 'number' || !Number.isFinite(value) || value === source.ticks_per_bar)
1073
+ continue;
1074
+ writes.push({ path: ['inputSources', name, 'ticks_per_bar'], kind: 'value', value, create: true });
1075
+ }
1076
+ return writes;
1077
+ }
1078
+ /** The lane words a setting rides (kit 0.77.0), off the param's run value (the init() number):
1079
+ * `currency_param` writes the picked label ("USD" or "Coin") into `currency`; a `when` gate that
1080
+ * is off marks the input `undemanded`. The browser's one authority: its plan reads neither. */
1081
+ function laneWordWrites(metadata, settings) {
1082
+ const sources = isRecord(metadata.inputSources) ? metadata.inputSources : {};
1083
+ const params = Array.isArray(metadata.params) ? metadata.params : [];
1084
+ const runValue = (name) => {
1085
+ const param = typeof name === 'string' ? params.find((candidate) => candidate.name === name) : undefined;
1086
+ return param === undefined
1087
+ ? undefined
1088
+ : { param, value: wrunParamValuesFromSettings({ params: [param] }, settings)[param.name] };
1089
+ };
1090
+ const writes = [];
1091
+ for (const [name, source] of Object.entries(sources)) {
1092
+ if (!isRecord(source))
1093
+ continue;
1094
+ const unit = runValue(source.currency_param);
1095
+ if (unit !== undefined) {
1096
+ const label = wrunParamChoices(unit.param)?.find((choice) => choice.value === unit.value)?.label;
1097
+ if ((label === 'USD' || label === 'Coin') && label !== source.currency) {
1098
+ writes.push({ path: ['inputSources', name, 'currency'], kind: 'value', value: label, create: true });
1099
+ }
1100
+ }
1101
+ const gate = runValue(source.when);
1102
+ if (gate !== undefined && source.undemanded !== true && !wrunInputGateOn(source, gate.value)) {
1103
+ writes.push({ path: ['inputSources', name, 'undemanded'], kind: 'flag', on: true, create: true });
1104
+ }
1105
+ }
1106
+ return writes;
1107
+ }
1108
+ // ---------------------------------------------------------------------------
1109
+ // Style page rows -> output properties.
1110
+ // ---------------------------------------------------------------------------
1111
+ /** A Style row's value as the output key it writes, or undefined when the
1112
+ * value does not fit the property (left as the package bakes it). */
1113
+ function styleRowValue(property, raw) {
1114
+ switch (property) {
1115
+ case 'width': {
1116
+ const value = typeof raw === 'number' || typeof raw === 'string' ? Number(raw) : Number.NaN;
1117
+ return raw !== '' && Number.isFinite(value) && value >= 0 ? { key: 'width', value } : undefined;
1118
+ }
1119
+ case 'opacity': {
1120
+ const value = typeof raw === 'number' || typeof raw === 'string' ? Number(raw) : Number.NaN;
1121
+ return raw !== '' && Number.isFinite(value) && value >= 0 && value <= 1 ? { key: 'opacity', value } : undefined;
1122
+ }
1123
+ case 'lineStyle':
1124
+ return typeof raw === 'string' && WRUN_LINE_STYLES.includes(raw)
1125
+ ? { key: 'line_style', value: raw }
1126
+ : undefined;
1127
+ case 'color': {
1128
+ const value = wrunColorSettingString(raw);
1129
+ return value === undefined ? undefined : { key: 'color', value };
1130
+ }
1131
+ default:
1132
+ // `visible` is applied after integration (applyWrunOutputVisibility), never a sheet write.
1133
+ return undefined;
1134
+ }
1135
+ }
1136
+ /** A `colors` row's swatches (C1) in the declaration's own order ([up, down]
1137
+ * for a sign pair, rung order for a `color_by` palette, low to high for a
1138
+ * palette), from a list or an { up, down } pair; a swatch that is no colour
1139
+ * is undefined (its declared colour stays). */
1140
+ function colorsRowValue(raw) {
1141
+ const swatches = Array.isArray(raw) ? raw : isRecord(raw) ? [raw.up, raw.down] : [];
1142
+ return swatches.map((swatch) => wrunColorSettingString(swatch));
1143
+ }
1144
+ /** Each swatch onto the colour list at `path`, entry by entry: a list the
1145
+ * declaration holds is recoloured in place, never grown, never created. */
1146
+ function colorListWrites(path, raw) {
1147
+ return colorsRowValue(raw).flatMap((color, at) => color === undefined ? [] : [{ path: [...path, at], kind: 'value', value: color, create: false }]);
1148
+ }
1149
+ /** Each swatch onto its own colour key (a footprint's or volume profile's
1150
+ * buy / sell pair), created when the declaration left it to the default. */
1151
+ function colorKeyWrites(base, keys, raw) {
1152
+ const swatches = colorsRowValue(raw);
1153
+ return keys.flatMap((key, at) => {
1154
+ const color = swatches[at];
1155
+ return color === undefined ? [] : [{ path: [...base, key], kind: 'value', value: color, create: true }];
1156
+ });
1157
+ }
1158
+ /** The largest and smallest fill opacity a batched marks section takes, in percent (`opacity_pct`, the
1159
+ * Opacity param's own range): a Style row's 0..1 opacity is written there rounded and clamped. */
1160
+ const WRUN_MARKS_OPACITY_PCT_MIN = 10;
1161
+ const WRUN_MARKS_OPACITY_PCT_MAX = 80;
1162
+ /** A ray's stroke width bounds in css px. */
1163
+ const WRUN_RAYS_WIDTH_MIN = 0.5;
1164
+ const WRUN_RAYS_WIDTH_MAX = 8;
1165
+ /**
1166
+ * The sheet writes of a batched section's Style row (WRUN-BATCHED-MARKS), past `visible`: `colors` swatch
1167
+ * by swatch onto the declared list (recoloured in place, never grown or created; each in the kind its
1168
+ * location holds, a colour word or a packed number, applyWrite); `opacity` onto a mark's `opacity_pct`
1169
+ * (percent, rounded, 10..80) or a span's or ray's `opacity` (0..1); a ray's `width` (0.5..8 css px) and
1170
+ * `lineStyle` (its `line_style`). Look, size, caption and position keys take no Style row: a param binds
1171
+ * them through `style_targets`.
1172
+ */
1173
+ function batchedStyleTargetWrites(kind, base, property, raw) {
1174
+ if (property === 'colors') {
1175
+ return colorsRowValue(raw).flatMap((color, at) => color === undefined ? [] : [{ path: [...base, 'colors', at], kind: 'color', color, create: false }]);
1176
+ }
1177
+ if (property === 'opacity') {
1178
+ const write = styleRowValue('opacity', raw);
1179
+ if (write === undefined)
1180
+ return [];
1181
+ const opacity = Number(write.value);
1182
+ if (kind !== 'marks')
1183
+ return [{ path: [...base, 'opacity'], kind: 'value', value: opacity, create: true }];
1184
+ const percent = Math.min(WRUN_MARKS_OPACITY_PCT_MAX, Math.max(WRUN_MARKS_OPACITY_PCT_MIN, Math.round(opacity * 100)));
1185
+ return [{ path: [...base, 'opacity_pct'], kind: 'value', value: percent, create: true }];
1186
+ }
1187
+ if (kind !== 'rays')
1188
+ return [];
1189
+ if (property === 'width') {
1190
+ const write = styleRowValue('width', raw);
1191
+ if (write === undefined)
1192
+ return [];
1193
+ const width = Math.min(WRUN_RAYS_WIDTH_MAX, Math.max(WRUN_RAYS_WIDTH_MIN, Number(write.value)));
1194
+ return [{ path: [...base, 'width'], kind: 'value', value: width, create: true }];
1195
+ }
1196
+ if (property === 'lineStyle') {
1197
+ const write = styleRowValue('lineStyle', raw);
1198
+ return write === undefined
1199
+ ? []
1200
+ : [{ path: [...base, 'line_style'], kind: 'value', value: write.value, create: true }];
1201
+ }
1202
+ return [];
1203
+ }
1204
+ /**
1205
+ * The sheet writes of one Style row (C1 frozen key `__style__<target>__<property>`):
1206
+ * - `visible` on any target: a write only where the visibility table's group
1207
+ * is `skip` (wrun-visibility-table.ts: every renderer kind, a price canvas, a
1208
+ * docked level, a matrix, a panel, a batched section, the mini-chart grid,
1209
+ * an inset output): false paints the declaration's `visible: false` the
1210
+ * mount reads (isWrunStyleTargetHidden: it mounts nothing), true deletes the
1211
+ * key (shown, the absence every reader takes as on). A `nested` target (an output,
1212
+ * a band, a box) is hidden in place after integration
1213
+ * (applyWrunOutputVisibility) and a `drawing` target (a sheet drawing, a
1214
+ * segment, a handle kind) at the drawing door, both read from the settings:
1215
+ * no sheet write;
1216
+ * - an output target: width, line_style, color or opacity (created when the
1217
+ * sheet left the key to the adapter's default), `colors` recolouring the
1218
+ * declared `colors` list (a two-tone histogram's sign pair or `color_by`
1219
+ * palette);
1220
+ * - `text:<name>`: `color` on the renderer;
1221
+ * - `heatmap:<name>`: `colors` recolouring its `palette`;
1222
+ * - `profile:<name>`: `colors` as a footprint's or volume profile's buy /
1223
+ * sell pair, a TPO's `palette`;
1224
+ * - `levels:<name>`: `color` on the level;
1225
+ * - `marks:<name>`, `spans:<name>`, `rays:<name>` (WRUN-BATCHED-MARKS):
1226
+ * `colors`, `opacity`, and a ray's `width` and `lineStyle`
1227
+ * (batchedStyleTargetWrites).
1228
+ * A target the sheet does not draw, a prefix the table does not list, a
1229
+ * property its target does not paint, or a value that does not fit it,
1230
+ * writes nothing.
1231
+ */
1232
+ function wrunStyleTargetWrites(metadata, target, property, raw) {
1233
+ const { kind, name } = parseWrunStyleTarget(target);
1234
+ if (kind === 'unknown')
1235
+ return [];
1236
+ if (property === 'visible') {
1237
+ const found = findWrunVisibilityTarget(metadata, target);
1238
+ if (found?.group !== 'skip' || typeof raw !== 'boolean')
1239
+ return [];
1240
+ const path = [found.section, found.at, 'visible'];
1241
+ // Shown is the key's absence: true deletes it (a declaration the author left hidden shows too), so only
1242
+ // a hidden declaration carries the FE-only flag, and the selection drops that one before any strict
1243
+ // reader (a panel frame refuses every key outside its grammar) can see it (wrunSelectionSheet).
1244
+ return raw ? [{ path, kind: 'delete' }] : [{ path, kind: 'flag', on: false, create: true }];
1245
+ }
1246
+ if (kind === 'output') {
1247
+ if (property === 'colors')
1248
+ return colorListWrites(['outputs', name, 'colors'], raw);
1249
+ const write = styleRowValue(property, raw);
1250
+ return write === undefined
1251
+ ? []
1252
+ : [{ path: ['outputs', name, write.key], kind: 'value', value: write.value, create: true }];
1253
+ }
1254
+ const section = wrunVisibilitySectionOfPrefix(kind);
1255
+ if (section === undefined)
1256
+ return [];
1257
+ const base = [section, name];
1258
+ if (kind === 'marks' || kind === 'spans' || kind === 'rays') {
1259
+ return batchedStyleTargetWrites(kind, base, property, raw);
1260
+ }
1261
+ if (property === 'color' && (kind === 'text' || kind === 'levels')) {
1262
+ const color = wrunColorSettingString(raw);
1263
+ return color === undefined ? [] : [{ path: [...base, 'color'], kind: 'value', value: color, create: true }];
1264
+ }
1265
+ if (property !== 'colors')
1266
+ return [];
1267
+ if (kind === 'heatmap')
1268
+ return colorListWrites([...base, 'palette'], raw);
1269
+ if (kind !== 'profile')
1270
+ return [];
1271
+ const profile = (metadata.profiles ?? []).find((entry) => isRecord(entry) && entry.name === name);
1272
+ if (profile?.kind === 'tpo')
1273
+ return colorListWrites([...base, 'palette'], raw);
1274
+ return profile?.kind === 'footprint' || profile?.kind === 'volume'
1275
+ ? colorKeyWrites(base, ['buy_color', 'sell_color'], raw)
1276
+ : [];
1277
+ }
1278
+ /** The sheet writes of every Style page row in the flat settings. */
1279
+ function styleRowWrites(metadata, settings) {
1280
+ const flat = flatSettings(settings);
1281
+ if (flat === undefined)
1282
+ return [];
1283
+ const writes = [];
1284
+ for (const [key, raw] of Object.entries(flat)) {
1285
+ const row = parseWrunStyleRowKey(key);
1286
+ if (row !== undefined)
1287
+ writes.push(...wrunStyleTargetWrites(metadata, row.output, row.property, raw));
1288
+ }
1289
+ return writes;
1290
+ }
1291
+ /**
1292
+ * The sheet as the overlay's current settings paint it: every colour param's
1293
+ * pick (else its default) written to its `style_targets`, every number / int
1294
+ * / select param's value (a select's `style_values` entry when it declares
1295
+ * them) to its targets, every om style knob's value to its targets (else its
1296
+ * bound output's property), every host-applied param's pick to the pins of
1297
+ * the inputs bound to it, every Style page row to its target's property (an
1298
+ * output's, or a text renderer's, heatmap's, profile's or level's: C1,
1299
+ * wrunStyleTargetWrites; after the params, so an explicit Style edit wins
1300
+ * over a code binding).
1301
+ * THE seam the full run applies before anything reads the sheet (the run
1302
+ * request's handle defaults, the run result, the live context the ticks and
1303
+ * reseeds reuse). A copy: containers on a written path are copied,
1304
+ * everything else is shared; a sheet with nothing to write is returned as is.
1305
+ */
1306
+ export function wrunSheetWithSettings(metadata, settings) {
1307
+ const params = Array.isArray(metadata.params) ? metadata.params : [];
1308
+ const members = wrunColorArrayMembers(params);
1309
+ const writes = [
1310
+ ...params.flatMap((param) => paramWrites(param, settings, members)),
1311
+ ...params.flatMap((param) => hostWrites(metadata, param, settings)),
1312
+ ...ticksPerBarWrites(metadata, settings),
1313
+ ...laneWordWrites(metadata, settings),
1314
+ ...styleRowWrites(metadata, settings),
1315
+ ];
1316
+ const root = { ...metadata };
1317
+ const owned = new WeakSet([root]);
1318
+ for (const write of writes)
1319
+ applyWrite(root, write, owned);
1320
+ // Decided over the painted sheet, after every write (a Style row and a
1321
+ // bound colour param alike): see levelColorPickedWrites.
1322
+ const pickedWrites = levelColorPickedWrites(metadata, root);
1323
+ if (writes.length === 0 && pickedWrites.length === 0)
1324
+ return metadata;
1325
+ for (const write of pickedWrites)
1326
+ applyWrite(root, write, owned);
1327
+ return root;
1328
+ }
1329
+ /**
1330
+ * The overlay palette (the collapsed-legend chip) of a sheet with colour
1331
+ * rows: every colour row's CURRENT colour in row
1332
+ * order, a colour-array row flattened over its declared length. The kScript
1333
+ * control's own rule (its extractColorArray flattens the colour inputs in
1334
+ * declaration order). Rows are settings declarations
1335
+ * (buildWrunScriptInputs) or the dialog's options built from them; a row
1336
+ * with no usable setting reads its default.
1337
+ */
1338
+ export function wrunColorPalette(rows, settings) {
1339
+ const flat = flatSettings(settings);
1340
+ const palette = [];
1341
+ for (const row of rows) {
1342
+ if (typeof row.name !== 'string')
1343
+ continue;
1344
+ const raw = flat?.[row.name];
1345
+ if (row.type === 'color') {
1346
+ const fallback = wrunColorSettingString(row.defaultValue);
1347
+ const color = wrunColorSettingString(raw) ?? fallback;
1348
+ if (color !== undefined)
1349
+ palette.push(color);
1350
+ }
1351
+ else if (row.type === 'color[]' && Array.isArray(row.defaultValue)) {
1352
+ row.defaultValue.forEach((fallback, at) => {
1353
+ const color = wrunColorSettingString(Array.isArray(raw) ? raw[at] : undefined) ?? wrunColorSettingString(fallback);
1354
+ if (color !== undefined)
1355
+ palette.push(color);
1356
+ });
1357
+ }
1358
+ }
1359
+ return palette;
1360
+ }
1361
+ // The chart store's door (wrun-color-settings.lazy.ts): bound as this module evaluates, so the CME
1362
+ // wall reads an overlay's effective sheet in its own turn wherever a sheet was remembered.
1363
+ bindWrunColorSettings({ wrunSheetWithSettings });