@cslug/inspector 0.0.0-placeholder → 0.15.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/ui/app.js ADDED
@@ -0,0 +1,479 @@
1
+ // The inspector's client: no build step, no framework. Every node is built with textContent: recorded data
2
+ // (request bodies, mail, log lines) is never parsed as HTML here; a mail's HTML only renders in a sandboxed iframe.
3
+
4
+ const base = document.body.dataset.base ?? '/_inspector'
5
+ const api = (path) => `${base}/api${path}`
6
+ const MUTATION = { 'x-cslug-inspector': '1', 'content-type': 'application/json' }
7
+
8
+ const KINDS = [
9
+ ['request', 'Requests'],
10
+ ['exception', 'Exceptions'],
11
+ ['query', 'Queries'],
12
+ ['log', 'Logs'],
13
+ ['event', 'Events'],
14
+ ['job', 'Jobs'],
15
+ ['schedule', 'Schedule'],
16
+ ['mail', 'Mail'],
17
+ ['notification', 'Notifications'],
18
+ ['cache', 'Cache'],
19
+ ['http_client', 'HTTP client'],
20
+ ['view', 'Views'],
21
+ ['ai', 'AI'],
22
+ ]
23
+ const LABEL = Object.fromEntries(KINDS)
24
+
25
+ const state = { q: '', tag: '', paused: false, entries: [], route: null, timer: 0, renderedFor: '' }
26
+
27
+ // ── DOM helpers ──────────────────────────────────────────────────────────────────────────────────────────
28
+ function el(tag, attrs = {}, ...children) {
29
+ const node = document.createElement(tag)
30
+ for (const [k, v] of Object.entries(attrs)) {
31
+ if (v === undefined || v === null || v === false) continue
32
+ if (k === 'class') node.className = v
33
+ else if (k.startsWith('on')) node.addEventListener(k.slice(2), v)
34
+ else node.setAttribute(k, v === true ? '' : String(v))
35
+ }
36
+ for (const child of children.flat()) {
37
+ if (child === undefined || child === null || child === false) continue
38
+ node.append(child instanceof Node ? child : document.createTextNode(String(child)))
39
+ }
40
+ return node
41
+ }
42
+ const $ = (id) => document.getElementById(id)
43
+ const time = (ms) =>
44
+ new Date(ms).toLocaleTimeString(undefined, { hour12: false }) + `.${String(ms % 1000).padStart(3, '0')}`
45
+ const pretty = (v) => (typeof v === 'string' ? v : JSON.stringify(v, null, 2))
46
+ const isEmpty = (v) =>
47
+ v === undefined || v === null || v === '' || (typeof v === 'object' && Object.keys(v).length === 0)
48
+
49
+ function tagClass(tag) {
50
+ if (tag === 'failed' || tag === 'status:5xx' || tag === 'error' || tag === 'miss') return 'badge bad'
51
+ if (tag === 'slow' || tag === 'status:4xx' || tag === 'warn' || tag === 'retrying') return 'badge warn'
52
+ if (tag === 'status:2xx' || tag === 'hit' || tag === 'processed' || tag === 'sent' || tag === 'completed')
53
+ return 'badge ok'
54
+ return 'badge'
55
+ }
56
+
57
+ async function getJson(url, init) {
58
+ const res = await fetch(url, init)
59
+ if (!res.ok) throw new Error(`${res.status} ${await res.text()}`)
60
+ return res.json()
61
+ }
62
+
63
+ // ── routing ──────────────────────────────────────────────────────────────────────────────────────────────
64
+ function parseRoute() {
65
+ const [, view, arg] = /^#\/(k|e|b)\/(.+)$/.exec(location.hash) ?? []
66
+ if (view === 'e') return { view: 'entry', id: decodeURIComponent(arg) }
67
+ if (view === 'b') return { view: 'batch', batch: decodeURIComponent(arg) }
68
+ if (view === 'k') return { view: 'list', kind: decodeURIComponent(arg) }
69
+ return { view: 'list', kind: '' }
70
+ }
71
+
72
+ async function navigate() {
73
+ state.route = parseRoute()
74
+ state.entries = []
75
+ state.renderedFor = ''
76
+ if (state.route.view === 'entry') {
77
+ getJson(api('/entries?limit=1'))
78
+ .then((d) => {
79
+ renderKinds(d.counts)
80
+ setPaused(d.paused)
81
+ })
82
+ .catch(() => {})
83
+ await showEntry(state.route.id)
84
+ } else await refresh(true)
85
+ }
86
+
87
+ // ── lists ────────────────────────────────────────────────────────────────────────────────────────────────
88
+ function listUrl(before) {
89
+ const r = state.route
90
+ const params = new URLSearchParams()
91
+ if (r.view === 'list' && r.kind) params.set('kind', r.kind)
92
+ if (r.view === 'batch') {
93
+ params.set('batch', r.batch)
94
+ params.set('limit', '500')
95
+ }
96
+ if (state.q) params.set('q', state.q)
97
+ if (state.tag) params.set('tag', state.tag)
98
+ if (before) params.set('before', before)
99
+ return api(`/entries?${params}`)
100
+ }
101
+
102
+ async function refresh(replace = false) {
103
+ if (!state.route || state.route.view === 'entry') return
104
+ let data
105
+ try {
106
+ data = await getJson(listUrl())
107
+ } catch (error) {
108
+ renderError(error)
109
+ return
110
+ }
111
+ renderKinds(data.counts)
112
+ setPaused(data.paused)
113
+ if (replace || !state.entries.length) state.entries = data.entries
114
+ else {
115
+ // keep what was loaded with "Older"; put new ones on top
116
+ const known = new Set(state.entries.map((e) => e.id))
117
+ state.entries = [...data.entries.filter((e) => !known.has(e.id)), ...state.entries]
118
+ }
119
+ renderList()
120
+ }
121
+
122
+ async function loadOlder() {
123
+ const last = state.entries.at(-1)
124
+ if (!last) return
125
+ const data = await getJson(listUrl(last.id))
126
+ state.entries.push(...data.entries)
127
+ renderList(data.entries.length === 0)
128
+ }
129
+
130
+ function renderKinds(counts = {}) {
131
+ const current = state.route?.view === 'list' ? state.route.kind : null
132
+ const total = Object.values(counts).reduce((a, b) => a + b, 0)
133
+ const link = (kind, label, n) =>
134
+ el(
135
+ 'a',
136
+ { href: kind ? `#/k/${kind}` : '#/', class: current === kind ? 'current' : undefined },
137
+ el('span', {}, label),
138
+ el('span', { class: 'count' }, n ?? 0),
139
+ )
140
+ $('kinds').replaceChildren(link('', 'All', total), ...KINDS.map(([k, label]) => link(k, label, counts[k])))
141
+ }
142
+
143
+ function renderList(exhausted = false) {
144
+ const r = state.route
145
+ const main = $('main')
146
+ const title =
147
+ r.view === 'batch'
148
+ ? el(
149
+ 'div',
150
+ { class: 'detail' },
151
+ el('a', { class: 'back', href: '#/' }, '← All entries'),
152
+ el('h1', {}, `Batch ${r.batch}`),
153
+ )
154
+ : null
155
+ const filter = state.tag
156
+ ? el(
157
+ 'div',
158
+ { class: 'tags-filter' },
159
+ 'Tag: ',
160
+ el('button', { class: 'tag on', type: 'button', onclick: () => setTag('') }, `${state.tag} ✕`),
161
+ )
162
+ : null
163
+ if (!state.entries.length) {
164
+ main.replaceChildren(
165
+ ...[title, filter].filter(Boolean),
166
+ el(
167
+ 'p',
168
+ { class: 'empty' },
169
+ state.q || state.tag ? 'Nothing matches.' : 'Nothing recorded yet. Use the app; entries appear here.',
170
+ ),
171
+ )
172
+ return
173
+ }
174
+ const rows = state.entries.map((e) =>
175
+ el(
176
+ 'tr',
177
+ { onclick: () => (location.hash = `#/e/${e.id}`) },
178
+ el('td', { class: 'time' }, time(e.createdAt)),
179
+ el('td', { class: 'kind' }, el('span', { class: 'badge kind' }, LABEL[e.kind] ?? e.kind)),
180
+ el(
181
+ 'td',
182
+ { class: 'summary' },
183
+ e.summary,
184
+ el(
185
+ 'span',
186
+ { class: 'tags' },
187
+ e.tags.map((t) =>
188
+ el(
189
+ 'button',
190
+ {
191
+ type: 'button',
192
+ class: `tag ${tagClass(t)}`,
193
+ title: 'Filter by this tag',
194
+ onclick: (event) => {
195
+ event.stopPropagation()
196
+ setTag(t)
197
+ },
198
+ },
199
+ t,
200
+ ),
201
+ ),
202
+ ),
203
+ ),
204
+ el('td', { class: 'role' }, e.role ?? ''),
205
+ ),
206
+ )
207
+ const more =
208
+ r.view === 'batch' || exhausted || state.entries.length < 50
209
+ ? null
210
+ : el('button', { class: 'more', type: 'button', onclick: loadOlder }, 'Older entries')
211
+ // replaceChildren would print a null as text
212
+ main.replaceChildren(
213
+ ...[title, filter, el('table', { class: 'entries' }, el('tbody', {}, rows)), more].filter(Boolean),
214
+ )
215
+ }
216
+
217
+ function renderError(error) {
218
+ $('main').replaceChildren(el('p', { class: 'empty' }, `Could not load: ${error.message}`))
219
+ }
220
+
221
+ // ── one entry ────────────────────────────────────────────────────────────────────────────────────────────
222
+ function card(title, body, action) {
223
+ return el(
224
+ 'section',
225
+ { class: 'card' },
226
+ el('h2', {}, el('span', {}, title), action ?? null),
227
+ el('div', { class: 'body' }, body),
228
+ )
229
+ }
230
+ const code = (v) => el('pre', {}, pretty(v))
231
+ function kv(object) {
232
+ const rows = Object.entries(object ?? {})
233
+ .filter(([, v]) => v !== undefined)
234
+ .map(([k, v]) =>
235
+ el('tr', {}, el('td', {}, k), el('td', {}, typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v))),
236
+ )
237
+ return rows.length ? el('table', { class: 'kv' }, el('tbody', {}, rows)) : el('span', { class: 'badge' }, 'none')
238
+ }
239
+ function body(text) {
240
+ if (typeof text !== 'string') return code(text)
241
+ try {
242
+ return code(JSON.parse(text))
243
+ } catch {
244
+ return code(text)
245
+ }
246
+ }
247
+ function copyButton(label, text) {
248
+ const button = el('button', { type: 'button' }, label)
249
+ button.addEventListener('click', async () => {
250
+ await navigator.clipboard.writeText(text)
251
+ button.textContent = 'Copied'
252
+ setTimeout(() => (button.textContent = label), 1200)
253
+ })
254
+ return button
255
+ }
256
+ const shellQuote = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`
257
+ function curl(d) {
258
+ const parts = ['curl', '-X', d.method, shellQuote(d.url)]
259
+ for (const [k, v] of Object.entries(d.headers ?? {})) {
260
+ if (['host', 'content-length', 'connection'].includes(k) || v === '[redacted]') continue
261
+ parts.push('-H', shellQuote(`${k}: ${v}`))
262
+ }
263
+ if (d.payload !== undefined && d.method !== 'GET') parts.push('--data', shellQuote(JSON.stringify(d.payload)))
264
+ return parts.join(' ')
265
+ }
266
+
267
+ function sections(entry) {
268
+ const d = entry.data
269
+ switch (entry.kind) {
270
+ case 'request':
271
+ return [
272
+ card(
273
+ 'Request',
274
+ kv({
275
+ method: d.method,
276
+ url: d.url,
277
+ route: d.route,
278
+ pattern: d.routePath,
279
+ status: d.status,
280
+ duration: `${d.ms} ms`,
281
+ ip: d.ip,
282
+ }),
283
+ copyButton('Copy as cURL', curl(d)),
284
+ ),
285
+ card('Headers', kv(d.headers)),
286
+ isEmpty(d.query) ? null : card('Query', code(d.query)),
287
+ d.payload === undefined ? null : card('Payload', code(d.payload)),
288
+ card('Response headers', kv(d.responseHeaders)),
289
+ d.response === undefined ? null : card('Response body', body(d.response)),
290
+ ]
291
+ case 'exception':
292
+ return [
293
+ card(
294
+ 'Exception',
295
+ kv({
296
+ class: d.class,
297
+ message: d.message,
298
+ code: d.code,
299
+ status: d.status,
300
+ handlers: d.handlers?.join(', '),
301
+ path: d.path && `${d.method} ${d.path}`,
302
+ }),
303
+ ),
304
+ d.cause ? card('Cause', kv(d.cause)) : null,
305
+ d.stack ? card('Stack', code(d.stack)) : null,
306
+ ]
307
+ case 'query':
308
+ return [
309
+ card('SQL', code(d.sql), copyButton('Copy', d.sql)),
310
+ card('Parameters', code(d.params ?? [])),
311
+ card('Details', kv({ duration: `${d.ms} ms`, rows: d.rows, transaction: d.transaction, error: d.error })),
312
+ ]
313
+ case 'mail': {
314
+ const frame = el('iframe', {
315
+ class: 'mail',
316
+ sandbox: '',
317
+ title: 'Mail preview',
318
+ src: api(`/entries/${entry.id}/mail`),
319
+ referrerpolicy: 'no-referrer',
320
+ })
321
+ return [
322
+ card(
323
+ 'Mail',
324
+ kv({
325
+ mailable: d.mailable,
326
+ subject: d.subject,
327
+ from: addr(d.from),
328
+ to: addr(d.to),
329
+ cc: addr(d.cc),
330
+ bcc: addr(d.bcc),
331
+ replyTo: addr(d.replyTo),
332
+ locale: d.locale,
333
+ queued: d.queued,
334
+ transport: d.transport,
335
+ }),
336
+ ),
337
+ card('Preview', frame),
338
+ d.text ? card('Text part', code(d.text)) : null,
339
+ isEmpty(d.attachments) ? null : card('Attachments', code(d.attachments)),
340
+ ]
341
+ }
342
+ case 'log': {
343
+ const { level, msg, ...fields } = d
344
+ return [card(`[${level}] ${msg}`, isEmpty(fields) ? el('span', { class: 'badge' }, 'no fields') : code(fields))]
345
+ }
346
+ case 'job': {
347
+ const { payload, stack, ...rest } = d
348
+ return [card('Job', kv(rest)), card('Payload', code(payload)), stack ? card('Stack', code(stack)) : null]
349
+ }
350
+ case 'ai': {
351
+ const { messages, ...rest } = d
352
+ return [card('Run', kv(rest)), messages ? card('Messages', code(messages)) : null]
353
+ }
354
+ default:
355
+ return [card('Data', code(d))]
356
+ }
357
+ }
358
+ function addr(list) {
359
+ if (!list) return undefined
360
+ const one = (a) => (typeof a === 'string' ? a : a.name ? `${a.name} <${a.address}>` : a.address)
361
+ const all = Array.isArray(list) ? list.map(one) : [one(list)]
362
+ return all.length ? all.join(', ') : undefined
363
+ }
364
+
365
+ function timeline(entry, related, origin) {
366
+ if (!related.length && !origin) return null
367
+ const items = [...(origin ? [origin] : []), ...related]
368
+ const start = Math.min(entry.createdAt, ...items.map((e) => e.createdAt))
369
+ const li = (e) =>
370
+ el(
371
+ 'li',
372
+ { onclick: () => (location.hash = `#/e/${e.id}`) },
373
+ el('span', { class: 'offset' }, `+${e.createdAt - start} ms`),
374
+ el('span', {}, el('span', { class: 'badge kind' }, LABEL[e.kind] ?? e.kind)),
375
+ el('span', { class: 'summary' }, e.summary),
376
+ )
377
+ const title = entry.kind === 'request' ? 'What this request did' : 'In the same batch'
378
+ return [
379
+ origin ? card('Dispatched by', el('ul', { class: 'timeline' }, li(origin))) : null,
380
+ related.length
381
+ ? card(
382
+ `${title} (${related.length})`,
383
+ el('ul', { class: 'timeline' }, related.map(li)),
384
+ el('a', { href: `#/b/${encodeURIComponent(entry.batchId)}` }, 'As a list'),
385
+ )
386
+ : null,
387
+ ]
388
+ }
389
+
390
+ async function showEntry(id) {
391
+ let data
392
+ try {
393
+ data = await getJson(api(`/entries/${encodeURIComponent(id)}`))
394
+ } catch (error) {
395
+ renderError(error)
396
+ return
397
+ }
398
+ const { entry, related, origin } = data
399
+ const meta = el(
400
+ 'div',
401
+ { class: 'meta' },
402
+ el('span', {}, 'At ', el('b', {}, `${new Date(entry.createdAt).toLocaleDateString()} ${time(entry.createdAt)}`)),
403
+ entry.role ? el('span', {}, 'Process ', el('b', {}, entry.role)) : null,
404
+ entry.batchId
405
+ ? el('span', {}, 'Batch ', el('a', { href: `#/b/${encodeURIComponent(entry.batchId)}` }, entry.batchId))
406
+ : null,
407
+ entry.userId ? el('span', {}, 'User ', el('b', {}, entry.userId)) : null,
408
+ entry.traceId ? el('span', {}, 'Trace ', el('b', {}, entry.traceId)) : null,
409
+ entry.tags.length
410
+ ? el(
411
+ 'span',
412
+ {},
413
+ entry.tags.map((t) => el('span', { class: tagClass(t) }, t)),
414
+ )
415
+ : null,
416
+ )
417
+ $('main').replaceChildren(
418
+ el(
419
+ 'div',
420
+ { class: 'detail' },
421
+ el('a', { class: 'back', href: `#/k/${entry.kind}` }, `← ${LABEL[entry.kind] ?? entry.kind}`),
422
+ el('h1', {}, el('span', { class: 'badge kind' }, LABEL[entry.kind] ?? entry.kind), ' ', entry.summary),
423
+ meta,
424
+ ...sections(entry).filter(Boolean),
425
+ ...(timeline(entry, related, origin) ?? []).filter(Boolean),
426
+ ),
427
+ )
428
+ $('main').focus()
429
+ window.scrollTo(0, 0)
430
+ }
431
+
432
+ // ── toolbar ──────────────────────────────────────────────────────────────────────────────────────────────
433
+ function setTag(tag) {
434
+ state.tag = tag
435
+ refresh(true)
436
+ }
437
+ function setPaused(paused) {
438
+ state.paused = paused
439
+ $('pause').textContent = paused ? 'Resume' : 'Pause'
440
+ $('pause').classList.toggle('on', paused)
441
+ $('live').textContent = paused ? 'paused' : 'live'
442
+ $('live').classList.toggle('paused', paused)
443
+ }
444
+
445
+ $('pause').addEventListener('click', async () => {
446
+ const data = await getJson(api('/pause'), {
447
+ method: 'POST',
448
+ headers: MUTATION,
449
+ body: JSON.stringify({ paused: !state.paused }),
450
+ })
451
+ setPaused(data.paused)
452
+ })
453
+ $('clear').addEventListener('click', async () => {
454
+ if (!confirm('Delete every recorded entry?')) return
455
+ await getJson(api('/entries'), { method: 'DELETE', headers: MUTATION })
456
+ if (state.route?.view !== 'list') location.hash = '#/'
457
+ refresh(true)
458
+ })
459
+ let typing = 0
460
+ $('search').addEventListener('input', (event) => {
461
+ clearTimeout(typing)
462
+ typing = setTimeout(() => {
463
+ state.q = event.target.value.trim()
464
+ if (state.route?.view === 'entry') location.hash = '#/'
465
+ else refresh(true)
466
+ }, 200)
467
+ })
468
+
469
+ // poll while the tab is visible, on lists only (an open entry does not change)
470
+ function poll() {
471
+ clearInterval(state.timer)
472
+ state.timer = setInterval(() => {
473
+ if (document.visibilityState === 'visible' && state.route?.view !== 'entry') refresh()
474
+ }, 2000)
475
+ }
476
+ document.addEventListener('visibilitychange', () => document.visibilityState === 'visible' && refresh())
477
+ window.addEventListener('hashchange', navigate)
478
+ navigate()
479
+ poll()
package/ui/index.html ADDED
@@ -0,0 +1,25 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <meta name="robots" content="noindex" />
7
+ <title>Inspector</title>
8
+ <link rel="stylesheet" href="{{base}}/app.css" />
9
+ <script type="module" src="{{base}}/app.js"></script>
10
+ </head>
11
+ <body data-base="{{base}}">
12
+ <header class="bar">
13
+ <a class="brand" href="#/">Inspector</a>
14
+ <span class="env">development</span>
15
+ <input id="search" type="search" placeholder="Filter by text…" autocomplete="off" spellcheck="false" />
16
+ <span id="live" class="live" title="Updates every 2 seconds">live</span>
17
+ <button id="pause" type="button">Pause</button>
18
+ <button id="clear" type="button" class="danger">Clear</button>
19
+ </header>
20
+ <div class="layout">
21
+ <nav id="kinds" class="kinds" aria-label="Entry kinds"></nav>
22
+ <main id="main" class="main" tabindex="-1"></main>
23
+ </div>
24
+ </body>
25
+ </html>