catchfn 0.0.2 → 0.1.2

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,280 +1,332 @@
1
- # CatchFn
1
+ <!-- Generated by scripts/bare-readme.mjs from front-door.template.md and the READMEs it includes; edit those and run `npm run readmes:bare`. -->
2
2
 
3
- > Self-hosted bug reporting and context collection for developers
3
+ # catchfn
4
4
 
5
- CatchFn is a lightweight SDK for capturing bug reports with rich context including breadcrumbs, console logs, network activity, and device information. It's designed to integrate seamlessly with your development workflow and the superfunctions ecosystem.
5
+ Console, network, breadcrumb, error and WebSocket collectors that record what happened in a
6
+ browser or Node process as versioned **evidence events**. The collectors run on
7
+ their own: no reporter client, widget or server is needed.
6
8
 
7
- ## Features
8
-
9
- - 🍞 **Breadcrumb Tracking** - Automatic navigation, console, and network breadcrumbs
10
- - 📝 **Console Capture** - Optional console log buffering
11
- - 🌐 **Network Monitoring** - Track HTTP requests with automatic header redaction
12
- - 🔒 **Data Redaction** - Built-in sensitive data protection
13
- - 🎣 **Hooks System** - `beforeSend` hooks for custom processing
14
- - 🚫 **Ignore Patterns** - Filter unwanted reports
15
- - 📦 **Size Limiting** - Automatic payload size optimization
16
- - 🔧 **TypeScript-First** - Full type safety and inference
17
-
18
- ## Installation
9
+ ## Install
19
10
 
20
11
  ```bash
21
12
  npm install catchfn
22
13
  ```
23
14
 
24
- ## Quick Start
25
-
26
- ```typescript
27
- import { catchFn } from "catchfn";
28
-
29
- // Initialize CatchFn
30
- const catcher = catchFn({
31
- name: "my-app",
32
- environment: "production",
33
- enableBreadcrumbs: true,
34
- enableConsoleCapture: true,
35
- enableNetworkCapture: false,
36
- });
37
-
38
- // Add breadcrumbs manually
39
- catcher.addBreadcrumb({
40
- type: "navigation",
41
- message: "User navigated to dashboard",
42
- data: { from: "/home", to: "/dashboard" },
43
- });
44
-
45
- // Capture a bug report
46
- const report = await catcher.captureBug({
47
- title: "Payment failed",
48
- description: "User encountered error during checkout",
49
- severity: "high",
50
- tags: ["payment", "checkout"],
51
- user: {
52
- id: "user-123",
53
- email: "user@example.com",
54
- },
55
- });
56
-
57
- console.log("Bug report ID:", report.id);
58
- ```
59
-
60
- ## Configuration
61
-
62
- ```typescript
63
- interface CatchFnConfig {
64
- // Required
65
- name: string;
66
-
67
- // Breadcrumbs
68
- enableBreadcrumbs?: boolean; // default: true
69
- maxBreadcrumbs?: number; // default: 50
70
-
71
- // Console capture
72
- enableConsoleCapture?: boolean; // default: false
73
- maxConsoleLogs?: number; // default: 100
74
-
75
- // Network capture
76
- enableNetworkCapture?: boolean; // default: false
77
- maxNetworkRequests?: number; // default: 20
78
-
79
- // Bug settings
80
- defaultSeverity?: "low" | "medium" | "high" | "critical"; // default: "medium"
81
- environment?: string;
82
- release?: string;
83
- user?: { id?: string; email?: string; [key: string]: any };
84
-
85
- // Hooks and filters
86
- beforeSend?: (event: BugReportEvent) => BugReportEvent | null;
87
- ignorePatterns?: (string | RegExp)[];
88
-
89
- // Size limits
90
- maxPayloadSize?: number; // default: 262144 (256KB)
91
- sensitiveFields?: string[]; // Additional fields to redact
92
- }
93
- ```
94
-
95
- ## Usage Examples
96
-
97
- ### Basic Bug Capture
98
-
99
- ```typescript
100
- await catcher.captureBug({
101
- title: "API request failed",
102
- description: "Failed to fetch user data",
103
- severity: "medium",
104
- tags: ["api", "network"],
105
- });
106
- ```
107
-
108
- ### With User Context
109
-
110
- ```typescript
111
- await catcher.captureBug({
112
- title: "Feature access denied",
113
- description: "User tried to access premium feature",
114
- severity: "low",
115
- user: {
116
- id: "user-123",
117
- email: "user@example.com",
118
- plan: "free",
119
- },
120
- metadata: {
121
- feature: "analytics-dashboard",
122
- requestedAt: new Date().toISOString(),
123
- },
124
- });
125
- ```
126
-
127
- ### Using beforeSend Hook
128
-
129
- ```typescript
130
- const catcher = catchFn({
131
- name: "my-app",
132
- beforeSend: (event) => {
133
- // Add custom data
134
- event.metadata = {
135
- ...event.metadata,
136
- buildNumber: "1.2.3",
137
- };
138
-
139
- // Filter internal users
140
- if (event.user?.email?.endsWith("@company.com")) {
141
- return null; // Drop the event
142
- }
143
-
144
- return event;
145
- },
146
- });
147
- ```
148
-
149
- ### Ignore Patterns
150
-
151
- ```typescript
152
- const catcher = catchFn({
153
- name: "my-app",
154
- ignorePatterns: ["ResizeObserver loop", /network.*timeout/i],
155
- });
156
-
157
- // This will be ignored
158
- await catcher.captureBug({
159
- title: "ResizeObserver loop limit exceeded",
160
- description: "Browser warning",
161
- });
162
- ```
163
-
164
- ### Manual Breadcrumbs
165
-
166
- ```typescript
167
- // Navigation
168
- catcher.addBreadcrumb({
169
- type: "navigation",
170
- message: "User navigated to settings",
171
- data: { from: "/dashboard", to: "/settings" },
172
- });
173
-
174
- // User interaction
175
- catcher.addBreadcrumb({
176
- type: "user",
177
- message: "Button clicked",
178
- data: { button: "submit-form" },
179
- });
180
-
181
- // Custom
182
- catcher.addBreadcrumb({
183
- type: "custom",
184
- message: "Payment processed",
185
- data: { amount: 99.99, currency: "USD" },
186
- level: "info",
187
- });
188
- ```
189
-
190
- ## API Reference
191
-
192
- ### `catchFn(config: CatchFnConfig)`
193
-
194
- Factory function to create a new CatchFn instance.
195
-
196
- ### `CatchFn.captureBug(options: CaptureBugOptions)`
197
-
198
- Capture a bug report with context.
199
-
200
- **Returns:** `Promise<BugReportEvent>`
201
-
202
- ### `CatchFn.addBreadcrumb(breadcrumb: Breadcrumb)`
203
-
204
- Manually add a breadcrumb.
205
-
206
- ### `CatchFn.beforeSend(hook: BeforeSendHook)`
207
-
208
- Register a beforeSend hook.
209
-
210
- ### `CatchFn.addIgnorePattern(pattern: IgnorePattern)`
211
-
212
- Add a pattern to ignore.
213
-
214
- ### `CatchFn.clear()`
215
-
216
- Clear all collected context (breadcrumbs, logs, network requests).
217
-
218
- ### `CatchFn.stop()`
219
-
220
- Stop all collectors (console, network interceptors).
221
-
222
- ### `CatchFn.getConfig()`
223
-
224
- Get the current configuration.
225
-
226
- ## Advanced Usage
227
-
228
- ### Using Collectors Directly
229
-
230
- ```typescript
231
- import { BreadcrumbCollector } from "catchfn";
232
-
233
- const breadcrumbs = new BreadcrumbCollector(100);
234
-
235
- breadcrumbs.addNavigation("/home", "/profile");
236
- breadcrumbs.addUser("click", "edit-button");
237
-
238
- const collected = breadcrumbs.collect();
239
- console.log(collected);
240
- ```
241
-
242
- ### Data Redaction
243
-
244
- ```typescript
245
- import { redactObject, redactUrl } from "catchfn";
15
+ `catchfn` has no runtime dependencies and runs in browsers and Node.js.
246
16
 
247
- const data = {
248
- username: "john",
249
- password: "secret123", // Will be redacted
250
- apiKey: "abc123", // Will be redacted
251
- };
17
+ ## Quick start
252
18
 
253
- const redacted = redactObject(data);
254
- // { username: "john", password: "[REDACTED]", apiKey: "[REDACTED]" }
255
-
256
- const url = redactUrl("https://api.example.com?token=secret&id=123");
257
- // "https://api.example.com?token=[REDACTED]&id=123"
258
- ```
19
+ ```ts
20
+ import { BreadcrumbCollector, ConsoleCollector, ErrorCollector, NetworkCollector, WebSocketCollector, validateEvidenceEvent } from "catchfn";
259
21
 
260
- ## Integration with WatchFn
22
+ const consoleCollector = new ConsoleCollector(100); // keeps the newest 100 events
23
+ const network = new NetworkCollector(20, { blockUrls: ["/health"] });
24
+ const breadcrumbs = new BreadcrumbCollector(50);
25
+ const errors = new ErrorCollector(50);
26
+ const sockets = new WebSocketCollector(100);
261
27
 
262
- CatchFn is designed to integrate with [WatchFn](../watchfn) for centralized bug tracking and analysis.
28
+ consoleCollector.start();
29
+ network.start();
30
+ errors.start();
31
+ sockets.start();
32
+ breadcrumbs.addNavigation("/cart", "/checkout");
263
33
 
264
- ```typescript
265
- import { catchFn } from "catchfn";
266
- // import { watchFn } from "watchfn"; // Future integration
34
+ // Later: the last 30 seconds of evidence, oldest first across collectors.
35
+ const since = Date.now() - 30_000;
36
+ const events = [consoleCollector, network, breadcrumbs, errors, sockets]
37
+ .flatMap((collector) => collector.collect({ since }))
38
+ .sort((a, b) => a.timestamp - b.timestamp || a.seq - b.seq);
267
39
 
268
- const catcher = catchFn({
269
- name: "my-app",
270
- // watchfnClient: watch, // Future: send events to watchfn
271
- });
40
+ consoleCollector.stop();
41
+ network.stop();
42
+ errors.stop();
43
+ sockets.stop();
272
44
  ```
273
45
 
274
- ## License
275
-
276
- MIT © 21n
277
-
278
- ## Contributing
279
-
280
- See the main [superfunctions repository](https://github.com/21nCo/super-functions) for contribution guidelines.
46
+ ## Evidence events v1
47
+
48
+ Every event has `schemaVersion: 1`, a `kind` (`"console"`, `"network"`,
49
+ `"breadcrumb"`, `"error"` or `"websocket"`), a `seq` capture-order number and a `timestamp` in epoch
50
+ milliseconds, plus the fields of its kind. The format is closed: extra fields
51
+ are invalid. Check an event with `validateEvidenceEvent(event)` (returns a list
52
+ of problems, empty when valid) or with any JSON Schema 2020-12 validator and
53
+ the exported `evidenceEventSchema`. Integer fields (`seq`, `timestamp`,
54
+ `status`, `lineno`, `colno`, `size`, `code`) are safe integers in both, and nested records (`data`, header
55
+ records, objects in `args`) must be plain or null-prototype objects without a
56
+ callable `toJSON`.
57
+
58
+ | kind | fields |
59
+ | --- | --- |
60
+ | `console` | `level` (`log`, `info`, `warn`, `error`, `debug`), `args` |
61
+ | `network` | `transport` (`fetch`, `xhr`), `method`, `url`, optional `status`, `statusText`, `duration`, `requestHeaders`, `responseHeaders` |
62
+ | `breadcrumb` | `type` (`navigation`, `console`, `network`, `user`, `custom`), optional `message`, `data`, `category`, `level` (`debug`, `info`, `warning`, `error`) |
63
+ | `error` | `source` (`error`, `unhandledrejection`), `message`, optional `name`, `stack`, `filename`, `lineno`, `colno`, `value` |
64
+ | `websocket` | `type` (`open`, `message`, `close`, `error`), `url`, optional `direction` (`sent`, `received`) and `size` (messages), `code` and `wasClean` (close) |
65
+
66
+ Captured events are frozen.
67
+
68
+ ## Time-window queries
69
+
70
+ Each collector keeps its events in a fixed-size ring buffer (the constructor's
71
+ `maxSize`; `0` keeps nothing) and `collect({ since, until })` returns the
72
+ buffered events whose `timestamp` lies in the **inclusive** window, oldest
73
+ first. Either bound may be omitted, `since > until` matches nothing, and a
74
+ `NaN` or non-number bound throws a `RangeError`.
75
+
76
+ ## Patching and `stop()`
77
+
78
+ `ConsoleCollector` wraps `console.log/info/warn/error/debug`; `NetworkCollector`
79
+ wraps `fetch` and `XMLHttpRequest.prototype.open/send`. Overlapping collectors
80
+ share one set of wrappers. `stop()` on the last running collector restores
81
+ exactly the functions that were replaced, but only where its own wrapper is
82
+ still installed: if another library wrapped them after `start()`, the catchfn
83
+ wrapper stays in that chain, passes calls through and records nothing.
84
+
85
+ The network collector never changes the application's request: the original
86
+ arguments pass through untouched (a `null` or `undefined` receiver of `fetch`
87
+ becomes `globalThis`), and observation never runs the application's
88
+ iterators, getters or conversions (except the fulfilled value's `then` read
89
+ described below). The page's `fetch` and
90
+ `XMLHttpRequest.prototype.open` run first. Before they run, observation reads
91
+ only a string URL argument, or a platform `URL` argument through the `href`
92
+ getter captured when catchfn loads. The `URL` is read only where that
93
+ getter's brand check runs no Proxy trap, which a probe checks at load.
94
+ Browsers and current Node check an internal slot, which runs none. On Node
95
+ 18.17 the brand check runs a trap, so there a `URL` argument is recorded as
96
+ `[UNREAD_URL]`. A `Request`, `init` or headers
97
+ argument is read only after the call returns, and `send` reads nothing from
98
+ its arguments. A native `fetch`, or a wrapper that calls one synchronously,
99
+ has read the request by then. The application's own arguments and results
100
+ are read through the `URL`, `Request`, `Response`, `Headers`, `Promise`,
101
+ `XMLHttpRequest` and `EventTarget` getters and methods captured at load, so a
102
+ patch the page makes to those later never runs on them. Two exceptions:
103
+
104
+ - An `XMLHttpRequest` defined or replaced after catchfn loads has its getters
105
+ captured when `start()` installs the wrappers.
106
+ - Redacting the captured URL string after the call uses the live `URL` and
107
+ `URLSearchParams` API (see Redaction), so a page that patches it can run
108
+ code at that point.
109
+
110
+ Known limit, deferred to SFNS-60 (SFNS-56 owner scope amendment of
111
+ 2026-11-13): no script can tell a Proxy apart, so a stateful Proxy `init` or
112
+ headers object can observe the reads made after the call. Attribution can be
113
+ wrong after the input is consumed through a `fetch` installed before `start()`
114
+ that defers the native call, or through a reused `init` or `Request`,
115
+ including values an earlier wrapper changed.
116
+
117
+ When the page's `fetch` returns a plain platform `Promise` (not a subclass,
118
+ with no own properties, while `Promise.prototype.constructor` and
119
+ `Promise[Symbol.species]` are still the platform's), `fetch` returns a
120
+ promise derived from it through the `Promise.prototype.then` captured at load
121
+ (SFNS-56 owner amendment of 2026-11-14). It settles with the same value or
122
+ reason one microtask later and carries the application's rejection handling:
123
+ a rejection the application leaves unhandled is reported once, with the
124
+ original reason, and a handled one is not reported. Observation records
125
+ `status`, `statusText`, `duration` and response headers from it and never
126
+ raises. Only that promise's identity changes. Two limits follow from deriving
127
+ a native promise, and no script can avoid them:
128
+
129
+ - Resolving the derived promise reads the page value's `then`, as resolving
130
+ any promise does. A platform `Response` has none, unless the page adds one
131
+ (on the response, `Response.prototype` or `Object.prototype`); a callable
132
+ one is then adopted.
133
+ - Only handlers on the returned promise count. A rejection handled solely on
134
+ the page's own promise (by a `fetch` wrapper installed before `start()`, or
135
+ on a shared promise) is reported as unhandled if the caller drops the
136
+ returned promise.
137
+
138
+ Any other result (a custom thenable, a `Promise` subclass, a promise with own
139
+ properties, or any promise once the page replaced Promise's `constructor` or
140
+ species) is returned unchanged, its `then` is never called by catchfn, and
141
+ it is recorded when the call is made, without `status` or `duration`. A
142
+ stopped wrapper reads nothing at all. What observation then records:
143
+
144
+ - `init.headers` is captured only from a platform `Headers` object (not a
145
+ subclass, and only while neither it nor `Headers.prototype` has a replaced
146
+ iterator), a plain array of `[name, value]` string pairs or a plain record
147
+ of string data properties. Any other form (a generator, `Map.entries()`, an
148
+ accessor, a custom iterator, a non-string value, more than 200 pairs) is
149
+ not read and the request is recorded without `requestHeaders`. The headers
150
+ of a `Request` input and of the response are read from the platform's own
151
+ header list, so a replaced `Headers` iterator does not affect them. On a
152
+ runtime whose `Headers.prototype.forEach` runs the iterator (Node 18.17,
153
+ probed at load), no headers are recorded while the iterator is replaced.
154
+ - `init.method` and `init.headers` are read only from own data properties.
155
+ - The URL is read from a string, a platform `URL` (only where the load-time
156
+ probe found its `href` brand check trap-free) or a platform `Request`;
157
+ any other input is recorded as `"[UNREAD_URL]"` (`UNREAD_URL`), and a method
158
+ that is not a string as `"[UNREAD_METHOD]"` (`UNREAD_METHOD`).
159
+
160
+ The captured URL goes through `redactUrl` and the captured headers through
161
+ `redactHeaders`.
162
+
163
+ ### Errors
164
+
165
+ `ErrorCollector` adds `error` and `unhandledrejection` listeners to the
166
+ global (the window, or a worker's global scope) and removes them on the last
167
+ `stop()`; it replaces nothing and never cancels an event, so the page's own
168
+ handlers and the browser's console report run as before. Where the global is
169
+ not an event target (plain Node) it records nothing. The listeners go on
170
+ through the `EventTarget` methods captured at load, or, where the global is
171
+ not a platform event target but has its own `addEventListener` (a test
172
+ environment such as Vitest's jsdom, which copies a window's members onto
173
+ Node's global), through that method. There a running collector counts as a
174
+ page error listener, so the environment no longer fails a test on an
175
+ uncaught error while it runs.
176
+
177
+ - An uncaught error is read from a platform `ErrorEvent` through the getters
178
+ captured at load: `message` is the browser's text (`"Uncaught Error: boom"`)
179
+ when it has one, `filename` goes through `redactUrl`, and `lineno` and
180
+ `colno` are kept. An `error` event that is not an `ErrorEvent` (one the page
181
+ dispatches itself) is ignored.
182
+ - An unhandled rejection's reason is read through the captured
183
+ `PromiseRejectionEvent` getter, and an `unhandledrejection` event that is
184
+ not a `PromiseRejectionEvent` is ignored. Only on a runtime without that
185
+ class is the reason read from the event's own `reason` data property.
186
+ - A thrown value or reason that is an `Error` gives `name`, `message` and
187
+ `stack`, serialized as one entry; reading them can run the error's own
188
+ getters, as for a console argument. Each URL in the stack goes through
189
+ `redactUrl`, keeping its `:line:column` suffix. Any other value is serialized into
190
+ `value`, and `message` holds it as text (a string as is, anything else as
191
+ its JSON). An uncaught error whose `ErrorEvent.error` is `null` or
192
+ `undefined` has no `value`: a cross-origin `"Script error."` and an
193
+ uncaught `throw null` or `throw undefined` look the same there, and only the
194
+ browser's `message` tells them apart. A rejection keeps a `null` or
195
+ `undefined` reason in `value`.
196
+
197
+ ### WebSockets
198
+
199
+ `WebSocketCollector` replaces the global `WebSocket` with a `Proxy` of the
200
+ page's class (statics, `prototype`, `instanceof` and subclassing keep
201
+ working) and wraps the `send` its sockets inherit, on the prototype that
202
+ defines it (`WebSocket.prototype`, also when the global is a subclass); the last `stop()` restores
203
+ both where its own wrapper is still installed, as above. Every target is
204
+ resolved before anything is replaced, so `start()` never throws: a global it
205
+ cannot replace (or a failure part way) is rolled back, a wrapper it cannot
206
+ remove is left inert, and the collector records nothing. Each restore runs on its own, so one that throws
207
+ does not stop the others. Only sockets constructed while a collector runs
208
+ are observed: the constructor adds `open`, `message`, `close` and `error`
209
+ listeners before the page can add its own. They are removed after the
210
+ socket's `close` event and from every socket on the last `stop()`; the
211
+ page's own listeners stay and the socket is never closed. Sockets are held
212
+ only weakly, so a running collector never keeps one alive, also one that
213
+ fails without a `close` event. A restart observes
214
+ new sockets only. A class that extended `WebSocket` before `start()`
215
+ constructs through the page's own class and is not observed.
216
+
217
+ - Messages record their direction and their size in bytes: a string's UTF-8
218
+ length (counted with the `String.prototype.charCodeAt` captured at load),
219
+ or the size of an `ArrayBuffer`, typed array, `DataView` or `Blob`
220
+ through the platform getters captured at load, each used only when a
221
+ probe at load shows its brand check runs no `Proxy` trap. A browser's
222
+ `Blob` getter qualifies; Node's reads a symbol property, which runs a
223
+ trap, so on Node a `Blob` is recorded without `size`. Another payload
224
+ type is recorded without `size`. The payload itself is never recorded.
225
+ - `send()` on a socket constructed while no collector ran is passed straight
226
+ to the page's `send`, unobserved. On an observed socket the page's `send`
227
+ always receives the caller's arguments unchanged, and observing it runs
228
+ no page code. Before it only the socket's membership and `readyState`,
229
+ the clock, and the length of an `ArrayBuffer`, typed array or `DataView`
230
+ are read (a library's `send` may transfer the buffer, detaching it). A
231
+ `Blob` and a string are sized after the `send` returns; `readyState` is
232
+ read again only for an object the platform's own `send` converts (below).
233
+ - Only a `send()` on an open socket is recorded, its `readyState` read
234
+ before the call through the getter captured at load: the platform throws
235
+ while connecting (it still throws) and discards the data once the socket
236
+ is closing or closed (nothing is recorded). A `send` that transmits and
237
+ then closes the socket is recorded. An object other than binary data (a
238
+ bare `SharedArrayBuffer` included) is converted by the `send` itself,
239
+ which can run page code that closes the socket and discards the data, and
240
+ is recorded without `size`. Through the platform's own `send` (the one the
241
+ `WebSocket` at load defines; a replacement installed on its prototype
242
+ before catchfn loads counts as it), which never closes a socket itself,
243
+ such an object is recorded only if the socket is still open after the call.
244
+ Through a library's or subclass's `send` the collector cannot tell that
245
+ discard from a library that transmits and then closes, so the state
246
+ before the call decides and such a discard is recorded as sent.
247
+ - Event attributes are read only through the platform getters. A `message`
248
+ or `close` event the page dispatches on a socket itself, which is not a
249
+ platform `MessageEvent` or `CloseEvent`, is ignored where the runtime has
250
+ that class. Only on a runtime without the class (or for a stand-in socket
251
+ class without a `url` or `readyState` getter) is the attribute read from
252
+ an own data property; a getter there is never run.
253
+ - In a browser window or worker, which fires socket events trusted, an
254
+ untrusted event (`isTrusted` false, read through the platform getter) is
255
+ ignored, whatever its type. Node fires its socket events untrusted, so
256
+ there `isTrusted` is not checked; instead, on every runtime, an `open` is
257
+ recorded once and only on a socket whose `readyState` is open (or
258
+ closing, when an earlier listener closed it during the event), and a
259
+ `close` only on a socket whose `readyState` is closed. A page-dispatched
260
+ `error` event is not detected on Node.
261
+ - `url` is the socket's `url` attribute (through the getter captured at load
262
+ when the global class inherits from the platform's) through `redactUrl`. A close
263
+ event records `code` and `wasClean` through the `CloseEvent` getters
264
+ captured at load. On a runtime without a global `CloseEvent` (Node 22),
265
+ whose close events keep them in getters, they are omitted rather than read
266
+ through a getter that cannot be verified. Its `reason` is not recorded.
267
+ - A refused handshake fires `error`; browsers and Node 24 then fire a
268
+ `close` with code 1006, which Node 22 omits. The collector records what
269
+ the runtime emits.
270
+ - A recorded `size` is always a nonnegative safe integer; a size a platform
271
+ getter reports as anything else is omitted and the event kept.
272
+ - `start()` reentered while it installs (page code run by reading the global
273
+ or adding a listener) is a no-op, and a `stop()` during that install leaves
274
+ the session at once: a socket constructed meanwhile is never observed, also
275
+ after a restart. Each collector holds at most one subscription.
276
+ - Timestamps of the error and WebSocket collectors come from the `Date.now`
277
+ captured at load. An observation whose clock gives anything but a
278
+ nonnegative safe integer is dropped; the event or send itself is unchanged.
279
+ Loading never throws: with no `Date.now` to capture then (a throwing
280
+ accessor, or none), every observation is dropped.
281
+
282
+ Known limit, deferred to SFNS-60 (SFNS-57 owner decision of 2026-11-19):
283
+ against hostile same-realm page code (patched intrinsics such as `Set`
284
+ methods, accessor-backed sockets or payloads, Proxies, forwarding
285
+ library `send` methods), WebSocket send evidence is best-effort. Such code
286
+ can make a `send` the platform discarded be recorded as sent, run while a
287
+ send is observed, start a collector that then receives a send already under
288
+ way, or report a binary size that differs from what the platform sent. These
289
+ stay guaranteed: `send()` behaves as without the collector, collectors never
290
+ throw, every event is valid v1, `stop()` restores everything, and each
291
+ instance holds one subscription.
292
+
293
+ ## Serialization
294
+
295
+ Captured values are snapshotted under a closed set of forms:
296
+
297
+ - JSON primitives (strings, finite numbers, booleans, `null`) are kept;
298
+ - `Error` becomes `{ name, message, stack, ...own properties }`;
299
+ - plain objects and arrays are copied at most 5 container levels deep (deeper
300
+ containers become `"[Max Depth]"`) with at most 200 keys or items each,
301
+ a truncation marker included;
302
+ - a container that refers back to one of its ancestors becomes `"[Circular]"`;
303
+ - DOM nodes become `"<tag#id.class>"`;
304
+ - everything else becomes `String(value)`, or `"[Unserializable]"` when that
305
+ conversion throws.
306
+
307
+ One entry is at most 10 KB of UTF-8 JSON; strings are cut and containers stop
308
+ early with a `"[Truncated]"` marker (the last array item, or a record key
309
+ whose value counts the omitted keys; `"[Truncated 2]"`, ... when the record
310
+ already holds that key). A console event's argument list is one
311
+ entry, and each argument counts its depth from 1. A breadcrumb's `data` and
312
+ `message`, a network event's `url` and each header record, an error event's
313
+ `message`, `filename` and thrown value (an `Error`'s name, message and stack
314
+ together, or `value`), and a websocket event's `url`, are entries.
315
+
316
+ ## Redaction
317
+
318
+ - `redactUrl(url)` removes authority credentials, replaces sensitive query
319
+ values (`token`, `key`, `secret`, `password`, `api_key`, `access_token`,
320
+ `auth`, case-insensitive) with `[REDACTED]`, redacts a fragment that names a
321
+ token, secret, password or API key, keeps relative URLs relative and returns
322
+ `[REDACTED_URL]` for a URL it cannot parse.
323
+ - `redactHeaders(headers)` redacts `authorization`, `cookie`, `set-cookie`,
324
+ `x-api-key`, `x-auth-token` and `x-access-token`, case-insensitive.
325
+ - `redactObject(value)` snapshots a value and redacts keys that name secrets,
326
+ plus URLs under `url`/`href` keys; the redacted result keeps the 10 KB bound.
327
+ - `redactString(text)` masks card numbers.
328
+
329
+ ## Packages
330
+
331
+ `catchfn` is the whole product: the collectors, the evidence event schema and validator, and the redaction helpers
332
+ all ship in this one package, with no scoped packages to install alongside it.