@backtrack-js/browser 0.5.1 → 0.5.3
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 +30 -483
- package/dist/capturers/console.d.ts +0 -1
- package/dist/capturers/errors.d.ts +0 -1
- package/dist/capturers/index.d.ts +0 -1
- package/dist/capturers/navigation.d.ts +0 -1
- package/dist/capturers/network.d.ts +0 -1
- package/dist/capturers/performance.d.ts +0 -1
- package/dist/capturers/route-matcher.d.ts +0 -1
- package/dist/capturers/rrweb.d.ts +0 -1
- package/dist/capturers/sanitizer.d.ts +0 -1
- package/dist/core/flight-recorder.d.ts +0 -1
- package/dist/core/state-machine.d.ts +0 -1
- package/dist/dev-server/index.d.ts +0 -1
- package/dist/dev-server/middleware.d.ts +0 -1
- package/dist/dev-server.cjs +0 -1
- package/dist/dev-server.js +0 -1
- package/dist/index.cjs +6 -7
- package/dist/index.d.ts +0 -1
- package/dist/index.js +628 -608
- package/dist/markdown-Ao5Ah9MF.cjs +0 -1
- package/dist/markdown-D3C94OlY.js +0 -1
- package/dist/storage/batch-writer.d.ts +0 -1
- package/dist/storage/db.d.ts +0 -1
- package/dist/storage/incident-manager.d.ts +0 -1
- package/dist/storage/index.d.ts +0 -1
- package/dist/storage/retention.d.ts +0 -1
- package/dist/storage/session.d.ts +0 -1
- package/dist/types/artifact.d.ts +0 -1
- package/dist/types/chunk.d.ts +0 -1
- package/dist/types/health.d.ts +0 -1
- package/dist/types/incident.d.ts +1 -1
- package/dist/types/index.d.ts +0 -1
- package/dist/types/options.d.ts +0 -1
- package/dist/types/timeline.d.ts +0 -1
- package/dist/types/transport.d.ts +0 -1
- package/dist/utils/compression.d.ts +0 -1
- package/dist/utils/gist-uploader.d.ts +0 -1
- package/dist/utils/markdown.d.ts +0 -1
- package/dist/validation/validate.d.ts +0 -1
- package/dist/viewer/assets/index-092olPra.css +1 -0
- package/dist/viewer/assets/index-BkV3C4kX.js +197 -0
- package/dist/viewer/index.html +2 -2
- package/dist/widget/annotator.d.ts +0 -1
- package/dist/widget/styles.d.ts +0 -1
- package/dist/widget/widget.d.ts +0 -1
- package/package.json +15 -4
- package/dist/capturers/console.d.ts.map +0 -1
- package/dist/capturers/errors.d.ts.map +0 -1
- package/dist/capturers/index.d.ts.map +0 -1
- package/dist/capturers/navigation.d.ts.map +0 -1
- package/dist/capturers/network.d.ts.map +0 -1
- package/dist/capturers/performance.d.ts.map +0 -1
- package/dist/capturers/route-matcher.d.ts.map +0 -1
- package/dist/capturers/rrweb.d.ts.map +0 -1
- package/dist/capturers/sanitizer.d.ts.map +0 -1
- package/dist/core/flight-recorder.d.ts.map +0 -1
- package/dist/core/state-machine.d.ts.map +0 -1
- package/dist/dev-server/index.d.ts.map +0 -1
- package/dist/dev-server/middleware.d.ts.map +0 -1
- package/dist/dev-server.cjs.map +0 -1
- package/dist/dev-server.js.map +0 -1
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/markdown-Ao5Ah9MF.cjs.map +0 -1
- package/dist/markdown-D3C94OlY.js.map +0 -1
- package/dist/storage/batch-writer.d.ts.map +0 -1
- package/dist/storage/db.d.ts.map +0 -1
- package/dist/storage/incident-manager.d.ts.map +0 -1
- package/dist/storage/index.d.ts.map +0 -1
- package/dist/storage/retention.d.ts.map +0 -1
- package/dist/storage/session.d.ts.map +0 -1
- package/dist/types/artifact.d.ts.map +0 -1
- package/dist/types/chunk.d.ts.map +0 -1
- package/dist/types/health.d.ts.map +0 -1
- package/dist/types/incident.d.ts.map +0 -1
- package/dist/types/index.d.ts.map +0 -1
- package/dist/types/options.d.ts.map +0 -1
- package/dist/types/timeline.d.ts.map +0 -1
- package/dist/types/transport.d.ts.map +0 -1
- package/dist/utils/compression.d.ts.map +0 -1
- package/dist/utils/gist-uploader.d.ts.map +0 -1
- package/dist/utils/markdown.d.ts.map +0 -1
- package/dist/validation/validate.d.ts.map +0 -1
- package/dist/viewer/assets/index-C3SZvpLL.js +0 -197
- package/dist/viewer/assets/index-CKVr0pQ5.css +0 -1
- package/dist/widget/annotator.d.ts.map +0 -1
- package/dist/widget/styles.d.ts.map +0 -1
- package/dist/widget/widget.d.ts.map +0 -1
package/README.md
CHANGED
|
@@ -1,507 +1,54 @@
|
|
|
1
|
-
# Backtrack
|
|
1
|
+
# Backtrack JS
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Flight recorder para aplicações web: captura uma janela recente da sessão, salva incidentes localmente e ajuda a investigar replay, rede e stack traces.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
[](LICENSE)
|
|
5
|
+
## Instalação
|
|
7
6
|
|
|
8
|
-
|
|
9
|
-
<!--  -->
|
|
10
|
-
|
|
11
|
-
Your users hit a bug you can't reproduce. Error trackers tell you what broke, but not what the user did before it did.
|
|
12
|
-
|
|
13
|
-
Backtrack keeps the last few minutes of DOM changes, clicks, network calls, console logs and errors in a rolling local buffer. When something breaks (or the user asks for help), it freezes that buffer into a replayable incident file. Open it in the built-in viewer and press play.
|
|
14
|
-
|
|
15
|
-
- **Private by default.** Passwords, card numbers, CPFs and form inputs are masked. Request and response bodies are off unless you turn them on. Nothing leaves the browser unless you export an incident or configure a transport.
|
|
16
|
-
- **Light on the page.** Recording runs into a ring buffer in IndexedDB with automatic retention, so old events are dropped instead of piling up.
|
|
17
|
-
- **Framework-agnostic.** Pure TypeScript core, no React or other framework in your client bundle. ESM and CommonJS builds.
|
|
18
|
-
- **Replay offline.** An interactive viewer with DOM playback, a synchronized timeline, and console and network panels. No account, no server.
|
|
19
|
-
- **Readable production stack traces.** `backtrack symbolize` maps minified frames like `app.min.js:1:48213` back to your original TypeScript, with the surrounding source lines.
|
|
20
|
-
- **Zero-friction local debugging & AI agents.** Automatic dev-server export saves structured Markdown reports (`.backtrack/latest.md`) and full replays straight to your project disk upon error—no manual downloads or copy-pasting required.
|
|
21
|
-
- **Send it where you want.** `transport` and `beforeSend` let you forward incidents to your own backend or observability stack.
|
|
22
|
-
|
|
23
|
-
---
|
|
24
|
-
|
|
25
|
-
## Why Backtrack?
|
|
26
|
-
|
|
27
|
-
| Feature | Error trackers | Hosted session replay | Backtrack |
|
|
28
|
-
| :--- | :---: | :---: | :---: |
|
|
29
|
-
| Shows the error and stack trace | ✅ | ✅ | ✅ |
|
|
30
|
-
| Shows what the user did before it | ⚠️ limited breadcrumbs | ✅ | ✅ |
|
|
31
|
-
| Data stays in the browser by default | ❌ | ❌ | ✅ |
|
|
32
|
-
| Works fully offline | ❌ | ❌ | ✅ |
|
|
33
|
-
| Only records around incidents | n/a | ❌ usually continuous upload | ✅ rolling buffer |
|
|
34
|
-
|
|
35
|
-
Backtrack doesn't replace your error tracker. It gives you the context your error tracker is missing, and you can correlate the two with `traceId` and `release` (see [Release and trace correlation](#release-and-trace-correlation)).
|
|
36
|
-
|
|
37
|
-
---
|
|
38
|
-
|
|
39
|
-
## Installation
|
|
40
|
-
|
|
41
|
-
```bash
|
|
42
|
-
# npm
|
|
7
|
+
```sh
|
|
43
8
|
npm install @backtrack-js/browser
|
|
44
|
-
|
|
45
|
-
# yarn
|
|
46
|
-
yarn add @backtrack-js/browser
|
|
47
|
-
|
|
48
|
-
# pnpm
|
|
49
|
-
pnpm add @backtrack-js/browser
|
|
50
9
|
```
|
|
51
10
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
## Quick Start
|
|
11
|
+
Inicialize uma vez no cliente:
|
|
55
12
|
|
|
56
13
|
```typescript
|
|
57
14
|
import { Backtrack } from '@backtrack-js/browser';
|
|
58
15
|
|
|
59
|
-
|
|
60
|
-
bufferMinutes: 5,
|
|
61
|
-
|
|
16
|
+
void Backtrack.init({
|
|
17
|
+
bufferMinutes: 5,
|
|
18
|
+
showWidget: true,
|
|
19
|
+
network: { capturePayloads: false }
|
|
20
|
+
}).catch(error => {
|
|
21
|
+
console.warn('Backtrack não pôde iniciar', error);
|
|
62
22
|
});
|
|
63
|
-
|
|
64
|
-
await recorder.start();
|
|
65
|
-
|
|
66
|
-
// Optional: capture manually, e.g. from a "Report a problem" button
|
|
67
|
-
const incidentId = await recorder.capture('User reported payment bug', 30);
|
|
68
23
|
```
|
|
69
24
|
|
|
70
|
-
|
|
25
|
+
O widget permite salvar uma gravação. Abra o artefato no visualizador para investigar. A biblioteca não envia gravações para um servidor por padrão.
|
|
71
26
|
|
|
72
|
-
|
|
73
|
-
npx backtrack
|
|
74
|
-
```
|
|
27
|
+
## Documentação
|
|
75
28
|
|
|
76
|
-
|
|
29
|
+
[English documentation](site/docs/content/en/overview.md) · [Português](site/docs/content/pt/overview.md)
|
|
77
30
|
|
|
78
|
-
|
|
31
|
+
- [Primeiros passos](site/docs/content/pt/quickstart.md) e [integrações](site/docs/content/pt/integrations.md).
|
|
32
|
+
- [Configuração](site/docs/content/pt/configuration.md), [privacidade e sanitização](site/docs/content/pt/privacy.md), [rede e disparos automáticos](site/docs/content/pt/network.md).
|
|
33
|
+
- [Visualizador](site/docs/content/pt/viewer.md), [source maps](site/docs/content/pt/source-maps.md), [exportação local](site/docs/content/pt/local-export.md) e [transportes](site/docs/content/pt/transport.md).
|
|
34
|
+
- [Referência da API](site/docs/content/pt/api.md), [solução de problemas](site/docs/content/pt/troubleshooting.md) e [versões e limitações](site/docs/content/pt/releases.md).
|
|
79
35
|
|
|
80
|
-
|
|
36
|
+
Os guias descrevem o contrato local da versão 0.5.1. Recursos ainda não implementados são identificados explicitamente. Dados sintéticos não desativam automaticamente a sanitização fixa.
|
|
81
37
|
|
|
82
|
-
|
|
38
|
+
## Desenvolvimento
|
|
83
39
|
|
|
84
|
-
```
|
|
85
|
-
|
|
40
|
+
```sh
|
|
41
|
+
npm install
|
|
42
|
+
npm run build
|
|
43
|
+
npm run build:viewer
|
|
44
|
+
npm run build:site
|
|
45
|
+
npm run preview:site
|
|
86
46
|
```
|
|
87
47
|
|
|
88
|
-
|
|
89
|
-
| :--- | :--- |
|
|
90
|
-
| `<incident>` | Path to an exported incident: `.json`, `.ffr.json`, `.gz` or `.ffr.json.gz`. Gzip is detected automatically. |
|
|
91
|
-
| `--sourcemaps <directory>` | Directory containing your `.js.map`, `.mjs.map` and `.cjs.map` files. Searched recursively (e.g. `./dist`, `./build`). |
|
|
92
|
-
| `--output <file>` | Custom output path. Defaults to `<name>.symbolicated.ffr.json` next to the original. The output can never overwrite the input file. |
|
|
93
|
-
| `--release <id>` | Build or release identifier. Validates against the incident's recorded release (if present), warning on mismatch. |
|
|
94
|
-
| `--context-lines <number>` | Lines of original source shown before and after the failing line. Range 0–10, default 3. |
|
|
95
|
-
| `-h, --help` | Show help. |
|
|
96
|
-
|
|
97
|
-
### Example
|
|
98
|
-
|
|
99
|
-
```bash
|
|
100
|
-
npx backtrack symbolize ./incidents/checkout-bug.ffr.json --sourcemaps ./dist --context-lines 5
|
|
101
|
-
```
|
|
102
|
-
|
|
103
|
-
```text
|
|
104
|
-
[Backtrack] Symbolication concluída.
|
|
105
|
-
|
|
106
|
-
Incidente: inc_1727500000_3f2a
|
|
107
|
-
Erros encontrados: 1
|
|
108
|
-
Frames da exceção resolvidos: 4
|
|
109
|
-
Frames da exceção não resolvidos: 0
|
|
110
|
-
Frames React resolvidos: 2
|
|
111
|
-
Frames React não resolvidos: 0
|
|
112
|
-
Saída: /projects/app/incidents/checkout-bug.symbolicated.ffr.json
|
|
113
|
-
```
|
|
114
|
-
|
|
115
|
-
If some frames have no matching source map, the command reports a partial symbolication with warnings instead of failing.
|
|
116
|
-
|
|
117
|
-
Open the `.symbolicated.ffr.json` file in the viewer (`npx backtrack`) and the error tab shows the resolved stack trace, with the failing line highlighted:
|
|
118
|
-
|
|
119
|
-
```text
|
|
120
|
-
applyCoupon src/cart/coupon.ts:42:18
|
|
121
|
-
|
|
122
|
-
40 function applyCoupon(cart, coupon) {
|
|
123
|
-
41 // coupon discount might be missing from API
|
|
124
|
-
42 const off = coupon.discount.percent; <-- highlighted
|
|
125
|
-
43 return cart.total * (1 - off / 100);
|
|
126
|
-
44 }
|
|
127
|
-
```
|
|
128
|
-
|
|
129
|
-
### What it does (and doesn't do)
|
|
130
|
-
|
|
131
|
-
- **Validates safely:** Reads the incident (up to 50 MB, gzip supported) and validates its schema with a strict validator. The original file is never modified.
|
|
132
|
-
- **Multi-browser stack parsing:** Supports V8 (Chrome/Edge), Firefox, and Safari stack formats, stripping URL hashes/query strings and skipping native frames (`[native code]`).
|
|
133
|
-
- **Resolves both exception location and React tree:** Simboliza tanto o ponto onde a exceção foi lançada (`resolvedStack`) quanto a árvore de componentes React (`resolvedComponentStack`), mantendo-os estritamente separados.
|
|
134
|
-
- **Sourcemap validation:** Checks the sourcemap `file` attribute against the minified bundle to prevent cross-bundle misattribution.
|
|
135
|
-
- **Extracts source context:** Extracts the original code from `sourcesContent`, so your source maps must include it.
|
|
136
|
-
- **Doesn't leak local paths:** File paths are normalized (e.g. `C:\Users\alice\...` or `/home/bob/...` become paths starting at `src/`).
|
|
137
|
-
- **Atomic write:** Writes the result atomically (to a `.tmp` file, then renames) and stores it in `resolvedStack` and `resolvedComponentStack`.
|
|
138
|
-
|
|
139
|
-
### Limitations & Caveats
|
|
140
|
-
|
|
141
|
-
- **Frames without line/column:** Stack frames missing line or column numbers cannot be mapped to source locations.
|
|
142
|
-
- **Matching sourcemap release:** Source maps must correspond to the exact production build that generated the incident. Use `--release <id>` to ensure compatibility.
|
|
143
|
-
- **Privacy notice:** O artefato poderá incluir replay visual, URLs, logs, respostas de rede, anotações e trechos do código-fonte incorporados durante a symbolication.
|
|
144
|
-
|
|
145
|
-
---
|
|
146
|
-
|
|
147
|
-
## Privacy & Data Masking
|
|
148
|
-
|
|
149
|
-
Backtrack is designed with strict security defaults:
|
|
150
|
-
|
|
151
|
-
- **Inputs & Forms:** All `<input>`, `<textarea>`, and `<select>` values are masked by default (`maskAllInputs: true`).
|
|
152
|
-
- **Network Headers:** Authorization, Cookies, API keys, and Bearer tokens are automatically redacted.
|
|
153
|
-
- **Sensitive Selectors:** Use standard selectors or CSS classes to protect proprietary or personal data:
|
|
154
|
-
|
|
155
|
-
```typescript
|
|
156
|
-
const recorder = new Backtrack({
|
|
157
|
-
privacy: {
|
|
158
|
-
maskAllInputs: true,
|
|
159
|
-
blockMedia: true,
|
|
160
|
-
blockSelector: '.backtrack-block, [data-private]', // Completely hides elements in replay
|
|
161
|
-
maskTextSelector: '.backtrack-mask, .customer-pII', // Scrambles text content
|
|
162
|
-
sanitizeUrl: (url) => {
|
|
163
|
-
// Remove sensitive query parameters
|
|
164
|
-
url.searchParams.delete('token');
|
|
165
|
-
return url.toString();
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
});
|
|
169
|
-
```
|
|
170
|
-
|
|
171
|
-
---
|
|
172
|
-
|
|
173
|
-
## Network & Payload Capture
|
|
174
|
-
|
|
175
|
-
Network requests and responses can be configured using `network` options:
|
|
176
|
-
|
|
177
|
-
```typescript
|
|
178
|
-
const recorder = new Backtrack({
|
|
179
|
-
network: {
|
|
180
|
-
capturePayloads: false, // Bodies are disabled by default for privacy
|
|
181
|
-
maxPayloadSize: 64 * 1024
|
|
182
|
-
}
|
|
183
|
-
});
|
|
184
|
-
```
|
|
185
|
-
|
|
186
|
-
- **Bodies are not captured by default (`capturePayloads: false`):** Request and response bodies are disabled by default to prevent unintentional data leakage. HTTP method, URL, status, timing, and sanitized headers continue to be captured.
|
|
187
|
-
- **Enabling bodies increases the risk of PII:** Enabling `capturePayloads: true` should be done mindfully according to your compliance and privacy requirements.
|
|
188
|
-
- **Sanitization remains active:** Even when payload capture is explicitly enabled, Backtrack continues to sanitize and redact known sensitive keys (passwords, tokens, credentials, etc.) and patterns (Bearer tokens, emails, CPFs, cards).
|
|
189
|
-
- **`maxPayloadSize` is a limit per payload, not per incident:** It bounds each individual request or response body (default is `64 * 1024` bytes). Payloads exceeding this limit are truncated safely with a truncation marker.
|
|
190
|
-
|
|
191
|
-
---
|
|
192
|
-
|
|
193
|
-
## Capturing Incidents
|
|
194
|
-
|
|
195
|
-
### Automatic Triggers
|
|
196
|
-
Backtrack automatically triggers and freezes an incident when:
|
|
197
|
-
1. An unhandled window exception occurs (`window.onerror`).
|
|
198
|
-
2. An unhandled promise rejection occurs (`unhandledrejection`).
|
|
199
|
-
3. An HTTP request returns a matching error status (`captureHttpStatus`).
|
|
200
|
-
|
|
201
|
-
### Manual Capture
|
|
202
|
-
You can trigger incident recording manually anywhere in your code (e.g. from an error boundary or user feedback modal):
|
|
203
|
-
|
|
204
|
-
```typescript
|
|
205
|
-
// Capture the last 60 seconds of context
|
|
206
|
-
const incidentId = await recorder.capture('Checkout error', 60);
|
|
207
|
-
|
|
208
|
-
// Export the complete incident artifact as a JSON object
|
|
209
|
-
const artifact = await recorder.exportIncident(incidentId);
|
|
210
|
-
|
|
211
|
-
// Download or send artifact to your support/logging service
|
|
212
|
-
const jsonBlob = new Blob([JSON.stringify(artifact, null, 2)], { type: 'application/json' });
|
|
213
|
-
```
|
|
214
|
-
|
|
215
|
-
### Exception Capture
|
|
216
|
-
|
|
217
|
-
#### React Error Boundary
|
|
218
|
-
Em Error Boundaries (ex: `componentDidCatch` ou `react-error-boundary`), forneça `source: 'react'` e a árvore de componentes `componentStack`:
|
|
219
|
-
|
|
220
|
-
```typescript
|
|
221
|
-
// React Error Boundary (captura renderização/lifecycle com árvore de componentes)
|
|
222
|
-
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
|
|
223
|
-
recorder.captureException(error, {
|
|
224
|
-
source: 'react',
|
|
225
|
-
componentStack: errorInfo.componentStack
|
|
226
|
-
});
|
|
227
|
-
}
|
|
228
|
-
```
|
|
229
|
-
|
|
230
|
-
#### Captura manual (try / catch)
|
|
231
|
-
Para exceções capturadas imperativamente em handlers de eventos, chamadas assíncronas ou blocos `try/catch`, use `source: 'manual'`:
|
|
232
|
-
|
|
233
|
-
```typescript
|
|
234
|
-
// Captura imperativa sem árvore de componentes React
|
|
235
|
-
try {
|
|
236
|
-
processCheckout();
|
|
237
|
-
} catch (err) {
|
|
238
|
-
recorder.captureException(err, {
|
|
239
|
-
source: 'manual'
|
|
240
|
-
});
|
|
241
|
-
}
|
|
242
|
-
```
|
|
243
|
-
|
|
244
|
-
> **Atenção:** Use `source: 'react'` apenas quando o erro foi capturado por um Error Boundary com a árvore de renderização. O visualizador e o simbolizador tratam `source: 'react'` e `componentStack` como a árvore de componentes da interface, e a stack JavaScript comum como o local exato do disparo da exceção.
|
|
245
|
-
|
|
246
|
-
---
|
|
247
|
-
|
|
248
|
-
## Remote Transport & beforeSend
|
|
249
|
-
|
|
250
|
-
Backtrack allows applications to automatically dispatch finalized incidents to any remote endpoint or telemetry backend using `transport` and `beforeSend`:
|
|
251
|
-
|
|
252
|
-
```typescript
|
|
253
|
-
const recorder = new Backtrack({
|
|
254
|
-
transport: {
|
|
255
|
-
async send(artifact) {
|
|
256
|
-
const response = await fetch('/api/backtrack/incidents', {
|
|
257
|
-
method: 'POST',
|
|
258
|
-
headers: {
|
|
259
|
-
'content-type': 'application/json'
|
|
260
|
-
},
|
|
261
|
-
body: JSON.stringify(artifact)
|
|
262
|
-
});
|
|
263
|
-
|
|
264
|
-
if (!response.ok) {
|
|
265
|
-
throw new Error(`Upload failed: ${response.status}`);
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
},
|
|
269
|
-
|
|
270
|
-
beforeSend(artifact) {
|
|
271
|
-
if (artifact.environment.url.includes('/healthcheck')) {
|
|
272
|
-
return null;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
return artifact;
|
|
276
|
-
}
|
|
277
|
-
});
|
|
278
|
-
```
|
|
279
|
-
|
|
280
|
-
### Dispatch Flow & Semantics
|
|
281
|
-
|
|
282
|
-
- **Sent Only When Finalized:** Incidents are dispatched only after they have been completely finalized and safely written to IndexedDB.
|
|
283
|
-
```text
|
|
284
|
-
incident finalized
|
|
285
|
-
↓
|
|
286
|
-
build artifact
|
|
287
|
-
↓
|
|
288
|
-
beforeSend
|
|
289
|
-
↓
|
|
290
|
-
null? cancel upload
|
|
291
|
-
↓
|
|
292
|
-
transport.send
|
|
293
|
-
```
|
|
294
|
-
- **Role of `beforeSend`:**
|
|
295
|
-
- Affects **only** the automated transmission via `transport.send`.
|
|
296
|
-
- Does **not** mutate the artifact stored in local IndexedDB.
|
|
297
|
-
- Does **not** affect `getArtifact()` or explicit file downloads via `exportIncident()`.
|
|
298
|
-
- Returning `null` cancels the upload.
|
|
299
|
-
- If `beforeSend` throws an error, the upload is aborted cleanly without affecting the application or the recorded incident.
|
|
300
|
-
- **Fault Isolation:** Network or transport errors will never break the host application, reject user captures, delete local incidents, prevent finalization, or trigger unhandled promise rejections.
|
|
301
|
-
- **Concurrency & Delivery Guarantees:**
|
|
302
|
-
- Each finalized incident triggers at most one upload attempt.
|
|
303
|
-
- Multiple incidents can upload concurrently.
|
|
304
|
-
- `stop()` does not wait for pending network uploads.
|
|
305
|
-
- There is currently no delivery guarantee (persistent retry queue, offline backoff, etc.); if transport fails, the incident remains saved in local IndexedDB and can be accessed or resent by the application.
|
|
306
|
-
|
|
307
|
-
---
|
|
308
|
-
|
|
309
|
-
## Automatic Local Incident Export (`@backtrack-js/browser/dev-server`)
|
|
310
|
-
|
|
311
|
-
During local development, Backtrack can save finalized incidents directly to disk in your project folder (JSON + Markdown report) without requiring manual downloads or clipboard copying.
|
|
312
|
-
|
|
313
|
-
This is ideal for both human developers and **AI coding assistants** (Cursor, Copilot, Antigravity, Claude Code), enabling instant root-cause diagnosis directly from `.backtrack/latest.md`.
|
|
314
|
-
|
|
315
|
-
```text
|
|
316
|
-
.backtrack/
|
|
317
|
-
├── latest.md <- Structured markdown report (<= 32 KiB) for quick inspection
|
|
318
|
-
└── incidents/
|
|
319
|
-
├── <id>.json <- Full replay artifact with DOM, network & timeline
|
|
320
|
-
└── <id>.md <- Timestamped markdown report
|
|
321
|
-
```
|
|
322
|
-
|
|
323
|
-
### 1. Dev Server Setup
|
|
324
|
-
|
|
325
|
-
The middleware works with any Node-based development server (Vite, Webpack, CRA, Express, Fastify).
|
|
326
|
-
|
|
327
|
-
#### Vite (`vite.config.ts`)
|
|
328
|
-
```typescript
|
|
329
|
-
import { defineConfig } from 'vite';
|
|
330
|
-
import path from 'path';
|
|
331
|
-
import { createBacktrackMiddleware } from '@backtrack-js/browser/dev-server';
|
|
332
|
-
|
|
333
|
-
export default defineConfig({
|
|
334
|
-
plugins: [
|
|
335
|
-
{
|
|
336
|
-
name: 'backtrack-dev-server',
|
|
337
|
-
configureServer(server) {
|
|
338
|
-
server.middlewares.use(
|
|
339
|
-
createBacktrackMiddleware({
|
|
340
|
-
outputDir: path.resolve(__dirname, '.backtrack'),
|
|
341
|
-
})
|
|
342
|
-
);
|
|
343
|
-
},
|
|
344
|
-
},
|
|
345
|
-
],
|
|
346
|
-
});
|
|
347
|
-
```
|
|
348
|
-
|
|
349
|
-
#### Create React App / Webpack Dev Server (`src/setupProxy.js`)
|
|
350
|
-
```javascript
|
|
351
|
-
const path = require('path');
|
|
352
|
-
const { createBacktrackMiddleware } = require('@backtrack-js/browser/dev-server');
|
|
353
|
-
|
|
354
|
-
module.exports = function(app) {
|
|
355
|
-
if (process.env.NODE_ENV === 'development') {
|
|
356
|
-
app.use(
|
|
357
|
-
createBacktrackMiddleware({
|
|
358
|
-
outputDir: path.resolve(__dirname, '../.backtrack'),
|
|
359
|
-
allowedOrigins: ['http://localhost:3000', 'http://127.0.0.1:3000'],
|
|
360
|
-
})
|
|
361
|
-
);
|
|
362
|
-
}
|
|
363
|
-
};
|
|
364
|
-
```
|
|
365
|
-
|
|
366
|
-
#### Express / Custom Node Dev Server
|
|
367
|
-
```javascript
|
|
368
|
-
const path = require('path');
|
|
369
|
-
const { createBacktrackMiddleware } = require('@backtrack-js/browser/dev-server');
|
|
370
|
-
|
|
371
|
-
app.use(
|
|
372
|
-
createBacktrackMiddleware({
|
|
373
|
-
outputDir: path.resolve(__dirname, '.backtrack'),
|
|
374
|
-
maxIncidents: 20, // keeps disk clean automatically
|
|
375
|
-
})
|
|
376
|
-
);
|
|
377
|
-
```
|
|
378
|
-
|
|
379
|
-
### 2. Client Setup
|
|
380
|
-
|
|
381
|
-
In your client application initialization, configure `transport` to POST to `/__backtrack/incident`:
|
|
382
|
-
|
|
383
|
-
```typescript
|
|
384
|
-
import { Backtrack } from '@backtrack-js/browser';
|
|
385
|
-
|
|
386
|
-
const isDev = process.env.NODE_ENV === 'development';
|
|
387
|
-
|
|
388
|
-
const recorder = await Backtrack.init({
|
|
389
|
-
ignoredUrls: ['/__backtrack/incident'],
|
|
390
|
-
transport: isDev
|
|
391
|
-
? {
|
|
392
|
-
async send(artifact) {
|
|
393
|
-
await fetch('/__backtrack/incident', {
|
|
394
|
-
method: 'POST',
|
|
395
|
-
headers: { 'Content-Type': 'application/json' },
|
|
396
|
-
body: JSON.stringify(artifact),
|
|
397
|
-
});
|
|
398
|
-
},
|
|
399
|
-
}
|
|
400
|
-
: undefined,
|
|
401
|
-
});
|
|
402
|
-
```
|
|
403
|
-
|
|
404
|
-
### Middleware Options
|
|
405
|
-
|
|
406
|
-
| Option | Type | Default | Description |
|
|
407
|
-
| :--- | :--- | :--- | :--- |
|
|
408
|
-
| `outputDir` / `directory` | `string` | *(required)* | Absolute path to the directory where incidents are stored. |
|
|
409
|
-
| `allowedOrigins` | `string[]` | local origins | Allowed request origins. Defaults to loopback (`localhost`, `127.0.0.1`, `::1`). |
|
|
410
|
-
| `maxBodyBytes` | `number` | `52428800` (50 MiB) | Maximum allowed JSON request body size. Aborts stream early if exceeded. |
|
|
411
|
-
| `maxIncidents` | `number` | `20` | Maximum number of managed incidents retained on disk. |
|
|
412
|
-
| `maxStorageBytes` | `number` | `209715200` (200 MiB) | Aggregate disk space limit for managed incidents. Oldest files are pruned first. |
|
|
413
|
-
|
|
414
|
-
> **Security & Best Practices:**
|
|
415
|
-
> - Add `.backtrack/` to your `.gitignore`.
|
|
416
|
-
> - Never enable the local dev-server middleware in staging or production.
|
|
417
|
-
> - The middleware validates requests against local peer sockets and host headers to prevent external access. Writes are atomic via `.tmp` files.
|
|
418
|
-
|
|
419
|
-
## Release and trace correlation
|
|
420
|
-
|
|
421
|
-
Backtrack artifacts (`formatVersion: 2`) provide an observability `context` to correlate client-side replays with backend traces, application releases, and environments.
|
|
422
|
-
|
|
423
|
-
### Static Context
|
|
424
|
-
|
|
425
|
-
Configure static metadata when initializing Backtrack:
|
|
426
|
-
|
|
427
|
-
```typescript
|
|
428
|
-
const recorder = new Backtrack({
|
|
429
|
-
context: {
|
|
430
|
-
release: 'checkout-web@2.14.0',
|
|
431
|
-
environment: 'production',
|
|
432
|
-
traceId: '4bf92f3577b34da6a3ce929d0e0e4736',
|
|
433
|
-
spanId: '00f067aa0ba902b7'
|
|
434
|
-
}
|
|
435
|
-
});
|
|
436
|
-
```
|
|
437
|
-
|
|
438
|
-
### Dynamic Context (`getContext`)
|
|
439
|
-
|
|
440
|
-
When trace IDs or active environments change dynamically during user navigation (e.g. from OpenTelemetry, Datadog, Sentry, or custom APM SDKs), use `getContext` to evaluate the latest context at incident export time:
|
|
441
|
-
|
|
442
|
-
```typescript
|
|
443
|
-
const recorder = new Backtrack({
|
|
444
|
-
context: {
|
|
445
|
-
release: 'checkout-web@2.14.0',
|
|
446
|
-
environment: 'production'
|
|
447
|
-
},
|
|
448
|
-
getContext: async () => {
|
|
449
|
-
const activeSpan = tracer.getActiveSpan();
|
|
450
|
-
const spanContext = activeSpan?.spanContext();
|
|
451
|
-
|
|
452
|
-
return {
|
|
453
|
-
release: 'checkout-web@2.14.0',
|
|
454
|
-
environment: 'production',
|
|
455
|
-
traceId: spanContext?.traceId,
|
|
456
|
-
spanId: spanContext?.spanId
|
|
457
|
-
};
|
|
458
|
-
}
|
|
459
|
-
});
|
|
460
|
-
```
|
|
461
|
-
|
|
462
|
-
### Correlation Semantics
|
|
463
|
-
|
|
464
|
-
- **Precedence:** `getContext() > context (static) > environment metadata`.
|
|
465
|
-
- **Trace correlation scope:** Backtrack **only correlates** external trace and span identifiers supplied by your application. It does **not** generate backend traces, start trace spans, or perform distributed instrumentation on its own.
|
|
466
|
-
- **Normalization:** `traceId` (32 hex characters) and `spanId` (16 hex characters) are validated and normalized to lowercase. A `spanId` cannot be supplied without an accompanying `traceId`.
|
|
467
|
-
- **Fault Resilience:** If `getContext()` throws an error or rejects, incident export continues safely using available static context without failing the export or losing incident data.
|
|
468
|
-
|
|
469
|
-
---
|
|
470
|
-
|
|
471
|
-
## Inspecting Incidents (Viewer)
|
|
472
|
-
|
|
473
|
-
Backtrack includes an offline visualizer with video replay, console logs, network inspection, and breadcrumbs.
|
|
474
|
-
|
|
475
|
-
### Launch the Viewer CLI
|
|
476
|
-
Run the embedded CLI to launch the local visualizer:
|
|
477
|
-
|
|
478
|
-
```bash
|
|
479
|
-
npx backtrack
|
|
480
|
-
```
|
|
481
|
-
|
|
482
|
-
This starts a local server at `http://localhost:5173/` and opens your default browser. Drag and drop any exported incident `.json` file to replay it!
|
|
483
|
-
|
|
484
|
-
---
|
|
485
|
-
|
|
486
|
-
## API Reference
|
|
487
|
-
|
|
488
|
-
### `Backtrack`
|
|
489
|
-
|
|
490
|
-
| Method | Return Type | Description |
|
|
491
|
-
| --- | --- | --- |
|
|
492
|
-
| `start()` | `Promise<void>` | Initializes storage and begins recording. |
|
|
493
|
-
| `stop()` | `Promise<void>` | Stops recording, flushes pending batches to storage, and detaches listeners. |
|
|
494
|
-
| `capture(reason?, windowSeconds?)` | `Promise<string>` | Manually captures and finalizes an incident. Returns incident ID. |
|
|
495
|
-
| `captureException(error, context?)` | `Promise<string \| undefined> \| void` | Records a caught exception and triggers an incident. |
|
|
496
|
-
| `listIncidents()` | `Promise<IncidentSummary[]>` | Lists all stored incidents. |
|
|
497
|
-
| `getArtifact(incidentId)` | `Promise<FlightRecorderArtifact>` | Retrieves the full artifact for an incident (v1 or v2). |
|
|
498
|
-
| `exportIncident(incidentId)` | `Promise<FlightRecorderArtifact>` | Exports the artifact and marks it finalized. |
|
|
499
|
-
| `deleteIncident(incidentId)` | `Promise<void>` | Deletes an incident from local storage. |
|
|
500
|
-
| `clear()` | `Promise<void>` | Clears all stored chunks, sessions, and incidents. |
|
|
501
|
-
| `getHealth()` | `RecorderHealth` | Returns current buffer status, storage usage, and state. |
|
|
48
|
+
Documentação local: http://localhost:4174/docs/
|
|
502
49
|
|
|
503
|
-
|
|
50
|
+
[Como editar e publicar o site](site/README.md). A saída do site é `dist/site`; a do visualizador permanece separada. A documentação ainda precisa de um destino de publicação.
|
|
504
51
|
|
|
505
|
-
##
|
|
52
|
+
## Licença
|
|
506
53
|
|
|
507
|
-
[Backtrack Free-Use License](LICENSE)
|
|
54
|
+
[Backtrack Free-Use License](LICENSE)
|
|
@@ -7,4 +7,3 @@ export declare function globToRegex(pattern: string): RegExp;
|
|
|
7
7
|
* Verifica se um pathname ou URL corresponde a alguma das regras de sensitiveRoutes configuradas.
|
|
8
8
|
*/
|
|
9
9
|
export declare function matchesSensitiveRoute(pathname: string, matchers?: RouteMatcher[]): boolean;
|
|
10
|
-
//# sourceMappingURL=route-matcher.d.ts.map
|
|
@@ -34,4 +34,3 @@ export declare function sanitizePayloadString(payload: string, maxLength?: numbe
|
|
|
34
34
|
* Sanitiza headers HTTP redigindo Authorization, Cookies, Tokens e Chaves.
|
|
35
35
|
*/
|
|
36
36
|
export declare function sanitizeHeaders(headers: Record<string, string> | Headers | [string, string][] | undefined | null): Record<string, string> | undefined;
|
|
37
|
-
//# sourceMappingURL=sanitizer.d.ts.map
|
|
@@ -72,4 +72,3 @@ export declare class FlightRecorderImpl implements FlightRecorder {
|
|
|
72
72
|
* Função factory pública para instanciar o Flight Recorder.
|
|
73
73
|
*/
|
|
74
74
|
export declare function createFlightRecorder(options?: FlightRecorderOptions): FlightRecorder;
|
|
75
|
-
//# sourceMappingURL=flight-recorder.d.ts.map
|
|
@@ -11,4 +11,3 @@ export interface BacktrackMiddlewareOptions {
|
|
|
11
11
|
}
|
|
12
12
|
export type ConnectLikeMiddleware = (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => void;
|
|
13
13
|
export declare function createBacktrackMiddleware(options: BacktrackMiddlewareOptions): ConnectLikeMiddleware;
|
|
14
|
-
//# sourceMappingURL=middleware.d.ts.map
|
package/dist/dev-server.cjs
CHANGED
|
@@ -4,4 +4,3 @@
|
|
|
4
4
|
`+e.readFileSync(r.mdPath,"utf8"),n=`${f}.${Date.now()}.tmp`;try{e.writeFileSync(n,s,{encoding:"utf8",flag:"wx"}),e.renameSync(n,f)}finally{m(n)&&e.unlinkSync(n)}return r.id}function E(i){const r=x();let s=r.length,n=r.reduce((c,a)=>c+a.size,e.statSync(f).size);for(const c of r){if(s<=F&&n<=v)break;c.id!==i&&(e.unlinkSync(c.mdPath),e.unlinkSync(c.jsonPath),s--,n-=c.size)}}return(i,r,s)=>{const n=(l,$)=>{!r.destroyed&&!r.headersSent&&(r.writeHead(l,{"Content-Type":"application/json",...l===405?{Allow:"POST"}:{}}),r.end(JSON.stringify($)))};if((i.url||"").split("?")[0]!=="/__backtrack/incident"){s?s():n(404,{error:"Not found"});return}if(i.method!=="POST"){n(405,{error:"Method Not Allowed"});return}if((i.headers["content-type"]||"").split(";")[0].trim().toLowerCase()!=="application/json"){n(415,{error:"Unsupported Media Type: application/json required"});return}if(!V(i,t.allowedOrigins)){n(403,{error:"Forbidden: invalid origin or non-local access"});return}let c=0,a=!1;const p=[];i.on("error",()=>{a=!0,p.length=0}),i.on("aborted",()=>{a=!0,p.length=0}),i.on("data",l=>{a||(c+=l.length,c>h?(a=!0,p.length=0,r.setHeader("Connection","close"),n(413,{error:"Payload Too Large"})):p.push(l))}),i.on("end",()=>{if(a)return;const l=Buffer.concat(p).toString("utf8");p.length=0;let $;try{$=JSON.parse(l)}catch{n(400,{error:"Invalid JSON"});return}const z=I.validateFlightRecorderArtifact($);if(!z.success){n(400,{error:"Invalid artifact schema"});return}const M=z.data,g=M.incident.id;if(!_(g)){n(400,{error:"Invalid incident ID format"});return}P=P.then(()=>{try{for(const u of[S,d]){if(e.existsSync(u)&&!e.lstatSync(u).isDirectory())throw new Error("Invalid output directory");e.mkdirSync(u,{recursive:!0})}const w=y.join(d,`${g}.json`),k=y.join(d,`${g}.md`),j=e.existsSync(w),O=e.existsSync(k);if(j&&(!m(w)||e.readFileSync(w,"utf8")!==l)||O&&(!m(k)||!j)){n(409,{error:"Conflict: incident ID exists with different content"});return}if(j&&O){const u=D();E(u),n(200,{id:g,status:"already_persisted"});return}const N=I.formatIncidentMarkdown(M),H=`> **Artefato completo:** [\`${g}.json\`](incidents/${g}.json)
|
|
5
5
|
|
|
6
6
|
`;if(Buffer.byteLength(l)+2*Buffer.byteLength(N)+Buffer.byteLength(H)>v){n(413,{error:"Incident size exceeds maxStorageBytes limit"});return}const R=`${Date.now()}-${Math.random().toString(36).slice(2)}`,B=`${w}.${R}.tmp`,b=`${k}.${R}.tmp`;let T=!1,C=!1;try{j||e.writeFileSync(B,l,{encoding:"utf8",flag:"wx"}),e.writeFileSync(b,N,{encoding:"utf8",flag:"wx"}),j||(e.renameSync(B,w),T=!0),e.renameSync(b,k),C=!0,D()}catch(u){throw C&&m(k)&&e.unlinkSync(k),T&&m(w)&&e.unlinkSync(w),u}finally{for(const u of[B,b])m(u)&&e.unlinkSync(u)}const J=x();E(J[J.length-1].id),n(201,{id:g,status:"saved"})}catch{n(500,{error:"Failed to persist incident"})}})})}}exports.createBacktrackMiddleware=G;
|
|
7
|
-
//# sourceMappingURL=dev-server.cjs.map
|
package/dist/dev-server.js
CHANGED