bugstack-sdk 2.2.1 → 2.3.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.
Files changed (36) hide show
  1. package/CHANGELOG.md +139 -96
  2. package/README.md +496 -421
  3. package/bin/bugstack.cjs +6 -6
  4. package/dist/adapters/express/index.d.mts +2 -2
  5. package/dist/adapters/express/index.d.ts +2 -2
  6. package/dist/adapters/express/index.js +409 -43
  7. package/dist/adapters/express/index.js.map +1 -1
  8. package/dist/adapters/express/index.mjs +409 -43
  9. package/dist/adapters/express/index.mjs.map +1 -1
  10. package/dist/adapters/generic/index.d.mts +2 -2
  11. package/dist/adapters/generic/index.d.ts +2 -2
  12. package/dist/adapters/generic/index.js +457 -43
  13. package/dist/adapters/generic/index.js.map +1 -1
  14. package/dist/adapters/generic/index.mjs +454 -44
  15. package/dist/adapters/generic/index.mjs.map +1 -1
  16. package/dist/adapters/nextjs/index.d.mts +2 -2
  17. package/dist/adapters/nextjs/index.d.ts +2 -2
  18. package/dist/adapters/nextjs/index.js +409 -43
  19. package/dist/adapters/nextjs/index.js.map +1 -1
  20. package/dist/adapters/nextjs/index.mjs +409 -43
  21. package/dist/adapters/nextjs/index.mjs.map +1 -1
  22. package/dist/build/cli.js.map +1 -1
  23. package/dist/build/cli.mjs.map +1 -1
  24. package/dist/build/upload.js.map +1 -1
  25. package/dist/build/upload.mjs.map +1 -1
  26. package/dist/{client-DoqE7sNh.d.mts → client-B9WaTEYj.d.mts} +149 -2
  27. package/dist/{client-DoqE7sNh.d.ts → client-B9WaTEYj.d.ts} +149 -2
  28. package/dist/index.d.mts +2 -2
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.js +469 -55
  31. package/dist/index.js.map +1 -1
  32. package/dist/index.mjs +466 -56
  33. package/dist/index.mjs.map +1 -1
  34. package/dist/next-config/index.js.map +1 -1
  35. package/dist/next-config/index.mjs.map +1 -1
  36. package/package.json +107 -104
package/README.md CHANGED
@@ -1,421 +1,496 @@
1
- # bugstack-sdk
2
-
3
- Framework-agnostic error capture SDK for Node.js. Automatically captures errors with full context and reports them to BugStack for AI-powered fix generation.
4
-
5
- **Get your API key at:** [dashboard.bugstack.ai](https://dashboard.bugstack.ai)
6
-
7
- ## Features
8
-
9
- - **Multiple frameworks** — First-class support for Next.js, Express, and generic Node.js
10
- - **Full error context** — Captures stack traces, request body, headers, query params, route params
11
- - **Automatic sanitization** — Sensitive data (passwords, tokens, API keys) is redacted automatically
12
- - **Non-blocking** — Error reporting is async and never slows down your responses
13
- - **Deduplication** — Same errors are batched within a configurable time window
14
- - **Retry queue** — Failed reports are retried with exponential backoff
15
- - **TypeScript first** — Full type safety with comprehensive type definitions
16
-
17
- ## Installation
18
-
19
- ```bash
20
- npm install bugstack-sdk
21
- ```
22
-
23
- ## Quick Start
24
-
25
- ### Next.js (App Router)
26
-
27
- **1. Initialize the client once:**
28
-
29
- ```typescript
30
- // lib/bugstack.ts
31
- import { ErrorCaptureClient } from "bugstack-sdk";
32
-
33
- ErrorCaptureClient.init({
34
- apiKey: process.env.BUGSTACK_API_KEY!,
35
- endpoint: "https://bugstack-error-service.onrender.com/api/capture",
36
- });
37
- ```
38
-
39
- **2. Wrap your API route handlers:**
40
-
41
- ```typescript
42
- // app/api/users/route.ts
43
- import { NextResponse } from "next/server";
44
- import { withErrorCapture } from "bugstack-sdk/next";
45
- import "@/lib/bugstack"; // ensures client is initialized
46
-
47
- export const GET = withErrorCapture(async (request) => {
48
- const users = await db.users.findMany();
49
- return NextResponse.json({ users });
50
- });
51
-
52
- export const POST = withErrorCapture(async (request) => {
53
- const body = await request.json();
54
- const user = await db.users.create({ data: body });
55
- return NextResponse.json({ user }, { status: 201 });
56
- });
57
- ```
58
-
59
- **3. Dynamic routes with params:**
60
-
61
- ```typescript
62
- // app/api/users/[id]/route.ts
63
- import { NextResponse } from "next/server";
64
- import { withErrorCapture } from "bugstack-sdk/next";
65
- import "@/lib/bugstack";
66
-
67
- export const GET = withErrorCapture<{ id: string }>(
68
- async (request, { params }) => {
69
- const user = await db.users.findUnique({ where: { id: params.id } });
70
- if (!user) throw new Error("User not found");
71
- return NextResponse.json({ user });
72
- }
73
- );
74
- ```
75
-
76
- ---
77
-
78
- ### Express
79
-
80
- **Option A: Error handler middleware (recommended)**
81
-
82
- ```typescript
83
- import express from "express";
84
- import { bugstackErrorHandler } from "bugstack-sdk/express";
85
-
86
- const app = express();
87
-
88
- // Your routes
89
- app.get("/api/users", async (req, res) => {
90
- const users = await db.users.findMany();
91
- res.json({ users });
92
- });
93
-
94
- // Add BugStack error handler AFTER all routes
95
- app.use(
96
- bugstackErrorHandler({
97
- apiKey: process.env.BUGSTACK_API_KEY!,
98
- endpoint: "https://bugstack-error-service.onrender.com/api/capture",
99
- })
100
- );
101
- ```
102
-
103
- **Option B: Wrap individual route handlers**
104
-
105
- ```typescript
106
- import { initBugStack, wrapExpressHandler } from "bugstack-sdk/express";
107
-
108
- // Initialize once
109
- app.use(
110
- initBugStack({
111
- apiKey: process.env.BUGSTACK_API_KEY!,
112
- endpoint: "https://bugstack-error-service.onrender.com/api/capture",
113
- })
114
- );
115
-
116
- // Wrap specific routes
117
- app.get("/api/users/:id", wrapExpressHandler(async (req, res) => {
118
- const user = await getUser(req.params.id);
119
- res.json(user);
120
- }));
121
- ```
122
-
123
- ---
124
-
125
- ### Generic Node.js
126
-
127
- For any Node.js application (scripts, workers, serverless functions, etc.):
128
-
129
- ```typescript
130
- import { initBugStack, captureError, installGlobalHandlers } from "bugstack-sdk/generic";
131
-
132
- // Initialize once
133
- initBugStack({
134
- apiKey: process.env.BUGSTACK_API_KEY!,
135
- endpoint: "https://bugstack-error-service.onrender.com/api/capture",
136
- });
137
-
138
- // Optional: catch uncaught exceptions and unhandled rejections globally
139
- installGlobalHandlers();
140
-
141
- // Capture errors manually in try/catch blocks
142
- try {
143
- await processData();
144
- } catch (error) {
145
- await captureError(error, { operation: "processData" });
146
- }
147
- ```
148
-
149
- **Wrap functions for automatic capture:**
150
-
151
- ```typescript
152
- import { wrapFunction } from "bugstack-sdk/generic";
153
-
154
- const processData = wrapFunction(
155
- async (data: Input) => {
156
- // errors thrown here are automatically captured
157
- return transform(data);
158
- },
159
- { operation: "processData" }
160
- );
161
- ```
162
-
163
- **Create scoped capture functions:**
164
-
165
- ```typescript
166
- import { createErrorCapture } from "bugstack-sdk/generic";
167
-
168
- const captureDbError = createErrorCapture({ component: "database" });
169
-
170
- try {
171
- await db.query("SELECT ...");
172
- } catch (error) {
173
- await captureDbError(error, { query: "SELECT ..." });
174
- }
175
- ```
176
-
177
- ---
178
-
179
- ## Source Maps for Production (Next.js)
180
-
181
- By default, server-side errors in a Next.js production build come back with stack frames that point at compiled chunks like `.next/server/chunks/8393.js:1:8734`. The bugstack orchestrator can't fix what it can't locate — so without source maps, those errors land in your dashboard as "Could not identify primary file from error" and never auto-fix.
182
-
183
- Uploading source maps closes that loop. The orchestrator resolves bundled frames back to source-file positions (`app/api/orders/route.ts:42:5`) before deciding which file to patch.
184
-
185
- ### Two-step setup
186
-
187
- **1. Wrap your `next.config.js`:**
188
-
189
- ```js
190
- const { withBugstack } = require('bugstack-sdk/next-config')
191
-
192
- module.exports = withBugstack({
193
- // your existing Next.js config
194
- })
195
- ```
196
-
197
- This enables `webpack.devtool = 'source-map'` for production server builds (no effect on dev or client). Any existing `webpack` hook you have is preserved and runs first.
198
-
199
- **2. Append the upload command to your `build` script:**
200
-
201
- ```json
202
- {
203
- "scripts": {
204
- "build": "next build && bugstack sourcemaps upload"
205
- }
206
- }
207
- ```
208
-
209
- The CLI walks `.next/server/**/*.map`, uploads each to bugstack keyed by the active release, and **never fails the build** — source maps are an optimisation, not a release gate.
210
-
211
- ### Required environment
212
-
213
- The CLI needs two env vars at build time. Set them in your CI / hosting provider:
214
-
215
- | Variable | Purpose |
216
- |---|---|
217
- | `BUGSTACK_PROJECT_API_KEY` | Your project SDK key (find it in your project settings on the bugstack dashboard). |
218
- | `BUGSTACK_ENDPOINT` | Base URL of the bugstack ingest service. The CLI appends `/api/sourcemaps/upload` automatically. |
219
-
220
- Release identifiers are auto-detected from `BUGSTACK_RELEASE`, `RENDER_GIT_COMMIT`, `VERCEL_GIT_COMMIT_SHA`, `GITHUB_SHA`, or `git rev-parse HEAD` — in that order. Override with `--release <id>` if you have a different versioning scheme.
221
-
222
- ### Verifying
223
-
224
- After your next deploy with these env vars set, the build log should print something like:
225
-
226
- ```
227
- [bugstack] Uploading 68 source map(s) to https://… (release=a9ad704)…
228
- [bugstack] Uploaded 68/68 maps (10.0MB) in 4.2s.
229
- ```
230
-
231
- When a server-side error captures next, the row's stack trace and proposed fix will reference real source files (`app/api/.../route.ts`) instead of bundled chunks.
232
-
233
- ### Programmatic API
234
-
235
- If you'd rather drive the upload from a custom script:
236
-
237
- ```ts
238
- import { uploadSourceMaps } from 'bugstack-sdk/build'
239
-
240
- await uploadSourceMaps({
241
- apiKey: process.env.BUGSTACK_PROJECT_API_KEY,
242
- endpoint: process.env.BUGSTACK_ENDPOINT,
243
- release: process.env.GIT_SHA,
244
- serverDir: '.next/server', // override for non-Next builds
245
- })
246
- ```
247
-
248
- ### Other build systems
249
-
250
- The CLI defaults to `.next/server` but accepts `--server-dir <path>` so it works for any directory of compiled `.js` + `.js.map` pairs (e.g. `dist/` for tsc, `build/` for CRA, custom esbuild outputs). The `withBugstack` wrapper is Next.js-specific; for other frameworks, enable source-map emission in your bundler config and run the CLI directly.
251
-
252
- ---
253
-
254
- ## Other Languages
255
-
256
- BugStack also provides SDKs for:
257
-
258
- | Language | Package | Install |
259
- |----------|---------|---------|
260
- | Python | [bugstack](https://pypi.org/project/bugstack/) | `pip install bugstack` |
261
- | Ruby | [bugstack](https://rubygems.org/gems/bugstack) | `gem install bugstack` |
262
- | Go | [bugstack-go](https://github.com/MasonBachmann7/Bugstack-SDK-Go) | `go get github.com/MasonBachmann7/bugstack-go` |
263
-
264
- ---
265
-
266
- ## Configuration
267
-
268
- ### Full Options
269
-
270
- ```typescript
271
- import { ErrorCaptureClient } from "bugstack-sdk";
272
-
273
- ErrorCaptureClient.init({
274
- // Required
275
- apiKey: "your-api-key",
276
-
277
- // Endpoint (defaults to localhost for local dev)
278
- endpoint: "https://bugstack-error-service.onrender.com/api/capture",
279
-
280
- // Optional — defaults shown
281
- projectId: "",
282
- environment: process.env.NODE_ENV, // "development", "production", etc.
283
- enabled: true, // set false to disable capture entirely
284
-
285
- // Request capture
286
- captureRequestBody: true,
287
- captureQueryParams: true,
288
- captureHeaders: true,
289
- maxBodySize: 10000, // 10KB max body capture
290
-
291
- // Additional fields to redact (added to built-in defaults)
292
- redactFields: ["customSecret", "internalToken"],
293
-
294
- // Custom metadata included with every error
295
- metadata: { service: "api", version: "1.0.0" },
296
-
297
- // Network
298
- timeout: 5000, // 5s timeout for error reporting
299
- deduplicationWindow: 5 * 60 * 1000, // 5 min window for dedup
300
-
301
- // Debug logging (defaults to true in development)
302
- debug: false,
303
-
304
- // Custom filter — return false to skip certain errors
305
- shouldCapture: (error, request) => {
306
- if (error.message.includes("not found")) return false;
307
- return true;
308
- },
309
-
310
- // Transform errors before sending
311
- beforeSend: (capturedError) => {
312
- capturedError.metadata = { ...capturedError.metadata, custom: "value" };
313
- return capturedError; // return null to skip
314
- },
315
- });
316
- ```
317
-
318
- ### Environment Variables
319
-
320
- The SDK reads these automatically:
321
-
322
- ```bash
323
- BUGSTACK_API_KEY=your-api-key # Required
324
- BUGSTACK_ENDPOINT=https://bugstack-error-service.onrender.com/api/capture # Optional
325
- BUGSTACK_PROJECT_ID=my-project # Optional
326
- NODE_ENV=production # Optional
327
- ```
328
-
329
- ### Per-Route Options (Next.js)
330
-
331
- ```typescript
332
- export const POST = withErrorCapture(
333
- async (request) => { /* ... */ },
334
- undefined, // use existing client config
335
- {
336
- statusCode: 400,
337
- metadata: { operation: "createUser" },
338
- shouldCapture: (error) => error.name !== "ValidationError",
339
- }
340
- );
341
- ```
342
-
343
- ---
344
-
345
- ## Automatic Sanitization
346
-
347
- The SDK redacts sensitive data from headers, request bodies, and query params.
348
-
349
- **Built-in redacted fields:**
350
- `password`, `secret`, `token`, `apikey`, `api_key`, `apiKey`, `authorization`, `auth`, `credential`, `private`, `credit_card`, `creditcard`, `card_number`, `cvv`, `ssn`, `social_security`
351
-
352
- **Always-redacted headers:**
353
- `authorization`, `cookie`, `set-cookie`, `x-api-key`, `x-auth-token`, `proxy-authorization`
354
-
355
- Add custom fields via the `redactFields` config option.
356
-
357
- ---
358
-
359
- ## Error Resilience
360
-
361
- The SDK never interferes with your application:
362
-
363
- - **Network failures** — Silently retried (up to 5 times with exponential backoff)
364
- - **Timeouts** — Configurable, defaults to 5 seconds
365
- - **SDK errors** — Caught and logged in debug mode, never thrown to your app
366
- - **Original error preserved** — The wrapper re-throws the original error so your framework handles the response normally
367
-
368
- ---
369
-
370
- ## Captured Data
371
-
372
- Each error report includes:
373
-
374
- | Field | Description |
375
- |-------|-------------|
376
- | `id` | Unique error ID |
377
- | `fingerprint` | Stable hash for deduplication |
378
- | `name` | Error type (TypeError, etc.) |
379
- | `message` | Error message |
380
- | `stack` | Full stack trace |
381
- | `stackFrames` | Parsed stack frames with file, line, column |
382
- | `route` | API route path |
383
- | `method` | HTTP method |
384
- | `statusCode` | HTTP status code |
385
- | `url` | Full request URL |
386
- | `queryParams` | Sanitized query parameters |
387
- | `requestBody` | Sanitized request body |
388
- | `requestHeaders` | Sanitized headers |
389
- | `routeParams` | Dynamic route parameters |
390
- | `environment` | Environment name |
391
- | `projectId` | Project identifier |
392
- | `metadata` | Custom metadata |
393
-
394
- ---
395
-
396
- ## TypeScript
397
-
398
- All types are exported:
399
-
400
- ```typescript
401
- import type {
402
- ErrorCaptureConfig,
403
- CapturedError,
404
- StackFrame,
405
- RouteOptions,
406
- RouteContext,
407
- ErrorReportPayload,
408
- SourceContext,
409
- } from "bugstack-sdk";
410
- ```
411
-
412
- ## Compatibility
413
-
414
- - **Next.js**: 14.0.0+
415
- - **Express**: 4.x or 5.x
416
- - **Node.js**: 18.0.0+
417
- - **TypeScript**: 5.0.0+ (optional)
418
-
419
- ## License
420
-
421
- MIT
1
+ # bugstack-sdk
2
+
3
+ The [Bugstack](https://bugstack.ai) SDK for Node.js: Next.js, Express and any Node process.
4
+
5
+ Bugstack is autonomous software maintenance. It watches your app and your repository, fixes what breaks, and sends every change as a pull request you control. This SDK is how your app tells Bugstack about a server error: an uncaught one, or one your code caught and logged with `console.error`. It sends the error, its stack trace and where it happened, and Bugstack takes it from there.
6
+
7
+ **Get your API key at:** [dashboard.bugstack.ai](https://dashboard.bugstack.ai)
8
+
9
+ ## Features
10
+
11
+ - **Multiple frameworks** — First-class support for Next.js, Express, and generic Node.js
12
+ - **Caught-and-logged errors** — A `console.error(err)` in a `catch` block reaches Bugstack too, on by default; pino and winston with one line each
13
+ - **Full error context** — Captures stack traces, request body, headers, query params, route params
14
+ - **Automatic sanitization** — Sensitive data (passwords, tokens, API keys) is redacted automatically
15
+ - **Non-blocking** — Error reporting is async and never slows down your responses
16
+ - **Deduplication** — Same errors are batched within a configurable time window
17
+ - **Retry queue** — Failed reports are retried with exponential backoff
18
+ - **TypeScript first** — Full type safety with comprehensive type definitions
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ npm install --save-exact bugstack-sdk
24
+ ```
25
+
26
+ ## Quick Start
27
+
28
+ ### Next.js (App Router)
29
+
30
+ **1. Initialize the client once:**
31
+
32
+ ```typescript
33
+ // lib/bugstack.ts
34
+ import { ErrorCaptureClient } from "bugstack-sdk";
35
+
36
+ ErrorCaptureClient.init({
37
+ apiKey: process.env.BUGSTACK_API_KEY!,
38
+ endpoint: "https://dashboard.bugstack.ai/api/ingest/sdk",
39
+ });
40
+ ```
41
+
42
+ **2. Wrap your API route handlers:**
43
+
44
+ ```typescript
45
+ // app/api/users/route.ts
46
+ import { NextResponse } from "next/server";
47
+ import { withErrorCapture } from "bugstack-sdk/next";
48
+ import "@/lib/bugstack"; // ensures client is initialized
49
+
50
+ export const GET = withErrorCapture(async (request) => {
51
+ const users = await db.users.findMany();
52
+ return NextResponse.json({ users });
53
+ });
54
+
55
+ export const POST = withErrorCapture(async (request) => {
56
+ const body = await request.json();
57
+ const user = await db.users.create({ data: body });
58
+ return NextResponse.json({ user }, { status: 201 });
59
+ });
60
+ ```
61
+
62
+ **3. Dynamic routes with params:**
63
+
64
+ ```typescript
65
+ // app/api/users/[id]/route.ts
66
+ import { NextResponse } from "next/server";
67
+ import { withErrorCapture } from "bugstack-sdk/next";
68
+ import "@/lib/bugstack";
69
+
70
+ export const GET = withErrorCapture<{ id: string }>(
71
+ async (request, { params }) => {
72
+ const user = await db.users.findUnique({ where: { id: params.id } });
73
+ if (!user) throw new Error("User not found");
74
+ return NextResponse.json({ user });
75
+ }
76
+ );
77
+ ```
78
+
79
+ ---
80
+
81
+ ### Express
82
+
83
+ **Option A: Error handler middleware (recommended)**
84
+
85
+ ```typescript
86
+ import express from "express";
87
+ import { bugstackErrorHandler } from "bugstack-sdk/express";
88
+
89
+ const app = express();
90
+
91
+ // Your routes
92
+ app.get("/api/users", async (req, res) => {
93
+ const users = await db.users.findMany();
94
+ res.json({ users });
95
+ });
96
+
97
+ // Add the Bugstack error handler AFTER all routes
98
+ app.use(
99
+ bugstackErrorHandler({
100
+ apiKey: process.env.BUGSTACK_API_KEY!,
101
+ endpoint: "https://dashboard.bugstack.ai/api/ingest/sdk",
102
+ })
103
+ );
104
+ ```
105
+
106
+ **Option B: Wrap individual route handlers**
107
+
108
+ ```typescript
109
+ import { initBugStack, wrapExpressHandler } from "bugstack-sdk/express";
110
+
111
+ // Initialize once
112
+ app.use(
113
+ initBugStack({
114
+ apiKey: process.env.BUGSTACK_API_KEY!,
115
+ endpoint: "https://dashboard.bugstack.ai/api/ingest/sdk",
116
+ })
117
+ );
118
+
119
+ // Wrap specific routes
120
+ app.get("/api/users/:id", wrapExpressHandler(async (req, res) => {
121
+ const user = await getUser(req.params.id);
122
+ res.json(user);
123
+ }));
124
+ ```
125
+
126
+ ---
127
+
128
+ ### Generic Node.js
129
+
130
+ For any Node.js application (scripts, workers, serverless functions, etc.):
131
+
132
+ ```typescript
133
+ import { initBugStack, captureError, installGlobalHandlers } from "bugstack-sdk/generic";
134
+
135
+ // Initialize once
136
+ initBugStack({
137
+ apiKey: process.env.BUGSTACK_API_KEY!,
138
+ endpoint: "https://dashboard.bugstack.ai/api/ingest/sdk",
139
+ });
140
+
141
+ // Optional: catch uncaught exceptions and unhandled rejections globally
142
+ installGlobalHandlers();
143
+
144
+ // Capture errors manually in try/catch blocks
145
+ try {
146
+ await processData();
147
+ } catch (error) {
148
+ await captureError(error, { operation: "processData" });
149
+ }
150
+ ```
151
+
152
+ **Wrap functions for automatic capture:**
153
+
154
+ ```typescript
155
+ import { wrapFunction } from "bugstack-sdk/generic";
156
+
157
+ const processData = wrapFunction(
158
+ async (data: Input) => {
159
+ // errors thrown here are automatically captured
160
+ return transform(data);
161
+ },
162
+ { operation: "processData" }
163
+ );
164
+ ```
165
+
166
+ **Create scoped capture functions:**
167
+
168
+ ```typescript
169
+ import { createErrorCapture } from "bugstack-sdk/generic";
170
+
171
+ const captureDbError = createErrorCapture({ component: "database" });
172
+
173
+ try {
174
+ await db.query("SELECT ...");
175
+ } catch (error) {
176
+ await captureDbError(error, { query: "SELECT ..." });
177
+ }
178
+ ```
179
+
180
+ ---
181
+
182
+ ## Caught-and-Logged Errors
183
+
184
+ Most failures never reach an uncaught-exception handler. A `catch` block logs them and the app carries on:
185
+
186
+ ```typescript
187
+ try {
188
+ await grantCredits(order);
189
+ } catch (err) {
190
+ console.error("[billing] grant failed", err); // a log line nobody reads
191
+ }
192
+ ```
193
+
194
+ Once the client is initialised, the SDK forwards these to Bugstack. It is on by default, and the console line is written exactly as before.
195
+
196
+ **What is forwarded:** a `console.error` call that carries an `Error` (as an argument, or as the `err` / `error` field of an object argument), or a string holding a stack trace (`console.error("failed", err.stack)`). The report is anchored at the line that logged it, so each logging site is its own issue; the original error's name and stack ride along in `metadata.causeName` / `metadata.causeStack`. A `[billing]` style tag at the start of the line becomes the route (`log:billing`).
197
+
198
+ **What stays a console line:** a plain message with no error and no stack (unless you set `messages: true`), Node's own process warnings (`(node:1) [DEP0169] DeprecationWarning: …`), the SDK's own `[BugStack]` lines, and lines matching `ignore`. An error the SDK already reported (through `withErrorCapture`, `bugstackErrorHandler` or `captureError`) is not sent again when your framework logs it.
199
+
200
+ **Bounded:** at most 20 forwards a minute per process, the same site and message at most once per 5 minutes, then the usual fingerprint dedup. Logged text goes through the same `redactFields` as request data (`password=…`, `token: …`), and bearer tokens are masked. Only the message and stacks are sent, never the other log arguments. Forwarding never throws into your code.
201
+
202
+ ```typescript
203
+ ErrorCaptureClient.init({
204
+ apiKey: "your-api-key",
205
+
206
+ // captureConsoleErrors: false turns it off. To tune it instead
207
+ // (every field optional, defaults shown):
208
+ captureConsoleErrors: {
209
+ messages: false, // also forward console.error lines that carry only a message
210
+ maxPerMinute: 20,
211
+ repeatWindowMs: 5 * 60 * 1000,
212
+ ignore: [/ECONNRESET/], // strings or RegExps; matching lines stay console lines
213
+ },
214
+ });
215
+ ```
216
+
217
+ ### pino
218
+
219
+ ```typescript
220
+ import pino from "pino";
221
+ import { bugstackPinoHooks } from "bugstack-sdk";
222
+
223
+ const logger = pino({ hooks: bugstackPinoHooks() });
224
+
225
+ logger.error({ err, orderId }, "[checkout] charge failed"); // forwarded
226
+ ```
227
+
228
+ `error` and `fatal` logs are forwarded under the same rules. If you already use `hooks.logMethod`, call the returned `logMethod` from yours.
229
+
230
+ ### winston
231
+
232
+ ```typescript
233
+ import winston from "winston";
234
+ import { bugstackWinstonFormat } from "bugstack-sdk";
235
+
236
+ const logger = winston.createLogger({
237
+ format: winston.format.combine(bugstackWinstonFormat(), winston.format.json()),
238
+ transports: [new winston.transports.Console()],
239
+ });
240
+
241
+ logger.error("[upload] write failed", err); // forwarded
242
+ ```
243
+
244
+ Put `bugstackWinstonFormat()` first in the chain. `error` and higher levels are forwarded, and the log entry passes through unchanged.
245
+
246
+ `loggedErrorStats()` returns how many logged errors were forwarded and how many were left as log lines, counted per rule.
247
+
248
+ ---
249
+
250
+ ## Source Maps for Production (Next.js)
251
+
252
+ By default, server-side errors in a Next.js production build come back with stack frames that point at compiled chunks like `.next/server/chunks/8393.js:1:8734`. The Bugstack orchestrator can't fix what it can't locate — so without source maps, those errors land in your dashboard as "Could not identify primary file from error" and never auto-fix.
253
+
254
+ Uploading source maps closes that loop. The orchestrator resolves bundled frames back to source-file positions (`app/api/orders/route.ts:42:5`) before deciding which file to patch.
255
+
256
+ ### Two-step setup
257
+
258
+ **1. Wrap your `next.config.js`:**
259
+
260
+ ```js
261
+ const { withBugstack } = require('bugstack-sdk/next-config')
262
+
263
+ module.exports = withBugstack({
264
+ // your existing Next.js config
265
+ })
266
+ ```
267
+
268
+ This enables `webpack.devtool = 'source-map'` for production server builds (no effect on dev or client). Any existing `webpack` hook you have is preserved and runs first.
269
+
270
+ **2. Append the upload command to your `build` script:**
271
+
272
+ ```json
273
+ {
274
+ "scripts": {
275
+ "build": "next build && bugstack sourcemaps upload"
276
+ }
277
+ }
278
+ ```
279
+
280
+ The CLI walks `.next/server/**/*.map`, uploads each to Bugstack keyed by the active release, and **never fails the build** — source maps are an optimisation, not a release gate.
281
+
282
+ ### Required environment
283
+
284
+ The CLI needs two env vars at build time. Set them in your CI / hosting provider:
285
+
286
+ | Variable | Purpose |
287
+ |---|---|
288
+ | `BUGSTACK_PROJECT_API_KEY` | Your project SDK key (find it in your project settings on the Bugstack dashboard). |
289
+ | `BUGSTACK_ENDPOINT` | Base URL of the Bugstack ingest service. The CLI appends `/api/sourcemaps/upload` automatically. |
290
+
291
+ Release identifiers are auto-detected from `BUGSTACK_RELEASE`, `RENDER_GIT_COMMIT`, `VERCEL_GIT_COMMIT_SHA`, `GITHUB_SHA`, or `git rev-parse HEAD` — in that order. Override with `--release <id>` if you have a different versioning scheme.
292
+
293
+ ### Verifying
294
+
295
+ After your next deploy with these env vars set, the build log should print something like:
296
+
297
+ ```
298
+ [bugstack] Uploading 68 source map(s) to https://… (release=a9ad704)…
299
+ [bugstack] Uploaded 68/68 maps (10.0MB) in 4.2s.
300
+ ```
301
+
302
+ When a server-side error captures next, the row's stack trace and proposed fix will reference real source files (`app/api/.../route.ts`) instead of bundled chunks.
303
+
304
+ ### Programmatic API
305
+
306
+ If you'd rather drive the upload from a custom script:
307
+
308
+ ```ts
309
+ import { uploadSourceMaps } from 'bugstack-sdk/build'
310
+
311
+ await uploadSourceMaps({
312
+ apiKey: process.env.BUGSTACK_PROJECT_API_KEY,
313
+ endpoint: process.env.BUGSTACK_ENDPOINT,
314
+ release: process.env.GIT_SHA,
315
+ serverDir: '.next/server', // override for non-Next builds
316
+ })
317
+ ```
318
+
319
+ ### Other build systems
320
+
321
+ The CLI defaults to `.next/server` but accepts `--server-dir <path>` so it works for any directory of compiled `.js` + `.js.map` pairs (e.g. `dist/` for tsc, `build/` for CRA, custom esbuild outputs). The `withBugstack` wrapper is Next.js-specific; for other frameworks, enable source-map emission in your bundler config and run the CLI directly.
322
+
323
+ ---
324
+
325
+ ## Other Languages
326
+
327
+ Bugstack also provides SDKs for:
328
+
329
+ | Language | Package | Install |
330
+ |----------|---------|---------|
331
+ | Python | [bugstack](https://pypi.org/project/bugstack/) | `pip install bugstack` |
332
+ | Ruby | [bugstack](https://rubygems.org/gems/bugstack) | `gem install bugstack` |
333
+ | Go | [bugstack-go](https://github.com/MasonBachmann7/Bugstack-SDK-Go) | `go get github.com/MasonBachmann7/bugstack-go` |
334
+
335
+ ---
336
+
337
+ ## Configuration
338
+
339
+ ### Full Options
340
+
341
+ ```typescript
342
+ import { ErrorCaptureClient } from "bugstack-sdk";
343
+
344
+ ErrorCaptureClient.init({
345
+ // Required
346
+ apiKey: "your-api-key",
347
+
348
+ // Endpoint (defaults to the Bugstack ingest endpoint)
349
+ endpoint: "https://dashboard.bugstack.ai/api/ingest/sdk",
350
+
351
+ // Optional — defaults shown
352
+ projectId: "",
353
+ environment: process.env.NODE_ENV, // "development", "production", etc.
354
+ enabled: true, // set false to disable capture entirely
355
+
356
+ // Request capture
357
+ captureRequestBody: true,
358
+ captureQueryParams: true,
359
+ captureHeaders: true,
360
+ maxBodySize: 10000, // 10KB max body capture
361
+
362
+ // Additional fields to redact (added to built-in defaults)
363
+ redactFields: ["customSecret", "internalToken"],
364
+
365
+ // Custom metadata included with every error
366
+ metadata: { service: "api", version: "1.0.0" },
367
+
368
+ // Network
369
+ timeout: 5000, // 5s timeout for error reporting
370
+ deduplicationWindow: 5 * 60 * 1000, // 5 min window for dedup
371
+
372
+ // Debug logging (defaults to true in development)
373
+ debug: false,
374
+
375
+ // Custom filter — return false to skip certain errors
376
+ shouldCapture: (error, request) => {
377
+ if (error.message.includes("not found")) return false;
378
+ return true;
379
+ },
380
+
381
+ // Caught-and-logged errors (console.error); see "Caught-and-Logged Errors"
382
+ captureConsoleErrors: true, // false to turn off, or an options object
383
+
384
+ // Transform errors before sending
385
+ beforeSend: (capturedError) => {
386
+ capturedError.metadata = { ...capturedError.metadata, custom: "value" };
387
+ return capturedError; // return null to skip
388
+ },
389
+ });
390
+ ```
391
+
392
+ ### Environment Variables
393
+
394
+ The SDK reads these automatically:
395
+
396
+ ```bash
397
+ BUGSTACK_API_KEY=your-api-key # Required
398
+ BUGSTACK_ENDPOINT=https://dashboard.bugstack.ai/api/ingest/sdk # Optional
399
+ BUGSTACK_PROJECT_ID=my-project # Optional
400
+ NODE_ENV=production # Optional
401
+ ```
402
+
403
+ ### Per-Route Options (Next.js)
404
+
405
+ ```typescript
406
+ export const POST = withErrorCapture(
407
+ async (request) => { /* ... */ },
408
+ undefined, // use existing client config
409
+ {
410
+ statusCode: 400,
411
+ metadata: { operation: "createUser" },
412
+ shouldCapture: (error) => error.name !== "ValidationError",
413
+ }
414
+ );
415
+ ```
416
+
417
+ ---
418
+
419
+ ## Automatic Sanitization
420
+
421
+ The SDK redacts sensitive data from headers, request bodies, and query params, and from the text of caught-and-logged errors.
422
+
423
+ **Built-in redacted fields:**
424
+ `password`, `secret`, `token`, `apikey`, `api_key`, `apiKey`, `authorization`, `auth`, `credential`, `private`, `credit_card`, `creditcard`, `card_number`, `cvv`, `ssn`, `social_security`
425
+
426
+ **Always-redacted headers:**
427
+ `authorization`, `cookie`, `set-cookie`, `x-api-key`, `x-auth-token`, `proxy-authorization`
428
+
429
+ Add custom fields via the `redactFields` config option.
430
+
431
+ ---
432
+
433
+ ## Error Resilience
434
+
435
+ The SDK never interferes with your application:
436
+
437
+ - **Network failures** — Silently retried (up to 5 times with exponential backoff)
438
+ - **Timeouts** — Configurable, defaults to 5 seconds
439
+ - **SDK errors** — Caught and logged in debug mode, never thrown to your app
440
+ - **Console behaviour preserved** — `console.error` writes exactly what it wrote before; forwarding happens after, one tick later
441
+ - **Original error preserved** — The wrapper re-throws the original error so your framework handles the response normally
442
+
443
+ ---
444
+
445
+ ## Captured Data
446
+
447
+ Each error report includes:
448
+
449
+ | Field | Description |
450
+ |-------|-------------|
451
+ | `id` | Unique error ID |
452
+ | `fingerprint` | Stable hash for deduplication |
453
+ | `name` | Error type (TypeError, etc.) |
454
+ | `message` | Error message |
455
+ | `stack` | Full stack trace |
456
+ | `stackFrames` | Parsed stack frames with file, line, column |
457
+ | `route` | API route path |
458
+ | `method` | HTTP method |
459
+ | `statusCode` | HTTP status code |
460
+ | `url` | Full request URL |
461
+ | `queryParams` | Sanitized query parameters |
462
+ | `requestBody` | Sanitized request body |
463
+ | `requestHeaders` | Sanitized headers |
464
+ | `routeParams` | Dynamic route parameters |
465
+ | `environment` | Environment name |
466
+ | `projectId` | Project identifier |
467
+ | `metadata` | Custom metadata |
468
+
469
+ ---
470
+
471
+ ## TypeScript
472
+
473
+ All types are exported:
474
+
475
+ ```typescript
476
+ import type {
477
+ ErrorCaptureConfig,
478
+ CapturedError,
479
+ StackFrame,
480
+ RouteOptions,
481
+ RouteContext,
482
+ ErrorReportPayload,
483
+ SourceContext,
484
+ } from "bugstack-sdk";
485
+ ```
486
+
487
+ ## Compatibility
488
+
489
+ - **Next.js**: 14.0.0+
490
+ - **Express**: 4.x or 5.x
491
+ - **Node.js**: 18.0.0+
492
+ - **TypeScript**: 5.0.0+ (optional)
493
+
494
+ ## License
495
+
496
+ MIT