@orangecharts/wrun-chart-host 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +72 -0
  2. package/dist/constants/governed-exchanges.constants.d.ts +11 -0
  3. package/dist/constants/governed-exchanges.constants.js +11 -0
  4. package/dist/constants/indicator-sets.constants.d.ts +8 -0
  5. package/dist/constants/indicator-sets.constants.js +8 -0
  6. package/dist/constants/interval.constants.d.ts +34 -0
  7. package/dist/constants/interval.constants.js +121 -0
  8. package/dist/constants/scriptEditor/technicalIndicatorScriptKeys.constants.d.ts +28 -0
  9. package/dist/constants/scriptEditor/technicalIndicatorScriptKeys.constants.js +65 -0
  10. package/dist/constants/tpo-color-schemes.constants.d.ts +30 -0
  11. package/dist/constants/tpo-color-schemes.constants.js +32 -0
  12. package/dist/host-env.d.ts +102 -0
  13. package/dist/host-env.js +26 -0
  14. package/dist/index.d.ts +93 -0
  15. package/dist/index.js +96 -0
  16. package/dist/indicators/controls/tpo-letter.util.d.ts +2 -0
  17. package/dist/indicators/controls/tpo-letter.util.js +13 -0
  18. package/dist/indicators/controls/tpo-session.util.d.ts +99 -0
  19. package/dist/indicators/controls/tpo-session.util.js +389 -0
  20. package/dist/interfaces/kscript-diagnostics.interface.d.ts +64 -0
  21. package/dist/interfaces/kscript-diagnostics.interface.js +1 -0
  22. package/dist/interfaces/om-panel-data.interface.d.ts +103 -0
  23. package/dist/interfaces/om-panel-data.interface.js +7 -0
  24. package/dist/interfaces/wrun-runtime.interface.d.ts +2659 -0
  25. package/dist/interfaces/wrun-runtime.interface.js +55 -0
  26. package/dist/utility/chart/calendar-interval.util.d.ts +24 -0
  27. package/dist/utility/chart/calendar-interval.util.js +81 -0
  28. package/dist/utility/chart/candle-bar-end.util.d.ts +15 -0
  29. package/dist/utility/chart/candle-bar-end.util.js +23 -0
  30. package/dist/utility/chart/cme-realtime.util.d.ts +24 -0
  31. package/dist/utility/chart/cme-realtime.util.js +53 -0
  32. package/dist/utility/chart/interval-ladder.util.d.ts +27 -0
  33. package/dist/utility/chart/interval-ladder.util.js +92 -0
  34. package/dist/utility/chart/kscript-drawing-prep.util.d.ts +40 -0
  35. package/dist/utility/chart/kscript-drawing-prep.util.js +184 -0
  36. package/dist/utility/chart/kscript-drawing-safe-area.util.d.ts +95 -0
  37. package/dist/utility/chart/kscript-drawing-safe-area.util.js +805 -0
  38. package/dist/utility/chart/kscript-legend-entries.util.d.ts +166 -0
  39. package/dist/utility/chart/kscript-legend-entries.util.js +538 -0
  40. package/dist/utility/chart/kscript-output-role.util.d.ts +32 -0
  41. package/dist/utility/chart/kscript-output-role.util.js +215 -0
  42. package/dist/utility/chart/kscript-provenance-keys.util.d.ts +22 -0
  43. package/dist/utility/chart/kscript-provenance-keys.util.js +56 -0
  44. package/dist/utility/chart/kscript-run-result-normalize.util.d.ts +53 -0
  45. package/dist/utility/chart/kscript-run-result-normalize.util.js +476 -0
  46. package/dist/utility/chart/kscript-run-result-shape.util.d.ts +14 -0
  47. package/dist/utility/chart/kscript-run-result-shape.util.js +66 -0
  48. package/dist/utility/chart/kscript-titancharts-container.util.d.ts +29 -0
  49. package/dist/utility/chart/kscript-titancharts-container.util.js +151 -0
  50. package/dist/utility/chart/kscript-viewport-overlays.util.d.ts +83 -0
  51. package/dist/utility/chart/kscript-viewport-overlays.util.js +443 -0
  52. package/dist/utility/chart/om-panel-push-style.util.d.ts +78 -0
  53. package/dist/utility/chart/om-panel-push-style.util.js +301 -0
  54. package/dist/utility/chart/om-panel.util.d.ts +166 -0
  55. package/dist/utility/chart/om-panel.util.js +815 -0
  56. package/dist/utility/chart/om-series.util.d.ts +42 -0
  57. package/dist/utility/chart/om-series.util.js +330 -0
  58. package/dist/utility/chart/om-target.util.d.ts +11 -0
  59. package/dist/utility/chart/om-target.util.js +24 -0
  60. package/dist/utility/chart/om-widget.util.d.ts +148 -0
  61. package/dist/utility/chart/om-widget.util.js +413 -0
  62. package/dist/utility/chart/overlay-output-budget.util.d.ts +16 -0
  63. package/dist/utility/chart/overlay-output-budget.util.js +109 -0
  64. package/dist/utility/chart/overlay-paint-flags.util.d.ts +24 -0
  65. package/dist/utility/chart/overlay-paint-flags.util.js +55 -0
  66. package/dist/utility/chart/profile-row-height.util.d.ts +21 -0
  67. package/dist/utility/chart/profile-row-height.util.js +110 -0
  68. package/dist/utility/chart/session-interval.util.d.ts +1 -0
  69. package/dist/utility/chart/session-interval.util.js +35 -0
  70. package/dist/utility/chart/technical-script-legend-value.util.d.ts +18 -0
  71. package/dist/utility/chart/technical-script-legend-value.util.js +53 -0
  72. package/dist/utility/chart/trading-day.util.d.ts +70 -0
  73. package/dist/utility/chart/trading-day.util.js +238 -0
  74. package/dist/utility/chart/wrun-legend-name.util.d.ts +25 -0
  75. package/dist/utility/chart/wrun-legend-name.util.js +87 -0
  76. package/dist/utility/chart/wrun-run-result.util.d.ts +977 -0
  77. package/dist/utility/chart/wrun-run-result.util.js +5179 -0
  78. package/dist/utility/chart/wrun-visibility-chart.util.d.ts +25 -0
  79. package/dist/utility/chart/wrun-visibility-chart.util.js +22 -0
  80. package/dist/utility/indicators/heatmap-sensitivity.util.d.ts +62 -0
  81. package/dist/utility/indicators/heatmap-sensitivity.util.js +82 -0
  82. package/dist/utility/number-format.util.d.ts +68 -0
  83. package/dist/utility/number-format.util.js +188 -0
  84. package/dist/utility/v2/opra-governed.util.d.ts +1 -0
  85. package/dist/utility/v2/opra-governed.util.js +13 -0
  86. package/dist/utility/wrun/wrun-auto-row.util.d.ts +54 -0
  87. package/dist/utility/wrun/wrun-auto-row.util.js +96 -0
  88. package/dist/utility/wrun/wrun-batched-marks.util.d.ts +341 -0
  89. package/dist/utility/wrun/wrun-batched-marks.util.js +938 -0
  90. package/dist/utility/wrun/wrun-batched-readout.util.d.ts +75 -0
  91. package/dist/utility/wrun/wrun-batched-readout.util.js +171 -0
  92. package/dist/utility/wrun/wrun-box-segment.util.d.ts +185 -0
  93. package/dist/utility/wrun/wrun-box-segment.util.js +570 -0
  94. package/dist/utility/wrun/wrun-build-memo.util.d.ts +133 -0
  95. package/dist/utility/wrun/wrun-build-memo.util.js +301 -0
  96. package/dist/utility/wrun/wrun-builtin-twin-ports.util.d.ts +25 -0
  97. package/dist/utility/wrun/wrun-builtin-twin-ports.util.js +75 -0
  98. package/dist/utility/wrun/wrun-builtin-twin.util.d.ts +9 -0
  99. package/dist/utility/wrun/wrun-builtin-twin.util.js +40 -0
  100. package/dist/utility/wrun/wrun-canvas-cache.util.d.ts +28 -0
  101. package/dist/utility/wrun/wrun-canvas-cache.util.js +56 -0
  102. package/dist/utility/wrun/wrun-canvas-readout.util.d.ts +69 -0
  103. package/dist/utility/wrun/wrun-canvas-readout.util.js +53 -0
  104. package/dist/utility/wrun/wrun-canvases.util.d.ts +295 -0
  105. package/dist/utility/wrun/wrun-canvases.util.js +1432 -0
  106. package/dist/utility/wrun/wrun-cap-notice.util.d.ts +77 -0
  107. package/dist/utility/wrun/wrun-cap-notice.util.js +296 -0
  108. package/dist/utility/wrun/wrun-card-style.util.d.ts +154 -0
  109. package/dist/utility/wrun/wrun-card-style.util.js +539 -0
  110. package/dist/utility/wrun/wrun-chart-context.util.d.ts +89 -0
  111. package/dist/utility/wrun/wrun-chart-context.util.js +213 -0
  112. package/dist/utility/wrun/wrun-chart-names.util.d.ts +23 -0
  113. package/dist/utility/wrun/wrun-chart-names.util.js +33 -0
  114. package/dist/utility/wrun/wrun-chart-time.util.d.ts +12 -0
  115. package/dist/utility/wrun/wrun-chart-time.util.js +23 -0
  116. package/dist/utility/wrun/wrun-child-overlay-id.util.d.ts +13 -0
  117. package/dist/utility/wrun/wrun-child-overlay-id.util.js +44 -0
  118. package/dist/utility/wrun/wrun-color-facts.util.d.ts +40 -0
  119. package/dist/utility/wrun/wrun-color-facts.util.js +88 -0
  120. package/dist/utility/wrun/wrun-color-settings.lazy.d.ts +26 -0
  121. package/dist/utility/wrun/wrun-color-settings.lazy.js +9 -0
  122. package/dist/utility/wrun/wrun-color-settings.util.d.ts +351 -0
  123. package/dist/utility/wrun/wrun-color-settings.util.js +1363 -0
  124. package/dist/utility/wrun/wrun-footprint-modes.util.d.ts +23 -0
  125. package/dist/utility/wrun/wrun-footprint-modes.util.js +24 -0
  126. package/dist/utility/wrun/wrun-frames.d.ts +217 -0
  127. package/dist/utility/wrun/wrun-frames.js +1021 -0
  128. package/dist/utility/wrun/wrun-handles.util.d.ts +792 -0
  129. package/dist/utility/wrun/wrun-handles.util.js +2050 -0
  130. package/dist/utility/wrun/wrun-heatmap-cell-budget.util.d.ts +156 -0
  131. package/dist/utility/wrun/wrun-heatmap-cell-budget.util.js +342 -0
  132. package/dist/utility/wrun/wrun-hosted-wire-caps.d.ts +218 -0
  133. package/dist/utility/wrun/wrun-hosted-wire-caps.js +667 -0
  134. package/dist/utility/wrun/wrun-hosted-wire.util.d.ts +40 -0
  135. package/dist/utility/wrun/wrun-hosted-wire.util.js +27 -0
  136. package/dist/utility/wrun/wrun-hover.util.d.ts +182 -0
  137. package/dist/utility/wrun/wrun-hover.util.js +534 -0
  138. package/dist/utility/wrun/wrun-hud-looks.util.d.ts +246 -0
  139. package/dist/utility/wrun/wrun-hud-looks.util.js +587 -0
  140. package/dist/utility/wrun/wrun-integration-budget.util.d.ts +47 -0
  141. package/dist/utility/wrun/wrun-integration-budget.util.js +122 -0
  142. package/dist/utility/wrun/wrun-latest-snapshot.d.ts +19 -0
  143. package/dist/utility/wrun/wrun-latest-snapshot.js +7 -0
  144. package/dist/utility/wrun/wrun-levels-child.util.d.ts +131 -0
  145. package/dist/utility/wrun/wrun-levels-child.util.js +514 -0
  146. package/dist/utility/wrun/wrun-lifecycle.contract.d.ts +75 -0
  147. package/dist/utility/wrun/wrun-lifecycle.contract.js +9 -0
  148. package/dist/utility/wrun/wrun-market-facts.util.d.ts +116 -0
  149. package/dist/utility/wrun/wrun-market-facts.util.js +238 -0
  150. package/dist/utility/wrun/wrun-output-style.util.d.ts +344 -0
  151. package/dist/utility/wrun/wrun-output-style.util.js +1239 -0
  152. package/dist/utility/wrun/wrun-overlay-identity.util.d.ts +84 -0
  153. package/dist/utility/wrun/wrun-overlay-identity.util.js +142 -0
  154. package/dist/utility/wrun/wrun-overlay-result.util.d.ts +120 -0
  155. package/dist/utility/wrun/wrun-overlay-result.util.js +219 -0
  156. package/dist/utility/wrun/wrun-pack.util.d.ts +70 -0
  157. package/dist/utility/wrun/wrun-pack.util.js +301 -0
  158. package/dist/utility/wrun/wrun-pane-format.util.d.ts +180 -0
  159. package/dist/utility/wrun/wrun-pane-format.util.js +299 -0
  160. package/dist/utility/wrun/wrun-panel-style.lazy.d.ts +25 -0
  161. package/dist/utility/wrun/wrun-panel-style.lazy.js +15 -0
  162. package/dist/utility/wrun/wrun-panel-style.util.d.ts +174 -0
  163. package/dist/utility/wrun/wrun-panel-style.util.js +726 -0
  164. package/dist/utility/wrun/wrun-param-values.util.d.ts +69 -0
  165. package/dist/utility/wrun/wrun-param-values.util.js +230 -0
  166. package/dist/utility/wrun/wrun-refusal.util.d.ts +263 -0
  167. package/dist/utility/wrun/wrun-refusal.util.js +1259 -0
  168. package/dist/utility/wrun/wrun-registry-errors.util.d.ts +199 -0
  169. package/dist/utility/wrun/wrun-registry-errors.util.js +257 -0
  170. package/dist/utility/wrun/wrun-render-select.util.d.ts +336 -0
  171. package/dist/utility/wrun/wrun-render-select.util.js +1157 -0
  172. package/dist/utility/wrun/wrun-script-inputs.util.d.ts +434 -0
  173. package/dist/utility/wrun/wrun-script-inputs.util.js +1971 -0
  174. package/dist/utility/wrun/wrun-setting-words.lazy.d.ts +20 -0
  175. package/dist/utility/wrun/wrun-setting-words.lazy.js +9 -0
  176. package/dist/utility/wrun/wrun-setting-words.util.d.ts +79 -0
  177. package/dist/utility/wrun/wrun-setting-words.util.js +176 -0
  178. package/dist/utility/wrun/wrun-socket-row-store.d.ts +98 -0
  179. package/dist/utility/wrun/wrun-socket-row-store.js +417 -0
  180. package/dist/utility/wrun/wrun-style-flags.util.d.ts +18 -0
  181. package/dist/utility/wrun/wrun-style-flags.util.js +21 -0
  182. package/dist/utility/wrun/wrun-style-words.util.d.ts +148 -0
  183. package/dist/utility/wrun/wrun-style-words.util.js +439 -0
  184. package/dist/utility/wrun/wrun-table-look.util.d.ts +125 -0
  185. package/dist/utility/wrun/wrun-table-look.util.js +225 -0
  186. package/dist/utility/wrun/wrun-text-look.util.d.ts +51 -0
  187. package/dist/utility/wrun/wrun-text-look.util.js +227 -0
  188. package/dist/utility/wrun/wrun-text-params.util.d.ts +106 -0
  189. package/dist/utility/wrun/wrun-text-params.util.js +171 -0
  190. package/dist/utility/wrun/wrun-tpo-rows.util.d.ts +71 -0
  191. package/dist/utility/wrun/wrun-tpo-rows.util.js +438 -0
  192. package/dist/utility/wrun/wrun-twin-compute-inputs.util.d.ts +14 -0
  193. package/dist/utility/wrun/wrun-twin-compute-inputs.util.js +58 -0
  194. package/dist/utility/wrun/wrun-visibility-table.d.ts +437 -0
  195. package/dist/utility/wrun/wrun-visibility-table.js +237 -0
  196. package/dist/utility/wrun/wrun-volume-profile.util.d.ts +37 -0
  197. package/dist/utility/wrun/wrun-volume-profile.util.js +278 -0
  198. package/package.json +38 -0
@@ -0,0 +1,2050 @@
1
+ /**
2
+ * Indicator handles (ABI wrun-3, contract OM-WRUN3-DRAWINGS-CONTRACT.md
3
+ * sections 2, 6 and 7; WRUN-STYLE group 4 and Appendix C): the sheet's
4
+ * `handles` section, the runtime handle ledger the sandbox worker drives
5
+ * from the draw channel (`wrun_draw_*`), and the ledger's wire records,
6
+ * which are the kScript engine's own `DrawingObject` records so
7
+ * `kscript-drawings.util.ts` and titan's `updateDrawings` need no change.
8
+ *
9
+ * A handle is a drawing the module keys by an `i32` id and creates, mutates
10
+ * or deletes across bars. Every draw call during a row's `finalize()` is one
11
+ * op against the ledger (`Map<id, {kind, props, createdBar, mutatedBar,
12
+ * seq}>`): a geometry call on an unknown id creates (style from the sheet
13
+ * defaults, `createdBar = mutatedBar = row`, `seq` = creation index), on a
14
+ * known id of the same kind mutates (`mutatedBar = row`), on another kind
15
+ * skips; a style or color call on a known id mutates, on an unknown id
16
+ * skips; delete removes without a stamp and frees the id for a later row.
17
+ * The ledger is a pure function of the rows, so a full run from row 0
18
+ * rebuilds it; a live session keeps it bit-identical to a full run through
19
+ * the journal (the ops since the last snapshot, undone on restore) and the
20
+ * worker's close-confirm re-evaluation.
21
+ *
22
+ * Skipped calls (om docs/WRUN3_ABI.md "Skipped calls", 2026-10-15): a call
23
+ * one bar's values cannot carry (a non-finite coordinate, a style value out
24
+ * of range, a missing handle, an unwritten label slot, an empty polyline, a
25
+ * kind mismatch: WRUN3_DRAW_SKIP_CODES) is skipped and recorded, and the run
26
+ * goes on; a limit or a mistake the code makes on every bar
27
+ * (WRUN3_DRAW_FATAL_CODES) still refuses the evaluation by name. Every fatal
28
+ * check of a call runs before its skip checks, so a skip never bypasses a
29
+ * refusal. The om reference worker, the kit host and kscript-backend split
30
+ * the codes the same way; the handle-ledger corpus pins it.
31
+ *
32
+ * WRUN-STYLE (2026-10-03, Appendix C, wrun-3 additive): style props 10..30
33
+ * (word, slot and numeric looks), colour props 2..6, the pre-round props
34
+ * widened to more kinds, `wrun_draw_label` slot -1 (a label with no text, a
35
+ * mark), slot props read through the host's slot reader, and theme tokens
36
+ * riding the wire as `theme.<t>` / `theme.<t>/aa` (the foundation's
37
+ * `wrunDrawColorWire`). The sheet side (g4 section 2.1) adds the look keys
38
+ * to every `handles.<kind>` entry and to the geometry drawings; ONE mapper,
39
+ * `wrunDrawingStyleWire`, turns those sheet keys into wire props for the
40
+ * declared-drawing adapter, and `wrunHandleInitialProps` reuses it for a new
41
+ * handle's initial props.
42
+ *
43
+ * Environment-agnostic on purpose: the worker and the Node specs run this
44
+ * same code, and nothing here touches the DOM or a store. Theme tokens are
45
+ * never resolved here: they ride the wire as words and resolve at the mount
46
+ * doors (wrun-style-words.util.ts, TH-theme-tokens).
47
+ *
48
+ * The wrun-3 vocabulary below (import names, prop enums, caps, refusal
49
+ * names, sheet defaults) mirrors `@openmarket/sdk` `wrun-wasm-abi.ts` and
50
+ * `wrun-metadata-schema.ts` verbatim. The indicator kit
51
+ * (the `@orangecharts/indicator-kit` package, since scaffold 9) exports the same names, but
52
+ * this module runs inside the sandbox worker and the Node specs, where
53
+ * pulling the 1 MB kit bundle in for a few constants is not worth it. The
54
+ * existing values must never drift from the kit's: `wrun-handles.kit-mirror.spec.ts`
55
+ * pins them to the kit exports and separately pins the additive Appendix C
56
+ * contract until the kit is re-vendored. A changed cap, range or default
57
+ * fails there by name.
58
+ */
59
+ import { wrunAbiVersion } from './wrun-pack.util.js';
60
+ import { abiAtLeast } from '../../interfaces/wrun-runtime.interface.js';
61
+ import { utf8ByteLength, WRUN_RENDER_RESULT_LIMIT_BYTES } from './wrun-render-select.util.js';
62
+ import { isWrunColorWord, parseWrunThemeToken, WRUN_FONT_FAMILIES, WRUN_FONT_WEIGHTS, WRUN_THEME_COLOR_TOKENS, wrunDrawColorWire, wrunThemeTokenWithAlpha, } from './wrun-style-words.util.js';
63
+ // ---------------------------------------------------------------------------
64
+ // ABI vocabulary (mirror of the SDK's wrun-wasm-abi.ts).
65
+ // ---------------------------------------------------------------------------
66
+ export const WRUN3_HANDLE_KINDS = ['line', 'box', 'label', 'polyline'];
67
+ /** Style prop 7 uses 1-based indexes; 0 restores chart coordinates. */
68
+ export const WRUN_DRAWING_ANCHORS = [
69
+ 'top_left',
70
+ 'top_center',
71
+ 'top_right',
72
+ 'middle_left',
73
+ 'middle_center',
74
+ 'middle_right',
75
+ 'bottom_left',
76
+ 'bottom_center',
77
+ 'bottom_right',
78
+ 'top',
79
+ 'bottom',
80
+ 'left',
81
+ 'right',
82
+ ];
83
+ /** Label text alignment words (which edge of the text sits on x); absent is
84
+ * centred. Style prop 8 uses 1-based indexes; 0 clears the word. Labels and
85
+ * (box text, DW31) boxes. */
86
+ export const WRUN_LABEL_ALIGNS = ['left', 'center', 'right'];
87
+ /** `wrun_draw_style(id, prop, value)`: the prop enum. `fill_to` (lines only)
88
+ * shades from the line to another line: the value is the other line's
89
+ * handle id, -1 clears; the fill colour is the line's `fill` colour prop
90
+ * (its alpha the fill opacity). Props 10..30 (WRUN-STYLE, Appendix C) are
91
+ * wrun-3 additive like `fill_to`: no new import, refusal name or ABI
92
+ * version. */
93
+ export const WRUN3_STYLE_PROPS = {
94
+ width: 0,
95
+ line_style: 1,
96
+ opacity: 2,
97
+ size: 3,
98
+ extend: 4,
99
+ border_width: 5,
100
+ zorder: 6,
101
+ anchor: 7,
102
+ align: 8,
103
+ fill_to: 9,
104
+ font_weight: 10,
105
+ font_family: 11,
106
+ valign: 12,
107
+ padding: 13,
108
+ max_width: 14,
109
+ corner_radius: 15,
110
+ glow: 16,
111
+ label_style: 17,
112
+ emblem_shape: 18,
113
+ sticky_right: 19,
114
+ axis_label: 20,
115
+ tooltip_slot: 21,
116
+ text_slot: 22,
117
+ group: 23,
118
+ fit_group: 24,
119
+ box_shape: 25,
120
+ gradient_direction: 26,
121
+ arrow: 27,
122
+ closed: 28,
123
+ smooth: 29,
124
+ angle: 30,
125
+ };
126
+ /** `line_style` values by enum index. */
127
+ export const WRUN3_LINE_STYLES = ['solid', 'dashed', 'dotted'];
128
+ /** `extend` values by enum index. */
129
+ export const WRUN3_EXTENDS = ['none', 'left', 'right', 'both'];
130
+ // Word props: a 1-based index into the vocabulary selects a word, 0 clears
131
+ // the prop (the wire key is deleted). The vocabularies are the sheet's words
132
+ // without the sheet's "none" / default entry, which the 0 stands for.
133
+ /** `label_style` (17): 1 box, 2 plain, 3 knockout, 4 emblem, 5 pill, 6 badge, 7 callout. */
134
+ export const WRUN3_LABEL_STYLES = ['box', 'plain', 'knockout', 'emblem', 'pill', 'badge', 'callout'];
135
+ /** `emblem_shape` (18): 1 dot, 2 square, 3 diamond, 4 triangle_up, 5 triangle_down. */
136
+ export const WRUN3_EMBLEM_SHAPES = ['dot', 'square', 'diamond', 'triangle_up', 'triangle_down'];
137
+ /** `axis_label` (20): 1 price, 2 text (a line stops at 1: it has no text). */
138
+ export const WRUN3_AXIS_LABELS = ['price', 'text'];
139
+ /** `arrow` (27): 1 start, 2 end, 3 both. */
140
+ export const WRUN3_ARROWS = ['start', 'end', 'both'];
141
+ /** `box_shape` (25): 1 rect, 2 ellipse; only "ellipse" rides the wire (rect
142
+ * is the default and deletes the key like 0). */
143
+ export const WRUN3_BOX_SHAPES = ['rect', 'ellipse'];
144
+ /** `valign` (12) words and the sheet's `valign` key (freeze 2.1, WRUN_VALIGNS). */
145
+ export const WRUN_VALIGNS = ['top', 'middle', 'bottom'];
146
+ /** `gradient_direction` (26) words and the sheet key (freeze 2.1). */
147
+ export const WRUN_GRADIENT_DIRECTIONS = ['vertical', 'horizontal'];
148
+ /** `font_weight` (10) words (`WRUN_FONT_WEIGHTS`: 1 normal, 2 medium, 3 bold)
149
+ * reach the wire as the CSS weights the engine reads. */
150
+ export const WRUN3_FONT_WEIGHT_CSS = {
151
+ normal: 400,
152
+ medium: 500,
153
+ bold: 700,
154
+ };
155
+ /** The sheet's own word lists for the g4 keys (the ABI vocabularies above
156
+ * plus their "none" / default entry, which the ABI's 0 stands for). */
157
+ export const WRUN_LABEL_LOOKS = WRUN3_LABEL_STYLES;
158
+ export const WRUN_EMBLEM_SHAPES = WRUN3_EMBLEM_SHAPES;
159
+ export const WRUN_AXIS_LABELS = ['none', 'price', 'text'];
160
+ export const WRUN_ARROWS = ['none', 'start', 'end', 'both'];
161
+ export const WRUN_BOX_SHAPES = WRUN3_BOX_SHAPES;
162
+ /** The numeric ranges of the look props, the contract's (px unless named).
163
+ * Validation ranges only, the kit's: a value past one refuses by name. The
164
+ * mount caps of the LABELS contract (label and box text at 256 characters,
165
+ * ellipsized; zorder clamped to -100..100; 16 widgets per overlay per pane)
166
+ * are applied at the drawing door instead (kscript-drawing-caps.util.ts) and
167
+ * never refuse a sheet or an op that validates here. */
168
+ export const WRUN_CORNER_RADIUS_MAX = 32;
169
+ export const WRUN3_MAX_PADDING_PX = 64;
170
+ export const WRUN3_MAX_LABEL_WIDTH_PX = 2000;
171
+ /** Glow's validation range (the kit's), and the ceiling every wrun glow
172
+ * lands at: the run-result adapter holds a handle's glow to it like an
173
+ * output's (PLOTS-2, `landWrunGlowPx` in wrun-output-style.util). */
174
+ export const WRUN3_MAX_GLOW_PX = 32;
175
+ export const WRUN3_MAX_LABEL_ANGLE_DEG = 90;
176
+ /** `group` (23) and `fit_group` (24): an integer 1..65535 names a group, 0 leaves it. */
177
+ export const WRUN3_MAX_GROUP_ID = 65535;
178
+ /** `wrun_draw_label(id, x, y, slot)` with this slot draws a label with no
179
+ * text (text "", no slot is read): a mark. Any other negative slot keeps
180
+ * refusing `wrun_draw_label_slot_undeclared`. The same value clears a slot
181
+ * prop (tooltip_slot, text_slot). */
182
+ export const NO_TEXT_SLOT = -1;
183
+ /** Per-prop legality and range, the engine's setter table (Appendix C: the
184
+ * pre-round props widen, `line_style` to box as `borderStyle`, `opacity`
185
+ * and `zorder` to polyline, `size` to box as `textSize`, `extend` and
186
+ * `align` to box, `border_width` to label; props 10..30 join). */
187
+ export const WRUN3_STYLE_PROP_SPECS = [
188
+ { prop: WRUN3_STYLE_PROPS.width, name: 'width', kinds: ['line', 'polyline'], min: 0.5, max: 20 },
189
+ {
190
+ prop: WRUN3_STYLE_PROPS.line_style,
191
+ name: 'line_style',
192
+ kinds: ['line', 'polyline', 'box'],
193
+ integer: true,
194
+ values: WRUN3_LINE_STYLES,
195
+ },
196
+ { prop: WRUN3_STYLE_PROPS.opacity, name: 'opacity', kinds: ['line', 'box', 'label', 'polyline'], min: 0, max: 1 },
197
+ { prop: WRUN3_STYLE_PROPS.size, name: 'size', kinds: ['label', 'box'], min: 6, max: 64, integer: true },
198
+ { prop: WRUN3_STYLE_PROPS.extend, name: 'extend', kinds: ['line', 'box'], integer: true, values: WRUN3_EXTENDS },
199
+ { prop: WRUN3_STYLE_PROPS.border_width, name: 'border_width', kinds: ['box', 'label'], min: 0, max: 10 },
200
+ // Any integer validates (the kit's range); the drawing door clamps it to -100..100 at mount.
201
+ { prop: WRUN3_STYLE_PROPS.zorder, name: 'zorder', kinds: ['line', 'box', 'label', 'polyline'], integer: true },
202
+ { prop: WRUN3_STYLE_PROPS.anchor, name: 'anchor', kinds: WRUN3_HANDLE_KINDS, integer: true, min: 0, max: 13 },
203
+ { prop: WRUN3_STYLE_PROPS.align, name: 'align', kinds: ['label', 'box'], integer: true, min: 0, max: 3 },
204
+ { prop: WRUN3_STYLE_PROPS.fill_to, name: 'fill_to', kinds: ['line'], integer: true, min: -1, target: 'line' },
205
+ {
206
+ prop: WRUN3_STYLE_PROPS.font_weight,
207
+ name: 'font_weight',
208
+ kinds: ['label', 'box'],
209
+ integer: true,
210
+ words: WRUN_FONT_WEIGHTS,
211
+ },
212
+ {
213
+ prop: WRUN3_STYLE_PROPS.font_family,
214
+ name: 'font_family',
215
+ kinds: ['label', 'box'],
216
+ integer: true,
217
+ words: WRUN_FONT_FAMILIES,
218
+ },
219
+ { prop: WRUN3_STYLE_PROPS.valign, name: 'valign', kinds: ['label', 'box'], integer: true, words: WRUN_VALIGNS },
220
+ { prop: WRUN3_STYLE_PROPS.padding, name: 'padding', kinds: ['label', 'box'], min: 0, max: WRUN3_MAX_PADDING_PX },
221
+ { prop: WRUN3_STYLE_PROPS.max_width, name: 'max_width', kinds: ['label'], min: 0, max: WRUN3_MAX_LABEL_WIDTH_PX },
222
+ {
223
+ prop: WRUN3_STYLE_PROPS.corner_radius,
224
+ name: 'corner_radius',
225
+ kinds: ['label', 'box'],
226
+ min: 0,
227
+ max: WRUN_CORNER_RADIUS_MAX,
228
+ },
229
+ {
230
+ prop: WRUN3_STYLE_PROPS.glow,
231
+ name: 'glow',
232
+ kinds: ['line', 'box', 'label', 'polyline'],
233
+ min: 0,
234
+ max: WRUN3_MAX_GLOW_PX,
235
+ },
236
+ {
237
+ prop: WRUN3_STYLE_PROPS.label_style,
238
+ name: 'label_style',
239
+ kinds: ['label'],
240
+ integer: true,
241
+ words: WRUN3_LABEL_STYLES,
242
+ },
243
+ {
244
+ prop: WRUN3_STYLE_PROPS.emblem_shape,
245
+ name: 'emblem_shape',
246
+ kinds: ['label'],
247
+ integer: true,
248
+ words: WRUN3_EMBLEM_SHAPES,
249
+ },
250
+ {
251
+ prop: WRUN3_STYLE_PROPS.sticky_right,
252
+ name: 'sticky_right',
253
+ kinds: ['line', 'label'],
254
+ integer: true,
255
+ min: 0,
256
+ max: 1,
257
+ },
258
+ {
259
+ prop: WRUN3_STYLE_PROPS.axis_label,
260
+ name: 'axis_label',
261
+ kinds: ['line', 'label'],
262
+ integer: true,
263
+ words: WRUN3_AXIS_LABELS,
264
+ maxByKind: { line: 1, label: 2 },
265
+ },
266
+ {
267
+ prop: WRUN3_STYLE_PROPS.tooltip_slot,
268
+ name: 'tooltip_slot',
269
+ kinds: ['line', 'box', 'label', 'polyline'],
270
+ integer: true,
271
+ slot: true,
272
+ },
273
+ { prop: WRUN3_STYLE_PROPS.text_slot, name: 'text_slot', kinds: ['box'], integer: true, slot: true },
274
+ { prop: WRUN3_STYLE_PROPS.group, name: 'group', kinds: ['label'], integer: true, min: 0, max: WRUN3_MAX_GROUP_ID },
275
+ {
276
+ prop: WRUN3_STYLE_PROPS.fit_group,
277
+ name: 'fit_group',
278
+ kinds: ['box'],
279
+ integer: true,
280
+ min: 0,
281
+ max: WRUN3_MAX_GROUP_ID,
282
+ },
283
+ { prop: WRUN3_STYLE_PROPS.box_shape, name: 'box_shape', kinds: ['box'], integer: true, words: WRUN3_BOX_SHAPES },
284
+ {
285
+ prop: WRUN3_STYLE_PROPS.gradient_direction,
286
+ name: 'gradient_direction',
287
+ kinds: ['box'],
288
+ integer: true,
289
+ words: WRUN_GRADIENT_DIRECTIONS,
290
+ },
291
+ { prop: WRUN3_STYLE_PROPS.arrow, name: 'arrow', kinds: ['line', 'polyline'], integer: true, words: WRUN3_ARROWS },
292
+ { prop: WRUN3_STYLE_PROPS.closed, name: 'closed', kinds: ['polyline'], integer: true, min: 0, max: 1 },
293
+ { prop: WRUN3_STYLE_PROPS.smooth, name: 'smooth', kinds: ['polyline'], integer: true, min: 0, max: 1 },
294
+ {
295
+ prop: WRUN3_STYLE_PROPS.angle,
296
+ name: 'angle',
297
+ kinds: ['label'],
298
+ min: -WRUN3_MAX_LABEL_ANGLE_DEG,
299
+ max: WRUN3_MAX_LABEL_ANGLE_DEG,
300
+ },
301
+ ];
302
+ /** The props whose 0 (or -1) clears rather than sets: anchor, align, the
303
+ * target prop and every word and slot prop. A non-finite value on one of
304
+ * these skips by the range name (`wrun_draw_style_out_of_range`), as a
305
+ * value outside the table does; on a plain numeric prop it skips
306
+ * `wrun_draw_non_finite` (the om reference ledger's rule). */
307
+ export function wrunDrawStylePropClears(spec) {
308
+ return (spec.name === 'anchor' ||
309
+ spec.name === 'align' ||
310
+ spec.target !== undefined ||
311
+ spec.words !== undefined ||
312
+ spec.slot === true);
313
+ }
314
+ /** `wrun_draw_color(id, prop, rgba)`: the prop enum. `rgba` is `0xRRGGBBAA`
315
+ * as an i32 bit pattern; a theme token sentinel (alpha byte 0x00, red byte
316
+ * 0x7e, green byte 1..7, the token's alpha in the blue byte; see the
317
+ * foundation's `wrunThemeTokenOfI32`) rides the wire as `theme.<t>` /
318
+ * `theme.<t>/aa` through `wrunDrawColorWire`, every other value as
319
+ * `rgba(r,g,b,a)`. `stroke` is a line's, polyline's or label's `color` and
320
+ * a box's `borderColor`; `fill` is a box's `backgroundColor` (and
321
+ * `fillColor`), a label's `backgroundColor`, a polyline's `fillColor` (its
322
+ * polygon fill) and a line's fill toward its `fill_to` line (`fillColor`,
323
+ * on the wire only while a target is set; alpha is the fill's opacity);
324
+ * `border` is a label's `border`; `glow` is every kind's `glowColor`;
325
+ * `emblem` a label's `emblemColor`; `gradient_end` a box's `gradient:
326
+ * [backgroundColor at the call, end]` (and `gradientDirection: "vertical"`
327
+ * when unset); `text` a box's `textColor`. */
328
+ export const WRUN3_COLOR_PROPS = {
329
+ stroke: 0,
330
+ fill: 1,
331
+ border: 2,
332
+ glow: 3,
333
+ emblem: 4,
334
+ gradient_end: 5,
335
+ text: 6,
336
+ };
337
+ /** Per-prop legality for the colour channel. */
338
+ export const WRUN3_COLOR_PROP_SPECS = [
339
+ { prop: WRUN3_COLOR_PROPS.stroke, name: 'stroke', kinds: ['line', 'box', 'label', 'polyline'] },
340
+ { prop: WRUN3_COLOR_PROPS.fill, name: 'fill', kinds: ['line', 'box', 'label', 'polyline'] },
341
+ { prop: WRUN3_COLOR_PROPS.border, name: 'border', kinds: ['label'] },
342
+ { prop: WRUN3_COLOR_PROPS.glow, name: 'glow', kinds: ['line', 'box', 'label', 'polyline'] },
343
+ { prop: WRUN3_COLOR_PROPS.emblem, name: 'emblem', kinds: ['label'] },
344
+ { prop: WRUN3_COLOR_PROPS.gradient_end, name: 'gradient_end', kinds: ['box'] },
345
+ { prop: WRUN3_COLOR_PROPS.text, name: 'text', kinds: ['box'] },
346
+ ];
347
+ /** Caps: a breach refuses the evaluation by name, never drops or truncates.
348
+ * One kind holds up to 1000 live handles, the most the drawing door draws of
349
+ * one kind (KSCRIPT_DRAWING_CAP_PER_KIND): the engine's MAX_DRAWINGS_PER_KIND
350
+ * is 500, but a kScript level drawn with plotRange is a plot row no drawing
351
+ * cap bounds, and its port draws the same level as a handle. Every kind
352
+ * together stays at 1500, so the largest ledger a run holds does not grow. */
353
+ export const WRUN3_MAX_LIVE_HANDLES_PER_KIND = 1000;
354
+ export const WRUN3_MAX_LIVE_HANDLES_TOTAL = 1500;
355
+ /** The points one polyline call may carry: the engine's collection ceiling
356
+ * (`MAX_COLLECTION_SIZE`, 100,000), the only bound kScript puts on a
357
+ * polyline's points. */
358
+ export const WRUN3_MAX_POLYLINE_POINTS = 100_000;
359
+ /** The live polyline points one run may hold across every polyline handle:
360
+ * what the 8 MiB render result carries at 16 bytes a point
361
+ * (8 * 1024 * 1024 / 16). Checked on every polyline call: a re-emitted id
362
+ * gives its old points back and a deleted polyline frees its own. */
363
+ export const WRUN3_MAX_POLYLINE_POINTS_PER_RUN = 524_288;
364
+ export const WRUN3_MAX_DRAW_CALLS_PER_ROW = 4096;
365
+ /** Ledger bytes count against the same cap the expanded render result is
366
+ * held to: 16 per handle, 8 per number (a polyline point is two), the UTF-8
367
+ * bytes of every carried string. */
368
+ export const WRUN_HANDLE_LEDGER_LIMIT_BYTES = WRUN_RENDER_RESULT_LIMIT_BYTES;
369
+ /** Every draw-channel refusal, by name, so each host refuses alike. */
370
+ export const WRUN3_DRAW_REFUSALS = {
371
+ kind_limit: 'wrun_draw_kind_limit',
372
+ total_limit: 'wrun_draw_total_limit',
373
+ polyline_too_large: 'wrun_draw_polyline_too_large',
374
+ calls_per_row: 'wrun_draw_calls_per_row',
375
+ render_result_too_large: 'wrun_render_result_too_large',
376
+ kind_mismatch: 'wrun_draw_kind_mismatch',
377
+ handle_missing: 'wrun_draw_handle_missing',
378
+ label_slot_absent: 'wrun_draw_label_slot_absent',
379
+ non_finite: 'wrun_draw_non_finite',
380
+ phase: 'wrun_draw_phase',
381
+ id_negative: 'wrun_draw_id_negative',
382
+ kind_undeclared: 'wrun_draw_kind_undeclared',
383
+ prop_unknown: 'wrun_draw_prop_unknown',
384
+ prop_unsupported: 'wrun_draw_prop_unsupported',
385
+ style_out_of_range: 'wrun_draw_style_out_of_range',
386
+ polyline_empty: 'wrun_draw_polyline_empty',
387
+ polyline_out_of_bounds: 'wrun_draw_polyline_out_of_bounds',
388
+ label_slot_undeclared: 'wrun_draw_label_slot_undeclared',
389
+ /** A polyline call would bring the run's live polyline points over
390
+ * WRUN3_MAX_POLYLINE_POINTS_PER_RUN. */
391
+ polyline_budget: 'wrun_draw_polyline_budget',
392
+ };
393
+ /** The draw codes a value on one bar can trip (om `WRUN3_DRAW_SKIP_CODES`, docs/WRUN3_ABI.md "Skipped calls"):
394
+ * the call is skipped (nothing of it applies), recorded (`WrunDrawSkip`), and the run goes on. A host-side rule,
395
+ * so a published package is fixed without a republish. */
396
+ export const WRUN3_DRAW_SKIP_CODES = [
397
+ WRUN3_DRAW_REFUSALS.non_finite,
398
+ WRUN3_DRAW_REFUSALS.style_out_of_range,
399
+ WRUN3_DRAW_REFUSALS.handle_missing,
400
+ WRUN3_DRAW_REFUSALS.label_slot_absent,
401
+ WRUN3_DRAW_REFUSALS.polyline_empty,
402
+ WRUN3_DRAW_REFUSALS.kind_mismatch,
403
+ ];
404
+ /** The draw codes that refuse the whole evaluation (om `WRUN3_DRAW_FATAL_CODES`): the limits, and the mistakes a
405
+ * module makes on every bar (a phase, an id, a kind, a prop, a slot or a pointer the code itself names). With
406
+ * WRUN3_DRAW_SKIP_CODES they partition WRUN3_DRAW_REFUSALS (wrun-handles.kit-mirror.spec.ts), and
407
+ * `WrunDrawRefusalError` takes these alone: a skip code thrown as a refusal does not typecheck. */
408
+ export const WRUN3_DRAW_FATAL_CODES = [
409
+ WRUN3_DRAW_REFUSALS.kind_limit,
410
+ WRUN3_DRAW_REFUSALS.total_limit,
411
+ WRUN3_DRAW_REFUSALS.polyline_too_large,
412
+ WRUN3_DRAW_REFUSALS.calls_per_row,
413
+ WRUN3_DRAW_REFUSALS.render_result_too_large,
414
+ WRUN3_DRAW_REFUSALS.polyline_budget,
415
+ WRUN3_DRAW_REFUSALS.phase,
416
+ WRUN3_DRAW_REFUSALS.id_negative,
417
+ WRUN3_DRAW_REFUSALS.kind_undeclared,
418
+ WRUN3_DRAW_REFUSALS.prop_unknown,
419
+ WRUN3_DRAW_REFUSALS.prop_unsupported,
420
+ WRUN3_DRAW_REFUSALS.label_slot_undeclared,
421
+ WRUN3_DRAW_REFUSALS.polyline_out_of_bounds,
422
+ ];
423
+ /** The skipped calls a run records in full (om `WRUN3_MAX_DRAW_SKIPS`); past it a run only counts them
424
+ * (`skippedCount`), so a package that skips on every bar answers a bounded list. */
425
+ export const WRUN3_MAX_DRAW_SKIPS = 64;
426
+ const SKIP_CODES = new Set(WRUN3_DRAW_SKIP_CODES);
427
+ /** Whether a draw code skips its call (true) or refuses the evaluation (false). */
428
+ export function isWrunDrawSkipCode(code) {
429
+ return SKIP_CODES.has(code);
430
+ }
431
+ /** Wire ids: `wrun_h_<kind>_<id>`, e.g. `wrun_h_line_7`. */
432
+ export const WRUN3_HANDLE_ID_PREFIX = 'wrun_h_';
433
+ export function wrunHandleWireId(kind, id) {
434
+ return `${WRUN3_HANDLE_ID_PREFIX}${kind}_${id}`;
435
+ }
436
+ /** The nine chart-corner anchors a `label` renderer may pin to (the engine's
437
+ * plotLabel `position` vocabulary). */
438
+ export const WRUN_LABEL_POSITIONS = [
439
+ 'top_left',
440
+ 'top_center',
441
+ 'top_right',
442
+ 'middle_left',
443
+ 'middle_center',
444
+ 'middle_right',
445
+ 'bottom_left',
446
+ 'bottom_center',
447
+ 'bottom_right',
448
+ ];
449
+ /** The `text` renderer's presentation styles: `price_label` draws the row's
450
+ * text as a price tag at y (the engine's plotPriceLabel); `box`, `knockout`
451
+ * and `emblem` (DW26) are the same tag in the label looks of DW07. Mirrors
452
+ * the kit export of the same name (wrun-handles.kit-mirror.spec pins it),
453
+ * so the FE-only presentation words live in their own list below. */
454
+ export const WRUN_TEXT_STYLES = ['price_label', 'box', 'knockout', 'emblem'];
455
+ /** The presentation style words the browser lane also accepts on a `text`
456
+ * renderer, a `label` renderer and a label drawing (WRUN-INPUTS-PLAN 1.4):
457
+ * `plain` is the bare text (the default, the same as no style), and
458
+ * `callout`, `pill` and `badge` ride the price-label rendering path with
459
+ * the look `wrunTextStyleLook` normalizes them into. */
460
+ export const WRUN_PRESENTATION_TEXT_STYLES = ['plain', 'callout', 'pill', 'badge'];
461
+ /** Every accepted style word, the kit's first (the refusal lists them in
462
+ * this order). */
463
+ export const WRUN_ACCEPTED_TEXT_STYLES = [...WRUN_TEXT_STYLES, ...WRUN_PRESENTATION_TEXT_STYLES];
464
+ export function wrunTextStyleLook(style) {
465
+ switch (style) {
466
+ case 'callout':
467
+ return { type: 'callout' };
468
+ case 'pill':
469
+ return { type: 'simple', shape: 'pill' };
470
+ case 'badge':
471
+ return { type: 'simple', shape: 'badge', border: true };
472
+ case 'box':
473
+ return { type: 'simple', shape: 'box' };
474
+ case 'knockout':
475
+ return { type: 'simple', shape: 'knockout' };
476
+ case 'emblem':
477
+ return { type: 'simple', shape: 'emblem' };
478
+ default:
479
+ return undefined;
480
+ }
481
+ }
482
+ /** true when a style draws through the price-label path (a tag at y). */
483
+ export function wrunTextStyleIsPriceLabel(style) {
484
+ return style === 'price_label' || wrunTextStyleLook(style) !== undefined;
485
+ }
486
+ /** The host-side fallbacks for a `handles` entry's omitted pre-round fields
487
+ * (the contract's sheet example): every host initializes a new handle from
488
+ * the sheet's entry over these. The look keys have no fallback: absent is
489
+ * the engine default. */
490
+ export const WRUN_HANDLE_DEFAULTS = {
491
+ line: { panel: 'overlay', color: '#38bdf8', width: 1, line_style: 'solid', extend: 'none' },
492
+ box: { panel: 'overlay', color: '#38bdf8', border_color: '#38bdf8', opacity: 0.2, border_width: 1 },
493
+ label: { panel: 'overlay', color: '#e5e7eb', size: 12 },
494
+ polyline: { panel: 'overlay', color: '#38bdf8', width: 1, line_style: 'solid' },
495
+ };
496
+ /** The g4 look keys per kind (freeze 2.1), shared by `handles.<kind>` and
497
+ * `drawings[kind]`; the handle side adds `safe_area` (DW06, X20). */
498
+ const WRUN_LINE_STYLE_KEYS = ['arrow', 'glow', 'glow_color', 'sticky_right', 'axis_label', 'opacity'];
499
+ const WRUN_BOX_STYLE_KEYS = [
500
+ 'border_style',
501
+ 'corner_radius',
502
+ 'extend',
503
+ 'shape',
504
+ 'gradient',
505
+ 'gradient_direction',
506
+ 'glow',
507
+ 'glow_color',
508
+ 'text_color',
509
+ 'font_size',
510
+ 'font_weight',
511
+ 'font_family',
512
+ 'align',
513
+ 'valign',
514
+ 'padding',
515
+ ];
516
+ const WRUN_LABEL_STYLE_KEYS = [
517
+ 'style',
518
+ 'background_color',
519
+ 'border_color',
520
+ 'border_width',
521
+ 'corner_radius',
522
+ 'font_weight',
523
+ 'font_family',
524
+ 'valign',
525
+ 'padding',
526
+ 'max_width',
527
+ 'angle',
528
+ 'glow',
529
+ 'glow_color',
530
+ 'emblem_shape',
531
+ 'emblem_color',
532
+ 'sticky_right',
533
+ 'axis_label',
534
+ 'opacity',
535
+ ];
536
+ const WRUN_POLYLINE_STYLE_KEYS = ['opacity', 'fill_color', 'closed', 'smooth', 'arrow', 'glow', 'glow_color'];
537
+ const WRUN_HANDLE_FIELDS = {
538
+ line: new Set(['panel', 'anchor', 'color', 'width', 'line_style', 'extend', ...WRUN_LINE_STYLE_KEYS, 'safe_area']),
539
+ box: new Set([
540
+ 'panel',
541
+ 'anchor',
542
+ 'color',
543
+ 'border_color',
544
+ 'opacity',
545
+ 'border_width',
546
+ ...WRUN_BOX_STYLE_KEYS,
547
+ 'safe_area',
548
+ ]),
549
+ label: new Set(['panel', 'anchor', 'align', 'color', 'size', ...WRUN_LABEL_STYLE_KEYS, 'safe_area']),
550
+ polyline: new Set(['panel', 'anchor', 'color', 'width', 'line_style', ...WRUN_POLYLINE_STYLE_KEYS, 'safe_area']),
551
+ };
552
+ const MAX_SHEET_COLOR_CHARS = 64;
553
+ /** The color forms a box fill may take (the fill takes the opacity, so the
554
+ * hosts must be able to rewrite its alpha): hex, rgb()/rgba(), hsl()/hsla()
555
+ * and (TH-theme-tokens) the seven theme tokens. */
556
+ const BOX_FILL_COLOR_RE = /^(?:#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|rgba?\(\s*\d+(?:\.\d+)?\s*,\s*\d+(?:\.\d+)?\s*,\s*\d+(?:\.\d+)?\s*(?:,[^)]*)?\)|hsla?\(\s*-?\d+(?:\.\d+)?(?:deg)?\s*,\s*\d+(?:\.\d+)?%\s*,\s*\d+(?:\.\d+)?%\s*(?:,[^)]*)?\))$/i;
557
+ const WRUN_THEME_TOKEN_PREFIX = 'theme.';
558
+ /** The freeze's 2.1 message for a "theme." word that is not one of the seven. */
559
+ export const WRUN_THEME_TOKEN_MESSAGE = `colour token must be one of ${WRUN_THEME_COLOR_TOKENS.map((token) => `theme.${token}`).join(', ')}`;
560
+ /** The messages g4 names (DW07, DW16, DW34). */
561
+ export const WRUN_DRAWING_PRICE_LABEL_MESSAGE = 'price_label is a plot look; a drawing label takes box';
562
+ export const WRUN_LINE_AXIS_TEXT_MESSAGE = 'a line has no text; use price';
563
+ export const WRUN_GRADIENT_DIRECTION_MESSAGE = 'gradient_direction needs gradient';
564
+ const WRUN_MIN_GRADIENT_STOPS = 2;
565
+ const WRUN_MAX_GRADIENT_STOPS = 8;
566
+ /** True for an exact theme token word (`theme.up`); the `/aa` wire form and
567
+ * any other `theme.` word are not sheet words. */
568
+ function isExactThemeToken(value) {
569
+ return value.startsWith(WRUN_THEME_TOKEN_PREFIX) && isWrunColorWord(value);
570
+ }
571
+ /** The box fill grammar: the alpha-rewritable forms or a theme token. */
572
+ export function isWrunBoxFillColor(value) {
573
+ return typeof value === 'string' && (BOX_FILL_COLOR_RE.test(value) || isExactThemeToken(value));
574
+ }
575
+ function isRecord(value) {
576
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
577
+ }
578
+ const WAY_IN = 'needs abi_version "wrun-3" (wrun-1 and wrun-2 are frozen and have no draw channel)';
579
+ /** Field readers for one `handles.<kind>` entry or one geometry drawing
580
+ * declaration; every refusal names the sheet, the entry and the field
581
+ * (`label(field)` spells the entry's prefix). */
582
+ class WrunStyleFields {
583
+ label;
584
+ entry;
585
+ constructor(label, entry) {
586
+ this.label = label;
587
+ this.entry = entry;
588
+ }
589
+ refuse(field, requirement) {
590
+ throw new Error(`${this.label(field)} ${requirement}`);
591
+ }
592
+ has(field) {
593
+ return this.entry[field] !== undefined;
594
+ }
595
+ panel(fallback) {
596
+ const value = this.entry.panel;
597
+ if (value === undefined)
598
+ return fallback;
599
+ if (value !== 'overlay' && value !== 'lower')
600
+ this.refuse('panel', "must be 'overlay' or 'lower'");
601
+ return value;
602
+ }
603
+ anchor() {
604
+ return this.word('anchor', WRUN_DRAWING_ANCHORS);
605
+ }
606
+ align() {
607
+ return this.word('align', WRUN_LABEL_ALIGNS);
608
+ }
609
+ /** A word from a list; absent stays absent (the caller's default). */
610
+ word(field, words) {
611
+ const value = this.entry[field];
612
+ if (value === undefined)
613
+ return undefined;
614
+ if (typeof value !== 'string' || !words.includes(value)) {
615
+ this.refuse(field, `must be one of ${words.join(', ')}`);
616
+ }
617
+ return value;
618
+ }
619
+ flag(field) {
620
+ const value = this.entry[field];
621
+ if (value === undefined)
622
+ return undefined;
623
+ if (typeof value !== 'boolean')
624
+ this.refuse(field, 'must be true or false');
625
+ return value;
626
+ }
627
+ /** A colour in the handles' grammar (a non-empty CSS colour string of at
628
+ * most 64 chars) made token-aware (X12): a "theme." word must be one of
629
+ * the seven tokens; `alphaForm` narrows to the box fill grammar. */
630
+ color(field, fallback, alphaForm = false) {
631
+ const value = this.entry[field];
632
+ if (value === undefined)
633
+ return fallback;
634
+ if (typeof value === 'string' && value.startsWith(WRUN_THEME_TOKEN_PREFIX)) {
635
+ if (!isExactThemeToken(value))
636
+ this.refuse(field, WRUN_THEME_TOKEN_MESSAGE);
637
+ return value;
638
+ }
639
+ if (typeof value !== 'string' || value.length === 0 || value.length > MAX_SHEET_COLOR_CHARS) {
640
+ this.refuse(field, `must be a non-empty color string of at most ${MAX_SHEET_COLOR_CHARS} chars`);
641
+ }
642
+ if (alphaForm && !BOX_FILL_COLOR_RE.test(value)) {
643
+ this.refuse(field, 'must be a hex, rgb() or hsl() color (the fill takes the opacity)');
644
+ }
645
+ return value;
646
+ }
647
+ /** 2..8 colour stops, each in the handles' colour grammar (DW34). */
648
+ colors(field) {
649
+ const value = this.entry[field];
650
+ if (value === undefined)
651
+ return undefined;
652
+ if (!Array.isArray(value) || value.length < WRUN_MIN_GRADIENT_STOPS || value.length > WRUN_MAX_GRADIENT_STOPS) {
653
+ this.refuse(field, `must list ${WRUN_MIN_GRADIENT_STOPS} to ${WRUN_MAX_GRADIENT_STOPS} colours`);
654
+ }
655
+ return value.map((stop, at) => {
656
+ const reader = new WrunStyleFields((inner) => this.label(`${inner}[${at}]`), { [field]: stop });
657
+ return reader.color(field, undefined);
658
+ });
659
+ }
660
+ number(field, fallback, min, max, integer = false) {
661
+ const value = this.entry[field];
662
+ if (value === undefined)
663
+ return fallback;
664
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < min || value > max) {
665
+ this.refuse(field, `must be a number in ${min}..${max}`);
666
+ }
667
+ if (integer && !Number.isInteger(value))
668
+ this.refuse(field, 'must be an integer');
669
+ return value;
670
+ }
671
+ lineStyle(field, fallback) {
672
+ const value = this.entry[field];
673
+ if (value === undefined)
674
+ return fallback;
675
+ if (typeof value !== 'string' || !WRUN3_LINE_STYLES.includes(value)) {
676
+ this.refuse(field, "must be 'solid', 'dashed' or 'dotted'");
677
+ }
678
+ return value;
679
+ }
680
+ extend(fallback) {
681
+ const value = this.entry.extend;
682
+ if (value === undefined)
683
+ return fallback;
684
+ if (typeof value !== 'string' || !WRUN3_EXTENDS.includes(value)) {
685
+ this.refuse('extend', "must be 'none', 'left', 'right' or 'both'");
686
+ }
687
+ return value;
688
+ }
689
+ }
690
+ /** The g4 keys of one kind, validated (ranges, words, the token-aware colour
691
+ * grammar, and the cross-key rules the contract names: `price_label` on a
692
+ * label, `axis_label: "text"` on a line, `gradient_direction` without
693
+ * `gradient`). Absent keys stay absent. */
694
+ function readStyleKeys(kind, fields) {
695
+ const style = {};
696
+ const put = (key, value) => {
697
+ if (value !== undefined)
698
+ style[key] = value;
699
+ };
700
+ const glow = () => {
701
+ put('glow', fields.number('glow', undefined, 0, WRUN3_MAX_GLOW_PX));
702
+ put('glow_color', fields.color('glow_color', undefined));
703
+ };
704
+ const font = () => {
705
+ put('font_weight', fields.word('font_weight', WRUN_FONT_WEIGHTS));
706
+ put('font_family', fields.word('font_family', WRUN_FONT_FAMILIES));
707
+ };
708
+ switch (kind) {
709
+ case 'line': {
710
+ // `extend` is a pre-round key on handles.line (always filled there) and
711
+ // a new key on a line drawing (DW31); the mapper reads it either way.
712
+ put('extend', fields.extend(undefined));
713
+ put('arrow', fields.word('arrow', WRUN_ARROWS));
714
+ glow();
715
+ put('sticky_right', fields.flag('sticky_right'));
716
+ const axisLabel = fields.word('axis_label', WRUN_AXIS_LABELS);
717
+ if (axisLabel === 'text')
718
+ fields.refuse('axis_label', WRUN_LINE_AXIS_TEXT_MESSAGE);
719
+ put('axis_label', axisLabel);
720
+ put('opacity', fields.number('opacity', undefined, 0, 1));
721
+ break;
722
+ }
723
+ case 'box': {
724
+ put('border_style', fields.lineStyle('border_style', undefined));
725
+ put('corner_radius', fields.number('corner_radius', undefined, 0, WRUN_CORNER_RADIUS_MAX));
726
+ put('extend', fields.extend(undefined));
727
+ put('shape', fields.word('shape', WRUN_BOX_SHAPES));
728
+ const gradient = fields.colors('gradient');
729
+ put('gradient', gradient);
730
+ const direction = fields.word('gradient_direction', WRUN_GRADIENT_DIRECTIONS);
731
+ if (direction !== undefined && gradient === undefined) {
732
+ fields.refuse('gradient_direction', WRUN_GRADIENT_DIRECTION_MESSAGE);
733
+ }
734
+ put('gradient_direction', direction);
735
+ glow();
736
+ put('text_color', fields.color('text_color', undefined));
737
+ put('font_size', fields.number('font_size', undefined, 6, 64, true));
738
+ font();
739
+ put('align', fields.align());
740
+ put('valign', fields.word('valign', WRUN_VALIGNS));
741
+ put('padding', fields.number('padding', undefined, 0, WRUN3_MAX_PADDING_PX));
742
+ break;
743
+ }
744
+ case 'label': {
745
+ const look = fields.has('style') ? fields.word('style', [...WRUN_LABEL_LOOKS, 'price_label']) : undefined;
746
+ if (look === 'price_label')
747
+ fields.refuse('style', WRUN_DRAWING_PRICE_LABEL_MESSAGE);
748
+ put('style', look);
749
+ put('background_color', fields.color('background_color', undefined));
750
+ put('border_color', fields.color('border_color', undefined));
751
+ put('border_width', fields.number('border_width', undefined, 0, 10));
752
+ put('corner_radius', fields.number('corner_radius', undefined, 0, WRUN_CORNER_RADIUS_MAX));
753
+ font();
754
+ put('valign', fields.word('valign', WRUN_VALIGNS));
755
+ put('padding', fields.number('padding', undefined, 0, WRUN3_MAX_PADDING_PX));
756
+ put('max_width', fields.number('max_width', undefined, 0, WRUN3_MAX_LABEL_WIDTH_PX));
757
+ put('angle', fields.number('angle', undefined, -WRUN3_MAX_LABEL_ANGLE_DEG, WRUN3_MAX_LABEL_ANGLE_DEG));
758
+ glow();
759
+ put('emblem_shape', fields.word('emblem_shape', WRUN_EMBLEM_SHAPES));
760
+ put('emblem_color', fields.color('emblem_color', undefined));
761
+ put('sticky_right', fields.flag('sticky_right'));
762
+ put('axis_label', fields.word('axis_label', WRUN_AXIS_LABELS));
763
+ put('opacity', fields.number('opacity', undefined, 0, 1));
764
+ break;
765
+ }
766
+ case 'polyline': {
767
+ put('opacity', fields.number('opacity', undefined, 0, 1));
768
+ put('fill_color', fields.color('fill_color', undefined));
769
+ put('closed', fields.flag('closed'));
770
+ put('smooth', fields.flag('smooth'));
771
+ put('arrow', fields.word('arrow', WRUN_ARROWS));
772
+ glow();
773
+ break;
774
+ }
775
+ }
776
+ return style;
777
+ }
778
+ /** The sheet's `handles` section, defaults applied per declared kind,
779
+ * refused by name on a bad declaration (contract section 7 validator rules
780
+ * 1 and 3, g4 section 2.1): `handles` needs abi_version wrun-3 even when
781
+ * empty, a kind key is one of the four handle kinds, every field sits in
782
+ * its range, every colour takes the token-aware grammar. A label handle no
783
+ * longer needs a string slot (DW29: a mark is a label with no text).
784
+ * Absent = no kind enabled. */
785
+ export function readWrunHandleDefaults(metadata) {
786
+ const sheet = metadata.handles;
787
+ if (sheet === undefined)
788
+ return {};
789
+ if (!abiAtLeast(wrunAbiVersion(metadata), 'wrun-3')) {
790
+ throw new Error(`Indicator ${metadata.id}: handles ${WAY_IN}`);
791
+ }
792
+ if (!isRecord(sheet))
793
+ throw new Error(`Indicator ${metadata.id}: handles must be an object keyed by handle kind`);
794
+ const defaults = {};
795
+ for (const [key, entry] of Object.entries(sheet)) {
796
+ if (!WRUN3_HANDLE_KINDS.includes(key)) {
797
+ throw new Error(`Indicator ${metadata.id}: unknown handle kind '${key}'; the handle kinds are ${WRUN3_HANDLE_KINDS.join(', ')}`);
798
+ }
799
+ const kind = key;
800
+ if (!isRecord(entry))
801
+ throw new Error(`Indicator ${metadata.id}: handles.${kind} must be an object`);
802
+ for (const field of Object.keys(entry)) {
803
+ if (!WRUN_HANDLE_FIELDS[kind].has(field)) {
804
+ throw new Error(`Indicator ${metadata.id}: handles.${kind} has no field '${field}'`);
805
+ }
806
+ }
807
+ const fields = new WrunStyleFields((field) => `Indicator ${metadata.id}: handles.${kind}.${field}`, entry);
808
+ const anchor = fields.anchor();
809
+ const placement = anchor !== undefined ? { anchor } : {};
810
+ const safeArea = fields.flag('safe_area');
811
+ const safe = safeArea !== undefined ? { safe_area: safeArea } : {};
812
+ const look = readStyleKeys(kind, fields);
813
+ switch (kind) {
814
+ case 'line': {
815
+ const base = WRUN_HANDLE_DEFAULTS.line;
816
+ defaults.line = {
817
+ ...placement,
818
+ panel: fields.panel(base.panel),
819
+ color: fields.color('color', base.color),
820
+ width: fields.number('width', base.width, 0.5, 20),
821
+ line_style: fields.lineStyle('line_style', base.line_style),
822
+ extend: fields.extend(base.extend),
823
+ ...look,
824
+ ...safe,
825
+ };
826
+ break;
827
+ }
828
+ case 'box': {
829
+ const base = WRUN_HANDLE_DEFAULTS.box;
830
+ defaults.box = {
831
+ ...placement,
832
+ panel: fields.panel(base.panel),
833
+ color: fields.color('color', base.color, true),
834
+ border_color: fields.color('border_color', base.border_color),
835
+ opacity: fields.number('opacity', base.opacity, 0, 1),
836
+ border_width: fields.number('border_width', base.border_width, 0, 10),
837
+ ...look,
838
+ ...safe,
839
+ };
840
+ break;
841
+ }
842
+ case 'label': {
843
+ const base = WRUN_HANDLE_DEFAULTS.label;
844
+ const align = fields.align();
845
+ defaults.label = {
846
+ ...placement,
847
+ ...(align !== undefined ? { align } : {}),
848
+ panel: fields.panel(base.panel),
849
+ color: fields.color('color', base.color),
850
+ size: fields.number('size', base.size, 6, 64, true),
851
+ ...look,
852
+ ...safe,
853
+ };
854
+ break;
855
+ }
856
+ case 'polyline': {
857
+ const base = WRUN_HANDLE_DEFAULTS.polyline;
858
+ defaults.polyline = {
859
+ ...placement,
860
+ panel: fields.panel(base.panel),
861
+ color: fields.color('color', base.color),
862
+ width: fields.number('width', base.width, 0.5, 20),
863
+ line_style: fields.lineStyle('line_style', base.line_style),
864
+ ...look,
865
+ ...safe,
866
+ };
867
+ break;
868
+ }
869
+ }
870
+ }
871
+ return defaults;
872
+ }
873
+ /** The wrun-3 renderer fields, read off a renderer as parsed JSON (the
874
+ * interface types them, the sheet on disk may carry anything). */
875
+ export function readWrunLabelPosition(sheetId, renderer) {
876
+ if (renderer.kind !== 'label')
877
+ return undefined;
878
+ const value = renderer.position;
879
+ if (value === undefined)
880
+ return undefined;
881
+ if (typeof value !== 'string' || !WRUN_LABEL_POSITIONS.includes(value)) {
882
+ throw new Error(`Indicator ${sheetId}: label '${renderer.name}' position must be one of ${WRUN_LABEL_POSITIONS.join(', ')}`);
883
+ }
884
+ return value;
885
+ }
886
+ export function readWrunTextStyle(sheetId, renderer) {
887
+ if (renderer.kind !== 'text' && renderer.kind !== 'label')
888
+ return undefined;
889
+ return readWrunPresentationStyle(sheetId, renderer.kind, renderer.name, renderer.style);
890
+ }
891
+ /** The presentation `style` word of a text renderer, a label renderer or a
892
+ * label drawing (read as parsed JSON): one of WRUN_ACCEPTED_TEXT_STYLES,
893
+ * refused by name otherwise; `plain` reads as no style (the bare text). On
894
+ * a label DRAWING (`kind` 'label drawing') `price_label` is an alias of
895
+ * `box` (DW07: a plot look on an already-published drawing); its `plain`
896
+ * rides `wrunDrawingStyleWire` as the engine's text-only look. */
897
+ export function readWrunPresentationStyle(sheetId, kind, name, value) {
898
+ if (value === undefined)
899
+ return undefined;
900
+ if (typeof value !== 'string' || !WRUN_ACCEPTED_TEXT_STYLES.includes(value)) {
901
+ throw new Error(`Indicator ${sheetId}: ${kind} '${name}' style must be one of ${WRUN_ACCEPTED_TEXT_STYLES.map((style) => `'${style}'`).join(', ')}`);
902
+ }
903
+ if (value === 'price_label' && kind === 'label drawing')
904
+ return 'box';
905
+ return value === 'plain' ? undefined : value;
906
+ }
907
+ /** The `tooltip` template of a text renderer, a label renderer or a
908
+ * geometry drawing (DW32; read as parsed JSON): a string, refused by name
909
+ * otherwise; empty reads as none. */
910
+ export function readWrunPresentationTooltip(sheetId, kind, name, value) {
911
+ if (value === undefined)
912
+ return undefined;
913
+ if (typeof value !== 'string') {
914
+ throw new Error(`Indicator ${sheetId}: ${kind} '${name}' tooltip must be a template string ({{name}} placeholders)`);
915
+ }
916
+ return value.trim() === '' ? undefined : value;
917
+ }
918
+ /** Contract section 7 validator rules for the sheet additions, the same
919
+ * refusals the registry gate and the om validator make: `handles` (even
920
+ * empty), a label renderer's corner `position`, and a text renderer's
921
+ * `style` each need abi_version wrun-3 (rule 1); a label sits at an (x, y)
922
+ * point or in a corner, and a lone x or y locates nothing (rule 3). Runs
923
+ * before every run, beside the string-slot checks. */
924
+ export function assertWrunSheetAbiCoupling(metadata) {
925
+ const abi = wrunAbiVersion(metadata);
926
+ readWrunHandleDefaults(metadata);
927
+ for (const renderer of metadata.renderers ?? []) {
928
+ const position = readWrunLabelPosition(metadata.id, renderer);
929
+ const style = readWrunTextStyle(metadata.id, renderer);
930
+ if (!abiAtLeast(abi, 'wrun-3')) {
931
+ if (position !== undefined) {
932
+ throw new Error(`Indicator ${metadata.id}: label '${renderer.name}' declares a corner position, which ${WAY_IN}`);
933
+ }
934
+ if (style !== undefined) {
935
+ throw new Error(`Indicator ${metadata.id}: ${renderer.kind} '${renderer.name}' declares a style, which ${WAY_IN}`);
936
+ }
937
+ }
938
+ if (renderer.kind !== 'label')
939
+ continue;
940
+ const hasX = renderer.x !== undefined;
941
+ const hasY = renderer.y !== undefined;
942
+ if (position === undefined && !(hasX && hasY)) {
943
+ throw new Error(`Indicator ${metadata.id}: label '${renderer.name}' needs x and y (a label sits at an (x, y) point unless a corner position places it)`);
944
+ }
945
+ if (position !== undefined && hasX !== hasY) {
946
+ throw new Error(`Indicator ${metadata.id}: label '${renderer.name}' declares ${hasX ? 'x' : 'y'} without ${hasX ? 'y' : 'x'} (a point needs both, or drop it and keep the corner position)`);
947
+ }
948
+ }
949
+ }
950
+ /** `rgba(r,g,b,a)` with the alpha as a plain number rounded to three
951
+ * decimals (255 -> 1, 51 -> 0.2), the wire spelling every host emits. */
952
+ function rgbaString(r, g, b, alpha255) {
953
+ return `rgba(${r},${g},${b},${Math.round((alpha255 / 255) * 1000) / 1000})`;
954
+ }
955
+ /** `wrun_draw_color`'s `0xRRGGBBAA` i32 bit pattern as a plain CSS color
956
+ * (no token decode; the ledger's colour channel reads the token sentinel
957
+ * through the foundation's `wrunDrawColorWire`). */
958
+ export function wrunRgbaFromI32(rgba) {
959
+ const bits = rgba >>> 0;
960
+ return rgbaString((bits >>> 24) & 0xff, (bits >>> 16) & 0xff, (bits >>> 8) & 0xff, bits & 0xff);
961
+ }
962
+ const HEX_COLOR_RE = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
963
+ /** A sheet color on the wire: hex forms become `rgba(r,g,b,a)` (the
964
+ * contract's wire example spells `#38bdf8` as `rgba(56,189,248,1)`); every
965
+ * other form (rgb(), hsl(), a named color, a theme token such as
966
+ * `theme.up`) rides verbatim: tokens resolve at paint time on the chart,
967
+ * never here (TH-theme-tokens). */
968
+ export function wrunSheetColorToWire(color) {
969
+ const match = HEX_COLOR_RE.exec(color);
970
+ if (!match)
971
+ return color;
972
+ const hex = match[1];
973
+ if (hex.length <= 4) {
974
+ const channel = (at) => parseInt(hex[at] + hex[at], 16);
975
+ return rgbaString(channel(0), channel(1), channel(2), hex.length === 4 ? channel(3) : 255);
976
+ }
977
+ const channel = (at) => parseInt(hex.slice(at, at + 2), 16);
978
+ return rgbaString(channel(0), channel(2), channel(4), hex.length === 8 ? channel(6) : 255);
979
+ }
980
+ /** A colour with its alpha REPLACED by `opacity` (the kScript opacity()
981
+ * convention; the engine's box painter reads translucency off the fill
982
+ * colour itself): a theme token keeps its word and takes the alpha
983
+ * (`theme.up` at 0.2 is `theme.up/33`, resolved at paint time); 3/4/6/8
984
+ * digit hex, rgb()/rgba() and hsl()/hsla() are rewritten; any other string
985
+ * passes unchanged, as does an opacity of 1 or out of range. The same
986
+ * text the run-result adapter's withOpacity prints. */
987
+ export function wrunColorWithOpacity(color, opacity) {
988
+ if (opacity === undefined || !(opacity >= 0 && opacity < 1))
989
+ return color;
990
+ if (color.startsWith(WRUN_THEME_TOKEN_PREFIX))
991
+ return wrunThemeTokenWithAlpha(color, opacity);
992
+ const hex = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})(?:[0-9a-f]{2})?$/i.exec(color);
993
+ if (hex) {
994
+ return `rgba(${parseInt(hex[1], 16)}, ${parseInt(hex[2], 16)}, ${parseInt(hex[3], 16)}, ${opacity})`;
995
+ }
996
+ const shortHex = /^#([0-9a-f])([0-9a-f])([0-9a-f])[0-9a-f]?$/i.exec(color);
997
+ if (shortHex) {
998
+ const channel = (digit) => parseInt(digit + digit, 16);
999
+ return `rgba(${channel(shortHex[1])}, ${channel(shortHex[2])}, ${channel(shortHex[3])}, ${opacity})`;
1000
+ }
1001
+ const rgb = /^(rgba?\(\s*\d+(?:\.\d+)?\s*,\s*\d+(?:\.\d+)?\s*,\s*\d+(?:\.\d+)?)\s*(?:,[^)]*)?\)$/i.exec(color);
1002
+ if (rgb)
1003
+ return `${rgb[1]}, ${opacity})`;
1004
+ const hsl = /^hsla?(\(\s*-?\d+(?:\.\d+)?(?:deg)?\s*,\s*\d+(?:\.\d+)?%\s*,\s*\d+(?:\.\d+)?%)\s*(?:,[^)]*)?\)$/i.exec(color);
1005
+ if (hsl)
1006
+ return `hsla${hsl[1]}, ${opacity})`;
1007
+ return color;
1008
+ }
1009
+ /** A colour's own alpha in the forms wrunColorWithOpacity rewrites (3/4/6/8
1010
+ * digit hex, rgb()/rgba(), hsl()/hsla(), a number or a percentage) and in a
1011
+ * theme token (`theme.<t>/aa`): 1 when the form carries none, undefined for
1012
+ * any other string (a named colour). */
1013
+ export function wrunColorOwnAlpha(color) {
1014
+ const token = parseWrunThemeToken(color);
1015
+ if (token !== null)
1016
+ return token.alpha;
1017
+ const hex = /^#(?:[0-9a-f]{3}([0-9a-f])?|[0-9a-f]{6}([0-9a-f]{2})?)$/i.exec(color);
1018
+ if (hex) {
1019
+ if (hex[1] !== undefined)
1020
+ return parseInt(hex[1] + hex[1], 16) / 255;
1021
+ return hex[2] !== undefined ? parseInt(hex[2], 16) / 255 : 1;
1022
+ }
1023
+ const functional = /^rgba?\(\s*\d+(?:\.\d+)?\s*,\s*\d+(?:\.\d+)?\s*,\s*\d+(?:\.\d+)?\s*(?:,\s*([^)]*?)\s*)?\)$/i.exec(color) ??
1024
+ /^hsla?\(\s*-?\d+(?:\.\d+)?(?:deg)?\s*,\s*\d+(?:\.\d+)?%\s*,\s*\d+(?:\.\d+)?%\s*(?:,\s*([^)]*?)\s*)?\)$/i.exec(color);
1025
+ if (!functional)
1026
+ return undefined;
1027
+ const text = functional[1];
1028
+ if (text === undefined)
1029
+ return 1;
1030
+ const alpha = text.endsWith('%') ? Number(text.slice(0, -1)) / 100 : Number(text);
1031
+ return text !== '' && Number.isFinite(alpha) ? Math.min(1, Math.max(0, alpha)) : undefined;
1032
+ }
1033
+ /**
1034
+ * The opacity a box paints its fill at (the box fill rule, PINE-TV-PARITY 2026-10-05). An opacity
1035
+ * the module set (a `.opacity()` call, a declared `opacity`) is the fill's alpha, replacing the
1036
+ * colour's own. Without one, a fill colour that carries its own alpha below 1 keeps it: a Pine
1037
+ * `color.new(c, transp)` fade ported as `.fill(rgba(...))` paints at that alpha, row by row. Only an
1038
+ * opaque fill takes the default opacity (the sheet's `opacity`, else 0.2), as before. A packed
1039
+ * colour always carries an alpha byte, so an opaque fill reads as "no alpha given".
1040
+ */
1041
+ export function wrunBoxFillOpacity(fill, opacity, opacitySet) {
1042
+ if (opacitySet || opacity === undefined)
1043
+ return opacity;
1044
+ const own = wrunColorOwnAlpha(fill);
1045
+ return own !== undefined && own < 1 ? own : opacity;
1046
+ }
1047
+ // ---------------------------------------------------------------------------
1048
+ // Sheet look keys -> wire props (the one mapper, g4 section 2.1).
1049
+ // ---------------------------------------------------------------------------
1050
+ /** The wire props the g4 look keys of one validated entry map to (Appendix
1051
+ * C's wire column). A key with the ABI's "0 / none deletes" meaning puts no
1052
+ * key on the wire when it names that default (`arrow: "none"`, `glow: 0`,
1053
+ * `sticky_right: false`, `shape: "rect"`, `max_width: 0`, `angle: 0`), so a
1054
+ * sheet default and the runtime setter agree. Font words ride the wire as
1055
+ * words (the app resolves them to CSS at the drawing door, X14); font
1056
+ * weights as the CSS weights the engine reads. `colorToWire` spells the
1057
+ * colours: the handle ledger expands hex to rgba like its base colours,
1058
+ * the declared-drawing adapter keeps the sheet text. */
1059
+ function styleWireOf(kind, style, colorToWire) {
1060
+ const wire = {};
1061
+ const str = (key) => typeof style[key] === 'string' ? style[key] : undefined;
1062
+ const num = (key) => typeof style[key] === 'number' ? style[key] : undefined;
1063
+ const color = (key, wireKey) => {
1064
+ const value = str(key);
1065
+ if (value !== undefined)
1066
+ wire[wireKey] = colorToWire(value);
1067
+ };
1068
+ const number = (key, wireKey, zeroDeletes = false) => {
1069
+ const value = num(key);
1070
+ if (value !== undefined && !(zeroDeletes && value === 0))
1071
+ wire[wireKey] = value;
1072
+ };
1073
+ const word = (key, wireKey, none) => {
1074
+ const value = str(key);
1075
+ if (value !== undefined && value !== none)
1076
+ wire[wireKey] = value;
1077
+ };
1078
+ const flag = (key, wireKey) => {
1079
+ if (style[key] === true)
1080
+ wire[wireKey] = true;
1081
+ };
1082
+ const font = () => {
1083
+ const weight = str('font_weight');
1084
+ if (weight !== undefined)
1085
+ wire.fontWeight = WRUN3_FONT_WEIGHT_CSS[weight];
1086
+ word('font_family', 'fontFamily');
1087
+ };
1088
+ const glow = () => {
1089
+ number('glow', 'glow', true);
1090
+ color('glow_color', 'glowColor');
1091
+ };
1092
+ switch (kind) {
1093
+ case 'line':
1094
+ word('extend', 'extend', 'none');
1095
+ word('arrow', 'arrow', 'none');
1096
+ glow();
1097
+ flag('sticky_right', 'stickyRight');
1098
+ word('axis_label', 'axisLabel', 'none');
1099
+ number('opacity', 'opacity');
1100
+ break;
1101
+ case 'box': {
1102
+ word('border_style', 'borderStyle');
1103
+ number('corner_radius', 'radius');
1104
+ word('extend', 'extend', 'none');
1105
+ word('shape', 'shape', 'rect');
1106
+ const gradient = style.gradient;
1107
+ if (Array.isArray(gradient))
1108
+ wire.gradient = gradient.map((stop) => colorToWire(String(stop)));
1109
+ word('gradient_direction', 'gradientDirection');
1110
+ // A declared gradient without a direction runs vertical, the way the
1111
+ // runtime's gradient_end colour call and om's handle templates default
1112
+ // it (one wire record for a sheet default and a style call).
1113
+ if (wire.gradient !== undefined && wire.gradientDirection === undefined)
1114
+ wire.gradientDirection = 'vertical';
1115
+ glow();
1116
+ color('text_color', 'textColor');
1117
+ number('font_size', 'textSize');
1118
+ font();
1119
+ word('align', 'align');
1120
+ word('valign', 'valign');
1121
+ number('padding', 'padding');
1122
+ break;
1123
+ }
1124
+ case 'label':
1125
+ word('style', 'style');
1126
+ color('background_color', 'backgroundColor');
1127
+ color('border_color', 'border');
1128
+ number('border_width', 'borderWidth');
1129
+ number('corner_radius', 'radius');
1130
+ font();
1131
+ word('valign', 'valign');
1132
+ number('padding', 'padding');
1133
+ number('max_width', 'maxWidth', true);
1134
+ number('angle', 'angle', true);
1135
+ glow();
1136
+ word('emblem_shape', 'emblemShape');
1137
+ color('emblem_color', 'emblemColor');
1138
+ flag('sticky_right', 'stickyRight');
1139
+ word('axis_label', 'axisLabel', 'none');
1140
+ number('opacity', 'opacity');
1141
+ break;
1142
+ case 'polyline':
1143
+ number('opacity', 'opacity');
1144
+ color('fill_color', 'fillColor');
1145
+ flag('closed', 'closed');
1146
+ flag('smooth', 'smooth');
1147
+ word('arrow', 'arrow', 'none');
1148
+ glow();
1149
+ break;
1150
+ }
1151
+ return wire;
1152
+ }
1153
+ /** The handles.box default fill (the engine's own yellow fallback is gone, DW19). */
1154
+ const WRUN_BOX_DRAWING_FILL = WRUN_HANDLE_DEFAULTS.box.color;
1155
+ const WRUN_BOX_DRAWING_OPACITY = WRUN_HANDLE_DEFAULTS.box.opacity;
1156
+ const WRUN_BOX_DRAWING_BORDER_WIDTH = WRUN_HANDLE_DEFAULTS.box.border_width;
1157
+ /** The wire props a declared geometry drawing's g4 look keys map to (the
1158
+ * freeze's 3.5.3 seam; the adapter assigns them over the record's base
1159
+ * props). Every key is read off the declaration by name and refused by
1160
+ * name when out of its range or grammar. The box rules of DW19 live here:
1161
+ * `color` (the alpha-rewritable grammar or a token, default "#38bdf8") is
1162
+ * the fill at `opacity` (default 0.2 on an opaque colour; a colour with
1163
+ * its own alpha keeps it unless `opacity` is declared, wrunBoxFillOpacity)
1164
+ * on `backgroundColor` and `fillColor`,
1165
+ * and the border when `border_color` is absent; `border_width` defaults to
1166
+ * 1; `border_style` (else the legacy `line_style`) is the dash; the
1167
+ * declaration's bare `color` must not reach titan as the border (the
1168
+ * adapter drops it). A label's `price_label` is an alias of `box` (a plot
1169
+ * look on an already-published drawing); `plain` is the text-only look. */
1170
+ export function wrunDrawingStyleWire(kind, declaration, sheetId) {
1171
+ const name = typeof declaration.name === 'string' ? declaration.name : '';
1172
+ // A published label drawing's `price_label` is an alias of `box` (DW07).
1173
+ const entry = kind === 'label' && declaration.style === 'price_label' ? { ...declaration, style: 'box' } : declaration;
1174
+ const fields = new WrunStyleFields((field) => `Indicator ${sheetId}: ${kind} drawing '${name}' ${field}`, entry);
1175
+ const look = readStyleKeys(kind, fields);
1176
+ const wire = styleWireOf(kind, look, (color) => color);
1177
+ if (kind !== 'box')
1178
+ return wire;
1179
+ // The declared `color` is a HEAD key (any string; a published box may say
1180
+ // "red"), so it takes no refusal (R22: validation never refuses a sheet
1181
+ // that validated at HEAD). It is the fill only when the hosts can rewrite
1182
+ // its alpha (the box fill grammar); any other colour keeps HEAD's reading,
1183
+ // the border, over the default fill.
1184
+ const declared = typeof entry.color === 'string' && entry.color !== '' ? entry.color : undefined;
1185
+ const fill = declared !== undefined && isWrunBoxFillColor(declared) ? declared : WRUN_BOX_DRAWING_FILL;
1186
+ // A declared `opacity` is the fill's alpha; without one, a colour carrying
1187
+ // its own alpha keeps it and an opaque one takes 0.2 (wrunBoxFillOpacity).
1188
+ const opacity = wrunBoxFillOpacity(fill, fields.number('opacity', WRUN_BOX_DRAWING_OPACITY, 0, 1), entry.opacity !== undefined);
1189
+ const painted = wrunColorWithOpacity(fill, opacity);
1190
+ const borderColor = fields.color('border_color', declared ?? fill);
1191
+ const borderWidth = fields.number('border_width', WRUN_BOX_DRAWING_BORDER_WIDTH, 0, 10);
1192
+ const borderStyle = fields.lineStyle('border_style', fields.lineStyle('line_style', undefined));
1193
+ // A gradient box stays as translucent as its fill (DW34): the opacity folds
1194
+ // into every stop, the way the handle ledger's adapter folds it.
1195
+ const gradient = Array.isArray(wire.gradient)
1196
+ ? wire.gradient.map((stop) => (typeof stop === 'string' ? wrunColorWithOpacity(stop, opacity) : stop))
1197
+ : undefined;
1198
+ return {
1199
+ ...wire,
1200
+ ...(gradient !== undefined ? { gradient } : {}),
1201
+ backgroundColor: painted,
1202
+ fillColor: painted,
1203
+ borderColor,
1204
+ borderWidth,
1205
+ ...(borderStyle !== undefined ? { borderStyle } : {}),
1206
+ };
1207
+ }
1208
+ /** A new handle's initial wire props: the pre-round base keys (the sheet
1209
+ * colours expanded to rgba, the contract's wire example) plus the look
1210
+ * keys through the same mapper as a declared drawing's. A box keeps its
1211
+ * fill opacity as `fillOpacity` beside the raw fill colours (the adapter
1212
+ * folds it at the titan boundary, after every later `fill` colour and
1213
+ * `opacity` style call alike). The sheet's `safe_area` rides as written
1214
+ * for the adapter's `safeArea` (DW06). */
1215
+ export function wrunHandleInitialProps(kind, defaults) {
1216
+ const entry = defaults;
1217
+ let base;
1218
+ switch (kind) {
1219
+ case 'line': {
1220
+ const line = defaults;
1221
+ base = {
1222
+ color: wrunSheetColorToWire(line.color),
1223
+ width: line.width,
1224
+ lineStyle: line.line_style,
1225
+ extend: line.extend,
1226
+ };
1227
+ break;
1228
+ }
1229
+ case 'box': {
1230
+ const box = defaults;
1231
+ const fill = wrunSheetColorToWire(box.color);
1232
+ base = {
1233
+ borderColor: wrunSheetColorToWire(box.border_color),
1234
+ borderWidth: box.border_width,
1235
+ borderStyle: box.border_style ?? 'solid',
1236
+ fillColor: fill,
1237
+ backgroundColor: fill,
1238
+ fillOpacity: box.opacity,
1239
+ };
1240
+ break;
1241
+ }
1242
+ case 'label': {
1243
+ const label = defaults;
1244
+ base = {
1245
+ ...(label.align !== undefined ? { align: label.align } : {}),
1246
+ color: wrunSheetColorToWire(label.color),
1247
+ size: label.size,
1248
+ };
1249
+ break;
1250
+ }
1251
+ case 'polyline': {
1252
+ const polyline = defaults;
1253
+ base = { color: wrunSheetColorToWire(polyline.color), width: polyline.width, lineStyle: polyline.line_style };
1254
+ break;
1255
+ }
1256
+ }
1257
+ // The look keys of a validated entry: `extend` on a line is a base key
1258
+ // (always on the wire), so the mapper's copy is dropped there.
1259
+ const { extend: lineExtend, ...look } = styleWireOf(kind, entry, wrunSheetColorToWire);
1260
+ void lineExtend;
1261
+ const safe = entry.safe_area === true ? { safe_area: true } : {};
1262
+ return kind === 'line'
1263
+ ? { ...base, ...look, ...safe }
1264
+ : { ...base, ...look, ...(kind === 'box' && lineExtend !== undefined ? { extend: lineExtend } : {}), ...safe };
1265
+ }
1266
+ /** The element as the refusal's words carry it, so the text that crosses the worker and lands in Copy details and
1267
+ * the editor console names the handle and the bar: ` (handle 7, row 12, bar 2026-10-09T14:00:00.000Z)`. */
1268
+ function elementWords(element) {
1269
+ const parts = [];
1270
+ if (element.id !== undefined)
1271
+ parts.push(`handle ${element.id}`);
1272
+ if (element.arg !== undefined)
1273
+ parts.push(element.arg);
1274
+ if (element.row !== undefined)
1275
+ parts.push(`row ${element.row}`);
1276
+ if (element.ts !== undefined && Number.isFinite(element.ts)) {
1277
+ const time = new Date(element.ts);
1278
+ if (Number.isFinite(time.getTime()))
1279
+ parts.push(`bar ${time.toISOString()}`);
1280
+ }
1281
+ return parts.length > 0 ? ` (${parts.join(', ')})` : '';
1282
+ }
1283
+ /** A fatal draw-channel refusal: the evaluation fails by name (`refusal` is one of WRUN3_DRAW_FATAL_CODES and
1284
+ * leads the message), exactly like a string channel refusal fails a run. A skip code never reaches here: the
1285
+ * ledger records it and the run goes on. The element rides as fields and in the words. */
1286
+ export class WrunDrawRefusalError extends Error {
1287
+ refusal;
1288
+ id;
1289
+ row;
1290
+ ts;
1291
+ call;
1292
+ arg;
1293
+ constructor(refusal, detail, element = {}) {
1294
+ super(`${refusal}: ${detail}${elementWords(element)}`);
1295
+ this.name = 'WrunDrawRefusalError';
1296
+ this.refusal = refusal;
1297
+ if (element.id !== undefined)
1298
+ this.id = element.id;
1299
+ if (element.row !== undefined)
1300
+ this.row = element.row;
1301
+ if (element.ts !== undefined)
1302
+ this.ts = element.ts;
1303
+ if (element.call !== undefined)
1304
+ this.call = element.call;
1305
+ if (element.arg !== undefined)
1306
+ this.arg = element.arg;
1307
+ }
1308
+ }
1309
+ /** No slot is readable: every slot index is undeclared. */
1310
+ const NO_SLOT_TEXTS = { count: 0, text: () => null };
1311
+ /** The points a polyline entry holds (its share of the per-run budget). */
1312
+ function polylinePointCount(entry) {
1313
+ const points = entry.props.points;
1314
+ return Array.isArray(points) ? points.length : 0;
1315
+ }
1316
+ function entryBytes(props) {
1317
+ let bytes = 16;
1318
+ for (const value of Object.values(props)) {
1319
+ if (typeof value === 'number')
1320
+ bytes += 8;
1321
+ else if (typeof value === 'string')
1322
+ bytes += utf8ByteLength(value);
1323
+ else if (Array.isArray(value)) {
1324
+ for (const item of value)
1325
+ bytes += typeof item === 'string' ? utf8ByteLength(item) : 16;
1326
+ }
1327
+ }
1328
+ return bytes;
1329
+ }
1330
+ /** The first non-finite value of a call's coordinates in argument order, as `<name>=<value>`. */
1331
+ function firstNonFinite(values) {
1332
+ for (const [name, value] of values) {
1333
+ if (!Number.isFinite(value))
1334
+ return `${name}=${value}`;
1335
+ }
1336
+ return undefined;
1337
+ }
1338
+ /**
1339
+ * The per-instance handle ledger: create, mutate and delete by id with the engine's stamping rules, the caps, the
1340
+ * byte accounting, the skipped calls, and the journal that makes a live restore exact. Rows are the run window's
1341
+ * row indexes.
1342
+ *
1343
+ * Every call runs its fatal checks first (the per-row count, the id, the kind, the prop, the slot, then the limits a
1344
+ * call that would apply must pass: a skipped call still counts toward them), then its skip checks; a fatal check
1345
+ * throws `WrunDrawRefusalError`, a skip check records the call (`drawSkips`) and drops it, both BEFORE the ledger
1346
+ * changes, so nothing is ever half applied. A geometry call skipped on an id that holds no handle of its kind (a
1347
+ * skipped create, or a kind mismatch) absorbs that id's style and colour calls for the rest of the row: the
1348
+ * generated draw code re-sends a handle's setters after its geometry call, so one bad element is one record. The
1349
+ * phase guard is the host's (it runs before the ledger is reached).
1350
+ */
1351
+ export class WrunHandleLedger {
1352
+ limitBytes;
1353
+ entries = new Map();
1354
+ defaults;
1355
+ /** The sheet declares a `handles` section: without one every draw call but the last-bar signal refuses
1356
+ * `wrun_draw_kind_undeclared` (style, colour and delete included, the om hosts' rule). */
1357
+ declared;
1358
+ nextSeq = 0;
1359
+ bytes = 0;
1360
+ rowCalls = 0;
1361
+ /** The time of the row being evaluated (the skipped calls' `ts`). */
1362
+ rowTs = Number.NaN;
1363
+ journal = [];
1364
+ seqAtSnapshot = 0;
1365
+ /** The points every live polyline holds (WRUN3_MAX_POLYLINE_POINTS_PER_RUN). */
1366
+ polylinePoints = 0;
1367
+ /** The run's skipped calls: the first WRUN3_MAX_DRAW_SKIPS in call order, then a count, each with its mark at the
1368
+ * live snapshot (a restore truncates back to the marks). */
1369
+ skips = [];
1370
+ skipRest = 0;
1371
+ skipsAtSnapshot = 0;
1372
+ skipRestAtSnapshot = 0;
1373
+ /** The ids a skipped geometry call left absorbing this row, with the kind that call named. */
1374
+ absorbing = new Map();
1375
+ /** `defaults` undefined: the sheet declares no `handles` section (every draw call refuses by name). */
1376
+ constructor(defaults, limitBytes = WRUN_HANDLE_LEDGER_LIMIT_BYTES) {
1377
+ this.limitBytes = limitBytes;
1378
+ this.defaults = defaults ?? {};
1379
+ this.declared = defaults !== undefined;
1380
+ }
1381
+ /** Live handles. */
1382
+ get size() {
1383
+ return this.entries.size;
1384
+ }
1385
+ /** Accounted bytes of the live set. */
1386
+ get accountedBytes() {
1387
+ return this.bytes;
1388
+ }
1389
+ /** Start a row: the draw-calls-per-row cap counts from here, nothing absorbs, and a skip records `ts` (the row's
1390
+ * time in the host's row unit). */
1391
+ beginRow(ts = Number.NaN) {
1392
+ this.rowCalls = 0;
1393
+ this.rowTs = ts;
1394
+ this.absorbing.clear();
1395
+ }
1396
+ line(bar, id, x1, y1, x2, y2) {
1397
+ this.corners('line', 'wrun_draw_line', bar, id, [
1398
+ ['x1', x1],
1399
+ ['y1', y1],
1400
+ ['x2', x2],
1401
+ ['y2', y2],
1402
+ ]);
1403
+ }
1404
+ /** Corners normalize on the wire: ascending x and descending y. */
1405
+ box(bar, id, left, top, right, bottom) {
1406
+ this.corners('box', 'wrun_draw_box', bar, id, [
1407
+ ['left', left],
1408
+ ['top', top],
1409
+ ['right', right],
1410
+ ['bottom', bottom],
1411
+ ]);
1412
+ }
1413
+ /** `text`: the host's slot and reader (judged here: an undeclared slot refuses, an unwritten one skips), or the
1414
+ * text itself. A slot of NO_TEXT_SLOT draws a label with no text and reads nothing (DW29). */
1415
+ label(bar, id, x, y, text) {
1416
+ const call = 'wrun_draw_label';
1417
+ this.countCall(call, id, bar);
1418
+ this.requireKind(call, id, 'label', bar);
1419
+ const slot = typeof text === 'string' ? NO_TEXT_SLOT : text.slot;
1420
+ const slots = typeof text === 'string' ? NO_SLOT_TEXTS : text.slots;
1421
+ if (slot !== NO_TEXT_SLOT && !slotDeclared(slot, slots.count)) {
1422
+ throw new WrunDrawRefusalError(WRUN3_DRAW_REFUSALS.label_slot_undeclared, `${call}(${id}, ..., slot ${slot}): string slot ${slot} is not declared` +
1423
+ (slots.count === 0 ? ' (declare metadata string_slots)' : ` (declared slots: 0..${slots.count - 1})`), { id, row: bar, ts: this.rowTs, call, arg: `slot=${slot}` });
1424
+ }
1425
+ const existing = this.entries.get(id);
1426
+ if (existing === undefined)
1427
+ this.requireRoom(call, id, 'label', bar);
1428
+ const bad = firstNonFinite([
1429
+ ['x', x],
1430
+ ['y', y],
1431
+ ]);
1432
+ if (bad !== undefined)
1433
+ return this.skipGeometry('wrun_draw_non_finite', 'label', id, bar, call, bad, existing);
1434
+ // The text is the slot's bytes as written on this row at the call (copied: a later rewrite does not follow);
1435
+ // a present empty write is a legal empty label.
1436
+ const written = typeof text === 'string' ? text : slot === NO_TEXT_SLOT ? '' : slots.text(slot);
1437
+ if (written === null) {
1438
+ return this.skipGeometry('wrun_draw_label_slot_absent', 'label', id, bar, call, `slot=${slot}`, existing);
1439
+ }
1440
+ if (existing !== undefined && existing.kind !== 'label') {
1441
+ return this.skipGeometry('wrun_draw_kind_mismatch', 'label', id, bar, call, `id=${id}`, existing);
1442
+ }
1443
+ this.apply('label', call, bar, id, { x, y, text: written }, existing);
1444
+ }
1445
+ /** `points`: `count` points read on demand (the host's memory read, bounds proven there), or the flat points. */
1446
+ polyline(bar, id, points) {
1447
+ const call = 'wrun_draw_polyline';
1448
+ const reader = isWrunPolylineReader(points) ? points : null;
1449
+ const count = reader !== null ? reader.count : points.length / 2;
1450
+ this.countCall(call, id, bar);
1451
+ this.requireKind(call, id, 'polyline', bar);
1452
+ if (count > WRUN3_MAX_POLYLINE_POINTS) {
1453
+ throw new WrunDrawRefusalError(WRUN3_DRAW_REFUSALS.polyline_too_large, `${call}(${id}, ...): ${count} points exceed the ${WRUN3_MAX_POLYLINE_POINTS}-point cap (WRUN3_MAX_POLYLINE_POINTS)`, { id, row: bar, ts: this.rowTs, call, arg: `count=${count}` });
1454
+ }
1455
+ const empty = !Number.isInteger(count) || count < 1;
1456
+ // The points of a call that carries any are read now: the host's memory and pointer bounds are fatal checks.
1457
+ const flat = empty ? null : reader !== null ? reader.read() : points;
1458
+ const existing = this.entries.get(id);
1459
+ if (existing === undefined)
1460
+ this.requireRoom(call, id, 'polyline', bar);
1461
+ // The run's live polyline points after this call (a re-emitted id gives its old points back), checked on a
1462
+ // call that would apply (an unknown id or a live polyline), after the caps: a skip never bypasses it.
1463
+ const held = existing?.kind === 'polyline' ? polylinePointCount(existing) : 0;
1464
+ const live = this.polylinePoints - held + (empty ? 0 : count);
1465
+ const applies = existing === undefined || existing.kind === 'polyline';
1466
+ if (!empty && applies && live > WRUN3_MAX_POLYLINE_POINTS_PER_RUN) {
1467
+ throw new WrunDrawRefusalError(WRUN3_DRAW_REFUSALS.polyline_budget, `${call}(${id}, count ${count}): the run's live polyline points would reach ${live}, over the budget of ` +
1468
+ `${WRUN3_MAX_POLYLINE_POINTS_PER_RUN} per run (WRUN3_MAX_POLYLINE_POINTS_PER_RUN); delete polylines the ` +
1469
+ `Indicator no longer draws or draw fewer points (the budget is what the 8 MiB render result carries at 16 bytes a point)`, { id, row: bar, ts: this.rowTs, call, arg: `count=${count}` });
1470
+ }
1471
+ if (flat === null) {
1472
+ return this.skipGeometry('wrun_draw_polyline_empty', 'polyline', id, bar, call, `count=${count}`, existing);
1473
+ }
1474
+ // One non-finite point skips the whole call, naming the point (points are never dropped one by one).
1475
+ const read = [];
1476
+ for (let at = 0; at < count; at += 1) {
1477
+ const x = flat[at * 2];
1478
+ const y = flat[at * 2 + 1];
1479
+ const bad = firstNonFinite([
1480
+ [`points[${at}].x`, x],
1481
+ [`points[${at}].y`, y],
1482
+ ]);
1483
+ if (bad !== undefined)
1484
+ return this.skipGeometry('wrun_draw_non_finite', 'polyline', id, bar, call, bad, existing);
1485
+ read.push({ x, y });
1486
+ }
1487
+ if (!applies)
1488
+ return this.skipGeometry('wrun_draw_kind_mismatch', 'polyline', id, bar, call, `id=${id}`, existing);
1489
+ this.apply('polyline', call, bar, id, { points: read }, existing);
1490
+ this.polylinePoints = live;
1491
+ }
1492
+ /**
1493
+ * A style call, in the om reference order. Fatal: the id, `handles` declared, the prop known, the prop legal on a
1494
+ * kind the call reaches (the kind an absorbing id's skipped geometry call named, the live handle's), a slot prop
1495
+ * naming an undeclared slot. Then an absorbing id does nothing and records nothing, an id no handle holds skips
1496
+ * `wrun_draw_handle_missing`, and the value skips when it is non-finite (by the range name on a clearing prop,
1497
+ * `wrun_draw_non_finite` on a plain numeric one), a fraction where an integer is required, outside its range or
1498
+ * vocabulary, a slot prop's slot unwritten this row, or a `fill_to` naming the line itself, no live handle or a
1499
+ * live handle of another kind. The patch follows Appendix C's wire column with the set-or-delete rule (0 clears a
1500
+ * word, -1 a slot, 0 a "0 deletes" number).
1501
+ */
1502
+ style(bar, id, prop, value, slots = NO_SLOT_TEXTS) {
1503
+ const call = 'wrun_draw_style';
1504
+ this.countCall(call, id, bar);
1505
+ this.requireId(call, id, bar);
1506
+ const spec = WRUN3_STYLE_PROP_SPECS.find((candidate) => candidate.prop === prop);
1507
+ if (spec === undefined) {
1508
+ throw new WrunDrawRefusalError(WRUN3_DRAW_REFUSALS.prop_unknown, `${call}(${id}, ${prop}, ...): unknown style prop; the props are ${WRUN3_STYLE_PROP_SPECS.map((entry) => `${entry.prop} ${entry.name}`).join(', ')}`, { id, row: bar, ts: this.rowTs, call });
1509
+ }
1510
+ const existing = this.entries.get(id);
1511
+ const absorbing = this.absorbing.get(id);
1512
+ this.requireReachableKind(call, id, bar, prop, spec, existing, absorbing);
1513
+ if (spec.slot === true && Number.isInteger(value) && value !== NO_TEXT_SLOT && !slotDeclared(value, slots.count)) {
1514
+ throw new WrunDrawRefusalError(WRUN3_DRAW_REFUSALS.label_slot_undeclared, `${call}(${id}, ${prop}, ${value}): ${spec.name} names string slot ${value}, which is not declared` +
1515
+ (slots.count === 0
1516
+ ? ' (declare metadata string_slots)'
1517
+ : ` (declared slots: 0..${slots.count - 1}, or -1 to clear)`), { id, row: bar, ts: this.rowTs, call, arg: `${spec.name}=${value}` });
1518
+ }
1519
+ if (absorbing !== undefined)
1520
+ return;
1521
+ if (existing === undefined)
1522
+ return this.skip('wrun_draw_handle_missing', null, id, bar, call, `id=${id}`);
1523
+ const skipped = styleValueSkip(spec, existing.kind, id, value, slots, this.entries);
1524
+ if (skipped !== null)
1525
+ return this.skip(skipped, existing.kind, id, bar, call, `${spec.name}=${value}`);
1526
+ const slotText = spec.slot === true && value !== NO_TEXT_SLOT ? slots.text(value) : null;
1527
+ const props = applyStyle(existing.kind, spec, value, slotText, { ...existing.props });
1528
+ this.commit(existing, { ...existing, props, mutatedBar: bar }, call, bar);
1529
+ }
1530
+ /** A colour call: the style call's fatal checks (the id, `handles` declared, the prop known, the prop legal on a
1531
+ * reachable kind), then an absorbing id does nothing and an id no handle holds skips `wrun_draw_handle_missing`. */
1532
+ color(bar, id, prop, rgba) {
1533
+ const call = 'wrun_draw_color';
1534
+ this.countCall(call, id, bar);
1535
+ this.requireId(call, id, bar);
1536
+ const spec = WRUN3_COLOR_PROP_SPECS.find((candidate) => candidate.prop === prop);
1537
+ if (spec === undefined) {
1538
+ throw new WrunDrawRefusalError(WRUN3_DRAW_REFUSALS.prop_unknown, `${call}(${id}, ${prop}, ...): unknown color prop; the props are ${WRUN3_COLOR_PROP_SPECS.map((entry) => `${entry.prop} ${entry.name}`).join(', ')}`, { id, row: bar, ts: this.rowTs, call });
1539
+ }
1540
+ const existing = this.entries.get(id);
1541
+ const absorbing = this.absorbing.get(id);
1542
+ this.requireReachableKind(call, id, bar, prop, spec, existing, absorbing);
1543
+ if (absorbing !== undefined)
1544
+ return;
1545
+ if (existing === undefined)
1546
+ return this.skip('wrun_draw_handle_missing', null, id, bar, call, `id=${id}`);
1547
+ // A theme token sentinel rides as its word, every other value as
1548
+ // rgba(r,g,b,a): the one rule every host restates (TH-theme-tokens).
1549
+ const color = wrunDrawColorWire(rgba >>> 0);
1550
+ const props = applyColor(existing.kind, spec, color, { ...existing.props });
1551
+ this.commit(existing, { ...existing, props, mutatedBar: bar }, call, bar);
1552
+ }
1553
+ /** Delete never stamps `mutatedBar`; an unknown id is a no-op (the
1554
+ * engine's rule, never a skip), and the id may be reused on a later row (new `seq`). */
1555
+ delete(id, bar) {
1556
+ const call = 'wrun_draw_delete';
1557
+ this.countCall(call, id, bar);
1558
+ this.requireId(call, id, bar);
1559
+ const existing = this.entries.get(id);
1560
+ if (!existing)
1561
+ return;
1562
+ this.journal.push({ id, previous: existing });
1563
+ this.entries.delete(id);
1564
+ this.bytes -= existing.bytes;
1565
+ if (existing.kind === 'polyline')
1566
+ this.polylinePoints -= polylinePointCount(existing);
1567
+ }
1568
+ /** Mark the restore baseline (taken beside the worker's memory snapshot):
1569
+ * the journal starts here, and so do the skipped calls a restore drops. */
1570
+ snapshot() {
1571
+ this.journal = [];
1572
+ this.seqAtSnapshot = this.nextSeq;
1573
+ this.skipsAtSnapshot = this.skips.length;
1574
+ this.skipRestAtSnapshot = this.skipRest;
1575
+ }
1576
+ /** Undo every op since the baseline, in reverse, and hand back the
1577
+ * creation counter, so a re-created handle takes the seq a full run would. The skips made since go with them and
1578
+ * nothing absorbs: a restore lands on a row boundary, and the row run again records its own. */
1579
+ restore() {
1580
+ for (let at = this.journal.length - 1; at >= 0; at -= 1) {
1581
+ const op = this.journal[at];
1582
+ if (op.previous === null)
1583
+ this.entries.delete(op.id);
1584
+ else
1585
+ this.entries.set(op.id, op.previous);
1586
+ }
1587
+ this.journal = [];
1588
+ this.nextSeq = this.seqAtSnapshot;
1589
+ this.bytes = 0;
1590
+ this.polylinePoints = 0;
1591
+ for (const entry of this.entries.values()) {
1592
+ this.bytes += entry.bytes;
1593
+ // The restored entries hold the snapshot's polylines again.
1594
+ if (entry.kind === 'polyline')
1595
+ this.polylinePoints += polylinePointCount(entry);
1596
+ }
1597
+ this.skips.length = this.skipsAtSnapshot;
1598
+ this.skipRest = this.skipRestAtSnapshot;
1599
+ this.absorbing.clear();
1600
+ }
1601
+ /** The live set as wire records, in creation (`seq`) order. */
1602
+ records() {
1603
+ return [...this.entries.values()]
1604
+ .sort((a, b) => a.seq - b.seq)
1605
+ .map((entry) => ({
1606
+ id: wrunHandleWireId(entry.kind, entry.id),
1607
+ kind: entry.kind,
1608
+ pane: entry.pane,
1609
+ createdBar: entry.createdBar,
1610
+ mutatedBar: entry.mutatedBar,
1611
+ props: wireProps(entry.kind, entry.props),
1612
+ }));
1613
+ }
1614
+ /** The run's skipped calls as an answer carries them: nothing when no call was skipped (a clean run's answer keeps
1615
+ * its shape byte for byte), else the first WRUN3_MAX_DRAW_SKIPS records (copies) and the count past them. */
1616
+ drawSkips() {
1617
+ if (this.skips.length === 0 && this.skipRest === 0)
1618
+ return {};
1619
+ return { skipped: this.skips.map((record) => ({ ...record })), skippedCount: this.skipRest };
1620
+ }
1621
+ /** Record a skipped call: in full up to WRUN3_MAX_DRAW_SKIPS a run, counted past it. */
1622
+ skip(code, kind, id, row, call, arg) {
1623
+ if (this.skips.length < WRUN3_MAX_DRAW_SKIPS)
1624
+ this.skips.push({ code, kind, id, row, ts: this.rowTs, call, arg });
1625
+ else
1626
+ this.skipRest += 1;
1627
+ }
1628
+ /** A skipped geometry call: recorded, and unless the id holds a handle of the call's kind (a skipped update keeps
1629
+ * its handle, and its setters that row apply), the id absorbs its style and colour calls for the row. */
1630
+ skipGeometry(code, kind, id, row, call, arg, existing) {
1631
+ this.skip(code, kind, id, row, call, arg);
1632
+ if (existing?.kind !== kind)
1633
+ this.absorbing.set(id, kind);
1634
+ }
1635
+ /** A line or box call: the fatal checks, then the first non-finite coordinate, then the kind of a live id. */
1636
+ corners(kind, call, bar, id, coordinates) {
1637
+ this.countCall(call, id, bar);
1638
+ this.requireKind(call, id, kind, bar);
1639
+ const existing = this.entries.get(id);
1640
+ if (existing === undefined)
1641
+ this.requireRoom(call, id, kind, bar);
1642
+ const bad = firstNonFinite(coordinates);
1643
+ if (bad !== undefined)
1644
+ return this.skipGeometry('wrun_draw_non_finite', kind, id, bar, call, bad, existing);
1645
+ if (existing !== undefined && existing.kind !== kind) {
1646
+ return this.skipGeometry('wrun_draw_kind_mismatch', kind, id, bar, call, `id=${id}`, existing);
1647
+ }
1648
+ const [a, b, c, d] = coordinates.map(([, value]) => value);
1649
+ const geometry = kind === 'line'
1650
+ ? { x1: a, y1: b, x2: c, y2: d }
1651
+ : { left: Math.min(a, c), top: Math.max(b, d), right: Math.max(a, c), bottom: Math.min(b, d) };
1652
+ this.apply(kind, call, bar, id, geometry, existing);
1653
+ }
1654
+ countCall(call, id, bar) {
1655
+ this.rowCalls += 1;
1656
+ if (this.rowCalls > WRUN3_MAX_DRAW_CALLS_PER_ROW) {
1657
+ throw new WrunDrawRefusalError(WRUN3_DRAW_REFUSALS.calls_per_row, `${call}: more than ${WRUN3_MAX_DRAW_CALLS_PER_ROW} draw calls on one row (WRUN3_MAX_DRAW_CALLS_PER_ROW, a skipped call included)`, { id, row: bar, ts: this.rowTs, call });
1658
+ }
1659
+ }
1660
+ /** The id is an integer >= 0 and the sheet declares `handles` (the om hosts' `requireId`). */
1661
+ requireId(call, id, bar) {
1662
+ if (!Number.isInteger(id) || id < 0) {
1663
+ throw new WrunDrawRefusalError(WRUN3_DRAW_REFUSALS.id_negative, `${call}(${id}, ...): handle ids are integers >= 0 chosen by the module`, { row: bar, ts: this.rowTs, call, arg: `id=${id}` });
1664
+ }
1665
+ if (!this.declared) {
1666
+ throw new WrunDrawRefusalError(WRUN3_DRAW_REFUSALS.kind_undeclared, `${call}(${id}, ...): this run declares no handles (declare metadata handles under abi_version "wrun-3")`, { id, row: bar, ts: this.rowTs, call });
1667
+ }
1668
+ }
1669
+ /** The id, then the call's kind declared in the sheet's `handles` section. */
1670
+ requireKind(call, id, kind, bar) {
1671
+ this.requireId(call, id, bar);
1672
+ if (this.defaults[kind] === undefined) {
1673
+ throw new WrunDrawRefusalError(WRUN3_DRAW_REFUSALS.kind_undeclared, `${call}(${id}, ...): the sheet's handles section does not declare '${kind}' (declare handles.${kind} to enable it)`, { id, row: bar, ts: this.rowTs, call });
1674
+ }
1675
+ }
1676
+ /** The live-handle caps a create must pass, checked whether or not the call is then skipped. */
1677
+ requireRoom(call, id, kind, bar) {
1678
+ let ofKind = 0;
1679
+ for (const entry of this.entries.values())
1680
+ if (entry.kind === kind)
1681
+ ofKind += 1;
1682
+ if (ofKind + 1 > WRUN3_MAX_LIVE_HANDLES_PER_KIND) {
1683
+ throw new WrunDrawRefusalError(WRUN3_DRAW_REFUSALS.kind_limit, `${call}(${id}, ...): ${ofKind} live ${kind} handles already exist; the cap is ${WRUN3_MAX_LIVE_HANDLES_PER_KIND} per kind (WRUN3_MAX_LIVE_HANDLES_PER_KIND); delete the ones the Indicator no longer needs`, { id, row: bar, ts: this.rowTs, call });
1684
+ }
1685
+ if (this.entries.size + 1 > WRUN3_MAX_LIVE_HANDLES_TOTAL) {
1686
+ throw new WrunDrawRefusalError(WRUN3_DRAW_REFUSALS.total_limit, `${call}(${id}, ...): ${this.entries.size} live handles already exist; the cap is ${WRUN3_MAX_LIVE_HANDLES_TOTAL} in total (WRUN3_MAX_LIVE_HANDLES_TOTAL)`, { id, row: bar, ts: this.rowTs, call });
1687
+ }
1688
+ }
1689
+ /** A style or colour prop must apply to a kind the call reaches (the kind an absorbing id's skipped geometry call
1690
+ * named, then the live handle's): a prop none of them takes is a code mistake whatever the row skipped. An id
1691
+ * with neither reaches no kind, and its call skips as a missing handle instead. */
1692
+ requireReachableKind(call, id, bar, prop, spec, existing, absorbing) {
1693
+ const kinds = [...(absorbing === undefined ? [] : [absorbing]), ...(existing === undefined ? [] : [existing.kind])];
1694
+ if (kinds.length === 0 || kinds.some((kind) => spec.kinds.includes(kind)))
1695
+ return;
1696
+ throw new WrunDrawRefusalError(WRUN3_DRAW_REFUSALS.prop_unsupported, `${call}(${id}, ${prop}, ...): ${spec.name} is not supported on ${kinds[0]} drawings (legal on ${spec.kinds.join(', ')})`, { id, row: bar, ts: this.rowTs, call });
1697
+ }
1698
+ /** Apply a geometry call every check passed: create on an unknown id (style from the sheet defaults,
1699
+ * `createdBar = mutatedBar = row`, the next seq), update the id's handle of the same kind. An id that applies
1700
+ * absorbs nothing more this row. The byte account is the call's last rule (the chart's own: 16 bytes a point). */
1701
+ apply(kind, call, bar, id, geometry, existing) {
1702
+ this.absorbing.delete(id);
1703
+ if (existing !== undefined) {
1704
+ this.commit(existing, { ...existing, props: { ...existing.props, ...geometry }, mutatedBar: bar }, call, bar);
1705
+ return;
1706
+ }
1707
+ // requireKind proved the kind declared.
1708
+ const defaults = this.defaults[kind];
1709
+ const props = {
1710
+ ...wrunHandleInitialProps(kind, defaults),
1711
+ ...(defaults.anchor !== undefined ? { anchor: defaults.anchor } : {}),
1712
+ ...geometry,
1713
+ };
1714
+ const entry = {
1715
+ kind,
1716
+ id,
1717
+ seq: this.nextSeq,
1718
+ pane: defaults.panel === 'lower' ? 'offchart' : 'onchart',
1719
+ createdBar: bar,
1720
+ mutatedBar: bar,
1721
+ props,
1722
+ bytes: entryBytes(props),
1723
+ };
1724
+ this.requireBudget(call, id, bar, this.bytes + entry.bytes);
1725
+ this.journal.push({ id, previous: null });
1726
+ this.entries.set(id, entry);
1727
+ this.nextSeq += 1;
1728
+ this.bytes += entry.bytes;
1729
+ }
1730
+ commit(existing, next, call, bar) {
1731
+ next.bytes = entryBytes(next.props);
1732
+ this.requireBudget(call, existing.id, bar, this.bytes - existing.bytes + next.bytes);
1733
+ this.journal.push({ id: existing.id, previous: existing });
1734
+ this.entries.set(existing.id, next);
1735
+ this.bytes += next.bytes - existing.bytes;
1736
+ }
1737
+ requireBudget(call, id, bar, bytes) {
1738
+ if (bytes > this.limitBytes) {
1739
+ throw new WrunDrawRefusalError(WRUN3_DRAW_REFUSALS.render_result_too_large, `${call}(${id}, ...): the live handle set would account ${bytes} bytes, over the ${this.limitBytes}-byte render result limit`, { id, row: bar, ts: this.rowTs, call });
1740
+ }
1741
+ }
1742
+ }
1743
+ /** A polyline call carrying a reader (the host's memory read) rather than the flat points. */
1744
+ function isWrunPolylineReader(points) {
1745
+ return typeof points.read === 'function';
1746
+ }
1747
+ /** A declared string slot index: an integer 0..count-1. */
1748
+ function slotDeclared(slot, count) {
1749
+ return Number.isInteger(slot) && slot >= 0 && slot < count;
1750
+ }
1751
+ /** The skip code a style value earns on a live handle of `kind`, in the om reference order, or null when the value
1752
+ * applies: non-finite (by the range name on a clearing prop), a fraction where an integer is required, an index
1753
+ * outside its vocabulary, a slot prop's slot unwritten this row, a number outside its range, then a target prop's
1754
+ * own id, a missing target and a target of another kind. */
1755
+ function styleValueSkip(spec, kind, id, value, slots, entries) {
1756
+ if (!Number.isFinite(value)) {
1757
+ return wrunDrawStylePropClears(spec) ? 'wrun_draw_style_out_of_range' : 'wrun_draw_non_finite';
1758
+ }
1759
+ if (spec.integer === true && !Number.isInteger(value))
1760
+ return 'wrun_draw_style_out_of_range';
1761
+ if (spec.values !== undefined) {
1762
+ if (value < 0 || value >= spec.values.length)
1763
+ return 'wrun_draw_style_out_of_range';
1764
+ }
1765
+ else if (spec.words !== undefined) {
1766
+ // 0 clears; 1..n selects a word (n capped per kind by maxByKind).
1767
+ const max = spec.maxByKind?.[kind] ?? spec.words.length;
1768
+ if (value < 0 || value > max)
1769
+ return 'wrun_draw_style_out_of_range';
1770
+ }
1771
+ else if (spec.slot === true) {
1772
+ // -1 clears; any other value names a declared slot (the fatal check proved it), written on THIS row.
1773
+ if (value !== NO_TEXT_SLOT && slots.text(value) === null)
1774
+ return 'wrun_draw_label_slot_absent';
1775
+ }
1776
+ else if ((spec.min !== undefined && value < spec.min) || (spec.max !== undefined && value > spec.max)) {
1777
+ return 'wrun_draw_style_out_of_range';
1778
+ }
1779
+ if (spec.target !== undefined && value >= 0) {
1780
+ // A target is checked at the call only: a later delete of it is no skip (its wire id stops resolving).
1781
+ if (value === id)
1782
+ return 'wrun_draw_style_out_of_range';
1783
+ const target = entries.get(value);
1784
+ if (target === undefined)
1785
+ return 'wrun_draw_handle_missing';
1786
+ if (target.kind !== spec.target)
1787
+ return 'wrun_draw_kind_mismatch';
1788
+ }
1789
+ return null;
1790
+ }
1791
+ /** Apply a validated style value to a copy of the entry's props (Appendix
1792
+ * C's wire column, the om reference ledger's applyStyle): a word prop's 0,
1793
+ * a slot prop's -1 and a "0 deletes" numeric prop's 0 remove the wire key
1794
+ * (the handle falls back to the sheet default); `slotText` is the slot's
1795
+ * text for a slot prop (null clears). A line's `fillTo` stays the raw
1796
+ * target id here; `wireProps` projects the pair. */
1797
+ function applyStyle(kind, spec, value, slotText, props) {
1798
+ const setOrDelete = (key, present, wire) => {
1799
+ if (present)
1800
+ props[key] = wire;
1801
+ else
1802
+ delete props[key];
1803
+ };
1804
+ switch (spec.name) {
1805
+ case 'width':
1806
+ props.width = value;
1807
+ break;
1808
+ case 'line_style':
1809
+ if (kind === 'box')
1810
+ props.borderStyle = WRUN3_LINE_STYLES[value];
1811
+ else
1812
+ props.lineStyle = WRUN3_LINE_STYLES[value];
1813
+ break;
1814
+ case 'opacity':
1815
+ if (kind === 'box')
1816
+ props.fillOpacity = value;
1817
+ else
1818
+ props.opacity = value;
1819
+ break;
1820
+ case 'size':
1821
+ if (kind === 'box')
1822
+ props.textSize = value;
1823
+ else
1824
+ props.size = value;
1825
+ break;
1826
+ case 'extend':
1827
+ props.extend = WRUN3_EXTENDS[value];
1828
+ break;
1829
+ case 'border_width':
1830
+ props.borderWidth = value;
1831
+ break;
1832
+ case 'zorder':
1833
+ props.zOrder = value;
1834
+ break;
1835
+ case 'anchor':
1836
+ setOrDelete('anchor', value !== 0, WRUN_DRAWING_ANCHORS[value - 1]);
1837
+ break;
1838
+ case 'align':
1839
+ setOrDelete('align', value !== 0, WRUN_LABEL_ALIGNS[value - 1]);
1840
+ break;
1841
+ case 'fill_to':
1842
+ setOrDelete('fillTo', value !== -1, value);
1843
+ break;
1844
+ case 'font_weight':
1845
+ setOrDelete('fontWeight', value !== 0, WRUN3_FONT_WEIGHT_CSS[WRUN_FONT_WEIGHTS[value - 1]]);
1846
+ break;
1847
+ case 'font_family':
1848
+ setOrDelete('fontFamily', value !== 0, WRUN_FONT_FAMILIES[value - 1]);
1849
+ break;
1850
+ case 'valign':
1851
+ setOrDelete('valign', value !== 0, WRUN_VALIGNS[value - 1]);
1852
+ break;
1853
+ case 'padding':
1854
+ props.padding = value;
1855
+ break;
1856
+ case 'max_width':
1857
+ setOrDelete('maxWidth', value !== 0, value);
1858
+ break;
1859
+ case 'corner_radius':
1860
+ props.radius = value;
1861
+ break;
1862
+ case 'glow':
1863
+ setOrDelete('glow', value !== 0, value);
1864
+ break;
1865
+ case 'label_style':
1866
+ setOrDelete('style', value !== 0, WRUN3_LABEL_STYLES[value - 1]);
1867
+ break;
1868
+ case 'emblem_shape':
1869
+ setOrDelete('emblemShape', value !== 0, WRUN3_EMBLEM_SHAPES[value - 1]);
1870
+ break;
1871
+ case 'sticky_right':
1872
+ setOrDelete('stickyRight', value !== 0, true);
1873
+ break;
1874
+ case 'axis_label':
1875
+ setOrDelete('axisLabel', value !== 0, WRUN3_AXIS_LABELS[value - 1]);
1876
+ break;
1877
+ case 'tooltip_slot':
1878
+ setOrDelete('tooltip', slotText !== null, slotText);
1879
+ break;
1880
+ case 'text_slot':
1881
+ setOrDelete('text', slotText !== null, slotText);
1882
+ break;
1883
+ case 'group':
1884
+ setOrDelete('group', value !== 0, value);
1885
+ break;
1886
+ case 'fit_group':
1887
+ setOrDelete('fitGroup', value !== 0, value);
1888
+ break;
1889
+ case 'box_shape':
1890
+ // Only the ellipse rides the wire: rect (1) is the default and deletes
1891
+ // the key like 0.
1892
+ setOrDelete('shape', WRUN3_BOX_SHAPES[value - 1] === 'ellipse', 'ellipse');
1893
+ break;
1894
+ case 'gradient_direction':
1895
+ if (value === 0) {
1896
+ delete props.gradientDirection;
1897
+ delete props.gradient;
1898
+ }
1899
+ else {
1900
+ props.gradientDirection = WRUN_GRADIENT_DIRECTIONS[value - 1];
1901
+ }
1902
+ break;
1903
+ case 'arrow':
1904
+ setOrDelete('arrow', value !== 0, WRUN3_ARROWS[value - 1]);
1905
+ break;
1906
+ case 'closed':
1907
+ setOrDelete('closed', value !== 0, true);
1908
+ break;
1909
+ case 'smooth':
1910
+ setOrDelete('smooth', value !== 0, true);
1911
+ break;
1912
+ case 'angle':
1913
+ setOrDelete('angle', value !== 0, value);
1914
+ break;
1915
+ }
1916
+ return props;
1917
+ }
1918
+ /** Apply a colour prop's wire text to a copy of the entry's props: stroke
1919
+ * is a box's border and every other kind's colour; fill is a box's two
1920
+ * fill keys, a label's background, a polyline's polygon fill, and a line's
1921
+ * fill half (kept raw, on the wire only beside its fill_to target); border,
1922
+ * glow, emblem and text land on their own keys; gradient_end snapshots the
1923
+ * box's fill colour at the call as the first stop and defaults the
1924
+ * direction to vertical. */
1925
+ function applyColor(kind, spec, color, props) {
1926
+ switch (spec.name) {
1927
+ case 'stroke':
1928
+ if (kind === 'box')
1929
+ props.borderColor = color;
1930
+ else
1931
+ props.color = color;
1932
+ break;
1933
+ case 'fill':
1934
+ if (kind === 'box') {
1935
+ props.fillColor = color;
1936
+ props.backgroundColor = color;
1937
+ }
1938
+ else if (kind === 'line' || kind === 'polyline') {
1939
+ props.fillColor = color;
1940
+ }
1941
+ else {
1942
+ props.backgroundColor = color;
1943
+ }
1944
+ break;
1945
+ case 'border':
1946
+ props.border = color;
1947
+ break;
1948
+ case 'glow':
1949
+ props.glowColor = color;
1950
+ break;
1951
+ case 'emblem':
1952
+ props.emblemColor = color;
1953
+ break;
1954
+ case 'gradient_end':
1955
+ props.gradient = [props.backgroundColor, color];
1956
+ if (props.gradientDirection === undefined)
1957
+ props.gradientDirection = 'vertical';
1958
+ break;
1959
+ case 'text':
1960
+ props.textColor = color;
1961
+ break;
1962
+ }
1963
+ return props;
1964
+ }
1965
+ /** Convert only the time axis, once, on a copy of the current raw geometry.
1966
+ * A line's raw `fillTo` (the target's numeric id) and `fillColor` reach the
1967
+ * wire as a pair only (the target's wire id beside the colour), else
1968
+ * neither key appears. */
1969
+ function wireProps(kind, props) {
1970
+ const copy = { ...props };
1971
+ if (kind === 'line') {
1972
+ if (typeof props.fillTo === 'number' && typeof props.fillColor === 'string') {
1973
+ copy.fillTo = wrunHandleWireId('line', props.fillTo);
1974
+ }
1975
+ else {
1976
+ delete copy.fillTo;
1977
+ delete copy.fillColor;
1978
+ }
1979
+ }
1980
+ if (Array.isArray(props.gradient))
1981
+ copy.gradient = [...props.gradient];
1982
+ const xScale = props.anchor === undefined || props.anchor === 'top' || props.anchor === 'bottom' ? 1000 : 1;
1983
+ for (const key of ['x', 'x1', 'x2', 'left', 'right']) {
1984
+ if (typeof props[key] === 'number')
1985
+ copy[key] = props[key] * xScale;
1986
+ }
1987
+ if (Array.isArray(props.points)) {
1988
+ copy.points = props.points.map((point) => ({ x: point.x * xScale, y: point.y }));
1989
+ }
1990
+ return copy;
1991
+ }
1992
+ // ---------------------------------------------------------------------------
1993
+ // From the host to the adapter: the ledger rides beside the rows.
1994
+ // ---------------------------------------------------------------------------
1995
+ /** The run's handle records, keyed by the rows array the host handed back.
1996
+ * Every integration route hands that same array from the host to the
1997
+ * run-result adapter (the full run stores it in the live context, the tick
1998
+ * merges into it), so the ledger reaches `buildWrunRunResult` without a
1999
+ * second parameter threading through every caller. A wrun-1 or wrun-2 run
2000
+ * attaches nothing. */
2001
+ const handlesByRows = new WeakMap();
2002
+ export function attachWrunHandles(rows, handles) {
2003
+ handlesByRows.set(rows, handles);
2004
+ }
2005
+ export function wrunHandlesOf(rows) {
2006
+ return handlesByRows.get(rows);
2007
+ }
2008
+ /** The run's skipped draw calls, keyed by the same rows array as its handle records (the host's unpack attaches
2009
+ * them beside the handles; a run that skipped nothing attaches nothing). */
2010
+ const skipsByRows = new WeakMap();
2011
+ export function attachWrunDrawSkips(rows, skips) {
2012
+ if (skips.skipped !== undefined && skips.skipped.length > 0)
2013
+ skipsByRows.set(rows, skips);
2014
+ }
2015
+ export function wrunDrawSkipsOf(rows) {
2016
+ return skipsByRows.get(rows);
2017
+ }
2018
+ const SKIP_CALLS = new Set([
2019
+ 'wrun_draw_line',
2020
+ 'wrun_draw_box',
2021
+ 'wrun_draw_label',
2022
+ 'wrun_draw_polyline',
2023
+ 'wrun_draw_style',
2024
+ 'wrun_draw_color',
2025
+ ]);
2026
+ function isWrunDrawSkip(value) {
2027
+ if (!isRecord(value))
2028
+ return false;
2029
+ const { code, kind, id, row, ts, call, arg } = value;
2030
+ return (typeof code === 'string' &&
2031
+ isWrunDrawSkipCode(code) &&
2032
+ (kind === null || (typeof kind === 'string' && WRUN3_HANDLE_KINDS.includes(kind))) &&
2033
+ typeof id === 'number' &&
2034
+ typeof row === 'number' &&
2035
+ typeof ts === 'number' &&
2036
+ typeof call === 'string' &&
2037
+ SKIP_CALLS.has(call) &&
2038
+ typeof arg === 'string');
2039
+ }
2040
+ /** The skipped calls an answer read off a wire carries (the cloud's frame: `skipped`, `skippedCount`), kept to the
2041
+ * records that read as records and at most WRUN3_MAX_DRAW_SKIPS of them; nothing when none does. */
2042
+ export function wrunDrawSkipsFromWire(skipped, skippedCount) {
2043
+ if (!Array.isArray(skipped))
2044
+ return {};
2045
+ const records = skipped.filter(isWrunDrawSkip).slice(0, WRUN3_MAX_DRAW_SKIPS);
2046
+ if (records.length === 0)
2047
+ return {};
2048
+ const rest = typeof skippedCount === 'number' && Number.isInteger(skippedCount) && skippedCount > 0 ? skippedCount : 0;
2049
+ return { skipped: records.map((record) => ({ ...record })), skippedCount: rest };
2050
+ }