bugstack-sdk 2.2.1 → 2.2.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/CHANGELOG.md +109 -96
- package/README.md +423 -421
- package/bin/bugstack.cjs +6 -6
- package/dist/adapters/express/index.d.mts +2 -2
- package/dist/adapters/express/index.d.ts +2 -2
- package/dist/adapters/express/index.js +2 -2
- package/dist/adapters/express/index.js.map +1 -1
- package/dist/adapters/express/index.mjs +2 -2
- package/dist/adapters/express/index.mjs.map +1 -1
- package/dist/adapters/generic/index.d.mts +2 -2
- package/dist/adapters/generic/index.d.ts +2 -2
- package/dist/adapters/generic/index.js +2 -2
- package/dist/adapters/generic/index.js.map +1 -1
- package/dist/adapters/generic/index.mjs +2 -2
- package/dist/adapters/generic/index.mjs.map +1 -1
- package/dist/adapters/nextjs/index.d.mts +2 -2
- package/dist/adapters/nextjs/index.d.ts +2 -2
- package/dist/adapters/nextjs/index.js +2 -2
- package/dist/adapters/nextjs/index.js.map +1 -1
- package/dist/adapters/nextjs/index.mjs +2 -2
- package/dist/adapters/nextjs/index.mjs.map +1 -1
- package/dist/build/cli.js.map +1 -1
- package/dist/build/cli.mjs.map +1 -1
- package/dist/build/upload.js.map +1 -1
- package/dist/build/upload.mjs.map +1 -1
- package/dist/{client-DoqE7sNh.d.mts → client-DK_ItP55.d.mts} +1 -1
- package/dist/{client-DoqE7sNh.d.ts → client-DK_ItP55.d.ts} +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/next-config/index.js.map +1 -1
- package/dist/next-config/index.mjs.map +1 -1
- package/package.json +103 -104
package/bin/bugstack.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// Tiny shebang stub — keeps the `npx bugstack ...` entry point working
|
|
3
|
-
// without having to wrestle tsup into preserving a shebang on the bundled
|
|
4
|
-
// output. Adding/removing CLI logic happens in src/build/cli.ts; this
|
|
5
|
-
// file only ever needs to require the built artifact.
|
|
6
|
-
require("../dist/build/cli.js");
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Tiny shebang stub — keeps the `npx bugstack ...` entry point working
|
|
3
|
+
// without having to wrestle tsup into preserving a shebang on the bundled
|
|
4
|
+
// output. Adding/removing CLI logic happens in src/build/cli.ts; this
|
|
5
|
+
// file only ever needs to require the built artifact.
|
|
6
|
+
require("../dist/build/cli.js");
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ErrorRequestHandler, Request, Response, NextFunction } from 'express';
|
|
2
|
-
import { E as ErrorCaptureConfig } from '../../client-
|
|
3
|
-
export { B as BugStackClient, C as CapturedError, a as ErrorCaptureClient } from '../../client-
|
|
2
|
+
import { E as ErrorCaptureConfig } from '../../client-DK_ItP55.mjs';
|
|
3
|
+
export { B as BugStackClient, C as CapturedError, a as ErrorCaptureClient } from '../../client-DK_ItP55.mjs';
|
|
4
4
|
import 'next/server';
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ErrorRequestHandler, Request, Response, NextFunction } from 'express';
|
|
2
|
-
import { E as ErrorCaptureConfig } from '../../client-
|
|
3
|
-
export { B as BugStackClient, C as CapturedError, a as ErrorCaptureClient } from '../../client-
|
|
2
|
+
import { E as ErrorCaptureConfig } from '../../client-DK_ItP55.js';
|
|
3
|
+
export { B as BugStackClient, C as CapturedError, a as ErrorCaptureClient } from '../../client-DK_ItP55.js';
|
|
4
4
|
import 'next/server';
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -431,10 +431,10 @@ var RetryQueue = class {
|
|
|
431
431
|
};
|
|
432
432
|
|
|
433
433
|
// src/core/sdk-version.ts
|
|
434
|
-
var SDK_VERSION = "2.2.
|
|
434
|
+
var SDK_VERSION = "2.2.2" ;
|
|
435
435
|
|
|
436
436
|
// src/core/client.ts
|
|
437
|
-
var DEFAULT_ENDPOINT = "
|
|
437
|
+
var DEFAULT_ENDPOINT = "https://dashboard.bugstack.ai/api/ingest/sdk";
|
|
438
438
|
var DEFAULT_TIMEOUT = 5e3;
|
|
439
439
|
var DEFAULT_MAX_BODY_SIZE = 1e4;
|
|
440
440
|
var DEFAULT_DEDUPLICATION_WINDOW = 5 * 60 * 1e3;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/core/fingerprint.ts","../../../src/core/deduplicator.ts","../../../src/core/queue.ts","../../../src/core/sdk-version.ts","../../../src/core/client.ts","../../../src/core/utils/stack-parser.ts","../../../src/core/utils/sanitize.ts","../../../src/adapters/express/index.ts"],"names":[],"mappings":";;;;;;;;;;AAcO,SAAS,yBAAyB,KAAA,EAA8B;AAErE,EAAA,MAAM,SAAA,GAAY,MAAM,IAAA,IAAQ,OAAA;AAChC,EAAA,MAAM,KAAA,GAAQ,MAAM,KAAA,IAAS,SAAA;AAC7B,EAAA,MAAM,cAAA,GAAiB,iBAAA,CAAkB,KAAA,CAAM,KAAK,CAAA;AAEpD,EAAA,MAAM,MAAM,CAAA,EAAG,SAAS,CAAA,CAAA,EAAI,KAAK,IAAI,cAAc,CAAA,CAAA;AAGnD,EAAA,OAAO,WAAW,GAAG,CAAA;AACvB;AASA,SAAS,kBAAkB,KAAA,EAAwB;AACjD,EAAA,IAAI,CAAC,OAAO,OAAO,SAAA;AAEnB,EAAA,MAAM,KAAA,GAAQ,KAAA,CAAM,KAAA,CAAM,IAAI,CAAA;AAI9B,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,MAAM,OAAA,GAAU,KAAK,IAAA,EAAK;AAC1B,IAAA,IAAI,OAAA,CAAQ,UAAA,CAAW,KAAK,CAAA,EAAG;AAC7B,MAAA,OAAO,OAAA;AAAA,IACT;AAAA,EACF;AAGA,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO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,EACqB;AAErB,EAAA,IAAI,MAAA,IAAU,CAAC,kBAAA,CAAmB,aAAA,EAAc,EAAG;AACjD,IAAA,kBAAA,CAAmB,KAAK,MAAM,CAAA;AAAA,EAChC;AAGA,EAAA,OAAO,CAAC,GAAA,EAAY,GAAA,EAAc,IAAA,EAAgB,IAAA,KAA6B;AAC7E,IAAA,MAAM,MAAA,GAAS,mBAAmB,WAAA,EAAY;AAE9C,IAAA,IAAI,MAAA,IAAU,MAAA,CAAO,SAAA,EAAU,CAAE,OAAA,EAAS;AAExC,MAAA,MAAM,aAAA,GAAgB,kBAAA,CAAmB,GAAA,EAAK,GAAA,EAAK,MAAM,CAAA;AAEzD,MAAA,MAAA,CAAO,WAAA,CAAY,aAAa,CAAA,CAAE,KAAA,CAAM,MAAM;AAAA,MAE9C,CAAC,CAAA;AAAA,IACH;AAGA,IAAA,IAAA,CAAK,GAAG,CAAA;AAAA,EACV,CAAA;AACF;AA2BO,SAAS,aAAa,MAAA,EAA4B;AACvD,EAAA,IAAI,CAAC,kBAAA,CAAmB,aAAA,EAAc,EAAG;AACvC,IAAA,kBAAA,CAAmB,KAAK,MAAM,CAAA;AAAA,EAChC;AAGA,EAAA,OAAO,CAAC,IAAA,EAAe,IAAA,EAAgB,IAAA,KAA6B;AAClE,IAAA,IAAA,EAAK;AAAA,EACP,CAAA;AACF;AAkBO,SAAS,mBACd,OAAA,EACA;AACA,EAAA,OAAO,OAAO,GAAA,EAAc,GAAA,EAAe,IAAA,KAAsC;AAC/E,IAAA,IAAI;AACF,MAAA,MAAM,OAAA,CAAQ,GAAA,EAAK,GAAA,EAAK,IAAI,CAAA;AAAA,IAC9B,SAAS,KAAA,EAAO;AAEd,MAAA,IAAA,CAAK,KAAK,CAAA;AAAA,IACZ;AAAA,EACF,CAAA;AACF","file":"index.js","sourcesContent":["import type { CapturedError } from \"./types\";\r\n\r\n/**\r\n * Generate a stable fingerprint (hash) for an error\r\n *\r\n * The fingerprint is used for deduplication - same errors should produce\r\n * the same fingerprint. This is based on:\r\n * - Error type/name\r\n * - Route where error occurred\r\n * - First line of stack trace (usually the line that caused the error)\r\n *\r\n * @param error - The captured error object\r\n * @returns A hex string fingerprint\r\n */\r\nexport function generateErrorFingerprint(error: CapturedError): string {\r\n // Build a stable key from error properties\r\n const errorType = error.name || \"Error\";\r\n const route = error.route || \"unknown\";\r\n const stackFirstLine = getStackFirstLine(error.stack);\r\n\r\n const key = `${errorType}:${route}:${stackFirstLine}`;\r\n\r\n // Generate a simple hash\r\n return simpleHash(key);\r\n}\r\n\r\n/**\r\n * Extract the first meaningful line from a stack trace\r\n * This is usually the line where the error actually occurred\r\n *\r\n * @param stack - The stack trace string\r\n * @returns First line of stack or \"unknown\"\r\n */\r\nfunction getStackFirstLine(stack?: string): string {\r\n if (!stack) return \"unknown\";\r\n\r\n const lines = stack.split(\"\\n\");\r\n\r\n // Find first line that looks like a stack frame\r\n // (starts with \"at \" in V8 stack traces)\r\n for (const line of lines) {\r\n const trimmed = line.trim();\r\n if (trimmed.startsWith(\"at \")) {\r\n return trimmed;\r\n }\r\n }\r\n\r\n // Fallback: use first non-empty line\r\n for (const line of lines) {\r\n const trimmed = line.trim();\r\n if (trimmed) {\r\n return trimmed;\r\n }\r\n }\r\n\r\n return \"unknown\";\r\n}\r\n\r\n/**\r\n * Simple string hash function\r\n *\r\n * This is a basic implementation of the DJB2 hash algorithm.\r\n * It's not cryptographically secure, but it's fast and produces\r\n * reasonably distributed hashes for our use case.\r\n *\r\n * @param str - String to hash\r\n * @returns Hex string hash\r\n */\r\nfunction simpleHash(str: string): string {\r\n let hash = 5381;\r\n\r\n for (let i = 0; i < str.length; i++) {\r\n // hash * 33 + char\r\n hash = (hash << 5) + hash + str.charCodeAt(i);\r\n hash = hash & hash; // Convert to 32-bit integer\r\n }\r\n\r\n // Convert to unsigned 32-bit integer and then to hex\r\n const unsignedHash = hash >>> 0;\r\n return unsignedHash.toString(16).padStart(8, \"0\");\r\n}\r\n\r\n/**\r\n * Generate a fingerprint from error-like object\r\n *\r\n * This is a convenience function for generating fingerprints from\r\n * minimal error information (e.g., during server-side processing)\r\n *\r\n * @param errorName - Error type/name\r\n * @param route - Route where error occurred\r\n * @param stack - Stack trace\r\n * @returns Hex string fingerprint\r\n */\r\nexport function generateFingerprintFromParts(\r\n errorName: string,\r\n route: string,\r\n stack?: string\r\n): string {\r\n const stackFirstLine = getStackFirstLine(stack);\r\n const key = `${errorName}:${route}:${stackFirstLine}`;\r\n return simpleHash(key);\r\n}\r\n","/**\r\n * Client-side error deduplicator\r\n *\r\n * Prevents the same error (identified by fingerprint) from being sent\r\n * multiple times within a configurable time window. This helps avoid\r\n * flooding the BugStack service with duplicate errors.\r\n */\r\nexport class ErrorDeduplicator {\r\n /**\r\n * Cache of fingerprint → timestamp mapping\r\n * Key: error fingerprint (hex string)\r\n * Value: timestamp (ms) when error was last sent\r\n */\r\n private cache: Map<string, number>;\r\n\r\n /**\r\n * Time window in milliseconds\r\n * Errors with the same fingerprint within this window are considered duplicates\r\n */\r\n private window: number;\r\n\r\n /**\r\n * Interval ID for cleanup task\r\n */\r\n private cleanupIntervalId?: NodeJS.Timeout;\r\n\r\n /**\r\n * Create a new deduplicator\r\n *\r\n * @param window - Deduplication window in milliseconds (default: 5 minutes)\r\n */\r\n constructor(window: number = 5 * 60 * 1000) {\r\n this.cache = new Map();\r\n this.window = window;\r\n\r\n // Start automatic cleanup every minute\r\n this.startCleanup();\r\n }\r\n\r\n /**\r\n * Check if an error should be sent\r\n *\r\n * @param fingerprint - Error fingerprint\r\n * @returns true if error should be sent, false if it's a duplicate\r\n */\r\n shouldSend(fingerprint: string): boolean {\r\n const now = Date.now();\r\n const lastSent = this.cache.get(fingerprint);\r\n\r\n if (lastSent !== undefined) {\r\n const elapsed = now - lastSent;\r\n\r\n // If error was sent within the window, it's a duplicate\r\n if (elapsed < this.window) {\r\n return false;\r\n }\r\n }\r\n\r\n // Mark this fingerprint as sent\r\n this.cache.set(fingerprint, now);\r\n return true;\r\n }\r\n\r\n /**\r\n * Mark an error as sent (manually)\r\n *\r\n * This can be used to pre-populate the cache or update the timestamp\r\n * after a successful send.\r\n *\r\n * @param fingerprint - Error fingerprint\r\n */\r\n markSent(fingerprint: string): void {\r\n this.cache.set(fingerprint, Date.now());\r\n }\r\n\r\n /**\r\n * Check if an error fingerprint is in the cache\r\n *\r\n * @param fingerprint - Error fingerprint\r\n * @returns true if fingerprint exists and is within the window\r\n */\r\n has(fingerprint: string): boolean {\r\n const lastSent = this.cache.get(fingerprint);\r\n if (lastSent === undefined) {\r\n return false;\r\n }\r\n\r\n const elapsed = Date.now() - lastSent;\r\n return elapsed < this.window;\r\n }\r\n\r\n /**\r\n * Get the number of entries in the cache\r\n */\r\n get size(): number {\r\n return this.cache.size;\r\n }\r\n\r\n /**\r\n * Clear all entries from the cache\r\n */\r\n clear(): void {\r\n this.cache.clear();\r\n }\r\n\r\n /**\r\n * Remove expired entries from the cache\r\n *\r\n * This is called automatically every minute, but can also be\r\n * called manually to free up memory.\r\n */\r\n cleanup(): void {\r\n const now = Date.now();\r\n const toDelete: string[] = [];\r\n\r\n // Find expired entries\r\n for (const [fingerprint, timestamp] of this.cache.entries()) {\r\n const elapsed = now - timestamp;\r\n if (elapsed >= this.window) {\r\n toDelete.push(fingerprint);\r\n }\r\n }\r\n\r\n // Delete expired entries\r\n for (const fingerprint of toDelete) {\r\n this.cache.delete(fingerprint);\r\n }\r\n }\r\n\r\n /**\r\n * Start automatic cleanup task\r\n *\r\n * Runs cleanup every minute to remove expired entries\r\n */\r\n private startCleanup(): void {\r\n // Run cleanup every minute\r\n this.cleanupIntervalId = setInterval(() => {\r\n this.cleanup();\r\n }, 60 * 1000);\r\n\r\n // Ensure the interval doesn't prevent Node.js from exiting\r\n if (this.cleanupIntervalId.unref) {\r\n this.cleanupIntervalId.unref();\r\n }\r\n }\r\n\r\n /**\r\n * Stop automatic cleanup task\r\n *\r\n * This should be called when shutting down to prevent memory leaks\r\n */\r\n destroy(): void {\r\n if (this.cleanupIntervalId) {\r\n clearInterval(this.cleanupIntervalId);\r\n this.cleanupIntervalId = undefined;\r\n }\r\n this.cache.clear();\r\n }\r\n\r\n /**\r\n * Get cache statistics (for debugging)\r\n */\r\n getStats(): {\r\n size: number;\r\n window: number;\r\n entries: Array<{ fingerprint: string; age: number }>;\r\n } {\r\n const now = Date.now();\r\n const entries = Array.from(this.cache.entries()).map(([fingerprint, timestamp]) => ({\r\n fingerprint,\r\n age: now - timestamp,\r\n }));\r\n\r\n return {\r\n size: this.cache.size,\r\n window: this.window,\r\n entries,\r\n };\r\n }\r\n}\r\n","import type { CapturedError, SourceContext } from \"./types\";\r\n\r\n/**\r\n * Queued error item\r\n */\r\ninterface QueuedError {\r\n /**\r\n * The error to send\r\n */\r\n error: CapturedError;\r\n\r\n /**\r\n * Source context (if available)\r\n */\r\n sourceContext?: SourceContext;\r\n\r\n /**\r\n * Number of send attempts\r\n */\r\n attempts: number;\r\n\r\n /**\r\n * Timestamp of last attempt\r\n */\r\n lastAttempt?: number;\r\n\r\n /**\r\n * Next retry timestamp\r\n */\r\n nextRetry: number;\r\n}\r\n\r\n/**\r\n * Function that sends an error to the service\r\n */\r\ntype SendFunction = (\r\n error: CapturedError,\r\n sourceContext?: SourceContext\r\n) => Promise<boolean>;\r\n\r\n/**\r\n * Retry queue with exponential backoff\r\n *\r\n * Handles failed error reports by queuing them and retrying with\r\n * exponentially increasing delays. Never blocks the host application.\r\n */\r\nexport class RetryQueue {\r\n /**\r\n * Queue of errors waiting to be sent\r\n */\r\n private queue: QueuedError[] = [];\r\n\r\n /**\r\n * Whether the queue is currently processing\r\n */\r\n private processing: boolean = false;\r\n\r\n /**\r\n * Maximum number of retry attempts\r\n */\r\n private maxRetries: number = 5;\r\n\r\n /**\r\n * Base backoff delay in milliseconds\r\n */\r\n private baseDelay: number = 1000; // 1 second\r\n\r\n /**\r\n * Maximum backoff delay in milliseconds\r\n */\r\n private maxDelay: number = 16000; // 16 seconds\r\n\r\n /**\r\n * Function to send errors\r\n */\r\n private sendFn: SendFunction;\r\n\r\n /**\r\n * Debug mode\r\n */\r\n private debug: boolean;\r\n\r\n /**\r\n * Processing interval ID\r\n */\r\n private intervalId?: NodeJS.Timeout;\r\n\r\n /**\r\n * Create a new retry queue\r\n *\r\n * @param sendFn - Function to send errors\r\n * @param options - Configuration options\r\n */\r\n constructor(\r\n sendFn: SendFunction,\r\n options?: {\r\n maxRetries?: number;\r\n baseDelay?: number;\r\n maxDelay?: number;\r\n debug?: boolean;\r\n }\r\n ) {\r\n this.sendFn = sendFn;\r\n this.maxRetries = options?.maxRetries ?? 5;\r\n this.baseDelay = options?.baseDelay ?? 1000;\r\n this.maxDelay = options?.maxDelay ?? 16000;\r\n this.debug = options?.debug ?? false;\r\n\r\n // Start processing queue periodically\r\n this.startProcessing();\r\n }\r\n\r\n /**\r\n * Enqueue an error for sending\r\n *\r\n * This is non-blocking and returns immediately.\r\n *\r\n * @param error - The error to send\r\n * @param sourceContext - Source context (optional)\r\n */\r\n enqueue(error: CapturedError, sourceContext?: SourceContext): void {\r\n const queuedError: QueuedError = {\r\n error,\r\n sourceContext,\r\n attempts: 0,\r\n nextRetry: Date.now(), // Send immediately on first attempt\r\n };\r\n\r\n this.queue.push(queuedError);\r\n this.log(`Enqueued error: ${error.id} (queue size: ${this.queue.length})`);\r\n\r\n // Trigger processing\r\n this.processQueue();\r\n }\r\n\r\n /**\r\n * Get the current queue size\r\n */\r\n get size(): number {\r\n return this.queue.length;\r\n }\r\n\r\n /**\r\n * Clear all items from the queue\r\n */\r\n clear(): void {\r\n this.queue = [];\r\n }\r\n\r\n /**\r\n * Destroy the queue and stop processing\r\n */\r\n destroy(): void {\r\n if (this.intervalId) {\r\n clearInterval(this.intervalId);\r\n this.intervalId = undefined;\r\n }\r\n this.queue = [];\r\n this.processing = false;\r\n }\r\n\r\n /**\r\n * Start periodic queue processing\r\n */\r\n private startProcessing(): void {\r\n // Process queue every 500ms\r\n this.intervalId = setInterval(() => {\r\n this.processQueue();\r\n }, 500);\r\n\r\n // Ensure the interval doesn't prevent Node.js from exiting\r\n if (this.intervalId.unref) {\r\n this.intervalId.unref();\r\n }\r\n }\r\n\r\n /**\r\n * Process the queue\r\n *\r\n * This is called periodically and also immediately after enqueue.\r\n * Non-blocking - errors are caught and logged.\r\n */\r\n private async processQueue(): Promise<void> {\r\n if (this.processing || this.queue.length === 0) {\r\n return;\r\n }\r\n\r\n this.processing = true;\r\n\r\n try {\r\n const now = Date.now();\r\n\r\n // Find errors ready to be sent (nextRetry <= now)\r\n const readyErrors = this.queue.filter((item) => item.nextRetry <= now);\r\n\r\n if (readyErrors.length === 0) {\r\n return;\r\n }\r\n\r\n this.log(`Processing ${readyErrors.length} ready errors`);\r\n\r\n // Process each ready error\r\n for (const item of readyErrors) {\r\n await this.processItem(item);\r\n }\r\n } catch (err) {\r\n // Never let queue processing crash\r\n this.logError(\"Queue processing error:\", err);\r\n } finally {\r\n this.processing = false;\r\n }\r\n }\r\n\r\n /**\r\n * Process a single queued error\r\n *\r\n * @param item - The queued error item\r\n */\r\n private async processItem(item: QueuedError): Promise<void> {\r\n try {\r\n item.attempts++;\r\n item.lastAttempt = Date.now();\r\n\r\n this.log(\r\n `Sending error ${item.error.id} (attempt ${item.attempts}/${this.maxRetries})`\r\n );\r\n\r\n // Try to send the error\r\n const success = await this.sendFn(item.error, item.sourceContext);\r\n\r\n if (success) {\r\n // Success - remove from queue\r\n this.log(`Successfully sent error: ${item.error.id}`);\r\n this.removeFromQueue(item);\r\n } else {\r\n // Failed - retry or give up\r\n this.handleFailure(item);\r\n }\r\n } catch (err) {\r\n // Error during send - retry or give up\r\n this.logError(`Error sending ${item.error.id}:`, err);\r\n this.handleFailure(item);\r\n }\r\n }\r\n\r\n /**\r\n * Handle a failed send attempt\r\n *\r\n * @param item - The queued error item\r\n */\r\n private handleFailure(item: QueuedError): void {\r\n if (item.attempts >= this.maxRetries) {\r\n // Max retries exceeded - give up\r\n this.logError(\r\n `Max retries exceeded for error ${item.error.id}, dropping`\r\n );\r\n this.removeFromQueue(item);\r\n } else {\r\n // Schedule retry with exponential backoff\r\n const delay = this.calculateBackoff(item.attempts);\r\n item.nextRetry = Date.now() + delay;\r\n\r\n this.log(\r\n `Scheduling retry for error ${item.error.id} in ${delay}ms (attempt ${item.attempts}/${this.maxRetries})`\r\n );\r\n }\r\n }\r\n\r\n /**\r\n * Calculate exponential backoff delay\r\n *\r\n * Backoff formula: min(baseDelay * 2^(attempts - 1), maxDelay)\r\n * - Attempt 1: 1s\r\n * - Attempt 2: 2s\r\n * - Attempt 3: 4s\r\n * - Attempt 4: 8s\r\n * - Attempt 5: 16s\r\n *\r\n * @param attempts - Number of attempts\r\n * @returns Delay in milliseconds\r\n */\r\n private calculateBackoff(attempts: number): number {\r\n const delay = this.baseDelay * Math.pow(2, attempts - 1);\r\n return Math.min(delay, this.maxDelay);\r\n }\r\n\r\n /**\r\n * Remove an item from the queue\r\n *\r\n * @param item - The item to remove\r\n */\r\n private removeFromQueue(item: QueuedError): void {\r\n const index = this.queue.indexOf(item);\r\n if (index !== -1) {\r\n this.queue.splice(index, 1);\r\n }\r\n }\r\n\r\n /**\r\n * Log a message (if debug mode is enabled)\r\n *\r\n * @param message - Message to log\r\n */\r\n private log(message: string): void {\r\n if (this.debug) {\r\n console.log(`[BugStack Queue] ${message}`);\r\n }\r\n }\r\n\r\n /**\r\n * Log an error (if debug mode is enabled)\r\n *\r\n * @param message - Message to log\r\n * @param error - Error object (optional)\r\n */\r\n private logError(message: string, error?: unknown): void {\r\n if (this.debug) {\r\n if (error) {\r\n console.error(`[BugStack Queue] ${message}`, error);\r\n } else {\r\n console.error(`[BugStack Queue] ${message}`);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Get queue statistics (for debugging)\r\n */\r\n getStats(): {\r\n size: number;\r\n processing: boolean;\r\n items: Array<{\r\n errorId: string;\r\n attempts: number;\r\n nextRetry: number;\r\n timeUntilRetry: number;\r\n }>;\r\n } {\r\n const now = Date.now();\r\n\r\n return {\r\n size: this.queue.length,\r\n processing: this.processing,\r\n items: this.queue.map((item) => ({\r\n errorId: item.error.id,\r\n attempts: item.attempts,\r\n nextRetry: item.nextRetry,\r\n timeUntilRetry: Math.max(0, item.nextRetry - now),\r\n })),\r\n };\r\n }\r\n}\r\n","/**\r\n * Single source of truth for the SDK's wire version.\r\n *\r\n * `__BUGSTACK_SDK_VERSION__` is replaced at build time by tsup's `define`\r\n * (see tsup.config.ts) with the literal `package.json#version`. The fallback\r\n * `\"0.0.0-dev\"` is only reachable when the package is consumed unbuilt\r\n * (e.g. ts-node against src/) — not a path we publish, but it keeps dev\r\n * ergonomics sane and avoids a hard ReferenceError.\r\n *\r\n * Every adapter and client pulls SDK_VERSION from here so a release bump\r\n * propagates atomically without hand-edits across files.\r\n */\r\ndeclare const __BUGSTACK_SDK_VERSION__: string;\r\n\r\nexport const SDK_VERSION: string =\r\n typeof __BUGSTACK_SDK_VERSION__ !== \"undefined\" ? __BUGSTACK_SDK_VERSION__ : \"0.0.0-dev\";\r\n","import type {\r\n ErrorCaptureConfig,\r\n ResolvedConfig,\r\n CapturedError,\r\n ErrorReportPayload,\r\n SourceContext,\r\n} from \"./types\";\r\nimport { generateErrorFingerprint } from \"./fingerprint\";\r\nimport { ErrorDeduplicator } from \"./deduplicator\";\r\nimport { RetryQueue } from \"./queue\";\r\n\r\nimport { SDK_VERSION } from \"./sdk-version\";\r\nconst DEFAULT_ENDPOINT = \"http://localhost:3001/api/capture\";\r\nconst DEFAULT_TIMEOUT = 5000;\r\nconst DEFAULT_MAX_BODY_SIZE = 10000;\r\nconst DEFAULT_DEDUPLICATION_WINDOW = 5 * 60 * 1000; // 5 minutes\r\n\r\n/**\r\n * Default sensitive fields to redact from requests\r\n */\r\nconst DEFAULT_REDACT_FIELDS = [\r\n \"password\",\r\n \"secret\",\r\n \"token\",\r\n \"apikey\",\r\n \"api_key\",\r\n \"apiKey\",\r\n \"authorization\",\r\n \"auth\",\r\n \"credential\",\r\n \"private\",\r\n \"credit_card\",\r\n \"creditcard\",\r\n \"card_number\",\r\n \"cvv\",\r\n \"ssn\",\r\n \"social_security\",\r\n];\r\n\r\n/**\r\n * BugStack Error Capture Client\r\n *\r\n * Singleton client for capturing and reporting errors to the BugStack service.\r\n * Now includes client-side deduplication and retry queue with exponential backoff.\r\n */\r\nexport class ErrorCaptureClient {\r\n private config: ResolvedConfig;\r\n private static instance: ErrorCaptureClient | null = null;\r\n private deduplicator: ErrorDeduplicator;\r\n private retryQueue: RetryQueue;\r\n\r\n constructor(config: ErrorCaptureConfig) {\r\n const isProduction = process.env.NODE_ENV === \"production\";\r\n\r\n this.config = {\r\n apiKey: config.apiKey,\r\n endpoint:\r\n config.endpoint ??\r\n process.env.BUGSTACK_ENDPOINT ??\r\n DEFAULT_ENDPOINT,\r\n projectId: config.projectId ?? process.env.BUGSTACK_PROJECT_ID ?? \"\",\r\n environment:\r\n config.environment ?? process.env.NODE_ENV ?? \"development\",\r\n autoFix: config.autoFix ?? false,\r\n enabled: config.enabled ?? true,\r\n captureRequestBody: config.captureRequestBody ?? false,\r\n captureQueryParams: config.captureQueryParams ?? true,\r\n captureHeaders: config.captureHeaders ?? true,\r\n maxBodySize: config.maxBodySize ?? DEFAULT_MAX_BODY_SIZE,\r\n redactFields: [\r\n ...DEFAULT_REDACT_FIELDS,\r\n ...(config.redactFields ?? []),\r\n ],\r\n metadata: config.metadata ?? {},\r\n timeout: config.timeout ?? DEFAULT_TIMEOUT,\r\n deduplicationWindow:\r\n config.deduplicationWindow ?? DEFAULT_DEDUPLICATION_WINDOW,\r\n debug: config.debug ?? !isProduction,\r\n shouldCapture: config.shouldCapture,\r\n beforeSend: config.beforeSend,\r\n dropChunkErrors: config.dropChunkErrors ?? false,\r\n chunkErrorsEndpoint:\r\n config.chunkErrorsEndpoint ??\r\n deriveChunkErrorsEndpoint(\r\n config.endpoint ??\r\n process.env.BUGSTACK_ENDPOINT ??\r\n DEFAULT_ENDPOINT,\r\n ),\r\n };\r\n\r\n // Initialize deduplicator\r\n this.deduplicator = new ErrorDeduplicator(this.config.deduplicationWindow);\r\n\r\n // Initialize retry queue with send function bound to this instance\r\n this.retryQueue = new RetryQueue(\r\n (error, sourceContext) => this.sendErrorToService(error, sourceContext),\r\n {\r\n maxRetries: 5,\r\n baseDelay: 1000,\r\n maxDelay: 16000,\r\n debug: this.config.debug,\r\n }\r\n );\r\n\r\n this.log(\"BugStack client initialized\", {\r\n endpoint: this.config.endpoint,\r\n projectId: this.config.projectId,\r\n environment: this.config.environment,\r\n autoFix: this.config.autoFix,\r\n deduplicationWindow: this.config.deduplicationWindow,\r\n });\r\n }\r\n\r\n /**\r\n * Initialize the singleton client instance\r\n */\r\n static init(config: ErrorCaptureConfig): ErrorCaptureClient {\r\n // Clean up existing instance if present\r\n if (ErrorCaptureClient.instance) {\r\n ErrorCaptureClient.instance.destroy();\r\n }\r\n\r\n ErrorCaptureClient.instance = new ErrorCaptureClient(config);\r\n return ErrorCaptureClient.instance;\r\n }\r\n\r\n /**\r\n * Get the singleton client instance\r\n */\r\n static getInstance(): ErrorCaptureClient | null {\r\n return ErrorCaptureClient.instance;\r\n }\r\n\r\n /**\r\n * Check if the client has been initialized\r\n */\r\n static isInitialized(): boolean {\r\n return ErrorCaptureClient.instance !== null;\r\n }\r\n\r\n /**\r\n * Reset the client (mainly for testing)\r\n */\r\n static reset(): void {\r\n if (ErrorCaptureClient.instance) {\r\n ErrorCaptureClient.instance.destroy();\r\n }\r\n ErrorCaptureClient.instance = null;\r\n }\r\n\r\n /**\r\n * Report an error to the BugStack service\r\n *\r\n * This method includes deduplication and queuing for resilience.\r\n *\r\n * @param error - The captured error\r\n * @param sourceContext - Source code context (optional)\r\n * @returns Promise that resolves to true if error was accepted (not deduplicated)\r\n */\r\n async reportError(\r\n error: CapturedError,\r\n sourceContext?: SourceContext\r\n ): Promise<boolean> {\r\n if (!this.config.enabled) {\r\n this.log(\"Error capture is disabled, skipping report\");\r\n return false;\r\n }\r\n\r\n // Chunk-load errors don't go through the fix pipeline. By default they\r\n // get routed to the lightweight telemetry endpoint so the dashboard can\r\n // still spot CDN outages / broken deploys via spike detection. The\r\n // dropChunkErrors flag short-circuits even that path.\r\n if (isChunkLoadError(error)) {\r\n if (!this.config.dropChunkErrors) {\r\n this.sendChunkErrorTelemetry(error).catch(() => {\r\n /* fire and forget — telemetry failure must never escalate */\r\n });\r\n } else {\r\n this.log(`Dropped chunk-load error: ${error.message}`);\r\n }\r\n return false;\r\n }\r\n\r\n // Apply beforeSend hook if provided\r\n let errorToSend = error;\r\n if (this.config.beforeSend) {\r\n const modified = this.config.beforeSend(error);\r\n if (modified === null) {\r\n this.log(\"Error filtered by beforeSend hook\");\r\n return false;\r\n }\r\n errorToSend = modified;\r\n }\r\n\r\n // Generate fingerprint for deduplication\r\n const fingerprint = generateErrorFingerprint(errorToSend);\r\n errorToSend.fingerprint = fingerprint;\r\n\r\n // Check deduplication\r\n if (!this.deduplicator.shouldSend(fingerprint)) {\r\n this.log(`Error deduplicated: ${error.id} (fingerprint: ${fingerprint})`);\r\n return false;\r\n }\r\n\r\n this.log(`Reporting error: ${error.id} (fingerprint: ${fingerprint})`);\r\n\r\n // Add project metadata\r\n errorToSend.projectId = this.config.projectId || errorToSend.projectId;\r\n errorToSend.environment = this.config.environment;\r\n errorToSend.metadata = {\r\n ...this.config.metadata,\r\n ...errorToSend.metadata,\r\n autoFix: this.config.autoFix,\r\n };\r\n\r\n // Enqueue for sending (non-blocking)\r\n this.retryQueue.enqueue(errorToSend, sourceContext);\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Send an error to the service (internal method)\r\n *\r\n * This is used by the retry queue. Returns true on success, false on failure.\r\n *\r\n * @param error - The error to send\r\n * @param sourceContext - Source context (optional)\r\n * @returns Promise that resolves to true on success\r\n */\r\n private async sendErrorToService(\r\n error: CapturedError,\r\n sourceContext?: SourceContext\r\n ): Promise<boolean> {\r\n const payload: ErrorReportPayload = {\r\n error,\r\n sourceContext,\r\n };\r\n\r\n try {\r\n const controller = new AbortController();\r\n const timeoutId = setTimeout(\r\n () => controller.abort(),\r\n this.config.timeout\r\n );\r\n\r\n const response = await fetch(this.config.endpoint, {\r\n method: \"POST\",\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n \"X-BugStack-API-Key\": this.config.apiKey,\r\n \"X-BugStack-SDK-Version\": SDK_VERSION,\r\n },\r\n body: JSON.stringify(payload),\r\n signal: controller.signal,\r\n });\r\n\r\n clearTimeout(timeoutId);\r\n\r\n if (!response.ok) {\r\n this.logError(\r\n `Failed to send error: HTTP ${response.status} ${response.statusText}`\r\n );\r\n return false;\r\n }\r\n\r\n this.log(`Error sent successfully: ${error.id}`);\r\n return true;\r\n } catch (err) {\r\n if (err instanceof Error && err.name === \"AbortError\") {\r\n this.logError(`Error send timed out after ${this.config.timeout}ms`);\r\n } else {\r\n this.logError(\"Failed to send error:\", err);\r\n }\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * Forward a chunk-load error to the lightweight telemetry endpoint.\r\n * Fire-and-forget — never throws, never retries, never logs loud. The\r\n * point is to count these without spending real money on them.\r\n */\r\n private async sendChunkErrorTelemetry(error: CapturedError): Promise<void> {\r\n try {\r\n const controller = new AbortController();\r\n const timeoutId = setTimeout(() => controller.abort(), 2000);\r\n await fetch(this.config.chunkErrorsEndpoint, {\r\n method: \"POST\",\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n \"X-BugStack-API-Key\": this.config.apiKey,\r\n \"X-BugStack-SDK-Version\": SDK_VERSION,\r\n },\r\n body: JSON.stringify({\r\n message: error.message,\r\n url: error.url,\r\n route: error.route,\r\n userAgent:\r\n (error.requestHeaders && (error.requestHeaders[\"user-agent\"] || error.requestHeaders[\"User-Agent\"])) ||\r\n (typeof navigator !== \"undefined\" ? navigator.userAgent : undefined),\r\n release: this.config.metadata?.release as string | undefined,\r\n }),\r\n signal: controller.signal,\r\n // Browsers respect keepalive on cross-origin POSTs during unload.\r\n keepalive: true,\r\n });\r\n clearTimeout(timeoutId);\r\n this.log(`Chunk-error telemetry sent: ${error.message}`);\r\n } catch {\r\n // Intentionally silent. See method comment.\r\n }\r\n }\r\n\r\n /**\r\n * Get the resolved configuration\r\n */\r\n getConfig(): ResolvedConfig {\r\n return { ...this.config };\r\n }\r\n\r\n /**\r\n * Check if a field should be redacted\r\n */\r\n shouldRedact(fieldName: string): boolean {\r\n const lowerField = fieldName.toLowerCase();\r\n return this.config.redactFields.some(\r\n (redact) =>\r\n lowerField.includes(redact.toLowerCase()) ||\r\n redact.toLowerCase().includes(lowerField)\r\n );\r\n }\r\n\r\n /**\r\n * Get the SDK version\r\n */\r\n static getVersion(): string {\r\n return SDK_VERSION;\r\n }\r\n\r\n /**\r\n * Get client statistics (for debugging)\r\n */\r\n getStats(): {\r\n deduplicator: ReturnType<ErrorDeduplicator[\"getStats\"]>;\r\n retryQueue: ReturnType<RetryQueue[\"getStats\"]>;\r\n } {\r\n return {\r\n deduplicator: this.deduplicator.getStats(),\r\n retryQueue: this.retryQueue.getStats(),\r\n };\r\n }\r\n\r\n /**\r\n * Clean up resources\r\n *\r\n * Should be called when shutting down to prevent memory leaks\r\n */\r\n destroy(): void {\r\n this.deduplicator.destroy();\r\n this.retryQueue.destroy();\r\n }\r\n\r\n private log(message: string, data?: Record<string, unknown>): void {\r\n if (this.config.debug) {\r\n if (data) {\r\n console.log(`[BugStack] ${message}`, data);\r\n } else {\r\n console.log(`[BugStack] ${message}`);\r\n }\r\n }\r\n }\r\n\r\n private logError(message: string, error?: unknown): void {\r\n if (this.config.debug) {\r\n if (error) {\r\n console.error(`[BugStack] ${message}`, error);\r\n } else {\r\n console.error(`[BugStack] ${message}`);\r\n }\r\n }\r\n }\r\n}\r\n\r\n// Legacy alias for backwards compatibility\r\nexport const BugStackClient = ErrorCaptureClient;\r\n\r\n/**\r\n * Recognise the family of \"browser failed to load a code-split chunk\" errors.\r\n * Webpack and Vite emit slightly different messages; the regex covers both.\r\n *\r\n * Exported (via re-export from index.ts) so callers can reuse the same check\r\n * in their own error boundaries when deciding whether to soft-reload.\r\n */\r\nexport function isChunkLoadError(\r\n error: { name?: string; message?: string }\r\n): boolean {\r\n if (!error) return false;\r\n if (error.name === \"ChunkLoadError\") return true;\r\n const msg = error.message || \"\";\r\n return (\r\n /Loading chunk\\s+[\\w-]+\\s+failed/i.test(msg) ||\r\n /Loading CSS chunk\\s+[\\w-]+\\s+failed/i.test(msg) ||\r\n /Failed to fetch dynamically imported module/i.test(msg) ||\r\n /Importing a module script failed/i.test(msg)\r\n );\r\n}\r\n\r\n/**\r\n * Default-derive the chunk-errors telemetry endpoint from the main capture\r\n * endpoint, so callers don't have to configure both. We replace the trailing\r\n * `/capture` segment (whether prefixed by `/api` or not) with `/chunk-errors`.\r\n * If the URL doesn't match the expected shape we fall back to suffixing the\r\n * original endpoint, which still lands on the right route in the typical\r\n * `https://host/api/capture` deployment.\r\n */\r\nfunction deriveChunkErrorsEndpoint(captureEndpoint: string): string {\r\n if (/\\/api\\/capture(\\/?$|\\?)/.test(captureEndpoint)) {\r\n return captureEndpoint.replace(/\\/api\\/capture/, \"/api/chunk-errors\");\r\n }\r\n if (/\\/capture(\\/?$|\\?)/.test(captureEndpoint)) {\r\n return captureEndpoint.replace(/\\/capture/, \"/chunk-errors\");\r\n }\r\n return captureEndpoint.replace(/\\/?$/, \"/chunk-errors\");\r\n}\r\n","import type { StackFrame } from \"../types\";\r\n\r\n/**\r\n * Regular expression to parse V8 stack trace frames\r\n * Handles formats like:\r\n * at functionName (file:line:column)\r\n * at file:line:column\r\n * at async functionName (file:line:column)\r\n */\r\nconst V8_STACK_FRAME_REGEX =\r\n /^\\s*at\\s+(?:async\\s+)?(?:(.+?)\\s+\\()?(?:(.+?):(\\d+):(\\d+))\\)?$/;\r\n\r\n/**\r\n * Check if a file path is from node_modules\r\n */\r\nfunction isNodeModule(filePath: string): boolean {\r\n return filePath.includes(\"node_modules\");\r\n}\r\n\r\n/**\r\n * Check if a file path is internal Node.js code\r\n */\r\nfunction isInternalCode(filePath: string): boolean {\r\n return (\r\n filePath.startsWith(\"node:\") ||\r\n filePath.startsWith(\"internal/\") ||\r\n !filePath.includes(\"/\")\r\n );\r\n}\r\n\r\n/**\r\n * Clean up function names\r\n */\r\nfunction cleanFunctionName(name: string | undefined): string | undefined {\r\n if (!name) return undefined;\r\n\r\n // Remove common prefixes\r\n return name\r\n .replace(/^Object\\./, \"\")\r\n .replace(/^Module\\./, \"\")\r\n .replace(/^__webpack_require__\\./, \"\")\r\n .replace(/^webpack_require\\./, \"\")\r\n .trim();\r\n}\r\n\r\n/**\r\n * Parse a V8 stack trace into structured frames\r\n */\r\nexport function parseStackTrace(stack: string | undefined): StackFrame[] {\r\n if (!stack) return [];\r\n\r\n const lines = stack.split(\"\\n\");\r\n const frames: StackFrame[] = [];\r\n\r\n for (const line of lines) {\r\n const match = V8_STACK_FRAME_REGEX.exec(line);\r\n\r\n if (match) {\r\n const [, functionName, file, lineStr, columnStr] = match;\r\n\r\n const frame: StackFrame = {\r\n function: cleanFunctionName(functionName),\r\n file: file ?? undefined,\r\n line: lineStr ? parseInt(lineStr, 10) : undefined,\r\n column: columnStr ? parseInt(columnStr, 10) : undefined,\r\n };\r\n\r\n if (frame.file) {\r\n frame.isNodeModule = isNodeModule(frame.file);\r\n frame.isInternal = isInternalCode(frame.file);\r\n }\r\n\r\n frames.push(frame);\r\n }\r\n }\r\n\r\n return frames;\r\n}\r\n\r\n/**\r\n * Get the first application frame (non-node_modules, non-internal)\r\n */\r\nexport function getFirstAppFrame(frames: StackFrame[]): StackFrame | undefined {\r\n return frames.find((frame) => !frame.isNodeModule && !frame.isInternal);\r\n}\r\n\r\n/**\r\n * Filter stack frames to only include application code\r\n */\r\nexport function getAppFrames(frames: StackFrame[]): StackFrame[] {\r\n return frames.filter((frame) => !frame.isNodeModule && !frame.isInternal);\r\n}\r\n\r\n/**\r\n * Format stack frames back to a string (useful for cleaned stack traces)\r\n */\r\nexport function formatStackFrames(frames: StackFrame[]): string {\r\n return frames\r\n .map((frame) => {\r\n const location = [frame.file, frame.line, frame.column]\r\n .filter(Boolean)\r\n .join(\":\");\r\n\r\n if (frame.function) {\r\n return ` at ${frame.function} (${location})`;\r\n }\r\n return ` at ${location}`;\r\n })\r\n .join(\"\\n\");\r\n}\r\n","import type { ErrorCaptureClient } from \"../client\";\r\n\r\nconst REDACT_PLACEHOLDER = \"[REDACTED]\";\r\nconst TRUNCATE_PLACEHOLDER = \"[TRUNCATED]\";\r\n\r\n/**\r\n * Sensitive headers that are always redacted\r\n */\r\nconst SENSITIVE_HEADERS = new Set([\r\n \"authorization\",\r\n \"cookie\",\r\n \"set-cookie\",\r\n \"x-api-key\",\r\n \"x-auth-token\",\r\n \"x-bugstack-api-key\",\r\n \"proxy-authorization\",\r\n \"www-authenticate\",\r\n]);\r\n\r\n/**\r\n * Sanitize headers by removing sensitive values\r\n */\r\nexport function sanitizeHeaders(\r\n headers: Headers,\r\n client?: ErrorCaptureClient | null\r\n): Record<string, string> {\r\n const sanitized: Record<string, string> = {};\r\n\r\n headers.forEach((value, key) => {\r\n const lowerKey = key.toLowerCase();\r\n\r\n // Always redact known sensitive headers\r\n if (SENSITIVE_HEADERS.has(lowerKey)) {\r\n sanitized[key] = REDACT_PLACEHOLDER;\r\n return;\r\n }\r\n\r\n // Check against custom redact fields\r\n if (client?.shouldRedact(key)) {\r\n sanitized[key] = REDACT_PLACEHOLDER;\r\n return;\r\n }\r\n\r\n sanitized[key] = value;\r\n });\r\n\r\n return sanitized;\r\n}\r\n\r\n/**\r\n * Sanitize query parameters by redacting sensitive values\r\n */\r\nexport function sanitizeQueryParams(\r\n url: URL,\r\n client?: ErrorCaptureClient | null\r\n): Record<string, string> {\r\n const sanitized: Record<string, string> = {};\r\n\r\n url.searchParams.forEach((value, key) => {\r\n if (client?.shouldRedact(key)) {\r\n sanitized[key] = REDACT_PLACEHOLDER;\r\n } else {\r\n sanitized[key] = value;\r\n }\r\n });\r\n\r\n return sanitized;\r\n}\r\n\r\n/**\r\n * Recursively sanitize an object by redacting sensitive fields\r\n */\r\nexport function sanitizeObject(\r\n obj: unknown,\r\n client?: ErrorCaptureClient | null,\r\n maxDepth = 10,\r\n currentDepth = 0\r\n): unknown {\r\n // Prevent infinite recursion\r\n if (currentDepth > maxDepth) {\r\n return TRUNCATE_PLACEHOLDER;\r\n }\r\n\r\n if (obj === null || obj === undefined) {\r\n return obj;\r\n }\r\n\r\n if (typeof obj !== \"object\") {\r\n return obj;\r\n }\r\n\r\n if (Array.isArray(obj)) {\r\n return obj.map((item) =>\r\n sanitizeObject(item, client, maxDepth, currentDepth + 1)\r\n );\r\n }\r\n\r\n const sanitized: Record<string, unknown> = {};\r\n\r\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\r\n if (client?.shouldRedact(key)) {\r\n sanitized[key] = REDACT_PLACEHOLDER;\r\n } else if (typeof value === \"object\" && value !== null) {\r\n sanitized[key] = sanitizeObject(value, client, maxDepth, currentDepth + 1);\r\n } else {\r\n sanitized[key] = value;\r\n }\r\n }\r\n\r\n return sanitized;\r\n}\r\n\r\n/**\r\n * Truncate a string or object to a maximum size\r\n */\r\nexport function truncateBody(\r\n data: unknown,\r\n maxSize: number\r\n): { body: unknown; truncated: boolean } {\r\n const serialized = JSON.stringify(data);\r\n\r\n if (serialized.length <= maxSize) {\r\n return { body: data, truncated: false };\r\n }\r\n\r\n // For strings, truncate directly\r\n if (typeof data === \"string\") {\r\n return {\r\n body: {\r\n __truncated: true,\r\n __originalSize: serialized.length,\r\n preview: TRUNCATE_PLACEHOLDER,\r\n },\r\n truncated: true,\r\n };\r\n }\r\n\r\n // For objects, try to preserve structure but indicate truncation\r\n return {\r\n body: {\r\n __truncated: true,\r\n __originalSize: serialized.length,\r\n __maxSize: maxSize,\r\n preview: serialized.slice(0, maxSize),\r\n },\r\n truncated: true,\r\n };\r\n}\r\n\r\n/**\r\n * Safely parse request body with error handling\r\n */\r\nexport async function safeParseBody(\r\n request: Request,\r\n maxSize: number,\r\n client?: ErrorCaptureClient | null\r\n): Promise<{ body: unknown; truncated: boolean } | null> {\r\n try {\r\n // Clone the request to avoid consuming the body\r\n const cloned = request.clone();\r\n const contentType = cloned.headers.get(\"content-type\") ?? \"\";\r\n\r\n // Handle JSON bodies\r\n if (contentType.includes(\"application/json\")) {\r\n const text = await cloned.text();\r\n\r\n if (text.length > maxSize) {\r\n return {\r\n body: {\r\n __truncated: true,\r\n __originalSize: text.length,\r\n preview: TRUNCATE_PLACEHOLDER,\r\n },\r\n truncated: true,\r\n };\r\n }\r\n\r\n try {\r\n const parsed = JSON.parse(text);\r\n const sanitized = sanitizeObject(parsed, client);\r\n return truncateBody(sanitized, maxSize);\r\n } catch {\r\n // Not valid JSON, return as text\r\n return truncateBody(text, maxSize);\r\n }\r\n }\r\n\r\n // Handle form data\r\n if (\r\n contentType.includes(\"application/x-www-form-urlencoded\") ||\r\n contentType.includes(\"multipart/form-data\")\r\n ) {\r\n try {\r\n const formData = await cloned.formData();\r\n const data: Record<string, unknown> = {};\r\n\r\n formData.forEach((value, key) => {\r\n if (value instanceof File) {\r\n data[key] = {\r\n type: \"file\",\r\n name: value.name,\r\n size: value.size,\r\n mimeType: value.type,\r\n };\r\n } else if (client?.shouldRedact(key)) {\r\n data[key] = REDACT_PLACEHOLDER;\r\n } else {\r\n data[key] = value;\r\n }\r\n });\r\n\r\n return truncateBody(data, maxSize);\r\n } catch {\r\n return { body: \"[FormData parsing failed]\", truncated: false };\r\n }\r\n }\r\n\r\n // Handle text bodies\r\n if (contentType.includes(\"text/\")) {\r\n const text = await cloned.text();\r\n return truncateBody(text, maxSize);\r\n }\r\n\r\n // For other content types, just note the type\r\n return {\r\n body: {\r\n __contentType: contentType,\r\n __note: \"Body not captured for this content type\",\r\n },\r\n truncated: false,\r\n };\r\n } catch (err) {\r\n // Body may have already been consumed or other error\r\n return null;\r\n }\r\n}\r\n","/**\r\n * BugStack SDK - Express Adapter\r\n *\r\n * Error capture middleware for Express.js applications\r\n */\r\n\r\nimport type { Request, Response, NextFunction, ErrorRequestHandler } from \"express\";\r\nimport { ErrorCaptureClient } from \"../../core/client\";\r\nimport type { ErrorCaptureConfig, CapturedError } from \"../../core/types\";\r\nimport { parseStackTrace, getFirstAppFrame } from \"../../core/utils/stack-parser\";\r\nimport { sanitizeObject, truncateBody } from \"../../core/utils/sanitize\";\r\nimport { SDK_VERSION } from \"../../core/sdk-version\";\r\n\r\n/**\r\n * Generate a unique error ID\r\n */\r\nfunction generateErrorId(): string {\r\n const timestamp = Date.now().toString(36);\r\n const random = Math.random().toString(36).substring(2, 9);\r\n return `err_${timestamp}_${random}`;\r\n}\r\n\r\n/**\r\n * Get Node.js version\r\n */\r\nfunction getNodeVersion(): string {\r\n try {\r\n return process.version;\r\n } catch {\r\n return \"unknown\";\r\n }\r\n}\r\n\r\n/**\r\n * Get Express version\r\n */\r\nfunction getExpressVersion(): string | undefined {\r\n try {\r\n // eslint-disable-next-line @typescript-eslint/no-require-imports\r\n const pkg = require(\"express/package.json\");\r\n return pkg.version;\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\n/**\r\n * Sanitize headers for Express\r\n */\r\nfunction sanitizeExpressHeaders(\r\n headers: Request[\"headers\"],\r\n client?: ErrorCaptureClient | null\r\n): Record<string, string> {\r\n const sanitized: Record<string, string> = {};\r\n const SENSITIVE_HEADERS = new Set([\r\n \"authorization\",\r\n \"cookie\",\r\n \"set-cookie\",\r\n \"x-api-key\",\r\n \"x-auth-token\",\r\n \"x-bugstack-api-key\",\r\n \"proxy-authorization\",\r\n \"www-authenticate\",\r\n ]);\r\n\r\n for (const [key, value] of Object.entries(headers)) {\r\n const lowerKey = key.toLowerCase();\r\n\r\n if (SENSITIVE_HEADERS.has(lowerKey)) {\r\n sanitized[key] = \"[REDACTED]\";\r\n } else if (client?.shouldRedact(key)) {\r\n sanitized[key] = \"[REDACTED]\";\r\n } else if (typeof value === \"string\") {\r\n sanitized[key] = value;\r\n } else if (Array.isArray(value)) {\r\n sanitized[key] = value.join(\", \");\r\n } else {\r\n sanitized[key] = String(value);\r\n }\r\n }\r\n\r\n return sanitized;\r\n}\r\n\r\n/**\r\n * Sanitize query parameters\r\n */\r\nfunction sanitizeExpressQuery(\r\n query: Request[\"query\"],\r\n client?: ErrorCaptureClient | null\r\n): Record<string, string> {\r\n const sanitized: Record<string, string> = {};\r\n\r\n for (const [key, value] of Object.entries(query)) {\r\n if (client?.shouldRedact(key)) {\r\n sanitized[key] = \"[REDACTED]\";\r\n } else if (typeof value === \"string\") {\r\n sanitized[key] = value;\r\n } else if (Array.isArray(value)) {\r\n sanitized[key] = value.join(\", \");\r\n } else {\r\n sanitized[key] = String(value);\r\n }\r\n }\r\n\r\n return sanitized;\r\n}\r\n\r\n/**\r\n * Build captured error from Express context\r\n */\r\nfunction buildCapturedError(\r\n error: Error,\r\n req: Request,\r\n client: ErrorCaptureClient\r\n): CapturedError {\r\n const config = client.getConfig();\r\n const stackFrames = parseStackTrace(error.stack);\r\n const firstAppFrame = getFirstAppFrame(stackFrames);\r\n\r\n const capturedError: CapturedError = {\r\n id: generateErrorId(),\r\n name: error.name || \"Error\",\r\n message: error.message,\r\n stack: error.stack,\r\n stackFrames,\r\n timestamp: new Date().toISOString(),\r\n route: req.route?.path || req.path || req.url,\r\n method: req.method,\r\n statusCode: 500,\r\n url: req.originalUrl || req.url,\r\n environment: config.environment,\r\n projectId: config.projectId,\r\n sdkVersion: SDK_VERSION,\r\n nodeVersion: getNodeVersion(),\r\n };\r\n\r\n // Add Express version if available\r\n const expressVersion = getExpressVersion();\r\n if (expressVersion) {\r\n capturedError.metadata = {\r\n ...capturedError.metadata,\r\n expressVersion,\r\n };\r\n }\r\n\r\n // Add route params if available\r\n if (req.params && Object.keys(req.params).length > 0) {\r\n capturedError.routeParams = req.params as Record<string, string>;\r\n }\r\n\r\n // Add query params if configured\r\n if (config.captureQueryParams && req.query && Object.keys(req.query).length > 0) {\r\n capturedError.queryParams = sanitizeExpressQuery(req.query, client);\r\n }\r\n\r\n // Add headers if configured\r\n if (config.captureHeaders) {\r\n capturedError.requestHeaders = sanitizeExpressHeaders(req.headers, client);\r\n }\r\n\r\n // Add request body if configured\r\n if (config.captureRequestBody && req.body) {\r\n const sanitizedBody = sanitizeObject(req.body, client);\r\n const bodyResult = truncateBody(sanitizedBody, config.maxBodySize);\r\n capturedError.requestBody = bodyResult.body;\r\n if (bodyResult.truncated) {\r\n capturedError.metadata = {\r\n ...capturedError.metadata,\r\n bodyTruncated: true,\r\n };\r\n }\r\n }\r\n\r\n // Add source location from first app frame\r\n if (firstAppFrame) {\r\n capturedError.metadata = {\r\n ...capturedError.metadata,\r\n sourceLocation: {\r\n file: firstAppFrame.file,\r\n line: firstAppFrame.line,\r\n column: firstAppFrame.column,\r\n function: firstAppFrame.function,\r\n },\r\n };\r\n }\r\n\r\n return capturedError;\r\n}\r\n\r\n/**\r\n * Express error handling middleware\r\n *\r\n * This middleware captures errors and reports them to BugStack.\r\n * It must be registered AFTER all routes and other middleware.\r\n *\r\n * @example\r\n * ```typescript\r\n * import express from 'express';\r\n * import { bugstackErrorHandler } from '@bugstack/sdk/express';\r\n *\r\n * const app = express();\r\n *\r\n * // ... your routes and middleware\r\n *\r\n * // Register BugStack error handler (must be last)\r\n * app.use(bugstackErrorHandler({\r\n * apiKey: 'your-api-key',\r\n * projectId: 'your-project-id',\r\n * autoFix: true\r\n * }));\r\n * ```\r\n */\r\nexport function bugstackErrorHandler(\r\n config?: ErrorCaptureConfig\r\n): ErrorRequestHandler {\r\n // Initialize client if config provided and not already initialized\r\n if (config && !ErrorCaptureClient.isInitialized()) {\r\n ErrorCaptureClient.init(config);\r\n }\r\n\r\n // Return Express error middleware\r\n return (err: Error, req: Request, _res: Response, next: NextFunction): void => {\r\n const client = ErrorCaptureClient.getInstance();\r\n\r\n if (client && client.getConfig().enabled) {\r\n // Build and report error asynchronously (don't block response)\r\n const capturedError = buildCapturedError(err, req, client);\r\n\r\n client.reportError(capturedError).catch(() => {\r\n // Silently ignore capture/report failures\r\n });\r\n }\r\n\r\n // Pass error to next error handler (or default Express error handler)\r\n next(err);\r\n };\r\n}\r\n\r\n/**\r\n * Express middleware to initialize BugStack client\r\n *\r\n * Use this if you want to initialize the client separately from the error handler\r\n *\r\n * @example\r\n * ```typescript\r\n * import express from 'express';\r\n * import { initBugStack, bugstackErrorHandler } from '@bugstack/sdk/express';\r\n *\r\n * const app = express();\r\n *\r\n * // Initialize client early\r\n * app.use(initBugStack({\r\n * apiKey: 'your-api-key',\r\n * projectId: 'your-project-id',\r\n * autoFix: true\r\n * }));\r\n *\r\n * // ... your routes\r\n *\r\n * // Register error handler\r\n * app.use(bugstackErrorHandler());\r\n * ```\r\n */\r\nexport function initBugStack(config: ErrorCaptureConfig) {\r\n if (!ErrorCaptureClient.isInitialized()) {\r\n ErrorCaptureClient.init(config);\r\n }\r\n\r\n // Return a no-op middleware\r\n return (_req: Request, _res: Response, next: NextFunction): void => {\r\n next();\r\n };\r\n}\r\n\r\n/**\r\n * Wrap an Express route handler with error capture\r\n *\r\n * This is an alternative to using the error middleware. It catches errors\r\n * in async route handlers and reports them to BugStack.\r\n *\r\n * @example\r\n * ```typescript\r\n * import { wrapExpressHandler } from '@bugstack/sdk/express';\r\n *\r\n * app.get('/api/users/:id', wrapExpressHandler(async (req, res) => {\r\n * const user = await getUser(req.params.id);\r\n * res.json(user);\r\n * }));\r\n * ```\r\n */\r\nexport function wrapExpressHandler(\r\n handler: (req: Request, res: Response, next: NextFunction) => Promise<void> | void\r\n) {\r\n return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\r\n try {\r\n await handler(req, res, next);\r\n } catch (error) {\r\n // Pass to error handling middleware\r\n next(error);\r\n }\r\n };\r\n}\r\n\r\n// Re-export types and client for convenience\r\nexport type { ErrorCaptureConfig, CapturedError } from \"../../core/types\";\r\nexport { ErrorCaptureClient, BugStackClient } from \"../../core/client\";\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/core/fingerprint.ts","../../../src/core/deduplicator.ts","../../../src/core/queue.ts","../../../src/core/sdk-version.ts","../../../src/core/client.ts","../../../src/core/utils/stack-parser.ts","../../../src/core/utils/sanitize.ts","../../../src/adapters/express/index.ts"],"names":[],"mappings":";;;;;;;;;;AAcO,SAAS,yBAAyB,KAAA,EAA8B;AAErE,EAAA,MAAM,SAAA,GAAY,MAAM,IAAA,IAAQ,OAAA;AAChC,EAAA,MAAM,KAAA,GAAQ,MAAM,KAAA,IAAS,SAAA;AAC7B,EAAA,MAAM,cAAA,GAAiB,iBAAA,CAAkB,KAAA,CAAM,KAAK,CAAA;AAEpD,EAAA,MAAM,MAAM,CAAA,EAAG,SAAS,CAAA,CAAA,EAAI,KAAK,IAAI,cAAc,CAAA,CAAA;AAGnD,EAAA,OAAO,WAAW,GAAG,CAAA;AACvB;AASA,SAAS,kBAAkB,KAAA,EAAwB;AACjD,EAAA,IAAI,CAAC,OAAO,OAAO,SAAA;AAEnB,EAAA,MAAM,KAAA,GAAQ,KAAA,CAAM,KAAA,CAAM,IAAI,CAAA;AAI9B,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,MAAM,OAAA,GAAU,KAAK,IAAA,EAAK;AAC1B,IAAA,IAAI,OAAA,CAAQ,UAAA,CAAW,KAAK,CAAA,EAAG;AAC7B,MAAA,OAAO,OAAA;AAAA,IACT;AAAA,EACF;AAGA,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,MAAM,OAAA,GAAU,KAAK,IAAA,EAAK;AAC1B,IAAA,IAAI,OAAA,EAAS;AACX,MAAA,OAAO,OAAA;AAAA,IACT;AAAA,EACF;AAEA,EAAA,OAAO,SAAA;AACT;AAYA,SAAS,WAAW,GAAA,EAAqB;AACvC,EAAA,IAAI,IAAA,GAAO,IAAA;AAEX,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,GAAA,CAAI,QAAQ,CAAA,EAAA,EAAK;AAEnC,IAAA,IAAA,GAAA,CAAQ,IAAA,IAAQ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,kBAAA,CAAmB,GAAA,EAAK,GAAA,EAAK,MAAM,CAAA;AAEzD,MAAA,MAAA,CAAO,WAAA,CAAY,aAAa,CAAA,CAAE,KAAA,CAAM,MAAM;AAAA,MAE9C,CAAC,CAAA;AAAA,IACH;AAGA,IAAA,IAAA,CAAK,GAAG,CAAA;AAAA,EACV,CAAA;AACF;AA2BO,SAAS,aAAa,MAAA,EAA4B;AACvD,EAAA,IAAI,CAAC,kBAAA,CAAmB,aAAA,EAAc,EAAG;AACvC,IAAA,kBAAA,CAAmB,KAAK,MAAM,CAAA;AAAA,EAChC;AAGA,EAAA,OAAO,CAAC,IAAA,EAAe,IAAA,EAAgB,IAAA,KAA6B;AAClE,IAAA,IAAA,EAAK;AAAA,EACP,CAAA;AACF;AAkBO,SAAS,mBACd,OAAA,EACA;AACA,EAAA,OAAO,OAAO,GAAA,EAAc,GAAA,EAAe,IAAA,KAAsC;AAC/E,IAAA,IAAI;AACF,MAAA,MAAM,OAAA,CAAQ,GAAA,EAAK,GAAA,EAAK,IAAI,CAAA;AAAA,IAC9B,SAAS,KAAA,EAAO;AAEd,MAAA,IAAA,CAAK,KAAK,CAAA;AAAA,IACZ;AAAA,EACF,CAAA;AACF","file":"index.js","sourcesContent":["import type { CapturedError } from \"./types\";\n\n/**\n * Generate a stable fingerprint (hash) for an error\n *\n * The fingerprint is used for deduplication - same errors should produce\n * the same fingerprint. This is based on:\n * - Error type/name\n * - Route where error occurred\n * - First line of stack trace (usually the line that caused the error)\n *\n * @param error - The captured error object\n * @returns A hex string fingerprint\n */\nexport function generateErrorFingerprint(error: CapturedError): string {\n // Build a stable key from error properties\n const errorType = error.name || \"Error\";\n const route = error.route || \"unknown\";\n const stackFirstLine = getStackFirstLine(error.stack);\n\n const key = `${errorType}:${route}:${stackFirstLine}`;\n\n // Generate a simple hash\n return simpleHash(key);\n}\n\n/**\n * Extract the first meaningful line from a stack trace\n * This is usually the line where the error actually occurred\n *\n * @param stack - The stack trace string\n * @returns First line of stack or \"unknown\"\n */\nfunction getStackFirstLine(stack?: string): string {\n if (!stack) return \"unknown\";\n\n const lines = stack.split(\"\\n\");\n\n // Find first line that looks like a stack frame\n // (starts with \"at \" in V8 stack traces)\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.startsWith(\"at \")) {\n return trimmed;\n }\n }\n\n // Fallback: use first non-empty line\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed) {\n return trimmed;\n }\n }\n\n return \"unknown\";\n}\n\n/**\n * Simple string hash function\n *\n * This is a basic implementation of the DJB2 hash algorithm.\n * It's not cryptographically secure, but it's fast and produces\n * reasonably distributed hashes for our use case.\n *\n * @param str - String to hash\n * @returns Hex string hash\n */\nfunction simpleHash(str: string): string {\n let hash = 5381;\n\n for (let i = 0; i < str.length; i++) {\n // hash * 33 + char\n hash = (hash << 5) + hash + str.charCodeAt(i);\n hash = hash & hash; // Convert to 32-bit integer\n }\n\n // Convert to unsigned 32-bit integer and then to hex\n const unsignedHash = hash >>> 0;\n return unsignedHash.toString(16).padStart(8, \"0\");\n}\n\n/**\n * Generate a fingerprint from error-like object\n *\n * This is a convenience function for generating fingerprints from\n * minimal error information (e.g., during server-side processing)\n *\n * @param errorName - Error type/name\n * @param route - Route where error occurred\n * @param stack - Stack trace\n * @returns Hex string fingerprint\n */\nexport function generateFingerprintFromParts(\n errorName: string,\n route: string,\n stack?: string\n): string {\n const stackFirstLine = getStackFirstLine(stack);\n const key = `${errorName}:${route}:${stackFirstLine}`;\n return simpleHash(key);\n}\n","/**\n * Client-side error deduplicator\n *\n * Prevents the same error (identified by fingerprint) from being sent\n * multiple times within a configurable time window. This helps avoid\n * flooding the BugStack service with duplicate errors.\n */\nexport class ErrorDeduplicator {\n /**\n * Cache of fingerprint → timestamp mapping\n * Key: error fingerprint (hex string)\n * Value: timestamp (ms) when error was last sent\n */\n private cache: Map<string, number>;\n\n /**\n * Time window in milliseconds\n * Errors with the same fingerprint within this window are considered duplicates\n */\n private window: number;\n\n /**\n * Interval ID for cleanup task\n */\n private cleanupIntervalId?: NodeJS.Timeout;\n\n /**\n * Create a new deduplicator\n *\n * @param window - Deduplication window in milliseconds (default: 5 minutes)\n */\n constructor(window: number = 5 * 60 * 1000) {\n this.cache = new Map();\n this.window = window;\n\n // Start automatic cleanup every minute\n this.startCleanup();\n }\n\n /**\n * Check if an error should be sent\n *\n * @param fingerprint - Error fingerprint\n * @returns true if error should be sent, false if it's a duplicate\n */\n shouldSend(fingerprint: string): boolean {\n const now = Date.now();\n const lastSent = this.cache.get(fingerprint);\n\n if (lastSent !== undefined) {\n const elapsed = now - lastSent;\n\n // If error was sent within the window, it's a duplicate\n if (elapsed < this.window) {\n return false;\n }\n }\n\n // Mark this fingerprint as sent\n this.cache.set(fingerprint, now);\n return true;\n }\n\n /**\n * Mark an error as sent (manually)\n *\n * This can be used to pre-populate the cache or update the timestamp\n * after a successful send.\n *\n * @param fingerprint - Error fingerprint\n */\n markSent(fingerprint: string): void {\n this.cache.set(fingerprint, Date.now());\n }\n\n /**\n * Check if an error fingerprint is in the cache\n *\n * @param fingerprint - Error fingerprint\n * @returns true if fingerprint exists and is within the window\n */\n has(fingerprint: string): boolean {\n const lastSent = this.cache.get(fingerprint);\n if (lastSent === undefined) {\n return false;\n }\n\n const elapsed = Date.now() - lastSent;\n return elapsed < this.window;\n }\n\n /**\n * Get the number of entries in the cache\n */\n get size(): number {\n return this.cache.size;\n }\n\n /**\n * Clear all entries from the cache\n */\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Remove expired entries from the cache\n *\n * This is called automatically every minute, but can also be\n * called manually to free up memory.\n */\n cleanup(): void {\n const now = Date.now();\n const toDelete: string[] = [];\n\n // Find expired entries\n for (const [fingerprint, timestamp] of this.cache.entries()) {\n const elapsed = now - timestamp;\n if (elapsed >= this.window) {\n toDelete.push(fingerprint);\n }\n }\n\n // Delete expired entries\n for (const fingerprint of toDelete) {\n this.cache.delete(fingerprint);\n }\n }\n\n /**\n * Start automatic cleanup task\n *\n * Runs cleanup every minute to remove expired entries\n */\n private startCleanup(): void {\n // Run cleanup every minute\n this.cleanupIntervalId = setInterval(() => {\n this.cleanup();\n }, 60 * 1000);\n\n // Ensure the interval doesn't prevent Node.js from exiting\n if (this.cleanupIntervalId.unref) {\n this.cleanupIntervalId.unref();\n }\n }\n\n /**\n * Stop automatic cleanup task\n *\n * This should be called when shutting down to prevent memory leaks\n */\n destroy(): void {\n if (this.cleanupIntervalId) {\n clearInterval(this.cleanupIntervalId);\n this.cleanupIntervalId = undefined;\n }\n this.cache.clear();\n }\n\n /**\n * Get cache statistics (for debugging)\n */\n getStats(): {\n size: number;\n window: number;\n entries: Array<{ fingerprint: string; age: number }>;\n } {\n const now = Date.now();\n const entries = Array.from(this.cache.entries()).map(([fingerprint, timestamp]) => ({\n fingerprint,\n age: now - timestamp,\n }));\n\n return {\n size: this.cache.size,\n window: this.window,\n entries,\n };\n }\n}\n","import type { CapturedError, SourceContext } from \"./types\";\n\n/**\n * Queued error item\n */\ninterface QueuedError {\n /**\n * The error to send\n */\n error: CapturedError;\n\n /**\n * Source context (if available)\n */\n sourceContext?: SourceContext;\n\n /**\n * Number of send attempts\n */\n attempts: number;\n\n /**\n * Timestamp of last attempt\n */\n lastAttempt?: number;\n\n /**\n * Next retry timestamp\n */\n nextRetry: number;\n}\n\n/**\n * Function that sends an error to the service\n */\ntype SendFunction = (\n error: CapturedError,\n sourceContext?: SourceContext\n) => Promise<boolean>;\n\n/**\n * Retry queue with exponential backoff\n *\n * Handles failed error reports by queuing them and retrying with\n * exponentially increasing delays. Never blocks the host application.\n */\nexport class RetryQueue {\n /**\n * Queue of errors waiting to be sent\n */\n private queue: QueuedError[] = [];\n\n /**\n * Whether the queue is currently processing\n */\n private processing: boolean = false;\n\n /**\n * Maximum number of retry attempts\n */\n private maxRetries: number = 5;\n\n /**\n * Base backoff delay in milliseconds\n */\n private baseDelay: number = 1000; // 1 second\n\n /**\n * Maximum backoff delay in milliseconds\n */\n private maxDelay: number = 16000; // 16 seconds\n\n /**\n * Function to send errors\n */\n private sendFn: SendFunction;\n\n /**\n * Debug mode\n */\n private debug: boolean;\n\n /**\n * Processing interval ID\n */\n private intervalId?: NodeJS.Timeout;\n\n /**\n * Create a new retry queue\n *\n * @param sendFn - Function to send errors\n * @param options - Configuration options\n */\n constructor(\n sendFn: SendFunction,\n options?: {\n maxRetries?: number;\n baseDelay?: number;\n maxDelay?: number;\n debug?: boolean;\n }\n ) {\n this.sendFn = sendFn;\n this.maxRetries = options?.maxRetries ?? 5;\n this.baseDelay = options?.baseDelay ?? 1000;\n this.maxDelay = options?.maxDelay ?? 16000;\n this.debug = options?.debug ?? false;\n\n // Start processing queue periodically\n this.startProcessing();\n }\n\n /**\n * Enqueue an error for sending\n *\n * This is non-blocking and returns immediately.\n *\n * @param error - The error to send\n * @param sourceContext - Source context (optional)\n */\n enqueue(error: CapturedError, sourceContext?: SourceContext): void {\n const queuedError: QueuedError = {\n error,\n sourceContext,\n attempts: 0,\n nextRetry: Date.now(), // Send immediately on first attempt\n };\n\n this.queue.push(queuedError);\n this.log(`Enqueued error: ${error.id} (queue size: ${this.queue.length})`);\n\n // Trigger processing\n this.processQueue();\n }\n\n /**\n * Get the current queue size\n */\n get size(): number {\n return this.queue.length;\n }\n\n /**\n * Clear all items from the queue\n */\n clear(): void {\n this.queue = [];\n }\n\n /**\n * Destroy the queue and stop processing\n */\n destroy(): void {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n this.intervalId = undefined;\n }\n this.queue = [];\n this.processing = false;\n }\n\n /**\n * Start periodic queue processing\n */\n private startProcessing(): void {\n // Process queue every 500ms\n this.intervalId = setInterval(() => {\n this.processQueue();\n }, 500);\n\n // Ensure the interval doesn't prevent Node.js from exiting\n if (this.intervalId.unref) {\n this.intervalId.unref();\n }\n }\n\n /**\n * Process the queue\n *\n * This is called periodically and also immediately after enqueue.\n * Non-blocking - errors are caught and logged.\n */\n private async processQueue(): Promise<void> {\n if (this.processing || this.queue.length === 0) {\n return;\n }\n\n this.processing = true;\n\n try {\n const now = Date.now();\n\n // Find errors ready to be sent (nextRetry <= now)\n const readyErrors = this.queue.filter((item) => item.nextRetry <= now);\n\n if (readyErrors.length === 0) {\n return;\n }\n\n this.log(`Processing ${readyErrors.length} ready errors`);\n\n // Process each ready error\n for (const item of readyErrors) {\n await this.processItem(item);\n }\n } catch (err) {\n // Never let queue processing crash\n this.logError(\"Queue processing error:\", err);\n } finally {\n this.processing = false;\n }\n }\n\n /**\n * Process a single queued error\n *\n * @param item - The queued error item\n */\n private async processItem(item: QueuedError): Promise<void> {\n try {\n item.attempts++;\n item.lastAttempt = Date.now();\n\n this.log(\n `Sending error ${item.error.id} (attempt ${item.attempts}/${this.maxRetries})`\n );\n\n // Try to send the error\n const success = await this.sendFn(item.error, item.sourceContext);\n\n if (success) {\n // Success - remove from queue\n this.log(`Successfully sent error: ${item.error.id}`);\n this.removeFromQueue(item);\n } else {\n // Failed - retry or give up\n this.handleFailure(item);\n }\n } catch (err) {\n // Error during send - retry or give up\n this.logError(`Error sending ${item.error.id}:`, err);\n this.handleFailure(item);\n }\n }\n\n /**\n * Handle a failed send attempt\n *\n * @param item - The queued error item\n */\n private handleFailure(item: QueuedError): void {\n if (item.attempts >= this.maxRetries) {\n // Max retries exceeded - give up\n this.logError(\n `Max retries exceeded for error ${item.error.id}, dropping`\n );\n this.removeFromQueue(item);\n } else {\n // Schedule retry with exponential backoff\n const delay = this.calculateBackoff(item.attempts);\n item.nextRetry = Date.now() + delay;\n\n this.log(\n `Scheduling retry for error ${item.error.id} in ${delay}ms (attempt ${item.attempts}/${this.maxRetries})`\n );\n }\n }\n\n /**\n * Calculate exponential backoff delay\n *\n * Backoff formula: min(baseDelay * 2^(attempts - 1), maxDelay)\n * - Attempt 1: 1s\n * - Attempt 2: 2s\n * - Attempt 3: 4s\n * - Attempt 4: 8s\n * - Attempt 5: 16s\n *\n * @param attempts - Number of attempts\n * @returns Delay in milliseconds\n */\n private calculateBackoff(attempts: number): number {\n const delay = this.baseDelay * Math.pow(2, attempts - 1);\n return Math.min(delay, this.maxDelay);\n }\n\n /**\n * Remove an item from the queue\n *\n * @param item - The item to remove\n */\n private removeFromQueue(item: QueuedError): void {\n const index = this.queue.indexOf(item);\n if (index !== -1) {\n this.queue.splice(index, 1);\n }\n }\n\n /**\n * Log a message (if debug mode is enabled)\n *\n * @param message - Message to log\n */\n private log(message: string): void {\n if (this.debug) {\n console.log(`[BugStack Queue] ${message}`);\n }\n }\n\n /**\n * Log an error (if debug mode is enabled)\n *\n * @param message - Message to log\n * @param error - Error object (optional)\n */\n private logError(message: string, error?: unknown): void {\n if (this.debug) {\n if (error) {\n console.error(`[BugStack Queue] ${message}`, error);\n } else {\n console.error(`[BugStack Queue] ${message}`);\n }\n }\n }\n\n /**\n * Get queue statistics (for debugging)\n */\n getStats(): {\n size: number;\n processing: boolean;\n items: Array<{\n errorId: string;\n attempts: number;\n nextRetry: number;\n timeUntilRetry: number;\n }>;\n } {\n const now = Date.now();\n\n return {\n size: this.queue.length,\n processing: this.processing,\n items: this.queue.map((item) => ({\n errorId: item.error.id,\n attempts: item.attempts,\n nextRetry: item.nextRetry,\n timeUntilRetry: Math.max(0, item.nextRetry - now),\n })),\n };\n }\n}\n","/**\n * Single source of truth for the SDK's wire version.\n *\n * `__BUGSTACK_SDK_VERSION__` is replaced at build time by tsup's `define`\n * (see tsup.config.ts) with the literal `package.json#version`. The fallback\n * `\"0.0.0-dev\"` is only reachable when the package is consumed unbuilt\n * (e.g. ts-node against src/) — not a path we publish, but it keeps dev\n * ergonomics sane and avoids a hard ReferenceError.\n *\n * Every adapter and client pulls SDK_VERSION from here so a release bump\n * propagates atomically without hand-edits across files.\n */\ndeclare const __BUGSTACK_SDK_VERSION__: string;\n\nexport const SDK_VERSION: string =\n typeof __BUGSTACK_SDK_VERSION__ !== \"undefined\" ? __BUGSTACK_SDK_VERSION__ : \"0.0.0-dev\";\n","import type {\n ErrorCaptureConfig,\n ResolvedConfig,\n CapturedError,\n ErrorReportPayload,\n SourceContext,\n} from \"./types\";\nimport { generateErrorFingerprint } from \"./fingerprint\";\nimport { ErrorDeduplicator } from \"./deduplicator\";\nimport { RetryQueue } from \"./queue\";\n\nimport { SDK_VERSION } from \"./sdk-version\";\nconst DEFAULT_ENDPOINT = \"https://dashboard.bugstack.ai/api/ingest/sdk\";\nconst DEFAULT_TIMEOUT = 5000;\nconst DEFAULT_MAX_BODY_SIZE = 10000;\nconst DEFAULT_DEDUPLICATION_WINDOW = 5 * 60 * 1000; // 5 minutes\n\n/**\n * Default sensitive fields to redact from requests\n */\nconst DEFAULT_REDACT_FIELDS = [\n \"password\",\n \"secret\",\n \"token\",\n \"apikey\",\n \"api_key\",\n \"apiKey\",\n \"authorization\",\n \"auth\",\n \"credential\",\n \"private\",\n \"credit_card\",\n \"creditcard\",\n \"card_number\",\n \"cvv\",\n \"ssn\",\n \"social_security\",\n];\n\n/**\n * BugStack Error Capture Client\n *\n * Singleton client for capturing and reporting errors to the BugStack service.\n * Now includes client-side deduplication and retry queue with exponential backoff.\n */\nexport class ErrorCaptureClient {\n private config: ResolvedConfig;\n private static instance: ErrorCaptureClient | null = null;\n private deduplicator: ErrorDeduplicator;\n private retryQueue: RetryQueue;\n\n constructor(config: ErrorCaptureConfig) {\n const isProduction = process.env.NODE_ENV === \"production\";\n\n this.config = {\n apiKey: config.apiKey,\n endpoint:\n config.endpoint ??\n process.env.BUGSTACK_ENDPOINT ??\n DEFAULT_ENDPOINT,\n projectId: config.projectId ?? process.env.BUGSTACK_PROJECT_ID ?? \"\",\n environment:\n config.environment ?? process.env.NODE_ENV ?? \"development\",\n autoFix: config.autoFix ?? false,\n enabled: config.enabled ?? true,\n captureRequestBody: config.captureRequestBody ?? false,\n captureQueryParams: config.captureQueryParams ?? true,\n captureHeaders: config.captureHeaders ?? true,\n maxBodySize: config.maxBodySize ?? DEFAULT_MAX_BODY_SIZE,\n redactFields: [\n ...DEFAULT_REDACT_FIELDS,\n ...(config.redactFields ?? []),\n ],\n metadata: config.metadata ?? {},\n timeout: config.timeout ?? DEFAULT_TIMEOUT,\n deduplicationWindow:\n config.deduplicationWindow ?? DEFAULT_DEDUPLICATION_WINDOW,\n debug: config.debug ?? !isProduction,\n shouldCapture: config.shouldCapture,\n beforeSend: config.beforeSend,\n dropChunkErrors: config.dropChunkErrors ?? false,\n chunkErrorsEndpoint:\n config.chunkErrorsEndpoint ??\n deriveChunkErrorsEndpoint(\n config.endpoint ??\n process.env.BUGSTACK_ENDPOINT ??\n DEFAULT_ENDPOINT,\n ),\n };\n\n // Initialize deduplicator\n this.deduplicator = new ErrorDeduplicator(this.config.deduplicationWindow);\n\n // Initialize retry queue with send function bound to this instance\n this.retryQueue = new RetryQueue(\n (error, sourceContext) => this.sendErrorToService(error, sourceContext),\n {\n maxRetries: 5,\n baseDelay: 1000,\n maxDelay: 16000,\n debug: this.config.debug,\n }\n );\n\n this.log(\"BugStack client initialized\", {\n endpoint: this.config.endpoint,\n projectId: this.config.projectId,\n environment: this.config.environment,\n autoFix: this.config.autoFix,\n deduplicationWindow: this.config.deduplicationWindow,\n });\n }\n\n /**\n * Initialize the singleton client instance\n */\n static init(config: ErrorCaptureConfig): ErrorCaptureClient {\n // Clean up existing instance if present\n if (ErrorCaptureClient.instance) {\n ErrorCaptureClient.instance.destroy();\n }\n\n ErrorCaptureClient.instance = new ErrorCaptureClient(config);\n return ErrorCaptureClient.instance;\n }\n\n /**\n * Get the singleton client instance\n */\n static getInstance(): ErrorCaptureClient | null {\n return ErrorCaptureClient.instance;\n }\n\n /**\n * Check if the client has been initialized\n */\n static isInitialized(): boolean {\n return ErrorCaptureClient.instance !== null;\n }\n\n /**\n * Reset the client (mainly for testing)\n */\n static reset(): void {\n if (ErrorCaptureClient.instance) {\n ErrorCaptureClient.instance.destroy();\n }\n ErrorCaptureClient.instance = null;\n }\n\n /**\n * Report an error to the BugStack service\n *\n * This method includes deduplication and queuing for resilience.\n *\n * @param error - The captured error\n * @param sourceContext - Source code context (optional)\n * @returns Promise that resolves to true if error was accepted (not deduplicated)\n */\n async reportError(\n error: CapturedError,\n sourceContext?: SourceContext\n ): Promise<boolean> {\n if (!this.config.enabled) {\n this.log(\"Error capture is disabled, skipping report\");\n return false;\n }\n\n // Chunk-load errors don't go through the fix pipeline. By default they\n // get routed to the lightweight telemetry endpoint so the dashboard can\n // still spot CDN outages / broken deploys via spike detection. The\n // dropChunkErrors flag short-circuits even that path.\n if (isChunkLoadError(error)) {\n if (!this.config.dropChunkErrors) {\n this.sendChunkErrorTelemetry(error).catch(() => {\n /* fire and forget — telemetry failure must never escalate */\n });\n } else {\n this.log(`Dropped chunk-load error: ${error.message}`);\n }\n return false;\n }\n\n // Apply beforeSend hook if provided\n let errorToSend = error;\n if (this.config.beforeSend) {\n const modified = this.config.beforeSend(error);\n if (modified === null) {\n this.log(\"Error filtered by beforeSend hook\");\n return false;\n }\n errorToSend = modified;\n }\n\n // Generate fingerprint for deduplication\n const fingerprint = generateErrorFingerprint(errorToSend);\n errorToSend.fingerprint = fingerprint;\n\n // Check deduplication\n if (!this.deduplicator.shouldSend(fingerprint)) {\n this.log(`Error deduplicated: ${error.id} (fingerprint: ${fingerprint})`);\n return false;\n }\n\n this.log(`Reporting error: ${error.id} (fingerprint: ${fingerprint})`);\n\n // Add project metadata\n errorToSend.projectId = this.config.projectId || errorToSend.projectId;\n errorToSend.environment = this.config.environment;\n errorToSend.metadata = {\n ...this.config.metadata,\n ...errorToSend.metadata,\n autoFix: this.config.autoFix,\n };\n\n // Enqueue for sending (non-blocking)\n this.retryQueue.enqueue(errorToSend, sourceContext);\n\n return true;\n }\n\n /**\n * Send an error to the service (internal method)\n *\n * This is used by the retry queue. Returns true on success, false on failure.\n *\n * @param error - The error to send\n * @param sourceContext - Source context (optional)\n * @returns Promise that resolves to true on success\n */\n private async sendErrorToService(\n error: CapturedError,\n sourceContext?: SourceContext\n ): Promise<boolean> {\n const payload: ErrorReportPayload = {\n error,\n sourceContext,\n };\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n this.config.timeout\n );\n\n const response = await fetch(this.config.endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-BugStack-API-Key\": this.config.apiKey,\n \"X-BugStack-SDK-Version\": SDK_VERSION,\n },\n body: JSON.stringify(payload),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n this.logError(\n `Failed to send error: HTTP ${response.status} ${response.statusText}`\n );\n return false;\n }\n\n this.log(`Error sent successfully: ${error.id}`);\n return true;\n } catch (err) {\n if (err instanceof Error && err.name === \"AbortError\") {\n this.logError(`Error send timed out after ${this.config.timeout}ms`);\n } else {\n this.logError(\"Failed to send error:\", err);\n }\n return false;\n }\n }\n\n /**\n * Forward a chunk-load error to the lightweight telemetry endpoint.\n * Fire-and-forget — never throws, never retries, never logs loud. The\n * point is to count these without spending real money on them.\n */\n private async sendChunkErrorTelemetry(error: CapturedError): Promise<void> {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 2000);\n await fetch(this.config.chunkErrorsEndpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-BugStack-API-Key\": this.config.apiKey,\n \"X-BugStack-SDK-Version\": SDK_VERSION,\n },\n body: JSON.stringify({\n message: error.message,\n url: error.url,\n route: error.route,\n userAgent:\n (error.requestHeaders && (error.requestHeaders[\"user-agent\"] || error.requestHeaders[\"User-Agent\"])) ||\n (typeof navigator !== \"undefined\" ? navigator.userAgent : undefined),\n release: this.config.metadata?.release as string | undefined,\n }),\n signal: controller.signal,\n // Browsers respect keepalive on cross-origin POSTs during unload.\n keepalive: true,\n });\n clearTimeout(timeoutId);\n this.log(`Chunk-error telemetry sent: ${error.message}`);\n } catch {\n // Intentionally silent. See method comment.\n }\n }\n\n /**\n * Get the resolved configuration\n */\n getConfig(): ResolvedConfig {\n return { ...this.config };\n }\n\n /**\n * Check if a field should be redacted\n */\n shouldRedact(fieldName: string): boolean {\n const lowerField = fieldName.toLowerCase();\n return this.config.redactFields.some(\n (redact) =>\n lowerField.includes(redact.toLowerCase()) ||\n redact.toLowerCase().includes(lowerField)\n );\n }\n\n /**\n * Get the SDK version\n */\n static getVersion(): string {\n return SDK_VERSION;\n }\n\n /**\n * Get client statistics (for debugging)\n */\n getStats(): {\n deduplicator: ReturnType<ErrorDeduplicator[\"getStats\"]>;\n retryQueue: ReturnType<RetryQueue[\"getStats\"]>;\n } {\n return {\n deduplicator: this.deduplicator.getStats(),\n retryQueue: this.retryQueue.getStats(),\n };\n }\n\n /**\n * Clean up resources\n *\n * Should be called when shutting down to prevent memory leaks\n */\n destroy(): void {\n this.deduplicator.destroy();\n this.retryQueue.destroy();\n }\n\n private log(message: string, data?: Record<string, unknown>): void {\n if (this.config.debug) {\n if (data) {\n console.log(`[BugStack] ${message}`, data);\n } else {\n console.log(`[BugStack] ${message}`);\n }\n }\n }\n\n private logError(message: string, error?: unknown): void {\n if (this.config.debug) {\n if (error) {\n console.error(`[BugStack] ${message}`, error);\n } else {\n console.error(`[BugStack] ${message}`);\n }\n }\n }\n}\n\n// Legacy alias for backwards compatibility\nexport const BugStackClient = ErrorCaptureClient;\n\n/**\n * Recognise the family of \"browser failed to load a code-split chunk\" errors.\n * Webpack and Vite emit slightly different messages; the regex covers both.\n *\n * Exported (via re-export from index.ts) so callers can reuse the same check\n * in their own error boundaries when deciding whether to soft-reload.\n */\nexport function isChunkLoadError(\n error: { name?: string; message?: string }\n): boolean {\n if (!error) return false;\n if (error.name === \"ChunkLoadError\") return true;\n const msg = error.message || \"\";\n return (\n /Loading chunk\\s+[\\w-]+\\s+failed/i.test(msg) ||\n /Loading CSS chunk\\s+[\\w-]+\\s+failed/i.test(msg) ||\n /Failed to fetch dynamically imported module/i.test(msg) ||\n /Importing a module script failed/i.test(msg)\n );\n}\n\n/**\n * Default-derive the chunk-errors telemetry endpoint from the main capture\n * endpoint, so callers don't have to configure both. We replace the trailing\n * `/capture` segment (whether prefixed by `/api` or not) with `/chunk-errors`.\n * If the URL doesn't match the expected shape we fall back to suffixing the\n * original endpoint, which still lands on the right route in the typical\n * `https://host/api/capture` deployment.\n */\nfunction deriveChunkErrorsEndpoint(captureEndpoint: string): string {\n if (/\\/api\\/capture(\\/?$|\\?)/.test(captureEndpoint)) {\n return captureEndpoint.replace(/\\/api\\/capture/, \"/api/chunk-errors\");\n }\n if (/\\/capture(\\/?$|\\?)/.test(captureEndpoint)) {\n return captureEndpoint.replace(/\\/capture/, \"/chunk-errors\");\n }\n return captureEndpoint.replace(/\\/?$/, \"/chunk-errors\");\n}\n","import type { StackFrame } from \"../types\";\n\n/**\n * Regular expression to parse V8 stack trace frames\n * Handles formats like:\n * at functionName (file:line:column)\n * at file:line:column\n * at async functionName (file:line:column)\n */\nconst V8_STACK_FRAME_REGEX =\n /^\\s*at\\s+(?:async\\s+)?(?:(.+?)\\s+\\()?(?:(.+?):(\\d+):(\\d+))\\)?$/;\n\n/**\n * Check if a file path is from node_modules\n */\nfunction isNodeModule(filePath: string): boolean {\n return filePath.includes(\"node_modules\");\n}\n\n/**\n * Check if a file path is internal Node.js code\n */\nfunction isInternalCode(filePath: string): boolean {\n return (\n filePath.startsWith(\"node:\") ||\n filePath.startsWith(\"internal/\") ||\n !filePath.includes(\"/\")\n );\n}\n\n/**\n * Clean up function names\n */\nfunction cleanFunctionName(name: string | undefined): string | undefined {\n if (!name) return undefined;\n\n // Remove common prefixes\n return name\n .replace(/^Object\\./, \"\")\n .replace(/^Module\\./, \"\")\n .replace(/^__webpack_require__\\./, \"\")\n .replace(/^webpack_require\\./, \"\")\n .trim();\n}\n\n/**\n * Parse a V8 stack trace into structured frames\n */\nexport function parseStackTrace(stack: string | undefined): StackFrame[] {\n if (!stack) return [];\n\n const lines = stack.split(\"\\n\");\n const frames: StackFrame[] = [];\n\n for (const line of lines) {\n const match = V8_STACK_FRAME_REGEX.exec(line);\n\n if (match) {\n const [, functionName, file, lineStr, columnStr] = match;\n\n const frame: StackFrame = {\n function: cleanFunctionName(functionName),\n file: file ?? undefined,\n line: lineStr ? parseInt(lineStr, 10) : undefined,\n column: columnStr ? parseInt(columnStr, 10) : undefined,\n };\n\n if (frame.file) {\n frame.isNodeModule = isNodeModule(frame.file);\n frame.isInternal = isInternalCode(frame.file);\n }\n\n frames.push(frame);\n }\n }\n\n return frames;\n}\n\n/**\n * Get the first application frame (non-node_modules, non-internal)\n */\nexport function getFirstAppFrame(frames: StackFrame[]): StackFrame | undefined {\n return frames.find((frame) => !frame.isNodeModule && !frame.isInternal);\n}\n\n/**\n * Filter stack frames to only include application code\n */\nexport function getAppFrames(frames: StackFrame[]): StackFrame[] {\n return frames.filter((frame) => !frame.isNodeModule && !frame.isInternal);\n}\n\n/**\n * Format stack frames back to a string (useful for cleaned stack traces)\n */\nexport function formatStackFrames(frames: StackFrame[]): string {\n return frames\n .map((frame) => {\n const location = [frame.file, frame.line, frame.column]\n .filter(Boolean)\n .join(\":\");\n\n if (frame.function) {\n return ` at ${frame.function} (${location})`;\n }\n return ` at ${location}`;\n })\n .join(\"\\n\");\n}\n","import type { ErrorCaptureClient } from \"../client\";\n\nconst REDACT_PLACEHOLDER = \"[REDACTED]\";\nconst TRUNCATE_PLACEHOLDER = \"[TRUNCATED]\";\n\n/**\n * Sensitive headers that are always redacted\n */\nconst SENSITIVE_HEADERS = new Set([\n \"authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-api-key\",\n \"x-auth-token\",\n \"x-bugstack-api-key\",\n \"proxy-authorization\",\n \"www-authenticate\",\n]);\n\n/**\n * Sanitize headers by removing sensitive values\n */\nexport function sanitizeHeaders(\n headers: Headers,\n client?: ErrorCaptureClient | null\n): Record<string, string> {\n const sanitized: Record<string, string> = {};\n\n headers.forEach((value, key) => {\n const lowerKey = key.toLowerCase();\n\n // Always redact known sensitive headers\n if (SENSITIVE_HEADERS.has(lowerKey)) {\n sanitized[key] = REDACT_PLACEHOLDER;\n return;\n }\n\n // Check against custom redact fields\n if (client?.shouldRedact(key)) {\n sanitized[key] = REDACT_PLACEHOLDER;\n return;\n }\n\n sanitized[key] = value;\n });\n\n return sanitized;\n}\n\n/**\n * Sanitize query parameters by redacting sensitive values\n */\nexport function sanitizeQueryParams(\n url: URL,\n client?: ErrorCaptureClient | null\n): Record<string, string> {\n const sanitized: Record<string, string> = {};\n\n url.searchParams.forEach((value, key) => {\n if (client?.shouldRedact(key)) {\n sanitized[key] = REDACT_PLACEHOLDER;\n } else {\n sanitized[key] = value;\n }\n });\n\n return sanitized;\n}\n\n/**\n * Recursively sanitize an object by redacting sensitive fields\n */\nexport function sanitizeObject(\n obj: unknown,\n client?: ErrorCaptureClient | null,\n maxDepth = 10,\n currentDepth = 0\n): unknown {\n // Prevent infinite recursion\n if (currentDepth > maxDepth) {\n return TRUNCATE_PLACEHOLDER;\n }\n\n if (obj === null || obj === undefined) {\n return obj;\n }\n\n if (typeof obj !== \"object\") {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) =>\n sanitizeObject(item, client, maxDepth, currentDepth + 1)\n );\n }\n\n const sanitized: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n if (client?.shouldRedact(key)) {\n sanitized[key] = REDACT_PLACEHOLDER;\n } else if (typeof value === \"object\" && value !== null) {\n sanitized[key] = sanitizeObject(value, client, maxDepth, currentDepth + 1);\n } else {\n sanitized[key] = value;\n }\n }\n\n return sanitized;\n}\n\n/**\n * Truncate a string or object to a maximum size\n */\nexport function truncateBody(\n data: unknown,\n maxSize: number\n): { body: unknown; truncated: boolean } {\n const serialized = JSON.stringify(data);\n\n if (serialized.length <= maxSize) {\n return { body: data, truncated: false };\n }\n\n // For strings, truncate directly\n if (typeof data === \"string\") {\n return {\n body: {\n __truncated: true,\n __originalSize: serialized.length,\n preview: TRUNCATE_PLACEHOLDER,\n },\n truncated: true,\n };\n }\n\n // For objects, try to preserve structure but indicate truncation\n return {\n body: {\n __truncated: true,\n __originalSize: serialized.length,\n __maxSize: maxSize,\n preview: serialized.slice(0, maxSize),\n },\n truncated: true,\n };\n}\n\n/**\n * Safely parse request body with error handling\n */\nexport async function safeParseBody(\n request: Request,\n maxSize: number,\n client?: ErrorCaptureClient | null\n): Promise<{ body: unknown; truncated: boolean } | null> {\n try {\n // Clone the request to avoid consuming the body\n const cloned = request.clone();\n const contentType = cloned.headers.get(\"content-type\") ?? \"\";\n\n // Handle JSON bodies\n if (contentType.includes(\"application/json\")) {\n const text = await cloned.text();\n\n if (text.length > maxSize) {\n return {\n body: {\n __truncated: true,\n __originalSize: text.length,\n preview: TRUNCATE_PLACEHOLDER,\n },\n truncated: true,\n };\n }\n\n try {\n const parsed = JSON.parse(text);\n const sanitized = sanitizeObject(parsed, client);\n return truncateBody(sanitized, maxSize);\n } catch {\n // Not valid JSON, return as text\n return truncateBody(text, maxSize);\n }\n }\n\n // Handle form data\n if (\n contentType.includes(\"application/x-www-form-urlencoded\") ||\n contentType.includes(\"multipart/form-data\")\n ) {\n try {\n const formData = await cloned.formData();\n const data: Record<string, unknown> = {};\n\n formData.forEach((value, key) => {\n if (value instanceof File) {\n data[key] = {\n type: \"file\",\n name: value.name,\n size: value.size,\n mimeType: value.type,\n };\n } else if (client?.shouldRedact(key)) {\n data[key] = REDACT_PLACEHOLDER;\n } else {\n data[key] = value;\n }\n });\n\n return truncateBody(data, maxSize);\n } catch {\n return { body: \"[FormData parsing failed]\", truncated: false };\n }\n }\n\n // Handle text bodies\n if (contentType.includes(\"text/\")) {\n const text = await cloned.text();\n return truncateBody(text, maxSize);\n }\n\n // For other content types, just note the type\n return {\n body: {\n __contentType: contentType,\n __note: \"Body not captured for this content type\",\n },\n truncated: false,\n };\n } catch (err) {\n // Body may have already been consumed or other error\n return null;\n }\n}\n","/**\n * BugStack SDK - Express Adapter\n *\n * Error capture middleware for Express.js applications\n */\n\nimport type { Request, Response, NextFunction, ErrorRequestHandler } from \"express\";\nimport { ErrorCaptureClient } from \"../../core/client\";\nimport type { ErrorCaptureConfig, CapturedError } from \"../../core/types\";\nimport { parseStackTrace, getFirstAppFrame } from \"../../core/utils/stack-parser\";\nimport { sanitizeObject, truncateBody } from \"../../core/utils/sanitize\";\nimport { SDK_VERSION } from \"../../core/sdk-version\";\n\n/**\n * Generate a unique error ID\n */\nfunction generateErrorId(): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 9);\n return `err_${timestamp}_${random}`;\n}\n\n/**\n * Get Node.js version\n */\nfunction getNodeVersion(): string {\n try {\n return process.version;\n } catch {\n return \"unknown\";\n }\n}\n\n/**\n * Get Express version\n */\nfunction getExpressVersion(): string | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const pkg = require(\"express/package.json\");\n return pkg.version;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Sanitize headers for Express\n */\nfunction sanitizeExpressHeaders(\n headers: Request[\"headers\"],\n client?: ErrorCaptureClient | null\n): Record<string, string> {\n const sanitized: Record<string, string> = {};\n const SENSITIVE_HEADERS = new Set([\n \"authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-api-key\",\n \"x-auth-token\",\n \"x-bugstack-api-key\",\n \"proxy-authorization\",\n \"www-authenticate\",\n ]);\n\n for (const [key, value] of Object.entries(headers)) {\n const lowerKey = key.toLowerCase();\n\n if (SENSITIVE_HEADERS.has(lowerKey)) {\n sanitized[key] = \"[REDACTED]\";\n } else if (client?.shouldRedact(key)) {\n sanitized[key] = \"[REDACTED]\";\n } else if (typeof value === \"string\") {\n sanitized[key] = value;\n } else if (Array.isArray(value)) {\n sanitized[key] = value.join(\", \");\n } else {\n sanitized[key] = String(value);\n }\n }\n\n return sanitized;\n}\n\n/**\n * Sanitize query parameters\n */\nfunction sanitizeExpressQuery(\n query: Request[\"query\"],\n client?: ErrorCaptureClient | null\n): Record<string, string> {\n const sanitized: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(query)) {\n if (client?.shouldRedact(key)) {\n sanitized[key] = \"[REDACTED]\";\n } else if (typeof value === \"string\") {\n sanitized[key] = value;\n } else if (Array.isArray(value)) {\n sanitized[key] = value.join(\", \");\n } else {\n sanitized[key] = String(value);\n }\n }\n\n return sanitized;\n}\n\n/**\n * Build captured error from Express context\n */\nfunction buildCapturedError(\n error: Error,\n req: Request,\n client: ErrorCaptureClient\n): CapturedError {\n const config = client.getConfig();\n const stackFrames = parseStackTrace(error.stack);\n const firstAppFrame = getFirstAppFrame(stackFrames);\n\n const capturedError: CapturedError = {\n id: generateErrorId(),\n name: error.name || \"Error\",\n message: error.message,\n stack: error.stack,\n stackFrames,\n timestamp: new Date().toISOString(),\n route: req.route?.path || req.path || req.url,\n method: req.method,\n statusCode: 500,\n url: req.originalUrl || req.url,\n environment: config.environment,\n projectId: config.projectId,\n sdkVersion: SDK_VERSION,\n nodeVersion: getNodeVersion(),\n };\n\n // Add Express version if available\n const expressVersion = getExpressVersion();\n if (expressVersion) {\n capturedError.metadata = {\n ...capturedError.metadata,\n expressVersion,\n };\n }\n\n // Add route params if available\n if (req.params && Object.keys(req.params).length > 0) {\n capturedError.routeParams = req.params as Record<string, string>;\n }\n\n // Add query params if configured\n if (config.captureQueryParams && req.query && Object.keys(req.query).length > 0) {\n capturedError.queryParams = sanitizeExpressQuery(req.query, client);\n }\n\n // Add headers if configured\n if (config.captureHeaders) {\n capturedError.requestHeaders = sanitizeExpressHeaders(req.headers, client);\n }\n\n // Add request body if configured\n if (config.captureRequestBody && req.body) {\n const sanitizedBody = sanitizeObject(req.body, client);\n const bodyResult = truncateBody(sanitizedBody, config.maxBodySize);\n capturedError.requestBody = bodyResult.body;\n if (bodyResult.truncated) {\n capturedError.metadata = {\n ...capturedError.metadata,\n bodyTruncated: true,\n };\n }\n }\n\n // Add source location from first app frame\n if (firstAppFrame) {\n capturedError.metadata = {\n ...capturedError.metadata,\n sourceLocation: {\n file: firstAppFrame.file,\n line: firstAppFrame.line,\n column: firstAppFrame.column,\n function: firstAppFrame.function,\n },\n };\n }\n\n return capturedError;\n}\n\n/**\n * Express error handling middleware\n *\n * This middleware captures errors and reports them to BugStack.\n * It must be registered AFTER all routes and other middleware.\n *\n * @example\n * ```typescript\n * import express from 'express';\n * import { bugstackErrorHandler } from '@bugstack/sdk/express';\n *\n * const app = express();\n *\n * // ... your routes and middleware\n *\n * // Register BugStack error handler (must be last)\n * app.use(bugstackErrorHandler({\n * apiKey: 'your-api-key',\n * projectId: 'your-project-id',\n * autoFix: true\n * }));\n * ```\n */\nexport function bugstackErrorHandler(\n config?: ErrorCaptureConfig\n): ErrorRequestHandler {\n // Initialize client if config provided and not already initialized\n if (config && !ErrorCaptureClient.isInitialized()) {\n ErrorCaptureClient.init(config);\n }\n\n // Return Express error middleware\n return (err: Error, req: Request, _res: Response, next: NextFunction): void => {\n const client = ErrorCaptureClient.getInstance();\n\n if (client && client.getConfig().enabled) {\n // Build and report error asynchronously (don't block response)\n const capturedError = buildCapturedError(err, req, client);\n\n client.reportError(capturedError).catch(() => {\n // Silently ignore capture/report failures\n });\n }\n\n // Pass error to next error handler (or default Express error handler)\n next(err);\n };\n}\n\n/**\n * Express middleware to initialize BugStack client\n *\n * Use this if you want to initialize the client separately from the error handler\n *\n * @example\n * ```typescript\n * import express from 'express';\n * import { initBugStack, bugstackErrorHandler } from '@bugstack/sdk/express';\n *\n * const app = express();\n *\n * // Initialize client early\n * app.use(initBugStack({\n * apiKey: 'your-api-key',\n * projectId: 'your-project-id',\n * autoFix: true\n * }));\n *\n * // ... your routes\n *\n * // Register error handler\n * app.use(bugstackErrorHandler());\n * ```\n */\nexport function initBugStack(config: ErrorCaptureConfig) {\n if (!ErrorCaptureClient.isInitialized()) {\n ErrorCaptureClient.init(config);\n }\n\n // Return a no-op middleware\n return (_req: Request, _res: Response, next: NextFunction): void => {\n next();\n };\n}\n\n/**\n * Wrap an Express route handler with error capture\n *\n * This is an alternative to using the error middleware. It catches errors\n * in async route handlers and reports them to BugStack.\n *\n * @example\n * ```typescript\n * import { wrapExpressHandler } from '@bugstack/sdk/express';\n *\n * app.get('/api/users/:id', wrapExpressHandler(async (req, res) => {\n * const user = await getUser(req.params.id);\n * res.json(user);\n * }));\n * ```\n */\nexport function wrapExpressHandler(\n handler: (req: Request, res: Response, next: NextFunction) => Promise<void> | void\n) {\n return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n await handler(req, res, next);\n } catch (error) {\n // Pass to error handling middleware\n next(error);\n }\n };\n}\n\n// Re-export types and client for convenience\nexport type { ErrorCaptureConfig, CapturedError } from \"../../core/types\";\nexport { ErrorCaptureClient, BugStackClient } from \"../../core/client\";\n"]}
|
|
@@ -429,10 +429,10 @@ var RetryQueue = class {
|
|
|
429
429
|
};
|
|
430
430
|
|
|
431
431
|
// src/core/sdk-version.ts
|
|
432
|
-
var SDK_VERSION = "2.2.
|
|
432
|
+
var SDK_VERSION = "2.2.2" ;
|
|
433
433
|
|
|
434
434
|
// src/core/client.ts
|
|
435
|
-
var DEFAULT_ENDPOINT = "
|
|
435
|
+
var DEFAULT_ENDPOINT = "https://dashboard.bugstack.ai/api/ingest/sdk";
|
|
436
436
|
var DEFAULT_TIMEOUT = 5e3;
|
|
437
437
|
var DEFAULT_MAX_BODY_SIZE = 1e4;
|
|
438
438
|
var DEFAULT_DEDUPLICATION_WINDOW = 5 * 60 * 1e3;
|