bugstack-sdk 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,317 +1,310 @@
1
- # bugstack-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
- **Get your API key at:** https://dashboard.bugstack.ai
6
-
7
- ## Features
8
-
9
- - **Zero-config wrapping** - Simply wrap your route handlers with `withErrorCapture`
10
- - **Full error context** - Captures stack traces, request body, headers, query params
11
- - **Automatic sanitization** - Sensitive data (passwords, tokens, etc.) is automatically redacted
12
- - **Non-blocking** - Error reporting happens asynchronously without slowing down responses
13
- - **TypeScript first** - Full type safety with comprehensive type definitions
14
- - **Production ready** - Configurable timeouts, error handling, and kill switches
15
-
16
- ## Installation
17
-
18
- ```bash
19
- npm install bugstack-sdk
20
- # or
21
- pnpm add bugstack-sdk
22
- # or
23
- yarn add bugstack-sdk
24
- ```
25
-
26
- ## Quick Start
27
-
28
- ### 1. Initialize the client (once, in a shared file)
29
-
30
- ```typescript
31
- // lib/bugstack.ts
32
- import { ErrorCaptureClient } from "bugstack-sdk";
33
-
34
- export const bugstack = ErrorCaptureClient.init({
35
- apiKey: process.env.BUGSTACK_API_KEY!,
36
- projectId: "my-project",
37
- // Optional: customize endpoint
38
- // endpoint: "https://your-bugstack-server.com/api/capture",
39
- });
40
- ```
41
-
42
- ### 2. Wrap your API routes
43
-
44
- ```typescript
45
- // app/api/users/route.ts
46
- import { NextResponse } from "next/server";
47
- import { withErrorCapture } from "bugstack-sdk";
48
- import "@/lib/bugstack"; // Ensure 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";
68
- import "@/lib/bugstack";
69
-
70
- export const GET = withErrorCapture<{ id: string }>(
71
- async (request, { params }) => {
72
- const user = await db.users.findUnique({
73
- where: { id: params.id },
74
- });
75
-
76
- if (!user) {
77
- throw new Error("User not found");
78
- }
79
-
80
- return NextResponse.json({ user });
81
- }
82
- );
83
- ```
84
-
85
- ## Configuration
86
-
87
- ### Full Configuration Options
88
-
89
- ```typescript
90
- import { ErrorCaptureClient } from "bugstack-sdk";
91
-
92
- ErrorCaptureClient.init({
93
- // Required
94
- apiKey: "your-api-key",
95
-
96
- // Optional - defaults shown
97
- endpoint: "http://localhost:3001/api/capture",
98
- projectId: "",
99
- environment: process.env.NODE_ENV, // "development", "production", etc.
100
- enabled: true, // Set to false to disable capture
101
-
102
- // Request capture options
103
- captureRequestBody: true,
104
- captureQueryParams: true,
105
- captureHeaders: true,
106
- maxBodySize: 10000, // 10KB max body capture
107
-
108
- // Additional fields to redact (added to defaults)
109
- redactFields: ["customSecret", "internalToken"],
110
-
111
- // Custom metadata included with every error
112
- metadata: {
113
- service: "api",
114
- version: "1.0.0",
115
- },
116
-
117
- // Network options
118
- timeout: 5000, // 5 second timeout for error reporting
119
-
120
- // Debug logging (defaults to true in development)
121
- debug: true,
122
-
123
- // Custom filter - return false to skip certain errors
124
- shouldCapture: (error, request) => {
125
- // Don't capture 404s
126
- if (error.message.includes("not found")) {
127
- return false;
128
- }
129
- return true;
130
- },
131
-
132
- // Transform errors before sending
133
- beforeSend: (capturedError) => {
134
- // Add custom data
135
- capturedError.metadata = {
136
- ...capturedError.metadata,
137
- customField: "value",
138
- };
139
- return capturedError;
140
- // Return null to skip this error
141
- },
142
- });
143
- ```
144
-
145
- ### Environment Variables
146
-
147
- The SDK automatically reads these environment variables:
148
-
149
- ```bash
150
- # Required
151
- BUGSTACK_API_KEY=your-api-key
152
-
153
- # Optional
154
- BUGSTACK_ENDPOINT=https://bugstack-error-service.onrender.com/api/capture
155
- BUGSTACK_PROJECT_ID=my-project
156
- NODE_ENV=production
157
- ```
158
-
159
- **Note:** The default endpoint is `http://localhost:3001/api/capture` for local development. Set `BUGSTACK_ENDPOINT` to the production URL shown above for deployed applications.
160
-
161
- ### Per-Route Options
162
-
163
- You can override options for specific routes:
164
-
165
- ```typescript
166
- export const POST = withErrorCapture(
167
- async (request) => {
168
- // handler code
169
- },
170
- undefined, // Use existing client config
171
- {
172
- // Route-specific options
173
- statusCode: 400, // Report as 400 instead of 500
174
- metadata: {
175
- operation: "createUser",
176
- critical: true,
177
- },
178
- shouldCapture: (error) => {
179
- // Route-specific filter
180
- return error.name !== "ValidationError";
181
- },
182
- }
183
- );
184
- ```
185
-
186
- ## Captured Error Data
187
-
188
- Each error report includes:
189
-
190
- ```typescript
191
- interface CapturedError {
192
- id: string; // Unique error ID (err_xxx_xxx)
193
- name: string; // Error name (TypeError, etc.)
194
- message: string; // Error message
195
- stack: string; // Full stack trace
196
- stackFrames: StackFrame[]; // Parsed stack frames
197
- timestamp: string; // ISO 8601 timestamp
198
- route: string; // API route path
199
- method: string; // HTTP method
200
- statusCode: number; // HTTP status code
201
- url: string; // Full request URL
202
- queryParams: object; // Query parameters (sanitized)
203
- requestBody: unknown; // Request body (sanitized)
204
- requestHeaders: object; // Headers (sanitized)
205
- routeParams: object; // Dynamic route params
206
- environment: string; // Environment name
207
- projectId: string; // Project identifier
208
- sdkVersion: string; // SDK version
209
- nodeVersion: string; // Node.js version
210
- nextVersion: string; // Next.js version
211
- metadata: object; // Custom metadata
212
- }
213
- ```
214
-
215
- ## Automatic Data Sanitization
216
-
217
- The SDK automatically redacts sensitive fields from:
218
- - Request headers (Authorization, Cookie, etc.)
219
- - Request body
220
- - Query parameters
221
-
222
- **Default redacted fields:**
223
- - password, secret, token
224
- - apikey, api_key, apiKey
225
- - authorization, auth, credential
226
- - credit_card, creditcard, card_number
227
- - cvv, ssn, social_security
228
-
229
- Add custom fields via `redactFields` config option.
230
-
231
- ## Error Handling
232
-
233
- The SDK is designed to never interfere with your application:
234
-
235
- - **Network failures** - Silently ignored, your app continues normally
236
- - **Timeouts** - Configurable, defaults to 5 seconds
237
- - **SDK errors** - Caught and logged (in debug mode), never thrown
238
- - **Re-throws original error** - Next.js still handles the error response
239
-
240
- ## Advanced Usage
241
-
242
- ### Manual Error Reporting
243
-
244
- ```typescript
245
- import { ErrorCaptureClient } from "bugstack-sdk";
246
-
247
- const client = ErrorCaptureClient.getInstance();
248
-
249
- if (client) {
250
- await client.reportError({
251
- id: "manual_001",
252
- name: "CustomError",
253
- message: "Something went wrong",
254
- timestamp: new Date().toISOString(),
255
- route: "/api/custom",
256
- method: "POST",
257
- statusCode: 500,
258
- url: "https://example.com/api/custom",
259
- environment: "production",
260
- sdkVersion: "1.0.0",
261
- nodeVersion: process.version,
262
- });
263
- }
264
- ```
265
-
266
- ### Stack Trace Utilities
267
-
268
- ```typescript
269
- import {
270
- parseStackTrace,
271
- getFirstAppFrame,
272
- getAppFrames,
273
- } from "bugstack-sdk";
274
-
275
- const frames = parseStackTrace(error.stack);
276
- const firstAppFrame = getFirstAppFrame(frames); // First non-node_modules frame
277
- const appFrames = getAppFrames(frames); // All application frames
278
- ```
279
-
280
- ### Sanitization Utilities
281
-
282
- ```typescript
283
- import {
284
- sanitizeHeaders,
285
- sanitizeQueryParams,
286
- sanitizeObject,
287
- } from "bugstack-sdk";
288
-
289
- const safeHeaders = sanitizeHeaders(request.headers);
290
- const safeParams = sanitizeQueryParams(new URL(request.url));
291
- const safeBody = sanitizeObject(requestBody);
292
- ```
293
-
294
- ## TypeScript Support
295
-
296
- Full type definitions are included:
297
-
298
- ```typescript
299
- import type {
300
- ErrorCaptureConfig,
301
- CapturedError,
302
- StackFrame,
303
- RouteOptions,
304
- NextRouteHandler,
305
- RouteContext,
306
- } from "bugstack-sdk";
307
- ```
308
-
309
- ## Compatibility
310
-
311
- - **Next.js**: 14.0.0+
312
- - **Node.js**: 18.0.0+
313
- - **TypeScript**: 5.0.0+ (optional)
314
-
315
- ## License
316
-
317
- MIT
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