bugwatch 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/node/index.ts","../src/node/client.ts","../src/shared.ts","../src/node/stack.ts","../src/node/version.ts","../src/node/fetch.ts","../src/node/frameworks.ts","../src/node/process.ts"],"sourcesContent":["/**\n * Bugwatch Node SDK: `import { Bugwatch } from \"bugwatch/node\"`.\n *\n * Catches uncaught exceptions and unhandled rejections (keeping Node's exit\n * behavior), Express and Next.js request errors, and (with\n * `captureHttpErrors`) failed outgoing `fetch` calls; reports errors you pass\n * to `captureError`; keeps per-request context (user, breadcrumbs, request)\n * apart with AsyncLocalStorage. Every\n * public function catches its own errors and never throws into the app.\n */\n\nimport {\n captureError,\n configure,\n flush,\n removeTag,\n runInScope,\n setTag,\n setUser,\n type BugwatchNodeOptions,\n type BugwatchRequest,\n type CaptureOptions,\n type Level,\n} from \"./client\";\nimport { patchFetch } from \"./fetch\";\nimport { expressErrorHandler, expressRequestHandler, nextOnRequestError } from \"./frameworks\";\nimport { installProcessHandlers } from \"./process\";\n\nexport type { BugwatchHttpErrorOptions, BugwatchUser, TagValue } from \"../shared\";\nimport type { TagValue } from \"../shared\";\nexport type { BugwatchNodeOptions, BugwatchRequest, CaptureOptions, Level } from \"./client\";\n\n/** Next.js loads instrumentation in the Edge runtime too; there the SDK does nothing (for now). */\nfunction isSupportedRuntime(): boolean {\n try {\n if (typeof process === \"undefined\" || typeof process.on !== \"function\") return false;\n if (process.env.NEXT_RUNTIME === \"edge\") return false;\n return typeof (globalThis as { EdgeRuntime?: unknown }).EdgeRuntime === \"undefined\";\n } catch {\n return false;\n }\n}\n\nexport const Bugwatch = {\n /**\n * Starts reporting. The API key comes from `apiKey` or `$BUGWATCH_API_KEY`;\n * without one, nothing is sent. Safe to call again: a later call replaces\n * the options (process listeners are added once).\n */\n init(options: BugwatchNodeOptions = {}): void {\n try {\n if (!isSupportedRuntime()) return;\n if (!configure(options)) return;\n installProcessHandlers();\n patchFetch();\n } catch {\n // Never throw into the host app.\n }\n },\n\n /** Reports an error, e.g. one you caught. Optional `level` and `request`. */\n captureError(error: unknown, options?: CaptureOptions): void {\n captureError(error, options);\n },\n\n /**\n * Sets the user for later events. Inside a request (or `withScope`) only\n * that request gets it; outside, it is the default. `null` clears it.\n */\n setUser(user: { id?: string; email?: string } | null): void {\n try {\n setUser(user);\n } catch {\n // Never throw into the host app.\n }\n },\n\n /**\n * Adds a tag to later events, e.g. `setTag(\"plan\", \"pro\")`. Inside a\n * request (or `withScope`) only that request gets it; outside, every event.\n * Keys: 1–32 of a-z, 0-9, `_ . -`; values up to 200 characters; at most 20.\n * A tag that breaks a rule is ignored.\n */\n setTag(key: string, value: TagValue): void {\n try {\n setTag(key, value);\n } catch {\n // Never throw into the host app.\n }\n },\n\n /** Several tags at once: `setTags({ plan: \"pro\", region: \"eu\" })`. */\n setTags(values: Record<string, TagValue>): void {\n try {\n if (!values || typeof values !== \"object\") return;\n for (const [key, value] of Object.entries(values)) setTag(key, value);\n } catch {\n // Never throw into the host app.\n }\n },\n\n /** Stops sending a tag (in the current request, or everywhere outside one). */\n removeTag(key: string): void {\n try {\n removeTag(key);\n } catch {\n // Never throw into the host app.\n }\n },\n\n /** Runs `fn` with its own user, tags, and breadcrumbs (the integrations do this per request). */\n withScope<T>(fn: () => T): T {\n return runInScope(fn);\n },\n\n /**\n * Waits for events in flight, e.g. before a serverless function returns or\n * a script exits. Resolves `true` when all were sent within `timeoutMs`.\n */\n flush(timeoutMs?: number): Promise<boolean> {\n return flush(timeoutMs);\n },\n\n /** Express: `app.use(Bugwatch.expressRequestHandler())` before your routes. */\n expressRequestHandler,\n\n /** Express: `app.use(Bugwatch.expressErrorHandler())` after your routes; reports 5xx errors. */\n expressErrorHandler,\n\n /** Next.js: `export const onRequestError = Bugwatch.nextOnRequestError;` in `instrumentation.ts`. */\n nextOnRequestError,\n};\n\nexport default Bugwatch;\n","/**\n * The Node SDK's state: options, scopes, event building, and the transport.\n * Every exported function catches its own errors: a bug in Bugwatch must\n * never break the host app.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Breadcrumb } from \"../breadcrumbs\";\nimport {\n DEFAULT_ENDPOINT,\n ENVIRONMENT_RULE,\n MAX_BREADCRUMB_BYTES,\n MAX_MESSAGE,\n MAX_URL,\n MAX_USER_FIELD,\n RELEASE_RULE,\n byteLength,\n describe,\n isValidEnvironment,\n isValidRelease,\n putTag,\n readHttpErrors,\n readOption,\n readString,\n type BugwatchHttpErrorOptions,\n type BugwatchUser,\n type HttpErrorConfig,\n type Mechanism,\n} from \"../shared\";\nimport { relativeStack } from \"./stack\";\nimport { SDK_NAME, SDK_VERSION } from \"./version\";\n\nexport type Level = \"fatal\" | \"error\" | \"warning\" | \"info\" | \"debug\";\n\nexport interface BugwatchRequest {\n method: string;\n url: string;\n /** e.g. `/blog/[slug]` or `/api/orders/:id`. */\n route?: string;\n}\n\nexport interface BugwatchNodeOptions {\n /** Project API key (`bw_` + 32 hex characters). Default: `$BUGWATCH_API_KEY`. */\n apiKey?: string;\n /** Ingest endpoint. Defaults to Bugwatch's hosted API. */\n endpoint?: string;\n /** Your app's version. Default: `$BUGWATCH_RELEASE`. Same rules as the browser SDK. */\n release?: string;\n /** Where the app runs, e.g. `production`. Default: `$BUGWATCH_ENVIRONMENT`. */\n environment?: string;\n /** Sent with every event. Default: the host name; `false` leaves it out. */\n serverName?: string | false;\n /** Folder stripped from stack paths, so they read `dist/server.js`. Default: `process.cwd()`. */\n root?: string;\n /**\n * Reports failed outgoing `fetch` calls as errors. Off by default. `true`\n * reports 5xx responses; an object picks statuses, network errors, and URLs\n * to skip (same as the browser SDK).\n */\n captureHttpErrors?: boolean | BugwatchHttpErrorOptions;\n /**\n * After an uncaught exception: `\"exit\"` (default) sends the event, then\n * exits with code 1 as Node would; `\"keep-running\"` only reports.\n */\n onFatalError?: \"exit\" | \"keep-running\";\n /** Log why events are not sent. Default `false`. */\n debug?: boolean;\n}\n\nexport interface CaptureOptions {\n level?: Level;\n /** The incoming request, when the error is not inside a request scope. */\n request?: BugwatchRequest;\n}\n\n/** Internal: whether the app handled it (false for uncaught exceptions and rejections). */\nexport interface InternalCaptureOptions extends CaptureOptions {\n handled?: boolean;\n /** 0.7.0: how it was caught; `capture_error` when not set (the app called captureError). */\n mechanism?: Mechanism;\n}\n\n/** What one request (or `withScope` call) knows. Never shared between concurrent requests. */\nexport interface Scope {\n user?: BugwatchUser;\n /** 0.6.0: setTag inside the scope; starts as a copy of the outer tags. */\n tags: Record<string, string>;\n breadcrumbs: Breadcrumb[];\n request?: BugwatchRequest;\n userAgent?: string;\n}\n\ninterface Config {\n apiKey: string;\n endpoint: string;\n release?: string;\n environment?: string;\n serverName?: string;\n root?: string;\n httpErrors: HttpErrorConfig | null;\n onFatalError: \"exit\" | \"keep-running\";\n debug: boolean;\n}\n\ninterface IngestPayload {\n key: string;\n handled: boolean;\n mechanism: Mechanism;\n tags?: Record<string, string>;\n message: string;\n type?: string;\n stack?: string;\n level: Level;\n platform: \"node\";\n runtime: { name: string; version: string };\n serverName?: string;\n request?: BugwatchRequest;\n userAgent?: string;\n user?: BugwatchUser;\n release?: string;\n environment?: string;\n breadcrumbs?: Breadcrumb[];\n sdk: { name: string; version: string };\n timestamp: number;\n}\n\nconst MAX_BREADCRUMBS = 50;\nconst SEND_TIMEOUT_MS = 5_000;\nconst PAUSE_AFTER_429_MS = 60_000;\n/** The API rejects bodies over 100 KB (413). */\nconst MAX_BODY_BYTES = 100 * 1024 - 512;\n\n/** Set on Bugwatch's fetch wrapper: the fetch it wraps (shared by every copy of the SDK). */\nexport const ORIGINAL_FETCH = Symbol.for(\"bugwatch.originalFetch\");\n\n/**\n * The real `fetch`, captured before the SDK wraps it, so its own requests are\n * never recorded. If another copy of the SDK (ESM and CJS in one app) wrapped\n * it already, its original is used.\n */\nexport const nativeFetch: typeof fetch | undefined = (() => {\n if (typeof fetch !== \"function\") return undefined;\n const original = (fetch as unknown as Record<symbol, typeof fetch | undefined>)[ORIGINAL_FETCH] ?? fetch;\n return original.bind(globalThis);\n})();\n\nlet config: Config | null = null;\nlet defaultUser: BugwatchUser | undefined;\n/** 0.6.0: tags set outside any scope; every new scope starts with a copy. */\nconst defaultTags: Record<string, string> = {};\nconst storage = new AsyncLocalStorage<Scope>();\nconst pending = new Set<Promise<void>>();\nlet pausedUntil = 0;\n/** Set after a 401 until the next `init`. */\nlet rejectedKey = false;\nconst warned = new Set<string>();\n\nexport function getConfig(): Config | null {\n return config;\n}\n\n/** One warning per distinct message (never thrown, never repeated). */\nexport function warnOnce(message: string): void {\n if (warned.has(message)) return;\n warned.add(message);\n try {\n console.warn(message);\n } catch {\n // Never throw into the host app.\n }\n}\n\nfunction debugLog(message: string): void {\n if (config?.debug) warnOnce(`[Bugwatch] ${message}`);\n}\n\nfunction env(name: string): string | undefined {\n try {\n const value = process.env[name];\n return value && value.trim() ? value.trim() : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction hostName(): string | undefined {\n try {\n // Lazy: `node:os` must not be imported at the top (the Edge runtime has none).\n const getBuiltin = (process as unknown as { getBuiltinModule?: (id: string) => unknown }).getBuiltinModule;\n const os = getBuiltin?.(\"node:os\") as { hostname?: () => string } | undefined;\n const name = os?.hostname?.() ?? env(\"HOSTNAME\");\n return name ? name.slice(0, 200) : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction currentRoot(option: string | undefined): string | undefined {\n if (option !== undefined) return option.trim() || undefined;\n try {\n return process.cwd();\n } catch {\n return undefined;\n }\n}\n\n/** Applies `init` options. Returns false (and keeps the SDK off) without an API key. */\nexport function configure(options: BugwatchNodeOptions = {}): boolean {\n const apiKey = (typeof options.apiKey === \"string\" ? options.apiKey.trim() : \"\") || env(\"BUGWATCH_API_KEY\") || \"\";\n if (!apiKey) {\n config = null;\n return false;\n }\n const endpoint = (typeof options.endpoint === \"string\" ? options.endpoint.trim() : \"\") || DEFAULT_ENDPOINT;\n const warn = (message: string) => warnOnce(message);\n config = {\n apiKey,\n endpoint,\n release: readOption(\"release\", options.release ?? env(\"BUGWATCH_RELEASE\"), isValidRelease, RELEASE_RULE, warn),\n environment: readOption(\n \"environment\",\n options.environment ?? env(\"BUGWATCH_ENVIRONMENT\"),\n isValidEnvironment,\n ENVIRONMENT_RULE,\n warn,\n ),\n serverName:\n options.serverName === false\n ? undefined\n : typeof options.serverName === \"string\" && options.serverName.trim()\n ? options.serverName.trim().slice(0, 200)\n : hostName(),\n root: currentRoot(options.root),\n httpErrors: readHttpErrors(options.captureHttpErrors),\n onFatalError: options.onFatalError === \"keep-running\" ? \"keep-running\" : \"exit\",\n debug: options.debug === true,\n };\n rejectedKey = false;\n pausedUntil = 0;\n return true;\n}\n\nexport function scrubSecret(value: string): string {\n const key = config?.apiKey;\n return key && value.includes(key) ? value.split(key).join(\"[Filtered]\") : value;\n}\n\n/** Requests to the ingest endpoint are Bugwatch's own: never breadcrumbs or HTTP errors. */\nexport function isOwnRequest(url: string): boolean {\n const endpoint = config?.endpoint;\n return Boolean(url && endpoint) && url.split(\"?\")[0] === endpoint!.split(\"?\")[0];\n}\n\n// ---------------------------------------------------------------- scopes\n\nexport function currentScope(): Scope | undefined {\n try {\n return storage.getStore();\n } catch {\n return undefined;\n }\n}\n\n/** Runs `fn` in a new scope that starts with the current user (and request). */\nexport function runInScope<T>(fn: () => T, init: Partial<Scope> = {}): T {\n const parent = currentScope();\n const scope: Scope = {\n user: parent?.user,\n request: parent?.request,\n userAgent: parent?.userAgent,\n ...init,\n tags: { ...(parent?.tags ?? defaultTags) },\n breadcrumbs: [],\n };\n return storage.run(scope, fn);\n}\n\nexport function setUser(next: BugwatchUser | null): void {\n let value: BugwatchUser | undefined;\n if (next && typeof next === \"object\") {\n const id = readString(next.id, MAX_USER_FIELD, (text) => text);\n const email = readString(next.email, MAX_USER_FIELD, (text) => text);\n value = id || email ? { ...(id ? { id } : {}), ...(email ? { email } : {}) } : undefined;\n }\n const scope = currentScope();\n if (scope) scope.user = value;\n else defaultUser = value;\n}\n\n/** setTag / setTags / removeTag: the current scope's tags, or the process default. */\nexport function setTag(key: unknown, value: unknown): void {\n putTag(currentScope()?.tags ?? defaultTags, key, value);\n}\n\nexport function removeTag(key: unknown): void {\n if (typeof key === \"string\") delete (currentScope()?.tags ?? defaultTags)[key];\n}\n\n/** Adds a breadcrumb to the current scope (outside a scope there is none to keep). */\nexport function recordBreadcrumb(crumb: Omit<Breadcrumb, \"timestamp\">): void {\n const scope = currentScope();\n if (!scope) return;\n scope.breadcrumbs.push({ ...crumb, timestamp: Date.now() });\n if (scope.breadcrumbs.length > MAX_BREADCRUMBS) scope.breadcrumbs.shift();\n}\n\n/** Sets the route of the current request once the framework knows it. */\nexport function setRoute(route: string | undefined): void {\n const scope = currentScope();\n if (scope?.request && route) scope.request = { ...scope.request, route };\n}\n\n// ---------------------------------------------------------------- events\n\nfunction cleanRequest(request: BugwatchRequest | undefined): BugwatchRequest | undefined {\n if (!request || typeof request !== \"object\") return undefined;\n const method = readString(request.method, 10, scrubSecret);\n const url = readString(request.url, MAX_URL, scrubSecret);\n if (!method || !url) return undefined;\n const route = readString(request.route, 200, scrubSecret);\n return { method: method.toUpperCase(), url, ...(route ? { route } : {}) };\n}\n\nfunction breadcrumbsForEvent(scope: Scope | undefined): Breadcrumb[] {\n const list = (scope?.breadcrumbs ?? []).map((crumb) => {\n const copy: Breadcrumb = { ...crumb };\n if (copy.message) copy.message = scrubSecret(copy.message);\n if (copy.data?.url) copy.data = { ...copy.data, url: scrubSecret(copy.data.url) };\n return copy;\n });\n while (list.length > 0 && byteLength(JSON.stringify(list)) > MAX_BREADCRUMB_BYTES) list.shift();\n return list;\n}\n\n/** Builds the event for a thrown value, or null when there is nothing to send. */\nexport function buildEvent(error: unknown, options: InternalCaptureOptions = {}): IngestPayload | null {\n const current = config;\n if (!current) return null;\n const description = describe(error, scrubSecret);\n if (!description.message) return null;\n return buildPayload(current, { ...description, message: description.message }, options);\n}\n\n/** Builds an event from a message and type (HTTP errors). */\nexport function buildMessageEvent(message: string, type: string, options: InternalCaptureOptions = {}): IngestPayload | null {\n const current = config;\n const text = readString(message, MAX_MESSAGE, scrubSecret);\n if (!current || !text) return null;\n return buildPayload(current, { message: text, type }, options);\n}\n\nfunction buildPayload(\n current: Config,\n description: { message: string; type?: string; stack?: string },\n options: InternalCaptureOptions,\n): IngestPayload {\n const scope = currentScope();\n const user = scope ? scope.user : defaultUser;\n const request = cleanRequest(options.request) ?? cleanRequest(scope?.request);\n const userAgent = readString(scope?.userAgent, MAX_URL, scrubSecret);\n const payload: IngestPayload = {\n key: current.apiKey,\n message: description.message,\n level: options.level ?? \"error\",\n // Anything not from the process listeners was reported by the app or an integration.\n handled: options.handled ?? true,\n mechanism: options.mechanism ?? \"capture_error\",\n platform: \"node\",\n runtime: { name: \"node\", version: (process.versions?.node ?? \"\").slice(0, 50) || \"unknown\" },\n sdk: { name: SDK_NAME, version: SDK_VERSION },\n timestamp: Date.now(),\n };\n if (description.type) payload.type = description.type;\n if (description.stack) payload.stack = relativeStack(description.stack, current.root);\n if (current.serverName) payload.serverName = current.serverName;\n if (request) payload.request = request;\n if (userAgent) payload.userAgent = userAgent;\n if (user) {\n payload.user = {\n ...(user.id ? { id: scrubSecret(user.id) } : {}),\n ...(user.email ? { email: scrubSecret(user.email) } : {}),\n };\n }\n if (current.release) payload.release = current.release;\n if (current.environment) payload.environment = current.environment;\n const tags = scope ? scope.tags : defaultTags;\n if (Object.keys(tags).length > 0) {\n payload.tags = {};\n for (const [key, value] of Object.entries(tags)) payload.tags[key] = scrubSecret(value);\n }\n const breadcrumbs = breadcrumbsForEvent(scope);\n if (breadcrumbs.length > 0) payload.breadcrumbs = breadcrumbs;\n return payload;\n}\n\n/** JSON under the API's 100 KB limit: drop breadcrumbs, then cut the stack. */\nfunction serialize(payload: IngestPayload): string {\n let body = JSON.stringify(payload);\n if (byteLength(body) <= MAX_BODY_BYTES) return body;\n delete payload.breadcrumbs;\n body = JSON.stringify(payload);\n if (byteLength(body) <= MAX_BODY_BYTES || !payload.stack) return body;\n payload.stack = payload.stack.slice(0, 20_000);\n return JSON.stringify(payload);\n}\n\n// ------------------------------------------------------------- transport\n\n/** Sends in the background; `flush` waits for it. Never throws, never rejects. */\nexport function send(payload: IngestPayload | null): void {\n try {\n const current = config;\n if (!payload || !current) return;\n if (rejectedKey) return debugLog(\"Not sending: the API key was rejected (401). Check apiKey, then call init again\");\n if (Date.now() < pausedUntil) return debugLog(\"Not sending: the monthly event limit was reached (429); paused for a minute\");\n if (!nativeFetch) return debugLog(\"Not sending: this runtime has no global fetch (Node 20+ is required)\");\n\n const task = (async () => {\n try {\n const response = await nativeFetch(current.endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"User-Agent\": `${SDK_NAME}/${SDK_VERSION}` },\n body: serialize(payload),\n signal: AbortSignal.timeout(SEND_TIMEOUT_MS),\n });\n if (response.status === 401) {\n rejectedKey = true;\n warnOnce(\"[Bugwatch] The API key was rejected (401). Events are not sent until init is called with a valid key\");\n } else if (response.status === 429) {\n pausedUntil = Date.now() + PAUSE_AFTER_429_MS;\n debugLog(\"The monthly event limit was reached (429); pausing for a minute\");\n } else if (!response.ok) {\n debugLog(`Bugwatch answered ${response.status}`);\n }\n // Free the connection.\n await response.arrayBuffer().catch(() => undefined);\n } catch (error) {\n debugLog(`Could not reach Bugwatch: ${error instanceof Error ? error.message : String(error)}`);\n }\n })();\n pending.add(task);\n void task.finally(() => pending.delete(task));\n } catch {\n // Never throw into the host app.\n }\n}\n\n/** Waits for events in flight; `true` when all were sent within `timeoutMs`. */\nexport async function flush(timeoutMs = 2_000): Promise<boolean> {\n try {\n if (pending.size === 0) return true;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<false>((resolve) => {\n timer = setTimeout(() => resolve(false), Math.max(0, timeoutMs));\n // Never keep the process alive just for this timer.\n timer.unref?.();\n });\n const done = Promise.allSettled([...pending]).then(() => true as const);\n const result = await Promise.race([done, timeout]);\n if (timer) clearTimeout(timer);\n return result;\n } catch {\n return false;\n }\n}\n\n/** Errors already reported, so one error is sent once (a rethrown rejection, two handlers). */\nconst reported = new WeakSet<object>();\n\nexport function markReported(value: unknown): void {\n if (typeof value === \"object\" && value !== null) reported.add(value);\n}\n\nexport function wasReported(value: unknown): boolean {\n return typeof value === \"object\" && value !== null && reported.has(value);\n}\n\n/** Reports a thrown value (once per error object). */\nexport function captureError(error: unknown, options: InternalCaptureOptions = {}): void {\n try {\n if (wasReported(error)) return;\n markReported(error);\n send(buildEvent(error, options));\n } catch {\n // Never throw into the host app.\n }\n}\n","/**\n * Rules shared by the browser SDK (`bugwatch`) and the Node SDK\n * (`bugwatch/node`): limits, option checks, error description, and\n * `captureHttpErrors`. Pure: no DOM, no Node APIs.\n */\n\nexport const DEFAULT_ENDPOINT = \"https://sentry-like.vercel.app/api/ingest\";\n\nexport const MAX_MESSAGE = 2_000;\nexport const MAX_STACK = 50_000;\nexport const MAX_URL = 2_000;\nexport const MAX_USER_FIELD = 200;\nconst MAX_RELEASE = 200;\n/** Breadcrumbs stay under this many bytes of JSON, so a full stack still fits the API's 100 KB body. */\nexport const MAX_BREADCRUMB_BYTES = 20 * 1024;\n\n// Same rules as the Bugwatch API, which rejects the whole event (400) otherwise.\nconst RELEASE_CHARS = /^[^\\s\\u0000-\\u001f\\u007f-\\u009f]+$/;\nconst ENVIRONMENT_FORMAT = /^[A-Za-z0-9_.-]{1,64}$/;\n\nexport interface BugwatchUser {\n id?: string;\n email?: string;\n}\n\nexport interface BugwatchHttpErrorOptions {\n /** Statuses to report: codes or `[min, max]` ranges. Default `[[500, 599]]`. */\n statuses?: (number | [number, number])[];\n /**\n * Also report requests that got no response (offline, DNS, CORS, timeout).\n * Default `false`. Cancelled requests are never reported.\n */\n networkErrors?: boolean;\n /** Requests not to report: a URL contains the string, or matches the RegExp. */\n ignoreUrls?: (string | RegExp)[];\n}\n\nexport interface ErrorDescription {\n message?: string;\n type?: string;\n stack?: string;\n}\n\n/** Removes secrets (the API key) from a string. */\nexport type Scrub = (value: string) => string;\n\nexport function asRecord(value: unknown): Record<string, unknown> | null {\n return typeof value === \"object\" && value !== null ? (value as Record<string, unknown>) : null;\n}\n\n/** Trimmed, scrubbed, and cut; `undefined` for non-strings and empty strings. */\nexport function readString(value: unknown, limit: number, scrub: Scrub): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const trimmed = value.trim();\n\n if (!trimmed) {\n return undefined;\n }\n\n // Defense in depth: the project key can end up in a URL or an error\n // message. Never send it back in the payload.\n return scrub(trimmed).slice(0, limit);\n}\n\nexport function readStack(value: unknown, scrub: Scrub): string | undefined {\n if (typeof value === \"string\") {\n return readString(value, MAX_STACK, scrub);\n }\n\n if (Array.isArray(value)) {\n const lines = value.filter((line): line is string => typeof line === \"string\");\n return readString(lines.join(\"\\n\"), MAX_STACK, scrub);\n }\n\n return undefined;\n}\n\nexport function nonNegative(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : undefined;\n}\n\nexport function isValidRelease(value: string): boolean {\n return value.length <= MAX_RELEASE && RELEASE_CHARS.test(value) && value !== \".\" && value !== \"..\";\n}\n\nexport function isValidEnvironment(value: string): boolean {\n return ENVIRONMENT_FORMAT.test(value);\n}\n\nexport const RELEASE_RULE = \"1-200 characters, no spaces or control characters, not . or ..\";\nexport const ENVIRONMENT_RULE = \"letters, digits, _ . - only, max 64 characters\";\n\n/**\n * Reads the `release` / `environment` option: trimmed; empty or missing →\n * not set. An invalid value is dropped with one warning (events are still\n * sent, just without it), because the API would reject the whole event.\n */\nexport function readOption(\n name: string,\n value: unknown,\n isValid: (value: string) => boolean,\n rule: string,\n warn: (message: string) => void,\n): string | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n\n const trimmed = typeof value === \"string\" ? value.trim() : undefined;\n\n if (trimmed === \"\") {\n return undefined;\n }\n\n if (trimmed !== undefined && isValid(trimmed)) {\n return trimmed;\n }\n\n warn(`[Bugwatch] Ignoring invalid ${name} option: ${rule}`);\n return undefined;\n}\n\n/** Extracts the useful parts of an Error, or turns any thrown value into a message. */\nexport function describe(value: unknown, scrub: Scrub): ErrorDescription {\n const record = asRecord(value);\n const message = record ? readString(record.message, MAX_MESSAGE, scrub) : undefined;\n\n if (message) {\n return {\n message,\n type: record ? readString(record.name, MAX_USER_FIELD, scrub) : undefined,\n stack: record ? readStack(record.stack, scrub) : undefined,\n };\n }\n\n if (typeof value === \"string\") {\n return { message: readString(value, MAX_MESSAGE, scrub) };\n }\n\n if (value !== undefined && value !== null) {\n try {\n return { message: readString(String(value), MAX_MESSAGE, scrub) };\n } catch {\n // An object with a throwing toString/@@toPrimitive: nothing safe to send.\n }\n }\n\n return {};\n}\n\n// ------------------------------------------------------------------ tags\n\n/** Same rules as the Bugwatch API (Step 63): bad tags are dropped there too. */\nexport const TAG_KEY = /^[a-z0-9_.-]{1,32}$/;\nexport const MAX_TAG_VALUE = 200;\nexport const MAX_TAGS = 20;\n/** Set by Bugwatch itself; a custom tag with one of these keys is dropped. */\nconst AUTOMATIC_TAG_KEYS = new Set([\n \"browser\",\n \"os\",\n \"url\",\n \"route\",\n \"server\",\n \"platform\",\n \"release\",\n \"environment\",\n \"level\",\n \"handled\",\n]);\n\nexport type TagValue = string | number | boolean;\n\n/**\n * 0.7.0: how the error was caught, sent as `mechanism` (API Step 78). Browser:\n * `onerror`, `onunhandledrejection`; Node: `uncaught_exception`,\n * `unhandled_rejection`, `express`, `nextjs`; both: `capture_error`, `http`.\n */\nexport type Mechanism =\n | \"onerror\"\n | \"onunhandledrejection\"\n | \"uncaught_exception\"\n | \"unhandled_rejection\"\n | \"capture_error\"\n | \"http\"\n | \"express\"\n | \"nextjs\";\n\n/** The tag's value as sent, or undefined when the tag would be dropped (bad key, automatic key, empty or long value). */\nexport function tagValue(key: unknown, value: unknown): string | undefined {\n if (typeof key !== \"string\" || !TAG_KEY.test(key) || AUTOMATIC_TAG_KEYS.has(key)) return undefined;\n if (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\") return undefined;\n const text = String(value).trim();\n return text && text.length <= MAX_TAG_VALUE ? text : undefined;\n}\n\n/**\n * Applies `setTag(key, value)` to a tag map: a valid tag is set (replacing\n * the old value), at most 20 different keys; anything else changes nothing.\n * Returns whether it was set.\n */\nexport function putTag(tags: Record<string, string>, key: unknown, value: unknown): boolean {\n const text = tagValue(key, value);\n if (text === undefined) return false;\n const name = key as string;\n const known = Object.prototype.hasOwnProperty.call(tags, name);\n if (!known && Object.keys(tags).length >= MAX_TAGS) return false;\n tags[name] = text;\n return true;\n}\n\nexport function byteLength(value: string): number {\n try {\n return new TextEncoder().encode(value).length;\n } catch {\n return value.length;\n }\n}\n\n// ------------------------------------------------------- captureHttpErrors\n\nexport interface HttpErrorConfig {\n statuses: [number, number][];\n networkErrors: boolean;\n ignoreUrls: (string | RegExp)[];\n}\n\n/** Each failing request (method, URL, status) is reported at most once a minute. */\nconst HTTP_ERROR_INTERVAL_MS = 60_000;\nconst MAX_HTTP_ERROR_KEYS = 100;\n\n/** Reads the `captureHttpErrors` option; off → null. Bad entries are skipped. */\nexport function readHttpErrors(option: unknown): HttpErrorConfig | null {\n if (!option) {\n return null;\n }\n\n const record = asRecord(option) ?? {};\n let statuses: [number, number][] = [[500, 599]];\n\n if (Array.isArray(record.statuses)) {\n statuses = [];\n for (const entry of record.statuses as unknown[]) {\n if (typeof entry === \"number\") {\n statuses.push([entry, entry]);\n } else if (Array.isArray(entry) && typeof entry[0] === \"number\" && typeof entry[1] === \"number\") {\n statuses.push([entry[0], entry[1]]);\n }\n }\n }\n\n return {\n statuses,\n networkErrors: record.networkErrors === true,\n ignoreUrls: Array.isArray(record.ignoreUrls)\n ? (record.ignoreUrls as unknown[]).filter(\n (entry): entry is string | RegExp => typeof entry === \"string\" || entry instanceof RegExp,\n )\n : [],\n };\n}\n\nfunction isIgnoredUrl(url: string, patterns: (string | RegExp)[]): boolean {\n return patterns.some((pattern) => {\n if (typeof pattern === \"string\") {\n return url.includes(pattern);\n }\n pattern.lastIndex = 0;\n return pattern.test(url);\n });\n}\n\n/** A path segment that is an id: a number, a UUID, or 8+ hex characters with a digit (ObjectIds, hashes). */\nconst ID_SEGMENT = /^(?:\\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|(?=[a-f]*\\d)[0-9a-f]{8,})$/i;\n\n/**\n * The URL for an HTTP error message: no query string or hash (they often\n * carry tokens or personal data), and id segments as `:id`, so one endpoint\n * is one issue (`/api/projects/6740a1b2…` → `/api/projects/:id`). The host of\n * an absolute URL is kept as is.\n */\nexport function urlForMessage(url: string): string {\n const parts = (url.split(/[?#]/)[0] || url).split(\"/\");\n const first = /^[a-z][a-z0-9+.-]*:$/i.test(parts[0] ?? \"\") && parts[1] === \"\" ? 3 : 0;\n return parts.map((part, index) => (index >= first && ID_SEGMENT.test(part) ? \":id\" : part)).join(\"/\");\n}\n\n/** No response: `network` (offline, DNS, CORS, timeout) or `abort` (cancelled on purpose). */\nexport type HttpFailure = \"network\" | \"abort\";\n\n/**\n * `captureHttpErrors`: the event for a finished request, or null when it is\n * not reported (not a failure, ignored, cancelled, or the same one within a\n * minute; `sentAt` remembers the last 100). E.g. `HTTP 500: GET /api/orders/:id`\n * (type `HttpError`) or `Network error: GET /api/orders` (type `NetworkError`).\n */\nexport function httpErrorEvent(\n config: HttpErrorConfig | null,\n sentAt: Map<string, number>,\n method: string,\n url: string,\n status: number,\n failure?: HttpFailure,\n): { message: string; type: string } | null {\n if (!config || isIgnoredUrl(url, config.ignoreUrls)) {\n return null;\n }\n\n const target = `${method.toUpperCase()} ${urlForMessage(url)}`;\n let message: string;\n let type: string;\n\n if (failure) {\n if (failure === \"abort\" || !config.networkErrors) {\n return null;\n }\n message = `Network error: ${target}`;\n type = \"NetworkError\";\n } else if (config.statuses.some(([min, max]) => status >= min && status <= max)) {\n message = `HTTP ${status}: ${target}`;\n type = \"HttpError\";\n } else {\n return null;\n }\n\n const now = Date.now();\n const last = sentAt.get(message);\n if (last !== undefined && now - last < HTTP_ERROR_INTERVAL_MS) {\n return null;\n }\n sentAt.delete(message);\n sentAt.set(message, now);\n if (sentAt.size > MAX_HTTP_ERROR_KEYS) {\n // Oldest first (insertion order).\n sentAt.delete(sentAt.keys().next().value as string);\n }\n\n return { message, type };\n}\n","/**\n * Makes stack paths relative to the app's root folder:\n * `/opt/render/project/src/dist/server.js:10:5` → `dist/server.js:10:5`, and\n * the same for `file://` URLs from ES modules. Grouping then matches across\n * hosts and deploy folders, and no home folders or usernames are sent.\n */\nexport function relativeStack(stack: string, root: string | undefined): string {\n if (!root) return stack;\n const trimmed = root.replace(/[\\\\/]+$/, \"\");\n if (!trimmed) return stack;\n\n const forward = trimmed.replace(/\\\\/g, \"/\");\n const fileUrl = `file://${forward.startsWith(\"/\") ? \"\" : \"/\"}${forward}`;\n // Longest first, so the file URL is removed as a whole.\n const prefixes = [...new Set([`${fileUrl}/`, `${encodeURI(fileUrl)}/`, `${trimmed}/`, `${trimmed}\\\\`, `${forward}/`])].sort(\n (a, b) => b.length - a.length,\n );\n\n let result = stack;\n for (const prefix of prefixes) {\n if (result.includes(prefix)) result = result.split(prefix).join(\"\");\n }\n return result;\n}\n","export const SDK_NAME = \"bugwatch-node\";\n/** Keep in sync with package.json (a test checks it). */\nexport const SDK_VERSION = \"0.7.0\";\n","/**\n * Outgoing `fetch` (Step 56): inside a request scope each call is an `http`\n * breadcrumb, and `captureHttpErrors` reports failed calls. The wrapper keeps\n * the app's behavior: same arguments, `this`, return value, and errors.\n * Bugwatch's own requests use the unwrapped fetch and are never recorded.\n */\n\nimport { httpErrorEvent, type HttpFailure } from \"../shared\";\nimport { ORIGINAL_FETCH, buildMessageEvent, getConfig, isOwnRequest, recordBreadcrumb, send } from \"./client\";\n\nconst MAX_CRUMB_URL = 500;\nconst httpErrorSentAt = new Map<string, number>();\nlet patched = false;\n\nfunction target(input: unknown, init: unknown): { method: string; url: string } {\n let method = \"GET\";\n let url = \"\";\n try {\n if (typeof input === \"string\") url = input;\n else if (input instanceof URL) url = input.href;\n else if (input && typeof (input as { url?: unknown }).url === \"string\") url = (input as { url: string }).url;\n const requestMethod = (input as { method?: unknown } | null)?.method;\n if (typeof requestMethod === \"string\") method = requestMethod;\n const initMethod = (init as { method?: unknown } | undefined)?.method;\n if (typeof initMethod === \"string\") method = initMethod;\n } catch {\n // Unusual input: record what we have.\n }\n return { method: method.toUpperCase(), url };\n}\n\nfunction failureOf(error: unknown): HttpFailure {\n // AbortController → cancelled on purpose; a timeout (TimeoutError) or \"fetch failed\" → no response.\n return (error as { name?: unknown } | null)?.name === \"AbortError\" ? \"abort\" : \"network\";\n}\n\nfunction onResult(method: string, url: string, status: number, startedAt: number, failure?: HttpFailure): void {\n try {\n if (!url || isOwnRequest(url)) return;\n recordBreadcrumb({\n type: \"http\",\n level: failure || status >= 500 ? \"error\" : status >= 400 ? \"warning\" : \"info\",\n data: {\n method: method.slice(0, 10),\n url: url.slice(0, MAX_CRUMB_URL),\n status,\n durationMs: Math.max(0, Date.now() - startedAt),\n },\n });\n const event = httpErrorEvent(getConfig()?.httpErrors ?? null, httpErrorSentAt, method, url, status, failure);\n if (event) send(buildMessageEvent(event.message, event.type, { mechanism: \"http\" }));\n } catch {\n // Never throw into the host app.\n }\n}\n\n/** Wraps the global fetch once. */\nexport function patchFetch(): void {\n if (patched || typeof globalThis.fetch !== \"function\") return;\n const original = globalThis.fetch;\n\n const wrapped = function (this: unknown, ...args: Parameters<typeof fetch>) {\n const { method, url } = target(args[0], args[1]);\n const startedAt = Date.now();\n const result = original.apply(this, args);\n try {\n // Recording hangs off a separate branch that never rejects; the app gets `result` itself.\n result.then(\n (response) => onResult(method, url, response.status, startedAt),\n (error: unknown) => onResult(method, url, 0, startedAt, failureOf(error)),\n );\n } catch {\n // A non-promise result from a shimmed fetch: nothing to record.\n }\n return result;\n } as typeof fetch;\n\n // Keep markers other tools put on fetch (e.g. Next.js's `__nextPatched`), so they don't patch twice.\n for (const key of Reflect.ownKeys(original)) {\n if (key === \"length\" || key === \"name\" || key === \"prototype\") continue;\n try {\n const descriptor = Object.getOwnPropertyDescriptor(original, key);\n if (descriptor) Object.defineProperty(wrapped, key, descriptor);\n } catch {\n // Skip properties that cannot be copied.\n }\n }\n\n (wrapped as unknown as Record<symbol, unknown>)[ORIGINAL_FETCH] =\n (original as unknown as Record<symbol, unknown>)[ORIGINAL_FETCH] ?? original;\n globalThis.fetch = wrapped;\n patched = true;\n}\n","/**\n * Framework integrations (Step 56): Express request / error handlers and\n * Next.js `onRequestError`. No dependency on either framework: only the\n * shapes they pass in are used.\n */\n\nimport {\n captureError,\n currentScope,\n flush,\n getConfig,\n runInScope,\n setRoute,\n wasReported,\n type BugwatchRequest,\n} from \"./client\";\n\nconst NEXT_FLUSH_MS = 2_000;\n\ntype Headers = Record<string, string | string[] | undefined>;\n\nfunction header(headers: Headers | undefined, name: string): string | undefined {\n const value = headers?.[name];\n return Array.isArray(value) ? value[0] : value;\n}\n\n// ---------------------------------------------------------------- Express\n\n/** The parts of an Express request the SDK reads. */\ninterface ExpressRequest {\n method?: string;\n originalUrl?: string;\n url?: string;\n protocol?: string;\n baseUrl?: string;\n headers?: Headers;\n route?: { path?: unknown };\n}\n\ntype Next = (error?: unknown) => void;\n\nfunction expressUrl(req: ExpressRequest): string {\n const path = req.originalUrl || req.url || \"/\";\n const host = header(req.headers, \"host\");\n if (!host) return path;\n // `req.protocol` honors Express's \"trust proxy\" setting.\n const protocol = req.protocol || \"http\";\n return `${protocol}://${host}${path}`;\n}\n\n/** `/api/orders/:id` once Express has matched a route. */\nfunction expressRoute(req: ExpressRequest): string | undefined {\n const path = req.route?.path;\n return typeof path === \"string\" ? `${req.baseUrl ?? \"\"}${path}` || undefined : undefined;\n}\n\nfunction expressRequest(req: ExpressRequest): BugwatchRequest {\n const route = expressRoute(req);\n return { method: req.method || \"GET\", url: expressUrl(req), ...(route ? { route } : {}) };\n}\n\n/**\n * `app.use(Bugwatch.expressRequestHandler())` first: each request gets its own\n * scope (user, breadcrumbs, the request, and its User-Agent).\n */\nexport function expressRequestHandler() {\n return function bugwatchRequestHandler(req: ExpressRequest, _res: unknown, next: Next): void {\n let request: BugwatchRequest | undefined;\n let userAgent: string | undefined;\n try {\n request = expressRequest(req);\n userAgent = header(req.headers, \"user-agent\");\n } catch {\n // Run the request without Bugwatch context.\n }\n runInScope(() => next(), { request, userAgent });\n };\n}\n\n/** The status an Express error asks for (`status` / `statusCode`), if any. */\nfunction errorStatus(error: unknown): number | undefined {\n const record = error as { status?: unknown; statusCode?: unknown } | null;\n const status = record?.status ?? record?.statusCode;\n return typeof status === \"number\" ? status : undefined;\n}\n\n/**\n * `app.use(Bugwatch.expressErrorHandler())` after the routes, before your own\n * error handler: reports errors without a status or with a 5xx status, then\n * passes the error on (`next(err)`). 4xx errors are not reported.\n */\nexport function expressErrorHandler() {\n return function bugwatchErrorHandler(error: unknown, req: ExpressRequest, _res: unknown, next: Next): void {\n try {\n const status = errorStatus(error);\n if (status === undefined || status >= 500) {\n const request = expressRequest(req);\n if (currentScope()) {\n // Inside the request's scope: keep its user and breadcrumbs.\n setRoute(request.route);\n captureError(error, { request, mechanism: \"express\" });\n } else {\n // No request handler installed: report with what the request tells us.\n runInScope(() => captureError(error, { request, mechanism: \"express\" }), {\n request,\n userAgent: header(req.headers, \"user-agent\"),\n });\n }\n }\n } catch {\n // Never throw into the host app.\n }\n next(error);\n };\n}\n\n// ---------------------------------------------------------------- Next.js\n\n/** What Next.js passes to `onRequestError` (Next.js 15+). */\ninterface NextRequestInfo {\n path?: string;\n method?: string;\n headers?: Headers;\n}\n\ninterface NextErrorContext {\n routePath?: string;\n routeType?: string;\n routerKind?: string;\n}\n\n/** Errors Next.js throws on purpose (`redirect()`, `notFound()`, dynamic rendering bailouts). */\nconst NEXT_CONTROL_FLOW = [\n \"NEXT_REDIRECT\",\n \"NEXT_NOT_FOUND\",\n \"NEXT_HTTP_ERROR_FALLBACK\",\n \"DYNAMIC_SERVER_USAGE\",\n \"BAILOUT_TO_CLIENT_SIDE_RENDERING\",\n \"NEXT_PRERENDER_INTERRUPTED\",\n \"HANGING_PROMISE_REJECTION\",\n];\n\nfunction isNextControlFlow(error: unknown): boolean {\n const record = error as { digest?: unknown; message?: unknown } | null;\n const digest = typeof record?.digest === \"string\" ? record.digest : \"\";\n const message = typeof record?.message === \"string\" ? record.message : \"\";\n return NEXT_CONTROL_FLOW.some((prefix) => digest.startsWith(prefix) || message === prefix);\n}\n\nfunction nextUrl(request: NextRequestInfo): string {\n const path = request.path || \"/\";\n const host = header(request.headers, \"x-forwarded-host\") || header(request.headers, \"host\");\n if (!host) return path;\n const protocol = (header(request.headers, \"x-forwarded-proto\") || \"https\").split(\",\")[0]!.trim();\n return `${protocol}://${host}${path}`;\n}\n\n/**\n * `export const onRequestError = Bugwatch.nextOnRequestError;` in\n * `instrumentation.ts`: reports errors from server components, route\n * handlers, server actions, and middleware (Node runtime), then waits for the\n * send (2 s at most) so a serverless function is not frozen first.\n */\nexport async function nextOnRequestError(\n error: unknown,\n request: NextRequestInfo = {},\n context: NextErrorContext = {},\n): Promise<void> {\n try {\n if (!getConfig() || isNextControlFlow(error) || wasReported(error)) return;\n const info: BugwatchRequest = {\n method: request.method || \"GET\",\n url: nextUrl(request),\n ...(context.routePath ? { route: context.routePath } : {}),\n };\n runInScope(() => captureError(error, { request: info, mechanism: \"nextjs\" }), {\n request: info,\n userAgent: header(request.headers, \"user-agent\"),\n });\n await flush(NEXT_FLUSH_MS);\n } catch {\n // Never throw into Next.js.\n }\n}\n","/**\n * Uncaught exceptions and unhandled rejections.\n *\n * Adding a listener changes what Node does: without one, an uncaught\n * exception (and, by default, an unhandled rejection) prints the error and\n * exits with code 1. The SDK keeps that behavior: when its listener is the\n * only one, it sends the event, waits for it (2 s at most), prints the error,\n * and exits with code 1. When the app has its own listeners, it only reports.\n */\n\nimport { buildEvent, flush, getConfig, markReported, send, wasReported } from \"./client\";\n\nconst FATAL_FLUSH_MS = 2_000;\n\nlet installed = false;\nlet exiting = false;\n\n/** `--unhandled-rejections=<mode>` from the command line or NODE_OPTIONS; Node's default is `throw`. */\nfunction rejectionMode(): string {\n try {\n const args = [...process.execArgv, ...(process.env.NODE_OPTIONS ?? \"\").split(/\\s+/)];\n let mode = \"throw\";\n for (const arg of args) {\n const match = /^--unhandled-rejections=(.+)$/.exec(arg);\n if (match) mode = match[1]!;\n }\n return mode;\n } catch {\n return \"throw\";\n }\n}\n\nfunction printFatal(error: unknown): void {\n try {\n const text =\n error instanceof Error ? (error.stack ?? `${error.name}: ${error.message}`) : `Uncaught ${String(error)}`;\n process.stderr.write(`${text}\\n\\nNode.js ${process.version}\\n`);\n } catch {\n // Nothing else to do: the process is exiting.\n }\n}\n\nfunction exitAfterFlush(error: unknown): void {\n if (exiting) return;\n exiting = true;\n void flush(FATAL_FLUSH_MS).then(() => {\n printFatal(error);\n process.exit(1);\n });\n}\n\nfunction onUncaughtException(error: unknown): void {\n try {\n if (!wasReported(error)) {\n markReported(error);\n send(buildEvent(error, { level: \"fatal\", handled: false, mechanism: \"uncaught_exception\" }));\n }\n const onlyOurs = process.listenerCount(\"uncaughtException\") === 1;\n if (onlyOurs && (getConfig()?.onFatalError ?? \"exit\") === \"exit\") exitAfterFlush(error);\n } catch {\n // Never throw from here: it would end the process without the event.\n }\n}\n\n/** Node's own wrapper for a rejection whose reason is not an Error. */\nfunction rejectionError(reason: unknown): Error {\n let text: string;\n try {\n text = String(reason);\n } catch {\n text = \"[unprintable]\";\n }\n const error = new Error(\n \"This error originated either by throwing inside of an async function without a catch block, \" +\n `or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason \"${text}\".`,\n );\n (error as Error & { code?: string }).code = \"ERR_UNHANDLED_REJECTION\";\n return error;\n}\n\nfunction onUnhandledRejection(reason: unknown): void {\n try {\n const mode = rejectionMode();\n if (!wasReported(reason)) {\n markReported(reason);\n send(buildEvent(reason, { level: \"error\", handled: false, mechanism: \"unhandled_rejection\" }));\n }\n if (mode === \"warn-with-error-code\") process.exitCode = 1;\n\n // Under the default mode Node would raise it as an uncaught exception;\n // our listener stopped that, so raise it ourselves (reported only once).\n const onlyOurs = process.listenerCount(\"unhandledRejection\") === 1;\n if (mode === \"throw\" && onlyOurs) {\n const error = reason instanceof Error ? reason : rejectionError(reason);\n markReported(error);\n process.nextTick(() => {\n throw error;\n });\n }\n } catch {\n // Never throw into the host app.\n }\n}\n\n/** Adds the process listeners once. */\nexport function installProcessHandlers(): void {\n if (installed) return;\n installed = true;\n process.on(\"uncaughtException\", onUncaughtException);\n process.on(\"unhandledRejection\", onUnhandledRejection);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMA,8BAAkC;;;ACA3B,IAAM,mBAAmB;AAEzB,IAAM,cAAc;AACpB,IAAM,YAAY;AAClB,IAAM,UAAU;AAChB,IAAM,iBAAiB;AAC9B,IAAM,cAAc;AAEb,IAAM,uBAAuB,KAAK;AAGzC,IAAM,gBAAgB;AACtB,IAAM,qBAAqB;AA4BpB,SAAS,SAAS,OAAgD;AACvE,SAAO,OAAO,UAAU,YAAY,UAAU,OAAQ,QAAoC;AAC5F;AAGO,SAAS,WAAW,OAAgB,OAAe,OAAkC;AAC1F,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,MAAM,KAAK;AAE3B,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAIA,SAAO,MAAM,OAAO,EAAE,MAAM,GAAG,KAAK;AACtC;AAEO,SAAS,UAAU,OAAgB,OAAkC;AAC1E,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO,WAAW,OAAO,WAAW,KAAK;AAAA,EAC3C;AAEA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,UAAM,QAA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F,UAAI,CAAC,mBAAmB,EAAG;AAC3B,UAAI,CAAC,UAAU,OAAO,EAAG;AACzB,6BAAuB;AACvB,iBAAW;AAAA,IACb,QAAQ;AAAA,IAER;AAAA,EACF;AAAA;AAAA,EAGA,aAAa,OAAgB,SAAgC;AAC3D,iBAAa,OAAO,OAAO;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAQ,MAAoD;AAC1D,QAAI;AACF,cAAQ,IAAI;AAAA,IACd,QAAQ;AAAA,IAER;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,KAAa,OAAuB;AACzC,QAAI;AACF,aAAO,KAAK,KAAK;AAAA,IACnB,QAAQ;AAAA,IAER;AAAA,EACF;AAAA;AAAA,EAGA,QAAQ,QAAwC;AAC9C,QAAI;AACF,UAAI,CAAC,UAAU,OAAO,WAAW,SAAU;AAC3C,iBAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,EAAG,QAAO,KAAK,KAAK;AAAA,IACtE,QAAQ;AAAA,IAER;AAAA,EACF;AAAA;AAAA,EAGA,UAAU,KAAmB;AAC3B,QAAI;AACF,gBAAU,GAAG;AAAA,IACf,QAAQ;AAAA,IAER;AAAA,EACF;AAAA;AAAA,EAGA,UAAa,IAAgB;AAC3B,WAAO,WAAW,EAAE;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,WAAsC;AAC1C,WAAO,MAAM,SAAS;AAAA,EACxB;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AACF;AAEA,IAAO,eAAQ;","names":["config","target"]}
1
+ {"version":3,"sources":["../src/node/index.ts","../src/node/client.ts","../src/shared.ts","../src/node/stack.ts","../src/node/version.ts","../src/node/fetch.ts","../src/node/frameworks.ts","../src/node/process.ts"],"sourcesContent":["/**\n * Bugwatch Node SDK: `import { Bugwatch } from \"bugwatch/node\"`.\n *\n * Catches uncaught exceptions and unhandled rejections (keeping Node's exit\n * behavior), Express and Next.js request errors, and (with\n * `captureHttpErrors`) failed outgoing `fetch` calls; reports errors you pass\n * to `captureError`; keeps per-request context (user, breadcrumbs, request)\n * apart with AsyncLocalStorage. Every\n * public function catches its own errors and never throws into the app.\n */\n\nimport {\n addFeatureFlag,\n captureError,\n configure,\n flush,\n removeTag,\n runInScope,\n setTag,\n setUser,\n type BugwatchNodeOptions,\n type BugwatchRequest,\n type CaptureOptions,\n type Level,\n} from \"./client\";\nimport { patchFetch } from \"./fetch\";\nimport { expressErrorHandler, expressRequestHandler, nextOnRequestError } from \"./frameworks\";\nimport { installProcessHandlers } from \"./process\";\n\nexport type { BugwatchHttpErrorOptions, BugwatchUser, TagValue } from \"../shared\";\nimport type { TagValue } from \"../shared\";\nexport type { BugwatchNodeOptions, BugwatchRequest, CaptureOptions, Level } from \"./client\";\n\n/** Next.js loads instrumentation in the Edge runtime too; there the SDK does nothing (for now). */\nfunction isSupportedRuntime(): boolean {\n try {\n if (typeof process === \"undefined\" || typeof process.on !== \"function\") return false;\n if (process.env.NEXT_RUNTIME === \"edge\") return false;\n return typeof (globalThis as { EdgeRuntime?: unknown }).EdgeRuntime === \"undefined\";\n } catch {\n return false;\n }\n}\n\nexport const Bugwatch = {\n /**\n * Starts reporting. The API key comes from `apiKey` or `$BUGWATCH_API_KEY`;\n * without one, nothing is sent. Safe to call again: a later call replaces\n * the options (process listeners are added once).\n */\n init(options: BugwatchNodeOptions = {}): void {\n try {\n if (!isSupportedRuntime()) return;\n if (!configure(options)) return;\n installProcessHandlers();\n patchFetch();\n } catch {\n // Never throw into the host app.\n }\n },\n\n /** Reports an error, e.g. one you caught. Optional `level` and `request`. */\n captureError(error: unknown, options?: CaptureOptions): void {\n captureError(error, options);\n },\n\n /**\n * Sets the user for later events. Inside a request (or `withScope`) only\n * that request gets it; outside, it is the default. `null` clears it.\n */\n setUser(user: { id?: string; email?: string } | null): void {\n try {\n setUser(user);\n } catch {\n // Never throw into the host app.\n }\n },\n\n /**\n * Adds a tag to later events, e.g. `setTag(\"plan\", \"pro\")`. Inside a\n * request (or `withScope`) only that request gets it; outside, every event.\n * Keys: 1–32 of a-z, 0-9, `_ . -`; values up to 200 characters; at most 20.\n * A tag that breaks a rule is ignored.\n */\n setTag(key: string, value: TagValue): void {\n try {\n setTag(key, value);\n } catch {\n // Never throw into the host app.\n }\n },\n\n /** Several tags at once: `setTags({ plan: \"pro\", region: \"eu\" })`. */\n setTags(values: Record<string, TagValue>): void {\n try {\n if (!values || typeof values !== \"object\") return;\n for (const [key, value] of Object.entries(values)) setTag(key, value);\n } catch {\n // Never throw into the host app.\n }\n },\n\n /**\n * Records a feature flag the app just evaluated, e.g.\n * `addFeatureFlag(\"new-checkout\", true)`. Inside a request (or `withScope`)\n * only that request's events carry it; outside, every event. The last 100,\n * one per flag (the latest result). Never throws.\n */\n addFeatureFlag(name: string, result: boolean | string): void {\n try {\n addFeatureFlag(name, result);\n } catch {\n // Never throw into the host app.\n }\n },\n\n /** Stops sending a tag (in the current request, or everywhere outside one). */\n removeTag(key: string): void {\n try {\n removeTag(key);\n } catch {\n // Never throw into the host app.\n }\n },\n\n /** Runs `fn` with its own user, tags, and breadcrumbs (the integrations do this per request). */\n withScope<T>(fn: () => T): T {\n return runInScope(fn);\n },\n\n /**\n * Waits for events in flight, e.g. before a serverless function returns or\n * a script exits. Resolves `true` when all were sent within `timeoutMs`.\n */\n flush(timeoutMs?: number): Promise<boolean> {\n return flush(timeoutMs);\n },\n\n /** Express: `app.use(Bugwatch.expressRequestHandler())` before your routes. */\n expressRequestHandler,\n\n /** Express: `app.use(Bugwatch.expressErrorHandler())` after your routes; reports 5xx errors. */\n expressErrorHandler,\n\n /** Next.js: `export const onRequestError = Bugwatch.nextOnRequestError;` in `instrumentation.ts`. */\n nextOnRequestError,\n};\n\nexport default Bugwatch;\n","/**\n * The Node SDK's state: options, scopes, event building, and the transport.\n * Every exported function catches its own errors: a bug in Bugwatch must\n * never break the host app.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Breadcrumb } from \"../breadcrumbs\";\nimport {\n DEFAULT_ENDPOINT,\n ENVIRONMENT_RULE,\n MAX_BREADCRUMB_BYTES,\n MAX_MESSAGE,\n MAX_URL,\n MAX_USER_FIELD,\n RELEASE_RULE,\n byteLength,\n describe,\n isValidEnvironment,\n isValidRelease,\n putTag,\n putFlag,\n flagList,\n frameworkVersion,\n readHttpErrors,\n readOption,\n readString,\n type BugwatchHttpErrorOptions,\n type BugwatchUser,\n type EventContexts,\n type HttpErrorConfig,\n type Mechanism,\n type FeatureFlag,\n type FlagResult,\n} from \"../shared\";\nimport { relativeStack } from \"./stack\";\nimport { SDK_NAME, SDK_VERSION } from \"./version\";\n\nexport type Level = \"fatal\" | \"error\" | \"warning\" | \"info\" | \"debug\";\n\nexport interface BugwatchRequest {\n method: string;\n url: string;\n /** e.g. `/blog/[slug]` or `/api/orders/:id`. */\n route?: string;\n}\n\nexport interface BugwatchNodeOptions {\n /** Project API key (`bw_` + 32 hex characters). Default: `$BUGWATCH_API_KEY`. */\n apiKey?: string;\n /** Ingest endpoint. Defaults to Bugwatch's hosted API. */\n endpoint?: string;\n /** Your app's version. Default: `$BUGWATCH_RELEASE`. Same rules as the browser SDK. */\n release?: string;\n /** Where the app runs, e.g. `production`. Default: `$BUGWATCH_ENVIRONMENT`. */\n environment?: string;\n /** Sent with every event. Default: the host name; `false` leaves it out. */\n serverName?: string | false;\n /** Folder stripped from stack paths, so they read `dist/server.js`. Default: `process.cwd()`. */\n root?: string;\n /**\n * Reports failed outgoing `fetch` calls as errors. Off by default. `true`\n * reports 5xx responses; an object picks statuses, network errors, and URLs\n * to skip (same as the browser SDK).\n */\n captureHttpErrors?: boolean | BugwatchHttpErrorOptions;\n /**\n * After an uncaught exception: `\"exit\"` (default) sends the event, then\n * exits with code 1 as Node would; `\"keep-running\"` only reports.\n */\n onFatalError?: \"exit\" | \"keep-running\";\n /** Log why events are not sent. Default `false`. */\n debug?: boolean;\n}\n\nexport interface CaptureOptions {\n level?: Level;\n /** The incoming request, when the error is not inside a request scope. */\n request?: BugwatchRequest;\n}\n\n/** Internal: whether the app handled it (false for uncaught exceptions and rejections). */\nexport interface InternalCaptureOptions extends CaptureOptions {\n handled?: boolean;\n /** 0.7.0: how it was caught; `capture_error` when not set (the app called captureError). */\n mechanism?: Mechanism;\n}\n\n/** What one request (or `withScope` call) knows. Never shared between concurrent requests. */\nexport interface Scope {\n user?: BugwatchUser;\n /** 0.6.0: setTag inside the scope; starts as a copy of the outer tags. */\n tags: Record<string, string>;\n /** 0.9.0: addFeatureFlag inside the scope; starts as a copy of the outer flags. */\n flags: Map<string, FlagResult>;\n breadcrumbs: Breadcrumb[];\n request?: BugwatchRequest;\n userAgent?: string;\n}\n\ninterface Config {\n apiKey: string;\n endpoint: string;\n release?: string;\n environment?: string;\n serverName?: string;\n root?: string;\n httpErrors: HttpErrorConfig | null;\n onFatalError: \"exit\" | \"keep-running\";\n debug: boolean;\n /** 0.8.0: framework versions installed in the app, read once at init. */\n frameworks: { name: string; version: string }[];\n}\n\ninterface IngestPayload {\n key: string;\n handled: boolean;\n mechanism: Mechanism;\n contexts?: EventContexts;\n tags?: Record<string, string>;\n flags?: FeatureFlag[];\n message: string;\n type?: string;\n stack?: string;\n level: Level;\n platform: \"node\";\n runtime: { name: string; version: string };\n serverName?: string;\n request?: BugwatchRequest;\n userAgent?: string;\n user?: BugwatchUser;\n release?: string;\n environment?: string;\n breadcrumbs?: Breadcrumb[];\n sdk: { name: string; version: string };\n timestamp: number;\n}\n\nconst MAX_BREADCRUMBS = 50;\nconst SEND_TIMEOUT_MS = 5_000;\nconst PAUSE_AFTER_429_MS = 60_000;\n/** The API rejects bodies over 100 KB (413). */\nconst MAX_BODY_BYTES = 100 * 1024 - 512;\n\n/** Set on Bugwatch's fetch wrapper: the fetch it wraps (shared by every copy of the SDK). */\nexport const ORIGINAL_FETCH = Symbol.for(\"bugwatch.originalFetch\");\n\n/**\n * The real `fetch`, captured before the SDK wraps it, so its own requests are\n * never recorded. If another copy of the SDK (ESM and CJS in one app) wrapped\n * it already, its original is used.\n */\nexport const nativeFetch: typeof fetch | undefined = (() => {\n if (typeof fetch !== \"function\") return undefined;\n const original = (fetch as unknown as Record<symbol, typeof fetch | undefined>)[ORIGINAL_FETCH] ?? fetch;\n return original.bind(globalThis);\n})();\n\nlet config: Config | null = null;\nlet defaultUser: BugwatchUser | undefined;\n/** 0.6.0: tags set outside any scope; every new scope starts with a copy. */\nconst defaultTags: Record<string, string> = {};\n/** 0.9.0: flags recorded outside any scope; every new scope starts with a copy. */\nconst defaultFlags = new Map<string, FlagResult>();\nconst storage = new AsyncLocalStorage<Scope>();\nconst pending = new Set<Promise<void>>();\nlet pausedUntil = 0;\n/** Set after a 401 until the next `init`. */\nlet rejectedKey = false;\nconst warned = new Set<string>();\n\nexport function getConfig(): Config | null {\n return config;\n}\n\n/** One warning per distinct message (never thrown, never repeated). */\nexport function warnOnce(message: string): void {\n if (warned.has(message)) return;\n warned.add(message);\n try {\n console.warn(message);\n } catch {\n // Never throw into the host app.\n }\n}\n\nfunction debugLog(message: string): void {\n if (config?.debug) warnOnce(`[Bugwatch] ${message}`);\n}\n\nfunction env(name: string): string | undefined {\n try {\n const value = process.env[name];\n return value && value.trim() ? value.trim() : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction hostName(): string | undefined {\n try {\n // Lazy: `node:os` must not be imported at the top (the Edge runtime has none).\n const getBuiltin = (process as unknown as { getBuiltinModule?: (id: string) => unknown }).getBuiltinModule;\n const os = getBuiltin?.(\"node:os\") as { hostname?: () => string } | undefined;\n const name = os?.hostname?.() ?? env(\"HOSTNAME\");\n return name ? name.slice(0, 200) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** 0.8.0: frameworks reported in `contexts`, by package name. */\nconst FRAMEWORK_PACKAGES = [\n [\"Next.js\", \"next\"],\n [\"Express\", \"express\"],\n] as const;\n\n/**\n * 0.8.0: versions of the frameworks installed in the app, from their\n * package.json, resolved from the working directory. Empty when the runtime\n * has no `node:module` (Edge, Node before 20.16) or nothing is installed.\n */\nfunction detectFrameworks(): { name: string; version: string }[] {\n const found: { name: string; version: string }[] = [];\n try {\n const getBuiltin = (process as unknown as { getBuiltinModule?: (id: string) => unknown }).getBuiltinModule;\n const moduleApi = getBuiltin?.(\"node:module\") as { createRequire?: (from: string) => (id: string) => unknown } | undefined;\n if (!moduleApi?.createRequire) return found;\n const load = moduleApi.createRequire(`${process.cwd().replace(/[\\\\/]+$/, \"\")}/package.json`);\n for (const [name, pkg] of FRAMEWORK_PACKAGES) {\n try {\n const version = frameworkVersion((load(`${pkg}/package.json`) as { version?: unknown }).version);\n if (version) found.push({ name, version });\n } catch {\n // Not installed (or its package.json is not exported).\n }\n }\n } catch {\n // No frameworks reported.\n }\n return found;\n}\n\nfunction currentRoot(option: string | undefined): string | undefined {\n if (option !== undefined) return option.trim() || undefined;\n try {\n return process.cwd();\n } catch {\n return undefined;\n }\n}\n\n/** Applies `init` options. Returns false (and keeps the SDK off) without an API key. */\nexport function configure(options: BugwatchNodeOptions = {}): boolean {\n const apiKey = (typeof options.apiKey === \"string\" ? options.apiKey.trim() : \"\") || env(\"BUGWATCH_API_KEY\") || \"\";\n if (!apiKey) {\n config = null;\n return false;\n }\n const endpoint = (typeof options.endpoint === \"string\" ? options.endpoint.trim() : \"\") || DEFAULT_ENDPOINT;\n const warn = (message: string) => warnOnce(message);\n config = {\n apiKey,\n endpoint,\n release: readOption(\"release\", options.release ?? env(\"BUGWATCH_RELEASE\"), isValidRelease, RELEASE_RULE, warn),\n environment: readOption(\n \"environment\",\n options.environment ?? env(\"BUGWATCH_ENVIRONMENT\"),\n isValidEnvironment,\n ENVIRONMENT_RULE,\n warn,\n ),\n serverName:\n options.serverName === false\n ? undefined\n : typeof options.serverName === \"string\" && options.serverName.trim()\n ? options.serverName.trim().slice(0, 200)\n : hostName(),\n root: currentRoot(options.root),\n httpErrors: readHttpErrors(options.captureHttpErrors),\n onFatalError: options.onFatalError === \"keep-running\" ? \"keep-running\" : \"exit\",\n debug: options.debug === true,\n frameworks: detectFrameworks(),\n };\n rejectedKey = false;\n pausedUntil = 0;\n return true;\n}\n\nexport function scrubSecret(value: string): string {\n const key = config?.apiKey;\n return key && value.includes(key) ? value.split(key).join(\"[Filtered]\") : value;\n}\n\n/** Requests to the ingest endpoint are Bugwatch's own: never breadcrumbs or HTTP errors. */\nexport function isOwnRequest(url: string): boolean {\n const endpoint = config?.endpoint;\n return Boolean(url && endpoint) && url.split(\"?\")[0] === endpoint!.split(\"?\")[0];\n}\n\n// ---------------------------------------------------------------- scopes\n\nexport function currentScope(): Scope | undefined {\n try {\n return storage.getStore();\n } catch {\n return undefined;\n }\n}\n\n/** Runs `fn` in a new scope that starts with the current user (and request). */\nexport function runInScope<T>(fn: () => T, init: Partial<Scope> = {}): T {\n const parent = currentScope();\n const scope: Scope = {\n user: parent?.user,\n request: parent?.request,\n userAgent: parent?.userAgent,\n ...init,\n tags: { ...(parent?.tags ?? defaultTags) },\n flags: new Map(parent?.flags ?? defaultFlags),\n breadcrumbs: [],\n };\n return storage.run(scope, fn);\n}\n\nexport function setUser(next: BugwatchUser | null): void {\n let value: BugwatchUser | undefined;\n if (next && typeof next === \"object\") {\n const id = readString(next.id, MAX_USER_FIELD, (text) => text);\n const email = readString(next.email, MAX_USER_FIELD, (text) => text);\n value = id || email ? { ...(id ? { id } : {}), ...(email ? { email } : {}) } : undefined;\n }\n const scope = currentScope();\n if (scope) scope.user = value;\n else defaultUser = value;\n}\n\n/** setTag / setTags / removeTag: the current scope's tags, or the process default. */\nexport function setTag(key: unknown, value: unknown): void {\n putTag(currentScope()?.tags ?? defaultTags, key, value);\n}\n\n/** 0.9.0: addFeatureFlag — the current scope's flags, or the process default. */\nexport function addFeatureFlag(name: unknown, result: unknown): void {\n putFlag(currentScope()?.flags ?? defaultFlags, name, result);\n}\n\nexport function removeTag(key: unknown): void {\n if (typeof key === \"string\") delete (currentScope()?.tags ?? defaultTags)[key];\n}\n\n/** Adds a breadcrumb to the current scope (outside a scope there is none to keep). */\nexport function recordBreadcrumb(crumb: Omit<Breadcrumb, \"timestamp\">): void {\n const scope = currentScope();\n if (!scope) return;\n scope.breadcrumbs.push({ ...crumb, timestamp: Date.now() });\n if (scope.breadcrumbs.length > MAX_BREADCRUMBS) scope.breadcrumbs.shift();\n}\n\n/** Sets the route of the current request once the framework knows it. */\nexport function setRoute(route: string | undefined): void {\n const scope = currentScope();\n if (scope?.request && route) scope.request = { ...scope.request, route };\n}\n\n// ---------------------------------------------------------------- events\n\nfunction cleanRequest(request: BugwatchRequest | undefined): BugwatchRequest | undefined {\n if (!request || typeof request !== \"object\") return undefined;\n const method = readString(request.method, 10, scrubSecret);\n const url = readString(request.url, MAX_URL, scrubSecret);\n if (!method || !url) return undefined;\n const route = readString(request.route, 200, scrubSecret);\n return { method: method.toUpperCase(), url, ...(route ? { route } : {}) };\n}\n\nfunction breadcrumbsForEvent(scope: Scope | undefined): Breadcrumb[] {\n const list = (scope?.breadcrumbs ?? []).map((crumb) => {\n const copy: Breadcrumb = { ...crumb };\n if (copy.message) copy.message = scrubSecret(copy.message);\n if (copy.data?.url) copy.data = { ...copy.data, url: scrubSecret(copy.data.url) };\n return copy;\n });\n while (list.length > 0 && byteLength(JSON.stringify(list)) > MAX_BREADCRUMB_BYTES) list.shift();\n return list;\n}\n\n/** Builds the event for a thrown value, or null when there is nothing to send. */\nexport function buildEvent(error: unknown, options: InternalCaptureOptions = {}): IngestPayload | null {\n const current = config;\n if (!current) return null;\n const description = describe(error, scrubSecret);\n if (!description.message) return null;\n return buildPayload(current, { ...description, message: description.message }, options);\n}\n\n/** Builds an event from a message and type (HTTP errors). */\nexport function buildMessageEvent(message: string, type: string, options: InternalCaptureOptions = {}): IngestPayload | null {\n const current = config;\n const text = readString(message, MAX_MESSAGE, scrubSecret);\n if (!current || !text) return null;\n return buildPayload(current, { message: text, type }, options);\n}\n\nfunction buildPayload(\n current: Config,\n description: { message: string; type?: string; stack?: string },\n options: InternalCaptureOptions,\n): IngestPayload {\n const scope = currentScope();\n const user = scope ? scope.user : defaultUser;\n const request = cleanRequest(options.request) ?? cleanRequest(scope?.request);\n const userAgent = readString(scope?.userAgent, MAX_URL, scrubSecret);\n const payload: IngestPayload = {\n key: current.apiKey,\n message: description.message,\n level: options.level ?? \"error\",\n // Anything not from the process listeners was reported by the app or an integration.\n handled: options.handled ?? true,\n mechanism: options.mechanism ?? \"capture_error\",\n platform: \"node\",\n runtime: { name: \"node\", version: (process.versions?.node ?? \"\").slice(0, 50) || \"unknown\" },\n sdk: { name: SDK_NAME, version: SDK_VERSION },\n timestamp: Date.now(),\n };\n if (description.type) payload.type = description.type;\n if (description.stack) payload.stack = relativeStack(description.stack, current.root);\n if (current.serverName) payload.serverName = current.serverName;\n if (current.frameworks.length > 0) payload.contexts = { frameworks: current.frameworks.map((framework) => ({ ...framework })) };\n if (request) payload.request = request;\n if (userAgent) payload.userAgent = userAgent;\n if (user) {\n payload.user = {\n ...(user.id ? { id: scrubSecret(user.id) } : {}),\n ...(user.email ? { email: scrubSecret(user.email) } : {}),\n };\n }\n if (current.release) payload.release = current.release;\n if (current.environment) payload.environment = current.environment;\n payload.flags = flagList(scope ? scope.flags : defaultFlags);\n const tags = scope ? scope.tags : defaultTags;\n if (Object.keys(tags).length > 0) {\n payload.tags = {};\n for (const [key, value] of Object.entries(tags)) payload.tags[key] = scrubSecret(value);\n }\n const breadcrumbs = breadcrumbsForEvent(scope);\n if (breadcrumbs.length > 0) payload.breadcrumbs = breadcrumbs;\n return payload;\n}\n\n/** JSON under the API's 100 KB limit: drop breadcrumbs, then cut the stack. */\nfunction serialize(payload: IngestPayload): string {\n let body = JSON.stringify(payload);\n if (byteLength(body) <= MAX_BODY_BYTES) return body;\n delete payload.breadcrumbs;\n body = JSON.stringify(payload);\n if (byteLength(body) <= MAX_BODY_BYTES || !payload.stack) return body;\n payload.stack = payload.stack.slice(0, 20_000);\n return JSON.stringify(payload);\n}\n\n// ------------------------------------------------------------- transport\n\n/** Sends in the background; `flush` waits for it. Never throws, never rejects. */\nexport function send(payload: IngestPayload | null): void {\n try {\n const current = config;\n if (!payload || !current) return;\n if (rejectedKey) return debugLog(\"Not sending: the API key was rejected (401). Check apiKey, then call init again\");\n if (Date.now() < pausedUntil) return debugLog(\"Not sending: the monthly event limit was reached (429); paused for a minute\");\n if (!nativeFetch) return debugLog(\"Not sending: this runtime has no global fetch (Node 20+ is required)\");\n\n const task = (async () => {\n try {\n const response = await nativeFetch(current.endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"User-Agent\": `${SDK_NAME}/${SDK_VERSION}` },\n body: serialize(payload),\n signal: AbortSignal.timeout(SEND_TIMEOUT_MS),\n });\n if (response.status === 401) {\n rejectedKey = true;\n warnOnce(\"[Bugwatch] The API key was rejected (401). Events are not sent until init is called with a valid key\");\n } else if (response.status === 429) {\n pausedUntil = Date.now() + PAUSE_AFTER_429_MS;\n debugLog(\"The monthly event limit was reached (429); pausing for a minute\");\n } else if (!response.ok) {\n debugLog(`Bugwatch answered ${response.status}`);\n }\n // Free the connection.\n await response.arrayBuffer().catch(() => undefined);\n } catch (error) {\n debugLog(`Could not reach Bugwatch: ${error instanceof Error ? error.message : String(error)}`);\n }\n })();\n pending.add(task);\n void task.finally(() => pending.delete(task));\n } catch {\n // Never throw into the host app.\n }\n}\n\n/** Waits for events in flight; `true` when all were sent within `timeoutMs`. */\nexport async function flush(timeoutMs = 2_000): Promise<boolean> {\n try {\n if (pending.size === 0) return true;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<false>((resolve) => {\n timer = setTimeout(() => resolve(false), Math.max(0, timeoutMs));\n // Never keep the process alive just for this timer.\n timer.unref?.();\n });\n const done = Promise.allSettled([...pending]).then(() => true as const);\n const result = await Promise.race([done, timeout]);\n if (timer) clearTimeout(timer);\n return result;\n } catch {\n return false;\n }\n}\n\n/** Errors already reported, so one error is sent once (a rethrown rejection, two handlers). */\nconst reported = new WeakSet<object>();\n\nexport function markReported(value: unknown): void {\n if (typeof value === \"object\" && value !== null) reported.add(value);\n}\n\nexport function wasReported(value: unknown): boolean {\n return typeof value === \"object\" && value !== null && reported.has(value);\n}\n\n/** Reports a thrown value (once per error object). */\nexport function captureError(error: unknown, options: InternalCaptureOptions = {}): void {\n try {\n if (wasReported(error)) return;\n markReported(error);\n send(buildEvent(error, options));\n } catch {\n // Never throw into the host app.\n }\n}\n","/**\n * Rules shared by the browser SDK (`bugwatch`) and the Node SDK\n * (`bugwatch/node`): limits, option checks, error description, and\n * `captureHttpErrors`. Pure: no DOM, no Node APIs.\n */\n\nexport const DEFAULT_ENDPOINT = \"https://sentry-like.vercel.app/api/ingest\";\n\nexport const MAX_MESSAGE = 2_000;\nexport const MAX_STACK = 50_000;\nexport const MAX_URL = 2_000;\nexport const MAX_USER_FIELD = 200;\nconst MAX_RELEASE = 200;\n/** Breadcrumbs stay under this many bytes of JSON, so a full stack still fits the API's 100 KB body. */\nexport const MAX_BREADCRUMB_BYTES = 20 * 1024;\n\n// Same rules as the Bugwatch API, which rejects the whole event (400) otherwise.\nconst RELEASE_CHARS = /^[^\\s\\u0000-\\u001f\\u007f-\\u009f]+$/;\nconst ENVIRONMENT_FORMAT = /^[A-Za-z0-9_.-]{1,64}$/;\n\nexport interface BugwatchUser {\n id?: string;\n email?: string;\n}\n\nexport interface BugwatchHttpErrorOptions {\n /** Statuses to report: codes or `[min, max]` ranges. Default `[[500, 599]]`. */\n statuses?: (number | [number, number])[];\n /**\n * Also report requests that got no response (offline, DNS, CORS, timeout).\n * Default `false`. Cancelled requests are never reported.\n */\n networkErrors?: boolean;\n /** Requests not to report: a URL contains the string, or matches the RegExp. */\n ignoreUrls?: (string | RegExp)[];\n}\n\nexport interface ErrorDescription {\n message?: string;\n type?: string;\n stack?: string;\n}\n\n/** Removes secrets (the API key) from a string. */\nexport type Scrub = (value: string) => string;\n\nexport function asRecord(value: unknown): Record<string, unknown> | null {\n return typeof value === \"object\" && value !== null ? (value as Record<string, unknown>) : null;\n}\n\n/** Trimmed, scrubbed, and cut; `undefined` for non-strings and empty strings. */\nexport function readString(value: unknown, limit: number, scrub: Scrub): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const trimmed = value.trim();\n\n if (!trimmed) {\n return undefined;\n }\n\n // Defense in depth: the project key can end up in a URL or an error\n // message. Never send it back in the payload.\n return scrub(trimmed).slice(0, limit);\n}\n\nexport function readStack(value: unknown, scrub: Scrub): string | undefined {\n if (typeof value === \"string\") {\n return readString(value, MAX_STACK, scrub);\n }\n\n if (Array.isArray(value)) {\n const lines = value.filter((line): line is string => typeof line === \"string\");\n return readString(lines.join(\"\\n\"), MAX_STACK, scrub);\n }\n\n return undefined;\n}\n\nexport function nonNegative(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : undefined;\n}\n\nexport function isValidRelease(value: string): boolean {\n return value.length <= MAX_RELEASE && RELEASE_CHARS.test(value) && value !== \".\" && value !== \"..\";\n}\n\nexport function isValidEnvironment(value: string): boolean {\n return ENVIRONMENT_FORMAT.test(value);\n}\n\nexport const RELEASE_RULE = \"1-200 characters, no spaces or control characters, not . or ..\";\nexport const ENVIRONMENT_RULE = \"letters, digits, _ . - only, max 64 characters\";\n\n/**\n * Reads the `release` / `environment` option: trimmed; empty or missing →\n * not set. An invalid value is dropped with one warning (events are still\n * sent, just without it), because the API would reject the whole event.\n */\nexport function readOption(\n name: string,\n value: unknown,\n isValid: (value: string) => boolean,\n rule: string,\n warn: (message: string) => void,\n): string | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n\n const trimmed = typeof value === \"string\" ? value.trim() : undefined;\n\n if (trimmed === \"\") {\n return undefined;\n }\n\n if (trimmed !== undefined && isValid(trimmed)) {\n return trimmed;\n }\n\n warn(`[Bugwatch] Ignoring invalid ${name} option: ${rule}`);\n return undefined;\n}\n\n/** Extracts the useful parts of an Error, or turns any thrown value into a message. */\nexport function describe(value: unknown, scrub: Scrub): ErrorDescription {\n const record = asRecord(value);\n const message = record ? readString(record.message, MAX_MESSAGE, scrub) : undefined;\n\n if (message) {\n return {\n message,\n type: record ? readString(record.name, MAX_USER_FIELD, scrub) : undefined,\n stack: record ? readStack(record.stack, scrub) : undefined,\n };\n }\n\n if (typeof value === \"string\") {\n return { message: readString(value, MAX_MESSAGE, scrub) };\n }\n\n if (value !== undefined && value !== null) {\n try {\n return { message: readString(String(value), MAX_MESSAGE, scrub) };\n } catch {\n // An object with a throwing toString/@@toPrimitive: nothing safe to send.\n }\n }\n\n return {};\n}\n\n// ------------------------------------------------------------------ tags\n\n/** Same rules as the Bugwatch API (Step 63): bad tags are dropped there too. */\nexport const TAG_KEY = /^[a-z0-9_.-]{1,32}$/;\nexport const MAX_TAG_VALUE = 200;\nexport const MAX_TAGS = 20;\n/** Set by Bugwatch itself; a custom tag with one of these keys is dropped. */\nconst AUTOMATIC_TAG_KEYS = new Set([\n \"browser\",\n \"os\",\n \"url\",\n \"route\",\n \"server\",\n \"platform\",\n \"release\",\n \"environment\",\n \"level\",\n \"handled\",\n]);\n\nexport type TagValue = string | number | boolean;\n\n/**\n * 0.8.0: sent as `contexts` (API Step 83). The API drops any field it finds\n * invalid, so these are best effort.\n */\nexport interface EventContexts {\n locale?: string;\n timezone?: string;\n screen?: { width: number; height: number; pixelRatio?: number };\n viewport?: { width: number; height: number };\n frameworks?: { name: string; version: string }[];\n}\n\n/** A framework version when it is a short non-empty string, else null. */\nexport function frameworkVersion(value: unknown): string | null {\n return typeof value === \"string\" && value.trim() && value.length <= 50 ? value.trim() : null;\n}\n\n/**\n * 0.7.0: how the error was caught, sent as `mechanism` (API Step 78). Browser:\n * `onerror`, `onunhandledrejection`; Node: `uncaught_exception`,\n * `unhandled_rejection`, `express`, `nextjs`; both: `capture_error`, `http`.\n */\nexport type Mechanism =\n | \"onerror\"\n | \"onunhandledrejection\"\n | \"uncaught_exception\"\n | \"unhandled_rejection\"\n | \"capture_error\"\n | \"http\"\n | \"express\"\n | \"nextjs\";\n\n/** The tag's value as sent, or undefined when the tag would be dropped (bad key, automatic key, empty or long value). */\nexport function tagValue(key: unknown, value: unknown): string | undefined {\n if (typeof key !== \"string\" || !TAG_KEY.test(key) || AUTOMATIC_TAG_KEYS.has(key)) return undefined;\n if (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\") return undefined;\n const text = String(value).trim();\n return text && text.length <= MAX_TAG_VALUE ? text : undefined;\n}\n\n/**\n * Applies `setTag(key, value)` to a tag map: a valid tag is set (replacing\n * the old value), at most 20 different keys; anything else changes nothing.\n * Returns whether it was set.\n */\nexport function putTag(tags: Record<string, string>, key: unknown, value: unknown): boolean {\n const text = tagValue(key, value);\n if (text === undefined) return false;\n const name = key as string;\n const known = Object.prototype.hasOwnProperty.call(tags, name);\n if (!known && Object.keys(tags).length >= MAX_TAGS) return false;\n tags[name] = text;\n return true;\n}\n\n/** 0.9.0: a feature flag result as sent (API Step 112). */\nexport type FlagResult = boolean | string;\nexport interface FeatureFlag {\n flag: string;\n result: FlagResult;\n}\n\n/**\n * 0.9.0: records `addFeatureFlag(name, result)` — one entry per flag, the last\n * result moved to the end, the oldest dropped past 100. Same rules as the API:\n * a name of 1–100 characters, a boolean or a 1–64 character string result.\n * Anything else changes nothing.\n */\nexport function putFlag(flags: Map<string, FlagResult>, name: unknown, result: unknown): void {\n const flag = typeof name === \"string\" ? name.trim() : \"\";\n const value = typeof result === \"string\" ? result.trim() : result;\n if (!flag || flag.length > 100) return;\n if (typeof value !== \"boolean\" && (typeof value !== \"string\" || !value || value.length > 64)) return;\n flags.delete(flag);\n flags.set(flag, value);\n if (flags.size > 100) flags.delete(flags.keys().next().value as string);\n}\n\n/** The flags as the `flags` field, or undefined when there are none. */\nexport function flagList(flags: Map<string, FlagResult>): FeatureFlag[] | undefined {\n return flags.size > 0 ? [...flags].map(([flag, result]) => ({ flag, result })) : undefined;\n}\n\nexport function byteLength(value: string): number {\n try {\n return new TextEncoder().encode(value).length;\n } catch {\n return value.length;\n }\n}\n\n// ------------------------------------------------------- captureHttpErrors\n\nexport interface HttpErrorConfig {\n statuses: [number, number][];\n networkErrors: boolean;\n ignoreUrls: (string | RegExp)[];\n}\n\n/** Each failing request (method, URL, status) is reported at most once a minute. */\nconst HTTP_ERROR_INTERVAL_MS = 60_000;\nconst MAX_HTTP_ERROR_KEYS = 100;\n\n/** Reads the `captureHttpErrors` option; off → null. Bad entries are skipped. */\nexport function readHttpErrors(option: unknown): HttpErrorConfig | null {\n if (!option) {\n return null;\n }\n\n const record = asRecord(option) ?? {};\n let statuses: [number, number][] = [[500, 599]];\n\n if (Array.isArray(record.statuses)) {\n statuses = [];\n for (const entry of record.statuses as unknown[]) {\n if (typeof entry === \"number\") {\n statuses.push([entry, entry]);\n } else if (Array.isArray(entry) && typeof entry[0] === \"number\" && typeof entry[1] === \"number\") {\n statuses.push([entry[0], entry[1]]);\n }\n }\n }\n\n return {\n statuses,\n networkErrors: record.networkErrors === true,\n ignoreUrls: Array.isArray(record.ignoreUrls)\n ? (record.ignoreUrls as unknown[]).filter(\n (entry): entry is string | RegExp => typeof entry === \"string\" || entry instanceof RegExp,\n )\n : [],\n };\n}\n\nfunction isIgnoredUrl(url: string, patterns: (string | RegExp)[]): boolean {\n return patterns.some((pattern) => {\n if (typeof pattern === \"string\") {\n return url.includes(pattern);\n }\n pattern.lastIndex = 0;\n return pattern.test(url);\n });\n}\n\n/** A path segment that is an id: a number, a UUID, or 8+ hex characters with a digit (ObjectIds, hashes). */\nconst ID_SEGMENT = /^(?:\\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|(?=[a-f]*\\d)[0-9a-f]{8,})$/i;\n\n/**\n * The URL for an HTTP error message: no query string or hash (they often\n * carry tokens or personal data), and id segments as `:id`, so one endpoint\n * is one issue (`/api/projects/6740a1b2…` → `/api/projects/:id`). The host of\n * an absolute URL is kept as is.\n */\nexport function urlForMessage(url: string): string {\n const parts = (url.split(/[?#]/)[0] || url).split(\"/\");\n const first = /^[a-z][a-z0-9+.-]*:$/i.test(parts[0] ?? \"\") && parts[1] === \"\" ? 3 : 0;\n return parts.map((part, index) => (index >= first && ID_SEGMENT.test(part) ? \":id\" : part)).join(\"/\");\n}\n\n/** No response: `network` (offline, DNS, CORS, timeout) or `abort` (cancelled on purpose). */\nexport type HttpFailure = \"network\" | \"abort\";\n\n/**\n * `captureHttpErrors`: the event for a finished request, or null when it is\n * not reported (not a failure, ignored, cancelled, or the same one within a\n * minute; `sentAt` remembers the last 100). E.g. `HTTP 500: GET /api/orders/:id`\n * (type `HttpError`) or `Network error: GET /api/orders` (type `NetworkError`).\n */\nexport function httpErrorEvent(\n config: HttpErrorConfig | null,\n sentAt: Map<string, number>,\n method: string,\n url: string,\n status: number,\n failure?: HttpFailure,\n): { message: string; type: string } | null {\n if (!config || isIgnoredUrl(url, config.ignoreUrls)) {\n return null;\n }\n\n const target = `${method.toUpperCase()} ${urlForMessage(url)}`;\n let message: string;\n let type: string;\n\n if (failure) {\n if (failure === \"abort\" || !config.networkErrors) {\n return null;\n }\n message = `Network error: ${target}`;\n type = \"NetworkError\";\n } else if (config.statuses.some(([min, max]) => status >= min && status <= max)) {\n message = `HTTP ${status}: ${target}`;\n type = \"HttpError\";\n } else {\n return null;\n }\n\n const now = Date.now();\n const last = sentAt.get(message);\n if (last !== undefined && now - last < HTTP_ERROR_INTERVAL_MS) {\n return null;\n }\n sentAt.delete(message);\n sentAt.set(message, now);\n if (sentAt.size > MAX_HTTP_ERROR_KEYS) {\n // Oldest first (insertion order).\n sentAt.delete(sentAt.keys().next().value as string);\n }\n\n return { message, type };\n}\n","/**\n * Makes stack paths relative to the app's root folder:\n * `/opt/render/project/src/dist/server.js:10:5` → `dist/server.js:10:5`, and\n * the same for `file://` URLs from ES modules. Grouping then matches across\n * hosts and deploy folders, and no home folders or usernames are sent.\n */\nexport function relativeStack(stack: string, root: string | undefined): string {\n if (!root) return stack;\n const trimmed = root.replace(/[\\\\/]+$/, \"\");\n if (!trimmed) return stack;\n\n const forward = trimmed.replace(/\\\\/g, \"/\");\n const fileUrl = `file://${forward.startsWith(\"/\") ? \"\" : \"/\"}${forward}`;\n // Longest first, so the file URL is removed as a whole.\n const prefixes = [...new Set([`${fileUrl}/`, `${encodeURI(fileUrl)}/`, `${trimmed}/`, `${trimmed}\\\\`, `${forward}/`])].sort(\n (a, b) => b.length - a.length,\n );\n\n let result = stack;\n for (const prefix of prefixes) {\n if (result.includes(prefix)) result = result.split(prefix).join(\"\");\n }\n return result;\n}\n","export const SDK_NAME = \"bugwatch-node\";\n/** Keep in sync with package.json (a test checks it). */\nexport const SDK_VERSION = \"0.9.0\";\n","/**\n * Outgoing `fetch` (Step 56): inside a request scope each call is an `http`\n * breadcrumb, and `captureHttpErrors` reports failed calls. The wrapper keeps\n * the app's behavior: same arguments, `this`, return value, and errors.\n * Bugwatch's own requests use the unwrapped fetch and are never recorded.\n */\n\nimport { httpErrorEvent, type HttpFailure } from \"../shared\";\nimport { ORIGINAL_FETCH, buildMessageEvent, getConfig, isOwnRequest, recordBreadcrumb, send } from \"./client\";\n\nconst MAX_CRUMB_URL = 500;\nconst httpErrorSentAt = new Map<string, number>();\nlet patched = false;\n\nfunction target(input: unknown, init: unknown): { method: string; url: string } {\n let method = \"GET\";\n let url = \"\";\n try {\n if (typeof input === \"string\") url = input;\n else if (input instanceof URL) url = input.href;\n else if (input && typeof (input as { url?: unknown }).url === \"string\") url = (input as { url: string }).url;\n const requestMethod = (input as { method?: unknown } | null)?.method;\n if (typeof requestMethod === \"string\") method = requestMethod;\n const initMethod = (init as { method?: unknown } | undefined)?.method;\n if (typeof initMethod === \"string\") method = initMethod;\n } catch {\n // Unusual input: record what we have.\n }\n return { method: method.toUpperCase(), url };\n}\n\nfunction failureOf(error: unknown): HttpFailure {\n // AbortController → cancelled on purpose; a timeout (TimeoutError) or \"fetch failed\" → no response.\n return (error as { name?: unknown } | null)?.name === \"AbortError\" ? \"abort\" : \"network\";\n}\n\nfunction onResult(method: string, url: string, status: number, startedAt: number, failure?: HttpFailure): void {\n try {\n if (!url || isOwnRequest(url)) return;\n recordBreadcrumb({\n type: \"http\",\n level: failure || status >= 500 ? \"error\" : status >= 400 ? \"warning\" : \"info\",\n data: {\n method: method.slice(0, 10),\n url: url.slice(0, MAX_CRUMB_URL),\n status,\n durationMs: Math.max(0, Date.now() - startedAt),\n },\n });\n const event = httpErrorEvent(getConfig()?.httpErrors ?? null, httpErrorSentAt, method, url, status, failure);\n if (event) send(buildMessageEvent(event.message, event.type, { mechanism: \"http\" }));\n } catch {\n // Never throw into the host app.\n }\n}\n\n/** Wraps the global fetch once. */\nexport function patchFetch(): void {\n if (patched || typeof globalThis.fetch !== \"function\") return;\n const original = globalThis.fetch;\n\n const wrapped = function (this: unknown, ...args: Parameters<typeof fetch>) {\n const { method, url } = target(args[0], args[1]);\n const startedAt = Date.now();\n const result = original.apply(this, args);\n try {\n // Recording hangs off a separate branch that never rejects; the app gets `result` itself.\n result.then(\n (response) => onResult(method, url, response.status, startedAt),\n (error: unknown) => onResult(method, url, 0, startedAt, failureOf(error)),\n );\n } catch {\n // A non-promise result from a shimmed fetch: nothing to record.\n }\n return result;\n } as typeof fetch;\n\n // Keep markers other tools put on fetch (e.g. Next.js's `__nextPatched`), so they don't patch twice.\n for (const key of Reflect.ownKeys(original)) {\n if (key === \"length\" || key === \"name\" || key === \"prototype\") continue;\n try {\n const descriptor = Object.getOwnPropertyDescriptor(original, key);\n if (descriptor) Object.defineProperty(wrapped, key, descriptor);\n } catch {\n // Skip properties that cannot be copied.\n }\n }\n\n (wrapped as unknown as Record<symbol, unknown>)[ORIGINAL_FETCH] =\n (original as unknown as Record<symbol, unknown>)[ORIGINAL_FETCH] ?? original;\n globalThis.fetch = wrapped;\n patched = true;\n}\n","/**\n * Framework integrations (Step 56): Express request / error handlers and\n * Next.js `onRequestError`. No dependency on either framework: only the\n * shapes they pass in are used.\n */\n\nimport {\n captureError,\n currentScope,\n flush,\n getConfig,\n runInScope,\n setRoute,\n wasReported,\n type BugwatchRequest,\n} from \"./client\";\n\nconst NEXT_FLUSH_MS = 2_000;\n\ntype Headers = Record<string, string | string[] | undefined>;\n\nfunction header(headers: Headers | undefined, name: string): string | undefined {\n const value = headers?.[name];\n return Array.isArray(value) ? value[0] : value;\n}\n\n// ---------------------------------------------------------------- Express\n\n/** The parts of an Express request the SDK reads. */\ninterface ExpressRequest {\n method?: string;\n originalUrl?: string;\n url?: string;\n protocol?: string;\n baseUrl?: string;\n headers?: Headers;\n route?: { path?: unknown };\n}\n\ntype Next = (error?: unknown) => void;\n\nfunction expressUrl(req: ExpressRequest): string {\n const path = req.originalUrl || req.url || \"/\";\n const host = header(req.headers, \"host\");\n if (!host) return path;\n // `req.protocol` honors Express's \"trust proxy\" setting.\n const protocol = req.protocol || \"http\";\n return `${protocol}://${host}${path}`;\n}\n\n/** `/api/orders/:id` once Express has matched a route. */\nfunction expressRoute(req: ExpressRequest): string | undefined {\n const path = req.route?.path;\n return typeof path === \"string\" ? `${req.baseUrl ?? \"\"}${path}` || undefined : undefined;\n}\n\nfunction expressRequest(req: ExpressRequest): BugwatchRequest {\n const route = expressRoute(req);\n return { method: req.method || \"GET\", url: expressUrl(req), ...(route ? { route } : {}) };\n}\n\n/**\n * `app.use(Bugwatch.expressRequestHandler())` first: each request gets its own\n * scope (user, breadcrumbs, the request, and its User-Agent).\n */\nexport function expressRequestHandler() {\n return function bugwatchRequestHandler(req: ExpressRequest, _res: unknown, next: Next): void {\n let request: BugwatchRequest | undefined;\n let userAgent: string | undefined;\n try {\n request = expressRequest(req);\n userAgent = header(req.headers, \"user-agent\");\n } catch {\n // Run the request without Bugwatch context.\n }\n runInScope(() => next(), { request, userAgent });\n };\n}\n\n/** The status an Express error asks for (`status` / `statusCode`), if any. */\nfunction errorStatus(error: unknown): number | undefined {\n const record = error as { status?: unknown; statusCode?: unknown } | null;\n const status = record?.status ?? record?.statusCode;\n return typeof status === \"number\" ? status : undefined;\n}\n\n/**\n * `app.use(Bugwatch.expressErrorHandler())` after the routes, before your own\n * error handler: reports errors without a status or with a 5xx status, then\n * passes the error on (`next(err)`). 4xx errors are not reported.\n */\nexport function expressErrorHandler() {\n return function bugwatchErrorHandler(error: unknown, req: ExpressRequest, _res: unknown, next: Next): void {\n try {\n const status = errorStatus(error);\n if (status === undefined || status >= 500) {\n const request = expressRequest(req);\n if (currentScope()) {\n // Inside the request's scope: keep its user and breadcrumbs.\n setRoute(request.route);\n captureError(error, { request, mechanism: \"express\" });\n } else {\n // No request handler installed: report with what the request tells us.\n runInScope(() => captureError(error, { request, mechanism: \"express\" }), {\n request,\n userAgent: header(req.headers, \"user-agent\"),\n });\n }\n }\n } catch {\n // Never throw into the host app.\n }\n next(error);\n };\n}\n\n// ---------------------------------------------------------------- Next.js\n\n/** What Next.js passes to `onRequestError` (Next.js 15+). */\ninterface NextRequestInfo {\n path?: string;\n method?: string;\n headers?: Headers;\n}\n\ninterface NextErrorContext {\n routePath?: string;\n routeType?: string;\n routerKind?: string;\n}\n\n/** Errors Next.js throws on purpose (`redirect()`, `notFound()`, dynamic rendering bailouts). */\nconst NEXT_CONTROL_FLOW = [\n \"NEXT_REDIRECT\",\n \"NEXT_NOT_FOUND\",\n \"NEXT_HTTP_ERROR_FALLBACK\",\n \"DYNAMIC_SERVER_USAGE\",\n \"BAILOUT_TO_CLIENT_SIDE_RENDERING\",\n \"NEXT_PRERENDER_INTERRUPTED\",\n \"HANGING_PROMISE_REJECTION\",\n];\n\nfunction isNextControlFlow(error: unknown): boolean {\n const record = error as { digest?: unknown; message?: unknown } | null;\n const digest = typeof record?.digest === \"string\" ? record.digest : \"\";\n const message = typeof record?.message === \"string\" ? record.message : \"\";\n return NEXT_CONTROL_FLOW.some((prefix) => digest.startsWith(prefix) || message === prefix);\n}\n\nfunction nextUrl(request: NextRequestInfo): string {\n const path = request.path || \"/\";\n const host = header(request.headers, \"x-forwarded-host\") || header(request.headers, \"host\");\n if (!host) return path;\n const protocol = (header(request.headers, \"x-forwarded-proto\") || \"https\").split(\",\")[0]!.trim();\n return `${protocol}://${host}${path}`;\n}\n\n/**\n * `export const onRequestError = Bugwatch.nextOnRequestError;` in\n * `instrumentation.ts`: reports errors from server components, route\n * handlers, server actions, and middleware (Node runtime), then waits for the\n * send (2 s at most) so a serverless function is not frozen first.\n */\nexport async function nextOnRequestError(\n error: unknown,\n request: NextRequestInfo = {},\n context: NextErrorContext = {},\n): Promise<void> {\n try {\n if (!getConfig() || isNextControlFlow(error) || wasReported(error)) return;\n const info: BugwatchRequest = {\n method: request.method || \"GET\",\n url: nextUrl(request),\n ...(context.routePath ? { route: context.routePath } : {}),\n };\n runInScope(() => captureError(error, { request: info, mechanism: \"nextjs\" }), {\n request: info,\n userAgent: header(request.headers, \"user-agent\"),\n });\n await flush(NEXT_FLUSH_MS);\n } catch {\n // Never throw into Next.js.\n }\n}\n","/**\n * Uncaught exceptions and unhandled rejections.\n *\n * Adding a listener changes what Node does: without one, an uncaught\n * exception (and, by default, an unhandled rejection) prints the error and\n * exits with code 1. The SDK keeps that behavior: when its listener is the\n * only one, it sends the event, waits for it (2 s at most), prints the error,\n * and exits with code 1. When the app has its own listeners, it only reports.\n */\n\nimport { buildEvent, flush, getConfig, markReported, send, wasReported } from \"./client\";\n\nconst FATAL_FLUSH_MS = 2_000;\n\nlet installed = false;\nlet exiting = false;\n\n/** `--unhandled-rejections=<mode>` from the command line or NODE_OPTIONS; Node's default is `throw`. */\nfunction rejectionMode(): string {\n try {\n const args = [...process.execArgv, ...(process.env.NODE_OPTIONS ?? \"\").split(/\\s+/)];\n let mode = \"throw\";\n for (const arg of args) {\n const match = /^--unhandled-rejections=(.+)$/.exec(arg);\n if (match) mode = match[1]!;\n }\n return mode;\n } catch {\n return \"throw\";\n }\n}\n\nfunction printFatal(error: unknown): void {\n try {\n const text =\n error instanceof Error ? (error.stack ?? `${error.name}: ${error.message}`) : `Uncaught ${String(error)}`;\n process.stderr.write(`${text}\\n\\nNode.js ${process.version}\\n`);\n } catch {\n // Nothing else to do: the process is exiting.\n }\n}\n\nfunction exitAfterFlush(error: unknown): void {\n if (exiting) return;\n exiting = true;\n void flush(FATAL_FLUSH_MS).then(() => {\n printFatal(error);\n process.exit(1);\n });\n}\n\nfunction onUncaughtException(error: unknown): void {\n try {\n if (!wasReported(error)) {\n markReported(error);\n send(buildEvent(error, { level: \"fatal\", handled: false, mechanism: \"uncaught_exception\" }));\n }\n const onlyOurs = process.listenerCount(\"uncaughtException\") === 1;\n if (onlyOurs && (getConfig()?.onFatalError ?? \"exit\") === \"exit\") exitAfterFlush(error);\n } catch {\n // Never throw from here: it would end the process without the event.\n }\n}\n\n/** Node's own wrapper for a rejection whose reason is not an Error. */\nfunction rejectionError(reason: unknown): Error {\n let text: string;\n try {\n text = String(reason);\n } catch {\n text = \"[unprintable]\";\n }\n const error = new Error(\n \"This error originated either by throwing inside of an async function without a catch block, \" +\n `or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason \"${text}\".`,\n );\n (error as Error & { code?: string }).code = \"ERR_UNHANDLED_REJECTION\";\n return error;\n}\n\nfunction onUnhandledRejection(reason: unknown): void {\n try {\n const mode = rejectionMode();\n if (!wasReported(reason)) {\n markReported(reason);\n send(buildEvent(reason, { level: \"error\", handled: false, mechanism: \"unhandled_rejection\" }));\n }\n if (mode === \"warn-with-error-code\") process.exitCode = 1;\n\n // Under the default mode Node would raise it as an uncaught exception;\n // our listener stopped that, so raise it ourselves (reported only once).\n const onlyOurs = process.listenerCount(\"unhandledRejection\") === 1;\n if (mode === \"throw\" && onlyOurs) {\n const error = reason instanceof Error ? reason : rejectionError(reason);\n markReported(error);\n process.nextTick(() => {\n throw error;\n });\n }\n } catch {\n // Never throw into the host app.\n }\n}\n\n/** Adds the process listeners once. */\nexport function installProcessHandlers(): void {\n if (installed) return;\n installed = true;\n process.on(\"uncaughtException\", onUncaughtException);\n process.on(\"unhandledR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AAI,CAAC,UAAU,OAAO,EAAG;AACzB,6BAAuB;AACvB,iBAAW;AAAA,IACb,QAAQ;AAAA,IAER;AAAA,EACF;AAAA;AAAA,EAGA,aAAa,OAAgB,SAAgC;AAC3D,iBAAa,OAAO,OAAO;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAQ,MAAoD;AAC1D,QAAI;AACF,cAAQ,IAAI;AAAA,IACd,QAAQ;AAAA,IAER;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,KAAa,OAAuB;AACzC,QAAI;AACF,aAAO,KAAK,KAAK;AAAA,IACnB,QAAQ;AAAA,IAER;AAAA,EACF;AAAA;AAAA,EAGA,QAAQ,QAAwC;AAC9C,QAAI;AACF,UAAI,CAAC,UAAU,OAAO,WAAW,SAAU;AAC3C,iBAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,EAAG,QAAO,KAAK,KAAK;AAAA,IACtE,QAAQ;AAAA,IAER;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,eAAe,MAAc,QAAgC;AAC3D,QAAI;AACF,qBAAe,MAAM,MAAM;AAAA,IAC7B,QAAQ;AAAA,IAER;AAAA,EACF;AAAA;AAAA,EAGA,UAAU,KAAmB;AAC3B,QAAI;AACF,gBAAU,GAAG;AAAA,IACf,QAAQ;AAAA,IAER;AAAA,EACF;AAAA;AAAA,EAGA,UAAa,IAAgB;AAC3B,WAAO,WAAW,EAAE;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,WAAsC;AAC1C,WAAO,MAAM,SAAS;AAAA,EACxB;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AACF;AAEA,IAAO,eAAQ;","names":["config","target"]}
package/dist/node.d.cts CHANGED
@@ -147,6 +147,13 @@ declare const Bugwatch: {
147
147
  setTag(key: string, value: TagValue): void;
148
148
  /** Several tags at once: `setTags({ plan: "pro", region: "eu" })`. */
149
149
  setTags(values: Record<string, TagValue>): void;
150
+ /**
151
+ * Records a feature flag the app just evaluated, e.g.
152
+ * `addFeatureFlag("new-checkout", true)`. Inside a request (or `withScope`)
153
+ * only that request's events carry it; outside, every event. The last 100,
154
+ * one per flag (the latest result). Never throws.
155
+ */
156
+ addFeatureFlag(name: string, result: boolean | string): void;
150
157
  /** Stops sending a tag (in the current request, or everywhere outside one). */
151
158
  removeTag(key: string): void;
152
159
  /** Runs `fn` with its own user, tags, and breadcrumbs (the integrations do this per request). */
package/dist/node.d.ts CHANGED
@@ -147,6 +147,13 @@ declare const Bugwatch: {
147
147
  setTag(key: string, value: TagValue): void;
148
148
  /** Several tags at once: `setTags({ plan: "pro", region: "eu" })`. */
149
149
  setTags(values: Record<string, TagValue>): void;
150
+ /**
151
+ * Records a feature flag the app just evaluated, e.g.
152
+ * `addFeatureFlag("new-checkout", true)`. Inside a request (or `withScope`)
153
+ * only that request's events carry it; outside, every event. The last 100,
154
+ * one per flag (the latest result). Never throws.
155
+ */
156
+ addFeatureFlag(name: string, result: boolean | string): void;
150
157
  /** Stops sending a tag (in the current request, or everywhere outside one). */
151
158
  removeTag(key: string): void;
152
159
  /** Runs `fn` with its own user, tags, and breadcrumbs (the integrations do this per request). */
package/dist/node.js CHANGED
@@ -92,6 +92,9 @@ var AUTOMATIC_TAG_KEYS = /* @__PURE__ */ new Set([
92
92
  "level",
93
93
  "handled"
94
94
  ]);
95
+ function frameworkVersion(value) {
96
+ return typeof value === "string" && value.trim() && value.length <= 50 ? value.trim() : null;
97
+ }
95
98
  function tagValue(key, value) {
96
99
  if (typeof key !== "string" || !TAG_KEY.test(key) || AUTOMATIC_TAG_KEYS.has(key)) return void 0;
97
100
  if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") return void 0;
@@ -107,6 +110,18 @@ function putTag(tags, key, value) {
107
110
  tags[name] = text;
108
111
  return true;
109
112
  }
113
+ function putFlag(flags, name, result) {
114
+ const flag = typeof name === "string" ? name.trim() : "";
115
+ const value = typeof result === "string" ? result.trim() : result;
116
+ if (!flag || flag.length > 100) return;
117
+ if (typeof value !== "boolean" && (typeof value !== "string" || !value || value.length > 64)) return;
118
+ flags.delete(flag);
119
+ flags.set(flag, value);
120
+ if (flags.size > 100) flags.delete(flags.keys().next().value);
121
+ }
122
+ function flagList(flags) {
123
+ return flags.size > 0 ? [...flags].map(([flag, result]) => ({ flag, result })) : void 0;
124
+ }
110
125
  function byteLength(value) {
111
126
  try {
112
127
  return new TextEncoder().encode(value).length;
@@ -206,7 +221,7 @@ function relativeStack(stack, root) {
206
221
 
207
222
  // src/node/version.ts
208
223
  var SDK_NAME = "bugwatch-node";
209
- var SDK_VERSION = "0.7.0";
224
+ var SDK_VERSION = "0.9.0";
210
225
 
211
226
  // src/node/client.ts
212
227
  var MAX_BREADCRUMBS = 50;
@@ -222,6 +237,7 @@ var nativeFetch = (() => {
222
237
  var config = null;
223
238
  var defaultUser;
224
239
  var defaultTags = {};
240
+ var defaultFlags = /* @__PURE__ */ new Map();
225
241
  var storage = new AsyncLocalStorage();
226
242
  var pending = /* @__PURE__ */ new Set();
227
243
  var pausedUntil = 0;
@@ -259,6 +275,28 @@ function hostName() {
259
275
  return void 0;
260
276
  }
261
277
  }
278
+ var FRAMEWORK_PACKAGES = [
279
+ ["Next.js", "next"],
280
+ ["Express", "express"]
281
+ ];
282
+ function detectFrameworks() {
283
+ const found = [];
284
+ try {
285
+ const getBuiltin = process.getBuiltinModule;
286
+ const moduleApi = getBuiltin?.("node:module");
287
+ if (!moduleApi?.createRequire) return found;
288
+ const load = moduleApi.createRequire(`${process.cwd().replace(/[\\/]+$/, "")}/package.json`);
289
+ for (const [name, pkg] of FRAMEWORK_PACKAGES) {
290
+ try {
291
+ const version = frameworkVersion(load(`${pkg}/package.json`).version);
292
+ if (version) found.push({ name, version });
293
+ } catch {
294
+ }
295
+ }
296
+ } catch {
297
+ }
298
+ return found;
299
+ }
262
300
  function currentRoot(option) {
263
301
  if (option !== void 0) return option.trim() || void 0;
264
302
  try {
@@ -290,7 +328,8 @@ function configure(options = {}) {
290
328
  root: currentRoot(options.root),
291
329
  httpErrors: readHttpErrors(options.captureHttpErrors),
292
330
  onFatalError: options.onFatalError === "keep-running" ? "keep-running" : "exit",
293
- debug: options.debug === true
331
+ debug: options.debug === true,
332
+ frameworks: detectFrameworks()
294
333
  };
295
334
  rejectedKey = false;
296
335
  pausedUntil = 0;
@@ -319,6 +358,7 @@ function runInScope(fn, init = {}) {
319
358
  userAgent: parent?.userAgent,
320
359
  ...init,
321
360
  tags: { ...parent?.tags ?? defaultTags },
361
+ flags: new Map(parent?.flags ?? defaultFlags),
322
362
  breadcrumbs: []
323
363
  };
324
364
  return storage.run(scope, fn);
@@ -337,6 +377,9 @@ function setUser(next) {
337
377
  function setTag(key, value) {
338
378
  putTag(currentScope()?.tags ?? defaultTags, key, value);
339
379
  }
380
+ function addFeatureFlag(name, result) {
381
+ putFlag(currentScope()?.flags ?? defaultFlags, name, result);
382
+ }
340
383
  function removeTag(key) {
341
384
  if (typeof key === "string") delete (currentScope()?.tags ?? defaultTags)[key];
342
385
  }
@@ -401,6 +444,7 @@ function buildPayload(current, description, options) {
401
444
  if (description.type) payload.type = description.type;
402
445
  if (description.stack) payload.stack = relativeStack(description.stack, current.root);
403
446
  if (current.serverName) payload.serverName = current.serverName;
447
+ if (current.frameworks.length > 0) payload.contexts = { frameworks: current.frameworks.map((framework) => ({ ...framework })) };
404
448
  if (request) payload.request = request;
405
449
  if (userAgent) payload.userAgent = userAgent;
406
450
  if (user) {
@@ -411,6 +455,7 @@ function buildPayload(current, description, options) {
411
455
  }
412
456
  if (current.release) payload.release = current.release;
413
457
  if (current.environment) payload.environment = current.environment;
458
+ payload.flags = flagList(scope ? scope.flags : defaultFlags);
414
459
  const tags = scope ? scope.tags : defaultTags;
415
460
  if (Object.keys(tags).length > 0) {
416
461
  payload.tags = {};
@@ -806,6 +851,18 @@ var Bugwatch = {
806
851
  } catch {
807
852
  }
808
853
  },
854
+ /**
855
+ * Records a feature flag the app just evaluated, e.g.
856
+ * `addFeatureFlag("new-checkout", true)`. Inside a request (or `withScope`)
857
+ * only that request's events carry it; outside, every event. The last 100,
858
+ * one per flag (the latest result). Never throws.
859
+ */
860
+ addFeatureFlag(name, result) {
861
+ try {
862
+ addFeatureFlag(name, result);
863
+ } catch {
864
+ }
865
+ },
809
866
  /** Stops sending a tag (in the current request, or everywhere outside one). */
810
867
  removeTag(key) {
811
868
  try {