@orangecharts/wrun-chart-host 0.2.0 → 0.4.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 (342) hide show
  1. package/README.md +22 -8
  2. package/dist/constants/common.constants.d.ts +15 -0
  3. package/dist/constants/common.constants.js +23 -0
  4. package/dist/constants/data-source.constants.d.ts +1 -0
  5. package/dist/constants/data-source.constants.js +1 -0
  6. package/dist/constants/economic.constants.d.ts +39 -0
  7. package/dist/constants/economic.constants.js +77 -0
  8. package/dist/constants/etf-covered-coins.constants.d.ts +1 -0
  9. package/dist/constants/etf-covered-coins.constants.js +9 -0
  10. package/dist/constants/feature-flags.constants.d.ts +60 -0
  11. package/dist/constants/feature-flags.constants.js +308 -0
  12. package/dist/constants/feature-limits.constants.d.ts +134 -0
  13. package/dist/constants/feature-limits.constants.js +155 -0
  14. package/dist/constants/marketCapabilities.constants.d.ts +87 -0
  15. package/dist/constants/marketCapabilities.constants.js +213 -0
  16. package/dist/constants/option-venues.constants.d.ts +100 -0
  17. package/dist/constants/option-venues.constants.js +167 -0
  18. package/dist/constants/overlay-data.constants.d.ts +53 -0
  19. package/dist/constants/overlay-data.constants.js +80 -0
  20. package/dist/constants/pane-grid.constants.d.ts +15 -0
  21. package/dist/constants/pane-grid.constants.js +17 -0
  22. package/dist/constants/scriptEditor/builtin-script-snippets.d.ts +133 -0
  23. package/dist/constants/scriptEditor/builtin-script-snippets.js +451 -0
  24. package/dist/constants/venue-presets.constants.d.ts +10 -0
  25. package/dist/constants/venue-presets.constants.js +22 -0
  26. package/dist/enums/chart.enum.d.ts +68 -0
  27. package/dist/enums/chart.enum.js +70 -0
  28. package/dist/helpers/data.helpers.d.ts +2 -0
  29. package/dist/helpers/data.helpers.js +14 -0
  30. package/dist/host-env.d.ts +163 -5
  31. package/dist/host-ports.types.d.ts +431 -0
  32. package/dist/host-ports.types.js +1 -0
  33. package/dist/index.d.ts +138 -0
  34. package/dist/index.js +138 -0
  35. package/dist/indicators/controls/technical-script/technical-script-input-rendering.d.ts +86 -0
  36. package/dist/indicators/controls/technical-script/technical-script-input-rendering.js +179 -0
  37. package/dist/interfaces/asset-venue.interface.d.ts +91 -0
  38. package/dist/interfaces/asset-venue.interface.js +1 -0
  39. package/dist/interfaces/cancel-reason.interface.d.ts +24 -0
  40. package/dist/interfaces/cancel-reason.interface.js +2 -0
  41. package/dist/interfaces/catalog-display.interface.d.ts +3 -0
  42. package/dist/interfaces/catalog-display.interface.js +1 -0
  43. package/dist/interfaces/cme-realtime.interface.d.ts +251 -0
  44. package/dist/interfaces/cme-realtime.interface.js +46 -0
  45. package/dist/interfaces/feed.interface.d.ts +80 -0
  46. package/dist/interfaces/feed.interface.js +7 -0
  47. package/dist/interfaces/market-kind.interface.d.ts +8 -0
  48. package/dist/interfaces/market-kind.interface.js +1 -0
  49. package/dist/interfaces/opra-realtime.interface.d.ts +224 -0
  50. package/dist/interfaces/opra-realtime.interface.js +105 -0
  51. package/dist/interfaces/option-instrument.interface.d.ts +32 -0
  52. package/dist/interfaces/option-instrument.interface.js +1 -0
  53. package/dist/interfaces/options-chain-scope.interface.d.ts +29 -0
  54. package/dist/interfaces/options-chain-scope.interface.js +7 -0
  55. package/dist/interfaces/prediction-market.interface.d.ts +88 -0
  56. package/dist/interfaces/prediction-market.interface.js +8 -0
  57. package/dist/interfaces/wrun-runtime.interface.d.ts +5 -0
  58. package/dist/kscript-data/controls/live-trades-merge.util.d.ts +185 -0
  59. package/dist/kscript-data/controls/live-trades-merge.util.js +357 -0
  60. package/dist/settings-templates/frvp-fields.d.ts +27 -0
  61. package/dist/settings-templates/frvp-fields.js +108 -0
  62. package/dist/settings-templates/index.d.ts +119 -0
  63. package/dist/settings-templates/index.js +442 -0
  64. package/dist/settings-templates/indicator-fields.d.ts +56 -0
  65. package/dist/settings-templates/indicator-fields.js +793 -0
  66. package/dist/settings-templates/tool-rules.d.ts +59 -0
  67. package/dist/settings-templates/tool-rules.js +49 -0
  68. package/dist/settings-templates/tool-tables.generated.d.ts +2 -0
  69. package/dist/settings-templates/tool-tables.generated.js +1668 -0
  70. package/dist/utility/blk-market.util.d.ts +5 -0
  71. package/dist/utility/blk-market.util.js +12 -0
  72. package/dist/utility/chart/chart-load-phase.util.d.ts +32 -0
  73. package/dist/utility/chart/chart-load-phase.util.js +78 -0
  74. package/dist/utility/chart/cme-cache-context.util.d.ts +108 -0
  75. package/dist/utility/chart/cme-cache-context.util.js +166 -0
  76. package/dist/utility/chart/cme-session-bucket.util.d.ts +82 -0
  77. package/dist/utility/chart/cme-session-bucket.util.js +343 -0
  78. package/dist/utility/chart/cme-trade-calendar.util.d.ts +26 -0
  79. package/dist/utility/chart/cme-trade-calendar.util.js +147 -0
  80. package/dist/utility/chart/continuous-contracts.util.d.ts +138 -0
  81. package/dist/utility/chart/continuous-contracts.util.js +374 -0
  82. package/dist/utility/chart/date-labelled-interval.leaf.d.ts +15 -0
  83. package/dist/utility/chart/date-labelled-interval.leaf.js +19 -0
  84. package/dist/utility/chart/feed-interval.util.d.ts +119 -0
  85. package/dist/utility/chart/feed-interval.util.js +321 -0
  86. package/dist/utility/chart/fetch-dedupe-policy.util.d.ts +110 -0
  87. package/dist/utility/chart/fetch-dedupe-policy.util.js +407 -0
  88. package/dist/utility/chart/footprint-band.util.d.ts +76 -0
  89. package/dist/utility/chart/footprint-band.util.js +205 -0
  90. package/dist/utility/chart/footprint-cell-identity.util.d.ts +82 -0
  91. package/dist/utility/chart/footprint-cell-identity.util.js +346 -0
  92. package/dist/utility/chart/formula-calendar.util.d.ts +27 -0
  93. package/dist/utility/chart/formula-calendar.util.js +59 -0
  94. package/dist/utility/chart/history-wall.util.d.ts +67 -0
  95. package/dist/utility/chart/history-wall.util.js +87 -0
  96. package/dist/utility/chart/index-mode.util.d.ts +66 -0
  97. package/dist/utility/chart/index-mode.util.js +360 -0
  98. package/dist/utility/chart/indicator-coverage-planner.util.d.ts +217 -0
  99. package/dist/utility/chart/indicator-coverage-planner.util.js +443 -0
  100. package/dist/utility/chart/indicator-coverage-state.util.d.ts +33 -0
  101. package/dist/utility/chart/indicator-coverage-state.util.js +110 -0
  102. package/dist/utility/chart/indicator-gap-detector.util.d.ts +127 -0
  103. package/dist/utility/chart/indicator-gap-detector.util.js +260 -0
  104. package/dist/utility/chart/indicator-gap-repair.util.d.ts +88 -0
  105. package/dist/utility/chart/indicator-gap-repair.util.js +177 -0
  106. package/dist/utility/chart/indicator-inflight-registry.util.d.ts +26 -0
  107. package/dist/utility/chart/indicator-inflight-registry.util.js +254 -0
  108. package/dist/utility/chart/indicator-run-interval.util.d.ts +130 -0
  109. package/dist/utility/chart/indicator-run-interval.util.js +268 -0
  110. package/dist/utility/chart/interval-registry.util.d.ts +23 -0
  111. package/dist/utility/chart/interval-registry.util.js +83 -0
  112. package/dist/utility/chart/kscript-main-grid-stages.util.d.ts +21 -0
  113. package/dist/utility/chart/kscript-main-grid-stages.util.js +332 -0
  114. package/dist/utility/chart/legacy-exchange.leaf.d.ts +11 -0
  115. package/dist/utility/chart/legacy-exchange.leaf.js +43 -0
  116. package/dist/utility/chart/live-bucket.util.d.ts +66 -0
  117. package/dist/utility/chart/live-bucket.util.js +165 -0
  118. package/dist/utility/chart/market-session-schedule.util.d.ts +91 -0
  119. package/dist/utility/chart/market-session-schedule.util.js +337 -0
  120. package/dist/utility/chart/marketKind.util.d.ts +181 -0
  121. package/dist/utility/chart/marketKind.util.js +371 -0
  122. package/dist/utility/chart/opra-read-access.leaf.d.ts +26 -0
  123. package/dist/utility/chart/opra-read-access.leaf.js +25 -0
  124. package/dist/utility/chart/prediction-identity.util.d.ts +159 -0
  125. package/dist/utility/chart/prediction-identity.util.js +236 -0
  126. package/dist/utility/chart/rth-session.util.d.ts +352 -0
  127. package/dist/utility/chart/rth-session.util.js +926 -0
  128. package/dist/utility/chart/titan-constants.pin.d.ts +43 -0
  129. package/dist/utility/chart/titan-constants.pin.js +50 -0
  130. package/dist/utility/chart/us-equities-session.util.d.ts +127 -0
  131. package/dist/utility/chart/us-equities-session.util.js +251 -0
  132. package/dist/utility/chart/window-geometry.leaf.d.ts +119 -0
  133. package/dist/utility/chart/window-geometry.leaf.js +391 -0
  134. package/dist/utility/chart/window-owner.leaf.d.ts +19 -0
  135. package/dist/utility/chart/window-owner.leaf.js +24 -0
  136. package/dist/utility/chart/wrun-bar-session-facts.util.d.ts +100 -0
  137. package/dist/utility/chart/wrun-bar-session-facts.util.js +354 -0
  138. package/dist/utility/chart/wrun-wire-ref.util.d.ts +23 -0
  139. package/dist/utility/chart/wrun-wire-ref.util.js +16 -0
  140. package/dist/utility/common/safe-math-eval.d.ts +18 -0
  141. package/dist/utility/common/safe-math-eval.js +160 -0
  142. package/dist/utility/common/time.util.d.ts +134 -0
  143. package/dist/utility/common/time.util.js +428 -0
  144. package/dist/utility/common/transformations.util.d.ts +126 -0
  145. package/dist/utility/common/transformations.util.js +711 -0
  146. package/dist/utility/common/visible-timeout.util.d.ts +17 -0
  147. package/dist/utility/common/visible-timeout.util.js +75 -0
  148. package/dist/utility/exchange-normalization.util.d.ts +8 -0
  149. package/dist/utility/exchange-normalization.util.js +32 -0
  150. package/dist/utility/html-escape.leaf.d.ts +11 -0
  151. package/dist/utility/html-escape.leaf.js +20 -0
  152. package/dist/utility/intl-locale.util.d.ts +2 -0
  153. package/dist/utility/intl-locale.util.js +28 -0
  154. package/dist/utility/number-format.util.d.ts +14 -1
  155. package/dist/utility/number-format.util.js +50 -19
  156. package/dist/utility/options/option-symbol.util.d.ts +28 -0
  157. package/dist/utility/options/option-symbol.util.js +176 -0
  158. package/dist/utility/options/option-trade-units.util.d.ts +190 -0
  159. package/dist/utility/options/option-trade-units.util.js +283 -0
  160. package/dist/utility/options/option-venue.util.d.ts +75 -0
  161. package/dist/utility/options/option-venue.util.js +85 -0
  162. package/dist/utility/pool-symbol.leaf.d.ts +34 -0
  163. package/dist/utility/pool-symbol.leaf.js +95 -0
  164. package/dist/utility/scriptEditor/wrun-runtime-diagnostics.leaf.d.ts +109 -0
  165. package/dist/utility/scriptEditor/wrun-runtime-diagnostics.leaf.js +302 -0
  166. package/dist/utility/symbol-selection/contract-expiry.util.d.ts +39 -0
  167. package/dist/utility/symbol-selection/contract-expiry.util.js +111 -0
  168. package/dist/utility/v2/gate-plane.util.d.ts +58 -0
  169. package/dist/utility/v2/gate-plane.util.js +99 -0
  170. package/dist/utility/v2/gate-session-latch.util.d.ts +22 -0
  171. package/dist/utility/v2/gate-session-latch.util.js +34 -0
  172. package/dist/utility/watchlist/import/tradingview-symbols.leaf.d.ts +76 -0
  173. package/dist/utility/watchlist/import/tradingview-symbols.leaf.js +221 -0
  174. package/dist/utility/wrun/sources/host-grid-landing.d.ts +15 -0
  175. package/dist/utility/wrun/sources/host-grid-landing.js +26 -0
  176. package/dist/utility/wrun/sources/lanes/bitfinex_funding.d.ts +27 -0
  177. package/dist/utility/wrun/sources/lanes/bitfinex_funding.js +85 -0
  178. package/dist/utility/wrun/sources/lanes/economic.d.ts +27 -0
  179. package/dist/utility/wrun/sources/lanes/economic.js +79 -0
  180. package/dist/utility/wrun/sources/lanes/etf_holdings.d.ts +35 -0
  181. package/dist/utility/wrun/sources/lanes/etf_holdings.js +165 -0
  182. package/dist/utility/wrun/sources/lanes/etf_premium.d.ts +19 -0
  183. package/dist/utility/wrun/sources/lanes/etf_premium.js +114 -0
  184. package/dist/utility/wrun/sources/lanes/ethena_positions.d.ts +30 -0
  185. package/dist/utility/wrun/sources/lanes/ethena_positions.js +51 -0
  186. package/dist/utility/wrun/sources/lanes/index.d.ts +2 -0
  187. package/dist/utility/wrun/sources/lanes/index.js +32 -0
  188. package/dist/utility/wrun/sources/lanes/long_short_ratio.d.ts +17 -0
  189. package/dist/utility/wrun/sources/lanes/long_short_ratio.js +47 -0
  190. package/dist/utility/wrun/sources/lanes/option_daily.d.ts +58 -0
  191. package/dist/utility/wrun/sources/lanes/option_daily.js +111 -0
  192. package/dist/utility/wrun/sources/lanes/option_stats_10m.d.ts +27 -0
  193. package/dist/utility/wrun/sources/lanes/option_stats_10m.js +21 -0
  194. package/dist/utility/wrun/sources/lanes/options_flow.d.ts +50 -0
  195. package/dist/utility/wrun/sources/lanes/options_flow.js +155 -0
  196. package/dist/utility/wrun/sources/lanes/options_oi.d.ts +29 -0
  197. package/dist/utility/wrun/sources/lanes/options_oi.js +59 -0
  198. package/dist/utility/wrun/sources/lanes/options_volume.d.ts +38 -0
  199. package/dist/utility/wrun/sources/lanes/options_volume.js +63 -0
  200. package/dist/utility/wrun/sources/lanes/series.d.ts +67 -0
  201. package/dist/utility/wrun/sources/lanes/series.js +321 -0
  202. package/dist/utility/wrun/sources/lanes/token_supply.d.ts +30 -0
  203. package/dist/utility/wrun/sources/lanes/token_supply.js +145 -0
  204. package/dist/utility/wrun/sources/lanes/treasury_balance.d.ts +25 -0
  205. package/dist/utility/wrun/sources/lanes/treasury_balance.js +47 -0
  206. package/dist/utility/wrun/sources/lanes/volatility_index.d.ts +21 -0
  207. package/dist/utility/wrun/sources/lanes/volatility_index.js +11 -0
  208. package/dist/utility/wrun/sources/opra-option-lanes.util.d.ts +215 -0
  209. package/dist/utility/wrun/sources/opra-option-lanes.util.js +477 -0
  210. package/dist/utility/wrun/sources/registry.d.ts +21 -0
  211. package/dist/utility/wrun/sources/registry.js +237 -0
  212. package/dist/utility/wrun/sources/row-lane-registry.d.ts +28 -0
  213. package/dist/utility/wrun/sources/row-lane-registry.js +230 -0
  214. package/dist/utility/wrun/sources/row-lanes/index.d.ts +2 -0
  215. package/dist/utility/wrun/sources/row-lanes/index.js +12 -0
  216. package/dist/utility/wrun/sources/row-lanes/option_contract_flow.d.ts +2 -0
  217. package/dist/utility/wrun/sources/row-lanes/option_contract_flow.js +38 -0
  218. package/dist/utility/wrun/sources/row-lanes/option_contract_state.d.ts +55 -0
  219. package/dist/utility/wrun/sources/row-lanes/option_contract_state.js +126 -0
  220. package/dist/utility/wrun/sources/row-lanes/option_prints.d.ts +4 -0
  221. package/dist/utility/wrun/sources/row-lanes/option_prints.js +191 -0
  222. package/dist/utility/wrun/sources/row-lanes/option_strikes.d.ts +62 -0
  223. package/dist/utility/wrun/sources/row-lanes/option_strikes.js +147 -0
  224. package/dist/utility/wrun/sources/row-lanes/option_surface.d.ts +70 -0
  225. package/dist/utility/wrun/sources/row-lanes/option_surface.js +144 -0
  226. package/dist/utility/wrun/sources/wrun-poll-lane.types.d.ts +309 -0
  227. package/dist/utility/wrun/sources/wrun-poll-lane.types.js +26 -0
  228. package/dist/utility/wrun/sources/wrun-poll-lanes.util.d.ts +350 -0
  229. package/dist/utility/wrun/sources/wrun-poll-lanes.util.js +576 -0
  230. package/dist/utility/wrun/sources/wrun-row-lane.types.d.ts +275 -0
  231. package/dist/utility/wrun/sources/wrun-row-lane.types.js +16 -0
  232. package/dist/utility/wrun/sources/wrun-row-lanes.util.d.ts +207 -0
  233. package/dist/utility/wrun/sources/wrun-row-lanes.util.js +450 -0
  234. package/dist/utility/wrun/wrun-browser-sources.leaf.d.ts +28 -0
  235. package/dist/utility/wrun/wrun-browser-sources.leaf.js +66 -0
  236. package/dist/utility/wrun/wrun-cloud-record.util.d.ts +65 -0
  237. package/dist/utility/wrun/wrun-cloud-record.util.js +121 -0
  238. package/dist/utility/wrun/wrun-daily-lane.util.d.ts +95 -0
  239. package/dist/utility/wrun/wrun-daily-lane.util.js +297 -0
  240. package/dist/utility/wrun/wrun-deadline.util.d.ts +52 -0
  241. package/dist/utility/wrun/wrun-deadline.util.js +82 -0
  242. package/dist/utility/wrun/wrun-etf-flow-lane.util.d.ts +94 -0
  243. package/dist/utility/wrun/wrun-etf-flow-lane.util.js +224 -0
  244. package/dist/utility/wrun/wrun-etf-funds.util.d.ts +82 -0
  245. package/dist/utility/wrun/wrun-etf-funds.util.js +242 -0
  246. package/dist/utility/wrun/wrun-frames.d.ts +20 -1
  247. package/dist/utility/wrun/wrun-frames.js +103 -49
  248. package/dist/utility/wrun/wrun-hosted-wire-caps.d.ts +2 -2
  249. package/dist/utility/wrun/wrun-hosted-wire-caps.js +27 -0
  250. package/dist/utility/wrun/wrun-lane-refusal.leaf.d.ts +22 -0
  251. package/dist/utility/wrun/wrun-lane-refusal.leaf.js +32 -0
  252. package/dist/utility/wrun/wrun-lane-warmup.util.d.ts +18 -0
  253. package/dist/utility/wrun/wrun-lane-warmup.util.js +112 -0
  254. package/dist/utility/wrun/wrun-leg-close.util.d.ts +57 -0
  255. package/dist/utility/wrun/wrun-leg-close.util.js +187 -0
  256. package/dist/utility/wrun/wrun-leg-fetch.util.d.ts +144 -0
  257. package/dist/utility/wrun/wrun-leg-fetch.util.js +212 -0
  258. package/dist/utility/wrun/wrun-leg-stream-classes.d.ts +73 -0
  259. package/dist/utility/wrun/wrun-leg-stream-classes.js +86 -0
  260. package/dist/utility/wrun/wrun-levels-child.util.d.ts +101 -6
  261. package/dist/utility/wrun/wrun-levels-child.util.js +335 -157
  262. package/dist/utility/wrun/wrun-memory-clamp.util.d.ts +33 -0
  263. package/dist/utility/wrun/wrun-memory-clamp.util.js +146 -0
  264. package/dist/utility/wrun/wrun-odds-template-market.util.d.ts +51 -0
  265. package/dist/utility/wrun/wrun-odds-template-market.util.js +251 -0
  266. package/dist/utility/wrun/wrun-opra-flow.leaf.d.ts +65 -0
  267. package/dist/utility/wrun/wrun-opra-flow.leaf.js +94 -0
  268. package/dist/utility/wrun/wrun-opra-lane.util.d.ts +47 -0
  269. package/dist/utility/wrun/wrun-opra-lane.util.js +58 -0
  270. package/dist/utility/wrun/wrun-opra-stats.leaf.d.ts +49 -0
  271. package/dist/utility/wrun/wrun-opra-stats.leaf.js +115 -0
  272. package/dist/utility/wrun/wrun-opra-underlying.util.d.ts +12 -0
  273. package/dist/utility/wrun/wrun-opra-underlying.util.js +1 -0
  274. package/dist/utility/wrun/wrun-option-contract-flow.util.d.ts +142 -0
  275. package/dist/utility/wrun/wrun-option-contract-flow.util.js +451 -0
  276. package/dist/utility/wrun/wrun-option-knobs.util.d.ts +43 -0
  277. package/dist/utility/wrun/wrun-option-knobs.util.js +81 -0
  278. package/dist/utility/wrun/wrun-option-prints.util.d.ts +144 -0
  279. package/dist/utility/wrun/wrun-option-prints.util.js +356 -0
  280. package/dist/utility/wrun/wrun-option-summary-lane.util.d.ts +102 -0
  281. package/dist/utility/wrun/wrun-option-summary-lane.util.js +143 -0
  282. package/dist/utility/wrun/wrun-options-chain.util.d.ts +308 -0
  283. package/dist/utility/wrun/wrun-options-chain.util.js +502 -0
  284. package/dist/utility/wrun/wrun-overlay-identity.util.d.ts +9 -4
  285. package/dist/utility/wrun/wrun-overlay-identity.util.js +16 -6
  286. package/dist/utility/wrun/wrun-panel-mount.lazy.d.ts +10 -0
  287. package/dist/utility/wrun/wrun-panel-mount.lazy.js +68 -0
  288. package/dist/utility/wrun/wrun-panel-mount.util.d.ts +377 -0
  289. package/dist/utility/wrun/wrun-panel-mount.util.js +2251 -0
  290. package/dist/utility/wrun/wrun-param-map.util.d.ts +298 -0
  291. package/dist/utility/wrun/wrun-param-map.util.js +581 -0
  292. package/dist/utility/wrun/wrun-pause-dim.util.d.ts +52 -0
  293. package/dist/utility/wrun/wrun-pause-dim.util.js +153 -0
  294. package/dist/utility/wrun/wrun-pin-spelling.util.d.ts +149 -0
  295. package/dist/utility/wrun/wrun-pin-spelling.util.js +523 -0
  296. package/dist/utility/wrun/wrun-pin-venues.util.d.ts +116 -0
  297. package/dist/utility/wrun/wrun-pin-venues.util.js +320 -0
  298. package/dist/utility/wrun/wrun-pinned-interval.util.d.ts +20 -0
  299. package/dist/utility/wrun/wrun-pinned-interval.util.js +47 -0
  300. package/dist/utility/wrun/wrun-plot-gate.types.d.ts +23 -0
  301. package/dist/utility/wrun/wrun-plot-gate.types.js +7 -0
  302. package/dist/utility/wrun/wrun-present-bits.util.d.ts +37 -0
  303. package/dist/utility/wrun/wrun-present-bits.util.js +73 -0
  304. package/dist/utility/wrun/wrun-protocol-pending.util.d.ts +33 -0
  305. package/dist/utility/wrun/wrun-protocol-pending.util.js +57 -0
  306. package/dist/utility/wrun/wrun-refusal.util.d.ts +41 -1
  307. package/dist/utility/wrun/wrun-refusal.util.js +69 -2
  308. package/dist/utility/wrun/wrun-registry-errors.util.d.ts +1 -14
  309. package/dist/utility/wrun/wrun-registry-errors.util.js +0 -16
  310. package/dist/utility/wrun/wrun-row-source.d.ts +158 -0
  311. package/dist/utility/wrun/wrun-row-source.js +75 -0
  312. package/dist/utility/wrun/wrun-run-health.util.d.ts +155 -0
  313. package/dist/utility/wrun/wrun-run-health.util.js +273 -0
  314. package/dist/utility/wrun/wrun-run-interval-projection.types.d.ts +14 -0
  315. package/dist/utility/wrun/wrun-run-interval-projection.types.js +1 -0
  316. package/dist/utility/wrun/wrun-socket-row-source.d.ts +439 -0
  317. package/dist/utility/wrun/wrun-socket-row-source.js +1689 -0
  318. package/dist/utility/wrun/wrun-socket-session-losses.util.d.ts +18 -0
  319. package/dist/utility/wrun/wrun-socket-session-losses.util.js +25 -0
  320. package/dist/utility/wrun/wrun-source-rows.util.d.ts +911 -0
  321. package/dist/utility/wrun/wrun-source-rows.util.js +2597 -0
  322. package/dist/utility/wrun/wrun-tape-source.util.d.ts +82 -0
  323. package/dist/utility/wrun/wrun-tape-source.util.js +151 -0
  324. package/dist/utility/wrun/wrun-tier-grid.util.d.ts +137 -0
  325. package/dist/utility/wrun/wrun-tier-grid.util.js +279 -0
  326. package/dist/utility/wrun/wrun-trades-lane.util.d.ts +52 -0
  327. package/dist/utility/wrun/wrun-trades-lane.util.js +58 -0
  328. package/dist/utility/wrun/wrun-volume-profile-lane.util.d.ts +41 -0
  329. package/dist/utility/wrun/wrun-volume-profile-lane.util.js +66 -0
  330. package/dist/utility/wrun-display-name.util.d.ts +33 -0
  331. package/dist/utility/wrun-display-name.util.js +64 -0
  332. package/dist/workers/constants/kscript-transport-codes.d.ts +15 -0
  333. package/dist/workers/constants/kscript-transport-codes.js +15 -0
  334. package/dist/workers/constants/socket-slots.d.ts +574 -0
  335. package/dist/workers/constants/socket-slots.js +539 -0
  336. package/dist/workers/utils/number.worker.util.d.ts +5 -0
  337. package/dist/workers/utils/number.worker.util.js +10 -0
  338. package/dist/workers/utils/time.worker.util.d.ts +12 -0
  339. package/dist/workers/utils/time.worker.util.js +24 -0
  340. package/dist/workers/utils/volume-profile.worker.util.d.ts +200 -0
  341. package/dist/workers/utils/volume-profile.worker.util.js +631 -0
  342. package/package.json +10 -4
@@ -0,0 +1,2597 @@
1
+ /**
2
+ * Chart rows -> WRUN input rows: maps each declared input (via
3
+ * `metadata.inputSources`) onto the per-source rows the chart's kScript lane
4
+ * already fetches, producing the positional scalar block plus cell blocks on
5
+ * the PRIMARY (ohlcv) grid.
6
+ *
7
+ * The rows are built by the shared wrun host (`planWrunRun` and
8
+ * `alignWrunRows` under the chart-browser profile, through the seam
9
+ * wrun-shared-host.ts): this module keeps the browser's lanes, its planners
10
+ * and their refusals in the browser's words, and answers the host's plan
11
+ * with the rows each lane and leg fetched (`wrunHostRunOf`). The contract
12
+ * below is the lanes' and the host's rows over them (contract Amendment 11:
13
+ * the chart app's own reads, the program decisions where they differ: a
14
+ * carry input's leading gap abstains the row, absent from the output; nan
15
+ * and zero read their fill on every bar, the leading ones included; a nan or
16
+ * zero primary rides the dense grid at the chart's phase, save a candle
17
+ * class's, which walks the chart's candles (a bucket with no trade is no
18
+ * bar); book cells are sorted with zero-size levels kept).
19
+ *
20
+ * Served source classes in the browser lane:
21
+ * - `ohlcv` fields (open/high/low/close/volume; `time` in ms) off the chart's
22
+ * candle rows `[ts, o, h, l, c, v]`, and the four blends (hl2, hlc3,
23
+ * ohlc4, hlcc4: wrunSourceBlend, the kit's arithmetic and NaN rule) of the
24
+ * candle each read is served: the chart's row, a pinned leg's candle (the
25
+ * folded candle of an interval pin), a foreign market's grid row, the
26
+ * folded candle of a forming view.
27
+ * - `time` with field `bar_open_sec` (the primary bar open in epoch seconds),
28
+ * `trade_date` or `session` (the bar's market facts, contract C3:
29
+ * wrun-bar-session-facts.util over `sources.venue`, the chart's market
30
+ * and bar interval; refused by name without one). Any other time field
31
+ * refuses.
32
+ * - `trades` with field `volume` and a `side` facet ('BUY' | 'SELL'), off the
33
+ * kScript buy_sell_volume lane rows `[ts, buy, sell]`, exact-joined onto
34
+ * the primary grid under the declared missing policy.
35
+ * - `oi` fields (open/high/low/close) off the kScript open_interest lane rows
36
+ * `[ts, o, h, l, c]`, exact-joined the same way.
37
+ * - `liquidations` with field `liquidations`, off the kScript K_LIQUIDATIONS
38
+ * lane rows `[ts, buyLiquidations, sellLiquidations]`
39
+ * (`liquidations.worker.ts` parse, sides zero-filled). The scalar follows
40
+ * the om runtime's frozen liquidations contract: `side` absent serves the
41
+ * per-bar TOTAL (buy + sell), `side: 'BUY' | 'SELL'` serves that side's
42
+ * column, any other side refuses by name. The series is naturally sparse,
43
+ * so ports pair it with `missing: 'nan'` (the footprint family does).
44
+ * - `funding` with field `rate_close`, off the kScript K_FUNDING_RATE lane
45
+ * rows `[ts, value]` (`k-funding-rate.worker.ts` parse). The FE lane
46
+ * serves ONE column, the close rate scaled to percent (rateClose * 100),
47
+ * so `rate_close` is the only servable field here and its unit is the FE
48
+ * engine's percent, NOT the om daemon's raw rate (the browser parity
49
+ * target is the FE kScript engine over these same rows); the om class's
50
+ * other fields (rate_open/high/low, predicted_*) refuse by name.
51
+ * - `implied_volatility` with field `implied_volatility` and a REQUIRED
52
+ * `tenor`, off the K_DERIBIT_IMPLIED_VOLATILITY lane rows `[ts, <one
53
+ * column per distinct declared tenor>]` in declaration order
54
+ * (`planWrunOptionSummaryLane`, wrun-option-summary-lane.util: the run
55
+ * pass asks exactly the declared tenors); the plan gives each input its
56
+ * column. Served: ONE_W, ONE_M, TWO_M, THREE_M, SIX_M; ONE_D, THREE_D
57
+ * and ONE_Y (no series on the gateway), a missing or unknown tenor and a
58
+ * wrong field refuse by name, before any row here and before any fetch
59
+ * in the run pass.
60
+ * - `skew` with field `skew`, a REQUIRED `tenor` and an optional `delta`
61
+ * (5, 15, 25 or 35; absent reads 25), off the K_SKEW lane rows under the
62
+ * same plan: a column per distinct (delta, tenor) pair, one K ask per
63
+ * delta zipped by timestamp (`zipWrunOptionSummaryRows`); a delta outside
64
+ * the four refuses by name before any row and before any fetch.
65
+ * - `etf_flow` with field `flow_usd` and a REQUIRED `fund` (an ETF ticker,
66
+ * or `all` for the sum over the chart coin's funds), off the kScript
67
+ * K_ETF_FLOW lane asked at DAY on every chart and zipped per declared fund
68
+ * word into `etfFlowRows` `[dayTs, ...columns]` (`wrun-etf-flow-lane.util`
69
+ * owns the contract: the coin comes from the chart market and refuses by
70
+ * name when it has no listed spot ETFs, a ticker the coin does not list
71
+ * refuses by name). A DAILY series: on an intraday chart the day's value
72
+ * lands on the FIRST bar of its day and the day's later bars follow the
73
+ * `missing` policy; a daily chart joins row for row; a coarser chart sums
74
+ * the days inside each bar. Needs the clock (the chart interval).
75
+ * - `book` (celled): the kScript orderbook lane's rows
76
+ * (`k-orderbook.worker.ts` parse: `[ts, bidPrice, bidSize, ...][askPrice,
77
+ * -askSize, ...]` with ask sizes NEGATIVE and asks sorted descending by
78
+ * price) become the ABI's `[price, abs(size), side]` tuples through the
79
+ * shared host's one cell adapter (the kScript row dialect), side +1 for a
80
+ * positive stored size / -1 for a negative one or a negated zero, in the
81
+ * shared order every host serves (a program decision): bids descending,
82
+ * then asks ascending, zero-size levels kept. A module ported against the
83
+ * lane's stored order (asks descending, walked positionally) reads another
84
+ * book here than the kScript engine does over the same rows. A primary
85
+ * bar with no book observation exact-joins as
86
+ * a PRESENT EMPTY block with a NaN placeholder in the scalar slot; celled
87
+ * inputs never gate readiness.
88
+ * - `volume_profile` (celled): the kScript K_VOLUME_PROFILE lane's
89
+ * array-celled rows (`k-volume-profile-agg.worker.ts` parse: `[ts,
90
+ * [priceLow, priceHigh, buyVolume, sellVolume], ...]` with buckets in
91
+ * stored ascending-price order) flatten into the ABI's contract-1
92
+ * 4-tuples [low, high, buy, sell] IN THE ROW'S OWN BUCKET ORDER. Unlike
93
+ * the om daemon's lane (which reconstructs low = high = price from the
94
+ * flat wire triplets), the FE lane serves REAL bucket bounds: the browser
95
+ * lane replays what the FE kScript engine sees, so the bounds survive.
96
+ * Missing observations exact-join as PRESENT EMPTY blocks, same as book.
97
+ * - `trade_volume_by_size` (celled): the K_TRADE_VOLUME_BY_SIZE lane's
98
+ * dense per-bar rows (`k-trade-volume-by-size.worker.ts`: `[ts, [bucketId,
99
+ * buyVolUsd, sellVolUsd, buyCount, sellCount], ...]`, one cell per USD
100
+ * order-size bucket that traded in the bar, ascending by bucket; a quiet
101
+ * bar is `[ts]`) flatten into the kit's 5-tuples `[bucket, buy_usd,
102
+ * sell_usd, buy_count, sell_count]` (`WRUN_TRADE_VOLUME_BY_SIZE_TUPLE_WIDTH`;
103
+ * bucket 1..7 = 0 to 1K, 1K to 10K, 10K to 100K, 100K to 500K, 500K to
104
+ * 1M, 1M to 10M, 10M and up; volumes USD notional, counts trades) IN THE
105
+ * ROW'S OWN BUCKET ORDER. Exact-joined on the primary grid: a quiet bar
106
+ * and a bar the lane holds no row for are PRESENT EMPTY blocks, like the
107
+ * profile. Own market only (the chart's symbol and exchange), a POLL lane
108
+ * (no live channel: the reconcile re-asks it).
109
+ * - `options_chain` (celled): the K_OPTIONS_CHAIN lane's snapshot rows
110
+ * `[stampTs, [strike, expiry_ms, side, oi, gamma, delta, mark_iv,
111
+ * underlying, multiplier, vega], ...]` (one tuple per listed contract, side +1
112
+ * call / -1 put; `wrun-options-chain.util.ts`). The hosts serve the LATEST
113
+ * chain, not a history of chains: the newest row's tuples become the LIVE
114
+ * primary row's block (the last chart row), every other row a PRESENT
115
+ * EMPTY block, and a package reads the chain on `bar.isLast()`. The
116
+ * input's `expiries` knob ("all" | "nearest:N") is applied here per input,
117
+ * so one lane feeds every chain input of a package; the `venue` knob is
118
+ * decided by the run lane before the fetch. A chain over `max_cells`
119
+ * refuses by name where the host builds the live row's block
120
+ * (`wrun_cell_block_too_large`, never truncated).
121
+ * - `tape` (celled): the K_TRADES large lane's rows (`k-trades.worker.ts`:
122
+ * `[barTs, [offsetMs, price, size, side], ...]`, the prints of the bar at or
123
+ * above the acquisition's `min_size`, history from TRADE_LARGE sorted by
124
+ * offset, live prints folded in arrival order by `live-trades-merge.util.ts`)
125
+ * become the ABI's `[offsetMs, price, size, side]` 4-tuples through the
126
+ * shared host's cell adapter, side +1 for a buy and -1 for a sell, in the
127
+ * row's own order, the plan's floor kept (the host plans the tape ask with
128
+ * `min_size` resolved from the run's settings, `sources.settings`, the floor
129
+ * the lane's acquisition was asked at). A primary bar with no row (before the
130
+ * served history, a quiet bar, a live-edge tape) is a PRESENT EMPTY block; a
131
+ * bar over the input's `max_cells` refuses by name where the rows are packed
132
+ * (`wrun_cell_block_too_large`, never truncated). The facets (`min_size`,
133
+ * `history`) are resolved and refused before any fetch by
134
+ * `wrun-tape-source.util.ts`, in the browser's own words.
135
+ * - `odds` (Polymarket): a pinned candle leg on the synthesized market
136
+ * `{ exchange: 'POLYMARKET', symbol: <condition id, lower-cased> }`, the
137
+ * rows the run pass fetches through the chart's K_OHLCV lane (gapfilled,
138
+ * polled live; `leg.odds` tells it apart), whose close IS the YES
139
+ * probability, 0..1, never scaled. Without an interval (or with the
140
+ * chart's own) it is a GRID leg exact-joined onto the chart grid under
141
+ * the missing policy; a coarser whole-multiple interval is a PERIOD leg
142
+ * with the `confirmed` and `is_new_period` views only. The field defaults
143
+ * to close; `outcome: 'NO'` (close only) reads `1 - close` for observed
144
+ * and carried values, a `nan` or `zero` fill staying as filled. A grid
145
+ * leg may carry ONE seed row before the first chart row (the market's
146
+ * last observation before the window, prepended by the run pass for a
147
+ * thin market): it seeds the carry of a wire that holds nothing yet, never
148
+ * overrides a `nan` / `zero` fill, and never resets a carried value when a
149
+ * live reconcile re-asks the leg without it. YES and
150
+ * NO inputs on one market share one leg. The odds input may be the
151
+ * PRIMARY (index 0), as in every kit starter: the row axis stays the
152
+ * chart's own candles either way (the hosted lane's "odds primary filled
153
+ * onto the chart grid"). Refused by name before any fetch, each with its
154
+ * stable code: the kit template's placeholder id
155
+ * (`wrun_odds_placeholder_market`), a `binding` or no `symbol`
156
+ * (`wrun_odds_binding_unsupported`: the chart has no market picker yet),
157
+ * an `exchange` (`wrun_odds_exchange_implicit`), a symbol that is not a
158
+ * condition id (`wrun_odds_symbol`), an outcome other than YES | NO or NO
159
+ * off close (`wrun_odds_outcome`), a `forming` view
160
+ * (`wrun_odds_forming_unsupported`), a chart interval under a minute
161
+ * (`wrun_odds_chart_1s`: prediction venues are blocked on seconds).
162
+ * - every class of the POLL-LANE REGISTRY (`sources/registry.ts`: one
163
+ * descriptor file per source, discovered by glob, none listed here): a
164
+ * scalar read off the lane instance the run pass planned the input into
165
+ * (`pollLanes`, `pollLaneRows`), by the lane's own join. A `bar` join
166
+ * exact-joins the bar under the missing policy like every scalar lane; a
167
+ * daily join lands day rows by the daily-lane rules (wrun-daily-lane.util:
168
+ * `sum` or `last`, needs the clock). The static plan
169
+ * (`planWrunPollLaneInputs`) refuses a celled input and a field no lane
170
+ * serves by name before any row. A `series` input (a published feed, the
171
+ * `series` lane) is planned as the kit's own series wire, so the shared
172
+ * host serves it only under the run's feed capability and seeds a carry
173
+ * from the lane's bar before the window (align rule e).
174
+ * - every class of the ROW-LANE REGISTRY (`sources/row-lane-registry.ts`:
175
+ * one celled descriptor per class, discovered by glob, none listed here):
176
+ * each input's blocks read off the instance the run pass planned it into
177
+ * (`rowLanes`, `rowLaneRows`: host-bar rows `[barOpen, ...tuples]` the run
178
+ * landed on the chart's grid), the lane's exact tuples through its
179
+ * per-input projection, exact-joined on the chart's bars (a bar with no
180
+ * row a PRESENT EMPTY block); a `latest` lane's newest row is the LIVE
181
+ * row's block, every other row an empty one (the options chain's rule).
182
+ * The shared host plans such an input as a celled stand-in and the browser
183
+ * answers it (`WRUN_ROWS_CELL_LANE_STAND_IN`): the class and its width ride
184
+ * the descriptor, so a lane serves before the kit names its class.
185
+ *
186
+ * Any other class refuses by name (fail closed), matching the daemon's
187
+ * serving-gate behavior for unserved classes.
188
+ *
189
+ * Scalar missingness honors the declared `missing` policy: absent = 'carry'
190
+ * (the latest eligible value forward-fills; until every carry input has a
191
+ * first value the row abstains, absent from the rows), 'nan' delivers NaN,
192
+ * 'zero' delivers 0 on bars that bring no observation of their own, the
193
+ * leading ones included. A nan or zero PRIMARY of a candle class (ohlcv,
194
+ * odds) walks the chart's candles on every chart, as a carry primary does:
195
+ * a candle bucket with no trade is no bar (the chart draws none, the tab's
196
+ * kScript lane serves a candle-only script none, and a NaN bar there holds
197
+ * a recursive output at NaN from the first hole on: the RSI twin on KRAKEN
198
+ * XRP/USD 1d, 2026-10-15). A nan or zero primary of any other class rides
199
+ * the host's dense grid: one row per bar open at the chart's phase from the
200
+ * first chart row through the last, a tradeless bar included; on a venue
201
+ * whose chart gives empty time no row (its gap policy is `never`: the CME
202
+ * family's daily break and weekends, a US listing's nights, forex weekends),
203
+ * a calendar chart or a daily-landed lane it walks the chart's rows instead,
204
+ * the rows the kScript lane reads (`wrunNeedsChartPrimary`). A package that
205
+ * reads another lane on the chart's timeline also runs each interior missing
206
+ * bar of the chart (a tradeless bucket between two candles) as a row, as the
207
+ * tab's kScript lane runs it for a script with another source
208
+ * (`wrunPrimaryRows`).
209
+ *
210
+ * Pinned inputs (the G4 multi-timeframe contract, round 3: the full
211
+ * version). An `ohlcv` input pinning an interval COARSER than the chart's,
212
+ * on the chart's own market or on ANOTHER market (`symbol` / `exchange`,
213
+ * any market the chart lane can fetch), is served off its own PERIOD leg:
214
+ * the candles fetched at that interval for the leg market and handed in as
215
+ * `pinnedCandleRows[fetchKey]` (`planWrunPinnedLegs` names the legs;
216
+ * `wrunPinnedLegFetchKey` is market + interval, the backend's
217
+ * `wrunFetchKey`). Four views, all derived HERE at alignment time, never
218
+ * by the module (`WrunInputSource.view`):
219
+ * - `confirmed` (absent = this): the latest leg candle `c` with
220
+ * `c.ts + L <= min(now, ts + P)` (P the chart span, L the leg span, `now`
221
+ * the evaluation clock), carried forward under the missing policy, NaN
222
+ * before the first one; the as-of close rule the backend, the daemon and
223
+ * the alerts engine apply. Gates readiness like any scalar.
224
+ * - `forming`: the running aggregate of the row's own leg bucket (a WEEK
225
+ * bucket is the Monday-anchored week, `findMonday`, the main path's
226
+ * rule; every other span is `floor(ts / L) * L`) up to and including the
227
+ * row (open = the first open, high = max, low = min, close = the latest
228
+ * close, volume = sum, time = the bucket open in ms); the declared field
229
+ * picks the component. An own-market leg folds the PRIMARY rows; a
230
+ * foreign leg folds the leg market's rows at the CHART interval, its GRID
231
+ * leg (a second fetch key `<market>|<chartInterval>`, the forming candle
232
+ * kept, tick-merged from that market's candle feed). Never gates
233
+ * readiness (no missing policy).
234
+ * - `is_new_period`: 1.0 on a DELIVERED row whose held confirmed candle
235
+ * differs from the candle held on the previously delivered row (the first
236
+ * delivered row reads 1 when any candle is held), else 0.0; 0 on the live
237
+ * forming row until it closes. A delivered row is one no carry-policy
238
+ * scalar input withholds by its leading gap (the hosts' readiness
239
+ * abstention: an abstained row is absent from the rows). On a pin
240
+ * EQUAL to the chart's interval every chart bar is a new period of its
241
+ * own interval: the view reads 1 on every row, no leg (`own_period`).
242
+ * - `offset` N: the candle the confirmed cursor held N candles before its
243
+ * current one (the leg history paragraph below); never gates readiness.
244
+ * A foreign `ohlcv` pin WITHOUT an interval (or with the chart's own) is a
245
+ * grid leg read row for row: the leg market's rows at the chart interval,
246
+ * exact-joined by timestamp under the missing policy (the forming row reads
247
+ * that market's forming candle), no view.
248
+ *
249
+ * Typed-feed interval pins (own market, the served typed classes
250
+ * `funding.rate_close` and the `oi` fields) bucket the lane's own rows by
251
+ * the clock, no extra fetch. An observation is a row with a finite
252
+ * component: a row without one is a gap fill, which the om daemon drops
253
+ * before any fold. A bucket's value: `funding` reads the LAST observation
254
+ * inside it (rate_close); `oi` folds PER COMPONENT like an ohlcv forming
255
+ * bucket (open = the first real observation's open, high = max high, low =
256
+ * min low, close = the last close; a NaN component is skipped).
257
+ * `confirmed` = the value of the HELD bucket: the latest
258
+ * bucket closed by the row's bound (bucket end <= min(now, ts + P), the
259
+ * ONE as-of row-close rule ohlcv legs use), the value carried across the
260
+ * rows that hold it, a held EMPTY bucket reading the missing policy
261
+ * (`carry` forward-fills the previous bucket's value, `nan` reads NaN,
262
+ * `zero` reads 0), NaN before the first held bucket; `forming` = the
263
+ * bucket value of the row's own bucket over the observations up to and
264
+ * including the row, NaN when none yet; `is_new_period` = 1 on the
265
+ * delivered row whose held bucket differs from the previous delivered
266
+ * row's (a bucket close fires it with or without an observation). A bucket
267
+ * that opened before the loaded window's head is partial and never held
268
+ * (the never-partial rule).
269
+ *
270
+ * Intrabar cells (`intrabar`, the fifth celled class on the wrun-2 cell
271
+ * channel; the chart's own market or one pinned with `symbol` AND `exchange`,
272
+ * finer bars folded as cells onto each chart row): `inputSources.m1 = { source:
273
+ * "intrabar", interval: "MINUTE" }` on a celled input `{ cellType: "array",
274
+ * max_cells: 60 }`. The leg is fetched at `L` over the chart window
275
+ * (`intrabarRows[fetchKey]`, `wrunIntrabarLegFetchKey`, keyed by market) and
276
+ * each row's block is the shared host's leg core slice (`WrunIntrabarSlicer`): every
277
+ * CLOSED leg candle `c` with `ts <= c.ts < ts + P`, ascending, as `[offset_ms,
278
+ * open, high, low, close, volume]` tuples, `offset_ms` = the candle's open minus
279
+ * the row's open (kScript's ltf(): each candle in the row holding its open, so a
280
+ * leg the grid does not divide straddles rows and an equal or coarser leg brings
281
+ * at most one candle to a row); a covered row with no candle is a PRESENT EMPTY
282
+ * block, a row the leg's coverage does not reach a MISSING block (no entry),
283
+ * never a partial one; never truncated (over `max_cells` the pack layer refuses,
284
+ * `wrun_cell_block_too_large`). The shape refusals fire first (a knob the class
285
+ * does not take, a scalar input, index 0 `wrun_intrabar_primary`, no interval
286
+ * `wrun_intrabar_interval_required`, one half of a market pin), then the leg
287
+ * core's plan-time check (`wrunCelledLegCheck`, the om words): a span off the
288
+ * vocabulary (`wrun_intrabar_leg_off_grid`), `max_cells` below the most candles
289
+ * a row holds (`wrun_intrabar_ratio_over_cap`). No chart refuses a leg for its
290
+ * span against the chart's: kScript declares ltf() statically and refuses only a
291
+ * read, which its originals guard by the chart interval. Readiness never gates
292
+ * (the celled rule); the scalar slot reads NaN.
293
+ *
294
+ * Leg history (WRUN-TIMEFRAMES, the shared host's leg core):
295
+ * view `offset` reads the candle the confirmed cursor held N candles back
296
+ * (`WrunOffsetRing`, a typed feed's closed buckets with an observation); the
297
+ * `candles` class streams a leg's closed candles (`WrunCandleStream`: the
298
+ * backlog on the first delivered row, then the candles admitted since, an
299
+ * undelivered row an empty block that hands its candles on, a leg without a
300
+ * closed candle a missing block), each row admitting by its own close (a
301
+ * month, quarter or year row's calendar end, never the chart's average span),
302
+ * on a leg of its own at the chart's interval (never the market's grid leg);
303
+ * a `candles` input read with view "forming" carries the leg's LIVE candle
304
+ * instead (`WrunLiveCandle`: one tuple on the row whose bar holds now, the
305
+ * venue's running candle as the leg's own fetch served it, an empty block on
306
+ * every other row, a missing block when the fetch holds no readable row),
307
+ * read from the stream's own leg fetch and never beside `bars`; one read with
308
+ * view "forming_open" carries, on EVERY row, the open of the leg candle holding
309
+ * it (`WrunFormingOpen`: one tuple [offset, open, NaN, NaN, NaN, NaN] off the
310
+ * same fetch's closed and live candles, the live candle's rows included, an
311
+ * empty block on a row no candle holds), never beside `bars` either;
312
+ * `bars` deepens a leg's fetch (the run pass); an own-market `forming` view
313
+ * folds its head bucket whole from `formingPreRoll`. The carry keeps the rings
314
+ * and each stream's resume point, so the tail build resumes them exactly
315
+ * (docs/features/kscript/wrun/wrun-browser-runtime.md, "Leg history").
316
+ *
317
+ * The builders take a `clock: { intervalMs, nowMs }` whenever a leg or a
318
+ * typed pin exists and refuse to guess without one (an open-stamped coarse
319
+ * leg is exactly the lookahead leak the clock prevents). Refused by name
320
+ * before any fetch: a market pin on anything but a secondary `ohlcv` input
321
+ * (typed feeds, cells and `time` follow the chart's own market; the primary
322
+ * input follows the chart's market; an `odds` input is the exception, it
323
+ * pins its own Polymarket market, primary included), a finer pin, a leg that is not a whole
324
+ * multiple of the chart interval (7 days for WEEK), a pin on a celled,
325
+ * `time`, trades, liquidations, implied_volatility or skew input, an
326
+ * interval pin on the primary input (index 0), an interval the vocabulary
327
+ * does not know, a view without a coarser pin, a `forming` view above WEEK,
328
+ * a `forming` view whose primary input is bindable, pinned to another
329
+ * market or not an ohlcv feed. An own-market interval pin EQUAL to the
330
+ * chart's is a no-op (the chart's own rows, as before).
331
+ *
332
+ * Contract A rules every host shares: the confirmed cursor advances on
333
+ * EVERY primary row, before any input is read, and `is_new_period` compares
334
+ * the held candle between DELIVERED rows only, so no input order can move
335
+ * the period-change signal and a late-observed carry input moves it to the
336
+ * first delivered row; the forming fold tracks validity PER COMPONENT (a
337
+ * NaN in one ohlcv column never discards the others); a bucket is never
338
+ * shipped partial: a row whose bucket the fold source's first row does not
339
+ * reach from its first primary slot (an own-market fold's pre-roll rows when
340
+ * the run pass fetched them, else the first loaded row) folds to NaN (except
341
+ * `time`, the bucket open itself) until a pan-back loads the rest, and the
342
+ * tail build gives the same answer.
343
+ */
344
+ import { wrunChartHostEnv } from '../../host-env.js';
345
+ import { FeatureFlag } from '../../constants/feature-flags.constants.js';
346
+ import { Intervals } from '../../constants/interval.constants.js';
347
+ import { barEndMs, calendarBarStartMs, calendarLongestBarMs, calendarMonthsOfMs, isCalendarIntervalMs, } from '../chart/calendar-interval.util.js';
348
+ import { WRUN_PINNED_INTERVALS, wrunPinnedIntervalOf } from './wrun-pinned-interval.util.js';
349
+ import { realMainRows } from '../chart/indicator-gap-detector.util.js';
350
+ import { findMonday } from '../chart/titan-constants.pin.js';
351
+ import { wrunBarSessionFactsResolver, } from '../chart/wrun-bar-session-facts.util.js';
352
+ import { wrunSettingRefusedMessage } from '../scriptEditor/wrun-runtime-diagnostics.leaf.js';
353
+ import { attachWrunRefusal, wrunPinFinerSeed } from './wrun-refusal.util.js';
354
+ import { planWrunRowLaneInputs, wrunRowLaneCellRows } from './sources/wrun-row-lanes.util.js';
355
+ import { wrunTradesLaneOf, wrunTradesLegLaneOf } from './wrun-trades-lane.util.js';
356
+ import { planWrunPollLaneInputs } from './sources/wrun-poll-lanes.util.js';
357
+ import { planWrunEtfFlowColumns } from './wrun-etf-flow-lane.util.js';
358
+ import { planWrunOptionSummaryLane } from './wrun-option-summary-lane.util.js';
359
+ import { WRUN_ODDS_PLACEHOLDER_MARKET } from './wrun-odds-template-market.util.js';
360
+ import { isWrunSourceBlendField, wrunFollowsCoin } from './wrun-market-facts.util.js';
361
+ import { WRUN_OPTIONS_CHAIN_EXPIRIES_CODE, wrunOptionsChainExpiries } from './wrun-options-chain.util.js';
362
+ import { wrunPinVenueVerdict } from './wrun-pin-venues.util.js';
363
+ import { WRUN_LEG_STREAM_CLASSES, isWrunLaneStreamClass, isWrunLegStreamClass, wrunLegStreamCurrency, wrunLegStreamKeyWords, } from './wrun-leg-stream-classes.js';
364
+ import { normalizeTicksPerBar } from '../../workers/utils/volume-profile.worker.util.js';
365
+ import { WRUN_VOLUME_PROFILE_TICKS_PARAM_CODE } from './wrun-volume-profile-lane.util.js';
366
+ const OHLCV_FIELD_COLUMNS = {
367
+ time: 0,
368
+ open: 1,
369
+ high: 2,
370
+ low: 3,
371
+ close: 4,
372
+ volume: 5,
373
+ };
374
+ /** True for the derived ohlcv fields, the blends hl2 / hlc3 / ohlc4 / hlcc4
375
+ * (the `param.source` menu's words no candle stores, WRUN-GAPS-1005): any
376
+ * ohlcv input may read one, as its declared field, a source default or a
377
+ * pick. Every host derives it from the candle it serves the input. */
378
+ export function isWrunDerivedOhlcvField(field) {
379
+ return isWrunSourceBlendField(field);
380
+ }
381
+ /** kScript open_interest lane row columns: [ts, open, high, low, close]. */
382
+ const OI_FIELD_COLUMNS = {
383
+ open: 1,
384
+ high: 2,
385
+ low: 3,
386
+ close: 4,
387
+ };
388
+ /** Where an open-interest stream's tuple fields sit in the browser's lane rows, in the tuple's order (open, high,
389
+ * low, close): the leg columns the shared host's stream reader takes (kit 0.86.0 `leg.columns`). */
390
+ const WRUN_OI_STREAM_LANE_COLUMNS = Object.freeze(['open', 'high', 'low', 'close'].map((field) => OI_FIELD_COLUMNS[field]));
391
+ /**
392
+ * The interior missing bars of a row array `wrunChartCandleRows` returned,
393
+ * keyed by that array: the bar opens of the chart's marker rows strictly
394
+ * between two traded candles, ascending. Kept beside the rows so every caller
395
+ * (the run and tick plans, their ends, spacing and evaluated tail, the run
396
+ * clock, the chart bar times and the executor's rows identity) reads the
397
+ * traded candles exactly as before (a clamped window slices them with
398
+ * `wrunChartCandleRowsWithin`, which carries the gaps inside it),
399
+ * while the row builder runs each gap as a bar for a package that reads
400
+ * another lane on the chart's timeline (`wrunPrimaryRows`).
401
+ */
402
+ const WRUN_CHART_GAP_BARS = new WeakMap();
403
+ /**
404
+ * The chart's candle rows as the wrun lane's PRIMARY grid: `metadata[0].rawData`
405
+ * minus the chart's own marker rows (2026-09-30), with the interior ones
406
+ * recorded as missing bars (2026-10-05).
407
+ *
408
+ * On a gap-detecting market (crypto) the main series holds one client-made
409
+ * marker row per bucket that never traded (titan `insertSyntheticGaps` and
410
+ * the live-tick bridge: `[ts, NaN, NaN, NaN, NaN]`, flagged in the
411
+ * index-aligned `syntheticFlags`) so the time axis stays uniform. A marker is
412
+ * dropped by its flag, or by a non-finite close when it arrived without one;
413
+ * a chart without markers (dense, or a session-bound venue whose grid is
414
+ * sparse by nature) returns its rows untouched. Every read of the chart's
415
+ * candles in the lane (the full run, the reseed, the tick plan and its
416
+ * evaluated tail) goes through here, so the session and the plan see one set
417
+ * of traded candles.
418
+ *
419
+ * Whether a package computes over the gaps follows from its declared inputs,
420
+ * not the caller: one that reads another lane on the chart's timeline gets a
421
+ * row at each recorded gap, as the tab's kScript lane keeps the markers for a
422
+ * script with another source; a candle-only one gets the traded candles
423
+ * alone whatever its primary's missing policy, as the tab serves a
424
+ * candle-only script (`wrunPrimaryRows`): a nan or zero candle primary never
425
+ * rides the shared host's dense grid, which would lay a NaN bar at every gap
426
+ * (`wrunNeedsChartPrimary`). Markers before the first traded candle or after
427
+ * the forming one are not gaps.
428
+ */
429
+ export function wrunChartCandleRows(tc) {
430
+ const main = tc?.metadata?.[0];
431
+ const raw = Array.isArray(main?.rawData) ? main.rawData : [];
432
+ const real = realMainRows(raw, main?.syntheticFlags ?? undefined) ?? raw;
433
+ let traded = real;
434
+ for (const row of real) {
435
+ if (!Array.isArray(row) || !Number.isFinite(row[4])) {
436
+ traded = real.filter((candidate) => Array.isArray(candidate) && Number.isFinite(candidate[4]));
437
+ break;
438
+ }
439
+ }
440
+ if (traded !== raw)
441
+ recordWrunChartGapBars(raw, traded);
442
+ return traded;
443
+ }
444
+ /** How many of the newest chart rows the interval-grid check reads. */
445
+ const WRUN_CHART_GRID_CHECK_ROWS = 8;
446
+ /** A spacing this many intervals wide or more, between every pair of the newest rows, is a coarser interval's. */
447
+ const WRUN_CHART_GRID_COARSER_FACTOR = 2.5;
448
+ /** This many bar phases or more among the newest rows is another interval's bars (a DST shift moves a session-bound venue's bars by one phase). */
449
+ const WRUN_CHART_GRID_MIXED_PHASES = 3;
450
+ /**
451
+ * Why `rows` are not the chart's candles at `intervalMs`, or null when they are. An interval switch
452
+ * replaces the main series in steps (the cached paint, then the resident commit), so a run planned
453
+ * between them reads the previous interval's bars under the new interval: it then asks its warm-up
454
+ * on the new clock over the old bars, and the host refuses the mixed phases it is handed
455
+ * (`wrun_densify_mixed_phase`, "Could not draw" over the stand-in; the 2026-10-15 tap-storm rig,
456
+ * three of four 300 ms storms, Ichimoku Cloud and EMA). The full run asks this before it plans and
457
+ * waits for the next chart trigger instead (`WrunNoBarsError`), as for no rows at all.
458
+ *
459
+ * Judged on the newest rows alone (a chart holds one interval at a time):
460
+ * - `mixed-phase`: the rows open on three or more phases of the interval (4h bars on a 1d chart
461
+ * open on six); a DST shift moves a session-bound venue's bars by one phase, never two;
462
+ * - `coarser`: every spacing between the newest rows is at least two and a half intervals (1d
463
+ * bars on a 4h chart); a session-bound venue's overnight or weekend gap is one spacing among
464
+ * several, never all of them.
465
+ * A calendar interval (1M, 3M, 6M, 1Y) opens on the 1st of a month at no fixed phase, a non-time
466
+ * interval has no grid, and a chart of fewer rows than the check reads (a new listing, a spec's
467
+ * three-row chart) leaves nothing to judge: all pass.
468
+ */
469
+ export function wrunChartRowsOffIntervalGrid(rows, intervalMs) {
470
+ if (!(intervalMs > 0) || isCalendarIntervalMs(intervalMs))
471
+ return null;
472
+ const newest = [];
473
+ for (let i = rows.length - 1; i >= 0 && newest.length < WRUN_CHART_GRID_CHECK_ROWS; i -= 1) {
474
+ const ts = Number(rows[i]?.[0]);
475
+ if (Number.isFinite(ts))
476
+ newest.unshift(ts);
477
+ }
478
+ if (newest.length < WRUN_CHART_GRID_CHECK_ROWS)
479
+ return null;
480
+ const phases = new Set();
481
+ for (const ts of newest)
482
+ phases.add(((ts % intervalMs) + intervalMs) % intervalMs);
483
+ if (phases.size >= WRUN_CHART_GRID_MIXED_PHASES)
484
+ return 'mixed-phase';
485
+ let coarser = true;
486
+ for (let i = 1; i < newest.length; i += 1) {
487
+ if (newest[i] - newest[i - 1] < WRUN_CHART_GRID_COARSER_FACTOR * intervalMs) {
488
+ coarser = false;
489
+ break;
490
+ }
491
+ }
492
+ return coarser ? 'coarser' : null;
493
+ }
494
+ /** Record the rows `traded` left out of `raw` (a subsequence of the same row
495
+ * objects) that sit strictly between two traded candles, as gap bar opens. */
496
+ function recordWrunChartGapBars(raw, traded) {
497
+ const gaps = [];
498
+ let next = 0;
499
+ for (const row of raw) {
500
+ if (next < traded.length && row === traded[next]) {
501
+ next += 1;
502
+ continue;
503
+ }
504
+ if (next === 0 || next === traded.length)
505
+ continue;
506
+ const ts = Array.isArray(row) ? Number(row[0]) : Number.NaN;
507
+ const floor = Math.max(Number(traded[next - 1][0]), gaps.length > 0 ? gaps[gaps.length - 1] : Number.NEGATIVE_INFINITY);
508
+ if (ts > floor && ts < Number(traded[next][0]))
509
+ gaps.push(ts);
510
+ }
511
+ if (gaps.length > 0)
512
+ WRUN_CHART_GAP_BARS.set(traded, gaps);
513
+ }
514
+ /**
515
+ * The rows of a `wrunChartCandleRows` array from `fromMs` through `toMs`, with its recorded
516
+ * missing bars strictly between the first and the last row kept: a clamped run window (the full
517
+ * run's and the reseed's, wrun-overlay-run.util) computes over its slice of the chart's candles
518
+ * and runs the gaps inside it as a run over the whole chart does. A plain `filter` would drop
519
+ * them, since the gaps ride the identity of the array.
520
+ */
521
+ export function wrunChartCandleRowsWithin(rows, fromMs, toMs = Number.POSITIVE_INFINITY) {
522
+ const within = rows.filter((row) => row[0] >= fromMs && row[0] <= toMs);
523
+ const gaps = WRUN_CHART_GAP_BARS.get(rows);
524
+ if (gaps === undefined || within.length < 2)
525
+ return within;
526
+ const firstTs = within[0][0];
527
+ const lastTs = within[within.length - 1][0];
528
+ const inside = gaps.filter((ts) => ts > firstTs && ts < lastTs);
529
+ if (inside.length > 0)
530
+ WRUN_CHART_GAP_BARS.set(within, inside);
531
+ return within;
532
+ }
533
+ /**
534
+ * Candles stamped before a `wrunChartCandleRows` array's first row (a replay window's head,
535
+ * fetched on the K_OHLCV lane) joined ahead of it, with its recorded missing bars kept: they sit
536
+ * strictly between two of its rows, so they stay interior to the joined rows. A spread would
537
+ * drop them, since the gaps ride the identity of the array. No head returns the rows themselves.
538
+ */
539
+ export function wrunChartCandleRowsAfterHead(head, rows) {
540
+ if (head.length === 0)
541
+ return rows;
542
+ const joined = [...head, ...rows];
543
+ const gaps = WRUN_CHART_GAP_BARS.get(rows);
544
+ if (gaps !== undefined)
545
+ WRUN_CHART_GAP_BARS.set(joined, gaps);
546
+ return joined;
547
+ }
548
+ /** The missing bars a `wrunChartCandleRows` array recorded strictly between its rows (ascending opens), read by the
549
+ * run budget's walk (wrun-run-retained.util); none for rows without markers. */
550
+ export function wrunChartGapBarsOf(rows) {
551
+ return WRUN_CHART_GAP_BARS.get(rows) ?? [];
552
+ }
553
+ /** The source class an input demands a lane for: its own, or none for an input the run's sheet on
554
+ * the chart's market left undemanded (wrunSheetWithLaneDemand: its needed_by leaves the market out). */
555
+ export function wrunDemandedSourceClass(source) {
556
+ return source === undefined || source.undemanded === true ? undefined : source.source;
557
+ }
558
+ /** A leg stream input (`candles`, `oi_candles`, `volume_profile_candles`: wrun-leg-stream-classes) the run's
559
+ * sheet on this chart left undemanded (wrunSheetWithLaneGate: its `chart_interval_below` gates the lane off
560
+ * on the chart's interval): no leg, no wire, no check, no ask; the row builder hands it a present EMPTY
561
+ * block on every row. */
562
+ function wrunGatedLegStream(source) {
563
+ return isWrunLegStreamClass(source?.source) && source?.undemanded === true;
564
+ }
565
+ /**
566
+ * The row builder's lane an input reads: its source class, except a `trades`
567
+ * input, which reads the trades lane of its quote (wrun-trades-lane.util,
568
+ * C1.4): the dollar lane `trades_usd` (rows `buySellVolumeUsdRows`) for
569
+ * `currency: "USD"`, the coin lane `trades` (the chart's own buy/sell lane)
570
+ * otherwise, and a trades input pinned to one whole market its quote's leg lane
571
+ * there (kit 0.77.0, `trades@BYBIT|BTCUSDT`); none for an undemanded input
572
+ * (wrunDemandedSourceClass) or a half pin (refused by name). The one rule the
573
+ * full run's lane fetches, the live intake and the reconcile share.
574
+ */
575
+ export function wrunSourceLane(source) {
576
+ if (source === undefined || source.undemanded === true)
577
+ return undefined;
578
+ if (source.source !== 'trades')
579
+ return source.source;
580
+ if (source.symbol === undefined && source.exchange === undefined && !wrunFollowsCoin(source)) {
581
+ return wrunTradesLaneOf(source);
582
+ }
583
+ return wrunTradesLegLaneOf(source);
584
+ }
585
+ /** Every lane a sheet's inputs read (wrunSourceLane), declaration order kept. */
586
+ export function wrunDeclaredSourceLanes(metadata) {
587
+ const lanes = new Set();
588
+ for (const input of metadata.inputs) {
589
+ const lane = wrunSourceLane(metadata.inputSources[input.name]);
590
+ if (lane !== undefined)
591
+ lanes.add(lane);
592
+ }
593
+ return lanes;
594
+ }
595
+ /** A calendar row's bounds (1M 3M 6M 1Y, on every market): from its label to its calendar end
596
+ * (February 2026 from Feb 1 to Mar 1, never the average month's Mar 3 10:30); undefined at a fixed
597
+ * span. The chart's own row rule: the clock carries it to every reader of a row's bounds, the
598
+ * `candles` stream's included. */
599
+ export function wrunCalendarRowBounds(intervalMs) {
600
+ if (!isCalendarIntervalMs(intervalMs))
601
+ return undefined;
602
+ return (rowOpenMs) => ({ openMs: rowOpenMs, closeMs: barEndMs(rowOpenMs, intervalMs) });
603
+ }
604
+ const WRUN_PINNED_INTERVAL_WORDS = `${Object.keys(WRUN_PINNED_INTERVALS).join(', ')} or ${Object.values(WRUN_PINNED_INTERVALS).join(', ')}`;
605
+ /** `forming` buckets are served up to WEEK (the Monday-anchored week, the
606
+ * widest span of the vocabulary). */
607
+ const WRUN_FORMING_MAX_MS = Intervals.WEEK;
608
+ /** The typed-feed classes an own-market interval pin buckets by the clock
609
+ * (no extra fetch: the lane's own rows). */
610
+ export const WRUN_TYPED_PINNED_SOURCES = new Set(['funding', 'oi']);
611
+ /** The intrabar cell tuple `[offset_ms, open, high, low, close, volume]`
612
+ * (f64 cells per finer bar): the shared host's `WRUN_HOST_CELL_TUPLE_WIDTHS.intrabar`,
613
+ * the width the packer packs (pinned by wrun-source-words.kit-mirror.spec.ts). */
614
+ export const WRUN_INTRABAR_TUPLE_WIDTH = 6;
615
+ /** The trade_volume_by_size cell tuple `[bucket, buy_usd, sell_usd,
616
+ * buy_count, sell_count]` (f64 cells per USD order-size bucket): the shared
617
+ * host's `WRUN_HOST_CELL_TUPLE_WIDTHS.trade_volume_by_size`, the width the packer
618
+ * packs (pinned by wrun-source-words.kit-mirror.spec.ts). */
619
+ export const WRUN_TRADE_VOLUME_BY_SIZE_TUPLE_WIDTH = 5;
620
+ /** The options an intrabar input may not declare (the celled refusals). */
621
+ const WRUN_INTRABAR_FORBIDDEN_OPTIONS = [
622
+ 'field',
623
+ 'missing',
624
+ 'view',
625
+ 'views',
626
+ 'offset',
627
+ 'binding',
628
+ 'side',
629
+ 'tenor',
630
+ 'delta',
631
+ ];
632
+ /** The options a `candles` input may not declare: the intrabar list but `view` and `offset`,
633
+ * which the om sheet answers in its own words (`checkCandlesView`): a candles input declares
634
+ * interval, `bars`, view "forming" or "forming_open", a market pin and max_cells. */
635
+ const WRUN_CANDLES_FORBIDDEN_OPTIONS = WRUN_INTRABAR_FORBIDDEN_OPTIONS.filter((option) => option !== 'view' && option !== 'offset');
636
+ /** The options a lane stream input (`oi_candles`, `volume_profile_candles`) may not declare: the intrabar
637
+ * list (no view, no offset: the stream itself is the closed candles), and `ticks_per_bar` on a class whose
638
+ * lane has no rows to bucket. Each declares interval, bars, a market pin, max_cells, chart_interval_below
639
+ * and its own lane words (WRUN_LEG_STREAM_CLASSES `laneWords`). */
640
+ function wrunLaneStreamForbiddenOptions(streamClass) {
641
+ const words = WRUN_LEG_STREAM_CLASSES[streamClass].laneWords;
642
+ return [...WRUN_INTRABAR_FORBIDDEN_OPTIONS, ...(words.includes('ticks_per_bar') ? [] : ['ticks_per_bar'])];
643
+ }
644
+ /** A leg's explicit depth refused where there is no leg to deepen (the om sheet's code). */
645
+ const WRUN_BARS_NEEDS_LEG_CODE = 'wrun_bars_needs_leg';
646
+ /** View "offset" without its count, and a count without the view (the om sheet's codes). */
647
+ const WRUN_OFFSET_COUNT_REQUIRED_CODE = 'wrun_offset_count_required';
648
+ const WRUN_OFFSET_NEEDS_VIEW_CODE = 'wrun_offset_needs_view';
649
+ /** Odds legs ride the Polymarket venue: the exchange is implicit on every
650
+ * host (an explicit one refuses) and the market is its condition id. */
651
+ export const WRUN_ODDS_EXCHANGE = 'POLYMARKET';
652
+ /** A Polymarket condition id, `0x` + 64 hex in any case (the om CLI's rule);
653
+ * the leg lower-cases it so mixed-case metadata shares one fetch. */
654
+ const WRUN_ODDS_CONDITION_ID_RE = /^0x[0-9a-f]{64}$/i;
655
+ /** Prediction venues are blocked on second charts: an odds bar is a minute
656
+ * at the finest, so a finer chart has no grid to join onto. */
657
+ const WRUN_ODDS_MIN_CHART_MS = Intervals.MINUTE;
658
+ /** An intrabar leg's fetch identity: the market (the chart's own through the
659
+ * fetch placeholders, or a pinned `symbol` + `exchange`) at the finer
660
+ * interval. */
661
+ export function wrunIntrabarLegFetchKey(intervalKey, market) {
662
+ return `intrabar|${market?.exchange ?? 'currentExchange'}|${market?.symbol ?? 'currentSymbol'}|${intervalKey}`;
663
+ }
664
+ // The interval pin vocabulary is a thin fact the alert target reads too (wrun-pinned-interval.util);
665
+ // this module keeps exporting it for its own readers.
666
+ export { wrunPinnedIntervalOf } from './wrun-pinned-interval.util.js';
667
+ /** The chart's spelling of an interval span (an `Intervals.map_unit` key),
668
+ * else the span in ms with a unit (a spelling `dataFetch` ignores, so a
669
+ * grid leg's fetch falls back to the chart's own interval either way). */
670
+ export function wrunChartIntervalKeyOf(intervalMs) {
671
+ const entry = Object.entries(Intervals.map_unit).find(([, ms]) => ms === intervalMs);
672
+ return entry ? entry[0] : `${intervalMs}ms`;
673
+ }
674
+ /** A pinned leg's fetch identity: the market (the chart's own when
675
+ * unpinned, so the fetch payload's placeholders) and the leg interval, the
676
+ * backend's `wrunFetchKey(exchange, symbol, intervalLiteral)` shape. An
677
+ * odds leg ends in `|odds`: the same market at the same interval is a
678
+ * DIFFERENT buffer fetched as odds (gapfilled, seeded, poll-only) than as
679
+ * a plain candle leg, so the key decides the mode, never the order the
680
+ * inputs were declared in. */
681
+ export function wrunPinnedLegFetchKey(source, intervalKey, odds = false) {
682
+ const key = `pinned|${source.exchange ?? 'currentExchange'}|${source.symbol ?? 'currentSymbol'}|${intervalKey}`;
683
+ return odds ? `${key}|odds` : key;
684
+ }
685
+ /** The fetch-key suffix a leg rides under a caller's prefix: the interval
686
+ * alone for an own-market period leg (the round-2 shape), the market
687
+ * appended for a foreign leg, `grid-` / `intrabar-` prefixed by kind,
688
+ * `-odds` appended for an odds leg (its own lane beside a plain candle
689
+ * leg on the same market). */
690
+ export function wrunPinnedLegFetchSuffix(leg) {
691
+ const market = leg.market
692
+ ? `-${leg.market.exchange ?? 'currentExchange'}-${leg.market.symbol ?? 'currentSymbol'}`
693
+ : '';
694
+ const kind = leg.kind === 'grid' ? 'grid-' : leg.kind === 'intrabar' ? 'intrabar-' : '';
695
+ // A lane stream rides its own lane: its class and lane words keep its fetch apart from a candle leg's.
696
+ const stream = leg.stream !== undefined ? `-${wrunLegStreamKeyWords(leg.stream).replace(/\|/g, '-')}` : '';
697
+ return `${kind}${leg.intervalKey}${market}${leg.odds === true ? '-odds' : ''}${stream}`;
698
+ }
699
+ const WRUN_INPUT_VIEWS = new Set([
700
+ 'confirmed',
701
+ 'forming',
702
+ 'is_new_period',
703
+ 'offset',
704
+ ]);
705
+ /** A leg knob's whole-number range check (`bars` 1..5000, `offset` 1..500), refused by name. */
706
+ function legKnobCount(name, knob, value, max) {
707
+ if (value === undefined)
708
+ return undefined;
709
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > max) {
710
+ throw new Error(knob === 'bars'
711
+ ? `Input '${name}' declares bars ${String(value)}: bars is a leg's fetch depth in its own candles, a whole number from 1 to ${max}`
712
+ : `Input '${name}' declares offset ${String(value)}: offset counts leg candles back from the confirmed one, a whole number from 1 to ${max} (offset 0 is the confirmed view itself)`);
713
+ }
714
+ return value;
715
+ }
716
+ /** The leg knobs every input is checked for before its class decides anything (the om
717
+ * sheet's rules, which a registry sheet the chart never schema-checks may still break): an
718
+ * `offset` count rides view "offset" only and that view needs its count, each refused on the
719
+ * half that is wrong or missing; both counts are whole numbers in range. Where `bars` may
720
+ * ride is the class's call (`bars` refusals name `wrun_bars_needs_leg`). */
721
+ function checkLegKnobs(name, source) {
722
+ const bars = legKnobCount(name, 'bars', source.bars, wrunChartHostEnv().sharedHost().WRUN_MAX_LEG_BARS);
723
+ if (source.offset !== undefined && source.view !== 'offset') {
724
+ throw new Error(`Input '${name}' declares offset ${String(source.offset)} without view 'offset' (${WRUN_OFFSET_NEEDS_VIEW_CODE}): the count reads candles back under view "offset" only`);
725
+ }
726
+ if (source.view === 'offset' && source.offset === undefined) {
727
+ throw new Error(`Input '${name}' declares view 'offset' without its count (${WRUN_OFFSET_COUNT_REQUIRED_CODE}): offset counts leg candles back from the confirmed one, 1 to ${wrunChartHostEnv().sharedHost().WRUN_MAX_LEG_OFFSET}`);
728
+ }
729
+ const offset = legKnobCount(name, 'offset', source.offset, wrunChartHostEnv().sharedHost().WRUN_MAX_LEG_OFFSET);
730
+ return { ...(bars !== undefined ? { bars } : {}), ...(offset !== undefined ? { offset } : {}) };
731
+ }
732
+ /** `bars` where no leg can take it, refused by name. */
733
+ function refuseBarsWithoutLeg(name, what) {
734
+ throw new Error(`Input '${name}' declares bars (${WRUN_BARS_NEEDS_LEG_CODE}): ${what}; bars sets the fetch depth of an interval-pinned feed leg or a candles stream`);
735
+ }
736
+ /** A `forming` view folds a candle grid on the chart's clock, so the primary
737
+ * input must be own-market ohlcv on every host: a bindable primary (its
738
+ * market arrives per use through `sourceBindings`, which the browser never
739
+ * resolves), a primary pinned to another market, or a non-ohlcv primary
740
+ * feed refuses by name. The browser's primary grid is the chart's own
741
+ * candles either way; the rule keeps the package's answer the same on
742
+ * every host. */
743
+ function requireOwnMarketOhlcvPrimary(metadata, inputs, formingInputName) {
744
+ const primary = inputs.find((input) => input.index === 0);
745
+ const primarySource = primary ? metadata.inputSources[primary.name] : undefined;
746
+ if (!primary || !primarySource) {
747
+ throw new Error(`Input '${formingInputName}' declares view 'forming' but the package has no primary input (index 0)`);
748
+ }
749
+ if (primarySource.binding !== undefined) {
750
+ throw new Error(`Input '${formingInputName}' declares view 'forming' but the primary input '${primary.name}' is bindable (binding '${primarySource.binding}'): forming buckets fold the primary rows, which must be own-market ohlcv`);
751
+ }
752
+ if (primarySource.source !== 'ohlcv' || primarySource.symbol !== undefined || primarySource.exchange !== undefined) {
753
+ // An odds primary pins its Polymarket market (the exchange is implicit).
754
+ const exchange = primarySource.source === 'odds' ? WRUN_ODDS_EXCHANGE : primarySource.exchange;
755
+ const market = primarySource.symbol !== undefined || exchange !== undefined
756
+ ? ` pinned to '${exchange ?? ''}/${primarySource.symbol ?? ''}'`
757
+ : '';
758
+ throw new Error(`Input '${formingInputName}' declares view 'forming' but the primary input '${primary.name}' (${primarySource.source}${market}) is not own-market ohlcv: forming buckets fold the primary rows`);
759
+ }
760
+ }
761
+ /**
762
+ * Classify every declared pin against the chart BEFORE any fetch: the legs
763
+ * a run must fetch (one per market + interval: period legs at the pinned
764
+ * interval, grid legs at the chart's for foreign markets), refusing by name
765
+ * every pin the browser lane cannot serve. Typed-feed pins plan no leg
766
+ * (they bucket the lane's own rows). `chartIntervalMs` is required whenever
767
+ * an input pins a market or an interval (nothing can be classified without
768
+ * it). Pure: the same call inside the row builders decides the wires.
769
+ */
770
+ export function planWrunPinnedLegs(metadata, chartIntervalMs) {
771
+ return planWrunPinnedWires(metadata, chartIntervalMs).legs;
772
+ }
773
+ function marketLabel(source) {
774
+ return `${source.exchange ?? ''}/${source.symbol ?? ''}`;
775
+ }
776
+ /** The span of a short interval spelling outside the vocabulary (`7m`,
777
+ * `3h`): the grid rules judge it before the vocabulary gate refuses it. */
778
+ function intervalSpanOfSpelling(word) {
779
+ const match = /^(\d+)(s|m|h|d|w)$/.exec(word);
780
+ if (!match)
781
+ return undefined;
782
+ const count = Number(match[1]);
783
+ const unit = { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 }[match[2]] ?? 0;
784
+ return count > 0 && unit > 0 ? count * unit : undefined;
785
+ }
786
+ /** A celled leg input's market: none (the chart's own, through the fetch placeholders) or a
787
+ * pinned `symbol` AND `exchange`, together (the om sheet's feed-pin pairing rule); one half
788
+ * alone refuses by name. */
789
+ function celledLegMarket(name, sourceClass, source) {
790
+ if (source.symbol === undefined && source.exchange === undefined)
791
+ return undefined;
792
+ if (source.symbol === undefined || source.exchange === undefined) {
793
+ const leg = sourceClass === 'intrabar' ? 'an intrabar' : `a ${sourceClass}`;
794
+ throw new Error(`Input '${name}' (${sourceClass}) pins the market '${marketLabel(source)}' with one half: ${leg} leg reads another market with symbol and exchange together, or the chart's own with neither`);
795
+ }
796
+ return { symbol: source.symbol, exchange: source.exchange };
797
+ }
798
+ /** The span of a celled leg's interval word: the vocabulary's spelling and span, or (for a
799
+ * short spelling outside the vocabulary, `7m`) the span alone, which the leg core's check
800
+ * refuses as off the interval words' spans. Refused by name when it names no span at all. */
801
+ function celledLegInterval(name, word) {
802
+ const interval = wrunPinnedIntervalOf(word);
803
+ const spanMs = interval?.ms ?? intervalSpanOfSpelling(word);
804
+ if (spanMs === undefined) {
805
+ throw new Error(`Input '${name}' pins interval '${word}': not an OpenMarket interval (${WRUN_PINNED_INTERVAL_WORDS})`);
806
+ }
807
+ return interval ? { interval, spanMs } : { spanMs };
808
+ }
809
+ /** A celled leg's interval once the leg core's check passed: the vocabulary's spelling, else
810
+ * refused by name. The check reads spans only, so a vocabulary span spelled outside it (`60s`,
811
+ * `1440m`, which the om sheet refuses too) passes it, and no fetch can ask that spelling. */
812
+ function celledLegFetchInterval(name, word, interval) {
813
+ if (interval === undefined) {
814
+ throw new Error(`Input '${name}' pins interval '${word}': not an OpenMarket interval (${WRUN_PINNED_INTERVAL_WORDS})`);
815
+ }
816
+ return interval;
817
+ }
818
+ /** A `candles` leg's fetch identity. Coarser or finer than the chart it is the period leg's key on
819
+ * its market and interval, so a confirmed or offset view there shares its one fetch (closed
820
+ * candles either way). At the chart's own interval that key is the market's GRID leg (the
821
+ * forming candle kept, fed live, asked from the window's head), so the stream keys a leg of its
822
+ * own (`|candles`): neither role reads the other's fetch, whatever the declaration order. */
823
+ export function wrunCandlesLegFetchKey(market, interval, chartIntervalMs) {
824
+ const key = wrunPinnedLegFetchKey(market ?? {}, interval.key);
825
+ return interval.ms === chartIntervalMs ? `${key}|candles` : key;
826
+ }
827
+ /** The plan-time check every host runs for a celled input with a leg clock (the shared host's
828
+ * `wrunCelledLegCheck`: the grid rules and the cap, each refusal by its stable code in the
829
+ * om words); answers the least max_cells a contiguous run needs. A calendar chart's rows are
830
+ * sized by its LONGEST bar (`calendarLongestBarMs`): its rows slice on the calendar, so a 31-day
831
+ * month holds 744 hourly candles, and a cap sized to the average month's 731 would refuse that
832
+ * block mid-run (`wrun_cell_block_too_large`). */
833
+ function celledLegMinCells(name, sourceClass, legMs, chartIntervalMs, maxCells, bars, view) {
834
+ const check = wrunChartHostEnv()
835
+ .sharedHost()
836
+ .wrunCelledLegCheck({
837
+ source: sourceClass,
838
+ legMs,
839
+ primaryMs: calendarLongestBarMs(chartIntervalMs),
840
+ maxCells: typeof maxCells === 'number' ? maxCells : Number.NaN,
841
+ bars,
842
+ view,
843
+ inputName: name,
844
+ });
845
+ if (!check.ok)
846
+ throw new Error(check.message);
847
+ return check.minCells;
848
+ }
849
+ /** The sheet-shape refusals a celled leg input shares (intrabar, candles), each by name before
850
+ * any fetch: a knob the class does not take, a scalar input, the primary slot, no interval,
851
+ * and a chart without an interval to classify against. */
852
+ function checkCelledLegShape(input, source, sourceClass, forbidden, chartIntervalMs) {
853
+ const name = input.name;
854
+ const declared = source;
855
+ const knob = forbidden.find((key) => declared[key] !== undefined);
856
+ if (knob !== undefined) {
857
+ throw new Error(sourceClass === 'intrabar'
858
+ ? `Input '${name}' (intrabar) declares '${knob}': an intrabar input declares interval, a market pin and max_cells only`
859
+ : sourceClass === 'candles'
860
+ ? `Input '${name}' (candles) declares '${knob}': a candles input declares interval, bars, view "forming" or "forming_open", a market pin and max_cells only`
861
+ : `Input '${name}' (${sourceClass}) declares '${knob}': ${laneStreamKnobsText(sourceClass)}`);
862
+ }
863
+ if (input.cellType !== 'array') {
864
+ throw new Error(`Input '${name}' (${sourceClass}) is not celled: declare cellType "array" with max_cells`);
865
+ }
866
+ if (input.index === 0) {
867
+ throw new Error(`Input '${name}' (${sourceClass}) is the primary input (index 0) (wrun_${sourceClass}_primary): ${sourceClass} cells ride a secondary input`);
868
+ }
869
+ if (source.interval === undefined) {
870
+ throw new Error(`Input '${name}' (${sourceClass}) declares no interval (wrun_${sourceClass}_interval_required): the leg's interval is required`);
871
+ }
872
+ if (!(typeof chartIntervalMs === 'number' && Number.isFinite(chartIntervalMs) && chartIntervalMs > 0)) {
873
+ throw new Error(`Input '${name}' pins interval '${source.interval}': the chart's own interval is required to classify interval pins and was not provided`);
874
+ }
875
+ return { interval: source.interval, chartIntervalMs };
876
+ }
877
+ /** Classify one intrabar input against the chart (the intrabar contract): the shared shape
878
+ * refusals, the market pin (symbol AND exchange, or neither), then the leg core's own check
879
+ * (the leg an interval word's span, the chart's custom timeframes included, max_cells at least
880
+ * the most leg candles a row holds: ceil(P / L) on a finer leg, one on an equal or coarser one),
881
+ * every refusal by name with its stable code. */
882
+ function planIntrabarWire(input, source, chartIntervalMs) {
883
+ const name = input.name;
884
+ if (source.bars !== undefined) {
885
+ refuseBarsWithoutLeg(name, `celled source 'intrabar' has no leg history to deepen (its blocks slice the row)`);
886
+ }
887
+ const shape = checkCelledLegShape(input, source, 'intrabar', WRUN_INTRABAR_FORBIDDEN_OPTIONS, chartIntervalMs);
888
+ const market = celledLegMarket(name, 'intrabar', source);
889
+ const { interval, spanMs } = celledLegInterval(name, shape.interval);
890
+ const minCells = celledLegMinCells(name, 'intrabar', spanMs, shape.chartIntervalMs, input.max_cells);
891
+ const leg = celledLegFetchInterval(name, shape.interval, interval);
892
+ return {
893
+ kind: 'intrabar',
894
+ inputIndex: input.index,
895
+ source,
896
+ minCells,
897
+ leg: {
898
+ fetchKey: wrunIntrabarLegFetchKey(leg.key, market),
899
+ intervalKey: leg.key,
900
+ legMs: leg.ms,
901
+ inputIndexes: [],
902
+ ...(market ? { market } : {}),
903
+ },
904
+ };
905
+ }
906
+ /** A `candles` input's view and offset, the om sheet's rules in its words: the class takes two
907
+ * views, "forming" (the leg's live candle) and "forming_open" (on every row the open of the leg
908
+ * candle holding it), neither beside `bars` (neither reading has a backlog), and no offset at
909
+ * all (the stream already carries the closed candles). Answers the view the input reads. */
910
+ function checkCandlesView(name, source) {
911
+ if (source.offset !== undefined) {
912
+ throw new Error(`Input '${name}' (candles) declares offset ${String(source.offset)}: a candles input takes no offset: the stream already carries the leg's closed candles, newest last, and offset ${String(source.offset)} is a scalar reading of a feed leg with an interval pin`);
913
+ }
914
+ const view = source.view;
915
+ if (view === undefined)
916
+ return undefined;
917
+ const { WRUN_CANDLES_FORMING_VIEW: formingView, WRUN_CANDLES_FORMING_OPEN_VIEW: formingOpenView } = wrunChartHostEnv().sharedHost();
918
+ if (view !== formingView && view !== formingOpenView) {
919
+ throw new Error(`Input '${name}' (candles) declares view '${view}': a candles input takes two views, "forming" (the leg's live candle on the live row) and "forming_open" (on every row, the open of the leg candle holding it), not "${view}"; the stream itself is the closed candles, and confirmed, is_new_period and offset are scalar readings of a feed leg with an interval pin`);
920
+ }
921
+ if (source.bars !== undefined) {
922
+ throw new Error(view === formingView
923
+ ? `Input '${name}' (candles) declares bars beside view 'forming': a candles input read with view "forming" takes no bars: it carries the leg's live candle alone, with no backlog to deepen; read the closed candles through a second candles input with bars`
924
+ : `Input '${name}' (candles) declares bars beside view 'forming_open': a candles input read with view "forming_open" takes no bars: each row carries the open of the leg candle holding it, with no backlog to deepen; read the closed candles through a second candles input with bars`);
925
+ }
926
+ return view;
927
+ }
928
+ /** Classify one `candles` input against the chart: the shared shape refusals, the market pin,
929
+ * the depth (`bars`, 1..5000), then the leg core's own check (the leg one of the eight
930
+ * intervals, any of them finer than, equal to or coarser than the chart; max_cells at least
931
+ * `bars` and the candles one row can carry, 1 for a view's one candle per row). The leg is a
932
+ * closed-candle leg at its own interval (`wrunCandlesLegFetchKey`: a period leg's key, its own
933
+ * at the chart's interval), the one fetch a stream and the views' readings share. */
934
+ function planCandlesWire(input, source, chartIntervalMs, bars, view) {
935
+ const name = input.name;
936
+ const shape = checkCelledLegShape(input, source, 'candles', WRUN_CANDLES_FORBIDDEN_OPTIONS, chartIntervalMs);
937
+ const market = celledLegMarket(name, 'candles', source);
938
+ const { interval, spanMs } = celledLegInterval(name, shape.interval);
939
+ const minCells = celledLegMinCells(name, 'candles', spanMs, shape.chartIntervalMs, input.max_cells, bars, view);
940
+ const leg = celledLegFetchInterval(name, shape.interval, interval);
941
+ return {
942
+ kind: 'candles',
943
+ inputIndex: input.index,
944
+ source,
945
+ minCells,
946
+ ...(view === wrunChartHostEnv().sharedHost().WRUN_CANDLES_FORMING_VIEW ? { forming: true } : {}),
947
+ ...(view === wrunChartHostEnv().sharedHost().WRUN_CANDLES_FORMING_OPEN_VIEW ? { formingOpen: true } : {}),
948
+ ...(bars !== undefined ? { bars } : {}),
949
+ leg: {
950
+ fetchKey: wrunCandlesLegFetchKey(market, leg, shape.chartIntervalMs),
951
+ intervalKey: leg.key,
952
+ legMs: leg.ms,
953
+ inputIndexes: [],
954
+ ...(market ? { market } : {}),
955
+ },
956
+ };
957
+ }
958
+ /** What a lane stream input declares, in its refusal's words. */
959
+ function laneStreamKnobsText(streamClass) {
960
+ const words = WRUN_LEG_STREAM_CLASSES[streamClass].laneWords;
961
+ return `a ${streamClass} input declares interval, bars, ${words.join(', ')}, a market pin, max_cells and chart_interval_below only (the stream is the leg's closed candles: no view, no offset)`;
962
+ }
963
+ /** A lane stream leg's fetch identity (`oi_candles`, `volume_profile_candles`): the market's candle-leg key at the
964
+ * leg's interval, then the class and its lane words (`wrunLegStreamKeyWords`), so it is never a candle leg's key,
965
+ * at the chart's own interval included, and two inputs with the same class, market, interval and lane words share
966
+ * one fetch. */
967
+ export function wrunLaneStreamLegFetchKey(market, interval, lane) {
968
+ return `${wrunPinnedLegFetchKey(market ?? {}, interval.key)}|${wrunLegStreamKeyWords(lane)}`;
969
+ }
970
+ /** The lane identity a lane stream input's fetch carries: its class, its quote (`wrunLegStreamCurrency`: "USD" only
971
+ * when the input says so, the market's native units otherwise) and, on a volume-profile stream, its bucket size
972
+ * (`normalizeTicksPerBar`, the profile lane's own rule). A `"@<param>"` reference the paint seam could not resolve
973
+ * names no declared param and refuses by name (the profile lane's code). */
974
+ function laneStreamLaneOf(name, streamClass, source) {
975
+ const currency = wrunLegStreamCurrency(streamClass, source.currency);
976
+ const laneWords = WRUN_LEG_STREAM_CLASSES[streamClass].laneWords;
977
+ if (!laneWords.includes('ticks_per_bar'))
978
+ return { class: streamClass, currency };
979
+ if (typeof source.ticks_per_bar === 'string' && source.ticks_per_bar.startsWith('@')) {
980
+ throw new Error(`Input '${name}' (${streamClass}) ticks_per_bar '${source.ticks_per_bar}' names no declared param ` +
981
+ `(${WRUN_VOLUME_PROFILE_TICKS_PARAM_CODE}): bind the bucket size to a declared int param`);
982
+ }
983
+ return { class: streamClass, currency, ticksPerBar: normalizeTicksPerBar(source.ticks_per_bar) };
984
+ }
985
+ /** Classify one lane stream input (`oi_candles`, `volume_profile_candles`) against the chart: the shared shape
986
+ * refusals (no view, no offset, its own lane words only, celled, never index 0, an interval), the depth (`bars`,
987
+ * 1..5000), the market pin (symbol AND exchange, or neither), then the leg core's own check (`wrunCelledLegCheck`:
988
+ * the leg an interval word's span, max_cells at least `bars` and the candles one row can carry; a volume-profile
989
+ * stream's `max_cells` declared, its sizing rule the rows per candle times the candles). The leg is a closed-candle
990
+ * PERIOD leg at its own interval on the class's lane (`stream`), the candles stream's delivery rules (the shared
991
+ * host's leg stream). */
992
+ function planLaneStreamWire(input, source, streamClass, chartIntervalMs) {
993
+ const name = input.name;
994
+ const shape = checkCelledLegShape(input, source, streamClass, wrunLaneStreamForbiddenOptions(streamClass), chartIntervalMs);
995
+ const { bars } = checkLegKnobs(name, source);
996
+ const market = celledLegMarket(name, streamClass, source);
997
+ const stream = laneStreamLaneOf(name, streamClass, source);
998
+ const { interval, spanMs } = celledLegInterval(name, shape.interval);
999
+ const minCells = celledLegMinCells(name, streamClass, spanMs, shape.chartIntervalMs, input.max_cells, bars);
1000
+ const leg = celledLegFetchInterval(name, shape.interval, interval);
1001
+ return {
1002
+ kind: 'candles',
1003
+ inputIndex: input.index,
1004
+ source,
1005
+ minCells,
1006
+ ...(bars !== undefined ? { bars } : {}),
1007
+ leg: {
1008
+ fetchKey: wrunLaneStreamLegFetchKey(market, leg, stream),
1009
+ intervalKey: leg.key,
1010
+ legMs: leg.ms,
1011
+ inputIndexes: [],
1012
+ ...(market ? { market } : {}),
1013
+ stream,
1014
+ },
1015
+ };
1016
+ }
1017
+ /** The static half of an odds input's classification (no chart needed): the
1018
+ * Polymarket market it pins, its column and the NO projection, every
1019
+ * refusal by name with its stable code before any fetch. The interval and
1020
+ * view rules are the candle-class rules the planner shares with ohlcv. */
1021
+ function classifyOddsInput(input, source) {
1022
+ const label = `Input '${input.name}' (odds)`;
1023
+ const pinHint = "the chart has no market picker yet; pin the market's condition id (0x…) in the input's symbol";
1024
+ if (input.cellType === 'array') {
1025
+ throw new Error(`${label} is celled: odds serve one probability per bar, a scalar input`);
1026
+ }
1027
+ if (source.binding !== undefined) {
1028
+ throw new Error(`${label} binds its market per use (binding '${source.binding}') (wrun_odds_binding_unsupported): ${pinHint}`);
1029
+ }
1030
+ if (source.symbol === undefined) {
1031
+ throw new Error(`${label} pins no market (wrun_odds_binding_unsupported): ${pinHint}`);
1032
+ }
1033
+ if (source.exchange !== undefined) {
1034
+ throw new Error(`${label} pins the exchange '${source.exchange}' (wrun_odds_exchange_implicit): odds are served on Polymarket implicitly; declare the symbol alone`);
1035
+ }
1036
+ if (!WRUN_ODDS_CONDITION_ID_RE.test(source.symbol)) {
1037
+ throw new Error(`${label} pins the symbol '${source.symbol}' (wrun_odds_symbol): a Polymarket market is its condition id (0x followed by 64 hex characters)`);
1038
+ }
1039
+ const symbol = source.symbol.toLowerCase();
1040
+ if (symbol === WRUN_ODDS_PLACEHOLDER_MARKET) {
1041
+ throw new Error(`${label} pins the template's placeholder market (wrun_odds_placeholder_market): paste the market's condition id (0x…) into the input's symbol and Run again`);
1042
+ }
1043
+ const field = source.field ?? 'close';
1044
+ const column = OHLCV_FIELD_COLUMNS[field];
1045
+ if (column === undefined) {
1046
+ throw new Error(`${label}: unknown odds field '${field}' (open, high, low, close or volume)`);
1047
+ }
1048
+ const outcome = source.outcome;
1049
+ if (outcome !== undefined && outcome !== 'YES' && outcome !== 'NO') {
1050
+ throw new Error(`${label} declares outcome '${String(outcome)}' (wrun_odds_outcome): the outcome is YES or NO`);
1051
+ }
1052
+ if (outcome === 'NO' && field !== 'close') {
1053
+ throw new Error(`${label} declares outcome 'NO' on field '${field}' (wrun_odds_outcome): the NO complement (1 - probability) applies to close only`);
1054
+ }
1055
+ if (source.view === 'forming') {
1056
+ throw new Error(`${label} declares view 'forming' (wrun_odds_forming_unsupported): odds legs serve the confirmed and is_new_period views only`);
1057
+ }
1058
+ return {
1059
+ market: { exchange: WRUN_ODDS_EXCHANGE, symbol },
1060
+ column,
1061
+ ...(outcome === 'NO' ? { transform: 'no_complement' } : {}),
1062
+ };
1063
+ }
1064
+ /** The legs a run must fetch AND the per-input wires the row builders read
1065
+ * (`planWrunPinnedLegs` is the legs half); exported for specs. */
1066
+ export function planWrunPinnedWires(metadata, chartIntervalMs) {
1067
+ const legs = new Map();
1068
+ const wires = new Map();
1069
+ const inputs = [...metadata.inputs].sort((a, b) => a.index - b.index);
1070
+ const chartKnown = typeof chartIntervalMs === 'number' && Number.isFinite(chartIntervalMs) && chartIntervalMs > 0;
1071
+ const requireChart = (name, what) => {
1072
+ if (!chartKnown) {
1073
+ throw new Error(`Input '${name}' pins ${what}: the chart's own interval is required to classify interval pins and was not provided`);
1074
+ }
1075
+ return chartIntervalMs;
1076
+ };
1077
+ const legFor = (fetchKey, intervalKey, legMs, extras) => {
1078
+ let leg = legs.get(fetchKey);
1079
+ if (!leg) {
1080
+ leg = { fetchKey, intervalKey, legMs, inputIndexes: [], ...extras };
1081
+ legs.set(fetchKey, leg);
1082
+ }
1083
+ else if (leg.kind !== extras.kind) {
1084
+ // One key is one acquisition role (the run pass and the live tick fetch, merge and feed a
1085
+ // leg by its kind): a second kind on the key would let declaration order decide another
1086
+ // input's numbers. The keys keep the roles apart; this holds them to it.
1087
+ throw new Error(`WRUN ${metadata.id}: leg '${fetchKey}' is planned as both ${leg.kind ?? 'period'} and ${extras.kind ?? 'period'}`);
1088
+ }
1089
+ return leg;
1090
+ };
1091
+ const gridLegFor = (market, chartMs, odds) => {
1092
+ const intervalKey = wrunChartIntervalKeyOf(chartMs);
1093
+ return legFor(wrunPinnedLegFetchKey(market, intervalKey, odds), intervalKey, chartMs, {
1094
+ kind: 'grid',
1095
+ market,
1096
+ ...(odds ? { odds: true } : {}),
1097
+ });
1098
+ };
1099
+ // A blend field (hl2 / hlc3 / ohlc4 / hlcc4) reads the blend of the candle the wire serves:
1100
+ // the leg candle (an interval pin's folded candle), the grid row, the forming fold's candle.
1101
+ const ohlcvRead = (source, name) => {
1102
+ if (isWrunSourceBlendField(source.field))
1103
+ return { column: Number.NaN, blend: source.field };
1104
+ const column = OHLCV_FIELD_COLUMNS[source.field ?? ''];
1105
+ if (column === undefined) {
1106
+ throw new Error(`WRUN ${metadata.id}: unknown ohlcv field '${source.field}' (input '${name}')`);
1107
+ }
1108
+ return { column };
1109
+ };
1110
+ for (const input of inputs) {
1111
+ const source = metadata.inputSources[input.name];
1112
+ // A candles lane gated off on this chart (wrunGatedLegStream) plans nothing, before any check: no
1113
+ // leg to fetch, wall-check or re-ask, and never a refusal for its knobs or its cells here.
1114
+ if (!source || wrunGatedLegStream(source))
1115
+ continue;
1116
+ const name = input.name;
1117
+ if (isWrunLaneStreamClass(source.source)) {
1118
+ // A lane stream (oi_candles, volume_profile_candles): the candles stream's rules on its own lane,
1119
+ // classified before any scalar view rule (it takes no view and no offset at all).
1120
+ const wire = planLaneStreamWire(input, source, source.source, chartKnown ? chartIntervalMs : undefined);
1121
+ const leg = legFor(wire.leg.fetchKey, wire.leg.intervalKey, wire.leg.legMs, {
1122
+ ...(wire.leg.market ? { market: wire.leg.market } : {}),
1123
+ ...(wire.leg.stream ? { stream: wire.leg.stream } : {}),
1124
+ });
1125
+ leg.inputIndexes.push(input.index);
1126
+ wires.set(input.index, { ...wire, leg });
1127
+ continue;
1128
+ }
1129
+ // A candles input's view and offset are the class's own rules, answered first in the om
1130
+ // sheet's words (the offset pairing below would point it at a view the class refuses).
1131
+ // Every other source reads a scalar view, and "forming_open" is a candles view.
1132
+ const candlesView = source.source === 'candles' ? checkCandlesView(name, source) : undefined;
1133
+ const view = source.source === 'candles' ? undefined : source.view;
1134
+ if (view === wrunChartHostEnv().sharedHost().WRUN_CANDLES_FORMING_OPEN_VIEW) {
1135
+ throw new Error(`Input '${name}' declares view 'forming_open': view "forming_open" is a candles view: it hands each row the open of the leg candle holding it with that candle's stamp, a one-tuple block a scalar slot cannot carry; declare input(name, candles.cells, { interval, view: "forming_open" }), or read this ${source.source} leg confirmed, forming, is_new_period or offset`);
1136
+ }
1137
+ if (view !== undefined && !WRUN_INPUT_VIEWS.has(view)) {
1138
+ throw new Error(`Input '${name}' declares view '${String(view)}': views are confirmed, forming, is_new_period or offset`);
1139
+ }
1140
+ const knobs = checkLegKnobs(name, source);
1141
+ const chartArg = chartKnown ? chartIntervalMs : undefined;
1142
+ if (source.source === 'intrabar') {
1143
+ const wire = planIntrabarWire(input, source, chartArg);
1144
+ const leg = legFor(wire.leg.fetchKey, wire.leg.intervalKey, wire.leg.legMs, {
1145
+ kind: 'intrabar',
1146
+ ...(wire.leg.market ? { market: wire.leg.market } : {}),
1147
+ });
1148
+ leg.inputIndexes.push(input.index);
1149
+ wires.set(input.index, { ...wire, leg });
1150
+ continue;
1151
+ }
1152
+ if (source.source === 'candles') {
1153
+ // The history primitive: the leg's closed candles as a cell stream, any of the eight
1154
+ // intervals on the chart's market or a pinned one. Keyed like a period leg, so a
1155
+ // confirmed or offset view of the same market and interval shares its one fetch; at the
1156
+ // chart's interval it keys its own leg, apart from that market's grid leg.
1157
+ const wire = planCandlesWire(input, source, chartArg, knobs.bars, candlesView);
1158
+ const leg = legFor(wire.leg.fetchKey, wire.leg.intervalKey, wire.leg.legMs, {
1159
+ ...(wire.leg.market ? { market: wire.leg.market } : {}),
1160
+ });
1161
+ leg.inputIndexes.push(input.index);
1162
+ wires.set(input.index, { ...wire, leg });
1163
+ continue;
1164
+ }
1165
+ if (knobs.bars !== undefined) {
1166
+ // bars deepens a secondary interval-pinned leg; every other place has nothing to deepen.
1167
+ if (input.cellType === 'array') {
1168
+ refuseBarsWithoutLeg(name, `celled source '${source.source}' has no leg history to deepen (its blocks exact-join the primary grid)`);
1169
+ }
1170
+ if (source.interval === undefined) {
1171
+ refuseBarsWithoutLeg(name, 'this source has no interval pin, so it rides the primary grid, whose depth is the window; declare interval beside bars to read it as a leg');
1172
+ }
1173
+ if (input.index === 0) {
1174
+ refuseBarsWithoutLeg(name, 'the primary input (index 0) takes no bars: its rows are the request window, and bars deepens a secondary leg');
1175
+ }
1176
+ }
1177
+ // A trades pin (kit 0.77.0) plans no leg and no wire: it reads its leg lane row for row.
1178
+ if (source.source === 'trades' && wrunTradesPinned(source)) {
1179
+ checkWrunTradesPin(input, source);
1180
+ continue;
1181
+ }
1182
+ // An odds input pins its own Polymarket market (primary included, the
1183
+ // hosted lane's exception to "the primary follows the chart"): its
1184
+ // static refusals fire here, its leg rides the candle-class rules below.
1185
+ const odds = source.source === 'odds' ? classifyOddsInput(input, source) : undefined;
1186
+ const marketPinned = source.symbol !== undefined || source.exchange !== undefined;
1187
+ const market = odds
1188
+ ? odds.market
1189
+ : marketPinned
1190
+ ? {
1191
+ ...(source.symbol !== undefined ? { symbol: source.symbol } : {}),
1192
+ ...(source.exchange !== undefined ? { exchange: source.exchange } : {}),
1193
+ }
1194
+ : undefined;
1195
+ const candleClass = source.source === 'ohlcv' || odds !== undefined;
1196
+ const candleRead = () => (odds ? { column: odds.column } : ohlcvRead(source, name));
1197
+ const projection = odds !== undefined && odds.transform !== undefined ? { transform: odds.transform } : {};
1198
+ if (odds !== undefined) {
1199
+ const chartMs = requireChart(name, `the odds market '${odds.market.symbol}'`);
1200
+ if (chartMs < WRUN_ODDS_MIN_CHART_MS) {
1201
+ throw new Error(`Input '${name}' (odds) rides a ${wrunChartIntervalKeyOf(chartMs)} chart (wrun_odds_chart_1s): prediction markets are served on MINUTE and coarser charts`);
1202
+ }
1203
+ }
1204
+ else if (market !== undefined) {
1205
+ // A market pin is served on secondary ohlcv inputs only: typed feeds,
1206
+ // cells and `time` follow the chart's own market on this lane, and the
1207
+ // primary input IS the chart's market on every host.
1208
+ if (input.cellType === 'array' || source.source !== 'ohlcv') {
1209
+ throw new Error(`Input '${name}' (${source.source}) pins the market '${marketLabel(source)}': ` +
1210
+ `the browser lane serves market pins on secondary ohlcv inputs only (typed feeds, cells and time follow the chart's own market)`);
1211
+ }
1212
+ if (input.index === 0) {
1213
+ throw new Error(`Input '${name}' (ohlcv) pins the market '${marketLabel(source)}' on the primary input (index 0): ` +
1214
+ `the primary input follows the chart's market; market pins are served on secondary inputs only`);
1215
+ }
1216
+ }
1217
+ if (source.interval === undefined) {
1218
+ if (view !== undefined) {
1219
+ throw new Error(`Input '${name}' declares view '${view}' without an interval pin: views need an interval pin coarser than the chart's`);
1220
+ }
1221
+ if (market !== undefined) {
1222
+ // A foreign market at the chart's own interval (an odds market
1223
+ // always is one): its grid leg, read row for row.
1224
+ const chartMs = requireChart(name, `the market '${marketLabel(source)}'`);
1225
+ const gridLeg = gridLegFor(market, chartMs, odds !== undefined);
1226
+ gridLeg.inputIndexes.push(input.index);
1227
+ wires.set(input.index, {
1228
+ kind: 'grid',
1229
+ inputIndex: input.index,
1230
+ source,
1231
+ ...candleRead(),
1232
+ gridLeg,
1233
+ ...projection,
1234
+ });
1235
+ }
1236
+ continue;
1237
+ }
1238
+ const interval = wrunPinnedIntervalOf(source.interval);
1239
+ if (interval === undefined) {
1240
+ throw new Error(`Input '${name}' pins interval '${source.interval}': not an OpenMarket interval (${WRUN_PINNED_INTERVAL_WORDS})`);
1241
+ }
1242
+ const chartMs = requireChart(name, `interval '${source.interval}'`);
1243
+ if (interval.ms === chartMs) {
1244
+ // An equal pin is the chart's own grid: the input reads the chart's
1245
+ // rows as an unpinned one does (open-stamp, row for row), on every
1246
+ // class. `is_new_period` has one answer there on every class and
1247
+ // market: every chart bar is a new period of its own interval, so the
1248
+ // input reads 1 on every row and no leg is fetched for it (the market
1249
+ // pin, if any, has nothing to add to a constant). The confirmed and
1250
+ // forming views have nothing to view at the chart's own interval and
1251
+ // still refuse by name. A foreign market at the chart's interval is
1252
+ // its grid leg, read the same way.
1253
+ if (view === 'is_new_period') {
1254
+ wires.set(input.index, { kind: 'own_period', inputIndex: input.index, source });
1255
+ continue;
1256
+ }
1257
+ if (view !== undefined) {
1258
+ throw new Error(`Input '${name}' declares view '${view}' on interval '${source.interval}', the chart's own: the confirmed, forming and offset views need an interval pin coarser than the chart's (is_new_period reads 1 on every row there)`);
1259
+ }
1260
+ if (market !== undefined) {
1261
+ const gridLeg = gridLegFor(market, chartMs, odds !== undefined);
1262
+ gridLeg.inputIndexes.push(input.index);
1263
+ wires.set(input.index, {
1264
+ kind: 'grid',
1265
+ inputIndex: input.index,
1266
+ source,
1267
+ ...candleRead(),
1268
+ gridLeg,
1269
+ ...projection,
1270
+ });
1271
+ }
1272
+ continue;
1273
+ }
1274
+ if (input.cellType === 'array') {
1275
+ throw new Error(`Input '${name}' is celled ('${source.source}') and pins interval '${source.interval}': celled inputs exact-join the primary grid and may not pin an interval`);
1276
+ }
1277
+ if (!candleClass && !WRUN_TYPED_PINNED_SOURCES.has(source.source)) {
1278
+ throw new Error(`Input '${name}' (${source.source}) pins interval '${source.interval}': the browser lane serves interval pins on secondary ohlcv inputs and the funding and oi feeds only`);
1279
+ }
1280
+ if (input.index === 0 && odds === undefined) {
1281
+ // An odds primary rides its own leg either way (the row axis stays the
1282
+ // chart's candles); every other primary follows the chart's interval.
1283
+ throw new Error(`Input '${name}' is the primary input (index 0) and pins interval '${source.interval}': the primary input follows the chart's interval; interval pins are served on secondary inputs only`);
1284
+ }
1285
+ if (interval.ms < chartMs) {
1286
+ // The way out is a finer chart: the record names the coarsest picker interval that serves the pin.
1287
+ throw attachWrunRefusal(new Error(`Input '${name}' pins interval '${source.interval}', finer than the chart's: the browser lane serves interval pins coarser than the chart only`), wrunPinFinerSeed(interval.ms, view !== undefined && view !== 'is_new_period'));
1288
+ }
1289
+ if (interval.ms % chartMs !== 0) {
1290
+ // Contract A: a leg is a whole number of chart bars (7 days for WEEK),
1291
+ // so every leg bucket closes on a row close and the forming fold never
1292
+ // straddles a row (FIVE_MINUTES on a 3m chart has no such grid).
1293
+ throw new Error(`Input '${name}' pins interval '${source.interval}', not a whole multiple of the chart's interval: a pinned leg must be a whole number of chart bars`);
1294
+ }
1295
+ const resolvedView = view ?? 'confirmed';
1296
+ if (resolvedView === 'forming' && interval.ms > WRUN_FORMING_MAX_MS) {
1297
+ throw new Error(`Input '${name}' declares view 'forming' on interval '${source.interval}': forming buckets are served up to WEEK`);
1298
+ }
1299
+ if (resolvedView === 'forming')
1300
+ requireOwnMarketOhlcvPrimary(metadata, inputs, name);
1301
+ if (candleClass) {
1302
+ const read = candleRead();
1303
+ const leg = legFor(wrunPinnedLegFetchKey(market ?? source, interval.key, odds !== undefined), interval.key, interval.ms, {
1304
+ ...(market ? { market } : {}),
1305
+ ...(odds ? { odds: true } : {}),
1306
+ });
1307
+ leg.inputIndexes.push(input.index);
1308
+ if (resolvedView === 'forming') {
1309
+ // Never odds: `classifyOddsInput` refused the view already.
1310
+ const field = source.field ?? '';
1311
+ let gridLeg;
1312
+ if (market !== undefined) {
1313
+ // A foreign forming view folds the leg market's chart-interval
1314
+ // rows: its grid leg, opened at the widest fold bucket.
1315
+ gridLeg = gridLegFor(market, chartMs, false);
1316
+ gridLeg.inputIndexes.push(input.index);
1317
+ gridLeg.foldSpanMs = Math.max(gridLeg.foldSpanMs ?? 0, interval.ms);
1318
+ }
1319
+ wires.set(input.index, {
1320
+ kind: 'forming',
1321
+ inputIndex: input.index,
1322
+ source,
1323
+ field,
1324
+ ...read,
1325
+ legMs: interval.ms,
1326
+ leg,
1327
+ ...(gridLeg ? { gridLeg } : {}),
1328
+ });
1329
+ }
1330
+ else {
1331
+ // The NO projection rides the confirmed and offset values (`is_new_period`
1332
+ // is a signal, never a probability).
1333
+ wires.set(input.index, {
1334
+ kind: 'period',
1335
+ inputIndex: input.index,
1336
+ source,
1337
+ view: resolvedView,
1338
+ ...read,
1339
+ leg,
1340
+ ...(resolvedView === 'offset' ? { offset: knobs.offset } : {}),
1341
+ ...(resolvedView !== 'is_new_period' ? projection : {}),
1342
+ });
1343
+ }
1344
+ continue;
1345
+ }
1346
+ // A typed feed (funding, oi) on the chart's own market, bucketed by the
1347
+ // clock over the lane's own rows: no leg to fetch.
1348
+ const lane = source.source;
1349
+ let column;
1350
+ if (lane === 'funding') {
1351
+ if (source.field !== 'rate_close') {
1352
+ throw new Error(`WRUN ${metadata.id}: funding field '${source.field}' is not served by the browser lane ` +
1353
+ `(the FE engine's K_FUNDING_RATE rows carry only rate_close, as percent) (input '${name}')`);
1354
+ }
1355
+ column = 1;
1356
+ }
1357
+ else {
1358
+ column = OI_FIELD_COLUMNS[source.field ?? ''];
1359
+ if (column === undefined) {
1360
+ throw new Error(`WRUN ${metadata.id}: unknown oi field '${source.field}' (input '${name}')`);
1361
+ }
1362
+ }
1363
+ wires.set(input.index, {
1364
+ kind: 'typed',
1365
+ inputIndex: input.index,
1366
+ source,
1367
+ view: resolvedView,
1368
+ field: source.field ?? '',
1369
+ column,
1370
+ lane,
1371
+ legKey: `typed|${lane}|${interval.key}`,
1372
+ legMs: interval.ms,
1373
+ ...(resolvedView === 'offset' ? { offset: knobs.offset } : {}),
1374
+ });
1375
+ }
1376
+ return { legs: [...legs.values()], wires };
1377
+ }
1378
+ function wrunTradesPinned(source) {
1379
+ return source.symbol !== undefined || source.exchange !== undefined || wrunFollowsCoin(source);
1380
+ }
1381
+ /** A trades pin's shape, refused by name (`secondary-ohlcv-trades`): a secondary input naming one
1382
+ * whole market at the chart's interval; an undemanded one reads its fill. */
1383
+ function checkWrunTradesPin(input, source) {
1384
+ if (source.undemanded === true)
1385
+ return;
1386
+ const name = input.name;
1387
+ if (input.index === 0) {
1388
+ throw new Error(`Input '${name}' (trades) pins the market '${marketLabel(source)}' on the primary input (index 0): ` +
1389
+ `the primary input follows the chart's market; market pins are served on secondary inputs only`);
1390
+ }
1391
+ if (wrunFollowsCoin(source)) {
1392
+ throw new Error(`Input '${name}' (trades) follows the chart's coin on ${source.exchange ?? 'no venue'}, and this run resolved ` +
1393
+ 'no market there (wrun_coin_leg_unresolved)');
1394
+ }
1395
+ if (source.symbol === undefined || source.exchange === undefined) {
1396
+ throw new Error(`Input '${name}' (trades) pins the market '${marketLabel(source)}': a market pin carries symbol AND exchange together`);
1397
+ }
1398
+ if (source.interval !== undefined) {
1399
+ throw new Error(`Input '${name}' (trades) pins interval '${source.interval}': the browser lane serves interval pins on secondary ohlcv inputs and the funding and oi feeds only`);
1400
+ }
1401
+ if (source.view !== undefined) {
1402
+ throw new Error(`Input '${name}' declares view '${source.view}' without an interval pin: views need an interval pin coarser than the chart's`);
1403
+ }
1404
+ }
1405
+ function requireSource(metadata, inputName) {
1406
+ const source = metadata.inputSources[inputName];
1407
+ if (!source) {
1408
+ throw new Error(`WRUN ${metadata.id}: input '${inputName}' declares no inputSources entry`);
1409
+ }
1410
+ return source;
1411
+ }
1412
+ /** The `time` fields that are facts of the bar's market (contract C3). */
1413
+ const WRUN_BAR_FACT_FIELDS = new Set(['trade_date', 'session']);
1414
+ /** The market-facts reader one build binds: undefined when no input reads a
1415
+ * fact; refused by name when one does and the chart's series is unknown
1416
+ * (never guessed: a CME chart read on the UTC rule is silently wrong). */
1417
+ function wrunBarFactsReaderFor(metadata, venue) {
1418
+ const reader = metadata.inputs.find((input) => {
1419
+ const source = metadata.inputSources[input.name];
1420
+ return source?.source === 'time' && WRUN_BAR_FACT_FIELDS.has(source.field ?? '');
1421
+ });
1422
+ if (reader === undefined)
1423
+ return undefined;
1424
+ if (venue === undefined) {
1425
+ throw new Error(`WRUN ${metadata.id}: time.${metadata.inputSources[reader.name].field} needs the chart's market ` +
1426
+ `(exchange, symbol and interval) (input '${reader.name}')`);
1427
+ }
1428
+ return wrunBarSessionFactsResolver(venue);
1429
+ }
1430
+ /** A leg bucket's open: the Monday-anchored week for a WEEK leg (the main
1431
+ * path's `findMonday`, never the epoch week), the calendar bar at a month,
1432
+ * quarter, half-year or year length (the chart's own rows on a calendar
1433
+ * chart: an epoch floor of the average month put March 10 at March 2 21:00,
1434
+ * no row's open), `floor(ts / L) * L` for every other span. Exported for the
1435
+ * run pass (a grid leg's fetch opens at the first row's fold bucket) and the
1436
+ * live tick (the chart row a revised candle reaches). */
1437
+ export function wrunFormingBucketStart(ts, legMs) {
1438
+ if (legMs === Intervals.WEEK)
1439
+ return findMonday(ts);
1440
+ const months = calendarMonthsOfMs(legMs);
1441
+ if (months !== null)
1442
+ return calendarBarStartMs(ts, months);
1443
+ return Math.floor(ts / legMs) * legMs;
1444
+ }
1445
+ /**
1446
+ * True when the package reads a lane laid on the chart's timeline besides the chart's own
1447
+ * candles: the structural twin of the tab's kScript rule. There the chart-own `ohlcv` source is
1448
+ * served the traded candles only when the run registers no other source outside the hidden
1449
+ * grids (`soleTimelineSource`: kscript-engine.worker.ts `sourceRoleForRequest` counts every
1450
+ * other source not flagged `isLTF`, `isHTFNative` or `isHTFDeepDaily`; the proxy reads a zero
1451
+ * as sole, script-engine-worker-manager.ts; ohlcv-row-readiness.util.ts
1452
+ * `chartMainRowsAsOhlcvSource`), and with another source its rows keep the gap markers. The
1453
+ * engine flags a hidden grid only for `ltf()`, a `request()` coarser than the chart (and its
1454
+ * calendar backing) and `requestBars()`; a plain source of any class, celled ones included, is
1455
+ * laid on the timeline (kscript 3.0.93 engine.ts `buildRequestSourceDeclarations`,
1456
+ * `nativeHTFRequestInterval`, `buildLTFSourceDeclarations`). Mirrored per input: a `grid` wire
1457
+ * (another market, odds included, at the chart's interval) is such a lane; the other wires are
1458
+ * the hidden grids (`period`, `forming` and `typed` a coarser request, `intrabar` an ltf,
1459
+ * `candles` a requestBars) or read no lane (`own_period`); an unwired input is a lane unless it
1460
+ * reads the chart's own candles (`ohlcv`) or the bar's own facts (`time`).
1461
+ */
1462
+ function wrunReadsChartTimelineLane(metadata, wires) {
1463
+ for (const input of metadata.inputs) {
1464
+ const wire = wires.get(input.index);
1465
+ if (wire !== undefined) {
1466
+ if (wire.kind === 'grid')
1467
+ return true;
1468
+ continue;
1469
+ }
1470
+ const sourceClass = metadata.inputSources[input.name]?.source;
1471
+ if (sourceClass !== undefined && sourceClass !== 'ohlcv' && sourceClass !== 'time')
1472
+ return true;
1473
+ }
1474
+ return false;
1475
+ }
1476
+ /**
1477
+ * The primary rows a run walks: the chart's candles and, for a package that reads another lane
1478
+ * on the chart's timeline (`wrunReadsChartTimelineLane`), a row at each interior missing bar the
1479
+ * chart's rows recorded (`wrunChartCandleRows`), every cell NaN: the marker the tab's kScript lane
1480
+ * hands such a run, which its engine runs as a NaN bar with the other lanes' rows exact-joined
1481
+ * onto it (ruled 2026-10-05: wrun matches the original as the chart runs it). Each input reads
1482
+ * the gap row under its own missing policy, `time` reads the bar's own open, and the lanes
1483
+ * exact-join it like any bar. A candle-only package walks the traded candles alone, whatever its
1484
+ * primary's policy, as the tab serves a candle-only kScript run since 2026-09-30 (a recursive
1485
+ * class fed NaN keeps NaN: `@om-core/rsi` on GATE_IO_FUTURES PROLOGUE_USDT 30m held 35 values and
1486
+ * nothing after); a nan or zero candle primary is planned behind the chart's close for it
1487
+ * (`wrunNeedsChartPrimary`), so the host's dense grid lays no bar between the candles either
1488
+ * (`@om-core/rsi` 0.3.2 on KRAKEN XRP/USD 1d, 2026-10-15).
1489
+ */
1490
+ function wrunPrimaryRows(metadata, wires, ohlcvRows) {
1491
+ const gaps = WRUN_CHART_GAP_BARS.get(ohlcvRows);
1492
+ if (gaps === undefined || gaps.length === 0 || !wrunReadsChartTimelineLane(metadata, wires))
1493
+ return ohlcvRows;
1494
+ const rows = [];
1495
+ let at = 0;
1496
+ for (const row of ohlcvRows) {
1497
+ const ts = Number(row[0]);
1498
+ while (at < gaps.length && gaps[at] < ts) {
1499
+ rows.push([gaps[at], Number.NaN, Number.NaN, Number.NaN, Number.NaN, Number.NaN]);
1500
+ at += 1;
1501
+ }
1502
+ rows.push(row);
1503
+ }
1504
+ return rows;
1505
+ }
1506
+ // ── The row builder: the shared host's aligner ──────────────────────────────────────────────
1507
+ /** The chart's own market as the browser's leg fetch keys spell it (the fetch placeholders): the
1508
+ * plan reads the rows against it, so an explicit market pin is another market to the plan
1509
+ * exactly as it is to the browser's planner (every pinned market rides a leg of its own). */
1510
+ const WRUN_ROWS_CHART_MARKET = Object.freeze({ exchange: 'currentExchange', symbol: 'currentSymbol' });
1511
+ /** The read scope an own run plans under: the browser's fetches carry the user's own entitlement,
1512
+ * and the venues no chart reads refuse by name before any fetch (wrun-pin-venues), so the plan
1513
+ * refuses no venue for scope. */
1514
+ const WRUN_ROWS_PERMISSIONS = Object.freeze(['read:openmarket']);
1515
+ /** Whether this chart reads published feeds: the Feeds flag (LIVE-SERIES P4), the one switch
1516
+ * behind the feed capability the run advertises (`wrunBrowserRunWireCaps`) and the `series` lane's
1517
+ * plan. Read per build through the host (`user.isFeatureOn`), as the flag map lands after boot; with no
1518
+ * flag store up (a spec, a worker) the read throws and it reads none. */
1519
+ export function wrunBrowserReadsFeeds() {
1520
+ try {
1521
+ return wrunChartHostEnv().user.isFeatureOn(FeatureFlag.Feeds);
1522
+ }
1523
+ catch {
1524
+ return false;
1525
+ }
1526
+ }
1527
+ /**
1528
+ * The wire capabilities the browser run advertises to the shared host's planner (the chart-browser
1529
+ * profile's `wireCaps`): the kit's feed capability (the host entry's `WRUN_FEED_HOST_CAP`, read off
1530
+ * the loaded shared host like every host constant this file reads) while the Feeds flag is on
1531
+ * (LIVE-SERIES P4: the chart then reads feeds, through the `series` poll lane), else none. Under it
1532
+ * the chart profile serves the `series` class; without it the plan refuses a series input
1533
+ * `wrun_source_unsupported`. Never the hosted run's caps: the socket's own
1534
+ * (`wrunAdvertisedWireCaps`) leave it out, the cloud advertises its feed cap itself. The shared host
1535
+ * must be loaded first (`wrunChartHostEnv().loadSharedHost()`) whenever the flag is on.
1536
+ */
1537
+ export function wrunBrowserRunWireCaps() {
1538
+ return wrunBrowserReadsFeeds() ? [wrunChartHostEnv().sharedHost().WRUN_FEED_HOST_CAP] : [];
1539
+ }
1540
+ /** The chart-candles primary a sheet is planned behind when its own input 0 is no primary the
1541
+ * shared host takes (`wrunNeedsChartPrimary`): the chart's close, the axis the browser always
1542
+ * read its rows on. Never a declared name (sheet names are identifiers). */
1543
+ const WRUN_ROWS_CHART_PRIMARY = '#chart-close';
1544
+ /** The stand-in a lane read is planned as (`WrunLaneRead`): an own-market exact-join feed, which
1545
+ * the plan types as a plain scalar on the chart's grid and never gates beyond its policy. Every
1546
+ * lane read but a published feed's: a `series` read is planned as itself (`wrunPlannedSeriesRead`). */
1547
+ const WRUN_ROWS_LANE_STAND_IN = Object.freeze({ source: 'oi', field: 'close' });
1548
+ /** The class a published feed is read as (the `series` lane, LIVE-SERIES). */
1549
+ const WRUN_ROWS_SERIES_CLASS = 'series';
1550
+ /** The stand-in a row-lane read is planned as (`WrunCellLaneRead`): an own-market exact-join celled class the
1551
+ * chart profile serves with no knob of its own, which the plan types as a cell block on the chart's grid with
1552
+ * an empty block where a bar has none. The browser answers the read itself and re-points the wire at its own
1553
+ * rows, its class and its width (the descriptor's), so the stand-in's ask is never read. */
1554
+ const WRUN_ROWS_CELL_LANE_STAND_IN = Object.freeze({ source: 'trade_volume_by_size' });
1555
+ /**
1556
+ * A `series` lane read as the shared host plans it: the kit's own series wire, `{ source: 'series',
1557
+ * field: 'value', ref, missing }` (the feed address trimmed, as the lane's plan reads it; the sheet's
1558
+ * `missing` when it declares one, else the host's default, carry), never the stand-in. Planned as
1559
+ * its own class, the read keeps the host's series rules: the chart profile serves it only under the
1560
+ * feed capability the run advertises (`wrunBrowserRunWireCaps`), and the aligner's rule e lands the
1561
+ * last lane row before the grid's head (the relay's bar before the window, which the lane asks one
1562
+ * interval early: `fetchWrunSeriesRows`) on the leading rows a `carry` input holds no reading of its
1563
+ * own for. The lane's rows answer the plan's own series ask (`wrunHostRunOf`).
1564
+ */
1565
+ function wrunPlannedSeriesRead(source) {
1566
+ const ref = source.ref;
1567
+ return {
1568
+ source: WRUN_ROWS_SERIES_CLASS,
1569
+ field: 'value',
1570
+ ref: typeof ref === 'string' ? ref.trim() : ref,
1571
+ ...(source.missing !== undefined ? { missing: source.missing } : {}),
1572
+ };
1573
+ }
1574
+ /** The kScript lane rows' facts for the cell adapter: the chart hosts' own row dialect, ms
1575
+ * stamps, native amounts (the lanes' own units). */
1576
+ function wrunLaneCellFacts(ask) {
1577
+ return {
1578
+ dialect: 'kscript-rows',
1579
+ tsUnit: 'ms',
1580
+ amounts: 'native',
1581
+ coverage: { fromMs: ask.fromMs, toMs: ask.toMs },
1582
+ };
1583
+ }
1584
+ /**
1585
+ * The options chains an own run's plan reads: the run pass resolved the one chain its
1586
+ * options_chain inputs read before any fetch (`wrunOptionsChainLaneExtrasFor`, refusing a venue
1587
+ * word the chart cannot read, its crypto venues behind the browser's own switch, in the browser's
1588
+ * words), and the lane's rows are that chain. So each declared venue word reads the chain the lane
1589
+ * fetched (the chart's own market placeholders name it) under the browser's venue capability; the
1590
+ * chain's identity rides the lane's fetch, never the plan.
1591
+ */
1592
+ function wrunRowsOptionsChains(metadata, host) {
1593
+ const words = new Set();
1594
+ for (const input of metadata.inputs) {
1595
+ const source = metadata.inputSources[input.name];
1596
+ if (source?.source === 'options_chain')
1597
+ words.add(typeof source.venue === 'string' ? source.venue : 'auto');
1598
+ }
1599
+ if (words.size === 0)
1600
+ return {};
1601
+ const chain = { ...WRUN_ROWS_CHART_MARKET };
1602
+ return {
1603
+ optionsChains: Object.fromEntries([...words].map((word) => [word, chain])),
1604
+ hostCaps: [host.WRUN_OPTIONS_VENUES_HOST_CAP],
1605
+ };
1606
+ }
1607
+ /** The plan's `coinLegs` (kit 0.77.0): the market seam left only unlisted coin legs (undemanded),
1608
+ * each null, so the plan reads them unserved as the chart does; a demanded one stays out. */
1609
+ function wrunRowsCoinLegs(metadata) {
1610
+ let coinLegs;
1611
+ for (const input of metadata.inputs) {
1612
+ const source = metadata.inputSources[input.name];
1613
+ if (source === undefined || !wrunFollowsCoin(source) || source.undemanded !== true)
1614
+ continue;
1615
+ if (typeof source.exchange === 'string')
1616
+ (coinLegs ??= {})[source.exchange] = null;
1617
+ }
1618
+ return coinLegs === undefined ? {} : { coinLegs };
1619
+ }
1620
+ /**
1621
+ * The browser's refusals, in its own words and in the order its builder raised them, before the
1622
+ * shared host plans anything: a market fact without the chart's market, every pin the browser
1623
+ * lane cannot serve (`planWrunPinnedWires`), a leg or a daily landing without the clock, the
1624
+ * etf_flow, poll-lane and option-summary column plans, the options_chain `expiries` word, and,
1625
+ * once there are rows to build, each lane input's field and side and a class no browser lane
1626
+ * serves. Answers what the routing needs.
1627
+ */
1628
+ function checkWrunRowReads(metadata, sources, clock, hasRows) {
1629
+ const barFacts = wrunBarFactsReaderFor(metadata, sources.venue);
1630
+ const { legs, wires } = planWrunPinnedWires(metadata, clock?.intervalMs);
1631
+ if ((legs.length > 0 || wires.size > 0) && clock === undefined) {
1632
+ // Never guess: an open-stamped coarse leg is exactly the lookahead leak
1633
+ // the clock exists to prevent.
1634
+ throw new Error(`WRUN ${metadata.id}: as-of alignment needs the chart interval and captured now (a pinned leg is declared)`);
1635
+ }
1636
+ const lanes = new Map();
1637
+ // The ETF lane's columns (its static refusals fire here, before any row):
1638
+ // the daily landing rule reads the chart interval, so the clock is required.
1639
+ const etfColumns = planWrunEtfFlowColumns(metadata);
1640
+ if (etfColumns.length > 0 && clock === undefined) {
1641
+ throw new Error(`WRUN ${metadata.id}: the etf_flow landing needs the chart interval and captured now (an etf_flow input is declared)`);
1642
+ }
1643
+ for (const column of etfColumns) {
1644
+ for (const index of column.inputIndexes) {
1645
+ lanes.set(index, {
1646
+ key: 'lane|etf_flow',
1647
+ rows: sources.etfFlowRows ?? [],
1648
+ column: column.column,
1649
+ join: 'daily_sum',
1650
+ });
1651
+ }
1652
+ }
1653
+ // The registry poll lanes (sources/): each input's lane and column from the static plan (a
1654
+ // celled input and a field no lane serves refuse here), its rows from the instance the run pass
1655
+ // planned it into (`sources.pollLanes`; a caller that planned none reads an empty lane). A daily
1656
+ // landing reads the chart interval, so the clock is required.
1657
+ const pollInputs = planWrunPollLaneInputs(metadata);
1658
+ if (pollInputs.length > 0) {
1659
+ const instanceKeyOf = new Map();
1660
+ for (const instance of sources.pollLanes ?? []) {
1661
+ for (const index of instance.inputIndexes)
1662
+ instanceKeyOf.set(index, instance.key);
1663
+ }
1664
+ for (const planned of pollInputs) {
1665
+ const { join } = planned.lane;
1666
+ if (join !== 'bar' && clock === undefined) {
1667
+ throw new Error(`WRUN ${metadata.id}: the ${planned.lane.sourceClass} landing needs the chart interval and captured now ` +
1668
+ `(a daily input is declared: '${planned.inputName}')`);
1669
+ }
1670
+ const instance = instanceKeyOf.get(planned.inputIndex);
1671
+ lanes.set(planned.inputIndex, {
1672
+ key: instance === undefined ? `lane|unplanned|${planned.inputIndex}` : `lane|${instance}`,
1673
+ rows: (instance === undefined ? undefined : sources.pollLaneRows?.[instance]) ?? [],
1674
+ column: planned.column,
1675
+ ...(join === 'bar' ? {} : { join: join.landing === 'sum' ? 'daily_sum' : 'daily_last' }),
1676
+ });
1677
+ }
1678
+ }
1679
+ // The row lanes (sources/row-lane-registry.ts): each celled input's lane from the static plan (a
1680
+ // scalar input and one with no max_cells refuse here), its rows from the instance the run pass
1681
+ // planned it into (`sources.rowLanes`; a caller that planned none reads an empty lane).
1682
+ const cellLanes = new Map();
1683
+ const rowInputs = planWrunRowLaneInputs(metadata);
1684
+ if (rowInputs.length > 0) {
1685
+ const instanceKeyOf = new Map();
1686
+ for (const instance of sources.rowLanes ?? []) {
1687
+ for (const index of instance.inputIndexes)
1688
+ instanceKeyOf.set(index, instance.key);
1689
+ }
1690
+ for (const planned of rowInputs) {
1691
+ const instance = instanceKeyOf.get(planned.inputIndex);
1692
+ cellLanes.set(planned.inputIndex, {
1693
+ key: `lane|${instance ?? 'unplanned'}#${planned.inputIndex}`,
1694
+ rows: (instance === undefined ? undefined : sources.rowLaneRows?.[instance]) ?? [],
1695
+ lane: planned.lane,
1696
+ input: { name: planned.inputName, source: planned.source, maxCells: planned.maxCells },
1697
+ });
1698
+ }
1699
+ }
1700
+ // The option-summary lanes' columns (their static refusals fire here too: a wrong field, a
1701
+ // missing or unserved tenor): each input reads the column the run pass asked its tenor into.
1702
+ for (const sourceClass of ['implied_volatility', 'skew']) {
1703
+ const rows = (sourceClass === 'skew' ? sources.skewRows : sources.impliedVolatilityRows) ?? [];
1704
+ for (const column of planWrunOptionSummaryLane(metadata, sourceClass).columns) {
1705
+ for (const index of column.inputIndexes) {
1706
+ lanes.set(index, { key: `lane|${sourceClass}`, rows, column: column.column });
1707
+ }
1708
+ }
1709
+ }
1710
+ const inputs = [...metadata.inputs].sort((a, b) => a.index - b.index);
1711
+ for (const input of inputs) {
1712
+ const source = requireSource(metadata, input.name);
1713
+ if (source.source !== 'options_chain')
1714
+ continue;
1715
+ if (wrunOptionsChainExpiries(source.expiries) === undefined) {
1716
+ throw new Error(`WRUN ${metadata.id}: input '${input.name}' reads options_chain cells with expiries '${source.expiries}' ` +
1717
+ `(${WRUN_OPTIONS_CHAIN_EXPIRIES_CODE}): declare "all" or "nearest:N"`);
1718
+ }
1719
+ }
1720
+ if (hasRows) {
1721
+ for (const input of inputs) {
1722
+ if (wires.has(input.index) || lanes.has(input.index) || cellLanes.has(input.index))
1723
+ continue;
1724
+ const source = requireSource(metadata, input.name);
1725
+ // A gated candles lane reads its empty block, no lane (wrunGatedLegStream).
1726
+ if (wrunGatedLegStream(source))
1727
+ continue;
1728
+ checkWrunLaneRead(metadata, input, source);
1729
+ }
1730
+ }
1731
+ return { wires, lanes, cellLanes, ...(barFacts !== undefined ? { barFacts } : {}) };
1732
+ }
1733
+ /** One lane input's field and side against the lane the browser serves it from, refused by name
1734
+ * (the browser's per-row refusals, raised once). */
1735
+ function checkWrunLaneRead(metadata, input, source) {
1736
+ const unknownField = () => new Error(`WRUN ${metadata.id}: unknown ${source.source} field '${source.field}' (input '${input.name}')`);
1737
+ if (input.cellType === 'array') {
1738
+ if (!WRUN_LANE_CELL_CLASSES.has(source.source)) {
1739
+ throw new Error(`WRUN ${metadata.id}: celled source class '${source.source}' is not served by the ` +
1740
+ `browser lane yet (input '${input.name}')`);
1741
+ }
1742
+ return;
1743
+ }
1744
+ switch (source.source) {
1745
+ case 'ohlcv':
1746
+ if (!isWrunSourceBlendField(source.field ?? '') && OHLCV_FIELD_COLUMNS[source.field ?? ''] === undefined) {
1747
+ throw unknownField();
1748
+ }
1749
+ return;
1750
+ case 'time':
1751
+ if (source.field !== 'bar_open_sec' && !WRUN_BAR_FACT_FIELDS.has(source.field ?? ''))
1752
+ throw unknownField();
1753
+ return;
1754
+ case 'trades':
1755
+ if (source.field !== 'volume')
1756
+ throw unknownField();
1757
+ if (source.side !== 'BUY' && source.side !== 'SELL') {
1758
+ throw new Error(`WRUN ${metadata.id}: trades volume needs side 'BUY' or 'SELL', got '${source.side}' ` +
1759
+ `(input '${input.name}')`);
1760
+ }
1761
+ return;
1762
+ case 'liquidations':
1763
+ if (source.field !== 'liquidations')
1764
+ throw unknownField();
1765
+ // The om runtime's frozen liquidations contract: side absent = the per-bar TOTAL of every
1766
+ // side; a pinned side = that side's column; anything else refuses by name.
1767
+ if (source.side !== undefined && source.side !== 'BUY' && source.side !== 'SELL') {
1768
+ throw new Error(`WRUN ${metadata.id}: liquidations side must be 'BUY', 'SELL', or absent (the per-bar total), ` +
1769
+ `got '${source.side}' (input '${input.name}')`);
1770
+ }
1771
+ return;
1772
+ case 'funding':
1773
+ // The FE K_FUNDING_RATE lane serves ONE column: the close rate in PERCENT (rateClose * 100,
1774
+ // the value the FE kScript engine sees). The om class's other fields never reach the
1775
+ // browser: refuse.
1776
+ if (source.field !== 'rate_close') {
1777
+ throw new Error(`WRUN ${metadata.id}: funding field '${source.field}' is not served by the browser lane ` +
1778
+ `(the FE engine's K_FUNDING_RATE rows carry only rate_close, as percent) (input '${input.name}')`);
1779
+ }
1780
+ return;
1781
+ case 'oi':
1782
+ if (OI_FIELD_COLUMNS[source.field ?? ''] === undefined)
1783
+ throw unknownField();
1784
+ return;
1785
+ case 'tape':
1786
+ throw new Error(`WRUN ${metadata.id}: input '${input.name}' (tape) is not celled: declare cellType "array" with max_cells`);
1787
+ default:
1788
+ throw new Error(`WRUN ${metadata.id}: source class '${source.source}' is not served by the browser lane yet ` +
1789
+ `(input '${input.name}')`);
1790
+ }
1791
+ }
1792
+ /** The celled classes the browser lanes serve by an exact join (intrabar and candles ride legs). */
1793
+ const WRUN_LANE_CELL_CLASSES = new Set([
1794
+ 'book',
1795
+ 'volume_profile',
1796
+ 'trade_volume_by_size',
1797
+ 'options_chain',
1798
+ 'tape',
1799
+ ]);
1800
+ /**
1801
+ * The market whose gap policy says whether the chart's own grid gives empty time no row: a policy
1802
+ * of `never` (the host's gap policy, `market.gapPolicyKind`: the CME family, US listings, forex,
1803
+ * prediction markets, economic series) means its rows are the bars that traded and the kScript lane
1804
+ * runs over exactly those; a crypto venue detects gaps and marks each tradeless bucket instead. The
1805
+ * chart's session market (every chart build passes it), else the facts' venue; none (no market)
1806
+ * reads as a gap-detecting one. The caller reads the policy after its `sharedHost()` call.
1807
+ */
1808
+ function wrunChartGridMarket(sources) {
1809
+ const exchange = sources.session?.exchange ?? sources.venue?.exchange;
1810
+ return typeof exchange === 'string' && exchange !== '' ? { exchange, symbol: sources.venue?.symbol } : undefined;
1811
+ }
1812
+ /**
1813
+ * True when the sheet's input 0 is no primary the shared host takes, while the browser serves it:
1814
+ * no input at all, a celled or `time` input, or a view or an interval pin on input 0 (the host's
1815
+ * primary is an unpinned fetched series, plan.ts planTime, planCells and the primary branch), or a
1816
+ * nan or zero input 0 the browser keeps off the host's dense grid (below): a candle class's on every
1817
+ * chart, any other class's where the grid cannot be laid. The browser's row axis is the chart's
1818
+ * candles whatever input 0 reads, so such a sheet is planned behind the chart's close
1819
+ * (`WRUN_ROWS_CHART_PRIMARY`) and every declared input reads as a secondary on that axis.
1820
+ */
1821
+ function wrunNeedsChartPrimary(metadata, intervalMs, lanes, sparseGrid) {
1822
+ const first = metadata.inputs.find((input) => input.index === 0);
1823
+ if (first === undefined)
1824
+ return true;
1825
+ if (first.cellType === 'array')
1826
+ return true;
1827
+ const source = metadata.inputSources[first.name];
1828
+ if (source === undefined || source.source === 'time' || source.view !== undefined)
1829
+ return true;
1830
+ // A published feed is a primary on no host: never planned behind the chart's close, so the
1831
+ // shared host refuses it by its own words on every chart (wrun_series_source_primary, under nan
1832
+ // or zero wrun_series_source_densification), as the cloud and the runner do.
1833
+ if (source.source === WRUN_ROWS_SERIES_CLASS)
1834
+ return false;
1835
+ // A nan or zero input 0 rides the host's dense grid, one bar every `intervalMs` at one phase from
1836
+ // the first row through the last (align.ts primaryGrid, densify.ts wrunDensePrimaryGrid), a bar
1837
+ // for every bucket whether it traded or not. The browser keeps the chart's candles as that run's
1838
+ // grid instead:
1839
+ // - a candle class (the host's WRUN_CANDLE_CLASSES: ohlcv, odds), on EVERY chart. A candle bucket
1840
+ // with no trade is no bar: the chart draws none (a gap-detecting venue marks it and
1841
+ // wrunChartCandleRows drops the marker, a session venue gives it no row), and the tab's kScript
1842
+ // lane serves a candle-only script the traded candles alone (2026-09-30). The dense grid fed
1843
+ // every such bucket to the package as a NaN bar, and a recursive output (Wilder RSI, EMA, a
1844
+ // running OBV) holds NaN from the first one on: `@om-core/rsi` 0.3.2 on KRAKEN XRP/USD 1d (no
1845
+ // Kraken daily bar 2026-05-01..05-04) held 60 values of 742 bars and drew nothing (2026-10-15;
1846
+ // the session-venue case below met the same death on CME first, for that venue kind alone). A
1847
+ // package that reads another lane on the chart's timeline still runs each recorded gap as a NaN row
1848
+ // (`wrunPrimaryRows`), as the kScript lane keeps the markers for it. The kit's own fix keeps its
1849
+ // dense grid off the candle classes too (`wrunPrimaryDensifies`, after kit 0.78.1);
1850
+ // - any other class (a feed such as oi or trades as input 0) where the grid cannot be laid or
1851
+ // lays rows the chart never has:
1852
+ // - a daily-landed lane (etf_flow, a daily poll lane): the host would read the grid's phase off
1853
+ // the lane's DAY stamps, which a chart coarser than a day refuses as mixed phases, until the
1854
+ // package grids a landed primary on the chart;
1855
+ // - a calendar chart (1M 3M 6M 1Y): its rows open on the 1st of a month, never on one phase of
1856
+ // the average length (36 month starts sit on 26 phases), so EVERY such package refused
1857
+ // `wrun_densify_mixed_phase` (the RSI twin's candle shape too, before the candle rule). Its
1858
+ // rows are the chart's rows (a tradeless month the chart does not draw has no row) until the
1859
+ // host steps the dense grid by calendar bars;
1860
+ // - a venue whose chart gives empty time no row (`sparseGrid`, wrunChartGridSparse): the dense
1861
+ // grid would hand the package a NaN row for every hour the market is shut (the CME family's
1862
+ // daily break and weekends), rows the chart and the kScript lane never have, so a recursive
1863
+ // output never recovers and a running total steps at every session open (RSI and OBV on CME
1864
+ // found it first, 7d8f6439ea).
1865
+ const dense = source.missing === 'nan' || source.missing === 'zero';
1866
+ if (dense && wrunChartHostEnv().sharedHost().WRUN_CANDLE_CLASSES.has(source.source))
1867
+ return true;
1868
+ if (dense && (lanes.get(0)?.join !== undefined || isCalendarIntervalMs(intervalMs) || sparseGrid))
1869
+ return true;
1870
+ return source.interval !== undefined && wrunPinnedIntervalOf(source.interval)?.ms !== intervalMs;
1871
+ }
1872
+ /** The run's settings the plan reads: the values of the params a tape input's `min_size` names
1873
+ * (the floor the lane's acquisition was asked at), and no other (the browser paints every other
1874
+ * setting on the sheet), so a sheet without a param-bound floor plans with none, as before. */
1875
+ function wrunTapePlanSettings(metadata, settings) {
1876
+ const planned = {};
1877
+ if (settings === undefined)
1878
+ return planned;
1879
+ for (const name of wrunTapeFloorParams(metadata)) {
1880
+ if (Object.hasOwn(settings, name))
1881
+ planned[name] = settings[name];
1882
+ }
1883
+ return planned;
1884
+ }
1885
+ /** The params a tape input's `min_size` names: the host resolves that floor itself, from the run's
1886
+ * settings (its planTapeFloors), so the plan reads their declarations and their values. */
1887
+ function wrunTapeFloorParams(metadata) {
1888
+ const names = new Set();
1889
+ for (const source of Object.values(metadata.inputSources)) {
1890
+ if (source?.source === 'tape' && typeof source.min_size === 'string')
1891
+ names.add(source.min_size);
1892
+ }
1893
+ return names;
1894
+ }
1895
+ /**
1896
+ * The sheet the shared host plans for one build: every lane read (`WrunLaneRead`) as the lane
1897
+ * stand-in under its own missing policy, save a published feed's, planned as the kit's own series
1898
+ * wire (`wrunPlannedSeriesRead`: the host's rule e then carries the lane's pre-window bar), every
1899
+ * stamp read (`wrunStampReads`) as an `open` read, a candles lane gated off on this chart
1900
+ * (`wrunGatedLegStream`) as a cell-less NaN stand-in, and, when input 0 is no host primary, the
1901
+ * chart's close prepended as input 0 (every declared input one index later). The sheet's
1902
+ * presentation families and params stay out: the browser delivers its own families, and the pins
1903
+ * the params set are already painted on the inputs (wrunSheetWithSettings). The one exception is a
1904
+ * param a tape input's `min_size` names, which the plan resolves from the run's settings
1905
+ * (`wrunTapeFloorParams`).
1906
+ */
1907
+ function wrunPlannedSheet(metadata, lanes, stamps, shift, cellLanes = new Map()) {
1908
+ const inputSources = {};
1909
+ for (const input of metadata.inputs) {
1910
+ const source = metadata.inputSources[input.name];
1911
+ if (source === undefined)
1912
+ continue;
1913
+ if (cellLanes.has(input.index)) {
1914
+ // A row-lane read: the celled stand-in, its wire re-pointed at the lane's own blocks below.
1915
+ inputSources[input.name] = { ...WRUN_ROWS_CELL_LANE_STAND_IN };
1916
+ }
1917
+ else if (wrunGatedLegStream(source)) {
1918
+ // A gated candles lane is planned as a scalar stand-in (its cells dropped below) and read as the
1919
+ // plan's unserved wire, the NaN placeholder of a celled slot: the host never plans, checks or
1920
+ // asks its leg, and the browser hands it an empty block on every row (wrunBrowserRowsOf).
1921
+ inputSources[input.name] = { ...WRUN_ROWS_LANE_STAND_IN, missing: 'nan' };
1922
+ }
1923
+ else if (lanes.has(input.index)) {
1924
+ inputSources[input.name] =
1925
+ source.source === WRUN_ROWS_SERIES_CLASS
1926
+ ? wrunPlannedSeriesRead(source)
1927
+ : {
1928
+ ...WRUN_ROWS_LANE_STAND_IN,
1929
+ ...(source.missing !== undefined ? { missing: source.missing } : {}),
1930
+ };
1931
+ }
1932
+ else if (stamps.has(input.index)) {
1933
+ inputSources[input.name] = { ...source, field: 'open' };
1934
+ }
1935
+ else {
1936
+ inputSources[input.name] = source;
1937
+ }
1938
+ }
1939
+ const inputs = metadata.inputs.map((input) => {
1940
+ const planned = wrunGatedLegStream(metadata.inputSources[input.name])
1941
+ ? { index: input.index, name: input.name }
1942
+ : input;
1943
+ return shift === 0 ? planned : { ...planned, index: planned.index + 1 };
1944
+ });
1945
+ if (shift === 1) {
1946
+ inputSources[WRUN_ROWS_CHART_PRIMARY] = { source: 'ohlcv', field: 'close' };
1947
+ inputs.unshift({ index: 0, name: WRUN_ROWS_CHART_PRIMARY });
1948
+ }
1949
+ const floorParams = wrunTapeFloorParams(metadata);
1950
+ return {
1951
+ id: metadata.id,
1952
+ name: metadata.name,
1953
+ ...(metadata.abi_version !== undefined ? { abi_version: metadata.abi_version } : {}),
1954
+ params: floorParams.size === 0 ? [] : metadata.params.filter((param) => floorParams.has(param.name)),
1955
+ inputSources,
1956
+ inputs,
1957
+ outputs: metadata.outputs.map((output) => ({ index: output.index, name: output.name })),
1958
+ };
1959
+ }
1960
+ /**
1961
+ * The ohlcv inputs reading `time` (the candle's open stamp, in ms: OHLCV_FIELD_COLUMNS), by input
1962
+ * index, with the span of a forming view's bucket. The browser serves them and the shared host's
1963
+ * chart profiles do not (its FEED_FIELDS lists no ohlcv `time`, wrun_field_unsupported): the
1964
+ * browser's own read is kept here until the package serves it. The plan reads each one as `open`
1965
+ * (the same candle, the same policy and views), the aligner at the stamp column; a forming view
1966
+ * reads its bucket's open on every row, the browser's rule (a stamp is exact even on a partial
1967
+ * bucket).
1968
+ */
1969
+ function wrunStampReads(metadata) {
1970
+ const stamps = new Map();
1971
+ for (const input of metadata.inputs) {
1972
+ const source = metadata.inputSources[input.name];
1973
+ if (source?.source !== 'ohlcv' || source.field !== 'time')
1974
+ continue;
1975
+ const formingMs = source.view === 'forming' ? wrunPinnedIntervalOf(source.interval)?.ms : undefined;
1976
+ stamps.set(input.index, formingMs !== undefined ? { formingMs } : {});
1977
+ }
1978
+ return stamps;
1979
+ }
1980
+ /** A finite row stamp, else NaN. */
1981
+ function wrunRowTs(row) {
1982
+ const ts = Number(row[0]);
1983
+ return Number.isFinite(ts) ? ts : Number.NaN;
1984
+ }
1985
+ /** The first and last finite stamps of ascending rows, undefined when none is finite. */
1986
+ function wrunRowsSpan(rows) {
1987
+ let first;
1988
+ for (const row of rows) {
1989
+ first = wrunRowTs(row);
1990
+ if (Number.isFinite(first))
1991
+ break;
1992
+ }
1993
+ let last;
1994
+ for (let at = rows.length - 1; at >= 0; at -= 1) {
1995
+ last = wrunRowTs(rows[at]);
1996
+ if (Number.isFinite(last))
1997
+ break;
1998
+ }
1999
+ return first !== undefined && last !== undefined && Number.isFinite(first) && Number.isFinite(last)
2000
+ ? { first, last }
2001
+ : undefined;
2002
+ }
2003
+ /** Several answers to one ask (the chart's candles and a deeper leg of the same market and span,
2004
+ * the forming pre-roll), merged by stamp, ascending: on a stamp two answers hold, the earlier
2005
+ * answer's row stands (the chart's own row over a leg's, a leg's over a pre-roll's). Answers that
2006
+ * sit one after the other (the pre-roll before the chart's first row, every tick) are laid end to
2007
+ * end. */
2008
+ function mergeWrunRowsByTs(answers) {
2009
+ const spans = answers.map((rows) => ({ rows, span: wrunRowsSpan(rows) })).filter((entry) => entry.span !== undefined);
2010
+ spans.sort((a, b) => (a.span?.first ?? 0) - (b.span?.first ?? 0));
2011
+ if (spans.every((entry, at) => at === 0 || (spans[at - 1].span?.last ?? 0) < (entry.span?.first ?? 0))) {
2012
+ return spans.length === 1 ? spans[0].rows : spans.flatMap((entry) => entry.rows);
2013
+ }
2014
+ const byTs = new Map();
2015
+ for (const rows of answers) {
2016
+ for (const row of rows) {
2017
+ const ts = wrunRowTs(row);
2018
+ if (Number.isFinite(ts) && !byTs.has(ts))
2019
+ byTs.set(ts, row);
2020
+ }
2021
+ }
2022
+ return [...byTs.entries()].sort((a, b) => a[0] - b[0]).map(([, row]) => row);
2023
+ }
2024
+ /** The smallest step between two consecutive stamps: a clockless build's grid span. */
2025
+ function wrunRowsStepMs(stamps) {
2026
+ let step;
2027
+ for (let at = 1; at < stamps.length; at += 1) {
2028
+ const gap = stamps[at] - stamps[at - 1];
2029
+ if (gap > 0 && (step === undefined || gap < step))
2030
+ step = gap;
2031
+ }
2032
+ return step;
2033
+ }
2034
+ /** The index of the last row of ascending `rows` stamped at or before `ms` (-1 when none is). */
2035
+ function wrunLastRowAtOrBefore(rows, ms) {
2036
+ let low = 0;
2037
+ let high = rows.length;
2038
+ while (low < high) {
2039
+ const mid = (low + high) >>> 1;
2040
+ if (Number(rows[mid][0]) <= ms)
2041
+ low = mid + 1;
2042
+ else
2043
+ high = mid;
2044
+ }
2045
+ return low - 1;
2046
+ }
2047
+ /** A lane's rows stamped after `afterTs`, in lane order (a row without a finite stamp stays: the
2048
+ * cell adapter skips it either way). */
2049
+ function wrunLaneRowsAfter(rows, afterTs) {
2050
+ return rows === undefined ? [] : rows.filter((row) => !(Number(row[0]) <= afterTs));
2051
+ }
2052
+ /** A lane's rows as the host's cell adapter reads them. The adapter takes `Array.isArray` rows only
2053
+ * and skips any other row without a word, and the book lane holds typed ones: every live book row
2054
+ * (the push intake's fold, the heatmap rider, Float64Array) and the plain K_ORDERBOOK lane's whole
2055
+ * history. A typed row is copied to a plain array; plain rows pass as they are. */
2056
+ /** A profile stream's adapted rows, kept per leg buffer and ask: the buffer is replaced whole by every merge of its
2057
+ * fetch, so a tail build over the same buffer (a live tick) adapts nothing again. */
2058
+ const WRUN_LEG_STREAM_CELL_ROWS = new WeakMap();
2059
+ /** A `volume_profile_candles` leg's lane rows (`[ts, [low, high, buy, sell], ...]`, ms) as the cell rows its ask
2060
+ * reads, the shared host's adapter at the ask's own span and facets (the exact-join profile's rule). */
2061
+ function wrunLegStreamCellRows(host, ask, rows) {
2062
+ let byAsk = WRUN_LEG_STREAM_CELL_ROWS.get(rows);
2063
+ const kept = byAsk?.get(ask.key);
2064
+ if (kept !== undefined)
2065
+ return kept;
2066
+ const adapted = host.adaptWrunCells(ask, wrunPlainLaneRows(rows), wrunLaneCellFacts(ask));
2067
+ if (byAsk === undefined) {
2068
+ byAsk = new Map();
2069
+ WRUN_LEG_STREAM_CELL_ROWS.set(rows, byAsk);
2070
+ }
2071
+ byAsk.set(ask.key, adapted);
2072
+ return adapted;
2073
+ }
2074
+ function wrunPlainLaneRows(rows) {
2075
+ return rows.some((row) => !Array.isArray(row))
2076
+ ? rows.map((row) => (Array.isArray(row) ? row : Array.from(row)))
2077
+ : rows;
2078
+ }
2079
+ /** The session answers a run's clock carries (`WrunHostAlignClock`), keyed as the aligner reads
2080
+ * them: `wrunSessionClock` over the plan on the chart's session (the CME session rows' bounds, the
2081
+ * leg candles' closes and opens; none without a session), and a calendar row's bounds on every
2082
+ * market (`wrunCalendarRowBounds`, the chart's own rule beside the package's). The browser plans
2083
+ * under the chart's placeholder market (`WRUN_ROWS_CHART_MARKET`), so an ask on it (the chart's own
2084
+ * rows, a leg that names no exchange) reads the chart's exchange, as the browser's fetch does. */
2085
+ function wrunSessionAnswersOf(host, plan, session, intervalMs) {
2086
+ const calendarBounds = wrunCalendarRowBounds(intervalMs);
2087
+ const calendar = calendarBounds === undefined ? {} : { rowBounds: calendarBounds };
2088
+ if (session === undefined)
2089
+ return calendar;
2090
+ const { exchange, sessionType } = session;
2091
+ const fetches = exchange === undefined
2092
+ ? plan.fetches
2093
+ : plan.fetches.map((ask) => (ask.exchange === WRUN_ROWS_CHART_MARKET.exchange ? { ...ask, exchange } : ask));
2094
+ return {
2095
+ ...host.wrunSessionClock({ ...plan, fetches }, { exchange: exchange ?? '', intervalMs, sessionType }),
2096
+ ...calendar,
2097
+ };
2098
+ }
2099
+ /**
2100
+ * Plan a sheet's rows on the shared host under the chart-browser profile and answer the plan with
2101
+ * the browser's own rows: the browser's refusals first (`checkWrunRowReads`), then `planWrunRun`
2102
+ * over `wrunPlannedSheet` against the chart (its own market as the fetch placeholders, the window
2103
+ * the chart's rows span), then each ask answered by the rows of the lane or leg the browser
2104
+ * fetched it through. Undefined when there is no primary row to build.
2105
+ *
2106
+ * The answers: the chart's candles (the interior gap markers included for a timeline lane, the
2107
+ * forming pre-roll and any deeper own-market leg at the chart's span before them) for the chart's
2108
+ * own candles; a pinned leg's closed candles, then the running ones a forming view reads; the
2109
+ * lanes' own rows, each scalar wire re-pointed at the column its field reads there (the browser's
2110
+ * lanes answer wider rows than the plan's `[ts, ...fields]`), the liquidations total summed per
2111
+ * row; each lane read's lane rows under the lane's join; the celled lanes through the host's cell
2112
+ * adapter (`adaptWrunCells`, the kScript row dialect). The clock carries the chart's own row
2113
+ * stamps as the grid (and their phase for a dense one), the session calendar's answers for the plan
2114
+ * on the chart's session (`wrunSessionAnswersOf`: the CME session rows' bounds, the leg candles'
2115
+ * closes and opens, a calendar row's bounds), and the venue's calendar.
2116
+ *
2117
+ * `cellsAfterTs`: a tail build's or a carry advance's carry `throughTs`. The host's pass starts at
2118
+ * the first row after it and a cell block never carries, so only the celled lanes' rows stamped
2119
+ * after it are adapted and only an intrabar leg's candles those rows can hold are sliced (a live
2120
+ * tick never converts the whole window's book, profile or finer candles again).
2121
+ */
2122
+ function wrunHostRunOf(metadata, sources, clock, cellsAfterTs) {
2123
+ const ohlcvRows = sources.ohlcvRows ?? [];
2124
+ const reads = checkWrunRowReads(metadata, sources, clock, ohlcvRows.length > 0);
2125
+ const primaryRows = wrunPrimaryRows(metadata, reads.wires, ohlcvRows);
2126
+ const gridTs = [];
2127
+ for (const row of primaryRows) {
2128
+ const ts = wrunRowTs(row);
2129
+ if (Number.isFinite(ts))
2130
+ gridTs.push(ts);
2131
+ }
2132
+ if (gridTs.length === 0)
2133
+ return undefined;
2134
+ const firstTs = gridTs[0];
2135
+ const lastTs = gridTs[gridTs.length - 1];
2136
+ const intervalMs = clock?.intervalMs ?? sources.venue?.intervalMs ?? wrunRowsStepMs(gridTs) ?? Intervals.MINUTE;
2137
+ const nowMs = clock?.nowMs ?? lastTs + intervalMs;
2138
+ const host = wrunChartHostEnv().sharedHost();
2139
+ const stamps = wrunStampReads(metadata);
2140
+ // The grid is sparse when the market's gap policy is `never`: read here, after `sharedHost()` above (the rows binder
2141
+ // that answers it loads with the host).
2142
+ const gridMarket = wrunChartGridMarket(sources);
2143
+ const gridSparse = gridMarket !== undefined &&
2144
+ wrunChartHostEnv().market.gapPolicyKind(gridMarket.exchange, gridMarket.symbol) === 'never';
2145
+ const shift = wrunNeedsChartPrimary(metadata, intervalMs, reads.lanes, gridSparse) ? 1 : 0;
2146
+ const context = {
2147
+ ...WRUN_ROWS_CHART_MARKET,
2148
+ intervalMs,
2149
+ nowMs,
2150
+ fromMs: firstTs,
2151
+ toMs: lastTs,
2152
+ permissions: WRUN_ROWS_PERMISSIONS,
2153
+ settings: wrunTapePlanSettings(metadata, sources.settings),
2154
+ wireCaps: wrunBrowserRunWireCaps(),
2155
+ ...wrunRowsOptionsChains(metadata, host),
2156
+ ...wrunRowsCoinLegs(metadata),
2157
+ };
2158
+ const planned = host.planWrunRun(wrunPlannedSheet(metadata, reads.lanes, stamps, shift, reads.cellLanes), context, 'chart-browser');
2159
+ // The session calendar's answers, keyed as the aligner reads them; the intrabar slice below reads
2160
+ // them too.
2161
+ const session = wrunSessionAnswersOf(host, planned, sources.session, intervalMs);
2162
+ const askByKey = new Map(planned.fetches.map((ask) => [ask.key, ask]));
2163
+ const answers = new Map();
2164
+ const cellAnswers = new Map();
2165
+ const columns = new Map();
2166
+ const laneWires = new Map();
2167
+ const cellLaneWires = new Map();
2168
+ const cellLegKeys = new Map();
2169
+ const softRefused = new Set();
2170
+ // The inputs this market does not need (wrunSheetWithLaneDemand: their needed_by leaves it out), and
2171
+ // the candles lanes gated off on this chart (wrunSheetWithLaneGate, planned as a scalar stand-in): no
2172
+ // lane was asked for them, so each scalar read is the plan's unserved wire, its fill on every row,
2173
+ // never gating.
2174
+ const undemanded = new Set(metadata.inputs
2175
+ .filter((input) => metadata.inputSources[input.name]?.undemanded === true)
2176
+ .map((input) => input.index));
2177
+ const offer = (key, rows) => {
2178
+ if (rows === undefined)
2179
+ return;
2180
+ const list = answers.get(key);
2181
+ if (list === undefined)
2182
+ answers.set(key, [rows]);
2183
+ else if (!list.includes(rows))
2184
+ list.push(rows);
2185
+ };
2186
+ // A leg's rows: its closed candles, then the running ones its fetch answered (the live candle and
2187
+ // the holding candle's open read them; no cursor admits a candle before its close).
2188
+ const legRows = new Map();
2189
+ const legRowsOf = (leg) => {
2190
+ let rows = legRows.get(leg.fetchKey);
2191
+ if (rows === undefined) {
2192
+ const closed = sources.pinnedCandleRows?.[leg.fetchKey] ?? [];
2193
+ const live = sources.pinnedLiveCandleRows?.[leg.fetchKey];
2194
+ rows = live !== undefined && live.length > 0 ? [...closed, ...live] : closed;
2195
+ legRows.set(leg.fetchKey, rows);
2196
+ }
2197
+ return rows;
2198
+ };
2199
+ // An intrabar leg's candles as this build reads them: past the carry (`cellsAfterTs`) a tail
2200
+ // reads blocks only from the bounds of the carry's own row on (later rows open no earlier), so
2201
+ // the candles from there on, behind the newest candle closed by now that opens before them (the
2202
+ // slicer's coverage witness: the leg reaches each of those rows exactly as the whole buffer does).
2203
+ // The buffer ascends by open (the leg merge keeps it so). The whole buffer for a full build.
2204
+ // `closeMs`: the leg's candle closes, the session calendar's under the wire's leg key.
2205
+ const intrabarRows = new Map();
2206
+ const intrabarRowsOf = (leg, closeMs) => {
2207
+ if (intrabarRows.has(leg.fetchKey))
2208
+ return intrabarRows.get(leg.fetchKey);
2209
+ const rows = sources.intrabarRows?.[leg.fetchKey];
2210
+ let read = rows;
2211
+ if (rows !== undefined && cellsAfterTs !== undefined) {
2212
+ const fromMs = Math.min(cellsAfterTs, host.wrunLegRowBoundsMs(cellsAfterTs, intervalMs, session.rowBounds).openMs);
2213
+ let at = wrunLastRowAtOrBefore(rows, fromMs);
2214
+ while (at >= 0 && host.wrunLegCandleCloseMs(Number(rows[at][0]), leg.legMs, closeMs) > nowMs)
2215
+ at -= 1;
2216
+ if (at > 0)
2217
+ read = rows.slice(at);
2218
+ }
2219
+ intrabarRows.set(leg.fetchKey, read);
2220
+ return read;
2221
+ };
2222
+ let liquidationTotals;
2223
+ const liquidationTotalRows = () => {
2224
+ liquidationTotals ??= (sources.liquidationRows ?? []).map((row) => [
2225
+ Number(row[0]),
2226
+ Number(row[1]) + Number(row[2]),
2227
+ ]);
2228
+ return liquidationTotals;
2229
+ };
2230
+ // The chart's own candles at the chart's span: the chart's rows first, then the forming
2231
+ // pre-roll (strictly before the first row: the fold's reach, never a row).
2232
+ for (const ask of planned.fetches) {
2233
+ if (ask.class !== 'ohlcv' || ask.foreign || ask.intervalMs !== intervalMs)
2234
+ continue;
2235
+ offer(ask.key, primaryRows);
2236
+ offer(ask.key, sources.formingPreRoll?.rows);
2237
+ }
2238
+ for (const wire of planned.wires) {
2239
+ if (wire.kind === 'time')
2240
+ continue;
2241
+ if (wire.kind === 'scalar' && (wire.unserved === true || wire.ownPeriod === true))
2242
+ continue;
2243
+ const index = wire.inputIndex - shift;
2244
+ if (index < 0)
2245
+ continue;
2246
+ if (wire.kind === 'scalar' && undemanded.has(index))
2247
+ continue;
2248
+ const key = wire.fetchKey;
2249
+ const lane = reads.lanes.get(index);
2250
+ if (lane !== undefined) {
2251
+ // A published feed's read is planned as its own class (`wrunPlannedSeriesRead`): the lane's
2252
+ // rows answer the plan's own series ask, so the aligner reads them under the host's series
2253
+ // rules (rule e: the pre-window bar seeds a carry). Every other lane read rides its lane's key.
2254
+ const read = askByKey.get(key)?.class === WRUN_ROWS_SERIES_CLASS ? { ...lane, key } : lane;
2255
+ laneWires.set(wire.inputIndex, read);
2256
+ offer(read.key, read.rows);
2257
+ continue;
2258
+ }
2259
+ const cellLane = wire.kind === 'cells' ? reads.cellLanes.get(index) : undefined;
2260
+ if (cellLane !== undefined) {
2261
+ // A row-lane read: the lane's own blocks under the input's own key (its projection), the live row the
2262
+ // chart's last, a tail's past its carry; the stand-in's ask is never read.
2263
+ cellLaneWires.set(wire.inputIndex, cellLane);
2264
+ if (!cellAnswers.has(cellLane.key)) {
2265
+ cellAnswers.set(cellLane.key, wrunRowLaneCellRows(cellLane.lane, cellLane.rows, cellLane.input, { liveTs: lastTs, afterTs: cellsAfterTs }));
2266
+ }
2267
+ continue;
2268
+ }
2269
+ const pinned = reads.wires.get(index);
2270
+ if (pinned !== undefined) {
2271
+ // A pin on a venue the gateway does not serve to scripts yet is soft-refused (never fetched,
2272
+ // a note names it, wrun-pin-venues): its confirmed read is the plan's unserved wire, its fill
2273
+ // on every row and never gating, so the sibling inputs still run (the browser's rule).
2274
+ const pinnedLeg = pinned.kind === 'period' ? pinned.leg : pinned.kind === 'grid' ? pinned.gridLeg : undefined;
2275
+ const venue = pinnedLeg?.market?.exchange;
2276
+ if (venue !== undefined && wrunPinVenueVerdict(venue) === 'unserved')
2277
+ softRefused.add(wire.inputIndex);
2278
+ switch (pinned.kind) {
2279
+ case 'period':
2280
+ offer(key, legRowsOf(pinned.leg));
2281
+ break;
2282
+ case 'grid':
2283
+ offer(key, legRowsOf(pinned.gridLeg));
2284
+ break;
2285
+ case 'forming':
2286
+ if (pinned.gridLeg !== undefined)
2287
+ offer(key, legRowsOf(pinned.gridLeg));
2288
+ break;
2289
+ case 'typed':
2290
+ offer(key, pinned.lane === 'funding' ? sources.fundingRateRows : sources.openInterestRows);
2291
+ columns.set(wire.inputIndex, pinned.column);
2292
+ break;
2293
+ case 'intrabar':
2294
+ case 'candles': {
2295
+ // A celled leg reads its own fetch (the browser asks each one apart, a leg at the chart's
2296
+ // own span included, where the plan would share the chart's candles): its rows ride a key
2297
+ // of their own.
2298
+ const own = `${key}|leg=${pinned.leg.fetchKey}`;
2299
+ cellLegKeys.set(wire.inputIndex, own);
2300
+ const legKey = wire.kind === 'cells' ? wire.leg?.key : undefined;
2301
+ const closeMs = legKey === undefined ? undefined : session.legCloses?.[legKey];
2302
+ if (pinned.leg.stream?.class === 'volume_profile_candles') {
2303
+ // A profile stream reads its ask's ADAPTED cell rows ({ ts, cells }, the shared host's leg stream
2304
+ // reader): the leg's lane rows adapted once, by the stream's own ask (its span and facets).
2305
+ if (!cellAnswers.has(own)) {
2306
+ const ask = askByKey.get(key);
2307
+ cellAnswers.set(own, ask === undefined ? [] : wrunLegStreamCellRows(host, ask, legRowsOf(pinned.leg)));
2308
+ }
2309
+ break;
2310
+ }
2311
+ offer(own, pinned.kind === 'intrabar' ? intrabarRowsOf(pinned.leg, closeMs) : legRowsOf(pinned.leg));
2312
+ break;
2313
+ }
2314
+ default:
2315
+ break;
2316
+ }
2317
+ continue;
2318
+ }
2319
+ const source = requireSource(metadata, wire.inputName);
2320
+ if (wire.kind === 'cells') {
2321
+ const ask = askByKey.get(key);
2322
+ if (ask === undefined || cellAnswers.has(key))
2323
+ continue;
2324
+ const lane = source.source === 'book'
2325
+ ? sources.bookRows
2326
+ : source.source === 'volume_profile'
2327
+ ? sources.volumeProfileRows
2328
+ : source.source === 'trade_volume_by_size'
2329
+ ? sources.tradeVolumeBySizeRows
2330
+ : source.source === 'tape'
2331
+ ? sources.tapeRows
2332
+ : sources.optionsChainRows;
2333
+ // The browser's book lane is asked at the sheet's depth already: its rows are read whole. The
2334
+ // tape keeps the plan's floor (the one its lane was asked at, from the run's settings).
2335
+ const adapted = ask.class === 'book' ? { ...ask, max_depth: undefined } : ask;
2336
+ // Past the carry only (`cellsAfterTs`), except the options chain: the live row reads its newest poll, however old.
2337
+ const rows = wrunPlainLaneRows(cellsAfterTs === undefined || source.source === 'options_chain'
2338
+ ? (lane ?? [])
2339
+ : wrunLaneRowsAfter(lane, cellsAfterTs));
2340
+ cellAnswers.set(key, host.adaptWrunCells(adapted, rows, wrunLaneCellFacts(ask)));
2341
+ continue;
2342
+ }
2343
+ switch (source.source) {
2344
+ case 'trades': {
2345
+ const lane = wrunSourceLane(source);
2346
+ offer(key, lane === 'trades_usd'
2347
+ ? sources.buySellVolumeUsdRows
2348
+ : lane === 'trades'
2349
+ ? sources.buySellVolumeRows
2350
+ : ((lane === undefined ? undefined : sources.tradeLegRows?.[lane]) ?? []));
2351
+ columns.set(wire.inputIndex, source.side === 'SELL' ? 2 : 1);
2352
+ // A pin on a venue not served to scripts yet is never asked: its fill, as a candle pin's.
2353
+ if (source.exchange !== undefined && wrunPinVenueVerdict(source.exchange) === 'unserved') {
2354
+ softRefused.add(wire.inputIndex);
2355
+ }
2356
+ break;
2357
+ }
2358
+ case 'liquidations':
2359
+ if (source.side === undefined) {
2360
+ offer(key, liquidationTotalRows());
2361
+ columns.set(wire.inputIndex, 1);
2362
+ }
2363
+ else {
2364
+ offer(key, sources.liquidationRows);
2365
+ columns.set(wire.inputIndex, source.side === 'SELL' ? 2 : 1);
2366
+ }
2367
+ break;
2368
+ case 'funding':
2369
+ offer(key, sources.fundingRateRows);
2370
+ columns.set(wire.inputIndex, 1);
2371
+ break;
2372
+ case 'oi':
2373
+ offer(key, sources.openInterestRows);
2374
+ columns.set(wire.inputIndex, OI_FIELD_COLUMNS[source.field ?? '']);
2375
+ break;
2376
+ default:
2377
+ break;
2378
+ }
2379
+ }
2380
+ // A candle's stamp reads the stamp column (the browser's ohlcv `time`, kept local: the shared
2381
+ // host's chart profiles serve no ohlcv `time`).
2382
+ for (const index of stamps.keys())
2383
+ columns.set(index + shift, 0);
2384
+ const answered = new Map();
2385
+ for (const [key, list] of answers)
2386
+ answered.set(key, list.length === 1 ? list[0] : mergeWrunRowsByTs(list));
2387
+ for (const [key, rows] of cellAnswers)
2388
+ answered.set(key, rows);
2389
+ const plan = {
2390
+ ...planned,
2391
+ wires: planned.wires.map((wire) => {
2392
+ if (wire.kind === 'cells') {
2393
+ const laneRead = cellLaneWires.get(wire.inputIndex);
2394
+ if (laneRead !== undefined) {
2395
+ // The row lane's own blocks, class and width (the stand-in's never reach the aligner or the packer).
2396
+ return {
2397
+ ...wire,
2398
+ fetchKey: laneRead.key,
2399
+ cell: { ...wire.cell, class: laneRead.lane.sourceClass, tupleWidth: laneRead.lane.width },
2400
+ ...(laneRead.input.source.missing === 'empty' ? { missing: 'empty' } : {}),
2401
+ };
2402
+ }
2403
+ const own = cellLegKeys.get(wire.inputIndex);
2404
+ if (own === undefined)
2405
+ return wire;
2406
+ // An open-interest stream reads its rows through the columns its leg names: the browser's lane serves
2407
+ // `[ts, open, high, low, close]` whatever field order the plan's own ask holds (as a scalar oi read's column).
2408
+ const cellClass = wire.cell.class;
2409
+ const leg = cellClass === 'oi_candles' ? wire.leg : undefined;
2410
+ return leg === undefined
2411
+ ? { ...wire, fetchKey: own }
2412
+ : { ...wire, fetchKey: own, leg: { ...leg, columns: WRUN_OI_STREAM_LANE_COLUMNS } };
2413
+ }
2414
+ if (wire.kind !== 'scalar')
2415
+ return wire;
2416
+ // An undemanded input reads its fill, except an is_new_period view on a pin equal to the grid
2417
+ // (`ownPeriod`), which asks nothing on any market and keeps its 1, as the shared planner plans it.
2418
+ if (undemanded.has(wire.inputIndex - shift) && wire.ownPeriod !== true) {
2419
+ return { ...wire, unserved: true };
2420
+ }
2421
+ const lane = laneWires.get(wire.inputIndex);
2422
+ if (lane !== undefined) {
2423
+ // The lane read: the lane's rows, its column, its join (the stand-in's ask is never read; a
2424
+ // series read keeps its own ask's key, which the lane's rows answer).
2425
+ return {
2426
+ ...wire,
2427
+ fetchKey: lane.key,
2428
+ column: lane.column,
2429
+ ...(lane.join !== undefined ? { join: lane.join } : {}),
2430
+ };
2431
+ }
2432
+ if (softRefused.has(wire.inputIndex) && wire.view === 'confirmed')
2433
+ return { ...wire, unserved: true };
2434
+ const column = columns.get(wire.inputIndex);
2435
+ return column === undefined || wire.blend !== undefined ? wire : { ...wire, column };
2436
+ }),
2437
+ // The chart's rows are the window: the warm-up rides inside them (the run pass widened the
2438
+ // fetch), so the first row the run evaluates is the chart's first.
2439
+ warmup: { ...planned.warmup, evaluateFromMs: firstTs },
2440
+ };
2441
+ const hostClock = {
2442
+ nowMs,
2443
+ intervalMs,
2444
+ primaryTs: gridTs,
2445
+ // The chart's own bar phase: the phase witness a dense primary grid reads beside its rows.
2446
+ phaseHint: firstTs,
2447
+ ...session,
2448
+ ...(reads.barFacts !== undefined ? { barFacts: reads.barFacts } : {}),
2449
+ };
2450
+ const emptyBlocks = metadata.inputs
2451
+ .filter((input) => wrunGatedLegStream(metadata.inputSources[input.name]))
2452
+ .map((input) => input.index);
2453
+ return { plan, sources: answered, clock: hostClock, shift, stamps, emptyBlocks };
2454
+ }
2455
+ /** The host's rows as the browser packs them: the scalar block (the prepended chart close
2456
+ * dropped), and the celled inputs' blocks by the sheet's input index (absent when the row carries
2457
+ * none; a present empty block for a candles lane gated off on this chart, `emptyBlocks`); the
2458
+ * strategy bar rides the broker feed. A block is the host's own array for this build and nothing
2459
+ * writes to it, so it rides uncopied: `packWrunRows` makes the one copy. */
2460
+ function wrunBrowserRowsOf(rows, run) {
2461
+ const { shift, emptyBlocks } = run;
2462
+ return rows.map((row) => {
2463
+ let cellBlocks;
2464
+ if (row.cellBlocks !== undefined) {
2465
+ for (const [index, block] of Object.entries(row.cellBlocks)) {
2466
+ (cellBlocks ??= new Map()).set(Number(index) - shift, Array.isArray(block) ? block : Array.from(block));
2467
+ }
2468
+ }
2469
+ for (const index of emptyBlocks)
2470
+ (cellBlocks ??= new Map()).set(index, []);
2471
+ const values = shift === 0 ? [...row.values] : row.values.slice(shift);
2472
+ for (const [index, stamp] of run.stamps) {
2473
+ if (stamp.formingMs !== undefined)
2474
+ values[index] = wrunFormingBucketStart(row.ts, stamp.formingMs);
2475
+ }
2476
+ return { ts: row.ts, values, ...(cellBlocks !== undefined ? { cellBlocks } : {}) };
2477
+ });
2478
+ }
2479
+ /** The browser's rows as the host's carry reads them (a replay reads the last stamp; a carry
2480
+ * input's value off the rows when there is nothing to replay). */
2481
+ function wrunHostRowsOf(rows, shift) {
2482
+ return rows.map((row) => ({ ts: row.ts, values: shift === 0 ? row.values : [Number.NaN, ...row.values] }));
2483
+ }
2484
+ /** The empty seed: the state before any row (a tail from it equals the full build). */
2485
+ export function emptyWrunInputCarry() {
2486
+ return wrunChartHostEnv().sharedHost().emptyWrunInputCarry();
2487
+ }
2488
+ /**
2489
+ * Build the per-bar input rows for a package over the chart's source rows: the shared host's
2490
+ * aligner (`alignWrunRows` under the chart-browser profile) over the browser's own rows
2491
+ * (`wrunHostRunOf`). The row axis is the chart's candles; a row a carry input's leading gap
2492
+ * abstains is absent (the program's decision 1). A nan or zero primary of a candle class walks the
2493
+ * chart's candles on every chart: a bucket with no trade is no bar, and a dense NaN bar there
2494
+ * would hold a recursive output at NaN from the first hole on, where the tab's kScript lane serves
2495
+ * a candle-only script the traded candles alone. A nan or zero primary of any other class rides the
2496
+ * dense grid at the chart's phase (the decision's dense primary grid), save on a calendar chart, a
2497
+ * session venue or a daily-landed lane, where it walks the chart's own rows too
2498
+ * (`wrunNeedsChartPrimary`). `clock` is required when any input pins a leg, a typed feed or a daily
2499
+ * lane (the as-of alignment), and carries the chart's exact interval: a calendar chart is known by
2500
+ * it.
2501
+ */
2502
+ export function buildWrunInputRows(metadata, sources, clock) {
2503
+ const run = wrunHostRunOf(metadata, sources, clock);
2504
+ if (run === undefined)
2505
+ return [];
2506
+ return wrunBrowserRowsOf(wrunChartHostEnv().sharedHost().alignWrunRows(run.plan, run.sources, run.clock), run);
2507
+ }
2508
+ /**
2509
+ * The TAIL of the full build: the input rows for every primary bar at or after `fromTs`, resumed
2510
+ * from `carrySeed` (the state after every bar strictly before `fromTs`, see
2511
+ * `advanceWrunInputCarry`); equal, row for row, to `buildWrunInputRows(...).filter(row => row.ts
2512
+ * >= fromTs)` (the host's `alignWrunTailRows`).
2513
+ */
2514
+ export function buildWrunInputTailRows(metadata, sources, fromTs, carrySeed, clock) {
2515
+ const run = wrunHostRunOf(metadata, sources, clock, carrySeed.throughTs);
2516
+ if (run === undefined)
2517
+ return [];
2518
+ return wrunBrowserRowsOf(wrunChartHostEnv().sharedHost().alignWrunTailRows(run.plan, run.sources, run.clock, fromTs, carrySeed), run);
2519
+ }
2520
+ /**
2521
+ * Advance a carry seed over CLOSED input rows (rows the session committed) to exactly the state the
2522
+ * full build holds after them (the host's `advanceWrunCarry`: the aligner's own pass replayed
2523
+ * through the last closed row over the same rows and clock; with no rows handed in, a plan that
2524
+ * reads no leg advances from the rows' carry values alone). Returns a NEW carry; the seed is never
2525
+ * mutated.
2526
+ */
2527
+ export function advanceWrunInputCarry(metadata, seed, closedRows, sources, clock) {
2528
+ const host = wrunChartHostEnv().sharedHost();
2529
+ if (closedRows.length === 0)
2530
+ return host.cloneWrunInputCarry(seed);
2531
+ const replay = sources?.ohlcvRows !== undefined && sources.ohlcvRows.length > 0;
2532
+ // With no chart rows handed in, the committed rows' stamps stand for them (the plan alone).
2533
+ const run = wrunHostRunOf(metadata, replay ? sources : { ...sources, ohlcvRows: closedRows.map((row) => [row.ts]) }, clock, seed.throughTs);
2534
+ if (run === undefined)
2535
+ return host.cloneWrunInputCarry(seed);
2536
+ const rows = wrunHostRowsOf(closedRows, run.shift);
2537
+ return replay
2538
+ ? host.advanceWrunCarry(run.plan, rows, seed, run.sources, run.clock)
2539
+ : host.advanceWrunCarry(run.plan, rows, seed);
2540
+ }
2541
+ /** init()'s positional argument block: declared param defaults overlaid with
2542
+ * any user-provided values by param name (wrunParamValuesFromSettings reads
2543
+ * them off the overlay's settings, a colour as its packed number). Every
2544
+ * param keeps its declared position; an om style knob holds its slot as a 0
2545
+ * placeholder and never reaches the module (the om runtime's own layout:
2546
+ * `metadata.params.map((p) => resolvedParams[p.name] ?? 0)` over the
2547
+ * non-style params), so its string default never becomes an argument.
2548
+ * Each setting passes the param value rule the om daemon runs
2549
+ * (the shared host's wrunParamValueRefusal: finite, within min and max, a
2550
+ * whole number for an int, one of a choice's options; a declared step is
2551
+ * only the stepper's increment, never a grid the value must sit on) or the
2552
+ * run is refused by the setting's name before init(), where a kScript
2553
+ * built-in refuses the same setting at input(). A host-filled slot holds the
2554
+ * host's number and a text setting's its byte count, so neither is a setting
2555
+ * the rule reads. */
2556
+ export function buildWrunInitArgs(metadata, overrides = {}) {
2557
+ return metadata.params.map((param) => {
2558
+ if (param.style)
2559
+ return 0;
2560
+ const override = overrides[param.name];
2561
+ const value = override !== undefined && Number.isFinite(override)
2562
+ ? override
2563
+ : typeof param.default === 'number'
2564
+ ? param.default
2565
+ : 0;
2566
+ const refusal = wrunParamRunValueRefusal(param, value);
2567
+ if (refusal !== undefined)
2568
+ throw new Error(wrunSettingRefusedMessage(param.name, refusal));
2569
+ return value;
2570
+ });
2571
+ }
2572
+ /** The param value rule's word on one param's run value (buildWrunInitArgs reads it before init()):
2573
+ * undefined when the param takes the value, or when the rule never reads the param (an om style
2574
+ * knob holds a placeholder, a host-filled slot the host's number, a text slot its byte count). */
2575
+ function wrunParamRunValueRefusal(param, value) {
2576
+ if (param.style || param.host_fill !== undefined || param.type === 'text')
2577
+ return undefined;
2578
+ return wrunChartHostEnv().sharedHost().wrunParamValueRefusal(param, value);
2579
+ }
2580
+ /**
2581
+ * The run's param value rule as a test of saved settings by param name, the shared host loaded
2582
+ * first: whether `params` refuse a setting's value the way buildWrunInitArgs refuses it before
2583
+ * init(). A draft's carried value the rule refuses would refuse every run of the new build, so the
2584
+ * mount drops it (wrun-draft-settings.util wrunCarriedSettingsPatch). Only a finite number is a
2585
+ * run value the rule reads; a name no param holds is no param setting.
2586
+ */
2587
+ export async function loadWrunParamRefusalTest(params) {
2588
+ await wrunChartHostEnv().loadSharedHost();
2589
+ const byName = new Map(params.map((param) => [param.name, param]));
2590
+ return (name, value) => {
2591
+ const param = byName.get(name);
2592
+ return (param !== undefined &&
2593
+ typeof value === 'number' &&
2594
+ Number.isFinite(value) &&
2595
+ wrunParamRunValueRefusal(param, value) !== undefined);
2596
+ };
2597
+ }