@orangecharts/wrun-chart-host 0.3.0 → 0.5.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 (362) hide show
  1. package/README.md +23 -6
  2. package/dist/constants/exchange-names.leaf.d.ts +8 -0
  3. package/dist/constants/exchange-names.leaf.js +101 -0
  4. package/dist/constants/kscript-data-interval-restrictions.constants.d.ts +15 -0
  5. package/dist/constants/kscript-data-interval-restrictions.constants.js +40 -0
  6. package/dist/constants/opra-compliance.constants.d.ts +19 -0
  7. package/dist/constants/opra-compliance.constants.js +19 -0
  8. package/dist/constants/replay-ladder.leaf.d.ts +30 -0
  9. package/dist/constants/replay-ladder.leaf.js +99 -0
  10. package/dist/constants/scriptEditor/builtin-script-snippets.d.ts +133 -0
  11. package/dist/constants/scriptEditor/builtin-script-snippets.js +451 -0
  12. package/dist/constants/scriptEditor/cme-official-scripts.constants.d.ts +168 -0
  13. package/dist/constants/scriptEditor/cme-official-scripts.constants.js +398 -0
  14. package/dist/constants/scriptEditor/converted-script-id.leaf.d.ts +8 -0
  15. package/dist/constants/scriptEditor/converted-script-id.leaf.js +10 -0
  16. package/dist/constants/scriptEditor/execution.constants.d.ts +4 -0
  17. package/dist/constants/scriptEditor/execution.constants.js +14 -0
  18. package/dist/constants/wrun-prefix-safe.constants.d.ts +23 -0
  19. package/dist/constants/wrun-prefix-safe.constants.js +26 -0
  20. package/dist/host-env.d.ts +321 -24
  21. package/dist/host-env.js +15 -0
  22. package/dist/host-ports.types.d.ts +857 -35
  23. package/dist/index.d.ts +149 -2
  24. package/dist/index.js +149 -2
  25. package/dist/instances/script-engine-worker-ohlcv-transfer.d.ts +31 -0
  26. package/dist/instances/script-engine-worker-ohlcv-transfer.js +164 -0
  27. package/dist/interfaces/market-event.interface.d.ts +231 -0
  28. package/dist/interfaces/market-event.interface.js +15 -0
  29. package/dist/interfaces/opra-realtime.interface.d.ts +70 -134
  30. package/dist/interfaces/opra-realtime.interface.js +34 -59
  31. package/dist/interfaces/replay.interface.d.ts +285 -0
  32. package/dist/interfaces/replay.interface.js +1 -0
  33. package/dist/kscript-data/controls/live-ohlcv-merge.util.d.ts +1 -0
  34. package/dist/kscript-data/controls/live-ohlcv-merge.util.js +93 -0
  35. package/dist/kscript-data/controls/live-trades-merge.util.d.ts +5 -1
  36. package/dist/kscript-data/controls/live-trades-merge.util.js +2 -2
  37. package/dist/market-data/billing.interface.d.ts +219 -0
  38. package/dist/market-data/billing.interface.js +58 -0
  39. package/dist/market-data/venue-governed.util.d.ts +2 -0
  40. package/dist/market-data/venue-governed.util.js +10 -0
  41. package/dist/market-data/venue.d.ts +122 -0
  42. package/dist/market-data/venue.js +1 -0
  43. package/dist/market-data/venues/index.d.ts +97 -0
  44. package/dist/market-data/venues/index.js +33 -0
  45. package/dist/market-data/venues/opra.contract.copy.json +35 -0
  46. package/dist/market-data/venues/opra.d.ts +70 -0
  47. package/dist/market-data/venues/opra.js +74 -0
  48. package/dist/replay/replayIndicatorRows.d.ts +31 -0
  49. package/dist/replay/replayIndicatorRows.js +117 -0
  50. package/dist/replay/replayLadder.d.ts +85 -0
  51. package/dist/replay/replayLadder.js +388 -0
  52. package/dist/utility/auth/server-clock.util.d.ts +81 -0
  53. package/dist/utility/auth/server-clock.util.js +238 -0
  54. package/dist/utility/chart/builtin-identity.util.d.ts +18 -0
  55. package/dist/utility/chart/builtin-identity.util.js +51 -0
  56. package/dist/utility/chart/cache-alignment.util.d.ts +454 -0
  57. package/dist/utility/chart/cache-alignment.util.js +926 -0
  58. package/dist/utility/chart/chart-data-fetch-generation.util.d.ts +15 -0
  59. package/dist/utility/chart/chart-data-fetch-generation.util.js +22 -0
  60. package/dist/utility/chart/chart-mount-epoch.util.d.ts +5 -0
  61. package/dist/utility/chart/chart-mount-epoch.util.js +29 -0
  62. package/dist/utility/chart/chart-time-domain.util.d.ts +12 -0
  63. package/dist/utility/chart/chart-time-domain.util.js +23 -0
  64. package/dist/utility/chart/color-customization.leaf.d.ts +10 -0
  65. package/dist/utility/chart/color-customization.leaf.js +16 -0
  66. package/dist/utility/chart/date-labelled-interval.leaf.d.ts +15 -0
  67. package/dist/utility/chart/date-labelled-interval.leaf.js +19 -0
  68. package/dist/utility/chart/footprint-tick-grid.util.d.ts +106 -0
  69. package/dist/utility/chart/footprint-tick-grid.util.js +167 -0
  70. package/dist/utility/chart/gesture-timing.leaf.d.ts +29 -0
  71. package/dist/utility/chart/gesture-timing.leaf.js +29 -0
  72. package/dist/utility/chart/governed-contract-coin.util.d.ts +22 -0
  73. package/dist/utility/chart/governed-contract-coin.util.js +39 -0
  74. package/dist/utility/chart/host-bar-placement.util.d.ts +107 -0
  75. package/dist/utility/chart/host-bar-placement.util.js +447 -0
  76. package/dist/utility/chart/index-host-tier.util.d.ts +31 -0
  77. package/dist/utility/chart/index-host-tier.util.js +118 -0
  78. package/dist/utility/chart/index-mode-admission.util.d.ts +34 -0
  79. package/dist/utility/chart/index-mode-admission.util.js +67 -0
  80. package/dist/utility/chart/indicator-error-message.util.d.ts +35 -0
  81. package/dist/utility/chart/indicator-error-message.util.js +44 -0
  82. package/dist/utility/chart/indicator-run-interval.util.d.ts +130 -0
  83. package/dist/utility/chart/indicator-run-interval.util.js +268 -0
  84. package/dist/utility/chart/kscript-apply-fingerprint.util.d.ts +65 -0
  85. package/dist/utility/chart/kscript-apply-fingerprint.util.js +357 -0
  86. package/dist/utility/chart/kscript-chart-flush.leaf.d.ts +22 -0
  87. package/dist/utility/chart/kscript-chart-flush.leaf.js +13 -0
  88. package/dist/utility/chart/kscript-data-interval-restriction.leaf.d.ts +6 -0
  89. package/dist/utility/chart/kscript-data-interval-restriction.leaf.js +27 -0
  90. package/dist/utility/chart/kscript-integration-decision.leaf.d.ts +89 -0
  91. package/dist/utility/chart/kscript-integration-decision.leaf.js +80 -0
  92. package/dist/utility/chart/kscript-live-coalesce.util.d.ts +76 -0
  93. package/dist/utility/chart/kscript-live-coalesce.util.js +156 -0
  94. package/dist/utility/chart/kscript-live-rest-pace.util.d.ts +34 -0
  95. package/dist/utility/chart/kscript-live-rest-pace.util.js +134 -0
  96. package/dist/utility/chart/kscript-live-source-identity.util.d.ts +98 -0
  97. package/dist/utility/chart/kscript-live-source-identity.util.js +121 -0
  98. package/dist/utility/chart/kscript-mounted-plot-set.leaf.d.ts +48 -0
  99. package/dist/utility/chart/kscript-mounted-plot-set.leaf.js +145 -0
  100. package/dist/utility/chart/kscript-perf-tracker.util.d.ts +243 -0
  101. package/dist/utility/chart/kscript-perf-tracker.util.js +522 -0
  102. package/dist/utility/chart/kscript-run-interval-projection.util.d.ts +43 -0
  103. package/dist/utility/chart/kscript-run-interval-projection.util.js +471 -0
  104. package/dist/utility/chart/kscript-run-result-equality.util.d.ts +38 -0
  105. package/dist/utility/chart/kscript-run-result-equality.util.js +89 -0
  106. package/dist/utility/chart/kscript-settings-revision.leaf.d.ts +2 -0
  107. package/dist/utility/chart/kscript-settings-revision.leaf.js +12 -0
  108. package/dist/utility/chart/kscript-source-degrade.leaf.d.ts +63 -0
  109. package/dist/utility/chart/kscript-source-degrade.leaf.js +68 -0
  110. package/dist/utility/chart/kscript-source-retention.util.d.ts +134 -0
  111. package/dist/utility/chart/kscript-source-retention.util.js +218 -0
  112. package/dist/utility/chart/kscript-standin-identity.leaf.d.ts +57 -0
  113. package/dist/utility/chart/kscript-standin-identity.leaf.js +61 -0
  114. package/dist/utility/chart/kscript-titancharts-preparation.util.d.ts +15 -0
  115. package/dist/utility/chart/kscript-titancharts-preparation.util.js +376 -0
  116. package/dist/utility/chart/kscript-titancharts-render-keys.constants.d.ts +9 -0
  117. package/dist/utility/chart/kscript-titancharts-render-keys.constants.js +130 -0
  118. package/dist/utility/chart/kscript-venue-policy.util.d.ts +217 -0
  119. package/dist/utility/chart/kscript-venue-policy.util.js +324 -0
  120. package/dist/utility/chart/live-cadence.util.d.ts +38 -0
  121. package/dist/utility/chart/live-cadence.util.js +37 -0
  122. package/dist/utility/chart/live-feed-series-match.leaf.d.ts +13 -0
  123. package/dist/utility/chart/live-feed-series-match.leaf.js +21 -0
  124. package/dist/utility/chart/local-engine-self-heal-backoff.util.d.ts +46 -0
  125. package/dist/utility/chart/local-engine-self-heal-backoff.util.js +46 -0
  126. package/dist/utility/chart/local-engine-uninit.leaf.d.ts +21 -0
  127. package/dist/utility/chart/local-engine-uninit.leaf.js +22 -0
  128. package/dist/utility/chart/local-kscript-source-revalidation.util.d.ts +62 -0
  129. package/dist/utility/chart/local-kscript-source-revalidation.util.js +123 -0
  130. package/dist/utility/chart/local-kscript-warmup-depth.util.d.ts +214 -0
  131. package/dist/utility/chart/local-kscript-warmup-depth.util.js +376 -0
  132. package/dist/utility/chart/local-technical-script-live-apply-coalescer.util.d.ts +85 -0
  133. package/dist/utility/chart/local-technical-script-live-apply-coalescer.util.js +197 -0
  134. package/dist/utility/chart/local-technical-script-range.leaf.d.ts +72 -0
  135. package/dist/utility/chart/local-technical-script-range.leaf.js +126 -0
  136. package/dist/utility/chart/mixed-mode.util.d.ts +167 -0
  137. package/dist/utility/chart/mixed-mode.util.js +139 -0
  138. package/dist/utility/chart/ohlcv-row-readiness.util.d.ts +36 -0
  139. package/dist/utility/chart/ohlcv-row-readiness.util.js +90 -0
  140. package/dist/utility/chart/opra-user-scripts-gate.util.d.ts +19 -0
  141. package/dist/utility/chart/opra-user-scripts-gate.util.js +32 -0
  142. package/dist/utility/chart/overlay-execution-guard-key.leaf.d.ts +8 -0
  143. package/dist/utility/chart/overlay-execution-guard-key.leaf.js +10 -0
  144. package/dist/utility/chart/price-precision.util.d.ts +40 -0
  145. package/dist/utility/chart/price-precision.util.js +70 -0
  146. package/dist/utility/chart/profile-block-size.util.d.ts +64 -0
  147. package/dist/utility/chart/profile-block-size.util.js +141 -0
  148. package/dist/utility/chart/protected-kscript-degenerate-rows.leaf.d.ts +11 -0
  149. package/dist/utility/chart/protected-kscript-degenerate-rows.leaf.js +29 -0
  150. package/dist/utility/chart/protected-kscript-empty-output.util.d.ts +28 -0
  151. package/dist/utility/chart/protected-kscript-empty-output.util.js +84 -0
  152. package/dist/utility/chart/run-interval-unservable.leaf.d.ts +9 -0
  153. package/dist/utility/chart/run-interval-unservable.leaf.js +20 -0
  154. package/dist/utility/chart/run-interval-warmup.leaf.d.ts +19 -0
  155. package/dist/utility/chart/run-interval-warmup.leaf.js +35 -0
  156. package/dist/utility/chart/titan-constants.pin.d.ts +9 -5
  157. package/dist/utility/chart/titan-constants.pin.js +18 -5
  158. package/dist/utility/chart/warmup-backfill-retry.leaf.d.ts +9 -0
  159. package/dist/utility/chart/warmup-backfill-retry.leaf.js +9 -0
  160. package/dist/utility/chart/window-geometry.leaf.d.ts +119 -0
  161. package/dist/utility/chart/window-geometry.leaf.js +391 -0
  162. package/dist/utility/chart/window-owner.leaf.d.ts +19 -0
  163. package/dist/utility/chart/window-owner.leaf.js +24 -0
  164. package/dist/utility/chart/wrun-bar-session-facts.util.d.ts +11 -2
  165. package/dist/utility/chart/wrun-bar-session-facts.util.js +10 -3
  166. package/dist/utility/chart/wrun-run-result.util.d.ts +5 -1
  167. package/dist/utility/chart/wrun-run-result.util.js +20 -14
  168. package/dist/utility/common/data-processing.util.d.ts +138 -0
  169. package/dist/utility/common/data-processing.util.js +346 -0
  170. package/dist/utility/common/visible-timeout.util.d.ts +13 -4
  171. package/dist/utility/common/visible-timeout.util.js +23 -8
  172. package/dist/utility/exchange-format.leaf.d.ts +1 -0
  173. package/dist/utility/exchange-format.leaf.js +47 -0
  174. package/dist/utility/html-escape.leaf.d.ts +11 -0
  175. package/dist/utility/html-escape.leaf.js +20 -0
  176. package/dist/utility/market-events/earnings-scope.util.d.ts +60 -0
  177. package/dist/utility/market-events/earnings-scope.util.js +92 -0
  178. package/dist/utility/market-events/market-events.util.d.ts +147 -0
  179. package/dist/utility/market-events/market-events.util.js +392 -0
  180. package/dist/utility/market-events/zoned-clock.util.d.ts +1 -0
  181. package/dist/utility/market-events/zoned-clock.util.js +11 -0
  182. package/dist/utility/options/option-venue-disclosure.util.d.ts +43 -0
  183. package/dist/utility/options/option-venue-disclosure.util.js +56 -0
  184. package/dist/utility/scriptEditor/package-semver.util.d.ts +51 -0
  185. package/dist/utility/scriptEditor/package-semver.util.js +120 -0
  186. package/dist/utility/scriptEditor/temp-script-id.util.d.ts +18 -0
  187. package/dist/utility/scriptEditor/temp-script-id.util.js +25 -0
  188. package/dist/utility/symbol-selection/markets-request-from-symbols.leaf.d.ts +20 -0
  189. package/dist/utility/symbol-selection/markets-request-from-symbols.leaf.js +81 -0
  190. package/dist/utility/v2/governed-tier.leaf.d.ts +103 -0
  191. package/dist/utility/v2/governed-tier.leaf.js +113 -0
  192. package/dist/utility/watchlist/import/import-request.leaf.d.ts +10 -0
  193. package/dist/utility/watchlist/import/import-request.leaf.js +10 -0
  194. package/dist/utility/wrun/sources/lanes/option_daily.d.ts +43 -15
  195. package/dist/utility/wrun/sources/lanes/option_daily.js +78 -20
  196. package/dist/utility/wrun/sources/lanes/option_stats_10m.d.ts +14 -10
  197. package/dist/utility/wrun/sources/lanes/option_stats_10m.js +5 -4
  198. package/dist/utility/wrun/sources/lanes/series.js +2 -2
  199. package/dist/utility/wrun/sources/opra-option-lanes.util.d.ts +22 -3
  200. package/dist/utility/wrun/sources/opra-option-lanes.util.js +38 -7
  201. package/dist/utility/wrun/sources/registry.js +31 -1
  202. package/dist/utility/wrun/sources/row-lane-registry.js +5 -5
  203. package/dist/utility/wrun/sources/row-lanes/option_contract_state.d.ts +49 -0
  204. package/dist/utility/wrun/sources/row-lanes/option_contract_state.js +75 -20
  205. package/dist/utility/wrun/sources/row-lanes/option_strikes.d.ts +49 -0
  206. package/dist/utility/wrun/sources/row-lanes/option_strikes.js +57 -47
  207. package/dist/utility/wrun/sources/row-lanes/option_surface.d.ts +36 -4
  208. package/dist/utility/wrun/sources/row-lanes/option_surface.js +6 -12
  209. package/dist/utility/wrun/sources/wrun-poll-lane.types.d.ts +37 -3
  210. package/dist/utility/wrun/sources/wrun-poll-lanes.util.d.ts +128 -2
  211. package/dist/utility/wrun/sources/wrun-poll-lanes.util.js +233 -51
  212. package/dist/utility/wrun/sources/wrun-row-lane.types.d.ts +0 -8
  213. package/dist/utility/wrun/sources/wrun-row-lanes.util.d.ts +26 -24
  214. package/dist/utility/wrun/sources/wrun-row-lanes.util.js +85 -104
  215. package/dist/utility/wrun/wrun-alert-outputs.registry.d.ts +166 -0
  216. package/dist/utility/wrun/wrun-alert-outputs.registry.js +219 -0
  217. package/dist/utility/wrun/wrun-bar-count.util.d.ts +83 -0
  218. package/dist/utility/wrun/wrun-bar-count.util.js +259 -0
  219. package/dist/utility/wrun/wrun-chart-context-names.util.d.ts +84 -0
  220. package/dist/utility/wrun/wrun-chart-context-names.util.js +186 -0
  221. package/dist/utility/wrun/wrun-chart-market-facts.util.d.ts +253 -0
  222. package/dist/utility/wrun/wrun-chart-market-facts.util.js +731 -0
  223. package/dist/utility/wrun/wrun-cloud-opra-stamp.util.d.ts +28 -0
  224. package/dist/utility/wrun/wrun-cloud-opra-stamp.util.js +45 -0
  225. package/dist/utility/wrun/wrun-coin-lane-live.util.d.ts +18 -0
  226. package/dist/utility/wrun/wrun-coin-lane-live.util.js +47 -0
  227. package/dist/utility/wrun/wrun-deadline.util.js +2 -1
  228. package/dist/utility/wrun/wrun-debug-output.util.d.ts +39 -0
  229. package/dist/utility/wrun/wrun-debug-output.util.js +63 -0
  230. package/dist/utility/wrun/wrun-declared-warmup.util.d.ts +113 -0
  231. package/dist/utility/wrun/wrun-declared-warmup.util.js +181 -0
  232. package/dist/utility/wrun/wrun-draft-legend-note.util.d.ts +43 -0
  233. package/dist/utility/wrun/wrun-draft-legend-note.util.js +158 -0
  234. package/dist/utility/wrun/wrun-draft-overlay.util.d.ts +181 -0
  235. package/dist/utility/wrun/wrun-draft-overlay.util.js +357 -0
  236. package/dist/utility/wrun/wrun-draw-skipped.leaf.d.ts +16 -0
  237. package/dist/utility/wrun/wrun-draw-skipped.leaf.js +16 -0
  238. package/dist/utility/wrun/wrun-earnings-facts.util.d.ts +42 -0
  239. package/dist/utility/wrun/wrun-earnings-facts.util.js +131 -0
  240. package/dist/utility/wrun/wrun-first-run-depth.util.d.ts +32 -0
  241. package/dist/utility/wrun/wrun-first-run-depth.util.js +118 -0
  242. package/dist/utility/wrun/wrun-gate-plane-readers.util.d.ts +24 -0
  243. package/dist/utility/wrun/wrun-gate-plane-readers.util.js +31 -0
  244. package/dist/utility/wrun/wrun-held-lanes.util.d.ts +32 -0
  245. package/dist/utility/wrun/wrun-held-lanes.util.js +94 -0
  246. package/dist/utility/wrun/wrun-host-visible-clock.util.d.ts +2 -0
  247. package/dist/utility/wrun/wrun-host-visible-clock.util.js +17 -0
  248. package/dist/utility/wrun/wrun-host.service.d.ts +266 -0
  249. package/dist/utility/wrun/wrun-host.service.js +655 -0
  250. package/dist/utility/wrun/wrun-inert-legend.util.d.ts +33 -0
  251. package/dist/utility/wrun/wrun-inert-legend.util.js +125 -0
  252. package/dist/utility/wrun/wrun-input-requirements.leaf.d.ts +155 -0
  253. package/dist/utility/wrun/wrun-input-requirements.leaf.js +450 -0
  254. package/dist/utility/wrun/wrun-integration-route.util.d.ts +51 -0
  255. package/dist/utility/wrun/wrun-integration-route.util.js +59 -0
  256. package/dist/utility/wrun/wrun-latest-history.leaf.d.ts +8 -0
  257. package/dist/utility/wrun/wrun-latest-history.leaf.js +8 -0
  258. package/dist/utility/wrun/wrun-legend-hover.lazy.d.ts +12 -0
  259. package/dist/utility/wrun/wrun-legend-hover.lazy.js +96 -0
  260. package/dist/utility/wrun/wrun-lifecycle-runtime.util.d.ts +21 -0
  261. package/dist/utility/wrun/wrun-lifecycle-runtime.util.js +21 -0
  262. package/dist/utility/wrun/wrun-live-hidden-hold.util.d.ts +23 -0
  263. package/dist/utility/wrun/wrun-live-hidden-hold.util.js +13 -0
  264. package/dist/utility/wrun/wrun-live-intake.util.d.ts +374 -0
  265. package/dist/utility/wrun/wrun-live-intake.util.js +2027 -0
  266. package/dist/utility/wrun/wrun-live-patch.util.d.ts +116 -0
  267. package/dist/utility/wrun/wrun-live-patch.util.js +523 -0
  268. package/dist/utility/wrun/wrun-live-tick.util.d.ts +619 -0
  269. package/dist/utility/wrun/wrun-live-tick.util.js +4974 -0
  270. package/dist/utility/wrun/wrun-loading-owner.util.d.ts +58 -0
  271. package/dist/utility/wrun/wrun-loading-owner.util.js +89 -0
  272. package/dist/utility/wrun/wrun-official-scope.leaf.d.ts +29 -0
  273. package/dist/utility/wrun/wrun-official-scope.leaf.js +36 -0
  274. package/dist/utility/wrun/wrun-oi-lane.util.d.ts +27 -0
  275. package/dist/utility/wrun/wrun-oi-lane.util.js +42 -0
  276. package/dist/utility/wrun/wrun-opra-stats.leaf.d.ts +29 -10
  277. package/dist/utility/wrun/wrun-opra-stats.leaf.js +29 -10
  278. package/dist/utility/wrun/wrun-options-stop.util.d.ts +52 -0
  279. package/dist/utility/wrun/wrun-options-stop.util.js +123 -0
  280. package/dist/utility/wrun/wrun-overlay-drivers.util.d.ts +719 -0
  281. package/dist/utility/wrun/wrun-overlay-drivers.util.js +1180 -0
  282. package/dist/utility/wrun/wrun-overlay-lifecycle.lazy.d.ts +50 -0
  283. package/dist/utility/wrun/wrun-overlay-lifecycle.lazy.js +131 -0
  284. package/dist/utility/wrun/wrun-overlay-lifecycle.util.d.ts +118 -0
  285. package/dist/utility/wrun/wrun-overlay-lifecycle.util.js +466 -0
  286. package/dist/utility/wrun/wrun-overlay-metadata.util.d.ts +45 -0
  287. package/dist/utility/wrun/wrun-overlay-metadata.util.js +112 -0
  288. package/dist/utility/wrun/wrun-overlay-recovery.util.d.ts +114 -0
  289. package/dist/utility/wrun/wrun-overlay-recovery.util.js +971 -0
  290. package/dist/utility/wrun/wrun-overlay-run.util.d.ts +858 -0
  291. package/dist/utility/wrun/wrun-overlay-run.util.js +11013 -0
  292. package/dist/utility/wrun/wrun-panel-mount.lazy.d.ts +10 -0
  293. package/dist/utility/wrun/wrun-panel-mount.lazy.js +68 -0
  294. package/dist/utility/wrun/wrun-panel-mount.util.d.ts +392 -0
  295. package/dist/utility/wrun/wrun-panel-mount.util.js +2346 -0
  296. package/dist/utility/wrun/wrun-param-map.util.d.ts +19 -4
  297. package/dist/utility/wrun/wrun-param-map.util.js +40 -47
  298. package/dist/utility/wrun/wrun-param-values.util.d.ts +9 -3
  299. package/dist/utility/wrun/wrun-param-values.util.js +5 -5
  300. package/dist/utility/wrun/wrun-pause-dim.util.d.ts +52 -0
  301. package/dist/utility/wrun/wrun-pause-dim.util.js +153 -0
  302. package/dist/utility/wrun/wrun-plot-gate.types.d.ts +23 -0
  303. package/dist/utility/wrun/wrun-plot-gate.types.js +7 -0
  304. package/dist/utility/wrun/wrun-prefix-cohort.util.d.ts +93 -0
  305. package/dist/utility/wrun/wrun-prefix-cohort.util.js +484 -0
  306. package/dist/utility/wrun/wrun-prefix-lanes.util.d.ts +114 -0
  307. package/dist/utility/wrun/wrun-prefix-lanes.util.js +486 -0
  308. package/dist/utility/wrun/wrun-prefix-proof.util.d.ts +317 -0
  309. package/dist/utility/wrun/wrun-prefix-proof.util.js +630 -0
  310. package/dist/utility/wrun/wrun-refusal-surface.util.d.ts +73 -0
  311. package/dist/utility/wrun/wrun-refusal-surface.util.js +380 -0
  312. package/dist/utility/wrun/wrun-refusal-text.util.d.ts +15 -0
  313. package/dist/utility/wrun/wrun-refusal-text.util.js +40 -0
  314. package/dist/utility/wrun/wrun-replay-lane.util.d.ts +139 -0
  315. package/dist/utility/wrun/wrun-replay-lane.util.js +520 -0
  316. package/dist/utility/wrun/wrun-replay-rows.util.d.ts +21 -0
  317. package/dist/utility/wrun/wrun-replay-rows.util.js +172 -0
  318. package/dist/utility/wrun/wrun-row-source-factory.d.ts +53 -0
  319. package/dist/utility/wrun/wrun-row-source-factory.js +435 -0
  320. package/dist/utility/wrun/wrun-run-cells.util.d.ts +36 -0
  321. package/dist/utility/wrun/wrun-run-cells.util.js +46 -0
  322. package/dist/utility/wrun/wrun-run-interval-projection.types.d.ts +14 -0
  323. package/dist/utility/wrun/wrun-run-interval-projection.types.js +1 -0
  324. package/dist/utility/wrun/wrun-run-interval-session.util.d.ts +133 -0
  325. package/dist/utility/wrun/wrun-run-interval-session.util.js +121 -0
  326. package/dist/utility/wrun/wrun-run-interval.util.d.ts +98 -0
  327. package/dist/utility/wrun/wrun-run-interval.util.js +207 -0
  328. package/dist/utility/wrun/wrun-run-retained.util.d.ts +122 -0
  329. package/dist/utility/wrun/wrun-run-retained.util.js +255 -0
  330. package/dist/utility/wrun/wrun-sandbox-row-source.d.ts +184 -0
  331. package/dist/utility/wrun/wrun-sandbox-row-source.js +444 -0
  332. package/dist/utility/wrun/wrun-script-inputs.util.js +4 -4
  333. package/dist/utility/wrun/wrun-series-stream.util.d.ts +86 -0
  334. package/dist/utility/wrun/wrun-series-stream.util.js +537 -0
  335. package/dist/utility/wrun/wrun-sheet-remembered.util.d.ts +21 -0
  336. package/dist/utility/wrun/wrun-sheet-remembered.util.js +36 -0
  337. package/dist/utility/wrun/wrun-signal-sound-reasons.leaf.d.ts +7 -0
  338. package/dist/utility/wrun/wrun-signal-sound-reasons.leaf.js +12 -0
  339. package/dist/utility/wrun/wrun-socket-row-source.js +4 -2
  340. package/dist/utility/wrun/wrun-source-rows.util.d.ts +175 -3
  341. package/dist/utility/wrun/wrun-source-rows.util.js +294 -8
  342. package/dist/utility/wrun/wrun-stats-strip.util.d.ts +46 -0
  343. package/dist/utility/wrun/wrun-stats-strip.util.js +87 -0
  344. package/dist/utility/wrun/wrun-table-chrome.util.d.ts +163 -0
  345. package/dist/utility/wrun/wrun-table-chrome.util.js +557 -0
  346. package/dist/utility/wrun/wrun-text-params.util.d.ts +11 -6
  347. package/dist/utility/wrun/wrun-text-params.util.js +19 -30
  348. package/dist/utility/wrun/wrun-transient-rerun.util.d.ts +64 -0
  349. package/dist/utility/wrun/wrun-transient-rerun.util.js +317 -0
  350. package/dist/utility/wrun/wrun-twin-lookback.util.d.ts +10 -0
  351. package/dist/utility/wrun/wrun-twin-lookback.util.js +43 -0
  352. package/dist/utility/wrun/wrun-warmup-head-store.util.d.ts +41 -0
  353. package/dist/utility/wrun/wrun-warmup-head-store.util.js +120 -0
  354. package/dist/utility/wrun-alert-params.leaf.d.ts +24 -0
  355. package/dist/utility/wrun-alert-params.leaf.js +24 -0
  356. package/dist/utils/replay/replay-buffer-math.d.ts +148 -0
  357. package/dist/utils/replay/replay-buffer-math.js +684 -0
  358. package/dist/workers/wrun/wrun-abi-host.d.ts +190 -0
  359. package/dist/workers/wrun/wrun-abi-host.js +1201 -0
  360. package/dist/workers/wrun/wrun-engine-handler.d.ts +37 -0
  361. package/dist/workers/wrun/wrun-engine-handler.js +211 -0
  362. package/package.json +3 -3
@@ -0,0 +1,2346 @@
1
+ /**
2
+ * The child-overlay mount of a browser-run Indicator (wrun): every panel,
3
+ * docked level, inset, price canvas (heatmap, profile, matrix) and lower pane
4
+ * a run result declares becomes an engine overlay owned by the parent
5
+ * Indicator, mounted here and torn down with it.
6
+ *
7
+ * The mount door (WRUN-STYLE 2.5, 3.5.4): colour WORDS ride the run result
8
+ * unresolved (`theme.*` tokens included) and resolve here against the chart's
9
+ * palette (`wrunColorThemeOf`), so a theme switch or a display-timezone
10
+ * change re-resolves every mounted child without a rerun
11
+ * (`retranslateWrunChildOverlays`, X13). Each mounted child keeps its last
12
+ * unresolved input beside its engine config for exactly that.
13
+ *
14
+ * Panels (g1): the frame translates through om-panel.util with the context
15
+ * this file builds (theme, the chart's price digits, the display timezone);
16
+ * the pane's name, caption, maximize button, stats row, formatter hooks and
17
+ * height share are set here (SC08 SC09 SC10 SC17 SC37); `place: "side"`
18
+ * mounts below the chart like every panel (the window is a side panel's
19
+ * opened form, Kyle 2026-10-04; the engine's side strip stays for `dock:
20
+ * "side"` canvases). Docked levels (g2) take
21
+ * their settings and rows from wrun-levels-child.util's mount helpers and
22
+ * keep their hover rows under the child id (DL-hover). Price canvases (g6)
23
+ * take their config from wrun-canvases.util: heatmap and profile children
24
+ * are row-backed on ticks (the newest row through `liveUpdateData`, every
25
+ * row since the bar they last painted on a tick that added bars; a
26
+ * windowed run's heatmap merges its rows inside the run's history window,
27
+ * a prefix run's through a landing prepared ahead and committed with no
28
+ * await: prepareWrunHeatmapWindowLanding),
29
+ * matrices frame-backed like levels; a heatmap takes the viewer's
30
+ * Sensitivity at this door (`rescaleWrunHeatmapChildren` re-picks the mounted
31
+ * bounds with no run). Batched marks (WRUN-BATCHED-MARKS: marks, spans and
32
+ * rays children) are row-backed like heatmaps: a tick merges every row it
33
+ * re-evaluated, row by row; a windowed run lands inside its window; the engine
34
+ * gate refuses a kind the chart cannot draw by name; their own cell budget
35
+ * charges every seam (wrun-batched-marks.util). The series child (the lower pane, or a
36
+ * pane pinned over the candles, g5 OT08 OT20 OT24) rides the shared kScript
37
+ * adapter and prints its legend through the legend helpers (OT27 OT28 OT29
38
+ * OT32). Every child's eye follows the parent's, except where the reader
39
+ * moved a child's own eye (an inset's): that flip stands (syncChildVisibility).
40
+ */
41
+ import { wrunChartHostEnv } from '../../host-env.js';
42
+ import { isDateLabelledBarInterval } from '../chart/date-labelled-interval.leaf.js';
43
+ import { KSCRIPT_LEGEND_VALUE_INK, kScriptLegendEntries, kScriptLegendLineFormat, kScriptLegendLineFormatOptions, kScriptLegendLines, kScriptLegendLineSwatchAt, kScriptLegendLineValueAt, kScriptLegendSlotCells, padKScriptLegendSlots, } from '../chart/kscript-legend-entries.util.js';
44
+ import { panelGridHeight, refreshPanelOverlayInPlace, samePanelPane, translatePanelToEngine, } from '../chart/om-panel.util.js';
45
+ import { isWrunWindowOwner } from '../chart/window-owner.leaf.js';
46
+ import { planWindowWeights, reconcileWindowOwnerGeometry, savedWindowSplit, tableRowCountOf, } from '../chart/window-geometry.leaf.js';
47
+ import { wrunLegendName } from '../chart/wrun-legend-name.util.js';
48
+ import { wrunResultLegendColors, wrunSeriesChildId, } from '../chart/wrun-run-result.util.js';
49
+ import { budgetWrunBatchedRetained, budgetWrunBatchedRows, commitWrunBatchedPlan, currentWrunBatchedPlan, forgetWrunBatchedCells, isWrunBatchedMarksKind, noteWrunBatchedRowsCut, planWrunBatchedMerged, restoreWrunBatchedLedger, snapshotWrunBatchedLedger, wrunBatchedChargeOf, wrunBatchedChildConfig, wrunBatchedChildrenOverShare, wrunBatchedSiblingsToRebalance, } from './wrun-batched-marks.util.js';
50
+ import { forgetWrunCanvasReadout, keepWrunHeatmapScaleSample, rememberWrunCanvasReadout, wrunCanvasChildConfig, wrunHeatmapSensitivityBounds, wrunPlainCanvasRow, } from './wrun-canvases.util.js';
51
+ import { wrunChildHiddenRowKey } from './wrun-child-overlay-id.util.js';
52
+ import { wrunHeatmapSensitivitySetting, wrunHeatmapSensitivityValue } from './wrun-color-settings.util.js';
53
+ import { budgetWrunHeatmapRetained, budgetWrunHeatmapRows, commitWrunHeatmapPlan, currentWrunHeatmapPlan, planWrunHeatmapMerged, restoreWrunHeatmapLedger, snapshotWrunHeatmapLedger, wrunHeatmapCellLayoutOf, wrunHeatmapChildrenOverShare, wrunHeatmapSiblingsToRebalance, } from './wrun-heatmap-cell-budget.util.js';
54
+ import { wrunChildOverlayParentId } from './wrun-child-overlay-id.util.js';
55
+ import { forgetWrunLevelsHoverRows, rememberWrunLevelsHoverRows, wrunLevelsChildId, wrunLevelsMountData, wrunLevelsMountSettings, } from './wrun-levels-child.util.js';
56
+ import { wrunPaneChildMountSettings } from './wrun-output-style.util.js';
57
+ import { formatWrunLegendValue, WRUN_PANE_DEFAULT_DIGITS, wrunBuiltinTwin, wrunBuiltinTwinYLabel, wrunPaneYLabel, } from './wrun-pane-format.util.js';
58
+ import { wrunPanelChrome } from './wrun-panel-style.util.js';
59
+ import { reapplyWrunPauseDim } from './wrun-pause-dim.util.js';
60
+ import { resolveWrunColorWord, wrunColorThemeOf } from './wrun-style-words.util.js';
61
+ import { bindWrunPanelMountRuntime } from './wrun-panel-mount.lazy.js';
62
+ const chartChildren = new WeakMap();
63
+ /** The legend controls a child pane's own row hides: the eye (the parent's
64
+ * eye governs its panes, syncChildVisibility) and the pane moves, which
65
+ * belong to the parent. The gear and the close button stay, so the row
66
+ * offers what the owner's row does: the store routes a child id's settings
67
+ * to the owning Indicator's dialog (`openIndicatorSettings`, the gear, a
68
+ * double-click and the "..." menu's Settings alike) and its removal to the
69
+ * owning Indicator (wrun-child-overlay-id.util, `wrunChildOverlayParentId`).
70
+ * QA 200: Absorption's lower pane had no gear and no Settings in its menu. */
71
+ const CHILD_LEGEND_CONTROLS = {
72
+ hideVisibilityBtn: true,
73
+ hideMergePaneBtn: true,
74
+ hidePinToChartBtn: true,
75
+ };
76
+ /**
77
+ * Every child kind and its legend row, decided here once (the legend guard in
78
+ * the mount spec mounts one of each kind listed). The `own` kinds are the
79
+ * allowlist that keeps a row by design: a panel (a side panel too) and a
80
+ * series pane own a pane, a title and controls, and an inset's row carries its
81
+ * latest value. Every other kind folds into the parent's row: `childConfig`
82
+ * sends it `hideLegend: true`, so the engine builds no row, the parent's row
83
+ * carries the Indicator and the parent's eye still governs the child
84
+ * (`syncChildVisibility`). A kind missing here gets no row either, and the
85
+ * typecheck refuses the table until it is decided. Each kind used to opt out
86
+ * on its own, and the levels child that forgot printed a second row titled
87
+ * "gex_by_strike".
88
+ */
89
+ export const WRUN_CHILD_LEGEND_ROW = {
90
+ panel: 'own',
91
+ series: 'own',
92
+ inset: 'own',
93
+ levels: 'parent',
94
+ heatmap: 'parent',
95
+ profile: 'parent',
96
+ matrix: 'parent',
97
+ marks: 'parent',
98
+ spans: 'parent',
99
+ rays: 'parent',
100
+ };
101
+ /** The pane height panels and the series lower pane share below the chart. */
102
+ const CHILD_PANE_GRID_HEIGHT = 0.22;
103
+ /** The pane words a series child carries at the meta level (OT24: the
104
+ * pinned onchart flags), apart from its settings. */
105
+ const SERIES_META_KEYS = new Set([
106
+ 'isPinnedToChart',
107
+ 'showIndependentYAxis',
108
+ 'isIndependentSubsetRange',
109
+ 'hidePriceScale',
110
+ 'shouldAdjustMainGridRange',
111
+ ]);
112
+ /** The child kinds a tick carries: insets and the lower pane take the tick's
113
+ * rows in place, heatmaps and profiles the newest row, batched marks every
114
+ * row the tick re-evaluated; panels, levels and matrices are frame-backed
115
+ * and wait for a tick that carries frames. */
116
+ const ROW_BACKED_KINDS = new Set([
117
+ 'inset',
118
+ 'series',
119
+ 'heatmap',
120
+ 'profile',
121
+ 'marks',
122
+ 'spans',
123
+ 'rays',
124
+ ]);
125
+ function overlayPresent(tc, id) {
126
+ return tc.metadata.some((meta) => meta.id === id);
127
+ }
128
+ /** The price canvases (g6: heatmap, profile and matrix children) and the
129
+ * batched marks drawn over the price pane like them (marks, spans, rays):
130
+ * no price marker, a readout registered when the config is built. */
131
+ function isCanvasChild(child) {
132
+ return child.kind === 'heatmap' || child.kind === 'profile' || child.kind === 'matrix' || isBatchedChild(child);
133
+ }
134
+ /** A batched child (WRUN-BATCHED-MARKS): marks, spans or rays. */
135
+ function isBatchedChild(child) {
136
+ return isWrunBatchedMarksKind(child.kind);
137
+ }
138
+ /** The engine keeps the config's `settings` object as the meta's and rewrites
139
+ * `gridHeight` to the fraction it carved, so the mounted set keeps the intent
140
+ * and the engine gets its own copy: the next run's same-pane check and the
141
+ * in-place settings diff both read what was asked, never what was carved. */
142
+ function addChild(tc, config) {
143
+ wrunChartHostEnv().chart.registerLoadedPacks(tc);
144
+ tc.addOverlay({ ...config, settings: { ...config.settings } });
145
+ }
146
+ /** Mount a child and register what the hover surfaces read off it: a levels
147
+ * child's hover rows (DL-hover, colour words resolved against the palette),
148
+ * or none when the child keeps none (a replacement that turned hover off
149
+ * leaves no rows of its predecessor behind); a canvas readout is
150
+ * registered by its config builder. */
151
+ function installChild(tc, child, theme) {
152
+ addChild(tc, child.config);
153
+ if (child.input.kind !== 'levels')
154
+ return;
155
+ if (child.input.hover !== undefined)
156
+ rememberWrunLevelsHoverRows(child.config.id, child.input.hover, theme);
157
+ else
158
+ forgetWrunLevelsHoverRows(child.config.id);
159
+ }
160
+ function removeChild(tc, id) {
161
+ if (overlayPresent(tc, id))
162
+ tc.removeOverlay(id);
163
+ }
164
+ /** Drop what a child registered for the hover surfaces (the symmetric
165
+ * retract of installChild and the canvas config builder). */
166
+ function forgetChildExtras(id, kind) {
167
+ if (kind === 'levels')
168
+ forgetWrunLevelsHoverRows(id);
169
+ if (kind === 'heatmap' || kind === 'profile' || kind === 'matrix' || isWrunBatchedMarksKind(kind)) {
170
+ forgetWrunCanvasReadout(id);
171
+ }
172
+ }
173
+ /** A canvas config registers its hover readout when it is BUILT, before the
174
+ * pack preflight settles and before the engine took the child: after a run
175
+ * that failed part way, point the registry back at what is mounted (the
176
+ * readout of every mounted canvas, none for a built one that never
177
+ * mounted). A batched child's readout carries its record text on the input
178
+ * (wrun-batched-marks.util), so this restores its hover card whole. */
179
+ function syncCanvasReadouts(mounted, built) {
180
+ for (const { input, config } of built) {
181
+ if (isCanvasChild(input) && !mounted.has(config.id))
182
+ forgetWrunCanvasReadout(config.id);
183
+ }
184
+ for (const [id, { input }] of mounted) {
185
+ if (!isCanvasChild(input))
186
+ continue;
187
+ if (input.readout !== undefined)
188
+ rememberWrunCanvasReadout(id, input.readout);
189
+ else
190
+ forgetWrunCanvasReadout(id);
191
+ }
192
+ }
193
+ /** Whether the chart is in focus mode: false for a chart without a canvas (titan's own reader throws there) or one
194
+ * that answers nothing. */
195
+ function isFocusModeOn(tc) {
196
+ if (tc.isDestroyed || !tc.canvasChartController?.focusMode)
197
+ return false;
198
+ try {
199
+ return tc.isFocusModeActive?.() === true;
200
+ }
201
+ catch {
202
+ return false;
203
+ }
204
+ }
205
+ /** The pane a chart holds expanded (titan's focus mode), or null when none is. */
206
+ function focusedPaneOf(tc) {
207
+ return isFocusModeOn(tc) ? (tc.canvasChartController?.focusMode?.focusedGridId ?? null) : null;
208
+ }
209
+ /**
210
+ * Keep the reader's expanded pane through a pass that takes children off the chart: titan's removeOverlay ends focus
211
+ * mode whatever pane it removes, so the pane the chart held before the pass is entered again after it, when it is
212
+ * still mounted and the focus is off. A pane the pass took away stays exited (there is nothing to expand). Runs on
213
+ * every pass that retires or rebuilds a child: a later run, the retranslate, an unmount that leaves the chart.
214
+ */
215
+ function keepFocusedPane(tc, pass) {
216
+ const focused = focusedPaneOf(tc);
217
+ try {
218
+ return pass();
219
+ }
220
+ finally {
221
+ if (focused !== null && !tc.isDestroyed && !isFocusModeOn(tc)) {
222
+ if (focused === 'main' || overlayPresent(tc, focused))
223
+ tc.enterFocusMode?.(focused);
224
+ }
225
+ }
226
+ }
227
+ /** Remove a child from the chart; its registrations go with it unless the
228
+ * same id is about to be mounted again (a replaced child keeps the rows and
229
+ * readout its new config already registered). */
230
+ function retireChild(tc, id, kind, replaced) {
231
+ if (!tc.isDestroyed)
232
+ removeChild(tc, id);
233
+ if (replaced)
234
+ return;
235
+ forgetChildExtras(id, kind);
236
+ // A batched child's cells leave its Indicator's ledger with it (the "Cells capped" row follows).
237
+ const overlayId = isWrunBatchedMarksKind(kind) ? wrunChildOverlayParentId(id) : null;
238
+ if (overlayId !== null)
239
+ forgetWrunBatchedCells(tc, overlayId, id);
240
+ }
241
+ /** The child pane's close button removes the OWNING Indicator (the store
242
+ * maps the child id to its parent), so its tooltip names the Indicator. */
243
+ function childLegendControls(parentName) {
244
+ return parentName ? { ...CHILD_LEGEND_CONTROLS, legendRemoveLabel: `Remove ${parentName}` } : CHILD_LEGEND_CONTROLS;
245
+ }
246
+ /** Every colour word in a settings bag (strings and string lists) resolved
247
+ * against the palette; anything that is not a token passes unchanged. */
248
+ function resolveSettingsColorWords(settings, theme) {
249
+ const resolved = {};
250
+ for (const [key, value] of Object.entries(settings)) {
251
+ if (typeof value === 'string')
252
+ resolved[key] = resolveWrunColorWord(value, theme);
253
+ else if (Array.isArray(value) && value.every((entry) => typeof entry === 'string')) {
254
+ resolved[key] = value.map((entry) => resolveWrunColorWord(entry, theme));
255
+ }
256
+ else
257
+ resolved[key] = value;
258
+ }
259
+ return resolved;
260
+ }
261
+ /** The chart's display timezone offset for the panel translation (SC37).
262
+ * A chart mounted before the user store exists (a bare test chart, a boot
263
+ * path) reads as UTC, the engine's own default. */
264
+ function displayTimezoneOffsetMs() {
265
+ try {
266
+ return wrunChartHostEnv().user.chartDisplayTimezoneOffsetMs();
267
+ }
268
+ catch {
269
+ return 0;
270
+ }
271
+ }
272
+ /** The user's theme name, the key of the TPO letter scheme a profile child
273
+ * without its own palette takes (PT-tpo, as the native TPO control reads
274
+ * it). A chart mounted before the user store exists reads the default
275
+ * scheme. */
276
+ function userThemeMode() {
277
+ try {
278
+ const mode = wrunChartHostEnv().user.themeMode();
279
+ return typeof mode === 'string' && mode !== '' ? mode : undefined;
280
+ }
281
+ catch {
282
+ return undefined;
283
+ }
284
+ }
285
+ /** A panel child's config (g1): the frame translated with the chart's
286
+ * theme, price digits and display timezone (SC08 SC16 SC37); the run's
287
+ * title and caption on the legend as text (SC17: titan renders both as text); the maximize
288
+ * button and stats row (SC10); the declared height share (SC09); every
289
+ * panel below the chart at its carved height, `place: "side"` included (a
290
+ * side panel's right-side home is the window, never a strip that narrows
291
+ * the candles; `width_px` / `height_px` therefore size nothing here). */
292
+ function panelChildConfig(child, ctx) {
293
+ const translateContext = {
294
+ theme: ctx.theme,
295
+ ...(ctx.priceDigits !== undefined ? { priceDigits: ctx.priceDigits() } : {}),
296
+ timezoneOffsetMs: ctx.timezoneOffsetMs,
297
+ };
298
+ const translated = translatePanelToEngine(child.frame, translateContext);
299
+ const { panel, rows, chrome } = child.frame;
300
+ const caption = chrome?.caption;
301
+ const id = `${ctx.overlayId}::panel:${child.name}`;
302
+ // A table owns no value axis and a rich line (every chrome but box: the
303
+ // numeric curve, or grid / none on a time, category or stacked line) draws
304
+ // its own left axis (C4): neither pane echoes the chart's prices in its
305
+ // scale cell. A box line and every other kind keep it (every panel mounts
306
+ // below, `place: "side"` included).
307
+ const ownAxis = panel.kind === 'table' || (panel.kind === 'line' && wrunPanelChrome(panel) !== 'box');
308
+ return {
309
+ id,
310
+ name: translated.name,
311
+ plot: translated.plot,
312
+ type: 'offchart',
313
+ interval: ctx.interval,
314
+ data: translated.rows,
315
+ ...(ownAxis ? { hidePriceScale: true } : {}),
316
+ ...translated.hooks,
317
+ settings: {
318
+ ...translated.settings,
319
+ ...childLegendControls(ctx.parentName),
320
+ // The pane this one lands right above (C6): a settings key the engine
321
+ // reads once at addOverlay, like keepAtBottom (alpha.1018 and up; an
322
+ // older engine, an anchor not mounted yet or an onchart one appends).
323
+ // A pane-layout key for the in-place refresh (PANEL_PANE_LAYOUT_KEYS),
324
+ // so a later run's anchor never churns a mounted pane.
325
+ ...(ctx.anchorPaneId !== undefined ? { insertBeforePaneId: ctx.anchorPaneId } : {}),
326
+ ...(panel.maximize === true ? { showMaximizeBtn: true } : {}),
327
+ ...(panel.stats_row === true ? { showStatsRow: true } : {}),
328
+ // The function form skips the engine's $token expansion of a title.
329
+ ...(caption !== undefined ? { customTitle: () => ` · ${caption}` } : {}),
330
+ // A pane below the chart takes the declared share, else the table's row
331
+ // height or the shared weight; on a window the plan's weight.
332
+ gridHeight: ctx.planned?.get(id) ?? panelGridHeight(panel, rows.length, ctx.chartHeightPx),
333
+ },
334
+ };
335
+ }
336
+ /** The lower pane (or a pane pinned over the candles, OT24): an offchart
337
+ * kScript container the shared adapter fills from the child's result
338
+ * (nested plots, styled rows, drawings, the engine-native legend), mounted
339
+ * ONCE and re-integrated in place on every run, so its pane, scale and
340
+ * legend survive ticks and reruns. */
341
+ function seriesChildConfig(child, ctx) {
342
+ const { tc, overlayId } = ctx;
343
+ const id = wrunSeriesChildId(overlayId, child.name);
344
+ // The pane's legend palette (its collapsed chip): its own result's
345
+ // legend-line colours, the way the parent mounts
346
+ // with the sheet's (wrunSheetOverlayPalette); empty mounts none.
347
+ const palette = wrunResultLegendColors(child.result.outputs);
348
+ const parentSettings = tc.metadata.find((meta) => meta.id === overlayId)?.settings;
349
+ // A proven twin's lower pane (the parent's `builtinTwinOf`) reads like
350
+ // its built-in: the built-in's axis label (none but a volume-based one's)
351
+ // and its legend rule, never the wrun pane's.
352
+ const builtinTwin = wrunBuiltinTwin(parentSettings);
353
+ const getYLabel = builtinTwin === undefined ? wrunPaneYLabel(() => tc, id) : wrunBuiltinTwinYLabel(builtinTwin);
354
+ // The pane words (OT20 OT24): the pinned onchart flags live on the meta,
355
+ // the height share in the settings.
356
+ const paneWords = wrunPaneChildMountSettings(child.result.pane);
357
+ const metaWords = {};
358
+ const settingWords = {};
359
+ for (const [key, value] of Object.entries(paneWords)) {
360
+ if (SERIES_META_KEYS.has(key))
361
+ metaWords[key] = value;
362
+ else
363
+ settingWords[key] = value;
364
+ }
365
+ const onPrice = child.result.pane?.place === 'price';
366
+ return {
367
+ id,
368
+ name: child.result.define.title,
369
+ plot: 'spline',
370
+ type: onPrice ? 'onchart' : 'offchart',
371
+ interval: ctx.interval,
372
+ data: [],
373
+ isIndependentSubsetRange: true,
374
+ showIndependentYAxis: true,
375
+ ...metaWords,
376
+ // The pane's axis: K/M/B from 1K, its own digits below (the
377
+ // volume-based technical scripts' path), never the main precision.
378
+ ...(getYLabel !== undefined ? { getYLabel } : {}),
379
+ initLegendText: () => wrunSeriesChildLegendSlots(palette),
380
+ getLegendText: wrunSeriesChildLegendText(builtinTwin, ctx.priceDigits),
381
+ settings: {
382
+ ...childLegendControls(ctx.parentName),
383
+ // Below the chart: the shared weight, or on a window the plan's.
384
+ ...(onPrice ? {} : { gridHeight: ctx.planned?.get(id) ?? CHILD_PANE_GRID_HEIGHT }),
385
+ ...settingWords,
386
+ ...(palette.length > 0 ? { colors: palette } : {}),
387
+ ...seriesChildChartSettings(parentSettings),
388
+ },
389
+ };
390
+ }
391
+ /** The chart switches the settings dialog keeps on a package overlay: Plot settings (Hide weekends,
392
+ * Interpolation) and Price marker (Price line, Axis label, Name label). The parent's container takes
393
+ * them through its save, but a series child is a container of its own, so it carries a copy, from its
394
+ * mount and after every save; without one its pane's plots ignored every switch. */
395
+ const SERIES_CHILD_CHART_KEYS = [
396
+ 'hideWeekends',
397
+ 'preventGapInterpolation',
398
+ 'showLastValueLine',
399
+ 'showYAxisPriceLabel',
400
+ 'showYAxisNameLabel',
401
+ ];
402
+ function seriesChildChartSettings(settings) {
403
+ const chartSettings = {};
404
+ for (const key of SERIES_CHILD_CHART_KEYS) {
405
+ if (typeof settings?.[key] === 'boolean')
406
+ chartSettings[key] = settings[key];
407
+ }
408
+ return chartSettings;
409
+ }
410
+ /** A save of the package overlay: every mounted series child takes the chart switches it carries,
411
+ * its container through the engine's settings door and its plots' price markers through the
412
+ * adapter's own stamp (the one the parent's plots take). */
413
+ export function syncWrunSeriesChildChartSettings(tc, overlayId, settings) {
414
+ const chartSettings = seriesChildChartSettings(settings);
415
+ if (Object.keys(chartSettings).length === 0)
416
+ return;
417
+ for (const meta of tc.metadata) {
418
+ if (!isSeriesChildId(meta.id) || !meta.id.startsWith(`${overlayId}::`))
419
+ continue;
420
+ tc.updateSettings?.(meta.id, chartSettings);
421
+ wrunChartHostEnv().chart.syncPriceMarkers({ metadata: [...tc.metadata], renderService: tc.renderService }, meta.id, chartSettings);
422
+ }
423
+ }
424
+ /** A docked levels child (g2): the door settings and rows with every colour
425
+ * word resolved, `beside` and `panel: "lower"` mapped to engine ids
426
+ * (wrun-levels-child.util's mount helpers). The engine's docked door keeps
427
+ * only the sender fields and its boolean legend flags, and warns about
428
+ * anything else: the control keys stay unsent. `hideLegend` is one of those
429
+ * flags from the titan release that adds it to `DOCKED_LEGEND_FLAGS` (an
430
+ * older door drops it and warns once per overlay); `childConfig` sends it,
431
+ * as it does for every kind outside the legend allowlist (WRUN_CHILD_LEGEND_ROW).
432
+ * The name, read as words, titles the child wherever the engine still lists
433
+ * it. */
434
+ function levelsChildConfig(child, ctx) {
435
+ return {
436
+ id: wrunLevelsChildId(ctx.overlayId, child.name),
437
+ // The legend row reads the level's name in words; the id keeps the name.
438
+ name: wrunLegendName(child.name),
439
+ plot: 'levels',
440
+ type: 'onchart',
441
+ interval: ctx.interval,
442
+ data: wrunLevelsMountData(child, ctx.theme),
443
+ settings: wrunLevelsMountSettings(child, ctx.theme, {
444
+ overlayId: ctx.overlayId,
445
+ parentOffchart: ctx.parentOffchart,
446
+ }),
447
+ };
448
+ }
449
+ /** A price canvas child (g6): the config wrun-canvases.util builds (the
450
+ * child id, the engine plot, settings resolved against the theme, a
451
+ * heatmap's bounds at the viewer's Sensitivity, a TPO's default letter
452
+ * scheme from the user's theme name, the profile extractor, the live merge,
453
+ * a matrix's rows re-resolved). */
454
+ function canvasChildConfig(child, ctx) {
455
+ const sensitivity = child.kind === 'heatmap' ? ctx.heatmapSensitivity(child.name) : undefined;
456
+ const config = wrunCanvasChildConfig(child, {
457
+ overlayId: ctx.overlayId,
458
+ theme: ctx.theme,
459
+ ...(ctx.themeMode !== undefined ? { themeMode: ctx.themeMode } : {}),
460
+ ...(sensitivity !== undefined ? { heatmapSensitivity: sensitivity } : {}),
461
+ formatters: ctx.formatters,
462
+ });
463
+ return {
464
+ id: config.id,
465
+ name: child.name,
466
+ plot: config.plot,
467
+ type: config.type,
468
+ interval: ctx.interval,
469
+ // The engine wire rows (book, profile, grid and matrix rows are arrays).
470
+ data: (config.data ?? child.data),
471
+ ...(config.extractors !== undefined ? { extractors: config.extractors } : {}),
472
+ ...(config.mergeLiveDataPoint !== undefined ? { mergeLiveDataPoint: config.mergeLiveDataPoint } : {}),
473
+ ...(config.tailOnly === true ? { tailOnly: true } : {}),
474
+ settings: config.settings,
475
+ };
476
+ }
477
+ /** A batched child (WRUN-BATCHED-MARKS): the config wrun-batched-marks.util
478
+ * builds (the id, the kind as the engine plot, the section look with every
479
+ * colour resolved against the theme, the live merge), its rows the engine
480
+ * wire `[ts, ...fields]`. Its rows are its own subset of the bars (budget
481
+ * trims, live appends), so it mounts as an independent subset: without the
482
+ * flag titan's band and sliver narrowing and its drawn-rows pass read the
483
+ * main series' rows for it, and a partial pass redrew the whole window. */
484
+ function batchedChildConfig(child, ctx) {
485
+ // A timed record's `{{start}}` and `{{end}}` print in the display timezone the time axis labels the chart's bars in.
486
+ const config = wrunBatchedChildConfig(child, {
487
+ overlayId: ctx.overlayId,
488
+ theme: ctx.theme,
489
+ timeOffsetMs: isDateLabelledBarInterval(ctx.interval) ? 0 : ctx.timezoneOffsetMs,
490
+ });
491
+ return {
492
+ id: config.id,
493
+ name: child.name,
494
+ plot: config.plot,
495
+ type: config.type,
496
+ interval: ctx.interval,
497
+ data: child.data,
498
+ isIndependentSubsetRange: true,
499
+ mergeLiveDataPoint: config.mergeLiveDataPoint,
500
+ ...(config.tailOnly === true ? { tailOnly: true } : {}),
501
+ settings: config.settings,
502
+ };
503
+ }
504
+ /** True only for the kinds the legend allowlist marks `own`
505
+ * (WRUN_CHILD_LEGEND_ROW): any other kind, an unlisted one included,
506
+ * builds no legend row. */
507
+ function keepsOwnLegendRow(kind) {
508
+ return WRUN_CHILD_LEGEND_ROW[kind] === 'own';
509
+ }
510
+ /** A price canvas (heatmap, profile, matrix) is no series with a last value:
511
+ * titan tags every onchart overlay on the price axis unless its settings say
512
+ * false, which printed the first bucket price of a heatmap's last row as an
513
+ * amber tag (B37 B43). No axis tag, no name riding it, no last-value line. */
514
+ const CANVAS_PRICE_MARKERS_OFF = {
515
+ showYAxisPriceLabel: false,
516
+ showYAxisNameLabel: false,
517
+ showLastValueLine: false,
518
+ };
519
+ /** The engine config of a child, the one door every config passes before
520
+ * the engine takes it (a mount, the restore after a failed run, a
521
+ * retranslate): the kind's own config, `hideLegend: true` for every kind
522
+ * outside the legend allowlist (WRUN_CHILD_LEGEND_ROW), so no kind needs
523
+ * to remember it, and the price markers off on a price canvas
524
+ * (CANVAS_PRICE_MARKERS_OFF). */
525
+ function childConfig(child, ctx) {
526
+ const config = childKindConfig(child, ctx);
527
+ if (keepsOwnLegendRow(child.kind))
528
+ return config;
529
+ return {
530
+ ...config,
531
+ settings: { ...config.settings, hideLegend: true, ...(isCanvasChild(child) ? CANVAS_PRICE_MARKERS_OFF : {}) },
532
+ };
533
+ }
534
+ /** A child's config by its kind: colour words resolved at this door, the
535
+ * mount's own keys set (the unresolved input stays on the mounted record
536
+ * for a retranslate). */
537
+ function childKindConfig(child, ctx) {
538
+ switch (child.kind) {
539
+ case 'panel':
540
+ return panelChildConfig(child, ctx);
541
+ case 'series':
542
+ return seriesChildConfig(child, ctx);
543
+ case 'levels':
544
+ return levelsChildConfig(child, ctx);
545
+ case 'heatmap':
546
+ case 'profile':
547
+ case 'matrix':
548
+ return canvasChildConfig(child, ctx);
549
+ case 'marks':
550
+ case 'spans':
551
+ case 'rays':
552
+ return batchedChildConfig(child, ctx);
553
+ case 'inset':
554
+ // The docked door keeps the inset sender fields only (a colour word
555
+ // among them resolves here); no legend-control keys, so its row keeps
556
+ // the door's own eye, gear and X (the gear opens the owner's dialog, the
557
+ // eye the reader moves stands: syncChildVisibility). Its legend row
558
+ // stays (it carries the latest value), titled with the name in words,
559
+ // and is never rebuilt while the strip stays the same strip (sameInset).
560
+ return {
561
+ id: `${ctx.overlayId}::inset:${child.name}`,
562
+ name: wrunLegendName(child.name),
563
+ plot: 'inset',
564
+ type: 'onchart',
565
+ interval: ctx.interval,
566
+ data: child.data.map((row) => [...row]),
567
+ settings: resolveSettingsColorWords(child.settings, ctx.theme),
568
+ };
569
+ }
570
+ }
571
+ /** The legend's own O / H / L / C markers (OT28), read per call so a
572
+ * locale switch prints the new words. */
573
+ function legendOhlcLabels() {
574
+ const { t } = wrunChartHostEnv();
575
+ return {
576
+ open: t('chart.legend.open'),
577
+ high: t('chart.legend.high'),
578
+ low: t('chart.legend.low'),
579
+ close: t('chart.legend.close'),
580
+ };
581
+ }
582
+ /** The lower pane's legend readout, the parent's own rule brought to its
583
+ * child: every value line of the pane's nested plots at the hovered bar,
584
+ * named by its output's `labels` column (kScriptLegendEntries, the same
585
+ * entries the technical-script control prints for the parent) and printed
586
+ * by its output's declared `format` word and companions (OT32), else by the
587
+ * lower-pane legend rule (K/M/B from 1K, the built-in legend decimals below,
588
+ * never the axis step: formatWrunLegendValue); "price" prints at the chart's
589
+ * price digits (OT29, the provider). A candle group reads its four values
590
+ * after the legend's O / H / L / C markers (OT28); every dot shows the
591
+ * colour the hovered bar is drawn in (OT27). A single line keeps the
592
+ * unlabelled single-slot readout, like the parent. An output with
593
+ * `legend: false` is never a line (kScriptLegendLines). A proven twin's pane
594
+ * (`builtinTwin`) prints by its built-in's legend rule instead. */
595
+ export function wrunSeriesChildLegendText(builtinTwin, priceDigits) {
596
+ return (point, meta) => {
597
+ const placement = {
598
+ onPrice: false,
599
+ priceDigits: priceDigits?.() ?? WRUN_PANE_DEFAULT_DIGITS,
600
+ builtinTwin,
601
+ };
602
+ const format = (value, line) => formatWrunLegendValue(value, placement, kScriptLegendLineFormat(meta, line), kScriptLegendLineFormatOptions(meta, line));
603
+ const entries = kScriptLegendEntries(point, meta, format, { ohlcLabels: legendOhlcLabels() });
604
+ if (entries.length > 1)
605
+ return padKScriptLegendSlots(entries);
606
+ const [line] = kScriptLegendLines(meta);
607
+ if (line === undefined)
608
+ return padKScriptLegendSlots([]);
609
+ const ts = Array.isArray(point) && typeof point[0] === 'number' ? point[0] : undefined;
610
+ const value = kScriptLegendLineValueAt(line, ts, { meta });
611
+ return padKScriptLegendSlots([
612
+ {
613
+ id: 'value',
614
+ text: value === undefined ? '-' : format(value, line),
615
+ label: '',
616
+ color: KSCRIPT_LEGEND_VALUE_INK,
617
+ swatch: kScriptLegendLineSwatchAt(meta, line, ts),
618
+ },
619
+ ]);
620
+ };
621
+ }
622
+ /** The lower pane's static legend: the slot pool the dynamic readout
623
+ * addresses (one labelled span per slot, born empty, the parent's rule:
624
+ * titan creates legend spans only from this list and drops updates for ids
625
+ * it never created). The palette now rides each update's swatch, so the
626
+ * slots start in the value ink; the argument stays for the callers. */
627
+ export function wrunSeriesChildLegendSlots(_palette) {
628
+ return kScriptLegendSlotCells();
629
+ }
630
+ /** The series child's overlay id (`<parent>::series:<name>`), defined by the
631
+ * adapter (the visibility apply reads it there) and re-exported here. */
632
+ export { wrunSeriesChildId };
633
+ function isSeriesChildId(id) {
634
+ return id.includes('::series:');
635
+ }
636
+ /** True while the reader keeps a child hidden from its own legend row: the
637
+ * visibility door keeps that eye on the owner's settings
638
+ * (wrunChildHiddenRowKey), so it survives remounts and reloads. */
639
+ function hiddenByReader(parent, childId) {
640
+ const key = wrunChildHiddenRowKey(childId);
641
+ return key !== null && parent.settings?.[key] === true;
642
+ }
643
+ /** The parent's eye onto its children. When it moved, every child follows: a
644
+ * hidden Indicator leaves no pane, dock or canvas behind, and shown again
645
+ * each child shows unless the reader hid it on its own row. Otherwise only
646
+ * the children this pass added to the engine (`added`: back through
647
+ * addOverlay visible) take it; a child that stayed keeps the eye it has, so
648
+ * the flip a reader made on its row (titan toggles the child itself) stands
649
+ * through live blocks, reruns and the parent's other updates (QA 214). */
650
+ function syncChildVisibility(tc, parent, state, added = []) {
651
+ if (tc.isDestroyed || typeof tc.changeVisibilityOverlay !== 'function')
652
+ return;
653
+ const ownerVisible = parent.isHidden !== true;
654
+ const moved = state.ownerVisible !== ownerVisible;
655
+ state.ownerVisible = ownerVisible;
656
+ for (const id of moved ? [...state.children.keys()] : added) {
657
+ const child = tc.metadata.find((meta) => meta.id === id);
658
+ const visible = ownerVisible && !hiddenByReader(parent, id);
659
+ if (child && (child.isHidden === true) === visible)
660
+ tc.changeVisibilityOverlay(id, visible);
661
+ }
662
+ }
663
+ /** Apply a series child's result to its mounted container through the shared
664
+ * adapter: the mounted-row refresh on a tick (the kScript live ladder's
665
+ * first rung), the full metadata apply on a run, on a fresh mount, or when
666
+ * the refresh could not apply. A parent that ran at another interval hands
667
+ * its projection (the run's stamp, the chart and its venue), so the lower
668
+ * pane lands on the chart's bars like the parent's rows. Throws the
669
+ * adapter's diagnostics, so a failed child apply fails the run exactly like
670
+ * a failed pack. */
671
+ function integrateSeriesChild(tc, childId, result, mode, projection) {
672
+ const meta = tc.metadata.find((candidate) => candidate.id === childId);
673
+ if (!meta)
674
+ throw new Error(`wrun series child '${childId}' is not mounted`);
675
+ if (mode === 'tick') {
676
+ const refresh = wrunChartHostEnv().chart.refreshMountedRows({
677
+ tc: tc,
678
+ indicatorId: childId,
679
+ meta: meta,
680
+ runResult: result,
681
+ ...projection,
682
+ });
683
+ if (refresh.ok && refresh.applied)
684
+ return;
685
+ }
686
+ const integration = wrunChartHostEnv().chart.integrate({
687
+ tc: tc,
688
+ indicatorId: childId,
689
+ runResult: result,
690
+ mode: 'metadata',
691
+ meta: meta,
692
+ ...projection,
693
+ });
694
+ if (!integration.ok) {
695
+ throw new Error(`wrun lower pane integration failed: ${integration.diagnostics.map((d) => `${d.code}: ${d.message}`).join('; ')}`);
696
+ }
697
+ }
698
+ /** The same pane, the shared rule (om-panel.util), for a panel and for the
699
+ * series child alike: side, species, axis ownership, chrome and the carved
700
+ * height the child was mounted with. When the height is not the mount's to
701
+ * carve (`heightHeld`) only the other fields decide: on a window the height
702
+ * is the plan's and moves in place (reconcileWindowOwnerGeometry at the end
703
+ * of the mount), so a plan that shifts when a sibling arrives never re-mounts
704
+ * the panes that stay; a child a host's plan names on a normal cell holds the
705
+ * height its reader dragged (WrunMountCell.planned), which the engine pane
706
+ * already has, so a moved remembered height never re-mounts it either. */
707
+ function samePane(mounted, next, heightHeld = false) {
708
+ if (mounted.type !== next.type)
709
+ return false;
710
+ const shape = (config) => ({
711
+ plot: config.plot,
712
+ hidePriceScale: config.hidePriceScale,
713
+ gridHeight: heightHeld ? 0 : Number(config.settings.gridHeight ?? CHILD_PANE_GRID_HEIGHT),
714
+ ...(typeof config.settings.chromeStyle === 'string' ? { chromeStyle: config.settings.chromeStyle } : {}),
715
+ });
716
+ return samePanelPane(shape(mounted), shape(next));
717
+ }
718
+ /** The panes a window mount lays out, for the planner: the owner's own pane
719
+ * when it is mounted offchart (a lower-only package), the run's panel
720
+ * children (side panels included: they stack in the window) and series
721
+ * children that mount below the chart (a pane pinned over the candles
722
+ * carves nothing), and the mounted children a frameless tick keeps. */
723
+ function windowPanesOfMount(parent, overlayId, children, kept) {
724
+ const panes = [];
725
+ if (parent.type === 'offchart' && parent.isPaneHidden !== true)
726
+ panes.push({ id: overlayId, kind: 'time' });
727
+ const seen = new Set();
728
+ for (const child of children) {
729
+ if (child.kind === 'panel') {
730
+ const id = `${overlayId}::panel:${child.name}`;
731
+ seen.add(id);
732
+ panes.push(child.frame.panel.kind === 'table'
733
+ ? { id, kind: 'table', rows: child.frame.rows.length }
734
+ : { id, kind: 'chart' });
735
+ }
736
+ else if (child.kind === 'series') {
737
+ if (child.result.pane?.place === 'price')
738
+ continue;
739
+ const id = wrunSeriesChildId(overlayId, child.name);
740
+ seen.add(id);
741
+ panes.push({ id, kind: 'time' });
742
+ }
743
+ }
744
+ for (const config of kept) {
745
+ if (seen.has(config.id) || config.type !== 'offchart')
746
+ continue;
747
+ if (isSeriesChildId(config.id))
748
+ panes.push({ id: config.id, kind: 'time' });
749
+ else if (config.plot === 'table')
750
+ panes.push({ id: config.id, kind: 'table', rows: tableRowCountOf(config) });
751
+ else
752
+ panes.push({ id: config.id, kind: 'chart' });
753
+ }
754
+ return panes;
755
+ }
756
+ /** A row-backed canvas keeps its overlay across runs while it stays the
757
+ * same canvas: the same engine plot over the same cell layout (a heatmap's
758
+ * `cellLayout`, a profile's `variant`) and, on a batched child, the same row
759
+ * geometry (`slots` and `stride`: a row of another width is another canvas). */
760
+ function sameCanvas(mounted, next) {
761
+ const layout = (config) => [
762
+ config.plot,
763
+ config.settings.cellLayout ?? '',
764
+ config.settings.variant ?? '',
765
+ config.settings.slots ?? '',
766
+ config.settings.stride ?? '',
767
+ ]
768
+ .map(String)
769
+ .join('|');
770
+ return layout(mounted) === layout(next);
771
+ }
772
+ /** The inset keys the docked door lays a strip out by. */
773
+ const INSET_STRIP_KEYS = ['dock', 'height_px', 'shape'];
774
+ /** An inset keeps its overlay across ticks and runs while it stays the same
775
+ * strip (the same dock, height and shape): its rows and colours move in
776
+ * place, so its legend row (the latest value, the eye, the gear, the X) is
777
+ * never rebuilt under the reader's cursor (QA 214: an inset re-added on
778
+ * every live block ate the clicks on its row). Another strip mounts again. */
779
+ function sameInset(mounted, next) {
780
+ return INSET_STRIP_KEYS.every((key) => Object.is(mounted.settings[key], next.settings[key]));
781
+ }
782
+ /** Refresh a mounted panel child from the new run through the shared
783
+ * in-place path (om-panel.util): the pane keeps its place in the stack; the
784
+ * run's title and formatter hooks follow (R13: a bag without a hook
785
+ * deletes the mounted one). */
786
+ function refreshPanelChild(tc, mounted, next) {
787
+ const hooks = {
788
+ ...(next.formatDomainValue !== undefined ? { formatDomainValue: next.formatDomainValue } : {}),
789
+ ...(next.getYLabel !== undefined ? { getYLabel: next.getYLabel } : {}),
790
+ };
791
+ refreshPanelOverlayInPlace(tc, next.id, { data: next.data, settings: next.settings, name: next.name, hooks }, mounted.settings);
792
+ }
793
+ /** Refresh a mounted row-backed child in place (a canvas that stays the same
794
+ * canvas on a full run or a moved window, an inset that stays the same
795
+ * strip on any pass): the settings move onto the engine's meta (the keys the
796
+ * mount set and the run dropped go), then the rows swap through the engine's
797
+ * own update path; the overlay keeps its place, its GL cells and its legend
798
+ * row. */
799
+ function refreshChildInPlace(tc, mounted, next) {
800
+ const meta = tc.metadata.find((candidate) => candidate.id === next.id);
801
+ if (!meta)
802
+ throw new Error(`wrun child '${next.id}' is not mounted`);
803
+ const settings = (meta.settings ??= {});
804
+ for (const key of Object.keys(mounted.settings)) {
805
+ if (!(key in next.settings))
806
+ delete settings[key];
807
+ }
808
+ Object.assign(settings, next.settings);
809
+ if (typeof tc.updateData === 'function') {
810
+ tc.updateData(next.id, next.data, { shouldResetRange: false });
811
+ return;
812
+ }
813
+ meta.rawData = next.data;
814
+ meta.data = next.data;
815
+ }
816
+ /** A tick's rows for a mounted row-backed canvas through the engine's live
817
+ * merge (the forming row replaced, a newer one appended): the newest row, or,
818
+ * on a tick that added bars (`fromTs`, the bar the canvases last painted),
819
+ * every row from the one holding that bar on, oldest first
820
+ * (`liveCanvasRows`), so each bar keeps its column, a roll's closed bar its
821
+ * final row included. An engine
822
+ * without the merge takes the rows whole, unless they are a heatmap tail: a
823
+ * tail would replace the canvas's history. A heatmap's record then follows
824
+ * the rows the engine holds (`adoptMergedHeatmapRows`, or the rows handed
825
+ * whole) and its retained rows answer to the cell budget
826
+ * (`budgetLiveHeatmap`). */
827
+ function liveUpdateCanvasChild(tc, config, fromTs) {
828
+ if (config.data[config.data.length - 1] === undefined)
829
+ return;
830
+ if (typeof tc.liveUpdateData === 'function') {
831
+ for (const row of liveCanvasRows(config.data, fromTs))
832
+ tc.liveUpdateData(config.id, row);
833
+ adoptMergedHeatmapRows(tc, config.id);
834
+ }
835
+ else if (config.tailOnly !== true) {
836
+ tc.updateData?.(config.id, config.data, { shouldResetRange: false });
837
+ const record = mountedHeatmapRecord(tc, config.id);
838
+ if (record !== undefined)
839
+ keepHeatmapRows(record, config.data);
840
+ }
841
+ budgetLiveHeatmap(tc, config);
842
+ }
843
+ /** The rows a live merge hands a canvas, oldest first: the newest alone, or (`fromTs`) the row holding that bar
844
+ * (the newest at or before it: the bar's own row, or a profile's period) and every row after it, so a period the
845
+ * tick closed lands too. Rows come in time order; the newest is always among them. */
846
+ function liveCanvasRows(rows, fromTs) {
847
+ let from = rows.length - 1;
848
+ if (fromTs !== undefined) {
849
+ while (from > 0 && (rowTs(rows[from]) ?? Number.NEGATIVE_INFINITY) > fromTs)
850
+ from -= 1;
851
+ }
852
+ return rows.slice(from);
853
+ }
854
+ /**
855
+ * A mounted heatmap's record holds the rows the mount last meant the engine to hold (its intended
856
+ * input: what a retranslate rebuilds from and what a trim is cut from), never the engine's rows read
857
+ * right after an `updateData`: titan queues an overlay's replacement while a gesture is live and
858
+ * keeps its own array when an update proves identical, so its rows then are not the ones asked for.
859
+ * The record of the child `childId` names, when it is a heatmap.
860
+ */
861
+ function mountedHeatmapRecord(tc, childId) {
862
+ const overlayId = wrunChildOverlayParentId(childId);
863
+ const record = overlayId === null ? undefined : chartChildren.get(tc)?.get(overlayId)?.children.get(childId);
864
+ return record?.input.kind === 'heatmap' ? record : undefined;
865
+ }
866
+ /** A heatmap (or batched) record takes `rows` as its intended input, its config and its unresolved
867
+ * input alike. */
868
+ function keepHeatmapRows(record, rows) {
869
+ if (record.config.data === rows)
870
+ return;
871
+ record.config = { ...record.config, data: rows };
872
+ if (record.input.kind === 'heatmap')
873
+ record.input = { ...record.input, data: rows };
874
+ else if (isBatchedChild(record.input))
875
+ record.input = { ...record.input, data: rows };
876
+ }
877
+ /** After an actual live merge the engine's rows are the ones it adopted: titan lands every
878
+ * replacement it queued for the overlay before it merges. The heatmap's record points at them on
879
+ * every merge, a merge that trims nothing included, so the ticks after it land in the record's own
880
+ * array and a retranslate rebuilds what the engine draws. */
881
+ function adoptMergedHeatmapRows(tc, childId) {
882
+ const record = mountedHeatmapRecord(tc, childId);
883
+ if (record === undefined)
884
+ return;
885
+ const meta = tc.metadata.find((candidate) => candidate.id === childId);
886
+ const adopted = meta?.rawData ?? meta?.data;
887
+ if (Array.isArray(adopted))
888
+ keepHeatmapRows(record, adopted);
889
+ }
890
+ /**
891
+ * The cell budget at a seam that hands a heatmap child its rows in full (the first install, the
892
+ * full run's replace, the retranslation; WRUN-COST-GUARD U4): over the child's share of the
893
+ * Indicator's cell cap the oldest bars are dropped before the engine takes the rows, and the
894
+ * child's record (the unresolved input a retranslate rebuilds from, and the config) points at the
895
+ * rows the engine holds, so the live merges land in the record's own array as before. A mounted
896
+ * sibling the new demand pushed over its share drops its oldest bars too. Any other child passes.
897
+ * A retranslation (`rebuild`) hands back the record's rows, which are what the allowance left and
898
+ * never what the child asked for: they are counted as retained rows with no growth, so the ledger
899
+ * keeps the child's demand and the "Cells capped" row its numbers (they are trimmed again only when
900
+ * the allowance shrank meanwhile). A history-window merge budgets through its own landing
901
+ * (`landHeatmapWindow`).
902
+ */
903
+ function budgetHeatmapChild(tc, overlayId, child, seam = 'run') {
904
+ if (child.input.kind !== 'heatmap' || child.config.tailOnly === true)
905
+ return;
906
+ const held = heldByMount(tc, overlayId);
907
+ const layout = wrunHeatmapCellLayoutOf(child.config.settings);
908
+ const id = child.config.id;
909
+ const rows = seam === 'rebuild'
910
+ ? (budgetWrunHeatmapRetained(tc, overlayId, id, layout, child.config.data, held) ?? child.config.data)
911
+ : budgetWrunHeatmapRows(tc, overlayId, id, layout, child.config.data, held);
912
+ if (rows !== child.config.data) {
913
+ child.config.data = rows;
914
+ child.input = { ...child.input, data: rows };
915
+ }
916
+ for (const sibling of wrunHeatmapChildrenOverShare(tc, overlayId, child.config.id, held)) {
917
+ budgetMountedHeatmap(tc, overlayId, sibling);
918
+ }
919
+ }
920
+ /** The children the Indicator's mount holds a record for (a child about to be installed is one). */
921
+ function heldByMount(tc, overlayId) {
922
+ return (childId) => chartChildren.get(tc)?.get(overlayId)?.children.has(childId) === true;
923
+ }
924
+ /** The cell budget after a live merge into a mounted heatmap (the engine's history plus the bar a
925
+ * tick appended). The append's growth shrinks its siblings' shares (the water-filling the full
926
+ * seams apply): while the Indicator's mounted cells pass the cap, a sibling now over its share
927
+ * drops its oldest bars too, also one this tick already merged. */
928
+ function budgetLiveHeatmap(tc, config) {
929
+ const overlayId = wrunChildOverlayParentId(config.id);
930
+ if (config.plot !== 'heatmapCells' || overlayId === null)
931
+ return;
932
+ budgetMountedHeatmap(tc, overlayId, config.id);
933
+ for (const sibling of wrunHeatmapSiblingsToRebalance(tc, overlayId, config.id, heldByMount(tc, overlayId))) {
934
+ budgetMountedHeatmap(tc, overlayId, sibling);
935
+ }
936
+ }
937
+ /**
938
+ * A mounted heatmap's retained rows counted again: past its share the oldest bars are dropped
939
+ * through the engine's row swap (titan's `updateData` keeps the shorter array as its history). The
940
+ * rows counted are the child's record, the intended input (`mountedHeatmapRecord`), never the
941
+ * engine's own: a replacement handed earlier may still wait in titan's queue. The record then holds
942
+ * the trimmed rows, so the next trim and a retranslate start from them.
943
+ */
944
+ function budgetMountedHeatmap(tc, overlayId, childId) {
945
+ const record = mountedHeatmapRecord(tc, childId);
946
+ if (record === undefined || !overlayPresent(tc, childId))
947
+ return;
948
+ const layout = wrunHeatmapCellLayoutOf(record.config.settings);
949
+ const retained = record.config.data;
950
+ const rows = budgetWrunHeatmapRetained(tc, overlayId, childId, layout, retained, heldByMount(tc, overlayId));
951
+ if (rows === null)
952
+ return;
953
+ tc.updateData?.(childId, rows, { shouldResetRange: false });
954
+ keepHeatmapRows(record, rows);
955
+ }
956
+ function isBatchedRecord(record) {
957
+ return record !== undefined && isBatchedChild(record.input);
958
+ }
959
+ /** The record of the batched child `childId` names, when it is one. */
960
+ function mountedBatchedRecord(tc, childId) {
961
+ const overlayId = wrunChildOverlayParentId(childId);
962
+ const record = overlayId === null ? undefined : chartChildren.get(tc)?.get(overlayId)?.children.get(childId);
963
+ return isBatchedRecord(record) ? record : undefined;
964
+ }
965
+ /**
966
+ * The cell budget at a seam that hands a batched child its rows in full (WRUN-BATCHED-MARKS): the
967
+ * first install and a full run's replace charge the rows the build kept under its share (a replace
968
+ * keeps the hard allowance: the old copy goes at the swap and is never charged), and a
969
+ * retranslation's rebuild counts the record's rows as retained with no growth (it removes the old
970
+ * copy before it adds the new one). The child's record and config point at the rows the engine is
971
+ * handed; a sibling the demand pushed over its share drops its oldest bars too. Any other child
972
+ * passes. A history-window merge budgets through its own landing (`landHeatmapWindow`).
973
+ */
974
+ function budgetBatchedChild(tc, overlayId, child, seam = 'run') {
975
+ if (!isBatchedChild(child.input) || child.config.tailOnly === true)
976
+ return;
977
+ const held = heldByMount(tc, overlayId);
978
+ const charge = wrunBatchedChargeOf(child.config.settings);
979
+ const id = child.config.id;
980
+ const rows = seam === 'rebuild'
981
+ ? (budgetWrunBatchedRetained(tc, overlayId, id, child.config.data, charge, held) ?? child.config.data)
982
+ : budgetWrunBatchedRows(tc, overlayId, id, child.config.data, charge, {
983
+ ...(child.input.budget !== undefined ? { built: child.input.budget } : {}),
984
+ isMounted: held,
985
+ });
986
+ if (rows !== child.config.data) {
987
+ child.config.data = rows;
988
+ child.input = { ...child.input, data: rows };
989
+ }
990
+ for (const sibling of wrunBatchedChildrenOverShare(tc, overlayId, id, held)) {
991
+ budgetMountedBatched(tc, overlayId, sibling);
992
+ }
993
+ }
994
+ /** A mounted batched child's retained rows counted again (its record, the rows the mount means the
995
+ * engine to hold): past its share the oldest bars are dropped through the engine's row swap down to
996
+ * the watermark, and the record holds the trimmed rows. */
997
+ function budgetMountedBatched(tc, overlayId, childId) {
998
+ const record = mountedBatchedRecord(tc, childId);
999
+ if (record === undefined || !overlayPresent(tc, childId))
1000
+ return;
1001
+ const charge = wrunBatchedChargeOf(record.config.settings);
1002
+ const held = heldByMount(tc, overlayId);
1003
+ const rows = budgetWrunBatchedRetained(tc, overlayId, childId, record.config.data, charge, held);
1004
+ if (rows === null)
1005
+ return;
1006
+ tc.updateData?.(childId, rows, { shouldResetRange: false });
1007
+ keepHeatmapRows(record, rows);
1008
+ }
1009
+ /** The cell budget after a live merge into a mounted batched child: the child counted again, and
1010
+ * while the Indicator's batched cells pass the cap, a sibling now over its share trimmed too. */
1011
+ function budgetLiveBatched(tc, childId) {
1012
+ const overlayId = wrunChildOverlayParentId(childId);
1013
+ if (overlayId === null)
1014
+ return;
1015
+ budgetMountedBatched(tc, overlayId, childId);
1016
+ for (const sibling of wrunBatchedSiblingsToRebalance(tc, overlayId, childId, heldByMount(tc, overlayId))) {
1017
+ budgetMountedBatched(tc, overlayId, sibling);
1018
+ }
1019
+ }
1020
+ /**
1021
+ * The changed tail of a pass merged into a mounted batched child, row by row (the live tick's
1022
+ * contract): every row of the pass at or after the newest row the child's record holds (the bar the
1023
+ * engine holds as its forming bar), found walking back from the pass's newest row, so a tick costs
1024
+ * its tail and never the history. Each row goes through the engine's live merge in timestamp order:
1025
+ * the first replaces the bar the engine holds as its newest (the previous forming bar on a roll),
1026
+ * each newer one appends; an all-NaN row clears its bar's records. The record then follows the rows
1027
+ * the engine adopted (an engine without the live merge takes the merged rows whole) and the cell
1028
+ * budget counts them again. A child holding no rows takes none (the engine merges no live row into an
1029
+ * empty overlay): the tick asks a whole window for it instead (wrun-live-tick.util).
1030
+ */
1031
+ function mergeBatchedChangedRows(tc, record, config) {
1032
+ const held = record.config.data;
1033
+ const newestTs = rowTs(held[held.length - 1]);
1034
+ if (newestTs === undefined)
1035
+ return;
1036
+ const pass = config.data;
1037
+ let from = pass.length;
1038
+ while (from > 0) {
1039
+ const ts = rowTs(pass[from - 1]);
1040
+ if (ts === undefined || ts < newestTs)
1041
+ break;
1042
+ from -= 1;
1043
+ }
1044
+ if (from === pass.length)
1045
+ return;
1046
+ if (typeof tc.liveUpdateData === 'function') {
1047
+ for (let at = from; at < pass.length; at += 1)
1048
+ tc.liveUpdateData(config.id, pass[at]);
1049
+ const meta = tc.metadata.find((candidate) => candidate.id === config.id);
1050
+ const adopted = meta?.rawData ?? meta?.data;
1051
+ if (Array.isArray(adopted))
1052
+ keepHeatmapRows(record, adopted);
1053
+ }
1054
+ else {
1055
+ const firstTs = rowTs(pass[from]);
1056
+ let keep = held.length;
1057
+ while (keep > 0 && (rowTs(held[keep - 1]) ?? Number.NEGATIVE_INFINITY) >= firstTs)
1058
+ keep -= 1;
1059
+ const merged = [...held.slice(0, keep), ...pass.slice(from)];
1060
+ tc.updateData?.(config.id, merged, { shouldResetRange: false });
1061
+ keepHeatmapRows(record, merged);
1062
+ }
1063
+ budgetLiveBatched(tc, config.id);
1064
+ }
1065
+ /** Why the engine gate refuses a batched child, null when the chart draws it: its pack failed to
1066
+ * load or to register on this chart (`pack-failed`), or after the pack settled the engine has no
1067
+ * renderer for the kind (`old-engine`: titan's `hasPlotRenderer` is also false for a known type no
1068
+ * pack registered, so it is read only after the await and the registration). */
1069
+ function batchedGateCause(tc, plot, packs) {
1070
+ if (packs !== undefined && packs.failed.length > 0)
1071
+ return 'pack-failed';
1072
+ wrunChartHostEnv().chart.registerLoadedPacks(tc);
1073
+ if (packs !== undefined &&
1074
+ typeof tc.hasFeaturePack === 'function' &&
1075
+ packs.loaded.some((name) => tc.hasFeaturePack?.(name) !== true)) {
1076
+ return 'pack-failed';
1077
+ }
1078
+ return typeof tc.hasPlotRenderer === 'function' && tc.hasPlotRenderer(plot) ? null : 'old-engine';
1079
+ }
1080
+ /**
1081
+ * True while the engine gate refuses the batched child `childId` of `overlayId` (the last pass that
1082
+ * judged it): a child the chart cannot draw is never mounted, so the live tick leaves it out of its
1083
+ * changed-tail decision (wrun-live-tick.util) instead of rebuilding every section's whole window on
1084
+ * every tick for as long as the refusal holds. A tick still carries its tail and the gate judges it
1085
+ * again: one the chart draws again stops reading as refused, and the next tick mounts it. A layout
1086
+ * refusal (a section or a retained record newer than this chart) is not the tail's to lift: it holds
1087
+ * until a full build (a run, a reseed, a whole-window tick) judges the child again.
1088
+ */
1089
+ export function isWrunBatchedChildRefused(tc, overlayId, childId) {
1090
+ return chartChildren.get(tc)?.get(overlayId)?.gateRefused?.has(childId) === true;
1091
+ }
1092
+ /** A row's time (its first cell), undefined for anything else. */
1093
+ function rowTs(row) {
1094
+ return Array.isArray(row) && typeof row[0] === 'number' && Number.isFinite(row[0]) ? row[0] : undefined;
1095
+ }
1096
+ /** True when a tick's canvas rows overlap the mounted rows (the tick's oldest
1097
+ * row is no newer than the mounted newest), so the newest row is the only
1098
+ * change; a sliding lane buffer that drops its oldest row still overlaps. A
1099
+ * window that rolled past every mounted row (a developing profile's session
1100
+ * changed) or that cannot be read takes the full row swap instead. */
1101
+ function sameDataWindow(mounted, next) {
1102
+ const mountedNewest = rowTs(mounted.data[mounted.data.length - 1]);
1103
+ const nextOldest = rowTs(next.data[0]);
1104
+ return mountedNewest !== undefined && nextOldest !== undefined && nextOldest <= mountedNewest;
1105
+ }
1106
+ /**
1107
+ * A mounted heatmap's rows with a windowed run's rows landed inside `window`: the mounted rows outside
1108
+ * the inclusive window stay, the pass's rows replace the window's contents (a mounted timestamp the
1109
+ * pass lacks there is deleted, an empty pass empties the window, a pass row at a mounted timestamp
1110
+ * wins), in timestamp order. A row with no finite timestamp has no place and is dropped. The rows that
1111
+ * stay are the mounted row objects themselves, never copies (C3: the suffix a prefix lands in front of is
1112
+ * untouched). Mounted rows and pass rows that each come in timestamp order (the engine's rows, a run's
1113
+ * rows) merge in one pass; anything else is sorted, stably, into the same order the merge gives.
1114
+ */
1115
+ function heatmapRowsWithWindow(mounted, pass, window) {
1116
+ const passRows = [];
1117
+ const passTs = [];
1118
+ const passTimes = new Set();
1119
+ let passOrdered = true;
1120
+ for (const row of pass) {
1121
+ const ts = rowTs(row);
1122
+ if (ts === undefined)
1123
+ continue;
1124
+ if (passTs.length > 0 && ts < passTs[passTs.length - 1])
1125
+ passOrdered = false;
1126
+ passRows.push(row);
1127
+ passTs.push(ts);
1128
+ passTimes.add(ts);
1129
+ }
1130
+ const keptRows = [];
1131
+ const keptTs = [];
1132
+ let keptOrdered = true;
1133
+ for (const row of mounted) {
1134
+ const ts = rowTs(row);
1135
+ if (ts === undefined || !(ts < window.fromMs || ts > window.toMs) || passTimes.has(ts))
1136
+ continue;
1137
+ if (keptTs.length > 0 && ts < keptTs[keptTs.length - 1])
1138
+ keptOrdered = false;
1139
+ keptRows.push(row);
1140
+ keptTs.push(ts);
1141
+ }
1142
+ const total = keptRows.length + passRows.length;
1143
+ const rows = [];
1144
+ const fromPass = new Uint8Array(total);
1145
+ if (passOrdered && keptOrdered) {
1146
+ // A kept row and a pass row never share a timestamp, so taking the older head each step is the
1147
+ // order a stable sort of the kept rows followed by the pass rows gives.
1148
+ let kept = 0;
1149
+ let landed = 0;
1150
+ while (rows.length < total) {
1151
+ if (landed < passRows.length && (kept >= keptRows.length || passTs[landed] < keptTs[kept])) {
1152
+ fromPass[rows.length] = 1;
1153
+ rows.push(passRows[landed++]);
1154
+ }
1155
+ else
1156
+ rows.push(keptRows[kept++]);
1157
+ }
1158
+ return { rows, fromPass, passRows: passRows.length };
1159
+ }
1160
+ const order = Array.from({ length: total }, (_, at) => at);
1161
+ const tsAt = (at) => (at < keptRows.length ? keptTs[at] : passTs[at - keptRows.length]);
1162
+ order.sort((a, b) => tsAt(a) - tsAt(b));
1163
+ for (const at of order) {
1164
+ if (at >= keptRows.length)
1165
+ fromPass[rows.length] = 1;
1166
+ rows.push(at < keptRows.length ? keptRows[at] : passRows[at - keptRows.length]);
1167
+ }
1168
+ return { rows, fromPass, passRows: passRows.length };
1169
+ }
1170
+ function isHeatmapRecord(record) {
1171
+ return record?.input.kind === 'heatmap';
1172
+ }
1173
+ function isWindowRecord(record) {
1174
+ return isHeatmapRecord(record) || isBatchedRecord(record);
1175
+ }
1176
+ /** The merge of a pass into a mounted heatmap's or batched child's window and its budget, planned from the
1177
+ * record's rows (the rows the mount means the engine to hold, a trim titan still queues included), writing
1178
+ * nothing. */
1179
+ function planHeatmapWindow(tc, overlayId, record, pass, window) {
1180
+ const base = record.config.data;
1181
+ const merged = heatmapRowsWithWindow(base, pass, window);
1182
+ const childId = record.config.id;
1183
+ const held = heldByMount(tc, overlayId);
1184
+ const budget = isBatchedRecord(record)
1185
+ ? {
1186
+ family: 'batched',
1187
+ plan: planWrunBatchedMerged(tc, overlayId, childId, merged.rows, wrunBatchedChargeOf(record.config.settings), held),
1188
+ }
1189
+ : {
1190
+ family: 'heatmap',
1191
+ plan: planWrunHeatmapMerged(tc, overlayId, childId, wrunHeatmapCellLayoutOf(record.config.settings), merged.rows, held),
1192
+ };
1193
+ return {
1194
+ childId,
1195
+ pass,
1196
+ window,
1197
+ base,
1198
+ baseLength: base.length,
1199
+ baseNewest: base[base.length - 1],
1200
+ merged,
1201
+ budget,
1202
+ };
1203
+ }
1204
+ /** The rows a window budget hands the engine. */
1205
+ function windowBudgetRows(budget) {
1206
+ return budget.plan.rows;
1207
+ }
1208
+ /** The record still holds exactly the rows a plan merged into: the same array, neither grown nor its newest
1209
+ * row replaced since. */
1210
+ function holdsPlannedRows(record, plan) {
1211
+ const rows = record.config.data;
1212
+ return rows === plan.base && rows.length === plan.baseLength && rows[rows.length - 1] === plan.baseNewest;
1213
+ }
1214
+ /** No sibling waits on a landing of its own (a mount pass lands one child at a time). */
1215
+ const NO_DEFERRED_SIBLINGS = new Set();
1216
+ /**
1217
+ * Land a planned window into its mounted heatmap, synchronously: the budget planned again when a sibling's
1218
+ * landing moved the ledger since, the kept rows through the engine's own row swap with the record's settings
1219
+ * (a windowed landing keeps the colour scale the canvas was drawn with, its Sensitivity sample too; only a full
1220
+ * run samples again), then the record and the ledger, then a sibling the growth pushed over its share trimmed,
1221
+ * unless it is `deferred`: a sibling whose own landing of the same run is still to commit is cut to its share
1222
+ * by that commit, from its merged rows (cut here, it would lose bars its landing could not bring back).
1223
+ * Nothing is recorded when the engine refuses the rows. Returns the record now held.
1224
+ */
1225
+ function landHeatmapWindow(tc, overlayId, state, record, plan, deferred = NO_DEFERRED_SIBLINGS) {
1226
+ const held = heldByMount(tc, overlayId);
1227
+ plan.budget =
1228
+ plan.budget.family === 'batched'
1229
+ ? { family: 'batched', plan: currentWrunBatchedPlan(tc, plan.budget.plan, held) }
1230
+ : { family: 'heatmap', plan: currentWrunHeatmapPlan(tc, plan.budget.plan, held) };
1231
+ const rows = windowBudgetRows(plan.budget);
1232
+ const landed = {
1233
+ input: { ...record.input, data: rows },
1234
+ config: { ...record.config, data: rows },
1235
+ };
1236
+ refreshChildInPlace(tc, record.config, landed.config);
1237
+ state.children.set(plan.childId, landed);
1238
+ if (plan.budget.family === 'batched') {
1239
+ commitWrunBatchedPlan(tc, plan.budget.plan, held);
1240
+ for (const sibling of wrunBatchedChildrenOverShare(tc, overlayId, plan.childId, held)) {
1241
+ if (!deferred.has(sibling))
1242
+ budgetMountedBatched(tc, overlayId, sibling);
1243
+ }
1244
+ return landed;
1245
+ }
1246
+ commitWrunHeatmapPlan(tc, plan.budget.plan, held);
1247
+ keepWrunHeatmapScaleSample(record.input.data, rows);
1248
+ for (const sibling of wrunHeatmapChildrenOverShare(tc, overlayId, plan.childId, held)) {
1249
+ if (!deferred.has(sibling))
1250
+ budgetMountedHeatmap(tc, overlayId, sibling);
1251
+ }
1252
+ return landed;
1253
+ }
1254
+ /** What a planned window lands (`PreparedWrunWindowLanding`): the budget drops the oldest merged rows, so the
1255
+ * pass rows among them are the ones that do not land. */
1256
+ function windowLandingCounts(plan) {
1257
+ const { rows, fromPass, passRows } = plan.merged;
1258
+ const kept = windowBudgetRows(plan.budget).length;
1259
+ const trimmedRows = rows.length - kept;
1260
+ let trimmedPass = 0;
1261
+ for (let at = 0; at < trimmedRows; at += 1)
1262
+ trimmedPass += fromPass[at];
1263
+ const landedRows = passRows - trimmedPass;
1264
+ return { landedRows, keptRows: kept - landedRows, trimmedRows };
1265
+ }
1266
+ /** A prepared heatmap landing that can no longer land (C6): nothing of it is applied. */
1267
+ export class WrunStaleLandingError extends Error {
1268
+ childId;
1269
+ reason;
1270
+ constructor(childId, reason) {
1271
+ super(`wrun heatmap landing for '${childId}' is stale (${reason})`);
1272
+ this.name = 'WrunStaleLandingError';
1273
+ this.childId = childId;
1274
+ this.reason = reason;
1275
+ }
1276
+ }
1277
+ /** The mount a landing for `childId` lands into: the chart's mount of the Indicator, its parent overlay
1278
+ * still the one mounted, and the child a mounted heatmap holding rows (an empty one kept no colour scale to
1279
+ * keep: a full run lands it). Throws `WrunStaleLandingError` otherwise. */
1280
+ function windowLandingTarget(tc, overlayId, childId) {
1281
+ if (!tc || tc.isDestroyed)
1282
+ throw new WrunStaleLandingError(childId, 'chart');
1283
+ const state = chartChildren.get(tc)?.get(overlayId);
1284
+ if (!state)
1285
+ throw new WrunStaleLandingError(childId, 'mount');
1286
+ if (tc.metadata.find((meta) => meta.id === overlayId) !== state.parent) {
1287
+ throw new WrunStaleLandingError(childId, 'parent');
1288
+ }
1289
+ const record = state.children.get(childId);
1290
+ if (!isWindowRecord(record) || record.config.data.length === 0 || !overlayPresent(tc, childId)) {
1291
+ throw new WrunStaleLandingError(childId, 'child');
1292
+ }
1293
+ return { tc, state, record };
1294
+ }
1295
+ const landingGroups = new WeakMap();
1296
+ /** The transaction a landing prepared now joins: the open one of the same mount, else a new one. */
1297
+ function joinLandingGroup(tc, overlayId, state, member) {
1298
+ const open = landingGroups.get(state);
1299
+ if (open !== undefined && open.token === state.token && open.pending.size > 0 && !open.rolledBack) {
1300
+ open.pending.add(member);
1301
+ return open;
1302
+ }
1303
+ const group = {
1304
+ tc,
1305
+ overlayId,
1306
+ state,
1307
+ token: state.token,
1308
+ pending: new Set([member]),
1309
+ landed: 0,
1310
+ rolledBack: false,
1311
+ };
1312
+ landingGroups.set(state, group);
1313
+ return group;
1314
+ }
1315
+ function snapshotLandingGroup(group) {
1316
+ if (group.snapshot !== undefined)
1317
+ return;
1318
+ const children = [];
1319
+ for (const [id, record] of group.state.children) {
1320
+ if (isWindowRecord(record))
1321
+ children.push({ id, record, config: record.config, input: record.input });
1322
+ }
1323
+ group.snapshot = {
1324
+ children,
1325
+ ledger: snapshotWrunHeatmapLedger(group.tc, group.overlayId),
1326
+ batchedLedger: snapshotWrunBatchedLedger(group.tc, group.overlayId),
1327
+ };
1328
+ }
1329
+ /**
1330
+ * Put back what a transaction's landings changed (their rows, the records and the ledger, a sibling's trim
1331
+ * included), once. Only on the mount the landings went into: after another pass (a tick, a run) the picture is
1332
+ * that pass's, and the full run a rejected prefix queues repaints it. A restore the engine refuses is skipped:
1333
+ * the rest still goes back.
1334
+ */
1335
+ function rollBackLandingGroup(group) {
1336
+ if (group.rolledBack)
1337
+ return;
1338
+ group.rolledBack = true;
1339
+ const snapshot = group.snapshot;
1340
+ group.snapshot = undefined;
1341
+ const { tc, overlayId, state } = group;
1342
+ if (snapshot === undefined || group.landed === 0)
1343
+ return;
1344
+ if (tc.isDestroyed || chartChildren.get(tc)?.get(overlayId) !== state || state.token !== group.token)
1345
+ return;
1346
+ for (const { id, record, config, input } of snapshot.children) {
1347
+ // Read before the record is put back: a trim reassigned the config of the very record the snapshot holds.
1348
+ const held = state.children.get(id)?.config;
1349
+ record.config = config;
1350
+ record.input = input;
1351
+ state.children.set(id, record);
1352
+ if (held === undefined || held.data === config.data || !overlayPresent(tc, id))
1353
+ continue;
1354
+ try {
1355
+ refreshChildInPlace(tc, held, config);
1356
+ }
1357
+ catch {
1358
+ // The engine refused the old rows: the record still says what was meant, and the next run lands it.
1359
+ }
1360
+ }
1361
+ restoreWrunHeatmapLedger(tc, overlayId, snapshot.ledger);
1362
+ restoreWrunBatchedLedger(tc, overlayId, snapshot.batchedLedger);
1363
+ paintAfterMount(tc);
1364
+ }
1365
+ /**
1366
+ * Prepare a mounted heatmap child's landing of `rows` inside `historyWindow` (both ends inclusive, epoch ms):
1367
+ * the C6 seam a prefix run lands its heatmap children through, as an asynchronous prepare and a synchronous
1368
+ * commit under the run's own lock. Every await is here: the chart the index names, the child's packs, the
1369
+ * pause lookup. Then, with no await, the rows merge into the rows the mount record holds (the rows outside the
1370
+ * window kept by identity, C3), the cell budget is planned from the merged rows and the ledger as it stands
1371
+ * (no whole-run skip: the budget only cuts the oldest bars), and the mounted scale is kept: a windowed landing
1372
+ * never samples colour bounds, a full run does. Rejects with `WrunStaleLandingError` when the mount holds no
1373
+ * such child to land into, and with the pack error when a pack failed.
1374
+ *
1375
+ * A batched child (WRUN-BATCHED-MARKS: marks, spans, rays) lands through the same seam (round-2 fold 10:
1376
+ * the row-backed canvas kinds prepend rows): its merged rows are budgeted on the batched ledger, each pass
1377
+ * row that replaces a mounted bar charged its old copy too, and the ring logs `wrun-batched-prefix-landed`;
1378
+ * a run's heatmap and batched landings commit as one transaction. `prepareWrunChildWindowLanding` names
1379
+ * the generalized seam.
1380
+ */
1381
+ export async function prepareWrunHeatmapWindowLanding(input) {
1382
+ const { chartIndex, indicatorId, childId } = input;
1383
+ const span = { fromMs: input.historyWindow.fromTs, toMs: input.historyWindow.toTs };
1384
+ // A typed row (the live book lane's) would draw no column: the engine reads plain rows only.
1385
+ const pass = input.rows.map(wrunPlainCanvasRow);
1386
+ const { getTC } = await wrunChartHostEnv().chart.loadTitanCharts();
1387
+ const chartAt = () => getTC(chartIndex);
1388
+ const { record: before } = windowLandingTarget(chartAt(), indicatorId, childId);
1389
+ const packs = await wrunChartHostEnv().chart.ensurePacks({ plotTypes: [before.config.plot] });
1390
+ if (packs.failed.length > 0)
1391
+ throw new Error(`wrun child overlay packs unavailable: ${packs.failed.join(', ')}`);
1392
+ const paused = await wrunMountPauseReader();
1393
+ // The awaits are done: the plan reads the mount as it stands now, and the commit holds it to that.
1394
+ const { tc, state, record } = windowLandingTarget(chartAt(), indicatorId, childId);
1395
+ const token = state.token;
1396
+ const parent = state.parent;
1397
+ let plan = planHeatmapWindow(tc, indicatorId, record, pass, span);
1398
+ let counts = windowLandingCounts(plan);
1399
+ let settled;
1400
+ const member = { childId };
1401
+ const group = joinLandingGroup(tc, indicatorId, state, member);
1402
+ // Checks the landing against the mount it was prepared on, then lands it (merged again from the rows the
1403
+ // child holds now when they moved since the plan). Throws before any change when a check fails.
1404
+ const land = (landing) => {
1405
+ if (group.rolledBack)
1406
+ throw new WrunStaleLandingError(childId, 'rolled-back');
1407
+ if (chartAt() !== tc || tc.isDestroyed)
1408
+ throw new WrunStaleLandingError(childId, 'chart');
1409
+ if (chartChildren.get(tc)?.get(indicatorId) !== state || state.token !== token) {
1410
+ throw new WrunStaleLandingError(childId, 'mount');
1411
+ }
1412
+ if (state.parent !== parent || tc.metadata.find((meta) => meta.id === indicatorId) !== parent) {
1413
+ throw new WrunStaleLandingError(childId, 'parent');
1414
+ }
1415
+ const current = state.children.get(childId);
1416
+ if (!isWindowRecord(current) || !overlayPresent(tc, childId))
1417
+ throw new WrunStaleLandingError(childId, 'child');
1418
+ if (paused(chartIndex, indicatorId))
1419
+ throw new WrunStaleLandingError(childId, 'paused');
1420
+ const fresh = holdsPlannedRows(current, landing)
1421
+ ? landing
1422
+ : planHeatmapWindow(tc, indicatorId, current, landing.pass, landing.window);
1423
+ snapshotLandingGroup(group);
1424
+ const deferred = new Set([...group.pending].map((other) => other.childId));
1425
+ landHeatmapWindow(tc, indicatorId, state, current, fresh, deferred);
1426
+ return fresh;
1427
+ };
1428
+ return {
1429
+ childId,
1430
+ get landedRows() {
1431
+ return counts.landedRows;
1432
+ },
1433
+ get keptRows() {
1434
+ return counts.keptRows;
1435
+ },
1436
+ get trimmedRows() {
1437
+ return counts.trimmedRows;
1438
+ },
1439
+ commit() {
1440
+ const landing = plan;
1441
+ if (landing === undefined || settled !== undefined)
1442
+ throw new WrunStaleLandingError(childId, 'spent');
1443
+ plan = undefined;
1444
+ group.pending.delete(member);
1445
+ let landed;
1446
+ try {
1447
+ landed = land(landing);
1448
+ }
1449
+ catch (error) {
1450
+ settled = 'failed';
1451
+ rollBackLandingGroup(group);
1452
+ throw error;
1453
+ }
1454
+ settled = 'landed';
1455
+ group.landed += 1;
1456
+ // Every landing of the run is in: nothing is left to roll back.
1457
+ if (group.pending.size === 0)
1458
+ group.snapshot = undefined;
1459
+ counts = windowLandingCounts(landed);
1460
+ paintAfterMount(tc);
1461
+ if (wrunChartHostEnv().diagnostics.debugEnabled()) {
1462
+ const event = isWrunBatchedMarksKind(before.input.kind)
1463
+ ? 'wrun-batched-prefix-landed'
1464
+ : 'wrun-heatmap-prefix-landed';
1465
+ wrunChartHostEnv().diagnostics.debug(event, { chartIndex, indicatorId, childId, ...counts });
1466
+ }
1467
+ },
1468
+ discard() {
1469
+ if (plan === undefined || settled !== undefined)
1470
+ return;
1471
+ plan = undefined;
1472
+ settled = 'dropped';
1473
+ group.pending.delete(member);
1474
+ // A landing dropped while another of its run landed leaves the run partial: roll the landed ones back.
1475
+ if (group.landed > 0)
1476
+ rollBackLandingGroup(group);
1477
+ else if (group.pending.size === 0)
1478
+ group.snapshot = undefined;
1479
+ },
1480
+ };
1481
+ }
1482
+ /** The window landing of any row-backed canvas child (a heatmap or a batched child), the generalized name. */
1483
+ export const prepareWrunChildWindowLanding = prepareWrunHeatmapWindowLanding;
1484
+ /** True when a tick's canvas moved its row grid: the TPO's rows-per-period
1485
+ * cap coarsened (or relaxed) the row height on this tick, or the auto unit
1486
+ * under it moved. The engine reads the mounted `barHeight` and
1487
+ * `minimumBarHeight` for every period, so the newest row alone would draw
1488
+ * a forming period on the new grid beside closed periods on the old one,
1489
+ * under the old height: the tick takes the full rows and settings instead. */
1490
+ function canvasGridMoved(mounted, next) {
1491
+ return (mounted.settings.barHeight !== next.settings.barHeight ||
1492
+ mounted.settings.minimumBarHeight !== next.settings.minimumBarHeight);
1493
+ }
1494
+ /**
1495
+ * The same-frame signature of a frame child's engine config (levels, matrix, inset): its rows and
1496
+ * its settings as text, compared part by part, so an in-place refresh hands the engine only the
1497
+ * part that changed (refreshInsetChild). A mount signs every frame config it built before any of
1498
+ * them reaches the engine (applyChildren): titan keeps the row arrays it is handed and mutates them
1499
+ * in place, so a signature taken from a mounted config after the hand-off would read the engine's
1500
+ * rows, and a next input equal to those would wrongly read as unchanged. A config never signed
1501
+ * before its hand-off (a retranslate's rebuild, a restore after a failed run) reads as changed,
1502
+ * and so do settings holding a function (text cannot compare one).
1503
+ */
1504
+ function sameFrameSignature(config) {
1505
+ const seen = { fn: false };
1506
+ const settings = JSON.stringify(config.settings, (_key, value) => {
1507
+ if (typeof value === 'function')
1508
+ seen.fn = true;
1509
+ return value;
1510
+ });
1511
+ return { rows: JSON.stringify(config.data), settings: seen.fn ? undefined : settings };
1512
+ }
1513
+ /** The signature of every mounted frame config, taken before its hand-off (sameFrameSignature). */
1514
+ const frameSignatures = new WeakMap();
1515
+ /**
1516
+ * Refresh a mounted frame child in place from the config this run built: while it stays the same
1517
+ * engine overlay (kind, side, plot, interval, name) it never leaves the engine, and only the part
1518
+ * that changed reaches it, through the engine's own doors: `updateSettings` (it bumps the docked
1519
+ * revision the renderers re-read; the keys the mounted config set and this one dropped leave the
1520
+ * engine's settings first, as in the canvas refresh) and `updateData` (it swaps the rows; the
1521
+ * engine's own row diff decides how much to repaint). An unchanged frame costs the engine
1522
+ * nothing. The inset is the bare case (it draws on its own pane); levels and matrices add their
1523
+ * pane rule and extras on top (refreshLevelsChild, refreshMatrixChild). False when the child
1524
+ * cannot stay (another overlay, an engine without both doors, a child the engine no longer
1525
+ * holds): the caller retires and re-adds it, as before.
1526
+ */
1527
+ function refreshInsetChild(tc, mounted, next) {
1528
+ const was = mounted.config;
1529
+ const is = next.config;
1530
+ if (next.input.kind !== mounted.input.kind ||
1531
+ is.type !== was.type ||
1532
+ is.plot !== was.plot ||
1533
+ is.interval !== was.interval ||
1534
+ is.name !== was.name) {
1535
+ return false;
1536
+ }
1537
+ if (typeof tc.updateData !== 'function' || typeof tc.updateSettings !== 'function')
1538
+ return false;
1539
+ const meta = tc.metadata.find((candidate) => candidate.id === is.id);
1540
+ if (!meta)
1541
+ return false;
1542
+ const before = frameSignatures.get(was);
1543
+ const after = frameSignatures.get(is);
1544
+ const same = (part) => {
1545
+ const signed = before?.[part];
1546
+ return signed !== undefined && signed === after?.[part];
1547
+ };
1548
+ if (!same('settings')) {
1549
+ const settings = (meta.settings ??= {});
1550
+ for (const key of Object.keys(was.settings)) {
1551
+ if (!(key in is.settings))
1552
+ delete settings[key];
1553
+ }
1554
+ void tc.updateSettings(is.id, { ...is.settings });
1555
+ }
1556
+ if (!same('rows'))
1557
+ tc.updateData(is.id, is.data, { shouldResetRange: false });
1558
+ return true;
1559
+ }
1560
+ /** A mounted levels child refreshed in place (refreshInsetChild) while it docks on the same pane:
1561
+ * the one `pane_id` names (a lower pane, DL-lower-pane), else the price pane; one that moved pane
1562
+ * is retired and re-added. Its hover rows follow this run's, resolved against the palette the way
1563
+ * installChild registers them (none once the run turned hover off). */
1564
+ function refreshLevelsChild(tc, mounted, next, theme) {
1565
+ if (next.input.kind !== 'levels' || next.config.settings.pane_id !== mounted.config.settings.pane_id)
1566
+ return false;
1567
+ if (!refreshInsetChild(tc, mounted, next))
1568
+ return false;
1569
+ if (next.input.hover !== undefined)
1570
+ rememberWrunLevelsHoverRows(next.config.id, next.input.hover, theme);
1571
+ else
1572
+ forgetWrunLevelsHoverRows(next.config.id);
1573
+ return true;
1574
+ }
1575
+ /** A mounted matrix refreshed in place (refreshInsetChild) while it stays on the same surface: the
1576
+ * price pane, or the side strip the engine plans apart (`dock: "side"`, MX-side-panel); one moving
1577
+ * between them is retired and re-added. Its hover readout was registered when its config was
1578
+ * built (wrunCanvasChildConfig). */
1579
+ function refreshMatrixChild(tc, mounted, next) {
1580
+ const sideStrip = ({ settings }) => settings.dock === 'side' || settings.sideDock === true;
1581
+ if (next.input.kind !== 'matrix' || sideStrip(next.config) !== sideStrip(mounted.config))
1582
+ return false;
1583
+ return refreshInsetChild(tc, mounted, next);
1584
+ }
1585
+ /** The owner's first time pane (C6): the parent itself when it homes
1586
+ * offchart (a lower-only package), else the first series child that mounts
1587
+ * below the chart (a pane pinned over the candles carves nothing); undefined
1588
+ * when the Indicator has none. */
1589
+ function ownerTimePaneId(parent, overlayId, children) {
1590
+ if (parent.type === 'offchart')
1591
+ return overlayId;
1592
+ const lower = children.find((child) => child.kind === 'series' && child.result.pane?.place !== 'price');
1593
+ return lower === undefined ? undefined : wrunSeriesChildId(overlayId, lower.name);
1594
+ }
1595
+ /** The run's children in mount order (C6): the panels first, then today's
1596
+ * order (series, levels, canvases, insets), each group as the run listed
1597
+ * it. Decided here, never in the run result, so the run golden's
1598
+ * `childOverlays` keeps its order. */
1599
+ function panelsFirst(children) {
1600
+ return [...children.filter((child) => child.kind === 'panel'), ...children.filter((child) => child.kind !== 'panel')];
1601
+ }
1602
+ /** The Sensitivity a heatmap draws with: the drag value a slider holds, else
1603
+ * the saved row on the parent's engine settings (read like the window's
1604
+ * saved split); undefined draws the author's bounds. */
1605
+ function heatmapSensitivityOf(previews, parent, name) {
1606
+ return wrunHeatmapSensitivityValue(previews?.get(name)) ?? wrunHeatmapSensitivitySetting(parent.settings, name);
1607
+ }
1608
+ /** The context every child config of one Indicator is built from: the
1609
+ * chart's palette, the user's theme name and the display timezone read
1610
+ * now, so a retranslate builds against the current ones; the owner's time
1611
+ * pane from the run's (or the mounted) children; each heatmap's Sensitivity
1612
+ * (a held drag value, else the parent's saved row) read when its config is
1613
+ * built; the Indicator's kept label formatters. */
1614
+ function mountContext(tc, overlayId, parent, children, priceDigits, chartHeightPx, windowCell, planned, previews, formatters) {
1615
+ return {
1616
+ tc,
1617
+ overlayId,
1618
+ interval: parent.interval ?? tc.metadata[0]?.interval ?? 1,
1619
+ chartHeightPx,
1620
+ parentName: parent.name,
1621
+ parentOffchart: parent.type === 'offchart',
1622
+ priceDigits,
1623
+ theme: wrunColorThemeOf(tc),
1624
+ themeMode: userThemeMode(),
1625
+ timezoneOffsetMs: displayTimezoneOffsetMs(),
1626
+ windowCell,
1627
+ planned,
1628
+ anchorPaneId: ownerTimePaneId(parent, overlayId, children),
1629
+ heatmapSensitivity: (name) => heatmapSensitivityOf(previews(), parent, name),
1630
+ formatters,
1631
+ };
1632
+ }
1633
+ /** Mount a run snapshot after every required pack has settled.
1634
+ * The parent remains the canonical numeric-output container. A panel child
1635
+ * the run still declares in the same pane takes the new rows in place; one
1636
+ * whose pane changed (side, species, axis, chrome, carved height) or that
1637
+ * the run dropped is replaced or removed. A heatmap or profile that stays
1638
+ * the same canvas, and an inset that stays the same strip (sameInset), takes
1639
+ * the run's rows in place too; a levels or matrix child in the same pane
1640
+ * and kind refreshes in place when its frame signature changed (one that
1641
+ * moved pane or kind is replaced). A tick
1642
+ * without frames touches only the row-backed kinds: an inset takes its rows
1643
+ * in place (a moved strip is replaced, one the tick dropped removed),
1644
+ * heatmaps and profiles their newest row (every row from `canvasRowsFromTs`
1645
+ * on when the tick added bars; all their rows and settings when
1646
+ * the row grid moved), and the series child is refreshed in place; a series
1647
+ * child is never removed while the run still declares it in the same pane (a
1648
+ * pane moved onto the price or given another height is re-carved). Every
1649
+ * child mounts with the parent's eye, a child the reader hid on its own row
1650
+ * hidden (syncChildVisibility). `priceDigits` is the chart's price
1651
+ * precision (OT29, X7): the panels' formatters and the lower pane's legend
1652
+ * print "price" values with it. A tick's heatmap tail (`tailOnly`) only
1653
+ * ever merges its rows into a mounted canvas. */
1654
+ export function mountWrunChildOverlays({ tc, overlayId, runResult, replaceFrames = true, swapCanvasRows, canvasRowsFromTs, historyWindow, projection, cell, priceDigits, onMainThreadMs, chartIndex, }) {
1655
+ if (runResult.failureReason !== undefined)
1656
+ return Promise.reject(new Error(runResult.failureReason));
1657
+ if (tc.isDestroyed)
1658
+ return Promise.resolve(false);
1659
+ const parent = tc.metadata.find((meta) => meta.id === overlayId);
1660
+ if (!parent)
1661
+ return Promise.resolve(false);
1662
+ let owners = chartChildren.get(tc);
1663
+ let state = owners?.get(overlayId);
1664
+ if (state && state.parent !== parent) {
1665
+ unmountWrunChildOverlays(tc, overlayId);
1666
+ state = undefined;
1667
+ }
1668
+ const children = (runResult.childOverlays ?? []).filter((child) => replaceFrames || ROW_BACKED_KINDS.has(child.kind));
1669
+ if (!state && children.length === 0)
1670
+ return Promise.resolve(true);
1671
+ if (!replaceFrames &&
1672
+ children.length === 0 &&
1673
+ ![...state.children.values()].some((child) => child.input.kind === 'inset'))
1674
+ return Promise.resolve(true);
1675
+ if (!owners) {
1676
+ owners = new Map();
1677
+ chartChildren.set(tc, owners);
1678
+ }
1679
+ if (!state) {
1680
+ state = { parent, token: Symbol(overlayId), children: new Map(), formatters: new Map() };
1681
+ owners.set(overlayId, state);
1682
+ state.unsubscribe = tc.on?.('objects', (event) => {
1683
+ // A `reset` names no overlay (titan's pane regroup, swap and order events carry no refs).
1684
+ if (!event.refs?.some((ref) => ref.id === overlayId))
1685
+ return;
1686
+ if (event.type === 'removed') {
1687
+ unmountWrunChildOverlays(tc, overlayId);
1688
+ return;
1689
+ }
1690
+ // The parent's eye (titan emits `updated` for the toggled overlay):
1691
+ // every child follows it, so a hidden Indicator leaves nothing behind.
1692
+ // An update that left the eye where it was (a settings save) moves no
1693
+ // child, so an eye the reader moved on a child's row stands.
1694
+ if (event.type !== 'updated')
1695
+ return;
1696
+ const live = chartChildren.get(tc)?.get(overlayId);
1697
+ if (live)
1698
+ syncChildVisibility(tc, parent, live);
1699
+ });
1700
+ }
1701
+ const current = state;
1702
+ const token = Symbol(overlayId);
1703
+ current.token = token;
1704
+ current.priceDigits = priceDigits;
1705
+ // A window (the parent carries the owner flag in its engine settings, or the
1706
+ // caller says so): the children mount at the plan's weights and the plan is
1707
+ // reconciled onto the mounted panes when the mount settles. A cell without
1708
+ // a flagged owner never enters that path: its configs are today's.
1709
+ const windowCell = cell?.window ?? isWrunWindowOwner(parent);
1710
+ current.chartHeightPx = cell?.canvasHeightPx ?? tc.canvasChartController?.canvasElement?.clientHeight;
1711
+ // The host's plan sizes the children on any cell (a normal cell's remembered heights included); a window without
1712
+ // one plans its own.
1713
+ let planned = cell?.planned;
1714
+ if (windowCell) {
1715
+ if (!planned) {
1716
+ const panes = windowPanesOfMount(parent, overlayId, children, replaceFrames ? [] : [...current.children.values()].map((mounted) => mounted.config));
1717
+ // The reader's saved split (the parent's settings carry it,
1718
+ // window-geometry.util) is the first paint when it names exactly these
1719
+ // panes: a reload mounts the children at the split with no flash of
1720
+ // the plan. Else the plan.
1721
+ const weights = savedWindowSplit(parent.settings, panes) ?? planWindowWeights(panes, current.chartHeightPx);
1722
+ planned = new Map(weights.map(({ id, gridHeight }) => [id, gridHeight]));
1723
+ }
1724
+ }
1725
+ current.windowCell = windowCell;
1726
+ current.planned = planned;
1727
+ const ctx = mountContext(tc, overlayId, parent, children, priceDigits, current.chartHeightPx, windowCell, planned, () => current.previews, current.formatters);
1728
+ // Panels mount ahead of the Indicator's time panes (C6), so a first mount
1729
+ // stacks them above the lower pane by order alone; the anchor keeps a
1730
+ // later or re-carved panel there.
1731
+ const entries = panelsFirst(children).map((child) => ({
1732
+ input: child,
1733
+ config: childConfig(child, ctx),
1734
+ }));
1735
+ const seriesResults = new Map(children.flatMap((child) => child.kind === 'series' ? [[wrunSeriesChildId(overlayId, child.name), child.result]] : []));
1736
+ const active = () => !tc.isDestroyed &&
1737
+ chartChildren.get(tc)?.get(overlayId) === current &&
1738
+ current.token === token &&
1739
+ tc.metadata.find((meta) => meta.id === overlayId) === parent;
1740
+ // A series child paints its result's plot kinds (markers, ranges, fills
1741
+ // and the rest ride packs the parent's mount usually already loaded).
1742
+ const plotTypesFor = (config) => {
1743
+ const result = seriesResults.get(config.id);
1744
+ const nested = result ? Object.values(result.outputs).map((output) => output.plotType) : [];
1745
+ return [
1746
+ config.plot,
1747
+ ...nested.filter((plotType, at) => plotType !== config.plot && nested.indexOf(plotType) === at),
1748
+ ];
1749
+ };
1750
+ // The children's application once their packs load: synchronous, the mount's own main-thread
1751
+ // work (the wait before it is not), timed whole inside this mount's continuation
1752
+ // (onMainThreadMs).
1753
+ let appliedMs;
1754
+ const applyChildren = (packs) => {
1755
+ if (!active())
1756
+ return false;
1757
+ // A batched child's pack is the engine gate's to judge (below): its failure refuses that child by
1758
+ // name and never the rest of the mount.
1759
+ const failed = [
1760
+ ...new Set(packs.flatMap((result, at) => (isBatchedChild(entries[at].input) ? [] : result.failed))),
1761
+ ];
1762
+ if (failed.length > 0) {
1763
+ syncCanvasReadouts(current.children, entries);
1764
+ throw new Error(`wrun child overlay packs unavailable: ${failed.join(', ')}`);
1765
+ }
1766
+ // The engine gate (WRUN-BATCHED-MARKS): every batched child is judged after its pack settled, and one
1767
+ // the chart cannot draw is refused by name (never silently: the Indicator's notice row names it, one
1768
+ // word for a pack that failed to load, another for an engine that needs a newer chart) and never
1769
+ // mounted; a mounted one of the same id leaves. The rest of the mount goes on. A child whose section
1770
+ // names a layout newer than this chart (`newer`: the build's gate over its declaration, or a record's
1771
+ // meta, WRUN-MARKS-CONTRACT F2) needs a newer chart whatever the engine holds.
1772
+ const refusals = [];
1773
+ const refused = new Map();
1774
+ entries.forEach((entry, at) => {
1775
+ if (!isBatchedChild(entry.input))
1776
+ return;
1777
+ // A layout refusal (its `reason`: the section's declaration, or a record in the retained history whose
1778
+ // meta packs a field this chart does not read) stands until a full build judges the child again
1779
+ // (WRUN-MARKS-CONTRACT F2, finding 5). A tick's tail copies only the rows the tick re-evaluated, so a
1780
+ // clean tail says nothing of the records before it: lifting the refusal there left the child neither
1781
+ // refused nor mounted, and the next tick rebuilt the whole history to refuse it again (a full copy
1782
+ // every other tick, the row flickering). The held refusal is the one published, so its row stays as is;
1783
+ // the tail mounts nothing (a tail never does). An engine gate refusal is judged again as before.
1784
+ const held = entry.config.tailOnly === true ? current.gateRefused?.get(entry.config.id) : undefined;
1785
+ if (held?.reason !== undefined) {
1786
+ refused.set(entry.config.id, held);
1787
+ refusals.push(held);
1788
+ forgetWrunCanvasReadout(entry.config.id);
1789
+ return;
1790
+ }
1791
+ const newer = entry.input.newer;
1792
+ const cause = newer !== undefined ? 'old-engine' : batchedGateCause(tc, entry.config.plot, packs[at]);
1793
+ if (cause === null)
1794
+ return;
1795
+ const refusal = {
1796
+ kind: entry.input.kind,
1797
+ name: entry.input.name,
1798
+ cause,
1799
+ ...(newer !== undefined ? { reason: newer } : {}),
1800
+ };
1801
+ refused.set(entry.config.id, refusal);
1802
+ refusals.push(refusal);
1803
+ forgetWrunCanvasReadout(entry.config.id);
1804
+ if (newer !== undefined && wrunChartHostEnv().diagnostics.debugEnabled()) {
1805
+ wrunChartHostEnv().diagnostics.debug('wrun-batched-layout-refused', {
1806
+ chartIndex,
1807
+ overlayId,
1808
+ childId: entry.config.id,
1809
+ reason: newer,
1810
+ });
1811
+ }
1812
+ });
1813
+ const applying = refused.size === 0 ? entries : entries.filter((entry) => !refused.has(entry.config.id));
1814
+ // Preserve the previous complete snapshot until all pack imports succeed.
1815
+ // An unmount or newer run during an import must not resurrect children.
1816
+ // A series child the run still declares in the same pane is preserved
1817
+ // in place (its result is re-applied below, never re-added); one the run
1818
+ // dropped goes with the frames.
1819
+ const previous = current.children;
1820
+ const nextById = new Map(applying.map((entry) => [entry.config.id, entry]));
1821
+ // Every frame config this run built is signed before any of it reaches the
1822
+ // engine (sameFrameSignature): the refresh below and the next run compare
1823
+ // against what was handed over, never against what the engine made of it.
1824
+ for (const { input, config } of applying) {
1825
+ if (input.kind === 'levels' || input.kind === 'matrix' || input.kind === 'inset') {
1826
+ frameSignatures.set(config, sameFrameSignature(config));
1827
+ }
1828
+ }
1829
+ const preserved = new Map([...previous].flatMap(([id, mounted]) => {
1830
+ const next = nextById.get(id);
1831
+ // An inset stays while the pass (a tick's or a run's) still declares
1832
+ // the same strip, and takes its rows in place below.
1833
+ if (mounted.input.kind === 'inset') {
1834
+ return next !== undefined && overlayPresent(tc, id) && sameInset(mounted.config, next.config)
1835
+ ? [[id, mounted]]
1836
+ : [];
1837
+ }
1838
+ // A tick: frame-backed children (panels, levels, matrices) stay as
1839
+ // mounted, row-backed canvases stay and take the tick's rows, the
1840
+ // series child is re-applied (insets were decided above).
1841
+ // A batched child the engine gate refused leaves, on a tick too.
1842
+ if (refused.has(id))
1843
+ return [];
1844
+ if (!replaceFrames)
1845
+ return [[id, mounted]];
1846
+ if (next === undefined || !overlayPresent(tc, id))
1847
+ return [];
1848
+ switch (mounted.input.kind) {
1849
+ case 'series':
1850
+ case 'panel':
1851
+ return samePane(mounted.config, next.config, windowCell || planned?.has(id) === true)
1852
+ ? [[id, mounted]]
1853
+ : [];
1854
+ case 'heatmap':
1855
+ case 'profile':
1856
+ case 'marks':
1857
+ case 'spans':
1858
+ case 'rays':
1859
+ return sameCanvas(mounted.config, next.config) ? [[id, mounted]] : [];
1860
+ // A frame that stays on its pane is refreshed in place right here and
1861
+ // kept as this run's child (the engine keeps one overlay throughout);
1862
+ // one that moved pane or kind is retired and re-added below.
1863
+ case 'levels':
1864
+ return refreshLevelsChild(tc, mounted, next, ctx.theme) ? [[id, next]] : [];
1865
+ case 'matrix':
1866
+ return refreshMatrixChild(tc, mounted, next) ? [[id, next]] : [];
1867
+ }
1868
+ }));
1869
+ current.children = new Map(preserved);
1870
+ // The configs were built before the pack await: a heatmap about to be
1871
+ // installed or refreshed re-picks its bounds from the Sensitivity it holds
1872
+ // NOW (a drag or a save during the await), never the one it was built with.
1873
+ const repickHeatmapBounds = ({ input, config }) => {
1874
+ if (input.kind !== 'heatmap' || input.scale === undefined)
1875
+ return;
1876
+ const bounds = wrunHeatmapSensitivityBounds(input, heatmapSensitivityOf(current.previews, parent, input.name));
1877
+ config.settings.min = bounds.min;
1878
+ config.settings.max = bounds.max;
1879
+ };
1880
+ // The children this pass adds to the engine (each comes back visible).
1881
+ const installed = [];
1882
+ try {
1883
+ for (const [id, mounted] of previous) {
1884
+ if (!preserved.has(id))
1885
+ retireChild(tc, id, mounted.input.kind, nextById.has(id));
1886
+ }
1887
+ for (const entry of applying) {
1888
+ if (!active())
1889
+ return false;
1890
+ const { config, input } = entry;
1891
+ const id = config.id;
1892
+ const mounted = preserved.has(id) && overlayPresent(tc, id);
1893
+ if (config.tailOnly === true) {
1894
+ // A tick's heatmap tail (the newest rows, no colour scale): its
1895
+ // newest row (every row from `canvasRowsFromTs` on, a tick that
1896
+ // added bars) merges into a mounted canvas, on a tick with frames
1897
+ // too, and that is all. It never mounts a canvas or swaps rows in
1898
+ // (a tail would replace the history), and the full run's record
1899
+ // stays, so a retranslate or a Sensitivity re-pick works from the
1900
+ // full rows, bounds and sample (the engine keeps that record's row
1901
+ // array and merges live rows into it). An unmounted one waits for
1902
+ // the next full run. A batched child's tail (every row the tick
1903
+ // re-evaluated) merges row by row the same way (mergeBatchedChangedRows).
1904
+ const stayed = mounted ? preserved.get(id) : undefined;
1905
+ if (isBatchedRecord(stayed))
1906
+ mergeBatchedChangedRows(tc, stayed, config);
1907
+ else if (mounted)
1908
+ liveUpdateCanvasChild(tc, config, canvasRowsFromTs);
1909
+ else
1910
+ forgetWrunCanvasReadout(id);
1911
+ }
1912
+ else if (!mounted) {
1913
+ repickHeatmapBounds(entry);
1914
+ current.children.set(id, entry);
1915
+ budgetHeatmapChild(tc, overlayId, entry);
1916
+ budgetBatchedChild(tc, overlayId, entry);
1917
+ installChild(tc, entry, ctx.theme);
1918
+ installed.push(id);
1919
+ }
1920
+ else if (isBatchedChild(input)) {
1921
+ // A batched child that stayed the same canvas: a windowed run lands inside its history window
1922
+ // (the rows outside it kept, the budget planned over the merged rows); a run (or the hosted
1923
+ // swap, or a pass whose rows no longer overlap the mounted ones) replaces its rows in place,
1924
+ // under the hard allowance; a frameless pass that built the whole window (a tick while a
1925
+ // sibling held no rows) merges only the rows it changed, row by row.
1926
+ const stayed = preserved.get(id);
1927
+ const mountedConfig = stayed.config;
1928
+ if (historyWindow !== undefined &&
1929
+ swapCanvasRows !== true &&
1930
+ isBatchedRecord(stayed) &&
1931
+ mountedConfig.data.length > 0) {
1932
+ landHeatmapWindow(tc, overlayId, current, stayed, planHeatmapWindow(tc, overlayId, stayed, config.data, historyWindow));
1933
+ }
1934
+ else if (replaceFrames || swapCanvasRows === true || !sameDataWindow(mountedConfig, config)) {
1935
+ budgetBatchedChild(tc, overlayId, entry);
1936
+ refreshChildInPlace(tc, mountedConfig, config);
1937
+ current.children.set(id, entry);
1938
+ }
1939
+ else if (isBatchedRecord(stayed)) {
1940
+ mergeBatchedChangedRows(tc, stayed, config);
1941
+ keepHeatmapRows(entry, stayed.config.data);
1942
+ current.children.set(id, entry);
1943
+ }
1944
+ }
1945
+ else if (input.kind === 'panel') {
1946
+ if (replaceFrames) {
1947
+ refreshPanelChild(tc, preserved.get(id).config, config);
1948
+ current.children.set(id, entry);
1949
+ }
1950
+ }
1951
+ else if (input.kind === 'heatmap' || input.kind === 'profile') {
1952
+ // A tick hands a canvas its newest row (every row from
1953
+ // `canvasRowsFromTs` on, a tick that added bars), unless its
1954
+ // dataset window moved (a developing profile's session rolled: the
1955
+ // builder returns the new session's rows only, and a merge would
1956
+ // leave the old session's rows under the new profile) or its row
1957
+ // grid moved (canvasGridMoved): then the rows and the settings swap.
1958
+ // A windowed run's heatmap merges inside its history window instead.
1959
+ const stayed = preserved.get(id);
1960
+ const mountedConfig = stayed.config;
1961
+ if (historyWindow !== undefined &&
1962
+ swapCanvasRows !== true &&
1963
+ isHeatmapRecord(stayed) &&
1964
+ mountedConfig.data.length > 0) {
1965
+ landHeatmapWindow(tc, overlayId, current, stayed, planHeatmapWindow(tc, overlayId, stayed, config.data, historyWindow));
1966
+ }
1967
+ else if (replaceFrames ||
1968
+ swapCanvasRows === true ||
1969
+ !sameDataWindow(mountedConfig, config) ||
1970
+ canvasGridMoved(mountedConfig, config)) {
1971
+ repickHeatmapBounds(entry);
1972
+ budgetHeatmapChild(tc, overlayId, entry);
1973
+ refreshChildInPlace(tc, mountedConfig, config);
1974
+ current.children.set(id, entry);
1975
+ }
1976
+ else {
1977
+ liveUpdateCanvasChild(tc, config, canvasRowsFromTs);
1978
+ // The entry stored holds the rows the engine holds after the merge (and any trim), never
1979
+ // the pass's own: the engine took only the rows it merged.
1980
+ const held = mountedHeatmapRecord(tc, id);
1981
+ if (held !== undefined)
1982
+ keepHeatmapRows(entry, held.config.data);
1983
+ current.children.set(id, entry);
1984
+ }
1985
+ }
1986
+ else if (input.kind === 'inset') {
1987
+ // A strip that stayed takes the pass's rows and colours in place: by
1988
+ // signature (rows only when they changed, settings only when they
1989
+ // moved), else the whole-config refresh.
1990
+ const stayed = preserved.get(id);
1991
+ if (!refreshInsetChild(tc, stayed, entry))
1992
+ refreshChildInPlace(tc, stayed.config, config);
1993
+ current.children.set(id, entry);
1994
+ }
1995
+ const seriesResult = seriesResults.get(id);
1996
+ if (seriesResult !== undefined) {
1997
+ integrateSeriesChild(tc, id, seriesResult, mounted && !replaceFrames ? 'tick' : 'run', projection);
1998
+ }
1999
+ if (!active())
2000
+ return false;
2001
+ }
2002
+ }
2003
+ catch (error) {
2004
+ for (const [id, mounted] of current.children) {
2005
+ if (!preserved.has(id))
2006
+ retireChild(tc, id, mounted.input.kind, previous.has(id));
2007
+ }
2008
+ // A preserved child keeps the record of what the engine holds: the
2009
+ // run's input when this run already refreshed it in place.
2010
+ current.children = new Map([...current.children].filter(([id]) => preserved.has(id)));
2011
+ if (active()) {
2012
+ // The previous children come back through the door (their hover
2013
+ // rows and readouts with them), resolved against the current theme.
2014
+ for (const [id, mounted] of previous) {
2015
+ if (preserved.has(id))
2016
+ continue;
2017
+ const restored = { input: mounted.input, config: childConfig(mounted.input, ctx) };
2018
+ current.children.set(id, restored);
2019
+ installChild(tc, restored, ctx.theme);
2020
+ }
2021
+ syncCanvasReadouts(current.children, entries);
2022
+ }
2023
+ throw error;
2024
+ }
2025
+ // A kept label formatter goes with its child: one mounted again starts afresh.
2026
+ for (const id of current.formatters.keys()) {
2027
+ if (!current.children.has(id))
2028
+ current.formatters.delete(id);
2029
+ }
2030
+ // The engine gate's notice, on every pass that judged a batched child, and on a run after a pass that
2031
+ // refused one (a run that carries none clears its rows; a tick carrying none leaves them as they are;
2032
+ // an Indicator without batched children never publishes). Reconciled against the Indicator's rows in
2033
+ // the store on every such pass, never against a memo of the last publish (publishWrunPlotGateNotice
2034
+ // writes only when they differ): a clear of the Indicator's diagnostics (Resume, the editor's Clear
2035
+ // console) takes the rows off while the refusal holds, and the next pass puts them back.
2036
+ const judged = entries.some((entry) => isBatchedChild(entry.input));
2037
+ if (judged || (replaceFrames && (current.gateRefused?.size ?? 0) > 0)) {
2038
+ current.gateRefused = refused;
2039
+ wrunChartHostEnv().diagnostics.publishPlotGateNotice(tc, overlayId, refusals);
2040
+ }
2041
+ // The window's weights onto the panes that are mounted now (the engine
2042
+ // carves at addOverlay only and, with main hidden, splits evenly): the
2043
+ // one reconciliation the window host also runs, idempotent, and silent
2044
+ // while the candle pane is still visible.
2045
+ if (windowCell)
2046
+ reconcileWindowOwnerGeometry(tc, overlayId, current.chartHeightPx);
2047
+ // A child mounted while the Indicator is hidden starts hidden too, and so
2048
+ // does one the reader hid on its own row; a child that stayed keeps its eye.
2049
+ syncChildVisibility(tc, parent, current, installed);
2050
+ // One engine pass for the whole mount, after it (paintAfterMount).
2051
+ paintAfterMount(tc);
2052
+ return true;
2053
+ };
2054
+ current.pending = (async () => {
2055
+ const packs = await Promise.all(entries.map((entry) => wrunChartHostEnv().chart.ensurePacks({ plotTypes: plotTypesFor(entry.config) })));
2056
+ // The pack wait is an await: a pause that landed meanwhile holds this mount (the async commit
2057
+ // gate of the pause semantics); the retained children stay as they are.
2058
+ if (chartIndex !== undefined && (await wrunMountParentPaused(chartIndex, overlayId)))
2059
+ return false;
2060
+ const applyingSince = mountClockMs();
2061
+ try {
2062
+ // A child this pass retires (removeOverlay) must not end the reader's expanded pane.
2063
+ return keepFocusedPane(tc, () => applyChildren(packs));
2064
+ }
2065
+ finally {
2066
+ // Stopped here, before this mount settles: a sibling mount that waited on the same packs
2067
+ // applies in its own continuation and never lands in this one's time.
2068
+ appliedMs = mountClockMs() - applyingSince;
2069
+ }
2070
+ })();
2071
+ if (onMainThreadMs !== undefined) {
2072
+ const report = () => {
2073
+ if (appliedMs !== undefined)
2074
+ onMainThreadMs(appliedMs);
2075
+ };
2076
+ void current.pending.then(report, report);
2077
+ }
2078
+ return current.pending;
2079
+ }
2080
+ /** One engine pass after a mount applied: a chart that can defer gets one request, folded with every
2081
+ * other this task makes on it, and the engine runs it on its frame (scheduleKScriptChartPaint). A chart
2082
+ * with neither deferred method keeps the synchronous pair inside the mount. */
2083
+ function paintAfterMount(tc) {
2084
+ const paint = tc;
2085
+ if (typeof paint.requestLiveRecompute === 'function' || typeof paint.requestProcessAndRender === 'function') {
2086
+ wrunChartHostEnv().chart.schedulePaint(paint);
2087
+ }
2088
+ else {
2089
+ tc.processData?.();
2090
+ tc.renderService?.renderOnce?.();
2091
+ }
2092
+ }
2093
+ /** The store is read through a dynamic import (the run util's pattern): this module is imported by
2094
+ * the store's own lanes, so a static import would close a cycle. A store that fails to load, or to
2095
+ * answer, reads as not paused. */
2096
+ async function wrunMountPauseReader() {
2097
+ try {
2098
+ const { useChartStore } = await wrunChartHostEnv().chart.loadChartStore();
2099
+ return (chartIndex, overlayId) => {
2100
+ try {
2101
+ return useChartStore().isKScriptOverlayPaused?.(chartIndex, overlayId) === true;
2102
+ }
2103
+ catch {
2104
+ return false;
2105
+ }
2106
+ };
2107
+ }
2108
+ catch {
2109
+ return () => false;
2110
+ }
2111
+ }
2112
+ async function wrunMountParentPaused(chartIndex, overlayId) {
2113
+ return (await wrunMountPauseReader())(chartIndex, overlayId);
2114
+ }
2115
+ function mountClockMs() {
2116
+ return typeof performance !== 'undefined' ? performance.now() : Date.now();
2117
+ }
2118
+ /**
2119
+ * A retranslated child refreshed on the overlay it has, by the rule a run keeps a child by (the same pane, canvas,
2120
+ * strip or docked surface, read with the run's own helpers, so the run and the retranslate never disagree on what
2121
+ * "unchanged" is): a panel through the shared panel refresh, a docked levels child, matrix or inset through the frame
2122
+ * refresh (its settings through the engine's settings door, then its rows through its row swap), a heatmap, profile
2123
+ * or batched canvas through the canvas refresh (budgeted as the rebuild was: the record's rows, no growth). False
2124
+ * when it cannot stay (another surface, an engine without the doors, the series child the adapter reguards): the
2125
+ * caller rebuilds it.
2126
+ */
2127
+ function refreshRetranslatedChild(tc, mounted, next, ctx, heightHeld) {
2128
+ const kind = mounted.input.kind;
2129
+ if (kind === 'panel') {
2130
+ if (!samePane(mounted.config, next.config, heightHeld))
2131
+ return false;
2132
+ refreshPanelChild(tc, mounted.config, next.config);
2133
+ return true;
2134
+ }
2135
+ if (kind === 'levels' || kind === 'matrix' || kind === 'inset') {
2136
+ // Signed as a run signs its frame configs before the engine sees them (sameFrameSignature).
2137
+ frameSignatures.set(next.config, sameFrameSignature(next.config));
2138
+ if (kind === 'levels')
2139
+ return refreshLevelsChild(tc, mounted, next, ctx.theme);
2140
+ if (kind === 'matrix')
2141
+ return refreshMatrixChild(tc, mounted, next);
2142
+ if (!sameInset(mounted.config, next.config))
2143
+ return false;
2144
+ if (!refreshInsetChild(tc, mounted, next))
2145
+ refreshChildInPlace(tc, mounted.config, next.config);
2146
+ return true;
2147
+ }
2148
+ if ((kind === 'heatmap' || kind === 'profile' || isBatchedChild(mounted.input)) &&
2149
+ overlayPresent(tc, next.config.id)) {
2150
+ if (!sameCanvas(mounted.config, next.config))
2151
+ return false;
2152
+ budgetHeatmapChild(tc, ctx.overlayId, next, 'rebuild');
2153
+ budgetBatchedChild(tc, ctx.overlayId, next, 'rebuild');
2154
+ refreshChildInPlace(tc, mounted.config, next.config);
2155
+ return true;
2156
+ }
2157
+ return false;
2158
+ }
2159
+ /** Re-resolve every mounted child of every Indicator on the chart against
2160
+ * the chart's current palette, theme name and display timezone, without a
2161
+ * rerun (X13; hosted runs follow too). A child that stays the child it was
2162
+ * (the run's own keep rule: the same pane, canvas, strip or docked surface)
2163
+ * is refreshed in place on the overlay it has (refreshRetranslatedChild:
2164
+ * its settings, then its rows), so it keeps its place in the stack, its
2165
+ * height, its legend row and the reader's expanded pane; only a child that
2166
+ * cannot stay (another surface, an engine without the doors) is rebuilt
2167
+ * from its unresolved input under the same id, in the chart's own order so
2168
+ * the rebuilt ones keep their stacking, with the reader's expanded pane
2169
+ * kept around the rebuild (keepFocusedPane). The series child's colours
2170
+ * ride the adapter's own theme reguard. Called by the theme rerun when a
2171
+ * packed colour moved and by the timezone sync per chart. */
2172
+ export function retranslateWrunChildOverlays(tc) {
2173
+ const owners = chartChildren.get(tc);
2174
+ if (!owners || tc.isDestroyed)
2175
+ return;
2176
+ const ownerOf = new Map();
2177
+ for (const [overlayId, state] of owners) {
2178
+ const parent = tc.metadata.find((meta) => meta.id === overlayId);
2179
+ if (!parent || state.parent !== parent)
2180
+ continue;
2181
+ const owner = {
2182
+ state,
2183
+ ctx: mountContext(tc, overlayId, parent, [...state.children.values()].map((mounted) => mounted.input), state.priceDigits, state.chartHeightPx, state.windowCell ?? false, state.planned, () => state.previews, state.formatters),
2184
+ };
2185
+ for (const [id, mounted] of state.children) {
2186
+ if (mounted.input.kind !== 'series')
2187
+ ownerOf.set(id, owner);
2188
+ }
2189
+ }
2190
+ let moved = false;
2191
+ const rebuilt = new Map();
2192
+ const refreshed = new Set();
2193
+ keepFocusedPane(tc, () => {
2194
+ for (const { id } of [...tc.metadata]) {
2195
+ const owner = ownerOf.get(id);
2196
+ const mounted = owner?.state.children.get(id);
2197
+ if (owner === undefined || mounted === undefined)
2198
+ continue;
2199
+ const next = { input: mounted.input, config: childConfig(mounted.input, owner.ctx) };
2200
+ const heightHeld = (owner.state.windowCell ?? false) || owner.state.planned?.has(id) === true;
2201
+ if (refreshRetranslatedChild(tc, mounted, next, owner.ctx, heightHeld)) {
2202
+ refreshed.add(owner.state);
2203
+ }
2204
+ else {
2205
+ removeChild(tc, id);
2206
+ budgetHeatmapChild(tc, owner.ctx.overlayId, next, 'rebuild');
2207
+ budgetBatchedChild(tc, owner.ctx.overlayId, next, 'rebuild');
2208
+ installChild(tc, next, owner.ctx.theme);
2209
+ rebuilt.set(owner.state, [...(rebuilt.get(owner.state) ?? []), id]);
2210
+ }
2211
+ owner.state.children.set(id, next);
2212
+ moved = true;
2213
+ }
2214
+ });
2215
+ if (!moved)
2216
+ return;
2217
+ // A rebuilt child comes back through addOverlay visible: it takes its
2218
+ // Indicator's eye again (a hidden Indicator leaves nothing behind on a
2219
+ // theme or timezone switch either), hidden too when the reader hid it.
2220
+ // It also comes back with its own opacity and painting: a paused
2221
+ // Indicator's rebuilt heatmaps take the pause dim again, and a paint-cost
2222
+ // pause's suspension reaches its rebuilt canvases (once per owner, after
2223
+ // its rebuild). A child refreshed in place keeps its overlay, its eye and
2224
+ // its painting, but its settings took the retranslated opacity: the pause
2225
+ // dim goes on again (it writes only what moved).
2226
+ for (const { state, ctx } of new Set(ownerOf.values())) {
2227
+ syncChildVisibility(tc, state.parent, state, rebuilt.get(state) ?? []);
2228
+ if (rebuilt.has(state) || refreshed.has(state))
2229
+ reapplyWrunPauseDim(tc, ctx.overlayId);
2230
+ if (rebuilt.has(state))
2231
+ wrunChartHostEnv().chart.reapplyPausedOverlayPaint(tc, ctx.overlayId);
2232
+ }
2233
+ tc.processData?.();
2234
+ tc.renderService?.renderOnce?.();
2235
+ }
2236
+ /**
2237
+ * Re-pick the colour bounds of an Indicator's mounted heatmaps for the
2238
+ * viewer's Sensitivity, with no run. With `preview` the named heatmap holds
2239
+ * the slider's drag value (ahead of the saved row, for every mount until a
2240
+ * commit); without one the call commits: held values drop and every heatmap
2241
+ * takes its saved row (`heatmap:<name>:sensitivity` on the parent's engine
2242
+ * settings; none draws the author's bounds). Only `min` and `max` move on the
2243
+ * engine meta: titan reads meta.settings on every draw and keys its colour
2244
+ * table on the bounds, so there is no row swap and no remount. The bounds go
2245
+ * through the engine's settings door (`updateSettings`), which also commits a
2246
+ * content mutation, so the 2D strip cache of the canvas fallback never blits
2247
+ * pixels drawn with the old bounds back on a live-edge sliver. The mounted
2248
+ * record keeps the config with the bounds it now holds, so the next run
2249
+ * diffs against them. Returns whether a bound moved.
2250
+ */
2251
+ export function rescaleWrunHeatmapChildren(tc, overlayId, preview) {
2252
+ const state = chartChildren.get(tc)?.get(overlayId);
2253
+ if (!state || tc.isDestroyed)
2254
+ return false;
2255
+ if (preview !== undefined)
2256
+ (state.previews ??= new Map()).set(preview.name, preview.value);
2257
+ else
2258
+ state.previews = undefined;
2259
+ const parent = tc.metadata.find((meta) => meta.id === overlayId);
2260
+ if (!parent || state.parent !== parent)
2261
+ return false;
2262
+ let moved = false;
2263
+ for (const [id, mounted] of state.children) {
2264
+ const input = mounted.input;
2265
+ if (input.kind !== 'heatmap' || input.scale === undefined)
2266
+ continue;
2267
+ if (preview !== undefined && input.name !== preview.name)
2268
+ continue;
2269
+ const meta = tc.metadata.find((candidate) => candidate.id === id);
2270
+ if (!meta)
2271
+ continue;
2272
+ const { min, max } = wrunHeatmapSensitivityBounds(input, heatmapSensitivityOf(state.previews, parent, input.name));
2273
+ const settings = (meta.settings ??= {});
2274
+ if (!Object.is(settings.min, min) || !Object.is(settings.max, max)) {
2275
+ moved = true;
2276
+ if (typeof tc.updateSettings === 'function')
2277
+ void tc.updateSettings(id, { min, max });
2278
+ else {
2279
+ settings.min = min;
2280
+ settings.max = max;
2281
+ }
2282
+ }
2283
+ state.children.set(id, {
2284
+ input,
2285
+ config: { ...mounted.config, settings: { ...mounted.config.settings, min, max } },
2286
+ });
2287
+ }
2288
+ // The settings door schedules its own paint; a chart without it repaints here.
2289
+ if (moved && typeof tc.updateSettings !== 'function')
2290
+ tc.renderService?.renderOnce?.();
2291
+ return moved;
2292
+ }
2293
+ /**
2294
+ * A replay cut of an Indicator's batched children (WRUN-BATCHED-MARKS, round-2 fold 9), synchronous with
2295
+ * the cut of the engine rows (wrun-replay-rows.util, which also tells the engine the rows moved in place so
2296
+ * a pack's cached geometry is read again): each mounted batched child's record (the input a retranslate
2297
+ * rebuilds from and the config) keeps the rows inside [fromTs, toTs] (fromTs NaN keeps every row through
2298
+ * toTs) and its cell ledger follows. A theme or timezone switch while the replay holds its reseed then
2299
+ * rebuilds the cut rows, never the rows the step took away. Returns the child ids whose records were cut.
2300
+ */
2301
+ export function cutWrunBatchedChildRecords(tc, overlayId, fromTs, toTs) {
2302
+ const state = chartChildren.get(tc)?.get(overlayId);
2303
+ if (!state || tc.isDestroyed)
2304
+ return [];
2305
+ const cut = [];
2306
+ for (const [id, record] of state.children) {
2307
+ if (!isBatchedRecord(record))
2308
+ continue;
2309
+ const rows = record.config.data;
2310
+ const kept = rows.filter((row) => {
2311
+ const ts = rowTs(row);
2312
+ return ts !== undefined && (!Number.isFinite(fromTs) || ts >= fromTs) && ts <= toTs;
2313
+ });
2314
+ if (kept.length === rows.length)
2315
+ continue;
2316
+ keepHeatmapRows(record, kept);
2317
+ noteWrunBatchedRowsCut(tc, overlayId, id, kept, wrunBatchedChargeOf(record.config.settings));
2318
+ cut.push(id);
2319
+ }
2320
+ return cut;
2321
+ }
2322
+ /** Full compute runs await the async work started by the synchronous
2323
+ * integration seam. A failed pack never becomes a successful full run. */
2324
+ export function awaitWrunChildOverlays(tc, overlayId) {
2325
+ return (chartChildren.get(tc)?.get(overlayId)?.pending ?? Promise.resolve(!tc.isDestroyed && overlayPresent(tc, overlayId)));
2326
+ }
2327
+ /** Explicit teardown is also used by the engine's post-removal object event. */
2328
+ export function unmountWrunChildOverlays(tc, overlayId) {
2329
+ const owners = chartChildren.get(tc);
2330
+ const state = owners?.get(overlayId);
2331
+ if (!state)
2332
+ return;
2333
+ owners?.delete(overlayId);
2334
+ state.token = Symbol(overlayId);
2335
+ state.unsubscribe?.();
2336
+ // The children leave; a pane the reader expanded elsewhere stays expanded (a removal of the parent itself ended
2337
+ // focus before this runs, so nothing is entered again then).
2338
+ keepFocusedPane(tc, () => {
2339
+ for (const [id, mounted] of state.children)
2340
+ retireChild(tc, id, mounted.input.kind, false);
2341
+ });
2342
+ state.children.clear();
2343
+ }
2344
+ // The boot graph's door (wrun-panel-mount.lazy.ts): bound as this module evaluates, since it owns
2345
+ // the mounted children, so the timezone sync reaches them in its own turn whenever any exist.
2346
+ bindWrunPanelMountRuntime({ retranslateWrunChildOverlays, cutWrunBatchedChildRecords });