@orangecharts/wrun-chart-host 0.17.0 → 0.19.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 (43) hide show
  1. package/README.md +2 -0
  2. package/dist/constants/feature-flags.constants.d.ts +1 -6
  3. package/dist/constants/feature-flags.constants.js +17 -87
  4. package/dist/host-env.d.ts +2 -0
  5. package/dist/host-ports.types.d.ts +10 -0
  6. package/dist/index.d.ts +2 -0
  7. package/dist/index.js +2 -0
  8. package/dist/market-data/venues/index.d.ts +128 -143
  9. package/dist/market-data/venues/index.js +2 -2
  10. package/dist/market-data/venues/stocks.d.ts +1 -1
  11. package/dist/market-data/venues/stocks.js +2 -4
  12. package/dist/settings-templates/frvp-fields.js +28 -19
  13. package/dist/settings-templates/index.d.ts +25 -0
  14. package/dist/settings-templates/index.js +62 -2
  15. package/dist/settings-templates/indicator-fields.d.ts +35 -0
  16. package/dist/settings-templates/indicator-fields.js +261 -114
  17. package/dist/settings-templates/market-bound.d.ts +214 -0
  18. package/dist/settings-templates/market-bound.js +369 -0
  19. package/dist/utility/chart/cme-user-scripts-gate.util.d.ts +8 -8
  20. package/dist/utility/chart/cme-user-scripts-gate.util.js +8 -8
  21. package/dist/utility/chart/governed-lanes-gate.util.d.ts +6 -6
  22. package/dist/utility/chart/governed-lanes-gate.util.js +6 -6
  23. package/dist/utility/chart/index-otc.leaf.d.ts +13 -0
  24. package/dist/utility/chart/index-otc.leaf.js +18 -0
  25. package/dist/utility/chart/server-built-bars.util.d.ts +4 -0
  26. package/dist/utility/chart/server-built-bars.util.js +18 -0
  27. package/dist/utility/v2/gate-plane.util.d.ts +7 -0
  28. package/dist/utility/v2/gate-plane.util.js +6 -0
  29. package/dist/utility/wrun/wrun-dark-pool.util.js +1 -1
  30. package/dist/utility/wrun/wrun-declared-warmup.util.d.ts +1 -1
  31. package/dist/utility/wrun/wrun-lane-warmup.util.d.ts +10 -0
  32. package/dist/utility/wrun/wrun-lane-warmup.util.js +32 -0
  33. package/dist/utility/wrun/wrun-live-intake.util.d.ts +3 -0
  34. package/dist/utility/wrun/wrun-live-intake.util.js +6 -0
  35. package/dist/utility/wrun/wrun-live-tick.util.js +5 -0
  36. package/dist/utility/wrun/wrun-overlay-drivers.util.d.ts +2 -0
  37. package/dist/utility/wrun/wrun-overlay-recovery.util.js +1 -1
  38. package/dist/utility/wrun/wrun-overlay-run.util.d.ts +3 -1
  39. package/dist/utility/wrun/wrun-overlay-run.util.js +128 -21
  40. package/dist/utility/wrun/wrun-replay-lane.util.js +3 -1
  41. package/dist/utility/wrun/wrun-twin-lookback.util.d.ts +4 -0
  42. package/dist/utility/wrun/wrun-twin-lookback.util.js +17 -0
  43. package/package.json +7 -7
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Market-bound values: a value measured or typed on one market means nothing on another (a heatmap colour range of
3
+ * 20..55 contracts on one future is noise on a coin that trades millions). So a row that holds such values also holds
4
+ * a stamp of the market they were measured or typed on, and a reader trusts the values only when the stamp names the
5
+ * market it draws.
6
+ *
7
+ * The stamp is `<market key>#<signature>`. The signature is a short hash of the bound values themselves, so a writer
8
+ * that changes the values without writing a new stamp (an older client, or a write site that forgot the stamp)
9
+ * leaves a stamp that no longer matches, and the reader treats the row as unkeyed instead of trusting a wrong key.
10
+ *
11
+ * A heatmap row's bound values all live in its `meta`: `range`, `outerRange`, `rangeSource` and `sizeCeil`. Its stamp
12
+ * is the row's top-level `boundKey`, and its top-level `boundByMarket` keeps the typed values of markets the row left
13
+ * (a list, at most BOUND_STASH_CAP entries, oldest out), so a return to a market gives its typed values back.
14
+ *
15
+ * A typed threshold (a footprint's or a volume profile's volume filter, the Big Trades floors) is bound the same way
16
+ * when it is typed in the market's native unit: the registry (./indicator-fields) names those fields (`quantity:
17
+ * 'bound'` with `keep`), the unit they are bound in (`boundWhen`) and their group companions (`with`). Its row holds the
18
+ * same two top-level fields, stamped with marketBoundKey (`<EXCHANGE>-<UNIT>-<SYMBOL>-<INTERVAL>`) and the signature
19
+ * of the typed values (marketBoundSignature), and reconcileMarketBound is the one decision a reader makes when the row
20
+ * meets a market: keep (OWN), swap for that market's remembered or default values (FOREIGN), or trust and stamp
21
+ * (UNKEYED). A heatmap row keeps its own path (settleHeatmapScale on web): reconcileMarketBound leaves it alone.
22
+ *
23
+ * This file imports only the registry, holds no state and never mutates an input. Every input is read defensively: a
24
+ * stored document can hold anything.
25
+ */
26
+ import { type BoundCondition, type BoundKeep } from './indicator-fields.js';
27
+ /** What a heatmap's scale was measured on. Every part is passed in: the caller has already resolved them. */
28
+ export interface HeatmapKeyParts {
29
+ /** The indicator type id (ORDERBOOK_HEATMAP, AGGREGATED_ORDERBOOK_HEATMAP, ...). */
30
+ type: string;
31
+ exchange: string;
32
+ symbol: string;
33
+ coin: string;
34
+ /** The size unit. Missing (null, undefined) or empty spells 'Coin'. */
35
+ currency?: string | null;
36
+ /** The app's interval id, in the case the app holds it: '1m' is a minute, '1M' a month. */
37
+ interval: string;
38
+ /** The resolution tier. Missing spells 'HD'. */
39
+ resolution?: string | null;
40
+ /** The aggregated heatmap's venue set. Its order does not matter. */
41
+ exchanges?: readonly string[] | null;
42
+ }
43
+ /**
44
+ * The market key of a heatmap's scale, in the spelling of the account's saved heatmap settings map:
45
+ * `<head>-<unit>-<ticker>-<interval>-<tier>`, or `AGGR-<venues>-<unit>-<ticker>-<interval>-<tier>` for an aggregated
46
+ * heatmap with venues, all upper case.
47
+ * - head: AGGR for an aggregated type, HYPERLIQUID_TPSL for a TP/SL type, HYPERLIQUID for another Hyperliquid type
48
+ * (tested in that order), else the exchange.
49
+ * - ticker: the coin for those three heads (they span venues), else the symbol.
50
+ * - unit: the currency, or 'Coin' when it is missing or empty.
51
+ * - interval: a month id ('1M') is spelled '1MO', so it never meets the minute ('1m' spells '1M').
52
+ * - tier: the resolution, or 'HD'.
53
+ * - venues: a sorted copy of the venue set, joined with nothing.
54
+ */
55
+ export declare function heatmapMarketKey(parts: HeatmapKeyParts): string;
56
+ /** The stamp a row holds: `${key}#${signature}`. */
57
+ export declare function stampBoundKey(key: string, signature: string): string;
58
+ /**
59
+ * A stamp read back: the key and the signature, split on the LAST '#' (a key may hold a '#', a signature never does).
60
+ * Null for a missing, empty or malformed stamp (not a string, no '#', an empty key, or a signature that is not
61
+ * base 36).
62
+ */
63
+ export declare function parseBoundKey(stamp: unknown): {
64
+ key: string;
65
+ signature: string;
66
+ } | null;
67
+ /**
68
+ * A short signature of a list of values: FNV-1a 32 bit over the UTF-16 code units of JSON.stringify(values), as an
69
+ * unsigned number in base 36. An undefined value counts as null, so a missing part and a cleared part sign the same.
70
+ */
71
+ export declare function boundSignature(values: readonly unknown[]): string;
72
+ /**
73
+ * The signature of a heatmap row's scale, from its meta, over the parts in this fixed order: range.min, range.max,
74
+ * outerRange.min, outerRange.max, rangeSource, sizeCeil. A missing part (a missing range gives two) counts as null.
75
+ */
76
+ export declare function heatmapScaleSignature(meta: {
77
+ range?: unknown;
78
+ outerRange?: unknown;
79
+ rangeSource?: unknown;
80
+ sizeCeil?: unknown;
81
+ } | null | undefined): string;
82
+ /** The most markets a row keeps typed values for. */
83
+ export declare const BOUND_STASH_CAP = 8;
84
+ /** The typed values a row held on one market it left, under that market's key. */
85
+ export interface BoundStashEntry {
86
+ key: string;
87
+ values: Record<string, unknown>;
88
+ }
89
+ /**
90
+ * A new stash list: any entry for `key` removed, the new entry appended last, and the oldest entries dropped past
91
+ * BOUND_STASH_CAP. Malformed entries of the given list are dropped. Never mutates its inputs.
92
+ */
93
+ export declare function stashBound(list: readonly BoundStashEntry[] | null | undefined, key: string, values: Record<string, unknown>): BoundStashEntry[];
94
+ /**
95
+ * The stashed values for `key` (null when none) and a new list without that entry. Tolerates a malformed list (gives
96
+ * null and []) and drops malformed entries. Never mutates its input.
97
+ */
98
+ export declare function takeBound(list: unknown, key: string): {
99
+ values: Record<string, unknown> | null;
100
+ list: BoundStashEntry[];
101
+ };
102
+ /** Whether a type's market-bound values are a heatmap's scale (wave 1's path, never reconcileMarketBound). */
103
+ export declare function isHeatmapScaleType(type: unknown): boolean;
104
+ /**
105
+ * What a row's market-bound values were typed or measured on. Every part is passed in, resolved by the caller: the
106
+ * row's market, its unit field as the row holds it, and the interval of the chart the row draws on.
107
+ */
108
+ export interface MarketBoundKeyParts {
109
+ /** The indicator type id. */
110
+ type: string;
111
+ exchange: string;
112
+ symbol: string;
113
+ /** The coin: read only for a heatmap type (HeatmapKeyParts.coin). */
114
+ coin?: string | null;
115
+ /** The row's unit (`currency`). Missing (null, undefined) or empty spells 'Coin'. */
116
+ currency?: string | null;
117
+ /** The app's interval id, in the case the app holds it: '1m' is a minute, '1M' a month. */
118
+ interval: string;
119
+ /** A heatmap's resolution tier; no other type reads it. */
120
+ resolution?: string | null;
121
+ /** An aggregated heatmap's venue set; no other type reads it. */
122
+ exchanges?: readonly string[] | null;
123
+ }
124
+ /**
125
+ * The market key of a row's market-bound values. A heatmap type gets heatmapMarketKey(parts) unchanged. Any other type
126
+ * gets `<EXCHANGE>-<UNIT>-<SYMBOL>-<INTERVAL>`, upper case, spelled as the heatmap key spells them (a missing or empty
127
+ * unit is 'Coin', a month interval '1M' is '1MO', a minute '1m' is '1M'), with no tier and no venue set.
128
+ */
129
+ export declare function marketBoundKey(parts: MarketBoundKeyParts): string;
130
+ /**
131
+ * One reconciled unit of a type: a kept bound field (`key`) and its group companions, kept, given back and removed
132
+ * together (`keys`: the field first, then its companions in declared order).
133
+ */
134
+ export interface BoundFieldUnit {
135
+ key: string;
136
+ keys: readonly string[];
137
+ keep: BoundKeep;
138
+ /** The native unit the field is bound in; absent means bound in every unit. */
139
+ boundWhen?: BoundCondition;
140
+ }
141
+ /**
142
+ * The reconciled units of a type, in the registry's declared order: every settings-bag field with `quantity: 'bound'`
143
+ * and a `keep`, with its `with` companions (a companion is never a unit of its own). None for a heatmap type (its own
144
+ * path), a technical script (its inputs are the script's) or a type without such a field. Frozen and cached.
145
+ */
146
+ export declare function boundFieldsOf(type: string): readonly BoundFieldUnit[];
147
+ /**
148
+ * Whether a condition holds on a settings bag: no condition always holds; otherwise the sibling's value (undefined
149
+ * when the bag or the key is missing) is one of `oneOf` when that is named and none of `noneOf` when that is named.
150
+ */
151
+ export declare function isBoundNow(condition: BoundCondition | null | undefined, settings: unknown): boolean;
152
+ /** The units of a type that are bound right now on this bag (each unit's `boundWhen` read off the bag). */
153
+ export declare function boundUnitsNow(type: string, settings: unknown): readonly BoundFieldUnit[];
154
+ /**
155
+ * The signature of a threshold row: boundSignature over the values of the type's typed units that are bound right now,
156
+ * each unit's keys in order, the units in the registry's declared order, a missing value as null. A non-record bag reads
157
+ * as empty.
158
+ */
159
+ export declare function marketBoundSignature(type: string, settings: unknown): string;
160
+ /**
161
+ * The row after a user's edit of its bound values (they were just typed on the live market): `boundKey` stamped with
162
+ * `liveKey` and the row's signature. The same object when the stamp is already that one, and for a type with no
163
+ * reconciled unit or a bag that is no record.
164
+ */
165
+ export declare function stampMarketBound<T extends object>(type: string, settings: T, liveKey: string): T;
166
+ /**
167
+ * What one reconcile did: `none` (no unit bound right now, a heatmap or a script, no live key, or a bag that is no
168
+ * record), `own` (the stamp names the live market and signs the values), `key-mismatch` (the values belong to another
169
+ * market and were swapped for the live market's), `unkeyed-stamped` (no valid stamp: the values are trusted here).
170
+ */
171
+ export type MarketBoundVerdict = 'none' | 'own' | 'key-mismatch' | 'unkeyed-stamped';
172
+ export interface ReconcileMarketBoundOptions {
173
+ /**
174
+ * The values to write where the live market has none remembered, by field key (a group's companions by their own
175
+ * keys). A unit whose field is not named here is removed, so its reader uses its own default.
176
+ */
177
+ defaults?: Readonly<Record<string, unknown>> | null;
178
+ /**
179
+ * The market key an unkeyed row was saved on, when the caller knows it (a workspace or layout document that names its
180
+ * market): the row is then read as stamped with it and judged OWN or FOREIGN.
181
+ */
182
+ unkeyedAs?: string | null;
183
+ }
184
+ export interface MarketBoundReconciliation<T> {
185
+ /** The settings to keep: the same object when nothing changed, else a new one. */
186
+ settings: T;
187
+ verdict: MarketBoundVerdict;
188
+ /** The key the row was read as (its stamp's, or `unkeyedAs`); null for a row with no valid stamp. */
189
+ rowKey: string | null;
190
+ liveKey: string;
191
+ /** FOREIGN: a value remembered for the live market came back. */
192
+ restored: boolean;
193
+ /** FOREIGN: typed values were kept under the row's old key. */
194
+ stashed: boolean;
195
+ }
196
+ /**
197
+ * The one decision a reader makes when a threshold row meets the live market `liveKey` (contract section 6). Pure:
198
+ * reads its inputs defensively and never mutates them.
199
+ * - OWN (the stamp parses, its signature matches, its key is `liveKey`): unchanged, the same object.
200
+ * - FOREIGN (the stamp parses and signs, another key): the typed units bound right now are kept under the stamp's key
201
+ * in `boundByMarket` (measured ones are dropped); each unit takes the live market's remembered values out of the
202
+ * stash, else `options.defaults`, else is removed; the row is stamped with `liveKey`. A group is one unit.
203
+ * - UNKEYED (no stamp, a malformed one, or a signature that does not match): the values are trusted on this market and
204
+ * stamped with `liveKey`; with `options.unkeyedAs` the row is first read as stamped with that key (OWN or FOREIGN).
205
+ * A field not bound right now (its unit is notional) is never kept, reset or signed. A heatmap type, a script, a type
206
+ * without a reconciled unit and a row with no unit bound right now come back untouched (`none`).
207
+ */
208
+ export declare function reconcileMarketBound<T extends object>(type: string, settings: T, liveKey: string, options?: ReconcileMarketBoundOptions | null): MarketBoundReconciliation<T>;
209
+ /**
210
+ * The paths of a sample settings bag that hold a number (or a container of numbers) and whose field declares no
211
+ * quantity, or is not declared at all: what the classification guard reports. A meta object's keys are read as
212
+ * `meta.<key>`. A technical script reports none (its inputs are the script's, never reconciled).
213
+ */
214
+ export declare function unclassifiedNumericFields(type: string, sampleBag: unknown): string[];
@@ -0,0 +1,369 @@
1
+ /**
2
+ * Market-bound values: a value measured or typed on one market means nothing on another (a heatmap colour range of
3
+ * 20..55 contracts on one future is noise on a coin that trades millions). So a row that holds such values also holds
4
+ * a stamp of the market they were measured or typed on, and a reader trusts the values only when the stamp names the
5
+ * market it draws.
6
+ *
7
+ * The stamp is `<market key>#<signature>`. The signature is a short hash of the bound values themselves, so a writer
8
+ * that changes the values without writing a new stamp (an older client, or a write site that forgot the stamp)
9
+ * leaves a stamp that no longer matches, and the reader treats the row as unkeyed instead of trusting a wrong key.
10
+ *
11
+ * A heatmap row's bound values all live in its `meta`: `range`, `outerRange`, `rangeSource` and `sizeCeil`. Its stamp
12
+ * is the row's top-level `boundKey`, and its top-level `boundByMarket` keeps the typed values of markets the row left
13
+ * (a list, at most BOUND_STASH_CAP entries, oldest out), so a return to a market gives its typed values back.
14
+ *
15
+ * A typed threshold (a footprint's or a volume profile's volume filter, the Big Trades floors) is bound the same way
16
+ * when it is typed in the market's native unit: the registry (./indicator-fields) names those fields (`quantity:
17
+ * 'bound'` with `keep`), the unit they are bound in (`boundWhen`) and their group companions (`with`). Its row holds the
18
+ * same two top-level fields, stamped with marketBoundKey (`<EXCHANGE>-<UNIT>-<SYMBOL>-<INTERVAL>`) and the signature
19
+ * of the typed values (marketBoundSignature), and reconcileMarketBound is the one decision a reader makes when the row
20
+ * meets a market: keep (OWN), swap for that market's remembered or default values (FOREIGN), or trust and stamp
21
+ * (UNKEYED). A heatmap row keeps its own path (settleHeatmapScale on web): reconcileMarketBound leaves it alone.
22
+ *
23
+ * This file imports only the registry, holds no state and never mutates an input. Every input is read defensively: a
24
+ * stored document can hold anything.
25
+ */
26
+ import { HEATMAP_SCALE_TYPES, INDICATOR_COMMON_FIELDS, INDICATOR_TYPE_FIELDS, SCRIPT_INDICATOR_TYPE, } from './indicator-fields.js';
27
+ /** A capital M after the count is a month ('1M', '3M'); a lower-case m is a minute. */
28
+ const MONTH_INTERVAL = /^\d+M$/;
29
+ /** An interval id as a key spells it before upper-casing: a month ('1M') as '1MO', so it never meets the minute. */
30
+ const spellInterval = (value) => {
31
+ const interval = `${value}`;
32
+ return MONTH_INTERVAL.test(interval) ? `${interval.slice(0, -1)}MO` : interval;
33
+ };
34
+ /**
35
+ * The market key of a heatmap's scale, in the spelling of the account's saved heatmap settings map:
36
+ * `<head>-<unit>-<ticker>-<interval>-<tier>`, or `AGGR-<venues>-<unit>-<ticker>-<interval>-<tier>` for an aggregated
37
+ * heatmap with venues, all upper case.
38
+ * - head: AGGR for an aggregated type, HYPERLIQUID_TPSL for a TP/SL type, HYPERLIQUID for another Hyperliquid type
39
+ * (tested in that order), else the exchange.
40
+ * - ticker: the coin for those three heads (they span venues), else the symbol.
41
+ * - unit: the currency, or 'Coin' when it is missing or empty.
42
+ * - interval: a month id ('1M') is spelled '1MO', so it never meets the minute ('1m' spells '1M').
43
+ * - tier: the resolution, or 'HD'.
44
+ * - venues: a sorted copy of the venue set, joined with nothing.
45
+ */
46
+ export function heatmapMarketKey(parts) {
47
+ const type = typeof parts.type === 'string' ? parts.type : '';
48
+ let head;
49
+ if (type.includes('AGGREGATED'))
50
+ head = 'AGGR';
51
+ else if (type.includes('TPSL'))
52
+ head = 'HYPERLIQUID_TPSL';
53
+ else if (type.includes('HYPERLIQUID'))
54
+ head = 'HYPERLIQUID';
55
+ else
56
+ head = `${parts.exchange}`;
57
+ const spansVenues = head === 'AGGR' || head === 'HYPERLIQUID' || head === 'HYPERLIQUID_TPSL';
58
+ const ticker = spansVenues ? parts.coin : parts.symbol;
59
+ const unit = parts.currency === null || parts.currency === undefined || parts.currency === '' ? 'Coin' : parts.currency;
60
+ const spelledInterval = spellInterval(parts.interval);
61
+ const tier = parts.resolution ?? 'HD';
62
+ const venues = head === 'AGGR' && Array.isArray(parts.exchanges) ? [...parts.exchanges].sort().join('') : '';
63
+ if (venues)
64
+ return `${head}-${venues}-${unit}-${ticker}-${spelledInterval}-${tier}`.toUpperCase();
65
+ return `${head}-${unit}-${ticker}-${spelledInterval}-${tier}`.toUpperCase();
66
+ }
67
+ /** The stamp a row holds: `${key}#${signature}`. */
68
+ export function stampBoundKey(key, signature) {
69
+ return `${key}#${signature}`;
70
+ }
71
+ const SIGNATURE_SHAPE = /^[0-9a-z]+$/;
72
+ /**
73
+ * A stamp read back: the key and the signature, split on the LAST '#' (a key may hold a '#', a signature never does).
74
+ * Null for a missing, empty or malformed stamp (not a string, no '#', an empty key, or a signature that is not
75
+ * base 36).
76
+ */
77
+ export function parseBoundKey(stamp) {
78
+ if (typeof stamp !== 'string' || stamp === '')
79
+ return null;
80
+ const cut = stamp.lastIndexOf('#');
81
+ if (cut <= 0)
82
+ return null;
83
+ const key = stamp.slice(0, cut);
84
+ const signature = stamp.slice(cut + 1);
85
+ if (!SIGNATURE_SHAPE.test(signature))
86
+ return null;
87
+ return { key, signature };
88
+ }
89
+ /**
90
+ * A short signature of a list of values: FNV-1a 32 bit over the UTF-16 code units of JSON.stringify(values), as an
91
+ * unsigned number in base 36. An undefined value counts as null, so a missing part and a cleared part sign the same.
92
+ */
93
+ export function boundSignature(values) {
94
+ const text = JSON.stringify(Array.from(values, (value) => (value === undefined ? null : value)));
95
+ let hash = 0x811c9dc5;
96
+ for (let i = 0; i < text.length; i++) {
97
+ hash ^= text.charCodeAt(i);
98
+ hash = Math.imul(hash, 0x01000193);
99
+ }
100
+ return (hash >>> 0).toString(36);
101
+ }
102
+ const isPlainRecord = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
103
+ /** One end of a range pair, or null when the range or the end is missing. */
104
+ const endOf = (range, end) => (isPlainRecord(range) ? (range[end] ?? null) : null);
105
+ /**
106
+ * The signature of a heatmap row's scale, from its meta, over the parts in this fixed order: range.min, range.max,
107
+ * outerRange.min, outerRange.max, rangeSource, sizeCeil. A missing part (a missing range gives two) counts as null.
108
+ */
109
+ export function heatmapScaleSignature(meta) {
110
+ const source = isPlainRecord(meta) ? meta : {};
111
+ return boundSignature([
112
+ endOf(source.range, 'min'),
113
+ endOf(source.range, 'max'),
114
+ endOf(source.outerRange, 'min'),
115
+ endOf(source.outerRange, 'max'),
116
+ source.rangeSource ?? null,
117
+ source.sizeCeil ?? null,
118
+ ]);
119
+ }
120
+ /** The most markets a row keeps typed values for. */
121
+ export const BOUND_STASH_CAP = 8;
122
+ /** A detached copy of a JSON-like value, so a returned entry never shares an object with an input. */
123
+ function clonePlain(value) {
124
+ if (Array.isArray(value))
125
+ return value.map(clonePlain);
126
+ if (isPlainRecord(value)) {
127
+ const copy = {};
128
+ for (const key of Object.keys(value))
129
+ copy[key] = clonePlain(value[key]);
130
+ return copy;
131
+ }
132
+ return value;
133
+ }
134
+ const isStashEntry = (entry) => isPlainRecord(entry) && typeof entry.key === 'string' && entry.key !== '' && isPlainRecord(entry.values);
135
+ /** The well-formed entries of a stored list, copied; anything else in the list (or a list that is none) is dropped. */
136
+ function readStash(list) {
137
+ if (!Array.isArray(list))
138
+ return [];
139
+ return list
140
+ .filter(isStashEntry)
141
+ .map((entry) => ({ key: entry.key, values: clonePlain(entry.values) }));
142
+ }
143
+ /**
144
+ * A new stash list: any entry for `key` removed, the new entry appended last, and the oldest entries dropped past
145
+ * BOUND_STASH_CAP. Malformed entries of the given list are dropped. Never mutates its inputs.
146
+ */
147
+ export function stashBound(list, key, values) {
148
+ const kept = readStash(list).filter((entry) => entry.key !== key);
149
+ kept.push({ key, values: clonePlain(isPlainRecord(values) ? values : {}) });
150
+ return kept.length > BOUND_STASH_CAP ? kept.slice(kept.length - BOUND_STASH_CAP) : kept;
151
+ }
152
+ /**
153
+ * The stashed values for `key` (null when none) and a new list without that entry. Tolerates a malformed list (gives
154
+ * null and []) and drops malformed entries. Never mutates its input.
155
+ */
156
+ export function takeBound(list, key) {
157
+ const entries = readStash(list);
158
+ const found = entries.find((entry) => entry.key === key);
159
+ return {
160
+ values: found ? found.values : null,
161
+ list: entries.filter((entry) => entry.key !== key),
162
+ };
163
+ }
164
+ // ─── Typed thresholds: the key, the units, the signature and the one decision ──────────────────────────────────────
165
+ const HEATMAP_TYPES = new Set(HEATMAP_SCALE_TYPES);
166
+ /** Whether a type's market-bound values are a heatmap's scale (wave 1's path, never reconcileMarketBound). */
167
+ export function isHeatmapScaleType(type) {
168
+ return typeof type === 'string' && HEATMAP_TYPES.has(type);
169
+ }
170
+ /**
171
+ * The market key of a row's market-bound values. A heatmap type gets heatmapMarketKey(parts) unchanged. Any other type
172
+ * gets `<EXCHANGE>-<UNIT>-<SYMBOL>-<INTERVAL>`, upper case, spelled as the heatmap key spells them (a missing or empty
173
+ * unit is 'Coin', a month interval '1M' is '1MO', a minute '1m' is '1M'), with no tier and no venue set.
174
+ */
175
+ export function marketBoundKey(parts) {
176
+ if (isHeatmapScaleType(parts.type))
177
+ return heatmapMarketKey(parts);
178
+ const unit = parts.currency === null || parts.currency === undefined || parts.currency === '' ? 'Coin' : parts.currency;
179
+ return `${parts.exchange}-${unit}-${parts.symbol}-${spellInterval(parts.interval)}`.toUpperCase();
180
+ }
181
+ const isScriptType = (type) => type === SCRIPT_INDICATOR_TYPE || type.startsWith(`${SCRIPT_INDICATOR_TYPE}:`);
182
+ const isSettingsOwned = (field) => field.owner === undefined || field.owner === 'settings';
183
+ const fieldPath = (key, field) => (field.owner === 'meta' ? `meta.${key}` : key);
184
+ /** A type's declared fields by path (`key`, or `meta.<key>`): the shared rows, then its own (a same path replaces). */
185
+ function declaredFieldsOf(type) {
186
+ const own = Object.hasOwn(INDICATOR_TYPE_FIELDS, type) ? INDICATOR_TYPE_FIELDS[type] : [];
187
+ const fields = new Map();
188
+ for (const [key, field] of [...INDICATOR_COMMON_FIELDS, ...own])
189
+ fields.set(fieldPath(key, field), field);
190
+ return fields;
191
+ }
192
+ const UNITS = new Map();
193
+ /**
194
+ * The reconciled units of a type, in the registry's declared order: every settings-bag field with `quantity: 'bound'`
195
+ * and a `keep`, with its `with` companions (a companion is never a unit of its own). None for a heatmap type (its own
196
+ * path), a technical script (its inputs are the script's) or a type without such a field. Frozen and cached.
197
+ */
198
+ export function boundFieldsOf(type) {
199
+ if (typeof type !== 'string' || isHeatmapScaleType(type) || isScriptType(type))
200
+ return [];
201
+ let units = UNITS.get(type);
202
+ if (!units) {
203
+ const fields = declaredFieldsOf(type);
204
+ const companions = new Set();
205
+ for (const field of fields.values())
206
+ for (const key of field.with ?? [])
207
+ companions.add(key);
208
+ const list = [];
209
+ for (const [path, field] of fields) {
210
+ if (field.quantity !== 'bound' || !field.keep || !isSettingsOwned(field) || companions.has(path))
211
+ continue;
212
+ const unit = { key: path, keys: Object.freeze([path, ...(field.with ?? [])]), keep: field.keep };
213
+ if (field.boundWhen)
214
+ unit.boundWhen = field.boundWhen;
215
+ list.push(Object.freeze(unit));
216
+ }
217
+ units = Object.freeze(list);
218
+ UNITS.set(type, units);
219
+ }
220
+ return units;
221
+ }
222
+ /**
223
+ * Whether a condition holds on a settings bag: no condition always holds; otherwise the sibling's value (undefined
224
+ * when the bag or the key is missing) is one of `oneOf` when that is named and none of `noneOf` when that is named.
225
+ */
226
+ export function isBoundNow(condition, settings) {
227
+ if (!condition)
228
+ return true;
229
+ const value = isPlainRecord(settings) && Object.hasOwn(settings, condition.key) ? settings[condition.key] : undefined;
230
+ if (condition.oneOf && !condition.oneOf.includes(value))
231
+ return false;
232
+ return !condition.noneOf?.includes(value);
233
+ }
234
+ /** The units of a type that are bound right now on this bag (each unit's `boundWhen` read off the bag). */
235
+ export function boundUnitsNow(type, settings) {
236
+ return boundFieldsOf(type).filter((unit) => isBoundNow(unit.boundWhen, settings));
237
+ }
238
+ const ownValue = (settings, key) => Object.hasOwn(settings, key) ? settings[key] : undefined;
239
+ /**
240
+ * The signature of a threshold row: boundSignature over the values of the type's typed units that are bound right now,
241
+ * each unit's keys in order, the units in the registry's declared order, a missing value as null. A non-record bag reads
242
+ * as empty.
243
+ */
244
+ export function marketBoundSignature(type, settings) {
245
+ const bag = isPlainRecord(settings) ? settings : {};
246
+ const values = boundUnitsNow(type, bag)
247
+ .filter((unit) => unit.keep === 'typed')
248
+ .flatMap((unit) => unit.keys.map((key) => ownValue(bag, key)));
249
+ return boundSignature(values);
250
+ }
251
+ /**
252
+ * The row after a user's edit of its bound values (they were just typed on the live market): `boundKey` stamped with
253
+ * `liveKey` and the row's signature. The same object when the stamp is already that one, and for a type with no
254
+ * reconciled unit or a bag that is no record.
255
+ */
256
+ export function stampMarketBound(type, settings, liveKey) {
257
+ if (!isPlainRecord(settings) || !boundFieldsOf(type).length || typeof liveKey !== 'string' || liveKey === '') {
258
+ return settings;
259
+ }
260
+ const stamp = stampBoundKey(liveKey, marketBoundSignature(type, settings));
261
+ if (settings.boundKey === stamp)
262
+ return settings;
263
+ return { ...settings, boundKey: stamp };
264
+ }
265
+ /**
266
+ * The one decision a reader makes when a threshold row meets the live market `liveKey` (contract section 6). Pure:
267
+ * reads its inputs defensively and never mutates them.
268
+ * - OWN (the stamp parses, its signature matches, its key is `liveKey`): unchanged, the same object.
269
+ * - FOREIGN (the stamp parses and signs, another key): the typed units bound right now are kept under the stamp's key
270
+ * in `boundByMarket` (measured ones are dropped); each unit takes the live market's remembered values out of the
271
+ * stash, else `options.defaults`, else is removed; the row is stamped with `liveKey`. A group is one unit.
272
+ * - UNKEYED (no stamp, a malformed one, or a signature that does not match): the values are trusted on this market and
273
+ * stamped with `liveKey`; with `options.unkeyedAs` the row is first read as stamped with that key (OWN or FOREIGN).
274
+ * A field not bound right now (its unit is notional) is never kept, reset or signed. A heatmap type, a script, a type
275
+ * without a reconciled unit and a row with no unit bound right now come back untouched (`none`).
276
+ */
277
+ export function reconcileMarketBound(type, settings, liveKey, options) {
278
+ const result = (next, verdict, rowKey, restored = false, stashed = false) => ({ settings: next, verdict, rowKey, liveKey, restored, stashed });
279
+ if (!isPlainRecord(settings) || typeof liveKey !== 'string' || liveKey === '')
280
+ return result(settings, 'none', null);
281
+ const units = boundUnitsNow(type, settings);
282
+ if (!units.length)
283
+ return result(settings, 'none', null);
284
+ const signature = marketBoundSignature(type, settings);
285
+ const stamp = parseBoundKey(settings.boundKey);
286
+ const unkeyedAs = typeof options?.unkeyedAs === 'string' && options.unkeyedAs !== '' ? options.unkeyedAs : null;
287
+ const signed = !!stamp && stamp.signature === signature;
288
+ const rowKey = signed && stamp ? stamp.key : unkeyedAs;
289
+ if (signed && rowKey === liveKey)
290
+ return result(settings, 'own', rowKey);
291
+ if (rowKey === null || rowKey === liveKey) {
292
+ return result({ ...settings, boundKey: stampBoundKey(liveKey, signature) }, 'unkeyed-stamped', rowKey);
293
+ }
294
+ // FOREIGN: the values belong to `rowKey`.
295
+ const next = { ...settings };
296
+ const typed = {};
297
+ for (const unit of units) {
298
+ if (unit.keep !== 'typed')
299
+ continue;
300
+ for (const key of unit.keys) {
301
+ const value = ownValue(settings, key);
302
+ if (value !== undefined)
303
+ typed[key] = value;
304
+ }
305
+ }
306
+ const taken = takeBound(settings.boundByMarket, liveKey);
307
+ const stashed = Object.keys(typed).length > 0;
308
+ const list = stashed ? stashBound(taken.list, rowKey, typed) : taken.list;
309
+ const remembered = taken.values;
310
+ const defaults = isPlainRecord(options?.defaults) ? options.defaults : null;
311
+ let restored = false;
312
+ for (const unit of units) {
313
+ let source = null;
314
+ if (unit.keep === 'typed' && remembered && unit.keys.some((key) => Object.hasOwn(remembered, key))) {
315
+ source = remembered;
316
+ restored = true;
317
+ }
318
+ else if (defaults && Object.hasOwn(defaults, unit.key)) {
319
+ source = defaults;
320
+ }
321
+ for (const key of unit.keys) {
322
+ if (source && Object.hasOwn(source, key) && source[key] !== undefined)
323
+ next[key] = clonePlain(source[key]);
324
+ else
325
+ delete next[key];
326
+ }
327
+ }
328
+ if (list.length)
329
+ next.boundByMarket = list;
330
+ else
331
+ delete next.boundByMarket;
332
+ next.boundKey = stampBoundKey(liveKey, marketBoundSignature(type, next));
333
+ return result(next, 'key-mismatch', rowKey, restored, stashed);
334
+ }
335
+ /** Whether a value is a number, or a list or record that holds one at any depth (a container of numbers). */
336
+ function holdsNumber(value, depth = 0) {
337
+ if (typeof value === 'number')
338
+ return true;
339
+ if (depth > 8 || !value || typeof value !== 'object')
340
+ return false;
341
+ const children = Array.isArray(value) ? value : Object.values(value);
342
+ return children.some((child) => holdsNumber(child, depth + 1));
343
+ }
344
+ /**
345
+ * The paths of a sample settings bag that hold a number (or a container of numbers) and whose field declares no
346
+ * quantity, or is not declared at all: what the classification guard reports. A meta object's keys are read as
347
+ * `meta.<key>`. A technical script reports none (its inputs are the script's, never reconciled).
348
+ */
349
+ export function unclassifiedNumericFields(type, sampleBag) {
350
+ if (typeof type !== 'string' || isScriptType(type) || !isPlainRecord(sampleBag))
351
+ return [];
352
+ const fields = declaredFieldsOf(type);
353
+ const found = [];
354
+ const check = (path, value) => {
355
+ if (holdsNumber(value) && !fields.get(path)?.quantity)
356
+ found.push(path);
357
+ };
358
+ for (const key of Object.keys(sampleBag)) {
359
+ const value = sampleBag[key];
360
+ if (key === 'meta' && isPlainRecord(value)) {
361
+ for (const metaKey of Object.keys(value))
362
+ check(`meta.${metaKey}`, value[metaKey]);
363
+ }
364
+ else {
365
+ check(key, value);
366
+ }
367
+ }
368
+ return found;
369
+ }
@@ -5,10 +5,9 @@
5
5
  * stays worker-safe and store-free, so the main thread hands it readers instead.
6
6
  *
7
7
  * The gate is open only while BOTH of its facts answer `true`, each read live on every call:
8
- * - The flag. The flags store registers its override-aware `isOn` as the fallback when it is created, and publishes
9
- * its reader again after every successful fetch. Until a fetch publishes, the fallback answers, so the dev and
10
- * internal `kiyo.flag-overrides` lens reaches the walls before the map lands and through a failed fetch, exactly as
11
- * it reaches every surface that reads `isOn`: the walls and the surfaces never disagree.
8
+ * - The flag. The flags store registers `licenceFlagOn` as the fallback when it is created, read live: an explicit
9
+ * override answers, so the dev and internal `kiyo.flag-overrides` lens reaches the walls before the map lands, and
10
+ * once the map has answered an absent or archived record reads on. A published reader (a spec's) answers over it.
12
11
  * - The viewer's CME entitlement. The web hands its `viewerMayReadCme()` reader: signed in, not a guest, the CME data
13
12
  * terms not blocked. Delayed and real-time access both count: the tier a read rides is the gate plane's, decided per
14
13
  * socket, never this answer's.
@@ -26,8 +25,8 @@
26
25
  * its answer (titan-charts' dataFetch result, the script engine's result, the wrun run's `isCurrent`) compares the
27
26
  * token and drops an answer from a previous authorisation context, so a late answer never lands after access changed.
28
27
  * A missing token is never current. The epoch is main-thread state: a worker's copy of this module never sees a bump,
29
- * so a worker carries the captured token back and never judges it. Publishing a reader never moves the epoch (a flag
30
- * fetch publishes after every fetch, moved or not): only the watcher bumps it, on a move it saw.
28
+ * so a worker carries the captured token back and never judges it. Publishing a reader never moves the epoch: only the
29
+ * watcher bumps it, on a move it saw.
31
30
  *
32
31
  * The stopped-study register (`markCmeStudyStopped`, `clearCmeStudyStopped`, `cmeStudyStopReason`,
33
32
  * `isCmeStudyStopped`): the studies the lifecycle watcher stopped in place when the gate closed (the viewer's access
@@ -57,9 +56,10 @@ export declare function cmeStudyRemountStash(chartIndex: number, overlayId: stri
57
56
  export declare function cmeStudyStopReason(chartIndex: number, overlayId: string): CmeStudyStopReason | undefined;
58
57
  /** Whether the lifecycle stopped this study and nothing has mounted it again since. */
59
58
  export declare function isCmeStudyStopped(chartIndex: number, overlayId: string): boolean;
60
- /** Called by the flags store after a successful fetch (and by specs); null unpublishes. */
59
+ /** Called by specs (and a host that hands its own reader); null unpublishes. */
61
60
  export declare function publishCmeUserScriptsFlag(next: (() => boolean) | null): void;
62
- /** Called by the flags store when it is created: its override-aware `isOn`, read until a fetch publishes. */
61
+ /** Called by the flags store when it is created: `licenceFlagOn`, which reads an absent or archived record as on once
62
+ * the map has answered; read whenever nothing is published. */
63
63
  export declare function setCmeUserScriptsFlagFallback(next: (() => boolean) | null): void;
64
64
  /** Called by the web with its `viewerMayReadCme()` reader (signed in, not a guest, CME data terms not blocked); null
65
65
  * unregisters, and no reader reads closed. */