@rtkelly-labs/design-system 0.16.0 → 0.18.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.
- package/CHANGELOG.md +28 -0
- package/dist/components/AlertList.js +246 -0
- package/dist/components/AlertList.js.map +1 -0
- package/dist/components/FilterBar.js +215 -0
- package/dist/components/FilterBar.js.map +1 -0
- package/dist/components/FreshnessIndicator.js +50 -0
- package/dist/components/FreshnessIndicator.js.map +1 -0
- package/dist/components/IdChip.js +58 -0
- package/dist/components/IdChip.js.map +1 -0
- package/dist/components/IncidentTimeline.js +122 -0
- package/dist/components/IncidentTimeline.js.map +1 -0
- package/dist/components/LatencyHeatmap.js +382 -0
- package/dist/components/LatencyHeatmap.js.map +1 -0
- package/dist/components/LatencyHistogram.js +282 -0
- package/dist/components/LatencyHistogram.js.map +1 -0
- package/dist/components/LogViewer.js +393 -0
- package/dist/components/LogViewer.js.map +1 -0
- package/dist/components/ServiceMap.js +404 -0
- package/dist/components/ServiceMap.js.map +1 -0
- package/dist/components/SeverityBadge.js +15 -0
- package/dist/components/SeverityBadge.js.map +1 -0
- package/dist/components/TimeRange.js +89 -0
- package/dist/components/TimeRange.js.map +1 -0
- package/dist/components/TimeSeriesChart.js +507 -0
- package/dist/components/TimeSeriesChart.js.map +1 -0
- package/dist/components/TraceViewer.js +159 -0
- package/dist/components/TraceViewer.js.map +1 -0
- package/dist/components/TraceWaterfall.js +226 -0
- package/dist/components/TraceWaterfall.js.map +1 -0
- package/dist/components/docs/figures/ChangeSummary.js +5 -5
- package/dist/components/docs/figures/ChangeSummary.js.map +1 -1
- package/dist/components/docs/figures/FileChangeTree.js +4 -4
- package/dist/components/docs/figures/FileChangeTree.js.map +1 -1
- package/dist/components/saas/ObservabilityConsole.js +220 -0
- package/dist/components/saas/ObservabilityConsole.js.map +1 -0
- package/dist/components/saas/observabilityData.js +250 -0
- package/dist/components/saas/observabilityData.js.map +1 -0
- package/dist/hooks/useMeasuredWidth.js +22 -0
- package/dist/hooks/useMeasuredWidth.js.map +1 -0
- package/dist/hooks/useTraceClock.js +17 -0
- package/dist/hooks/useTraceClock.js.map +1 -0
- package/dist/hooks/useTraceReplay.js +75 -0
- package/dist/hooks/useTraceReplay.js.map +1 -0
- package/dist/index.d.ts +1596 -3
- package/dist/index.js +25 -0
- package/dist/index.js.map +1 -1
- package/dist/lib/filters.js +130 -0
- package/dist/lib/filters.js.map +1 -0
- package/dist/lib/ids.js +9 -0
- package/dist/lib/ids.js.map +1 -0
- package/dist/lib/latency.js +228 -0
- package/dist/lib/latency.js.map +1 -0
- package/dist/lib/logs.js +78 -0
- package/dist/lib/logs.js.map +1 -0
- package/dist/lib/serviceGraph.js +243 -0
- package/dist/lib/serviceGraph.js.map +1 -0
- package/dist/lib/severity.js +23 -0
- package/dist/lib/severity.js.map +1 -0
- package/dist/lib/theme.js +12 -0
- package/dist/lib/theme.js.map +1 -1
- package/dist/lib/timeRange.js +94 -0
- package/dist/lib/timeRange.js.map +1 -0
- package/dist/lib/timeSeries.js +285 -0
- package/dist/lib/timeSeries.js.map +1 -0
- package/dist/lib/trace.js +251 -0
- package/dist/lib/trace.js.map +1 -0
- package/dist/theme/contrast.js +15 -0
- package/dist/theme/contrast.js.map +1 -1
- package/dist/theme/levels.js +31 -0
- package/dist/theme/levels.js.map +1 -1
- package/dist/theme.css +30 -0
- package/package.json +1 -1
- package/tokens/palette.midnight.tokens.json +50 -0
- package/tokens/palette.sketch.tokens.json +50 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/lib/logs.ts"],"sourcesContent":["/**\n * The log model: entries in, the lines a viewer draws out.\n *\n * Pure data, no React, so a caller can filter, order or search a log stream\n * without rendering one — `LogViewer` highlights a query but never filters by\n * it, and this is what the caller filters with.\n *\n * Time is epoch milliseconds, and nothing here reads the clock.\n */\n\nimport type { LogSeverity } from './severity';\nimport { formatTimestamp, type TimeRange } from './timeRange';\n\n/** A log field value, flattened the way OTLP attributes are. */\nexport type LogFieldValue = string | number | boolean;\n\n/** One log line. */\nexport interface LogEntry {\n /** Unique within the stream; rows are keyed by it. */\n id: string;\n /** When the line was emitted, in epoch milliseconds. */\n time: number;\n /** OpenTelemetry's severity name, lower case. */\n severity: LogSeverity;\n /** The log body. One line in the list; in full when the row is expanded. */\n message: string;\n /** The emitting service (OTLP `service.name`). */\n service?: string;\n /** The trace this line was written inside, when it was. */\n traceId?: string;\n /** The span this line was written inside, when it was. */\n spanId?: string;\n /** Structured attributes, shown as a key/value list when expanded. */\n fields?: Record<string, LogFieldValue>;\n}\n\n/** Severities from least to most severe. */\nexport const LOG_SEVERITIES: readonly LogSeverity[] = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];\n\n/** What `filterLogEntries` keeps. Every criterion is optional and they combine with AND. */\nexport interface LogFilter {\n /** Case-insensitive text matched against the message, service, ids and field values. */\n query?: string;\n /** Keep only these severities. An empty list keeps nothing. */\n severities?: readonly LogSeverity[];\n /** Keep only entries inside this closed window. */\n range?: TimeRange | null;\n}\n\n/** Whether `entry` contains `query` (already lower-cased) anywhere a reader would look. */\nexport function matchLogEntry(entry: LogEntry, query: string): boolean {\n const needle = query.trim().toLowerCase();\n if (!needle) return true;\n if (entry.message.toLowerCase().includes(needle)) return true;\n if (entry.service?.toLowerCase().includes(needle)) return true;\n if (entry.traceId?.toLowerCase().includes(needle) || entry.spanId?.toLowerCase().includes(needle)) return true;\n if (!entry.fields) return false;\n return Object.entries(entry.fields).some(\n ([key, value]) => `${key}=${String(value)}`.toLowerCase().includes(needle),\n );\n}\n\n/** Whether `time` lies inside `range`, both ends included. */\nexport function inLogRange(time: number, range: TimeRange): boolean {\n const from = Math.min(range.from, range.to);\n const to = Math.max(range.from, range.to);\n return time >= from && time <= to;\n}\n\n/**\n * The entries a filter keeps, in their original order. A pure helper: the\n * caller filters, the viewer only highlights.\n */\nexport function filterLogEntries(entries: readonly LogEntry[], filter: LogFilter = {}): LogEntry[] {\n const { query, severities, range } = filter;\n const allowed = severities ? new Set(severities) : null;\n return entries.filter(\n (entry) =>\n (!allowed || allowed.has(entry.severity)) &&\n (!range || inLogRange(entry.time, range)) &&\n (!query || matchLogEntry(entry, query)),\n );\n}\n\n/**\n * Entries in time order, oldest first (`asc`) or newest first (`desc`).\n * Stable: lines with the same timestamp keep the order they arrived in.\n */\nexport function sortLogEntries(entries: readonly LogEntry[], order: 'asc' | 'desc' = 'asc'): LogEntry[] {\n const sign = order === 'desc' ? -1 : 1;\n return entries\n .map((entry, index) => ({ entry, index }))\n .sort((a, b) => (a.entry.time - b.entry.time) * sign || a.index - b.index)\n .map(({ entry }) => entry);\n}\n\n/** One run of text, and whether it matched the query. */\nexport interface LogHighlightPart {\n text: string;\n match: boolean;\n}\n\n/**\n * Split `text` into runs around every case-insensitive occurrence of `query`.\n * An empty query is one unmatched run.\n */\nexport function highlightLogText(text: string, query: string | undefined): LogHighlightPart[] {\n const needle = query?.trim().toLowerCase();\n if (!needle) return [{ text, match: false }];\n const haystack = text.toLowerCase();\n const parts: LogHighlightPart[] = [];\n let at = 0;\n for (let hit = haystack.indexOf(needle); hit !== -1; hit = haystack.indexOf(needle, at)) {\n if (hit > at) parts.push({ text: text.slice(at, hit), match: false });\n parts.push({ text: text.slice(hit, hit + needle.length), match: true });\n at = hit + needle.length;\n }\n if (at < text.length) parts.push({ text: text.slice(at), match: false });\n return parts.length ? parts : [{ text, match: false }];\n}\n\n/**\n * The index of the entry whose time is nearest `time`, in a list already in\n * time order (either direction). Null when the list is empty or `time` lies\n * outside the span the list covers — a cursor past the last line marks none.\n */\nexport function nearestLogIndex(entries: readonly LogEntry[], time: number | null | undefined): number | null {\n if (time == null || !Number.isFinite(time) || !entries.length) return null;\n const first = entries[0].time;\n const last = entries[entries.length - 1].time;\n const desc = first > last;\n const lo = Math.min(first, last);\n const hi = Math.max(first, last);\n if (time < lo || time > hi) return null;\n // Binary search for the first index at or past `time` in reading order.\n let low = 0;\n let high = entries.length - 1;\n while (low < high) {\n const mid = (low + high) >> 1;\n const past = desc ? entries[mid].time <= time : entries[mid].time >= time;\n if (past) high = mid;\n else low = mid + 1;\n }\n const prev = low - 1;\n if (prev >= 0 && Math.abs(entries[prev].time - time) <= Math.abs(entries[low].time - time)) return prev;\n return low;\n}\n\n/** What a screen reader hears for one line: time, severity, service, message. */\nexport function describeLogEntry(entry: LogEntry): string {\n return [`${formatTimestamp(entry.time, 'millisecond')} UTC`, entry.severity.toUpperCase(), entry.service, entry.message].filter(Boolean).join(', ');\n}\n"],"mappings":";AAWA,SAAS,uBAAuC;AA0BzC,IAAM,iBAAyC,CAAC,SAAS,SAAS,QAAQ,QAAQ,SAAS,OAAO;AAalG,SAAS,cAAc,OAAiB,OAAwB;AACrE,QAAM,SAAS,MAAM,KAAK,EAAE,YAAY;AACxC,MAAI,CAAC,OAAQ,QAAO;AACpB,MAAI,MAAM,QAAQ,YAAY,EAAE,SAAS,MAAM,EAAG,QAAO;AACzD,MAAI,MAAM,SAAS,YAAY,EAAE,SAAS,MAAM,EAAG,QAAO;AAC1D,MAAI,MAAM,SAAS,YAAY,EAAE,SAAS,MAAM,KAAK,MAAM,QAAQ,YAAY,EAAE,SAAS,MAAM,EAAG,QAAO;AAC1G,MAAI,CAAC,MAAM,OAAQ,QAAO;AAC1B,SAAO,OAAO,QAAQ,MAAM,MAAM,EAAE;AAAA,IAClC,CAAC,CAAC,KAAK,KAAK,MAAM,GAAG,GAAG,IAAI,OAAO,KAAK,CAAC,GAAG,YAAY,EAAE,SAAS,MAAM;AAAA,EAC3E;AACF;AAGO,SAAS,WAAW,MAAc,OAA2B;AAClE,QAAM,OAAO,KAAK,IAAI,MAAM,MAAM,MAAM,EAAE;AAC1C,QAAM,KAAK,KAAK,IAAI,MAAM,MAAM,MAAM,EAAE;AACxC,SAAO,QAAQ,QAAQ,QAAQ;AACjC;AAMO,SAAS,iBAAiB,SAA8B,SAAoB,CAAC,GAAe;AACjG,QAAM,EAAE,OAAO,YAAY,MAAM,IAAI;AACrC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B,SAA8B,MAAgD;AAC5G,MAAI,QAAQ,QAAQ,CAAC,OAAO,SAAS,IAAI,KAAK,CAAC,QAAQ,OAAQ,QAAO;AACtE,QAAM,QAAQ,QAAQ,CAAC,EAAE;AACzB,QAAM,OAAO,QAAQ,QAAQ,SAAS,CAAC,EAAE;AACzC,QAAM,OAAO,QAAQ;AACrB,QAAM,KAAK,KAAK,IAAI,OAAO,IAAI;AAC/B,QAAM,KAAK,KAAK,IAAI,OAAO,IAAI;AAC/B,MAAI,OAAO,MAAM,OAAO,GAAI,QAAO;AAEnC,MAAI,MAAM;AACV,MAAI,OAAO,QAAQ,SAAS;AAC5B,SAAO,MAAM,MAAM;AACjB,UAAM,MAAO,MAAM,QAAS;AAC5B,UAAM,OAAO,OAAO,QAAQ,GAAG,EAAE,QAAQ,OAAO,QAAQ,GAAG,EAAE,QAAQ;AACrE,QAAI,KAAM,QAAO;AAAA,QACZ,OAAM,MAAM;AAAA,EACnB;AACA,QAAM,OAAO,MAAM;AACnB,MAAI,QAAQ,KAAK,KAAK,IAAI,QAAQ,IAAI,EAAE,OAAO,IAAI,KAAK,KAAK,IAAI,QAAQ,GAAG,EAAE,OAAO,IAAI,EAAG,QAAO;AACnG,SAAO;AACT;AAGO,SAAS,iBAAiB,OAAyB;AACxD,SAAO,CAAC,GAAG,gBAAgB,MAAM,MAAM,aAAa,CAAC,QAAQ,MAAM,SAAS,YAAY,GAAG,MAAM,SAAS,MAAM,OAAO,EAAE,OAAO,OAAO,EAAE,KAAK,IAAI;AACpJ;","names":[]}
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
// src/lib/serviceGraph.ts
|
|
2
|
+
var UNKNOWN_SERVICE = "unknown";
|
|
3
|
+
function finite(value) {
|
|
4
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
5
|
+
}
|
|
6
|
+
function spanDuration(span) {
|
|
7
|
+
if (!finite(span.start)) return null;
|
|
8
|
+
if (finite(span.end)) return Math.max(0, span.end - span.start);
|
|
9
|
+
if (finite(span.duration)) return Math.max(0, span.duration);
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
function mean(values) {
|
|
13
|
+
return values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : 0;
|
|
14
|
+
}
|
|
15
|
+
function p95(values) {
|
|
16
|
+
if (!values.length) return void 0;
|
|
17
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
18
|
+
return sorted[Math.max(0, Math.ceil(sorted.length * 0.95) - 1)];
|
|
19
|
+
}
|
|
20
|
+
function compare(a, b) {
|
|
21
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
22
|
+
}
|
|
23
|
+
function isTraceList(input) {
|
|
24
|
+
return input.length > 0 && Array.isArray(input[0]);
|
|
25
|
+
}
|
|
26
|
+
function serviceGraph(input) {
|
|
27
|
+
const traces = isTraceList(input) ? input : [input];
|
|
28
|
+
const nodes = /* @__PURE__ */ new Map();
|
|
29
|
+
const edges = /* @__PURE__ */ new Map();
|
|
30
|
+
const peers = [];
|
|
31
|
+
const nodeOf = (id) => {
|
|
32
|
+
let tally = nodes.get(id);
|
|
33
|
+
if (!tally) nodes.set(id, tally = { requests: 0, errors: 0, durations: [], database: false, queue: false });
|
|
34
|
+
return tally;
|
|
35
|
+
};
|
|
36
|
+
const edgeOf = (from, to) => {
|
|
37
|
+
const key = `${from}\0${to}`;
|
|
38
|
+
let tally = edges.get(key);
|
|
39
|
+
if (!tally) edges.set(key, tally = { from, to, calls: 0, errors: 0, durations: [] });
|
|
40
|
+
return tally;
|
|
41
|
+
};
|
|
42
|
+
for (const trace of traces) {
|
|
43
|
+
const byId = /* @__PURE__ */ new Map();
|
|
44
|
+
for (const span of trace) if (span && typeof span.id === "string" && finite(span.start) && !byId.has(span.id)) byId.set(span.id, span);
|
|
45
|
+
for (const span of byId.values()) {
|
|
46
|
+
const service = span.service || UNKNOWN_SERVICE;
|
|
47
|
+
const node = nodeOf(service);
|
|
48
|
+
const attributes = span.attributes ?? {};
|
|
49
|
+
if (attributes["db.system"] !== void 0) node.database = true;
|
|
50
|
+
if (attributes["messaging.system"] !== void 0 || span.kind === "producer" || span.kind === "consumer") node.queue = true;
|
|
51
|
+
const parent = span.parentId && span.parentId !== span.id ? byId.get(span.parentId) : void 0;
|
|
52
|
+
const parentService = parent ? parent.service || UNKNOWN_SERVICE : null;
|
|
53
|
+
const duration = spanDuration(span);
|
|
54
|
+
const error = span.status === "error";
|
|
55
|
+
if (parentService !== service) {
|
|
56
|
+
node.requests += 1;
|
|
57
|
+
if (error) node.errors += 1;
|
|
58
|
+
if (duration !== null) node.durations.push(duration);
|
|
59
|
+
}
|
|
60
|
+
if (parentService !== null && parentService !== service) {
|
|
61
|
+
const edge = edgeOf(parentService, service);
|
|
62
|
+
edge.calls += 1;
|
|
63
|
+
if (error) edge.errors += 1;
|
|
64
|
+
if (duration !== null) edge.durations.push(duration);
|
|
65
|
+
}
|
|
66
|
+
const peer = attributes["peer.service"];
|
|
67
|
+
if (span.kind === "client" && typeof peer === "string" && peer && peer !== service) peers.push({ from: service, to: peer, span });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const external = /* @__PURE__ */ new Set();
|
|
71
|
+
for (const { from, to, span } of peers) {
|
|
72
|
+
if (nodes.has(to) && !external.has(to)) continue;
|
|
73
|
+
external.add(to);
|
|
74
|
+
const node = nodeOf(to);
|
|
75
|
+
const edge = edgeOf(from, to);
|
|
76
|
+
const duration = spanDuration(span);
|
|
77
|
+
const error = span.status === "error";
|
|
78
|
+
node.requests += 1;
|
|
79
|
+
edge.calls += 1;
|
|
80
|
+
if (error) {
|
|
81
|
+
node.errors += 1;
|
|
82
|
+
edge.errors += 1;
|
|
83
|
+
}
|
|
84
|
+
if (duration !== null) {
|
|
85
|
+
node.durations.push(duration);
|
|
86
|
+
edge.durations.push(duration);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return {
|
|
90
|
+
nodes: [...nodes.entries()].sort(([a], [b]) => compare(a, b)).map(([id, tally]) => {
|
|
91
|
+
const node = {
|
|
92
|
+
id,
|
|
93
|
+
requests: tally.requests,
|
|
94
|
+
errors: tally.errors,
|
|
95
|
+
avgDuration: mean(tally.durations),
|
|
96
|
+
kind: external.has(id) ? "external" : tally.database ? "database" : tally.queue ? "queue" : "service"
|
|
97
|
+
};
|
|
98
|
+
const percentile = p95(tally.durations);
|
|
99
|
+
if (percentile !== void 0) node.p95Duration = percentile;
|
|
100
|
+
return node;
|
|
101
|
+
}),
|
|
102
|
+
edges: [...edges.values()].sort((a, b) => compare(a.from, b.from) || compare(a.to, b.to)).map(({ from, to, calls, errors, durations }) => ({ from, to, calls, errors, avgDuration: mean(durations) }))
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function positive(value, fallback) {
|
|
106
|
+
return finite(value) && value >= 0 ? value : fallback;
|
|
107
|
+
}
|
|
108
|
+
function layoutServiceGraph(graph, options = {}) {
|
|
109
|
+
const columnGap = positive(options.columnGap, 72);
|
|
110
|
+
const rowGap = positive(options.rowGap, 24);
|
|
111
|
+
const nodeWidth = positive(options.nodeWidth, 168);
|
|
112
|
+
const nodeHeight = positive(options.nodeHeight, 64);
|
|
113
|
+
const ids = [...new Set(graph.nodes.map((node) => node.id))].sort(compare);
|
|
114
|
+
const known = new Set(ids);
|
|
115
|
+
const pairs = /* @__PURE__ */ new Map();
|
|
116
|
+
for (const edge of graph.edges) {
|
|
117
|
+
if (edge.from === edge.to || !known.has(edge.from) || !known.has(edge.to)) continue;
|
|
118
|
+
pairs.set(`${edge.from}\0${edge.to}`, { from: edge.from, to: edge.to });
|
|
119
|
+
}
|
|
120
|
+
const out = new Map(ids.map((id) => [id, []]));
|
|
121
|
+
const indegree = new Map(ids.map((id) => [id, 0]));
|
|
122
|
+
for (const { from, to } of pairs.values()) {
|
|
123
|
+
out.get(from).push(to);
|
|
124
|
+
indegree.set(to, indegree.get(to) + 1);
|
|
125
|
+
}
|
|
126
|
+
for (const list of out.values()) list.sort(compare);
|
|
127
|
+
const reversed = /* @__PURE__ */ new Set();
|
|
128
|
+
const state = /* @__PURE__ */ new Map();
|
|
129
|
+
const visit = (id) => {
|
|
130
|
+
state.set(id, "open");
|
|
131
|
+
for (const next of out.get(id)) {
|
|
132
|
+
const seen = state.get(next);
|
|
133
|
+
if (seen === "open") reversed.add(`${id}\0${next}`);
|
|
134
|
+
else if (!seen) visit(next);
|
|
135
|
+
}
|
|
136
|
+
state.set(id, "done");
|
|
137
|
+
};
|
|
138
|
+
for (const id of ids) if (indegree.get(id) === 0 && !state.has(id)) visit(id);
|
|
139
|
+
for (const id of ids) if (!state.has(id)) visit(id);
|
|
140
|
+
const forward = [...pairs.entries()].filter(([key]) => !reversed.has(key)).map(([, pair]) => pair);
|
|
141
|
+
const preds = new Map(ids.map((id) => [id, []]));
|
|
142
|
+
const succs = new Map(ids.map((id) => [id, []]));
|
|
143
|
+
for (const { from, to } of forward) {
|
|
144
|
+
succs.get(from).push(to);
|
|
145
|
+
preds.get(to).push(from);
|
|
146
|
+
}
|
|
147
|
+
const layerOf = new Map(ids.map((id) => [id, 0]));
|
|
148
|
+
const remaining = new Map(ids.map((id) => [id, preds.get(id).length]));
|
|
149
|
+
const queue = ids.filter((id) => remaining.get(id) === 0);
|
|
150
|
+
while (queue.length) {
|
|
151
|
+
const id = queue.shift();
|
|
152
|
+
for (const next of succs.get(id)) {
|
|
153
|
+
layerOf.set(next, Math.max(layerOf.get(next), layerOf.get(id) + 1));
|
|
154
|
+
remaining.set(next, remaining.get(next) - 1);
|
|
155
|
+
if (remaining.get(next) === 0) queue.push(next);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
const layerCount = ids.length ? Math.max(...layerOf.values()) + 1 : 0;
|
|
159
|
+
const layers = Array.from({ length: layerCount }, () => []);
|
|
160
|
+
for (const id of ids) layers[layerOf.get(id)].push(id);
|
|
161
|
+
const row = /* @__PURE__ */ new Map();
|
|
162
|
+
const index = () => {
|
|
163
|
+
for (const layer of layers) layer.forEach((id, at) => row.set(id, at));
|
|
164
|
+
};
|
|
165
|
+
index();
|
|
166
|
+
const reorder = (layer, neighbours) => {
|
|
167
|
+
const keyed = layer.map((id) => {
|
|
168
|
+
const list = neighbours.get(id);
|
|
169
|
+
return { id, key: list.length ? mean(list.map((other) => row.get(other))) : row.get(id), at: row.get(id) };
|
|
170
|
+
});
|
|
171
|
+
keyed.sort((a, b) => a.key - b.key || a.at - b.at || compare(a.id, b.id));
|
|
172
|
+
layer.splice(0, layer.length, ...keyed.map((entry) => entry.id));
|
|
173
|
+
layer.forEach((id, at) => row.set(id, at));
|
|
174
|
+
};
|
|
175
|
+
for (let sweep = 0; sweep < 2; sweep += 1) {
|
|
176
|
+
for (let at = 1; at < layers.length; at += 1) reorder(layers[at], preds);
|
|
177
|
+
for (let at = layers.length - 2; at >= 0; at -= 1) reorder(layers[at], succs);
|
|
178
|
+
}
|
|
179
|
+
const tallest = layers.reduce((max, layer) => Math.max(max, layer.length), 0);
|
|
180
|
+
const pitch = nodeHeight + rowGap;
|
|
181
|
+
const height = tallest ? tallest * nodeHeight + (tallest - 1) * rowGap : 0;
|
|
182
|
+
const width = layerCount ? layerCount * nodeWidth + (layerCount - 1) * columnGap : 0;
|
|
183
|
+
const nodes = [];
|
|
184
|
+
const placed = /* @__PURE__ */ new Map();
|
|
185
|
+
layers.forEach((layer, at) => {
|
|
186
|
+
const offset = (tallest - layer.length) * pitch / 2;
|
|
187
|
+
layer.forEach((id, position) => {
|
|
188
|
+
const node = { id, x: at * (nodeWidth + columnGap), y: offset + position * pitch, layer: at, index: position };
|
|
189
|
+
nodes.push(node);
|
|
190
|
+
placed.set(id, node);
|
|
191
|
+
});
|
|
192
|
+
});
|
|
193
|
+
const edges = [...pairs.values()].map(({ from, to }) => {
|
|
194
|
+
const a = placed.get(from);
|
|
195
|
+
const b = placed.get(to);
|
|
196
|
+
if (b.layer > a.layer) {
|
|
197
|
+
return { from, to, back: false, source: { x: a.x + nodeWidth, y: a.y + nodeHeight / 2 }, target: { x: b.x, y: b.y + nodeHeight / 2 } };
|
|
198
|
+
}
|
|
199
|
+
return { from, to, back: true, dip: height + rowGap, source: { x: a.x + nodeWidth / 2, y: a.y + nodeHeight }, target: { x: b.x + nodeWidth / 2, y: b.y + nodeHeight } };
|
|
200
|
+
});
|
|
201
|
+
return { nodes, edges, width, height, nodeWidth, nodeHeight, layers: layerCount };
|
|
202
|
+
}
|
|
203
|
+
function dipOf(edge) {
|
|
204
|
+
return edge.dip ?? Math.max(edge.source.y, edge.target.y) + 24;
|
|
205
|
+
}
|
|
206
|
+
function serviceEdgePath(edge) {
|
|
207
|
+
const { source: s, target: t } = edge;
|
|
208
|
+
if (edge.back) {
|
|
209
|
+
const dip = dipOf(edge);
|
|
210
|
+
return `M ${s.x} ${s.y} C ${s.x} ${dip}, ${t.x} ${dip}, ${t.x} ${t.y}`;
|
|
211
|
+
}
|
|
212
|
+
const dx = (t.x - s.x) / 2;
|
|
213
|
+
return `M ${s.x} ${s.y} C ${s.x + dx} ${s.y}, ${t.x - dx} ${t.y}, ${t.x} ${t.y}`;
|
|
214
|
+
}
|
|
215
|
+
function serviceEdgeMidpoint(edge) {
|
|
216
|
+
const { source: s, target: t } = edge;
|
|
217
|
+
if (edge.back) return { x: (s.x + t.x) / 2, y: (s.y + t.y) / 8 + 3 * dipOf(edge) / 4 };
|
|
218
|
+
return { x: (s.x + t.x) / 2, y: (s.y + t.y) / 2 };
|
|
219
|
+
}
|
|
220
|
+
function formatServiceCount(value) {
|
|
221
|
+
if (!finite(value)) return "\u2014";
|
|
222
|
+
const abs = Math.abs(value);
|
|
223
|
+
const short = (n, unit) => `${n < 10 ? n.toFixed(1).replace(/\.0$/, "") : Math.round(n)}${unit}`;
|
|
224
|
+
if (abs < 1e3) return String(Math.round(value));
|
|
225
|
+
if (abs < 1e6) return short(value / 1e3, "k");
|
|
226
|
+
return short(value / 1e6, "M");
|
|
227
|
+
}
|
|
228
|
+
function formatServiceErrorRate(errors, total) {
|
|
229
|
+
if (!finite(errors) || !finite(total) || total <= 0) return "0%";
|
|
230
|
+
const percent = errors / total * 100;
|
|
231
|
+
if (percent === 0) return "0%";
|
|
232
|
+
if (percent < 1) return `${percent.toFixed(1)}%`;
|
|
233
|
+
return `${Math.round(percent)}%`;
|
|
234
|
+
}
|
|
235
|
+
export {
|
|
236
|
+
formatServiceCount,
|
|
237
|
+
formatServiceErrorRate,
|
|
238
|
+
layoutServiceGraph,
|
|
239
|
+
serviceEdgeMidpoint,
|
|
240
|
+
serviceEdgePath,
|
|
241
|
+
serviceGraph
|
|
242
|
+
};
|
|
243
|
+
//# sourceMappingURL=serviceGraph.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/lib/serviceGraph.ts"],"sourcesContent":["/**\n * The service graph: spans in, services and the calls between them out.\n *\n * Where `trace.ts` answers \"what happened in this request?\", this module\n * answers \"which services talk to which, how often, and how badly?\". It folds\n * any number of spans — one trace or a thousand — into one node per service\n * and one edge per caller → callee pair, then lays that graph out in layers.\n *\n * Pure data, no React, no clock: the same spans always produce the same graph\n * and the same coordinates, so a story or a snapshot is deterministic.\n *\n * Every duration is milliseconds, as in `trace.ts`.\n */\n\nimport type { TraceSpanInput } from './trace';\n\n/** What a service is, as far as its spans say. */\nexport type ServiceNodeKind = 'service' | 'database' | 'queue' | 'external';\n\n/** One service, with the traffic that entered it. */\nexport interface ServiceNode {\n /** The service name (OTLP `service.name`). */\n id: string;\n /** Spans that entered this service: roots, or spans whose parent is in another service. */\n requests: number;\n /** Of those requests, how many ended in error. */\n errors: number;\n /** Mean duration of the requests, in milliseconds. `0` when none had an end. */\n avgDuration: number;\n /** 95th-percentile (nearest rank) duration of the requests, in milliseconds. */\n p95Duration?: number;\n /** Inferred from span kind and attributes. */\n kind?: ServiceNodeKind;\n}\n\n/** Calls from one service into another. */\nexport interface ServiceEdge {\n /** The calling service. */\n from: string;\n /** The called service. */\n to: string;\n /** How many spans crossed from `from` into `to`. */\n calls: number;\n /** Of those, how many ended in error. */\n errors: number;\n /** Mean duration of the called spans, in milliseconds. */\n avgDuration: number;\n}\n\n/** Services and the calls between them. */\nexport interface ServiceGraph {\n /** Sorted by id. */\n nodes: ServiceNode[];\n /** Sorted by `from`, then `to`. */\n edges: ServiceEdge[];\n}\n\nconst UNKNOWN_SERVICE = 'unknown';\n\nfunction finite(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value);\n}\n\nfunction spanDuration(span: TraceSpanInput): number | null {\n if (!finite(span.start)) return null;\n if (finite(span.end)) return Math.max(0, span.end - span.start);\n if (finite(span.duration)) return Math.max(0, span.duration);\n return null;\n}\n\nfunction mean(values: readonly number[]): number {\n return values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : 0;\n}\n\nfunction p95(values: readonly number[]): number | undefined {\n if (!values.length) return undefined;\n const sorted = [...values].sort((a, b) => a - b);\n return sorted[Math.max(0, Math.ceil(sorted.length * 0.95) - 1)];\n}\n\nfunction compare(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\ninterface NodeTally { requests: number; errors: number; durations: number[]; database: boolean; queue: boolean }\ninterface EdgeTally { calls: number; errors: number; durations: number[] }\n\nfunction isTraceList(input: readonly TraceSpanInput[] | readonly (readonly TraceSpanInput[])[]): input is readonly (readonly TraceSpanInput[])[] {\n return input.length > 0 && Array.isArray(input[0]);\n}\n\n/**\n * Fold spans into a service graph.\n *\n * Pass one flat list (spans from one or many traces, ids unique across them),\n * or a list of traces — each resolved on its own, so span ids may repeat from\n * one trace to the next.\n *\n * - A **node** per service. Its requests are the spans that *entered* it: a\n * root, or a span whose parent belongs to another service.\n * - An **edge** per parent service → child service crossing, counting the\n * child spans.\n * - **Kind**: a span carrying `db.system` makes its service a database; one\n * carrying `messaging.system`, or of kind `producer`/`consumer`, a queue.\n * A `client` span naming a `peer.service` that emitted no spans of its own\n * adds an `external` node, with an edge into it.\n */\nexport function serviceGraph(input: readonly TraceSpanInput[] | readonly (readonly TraceSpanInput[])[]): ServiceGraph {\n const traces: readonly (readonly TraceSpanInput[])[] = isTraceList(input) ? input : [input as readonly TraceSpanInput[]];\n const nodes = new Map<string, NodeTally>();\n const edges = new Map<string, EdgeTally & { from: string; to: string }>();\n const peers: Array<{ from: string; to: string; span: TraceSpanInput }> = [];\n\n const nodeOf = (id: string): NodeTally => {\n let tally = nodes.get(id);\n if (!tally) nodes.set(id, (tally = { requests: 0, errors: 0, durations: [], database: false, queue: false }));\n return tally;\n };\n const edgeOf = (from: string, to: string) => {\n const key = `${from}\\u0000${to}`;\n let tally = edges.get(key);\n if (!tally) edges.set(key, (tally = { from, to, calls: 0, errors: 0, durations: [] }));\n return tally;\n };\n\n for (const trace of traces) {\n const byId = new Map<string, TraceSpanInput>();\n for (const span of trace) if (span && typeof span.id === 'string' && finite(span.start) && !byId.has(span.id)) byId.set(span.id, span);\n for (const span of byId.values()) {\n const service = span.service || UNKNOWN_SERVICE;\n const node = nodeOf(service);\n const attributes = span.attributes ?? {};\n if (attributes['db.system'] !== undefined) node.database = true;\n if (attributes['messaging.system'] !== undefined || span.kind === 'producer' || span.kind === 'consumer') node.queue = true;\n\n const parent = span.parentId && span.parentId !== span.id ? byId.get(span.parentId) : undefined;\n const parentService = parent ? parent.service || UNKNOWN_SERVICE : null;\n const duration = spanDuration(span);\n const error = span.status === 'error';\n if (parentService !== service) {\n node.requests += 1;\n if (error) node.errors += 1;\n if (duration !== null) node.durations.push(duration);\n }\n if (parentService !== null && parentService !== service) {\n const edge = edgeOf(parentService, service);\n edge.calls += 1;\n if (error) edge.errors += 1;\n if (duration !== null) edge.durations.push(duration);\n }\n const peer = attributes['peer.service'];\n if (span.kind === 'client' && typeof peer === 'string' && peer && peer !== service) peers.push({ from: service, to: peer, span });\n }\n }\n\n // A peer that emitted spans of its own is already on the map, reached by\n // the parent → child crossing; only a silent one becomes an external node.\n const external = new Set<string>();\n for (const { from, to, span } of peers) {\n if (nodes.has(to) && !external.has(to)) continue;\n external.add(to);\n const node = nodeOf(to);\n const edge = edgeOf(from, to);\n const duration = spanDuration(span);\n const error = span.status === 'error';\n node.requests += 1;\n edge.calls += 1;\n if (error) { node.errors += 1; edge.errors += 1; }\n if (duration !== null) { node.durations.push(duration); edge.durations.push(duration); }\n }\n\n return {\n nodes: [...nodes.entries()]\n .sort(([a], [b]) => compare(a, b))\n .map(([id, tally]) => {\n const node: ServiceNode = {\n id,\n requests: tally.requests,\n errors: tally.errors,\n avgDuration: mean(tally.durations),\n kind: external.has(id) ? 'external' : tally.database ? 'database' : tally.queue ? 'queue' : 'service',\n };\n const percentile = p95(tally.durations);\n if (percentile !== undefined) node.p95Duration = percentile;\n return node;\n }),\n edges: [...edges.values()]\n .sort((a, b) => compare(a.from, b.from) || compare(a.to, b.to))\n .map(({ from, to, calls, errors, durations }) => ({ from, to, calls, errors, avgDuration: mean(durations) })),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Layout\n// ---------------------------------------------------------------------------\n\n/** A point in the layout's coordinate space. */\nexport interface ServiceGraphPoint { x: number; y: number }\n\n/** A node placed by `layoutServiceGraph`. `x`, `y` is its top-left corner. */\nexport interface ServiceGraphLayoutNode {\n id: string;\n x: number;\n y: number;\n /** Column, counted from the roots. */\n layer: number;\n /** Row within the layer, top first. */\n index: number;\n}\n\n/** An edge placed by `layoutServiceGraph`. */\nexport interface ServiceGraphLayoutEdge {\n from: string;\n to: string;\n /** Where the edge leaves its source. */\n source: ServiceGraphPoint;\n /** Where the edge meets its target (the arrow's tip). */\n target: ServiceGraphPoint;\n /**\n * The edge does not run left to right — it closes a cycle, or joins two\n * nodes in the same layer — so it leaves and enters from below.\n */\n back: boolean;\n /** For a back edge, the depth its loop's control points sit at — below every node. */\n dip?: number;\n}\n\n/** A laid-out service graph. */\nexport interface ServiceGraphLayout {\n /** In layer order, then top to bottom. */\n nodes: ServiceGraphLayoutNode[];\n /** In the graph's edge order; self-calls are dropped. */\n edges: ServiceGraphLayoutEdge[];\n /** Extent of the nodes, from 0, 0. Back-edge loops dip up to `rowGap` below it. */\n width: number;\n height: number;\n /** Node size used, so a renderer can draw what was placed. */\n nodeWidth: number;\n nodeHeight: number;\n /** How many layers. */\n layers: number;\n}\n\n/** Spacing for `layoutServiceGraph`, in layout units. */\nexport interface ServiceGraphLayoutOptions {\n /** Horizontal space between layers. Default 72. */\n columnGap?: number;\n /** Vertical space between nodes in a layer. Default 24. */\n rowGap?: number;\n /** Default 168. */\n nodeWidth?: number;\n /** Default 64. */\n nodeHeight?: number;\n}\n\nfunction positive(value: number | undefined, fallback: number): number {\n return finite(value) && value >= 0 ? value : fallback;\n}\n\n/**\n * Place a service graph in left-to-right layers.\n *\n * 1. Cycles are broken by removing the back edges a depth-first search finds\n * (roots first, then by name), so every edge left points forward.\n * 2. A node's layer is its longest path from a root.\n * 3. Within a layer, nodes start in name order and are reordered by two\n * down-and-up sweeps of barycentres (the mean row of their neighbours in\n * the layer before, then after), ties kept by current row and then name.\n *\n * Deterministic: the same graph always lands on the same coordinates. Edges\n * naming an unknown node are ignored.\n */\nexport function layoutServiceGraph(graph: ServiceGraph, options: ServiceGraphLayoutOptions = {}): ServiceGraphLayout {\n const columnGap = positive(options.columnGap, 72);\n const rowGap = positive(options.rowGap, 24);\n const nodeWidth = positive(options.nodeWidth, 168);\n const nodeHeight = positive(options.nodeHeight, 64);\n\n const ids = [...new Set(graph.nodes.map((node) => node.id))].sort(compare);\n const known = new Set(ids);\n const pairs = new Map<string, { from: string; to: string }>();\n for (const edge of graph.edges) {\n if (edge.from === edge.to || !known.has(edge.from) || !known.has(edge.to)) continue;\n pairs.set(`${edge.from}\\u0000${edge.to}`, { from: edge.from, to: edge.to });\n }\n const out = new Map<string, string[]>(ids.map((id) => [id, []]));\n const indegree = new Map<string, number>(ids.map((id) => [id, 0]));\n for (const { from, to } of pairs.values()) {\n out.get(from)!.push(to);\n indegree.set(to, indegree.get(to)! + 1);\n }\n for (const list of out.values()) list.sort(compare);\n\n // 1. Depth-first search; an edge into a node still on the stack closes a cycle.\n const reversed = new Set<string>();\n const state = new Map<string, 'open' | 'done'>();\n const visit = (id: string) => {\n state.set(id, 'open');\n for (const next of out.get(id)!) {\n const seen = state.get(next);\n if (seen === 'open') reversed.add(`${id}\\u0000${next}`);\n else if (!seen) visit(next);\n }\n state.set(id, 'done');\n };\n for (const id of ids) if (indegree.get(id) === 0 && !state.has(id)) visit(id);\n for (const id of ids) if (!state.has(id)) visit(id);\n\n const forward = [...pairs.entries()].filter(([key]) => !reversed.has(key)).map(([, pair]) => pair);\n const preds = new Map<string, string[]>(ids.map((id) => [id, []]));\n const succs = new Map<string, string[]>(ids.map((id) => [id, []]));\n for (const { from, to } of forward) {\n succs.get(from)!.push(to);\n preds.get(to)!.push(from);\n }\n\n // 2. Longest path from the roots, over a topological order (Kahn, by name).\n const layerOf = new Map<string, number>(ids.map((id) => [id, 0]));\n const remaining = new Map<string, number>(ids.map((id) => [id, preds.get(id)!.length]));\n const queue = ids.filter((id) => remaining.get(id) === 0);\n while (queue.length) {\n const id = queue.shift()!;\n for (const next of succs.get(id)!) {\n layerOf.set(next, Math.max(layerOf.get(next)!, layerOf.get(id)! + 1));\n remaining.set(next, remaining.get(next)! - 1);\n if (remaining.get(next) === 0) queue.push(next);\n }\n }\n const layerCount = ids.length ? Math.max(...layerOf.values()) + 1 : 0;\n const layers: string[][] = Array.from({ length: layerCount }, () => []);\n for (const id of ids) layers[layerOf.get(id)!]!.push(id);\n\n // 3. Barycentre sweeps.\n const row = new Map<string, number>();\n const index = () => { for (const layer of layers) layer.forEach((id, at) => row.set(id, at)); };\n index();\n const reorder = (layer: string[], neighbours: Map<string, string[]>) => {\n const keyed = layer.map((id) => {\n const list = neighbours.get(id)!;\n return { id, key: list.length ? mean(list.map((other) => row.get(other)!)) : row.get(id)!, at: row.get(id)! };\n });\n keyed.sort((a, b) => a.key - b.key || a.at - b.at || compare(a.id, b.id));\n layer.splice(0, layer.length, ...keyed.map((entry) => entry.id));\n layer.forEach((id, at) => row.set(id, at));\n };\n for (let sweep = 0; sweep < 2; sweep += 1) {\n for (let at = 1; at < layers.length; at += 1) reorder(layers[at]!, preds);\n for (let at = layers.length - 2; at >= 0; at -= 1) reorder(layers[at]!, succs);\n }\n\n // Coordinates: layers left to right, each centred on the tallest.\n const tallest = layers.reduce((max, layer) => Math.max(max, layer.length), 0);\n const pitch = nodeHeight + rowGap;\n const height = tallest ? tallest * nodeHeight + (tallest - 1) * rowGap : 0;\n const width = layerCount ? layerCount * nodeWidth + (layerCount - 1) * columnGap : 0;\n const nodes: ServiceGraphLayoutNode[] = [];\n const placed = new Map<string, ServiceGraphLayoutNode>();\n layers.forEach((layer, at) => {\n const offset = ((tallest - layer.length) * pitch) / 2;\n layer.forEach((id, position) => {\n const node = { id, x: at * (nodeWidth + columnGap), y: offset + position * pitch, layer: at, index: position };\n nodes.push(node);\n placed.set(id, node);\n });\n });\n\n const edges: ServiceGraphLayoutEdge[] = [...pairs.values()].map(({ from, to }) => {\n const a = placed.get(from)!;\n const b = placed.get(to)!;\n if (b.layer > a.layer) {\n return { from, to, back: false, source: { x: a.x + nodeWidth, y: a.y + nodeHeight / 2 }, target: { x: b.x, y: b.y + nodeHeight / 2 } };\n }\n return { from, to, back: true, dip: height + rowGap, source: { x: a.x + nodeWidth / 2, y: a.y + nodeHeight }, target: { x: b.x + nodeWidth / 2, y: b.y + nodeHeight } };\n });\n\n return { nodes, edges, width, height, nodeWidth, nodeHeight, layers: layerCount };\n}\n\nfunction dipOf(edge: ServiceGraphLayoutEdge): number {\n return edge.dip ?? Math.max(edge.source.y, edge.target.y) + 24;\n}\n\n/**\n * An SVG path for a laid-out edge: a horizontal S-curve for a forward edge,\n * a loop under the nodes for a back edge.\n */\nexport function serviceEdgePath(edge: ServiceGraphLayoutEdge): string {\n const { source: s, target: t } = edge;\n if (edge.back) {\n const dip = dipOf(edge);\n return `M ${s.x} ${s.y} C ${s.x} ${dip}, ${t.x} ${dip}, ${t.x} ${t.y}`;\n }\n const dx = (t.x - s.x) / 2;\n return `M ${s.x} ${s.y} C ${s.x + dx} ${s.y}, ${t.x - dx} ${t.y}, ${t.x} ${t.y}`;\n}\n\n/** The middle of the curve `serviceEdgePath` draws — where its label sits. */\nexport function serviceEdgeMidpoint(edge: ServiceGraphLayoutEdge): ServiceGraphPoint {\n const { source: s, target: t } = edge;\n if (edge.back) return { x: (s.x + t.x) / 2, y: (s.y + t.y) / 8 + (3 * dipOf(edge)) / 4 };\n return { x: (s.x + t.x) / 2, y: (s.y + t.y) / 2 };\n}\n\n/** `950`, `1.2k`, `34k`, `1.5M`. */\nexport function formatServiceCount(value: number): string {\n if (!finite(value)) return '—';\n const abs = Math.abs(value);\n const short = (n: number, unit: string) => `${n < 10 ? n.toFixed(1).replace(/\\.0$/, '') : Math.round(n)}${unit}`;\n if (abs < 1000) return String(Math.round(value));\n if (abs < 1_000_000) return short(value / 1000, 'k');\n return short(value / 1_000_000, 'M');\n}\n\n/** An error rate as a percentage: `0%`, `0.4%`, `2%`, `100%`. */\nexport function formatServiceErrorRate(errors: number, total: number): string {\n if (!finite(errors) || !finite(total) || total <= 0) return '0%';\n const percent = (errors / total) * 100;\n if (percent === 0) return '0%';\n if (percent < 1) return `${percent.toFixed(1)}%`;\n return `${Math.round(percent)}%`;\n}\n"],"mappings":";AAyDA,IAAM,kBAAkB;AAExB,SAAS,OAAO,OAAiC;AAC/C,SAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK;AAC3D;AAEA,SAAS,aAAa,MAAqC;AACzD,MAAI,CAAC,OAAO,KAAK,KAAK,EAAG,QAAO;AAChC,MAAI,OAAO,KAAK,GAAG,EAAG,QAAO,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,KAAK;AAC9D,MAAI,OAAO,KAAK,QAAQ,EAAG,QAAO,KAAK,IAAI,GAAG,KAAK,QAAQ;AAC3D,SAAO;AACT;AAEA,SAAS,KAAK,QAAmC;AAC/C,SAAO,OAAO,SAAS,OAAO,OAAO,CAAC,KAAK,UAAU,MAAM,OAAO,CAAC,IAAI,OAAO,SAAS;A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QAAO;AAC3B,QAAM,MAAM,KAAK,IAAI,KAAK;AAC1B,QAAM,QAAQ,CAAC,GAAW,SAAiB,GAAG,IAAI,KAAK,EAAE,QAAQ,CAAC,EAAE,QAAQ,QAAQ,EAAE,IAAI,KAAK,MAAM,CAAC,CAAC,GAAG,IAAI;AAC9G,MAAI,MAAM,IAAM,QAAO,OAAO,KAAK,MAAM,KAAK,CAAC;AAC/C,MAAI,MAAM,IAAW,QAAO,MAAM,QAAQ,KAAM,GAAG;AACnD,SAAO,MAAM,QAAQ,KAAW,GAAG;AACrC;AAGO,SAAS,uBAAuB,QAAgB,OAAuB;AAC5E,MAAI,CAAC,OAAO,MAAM,KAAK,CAAC,OAAO,KAAK,KAAK,SAAS,EAAG,QAAO;AAC5D,QAAM,UAAW,SAAS,QAAS;AACnC,MAAI,YAAY,EAAG,QAAO;AAC1B,MAAI,UAAU,EAAG,QAAO,GAAG,QAAQ,QAAQ,CAAC,CAAC;AAC7C,SAAO,GAAG,KAAK,MAAM,OAAO,CAAC;AAC/B;","names":[]}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// src/lib/severity.ts
|
|
2
|
+
var SEVERITY_ACCENTS = {
|
|
3
|
+
trace: "quiet",
|
|
4
|
+
debug: "quiet",
|
|
5
|
+
info: "info",
|
|
6
|
+
warn: "warning",
|
|
7
|
+
error: "danger",
|
|
8
|
+
fatal: "danger",
|
|
9
|
+
firing: "danger",
|
|
10
|
+
pending: "warning",
|
|
11
|
+
resolved: "success",
|
|
12
|
+
silenced: "quiet",
|
|
13
|
+
critical: "danger",
|
|
14
|
+
warning: "warning"
|
|
15
|
+
};
|
|
16
|
+
function severityAccent(severity) {
|
|
17
|
+
return SEVERITY_ACCENTS[severity] ?? "quiet";
|
|
18
|
+
}
|
|
19
|
+
export {
|
|
20
|
+
SEVERITY_ACCENTS,
|
|
21
|
+
severityAccent
|
|
22
|
+
};
|
|
23
|
+
//# sourceMappingURL=severity.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/lib/severity.ts"],"sourcesContent":["/**\n * The observability severity vocabulary — log levels, alert states and alert\n * severities — and the role each is drawn in. Kept beside `SeverityBadge`'s\n * module rather than in it so non-React callers (a chart legend, a CSV export)\n * can map a word to a role without importing a component.\n */\n\nimport type { AccentToken } from './theme';\n\n/** Log levels, OpenTelemetry's severity names in lower case. */\nexport type LogSeverity = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';\n/** Alert lifecycle states. */\nexport type AlertState = 'firing' | 'pending' | 'resolved' | 'silenced';\n/** Alert or incident severity. */\nexport type AlertSeverity = 'critical' | 'warning' | 'info';\n/** Every word `SeverityBadge` knows. */\nexport type Severity = LogSeverity | AlertState | AlertSeverity;\n\n/**\n * The fixed vocabulary, mapped to roles once so every log list, alert table\n * and incident view on a page says \"error\" in the same colour.\n */\nexport const SEVERITY_ACCENTS: Readonly<Record<Severity, AccentToken>> = {\n trace: 'quiet',\n debug: 'quiet',\n info: 'info',\n warn: 'warning',\n error: 'danger',\n fatal: 'danger',\n firing: 'danger',\n pending: 'warning',\n resolved: 'success',\n silenced: 'quiet',\n critical: 'danger',\n warning: 'warning',\n};\n\n/** The role a severity is drawn in. Unknown words fall back to `quiet`. */\nexport function severityAccent(severity: string): AccentToken {\n return SEVERITY_ACCENTS[severity as Severity] ?? 'quiet';\n}\n\n"],"mappings":";AAsBO,IAAM,mBAA4D;AAAA,EACvE,OAAO;AAAA,EACP,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,UAAU;AAAA,EACV,UAAU;AAAA,EACV,UAAU;AAAA,EACV,SAAS;AACX;AAGO,SAAS,eAAe,UAA+B;AAC5D,SAAO,iBAAiB,QAAoB,KAAK;AACnD;","names":[]}
|
package/dist/lib/theme.js
CHANGED
|
@@ -11,6 +11,16 @@ var INTENT_VARS = {
|
|
|
11
11
|
warning: "var(--ds-intent-warning)",
|
|
12
12
|
danger: "var(--ds-intent-danger)"
|
|
13
13
|
};
|
|
14
|
+
var DELTA_VARS = {
|
|
15
|
+
added: "var(--ds-delta-added)",
|
|
16
|
+
removed: "var(--ds-delta-removed)",
|
|
17
|
+
moved: "var(--ds-delta-moved)"
|
|
18
|
+
};
|
|
19
|
+
var DELTA_GROUND_VARS = {
|
|
20
|
+
added: "var(--ds-delta-ground-added)",
|
|
21
|
+
removed: "var(--ds-delta-ground-removed)",
|
|
22
|
+
hunk: "var(--ds-delta-ground-hunk)"
|
|
23
|
+
};
|
|
14
24
|
var SURFACE_VARS = {
|
|
15
25
|
base: "var(--ds-surface-base)",
|
|
16
26
|
raised: "var(--ds-surface-raised)",
|
|
@@ -58,6 +68,8 @@ var HEADING_EMPHASIS = {
|
|
|
58
68
|
var semanticTokens = {
|
|
59
69
|
accent: EMPHASIS_VARS,
|
|
60
70
|
intent: INTENT_VARS,
|
|
71
|
+
delta: DELTA_VARS,
|
|
72
|
+
deltaGround: DELTA_GROUND_VARS,
|
|
61
73
|
surface: SURFACE_VARS,
|
|
62
74
|
text: TEXT_VARS,
|
|
63
75
|
border: BORDER_VARS,
|
package/dist/lib/theme.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/lib/theme.ts"],"sourcesContent":["/**\n * Semantic theming layer.\n *\n * Components should describe *what a thing is* — a primary accent, a danger\n * state, a raised surface — never which colour it happens to be. The brutalist\n * palette (cyan/pink/yellow/green) is one mapping of those roles; `.dim` and\n * `.sketch` are others, and a future mode is a third. Referencing\n * `var(--brutalist-cyan)` directly hard-codes today's mapping into every\n * component and makes retheming a find-and-replace across the package.\n *\n * The CSS variables below are declared in `theme.css` and resolve through the\n * raw palette, so they follow every mode swap automatically.\n */\n\n/**\n * Visual weight within a hierarchy. Use for decorative and navigational\n * emphasis — which of several things should draw the eye first — not for\n * meaning. `quiet` is the de-emphasised step, not a fifth colour.\n */\nexport type Emphasis = 'primary' | 'secondary' | 'tertiary' | 'quiet';\n\n/**\n * Communicated meaning. Use when the colour carries information the reader\n * must act on; these survive retheming because their semantics are fixed even\n * when their hues are not.\n */\nexport type Intent = 'info' | 'success' | 'warning' | 'danger';\n\n/**\n * Background elevation. `base` is the page, `raised` sits above it (cards,\n * header, drawers), `sunken` is inset (code wells), `overlay` is modal.\n */\nexport type Surface = 'base' | 'raised' | 'sunken' | 'overlay';\n\n/** Text prominence, coarsest to faintest. */\nexport type TextTone = 'primary' | 'secondary' | 'muted' | 'inverse';\n\n/** Rule weight. `strong` is the full-contrast brutalist border. */\nexport type BorderTone = 'strong' | 'default' | 'subtle';\n\n/**\n * Palette names accepted by components predating the semantic layer.\n *\n * @deprecated Pass an {@link Emphasis} or {@link Intent} instead. These remain\n * accepted so existing consumers keep compiling, and they resolve to the same\n * values, but they defeat the point of the abstraction.\n */\n/**\n * A colour's *appearance*, independent of any job — the vocabulary a Target\n * addresses when it has no notion of jobs. A terminal has sixteen positions\n * named by colour and no concept of a keyword.\n *\n * Declared below the Role vocabulary and referenced by it, never the reverse:\n * Hue -> Role is a declared lookup, Role -> Hue is a guess. See\n * `docs/adr/0001-hues-declared-below-roles.md`.\n *\n * **A Hue in component code is a defect.** Components address Roles only.\n * Ten is the ceiling rather than a comfortable middle — the tightest pair\n * already sits at deltaE 0.049. See `docs/palette-provenance.md`.\n */\nexport type Hue =\n | 'red'\n | 'orange'\n | 'yellow'\n | 'green'\n | 'teal'\n | 'cyan'\n | 'blue'\n | 'violet'\n | 'magenta'\n | 'pink';\n\n/**\n * The eight ANSI base slots a terminal needs, beyond which `bright` variants\n * fill the upper eight. `black` and `white` come from `FIXED_COLOURS`.\n */\nexport type AnsiHue = Extract<Hue, 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan'>;\n\n/**\n * What a Role points at in the Hue vocabulary.\n *\n * `'neutral'` is not a cop-out: some Roles genuinely are not hues.\n * `accent.quiet` is a warm or cool grey by design, and the palette has no\n * neutral ramp to point it at. Saying so explicitly keeps the map exhaustive —\n * a new Emphasis is still a compile error — while letting the gate distinguish\n * \"declared as not-a-hue\" from \"forgot to wire it up\", which a `Partial` could\n * not.\n */\nexport type HueRef = Hue | 'neutral';\n\n\n/** Anything a component's `accent`-style prop will take. */\nexport type AccentToken = Emphasis | Intent;\n\nconst EMPHASIS_VARS: Record<Emphasis, string> = {\n primary: 'var(--ds-accent-primary)',\n secondary: 'var(--ds-accent-secondary)',\n tertiary: 'var(--ds-accent-tertiary)',\n quiet: 'var(--ds-accent-quiet)',\n};\n\nconst INTENT_VARS: Record<Intent, string> = {\n info: 'var(--ds-intent-info)',\n success: 'var(--ds-intent-success)',\n warning: 'var(--ds-intent-warning)',\n danger: 'var(--ds-intent-danger)',\n};\n\nconst SURFACE_VARS: Record<Surface, string> = {\n base: 'var(--ds-surface-base)',\n raised: 'var(--ds-surface-raised)',\n sunken: 'var(--ds-surface-sunken)',\n overlay: 'var(--ds-surface-overlay)',\n};\n\nconst TEXT_VARS: Record<TextTone, string> = {\n primary: 'var(--ds-text-primary)',\n secondary: 'var(--ds-text-secondary)',\n muted: 'var(--ds-text-muted)',\n inverse: 'var(--ds-text-inverse)',\n};\n\nconst BORDER_VARS: Record<BorderTone, string> = {\n strong: 'var(--ds-border-strong)',\n default: 'var(--ds-border-default)',\n subtle: 'var(--ds-border-subtle)',\n};\n\n/**\n * Resolve any accent token to the CSS variable expression that renders it.\n *\n * Unknown values fall back to the primary accent rather than throwing —\n * a mistyped prop should degrade to something legible, not blank out a\n * component's colour and leave `color: undefined` on the element.\n */\nexport function accentVar(token: AccentToken | undefined, fallback: AccentToken = 'primary'): string {\n const resolved = token ?? fallback;\n return (\n EMPHASIS_VARS[resolved as Emphasis] ??\n INTENT_VARS[resolved as Intent] ??\n EMPHASIS_VARS.primary\n );\n}\n\nexport function surfaceVar(token: Surface = 'base'): string {\n return SURFACE_VARS[token] ?? SURFACE_VARS.base;\n}\n\nexport function textVar(token: TextTone = 'primary'): string {\n return TEXT_VARS[token] ?? TEXT_VARS.primary;\n}\n\nexport function borderVar(token: BorderTone = 'strong'): string {\n return BORDER_VARS[token] ?? BORDER_VARS.strong;\n}\n\n/** Semantic font roles. */\nexport const fontVar = {\n display: 'var(--ds-font-display)',\n body: 'var(--ds-font-body)',\n mono: 'var(--ds-font-mono)',\n pixel: 'var(--ds-font-pixel)',\n} as const;\n\n/**\n * Default emphasis per heading level, so a document's colour hierarchy follows\n * its structural hierarchy without every call site restating it.\n */\nexport const HEADING_EMPHASIS: Record<1 | 2 | 3 | 4 | 5 | 6, Emphasis> = {\n 1: 'primary',\n 2: 'primary',\n 3: 'secondary',\n 4: 'tertiary',\n 5: 'quiet',\n 6: 'quiet',\n};\n\n/**\n * The full semantic token surface, as CSS variable expressions. Useful for\n * inline styles and for consumers building their own components on the system.\n */\nexport const semanticTokens = {\n accent: EMPHASIS_VARS,\n intent: INTENT_VARS,\n surface: SURFACE_VARS,\n text: TEXT_VARS,\n border: BORDER_VARS,\n font: fontVar,\n shadowColor: 'var(--ds-shadow-color)',\n} as const;\n"],"mappings":";
|
|
1
|
+
{"version":3,"sources":["../../src/lib/theme.ts"],"sourcesContent":["/**\n * Semantic theming layer.\n *\n * Components should describe *what a thing is* — a primary accent, a danger\n * state, a raised surface — never which colour it happens to be. The brutalist\n * palette (cyan/pink/yellow/green) is one mapping of those roles; `.dim` and\n * `.sketch` are others, and a future mode is a third. Referencing\n * `var(--brutalist-cyan)` directly hard-codes today's mapping into every\n * component and makes retheming a find-and-replace across the package.\n *\n * The CSS variables below are declared in `theme.css` and resolve through the\n * raw palette, so they follow every mode swap automatically.\n */\n\n/**\n * Visual weight within a hierarchy. Use for decorative and navigational\n * emphasis — which of several things should draw the eye first — not for\n * meaning. `quiet` is the de-emphasised step, not a fifth colour.\n */\nexport type Emphasis = 'primary' | 'secondary' | 'tertiary' | 'quiet';\n\n/**\n * Communicated meaning. Use when the colour carries information the reader\n * must act on; these survive retheming because their semantics are fixed even\n * when their hues are not.\n */\nexport type Intent = 'info' | 'success' | 'warning' | 'danger';\n\n/**\n * Change, as a comparison reports it. Use for diff signs, change counts and\n * change bars — never for whether the change is acceptable, which is an\n * {@link Intent}. Red text on a removed line says *removed*, not *wrong*.\n */\nexport type Delta = 'added' | 'removed' | 'moved';\n\n/** The grounds a diff paints behind its rows. `hunk` sits behind a hunk header. */\nexport type DeltaGround = 'added' | 'removed' | 'hunk';\n\n/**\n * Background elevation. `base` is the page, `raised` sits above it (cards,\n * header, drawers), `sunken` is inset (code wells), `overlay` is modal.\n */\nexport type Surface = 'base' | 'raised' | 'sunken' | 'overlay';\n\n/** Text prominence, coarsest to faintest. */\nexport type TextTone = 'primary' | 'secondary' | 'muted' | 'inverse';\n\n/** Rule weight. `strong` is the full-contrast brutalist border. */\nexport type BorderTone = 'strong' | 'default' | 'subtle';\n\n/**\n * Palette names accepted by components predating the semantic layer.\n *\n * @deprecated Pass an {@link Emphasis} or {@link Intent} instead. These remain\n * accepted so existing consumers keep compiling, and they resolve to the same\n * values, but they defeat the point of the abstraction.\n */\n/**\n * A colour's *appearance*, independent of any job — the vocabulary a Target\n * addresses when it has no notion of jobs. A terminal has sixteen positions\n * named by colour and no concept of a keyword.\n *\n * Declared below the Role vocabulary and referenced by it, never the reverse:\n * Hue -> Role is a declared lookup, Role -> Hue is a guess. See\n * `docs/adr/0001-hues-declared-below-roles.md`.\n *\n * **A Hue in component code is a defect.** Components address Roles only.\n * Ten is the ceiling rather than a comfortable middle — the tightest pair\n * already sits at deltaE 0.049. See `docs/palette-provenance.md`.\n */\nexport type Hue =\n | 'red'\n | 'orange'\n | 'yellow'\n | 'green'\n | 'teal'\n | 'cyan'\n | 'blue'\n | 'violet'\n | 'magenta'\n | 'pink';\n\n/**\n * The eight ANSI base slots a terminal needs, beyond which `bright` variants\n * fill the upper eight. `black` and `white` come from `FIXED_COLOURS`.\n */\nexport type AnsiHue = Extract<Hue, 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan'>;\n\n/**\n * What a Role points at in the Hue vocabulary.\n *\n * `'neutral'` is not a cop-out: some Roles genuinely are not hues.\n * `accent.quiet` is a warm or cool grey by design, and the palette has no\n * neutral ramp to point it at. Saying so explicitly keeps the map exhaustive —\n * a new Emphasis is still a compile error — while letting the gate distinguish\n * \"declared as not-a-hue\" from \"forgot to wire it up\", which a `Partial` could\n * not.\n */\nexport type HueRef = Hue | 'neutral';\n\n\n/** Anything a component's `accent`-style prop will take. */\nexport type AccentToken = Emphasis | Intent;\n\nconst EMPHASIS_VARS: Record<Emphasis, string> = {\n primary: 'var(--ds-accent-primary)',\n secondary: 'var(--ds-accent-secondary)',\n tertiary: 'var(--ds-accent-tertiary)',\n quiet: 'var(--ds-accent-quiet)',\n};\n\nconst INTENT_VARS: Record<Intent, string> = {\n info: 'var(--ds-intent-info)',\n success: 'var(--ds-intent-success)',\n warning: 'var(--ds-intent-warning)',\n danger: 'var(--ds-intent-danger)',\n};\n\nconst DELTA_VARS: Record<Delta, string> = {\n added: 'var(--ds-delta-added)',\n removed: 'var(--ds-delta-removed)',\n moved: 'var(--ds-delta-moved)',\n};\n\nconst DELTA_GROUND_VARS: Record<DeltaGround, string> = {\n added: 'var(--ds-delta-ground-added)',\n removed: 'var(--ds-delta-ground-removed)',\n hunk: 'var(--ds-delta-ground-hunk)',\n};\n\nconst SURFACE_VARS: Record<Surface, string> = {\n base: 'var(--ds-surface-base)',\n raised: 'var(--ds-surface-raised)',\n sunken: 'var(--ds-surface-sunken)',\n overlay: 'var(--ds-surface-overlay)',\n};\n\nconst TEXT_VARS: Record<TextTone, string> = {\n primary: 'var(--ds-text-primary)',\n secondary: 'var(--ds-text-secondary)',\n muted: 'var(--ds-text-muted)',\n inverse: 'var(--ds-text-inverse)',\n};\n\nconst BORDER_VARS: Record<BorderTone, string> = {\n strong: 'var(--ds-border-strong)',\n default: 'var(--ds-border-default)',\n subtle: 'var(--ds-border-subtle)',\n};\n\n/**\n * Resolve any accent token to the CSS variable expression that renders it.\n *\n * Unknown values fall back to the primary accent rather than throwing —\n * a mistyped prop should degrade to something legible, not blank out a\n * component's colour and leave `color: undefined` on the element.\n */\nexport function accentVar(token: AccentToken | undefined, fallback: AccentToken = 'primary'): string {\n const resolved = token ?? fallback;\n return (\n EMPHASIS_VARS[resolved as Emphasis] ??\n INTENT_VARS[resolved as Intent] ??\n EMPHASIS_VARS.primary\n );\n}\n\nexport function surfaceVar(token: Surface = 'base'): string {\n return SURFACE_VARS[token] ?? SURFACE_VARS.base;\n}\n\nexport function textVar(token: TextTone = 'primary'): string {\n return TEXT_VARS[token] ?? TEXT_VARS.primary;\n}\n\nexport function borderVar(token: BorderTone = 'strong'): string {\n return BORDER_VARS[token] ?? BORDER_VARS.strong;\n}\n\n/** Semantic font roles. */\nexport const fontVar = {\n display: 'var(--ds-font-display)',\n body: 'var(--ds-font-body)',\n mono: 'var(--ds-font-mono)',\n pixel: 'var(--ds-font-pixel)',\n} as const;\n\n/**\n * Default emphasis per heading level, so a document's colour hierarchy follows\n * its structural hierarchy without every call site restating it.\n */\nexport const HEADING_EMPHASIS: Record<1 | 2 | 3 | 4 | 5 | 6, Emphasis> = {\n 1: 'primary',\n 2: 'primary',\n 3: 'secondary',\n 4: 'tertiary',\n 5: 'quiet',\n 6: 'quiet',\n};\n\n/**\n * The full semantic token surface, as CSS variable expressions. Useful for\n * inline styles and for consumers building their own components on the system.\n */\nexport const semanticTokens = {\n accent: EMPHASIS_VARS,\n intent: INTENT_VARS,\n delta: DELTA_VARS,\n deltaGround: DELTA_GROUND_VARS,\n surface: SURFACE_VARS,\n text: TEXT_VARS,\n border: BORDER_VARS,\n font: fontVar,\n shadowColor: 'var(--ds-shadow-color)',\n} as const;\n"],"mappings":";AAwGA,IAAM,gBAA0C;AAAA,EAC9C,SAAS;AAAA,EACT,WAAW;AAAA,EACX,UAAU;AAAA,EACV,OAAO;AACT;AAEA,IAAM,cAAsC;AAAA,EAC1C,MAAM;AAAA,EACN,SAAS;AAAA,EACT,SAA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,94 @@
|
|
|
1
|
+
// src/lib/timeRange.ts
|
|
2
|
+
var MINUTE = 6e4;
|
|
3
|
+
var HOUR = 60 * MINUTE;
|
|
4
|
+
var DAY = 24 * HOUR;
|
|
5
|
+
var TIME_RANGE_PRESETS = [
|
|
6
|
+
{ id: "15m", label: "15m", duration: 15 * MINUTE },
|
|
7
|
+
{ id: "1h", label: "1h", duration: HOUR },
|
|
8
|
+
{ id: "6h", label: "6h", duration: 6 * HOUR },
|
|
9
|
+
{ id: "24h", label: "24h", duration: DAY },
|
|
10
|
+
{ id: "7d", label: "7d", duration: 7 * DAY }
|
|
11
|
+
];
|
|
12
|
+
function presetRange(preset, now) {
|
|
13
|
+
return { from: now - preset.duration, to: now };
|
|
14
|
+
}
|
|
15
|
+
function normaliseRange(range) {
|
|
16
|
+
if (!range || !Number.isFinite(range.from) || !Number.isFinite(range.to)) return null;
|
|
17
|
+
return range.from <= range.to ? { from: range.from, to: range.to } : { from: range.to, to: range.from };
|
|
18
|
+
}
|
|
19
|
+
function clampToRange(time, range) {
|
|
20
|
+
return Math.max(range.from, Math.min(range.to, time));
|
|
21
|
+
}
|
|
22
|
+
var pad = (value) => String(value).padStart(2, "0");
|
|
23
|
+
var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
|
24
|
+
function formatClock(time, seconds = false) {
|
|
25
|
+
const date = new Date(time);
|
|
26
|
+
const base = `${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}`;
|
|
27
|
+
return seconds ? `${base}:${pad(date.getUTCSeconds())}` : base;
|
|
28
|
+
}
|
|
29
|
+
function formatDay(time) {
|
|
30
|
+
const date = new Date(time);
|
|
31
|
+
return `${MONTHS[date.getUTCMonth()]} ${date.getUTCDate()}`;
|
|
32
|
+
}
|
|
33
|
+
function formatTimestamp(time, precision = "second") {
|
|
34
|
+
const date = new Date(time);
|
|
35
|
+
const clock = formatClock(time, precision !== "minute");
|
|
36
|
+
const millis = precision === "millisecond" ? `.${String(date.getUTCMilliseconds()).padStart(3, "0")}` : "";
|
|
37
|
+
return `${formatDay(time)} ${clock}${millis}`;
|
|
38
|
+
}
|
|
39
|
+
function formatTimeTick(time, span) {
|
|
40
|
+
if (span > 2 * DAY) return formatDay(time);
|
|
41
|
+
if (span <= 2 * MINUTE) return formatClock(time, true);
|
|
42
|
+
return formatClock(time);
|
|
43
|
+
}
|
|
44
|
+
function formatRangeDuration(ms) {
|
|
45
|
+
if (!Number.isFinite(ms) || ms <= 0) return "0m";
|
|
46
|
+
const units = [["d", DAY], ["h", HOUR], ["m", MINUTE], ["s", 1e3]];
|
|
47
|
+
const parts = [];
|
|
48
|
+
let rest = ms;
|
|
49
|
+
for (const [unit, size] of units) {
|
|
50
|
+
const count = Math.floor(rest / size);
|
|
51
|
+
if (count) {
|
|
52
|
+
parts.push(`${count}${unit}`);
|
|
53
|
+
rest -= count * size;
|
|
54
|
+
}
|
|
55
|
+
if (parts.length === 2) break;
|
|
56
|
+
}
|
|
57
|
+
return parts.join(" ") || `${Math.round(ms)}ms`;
|
|
58
|
+
}
|
|
59
|
+
function formatRange(range) {
|
|
60
|
+
const span = range.to - range.from;
|
|
61
|
+
const sameDay = formatDay(range.from) === formatDay(range.to);
|
|
62
|
+
if (span > 2 * DAY || !sameDay) return `${formatDay(range.from)} ${formatClock(range.from)} \u2013 ${formatDay(range.to)} ${formatClock(range.to)}`;
|
|
63
|
+
return `${formatClock(range.from)} \u2013 ${formatClock(range.to)}`;
|
|
64
|
+
}
|
|
65
|
+
var STEPS = [1e3, 5e3, 15e3, 3e4, MINUTE, 5 * MINUTE, 15 * MINUTE, 30 * MINUTE, HOUR, 3 * HOUR, 6 * HOUR, 12 * HOUR, DAY, 2 * DAY, 7 * DAY];
|
|
66
|
+
function timeTicks(range, target = 5) {
|
|
67
|
+
const span = range.to - range.from;
|
|
68
|
+
if (!Number.isFinite(span) || span <= 0) return [range.from];
|
|
69
|
+
const raw = span / Math.max(1, target);
|
|
70
|
+
const step = STEPS.find((candidate) => candidate >= raw) ?? Math.ceil(raw / DAY) * DAY;
|
|
71
|
+
const ticks = [];
|
|
72
|
+
for (let tick = Math.ceil(range.from / step) * step; tick <= range.to; tick += step) ticks.push(tick);
|
|
73
|
+
return ticks;
|
|
74
|
+
}
|
|
75
|
+
function bucketTimes(range, count) {
|
|
76
|
+
const n = Math.max(1, Math.floor(count));
|
|
77
|
+
const width = (range.to - range.from) / n;
|
|
78
|
+
return Array.from({ length: n }, (_, index) => ({ from: range.from + index * width, to: index === n - 1 ? range.to : range.from + (index + 1) * width }));
|
|
79
|
+
}
|
|
80
|
+
export {
|
|
81
|
+
TIME_RANGE_PRESETS,
|
|
82
|
+
bucketTimes,
|
|
83
|
+
clampToRange,
|
|
84
|
+
formatClock,
|
|
85
|
+
formatDay,
|
|
86
|
+
formatRange,
|
|
87
|
+
formatRangeDuration,
|
|
88
|
+
formatTimeTick,
|
|
89
|
+
formatTimestamp,
|
|
90
|
+
normaliseRange,
|
|
91
|
+
presetRange,
|
|
92
|
+
timeTicks
|
|
93
|
+
};
|
|
94
|
+
//# sourceMappingURL=timeRange.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/lib/timeRange.ts"],"sourcesContent":["/**\n * Time ranges for observability views: the window every chart, log list and\n * heatmap on a page shares, the presets a picker offers, and axis ticks that\n * land on round clock times.\n *\n * ## Time is epoch milliseconds, and `now` is always passed in\n *\n * Nothing here reads the clock. A page hands its `now` to `TimeRangeProvider`\n * — `Date.now()` in an app, a fixed epoch in a story or a static export — so a\n * render is a pure function of its inputs and a server render hydrates.\n *\n * ## Labels are UTC, formatted by hand\n *\n * `toLocaleString` differs between the server and the browser and between\n * machines, which is a hydration mismatch and an unstable screenshot. The\n * formatters below write UTC digits themselves.\n */\n\n/** A closed window of time, in epoch milliseconds. */\nexport interface TimeRange {\n from: number;\n to: number;\n}\n\n/** A named relative window — \"the last hour\". */\nexport interface TimeRangePreset {\n id: string;\n label: string;\n /** Width of the window in milliseconds, ending at `now`. */\n duration: number;\n}\n\nconst MINUTE = 60_000;\nconst HOUR = 60 * MINUTE;\nconst DAY = 24 * HOUR;\n\n/** The windows a picker offers by default. */\nexport const TIME_RANGE_PRESETS: readonly TimeRangePreset[] = [\n { id: '15m', label: '15m', duration: 15 * MINUTE },\n { id: '1h', label: '1h', duration: HOUR },\n { id: '6h', label: '6h', duration: 6 * HOUR },\n { id: '24h', label: '24h', duration: DAY },\n { id: '7d', label: '7d', duration: 7 * DAY },\n];\n\n/** The window a preset names, ending at `now`. */\nexport function presetRange(preset: TimeRangePreset, now: number): TimeRange {\n return { from: now - preset.duration, to: now };\n}\n\n/** A range with `from <= to`, both finite; null when that cannot be made. */\nexport function normaliseRange(range: TimeRange | null | undefined): TimeRange | null {\n if (!range || !Number.isFinite(range.from) || !Number.isFinite(range.to)) return null;\n return range.from <= range.to ? { from: range.from, to: range.to } : { from: range.to, to: range.from };\n}\n\n/** Clamp `time` into `range`. */\nexport function clampToRange(time: number, range: TimeRange): number {\n return Math.max(range.from, Math.min(range.to, time));\n}\n\nconst pad = (value: number) => String(value).padStart(2, '0');\nconst MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n\n/** `14:05`, `14:05:30` with seconds, in UTC. */\nexport function formatClock(time: number, seconds = false): string {\n const date = new Date(time);\n const base = `${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}`;\n return seconds ? `${base}:${pad(date.getUTCSeconds())}` : base;\n}\n\n/** `Oct 22`, in UTC. */\nexport function formatDay(time: number): string {\n const date = new Date(time);\n return `${MONTHS[date.getUTCMonth()]} ${date.getUTCDate()}`;\n}\n\n/** `Oct 22 14:05:30.120 UTC`-style stamp for a log line or a tooltip, without the zone. */\nexport function formatTimestamp(time: number, precision: 'minute' | 'second' | 'millisecond' = 'second'): string {\n const date = new Date(time);\n const clock = formatClock(time, precision !== 'minute');\n const millis = precision === 'millisecond' ? `.${String(date.getUTCMilliseconds()).padStart(3, '0')}` : '';\n return `${formatDay(time)} ${clock}${millis}`;\n}\n\n/** A tick label sized to the window: seconds for short ranges, days for long ones. */\nexport function formatTimeTick(time: number, span: number): string {\n if (span > 2 * DAY) return formatDay(time);\n if (span <= 2 * MINUTE) return formatClock(time, true);\n return formatClock(time);\n}\n\n/** `15m`, `1h 30m`, `2d`: a window's width, rounded to its two largest units. */\nexport function formatRangeDuration(ms: number): string {\n if (!Number.isFinite(ms) || ms <= 0) return '0m';\n const units: Array<[string, number]> = [['d', DAY], ['h', HOUR], ['m', MINUTE], ['s', 1000]];\n const parts: string[] = [];\n let rest = ms;\n for (const [unit, size] of units) {\n const count = Math.floor(rest / size);\n if (count) { parts.push(`${count}${unit}`); rest -= count * size; }\n if (parts.length === 2) break;\n }\n return parts.join(' ') || `${Math.round(ms)}ms`;\n}\n\n/** `14:00 – 15:00`, or with days when the window crosses one. */\nexport function formatRange(range: TimeRange): string {\n const span = range.to - range.from;\n const sameDay = formatDay(range.from) === formatDay(range.to);\n if (span > 2 * DAY || !sameDay) return `${formatDay(range.from)} ${formatClock(range.from)} – ${formatDay(range.to)} ${formatClock(range.to)}`;\n return `${formatClock(range.from)} – ${formatClock(range.to)}`;\n}\n\nconst STEPS = [1000, 5000, 15_000, 30_000, MINUTE, 5 * MINUTE, 15 * MINUTE, 30 * MINUTE, HOUR, 3 * HOUR, 6 * HOUR, 12 * HOUR, DAY, 2 * DAY, 7 * DAY];\n\n/**\n * Ticks on round clock times inside `range` — every 5 minutes, every hour —\n * about `target` of them. UTC-aligned, so the same range always ticks alike.\n */\nexport function timeTicks(range: TimeRange, target = 5): number[] {\n const span = range.to - range.from;\n if (!Number.isFinite(span) || span <= 0) return [range.from];\n const raw = span / Math.max(1, target);\n const step = STEPS.find((candidate) => candidate >= raw) ?? Math.ceil(raw / DAY) * DAY;\n const ticks: number[] = [];\n for (let tick = Math.ceil(range.from / step) * step; tick <= range.to; tick += step) ticks.push(tick);\n return ticks;\n}\n\n/**\n * Group timestamps into `count` equal buckets across `range` — the shape a\n * histogram over time, a heatmap column or a log-volume strip needs.\n */\nexport function bucketTimes(range: TimeRange, count: number): TimeRange[] {\n const n = Math.max(1, Math.floor(count));\n const width = (range.to - range.from) / n;\n return Array.from({ length: n }, (_, index) => ({ from: range.from + index * width, to: index === n - 1 ? range.to : range.from + (index + 1) * width }));\n}\n"],"mappings":";AAgCA,IAAM,SAAS;AACf,IAAM,OAAO,KAAK;AAClB,IAAM,MAAM,KAAK;AAGV,IAAM,qBAAiD;AAAA,EAC5D,EAAE,IAAI,OAAO,OAAO,OAAO,UAAU,KAAK,OAAO;AAAA,EACjD,EAAE,IAAI,MAAM,OAAO,MAAM,UAAU,KAAK;AAAA,EACxC,EAAE,IAAI,MAAM,OAAO,MAAM,UAAU,IAAI,KAAK;AAAA,EAC5C,EAAE,IAAI,OAAO,OAAO,OAAO,UAAU,IAAI;AAAA,EACzC,EAAE,IAAI,MAAM,OAAO,MAAM,UAAU,IAAI,IAAI;AAC7C;AAGO,SAAS,YAAY,QAAyB,KAAwB;AAC3E,SAAO,EAAE,MAAM,MAAM,OAAO,UAAU,IAAI,IAAI;AAChD;AAGO,SAAS,eAAe,OAAuD;AACpF,MAAI,CAAC,SAAS,CAAC,OAAO,SAAS,MAAM,IAAI,KAAK,CAAC,OAAO,SAAS,MAAM,EAAE,EAAG,QAAO;AACjF,SAAO,MAAM,QAAQ,MAAM,KAAK,EAAE,MAAM,MAAM,MAAM,IAAI,MAAM,GAAG,IAAI,EAAE,MAAM,MAAM,IAAI,IAAI,MAAM,KAAK;AACxG;AAGO,SAAS,aAAa,MAAc,OAA0B;AACnE,SAAO,KAAK,IAAI,MAAM,MAAM,KAAK,IAAI,MAAM,IAAI,IAAI,CAAC;AACtD;AAEA,IAAM,MAAM,CAAC,UAAkB,OAAO,KAAK,EAAE,SAAS,GAAG,GAAG;AAC5D,IAAM,SAAS,CAAC,OAA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