hookdesk 0.1.0 → 0.2.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/src/ui/ui.js ADDED
@@ -0,0 +1,419 @@
1
+ const $ = id => document.getElementById(id);
2
+ // Every setting, route, and text comes from the config route (config/default.json, app.json, limits.json, messages.json).
3
+ const state = { config: null, events: [], mocks: [], mocksKey: '', selected: null, detail: null, listKey: '', online: true, seen: null, tab: null, flashes: new Map(), hover: null };
4
+ const ui = () => state.config.ui;
5
+ const t = () => state.config.messages;
6
+ const routes = () => state.config.routes;
7
+ const format = (template, values = {}) => template.replace(/\{(\w+)\}/g, (match, key) => key in values ? String(values[key]) : match);
8
+ const route = (name, id) => format(routes()[name], { id: encodeURIComponent(id) });
9
+ const node = (tag, text, cls) => { const el = document.createElement(tag); if (text !== undefined) el.textContent = text; if (cls) el.className = cls; return el; };
10
+ let toastTimer;
11
+ const showToast = message => { const el = $('toast'); el.textContent = message; el.classList.add('show'); clearTimeout(toastTimer); toastTimer = setTimeout(() => el.classList.remove('show'), ui().toastMs); };
12
+ const quote = s => "'" + String(s).replaceAll("'", "'\\''") + "'";
13
+ const copyText = (text, message) => navigator.clipboard.writeText(text).then(() => showToast(message)).catch(() => showToast(t().clipboardUnavailable));
14
+ async function getJson(path, options) {
15
+ const response = await fetch(path, { cache: 'no-store', ...options });
16
+ const data = await response.json().catch(() => ({}));
17
+ if (!response.ok) throw new Error(data.error || format(t().httpStatus, { status: response.status }));
18
+ return data;
19
+ }
20
+ const sendJson = (path, method, value) => getJson(path, { method, headers: { [state.config.headers.contentType]: state.config.contentTypes.json }, body: JSON.stringify(value) });
21
+
22
+ // Unit conversions (1024 bytes per KB, 60 seconds per minute) are arithmetic, not settings.
23
+ const bytesParts = n => n < 1024 ? [String(n), n === 1 ? t().byte : t().bytes] : n < 1048576 ? [(n / 1024).toFixed(1), t().kilobytes] : [(n / 1048576).toFixed(1), t().megabytes];
24
+ const fmtBytes = n => bytesParts(n).join(' ');
25
+ const exactBytes = n => format(t().exactBytes, { count: n.toLocaleString() });
26
+ const fmtAge = time => { const s = Math.max(0, Math.round((Date.now() - time) / 1000)); return s < 60 ? format(t().seconds, { value: s }) : s < 3600 ? format(t().minutes, { value: Math.floor(s / 60) }) : format(t().hours, { value: Math.floor(s / 3600) }); };
27
+ const fmtSpan = ms => ms >= 3600000 ? format(t().hours, { value: +(ms / 3600000).toFixed(1) }) : ms >= 60000 ? format(t().minutes, { value: +(ms / 60000).toFixed(1) }) : format(t().seconds, { value: Math.round(ms / 1000) });
28
+ const OTHER = 'other';
29
+ const methodKey = m => ui().methods.includes(m) ? m.toLowerCase() : OTHER;
30
+ const methodClass = m => `m m-${methodKey(m)}`;
31
+ const statusClass = s => s >= ui().errorStatusFrom ? 'num status-error' : 'num';
32
+
33
+ function setOnline(online) {
34
+ if (online === state.online) return;
35
+ state.online = online;
36
+ $('live-label').textContent = online ? t().live : t().offline;
37
+ $('live').classList.toggle('offline', !online);
38
+ showToast(online ? t().reconnected : t().unreachable);
39
+ }
40
+
41
+ // The number is shown large and the unit small, so values like "119 bytes" fit the stat box.
42
+ function setStat(id, value, unit = '', bump = true) {
43
+ const el = $(id); const text = `${value} ${unit}`;
44
+ if (el.dataset.v === text) return;
45
+ el.dataset.v = text;
46
+ el.replaceChildren(value);
47
+ if (unit) el.append(node('span', unit, 'unit'));
48
+ if (bump) { el.classList.remove('bump'); void el.offsetWidth; el.classList.add('bump'); }
49
+ }
50
+ function renderStats() {
51
+ const now = Date.now();
52
+ setStat('count', String(state.events.length));
53
+ setStat('rate', String(state.events.filter(e => now - e.t < ui().rateWindowMs).length));
54
+ if (state.events.length) setStat('last', fmtAge(state.events[0].t), t().ago, false); else setStat('last', t().none, '', false);
55
+ const total = state.events.reduce((sum, e) => sum + e.bytes, 0);
56
+ setStat('bytes', ...bytesParts(total)); $('bytes').title = exactBytes(total);
57
+ }
58
+ const tickAges = () => { document.querySelectorAll('[data-t]').forEach(el => { el.textContent = fmtAge(Number(el.dataset.t)); }); renderStats(); };
59
+
60
+ const currentListKey = () => `${state.selected}|${state.events.map(x => x.id).join(',')}`;
61
+ function renderList() {
62
+ state.listKey = currentListKey();
63
+ const list = $('entries'); list.replaceChildren();
64
+ if (!state.events.length) list.append(node('div', t().noRequests, 'empty'));
65
+ // Only requests that arrived after the first render flash in the list and on the timeline.
66
+ const firstRender = state.seen === null; state.seen ??= new Set();
67
+ for (const event of state.events) {
68
+ const isNew = !firstRender && !state.seen.has(event.id);
69
+ if (isNew) state.flashes.set(event.id, performance.now());
70
+ state.seen.add(event.id);
71
+ const row = node('button', undefined, ['row', event.id === state.selected && 'selected', isNew && 'is-new'].filter(Boolean).join(' '));
72
+ const path = node('span', event.path, 'path');
73
+ if (event.replayOf) path.append(node('span', t().replayMark, 'replay-mark'));
74
+ if (event.mockId) path.append(node('span', t().mockMark, 'mock-mark'));
75
+ const age = node('span', fmtAge(event.t), 'num'); age.dataset.t = String(event.t);
76
+ const size = node('span', fmtBytes(event.bytes), 'num'); size.title = exactBytes(event.bytes);
77
+ row.append(node('span', event.method, methodClass(event.method)), path, node('span', String(event.status), statusClass(event.status)), size, age);
78
+ row.addEventListener('click', () => select(event.id));
79
+ list.append(row);
80
+ if (event.id === state.selected) requestAnimationFrame(() => row.scrollIntoView({ block: 'nearest' }));
81
+ }
82
+ }
83
+
84
+ function curlCommand(event) {
85
+ const excluded = new Set(state.config.curlExcludedHeaders);
86
+ const headers = Object.entries(event.headers).filter(([k, v]) => !excluded.has(k.toLowerCase()) && v !== state.config.redactedPlaceholder);
87
+ return ['curl', '-X', quote(event.method), ...headers.flatMap(([k, v]) => ['-H', quote(`${k}: ${v}`)]), ...(event.body ? ['--data-raw', quote(event.body)] : []), quote(location.origin + event.path)].join(' ');
88
+ }
89
+
90
+ const TOKEN = /("(?:\\.|[^"\\])*")(\s*:)?|\b(true|false|null)\b|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|([{}[\],])/g;
91
+ function highlightJsonLine(line) {
92
+ const frag = document.createDocumentFragment(); let last = 0;
93
+ for (const m of line.matchAll(TOKEN)) {
94
+ if (m.index > last) frag.append(line.slice(last, m.index));
95
+ if (m[1]) { frag.append(node('span', m[1], m[2] ? 't-key' : 't-str')); if (m[2]) frag.append(node('span', m[2], 't-punc')); }
96
+ else if (m[3]) frag.append(node('span', m[3], 't-lit'));
97
+ else if (m[4]) frag.append(node('span', m[4], 't-num'));
98
+ else frag.append(node('span', m[5], 't-punc'));
99
+ last = m.index + m[0].length;
100
+ }
101
+ if (last < line.length) frag.append(line.slice(last));
102
+ return frag;
103
+ }
104
+ function codeBlock(text, highlight) {
105
+ const block = node('div', undefined, 'code');
106
+ for (const line of text.split('\n')) { const row = node('div', undefined, 'code-line'); const content = node('span'); content.append(highlight ? highlightJsonLine(line) : line); row.append(content); block.append(row); }
107
+ return block;
108
+ }
109
+ const keyValueTable = rows => {
110
+ const table = node('div', undefined, 'headers');
111
+ for (const [k, v, cls = 'hv'] of rows) { const row = node('div', undefined, 'header-row'); row.append(node('span', k, 'hk'), node('span', String(v), cls)); table.append(row); }
112
+ return table;
113
+ };
114
+
115
+ function waitingState() {
116
+ const box = node('div', undefined, 'waiting');
117
+ const title = node('h2', t().waitingTitle, 'waiting-title'); title.append(node('span', undefined, 'cursor'));
118
+ box.append(title, node('p', format(t().waitingText, { endpoint: state.endpoint }), 'waiting-text'));
119
+ box.append(codeBlock(state.demoCommand, false));
120
+ const actions = node('div', undefined, 'detail-actions');
121
+ const copy = node('button', t().copyCurl, 'btn btn-primary'); copy.addEventListener('click', () => copyText(state.demoCommand, t().curlCopied));
122
+ actions.append(copy); box.append(actions);
123
+ return box;
124
+ }
125
+
126
+ // Detail tabs, in display order. Each has a label from messages.json, an optional count, and a panel.
127
+ const TABS = [
128
+ { id: 'body', label: () => t().tabBody, count: e => fmtBytes(e.bytes), panel: e => {
129
+ const contentType = String(e.headers[state.config.headers.contentType] || '');
130
+ let text = e.body; let json = false;
131
+ if (text) { try { text = JSON.stringify(JSON.parse(text), null, 2); json = true; } catch {} }
132
+ return [text ? codeBlock(text, json) : node('div', t().emptyBody, 'note'), node('div', `${contentType || t().noContentType}${json ? t().formatted : ''}`, 'note')];
133
+ } },
134
+ { id: 'headers', label: () => t().tabHeaders, count: e => String(Object.keys(e.headers).length), panel: e =>
135
+ [keyValueTable(Object.entries(e.headers).map(([k, v]) => [k, v, v === state.config.redactedPlaceholder ? 'hv redacted' : 'hv'])), node('div', t().redactedNote, 'note')] },
136
+ { id: 'response', label: () => t().tabResponse, count: e => String(e.response.status), panel: e => {
137
+ const { status, mockId, mockPath, delayMs } = e.response;
138
+ return [keyValueTable([
139
+ [t().responseStatus, status, status >= ui().errorStatusFrom ? 'hv redacted' : 'hv'],
140
+ [t().responseAnsweredBy, mockId ? format(t().answeredByRule, { id: mockId, path: mockPath }) : t().answeredByDefault],
141
+ [t().responseDelay, format(t().milliseconds, { value: delayMs })],
142
+ ]), node('div', t().responseNote, 'note')];
143
+ } },
144
+ { id: 'curl', label: () => t().tabCurl, count: () => '', panel: e => [codeBlock(curlCommand(e), false), node('div', t().curlNote, 'note')] },
145
+ ];
146
+
147
+ function renderDetail() {
148
+ const detail = $('detail'); detail.replaceChildren();
149
+ const event = state.detail;
150
+ if (!event) { detail.append(state.events.length ? node('div', t().selectRequest, 'empty') : waitingState()); return; }
151
+ const short = id => id.slice(0, ui().shortIdLength);
152
+ const meta = node('div', undefined, 'detail-meta');
153
+ const chip = (text, cls = '') => node('span', text, `chip ${cls}`);
154
+ meta.append(chip(event.method, methodClass(event.method)), chip(new Date(event.timestamp).toLocaleString()), chip(fmtBytes(event.bytes)), chip(short(event.id)));
155
+ if (event.replayOf) meta.append(chip(format(t().replayOf, { id: short(event.replayOf) }), 'chip-accent'));
156
+ const actions = node('div', undefined, 'detail-actions');
157
+ const replay = node('button', t().replayLocally, 'btn btn-primary'); replay.id = 'replay-btn';
158
+ replay.addEventListener('click', replaySelected);
159
+ const copy = node('button', t().copyAsCurl, 'btn'); copy.addEventListener('click', () => copyText(curlCommand(event), t().curlCopiedWarning));
160
+ actions.append(replay, copy);
161
+
162
+ state.tab ??= TABS[0].id;
163
+ const tabs = node('div', undefined, 'tabs'); tabs.setAttribute('role', 'tablist');
164
+ for (const tab of TABS) {
165
+ const button = node('button', tab.label(), 'tab'); button.setAttribute('role', 'tab'); button.setAttribute('aria-selected', String(state.tab === tab.id));
166
+ const count = tab.count(event);
167
+ if (count) button.append(node('span', count, 'count'));
168
+ button.addEventListener('click', () => { state.tab = tab.id; renderDetail(); });
169
+ tabs.append(button);
170
+ }
171
+ const panel = node('div', undefined, 'tab-panel');
172
+ panel.append(...TABS.find(tab => tab.id === state.tab).panel(event));
173
+ detail.append(node('h2', event.path, 'detail-path'), meta, actions, tabs, panel);
174
+ }
175
+
176
+ // Full headers and body are fetched only for the selected event; the list carries summaries.
177
+ async function loadDetail(id) {
178
+ if (!id) { state.detail = null; renderDetail(); return; }
179
+ try { const { event } = await getJson(route('event', id)); if (state.selected !== id) return; state.detail = event; }
180
+ catch (error) { if (state.selected !== id) return; state.detail = null; showToast(format(t().cannotLoadRequest, { reason: error.message })); }
181
+ renderDetail();
182
+ }
183
+ function select(id) {
184
+ if (!id || id === state.selected) return;
185
+ state.selected = id;
186
+ renderList();
187
+ return loadDetail(id);
188
+ }
189
+ async function replaySelected() {
190
+ const event = state.detail; if (!event) return;
191
+ const button = $('replay-btn'); if (button) button.disabled = true;
192
+ try { const data = await getJson(route('replay', event.id), { method: state.config.methods.post }); showToast(format(t().replayed, { status: data.responseStatus })); await refresh(); }
193
+ catch (e) { showToast(format(t().replayFailed, { reason: e.message })); }
194
+ finally { const b = $('replay-btn'); if (b) b.disabled = false; }
195
+ }
196
+
197
+ // Mock rules: listed newest first, the first matching rule answers.
198
+ function renderMocks() {
199
+ const key = JSON.stringify(state.mocks);
200
+ if (key === state.mocksKey) return;
201
+ state.mocksKey = key;
202
+ const count = state.mocks.length;
203
+ $('mocks-count').textContent = format(count === 1 ? t().rulesOne : t().rulesMany, { count });
204
+ const list = $('mocks-list'); list.replaceChildren();
205
+ if (!count) list.append(node('div', t().noRules, 'note'));
206
+ for (const rule of state.mocks) {
207
+ const row = node('div', undefined, 'mock-row');
208
+ const remove = node('button', t().remove, 'btn btn-ghost btn-danger');
209
+ remove.addEventListener('click', async () => {
210
+ try { await getJson(route('mock', rule.id), { method: state.config.methods.delete }); await refreshMocks(); }
211
+ catch (e) { showToast(format(t().cannotRemoveRule, { reason: e.message })); }
212
+ });
213
+ row.append(node('span', rule.method, rule.method === state.config.anyMethod ? `m m-${OTHER}` : methodClass(rule.method)), node('span', rule.path, 'path'), node('span', String(rule.status), statusClass(rule.status)), node('span', format(t().milliseconds, { value: rule.delayMs }), 'num'), node('span', rule.id, 'mock-id'), remove);
214
+ list.append(row);
215
+ }
216
+ }
217
+ async function refreshMocks() {
218
+ try { state.mocks = (await getJson(routes().mocks)).rules; renderMocks(); } catch {}
219
+ }
220
+ async function addMock(e) {
221
+ e.preventDefault();
222
+ const f = e.target.elements;
223
+ const contentType = state.config.headers.contentType;
224
+ const rule = { method: f.method.value, path: f.path.value.trim(), status: Number(f.status.value), delayMs: Number(f.delayMs.value) };
225
+ try { if (f.headers.value.trim()) rule.headers = JSON.parse(f.headers.value); }
226
+ catch { showToast(t().headersNotJson); return; }
227
+ if (f.body.value) {
228
+ rule.body = f.body.value;
229
+ // A body that parses as JSON is sent as JSON unless the headers already name a content type.
230
+ const typed = Object.keys(rule.headers || {}).some(k => k.toLowerCase() === contentType);
231
+ if (!typed) { try { JSON.parse(rule.body); rule.headers = { ...rule.headers, [contentType]: state.config.contentTypes.json }; } catch {} }
232
+ }
233
+ try {
234
+ await sendJson(routes().mocks, state.config.methods.post, rule);
235
+ showToast(t().ruleAdded);
236
+ e.target.reset(); setupMockForm();
237
+ await refreshMocks();
238
+ } catch (err) { showToast(format(t().cannotAddRule, { reason: err.message })); }
239
+ }
240
+ function setupMockForm() {
241
+ const f = $('mock-form').elements;
242
+ const { mockRuleDefaults: defaults, statusRange } = state.config;
243
+ f.path.value = state.config.captureBase;
244
+ f.status.value = String(defaults.status); f.status.min = String(statusRange.min); f.status.max = String(statusRange.max);
245
+ f.delayMs.value = String(defaults.delayMs); f.delayMs.min = String(state.config.minDelayMs); f.delayMs.max = String(state.config.maxDelayMs);
246
+ }
247
+
248
+ // Re-renders only what changed so scroll position and text selection survive polling.
249
+ async function refresh() {
250
+ let data;
251
+ try { data = await getJson(routes().events); } catch { setOnline(false); return; }
252
+ setOnline(true);
253
+ state.events = data.events.map(e => ({ ...e, t: Date.parse(e.timestamp) }));
254
+ let target = state.selected;
255
+ if (target && !state.events.some(x => x.id === target)) target = null;
256
+ if (!target && state.events.length) target = state.events[0].id;
257
+ const selectionChanged = target !== state.selected;
258
+ state.selected = target;
259
+ if (currentListKey() !== state.listKey) renderList();
260
+ renderStats();
261
+ if (selectionChanged) await loadDetail(target);
262
+ }
263
+ async function poll() { await Promise.all([refresh(), refreshMocks()]); setTimeout(poll, state.config.pollIntervalMs); }
264
+
265
+ // Timeline: one spike per request, height by payload size (log scale), color by method.
266
+ const scope = { canvas: null, ctx: null, w: 0, h: 0, dpr: 1, colors: {}, lastDraw: 0 };
267
+ // The canvas cannot use CSS variables directly, so theme colors are re-read whenever the theme changes.
268
+ function readColors() {
269
+ const css = getComputedStyle(document.documentElement);
270
+ for (const name of ['line', 'line-strong', 'text', 'accent', 'raise', 'mono', ...[...ui().methods, OTHER].map(m => `m-${m.toLowerCase()}`)]) scope.colors[name] = css.getPropertyValue(`--${name}`).trim();
271
+ scope.lastDraw = 0;
272
+ }
273
+ function setupScope() {
274
+ const tl = ui().timeline;
275
+ scope.canvas = $('scope'); scope.ctx = scope.canvas.getContext('2d');
276
+ readColors();
277
+ const resize = () => { const r = scope.canvas.getBoundingClientRect(); scope.dpr = window.devicePixelRatio || 1; scope.w = r.width; scope.h = r.height; scope.canvas.width = Math.round(r.width * scope.dpr); scope.canvas.height = Math.round(r.height * scope.dpr); scope.lastDraw = 0; };
278
+ new ResizeObserver(resize).observe(scope.canvas); resize();
279
+ const axis = $('axis'); const step = state.config.timelineWindowMs / tl.divisions;
280
+ for (let i = tl.divisions; i >= 0; i--) axis.append(node('span', i ? `-${fmtSpan(step * i)}` : t().now));
281
+ scope.canvas.addEventListener('mousemove', e => {
282
+ const x = e.clientX - scope.canvas.getBoundingClientRect().left;
283
+ let best = null, bestDist = tl.hoverRadiusPx;
284
+ for (const ev of state.events) { const d = Math.abs(spikeX(ev.t) - x); if (d < bestDist) { best = ev; bestDist = d; } }
285
+ state.hover = best; scope.canvas.style.cursor = best ? 'pointer' : 'crosshair'; scope.lastDraw = 0;
286
+ });
287
+ scope.canvas.addEventListener('mouseleave', () => { state.hover = null; scope.lastDraw = 0; });
288
+ scope.canvas.addEventListener('click', () => { if (state.hover) select(state.hover.id); });
289
+ requestAnimationFrame(drawScope);
290
+ }
291
+ const spikeX = time => (time - (Date.now() - state.config.timelineWindowMs)) / state.config.timelineWindowMs * scope.w;
292
+ function drawScope(now) {
293
+ requestAnimationFrame(drawScope);
294
+ const tl = ui().timeline; const flashMs = ui().flashMs;
295
+ const animating = [...state.flashes.values()].some(start => now - start < flashMs);
296
+ if (!animating && now - scope.lastDraw < tl.redrawMs) return;
297
+ scope.lastDraw = now;
298
+ for (const [id, start] of state.flashes) if (now - start > flashMs) state.flashes.delete(id);
299
+ const { ctx, w, h, dpr, colors } = scope;
300
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, w, h);
301
+ // The 0.5 offsets put 1-pixel lines on pixel centers so they stay sharp.
302
+ const base = h - 0.5;
303
+ ctx.lineWidth = tl.lineWidth;
304
+ ctx.strokeStyle = colors.line;
305
+ for (let i = 0; i <= tl.divisions; i++) { const x = Math.round(i * (w - 1) / tl.divisions) + 0.5; ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke(); }
306
+ ctx.setLineDash(tl.gridDash);
307
+ for (let row = 1; row < tl.gridRows; row++) { const y = Math.round(h * row / tl.gridRows) + 0.5; ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(w, y); ctx.stroke(); }
308
+ ctx.setLineDash([]);
309
+ ctx.strokeStyle = colors['line-strong']; ctx.beginPath(); ctx.moveTo(0, base); ctx.lineTo(w, base); ctx.stroke();
310
+
311
+ const maxLog = Math.log2(state.config.maxBodyBytes + 1);
312
+ const emphasized = new Set([state.selected, state.hover?.id]);
313
+ for (const ev of [...state.events].reverse()) {
314
+ const x = spikeX(ev.t); if (x < -tl.hoverRadiusPx || x > w + tl.hoverRadiusPx) continue;
315
+ const height = tl.minSpikePx + (h - tl.topPaddingPx) * Math.min(1, Math.log2(ev.bytes + 1) / maxLog);
316
+ const color = colors[`m-${methodKey(ev.method)}`];
317
+ const strong = emphasized.has(ev.id);
318
+ const spikeWidth = strong ? tl.selectedSpikeWidthPx : tl.spikeWidthPx;
319
+ ctx.globalAlpha = strong ? 1 : tl.idleAlpha; ctx.fillStyle = color;
320
+ ctx.fillRect(Math.round(x) - spikeWidth / 2, base - height, spikeWidth, height);
321
+ ctx.beginPath(); ctx.arc(x, base - height, strong ? tl.selectedDotRadiusPx : tl.dotRadiusPx, 0, Math.PI * 2); ctx.fill();
322
+ const start = state.flashes.get(ev.id);
323
+ if (start !== undefined) {
324
+ const p = (now - start) / flashMs;
325
+ ctx.globalAlpha = Math.max(0, 1 - p); ctx.strokeStyle = color; ctx.lineWidth = tl.pulseLineWidth;
326
+ ctx.beginPath(); ctx.arc(x, base - height, tl.selectedDotRadiusPx + p * tl.pulseGrowPx, 0, Math.PI * 2); ctx.stroke(); ctx.lineWidth = tl.lineWidth;
327
+ }
328
+ }
329
+ ctx.globalAlpha = 1;
330
+ const sel = state.events.find(e => e.id === state.selected);
331
+ if (sel) { const x = Math.round(spikeX(sel.t)) + 0.5; ctx.strokeStyle = colors.accent; ctx.globalAlpha = tl.selectionAlpha; ctx.setLineDash(tl.selectionDash); ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; }
332
+ if (state.hover) {
333
+ const hv = state.hover;
334
+ const label = format(t().hoverLabel, { method: hv.method, path: hv.path, status: hv.status, size: fmtBytes(hv.bytes), age: fmtAge(hv.t) });
335
+ const pad = tl.labelPaddingPx; const lh = tl.labelHeightPx; const top = tl.labelTopPx;
336
+ ctx.font = `${tl.labelFontPx}px ${colors.mono}`;
337
+ const tw = Math.min(ctx.measureText(label).width + pad * 2, w);
338
+ const lx = Math.min(Math.max(spikeX(hv.t) - tw / 2, 0), w - tw);
339
+ ctx.fillStyle = colors.raise; ctx.strokeStyle = colors['line-strong'];
340
+ ctx.fillRect(lx, top, tw, lh); ctx.strokeRect(lx + 0.5, top + 0.5, tw - 1, lh - 1);
341
+ ctx.fillStyle = colors.text; ctx.textBaseline = 'middle'; ctx.fillText(label, lx + pad, top + lh / 2, tw - pad * 2);
342
+ }
343
+ }
344
+
345
+ function moveSelection(step) {
346
+ if (!state.events.length) return;
347
+ const index = state.events.findIndex(e => e.id === state.selected);
348
+ const next = state.events[Math.min(state.events.length - 1, Math.max(0, (index === -1 ? 0 : index + step)))];
349
+ select(next.id);
350
+ }
351
+ function onKey(e) {
352
+ if (e.metaKey || e.ctrlKey || e.altKey || /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName)) return;
353
+ const keys = ui().keys;
354
+ if (keys.next.includes(e.key)) { e.preventDefault(); moveSelection(1); }
355
+ else if (keys.previous.includes(e.key)) { e.preventDefault(); moveSelection(-1); }
356
+ else if (keys.replay.includes(e.key)) replaySelected();
357
+ else if (keys.copyCurl.includes(e.key) && state.detail) copyText(curlCommand(state.detail), t().curlCopiedWarning);
358
+ }
359
+
360
+ // Theme: the first theme in config/limits.json ("auto") follows the OS. The viewer's choice is remembered in this browser only.
361
+ function applyTheme(choice, remember) {
362
+ const themes = state.config.themes;
363
+ if (!themes.includes(choice)) choice = themes[0];
364
+ if (choice === themes[0]) delete document.documentElement.dataset.theme; else document.documentElement.dataset.theme = choice;
365
+ document.querySelectorAll('[data-theme-choice]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.themeChoice === choice)));
366
+ if (remember) { try { localStorage.setItem(ui().themeStorageKey, choice); } catch {} }
367
+ readColors();
368
+ }
369
+ function setupTheme() {
370
+ for (const theme of state.config.themes) { const b = node('button', t().themes[theme]); b.dataset.themeChoice = theme; $('themes').append(b); }
371
+ let stored = null;
372
+ try { stored = localStorage.getItem(ui().themeStorageKey); } catch {}
373
+ applyTheme(stored ?? state.config.defaultTheme, false);
374
+ document.querySelectorAll('[data-theme-choice]').forEach(b => b.addEventListener('click', () => applyTheme(b.dataset.themeChoice, true)));
375
+ matchMedia('(prefers-color-scheme: light)').addEventListener('change', readColors);
376
+ }
377
+
378
+ function bindText(name, value) { document.querySelectorAll(`[data-bind="${name}"]`).forEach(el => { el.textContent = value; }); }
379
+
380
+ async function init() {
381
+ try { state.config = await getJson(document.body.dataset.configUrl); }
382
+ catch { $('live-label').textContent = document.body.dataset.offline; $('live').classList.add('offline'); setTimeout(init, Number(document.body.dataset.retryMs)); return; }
383
+ state.online = true;
384
+ state.endpoint = `${location.origin}${state.config.captureBase}`;
385
+ state.demoCommand = format(state.config.exampleCommand, { url: `${state.endpoint}${state.config.examplePath}`, contentType: state.config.exampleContentType, body: state.config.exampleBody });
386
+ document.title = state.config.name;
387
+ bindText('host', state.config.host);
388
+ bindText('limit', String(state.config.maxEvents));
389
+ bindText('window', fmtSpan(state.config.timelineWindowMs));
390
+ bindText('version', state.config.version);
391
+ bindText('rate-window', fmtSpan(ui().rateWindowMs));
392
+ bindText('prefix-suffix', state.config.prefixSuffix);
393
+ document.querySelectorAll('[data-keys]').forEach(el => { for (const action of el.dataset.keys.split(' ')) el.append(node('kbd', ui().keys[action][0])); });
394
+ for (const method of ui().methods) $('legend').append(node('span', method, methodClass(method)));
395
+ $('legend').append(node('span', t().otherMethods, `m m-${OTHER}`));
396
+ for (const method of ui().mockMethods) $('mock-form').elements.method.append(node('option', method));
397
+ setupMockForm();
398
+ $('command').textContent = state.demoCommand;
399
+ $('copy').addEventListener('click', () => copyText(state.endpoint, t().endpointCopied));
400
+ $('copy-cmd').addEventListener('click', () => copyText(state.demoCommand, t().curlCopied));
401
+ $('refresh').addEventListener('click', refresh);
402
+ $('clear').addEventListener('click', async () => {
403
+ if (!confirm(t().confirmClear)) return;
404
+ try { await getJson(routes().events, { method: state.config.methods.delete }); } catch (e) { showToast(format(t().clearFailed, { reason: e.message })); return; }
405
+ state.selected = null; state.detail = null; await refresh(); renderDetail();
406
+ });
407
+ $('mock-form').addEventListener('submit', addMock);
408
+ $('mocks-clear').addEventListener('click', async () => {
409
+ if (!confirm(t().confirmRemoveRules)) return;
410
+ try { await getJson(routes().mocks, { method: state.config.methods.delete }); await refreshMocks(); } catch (e) { showToast(format(t().cannotRemoveRules, { reason: e.message })); }
411
+ });
412
+ document.addEventListener('keydown', onKey);
413
+ setupScope();
414
+ setupTheme();
415
+ // The list renders on the first poll, so requests already in memory at page load don't flash as new.
416
+ renderDetail(); poll();
417
+ setInterval(tickAges, ui().ageTickMs);
418
+ }
419
+ init();
package/src/config.js DELETED
@@ -1,71 +0,0 @@
1
- import { readFileSync } from 'node:fs';
2
- import { fileURLToPath } from 'node:url';
3
-
4
- export const defaultConfigPath = fileURLToPath(new URL('../config/default.json', import.meta.url));
5
- const LOOPBACK_HOSTS = ['127.0.0.1', 'localhost', '::1'];
6
- const LOOPBACK_HOSTNAMES = ['127.0.0.1', 'localhost', '[::1]'];
7
-
8
- export function readConfigFile(path) {
9
- try { return JSON.parse(readFileSync(path, 'utf8')); }
10
- catch (error) { throw new Error(`Cannot read config file ${path}: ${error.message}`); }
11
- }
12
-
13
- // Merges one level deep: each section is merged key by key, arrays are replaced whole.
14
- // Unknown sections and keys are rejected so typos never pass silently.
15
- export function mergeConfig(base, override = {}) {
16
- const merged = {};
17
- for (const [section, values] of Object.entries(override)) {
18
- if (!(section in base)) throw new Error(`Unknown config section "${section}"`);
19
- if (typeof values !== 'object' || values === null || Array.isArray(values)) throw new Error(`Config section "${section}" must be an object`);
20
- for (const key of Object.keys(values)) if (!(key in base[section])) throw new Error(`Unknown config key "${section}.${key}"`);
21
- }
22
- for (const section of Object.keys(base)) merged[section] = { ...base[section], ...(override[section] || {}) };
23
- return merged;
24
- }
25
-
26
- const isInt = (value, min, max) => Number.isInteger(value) && value >= min && value <= max;
27
- const isStringList = value => Array.isArray(value) && value.every(x => typeof x === 'string' && x.length > 0);
28
-
29
- export function validateConfig(config) {
30
- const { server, capture, replay, redaction, ui } = config;
31
- const errors = [];
32
- const check = (ok, message) => { if (!ok) errors.push(message); };
33
- check(LOOPBACK_HOSTS.includes(server.host), `server.host must be a loopback address (${LOOPBACK_HOSTS.join(', ')})`);
34
- check(isInt(server.port, 0, 65535), 'server.port must be an integer 0..65535 (0 picks a free port)');
35
- check(isStringList(server.allowedHostnames) && server.allowedHostnames.length > 0 && server.allowedHostnames.every(x => LOOPBACK_HOSTNAMES.includes(x)), `server.allowedHostnames must be a non-empty list of ${LOOPBACK_HOSTNAMES.join(', ')}`);
36
- check(isStringList(server.allowedHostnames) && server.allowedHostnames.includes(server.host === '::1' ? '[::1]' : server.host), 'server.allowedHostnames must include server.host');
37
- check(typeof capture.pathPrefix === 'string' && /^\/[A-Za-z0-9._~-]+(\/[A-Za-z0-9._~-]+)*$/.test(capture.pathPrefix) && !/^\/(api|ui\.)/.test(capture.pathPrefix), 'capture.pathPrefix must look like "/hook" (no trailing slash, not under /api)');
38
- check(isInt(capture.maxBodyBytes, 1, 100 * 1024 * 1024), 'capture.maxBodyBytes must be an integer 1..104857600');
39
- check(isInt(capture.maxEvents, 1, 100000), 'capture.maxEvents must be an integer 1..100000');
40
- check(isInt(replay.timeoutMs, 100, 60000), 'replay.timeoutMs must be an integer 100..60000');
41
- check(isStringList(replay.blockedMethods), 'replay.blockedMethods must be a list of method names');
42
- check(isStringList(replay.excludedHeaders), 'replay.excludedHeaders must be a list of header names');
43
- check(typeof redaction.placeholder === 'string' && redaction.placeholder.length > 0, 'redaction.placeholder must be a non-empty string');
44
- check(isStringList(redaction.sensitiveHeaders), 'redaction.sensitiveHeaders must be a list of header names');
45
- check(isInt(ui.pollIntervalMs, 250, 60000), 'ui.pollIntervalMs must be an integer 250..60000');
46
- check(isInt(ui.timelineWindowMs, 10000, 86400000), 'ui.timelineWindowMs must be an integer 10000..86400000');
47
- check(['auto', 'light', 'dark'].includes(ui.defaultTheme), 'ui.defaultTheme must be "auto", "light" or "dark"');
48
- check(isStringList(ui.curlExcludedHeaders), 'ui.curlExcludedHeaders must be a list of header names');
49
- if (errors.length) throw new Error(`Invalid configuration:\n - ${errors.join('\n - ')}`);
50
- }
51
-
52
- function normalize(config) {
53
- const lower = list => list.map(x => x.toLowerCase());
54
- return {
55
- ...config,
56
- replay: { ...config.replay, blockedMethods: config.replay.blockedMethods.map(x => x.toUpperCase()), excludedHeaders: lower(config.replay.excludedHeaders) },
57
- redaction: { ...config.redaction, sensitiveHeaders: lower(config.redaction.sensitiveHeaders) },
58
- ui: { ...config.ui, curlExcludedHeaders: lower(config.ui.curlExcludedHeaders) },
59
- };
60
- }
61
-
62
- const deepFreeze = value => { if (value && typeof value === 'object') { Object.values(value).forEach(deepFreeze); Object.freeze(value); } return value; };
63
-
64
- // Precedence: config/default.json < file (--config) < overrides (PORT, --port, tests).
65
- export function loadConfig({ file, overrides } = {}) {
66
- let config = readConfigFile(defaultConfigPath);
67
- if (file) config = mergeConfig(config, readConfigFile(file));
68
- if (overrides) config = mergeConfig(config, overrides);
69
- validateConfig(config);
70
- return deepFreeze(normalize(config));
71
- }
package/src/ui.html DELETED
@@ -1,66 +0,0 @@
1
- <!doctype html>
2
- <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>HookDesk Mini</title>
3
- <link rel="stylesheet" href="/ui.css">
4
- <link rel="icon" href="/logo.svg" type="image/svg+xml">
5
- </head><body>
6
- <header class="top">
7
- <div class="brand"><img class="brand-mark" src="/logo.svg" width="28" height="28" alt=""><span class="brand-name">hookdesk</span><span class="brand-tag">mini</span></div>
8
- <div class="top-meta">
9
- <span class="kv"><span class="k">host</span><span class="v" data-bind="host">127.0.0.1</span></span>
10
- <span class="kv"><span class="k">buffer</span><span class="v"><span data-bind="limit">200</span> req</span></span>
11
- <span class="kv"><span class="k">storage</span><span class="v">memory</span></span>
12
- </div>
13
- <div id="live" class="live" title="Whether the dashboard can reach the local server"><span class="live-dot" aria-hidden="true"></span><span id="live-label">Live</span></div>
14
- <div class="theme" role="group" aria-label="Color theme">
15
- <button data-theme-choice="auto" title="Follow the system setting">Auto</button>
16
- <button data-theme-choice="light" title="Light theme">Light</button>
17
- <button data-theme-choice="dark" title="Dark theme">Dark</button>
18
- </div>
19
- </header>
20
-
21
- <section class="scope">
22
- <div class="stats">
23
- <div class="stat"><div class="stat-k">Captured</div><div id="count" class="stat-v">0</div><div class="stat-d">requests held in memory</div></div>
24
- <div class="stat"><div class="stat-k">Last 60 s</div><div id="rate" class="stat-v">0</div><div class="stat-d">requests in the past minute</div></div>
25
- <div class="stat"><div class="stat-k">Last hit</div><div id="last" class="stat-v">none</div><div class="stat-d">since the newest request</div></div>
26
- <div class="stat"><div class="stat-k">In memory</div><div id="bytes" class="stat-v">0 B</div><div class="stat-d">total size of all bodies</div></div>
27
- </div>
28
- <div class="scope-chart">
29
- <div class="scope-head">
30
- <span class="scope-title">Activity, last <span data-bind="window">5m</span></span>
31
- <span class="scope-help">Each spike is one request. Taller means a bigger body. Hover to preview, click to open.</span>
32
- <span class="legend"><span class="m m-get">GET</span><span class="m m-post">POST</span><span class="m m-put">PUT/PATCH</span><span class="m m-delete">DELETE</span><span class="m m-other">other</span></span>
33
- </div>
34
- <canvas id="scope" role="img" aria-label="Request activity timeline"></canvas>
35
- <div id="axis" class="scope-axis"></div>
36
- </div>
37
- </section>
38
-
39
- <section class="command">
40
- <span class="command-label">Send a test</span>
41
- <span class="prompt" aria-hidden="true">$</span>
42
- <code id="command" class="command-text" title="Run this in a terminal to send a test webhook"></code>
43
- <div class="command-actions">
44
- <button id="copy" class="btn" title="Copy the base URL to paste into your webhook provider or app">Copy endpoint</button>
45
- <button id="copy-cmd" class="btn" title="Copy the test command on the left">Copy curl</button>
46
- <button id="refresh" class="btn btn-ghost" title="Reload the request list now">Refresh</button>
47
- <button id="clear" class="btn btn-ghost btn-danger" title="Delete all captured requests">Clear</button>
48
- </div>
49
- </section>
50
-
51
- <main class="split">
52
- <section class="pane pane-list">
53
- <div class="pane-head"><span class="pane-title">Requests<span class="pane-sub">newest first</span></span><span class="keys"><kbd>j</kbd><kbd>k</kbd> navigate</span></div>
54
- <div class="table-head"><span>Method</span><span>Path</span><span class="num">Size</span><span class="num">Age</span></div>
55
- <div id="entries" class="entries"></div>
56
- </section>
57
- <section class="pane pane-detail"><div id="detail" class="detail"></div></section>
58
- </main>
59
-
60
- <footer class="foot">
61
- <span>Local only. Bodies are shown as received and may contain secrets.</span>
62
- <span class="keys"><kbd>r</kbd> replay <kbd>c</kbd> copy curl</span>
63
- </footer>
64
-
65
- <div id="toast" class="toast" role="status"></div>
66
- <script src="/ui.js"></script></body></html>