@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,938 @@
1
+ import { WRUN_BATCHED_MARKS_CELL_BUDGET } from '../chart/overlay-output-budget.util.js';
2
+ import { wrunLegendName } from '../chart/wrun-legend-name.util.js';
3
+ import { scheduleWrunCellsCapNotice } from './wrun-cap-notice.util.js';
4
+ import { forgetWrunCanvasReadout, rememberWrunCanvasReadout } from './wrun-canvas-readout.util.js';
5
+ import { wrunCanvasMergeLive } from './wrun-canvases.util.js';
6
+ import { decodeWrunPackedColor, isWrunStyleTargetHidden, wrunPaintedDeclarationOf } from './wrun-color-settings.util.js';
7
+ import { WRUN_HEATMAP_TRIM_WATERMARK, wrunHeatmapCellShares, wrunHeatmapTrimTarget, } from './wrun-heatmap-cell-budget.util.js';
8
+ import { resolveWrunColorWord, wrunThemeTokenOfPacked, wrunThemeTokenWord, } from './wrun-style-words.util.js';
9
+ import { decodeWrunMarkMeta, decodeWrunSpanMeta, wrunBatchedReadoutText } from './wrun-batched-readout.util.js';
10
+ export { decodeWrunMarkMeta, decodeWrunSpanMeta, formatWrunBatchedNumber, wrunBatchedReadoutText, WRUN_MARK_META_MAX_OFFSET_MS, } from './wrun-batched-readout.util.js';
11
+ // ── The vocabulary ──────────────────────────────────────────────────────────
12
+ /** The three kinds, in mount order: each a sheet key, a child id kind and the engine plot type. */
13
+ export const WRUN_BATCHED_MARKS_KINDS = Object.freeze(['marks', 'spans', 'rays']);
14
+ /** The fields of one record, per kind: marks `[price, qty, meta]`, spans `[top, bottom, length,
15
+ * meta]`, rays `[y1, y2, length, meta]`. */
16
+ export const WRUN_BATCHED_STRIDE = Object.freeze({
17
+ marks: 3,
18
+ spans: 4,
19
+ rays: 4,
20
+ });
21
+ /** One slot's fields in output order, per kind (the kit's WRUN_BATCHED_FIELDS). */
22
+ export const WRUN_BATCHED_FIELDS = Object.freeze({
23
+ marks: Object.freeze(['price', 'qty', 'meta']),
24
+ spans: Object.freeze(['top', 'bottom', 'length', 'meta']),
25
+ rays: Object.freeze(['y1', 'y2', 'length', 'meta']),
26
+ });
27
+ /** The kinds that also take the timed layout (the kit's WRUN_BATCHED_TIMED_KINDS). */
28
+ export const WRUN_BATCHED_TIMED_KINDS = Object.freeze(['spans', 'rays']);
29
+ /** The stride of a timed section: the sheet says `stride: 5` (the kit's WRUN_BATCHED_TIMED_STRIDE). */
30
+ export const WRUN_BATCHED_TIMED_STRIDE = 5;
31
+ /** A timed slot's fields in output order (the kit's WRUN_BATCHED_TIMED_FIELDS): start and end are
32
+ * epoch seconds in the outputs and milliseconds in the child rows (the row copy converts them). */
33
+ export const WRUN_BATCHED_TIMED_FIELDS = Object.freeze({
34
+ spans: Object.freeze(['top', 'bottom', 'start', 'end', 'meta']),
35
+ rays: Object.freeze(['y1', 'y2', 'start', 'end', 'meta']),
36
+ });
37
+ /** Where a timed slot holds its start and end (the same two places on spans and rays). */
38
+ const TIMED_START = WRUN_BATCHED_TIMED_FIELDS.spans.indexOf('start');
39
+ const TIMED_END = WRUN_BATCHED_TIMED_FIELDS.spans.indexOf('end');
40
+ /** Whether a section of `kind` at `stride` takes the timed layout: spans or rays at stride 5. */
41
+ export function isWrunBatchedTimedLayout(kind, stride) {
42
+ return kind !== 'marks' && stride === WRUN_BATCHED_TIMED_STRIDE;
43
+ }
44
+ /** One slot's fields for a section of `kind` at `stride` (the kit's `wrunBatchedSectionFields`): the
45
+ * timed fields at stride 5 on spans and rays, WRUN_BATCHED_FIELDS otherwise. */
46
+ export function wrunBatchedSectionFields(kind, stride) {
47
+ return kind !== 'marks' && isWrunBatchedTimedLayout(kind, stride)
48
+ ? WRUN_BATCHED_TIMED_FIELDS[kind]
49
+ : WRUN_BATCHED_FIELDS[kind];
50
+ }
51
+ /** The records a section holds a bar at most. */
52
+ export const WRUN_BATCHED_MAX_SLOTS = 64;
53
+ /** The outputs a sheet declares at most (the ABI's 256 a row): a section ends inside them. */
54
+ export const WRUN_BATCHED_MAX_OUTPUTS = 256;
55
+ /** A hover template's longest text. */
56
+ export const WRUN_BATCHED_TOOLTIP_MAX_CHARS = 200;
57
+ /** The colours each kind declares (marks: indexed by the record's side, [sell, buy, ...]). */
58
+ const COLOR_COUNTS = {
59
+ marks: [2, 4],
60
+ spans: [1, 8],
61
+ rays: [1, 8],
62
+ };
63
+ /**
64
+ * The look a host applies for a key a section leaves out (the rule settled with the kit): a published
65
+ * sheet carries every look key (the kit's build writes these into the derived sheet) and a sheet that
66
+ * still lacks one draws with them instead of refusing; a `null` the sheet holds stays null (a span's
67
+ * border: none; a tooltip: no readout). A mirror of the kit's WRUN_MARKS_DEFAULTS, WRUN_SPANS_DEFAULTS
68
+ * and WRUN_RAYS_DEFAULTS (indicator-kit `wrun-style/batched.ts`): kit 0.71.0 exports them from kit.js,
69
+ * the editor-only entry, not from host.js, the runtime entry, and this module runs on the main thread,
70
+ * so the copy stays and wrun-batched-marks.kit-mirror.spec.ts holds it to the installed kit.
71
+ * `panel` is not read here: every batched section draws on the price pane.
72
+ */
73
+ const LOOK_DEFAULTS = {
74
+ marks: {
75
+ size: { law: 'sqrt', unit: 1, scale: 5 },
76
+ opacity_pct: 30,
77
+ look: 0,
78
+ text: { mode: 1, field: 'qty', format: 'compact', min_px: 22 },
79
+ x: 0,
80
+ colors: ['theme.down', 'theme.up'],
81
+ tooltip: null,
82
+ panel: 'overlay',
83
+ },
84
+ spans: {
85
+ colors: ['theme.accent'],
86
+ opacity: 0.2,
87
+ border: { width: 1, opacity: 0.8 },
88
+ words: [],
89
+ tooltip: null,
90
+ panel: 'overlay',
91
+ },
92
+ rays: {
93
+ colors: ['theme.accent'],
94
+ width: 1,
95
+ line_style: 'solid',
96
+ opacity: 1,
97
+ words: [],
98
+ tooltip: null,
99
+ panel: 'overlay',
100
+ },
101
+ };
102
+ const KINDS = new Set(WRUN_BATCHED_MARKS_KINDS);
103
+ export function isWrunBatchedMarksKind(kind) {
104
+ return typeof kind === 'string' && KINDS.has(kind);
105
+ }
106
+ /** A batched child's id: `<overlayId>::<kind>:<name>`. */
107
+ export function wrunBatchedChildId(overlayId, kind, name) {
108
+ return `${overlayId}::${kind}:${name}`;
109
+ }
110
+ function isRecord(value) {
111
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
112
+ }
113
+ function finite(value) {
114
+ return typeof value === 'number' && Number.isFinite(value);
115
+ }
116
+ /** The cells one kept bar of a section costs: its child row, the timestamp and every field of every
117
+ * slot (`1 + slots * stride`), and nothing else (the parent run's columns and a replace's old copy
118
+ * are not charged; the header says why). Empty slots count: the row is as wide as the section. */
119
+ export function wrunBatchedBarCells(spec) {
120
+ return 1 + spec.slots * spec.stride;
121
+ }
122
+ function sectionRefusal(sheetId, subject, reason) {
123
+ return new Error(`WRUN ${sheetId}: ${subject}: ${reason}`);
124
+ }
125
+ /**
126
+ * The sheet's batched sections in mount order (marks, spans, rays; each list in its order),
127
+ * validated against the sheet's outputs BY INDEX: `slots` a whole number from 1 to 64, `stride` one
128
+ * the gate admits (marks 3; spans and rays 4, or 5 for the timed layout), `first_output` a whole
129
+ * number, and outputs `first_output` through `first_output + slots * stride - 1` declared,
130
+ * contiguous, data-only (plot ""), inside the 256 a sheet declares and owned by no other section; a
131
+ * unique name; declared colours the kind takes (left out, the kit's default colours draw); a tooltip
132
+ * of at most 200 characters. Anything else refuses the run by name (thrown). A section whose
133
+ * declaration names a layout newer than this chart (`wrunBatchedLayoutVerdict`: a stride, a key or an
134
+ * option value it does not know) refuses nothing here: it is read with its reason (`newer`), its
135
+ * outputs unread, and its child alone is refused at the mount. A section the Style row switched off
136
+ * is read too (a malformed section refuses on every run, drawn or not).
137
+ */
138
+ export function readWrunBatchedSections(sheet) {
139
+ const sheetId = typeof sheet.id === 'string' && sheet.id !== '' ? sheet.id : 'sheet';
140
+ const outputsByIndex = new Map();
141
+ for (const output of Array.isArray(sheet.outputs) ? sheet.outputs : []) {
142
+ if (isRecord(output) && Number.isInteger(output.index))
143
+ outputsByIndex.set(output.index, output);
144
+ }
145
+ const owners = new Map();
146
+ const names = new Set();
147
+ const specs = [];
148
+ for (const kind of WRUN_BATCHED_MARKS_KINDS) {
149
+ const list = sheet[kind];
150
+ if (list === undefined)
151
+ continue;
152
+ if (!Array.isArray(list))
153
+ throw sectionRefusal(sheetId, kind, 'must be a list of sections');
154
+ list.forEach((entry, at) => {
155
+ if (!isRecord(entry))
156
+ throw sectionRefusal(sheetId, `${kind}[${at}]`, 'must be an object');
157
+ const name = entry.name;
158
+ if (typeof name !== 'string' || name === '')
159
+ throw sectionRefusal(sheetId, `${kind}[${at}]`, 'needs a name');
160
+ const subject = `${kind} '${name}'`;
161
+ if (names.has(name))
162
+ throw sectionRefusal(sheetId, subject, 'the name is taken by another batched section');
163
+ names.add(name);
164
+ // A layout newer than this chart (the gate, cached per declaration): its child alone is refused, by
165
+ // name, at the mount; the rules below are this layout's and never judge a newer one.
166
+ const newer = wrunBatchedLayoutVerdict(kind, entry);
167
+ if (newer !== null) {
168
+ specs.push({
169
+ kind,
170
+ name,
171
+ slots: wholeIn(entry.slots, 1, WRUN_BATCHED_MAX_SLOTS, 1),
172
+ firstOutput: 0,
173
+ stride: WRUN_BATCHED_STRIDE[kind],
174
+ declaration: entry,
175
+ newer,
176
+ });
177
+ return;
178
+ }
179
+ const slots = entry.slots;
180
+ if (typeof slots !== 'number' || !Number.isInteger(slots) || slots < 1 || slots > WRUN_BATCHED_MAX_SLOTS) {
181
+ throw sectionRefusal(sheetId, subject, `slots must be a whole number from 1 to ${WRUN_BATCHED_MAX_SLOTS}`);
182
+ }
183
+ // The gate admitted it: the kind's stride, or the timed layout's on spans and rays.
184
+ const stride = entry.stride;
185
+ const first = entry.first_output;
186
+ if (typeof first !== 'number' || !Number.isInteger(first) || first < 0) {
187
+ throw sectionRefusal(sheetId, subject, 'first_output must be a whole number from 0');
188
+ }
189
+ const last = first + slots * stride - 1;
190
+ if (last >= WRUN_BATCHED_MAX_OUTPUTS) {
191
+ throw sectionRefusal(sheetId, subject, `outputs ${first}..${last} pass the ${WRUN_BATCHED_MAX_OUTPUTS} outputs a sheet declares`);
192
+ }
193
+ for (let index = first; index <= last; index += 1) {
194
+ const output = outputsByIndex.get(index);
195
+ if (output === undefined) {
196
+ throw sectionRefusal(sheetId, subject, `output ${index} is not declared (the section reads outputs ${first}..${last} by index)`);
197
+ }
198
+ if (output.plot !== '') {
199
+ throw sectionRefusal(sheetId, subject, `output ${index} ('${output.name}') draws a plot; its outputs are data-only`);
200
+ }
201
+ const owner = owners.get(index);
202
+ if (owner !== undefined)
203
+ throw sectionRefusal(sheetId, subject, `output ${index} belongs to ${owner}`);
204
+ owners.set(index, subject);
205
+ }
206
+ // Left out, the kit's default colours draw (LOOK_DEFAULTS); declared, they must fit the kind.
207
+ const [fewest, most] = COLOR_COUNTS[kind];
208
+ const colors = entry.colors;
209
+ if (colors !== undefined && (!Array.isArray(colors) || colors.length < fewest || colors.length > most)) {
210
+ throw sectionRefusal(sheetId, subject, `colors must hold ${fewest} to ${most} colours`);
211
+ }
212
+ const tooltip = entry.tooltip;
213
+ if (tooltip !== undefined &&
214
+ tooltip !== null &&
215
+ (typeof tooltip !== 'string' || tooltip.length > WRUN_BATCHED_TOOLTIP_MAX_CHARS)) {
216
+ throw sectionRefusal(sheetId, subject, `tooltip must be text of at most ${WRUN_BATCHED_TOOLTIP_MAX_CHARS} characters`);
217
+ }
218
+ specs.push({
219
+ kind,
220
+ name,
221
+ slots,
222
+ firstOutput: first,
223
+ stride,
224
+ declaration: entry,
225
+ });
226
+ });
227
+ }
228
+ return specs;
229
+ }
230
+ /** True when the sheet declares any batched section (a non-empty list of any kind). */
231
+ export function wrunSheetHasBatchedMarks(sheet) {
232
+ return WRUN_BATCHED_MARKS_KINDS.some((kind) => Array.isArray(sheet?.[kind]) && sheet[kind].length > 0);
233
+ }
234
+ /** An epoch-seconds time as the engine's epoch ms, on the whole millisecond (a hole stays a hole):
235
+ * THE one conversion of a timed record's times, in the row copy and nowhere else. */
236
+ function secondsToMs(value) {
237
+ return Number.isFinite(value) ? Math.round(value * 1000) : value;
238
+ }
239
+ /** Whether a filled slot's meta is one this chart's decoders read (the kit's packers' range). */
240
+ function packedMetaKnown(kind, meta) {
241
+ return kind === 'marks' ? decodeWrunMarkMeta(meta) !== null : decodeWrunSpanMeta(meta) !== null;
242
+ }
243
+ /**
244
+ * The child rows of a section from the parent's rows `fromIndex` onward, by index: `[ts, ...fields]`,
245
+ * width `1 + slots * stride`, a field that is not finite NaN, a non-ready row all NaN (it still
246
+ * carries its timestamp). A row with no finite timestamp has no place and is skipped. A timed
247
+ * section's start and end (stride 5) are copied from epoch seconds to epoch ms here, once: the child
248
+ * rows, everything that cuts them and the engine read milliseconds. With an `audit`, each filled
249
+ * slot's meta is checked in the same pass (`WrunBatchedRowsAudit`).
250
+ */
251
+ export function wrunBatchedRowsOf(spec, outputRows, fromIndex = 0, audit) {
252
+ const { slots, stride } = spec;
253
+ const first = spec.firstOutput;
254
+ const timed = isWrunBatchedTimedLayout(spec.kind, stride);
255
+ const metaAt = wrunBatchedSectionFields(spec.kind, stride).length - 1;
256
+ const rows = [];
257
+ for (let at = Math.max(0, fromIndex); at < outputRows.length; at += 1) {
258
+ const source = outputRows[at];
259
+ if (!finite(source?.ts))
260
+ continue;
261
+ const outputs = source.outputs;
262
+ const row = [source.ts];
263
+ for (let slot = 0; slot < slots; slot += 1) {
264
+ const base = first + slot * stride;
265
+ for (let field = 0; field < stride; field += 1) {
266
+ const value = outputs === null ? Number.NaN : outputs[base + field];
267
+ row.push(finite(value) ? value : Number.NaN);
268
+ }
269
+ if (outputs === null)
270
+ continue;
271
+ const head = row.length - stride;
272
+ if (timed) {
273
+ row[head + TIMED_START] = secondsToMs(row[head + TIMED_START]);
274
+ row[head + TIMED_END] = secondsToMs(row[head + TIMED_END]);
275
+ }
276
+ if (audit === undefined || audit.newer !== undefined || !finite(row[head]))
277
+ continue;
278
+ const meta = row[head + metaAt];
279
+ if (finite(meta) && !packedMetaKnown(spec.kind, meta)) {
280
+ audit.newer = `a record's meta ${meta} packs a field this chart does not read`;
281
+ }
282
+ }
283
+ rows.push(row);
284
+ }
285
+ return rows;
286
+ }
287
+ /** The index of the first parent row at or after `fromTs`, walked back from the newest row (rows are
288
+ * in timestamp order), so a tick's tail costs its own rows and never the history. */
289
+ export function wrunBatchedTailStart(outputRows, fromTs) {
290
+ let at = outputRows.length;
291
+ while (at > 0 && outputRows[at - 1].ts >= fromTs)
292
+ at -= 1;
293
+ return at;
294
+ }
295
+ /** A whole number within [min, max], else `fallback`. */
296
+ function wholeIn(value, min, max, fallback) {
297
+ return typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max ? value : fallback;
298
+ }
299
+ /** A finite number clamped to [min, max], else `fallback`. */
300
+ function clampTo(value, min, max, fallback) {
301
+ return finite(value) ? Math.min(max, Math.max(min, value)) : fallback;
302
+ }
303
+ /** A word among `words` (its index), a whole number among the indexes, else `fallback`. */
304
+ function wordIndex(value, words, fallback) {
305
+ if (typeof value === 'string') {
306
+ const at = words.indexOf(value);
307
+ return at === -1 ? fallback : at;
308
+ }
309
+ return wholeIn(value, 0, words.length - 1, fallback);
310
+ }
311
+ /** The marks look words (round-2 fold 1), the numbers canonical; the first contract's words read too. */
312
+ const MARK_LOOKS = ['circle', 'dot', 'ring', 'square'];
313
+ const MARK_TEXT_MODES = ['off', 'largest', 'all'];
314
+ const MARK_X_WORDS = ['bar', 'offset'];
315
+ const MARK_TEXT_FORMATS = new Set(['compact', 'price', 'int']);
316
+ const LINE_STYLES = new Set(['solid', 'dashed', 'dotted']);
317
+ // ── The gate: layouts newer than this chart ─────────────────────────────────
318
+ /** A key's rule in the gate's vocabulary: `ANY` (the reader takes any value, clamping or defaulting
319
+ * it), the values an option takes (an index or a word), or a nested object's own vocabulary. */
320
+ const ANY = 'any';
321
+ /** The strides this chart reads, per kind: marks 3; spans and rays 4, and 5 (the timed layout). */
322
+ const KNOWN_STRIDES = {
323
+ marks: [WRUN_BATCHED_STRIDE.marks],
324
+ spans: [WRUN_BATCHED_STRIDE.spans, WRUN_BATCHED_TIMED_STRIDE],
325
+ rays: [WRUN_BATCHED_STRIDE.rays, WRUN_BATCHED_TIMED_STRIDE],
326
+ };
327
+ /** The marks options by index, or by the first contract's words (what the look readers take). */
328
+ const MARK_LOOK_VALUES = [0, 1, 2, 3, ...MARK_LOOKS];
329
+ const MARK_X_VALUES = [0, 1, ...MARK_X_WORDS];
330
+ const MARK_TEXT_MODE_VALUES = [0, 1, 2, ...MARK_TEXT_MODES];
331
+ /** Every batched section draws on the price pane: a lower-pane section needs a newer chart. */
332
+ const PANEL_VALUES = ['overlay'];
333
+ /**
334
+ * Every key a section of each kind may hold, with the values this chart reads under it: the kit's
335
+ * strict section schemas (indicator-kit `wrun-style/batched.ts`, the timed layout's kit), plus three keys the
336
+ * chart reads beyond them: `label` (the readout title published sheets carry: Big Trades 0.4.0), the
337
+ * first contract's `shape` (marks, legacy) and the chart's own `visible` (the Style row's eye, which
338
+ * the sheet painter writes: wrun-color-settings.util; it writes no other key outside this list).
339
+ */
340
+ const SECTION_VOCABULARY = {
341
+ marks: {
342
+ name: ANY,
343
+ slots: ANY,
344
+ first_output: ANY,
345
+ stride: ANY,
346
+ size: { law: ['sqrt', 'linear'], unit: ANY, scale: ANY },
347
+ opacity_pct: ANY,
348
+ look: MARK_LOOK_VALUES,
349
+ text: { mode: MARK_TEXT_MODE_VALUES, field: ['qty'], format: [...MARK_TEXT_FORMATS], min_px: ANY },
350
+ x: MARK_X_VALUES,
351
+ colors: ANY,
352
+ tooltip: ANY,
353
+ label: ANY,
354
+ panel: PANEL_VALUES,
355
+ shape: MARK_LOOK_VALUES,
356
+ visible: ANY,
357
+ },
358
+ spans: {
359
+ name: ANY,
360
+ slots: ANY,
361
+ first_output: ANY,
362
+ stride: ANY,
363
+ colors: ANY,
364
+ opacity: ANY,
365
+ border: { width: ANY, opacity: ANY },
366
+ words: ANY,
367
+ tooltip: ANY,
368
+ label: ANY,
369
+ panel: PANEL_VALUES,
370
+ visible: ANY,
371
+ },
372
+ rays: {
373
+ name: ANY,
374
+ slots: ANY,
375
+ first_output: ANY,
376
+ stride: ANY,
377
+ colors: ANY,
378
+ width: ANY,
379
+ line_style: [...LINE_STYLES],
380
+ opacity: ANY,
381
+ words: ANY,
382
+ tooltip: ANY,
383
+ label: ANY,
384
+ panel: PANEL_VALUES,
385
+ visible: ANY,
386
+ },
387
+ };
388
+ /** A value as the gate's reasons quote it. */
389
+ function quotedValue(value) {
390
+ try {
391
+ return JSON.stringify(value) ?? String(value);
392
+ }
393
+ catch {
394
+ return String(value);
395
+ }
396
+ }
397
+ /** The first key or option value of `value` its vocabulary does not hold (`at` the key path so far),
398
+ * null when every one is known. An absent or null value is the reader's default, never newer. */
399
+ function vocabularyVerdict(kind, vocabulary, value, at) {
400
+ for (const [key, entry] of Object.entries(value)) {
401
+ const path = `${at}${key}`;
402
+ if (!Object.hasOwn(vocabulary, key))
403
+ return `'${path}' is no ${kind} key this chart reads`;
404
+ const rule = vocabulary[key];
405
+ if (rule === ANY || entry === undefined || entry === null)
406
+ continue;
407
+ if (Array.isArray(rule)) {
408
+ if (!rule.includes(entry)) {
409
+ return `${path} ${quotedValue(entry)} is no ${kind} option this chart reads`;
410
+ }
411
+ continue;
412
+ }
413
+ if (!isRecord(entry))
414
+ return `${path} ${quotedValue(entry)} is no ${kind} option this chart reads`;
415
+ const nested = vocabularyVerdict(kind, rule, entry, `${path}.`);
416
+ if (nested !== null)
417
+ return nested;
418
+ }
419
+ return null;
420
+ }
421
+ /** The verdicts already reached, per kind, by section (a sheet's sections keep their identity across
422
+ * runs and ticks: the painter copies only a section it writes into, and every copy of a declaration
423
+ * reads that declaration's own verdict). */
424
+ const layoutVerdicts = {
425
+ marks: new WeakMap(),
426
+ spans: new WeakMap(),
427
+ rays: new WeakMap(),
428
+ };
429
+ /** A section's own stride, keys and option values against the vocabulary (uncached). */
430
+ function sectionLayoutVerdict(kind, section) {
431
+ const strides = KNOWN_STRIDES[kind];
432
+ return strides.includes(section.stride)
433
+ ? vocabularyVerdict(kind, SECTION_VOCABULARY[kind], section, '')
434
+ : `stride ${quotedValue(section.stride)} is no ${kind} layout this chart reads (it reads ${strides.join(' or ')})`;
435
+ }
436
+ /**
437
+ * Why this chart cannot draw a section of `kind` (the gate, round-1 finding 17), null when it can: a
438
+ * stride it does not know (marks 3; spans and rays 4, or 5 for the timed layout), a key it does not
439
+ * know, or an option value it does not know under a known key, nested keys included (`size`, `text`,
440
+ * `border`). The section's child is refused by name ("Needs a newer chart") and the Indicator's other
441
+ * children run: the next layout change is caught here as the timed one would have been. The reason is
442
+ * diagnostic text (the notice row's details), never copy. Read once per section (cached).
443
+ *
444
+ * The declaration the package wrote is judged BEFORE the look the settings paint on it (WRUN-MARKS-
445
+ * CONTRACT F2, finding 4): the builders read the painted sheet, and a saved Style row writes only values
446
+ * this chart reads, so judging the painted copy alone would let a setting hide a declaration this chart
447
+ * cannot draw (a saved `line_style: 'solid'` over a declared `'wavy'`). A painted section reaches its
448
+ * declaration through the painter (`wrunPaintedDeclarationOf`), whose verdict is cached on the
449
+ * declaration itself, so a pan or a tick that paints it again judges it once; the painted copy is judged
450
+ * after it (a param bound through `style_targets` may paint a value this chart does not read).
451
+ */
452
+ export function wrunBatchedLayoutVerdict(kind, section) {
453
+ const cache = layoutVerdicts[kind];
454
+ const known = cache.get(section);
455
+ if (known !== undefined)
456
+ return known;
457
+ const declared = wrunPaintedDeclarationOf(section);
458
+ const verdict = (declared !== section ? wrunBatchedLayoutVerdict(kind, declared) : null) ?? sectionLayoutVerdict(kind, section);
459
+ cache.set(section, verdict);
460
+ return verdict;
461
+ }
462
+ /** A section's words, each a string (the spans and rays `{{word}}` vocabulary, 0..16). */
463
+ function wordsOf(value) {
464
+ return Array.isArray(value) ? value.slice(0, 16).map((word) => (typeof word === 'string' ? word : '')) : [];
465
+ }
466
+ /** The marks look the engine draws (r6 parity): `look` 0..3 (Bubble, Soft dot, Ring, Square), the
467
+ * size law over the quantity (`unit` the Min size, `scale` the Bubble size 1..10), `x` 0..1
468
+ * (Candle center, Trade time), `opacity_pct` 10..80, the caption (`text.mode` 0 Off, 1 Big
469
+ * bubbles, 2 All; its format and the smallest bubble that holds one). A key left out, or an option
470
+ * that is none of its values (look, x, law, the caption's mode and format), takes the kit's default
471
+ * (LOOK_DEFAULTS.marks); a number past its range is clamped. */
472
+ function marksSettings(section) {
473
+ const defaults = LOOK_DEFAULTS.marks;
474
+ const size = isRecord(section.size) ? section.size : {};
475
+ const text = isRecord(section.text) ? section.text : {};
476
+ const legacyShape = section.shape;
477
+ return {
478
+ look: wordIndex(section.look ?? legacyShape, MARK_LOOKS, defaults.look),
479
+ size: {
480
+ law: size.law === 'linear' || size.law === 'sqrt' ? size.law : defaults.size.law,
481
+ unit: finite(size.unit) && size.unit > 0 ? size.unit : defaults.size.unit,
482
+ scale: clampTo(size.scale, 1, 10, defaults.size.scale),
483
+ },
484
+ x: wordIndex(section.x, MARK_X_WORDS, defaults.x),
485
+ colors: [...(section.colors ?? defaults.colors)],
486
+ opacity_pct: clampTo(section.opacity_pct, 10, 80, defaults.opacity_pct),
487
+ text: {
488
+ mode: wordIndex(text.mode, MARK_TEXT_MODES, defaults.text.mode),
489
+ field: defaults.text.field,
490
+ format: typeof text.format === 'string' && MARK_TEXT_FORMATS.has(text.format) ? text.format : defaults.text.format,
491
+ min_px: clampTo(text.min_px, 0, 64, defaults.text.min_px),
492
+ },
493
+ };
494
+ }
495
+ /** A span's edge: a `null` the sheet holds draws none; a declared edge takes each key it leaves out
496
+ * from the kit's default edge, which an edge left out (or one that is no object) takes whole. */
497
+ function spanBorderOf(value) {
498
+ if (value === null)
499
+ return null;
500
+ const border = isRecord(value) ? value : {};
501
+ const defaults = LOOK_DEFAULTS.spans.border;
502
+ return {
503
+ width: clampTo(border.width, 0, 4, defaults.width),
504
+ opacity: clampTo(border.opacity, 0, 1, defaults.opacity),
505
+ };
506
+ }
507
+ function spansSettings(section) {
508
+ const defaults = LOOK_DEFAULTS.spans;
509
+ return {
510
+ colors: [...(section.colors ?? defaults.colors)],
511
+ opacity: clampTo(section.opacity, 0, 1, defaults.opacity),
512
+ border: spanBorderOf(section.border),
513
+ words: wordsOf(section.words),
514
+ };
515
+ }
516
+ function raysSettings(section) {
517
+ const defaults = LOOK_DEFAULTS.rays;
518
+ return {
519
+ colors: [...(section.colors ?? defaults.colors)],
520
+ width: clampTo(section.width, 0.5, 8, defaults.width),
521
+ line_style: typeof section.line_style === 'string' && LINE_STYLES.has(section.line_style)
522
+ ? section.line_style
523
+ : defaults.line_style,
524
+ opacity: clampTo(section.opacity, 0, 1, defaults.opacity),
525
+ words: wordsOf(section.words),
526
+ };
527
+ }
528
+ /** The tooltip a section declares, null when it declares none (absent, null or blank). */
529
+ function tooltipOf(section) {
530
+ return typeof section.tooltip === 'string' && section.tooltip.trim() !== '' ? section.tooltip : null;
531
+ }
532
+ /** The engine settings of a section's child: the geometry (`slots`, `stride`; `first_output` stays
533
+ * here, the child rows start at field 0), the look of its kind, and `hoverReadout` when a tooltip is
534
+ * declared (the engine registers its drawn records for hover then). Colours stay as declared. */
535
+ export function wrunBatchedSettingsOf(spec) {
536
+ const look = spec.kind === 'marks'
537
+ ? marksSettings(spec.declaration)
538
+ : spec.kind === 'spans'
539
+ ? spansSettings(spec.declaration)
540
+ : raysSettings(spec.declaration);
541
+ return { slots: spec.slots, stride: spec.stride, ...look, hoverReadout: tooltipOf(spec.declaration) !== null };
542
+ }
543
+ /** The readout a section with a tooltip registers at its mount, with the record's text (the template
544
+ * printed by wrun-batched-readout.util) on it: the child carries the readout it registers, so a
545
+ * registration from the child alone (the mount's `syncCanvasReadouts` after a pass that failed part
546
+ * way) keeps the hover text. */
547
+ function readoutOf(spec) {
548
+ const tooltip = tooltipOf(spec.declaration);
549
+ if (tooltip === null)
550
+ return undefined;
551
+ const label = spec.declaration.label;
552
+ const words = spec.kind === 'marks' ? [] : wordsOf(spec.declaration.words);
553
+ const timed = isWrunBatchedTimedLayout(spec.kind, spec.stride);
554
+ const readout = {
555
+ kind: spec.kind,
556
+ label: typeof label === 'string' && label.trim() !== '' ? label : wrunLegendName(spec.name),
557
+ tooltip,
558
+ format: {},
559
+ ...(words.length > 0 ? { words } : {}),
560
+ // A timed record's `{{start}}` and `{{end}}` (their display offset is the mount door's to stamp).
561
+ ...(timed ? { timed: true } : {}),
562
+ };
563
+ readout.text = (record, formatters) => wrunBatchedReadoutText(readout, record, formatters);
564
+ return readout;
565
+ }
566
+ function childOf(spec, data, extra) {
567
+ const readout = readoutOf(spec);
568
+ return {
569
+ kind: spec.kind,
570
+ name: spec.name,
571
+ data,
572
+ settings: wrunBatchedSettingsOf(spec),
573
+ ...(readout !== undefined ? { readout } : {}),
574
+ ...extra,
575
+ };
576
+ }
577
+ /** The child of a section this chart cannot draw (`newer`, the reason): no rows, no readout, the
578
+ * geometry its settings carry a placeholder; the mount refuses it by name and never mounts it. */
579
+ function refusedChildOf(spec, newer, extra) {
580
+ return {
581
+ kind: spec.kind,
582
+ name: spec.name,
583
+ data: [],
584
+ settings: { slots: spec.slots, stride: spec.stride, hoverReadout: false },
585
+ newer,
586
+ ...extra,
587
+ };
588
+ }
589
+ /**
590
+ * One child per batched section the Style rows leave visible, in mount order. A full build charges
591
+ * the cell budget before any copy: every section's demand (its bars times its bar cells) is
592
+ * water-filled over WRUN_BATCHED_MARKS_CELL_BUDGET and each section builds only its newest bars that
593
+ * fit its share (the child carries the charge in `budget`), cut by each row's own (anchor) time: a
594
+ * timed record kept with its bar may start long before it. A tail build (`tailFromTs`) builds every
595
+ * row the tick re-evaluated and nothing older. A section the gate refused (`newer`) builds a refused
596
+ * child and asks no share; a record whose meta the copy cannot decode refuses its child the same way,
597
+ * and its share goes back to the cap: the shares are water-filled again over the children still drawn,
598
+ * each copying the older bars its grown share reaches (audited as the rest were), until no copy refuses
599
+ * another child (WRUN-MARKS-CONTRACT F2, finding 6).
600
+ */
601
+ export function wrunBatchedMarksChildren(sheet, outputRows, options = {}) {
602
+ const specs = readWrunBatchedSections(sheet).filter((spec) => !isWrunStyleTargetHidden(spec.declaration));
603
+ if (specs.length === 0)
604
+ return [];
605
+ if (options.tailFromTs !== undefined) {
606
+ const from = wrunBatchedTailStart(outputRows, options.tailFromTs);
607
+ return specs.map((spec) => {
608
+ if (spec.newer !== undefined)
609
+ return refusedChildOf(spec, spec.newer, { tailOnly: true });
610
+ const audit = {};
611
+ const data = wrunBatchedRowsOf(spec, outputRows, from, audit);
612
+ return audit.newer !== undefined
613
+ ? refusedChildOf(spec, audit.newer, { tailOnly: true })
614
+ : childOf(spec, data, { tailOnly: true });
615
+ });
616
+ }
617
+ const bars = outputRows.length;
618
+ const refusals = specs.map((spec) => spec.newer);
619
+ const data = specs.map(() => []);
620
+ // The first parent row each child copied from (`bars`: none yet). A share only grows when a sibling leaves
621
+ // (water-filling over less demand), so a pass after a refusal copies just the older rows a share now reaches.
622
+ const copiedFrom = specs.map(() => bars);
623
+ let demands;
624
+ let shares;
625
+ // Each pass that refuses a child water-fills the cap again over the children left; one that refuses none
626
+ // settles. Every other pass refuses one more child, so the build ends.
627
+ let refusedMore;
628
+ do {
629
+ refusedMore = false;
630
+ demands = specs.map((spec, at) => (refusals[at] !== undefined ? 0 : bars * wrunBatchedBarCells(spec)));
631
+ shares = wrunHeatmapCellShares(demands, WRUN_BATCHED_MARKS_CELL_BUDGET);
632
+ for (let at = 0; at < specs.length; at += 1) {
633
+ const spec = specs[at];
634
+ if (refusals[at] !== undefined)
635
+ continue;
636
+ const from = bars - Math.min(bars, Math.floor(shares[at] / wrunBatchedBarCells(spec)));
637
+ if (from >= copiedFrom[at])
638
+ continue;
639
+ const audit = {};
640
+ const older = wrunBatchedRowsOf(spec, copiedFrom[at] === bars ? outputRows : outputRows.slice(from, copiedFrom[at]), copiedFrom[at] === bars ? from : 0, audit);
641
+ copiedFrom[at] = from;
642
+ if (audit.newer !== undefined) {
643
+ refusals[at] = audit.newer;
644
+ data[at] = [];
645
+ refusedMore = true;
646
+ continue;
647
+ }
648
+ data[at] = data[at].length === 0 ? older : older.concat(data[at]);
649
+ }
650
+ } while (refusedMore);
651
+ return specs.map((spec, at) => {
652
+ const refusal = refusals[at];
653
+ if (refusal !== undefined)
654
+ return refusedChildOf(spec, refusal, {});
655
+ const perBar = wrunBatchedBarCells(spec);
656
+ return childOf(spec, data[at], {
657
+ budget: {
658
+ demand: demands[at],
659
+ demandBars: bars,
660
+ share: shares[at],
661
+ cells: data[at].length * perBar,
662
+ bars: data[at].length,
663
+ },
664
+ });
665
+ });
666
+ }
667
+ // ── The mount door ──────────────────────────────────────────────────────────
668
+ /** A section colour as the engine draws it: a colour word resolved against the theme; a packed
669
+ * number decoded (a packed theme token through its word, the existing packed-colour decode for the
670
+ * rest); undefined when it is neither. */
671
+ export function resolveWrunBatchedColor(value, theme) {
672
+ if (typeof value === 'string')
673
+ return value.trim() === '' ? undefined : resolveWrunColorWord(value, theme);
674
+ if (!finite(value))
675
+ return undefined;
676
+ const token = wrunThemeTokenOfPacked(value);
677
+ if (token !== null)
678
+ return resolveWrunColorWord(wrunThemeTokenWord(token), theme);
679
+ return decodeWrunPackedColor(value);
680
+ }
681
+ /** The colour a slot falls back to when its declared one does not resolve: a mark's side (sell the
682
+ * theme's down, buy its up), else the accent. */
683
+ function fallbackColor(kind, at, theme) {
684
+ if (kind === 'marks')
685
+ return at === 0 ? theme.down : at === 1 ? theme.up : theme.text;
686
+ return theme.accent;
687
+ }
688
+ /**
689
+ * The engine config of a batched child at its mount (and every retranslate): the id, the plot (the
690
+ * kind), the settings with every colour resolved against the chart's theme, the live merge. A child
691
+ * with a readout registers it for the hover inspector as the child carries it (its template's text
692
+ * as `text`); one without forgets any it had. A timed readout first takes the display offset its
693
+ * `{{start}}` and `{{end}}` print in (`timeOffsetMs`: the chart's display timezone, none on daily and
694
+ * longer bars), stamped on the child's own readout so every registration of it keeps it; a timezone
695
+ * switch retranslates, which stamps it again.
696
+ */
697
+ export function wrunBatchedChildConfig(child, ctx) {
698
+ const id = wrunBatchedChildId(ctx.overlayId, child.kind, child.name);
699
+ const declared = Array.isArray(child.settings.colors) ? child.settings.colors : [];
700
+ const colors = declared.map((value, at) => resolveWrunBatchedColor(value, ctx.theme) ?? fallbackColor(child.kind, at, ctx.theme));
701
+ if (child.readout !== undefined) {
702
+ if (child.readout.timed === true)
703
+ child.readout.timeOffsetMs = ctx.timeOffsetMs ?? 0;
704
+ rememberWrunCanvasReadout(id, child.readout);
705
+ }
706
+ else
707
+ forgetWrunCanvasReadout(id);
708
+ return {
709
+ id,
710
+ plot: child.kind,
711
+ type: 'onchart',
712
+ settings: { ...child.settings, colors },
713
+ mergeLiveDataPoint: wrunCanvasMergeLive,
714
+ ...(child.tailOnly === true ? { tailOnly: true } : {}),
715
+ };
716
+ }
717
+ /** A batched child's geometry read off its settings (the mount's budget and the window landing). */
718
+ export function wrunBatchedGeometryOf(settings) {
719
+ const slots = wholeIn(settings.slots, 1, WRUN_BATCHED_MAX_SLOTS, 1);
720
+ const stride = wholeIn(settings.stride, 1, WRUN_BATCHED_TIMED_STRIDE, 1);
721
+ return { slots, stride };
722
+ }
723
+ /** Per chart, per Indicator, per batched child id. */
724
+ const ledgers = new WeakMap();
725
+ function chartHolds(tc) {
726
+ return (id) => tc.metadata.some((meta) => meta.id === id);
727
+ }
728
+ /** The Indicator's ledger without the children it no longer holds (the seam mounting `keep` counts
729
+ * it). */
730
+ function ledgerOf(tc, overlayId, keep, isMounted = chartHolds(tc)) {
731
+ let overlays = ledgers.get(tc);
732
+ if (!overlays) {
733
+ overlays = new Map();
734
+ ledgers.set(tc, overlays);
735
+ }
736
+ let ledger = overlays.get(overlayId);
737
+ if (!ledger) {
738
+ ledger = new Map();
739
+ overlays.set(overlayId, ledger);
740
+ }
741
+ for (const id of [...ledger.keys()]) {
742
+ if (id !== keep && !isMounted(id))
743
+ ledger.delete(id);
744
+ }
745
+ return ledger;
746
+ }
747
+ /** The ledger as a plan reads it, writing nothing. */
748
+ function heldLedgerOf(tc, overlayId, keep, isMounted = chartHolds(tc)) {
749
+ const held = new Map();
750
+ for (const [id, cells] of ledgers.get(tc)?.get(overlayId) ?? []) {
751
+ if (id === keep || isMounted(id))
752
+ held.set(id, cells);
753
+ }
754
+ return held;
755
+ }
756
+ /** The child's water-filled share of the cap for `demand`, beside its siblings' last demands. */
757
+ function allowanceOf(ledger, childId, demand) {
758
+ const others = [...ledger].filter(([id]) => id !== childId).map(([, cells]) => cells.demand);
759
+ return wrunHeatmapCellShares([demand, ...others], WRUN_BATCHED_MARKS_CELL_BUDGET)[0];
760
+ }
761
+ /** The newest rows of `rows` whose bars fit `allowance` whole, `barCells` each (`rows` itself when they
762
+ * all fit): the oldest bars go first, never a partial row. */
763
+ function newestRowsUnder(rows, allowance, barCells) {
764
+ const keep = Math.max(0, Math.min(rows.length, Math.floor(allowance / barCells)));
765
+ return keep === rows.length ? rows : rows.slice(rows.length - keep);
766
+ }
767
+ /** A child's charge from its engine settings (`slots`, `stride`). */
768
+ export function wrunBatchedChargeOf(settings) {
769
+ return { barCells: wrunBatchedBarCells(wrunBatchedGeometryOf(settings)) };
770
+ }
771
+ /**
772
+ * The rows a seam hands a batched child in full (the first install, a full run's replace): the build
773
+ * already kept the newest bars under the section's share of the cap (`built`, charged over every
774
+ * section of the run, which replaces them all), else the child's water-filled share beside its
775
+ * siblings' last demands applies. A replace keeps the hard allowance, like a heatmap's hand-off: the
776
+ * old copy it replaces is released at the swap and never charged. Past the allowance the oldest bars
777
+ * are dropped. Returns the rows to hand the engine (`rows` itself when they fit).
778
+ */
779
+ export function budgetWrunBatchedRows(tc, overlayId, childId, rows, charge, options) {
780
+ const ledger = ledgerOf(tc, overlayId, childId, options.isMounted);
781
+ const demand = Math.max(options.built?.demand ?? 0, rows.length * charge.barCells);
782
+ const demandBars = Math.max(options.built?.demandBars ?? 0, rows.length);
783
+ const allowance = options.built?.share ?? allowanceOf(ledger, childId, demand);
784
+ const kept = newestRowsUnder(rows, allowance, charge.barCells);
785
+ ledger.set(childId, {
786
+ demand,
787
+ demandBars,
788
+ mounted: kept.length * charge.barCells,
789
+ mountedBars: kept.length,
790
+ });
791
+ noteWrunBatchedCells(tc, overlayId);
792
+ return kept;
793
+ }
794
+ /** The demand of rows that grew from what the child held: the cells and bars it last asked for,
795
+ * plus the growth over what it then held (never under the rows themselves). */
796
+ function carriedDemand(before, cells, bars) {
797
+ return {
798
+ demand: Math.max(cells, (before?.demand ?? cells) + cells - (before?.mounted ?? cells)),
799
+ demandBars: Math.max(bars, (before?.demandBars ?? bars) + bars - (before?.mountedBars ?? bars)),
800
+ };
801
+ }
802
+ /**
803
+ * After a live merge into a mounted batched child (the changed tail replaced and appended), or a
804
+ * rebuild from the rows it held: its retained rows counted again, the merge's growth joining its
805
+ * demand, and past its allowance the oldest bars dropped down to the watermark (95%, so the bars
806
+ * after it land in place; the newest bar never goes while it fits). Returns the shorter rows for the
807
+ * seam to hand the engine, or null when the retained rows fit.
808
+ */
809
+ export function budgetWrunBatchedRetained(tc, overlayId, childId, retained, charge, isMounted) {
810
+ const ledger = ledgerOf(tc, overlayId, childId, isMounted);
811
+ const cells = retained.length * charge.barCells;
812
+ const { demand, demandBars } = carriedDemand(ledger.get(childId), cells, retained.length);
813
+ const allowance = allowanceOf(ledger, childId, demand);
814
+ let kept = retained;
815
+ if (cells > allowance) {
816
+ const target = wrunHeatmapTrimTarget(allowance, charge.barCells);
817
+ const keep = Math.min(retained.length, Math.floor(target / charge.barCells));
818
+ kept = retained.slice(retained.length - keep);
819
+ }
820
+ ledger.set(childId, { demand, demandBars, mounted: kept.length * charge.barCells, mountedBars: kept.length });
821
+ noteWrunBatchedCells(tc, overlayId);
822
+ return kept === retained ? null : kept;
823
+ }
824
+ /**
825
+ * The budget of a history-window merge, writing nothing: the merged rows start from the rows the
826
+ * child holds (which its allowance already cut), so the demand carries what the earlier rows asked
827
+ * for, the merge's growth joining it; the rows are cut to the hard allowance, oldest first (the
828
+ * mounted rows a pass row replaces go at the swap and are not charged, as on a run's replace).
829
+ */
830
+ export function planWrunBatchedMerged(tc, overlayId, childId, merged, charge, isMounted) {
831
+ const basis = heldLedgerOf(tc, overlayId, childId, isMounted);
832
+ const { demand, demandBars } = carriedDemand(basis.get(childId), merged.length * charge.barCells, merged.length);
833
+ const rows = newestRowsUnder(merged, allowanceOf(basis, childId, demand), charge.barCells);
834
+ return {
835
+ overlayId,
836
+ childId,
837
+ charge,
838
+ merged,
839
+ rows,
840
+ cells: { demand, demandBars, mounted: rows.length * charge.barCells, mountedBars: rows.length },
841
+ basis,
842
+ };
843
+ }
844
+ /** The plan as the ledger stands now: `plan` itself while no seam wrote an entry it read, else the
845
+ * same merged rows planned again. */
846
+ export function currentWrunBatchedPlan(tc, plan, isMounted) {
847
+ const now = heldLedgerOf(tc, plan.overlayId, plan.childId, isMounted);
848
+ const current = now.size === plan.basis.size && [...plan.basis].every(([id, cells]) => now.get(id) === cells);
849
+ return current ? plan : planWrunBatchedMerged(tc, plan.overlayId, plan.childId, plan.merged, plan.charge, isMounted);
850
+ }
851
+ /** The ledger write of a plan whose rows the engine was just handed. */
852
+ export function commitWrunBatchedPlan(tc, plan, isMounted) {
853
+ ledgerOf(tc, plan.overlayId, plan.childId, isMounted).set(plan.childId, { ...plan.cells });
854
+ noteWrunBatchedCells(tc, plan.overlayId);
855
+ }
856
+ /** The ledger's children other than `except` holding more than their water-filled share. */
857
+ function childrenOverShare(ledger, except) {
858
+ const children = [...ledger];
859
+ const shares = wrunHeatmapCellShares(children.map(([, cells]) => cells.demand), WRUN_BATCHED_MARKS_CELL_BUDGET);
860
+ return children.flatMap(([id, cells], at) => (id !== except && cells.mounted > shares[at] ? [id] : []));
861
+ }
862
+ /** The Indicator's other batched children now over their share (a sibling just mounted or asked for
863
+ * more): the seam trims each through `budgetWrunBatchedRetained`. */
864
+ export function wrunBatchedChildrenOverShare(tc, overlayId, except, isMounted) {
865
+ return childrenOverShare(ledgerOf(tc, overlayId, except, isMounted), except);
866
+ }
867
+ /** After a live append grew one child: while the Indicator's mounted cells pass the cap, the siblings
868
+ * now over their share; under the cap nothing is named (one sum per tick). */
869
+ export function wrunBatchedSiblingsToRebalance(tc, overlayId, grown, isMounted) {
870
+ const ledger = ledgerOf(tc, overlayId, grown, isMounted);
871
+ let mounted = 0;
872
+ for (const cells of ledger.values())
873
+ mounted += cells.mounted;
874
+ return mounted > WRUN_BATCHED_MARKS_CELL_BUDGET ? childrenOverShare(ledger, grown) : [];
875
+ }
876
+ /**
877
+ * A replay cut (wrun-replay-rows.util): the child now holds `rows`, which the replay means it to hold,
878
+ * so its demand is them too (a cut is no cap). Written synchronously with the cut.
879
+ */
880
+ export function noteWrunBatchedRowsCut(tc, overlayId, childId, rows, charge) {
881
+ const cells = rows.length * charge.barCells;
882
+ ledgerOf(tc, overlayId, childId).set(childId, {
883
+ demand: cells,
884
+ demandBars: rows.length,
885
+ mounted: cells,
886
+ mountedBars: rows.length,
887
+ });
888
+ noteWrunBatchedCells(tc, overlayId);
889
+ }
890
+ /** A child that left the chart takes its entry with it. */
891
+ export function forgetWrunBatchedCells(tc, overlayId, childId) {
892
+ const ledger = ledgers.get(tc)?.get(overlayId);
893
+ if (ledger?.delete(childId))
894
+ noteWrunBatchedCells(tc, overlayId);
895
+ }
896
+ export function snapshotWrunBatchedLedger(tc, overlayId) {
897
+ const ledger = ledgers.get(tc)?.get(overlayId);
898
+ return ledger === undefined ? null : new Map(ledger);
899
+ }
900
+ export function restoreWrunBatchedLedger(tc, overlayId, snapshot) {
901
+ let overlays = ledgers.get(tc);
902
+ if (snapshot === null)
903
+ overlays?.delete(overlayId);
904
+ else {
905
+ if (!overlays) {
906
+ overlays = new Map();
907
+ ledgers.set(tc, overlays);
908
+ }
909
+ overlays.set(overlayId, new Map(snapshot));
910
+ }
911
+ noteWrunBatchedCells(tc, overlayId);
912
+ }
913
+ /** The Indicator's batched cells as the notice reads them: the mounted total, and the capped summary
914
+ * while a child holds fewer cells than it asked for. */
915
+ export function wrunBatchedCellSummary(tc, overlayId) {
916
+ const children = [...(ledgers.get(tc)?.get(overlayId)?.entries() ?? [])]
917
+ .filter(([id]) => tc.metadata.some((meta) => meta.id === id))
918
+ .map(([, cells]) => cells);
919
+ const mounted = children.reduce((sum, cells) => sum + cells.mounted, 0);
920
+ const trimmed = children.filter((cells) => cells.mounted < cells.demand);
921
+ if (trimmed.length === 0)
922
+ return { mounted, capped: null };
923
+ return {
924
+ mounted,
925
+ capped: {
926
+ total: children.reduce((sum, cells) => sum + cells.demand, 0),
927
+ drawn: mounted,
928
+ cap: WRUN_BATCHED_MARKS_CELL_BUDGET,
929
+ bars: Math.max(...children.map((cells) => cells.demandBars)),
930
+ drawnBars: Math.min(...trimmed.map((cells) => cells.mountedBars)),
931
+ },
932
+ };
933
+ }
934
+ function noteWrunBatchedCells(tc, overlayId) {
935
+ scheduleWrunCellsCapNotice(tc, overlayId, () => wrunBatchedCellSummary(tc, overlayId), 'batched');
936
+ }
937
+ /** The trim watermark the live seams cut a retained child back to (the heatmap budget's). */
938
+ export const WRUN_BATCHED_TRIM_WATERMARK = WRUN_HEATMAP_TRIM_WATERMARK;