bugstack-sdk 2.0.0 → 2.0.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,310 +1,346 @@
1
- # @bugstack/error-capture-sdk
2
-
3
- Error capture SDK for Next.js 14+ App Router API routes. Automatically captures errors with full context and reports them to the BugStack service for AI-powered fix generation.
4
-
5
- ## Features
6
-
7
- - **Zero-config wrapping** - Simply wrap your route handlers with `withErrorCapture`
8
- - **Full error context** - Captures stack traces, request body, headers, query params
9
- - **Automatic sanitization** - Sensitive data (passwords, tokens, etc.) is automatically redacted
10
- - **Non-blocking** - Error reporting happens asynchronously without slowing down responses
11
- - **TypeScript first** - Full type safety with comprehensive type definitions
12
- - **Production ready** - Configurable timeouts, error handling, and kill switches
13
-
14
- ## Installation
15
-
16
- ```bash
17
- npm install @bugstack/error-capture-sdk
18
- # or
19
- pnpm add @bugstack/error-capture-sdk
20
- # or
21
- yarn add @bugstack/error-capture-sdk
22
- ```
23
-
24
- ## Quick Start
25
-
26
- ### 1. Initialize the client (once, in a shared file)
27
-
28
- ```typescript
29
- // lib/bugstack.ts
30
- import { ErrorCaptureClient } from "@bugstack/error-capture-sdk";
31
-
32
- export const bugstack = ErrorCaptureClient.init({
33
- apiKey: process.env.BUGSTACK_API_KEY!,
34
- projectId: "my-project",
35
- // Optional: customize endpoint
36
- // endpoint: "https://your-bugstack-server.com/api/capture",
37
- });
38
- ```
39
-
40
- ### 2. Wrap your API routes
41
-
42
- ```typescript
43
- // app/api/users/route.ts
44
- import { NextResponse } from "next/server";
45
- import { withErrorCapture } from "@bugstack/error-capture-sdk";
46
- import "@/lib/bugstack"; // Ensure client is initialized
47
-
48
- export const GET = withErrorCapture(async (request) => {
49
- const users = await db.users.findMany();
50
- return NextResponse.json({ users });
51
- });
52
-
53
- export const POST = withErrorCapture(async (request) => {
54
- const body = await request.json();
55
- const user = await db.users.create({ data: body });
56
- return NextResponse.json({ user }, { status: 201 });
57
- });
58
- ```
59
-
60
- ### 3. Dynamic routes with params
61
-
62
- ```typescript
63
- // app/api/users/[id]/route.ts
64
- import { NextResponse } from "next/server";
65
- import { withErrorCapture } from "@bugstack/error-capture-sdk";
66
- import "@/lib/bugstack";
67
-
68
- export const GET = withErrorCapture<{ id: string }>(
69
- async (request, { params }) => {
70
- const user = await db.users.findUnique({
71
- where: { id: params.id },
72
- });
73
-
74
- if (!user) {
75
- throw new Error("User not found");
76
- }
77
-
78
- return NextResponse.json({ user });
79
- }
80
- );
81
- ```
82
-
83
- ## Configuration
84
-
85
- ### Full Configuration Options
86
-
87
- ```typescript
88
- import { ErrorCaptureClient } from "@bugstack/error-capture-sdk";
89
-
90
- ErrorCaptureClient.init({
91
- // Required
92
- apiKey: "your-api-key",
93
-
94
- // Optional - defaults shown
95
- endpoint: "http://localhost:3001/api/capture",
96
- projectId: "",
97
- environment: process.env.NODE_ENV, // "development", "production", etc.
98
- enabled: true, // Set to false to disable capture
99
-
100
- // Request capture options
101
- captureRequestBody: true,
102
- captureQueryParams: true,
103
- captureHeaders: true,
104
- maxBodySize: 10000, // 10KB max body capture
105
-
106
- // Additional fields to redact (added to defaults)
107
- redactFields: ["customSecret", "internalToken"],
108
-
109
- // Custom metadata included with every error
110
- metadata: {
111
- service: "api",
112
- version: "1.0.0",
113
- },
114
-
115
- // Network options
116
- timeout: 5000, // 5 second timeout for error reporting
117
-
118
- // Debug logging (defaults to true in development)
119
- debug: true,
120
-
121
- // Custom filter - return false to skip certain errors
122
- shouldCapture: (error, request) => {
123
- // Don't capture 404s
124
- if (error.message.includes("not found")) {
125
- return false;
126
- }
127
- return true;
128
- },
129
-
130
- // Transform errors before sending
131
- beforeSend: (capturedError) => {
132
- // Add custom data
133
- capturedError.metadata = {
134
- ...capturedError.metadata,
135
- customField: "value",
136
- };
137
- return capturedError;
138
- // Return null to skip this error
139
- },
140
- });
141
- ```
142
-
143
- ### Environment Variables
144
-
145
- The SDK automatically reads these environment variables:
146
-
147
- ```bash
148
- BUGSTACK_ENDPOINT=http://localhost:3001/api/capture
149
- BUGSTACK_API_KEY=your-api-key
150
- BUGSTACK_PROJECT_ID=my-project
151
- NODE_ENV=development
152
- ```
153
-
154
- ### Per-Route Options
155
-
156
- You can override options for specific routes:
157
-
158
- ```typescript
159
- export const POST = withErrorCapture(
160
- async (request) => {
161
- // handler code
162
- },
163
- undefined, // Use existing client config
164
- {
165
- // Route-specific options
166
- statusCode: 400, // Report as 400 instead of 500
167
- metadata: {
168
- operation: "createUser",
169
- critical: true,
170
- },
171
- shouldCapture: (error) => {
172
- // Route-specific filter
173
- return error.name !== "ValidationError";
174
- },
175
- }
176
- );
177
- ```
178
-
179
- ## Captured Error Data
180
-
181
- Each error report includes:
182
-
183
- ```typescript
184
- interface CapturedError {
185
- id: string; // Unique error ID (err_xxx_xxx)
186
- name: string; // Error name (TypeError, etc.)
187
- message: string; // Error message
188
- stack: string; // Full stack trace
189
- stackFrames: StackFrame[]; // Parsed stack frames
190
- timestamp: string; // ISO 8601 timestamp
191
- route: string; // API route path
192
- method: string; // HTTP method
193
- statusCode: number; // HTTP status code
194
- url: string; // Full request URL
195
- queryParams: object; // Query parameters (sanitized)
196
- requestBody: unknown; // Request body (sanitized)
197
- requestHeaders: object; // Headers (sanitized)
198
- routeParams: object; // Dynamic route params
199
- environment: string; // Environment name
200
- projectId: string; // Project identifier
201
- sdkVersion: string; // SDK version
202
- nodeVersion: string; // Node.js version
203
- nextVersion: string; // Next.js version
204
- metadata: object; // Custom metadata
205
- }
206
- ```
207
-
208
- ## Automatic Data Sanitization
209
-
210
- The SDK automatically redacts sensitive fields from:
211
- - Request headers (Authorization, Cookie, etc.)
212
- - Request body
213
- - Query parameters
214
-
215
- **Default redacted fields:**
216
- - password, secret, token
217
- - apikey, api_key, apiKey
218
- - authorization, auth, credential
219
- - credit_card, creditcard, card_number
220
- - cvv, ssn, social_security
221
-
222
- Add custom fields via `redactFields` config option.
223
-
224
- ## Error Handling
225
-
226
- The SDK is designed to never interfere with your application:
227
-
228
- - **Network failures** - Silently ignored, your app continues normally
229
- - **Timeouts** - Configurable, defaults to 5 seconds
230
- - **SDK errors** - Caught and logged (in debug mode), never thrown
231
- - **Re-throws original error** - Next.js still handles the error response
232
-
233
- ## Advanced Usage
234
-
235
- ### Manual Error Reporting
236
-
237
- ```typescript
238
- import { ErrorCaptureClient } from "@bugstack/error-capture-sdk";
239
-
240
- const client = ErrorCaptureClient.getInstance();
241
-
242
- if (client) {
243
- await client.reportError({
244
- id: "manual_001",
245
- name: "CustomError",
246
- message: "Something went wrong",
247
- timestamp: new Date().toISOString(),
248
- route: "/api/custom",
249
- method: "POST",
250
- statusCode: 500,
251
- url: "https://example.com/api/custom",
252
- environment: "production",
253
- sdkVersion: "0.1.0",
254
- nodeVersion: process.version,
255
- });
256
- }
257
- ```
258
-
259
- ### Stack Trace Utilities
260
-
261
- ```typescript
262
- import {
263
- parseStackTrace,
264
- getFirstAppFrame,
265
- getAppFrames,
266
- } from "@bugstack/error-capture-sdk";
267
-
268
- const frames = parseStackTrace(error.stack);
269
- const firstAppFrame = getFirstAppFrame(frames); // First non-node_modules frame
270
- const appFrames = getAppFrames(frames); // All application frames
271
- ```
272
-
273
- ### Sanitization Utilities
274
-
275
- ```typescript
276
- import {
277
- sanitizeHeaders,
278
- sanitizeQueryParams,
279
- sanitizeObject,
280
- } from "@bugstack/error-capture-sdk";
281
-
282
- const safeHeaders = sanitizeHeaders(request.headers);
283
- const safeParams = sanitizeQueryParams(new URL(request.url));
284
- const safeBody = sanitizeObject(requestBody);
285
- ```
286
-
287
- ## TypeScript Support
288
-
289
- Full type definitions are included:
290
-
291
- ```typescript
292
- import type {
293
- ErrorCaptureConfig,
294
- CapturedError,
295
- StackFrame,
296
- RouteOptions,
297
- NextRouteHandler,
298
- RouteContext,
299
- } from "@bugstack/error-capture-sdk";
300
- ```
301
-
302
- ## Compatibility
303
-
304
- - **Next.js**: 14.0.0+
305
- - **Node.js**: 18.0.0+
306
- - **TypeScript**: 5.0.0+ (optional)
307
-
308
- ## License
309
-
310
- MIT
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
+ ## Other Languages
180
+
181
+ BugStack also provides SDKs for:
182
+
183
+ | Language | Package | Install |
184
+ |----------|---------|---------|
185
+ | Python | [bugstack](https://pypi.org/project/bugstack/) | `pip install bugstack` |
186
+ | Ruby | [bugstack](https://rubygems.org/gems/bugstack) | `gem install bugstack` |
187
+ | Go | [bugstack-go](https://github.com/MasonBachmann7/Bugstack-SDK-Go) | `go get github.com/MasonBachmann7/bugstack-go` |
188
+
189
+ ---
190
+
191
+ ## Configuration
192
+
193
+ ### Full Options
194
+
195
+ ```typescript
196
+ import { ErrorCaptureClient } from "bugstack-sdk";
197
+
198
+ ErrorCaptureClient.init({
199
+ // Required
200
+ apiKey: "your-api-key",
201
+
202
+ // Endpoint (defaults to localhost for local dev)
203
+ endpoint: "https://bugstack-error-service.onrender.com/api/capture",
204
+
205
+ // Optional — defaults shown
206
+ projectId: "",
207
+ environment: process.env.NODE_ENV, // "development", "production", etc.
208
+ enabled: true, // set false to disable capture entirely
209
+
210
+ // Request capture
211
+ captureRequestBody: true,
212
+ captureQueryParams: true,
213
+ captureHeaders: true,
214
+ maxBodySize: 10000, // 10KB max body capture
215
+
216
+ // Additional fields to redact (added to built-in defaults)
217
+ redactFields: ["customSecret", "internalToken"],
218
+
219
+ // Custom metadata included with every error
220
+ metadata: { service: "api", version: "1.0.0" },
221
+
222
+ // Network
223
+ timeout: 5000, // 5s timeout for error reporting
224
+ deduplicationWindow: 5 * 60 * 1000, // 5 min window for dedup
225
+
226
+ // Debug logging (defaults to true in development)
227
+ debug: false,
228
+
229
+ // Custom filter — return false to skip certain errors
230
+ shouldCapture: (error, request) => {
231
+ if (error.message.includes("not found")) return false;
232
+ return true;
233
+ },
234
+
235
+ // Transform errors before sending
236
+ beforeSend: (capturedError) => {
237
+ capturedError.metadata = { ...capturedError.metadata, custom: "value" };
238
+ return capturedError; // return null to skip
239
+ },
240
+ });
241
+ ```
242
+
243
+ ### Environment Variables
244
+
245
+ The SDK reads these automatically:
246
+
247
+ ```bash
248
+ BUGSTACK_API_KEY=your-api-key # Required
249
+ BUGSTACK_ENDPOINT=https://bugstack-error-service.onrender.com/api/capture # Optional
250
+ BUGSTACK_PROJECT_ID=my-project # Optional
251
+ NODE_ENV=production # Optional
252
+ ```
253
+
254
+ ### Per-Route Options (Next.js)
255
+
256
+ ```typescript
257
+ export const POST = withErrorCapture(
258
+ async (request) => { /* ... */ },
259
+ undefined, // use existing client config
260
+ {
261
+ statusCode: 400,
262
+ metadata: { operation: "createUser" },
263
+ shouldCapture: (error) => error.name !== "ValidationError",
264
+ }
265
+ );
266
+ ```
267
+
268
+ ---
269
+
270
+ ## Automatic Sanitization
271
+
272
+ The SDK redacts sensitive data from headers, request bodies, and query params.
273
+
274
+ **Built-in redacted fields:**
275
+ `password`, `secret`, `token`, `apikey`, `api_key`, `apiKey`, `authorization`, `auth`, `credential`, `private`, `credit_card`, `creditcard`, `card_number`, `cvv`, `ssn`, `social_security`
276
+
277
+ **Always-redacted headers:**
278
+ `authorization`, `cookie`, `set-cookie`, `x-api-key`, `x-auth-token`, `proxy-authorization`
279
+
280
+ Add custom fields via the `redactFields` config option.
281
+
282
+ ---
283
+
284
+ ## Error Resilience
285
+
286
+ The SDK never interferes with your application:
287
+
288
+ - **Network failures** — Silently retried (up to 5 times with exponential backoff)
289
+ - **Timeouts** — Configurable, defaults to 5 seconds
290
+ - **SDK errors** — Caught and logged in debug mode, never thrown to your app
291
+ - **Original error preserved** — The wrapper re-throws the original error so your framework handles the response normally
292
+
293
+ ---
294
+
295
+ ## Captured Data
296
+
297
+ Each error report includes:
298
+
299
+ | Field | Description |
300
+ |-------|-------------|
301
+ | `id` | Unique error ID |
302
+ | `fingerprint` | Stable hash for deduplication |
303
+ | `name` | Error type (TypeError, etc.) |
304
+ | `message` | Error message |
305
+ | `stack` | Full stack trace |
306
+ | `stackFrames` | Parsed stack frames with file, line, column |
307
+ | `route` | API route path |
308
+ | `method` | HTTP method |
309
+ | `statusCode` | HTTP status code |
310
+ | `url` | Full request URL |
311
+ | `queryParams` | Sanitized query parameters |
312
+ | `requestBody` | Sanitized request body |
313
+ | `requestHeaders` | Sanitized headers |
314
+ | `routeParams` | Dynamic route parameters |
315
+ | `environment` | Environment name |
316
+ | `projectId` | Project identifier |
317
+ | `metadata` | Custom metadata |
318
+
319
+ ---
320
+
321
+ ## TypeScript
322
+
323
+ All types are exported:
324
+
325
+ ```typescript
326
+ import type {
327
+ ErrorCaptureConfig,
328
+ CapturedError,
329
+ StackFrame,
330
+ RouteOptions,
331
+ RouteContext,
332
+ ErrorReportPayload,
333
+ SourceContext,
334
+ } from "bugstack-sdk";
335
+ ```
336
+
337
+ ## Compatibility
338
+
339
+ - **Next.js**: 14.0.0+
340
+ - **Express**: 4.x or 5.x
341
+ - **Node.js**: 18.0.0+
342
+ - **TypeScript**: 5.0.0+ (optional)
343
+
344
+ ## License
345
+
346
+ MIT