@celestia-island/hikari 0.55.413 → 0.55.415

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.
@@ -0,0 +1,716 @@
1
+ // Pure layout for HkUsageFlow — the three-stage usage-distribution Sankey
2
+ // (caller → upstream → model). Kept dependency-free and framework-free so
3
+ // the component stays a thin renderer and every geometric claim is pinned
4
+ // by tests here (the HkBarChart/barChart.ts "pure logic module + thin
5
+ // component" line).
6
+ //
7
+ // Input = settled aggregate rows (the caller owns fetching/grouping):
8
+ //
9
+ // { source: "arona-1a…9f3c", middle: "upstream-a", target: "model-x", value: 1200 }
10
+ //
11
+ // The layout turns them into three stacked columns of bars plus ribbon
12
+ // paths, with ONE shared value scale across the columns: a ribbon's
13
+ // thickness means the same thing at every stage and the columns always line
14
+ // up. A node's bar is `value × scale` floored at a visibility minimum; its
15
+ // ribbon stacks are the EXACT `value × scale` slots (never floored), so a
16
+ // bar can be slightly taller than its stacks but no stack ever overhangs
17
+ // its bar. Nodes beyond `maxNodes` in a column collapse into one synthetic
18
+ // "others" bucket BEFORE geometry runs, so the collapsed total still equals
19
+ // the column total (the conservation invariant the tests pin). The cap is
20
+ // also clamped to what the frame can stack proportionally, so a tall
21
+ // column does not escape the viewBox. CAVEAT, by design: if a window holds
22
+ // so many similarly-sized keys that one key's share is smaller than the
23
+ // 2-unit visibility minimum, that key's bar sits ON the floor — the frame
24
+ // has a finite pixel budget and the bucket carries the rest. The cap only
25
+ // guarantees the column fits; it cannot create room the data does not
26
+ // leave.
27
+ //
28
+ // Colours: the last column (models) is the legend's colour source. A
29
+ // roster (`models`) fixes the colour order regardless of usage — so a
30
+ // registered model's swatch is stable across days/windows, and models with
31
+ // zero measured usage keep their slot. Without a roster the slots follow
32
+ // measured value, descending. Every fill is a theme token expression
33
+ // (`rgb(var(--color-*))` / `color-mix(...)`), so a scheme flip repaints
34
+ // without a re-render.
35
+ //
36
+ // AI-generated (DeepSeek V4.1 via DeepSeek Harness), 2026-11-17 — SySL-1.0 §2.3.
37
+
38
+ /** One settled aggregate flow row: caller → upstream → model. */
39
+ export interface HkUsageFlowRow {
40
+ /** First column key: the caller attribution (masked API-key id, session
41
+ * id, …) exactly as the metering source records it. */
42
+ source: string;
43
+ /** Middle column key: the upstream / backend that served the request. */
44
+ middle: string;
45
+ /** Last column key: the model id the request asked for. */
46
+ target: string;
47
+ /** Metric magnitude for this triple (tokens / requests / cost — the host
48
+ * picks the metric; the layout is metric-agnostic). */
49
+ value: number;
50
+ }
51
+
52
+ /** One entry of the complete registered-model roster. The colour is fixed
53
+ * by the entry's position so an idle model keeps its swatch. */
54
+ export interface HkUsageFlowRosterEntry {
55
+ label: string;
56
+ /** Optional explicit fill; absent = the palette slot for the position. */
57
+ color?: string;
58
+ }
59
+
60
+ /** One laid-out node (bar) in a column. */
61
+ export interface HkUsageFlowNode {
62
+ /** Stable DOM key: `<column>:<label>`. */
63
+ key: string;
64
+ label: string;
65
+ /** Untruncated label (for `title` / hints). */
66
+ fullLabel: string;
67
+ /** 0 = caller, 1 = upstream, 2 = model. */
68
+ column: number;
69
+ value: number;
70
+ x: number;
71
+ y: number;
72
+ width: number;
73
+ height: number;
74
+ color: string;
75
+ /** True for the synthetic collapsed bucket (`othersLabel`). */
76
+ others: boolean;
77
+ /** False when the bar is too short to carry a readable label (the
78
+ * `data-hint` and the legend still name it) — a dense tail must not
79
+ * stack overlapping text. */
80
+ labelVisible: boolean;
81
+ }
82
+
83
+ /** One ribbon between two adjacent columns. */
84
+ export interface HkUsageFlowLink {
85
+ key: string;
86
+ sourceKey: string;
87
+ targetKey: string;
88
+ value: number;
89
+ /** Ribbon outline: a closed path (two cubic edges + two straight caps). */
90
+ path: string;
91
+ /** The TARGET node's fill — ribbons are read as "flow into X". */
92
+ color: string;
93
+ /** Ribbon thickness in layout units (exactly `value × scale`). */
94
+ thickness: number;
95
+ /** Source-side slot origin (the top edge on the source bar). */
96
+ startY: number;
97
+ /** Target-side slot origin (the top edge on the target bar). */
98
+ endY: number;
99
+ }
100
+
101
+ /** One legend row: the measured total for a registered model (idle ones
102
+ * included) or for a model that served traffic but is not registered.
103
+ *
104
+ * Values are PRE-collapse: the chart may fold a long tail into its
105
+ * `othersLabel` node, but the legend is the full model table — a folded
106
+ * registered model reports the traffic it actually carried, never a
107
+ * zero it did not have. */
108
+ export interface HkUsageFlowLegendRow {
109
+ label: string;
110
+ value: number;
111
+ /** Share of the window total, 0–100 — the UNROUNDED ratio (callers
112
+ * round it for display; `percent` itself is never rounded, so
113
+ * consumers can re-derive sums without drift). */
114
+ percent: number;
115
+ color: string;
116
+ /** No measured usage: the registered-but-unused row (greyed by CSS). */
117
+ idle: boolean;
118
+ }
119
+
120
+ /** The full layout HkUsageFlow renders. */
121
+ export interface HkUsageFlowLayout {
122
+ width: number;
123
+ height: number;
124
+ nodes: HkUsageFlowNode[];
125
+ links: HkUsageFlowLink[];
126
+ legend: HkUsageFlowLegendRow[];
127
+ /** Sum of every positive row value (the metric's window total). */
128
+ total: number;
129
+ /** No positive rows: the component renders its empty state. */
130
+ empty: boolean;
131
+ }
132
+
133
+ /** Tunables; the component passes its props, tests pass their own. */
134
+ export interface HkUsageFlowLayoutOptions {
135
+ width?: number;
136
+ height?: number;
137
+ /** Per-column cap; beyond it the tail collapses into `othersLabel`.
138
+ * Clamped to ≥ 2 AND to what the frame can stack with an average
139
+ * proportional band per node, so an oversized cap silently shrinks
140
+ * instead of overrunning the viewBox. `0` / absent / non-finite =
141
+ * "as many as the frame allows". (A tail-heavy window can still leave
142
+ * individual keys on the 2-unit floor — that is the data's share, not
143
+ * the cap; see the module caveat.) */
144
+ maxNodes?: number;
145
+ othersLabel?: string;
146
+ /** The complete registered roster. Roster order fixes the model colours
147
+ * (idle rows included), so a model's swatch is stable across windows. */
148
+ models?: readonly HkUsageFlowRosterEntry[];
149
+ /** Colour ladder; defaults to the theme-token palette below. Readonly so
150
+ * a consumer can pass the exported `USAGE_FLOW_PALETTE` directly. */
151
+ colors?: readonly string[];
152
+ /** Label truncation budget in character units (CJK counts 2). */
153
+ labelMaxChars?: number;
154
+ }
155
+
156
+ const COLUMN_COUNT = 3;
157
+ const PAD_X = 8;
158
+ const PAD_Y = 12;
159
+ const NODE_WIDTH = 14;
160
+ const NODE_GAP = 10;
161
+ const MIN_NODE_HEIGHT = 2;
162
+ /* A bar shorter than this cannot carry a readable label without colliding
163
+ with its neighbours: the label is omitted (the hint and the legend still
164
+ name the node), so a dense tail never stacks unreadable text. */
165
+ const MIN_LABEL_HEIGHT = 12;
166
+ /* The per-node proportional band the cap must leave in the frame: a cap
167
+ that only "fits with floors" would paint every bar at the 2-unit
168
+ visibility minimum and lose every magnitude (found by an independent
169
+ round at 30+ flat nodes with `maxNodes: 0`). */
170
+ const MIN_PROPORTIONAL_HEIGHT = 6;
171
+
172
+ /** The default categorical ladder — every entry a theme-token expression, so
173
+ * light/dark/brand-preset flips repaint the chart without JS. The five
174
+ * semantic slots come first; the seven mixes fill the long tail with
175
+ * distinguishable hues that still derive from the active theme. */
176
+ export const USAGE_FLOW_PALETTE: readonly string[] = [
177
+ "rgb(var(--color-primary, 122 162 247))",
178
+ "rgb(var(--color-info, 106 190 214))",
179
+ "rgb(var(--color-success, 14 184 64))",
180
+ "rgb(var(--color-warning, 238 214 119))",
181
+ "rgb(var(--color-error, 247 118 142))",
182
+ "color-mix(in srgb, rgb(var(--color-primary, 122 162 247)) 55%, rgb(var(--color-info, 106 190 214)))",
183
+ "color-mix(in srgb, rgb(var(--color-info, 106 190 214)) 55%, rgb(var(--color-success, 14 184 64)))",
184
+ "color-mix(in srgb, rgb(var(--color-success, 14 184 64)) 55%, rgb(var(--color-warning, 238 214 119)))",
185
+ "color-mix(in srgb, rgb(var(--color-warning, 238 214 119)) 55%, rgb(var(--color-error, 247 118 142)))",
186
+ "color-mix(in srgb, rgb(var(--color-error, 247 118 142)) 55%, rgb(var(--color-primary, 122 162 247)))",
187
+ "color-mix(in srgb, rgb(var(--color-secondary, 81 154 115)) 65%, rgb(var(--color-primary, 122 162 247)))",
188
+ "color-mix(in srgb, rgb(var(--color-accent, 247 181 0)) 65%, rgb(var(--color-error, 247 118 142)))",
189
+ ];
190
+
191
+ /** The roster-only legend an empty face shows: every registered model at
192
+ * 0 / idle, in roster order with the assigned colour slot. */
193
+ function idleRosterRows(
194
+ roster: readonly HkUsageFlowRosterEntry[],
195
+ palette: readonly string[],
196
+ ): HkUsageFlowLegendRow[] {
197
+ const rows: HkUsageFlowLegendRow[] = [];
198
+ const seen = new Set<string>();
199
+ for (const entry of roster) {
200
+ if (!entry || typeof entry.label !== "string" || entry.label === "") continue;
201
+ if (seen.has(entry.label)) continue;
202
+ seen.add(entry.label);
203
+ const slot = seen.size - 1;
204
+ const explicit =
205
+ typeof entry.color === "string" && entry.color.trim() !== "" ? entry.color : null;
206
+ rows.push({
207
+ label: entry.label,
208
+ value: 0,
209
+ percent: 0,
210
+ color: explicit ?? palette[slot % palette.length],
211
+ idle: true,
212
+ });
213
+ }
214
+ return rows;
215
+ }
216
+
217
+ /** Truncate a label to `maxChars` character units (CJK counts 2), adding an
218
+ * ellipsis. The full label always rides the node's `fullLabel`. */
219
+ export function truncateFlowLabel(label: string, maxChars: number): string {
220
+ const budget = Math.max(4, Math.floor(maxChars));
221
+ let units = 0;
222
+ let out = "";
223
+ for (const ch of label) {
224
+ const width = /[\u1100-\u115f\u2e80-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6]/u.test(ch)
225
+ ? 2
226
+ : 1;
227
+ if (units + width > budget) {
228
+ return out + "…";
229
+ }
230
+ units += width;
231
+ out += ch;
232
+ }
233
+ return out;
234
+ }
235
+
236
+ /** One normalized flow after per-column label mapping. */
237
+ interface ResolvedFlow {
238
+ source: string;
239
+ middle: string;
240
+ target: string;
241
+ value: number;
242
+ }
243
+
244
+ interface CollapsedColumn {
245
+ /** Raw labels kept as-is (value desc). */
246
+ kept: Set<string>;
247
+ /** Raw label → display label (identity for kept labels). */
248
+ display: Map<string, string>;
249
+ }
250
+
251
+ /** Collapse one column's labels: keep the top `maxNodes-1` and fold the
252
+ * rest into the synthetic bucket. `maxNodes <= 0` means "no cap". */
253
+ function collapseColumn(
254
+ values: Map<string, number>,
255
+ maxNodes: number,
256
+ othersLabel: string,
257
+ ): CollapsedColumn {
258
+ const display = new Map<string, string>();
259
+ const kept = new Set<string>();
260
+ const entries = [...values.entries()];
261
+ for (const [label] of entries) {
262
+ display.set(label, label);
263
+ kept.add(label);
264
+ }
265
+ if (maxNodes <= 0 || entries.length <= maxNodes) {
266
+ return { kept, display };
267
+ }
268
+ const cap = Math.max(2, Math.floor(maxNodes));
269
+ const ranked = entries
270
+ .map(([label, value], index) => ({ label, value, index }))
271
+ .sort((a, b) => (b.value - a.value) || (a.label < b.label ? -1 : a.label > b.label ? 1 : a.index - b.index));
272
+ const keep = new Set(ranked.slice(0, cap - 1).map((e) => e.label));
273
+ for (const [label] of entries) {
274
+ if (!keep.has(label)) {
275
+ display.set(label, othersLabel);
276
+ }
277
+ }
278
+ return { kept: keep, display };
279
+ }
280
+
281
+ /** Add `value` to a map bucket. */
282
+ function addValue(map: Map<string, number>, label: string, value: number): void {
283
+ map.set(label, (map.get(label) ?? 0) + value);
284
+ }
285
+
286
+ /** Rank labels by value descending, ties broken by label ascending. */
287
+ function rankLabels(values: Map<string, number>): string[] {
288
+ return [...values.entries()]
289
+ .sort((a, b) => (b[1] - a[1]) || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
290
+ .map(([label]) => label);
291
+ }
292
+
293
+ /** Round a coordinate to two decimals so float noise never reaches the DOM. */
294
+ function px(value: number): number {
295
+ return Math.round(value * 100) / 100;
296
+ }
297
+
298
+ /** Whether a bar of this (layout-unit) height carries its label. Reads the
299
+ * ROUNDED height — the DOM's `height` attribute — so the label decision
300
+ * can never disagree with the rendered bar (a height rounded UP to 12
301
+ * still gets its label). */
302
+ export function flowLabelVisible(height: number): boolean {
303
+ return px(height) >= MIN_LABEL_HEIGHT;
304
+ }
305
+
306
+ /** The ribbon outline: right edge of the source bar → left edge of the
307
+ * target bar, thick end caps and two mirrored cubic edges. */
308
+ function ribbonPath(x0: number, y0: number, x1: number, y1: number, thickness: number): string {
309
+ // The drawn thickness IS the scaled slot: flooring it here would let a
310
+ // dense stack overhang its bar without the geometry saying so. The four
311
+ // cap edges are y0 / y0+t on the source side and y1 / y1+t on the target
312
+ // side; the layout builds the path from its exported slot values, so the
313
+ // drawn edges and the reported geometry can never disagree.
314
+ const t = Math.max(0, thickness);
315
+ const bend = Math.max(8, (x1 - x0) * 0.5);
316
+ const top0 = px(y0);
317
+ const bot0 = px(y0 + t);
318
+ const top1 = px(y1);
319
+ const bot1 = px(y1 + t);
320
+ const a = `${px(x0)} ${top0}`;
321
+ const b = `${px(x1)} ${top1}`;
322
+ const c0 = `${px(x0 + bend)} ${top0}`;
323
+ const c1 = `${px(x1 - bend)} ${top1}`;
324
+ const d0 = `${px(x1)} ${bot1}`;
325
+ const d1 = `${px(x0)} ${bot0}`;
326
+ const e0 = `${px(x1 - bend)} ${bot1}`;
327
+ const e1 = `${px(x0 + bend)} ${bot0}`;
328
+ return `M ${a} C ${c0}, ${c1}, ${b} L ${d0} C ${e0}, ${e1}, ${d1} Z`;
329
+ }
330
+
331
+ /**
332
+ * Lay out the three-stage usage flow.
333
+ *
334
+ * Invariants (pinned by usageFlowLayout.test.ts):
335
+ * * a column's node values sum to the same total at every stage;
336
+ * * a node's height equals its value × the shared scale (floored at the
337
+ * visibility minimum), and the incoming/outgoing ribbon stacks exactly
338
+ * fill the bar's height;
339
+ * * the legend carries EVERY roster entry (idle ones included) plus any
340
+ * unregistered model that served traffic;
341
+ * * the same input yields the same geometry and colours.
342
+ */
343
+ export function usageFlowLayout(
344
+ rows: readonly HkUsageFlowRow[],
345
+ options: HkUsageFlowLayoutOptions = {},
346
+ ): HkUsageFlowLayout {
347
+ const finite = (value: number | undefined, fallback: number): number =>
348
+ typeof value === "number" && Number.isFinite(value) ? value : fallback;
349
+ const width = Math.max(320, finite(options.width, 960));
350
+ const height = Math.max(180, finite(options.height, 420));
351
+ const requestedMax = finite(options.maxNodes, 0);
352
+ const othersLabel = options.othersLabel?.trim() || "Others";
353
+ const labelChars = options.labelMaxChars ?? 28;
354
+ // Non-finite / non-positive budgets are meaningless: the default keeps
355
+ // truncation on (a NaN comparison would otherwise disable it silently).
356
+ const labelMaxChars = Number.isFinite(labelChars) && labelChars > 0 ? labelChars : 28;
357
+ const palette = options.colors && options.colors.length > 0 ? options.colors : USAGE_FLOW_PALETTE;
358
+ const roster = options.models ?? [];
359
+
360
+ // ── Normalize: drop non-positive / non-finite rows, sum duplicates. ──
361
+ const raw = new Map<string, ResolvedFlow>();
362
+ for (const row of rows) {
363
+ if (!row) continue;
364
+ const value = row.value;
365
+ if (!Number.isFinite(value) || value <= 0) continue;
366
+ const source = String(row.source ?? "");
367
+ const middle = String(row.middle ?? "");
368
+ const target = String(row.target ?? "");
369
+ const key = `${source}\u0000${middle}\u0000${target}`;
370
+ const previous = raw.get(key);
371
+ if (previous) {
372
+ previous.value += value;
373
+ // A summed overflow (two absurd magnitudes, or a host feeding
374
+ // ±Infinity-ish values) must drop the row: an Infinity total makes
375
+ // `scale` zero and `value × scale` NaN, which poisons every later
376
+ // node in the column.
377
+ if (!Number.isFinite(previous.value)) raw.delete(key);
378
+ } else {
379
+ raw.set(key, { source, middle, target, value });
380
+ }
381
+ }
382
+
383
+ // A grand total that overflows means no column sum below it can be
384
+ // trusted either: the legend reads the PRE-fold column sums, and an
385
+ // Infinity there would print "∞" beside a normal-looking chart. Bail to
386
+ // the empty face before anything is derived. (All raw values are finite
387
+ // — the dedupe loop above dropped the overflowing ones.)
388
+ let rawTotal = 0;
389
+ for (const flow of raw.values()) rawTotal += flow.value;
390
+ if (!Number.isFinite(rawTotal)) {
391
+ return {
392
+ width,
393
+ height,
394
+ nodes: [],
395
+ links: [],
396
+ legend: idleRosterRows(roster, palette),
397
+ total: 0,
398
+ empty: true,
399
+ };
400
+ }
401
+ const empty = raw.size === 0;
402
+
403
+ // ── Per-column totals before collapsing. ──
404
+ const columnValues: Array<Map<string, number>> = [
405
+ new Map<string, number>(),
406
+ new Map<string, number>(),
407
+ new Map<string, number>(),
408
+ ];
409
+ for (const flow of raw.values()) {
410
+ addValue(columnValues[0], flow.source, flow.value);
411
+ addValue(columnValues[1], flow.middle, flow.value);
412
+ addValue(columnValues[2], flow.target, flow.value);
413
+ }
414
+
415
+ // ── Collapse each column, then re-key the flows onto display labels.
416
+ // The cap is clamped to what the frame can stack with PROPORTIONAL
417
+ // bars: each extra node costs `MIN_NODE_HEIGHT` + `NODE_GAP` plus the
418
+ // per-node proportional band (`MIN_PROPORTIONAL_HEIGHT`), inside
419
+ // `height - 2 × PAD_Y`. The floor-only fit is the looser upper bound
420
+ // kept for the degenerate small-frame case. ──
421
+ const fitsWithFloors = Math.floor(
422
+ (height - PAD_Y * 2 + NODE_GAP) / (MIN_NODE_HEIGHT + NODE_GAP),
423
+ );
424
+ const fitsProportionally = Math.floor(
425
+ (height - PAD_Y * 2 + NODE_GAP) /
426
+ (MIN_NODE_HEIGHT + NODE_GAP + MIN_PROPORTIONAL_HEIGHT),
427
+ );
428
+ const fitCount = Math.max(2, Math.min(fitsWithFloors, fitsProportionally));
429
+ const maxNodes =
430
+ requestedMax > 0 ? Math.max(2, Math.min(Math.floor(requestedMax), fitCount)) : fitCount;
431
+ const collapsed = columnValues.map((values) => collapseColumn(values, maxNodes, othersLabel));
432
+ const flows = new Map<string, ResolvedFlow>();
433
+ for (const flow of raw.values()) {
434
+ const source = collapsed[0].display.get(flow.source) ?? othersLabel;
435
+ const middle = collapsed[1].display.get(flow.middle) ?? othersLabel;
436
+ const target = collapsed[2].display.get(flow.target) ?? othersLabel;
437
+ const key = `${source}\u0000${middle}\u0000${target}`;
438
+ const previous = flows.get(key);
439
+ if (previous) {
440
+ // Cannot overflow: a fold merge sums a SUBSET of the raw rows, and
441
+ // the raw grand total was already required finite above — so this
442
+ // sum is finite too.
443
+ previous.value += flow.value;
444
+ } else {
445
+ flows.set(key, { source, middle, target, value: flow.value });
446
+ }
447
+ }
448
+
449
+ // ── Node values after collapsing (conserved: same total per column). ──
450
+ const nodeValues: Array<Map<string, number>> = [
451
+ new Map<string, number>(),
452
+ new Map<string, number>(),
453
+ new Map<string, number>(),
454
+ ];
455
+ let total = 0;
456
+ for (const flow of flows.values()) {
457
+ total += flow.value;
458
+ addValue(nodeValues[0], flow.source, flow.value);
459
+ addValue(nodeValues[1], flow.middle, flow.value);
460
+ addValue(nodeValues[2], flow.target, flow.value);
461
+ }
462
+
463
+ // Belt-and-braces: if any merge slipped a non-finite amount through,
464
+ // the whole layout is meaningless — an explicit empty face beats NaN
465
+ // geometry and invalid `d` attributes. A supplied roster still gets its
466
+ // (all-idle) table, exactly like the ordinary empty face.
467
+ if (!Number.isFinite(total)) {
468
+ return {
469
+ width,
470
+ height,
471
+ nodes: [],
472
+ links: [],
473
+ legend: idleRosterRows(roster, palette),
474
+ total: 0,
475
+ empty: true,
476
+ };
477
+ }
478
+
479
+ const columns = nodeValues.map((values) => rankLabels(values));
480
+
481
+ // ── Colour assignment ──
482
+ // Model (last-column) colours follow roster order when a roster is given
483
+ // (stable across windows, idle included); otherwise value rank. Extra
484
+ // models with traffic but no roster row take the slots after the roster.
485
+ const modelColor = new Map<string, string>();
486
+ const rosterIndex = new Map<string, number>();
487
+ roster.forEach((entry) => {
488
+ // A malformed roster entry must not throw out of the component's
489
+ // computed (which would kill the render) or render a literal
490
+ // "undefined" legend row.
491
+ if (!entry || typeof entry.label !== "string" || entry.label === "") return;
492
+ const label = entry.label;
493
+ if (rosterIndex.has(label)) return;
494
+ // The slot is the ASSIGNED position, not the raw array index: a
495
+ // duplicated roster row must not skip a palette slot (which would
496
+ // hand two different models the same colour).
497
+ const slot = rosterIndex.size;
498
+ rosterIndex.set(label, slot);
499
+ // A blank string is not an explicit colour: it would set an empty
500
+ // `background` and leave the swatch invisible.
501
+ const explicit =
502
+ typeof entry.color === "string" && entry.color.trim() !== "" ? entry.color : null;
503
+ modelColor.set(label, explicit ?? palette[slot % palette.length]);
504
+ });
505
+ // Unregistered models take the slots AFTER the roster. Colour
506
+ // assignment is pre-fold (ranked by the real totals), so a model that
507
+ // the chart folds into the bucket still owns its stable colour.
508
+ const unregistered = [...columnValues[2].entries()]
509
+ .filter(([label]) => !rosterIndex.has(label))
510
+ .sort((a, b) => (b[1] - a[1]) || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
511
+ .map(([label]) => label);
512
+ unregistered.forEach((label, rank) => {
513
+ modelColor.set(label, palette[(rosterIndex.size + rank) % palette.length]);
514
+ });
515
+ /** The folded bucket's own colour: after every real label. */
516
+ const bucketColor = palette[(rosterIndex.size + unregistered.length) % palette.length];
517
+
518
+ const sourceColor = new Map<string, string>();
519
+ columns[0].forEach((label, rank) => sourceColor.set(label, palette[rank % palette.length]));
520
+ const middleColor = new Map<string, string>();
521
+ columns[1].forEach((label, rank) => middleColor.set(label, palette[rank % palette.length]));
522
+
523
+ // ── Vertical scale: one scale for all three columns. ──
524
+ const maxCount = Math.max(1, ...columns.map((labels) => labels.length));
525
+ // Always ≥ 1: the fit clamp above guarantees the column fits, and the
526
+ // 1-unit floor keeps `scale` strictly positive for any non-empty input.
527
+ const usable = Math.max(
528
+ 1,
529
+ height - PAD_Y * 2 - (maxCount - 1) * NODE_GAP - maxCount * MIN_NODE_HEIGHT,
530
+ );
531
+ // A finite-but-tiny window total (e.g. 1e-320) can overflow the RATIO
532
+ // even though both operands are finite: an Infinity scale would paint
533
+ // Infinity heights and an invalid `d`. Clamp it to zero instead — the
534
+ // visibility floor still shows every bar; only the magnitudes vanish,
535
+ // which is honest for a window whose total is numerically degenerate.
536
+ const rawScale = total > 0 && Number.isFinite(total) ? usable / total : 0;
537
+ const scale = Number.isFinite(rawScale) && rawScale > 0 ? rawScale : 0;
538
+
539
+ const xForColumn = (column: number): number => {
540
+ if (column === 0) return PAD_X;
541
+ if (column === COLUMN_COUNT - 1) return width - PAD_X - NODE_WIDTH;
542
+ return Math.round((width - NODE_WIDTH) / 2);
543
+ };
544
+
545
+ const nodes: HkUsageFlowNode[] = [];
546
+ const nodeByColumn: Array<Map<string, HkUsageFlowNode>> = [
547
+ new Map(),
548
+ new Map(),
549
+ new Map(),
550
+ ];
551
+ for (let column = 0; column < COLUMN_COUNT; column += 1) {
552
+ const labels = columns[column];
553
+ const x = xForColumn(column);
554
+ let cursor = PAD_Y;
555
+ for (const label of labels) {
556
+ const value = nodeValues[column].get(label) ?? 0;
557
+ const nodeHeight = Math.max(MIN_NODE_HEIGHT, value * scale);
558
+ const node: HkUsageFlowNode = {
559
+ key: `${column}:${label}`,
560
+ label: truncateFlowLabel(label, labelMaxChars),
561
+ fullLabel: label,
562
+ column,
563
+ value,
564
+ x,
565
+ y: px(cursor),
566
+ width: NODE_WIDTH,
567
+ height: px(nodeHeight),
568
+ color:
569
+ column === 2
570
+ ? (modelColor.get(label) ?? bucketColor)
571
+ : column === 0
572
+ ? (sourceColor.get(label) ?? palette[0])
573
+ : (middleColor.get(label) ?? palette[0]),
574
+ others: label === othersLabel && !collapsed[column].kept.has(label),
575
+ labelVisible: flowLabelVisible(nodeHeight),
576
+ };
577
+ nodes.push(node);
578
+ nodeByColumn[column].set(label, node);
579
+ cursor += nodeHeight + NODE_GAP;
580
+ }
581
+ }
582
+
583
+ // ── Ribbons: stack each node's links in the neighbour's vertical order so
584
+ // crossing is minimised, then accumulate the two sides independently
585
+ // (each side's stack sums to the node height — the conservation
586
+ // invariant). ──
587
+ const links: HkUsageFlowLink[] = [];
588
+ for (let stage = 0; stage < COLUMN_COUNT - 1; stage += 1) {
589
+ const pairs = new Map<string, { left: string; right: string; value: number }>();
590
+ for (const flow of flows.values()) {
591
+ const left = stage === 0 ? flow.source : flow.middle;
592
+ const right = stage === 0 ? flow.middle : flow.target;
593
+ const key = `${left}\u0000${right}`;
594
+ const previous = pairs.get(key);
595
+ if (previous) {
596
+ previous.value += flow.value;
597
+ } else {
598
+ pairs.set(key, { left, right, value: flow.value });
599
+ }
600
+ }
601
+ const sourceNodes = nodeByColumn[stage];
602
+ const targetNodes = nodeByColumn[stage + 1];
603
+ const outgoing = new Map<string, Array<{ left: string; right: string; value: number }>>();
604
+ const incoming = new Map<string, Array<{ left: string; right: string; value: number }>>();
605
+ for (const pair of pairs.values()) {
606
+ if (!outgoing.has(pair.left)) outgoing.set(pair.left, []);
607
+ outgoing.get(pair.left)!.push(pair);
608
+ if (!incoming.has(pair.right)) incoming.set(pair.right, []);
609
+ incoming.get(pair.right)!.push(pair);
610
+ }
611
+ const startCursor = new Map<string, number>();
612
+ for (const [label, node] of sourceNodes) {
613
+ const items = (outgoing.get(label) ?? []).sort((a, b) => {
614
+ const ay = targetNodes.get(a.right)?.y ?? 0;
615
+ const by = targetNodes.get(b.right)?.y ?? 0;
616
+ return ay - by;
617
+ });
618
+ let cursor = node.y;
619
+ for (const item of items) {
620
+ startCursor.set(`${item.left}\u0000${item.right}`, cursor);
621
+ // The slot is the EXACT scaled value — never the floored bar
622
+ // height — so the stack sums to `value × scale` on both sides.
623
+ cursor += item.value * scale;
624
+ }
625
+ }
626
+ const endCursor = new Map<string, number>();
627
+ for (const [label, node] of targetNodes) {
628
+ const items = (incoming.get(label) ?? []).sort((a, b) => {
629
+ const ay = sourceNodes.get(a.left)?.y ?? 0;
630
+ const by = sourceNodes.get(b.left)?.y ?? 0;
631
+ return ay - by;
632
+ });
633
+ let cursor = node.y;
634
+ for (const item of items) {
635
+ endCursor.set(`${item.left}\u0000${item.right}`, cursor);
636
+ cursor += item.value * scale;
637
+ }
638
+ }
639
+ const ordered = [...pairs.values()].sort((a, b) => {
640
+ const ay = sourceNodes.get(a.left)?.y ?? 0;
641
+ const by = sourceNodes.get(b.left)?.y ?? 0;
642
+ if (ay !== by) return ay - by;
643
+ const at = targetNodes.get(a.right)?.y ?? 0;
644
+ const bt = targetNodes.get(b.right)?.y ?? 0;
645
+ if (at !== bt) return at - bt;
646
+ return a.right < b.right ? -1 : a.right > b.right ? 1 : 0;
647
+ });
648
+ for (const pair of ordered) {
649
+ const source = sourceNodes.get(pair.left);
650
+ const target = targetNodes.get(pair.right);
651
+ if (!source || !target) continue;
652
+ const thickness = pair.value * scale;
653
+ const y0 = px(startCursor.get(`${pair.left}\u0000${pair.right}`) ?? source.y);
654
+ const y1 = px(endCursor.get(`${pair.left}\u0000${pair.right}`) ?? target.y);
655
+ links.push({
656
+ key: `${source.key}->${target.key}`,
657
+ sourceKey: source.key,
658
+ targetKey: target.key,
659
+ value: pair.value,
660
+ // The path is built from the SAME rounded slot values the layout
661
+ // exports, so a draw-time floor (or any other divergence between
662
+ // the drawn edge and the geometry) is observable from `d`.
663
+ path: ribbonPath(source.x + source.width, y0, target.x, y1, thickness),
664
+ color: target.color,
665
+ thickness,
666
+ startY: y0,
667
+ endY: y1,
668
+ });
669
+ }
670
+ }
671
+
672
+ // ── Legend: the FULL model table, pre-collapse. Roster order first
673
+ // (idle rows included), then models that served traffic without a
674
+ // roster row. The chart's folded bucket is NOT a legend row: the
675
+ // legend's job is every model's real total, and folding is a chart
676
+ // layout decision, not a usage fact. ──
677
+ const measuredValues = columnValues[2];
678
+ const legend: HkUsageFlowLegendRow[] = [];
679
+ const seen = new Set<string>();
680
+ for (const entry of roster) {
681
+ if (!entry || typeof entry.label !== "string" || entry.label === "") continue;
682
+ const label = entry.label;
683
+ if (seen.has(label)) continue;
684
+ seen.add(label);
685
+ const value = measuredValues.get(label) ?? 0;
686
+ legend.push({
687
+ label,
688
+ value,
689
+ percent: total > 0 ? (value / total) * 100 : 0,
690
+ color: modelColor.get(label) ?? palette[(rosterIndex.get(label) ?? 0) % palette.length],
691
+ idle: value <= 0,
692
+ });
693
+ }
694
+ for (const label of unregistered) {
695
+ if (seen.has(label)) continue;
696
+ seen.add(label);
697
+ const value = measuredValues.get(label) ?? 0;
698
+ legend.push({
699
+ label,
700
+ value,
701
+ percent: total > 0 ? (value / total) * 100 : 0,
702
+ color: modelColor.get(label) ?? bucketColor,
703
+ idle: value <= 0,
704
+ });
705
+ }
706
+
707
+ return { width, height, nodes, links, legend, total, empty };
708
+ }
709
+
710
+ /** Share as the visible string: whole percents, with `<1%` for a real but
711
+ * sub-percent slice and `0%` for nothing. */
712
+ export function formatFlowPercent(percent: number): string {
713
+ if (!Number.isFinite(percent) || percent <= 0) return "0%";
714
+ if (percent < 1) return "<1%";
715
+ return `${Math.round(percent)}%`;
716
+ }