@cslug/inspector 0.0.0-stage → 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/README.md CHANGED
@@ -1,3 +1,10 @@
1
- # Temporary Holding Version
1
+ # @cslug/inspector
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A development-only dashboard: what the app did, request by request. Requests, exceptions, queries (with their
4
+ parameters), log lines, events, jobs, scheduled runs, mail (rendered), notifications, cache operations, outgoing
5
+ HTTP calls, rendered views and AI runs are recorded in `.cslug/inspector.sqlite`, each with the request or job it
6
+ belongs to, and shown at `/_inspector`. It runs only with `APP_ENV=development` and does nothing at all in any other environment.
7
+ `cslug add inspector` installs it, lists `InspectorProvider` first and writes `config/inspector.ts`.
8
+
9
+ Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
10
+ [guide 27](../../guides/27-inspector.md).
package/docs/README.md ADDED
@@ -0,0 +1,73 @@
1
+ # @cslug/inspector
2
+
3
+ ## The gate
4
+
5
+ `InspectorProvider` checks `inspectorEnabled(app)`: `config('app.env') === 'development'` and `inspector.enabled`
6
+ not `false`. Otherwise its `boot()` returns at once: nothing observes core's `Instrumentation` (so reports cost one
7
+ boolean check), no file is opened, no route is added. No setting turns it on in `test`, `staging` or `production`.
8
+
9
+ It is a regular dependency, not a dev dependency: `bootstrap/providers.ts` imports it, and a production install
10
+ without dev dependencies would fail to load the app. Installed in production, it stays inert.
11
+
12
+ ## Recording
13
+
14
+ `Recorder` observes `Instrumentation` (requests, exceptions, queries, events, jobs, schedules, mail,
15
+ notifications, AI runs, reported by each package) and adds what it gathers itself:
16
+
17
+ | Kind | How |
18
+ |---|---|
19
+ | `log` | A log target at `debug` level (`Logger.addTarget`); the line's `requestId` / `jobId` place it |
20
+ | `cache` | `Cache` wrapped (`app.instance(Cache, …)` at boot): get, has, set, forget, increment, decrement, flush, remember, with key, hit or miss and ttl; never values |
21
+ | `http_client` | `globalThis.fetch` wrapped: method, URL, status, duration, headers (restored at shutdown) |
22
+ | `view` | `onView` from `@cslug/vue`, when installed: the component and its props |
23
+
24
+ Each entry is redacted (`redact()`: keys containing `password`, `secret`, `token`, `authorization`, `cookie`,
25
+ `apikey`, `cardnumber`, `cvv` and `inspector.redact`; secret headers), summarised (`describeEntry()`), and written
26
+ in batches every 250 ms, so a request never waits on the file.
27
+
28
+ Not recorded: `/_inspector`, `/__cslug/live`, `/health/`, `/favicon.ico` and `inspector.ignore.paths`, with
29
+ everything those requests did; static files; kinds missing from `inspector.watch`.
30
+
31
+ ## Dashboard
32
+
33
+ `inspectorRoutes()`, registered at boot under `inspector.path` (default `/_inspector`), outside the web group (no
34
+ session, no CSRF):
35
+
36
+ | Route | |
37
+ |---|---|
38
+ | `GET /_inspector` | The page (`ui/index.html`, with the base path written in), `app.js`, `app.css`: vanilla JS, no build; its own `Content-Security-Policy` (`'self'` only) |
39
+ | `GET /_inspector/api/entries?kind&tag&q&before&batch&limit` | `{ entries (summaries, no data), counts, paused }` |
40
+ | `GET /_inspector/api/entries/:id` | `{ entry, related (its batch and the jobs it dispatched), origin (the request that dispatched a job) }` |
41
+ | `GET /_inspector/api/entries/:id/mail` | The mail's HTML: `default-src 'none'` with inline styles, `X-Frame-Options: SAMEORIGIN`, shown in a sandboxed iframe |
42
+ | `DELETE /_inspector/api/entries` | Clear (needs `X-Cslug-Inspector: 1`) |
43
+ | `POST /_inspector/api/pause` `{ paused }` | Pause or resume every process (needs `X-Cslug-Inspector: 1`) |
44
+
45
+ The client builds every node with `textContent`: recorded data is never parsed as HTML outside the mail frame.
46
+
47
+ ## Storage
48
+
49
+ `InspectorStore`: SQLite (`bun:sqlite`) at `inspector.file` (default `.cslug/inspector.sqlite`, git-ignored), WAL
50
+ with a busy timeout, so the web, worker and scheduler processes of `cslug dev` write to it together and entries
51
+ survive restarts. Never the app's database. Entries older than `inspector.keep` (default `24h`) and beyond
52
+ `inspector.maxEntries` (default 20 000) are pruned at boot and every hour. `paused` (shared by every process)
53
+ stops writing.
54
+
55
+ ## Config (`config/inspector.ts`)
56
+
57
+ | Key | Default | |
58
+ |---|---|---|
59
+ | `enabled` | `true` | `false`: off in development too |
60
+ | `path` | `/_inspector` | Where the dashboard is served (also never recorded) |
61
+ | `file` | `.cslug/inspector.sqlite` | Relative to the app |
62
+ | `watch` | every kind | The kinds to record |
63
+ | `ignore.paths` | `[]` | Prefixes (`/assets`) or globs (`/api/*/ping`, `/files/**`) |
64
+ | `redact` | `[]` | More key fragments never stored |
65
+ | `keep` | `24h` | |
66
+ | `maxEntries` | `20000` | |
67
+ | `slowQueryMs` | `100` | Tags a query `slow` |
68
+ | `slowRequestMs` | `1000` | Tags a request `slow` |
69
+
70
+ ## Commands
71
+
72
+ `cslug inspector:clear` deletes every entry; `cslug inspector:prune [--all]` applies `keep` and `maxEntries`.
73
+ Both refuse outside development.
package/docs/api.md ADDED
@@ -0,0 +1,21 @@
1
+ # @cslug/inspector: API
2
+
3
+ ```ts
4
+ import { InspectorProvider, InspectorStore, Recorder, inspectorEnabled, openStore, pruneStore, redact,
5
+ describeEntry, inspectorRoutes, IGNORED_PATHS, KINDS, MUTATION_HEADER, type Entry, type EntryQuery, type InspectorConfig } from '@cslug/inspector'
6
+ ```
7
+
8
+ | | |
9
+ |---|---|
10
+ | `InspectorProvider` | Records in development (see docs/README.md); `inspector:clear`, `inspector:prune` |
11
+ | `inspectorEnabled(app)` | `app.env === 'development'` and `inspector.enabled !== false` |
12
+ | `InspectorStore(file)` | `insert(entries)`, `list({ kind, before, tag, q, batch, limit })` (newest first, 50 by default, at most 500), `get(id)`, `related(batchId)` (the batch and the jobs it dispatched, oldest first), `counts()`, `clear()`, `prune(olderThan, max)`, `paused` (get/set), `close()`. Bound in the container while recording |
13
+ | `openStore(app)`, `pruneStore(app, store, now?)` | The store at `inspector.file`; prune with `inspector.keep` / `maxEntries` |
14
+ | `Recorder(app, store, options)` | `start()`, `flush()`, `stop()`; options `watch`, `ignorePaths`, `redact`, `slowQueryMs`, `slowRequestMs` |
15
+ | `Entry` | `{ id, kind, batchId?, originId?, traceId?, userId?, role?, createdAt, summary, tags, data }`; ids are UUIDv7 (they sort by time) |
16
+ | `redact(value, fragments?)` | The JSON-safe, redacted copy entries store |
17
+ | `describeEntry(kind, data, options)` | `{ summary, tags }` for lists and filters (`status:2xx`, `slow`, `failed`, `hit`, `miss`, a log level, a job status) |
18
+ | `IGNORED_PATHS` | Paths never recorded |
19
+ | `inspectorRoutes(router, store, path)` | The dashboard and its API (docs/README.md) |
20
+ | `KINDS` | Every kind, in the sidebar's order |
21
+ | `MUTATION_HEADER` | `x-cslug-inspector`: required (`1`) on clear and pause |
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@cslug/inspector",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.15.0",
4
+ "description": "A development-only dashboard for cslug apps: requests, exceptions, queries, logs, jobs, mail and more, with everything one request caused.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/cslugts/cslug.git",
10
+ "directory": "packages/inspector"
11
+ },
12
+ "homepage": "https://github.com/cslugts/cslug/tree/main/packages/inspector",
13
+ "keywords": [
14
+ "cslug",
15
+ "bun",
16
+ "framework",
17
+ "debug",
18
+ "devtools",
19
+ "inspector",
20
+ "development"
21
+ ],
22
+ "exports": {
23
+ ".": "./src/index.ts"
24
+ },
25
+ "files": [
26
+ "src",
27
+ "ui",
28
+ "docs",
29
+ "README.md"
30
+ ],
31
+ "engines": {
32
+ "bun": ">=1.3.14"
33
+ },
34
+ "peerDependencies": {
35
+ "@cslug/core": "0.15.0",
36
+ "@cslug/http": "0.15.0",
37
+ "@cslug/vue": "0.15.0"
38
+ },
39
+ "peerDependenciesMeta": {
40
+ "@cslug/vue": {
41
+ "optional": true
42
+ }
43
+ },
44
+ "devDependencies": {
45
+ "@cslug/testing": "workspace:*",
46
+ "@cslug/vue": "workspace:*"
47
+ }
48
+ }
package/src/index.ts ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @cslug/inspector: a development-only dashboard. Records what the app does, through core's `Instrumentation`, in
3
+ * `.cslug/inspector.sqlite`; does nothing at all unless `APP_ENV=development`.
4
+ */
5
+
6
+ export {
7
+ InspectorClearCommand,
8
+ type InspectorConfig,
9
+ InspectorProvider,
10
+ InspectorPruneCommand,
11
+ inspectorEnabled,
12
+ openStore,
13
+ pruneStore,
14
+ } from './provider'
15
+ export { IGNORED_PATHS, Recorder, type RecorderOptions } from './recorder'
16
+ export { redact } from './redact'
17
+ export { inspectorRoutes, KINDS, MUTATION_HEADER } from './routes'
18
+ export { type Entry, type EntryQuery, InspectorStore } from './store'
19
+ export { describeEntry } from './summary'
@@ -0,0 +1,136 @@
1
+ import { isAbsolute, join } from 'node:path'
2
+ import {
3
+ type Application,
4
+ Command,
5
+ type Duration,
6
+ flag,
7
+ type ObservationKind,
8
+ parseDuration,
9
+ ServiceProvider,
10
+ } from '@cslug/core'
11
+ import { Router } from '@cslug/http'
12
+ import { Recorder } from './recorder'
13
+ import { inspectorRoutes } from './routes'
14
+ import { InspectorStore } from './store'
15
+
16
+ export type InspectorConfig = {
17
+ /** Only ever on with `APP_ENV=development`; false turns it off there too. */
18
+ enabled?: boolean
19
+ /** Where the dashboard is served (default `/_inspector`). */
20
+ path?: string
21
+ /** The SQLite file, relative to the app (default `.cslug/inspector.sqlite`, git-ignored). */
22
+ file?: string
23
+ /** The kinds to record (default: all). */
24
+ watch?: ObservationKind[]
25
+ /** Request paths not recorded, with everything they did: prefixes (`/assets`) or globs (`/api/*\/ping`). */
26
+ ignore?: { paths?: string[] }
27
+ /** More key fragments whose values are never stored (on top of `password`, `token`, `secret`, `cookie`, …). */
28
+ redact?: string[]
29
+ /** How long entries are kept (default `24h`). */
30
+ keep?: Duration
31
+ /** At most this many entries (default 20 000). */
32
+ maxEntries?: number
33
+ /** A query slower than this is tagged `slow` (default 100). */
34
+ slowQueryMs?: number
35
+ /** A request slower than this is tagged `slow` (default 1000). */
36
+ slowRequestMs?: number
37
+ }
38
+
39
+ /**
40
+ * Whether the inspector runs: only with `APP_ENV=development` (never in test, staging or production, whatever the
41
+ * config says), unless `inspector.enabled` is false.
42
+ */
43
+ export function inspectorEnabled(app: Application): boolean {
44
+ return app.config('app.env') === 'development' && app.config('inspector.enabled') !== false
45
+ }
46
+
47
+ const config = (app: Application) => app.config<InspectorConfig | undefined>('inspector') ?? {}
48
+
49
+ /** The store for this app (`inspector.file`). */
50
+ export function openStore(app: Application): InspectorStore {
51
+ const file = config(app).file ?? '.cslug/inspector.sqlite'
52
+ return new InspectorStore(isAbsolute(file) ? file : join(app.rootDir, file))
53
+ }
54
+
55
+ /** Remove entries past `inspector.keep` and beyond `inspector.maxEntries`. */
56
+ export function pruneStore(app: Application, store: InspectorStore, now = Date.now()): number {
57
+ const c = config(app)
58
+ return store.prune(now - parseDuration(c.keep ?? '24h'), c.maxEntries ?? 20_000)
59
+ }
60
+
61
+ const HOUR = 3_600_000
62
+
63
+ /**
64
+ * The inspector: records what the app does (requests, exceptions, queries, logs, events, jobs, schedules, mail,
65
+ * notifications, cache, outgoing HTTP, views, AI runs) in `.cslug/inspector.sqlite`. In any environment but
66
+ * development it does nothing at all: nothing is observed, no file is opened.
67
+ */
68
+ export class InspectorProvider extends ServiceProvider {
69
+ private recorder?: Recorder
70
+ private store?: InspectorStore
71
+ private pruner?: ReturnType<typeof setInterval>
72
+
73
+ register() {
74
+ this.commands([InspectorClearCommand, InspectorPruneCommand])
75
+ }
76
+
77
+ boot() {
78
+ if (!inspectorEnabled(this.app)) return
79
+ const c = config(this.app)
80
+ this.store = openStore(this.app)
81
+ this.app.instance(InspectorStore, this.store)
82
+ pruneStore(this.app, this.store)
83
+ this.pruner = setInterval(() => this.store && pruneStore(this.app, this.store), HOUR)
84
+ this.pruner.unref?.()
85
+ const path = c.path ?? '/_inspector'
86
+ this.recorder = new Recorder(this.app, this.store, {
87
+ watch: c.watch,
88
+ ignorePaths: [path, ...(c.ignore?.paths ?? [])],
89
+ redact: c.redact,
90
+ slowQueryMs: c.slowQueryMs,
91
+ slowRequestMs: c.slowRequestMs,
92
+ })
93
+ this.recorder.start()
94
+ if (this.app.has(Router)) inspectorRoutes(this.app.resolve(Router), () => this.store ?? openStore(this.app), path)
95
+ }
96
+
97
+ shutdown() {
98
+ if (this.pruner) clearInterval(this.pruner)
99
+ this.recorder?.stop()
100
+ this.store?.close()
101
+ this.recorder = undefined
102
+ this.store = undefined
103
+ }
104
+ }
105
+
106
+ const unavailable = (cmd: Command) => {
107
+ cmd.error('The inspector runs only with APP_ENV=development (and inspector.enabled not false)')
108
+ return 1
109
+ }
110
+
111
+ /** `cslug inspector:clear`: delete every entry. */
112
+ export class InspectorClearCommand extends Command {
113
+ static signature = 'inspector:clear'
114
+ static description = 'Delete every inspector entry (development only)'
115
+
116
+ handle() {
117
+ if (!inspectorEnabled(this.app)) return unavailable(this)
118
+ const store = this.app.has(InspectorStore) ? this.app.resolve(InspectorStore) : openStore(this.app)
119
+ this.success(`${store.clear()} entries deleted`)
120
+ return 0
121
+ }
122
+ }
123
+
124
+ /** `cslug inspector:prune`: delete entries past `inspector.keep` / `inspector.maxEntries`. */
125
+ export class InspectorPruneCommand extends Command {
126
+ static signature = 'inspector:prune'
127
+ static description = 'Delete old inspector entries (inspector.keep, inspector.maxEntries)'
128
+ static args = { all: flag.boolean().describe('Delete every entry (same as inspector:clear)') }
129
+
130
+ handle({ all }: Command.Args<typeof InspectorPruneCommand>) {
131
+ if (!inspectorEnabled(this.app)) return unavailable(this)
132
+ const store = this.app.has(InspectorStore) ? this.app.resolve(InspectorStore) : openStore(this.app)
133
+ this.success(`${all ? store.clear() : pruneStore(this.app, store)} entries deleted`)
134
+ return 0
135
+ }
136
+ }
@@ -0,0 +1,272 @@
1
+ import {
2
+ type Application,
3
+ Cache,
4
+ currentContext,
5
+ Instrumentation,
6
+ Logger,
7
+ type Observation,
8
+ type ObservationBatch,
9
+ type ObservationKind,
10
+ } from '@cslug/core'
11
+ import { redact } from './redact'
12
+ import type { Entry, InspectorStore } from './store'
13
+ import { describeEntry } from './summary'
14
+
15
+ export type RecorderOptions = {
16
+ /** The kinds to record (default: all). */
17
+ watch?: readonly ObservationKind[]
18
+ /** Request paths not recorded, with everything they did: prefixes, or globs with `*`. */
19
+ ignorePaths?: readonly string[]
20
+ /** More key fragments to redact (on top of `password`, `token`, `secret`, …). */
21
+ redact?: readonly string[]
22
+ slowQueryMs?: number
23
+ slowRequestMs?: number
24
+ }
25
+
26
+ /** Paths never recorded: the inspector itself, the dev live-reload stream, health checks. */
27
+ export const IGNORED_PATHS = ['/_inspector', '/__cslug/live', '/health/', '/favicon.ico']
28
+ const FLUSH_MS = 250
29
+ const FLUSH_AT = 500
30
+
31
+ const matcher = (patterns: readonly string[]) => {
32
+ const tests = patterns.map((p) => {
33
+ if (!p.includes('*')) return (path: string) => path === p || path.startsWith(p.endsWith('/') ? p : `${p}/`)
34
+ // `**` crosses slashes, `*` stays within one segment
35
+ const segment = (s: string) => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*')
36
+ const re = new RegExp(`^${p.split('**').map(segment).join('.*')}$`)
37
+ return (path: string) => re.test(path)
38
+ })
39
+ return (path: string | undefined) => path !== undefined && tests.some((t) => t(path))
40
+ }
41
+
42
+ /**
43
+ * Turns what the packages report (`Instrumentation`) into entries: filtered, redacted, summarised, and written to
44
+ * the store in batches (every 250 ms), so a request never waits on the file. Also records log lines (a log target),
45
+ * cache operations (a `Cache` wrapper), outgoing `fetch` calls and rendered views (`onView`, with @cslug/vue).
46
+ */
47
+ export class Recorder {
48
+ private buffer: Entry[] = []
49
+ private stops: (() => void)[] = []
50
+ private timer?: ReturnType<typeof setInterval>
51
+ private readonly watch?: Set<ObservationKind>
52
+ private readonly ignored: (path: string | undefined) => boolean
53
+ private failed = false
54
+
55
+ constructor(
56
+ private readonly app: Application,
57
+ readonly store: InspectorStore,
58
+ private readonly options: RecorderOptions = {},
59
+ ) {
60
+ this.watch = options.watch ? new Set(options.watch) : undefined
61
+ this.ignored = matcher([...IGNORED_PATHS, ...(options.ignorePaths ?? [])])
62
+ }
63
+
64
+ start(): void {
65
+ const instrumentation = this.app.resolve(Instrumentation)
66
+ this.stops.push(instrumentation.observe((o) => this.record(o)))
67
+ this.recordLogs(instrumentation)
68
+ this.wrapCache(instrumentation)
69
+ this.wrapFetch(instrumentation)
70
+ void this.recordViews(instrumentation)
71
+ this.timer = setInterval(() => this.flush(), FLUSH_MS)
72
+ this.timer.unref?.()
73
+ }
74
+
75
+ /** Write what is buffered. */
76
+ flush(): void {
77
+ if (!this.buffer.length) return
78
+ const entries = this.buffer
79
+ this.buffer = []
80
+ try {
81
+ if (!this.store.paused) this.store.insert(entries)
82
+ } catch (error) {
83
+ // never through the logger: its lines are recorded too
84
+ if (!this.failed) process.stderr.write(`inspector: could not write entries: ${(error as Error).message}\n`)
85
+ this.failed = true
86
+ }
87
+ }
88
+
89
+ stop(): void {
90
+ if (this.timer) clearInterval(this.timer)
91
+ for (const stop of this.stops.splice(0).reverse()) stop()
92
+ this.flush()
93
+ }
94
+
95
+ private record(o: Observation): void {
96
+ if (this.watch && !this.watch.has(o.kind)) return
97
+ if (this.ignored(pathOf(o))) return
98
+ const data = redact(o.data, this.options.redact) as Record<string, unknown>
99
+ const { summary, tags } = describeEntry(o.kind, data, {
100
+ slowQueryMs: this.options.slowQueryMs ?? 100,
101
+ slowRequestMs: this.options.slowRequestMs ?? 1000,
102
+ })
103
+ this.buffer.push({
104
+ id: Bun.randomUUIDv7(),
105
+ kind: o.kind,
106
+ ...(o.requestId ? { batchId: o.requestId } : {}),
107
+ ...(o.originRequestId ? { originId: o.originRequestId } : {}),
108
+ ...(o.traceId ? { traceId: o.traceId } : {}),
109
+ ...(o.userId ? { userId: o.userId } : {}),
110
+ ...(o.role ? { role: o.role } : {}),
111
+ createdAt: o.at,
112
+ summary,
113
+ tags,
114
+ data,
115
+ })
116
+ if (this.buffer.length >= FLUSH_AT) this.flush()
117
+ }
118
+
119
+ /** Every log line (debug included), in the batch its line names. */
120
+ private recordLogs(instrumentation: Instrumentation): void {
121
+ let on = true
122
+ this.app.resolve(Logger).addTarget({
123
+ type: 'custom',
124
+ format: 'json',
125
+ level: 'debug',
126
+ write: (line) => {
127
+ if (!on) return
128
+ let fields: Record<string, unknown>
129
+ try {
130
+ fields = JSON.parse(line) as Record<string, unknown>
131
+ } catch {
132
+ return
133
+ }
134
+ const { time: _time, requestId, jobId, originRequestId, traceId, userId, spanId: _span, ...data } = fields
135
+ const batch: ObservationBatch = {}
136
+ if (typeof requestId === 'string') batch.requestId = requestId
137
+ if (typeof jobId === 'string') batch.jobId = jobId
138
+ if (typeof originRequestId === 'string') batch.originRequestId = originRequestId
139
+ if (typeof traceId === 'string') batch.traceId = traceId
140
+ if (userId !== undefined) batch.userId = String(userId)
141
+ instrumentation.report('log', () => data, batch)
142
+ },
143
+ })
144
+ // a logger cannot drop a target: this one goes quiet
145
+ this.stops.push(() => {
146
+ on = false
147
+ })
148
+ }
149
+
150
+ /** Cache reads and writes (keys and hit or miss, never values). */
151
+ private wrapCache(instrumentation: Instrumentation): void {
152
+ const cache = this.app.resolve(Cache)
153
+ const report = (operation: string, key: unknown, extra: Record<string, unknown> = {}) =>
154
+ instrumentation.report('cache', () => ({ operation, key, store: cache.constructor.name, ...extra }))
155
+ const wrapped = new Proxy(cache, {
156
+ get(target, prop) {
157
+ const value = Reflect.get(target, prop, target)
158
+ if (typeof value !== 'function') return value
159
+ const fn = value.bind(target) as (...args: unknown[]) => Promise<unknown>
160
+ switch (prop) {
161
+ case 'get':
162
+ return async (key: string) => {
163
+ const v = await fn(key)
164
+ report('get', key, { hit: v !== undefined })
165
+ return v
166
+ }
167
+ case 'has':
168
+ return async (key: string) => {
169
+ const v = await fn(key)
170
+ report('has', key, { hit: v === true })
171
+ return v
172
+ }
173
+ case 'set':
174
+ case 'forget':
175
+ case 'increment':
176
+ case 'decrement':
177
+ return async (key: string, ...rest: unknown[]) => {
178
+ const v = await fn(key, ...rest)
179
+ report(prop, key, prop === 'set' ? { ttl: rest[1] } : {})
180
+ return v
181
+ }
182
+ case 'flush':
183
+ return async () => {
184
+ await fn()
185
+ report('flush', undefined)
186
+ }
187
+ case 'remember':
188
+ return async (key: string, ttl: unknown, compute: () => unknown) => {
189
+ let computed = false
190
+ const v = await fn(key, ttl, () => {
191
+ computed = true
192
+ return compute()
193
+ })
194
+ report('remember', key, { hit: !computed, ttl })
195
+ return v
196
+ }
197
+ default:
198
+ return fn
199
+ }
200
+ },
201
+ })
202
+ this.app.instance(Cache, wrapped)
203
+ this.stops.push(() => {
204
+ this.app.instance(Cache, cache)
205
+ })
206
+ }
207
+
208
+ /** Outgoing `fetch` calls: method, URL, status, duration. */
209
+ private wrapFetch(instrumentation: Instrumentation): void {
210
+ const original = globalThis.fetch
211
+ const wrapped = Object.assign(
212
+ async (input: string | URL | Request, init?: RequestInit) => {
213
+ if (!instrumentation.active) return original(input, init)
214
+ const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase()
215
+ const url = input instanceof Request ? input.url : String(input)
216
+ const started = performance.now()
217
+ const ms = () => Math.round((performance.now() - started) * 10) / 10
218
+ try {
219
+ const res = await original(input, init)
220
+ instrumentation.report('http_client', () => ({
221
+ method,
222
+ url,
223
+ status: res.status,
224
+ ms: ms(),
225
+ requestHeaders: headerRecord(new Headers(init?.headers ?? (input instanceof Request ? input.headers : {}))),
226
+ responseHeaders: headerRecord(res.headers),
227
+ }))
228
+ return res
229
+ } catch (error) {
230
+ instrumentation.report('http_client', () => ({ method, url, ms: ms(), error: (error as Error).message }))
231
+ throw error
232
+ }
233
+ },
234
+ { preconnect: original.preconnect },
235
+ ) as typeof fetch
236
+ globalThis.fetch = wrapped
237
+ this.stops.push(() => {
238
+ if (globalThis.fetch === wrapped) globalThis.fetch = original
239
+ })
240
+ }
241
+
242
+ /** Pages rendered with `view()` (when @cslug/vue is installed). */
243
+ private async recordViews(instrumentation: Instrumentation): Promise<void> {
244
+ const vue = await import('@cslug/vue').catch(() => undefined)
245
+ if (!vue?.onView) return
246
+ const off = vue.onView((page, props) =>
247
+ instrumentation.report('view', () => ({
248
+ component:
249
+ (page as { name?: string; __name?: string }).name ?? (page as { __name?: string }).__name ?? 'anonymous',
250
+ file: (page as { __file?: string }).__file,
251
+ props,
252
+ })),
253
+ )
254
+ this.stops.push(off)
255
+ }
256
+ }
257
+
258
+ const headerRecord = (headers: Headers) => {
259
+ const out: Record<string, string> = {}
260
+ headers.forEach((value, name) => {
261
+ out[name] = value
262
+ })
263
+ return out
264
+ }
265
+
266
+ /** The request path an observation belongs to, to drop the inspector's own traffic and other ignored paths. */
267
+ function pathOf(o: Observation): string | undefined {
268
+ if ((o.kind === 'request' || o.kind === 'exception') && typeof o.data.path === 'string') return o.data.path
269
+ if (o.kind === 'log' && o.data.msg === 'request' && typeof o.data.path === 'string') return o.data.path
270
+ const http = currentContext()?.http as { request?: { path?: string } } | undefined
271
+ return http?.request?.path
272
+ }
package/src/redact.ts ADDED
@@ -0,0 +1,49 @@
1
+ import { DEFAULT_REDACT } from '@cslug/core'
2
+
3
+ /** Header names whose values are never stored (on top of keys matching the redaction fragments). */
4
+ const SECRET_HEADERS = ['authorization', 'proxy-authorization', 'cookie', 'set-cookie', 'x-csrf-token', 'x-api-key']
5
+ const STRING_LIMIT = 64 * 1024
6
+ const DEPTH_LIMIT = 8
7
+
8
+ /**
9
+ * A JSON-safe copy for storage: keys containing a redaction fragment (`password`, `token`, … plus yours) become
10
+ * `[redacted]`, as do secret headers; bigint → string, Date → ISO, Error → `{ name, message, stack }`, bytes → their
11
+ * size, long strings cut, cycles and deep nesting stopped.
12
+ */
13
+ export function redact(value: unknown, fragments: readonly string[] = []): unknown {
14
+ const keys = [...DEFAULT_REDACT, ...fragments].map((k) => k.toLowerCase())
15
+ const secret = (key: string) => {
16
+ const k = key.toLowerCase()
17
+ return SECRET_HEADERS.includes(k) || keys.some((f) => k.includes(f))
18
+ }
19
+ const seen = new WeakSet<object>()
20
+ const clean = (v: unknown, depth: number): unknown => {
21
+ if (v === null || v === undefined || typeof v === 'boolean' || typeof v === 'number') return v
22
+ if (typeof v === 'string')
23
+ return v.length > STRING_LIMIT ? `${v.slice(0, STRING_LIMIT)}… (${v.length} characters)` : v
24
+ if (typeof v === 'bigint') return v.toString()
25
+ if (typeof v === 'function' || typeof v === 'symbol') return undefined
26
+ if (v instanceof Date) return Number.isNaN(v.getTime()) ? null : v.toISOString()
27
+ if (v instanceof Error) return { name: v.name, message: v.message, stack: v.stack }
28
+ if (v instanceof Uint8Array || v instanceof ArrayBuffer) return `[${v.byteLength} bytes]`
29
+ if (typeof Blob !== 'undefined' && v instanceof Blob)
30
+ return `[${v instanceof File ? `file ${v.name}, ` : ''}${v.size} bytes]`
31
+ if (typeof v !== 'object') return String(v)
32
+ if (seen.has(v)) return '[circular]'
33
+ if (depth >= DEPTH_LIMIT) return '[…]'
34
+ seen.add(v)
35
+ try {
36
+ if (Array.isArray(v)) return v.map((item) => clean(item, depth + 1))
37
+ if (v instanceof Map) return clean(Object.fromEntries(v), depth)
38
+ if (v instanceof Set) return clean([...v], depth)
39
+ const json = (v as { toJSON?: () => unknown }).toJSON
40
+ if (typeof json === 'function') return clean(json.call(v), depth + 1)
41
+ const out: Record<string, unknown> = {}
42
+ for (const [k, item] of Object.entries(v)) out[k] = secret(k) ? '[redacted]' : clean(item, depth + 1)
43
+ return out
44
+ } finally {
45
+ seen.delete(v)
46
+ }
47
+ }
48
+ return clean(value, 0)
49
+ }