@orangecharts/wrun-chart-host 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (362) hide show
  1. package/README.md +23 -6
  2. package/dist/constants/exchange-names.leaf.d.ts +8 -0
  3. package/dist/constants/exchange-names.leaf.js +101 -0
  4. package/dist/constants/kscript-data-interval-restrictions.constants.d.ts +15 -0
  5. package/dist/constants/kscript-data-interval-restrictions.constants.js +40 -0
  6. package/dist/constants/opra-compliance.constants.d.ts +19 -0
  7. package/dist/constants/opra-compliance.constants.js +19 -0
  8. package/dist/constants/replay-ladder.leaf.d.ts +30 -0
  9. package/dist/constants/replay-ladder.leaf.js +99 -0
  10. package/dist/constants/scriptEditor/builtin-script-snippets.d.ts +133 -0
  11. package/dist/constants/scriptEditor/builtin-script-snippets.js +451 -0
  12. package/dist/constants/scriptEditor/cme-official-scripts.constants.d.ts +168 -0
  13. package/dist/constants/scriptEditor/cme-official-scripts.constants.js +398 -0
  14. package/dist/constants/scriptEditor/converted-script-id.leaf.d.ts +8 -0
  15. package/dist/constants/scriptEditor/converted-script-id.leaf.js +10 -0
  16. package/dist/constants/scriptEditor/execution.constants.d.ts +4 -0
  17. package/dist/constants/scriptEditor/execution.constants.js +14 -0
  18. package/dist/constants/wrun-prefix-safe.constants.d.ts +23 -0
  19. package/dist/constants/wrun-prefix-safe.constants.js +26 -0
  20. package/dist/host-env.d.ts +321 -24
  21. package/dist/host-env.js +15 -0
  22. package/dist/host-ports.types.d.ts +857 -35
  23. package/dist/index.d.ts +149 -2
  24. package/dist/index.js +149 -2
  25. package/dist/instances/script-engine-worker-ohlcv-transfer.d.ts +31 -0
  26. package/dist/instances/script-engine-worker-ohlcv-transfer.js +164 -0
  27. package/dist/interfaces/market-event.interface.d.ts +231 -0
  28. package/dist/interfaces/market-event.interface.js +15 -0
  29. package/dist/interfaces/opra-realtime.interface.d.ts +70 -134
  30. package/dist/interfaces/opra-realtime.interface.js +34 -59
  31. package/dist/interfaces/replay.interface.d.ts +285 -0
  32. package/dist/interfaces/replay.interface.js +1 -0
  33. package/dist/kscript-data/controls/live-ohlcv-merge.util.d.ts +1 -0
  34. package/dist/kscript-data/controls/live-ohlcv-merge.util.js +93 -0
  35. package/dist/kscript-data/controls/live-trades-merge.util.d.ts +5 -1
  36. package/dist/kscript-data/controls/live-trades-merge.util.js +2 -2
  37. package/dist/market-data/billing.interface.d.ts +219 -0
  38. package/dist/market-data/billing.interface.js +58 -0
  39. package/dist/market-data/venue-governed.util.d.ts +2 -0
  40. package/dist/market-data/venue-governed.util.js +10 -0
  41. package/dist/market-data/venue.d.ts +122 -0
  42. package/dist/market-data/venue.js +1 -0
  43. package/dist/market-data/venues/index.d.ts +97 -0
  44. package/dist/market-data/venues/index.js +33 -0
  45. package/dist/market-data/venues/opra.contract.copy.json +35 -0
  46. package/dist/market-data/venues/opra.d.ts +70 -0
  47. package/dist/market-data/venues/opra.js +74 -0
  48. package/dist/replay/replayIndicatorRows.d.ts +31 -0
  49. package/dist/replay/replayIndicatorRows.js +117 -0
  50. package/dist/replay/replayLadder.d.ts +85 -0
  51. package/dist/replay/replayLadder.js +388 -0
  52. package/dist/utility/auth/server-clock.util.d.ts +81 -0
  53. package/dist/utility/auth/server-clock.util.js +238 -0
  54. package/dist/utility/chart/builtin-identity.util.d.ts +18 -0
  55. package/dist/utility/chart/builtin-identity.util.js +51 -0
  56. package/dist/utility/chart/cache-alignment.util.d.ts +454 -0
  57. package/dist/utility/chart/cache-alignment.util.js +926 -0
  58. package/dist/utility/chart/chart-data-fetch-generation.util.d.ts +15 -0
  59. package/dist/utility/chart/chart-data-fetch-generation.util.js +22 -0
  60. package/dist/utility/chart/chart-mount-epoch.util.d.ts +5 -0
  61. package/dist/utility/chart/chart-mount-epoch.util.js +29 -0
  62. package/dist/utility/chart/chart-time-domain.util.d.ts +12 -0
  63. package/dist/utility/chart/chart-time-domain.util.js +23 -0
  64. package/dist/utility/chart/color-customization.leaf.d.ts +10 -0
  65. package/dist/utility/chart/color-customization.leaf.js +16 -0
  66. package/dist/utility/chart/date-labelled-interval.leaf.d.ts +15 -0
  67. package/dist/utility/chart/date-labelled-interval.leaf.js +19 -0
  68. package/dist/utility/chart/footprint-tick-grid.util.d.ts +106 -0
  69. package/dist/utility/chart/footprint-tick-grid.util.js +167 -0
  70. package/dist/utility/chart/gesture-timing.leaf.d.ts +29 -0
  71. package/dist/utility/chart/gesture-timing.leaf.js +29 -0
  72. package/dist/utility/chart/governed-contract-coin.util.d.ts +22 -0
  73. package/dist/utility/chart/governed-contract-coin.util.js +39 -0
  74. package/dist/utility/chart/host-bar-placement.util.d.ts +107 -0
  75. package/dist/utility/chart/host-bar-placement.util.js +447 -0
  76. package/dist/utility/chart/index-host-tier.util.d.ts +31 -0
  77. package/dist/utility/chart/index-host-tier.util.js +118 -0
  78. package/dist/utility/chart/index-mode-admission.util.d.ts +34 -0
  79. package/dist/utility/chart/index-mode-admission.util.js +67 -0
  80. package/dist/utility/chart/indicator-error-message.util.d.ts +35 -0
  81. package/dist/utility/chart/indicator-error-message.util.js +44 -0
  82. package/dist/utility/chart/indicator-run-interval.util.d.ts +130 -0
  83. package/dist/utility/chart/indicator-run-interval.util.js +268 -0
  84. package/dist/utility/chart/kscript-apply-fingerprint.util.d.ts +65 -0
  85. package/dist/utility/chart/kscript-apply-fingerprint.util.js +357 -0
  86. package/dist/utility/chart/kscript-chart-flush.leaf.d.ts +22 -0
  87. package/dist/utility/chart/kscript-chart-flush.leaf.js +13 -0
  88. package/dist/utility/chart/kscript-data-interval-restriction.leaf.d.ts +6 -0
  89. package/dist/utility/chart/kscript-data-interval-restriction.leaf.js +27 -0
  90. package/dist/utility/chart/kscript-integration-decision.leaf.d.ts +89 -0
  91. package/dist/utility/chart/kscript-integration-decision.leaf.js +80 -0
  92. package/dist/utility/chart/kscript-live-coalesce.util.d.ts +76 -0
  93. package/dist/utility/chart/kscript-live-coalesce.util.js +156 -0
  94. package/dist/utility/chart/kscript-live-rest-pace.util.d.ts +34 -0
  95. package/dist/utility/chart/kscript-live-rest-pace.util.js +134 -0
  96. package/dist/utility/chart/kscript-live-source-identity.util.d.ts +98 -0
  97. package/dist/utility/chart/kscript-live-source-identity.util.js +121 -0
  98. package/dist/utility/chart/kscript-mounted-plot-set.leaf.d.ts +48 -0
  99. package/dist/utility/chart/kscript-mounted-plot-set.leaf.js +145 -0
  100. package/dist/utility/chart/kscript-perf-tracker.util.d.ts +243 -0
  101. package/dist/utility/chart/kscript-perf-tracker.util.js +522 -0
  102. package/dist/utility/chart/kscript-run-interval-projection.util.d.ts +43 -0
  103. package/dist/utility/chart/kscript-run-interval-projection.util.js +471 -0
  104. package/dist/utility/chart/kscript-run-result-equality.util.d.ts +38 -0
  105. package/dist/utility/chart/kscript-run-result-equality.util.js +89 -0
  106. package/dist/utility/chart/kscript-settings-revision.leaf.d.ts +2 -0
  107. package/dist/utility/chart/kscript-settings-revision.leaf.js +12 -0
  108. package/dist/utility/chart/kscript-source-degrade.leaf.d.ts +63 -0
  109. package/dist/utility/chart/kscript-source-degrade.leaf.js +68 -0
  110. package/dist/utility/chart/kscript-source-retention.util.d.ts +134 -0
  111. package/dist/utility/chart/kscript-source-retention.util.js +218 -0
  112. package/dist/utility/chart/kscript-standin-identity.leaf.d.ts +57 -0
  113. package/dist/utility/chart/kscript-standin-identity.leaf.js +61 -0
  114. package/dist/utility/chart/kscript-titancharts-preparation.util.d.ts +15 -0
  115. package/dist/utility/chart/kscript-titancharts-preparation.util.js +376 -0
  116. package/dist/utility/chart/kscript-titancharts-render-keys.constants.d.ts +9 -0
  117. package/dist/utility/chart/kscript-titancharts-render-keys.constants.js +130 -0
  118. package/dist/utility/chart/kscript-venue-policy.util.d.ts +217 -0
  119. package/dist/utility/chart/kscript-venue-policy.util.js +324 -0
  120. package/dist/utility/chart/live-cadence.util.d.ts +38 -0
  121. package/dist/utility/chart/live-cadence.util.js +37 -0
  122. package/dist/utility/chart/live-feed-series-match.leaf.d.ts +13 -0
  123. package/dist/utility/chart/live-feed-series-match.leaf.js +21 -0
  124. package/dist/utility/chart/local-engine-self-heal-backoff.util.d.ts +46 -0
  125. package/dist/utility/chart/local-engine-self-heal-backoff.util.js +46 -0
  126. package/dist/utility/chart/local-engine-uninit.leaf.d.ts +21 -0
  127. package/dist/utility/chart/local-engine-uninit.leaf.js +22 -0
  128. package/dist/utility/chart/local-kscript-source-revalidation.util.d.ts +62 -0
  129. package/dist/utility/chart/local-kscript-source-revalidation.util.js +123 -0
  130. package/dist/utility/chart/local-kscript-warmup-depth.util.d.ts +214 -0
  131. package/dist/utility/chart/local-kscript-warmup-depth.util.js +376 -0
  132. package/dist/utility/chart/local-technical-script-live-apply-coalescer.util.d.ts +85 -0
  133. package/dist/utility/chart/local-technical-script-live-apply-coalescer.util.js +197 -0
  134. package/dist/utility/chart/local-technical-script-range.leaf.d.ts +72 -0
  135. package/dist/utility/chart/local-technical-script-range.leaf.js +126 -0
  136. package/dist/utility/chart/mixed-mode.util.d.ts +167 -0
  137. package/dist/utility/chart/mixed-mode.util.js +139 -0
  138. package/dist/utility/chart/ohlcv-row-readiness.util.d.ts +36 -0
  139. package/dist/utility/chart/ohlcv-row-readiness.util.js +90 -0
  140. package/dist/utility/chart/opra-user-scripts-gate.util.d.ts +19 -0
  141. package/dist/utility/chart/opra-user-scripts-gate.util.js +32 -0
  142. package/dist/utility/chart/overlay-execution-guard-key.leaf.d.ts +8 -0
  143. package/dist/utility/chart/overlay-execution-guard-key.leaf.js +10 -0
  144. package/dist/utility/chart/price-precision.util.d.ts +40 -0
  145. package/dist/utility/chart/price-precision.util.js +70 -0
  146. package/dist/utility/chart/profile-block-size.util.d.ts +64 -0
  147. package/dist/utility/chart/profile-block-size.util.js +141 -0
  148. package/dist/utility/chart/protected-kscript-degenerate-rows.leaf.d.ts +11 -0
  149. package/dist/utility/chart/protected-kscript-degenerate-rows.leaf.js +29 -0
  150. package/dist/utility/chart/protected-kscript-empty-output.util.d.ts +28 -0
  151. package/dist/utility/chart/protected-kscript-empty-output.util.js +84 -0
  152. package/dist/utility/chart/run-interval-unservable.leaf.d.ts +9 -0
  153. package/dist/utility/chart/run-interval-unservable.leaf.js +20 -0
  154. package/dist/utility/chart/run-interval-warmup.leaf.d.ts +19 -0
  155. package/dist/utility/chart/run-interval-warmup.leaf.js +35 -0
  156. package/dist/utility/chart/titan-constants.pin.d.ts +9 -5
  157. package/dist/utility/chart/titan-constants.pin.js +18 -5
  158. package/dist/utility/chart/warmup-backfill-retry.leaf.d.ts +9 -0
  159. package/dist/utility/chart/warmup-backfill-retry.leaf.js +9 -0
  160. package/dist/utility/chart/window-geometry.leaf.d.ts +119 -0
  161. package/dist/utility/chart/window-geometry.leaf.js +391 -0
  162. package/dist/utility/chart/window-owner.leaf.d.ts +19 -0
  163. package/dist/utility/chart/window-owner.leaf.js +24 -0
  164. package/dist/utility/chart/wrun-bar-session-facts.util.d.ts +11 -2
  165. package/dist/utility/chart/wrun-bar-session-facts.util.js +10 -3
  166. package/dist/utility/chart/wrun-run-result.util.d.ts +5 -1
  167. package/dist/utility/chart/wrun-run-result.util.js +20 -14
  168. package/dist/utility/common/data-processing.util.d.ts +138 -0
  169. package/dist/utility/common/data-processing.util.js +346 -0
  170. package/dist/utility/common/visible-timeout.util.d.ts +13 -4
  171. package/dist/utility/common/visible-timeout.util.js +23 -8
  172. package/dist/utility/exchange-format.leaf.d.ts +1 -0
  173. package/dist/utility/exchange-format.leaf.js +47 -0
  174. package/dist/utility/html-escape.leaf.d.ts +11 -0
  175. package/dist/utility/html-escape.leaf.js +20 -0
  176. package/dist/utility/market-events/earnings-scope.util.d.ts +60 -0
  177. package/dist/utility/market-events/earnings-scope.util.js +92 -0
  178. package/dist/utility/market-events/market-events.util.d.ts +147 -0
  179. package/dist/utility/market-events/market-events.util.js +392 -0
  180. package/dist/utility/market-events/zoned-clock.util.d.ts +1 -0
  181. package/dist/utility/market-events/zoned-clock.util.js +11 -0
  182. package/dist/utility/options/option-venue-disclosure.util.d.ts +43 -0
  183. package/dist/utility/options/option-venue-disclosure.util.js +56 -0
  184. package/dist/utility/scriptEditor/package-semver.util.d.ts +51 -0
  185. package/dist/utility/scriptEditor/package-semver.util.js +120 -0
  186. package/dist/utility/scriptEditor/temp-script-id.util.d.ts +18 -0
  187. package/dist/utility/scriptEditor/temp-script-id.util.js +25 -0
  188. package/dist/utility/symbol-selection/markets-request-from-symbols.leaf.d.ts +20 -0
  189. package/dist/utility/symbol-selection/markets-request-from-symbols.leaf.js +81 -0
  190. package/dist/utility/v2/governed-tier.leaf.d.ts +103 -0
  191. package/dist/utility/v2/governed-tier.leaf.js +113 -0
  192. package/dist/utility/watchlist/import/import-request.leaf.d.ts +10 -0
  193. package/dist/utility/watchlist/import/import-request.leaf.js +10 -0
  194. package/dist/utility/wrun/sources/lanes/option_daily.d.ts +43 -15
  195. package/dist/utility/wrun/sources/lanes/option_daily.js +78 -20
  196. package/dist/utility/wrun/sources/lanes/option_stats_10m.d.ts +14 -10
  197. package/dist/utility/wrun/sources/lanes/option_stats_10m.js +5 -4
  198. package/dist/utility/wrun/sources/lanes/series.js +2 -2
  199. package/dist/utility/wrun/sources/opra-option-lanes.util.d.ts +22 -3
  200. package/dist/utility/wrun/sources/opra-option-lanes.util.js +38 -7
  201. package/dist/utility/wrun/sources/registry.js +31 -1
  202. package/dist/utility/wrun/sources/row-lane-registry.js +5 -5
  203. package/dist/utility/wrun/sources/row-lanes/option_contract_state.d.ts +49 -0
  204. package/dist/utility/wrun/sources/row-lanes/option_contract_state.js +75 -20
  205. package/dist/utility/wrun/sources/row-lanes/option_strikes.d.ts +49 -0
  206. package/dist/utility/wrun/sources/row-lanes/option_strikes.js +57 -47
  207. package/dist/utility/wrun/sources/row-lanes/option_surface.d.ts +36 -4
  208. package/dist/utility/wrun/sources/row-lanes/option_surface.js +6 -12
  209. package/dist/utility/wrun/sources/wrun-poll-lane.types.d.ts +37 -3
  210. package/dist/utility/wrun/sources/wrun-poll-lanes.util.d.ts +128 -2
  211. package/dist/utility/wrun/sources/wrun-poll-lanes.util.js +233 -51
  212. package/dist/utility/wrun/sources/wrun-row-lane.types.d.ts +0 -8
  213. package/dist/utility/wrun/sources/wrun-row-lanes.util.d.ts +26 -24
  214. package/dist/utility/wrun/sources/wrun-row-lanes.util.js +85 -104
  215. package/dist/utility/wrun/wrun-alert-outputs.registry.d.ts +166 -0
  216. package/dist/utility/wrun/wrun-alert-outputs.registry.js +219 -0
  217. package/dist/utility/wrun/wrun-bar-count.util.d.ts +83 -0
  218. package/dist/utility/wrun/wrun-bar-count.util.js +259 -0
  219. package/dist/utility/wrun/wrun-chart-context-names.util.d.ts +84 -0
  220. package/dist/utility/wrun/wrun-chart-context-names.util.js +186 -0
  221. package/dist/utility/wrun/wrun-chart-market-facts.util.d.ts +253 -0
  222. package/dist/utility/wrun/wrun-chart-market-facts.util.js +731 -0
  223. package/dist/utility/wrun/wrun-cloud-opra-stamp.util.d.ts +28 -0
  224. package/dist/utility/wrun/wrun-cloud-opra-stamp.util.js +45 -0
  225. package/dist/utility/wrun/wrun-coin-lane-live.util.d.ts +18 -0
  226. package/dist/utility/wrun/wrun-coin-lane-live.util.js +47 -0
  227. package/dist/utility/wrun/wrun-deadline.util.js +2 -1
  228. package/dist/utility/wrun/wrun-debug-output.util.d.ts +39 -0
  229. package/dist/utility/wrun/wrun-debug-output.util.js +63 -0
  230. package/dist/utility/wrun/wrun-declared-warmup.util.d.ts +113 -0
  231. package/dist/utility/wrun/wrun-declared-warmup.util.js +181 -0
  232. package/dist/utility/wrun/wrun-draft-legend-note.util.d.ts +43 -0
  233. package/dist/utility/wrun/wrun-draft-legend-note.util.js +158 -0
  234. package/dist/utility/wrun/wrun-draft-overlay.util.d.ts +181 -0
  235. package/dist/utility/wrun/wrun-draft-overlay.util.js +357 -0
  236. package/dist/utility/wrun/wrun-draw-skipped.leaf.d.ts +16 -0
  237. package/dist/utility/wrun/wrun-draw-skipped.leaf.js +16 -0
  238. package/dist/utility/wrun/wrun-earnings-facts.util.d.ts +42 -0
  239. package/dist/utility/wrun/wrun-earnings-facts.util.js +131 -0
  240. package/dist/utility/wrun/wrun-first-run-depth.util.d.ts +32 -0
  241. package/dist/utility/wrun/wrun-first-run-depth.util.js +118 -0
  242. package/dist/utility/wrun/wrun-gate-plane-readers.util.d.ts +24 -0
  243. package/dist/utility/wrun/wrun-gate-plane-readers.util.js +31 -0
  244. package/dist/utility/wrun/wrun-held-lanes.util.d.ts +32 -0
  245. package/dist/utility/wrun/wrun-held-lanes.util.js +94 -0
  246. package/dist/utility/wrun/wrun-host-visible-clock.util.d.ts +2 -0
  247. package/dist/utility/wrun/wrun-host-visible-clock.util.js +17 -0
  248. package/dist/utility/wrun/wrun-host.service.d.ts +266 -0
  249. package/dist/utility/wrun/wrun-host.service.js +655 -0
  250. package/dist/utility/wrun/wrun-inert-legend.util.d.ts +33 -0
  251. package/dist/utility/wrun/wrun-inert-legend.util.js +125 -0
  252. package/dist/utility/wrun/wrun-input-requirements.leaf.d.ts +155 -0
  253. package/dist/utility/wrun/wrun-input-requirements.leaf.js +450 -0
  254. package/dist/utility/wrun/wrun-integration-route.util.d.ts +51 -0
  255. package/dist/utility/wrun/wrun-integration-route.util.js +59 -0
  256. package/dist/utility/wrun/wrun-latest-history.leaf.d.ts +8 -0
  257. package/dist/utility/wrun/wrun-latest-history.leaf.js +8 -0
  258. package/dist/utility/wrun/wrun-legend-hover.lazy.d.ts +12 -0
  259. package/dist/utility/wrun/wrun-legend-hover.lazy.js +96 -0
  260. package/dist/utility/wrun/wrun-lifecycle-runtime.util.d.ts +21 -0
  261. package/dist/utility/wrun/wrun-lifecycle-runtime.util.js +21 -0
  262. package/dist/utility/wrun/wrun-live-hidden-hold.util.d.ts +23 -0
  263. package/dist/utility/wrun/wrun-live-hidden-hold.util.js +13 -0
  264. package/dist/utility/wrun/wrun-live-intake.util.d.ts +374 -0
  265. package/dist/utility/wrun/wrun-live-intake.util.js +2027 -0
  266. package/dist/utility/wrun/wrun-live-patch.util.d.ts +116 -0
  267. package/dist/utility/wrun/wrun-live-patch.util.js +523 -0
  268. package/dist/utility/wrun/wrun-live-tick.util.d.ts +619 -0
  269. package/dist/utility/wrun/wrun-live-tick.util.js +4974 -0
  270. package/dist/utility/wrun/wrun-loading-owner.util.d.ts +58 -0
  271. package/dist/utility/wrun/wrun-loading-owner.util.js +89 -0
  272. package/dist/utility/wrun/wrun-official-scope.leaf.d.ts +29 -0
  273. package/dist/utility/wrun/wrun-official-scope.leaf.js +36 -0
  274. package/dist/utility/wrun/wrun-oi-lane.util.d.ts +27 -0
  275. package/dist/utility/wrun/wrun-oi-lane.util.js +42 -0
  276. package/dist/utility/wrun/wrun-opra-stats.leaf.d.ts +29 -10
  277. package/dist/utility/wrun/wrun-opra-stats.leaf.js +29 -10
  278. package/dist/utility/wrun/wrun-options-stop.util.d.ts +52 -0
  279. package/dist/utility/wrun/wrun-options-stop.util.js +123 -0
  280. package/dist/utility/wrun/wrun-overlay-drivers.util.d.ts +719 -0
  281. package/dist/utility/wrun/wrun-overlay-drivers.util.js +1180 -0
  282. package/dist/utility/wrun/wrun-overlay-lifecycle.lazy.d.ts +50 -0
  283. package/dist/utility/wrun/wrun-overlay-lifecycle.lazy.js +131 -0
  284. package/dist/utility/wrun/wrun-overlay-lifecycle.util.d.ts +118 -0
  285. package/dist/utility/wrun/wrun-overlay-lifecycle.util.js +466 -0
  286. package/dist/utility/wrun/wrun-overlay-metadata.util.d.ts +45 -0
  287. package/dist/utility/wrun/wrun-overlay-metadata.util.js +112 -0
  288. package/dist/utility/wrun/wrun-overlay-recovery.util.d.ts +114 -0
  289. package/dist/utility/wrun/wrun-overlay-recovery.util.js +971 -0
  290. package/dist/utility/wrun/wrun-overlay-run.util.d.ts +858 -0
  291. package/dist/utility/wrun/wrun-overlay-run.util.js +11013 -0
  292. package/dist/utility/wrun/wrun-panel-mount.lazy.d.ts +10 -0
  293. package/dist/utility/wrun/wrun-panel-mount.lazy.js +68 -0
  294. package/dist/utility/wrun/wrun-panel-mount.util.d.ts +392 -0
  295. package/dist/utility/wrun/wrun-panel-mount.util.js +2346 -0
  296. package/dist/utility/wrun/wrun-param-map.util.d.ts +19 -4
  297. package/dist/utility/wrun/wrun-param-map.util.js +40 -47
  298. package/dist/utility/wrun/wrun-param-values.util.d.ts +9 -3
  299. package/dist/utility/wrun/wrun-param-values.util.js +5 -5
  300. package/dist/utility/wrun/wrun-pause-dim.util.d.ts +52 -0
  301. package/dist/utility/wrun/wrun-pause-dim.util.js +153 -0
  302. package/dist/utility/wrun/wrun-plot-gate.types.d.ts +23 -0
  303. package/dist/utility/wrun/wrun-plot-gate.types.js +7 -0
  304. package/dist/utility/wrun/wrun-prefix-cohort.util.d.ts +93 -0
  305. package/dist/utility/wrun/wrun-prefix-cohort.util.js +484 -0
  306. package/dist/utility/wrun/wrun-prefix-lanes.util.d.ts +114 -0
  307. package/dist/utility/wrun/wrun-prefix-lanes.util.js +486 -0
  308. package/dist/utility/wrun/wrun-prefix-proof.util.d.ts +317 -0
  309. package/dist/utility/wrun/wrun-prefix-proof.util.js +630 -0
  310. package/dist/utility/wrun/wrun-refusal-surface.util.d.ts +73 -0
  311. package/dist/utility/wrun/wrun-refusal-surface.util.js +380 -0
  312. package/dist/utility/wrun/wrun-refusal-text.util.d.ts +15 -0
  313. package/dist/utility/wrun/wrun-refusal-text.util.js +40 -0
  314. package/dist/utility/wrun/wrun-replay-lane.util.d.ts +139 -0
  315. package/dist/utility/wrun/wrun-replay-lane.util.js +520 -0
  316. package/dist/utility/wrun/wrun-replay-rows.util.d.ts +21 -0
  317. package/dist/utility/wrun/wrun-replay-rows.util.js +172 -0
  318. package/dist/utility/wrun/wrun-row-source-factory.d.ts +53 -0
  319. package/dist/utility/wrun/wrun-row-source-factory.js +435 -0
  320. package/dist/utility/wrun/wrun-run-cells.util.d.ts +36 -0
  321. package/dist/utility/wrun/wrun-run-cells.util.js +46 -0
  322. package/dist/utility/wrun/wrun-run-interval-projection.types.d.ts +14 -0
  323. package/dist/utility/wrun/wrun-run-interval-projection.types.js +1 -0
  324. package/dist/utility/wrun/wrun-run-interval-session.util.d.ts +133 -0
  325. package/dist/utility/wrun/wrun-run-interval-session.util.js +121 -0
  326. package/dist/utility/wrun/wrun-run-interval.util.d.ts +98 -0
  327. package/dist/utility/wrun/wrun-run-interval.util.js +207 -0
  328. package/dist/utility/wrun/wrun-run-retained.util.d.ts +122 -0
  329. package/dist/utility/wrun/wrun-run-retained.util.js +255 -0
  330. package/dist/utility/wrun/wrun-sandbox-row-source.d.ts +184 -0
  331. package/dist/utility/wrun/wrun-sandbox-row-source.js +444 -0
  332. package/dist/utility/wrun/wrun-script-inputs.util.js +4 -4
  333. package/dist/utility/wrun/wrun-series-stream.util.d.ts +86 -0
  334. package/dist/utility/wrun/wrun-series-stream.util.js +537 -0
  335. package/dist/utility/wrun/wrun-sheet-remembered.util.d.ts +21 -0
  336. package/dist/utility/wrun/wrun-sheet-remembered.util.js +36 -0
  337. package/dist/utility/wrun/wrun-signal-sound-reasons.leaf.d.ts +7 -0
  338. package/dist/utility/wrun/wrun-signal-sound-reasons.leaf.js +12 -0
  339. package/dist/utility/wrun/wrun-socket-row-source.js +4 -2
  340. package/dist/utility/wrun/wrun-source-rows.util.d.ts +175 -3
  341. package/dist/utility/wrun/wrun-source-rows.util.js +294 -8
  342. package/dist/utility/wrun/wrun-stats-strip.util.d.ts +46 -0
  343. package/dist/utility/wrun/wrun-stats-strip.util.js +87 -0
  344. package/dist/utility/wrun/wrun-table-chrome.util.d.ts +163 -0
  345. package/dist/utility/wrun/wrun-table-chrome.util.js +557 -0
  346. package/dist/utility/wrun/wrun-text-params.util.d.ts +11 -6
  347. package/dist/utility/wrun/wrun-text-params.util.js +19 -30
  348. package/dist/utility/wrun/wrun-transient-rerun.util.d.ts +64 -0
  349. package/dist/utility/wrun/wrun-transient-rerun.util.js +317 -0
  350. package/dist/utility/wrun/wrun-twin-lookback.util.d.ts +10 -0
  351. package/dist/utility/wrun/wrun-twin-lookback.util.js +43 -0
  352. package/dist/utility/wrun/wrun-warmup-head-store.util.d.ts +41 -0
  353. package/dist/utility/wrun/wrun-warmup-head-store.util.js +120 -0
  354. package/dist/utility/wrun-alert-params.leaf.d.ts +24 -0
  355. package/dist/utility/wrun-alert-params.leaf.js +24 -0
  356. package/dist/utils/replay/replay-buffer-math.d.ts +148 -0
  357. package/dist/utils/replay/replay-buffer-math.js +684 -0
  358. package/dist/workers/wrun/wrun-abi-host.d.ts +190 -0
  359. package/dist/workers/wrun/wrun-abi-host.js +1201 -0
  360. package/dist/workers/wrun/wrun-engine-handler.d.ts +37 -0
  361. package/dist/workers/wrun/wrun-engine-handler.js +211 -0
  362. package/package.json +3 -3
@@ -0,0 +1,1201 @@
1
+ /**
2
+ * The WRUN ABI executor: instantiates a `wrun-indicator` wasm module with the
3
+ * version-specific import object (wrun-1 scalar channel; wrun-2 adds the cell
4
+ * and string channels; wrun-3 adds the handle-keyed draw channel and the
5
+ * last-bar signal; wrun-4 adds run-level frame snapshots) and drives it bar
6
+ * by bar over a packed request.
7
+ *
8
+ * This is a faithful browser port of the om daemon's worker host
9
+ * (openmarket packages/cli/src/runner/wrun/runtime-worker.js), kept
10
+ * environment-agnostic on purpose: it runs inside `wrun-engine.worker.ts` in
11
+ * the app and directly under Node in the ABI drive specs, so the same
12
+ * behavior is what both the tests and the chart exercise.
13
+ *
14
+ * Contract highlights (docs/WRUN2_ABI.md and docs/WRUN3_ABI.md in the
15
+ * openmarket repo):
16
+ * - Four exports: init/state/finalize/reset; positional argument blocks
17
+ * served through `wrun.wrun_arg_*`; outputs through `wrun_output_f64` +
18
+ * `wrun_result_write`.
19
+ * - Cell channel (`wrun_arg_len`/`wrun_arg_bytes`) is state-phase only,
20
+ * wrun-2 and later, and copies IEEE 754 f64 cells into exported memory.
21
+ * - String channel (`wrun_output_str`) is finalize-phase only, wrun-2 and
22
+ * later, declared slots only, fatal UTF-8 validation, caps checked before
23
+ * any copy, never truncated.
24
+ * - Frame channel (`wrun_output_frame`, wrun-4 and later): finalize-phase
25
+ * only, declared slots only, fatal UTF-8 validation. A later write replaces
26
+ * the slot for the run, sharing the string channel's render-result cap.
27
+ * - Text channel (`wrun_param_len` / `wrun_param_bytes`, wrun-5 and later,
28
+ * docs/WRUN5_ABI.md): init-phase only, the cell channel's shape on params.
29
+ * The host holds every typed text setting's plain UTF-8 bytes by init slot
30
+ * (`textParams`); a slot without one answers -1 on both imports (the
31
+ * generated reader reads the declared default), an empty value answers 0
32
+ * (the reader reads ""), and the copy into
33
+ * exported memory is bounds-checked. Refusals by name:
34
+ * `wrun_text_param_phase` outside init(), `wrun_text_param_memory` for a
35
+ * copy outside the module's memory. An older ABI refuses the two imports
36
+ * by name before anything links.
37
+ * - Row count (`wrun_bar_count`, wrun-6 and later, docs/WRUN6_ABI.md): the
38
+ * bars the run holds while the row is evaluated, the forming bar included,
39
+ * callable in state() and finalize() (`wrun_bar_count_phase` otherwise).
40
+ * Every row of a block reads the bars the session holds once the block is
41
+ * in: a full run's row count, a live seed's, and on a same-bar revision the
42
+ * count already held. A NEW bar would make every held bar's count stale, so
43
+ * the session never extends a module that reads it: the main thread reopens
44
+ * it over every bar (the engine's re-seed), and a block that would extend it
45
+ * refuses by name. An older ABI refuses the import by name before anything
46
+ * links.
47
+ * - Draw channel (`wrun_draw_*`, wrun-3 and later): finalize-phase only, every
48
+ * call one op against the session's handle ledger
49
+ * (`utility/wrun/wrun-handles.util.ts`); caps and refusals by name.
50
+ * `wrun_bar_last` (state and finalize) answers 1 on the newest bar the
51
+ * request holds.
52
+ * - Strategy channel (`wrun_strategy_*`, wrun-3 and later, contract
53
+ * OM-WRUN3-STRATEGIES-CONTRACT sections 2 and 5): a package whose sheet
54
+ * declares `strategy` runs the engine's own broker beside the guest
55
+ * (the shared host package's broker, read through the realm's chart-host env, `sharedHost()`, and
56
+ * driven by its `WrunStrategyHost`). Per row, `broker.beginBar` runs BEFORE the guest's
57
+ * state() (fills for orders queued on earlier rows, equity marked at the
58
+ * close), the getters read the post-fill position during state() and
59
+ * finalize(), and the intents queue during finalize() with createdBar =
60
+ * the row. A full run confirms every bar, the newest included (the
61
+ * engine's own full-run rule); on the live lane the newest bar the
62
+ * request holds (the forming bar) runs on a structured clone of the
63
+ * committed broker (no fills, intents rejected and counted), a same-bar
64
+ * replay re-clones, and a bar close folds the closed bar into the
65
+ * committed broker (the close-confirm) before the new forming bar, so a
66
+ * live session equals a full run over its closed bars plus the forming
67
+ * bar's mark. The OHLC feed rides the block (`strategyBars`, the
68
+ * primary lane's own candles); the wire is the engine's StrategyOutput.
69
+ * A module importing a strategy import with no `strategy` sheet refuses
70
+ * at instantiation by name (`wrun_strategy_not_declared`).
71
+ * - No memory growth after init(); the 4 MiB memory ceiling holds throughout.
72
+ * - Live mode replays a revised forming bar by snapshot/restore of linear
73
+ * memory plus the exported `__wrun_g*` globals AND the ledger journal; a
74
+ * live block that opens past the forming bar close-confirms it first
75
+ * (re-evaluates it as a closed bar), so a live session's ledger equals a
76
+ * full run's.
77
+ *
78
+ * Two entry points share one executor:
79
+ * - `runWrunPackedRequest` drives a whole request against a fresh instance
80
+ * (the historical mount/pan compute pass), exactly as before.
81
+ * - `createWrunAbiSession` keeps the instantiated guest ALIVE between calls
82
+ * so a live forming-bar tick feeds only the new/revised rows: the session
83
+ * carries the guest's memory, the forming-bar snapshot, the ledger, and
84
+ * the string accounting and frame slots across calls, and history is
85
+ * never re-executed per tick.
86
+ */
87
+ import { wrunChartHostEnv } from '../../host-env.js';
88
+ import { abiAtLeast, WrunLiveOrderError, } from '../../interfaces/wrun-runtime.interface.js';
89
+ import { WRUN3_DRAW_REFUSALS, WrunDrawRefusalError, WrunHandleLedger, } from '../../utility/wrun/wrun-handles.util.js';
90
+ import { WRUN_RENDER_RESULT_LIMIT_BYTES } from '../../utility/wrun/wrun-render-select.util.js';
91
+ import { WRUN5_TEXT_IMPORTS, WRUN5_TEXT_REFUSALS, wrunPlainText } from '../../utility/wrun/wrun-text-params.util.js';
92
+ import { WRUN6_BAR_REFUSALS, wrunModuleImportsBarCount } from '../../utility/wrun/wrun-bar-count.util.js';
93
+ import { WRUN_MEMORY_LIMIT_BYTES } from '../../utility/wrun/wrun-memory-clamp.util.js';
94
+ import { wrunRunCellsRefusal } from '../../utility/wrun/wrun-run-cells.util.js';
95
+ const WRUN_GLOBAL_PREFIX = '__wrun_g';
96
+ /** `strategyBars` stride: open, high, low, close per row. */
97
+ const STRATEGY_BAR_STRIDE = 4;
98
+ const STRATEGY_IMPORT_PREFIX = 'wrun_strategy_';
99
+ /** The memory ceiling: the clamp's own limit, which compileModule also stamps on every module
100
+ * as its memory maximum (wrun-memory-clamp.util), so the two can never drift. */
101
+ const WRUN_DEFAULT_MEMORY_LIMIT_BYTES = WRUN_MEMORY_LIMIT_BYTES;
102
+ const BYTES_PER_CELL = 8;
103
+ const BYTES_PER_POINT = 16;
104
+ const EMPTY_ARGS = [];
105
+ const EMPTY_SLOT_CAPS = new Int32Array(0);
106
+ const EMPTY_TEXT_PARAMS = {};
107
+ /** The text channel's import names without their `wrun:` module prefix. */
108
+ const TEXT_IMPORT_NAMES = new Set(WRUN5_TEXT_IMPORTS.map((key) => key.slice('wrun:'.length)));
109
+ // Fatal on purpose: wrun_output_str carries UTF-8 text only, validated at
110
+ // write time so an invalid byte refuses HERE by name instead of surfacing as
111
+ // replacement characters wherever the string is finally rendered.
112
+ const UTF8_FATAL = new TextDecoder('utf-8', { fatal: true });
113
+ const UTF8_ENCODER = new TextEncoder();
114
+ /** The string-slot bytes a module wrote, with the plain-text rule applied
115
+ * (newlines kept): the bytes themselves when nothing was stripped, else the
116
+ * clean text re-encoded (never longer than the write the caps admitted). */
117
+ function plainSlotBytes(bytes, text) {
118
+ const plain = wrunPlainText(text, { multiline: true });
119
+ return plain === text ? bytes : UTF8_ENCODER.encode(plain);
120
+ }
121
+ /** The row stamps restart past this value, so a stamp always stays a small
122
+ * integer (V8's Smi range); a session reaches it after a billion rows. */
123
+ const MAX_ROW_STAMP = 0x3fff_ffff;
124
+ /** The typed pre-evaluation ordering refusal lives with the wire types (the
125
+ * main-thread host rejects the coded response with the same class); kept
126
+ * exported here for the worker and the ABI drive specs. */
127
+ export { WrunLiveOrderError };
128
+ const now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now());
129
+ /** A wrun-3 module whose sheet declares no `strategy` section must import
130
+ * no strategy import: refused at instantiation by name, the same rule as a
131
+ * draw call for a kind absent from `handles`, before anything links. */
132
+ function refuseUndeclaredStrategyImports(module) {
133
+ const names = WebAssembly.Module.imports(module)
134
+ .filter((entry) => entry.module === 'wrun' && entry.name.startsWith(STRATEGY_IMPORT_PREFIX))
135
+ .map((entry) => entry.name);
136
+ if (names.length === 0)
137
+ return;
138
+ const { WrunStrategyRefusalError } = wrunChartHostEnv().sharedHost();
139
+ throw new WrunStrategyRefusalError('wrun_strategy_not_declared', `${names.join(', ')}: this package declares no strategy section`, `declare metadata strategy (an empty object enables the channel with the engine's defaults) under abi_version "wrun-3"`);
140
+ }
141
+ /** One row's OHLC out of the block's broker feed; a strategy package's
142
+ * block without one is a host bug, refused loudly rather than run as a
143
+ * NaN bar (which the broker would count as rejections). */
144
+ function strategyBarOf(block, row) {
145
+ const bars = block.strategyBars;
146
+ const at = row * STRATEGY_BAR_STRIDE;
147
+ if (bars === undefined || bars.length < at + STRATEGY_BAR_STRIDE) {
148
+ throw new Error(`WRUN strategy feed missing for row ${row}: a strategy package's rows block carries strategyBars ` +
149
+ `(open, high, low, close per row, the primary lane's own candles)`);
150
+ }
151
+ return { open: bars[at], high: bars[at + 1], low: bars[at + 2], close: bars[at + 3] };
152
+ }
153
+ export async function createWrunAbiSession(config) {
154
+ // The runtime caps are the kit's (om's one caps table, WRUN_CAPS), restated in the shared host's
155
+ // WRUN_HOST_ABI_TABLES and read here, as the session opens, through the realm's chart-host env (never at module
156
+ // load; both entries, `runWrunPackedRequest` and the worker's live start, open a session); never a number typed
157
+ // here, so a kit bump that moves a cap moves the executor with it. wrun-abi-host.kit-mirror.spec.ts holds each to
158
+ // its WRUN_CAPS row (docs/features/kscript/wrun/wrun-limits.md).
159
+ // The string caps are host-enforced per write with checked arithmetic BEFORE any
160
+ // allocation: per-slot max_bytes rides the request (schema-capped at 4096),
161
+ // these bound a row and a run, om's runtime-worker caps: every ABI keeps the
162
+ // string-only run limit, and wrun-4 shares one transport budget across its
163
+ // retained frames and row strings (WRUN_CAPS.frame_run_bytes).
164
+ // A live SESSION is one run for the caps:
165
+ // the total accumulates across its ticks, so a slot-writing package cannot
166
+ // stream unbounded text through an immortal session.
167
+ const sharedHost = wrunChartHostEnv().sharedHost();
168
+ const {
169
+ // Declared outputs one row may write (WRUN_CAPS.output_slots).
170
+ maxOutputWrites: MAX_OUTPUT_WRITES, stringRowLimitBytes: STRING_ROW_LIMIT_BYTES, stringRunLimitBytes: STRING_RUN_LIMIT_BYTES, frameRunLimitBytes: FRAME_RUN_LIMIT_BYTES, maxFrames: MAX_FRAME_SLOTS, } = sharedHost.WRUN_HOST_ABI_TABLES;
171
+ const memoryLimit = config.memoryLimitBytes ?? WRUN_DEFAULT_MEMORY_LIMIT_BYTES;
172
+ const outputCount = config.outputCount;
173
+ const stringMaxBytes = config.stringMaxBytes ?? EMPTY_SLOT_CAPS;
174
+ const stringSlotCount = stringMaxBytes.length;
175
+ const frameMaxBytes = config.frameMaxBytes ?? EMPTY_SLOT_CAPS;
176
+ const frameSlotCount = frameMaxBytes.length;
177
+ // wrun-4 shares one transport budget across frames and row strings
178
+ // (FRAME_RUN_LIMIT_BYTES); earlier ABIs keep the string-only run limit.
179
+ const wrun4 = abiAtLeast(config.abi, 'wrun-4');
180
+ // Frames can own every visual in a wrun-4 program, so that program has
181
+ // no numeric output columns. Earlier ABIs still require a numeric output.
182
+ const frameOnly = wrun4 && frameSlotCount > 0 && outputCount === 0;
183
+ if (!Number.isInteger(outputCount) || (outputCount < 1 && !frameOnly)) {
184
+ throw new Error('WRUN output count must be a positive integer');
185
+ }
186
+ if (frameSlotCount > MAX_FRAME_SLOTS) {
187
+ throw new Error(`WRUN frames declares ${frameSlotCount} slots; the maximum is ${MAX_FRAME_SLOTS}`);
188
+ }
189
+ if (!abiAtLeast(config.abi, 'wrun-4')) {
190
+ const importsFrame = WebAssembly.Module.imports(config.module).some((entry) => entry.module === 'wrun' && entry.name === 'wrun_output_frame');
191
+ if (importsFrame) {
192
+ throw new Error(`WRUN wrun_output_frame requires abi_version "wrun-4" or later (declared "${config.abi}")`);
193
+ }
194
+ }
195
+ // Every older ABI refuses the text channel by name (docs/WRUN5_ABI.md): a
196
+ // module compiled from a param.text declaration never links under a host
197
+ // or a sheet that has not reached wrun-5.
198
+ if (!abiAtLeast(config.abi, 'wrun-5')) {
199
+ const textImports = WebAssembly.Module.imports(config.module)
200
+ .filter((entry) => entry.module === 'wrun' && TEXT_IMPORT_NAMES.has(entry.name))
201
+ .map((entry) => entry.name);
202
+ if (textImports.length > 0) {
203
+ throw new Error(`WRUN ${textImports.join(', ')}: the text channel requires abi_version "wrun-5" or later ` +
204
+ `(declared "${config.abi}"); a param.text declaration derives it`);
205
+ }
206
+ }
207
+ // The row count is wrun-6's (docs/WRUN6_ABI.md): an older ABI refuses the
208
+ // import by name before anything links, the om hosts' way-in hint.
209
+ const importsBarCount = wrunModuleImportsBarCount(config.module);
210
+ if (importsBarCount && !abiAtLeast(config.abi, 'wrun-6')) {
211
+ throw new Error(`WRUN wrun_bar_count: the row count requires abi_version "wrun-6" or later ` +
212
+ `(declared "${config.abi}"); a bar.count() call derives it`);
213
+ }
214
+ const readsBarCount = importsBarCount && abiAtLeast(config.abi, 'wrun-6');
215
+ // A write at or past MAX_OUTPUT_WRITES refuses, so no output beyond it is
216
+ // ever tracked (a larger declared count fails validation on its first row).
217
+ const trackedOutputs = Math.min(outputCount, MAX_OUTPUT_WRITES);
218
+ // Guest-call context. `phase` sequences the request: "instantiate" (module
219
+ // compile + start section) -> "init" -> per row "state" then "finalize" ->
220
+ // "idle" between calls. The cell imports are legal during "state" only and
221
+ // the string import during "finalize" only; each names the offending phase
222
+ // otherwise, so a start-section or init-time call fails safely by name.
223
+ // `packedRow` >= 0 means the argument block is that row of the CURRENT
224
+ // packed rows block; -1 means `args` (init params, or empty for finalize).
225
+ const host = {
226
+ phase: 'instantiate',
227
+ args: EMPTY_ARGS,
228
+ packedRow: -1,
229
+ outputs: new Float64Array(trackedOutputs),
230
+ writtenAt: new Uint32Array(trackedOutputs),
231
+ rowStamp: 0,
232
+ writtenCount: 0,
233
+ count: 0,
234
+ ready: false,
235
+ stringWrites: new Array(stringSlotCount).fill(null),
236
+ rowStringBytes: 0,
237
+ rowIndex: 0,
238
+ barLast: 0,
239
+ barCount: 0,
240
+ };
241
+ // The rows block the import closures currently serve from. Reassigned per
242
+ // runRows call; the phase guards make any host import call outside a
243
+ // running block fail by name before this is read.
244
+ let current = null;
245
+ // Input index -> column in the current block's cell tables (cellLens/
246
+ // cellOffsets are row-major over these columns, in cellIndexes order).
247
+ let cellColumns = new Map();
248
+ let cellColumnCount = 0;
249
+ // The instance is assigned only after WebAssembly.instantiate resolves; a
250
+ // start-section call into the cell channel therefore CANNOT reach exported
251
+ // memory (the phase guard fires first, and this ref is still null).
252
+ const instanceRef = { exports: null };
253
+ const floatArg = (index) => {
254
+ if (host.packedRow >= 0 && current) {
255
+ // Absent-slot semantics stay bit-identical to the object transport: a
256
+ // slot at or beyond the row's ORIGINAL argument count is absent (NaN
257
+ // here, 0 through the int accessors), even though the packed stride is
258
+ // padded to the widest row.
259
+ if (!Number.isInteger(index) || index < 0 || index >= current.argCounts[host.packedRow]) {
260
+ return Number.NaN;
261
+ }
262
+ return current.values[host.packedRow * current.stride + index];
263
+ }
264
+ const value = host.args[index];
265
+ return value === undefined ? Number.NaN : value;
266
+ };
267
+ const intArg = (index) => {
268
+ const value = floatArg(index);
269
+ return Number.isFinite(value) ? Math.trunc(value) : 0;
270
+ };
271
+ const requireCellColumn = (name, index) => {
272
+ if (host.phase !== 'state') {
273
+ throw new Error(`WRUN ${name} is callable during state() only (called during ${host.phase}); ` +
274
+ `read cell blocks inside state() and carry what finalize() needs in module state`);
275
+ }
276
+ const column = cellColumns.get(index);
277
+ if (column === undefined) {
278
+ const declared = [...cellColumns.keys()].join(', ');
279
+ throw new Error(`WRUN ${name}(${index}): input ${index} is not declared cellType "array" in metadata` +
280
+ (declared === '' ? ' (no inputs are)' : ` (declared cell inputs: ${declared})`));
281
+ }
282
+ return host.packedRow * cellColumnCount + column;
283
+ };
284
+ const importObject = {
285
+ env: {
286
+ // The guest's trap: a `throw`, a std-lib check (`~lib/array.ts` bounds), or the
287
+ // author's own abort(). asc passes the message and the source path as AssemblyScript
288
+ // strings in the guest's memory (null pointers when it has none: an explicit abort()
289
+ // carries no file and 0:0), so the error names them; the editor's Problems lane
290
+ // anchors the row on the buffer only when the path is src/indicator.ts
291
+ // (utility/scriptEditor/runtime-diagnostics.util.ts). Reads only: nothing here
292
+ // touches the memory ceiling or the no-growth rule.
293
+ abort(message, fileName, line, column) {
294
+ const memory = exportedMemory(instanceRef.exports);
295
+ throw new Error(formatAssemblyScriptAbort(readAssemblyScriptString(memory, message), readAssemblyScriptString(memory, fileName), line, column));
296
+ },
297
+ },
298
+ wrun: {
299
+ wrun_arg_count() {
300
+ return host.packedRow >= 0 && current ? current.argCounts[host.packedRow] : host.args.length;
301
+ },
302
+ wrun_arg_i32(index) {
303
+ return intArg(index);
304
+ },
305
+ wrun_arg_i64(index) {
306
+ return BigInt(intArg(index));
307
+ },
308
+ wrun_arg_f32(index) {
309
+ return floatArg(index);
310
+ },
311
+ wrun_arg_f64(index) {
312
+ return floatArg(index);
313
+ },
314
+ wrun_output_f64(index, value) {
315
+ if (!Number.isInteger(index) || index < 0 || index >= MAX_OUTPUT_WRITES) {
316
+ throw new Error(`WRUN output index ${index} out of bounds for ${MAX_OUTPUT_WRITES} tracked outputs`);
317
+ }
318
+ if (value === Infinity || value === -Infinity) {
319
+ throw new Error(`WRUN output ${index} is ${value}; guard the calculation and emit NaN when the value is undefined`);
320
+ }
321
+ // A write past the declared outputs (inside the tracked range) is
322
+ // legal and read by nothing, so only declared indexes are kept.
323
+ if (index < trackedOutputs) {
324
+ host.outputs[index] = value;
325
+ if (host.writtenAt[index] !== host.rowStamp) {
326
+ host.writtenAt[index] = host.rowStamp;
327
+ host.writtenCount += 1;
328
+ }
329
+ }
330
+ },
331
+ wrun_result_write(count) {
332
+ if (!Number.isInteger(count) || count < 0 || count > MAX_OUTPUT_WRITES) {
333
+ throw new Error(`WRUN output count ${count} out of bounds for ${MAX_OUTPUT_WRITES} tracked outputs`);
334
+ }
335
+ host.count = count;
336
+ host.ready = true;
337
+ },
338
+ },
339
+ };
340
+ // Run-level string accounting: the sum of every COMMITTED row's final byte
341
+ // total plus the in-flight row's, checked on every write so the run cap
342
+ // refuses at the offending write, never after megabytes of transport.
343
+ // Persists across a session's runRows calls (a session is one run).
344
+ let runStringBytes = 0;
345
+ // Frames retain only the latest write per slot across the whole run. They
346
+ // do not participate in the per-row reset or the forming-bar rollback.
347
+ const frameWrites = new Array(frameSlotCount).fill(undefined);
348
+ let runFrameBytes = 0;
349
+ // The import object is VERSION-SPECIFIC: a wrun-1 instantiation never
350
+ // carries the cell channel or the string channel, and wrun-3 and later
351
+ // instantiations link the draw channel, so even a module that slipped past
352
+ // validation fails to link rather than reaching a later ABI's behavior.
353
+ if (abiAtLeast(config.abi, 'wrun-2')) {
354
+ importObject.wrun.wrun_arg_len = (index) => {
355
+ const at = requireCellColumn('wrun_arg_len', index);
356
+ // The phase guard inside requireCellColumn proves a block is running.
357
+ const block = current;
358
+ // -1 = the bar carries no block for this input; 0 = a zero-cell bar.
359
+ return block.cellLens[at];
360
+ };
361
+ importObject.wrun.wrun_arg_bytes = (index, ptr) => {
362
+ const at = requireCellColumn('wrun_arg_bytes', index);
363
+ const block = current;
364
+ const len = block.cellLens[at];
365
+ if (len < 0)
366
+ return -1;
367
+ if (len === 0)
368
+ return 0;
369
+ const memory = exportedMemory(instanceRef.exports);
370
+ if (!memory) {
371
+ throw new Error('WRUN wrun_arg_bytes: module exports no memory for the host to copy cells into');
372
+ }
373
+ const byteLength = len * BYTES_PER_CELL;
374
+ if (!Number.isInteger(ptr) || ptr < 0 || ptr + byteLength > memory.buffer.byteLength) {
375
+ throw new Error(`WRUN wrun_arg_bytes(${index}, ${ptr}): ${byteLength} bytes do not fit the module's ` +
376
+ `exported memory of ${memory.buffer.byteLength} bytes; reserve max_cells * ${BYTES_PER_CELL} ` +
377
+ `bytes per celled input and pass a pointer inside that buffer`);
378
+ }
379
+ new Uint8Array(memory.buffer, ptr, byteLength).set(new Uint8Array(block.cells.buffer, block.cells.byteOffset + block.cellOffsets[at] * BYTES_PER_CELL, byteLength));
380
+ return byteLength;
381
+ };
382
+ // The wrun-2 string channel: one import, callable during finalize() only,
383
+ // writing UTF-8 bytes from exported memory into a DECLARED string slot.
384
+ // Caps are enforced with checked arithmetic BEFORE the bytes are copied.
385
+ // A slot never written this row is ABSENT (length -1 in the packed
386
+ // table), distinct from a present empty write.
387
+ importObject.wrun.wrun_output_str = (slot, ptr, len) => {
388
+ if (host.phase !== 'finalize') {
389
+ throw new Error(`WRUN wrun_output_str is callable during finalize() only (called during ${host.phase}); ` +
390
+ `compute per-bar values in state(), carry them in module state, and write each string ` +
391
+ `slot beside the numeric outputs in finalize()`);
392
+ }
393
+ if (stringSlotCount === 0) {
394
+ throw new Error(`WRUN wrun_output_str(${slot}, ...): this run declares no string slots ` +
395
+ `(declare metadata string_slots under abi_version "wrun-2")`);
396
+ }
397
+ if (!Number.isInteger(slot) || slot < 0 || slot >= stringSlotCount) {
398
+ throw new Error(`WRUN wrun_output_str(${slot}, ...): string slot ${slot} is not declared ` +
399
+ `(declared slots: 0..${stringSlotCount - 1})`);
400
+ }
401
+ if (!Number.isInteger(len) || len < 0) {
402
+ throw new Error(`WRUN wrun_output_str(${slot}, ...): length ${len} must be a nonnegative integer`);
403
+ }
404
+ const cap = stringMaxBytes[slot];
405
+ if (len > cap) {
406
+ throw new Error(`WRUN string slot ${slot} write of ${len} bytes exceeds the slot's max_bytes ${cap}; ` +
407
+ `strings are never truncated; shorten the text or raise max_bytes in metadata.string_slots`);
408
+ }
409
+ const previous = host.stringWrites[slot];
410
+ const rowTotal = host.rowStringBytes - (previous ? previous.byteLength : 0) + len;
411
+ if (rowTotal > STRING_ROW_LIMIT_BYTES) {
412
+ throw new Error(`WRUN string writes for one row total ${rowTotal} bytes, over the per-row limit ` +
413
+ `${STRING_ROW_LIMIT_BYTES}; emit less text per bar`);
414
+ }
415
+ if (runStringBytes + rowTotal > STRING_RUN_LIMIT_BYTES) {
416
+ throw new Error(`WRUN string writes for this run total ${runStringBytes + rowTotal} bytes, over the ` +
417
+ `per-run limit ${STRING_RUN_LIMIT_BYTES}; emit less text or fewer rows`);
418
+ }
419
+ const runTotal = runStringBytes + rowTotal + runFrameBytes;
420
+ if (wrun4 && runTotal > FRAME_RUN_LIMIT_BYTES) {
421
+ throw new Error(`WRUN string and frame writes for this run total ${runTotal} bytes, over the ` +
422
+ `per-run limit ${FRAME_RUN_LIMIT_BYTES}; emit less text or fewer rows`);
423
+ }
424
+ const memory = exportedMemory(instanceRef.exports);
425
+ if (!memory) {
426
+ throw new Error('WRUN wrun_output_str: module exports no memory for the host to read the string from');
427
+ }
428
+ if (!Number.isInteger(ptr) || ptr < 0 || ptr + len > memory.buffer.byteLength) {
429
+ throw new Error(`WRUN wrun_output_str(${slot}, ${ptr}): ${len} bytes do not fit the module's exported ` +
430
+ `memory of ${memory.buffer.byteLength} bytes; pass a pointer to the encoded UTF-8 ` +
431
+ `inside exported memory`);
432
+ }
433
+ const bytes = new Uint8Array(len);
434
+ bytes.set(new Uint8Array(memory.buffer, ptr, len));
435
+ let text;
436
+ try {
437
+ text = UTF8_FATAL.decode(bytes);
438
+ }
439
+ catch {
440
+ throw new Error(`WRUN string slot ${slot} write of ${len} bytes is not valid UTF-8; wrun_output_str ` +
441
+ `carries UTF-8 text only (encode before writing)`);
442
+ }
443
+ // The no-disguises rule at the slot boundary (guard G2, every host): the
444
+ // bidi controls, zero-width and control characters a module wrote never
445
+ // reach a reader (the packed string table, a label handle's text), newlines
446
+ // kept. The caps above were judged on the bytes as written; the clean bytes
447
+ // are never longer.
448
+ host.stringWrites[slot] = plainSlotBytes(bytes, text);
449
+ host.rowStringBytes = rowTotal;
450
+ };
451
+ }
452
+ // The wrun-5 text channel: the cell channel's shape on params, callable
453
+ // during init() only (the generated pt_<name>() readers run there). The
454
+ // host hands over plain text already within the param's max_bytes
455
+ // (wrun-text-params.util); a slot the request holds no bytes for is not a
456
+ // text param and answers -1, so the reader reads the declared default and
457
+ // refuses nothing.
458
+ if (abiAtLeast(config.abi, 'wrun-5')) {
459
+ const textParams = config.textParams ?? EMPTY_TEXT_PARAMS;
460
+ const textBytesAt = (name, index) => {
461
+ if (host.phase !== 'init') {
462
+ throw new Error(`WRUN ${name} (${WRUN5_TEXT_REFUSALS.phase}): a text setting is readable during init() only ` +
463
+ `(called during ${host.phase}); read it in init() / onStart() and carry it in module state`);
464
+ }
465
+ return Number.isInteger(index) && index >= 0 ? textParams[index] : undefined;
466
+ };
467
+ importObject.wrun.wrun_param_len = (index) => {
468
+ const bytes = textBytesAt('wrun_param_len', index);
469
+ return bytes === undefined ? -1 : bytes.byteLength;
470
+ };
471
+ importObject.wrun.wrun_param_bytes = (index, ptr) => {
472
+ const bytes = textBytesAt('wrun_param_bytes', index);
473
+ if (bytes === undefined)
474
+ return -1;
475
+ const len = bytes.byteLength;
476
+ if (len === 0)
477
+ return 0;
478
+ const memory = exportedMemory(instanceRef.exports);
479
+ if (!memory) {
480
+ throw new Error(`WRUN wrun_param_bytes (${WRUN5_TEXT_REFUSALS.memory}): module exports no memory for the host to copy ` +
481
+ `the text setting into`);
482
+ }
483
+ if (!Number.isInteger(ptr) || ptr < 0 || ptr + len > memory.buffer.byteLength) {
484
+ throw new Error(`WRUN wrun_param_bytes(${index}, ${ptr}) (${WRUN5_TEXT_REFUSALS.memory}): ${len} bytes do not fit the ` +
485
+ `module's exported memory of ${memory.buffer.byteLength} bytes; pass a pointer to a buffer of ` +
486
+ `wrun_param_len(${index}) bytes inside exported memory`);
487
+ }
488
+ new Uint8Array(memory.buffer, ptr, len).set(bytes);
489
+ return len;
490
+ };
491
+ }
492
+ // The wrun-6 row count: the bars the session holds while the row is
493
+ // evaluated, the forming bar included (runRows sets it per block).
494
+ // Callable during state() and finalize() only.
495
+ if (abiAtLeast(config.abi, 'wrun-6')) {
496
+ importObject.wrun.wrun_bar_count = () => {
497
+ if (host.phase !== 'state' && host.phase !== 'finalize') {
498
+ throw new Error(`WRUN wrun_bar_count (${WRUN6_BAR_REFUSALS.phase}): wrun_bar_count is callable during state() and ` +
499
+ `finalize() only (called during ${host.phase}); read the row count per bar, never at init`);
500
+ }
501
+ return host.barCount;
502
+ };
503
+ }
504
+ if (abiAtLeast(config.abi, 'wrun-4')) {
505
+ importObject.wrun.wrun_output_frame = (slot, ptr, len) => {
506
+ if (host.phase !== 'finalize') {
507
+ throw new Error(`WRUN wrun_output_frame is callable during finalize() only (called during ${host.phase}); ` +
508
+ `compute per-bar values in state(), carry them in module state, and write each frame ` +
509
+ `slot beside the numeric outputs in finalize()`);
510
+ }
511
+ if (frameSlotCount === 0) {
512
+ throw new Error(`WRUN wrun_output_frame(${slot}, ...): this run declares no frame slots ` +
513
+ `(declare metadata frames under abi_version "wrun-4")`);
514
+ }
515
+ if (!Number.isInteger(slot) || slot < 0 || slot >= frameSlotCount) {
516
+ throw new Error(`WRUN wrun_output_frame(${slot}, ...): frame slot ${slot} is not declared ` +
517
+ `(declared slots: 0..${frameSlotCount - 1})`);
518
+ }
519
+ if (!Number.isInteger(len) || len < 0) {
520
+ throw new Error(`WRUN wrun_output_frame(${slot}, ...): length ${len} must be a nonnegative integer`);
521
+ }
522
+ const cap = frameMaxBytes[slot];
523
+ if (len > cap) {
524
+ throw new Error(`WRUN frame slot ${slot} write of ${len} bytes exceeds the slot's max_bytes ${cap}; ` +
525
+ `frames are never truncated; shorten the frame or raise max_bytes in metadata.frames`);
526
+ }
527
+ const nextFrameBytes = runFrameBytes - (frameWrites[slot]?.byteLength ?? 0) + len;
528
+ const runTotal = runStringBytes + host.rowStringBytes + nextFrameBytes;
529
+ if (runTotal > FRAME_RUN_LIMIT_BYTES) {
530
+ throw new Error(`WRUN frame and string writes for this run total ${runTotal} bytes, over the ` +
531
+ `per-run limit ${FRAME_RUN_LIMIT_BYTES}; emit smaller frames or less text`);
532
+ }
533
+ const memory = exportedMemory(instanceRef.exports);
534
+ if (!memory) {
535
+ throw new Error('WRUN wrun_output_frame: module exports no memory for the host to read the frame from');
536
+ }
537
+ if (!Number.isInteger(ptr) || ptr < 0 || ptr + len > memory.buffer.byteLength) {
538
+ throw new Error(`WRUN wrun_output_frame(${slot}, ${ptr}): ${len} bytes do not fit the module's exported ` +
539
+ `memory of ${memory.buffer.byteLength} bytes; pass a pointer to the encoded UTF-8 ` +
540
+ `inside exported memory`);
541
+ }
542
+ const bytes = new Uint8Array(len);
543
+ bytes.set(new Uint8Array(memory.buffer, ptr, len));
544
+ try {
545
+ UTF8_FATAL.decode(bytes);
546
+ }
547
+ catch {
548
+ throw new Error(`WRUN frame slot ${slot} write of ${len} bytes is not valid UTF-8; wrun_output_frame ` +
549
+ `carries UTF-8 text only (encode before writing)`);
550
+ }
551
+ // A frame is JSON, kept byte for byte (its byte accounting is the
552
+ // channel's contract); the no-disguises rule applies where the frame is
553
+ // parsed (wrun-frame-host.ts), after the JSON decode, which catches an
554
+ // escaped character beside a raw one.
555
+ frameWrites[slot] = bytes;
556
+ runFrameBytes = nextFrameBytes;
557
+ };
558
+ }
559
+ // The wrun-3 draw channel: seven finalize-only ops against the session's
560
+ // handle ledger plus the last-bar signal. The ledger owns the op rules,
561
+ // caps, the skip-or-refuse verdict of every code and its precedence
562
+ // (utility/wrun/wrun-handles.util.ts); the host owns what needs the guest:
563
+ // the phase, the row index and time, the row's string slots, and a
564
+ // polyline's points in exported memory.
565
+ const ledger = abiAtLeast(config.abi, 'wrun-3') ? new WrunHandleLedger(config.handleDefaults) : null;
566
+ if (ledger) {
567
+ const requireDrawPhase = (name) => {
568
+ if (host.phase !== 'finalize') {
569
+ throw new WrunDrawRefusalError(WRUN3_DRAW_REFUSALS.phase, `${name} is callable during finalize() only (called during ${host.phase}); compute in state(), ` +
570
+ `carry what the drawing needs in module state, and draw beside the outputs in finalize()`, { call: name });
571
+ }
572
+ };
573
+ // The row's string slots as a label or a slot prop reads them: a slot's
574
+ // text is its bytes as written on THIS row at the time of the call (the
575
+ // ledger copies them into the handle), null while it is not written yet
576
+ // this row (absent), "" for a present empty write. The ledger judges an
577
+ // undeclared slot (refused) and an unwritten one (skipped) in the
578
+ // contract's order; slot -1 (a mark, DW29) reads nothing.
579
+ const rowSlots = {
580
+ count: stringSlotCount,
581
+ text: (slot) => {
582
+ const bytes = host.stringWrites[slot];
583
+ return bytes === null || bytes === undefined ? null : UTF8_FATAL.decode(bytes);
584
+ },
585
+ };
586
+ // `count` points, each two little-endian f64 (x epoch seconds, y price),
587
+ // read out of exported memory at `ptr` and copied into the handle. The
588
+ // ledger asks for them after its count checks (an oversize count never
589
+ // reads, an empty one skips) and before its caps: the module's memory and
590
+ // the pointer bounds are fatal checks.
591
+ const readPolylinePoints = (id, ptr, count) => {
592
+ const call = `wrun_draw_polyline(${id}, ${ptr}, ${count})`;
593
+ const element = { id, row: host.rowIndex, call: 'wrun_draw_polyline', arg: `ptr=${ptr}` };
594
+ const memory = exportedMemory(instanceRef.exports);
595
+ if (!memory) {
596
+ throw new WrunDrawRefusalError(WRUN3_DRAW_REFUSALS.polyline_out_of_bounds, `${call}: the module exports no memory for the host to read the points from`, element);
597
+ }
598
+ const byteLength = count * BYTES_PER_POINT;
599
+ if (!Number.isInteger(ptr) || ptr < 0 || ptr + byteLength > memory.buffer.byteLength) {
600
+ throw new WrunDrawRefusalError(WRUN3_DRAW_REFUSALS.polyline_out_of_bounds, `${call}: ${byteLength} bytes of points do not fit the module's exported memory of ` +
601
+ `${memory.buffer.byteLength} bytes; pass a pointer to count (x, y) f64 pairs inside exported memory`, element);
602
+ }
603
+ const view = new DataView(memory.buffer, ptr, byteLength);
604
+ const flat = new Float64Array(count * 2);
605
+ for (let at = 0; at < flat.length; at += 1)
606
+ flat[at] = view.getFloat64(at * 8, true);
607
+ return flat;
608
+ };
609
+ importObject.wrun.wrun_bar_last = () => {
610
+ if (host.phase !== 'state' && host.phase !== 'finalize') {
611
+ throw new WrunDrawRefusalError(WRUN3_DRAW_REFUSALS.phase, `wrun_bar_last is callable during state() and finalize() only (called during ${host.phase})`);
612
+ }
613
+ return host.barLast;
614
+ };
615
+ importObject.wrun.wrun_draw_line = (id, x1, y1, x2, y2) => {
616
+ requireDrawPhase('wrun_draw_line');
617
+ ledger.line(host.rowIndex, id, x1, y1, x2, y2);
618
+ };
619
+ importObject.wrun.wrun_draw_box = (id, left, top, right, bottom) => {
620
+ requireDrawPhase('wrun_draw_box');
621
+ ledger.box(host.rowIndex, id, left, top, right, bottom);
622
+ };
623
+ importObject.wrun.wrun_draw_label = (id, x, y, slot) => {
624
+ requireDrawPhase('wrun_draw_label');
625
+ ledger.label(host.rowIndex, id, x, y, { slot, slots: rowSlots });
626
+ };
627
+ importObject.wrun.wrun_draw_polyline = (id, ptr, count) => {
628
+ requireDrawPhase('wrun_draw_polyline');
629
+ ledger.polyline(host.rowIndex, id, { count, read: () => readPolylinePoints(id, ptr, count) });
630
+ };
631
+ importObject.wrun.wrun_draw_style = (id, prop, value) => {
632
+ requireDrawPhase('wrun_draw_style');
633
+ ledger.style(host.rowIndex, id, prop, value, rowSlots);
634
+ };
635
+ importObject.wrun.wrun_draw_color = (id, prop, rgba) => {
636
+ requireDrawPhase('wrun_draw_color');
637
+ ledger.color(host.rowIndex, id, prop, rgba);
638
+ };
639
+ importObject.wrun.wrun_draw_delete = (id) => {
640
+ requireDrawPhase('wrun_draw_delete');
641
+ ledger.delete(id, host.rowIndex);
642
+ };
643
+ }
644
+ // The wrun-3 strategy channel: the shared host's engine broker, driven by its
645
+ // own host (intent decoding, id interning, caps, the forming-bar clone and
646
+ // the close-confirm, event diffs). The driver owns every rule; this
647
+ // executor owns what needs the guest: the phase, exported memory for the
648
+ // (ptr, len) strings, the row index, the bar and its confirmation. A
649
+ // wrun-3 or later instantiation links the channel when the sheet declares
650
+ // `strategy`; a module importing it without the section refuses by
651
+ // name before anything links.
652
+ const strategyHost = abiAtLeast(config.abi, 'wrun-3') && config.strategy !== undefined
653
+ ? new sharedHost.WrunStrategyHost({
654
+ config: config.strategy.config,
655
+ ...(config.strategy.intervalMs !== undefined ? { intervalMs: config.strategy.intervalMs } : {}),
656
+ phase: () => host.phase,
657
+ memory: () => exportedMemory(instanceRef.exports),
658
+ events: config.strategy.events === true,
659
+ })
660
+ : null;
661
+ if (strategyHost)
662
+ Object.assign(importObject.wrun, strategyHost.imports);
663
+ else if (abiAtLeast(config.abi, 'wrun-3'))
664
+ refuseUndeclaredStrategyImports(config.module);
665
+ const instance = await WebAssembly.instantiate(config.module, importObject);
666
+ instanceRef.exports = instance.exports;
667
+ const exports = instance.exports;
668
+ const init = requireFunction(exports.init, 'init');
669
+ const state = requireFunction(exports.state, 'state');
670
+ const finalize = requireFunction(exports.finalize, 'finalize');
671
+ requireFunction(exports.reset, 'reset');
672
+ resetHostResult(host);
673
+ guestCall(host, 'init', config.initArgs, -1, init);
674
+ checkMemoryLimit(exports, memoryLimit);
675
+ const memoryBaselineBytes = exportedMemoryByteLength(exports);
676
+ // The memory ceiling and the no-growth rule after EVERY guest call, with no
677
+ // `memory.buffer` read on the happy path: a held buffer that still reads
678
+ // the baseline proves the memory did not grow (growthWitness). Any other
679
+ // reading (a growth, or a memory.grow(0) that only swapped the buffer)
680
+ // takes the exact checks, same order and messages, and holds the buffer
681
+ // the memory has now. Without exported memory there is nothing to check.
682
+ const guestMemory = exportedMemory(exports);
683
+ let heldBuffer = growthWitness(guestMemory);
684
+ const checkMemoryAfterCall = () => {
685
+ if (guestMemory === null)
686
+ return;
687
+ if (heldBuffer !== null && heldBuffer.byteLength === memoryBaselineBytes)
688
+ return;
689
+ checkMemoryLimit(exports, memoryLimit);
690
+ checkMemoryGrowth(exports, memoryBaselineBytes);
691
+ heldBuffer = growthWitness(guestMemory);
692
+ };
693
+ // Live forming-bar state, carried ACROSS runRows calls: the timestamp the
694
+ // session last evaluated, the pre-evaluation snapshot that replays it, and
695
+ // (wrun-3 close-confirm) that row's inputs as last evaluated.
696
+ let liveTs = null;
697
+ let liveSnapshot = null;
698
+ let liveRow = null;
699
+ // Row indexes of the run window (the ledger's createdBar / mutatedBar): the
700
+ // index the next NEW timestamp takes, and the forming bar's index a live
701
+ // block may revise. A historical request is one block from row 0.
702
+ let nextRowIndex = 0;
703
+ let liveRowIndex = 0;
704
+ // Per block, not per row: every row of a block reads the same cell columns,
705
+ // so a row of the block already bound binds nothing (the close-confirm's
706
+ // one-row block and the block after it each bind once).
707
+ const bindBlock = (block) => {
708
+ if (block === current)
709
+ return;
710
+ current = block;
711
+ cellColumnCount = block.cellIndexes.length;
712
+ cellColumns = new Map();
713
+ for (let column = 0; column < cellColumnCount; column += 1) {
714
+ cellColumns.set(block.cellIndexes[column], column);
715
+ }
716
+ };
717
+ /** One row through state() and finalize(); the results stay in `host`
718
+ * for the caller to commit. False = the row is not ready. A strategy
719
+ * row begins on the broker FIRST (contract section 2, step 1: fills for
720
+ * orders queued on earlier rows, equity marked at the close), ready or
721
+ * not, so the equity series covers every bar. The broker confirms every
722
+ * bar of a full run (the engine's full-run rule: `isConfirmedBar` is
723
+ * false only for a live update's last bar); on the live lane the newest
724
+ * bar the request holds (`barLast`) is the forming bar and runs on a
725
+ * clone. `barLast` itself (the guest's `wrun_bar_last`) answers 1 on the
726
+ * newest bar in both modes. */
727
+ const evaluateRow = (block, row, rowIndex, barLast, mode) => {
728
+ bindBlock(block);
729
+ resetHostResult(host);
730
+ // The row's time rides every draw call it skips (the record's `ts`, the
731
+ // chart's row unit: epoch ms).
732
+ ledger?.beginRow(block.ts[row]);
733
+ host.rowIndex = rowIndex;
734
+ host.barLast = barLast;
735
+ const confirmed = mode === 'live' ? barLast === 0 : true;
736
+ strategyHost?.beginBar(rowIndex, block.ts[row], strategyBarOf(block, row), confirmed);
737
+ const stateResult = guestCall(host, 'state', EMPTY_ARGS, row, state);
738
+ checkMemoryAfterCall();
739
+ const readiness = typeof stateResult === 'number' ? stateResult : Number(stateResult ?? 0);
740
+ if (readiness < 1)
741
+ return false;
742
+ guestCall(host, 'finalize', EMPTY_ARGS, -1, finalize);
743
+ checkMemoryAfterCall();
744
+ validateDeclaredOutputs(host, outputCount);
745
+ return true;
746
+ };
747
+ const runRows = (block, mode) => {
748
+ const rowCount = block.rowCount;
749
+ // Live ordering is validated for the WHOLE block BEFORE any evaluation:
750
+ // a refused block must leave the guest state untouched (the typed error
751
+ // tells the worker the session survives).
752
+ if (mode === 'live') {
753
+ let expectedTs = liveTs;
754
+ for (let row = 0; row < rowCount; row += 1) {
755
+ const rowTs = block.ts[row];
756
+ if (expectedTs !== null && rowTs < expectedTs) {
757
+ throw new WrunLiveOrderError(`WRUN rows out of order: ${rowTs} < ${expectedTs}`);
758
+ }
759
+ expectedTs = rowTs;
760
+ }
761
+ }
762
+ // The wrun-6 row count every row of this block reads: the bars the session
763
+ // holds once the block is in. A historical block is all new bars; a live
764
+ // block adds the timestamps past the forming bar (a same-bar revision adds
765
+ // none). The pre-scan above has already ordered them.
766
+ let newBars = 0;
767
+ let newestTs = mode === 'live' ? liveTs : null;
768
+ for (let row = 0; row < rowCount; row += 1) {
769
+ const rowTs = block.ts[row];
770
+ if (mode !== 'live' || newestTs === null || rowTs > newestTs) {
771
+ newBars += 1;
772
+ newestTs = rowTs;
773
+ }
774
+ }
775
+ // A module reading the count never extends a session that already holds
776
+ // bars: a new bar changes the count every held bar read, which only a run
777
+ // over every bar again answers (the engine's re-seed). The main thread
778
+ // reopens the session instead; refused by name before any guest call.
779
+ if (readsBarCount && mode === 'live' && nextRowIndex > 0 && newBars > 0) {
780
+ throw new Error(`WRUN wrun_bar_count: a new bar runs a module that reads the row count again from its first ` +
781
+ `bar; the host reopens the session over every bar instead of extending it`);
782
+ }
783
+ // The block's buffer holds one cell per row and declared output: past the run allocation bound the
784
+ // block is refused by name BEFORE the buffer is allocated and before any guest call, so the session's
785
+ // state is untouched (wrun-run-cells.util).
786
+ const cellsRefusal = wrunRunCellsRefusal(rowCount, outputCount);
787
+ if (cellsRefusal !== null)
788
+ throw new Error(cellsRefusal);
789
+ host.barCount = nextRowIndex + newBars;
790
+ const ready = new Uint8Array(rowCount);
791
+ const outputs = new Float64Array(rowCount * outputCount);
792
+ // The packed string table (only when the run declares slots): row-major
793
+ // (row, slot) lengths (-1 = absent) and offsets into one concatenated
794
+ // byte buffer, assembled after the loop from the per-row commits.
795
+ const stringLens = stringSlotCount > 0 ? new Int32Array(rowCount * stringSlotCount).fill(-1) : null;
796
+ const stringOffsets = stringSlotCount > 0 ? new Int32Array(rowCount * stringSlotCount) : null;
797
+ const stringChunks = stringSlotCount > 0 ? [] : null;
798
+ let stringCursor = 0;
799
+ // The block's live accounting (answered on live-mode blocks only).
800
+ const startedAt = now();
801
+ let restored = 0;
802
+ let snapshotted = 0;
803
+ // A forming-bar restore: memory, globals, the ledger journal AND the
804
+ // run-level string accounting go back to the pre-evaluation state.
805
+ const restoreFormingBar = (snapshotValue) => {
806
+ restore(exports, snapshotValue);
807
+ ledger?.restore();
808
+ runStringBytes = snapshotValue.runStringBytes;
809
+ restored += 1;
810
+ config.onRestore?.();
811
+ };
812
+ try {
813
+ // Close-confirm (contract section 4): a live block that opens PAST the
814
+ // forming bar without re-sending it. That bar was evaluated as the
815
+ // newest bar (bar_last 1) while a full run evaluates it as a closed
816
+ // bar, so restore, re-evaluate it with bar_last 0 on its retained
817
+ // inputs, and commit that state (ledger included) before the new bar.
818
+ // Its replacement outputs have no row in this response to ride; the
819
+ // browser tick always re-sends the forming bar, where they ride the
820
+ // tick's own row through the replay branch below.
821
+ if (mode === 'live' && liveTs !== null && liveSnapshot && liveRow && rowCount > 0 && block.ts[0] > liveTs) {
822
+ restoreFormingBar(liveSnapshot);
823
+ if (evaluateRow(liveRow, 0, liveRowIndex, 0, mode))
824
+ runStringBytes += host.rowStringBytes;
825
+ liveSnapshot = null;
826
+ liveRow = null;
827
+ }
828
+ for (let row = 0; row < rowCount; row += 1) {
829
+ const rowTs = block.ts[row];
830
+ let rowIndex;
831
+ if (mode === 'live' && liveTs !== null && rowTs === liveTs) {
832
+ // A revised forming bar: back to the pre-evaluation state (memory,
833
+ // globals, ledger, string accounting), same row index. A row below
834
+ // the watermark cannot reach here: the pre-scan refused the whole
835
+ // block.
836
+ if (!liveSnapshot)
837
+ throw new Error('WRUN live restore requested before snapshot');
838
+ restoreFormingBar(liveSnapshot);
839
+ liveRow = sliceRow(block, row);
840
+ rowIndex = liveRowIndex;
841
+ }
842
+ else {
843
+ rowIndex = nextRowIndex;
844
+ nextRowIndex += 1;
845
+ // The ledger's baseline moves with every new bar on BOTH lanes: its
846
+ // journal is the ops of the current bar only (the live lane undoes
847
+ // them on a same-bar restore; the historical lane never restores,
848
+ // and without the per-row reset it would retain one op plus one
849
+ // replaced entry per draw call for the whole request).
850
+ ledger?.snapshot();
851
+ if (mode === 'live') {
852
+ // LAZY snapshot: only a row that can later be REPLAYED needs the
853
+ // pre-evaluation state saved: the block's LAST row (a future
854
+ // block may open with the same ts) or a row this same block
855
+ // revises (next ts equal). A historical prefix streamed through
856
+ // a live block therefore costs exactly ONE snapshot (its last
857
+ // row), not one per bar: the mount/pan cost path.
858
+ const nextTs = row + 1 < rowCount ? block.ts[row + 1] : null;
859
+ if (nextTs === null || nextTs === rowTs) {
860
+ liveSnapshot = snapshot(exports, runStringBytes);
861
+ liveRow = sliceRow(block, row);
862
+ snapshotted += 1;
863
+ config.onSnapshot?.();
864
+ }
865
+ else {
866
+ liveSnapshot = null;
867
+ liveRow = null;
868
+ }
869
+ liveTs = rowTs;
870
+ liveRowIndex = rowIndex;
871
+ }
872
+ }
873
+ // The last-bar signal: 1 exactly on the newest bar the request holds
874
+ // (a full run's row N, a live block's forming bar; a stale frame of
875
+ // that same bar is the same bar).
876
+ const barLast = rowTs === block.ts[rowCount - 1] ? 1 : 0;
877
+ if (!evaluateRow(block, row, rowIndex, barLast, mode))
878
+ continue;
879
+ ready[row] = 1;
880
+ // Validation proved every declared output was written this row.
881
+ const outputBase = row * outputCount;
882
+ for (let idx = 0; idx < outputCount; idx += 1) {
883
+ outputs[outputBase + idx] = host.outputs[idx];
884
+ }
885
+ if (stringLens !== null && stringOffsets !== null && stringChunks !== null) {
886
+ // Commit the row's final string writes: a live same-bar replay
887
+ // re-runs finalize after restore, so the LAST evaluation of a
888
+ // timestamp is the one whose strings ride out, exactly like its
889
+ // numeric outputs.
890
+ for (let slot = 0; slot < stringSlotCount; slot += 1) {
891
+ const bytes = host.stringWrites[slot];
892
+ const at = row * stringSlotCount + slot;
893
+ if (bytes === null) {
894
+ stringLens[at] = -1;
895
+ continue;
896
+ }
897
+ stringLens[at] = bytes.byteLength;
898
+ stringOffsets[at] = stringCursor;
899
+ stringChunks.push(bytes);
900
+ stringCursor += bytes.byteLength;
901
+ }
902
+ runStringBytes += host.rowStringBytes;
903
+ }
904
+ }
905
+ }
906
+ finally {
907
+ current = null;
908
+ }
909
+ // The ledger's full live set rides beside every block's rows (the wire
910
+ // replaces the drawing set wholesale), and so do the run's skipped calls
911
+ // when a call was skipped (journaled with the ledger, so a live session's
912
+ // equal a full run's); wrun-1 and wrun-2, and a run that skipped nothing,
913
+ // answer the exact shape they always did.
914
+ const handles = ledger ? { handles: ledger.records(), ...ledger.drawSkips() } : {};
915
+ const frames = frameSlotCount > 0
916
+ ? { frames: frameWrites.map((bytes) => (bytes === undefined ? undefined : UTF8_FATAL.decode(bytes))) }
917
+ : {};
918
+ // The strategy output after the block: the committed fold (plus the
919
+ // forming bar's mark on the live lane), replaced wholesale
920
+ // per response. Its bytes count against the same expanded render result
921
+ // as the ledger's (contract section 4).
922
+ const strategy = strategyHost ? strategyOutputOf(strategyHost, ledger, nextRowIndex, config.strategy?.events) : {};
923
+ // Live blocks answer their restore/snapshot accounting; a historical
924
+ // request keeps the exact shape it always had.
925
+ const live = mode === 'live'
926
+ ? {
927
+ live: {
928
+ restored,
929
+ snapshotted,
930
+ memoryBytes: exportedMemoryByteLength(exports) ?? 0,
931
+ evalMs: now() - startedAt,
932
+ rows: rowCount,
933
+ stringBytes: runStringBytes,
934
+ },
935
+ }
936
+ : {};
937
+ if (stringLens === null || stringOffsets === null || stringChunks === null) {
938
+ return { ready, outputs, strings: undefined, ...handles, ...strategy, ...frames, ...live };
939
+ }
940
+ const stringBytes = new Uint8Array(stringCursor);
941
+ let writeAt = 0;
942
+ for (const chunk of stringChunks) {
943
+ stringBytes.set(chunk, writeAt);
944
+ writeAt += chunk.byteLength;
945
+ }
946
+ return {
947
+ ready,
948
+ outputs,
949
+ strings: { lens: stringLens, offsets: stringOffsets, bytes: stringBytes },
950
+ ...handles,
951
+ ...strategy,
952
+ ...frames,
953
+ ...live,
954
+ };
955
+ };
956
+ return { runRows };
957
+ }
958
+ /** The strategy fields of a block's answer: the engine's StrategyOutput,
959
+ * refused by name when its wire bytes (plus the ledger's) exceed the
960
+ * expanded render result's cap, and with `events` on, the event streams and the
961
+ * reserved outputs over the `rowCount` rows the session has begun. */
962
+ function strategyOutputOf(strategyHost, ledger, rowCount, events) {
963
+ const output = strategyHost.finalize();
964
+ const { wrunStrategyWireBytes, WrunStrategyRefusalError } = wrunChartHostEnv().sharedHost();
965
+ const bytes = wrunStrategyWireBytes(output) + (ledger?.accountedBytes ?? 0);
966
+ if (bytes > WRUN_RENDER_RESULT_LIMIT_BYTES) {
967
+ throw new WrunStrategyRefusalError('wrun_render_result_too_large', `the strategy result (${output.trades.length} trades over ${output.equity.length} bars) and the drawings total ` +
968
+ `${bytes} bytes, over the ${WRUN_RENDER_RESULT_LIMIT_BYTES}-byte render result limit`, 'trade less often, draw less, or run the strategy over fewer bars');
969
+ }
970
+ if (events !== true)
971
+ return { strategy: output };
972
+ return {
973
+ strategy: output,
974
+ strategyEvents: strategyHost.events,
975
+ strategyReserved: strategyHost.reservedOutputs(rowCount),
976
+ };
977
+ }
978
+ export async function runWrunPackedRequest(request, options = {}) {
979
+ const session = await createWrunAbiSession({
980
+ module: request.module,
981
+ abi: request.abi,
982
+ outputCount: request.outputCount,
983
+ initArgs: request.initArgs,
984
+ textParams: request.textParams,
985
+ stringMaxBytes: request.stringMaxBytes,
986
+ frameMaxBytes: request.frameMaxBytes,
987
+ handleDefaults: request.handleDefaults,
988
+ strategy: request.strategy,
989
+ memoryLimitBytes: options.memoryLimitBytes,
990
+ });
991
+ return session.runRows(request, request.mode);
992
+ }
993
+ /** Run one guest export with the phase and argument block it is owed. A
994
+ * guest trap leaves `phase` at the phase that trapped: the whole request
995
+ * fails, and the error message (for the cell channel) names that phase. */
996
+ function guestCall(host, phase, args, packedRow, fn) {
997
+ host.phase = phase;
998
+ host.args = args;
999
+ host.packedRow = packedRow;
1000
+ const result = fn();
1001
+ host.phase = 'idle';
1002
+ host.args = EMPTY_ARGS;
1003
+ host.packedRow = -1;
1004
+ return result;
1005
+ }
1006
+ /** A fresh row in the session's own buffers: a new stamp un-writes every
1007
+ * output at once, and every string slot goes back to absent. */
1008
+ function resetHostResult(host) {
1009
+ if (host.rowStamp === MAX_ROW_STAMP) {
1010
+ host.writtenAt.fill(0);
1011
+ host.rowStamp = 0;
1012
+ }
1013
+ host.rowStamp += 1;
1014
+ host.writtenCount = 0;
1015
+ host.count = 0;
1016
+ host.ready = false;
1017
+ const stringWrites = host.stringWrites;
1018
+ for (let slot = 0; slot < stringWrites.length; slot += 1)
1019
+ stringWrites[slot] = null;
1020
+ host.rowStringBytes = 0;
1021
+ }
1022
+ function validateDeclaredOutputs(host, outputCount) {
1023
+ const returned = host.ready ? host.count : 0;
1024
+ // The happy path decides on the two counts, allocation-free: every
1025
+ // declared output written this row, and the returned count covering them.
1026
+ if (host.writtenCount === outputCount && returned >= outputCount)
1027
+ return;
1028
+ const missing = [];
1029
+ const truncated = [];
1030
+ for (let idx = 0; idx < outputCount; idx += 1) {
1031
+ if (host.writtenAt[idx] !== host.rowStamp) {
1032
+ missing.push(idx);
1033
+ continue;
1034
+ }
1035
+ if (idx >= returned)
1036
+ truncated.push(idx);
1037
+ }
1038
+ if (missing.length === 0 && truncated.length === 0)
1039
+ return;
1040
+ const problems = [];
1041
+ if (missing.length > 0)
1042
+ problems.push(`never wrote declared output(s) ${missing.join(', ')}`);
1043
+ if (truncated.length > 0) {
1044
+ problems.push(`left declared output(s) ${truncated.join(', ')} outside the returnOutput count ${returned}`);
1045
+ }
1046
+ throw new Error(`WRUN declared output validation failed: ${problems.join('; ')}; check setOutput indices and returnOutput count against metadata outputs`);
1047
+ }
1048
+ /** One row of a packed block as its own one-row block (the forming bar's
1049
+ * inputs, retained for a close-confirm re-evaluation): the scalar slice,
1050
+ * the row's cell blocks, copied contiguously, and its broker feed bar. */
1051
+ function sliceRow(block, row) {
1052
+ const columns = block.cellIndexes.length;
1053
+ const cellLens = block.cellLens.slice(row * columns, (row + 1) * columns);
1054
+ const cellOffsets = new Int32Array(columns);
1055
+ let total = 0;
1056
+ for (let column = 0; column < columns; column += 1)
1057
+ if (cellLens[column] > 0)
1058
+ total += cellLens[column];
1059
+ const cells = new Float64Array(total);
1060
+ let cursor = 0;
1061
+ for (let column = 0; column < columns; column += 1) {
1062
+ const len = cellLens[column];
1063
+ if (len <= 0)
1064
+ continue;
1065
+ const from = block.cellOffsets[row * columns + column];
1066
+ cells.set(block.cells.subarray(from, from + len), cursor);
1067
+ cellOffsets[column] = cursor;
1068
+ cursor += len;
1069
+ }
1070
+ const bars = block.strategyBars;
1071
+ return {
1072
+ rowCount: 1,
1073
+ stride: block.stride,
1074
+ ts: block.ts.slice(row, row + 1),
1075
+ argCounts: block.argCounts.slice(row, row + 1),
1076
+ values: block.values.slice(row * block.stride, (row + 1) * block.stride),
1077
+ cellIndexes: block.cellIndexes,
1078
+ cellLens,
1079
+ cellOffsets,
1080
+ cells,
1081
+ ...(bars !== undefined
1082
+ ? { strategyBars: bars.slice(row * STRATEGY_BAR_STRIDE, (row + 1) * STRATEGY_BAR_STRIDE) }
1083
+ : {}),
1084
+ };
1085
+ }
1086
+ /** Same-bar live restore semantics: copy linear memory plus the mutable
1087
+ * globals exported under __wrun_g*. The host exports EVERY mutable global
1088
+ * under that prefix when it compiles the module (WrunBrowserHost
1089
+ * .compileModule), so a compiler's top-level scalars restore beside the
1090
+ * heap they index; a module must still export its memory if it keeps state
1091
+ * there (AssemblyScript does by default). */
1092
+ function snapshot(exports, runStringBytes) {
1093
+ const memory = exportedMemory(exports);
1094
+ const view = memory ? new Uint8Array(memory.buffer) : null;
1095
+ const globals = new Map();
1096
+ for (const [name, value] of Object.entries(exports)) {
1097
+ if (!name.startsWith(WRUN_GLOBAL_PREFIX))
1098
+ continue;
1099
+ if (value instanceof WebAssembly.Global) {
1100
+ globals.set(name, value.value);
1101
+ }
1102
+ }
1103
+ return { memory: view ? new Uint8Array(view) : null, globals, runStringBytes };
1104
+ }
1105
+ function restore(exports, snapshotValue) {
1106
+ if (snapshotValue.memory) {
1107
+ const memory = exportedMemory(exports);
1108
+ if (!memory)
1109
+ throw new Error('WRUN module has no memory export to restore');
1110
+ const view = new Uint8Array(memory.buffer);
1111
+ if (view.byteLength !== snapshotValue.memory.byteLength) {
1112
+ throw new Error('WRUN memory size changed between snapshot and restore');
1113
+ }
1114
+ view.set(snapshotValue.memory);
1115
+ }
1116
+ for (const [name, value] of snapshotValue.globals) {
1117
+ const exported = exports[name];
1118
+ if (!(exported instanceof WebAssembly.Global)) {
1119
+ throw new Error(`WRUN global ${name} is not restorable`);
1120
+ }
1121
+ try {
1122
+ exported.value = value;
1123
+ }
1124
+ catch (err) {
1125
+ const detail = err instanceof Error ? `: ${err.message}` : '';
1126
+ throw new Error(`WRUN global ${name} is not restorable${detail}`, { cause: err });
1127
+ }
1128
+ }
1129
+ }
1130
+ function exportedMemory(exports) {
1131
+ if (!exports)
1132
+ return null;
1133
+ const memory = exports.memory;
1134
+ return memory instanceof WebAssembly.Memory ? memory : null;
1135
+ }
1136
+ const UTF16LE = new TextDecoder('utf-16le');
1137
+ /** Longest abort message or path the host repeats (a runaway string is still one line). */
1138
+ const ABORT_STRING_MAX_CHARS = 512;
1139
+ /** An AssemblyScript `string` in the guest's memory: UTF-16LE code units at `ptr`, the byte
1140
+ * length as the u32 at `ptr - 4` (the managed object header's rtSize). Null for a null
1141
+ * pointer, no memory, or a header that does not fit the memory: a trap never traps twice. */
1142
+ export function readAssemblyScriptString(memory, ptr) {
1143
+ if (!memory || !Number.isInteger(ptr) || ptr < 4)
1144
+ return null;
1145
+ const { buffer } = memory;
1146
+ if (ptr > buffer.byteLength)
1147
+ return null;
1148
+ const byteLength = new DataView(buffer).getUint32(ptr - 4, true);
1149
+ if (byteLength > buffer.byteLength - ptr)
1150
+ return null;
1151
+ const text = UTF16LE.decode(new Uint8Array(buffer, ptr, byteLength & ~1));
1152
+ return text.length > ABORT_STRING_MAX_CHARS ? text.slice(0, ABORT_STRING_MAX_CHARS) : text;
1153
+ }
1154
+ /** `AssemblyScript abort: <message> at <path>:<line>:<column>`; the message part only when
1155
+ * the guest passed one, the position only when asc supplied one (a path, or a non-zero
1156
+ * line/column without a path, the position-only shape this host used to throw). */
1157
+ export function formatAssemblyScriptAbort(message, fileName, line, column) {
1158
+ const head = message ? `AssemblyScript abort: ${message}` : 'AssemblyScript abort';
1159
+ if (fileName)
1160
+ return `${head} at ${fileName}:${line}:${column}`;
1161
+ if (line > 0 || column > 0)
1162
+ return `${head} at ${line}:${column}`;
1163
+ return head;
1164
+ }
1165
+ function checkMemoryLimit(exports, limit) {
1166
+ const memory = exportedMemory(exports);
1167
+ if (!memory)
1168
+ return;
1169
+ if (memory.buffer.byteLength > limit) {
1170
+ throw new Error(`WRUN memory ${memory.buffer.byteLength} bytes exceeds limit ${limit} bytes`);
1171
+ }
1172
+ }
1173
+ function checkMemoryGrowth(exports, baselineBytes) {
1174
+ const currentBytes = exportedMemoryByteLength(exports);
1175
+ if (currentBytes === null || baselineBytes === null)
1176
+ return;
1177
+ if (currentBytes > baselineBytes) {
1178
+ throw new Error(`WRUN memory grew from ${baselineBytes} to ${currentBytes} bytes after init; allocate persistent state in init and keep per-bar state/finalize work allocation-free`);
1179
+ }
1180
+ }
1181
+ /** The buffer whose own length vouches that the memory has not grown since:
1182
+ * a non-shared memory's, because every growth (a memory.grow(0) included)
1183
+ * detaches the buffer the memory had and a detached buffer's byteLength
1184
+ * reads 0. Null for a shared memory (its old buffer keeps its length; read
1185
+ * by tag, so a buffer from another realm answers the same) and for a
1186
+ * zero-byte one (detached or not, it reads 0). */
1187
+ function growthWitness(memory) {
1188
+ if (memory === null)
1189
+ return null;
1190
+ const buffer = memory.buffer;
1191
+ return buffer.byteLength > 0 && Object.prototype.toString.call(buffer) === '[object ArrayBuffer]' ? buffer : null;
1192
+ }
1193
+ function exportedMemoryByteLength(exports) {
1194
+ const memory = exportedMemory(exports);
1195
+ return memory ? memory.buffer.byteLength : null;
1196
+ }
1197
+ function requireFunction(value, name) {
1198
+ if (typeof value !== 'function')
1199
+ throw new Error(`WRUN module missing function export '${name}'`);
1200
+ return value;
1201
+ }