bugstack-sdk 2.2.2 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +117 -2
  3. package/dist/adapters/express/index.d.mts +2 -2
  4. package/dist/adapters/express/index.d.ts +2 -2
  5. package/dist/adapters/express/index.js +408 -42
  6. package/dist/adapters/express/index.js.map +1 -1
  7. package/dist/adapters/express/index.mjs +408 -42
  8. package/dist/adapters/express/index.mjs.map +1 -1
  9. package/dist/adapters/generic/index.d.mts +2 -2
  10. package/dist/adapters/generic/index.d.ts +2 -2
  11. package/dist/adapters/generic/index.js +456 -42
  12. package/dist/adapters/generic/index.js.map +1 -1
  13. package/dist/adapters/generic/index.mjs +453 -43
  14. package/dist/adapters/generic/index.mjs.map +1 -1
  15. package/dist/adapters/nextjs/index.d.mts +2 -2
  16. package/dist/adapters/nextjs/index.d.ts +2 -2
  17. package/dist/adapters/nextjs/index.js +408 -42
  18. package/dist/adapters/nextjs/index.js.map +1 -1
  19. package/dist/adapters/nextjs/index.mjs +408 -42
  20. package/dist/adapters/nextjs/index.mjs.map +1 -1
  21. package/dist/browser/index.d.mts +131 -0
  22. package/dist/browser/index.d.ts +131 -0
  23. package/dist/browser/index.js +992 -0
  24. package/dist/browser/index.js.map +1 -0
  25. package/dist/browser/index.mjs +984 -0
  26. package/dist/browser/index.mjs.map +1 -0
  27. package/dist/{client-DK_ItP55.d.mts → client-B9WaTEYj.d.mts} +148 -1
  28. package/dist/{client-DK_ItP55.d.ts → client-B9WaTEYj.d.ts} +148 -1
  29. package/dist/index.d.mts +2 -2
  30. package/dist/index.d.ts +2 -2
  31. package/dist/index.js +468 -54
  32. package/dist/index.js.map +1 -1
  33. package/dist/index.mjs +465 -55
  34. package/dist/index.mjs.map +1 -1
  35. package/package.json +17 -7
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/browser/redact.ts","../../src/browser/transport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AA,CAAU,cAAV,IAAA,GAAA,EAAA,GAAuB,IAAA;AAChC","file":"index.mjs","sourcesContent":["// What may leave the page, and in what shape. Every value the SDK records goes\n// through one of these, so the privacy rules live in one file:\n//\n// - a route or request is a PATH: never a query string or a hash (tokens,\n// emails and search terms live there);\n// - an element is a SELECTOR and a short visible LABEL: never an input's,\n// textarea's or password field's value, and never the text of anything\n// editable;\n// - every string is capped.\n\n/** The route the user is on: the path only. */\nexport function currentRoute(loc: Pick<Location, \"pathname\"> = location): string {\n return cap(loc.pathname || \"/\", 300);\n}\n\n/**\n * What a request was to: the path for a same-origin request, host + path for a\n * third-party one. Never the query or the hash.\n */\nexport function requestPath(raw: string, base: Pick<Location, \"href\" | \"origin\"> = location): string {\n try {\n const u = new URL(raw, base.href);\n return cap(u.origin === base.origin ? u.pathname : `${u.host}${u.pathname}`, 300);\n } catch {\n return cap(String(raw).split(/[?#]/)[0] ?? \"\", 300);\n }\n}\n\n/** Whether a URL is the SDK's own endpoint (any query): never recorded. */\nexport function isEndpoint(raw: string, endpoint: string, base: Pick<Location, \"href\"> = location): boolean {\n try {\n const u = new URL(raw, base.href);\n const e = new URL(endpoint, base.href);\n return u.origin === e.origin && u.pathname === e.pathname;\n } catch {\n return false;\n }\n}\n\nexport function cap(s: string, max: number): string {\n return s.length > max ? s.slice(0, max) : s;\n}\n\nconst ACTIONABLE =\n 'button, a[href], [role=\"button\"], input[type=\"submit\"], input[type=\"button\"], input[type=\"reset\"], input[type=\"image\"]';\n\n/** The element a click was meant for: the nearest button-like ancestor, else the target. */\nexport function clickTarget(target: EventTarget | null): Element | null {\n let el: Element | null = null;\n if (target && (target as Node).nodeType === 1) el = target as Element;\n else if (target && (target as Node).nodeType === 3) el = (target as Node).parentElement;\n if (!el) return null;\n return el.closest(ACTIONABLE) ?? el;\n}\n\n/** Whether a click on this element is expected to DO something. */\nexport function isActionable(el: Element): boolean {\n if (!el.matches(ACTIONABLE)) return false;\n if (el.matches(\"a[href]\")) {\n const href = el.getAttribute(\"href\") ?? \"\";\n // A new tab, a download or a mail/phone link changes nothing in this page.\n if (el.getAttribute(\"target\") === \"_blank\" || el.hasAttribute(\"download\")) return false;\n if (/^(mailto|tel|sms):/i.test(href)) return false;\n }\n return !isDisabled(el);\n}\n\nexport function isDisabled(el: Element): boolean {\n return (\n el.hasAttribute(\"disabled\") ||\n el.getAttribute(\"aria-disabled\") === \"true\" ||\n (el as HTMLButtonElement).disabled === true\n );\n}\n\n// A class that looks generated (CSS modules, styled-components) changes on\n// every build, so it is useless in a selector meant to name the same element\n// across sessions.\nfunction stableClass(c: string): boolean {\n if (!/^[A-Za-z_][\\w-]*$/.test(c)) return false;\n if (c.length > 40) return false;\n return !(/\\d/.test(c) && c.length > 8);\n}\n\nfunction escapeIdent(s: string): string {\n return s.replace(/[^\\w-]/g, (ch) => `\\\\${ch}`);\n}\n\n/**\n * A selector that names the same element across sessions: tag, #id,\n * [data-testid] and (on the element only) up to two stable classes, for the\n * element and up to 4 ancestors\n * (stopping at the first id), at most 200 characters.\n */\nexport function selectorFor(el: Element): string {\n const parts: string[] = [];\n let cur: Element | null = el;\n for (let depth = 0; cur && depth < 5; depth++) {\n if (cur.nodeType !== 1 || cur === cur.ownerDocument?.documentElement) break;\n let part = cur.tagName.toLowerCase();\n const id = cur.getAttribute(\"id\");\n if (id && id.length <= 60) part += `#${escapeIdent(id)}`;\n // Classes only on the element itself: an ancestor's classes are often\n // state (`main.dark` / `main.light`) and would split one element in two.\n const classes = depth === 0 ? Array.from(cur.classList ?? []).filter(stableClass).slice(0, 2) : [];\n for (const c of classes) part += `.${c}`;\n const testId = cur.getAttribute(\"data-testid\");\n if (testId) part += `[data-testid=\"${cap(testId, 40).replace(/\"/g, \"\")}\"]`;\n parts.unshift(part);\n if (id) break;\n cur = cur.parentElement;\n }\n return cap(parts.join(\" > \"), 200);\n}\n\nconst SECRET_INPUT = 'input, textarea, select, [contenteditable=\"\"], [contenteditable=\"true\"]';\n\n/**\n * What the element says to the user: its aria-label or title, else its visible\n * text, trimmed to 60 characters. Never a form field's value, and never text\n * from anything editable or anything containing a form field.\n */\nexport function labelFor(el: Element): string | undefined {\n const aria = el.getAttribute(\"aria-label\") ?? el.getAttribute(\"title\");\n if (aria && aria.trim()) return cap(aria.trim().replace(/\\s+/g, \" \"), 60);\n if (el.matches(SECRET_INPUT) || el.querySelector(SECRET_INPUT)) return undefined;\n if ((el as HTMLElement).isContentEditable || el.closest('[contenteditable=\"\"], [contenteditable=\"true\"]')) {\n return undefined;\n }\n const raw = (el as HTMLElement).innerText ?? el.textContent ?? \"\";\n const text = String(raw).trim().replace(/\\s+/g, \" \");\n return text ? cap(text, 60) : undefined;\n}\n\nexport function describeElement(el: Element): { selector: string; label?: string } {\n const label = labelFor(el);\n return label ? { selector: selectorFor(el), label } : { selector: selectorFor(el) };\n}\n\n/**\n * A form field as it may leave the page: its selector, and a label from its\n * aria-label, its <label>, its placeholder or its name attribute, in that\n * order. Never its value. Pure over the DOM.\n */\nexport function describeField(el: Element): { selector: string; label?: string } {\n const selector = selectorFor(el);\n let label: string | null = el.getAttribute(\"aria-label\");\n if (!label) {\n const id = el.getAttribute(\"id\");\n const doc = el.ownerDocument;\n const forLabel = id && doc ? doc.querySelector(`label[for=\"${id.replace(/[\"\\\\]/g, \"\")}\"]`) : null;\n const wrapping = el.closest(\"label\");\n const source = forLabel ?? wrapping;\n if (source) {\n // The label's own text, with any field inside it left out.\n const clone = source.cloneNode(true) as Element;\n for (const f of Array.from(clone.querySelectorAll(SECRET_INPUT))) f.remove();\n label = clone.textContent;\n }\n }\n if (!label) label = el.getAttribute(\"placeholder\") ?? el.getAttribute(\"name\");\n const t = label ? label.trim().replace(/\\s+/g, \" \") : \"\";\n return t ? { selector, label: cap(t, 60) } : { selector };\n}\n\n/** A form as it may leave the page: its selector, labelled by its submit control. */\nexport function describeForm(form: Element): { selector: string; label?: string } {\n const selector = selectorFor(form);\n const submit = form.querySelector('button[type=\"submit\"], button:not([type]), input[type=\"submit\"]');\n let label: string | undefined = form.getAttribute(\"aria-label\")?.trim() || undefined;\n if (!label && submit) {\n label = submit.matches(\"input\") ? (submit.getAttribute(\"value\") ?? undefined) : labelFor(submit);\n }\n return label ? { selector, label: cap(label.trim().replace(/\\s+/g, \" \"), 60) } : { selector };\n}\n\n/**\n * Whether the page now showing says it does not exist: Next.js marks a\n * not-found page with <meta name=\"next-error\" content=\"not-found\">; any\n * framework's default 404 has a title starting \"404\". Pure over the DOM.\n */\nexport function isNotFoundPage(doc: Document = document): boolean {\n try {\n if (doc.querySelector('meta[name=\"next-error\"][content=\"not-found\"]')) return true;\n return /^\\s*404\\b/.test(doc.title ?? \"\");\n } catch {\n return false;\n }\n}\n","// Batching and sending. A batch is at most 100 events and 64 KB (the most a\n// keepalive fetch or a beacon will carry). Sends go through the page's\n// ORIGINAL fetch, captured before the SDK wraps it, so the SDK never records\n// or counts its own traffic.\n//\n// 2xx sent\n// 429 backed off (10 s, doubling to 5 min), the batch kept\n// 401 / 403 the key is wrong for this page: stop sending for the page\n// 400 / 413 the server will never read this batch: dropped\n// other kept and retried, at most 3 times\n//\n// On page hide the queue goes out by navigator.sendBeacon, which cannot set\n// headers, so a beacon carries the key as `?key=` on the URL.\n\nimport type { SessionBatch, SessionEvent, SessionUser } from \"./types.js\";\n\nexport const MAX_EVENTS_PER_BATCH = 100;\nexport const MAX_BATCH_BYTES = 64 * 1024;\n/** The most events held while sending is impossible (offline, backed off). */\nexport const MAX_QUEUED_EVENTS = 500;\nconst MAX_ATTEMPTS = 3;\n\nexport function byteLength(s: string): number {\n try {\n return new TextEncoder().encode(s).length;\n } catch {\n return s.length * 3;\n }\n}\n\nexport type BatchEnvelope = Omit<SessionBatch, \"events\">;\n\n/**\n * Take the next batch off the front of `queue`: as many events as fit in 100\n * and 64 KB. An event that cannot fit even alone is dropped. Pure on its inputs\n * (mutates `queue` by removing what it takes).\n */\nexport function takeBatch(queue: SessionEvent[], envelope: BatchEnvelope): SessionBatch | null {\n const events: SessionEvent[] = [];\n const overhead = byteLength(JSON.stringify({ ...envelope, events: [] }));\n let bytes = overhead;\n while (queue.length > 0 && events.length < MAX_EVENTS_PER_BATCH) {\n const next = queue[0]!;\n const size = byteLength(JSON.stringify(next)) + 1;\n if (bytes + size > MAX_BATCH_BYTES) {\n if (events.length === 0) {\n queue.shift(); // cannot fit even alone\n continue;\n }\n break;\n }\n events.push(next);\n bytes += size;\n queue.shift();\n }\n return events.length > 0 ? { ...envelope, events } : null;\n}\n\nexport type TransportDeps = {\n endpoint: string;\n key: string;\n fetchImpl: typeof fetch | undefined;\n beacon: ((url: string, body: string) => boolean) | undefined;\n now: () => number;\n};\n\nexport class Transport {\n private queue: SessionEvent[] = [];\n private stopped = false;\n private backoffMs = 0;\n private notBefore = 0;\n private inFlight = false;\n private attempts = 0;\n\n constructor(\n private readonly deps: TransportDeps,\n private readonly envelope: () => BatchEnvelope,\n ) {}\n\n get isStopped(): boolean {\n return this.stopped;\n }\n\n get size(): number {\n return this.queue.length;\n }\n\n push(event: SessionEvent): void {\n if (this.stopped) return;\n this.queue.push(event);\n if (this.queue.length > MAX_QUEUED_EVENTS) this.queue.splice(0, this.queue.length - MAX_QUEUED_EVENTS);\n }\n\n /** Send one batch by fetch, when allowed. Never rejects. */\n async flush(): Promise<void> {\n if (this.stopped || this.inFlight || this.queue.length === 0) return;\n if (this.deps.now() < this.notBefore) return;\n const fetchImpl = this.deps.fetchImpl;\n if (!fetchImpl) return;\n const batch = takeBatch(this.queue, this.envelope());\n if (!batch) return;\n this.inFlight = true;\n try {\n const res = await fetchImpl(this.deps.endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"X-BugStack-Key\": this.deps.key },\n body: JSON.stringify(batch),\n keepalive: true,\n credentials: \"omit\",\n });\n this.settle(res.status, batch.events);\n } catch {\n this.retry(batch.events);\n } finally {\n this.inFlight = false;\n }\n }\n\n /** On page hide: everything left, by beacon (falls back to keepalive fetch). */\n flushOnHide(): void {\n if (this.stopped) return;\n while (this.queue.length > 0) {\n const batch = takeBatch(this.queue, this.envelope());\n if (!batch) return;\n const body = JSON.stringify(batch);\n const url = beaconUrl(this.deps.endpoint, this.deps.key);\n let sent = false;\n try {\n sent = this.deps.beacon ? this.deps.beacon(url, body) : false;\n } catch {\n sent = false;\n }\n if (!sent && this.deps.fetchImpl) {\n try {\n void this.deps\n .fetchImpl(this.deps.endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"X-BugStack-Key\": this.deps.key },\n body,\n keepalive: true,\n credentials: \"omit\",\n })\n .catch(() => {});\n } catch {\n /* the page is going away */\n }\n }\n }\n }\n\n stop(): void {\n this.stopped = true;\n this.queue = [];\n }\n\n private settle(status: number, events: SessionEvent[]): void {\n if (status >= 200 && status < 300) {\n this.backoffMs = 0;\n this.attempts = 0;\n return;\n }\n if (status === 401 || status === 403) {\n this.stop();\n return;\n }\n if (status === 429) {\n this.backoffMs = this.backoffMs === 0 ? 10_000 : Math.min(this.backoffMs * 2, 300_000);\n this.notBefore = this.deps.now() + this.backoffMs;\n this.queue.unshift(...events);\n return;\n }\n if (status === 400 || status === 413) return;\n this.retry(events);\n }\n\n private retry(events: SessionEvent[]): void {\n this.attempts += 1;\n if (this.attempts >= MAX_ATTEMPTS) {\n this.attempts = 0;\n return; // dropped\n }\n this.queue.unshift(...events);\n if (this.queue.length > MAX_QUEUED_EVENTS) this.queue.length = MAX_QUEUED_EVENTS;\n }\n}\n\nexport function beaconUrl(endpoint: string, key: string): string {\n return `${endpoint}${endpoint.includes(\"?\") ? \"&\" : \"?\"}key=${encodeURIComponent(key)}`;\n}\n\nexport function envelopeFor(input: {\n sessionId: string;\n user: SessionUser | null;\n release?: string;\n environment?: string;\n}): BatchEnvelope {\n const env: BatchEnvelope = { v: 1, sessionId: input.sessionId };\n if (input.user && (input.user.id || input.user.email)) env.user = input.user;\n if (input.release) env.release = input.release;\n if (input.environment) env.environment = input.environment;\n return env;\n}\n","// The session recorder: what a user actually hit in this page. Ported from\n// the Bugstack monorepo's packages/browser-sdk (MIT), plus frustration signals.\n//\n// error window `error` / `unhandledrejection`, and captureError()\n// failed_request fetch / XHR answered 5xx or not at all\n// navigation the first page and every route change\n//\n// Frustration signals, only with `frustration` set (OFF by default):\n//\n// rage_click 3+ clicks on one element within 1 s (one event per burst)\n// dead_click a click on something button-like that, within 1 s, caused\n// no navigation, no request and no DOM change; or a link\n// that navigated to a page saying it does not exist\n// error_click a click followed within 1 s by an uncaught error\n// form_abandon a form whose submit hit a validation error (a native\n// `invalid`, or aria-invalid / role=\"alert\" after submit),\n// then left without a submit that passed\n// thrash 4+ route changes within 10 s alternating between two routes\n//\n// Frustration is sampled (frustration.sampleRate, once per session) and\n// capped per page view (frustration.maxPerPage). Nothing records an input's\n// value or text beyond a 60-character element label (redact.ts).\n//\n// THE ONE RULE: the SDK must never hurt the page it watches. Every handler is\n// wrapped, nothing it does throws into the host, and the fetch / XHR wrappers\n// hand back the same Response and re-throw the same errors.\n\nimport {\n clickTarget,\n currentRoute,\n describeElement,\n describeField,\n describeForm,\n isActionable,\n isEndpoint,\n isNotFoundPage,\n requestPath,\n cap,\n} from \"./redact.js\";\nimport { Transport, envelopeFor } from \"./transport.js\";\nimport type { BrowserConfig, ElementRef, SessionEvent, SessionUser } from \"./types.js\";\n\nexport const DEFAULT_ENDPOINT = \"https://dashboard.bugstack.ai/api/v1/sessions/ingest\";\n\n/** How long after a click the page has to react, and the rage-click window. */\nexport const CLICK_WINDOW_MS = 1000;\nexport const RAGE_CLICKS = 3;\nconst FLUSH_INTERVAL_MS = 5000;\n\n// A broken page can throw the same error in a loop; one session must not flood.\nconst MAX_SAME_EVENT = 5;\nconst MAX_ERRORS_PER_PAGE = 100;\n\nconst SESSION_KEY = \"bugstack.session\";\nconst SAMPLED_KEY = \"bugstack.sampled\";\nconst FRUSTRATION_SAMPLED_KEY = \"bugstack.frustration\";\n/** The last link clicked, for a not-found check on the NEXT page (a framework may reload for a 404). */\nconst LAST_LINK_KEY = \"bugstack.lastLink\";\n\n/** Thrashing: route changes alternating between two routes within this window. */\nexport const THRASH_WINDOW_MS = 10_000;\nexport const THRASH_SWITCHES = 4;\nexport const DEFAULT_FRUSTRATION_PER_PAGE = 20;\nconst MAX_INVALID_FIELDS = 5;\nconst FIELD = \"input, select, textarea\";\n\n/** Whether this session records frustration: the config, then a once-per-session sample. */\nexport function frustrationFor(config: BrowserConfig): { on: boolean; maxPerPage: number } {\n const f = config.frustration;\n const off = { on: false, maxPerPage: 0 };\n if (!f) return off;\n const obj = typeof f === \"object\" ? f : {};\n if (obj.enabled === false) return off;\n const maxPerPage =\n typeof obj.maxPerPage === \"number\" && obj.maxPerPage >= 1 ? Math.min(100, Math.floor(obj.maxPerPage)) : DEFAULT_FRUSTRATION_PER_PAGE;\n const rate = typeof obj.sampleRate === \"number\" && Number.isFinite(obj.sampleRate) ? Math.min(1, Math.max(0, obj.sampleRate)) : 1;\n if (rate >= 1) return { on: true, maxPerPage };\n let storage: Storage | null = null;\n try {\n storage = window.sessionStorage;\n } catch {\n storage = null;\n }\n let raw = storage?.getItem(FRUSTRATION_SAMPLED_KEY) ?? null;\n if (raw !== \"1\" && raw !== \"0\") {\n raw = Math.random() < rate ? \"1\" : \"0\";\n try {\n storage?.setItem(FRUSTRATION_SAMPLED_KEY, raw);\n } catch {\n /* private mode */\n }\n }\n return { on: raw === \"1\", maxPerPage };\n}\n\nfunction safe(fn: () => void): void {\n try {\n fn();\n } catch {\n /* never into the host page */\n }\n}\n\nfunction randomId(): string {\n const bytes = new Uint8Array(12);\n try {\n crypto.getRandomValues(bytes);\n } catch {\n for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);\n }\n return `s_${Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nconst SESSION_ID_RE = /^[A-Za-z0-9_-]{8,64}$/;\n\n/** This browser session's id and whether it is recorded at all (sampleRate). */\nexport function sessionFor(sampleRate: number): { sessionId: string; sampled: boolean } {\n let storage: Storage | null = null;\n try {\n storage = window.sessionStorage;\n } catch {\n storage = null;\n }\n let sessionId = storage?.getItem(SESSION_KEY) ?? null;\n let sampledRaw = storage?.getItem(SAMPLED_KEY) ?? null;\n if (!sessionId || !SESSION_ID_RE.test(sessionId)) {\n sessionId = randomId();\n sampledRaw = null;\n try {\n storage?.setItem(SESSION_KEY, sessionId);\n } catch {\n /* private mode */\n }\n }\n if (sampledRaw !== \"1\" && sampledRaw !== \"0\") {\n const rate = Number.isFinite(sampleRate) ? Math.min(1, Math.max(0, sampleRate)) : 1;\n sampledRaw = Math.random() < rate ? \"1\" : \"0\";\n try {\n storage?.setItem(SAMPLED_KEY, sampledRaw);\n } catch {\n /* private mode */\n }\n }\n return { sessionId, sampled: sampledRaw === \"1\" };\n}\n\nfunction nowIso(): string {\n return new Date().toISOString();\n}\n\nfunction errorShape(err: unknown): { name: string; message: string; stack?: string } {\n if (err instanceof Error || (err && typeof err === \"object\" && \"message\" in (err as object))) {\n const e = err as Error;\n const out: { name: string; message: string; stack?: string } = {\n name: cap(String(e.name || \"Error\"), 200),\n message: cap(String(e.message ?? \"\"), 1000),\n };\n if (typeof e.stack === \"string\" && e.stack) out.stack = cap(e.stack, 8000);\n return out;\n }\n let message: string;\n try {\n message = typeof err === \"string\" ? err : JSON.stringify(err) ?? String(err);\n } catch {\n message = String(err);\n }\n return { name: \"UnhandledRejection\", message: cap(message, 1000) };\n}\n\n// The SDK's own code never throws into the page (every handler is wrapped),\n// so the only error it could cause is one raised in its own unbundled file.\n// Matched on the ErrorEvent's filename only: a stack that merely PASSES through\n// the fetch wrapper (an app's failed request it re-throws) is the app's error.\nconst OWN_FILE = /[/\\\\](?:@bugstack[/\\\\]browser|bugstack-sdk[/\\\\]dist[/\\\\]browser)[/\\\\]/i;\n\ntype Patched = { restore: () => void };\n\nexport class SessionRecorder {\n private readonly transport: Transport;\n private user: SessionUser | null = null;\n private readonly patches: Patched[] = [];\n private readonly listeners: Array<() => void> = [];\n private observer: MutationObserver | null = null;\n private flushTimer: ReturnType<typeof setInterval> | null = null;\n private activity = 0;\n private lastRoute: string | null = null;\n private readonly seen = new Map<string, number>();\n private errorsThisPage = 0;\n private readonly clickHistory = new Map<\n Element,\n { times: number[]; burst: number; startedAt: number; timer: ReturnType<typeof setTimeout> | null }\n >();\n private readonly deadReportedAt = new WeakMap<Element, number>();\n // Frustration (OFF unless config.frustration).\n private readonly frustration: boolean;\n private readonly maxFrustrationPerPage: number;\n private frustrationThisPage = 0;\n private lastClick: { el: Element; at: number; route: string; errored: boolean } | null = null;\n private pendingLink: { el: Element; at: number; route: string } | null = null;\n private readonly forms = new Map<\n Element,\n { route: string; fields: Map<string, ElementRef>; attempts: number; lastAttemptAt: number; submittedAt: number }\n >();\n private navTrail: Array<{ route: string; at: number }> = [];\n private readonly thrashReported = new Set<string>();\n /** Elements whose click already became an error click: never also a dead click. */\n private readonly errorClicked = new WeakSet<Element>();\n private unloading = false;\n private closed = false;\n readonly endpoint: string;\n\n constructor(\n config: BrowserConfig,\n readonly sessionId: string,\n ) {\n this.endpoint = config.endpoint || DEFAULT_ENDPOINT;\n const fr = frustrationFor(config);\n this.frustration = fr.on;\n this.maxFrustrationPerPage = fr.maxPerPage;\n const fetchImpl = typeof window.fetch === \"function\" ? window.fetch.bind(window) : undefined;\n const beacon =\n typeof navigator !== \"undefined\" && typeof navigator.sendBeacon === \"function\"\n ? (url: string, body: string) => navigator.sendBeacon(url, body)\n : undefined;\n this.transport = new Transport(\n { endpoint: this.endpoint, key: config.key, fetchImpl, beacon, now: () => Date.now() },\n () =>\n envelopeFor({\n sessionId: this.sessionId,\n user: this.user,\n release: config.release,\n environment: config.environment,\n }),\n );\n }\n\n /** For tests and flush(): the transport. */\n get queue(): Transport {\n return this.transport;\n }\n\n install(): void {\n this.listen(window, \"error\", (ev) => this.onError(ev as ErrorEvent));\n this.listen(window, \"unhandledrejection\", (ev) =>\n this.recordError((ev as PromiseRejectionEvent).reason),\n );\n this.listen(document, \"click\", (ev) => this.onClick(ev as MouseEvent), true);\n this.listen(window, \"popstate\", () => this.onNavigation());\n this.listen(window, \"hashchange\", () => this.onNavigation());\n this.listen(window, \"pagehide\", () => {\n this.unloading = true;\n this.flushForms();\n this.onHide();\n });\n if (this.frustration) {\n this.listen(document, \"invalid\", (ev) => this.onInvalid(ev.target), true);\n this.listen(document, \"submit\", (ev) => this.onSubmit(ev.target), true);\n }\n this.listen(window, \"beforeunload\", () => {\n this.unloading = true;\n });\n // A page restored from the back/forward cache is alive again.\n this.listen(window, \"pageshow\", () => {\n this.unloading = false;\n });\n this.listen(document, \"visibilitychange\", () => {\n if (document.visibilityState === \"hidden\") this.onHide();\n });\n this.patchFetch();\n this.patchXhr();\n this.patchHistory();\n safe(() => {\n // The observer only serves the dead-click check: no frustration, no observer.\n if (this.frustration && typeof MutationObserver === \"function\") {\n this.observer = new MutationObserver(() => {\n this.activity++;\n });\n this.observer.observe(document.documentElement, {\n subtree: true,\n childList: true,\n attributes: true,\n characterData: true,\n });\n }\n });\n this.flushTimer = setInterval(() => void this.flush(), FLUSH_INTERVAL_MS);\n this.onNavigation(true);\n }\n\n setUser(user: SessionUser | null): void {\n if (!user) {\n this.user = null;\n return;\n }\n const next: SessionUser = {};\n if (typeof user.id === \"string\" && user.id.trim()) next.id = cap(user.id.trim(), 200);\n else if (typeof user.id === \"number\") next.id = String(user.id);\n if (typeof user.email === \"string\" && user.email.trim()) next.email = cap(user.email.trim(), 320);\n this.user = next.id || next.email ? next : null;\n }\n\n captureError(err: unknown): void {\n this.recordError(err);\n }\n\n flush(): Promise<void> {\n return this.transport.flush();\n }\n\n close(): void {\n if (this.closed) return;\n this.closed = true;\n safe(() => this.transport.flushOnHide());\n for (const off of this.listeners.splice(0)) safe(off);\n for (const p of this.patches.splice(0)) safe(p.restore);\n safe(() => this.observer?.disconnect());\n if (this.flushTimer) clearInterval(this.flushTimer);\n for (const h of this.clickHistory.values()) if (h.timer) clearTimeout(h.timer);\n // Pending dead-click checks see `closed` and stand down.\n this.clickHistory.clear();\n }\n\n // --- recording -----------------------------------------------------------\n\n private push(event: SessionEvent, dedupeKey?: string): void {\n if (this.closed) return;\n if (dedupeKey) {\n const n = (this.seen.get(dedupeKey) ?? 0) + 1;\n this.seen.set(dedupeKey, n);\n if (n > MAX_SAME_EVENT) return;\n }\n this.transport.push(event);\n if (this.transport.size >= 100) void this.flush();\n }\n\n private onError(ev: ErrorEvent): void {\n safe(() => {\n // A resource that failed to load is not a script error.\n if (!ev || typeof ev.message !== \"string\") return;\n // A cross-origin script hides everything but this.\n if (ev.message === \"Script error.\" && !ev.filename && !ev.error) return;\n if (ev.filename && OWN_FILE.test(ev.filename)) return;\n this.recordError(ev.error ?? { name: \"Error\", message: ev.message });\n });\n }\n\n private recordError(err: unknown): void {\n safe(() => {\n const error = errorShape(err);\n if (this.errorsThisPage >= MAX_ERRORS_PER_PAGE) return;\n this.errorsThisPage++;\n const route = currentRoute();\n this.push({ kind: \"error\", at: nowIso(), route, error }, `error:${error.name}:${error.message}:${route}`);\n // A click followed by an uncaught error: the click's element is the lead.\n const c = this.lastClick;\n if (this.frustration && c && !c.errored && Date.now() - c.at <= CLICK_WINDOW_MS) {\n c.errored = true;\n this.errorClicked.add(c.el);\n const element = describeElement(c.el);\n this.pushFrustration(\n {\n kind: \"error_click\",\n at: new Date(c.at).toISOString(),\n route: c.route,\n element,\n error: { name: error.name, message: cap(error.message, 200) },\n },\n `error_click:${c.route}:${element.selector}:${error.name}`,\n );\n }\n });\n }\n\n /** A frustration event: only when recording frustration, at most maxPerPage a page view. */\n private pushFrustration(event: SessionEvent, dedupeKey: string): void {\n if (!this.frustration || this.frustrationThisPage >= this.maxFrustrationPerPage) return;\n this.frustrationThisPage++;\n this.push(event, dedupeKey);\n }\n\n // --- forms ---------------------------------------------------------------\n\n private formState(form: Element) {\n let st = this.forms.get(form);\n if (!st) {\n st = { route: currentRoute(), fields: new Map(), attempts: 0, lastAttemptAt: 0, submittedAt: 0 };\n this.forms.set(form, st);\n }\n return st;\n }\n\n private addFields(st: { fields: Map<string, ElementRef> }, fields: Element[]): void {\n for (const f of fields) {\n if (st.fields.size >= MAX_INVALID_FIELDS) return;\n const d = describeField(f);\n if (!st.fields.has(d.selector)) st.fields.set(d.selector, d);\n }\n }\n\n /** A native validation failure: one `invalid` per bad field, one attempt per submit. */\n private onInvalid(target: EventTarget | null): void {\n safe(() => {\n const field = target && (target as Node).nodeType === 1 ? (target as Element) : null;\n if (!field || !field.matches(FIELD)) return;\n const form = (field as HTMLInputElement).form ?? field.closest(\"form\");\n if (!form) return;\n const st = this.formState(form);\n const now = Date.now();\n if (now - st.lastAttemptAt > 250) st.attempts++;\n st.lastAttemptAt = now;\n this.addFields(st, [field]);\n });\n }\n\n /**\n * A submit that native validation let through: the app's own validation\n * may still reject it. Within the click window, a field marked\n * aria-invalid (or :invalid under novalidate) or a non-empty role=\"alert\"\n * in the form is a failed attempt; neither is a submit that passed.\n */\n private onSubmit(target: EventTarget | null): void {\n safe(() => {\n const form = target && (target as Node).nodeType === 1 ? (target as Element) : null;\n if (!form || !form.matches(\"form\")) return;\n const route = currentRoute();\n // A submit that leaves the page before the check runs passed (flushForms).\n const pending = this.forms.get(form);\n if (pending) pending.submittedAt = Date.now();\n setTimeout(() => {\n safe(() => {\n if (this.closed || this.unloading) return;\n if (!form.isConnected || currentRoute() !== route) {\n this.forms.delete(form);\n return;\n }\n const bad = Array.from(form.querySelectorAll('[aria-invalid=\"true\"], :invalid')).filter((el) => el.matches(FIELD));\n const alert = Array.from(form.querySelectorAll('[role=\"alert\"]')).some((el) => (el.textContent ?? \"\").trim() !== \"\");\n if (bad.length === 0 && !alert) {\n this.forms.delete(form);\n return;\n }\n const st = this.formState(form);\n st.attempts++;\n st.lastAttemptAt = Date.now();\n this.addFields(st, bad);\n });\n }, CLICK_WINDOW_MS);\n });\n }\n\n /** The page is being left: every form whose submit failed and never passed was abandoned. */\n private flushForms(): void {\n safe(() => {\n const now = Date.now();\n for (const [form, st] of this.forms) {\n if (st.attempts === 0) continue;\n // Left right after a submit native validation let through: the submit\n // navigated, which is what a submit that passed does.\n if (st.submittedAt > st.lastAttemptAt && now - st.submittedAt <= CLICK_WINDOW_MS) continue;\n const element = describeForm(form);\n this.pushFrustration(\n { kind: \"form_abandon\", at: nowIso(), route: st.route, element, fields: [...st.fields.values()], attempts: Math.min(100, st.attempts) },\n `form_abandon:${st.route}:${element.selector}`,\n );\n }\n this.forms.clear();\n });\n }\n\n // --- thrashing and dead links --------------------------------------------\n\n private onRouteChange(route: string, initial: boolean): void {\n if (!this.frustration) return;\n const now = Date.now();\n this.navTrail = this.navTrail.filter((n) => now - n.at <= THRASH_WINDOW_MS).slice(-8);\n this.navTrail.push({ route, at: now });\n if (!initial) {\n const r = this.navTrail.map((n) => n.route);\n let switches = 1;\n for (let i = r.length - 1; i >= 2 && r[i] === r[i - 2] && r[i] !== r[i - 1]; i--) switches++;\n if (switches + 1 >= THRASH_SWITCHES) {\n const pair = [r[r.length - 1]!, r[r.length - 2]!] as [string, string];\n const key = [...pair].sort().join(\"\\u0000\");\n if (!this.thrashReported.has(key)) {\n this.thrashReported.add(key);\n this.pushFrustration({ kind: \"thrash\", at: nowIso(), route, routes: pair, switches: switches + 1 }, `thrash:${key}`);\n }\n }\n }\n // A link whose click reloaded the page (Next.js does for a 404): the\n // previous page left it in sessionStorage.\n if (initial) {\n let stored: { at?: unknown; route?: unknown; element?: unknown } | null = null;\n try {\n const raw = window.sessionStorage.getItem(LAST_LINK_KEY);\n window.sessionStorage.removeItem(LAST_LINK_KEY);\n stored = raw ? JSON.parse(raw) : null;\n } catch {\n stored = null;\n }\n const e = stored?.element as ElementRef | undefined;\n if (\n stored && typeof stored.at === \"number\" && now - stored.at <= 5 * CLICK_WINDOW_MS &&\n typeof stored.route === \"string\" && stored.route !== route && e && typeof e.selector === \"string\"\n ) {\n const from = stored.route;\n const at = stored.at;\n const element: ElementRef = e.label ? { selector: cap(e.selector, 200), label: cap(String(e.label), 60) } : { selector: cap(e.selector, 200) };\n setTimeout(() => {\n safe(() => {\n if (this.closed || this.unloading || currentRoute() !== route || !isNotFoundPage()) return;\n this.pushFrustration(\n { kind: \"dead_click\", at: new Date(at).toISOString(), route: from, element, reason: \"not_found\", to: route },\n `dead:${from}:${element.selector}:not_found`,\n );\n });\n }, CLICK_WINDOW_MS);\n }\n return;\n }\n // A link that navigated to a page saying it does not exist.\n try {\n window.sessionStorage.removeItem(LAST_LINK_KEY);\n } catch {\n /* private mode */\n }\n const link = this.pendingLink;\n this.pendingLink = null;\n if (!initial && link && now - link.at <= 2 * CLICK_WINDOW_MS) {\n setTimeout(() => {\n safe(() => {\n if (this.closed || this.unloading || currentRoute() !== route || !isNotFoundPage()) return;\n const element = describeElement(link.el);\n this.pushFrustration(\n { kind: \"dead_click\", at: new Date(link.at).toISOString(), route: link.route, element, reason: \"not_found\", to: route },\n `dead:${link.route}:${element.selector}:not_found`,\n );\n });\n }, CLICK_WINDOW_MS);\n }\n }\n\n private recordFailedRequest(method: string, url: string, status: number | null, started: number): void {\n safe(() => {\n const path = requestPath(url);\n const route = currentRoute();\n this.push(\n {\n kind: \"failed_request\",\n at: nowIso(),\n route,\n request: { method: cap(method.toUpperCase(), 10), path, status, durationMs: Math.max(0, Date.now() - started) },\n },\n `request:${method}:${path}:${status}`,\n );\n });\n }\n\n private onNavigation(initial = false): void {\n safe(() => {\n this.activity++;\n const route = currentRoute();\n if (!initial && route === this.lastRoute) return;\n if (!initial) this.flushForms();\n this.lastRoute = route;\n this.frustrationThisPage = 0;\n this.push({ kind: \"navigation\", at: nowIso(), route });\n this.onRouteChange(route, initial);\n });\n }\n\n private onHide(): void {\n safe(() => {\n // Hiding the page is a reaction to a click (a new tab, a download, a\n // dialog in another window): never a dead click.\n this.activity++;\n this.transport.flushOnHide();\n });\n }\n\n // --- clicks --------------------------------------------------------------\n\n private onClick(ev: MouseEvent): void {\n safe(() => {\n const el = clickTarget(ev.target);\n if (!el) return;\n const now = Date.now();\n const route = currentRoute();\n // Every click below is frustration-only.\n if (!this.frustration) return;\n this.lastClick = { el, at: now, route, errored: false };\n if (el.matches(\"a[href]\")) {\n this.pendingLink = { el, at: now, route };\n try {\n window.sessionStorage.setItem(LAST_LINK_KEY, JSON.stringify({ at: now, route, element: describeElement(el) }));\n } catch {\n /* private mode */\n }\n }\n const h = this.clickHistory.get(el) ?? { times: [], burst: 0, startedAt: now, timer: null };\n h.times = h.times.filter((t) => now - t < CLICK_WINDOW_MS);\n h.times.push(now);\n this.clickHistory.set(el, h);\n\n if (h.burst > 0 || h.times.length >= RAGE_CLICKS) {\n // A burst: every click until the user stops for a second is part of\n // it, and the burst is ONE rage_click counting them all.\n if (h.burst === 0) {\n h.burst = h.times.length;\n h.startedAt = h.times[0] ?? now;\n } else {\n h.burst += 1;\n }\n if (h.timer) clearTimeout(h.timer);\n h.timer = setTimeout(() => {\n safe(() => {\n const clicks = h.burst;\n const at = new Date(h.startedAt).toISOString();\n h.burst = 0;\n h.times = [];\n h.timer = null;\n const element = describeElement(el);\n this.pushFrustration({ kind: \"rage_click\", at, route, element, clicks }, `rage:${route}:${element.selector}`);\n });\n }, CLICK_WINDOW_MS);\n return;\n }\n\n if (!isActionable(el)) return;\n const before = this.activity;\n setTimeout(() => {\n safe(() => {\n if (this.closed || this.unloading) return;\n // Part of a rage burst: that is the event, not this.\n if (h.burst > 0) return;\n if (this.activity !== before) return;\n if (!el.isConnected) return;\n // A control already in the state it selects (the active filter, the\n // current tab or page) does nothing when clicked, by design.\n if (el.matches('[aria-pressed=\"true\"], [aria-selected=\"true\"], [aria-checked=\"true\"], [aria-current]:not([aria-current=\"false\"])')) return;\n // A click that threw is an error click, not a dead one.\n if (this.errorClicked.has(el)) return;\n // Resubmitting a form whose validation already failed is the form's\n // abandon story, not a dead button.\n const form = el.closest(\"form\");\n if (form && el.matches('button[type=\"submit\"], button:not([type]), input[type=\"submit\"]') && (this.forms.get(form)?.attempts ?? 0) > 0) return;\n // A double-click on a dead button is one dead button.\n const last = this.deadReportedAt.get(el) ?? 0;\n if (Date.now() - last < 5 * CLICK_WINDOW_MS) return;\n this.deadReportedAt.set(el, Date.now());\n const element = describeElement(el);\n this.pushFrustration(\n { kind: \"dead_click\", at: new Date(now).toISOString(), route, element },\n `dead:${route}:${element.selector}`,\n );\n });\n }, CLICK_WINDOW_MS);\n });\n }\n\n // --- patches -------------------------------------------------------------\n\n private listen(target: EventTarget, type: string, fn: (ev: Event) => void, capture = false): void {\n const handler = (ev: Event) => safe(() => fn(ev));\n target.addEventListener(type, handler, capture);\n this.listeners.push(() => target.removeEventListener(type, handler, capture));\n }\n\n private patchFetch(): void {\n if (typeof window.fetch !== \"function\") return;\n const original = window.fetch;\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n const wrapped = function (this: unknown, input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n let method = \"GET\";\n let url = \"\";\n try {\n method = String(init?.method ?? (typeof Request !== \"undefined\" && input instanceof Request ? input.method : \"GET\"));\n url = typeof input === \"string\" ? input : input instanceof URL ? input.href : (input as Request).url;\n } catch {\n /* recorded as best it can be */\n }\n const own = isEndpoint(url, self.endpoint);\n if (!own) self.activity++;\n const started = Date.now();\n // eslint-disable-next-line prefer-rest-params\n const result = original.apply(this ?? window, arguments as unknown as [RequestInfo | URL, RequestInit?]);\n if (own) return result;\n return result.then(\n (res) => {\n safe(() => {\n if (res && res.status >= 500) self.recordFailedRequest(method, url, res.status, started);\n });\n return res;\n },\n (err: unknown) => {\n safe(() => {\n if (!(err && (err as { name?: string }).name === \"AbortError\")) {\n self.recordFailedRequest(method, url, null, started);\n }\n });\n throw err;\n },\n );\n };\n window.fetch = wrapped as typeof fetch;\n this.patches.push({\n restore: () => {\n if (window.fetch === (wrapped as typeof fetch)) window.fetch = original;\n },\n });\n }\n\n private patchXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") return;\n const proto = XMLHttpRequest.prototype;\n const originalOpen = proto.open;\n const originalSend = proto.send;\n const info = new WeakMap<XMLHttpRequest, { method: string; url: string }>();\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n proto.open = function (this: XMLHttpRequest, method: string, url: string | URL) {\n safe(() => info.set(this, { method: String(method), url: String(url) }));\n // eslint-disable-next-line prefer-rest-params\n return originalOpen.apply(this, arguments as unknown as Parameters<typeof originalOpen>);\n } as typeof proto.open;\n proto.send = function (this: XMLHttpRequest) {\n safe(() => {\n const req = info.get(this);\n if (!req || isEndpoint(req.url, self.endpoint)) return;\n self.activity++;\n const started = Date.now();\n let aborted = false;\n this.addEventListener(\"abort\", () => {\n aborted = true;\n });\n this.addEventListener(\"loadend\", () => {\n safe(() => {\n if (aborted) return;\n if (this.status === 0) self.recordFailedRequest(req.method, req.url, null, started);\n else if (this.status >= 500) self.recordFailedRequest(req.method, req.url, this.status, started);\n });\n });\n });\n // eslint-disable-next-line prefer-rest-params\n return originalSend.apply(this, arguments as unknown as Parameters<typeof originalSend>);\n };\n this.patches.push({\n restore: () => {\n proto.open = originalOpen;\n proto.send = originalSend;\n },\n });\n }\n\n private patchHistory(): void {\n const h = window.history;\n if (!h) return;\n for (const name of [\"pushState\", \"replaceState\"] as const) {\n const original = h[name];\n if (typeof original !== \"function\") continue;\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n const wrapped = function (this: History, ...args: Parameters<History[\"pushState\"]>) {\n const out = original.apply(this, args);\n self.onNavigation();\n return out;\n };\n h[name] = wrapped;\n this.patches.push({\n restore: () => {\n if (h[name] === wrapped) h[name] = original;\n },\n });\n }\n }\n}\n","// bugstack-sdk/browser — what your users actually hit in the browser, as\n// evidence Bugstack can fix from: uncaught errors, failed requests and the\n// route trail, and, when you opt in, frustration signals (rage clicks, dead\n// clicks, clicks followed by an error, forms left after a validation error,\n// rapid back-and-forth between pages).\n//\n// import { init, setUser } from \"bugstack-sdk/browser\";\n// init({ key: \"<your BROWSER key>\", frustration: true });\n// setUser({ id: user.id, email: user.email });\n//\n// Next.js App Router: call init() in instrumentation-client.ts (Next 15.3+)\n// or in a \"use client\" component mounted once in the root layout. Pages\n// Router: call it in pages/_app.tsx inside useEffect.\n//\n// Every function here is safe to call anywhere: on the server (it does\n// nothing), before init (it does nothing), and it never throws. No\n// dependencies; never records input values, query strings or request bodies.\n\nimport { SessionRecorder, sessionFor, DEFAULT_ENDPOINT } from \"./recorder.js\";\nimport type { BrowserConfig, SessionUser } from \"./types.js\";\n\nexport type { BrowserConfig, FrustrationConfig, SessionUser, SessionEvent, SessionBatch, ElementRef } from \"./types.js\";\nexport { DEFAULT_ENDPOINT };\n\nlet recorder: SessionRecorder | null = null;\n\nfunction inBrowser(): boolean {\n return typeof window !== \"undefined\" && typeof document !== \"undefined\";\n}\n\n/**\n * Start recording this browser session. Call once, as early as you can. A\n * second call is ignored; close() first to start over.\n */\nexport function init(config: BrowserConfig): void {\n try {\n if (!inBrowser() || recorder) return;\n if (!config || typeof config.key !== \"string\" || config.key.trim() === \"\") return;\n const { sessionId, sampled } = sessionFor(config.sampleRate ?? 1);\n if (!sampled) return;\n recorder = new SessionRecorder({ ...config, key: config.key.trim() }, sessionId);\n recorder.install();\n } catch {\n recorder = null;\n }\n}\n\n/**\n * Who this session belongs to. bugstack stores only a salted hash of it, which\n * is how a support ticket from the same person finds what they saw. Pass null\n * on sign-out.\n */\nexport function setUser(user: SessionUser | null): void {\n try {\n recorder?.setUser(user);\n } catch {\n /* never into the host page */\n }\n}\n\n/** Report an error you caught yourself. */\nexport function captureError(err: unknown): void {\n try {\n recorder?.captureError(err);\n } catch {\n /* never into the host page */\n }\n}\n\n/** Send what is queued now. Resolves when the send settles; never rejects. */\nexport function flush(): Promise<void> {\n try {\n return recorder ? recorder.flush().catch(() => {}) : Promise.resolve();\n } catch {\n return Promise.resolve();\n }\n}\n\n/** Stop recording: send what is queued, remove every listener and wrapper. */\nexport function close(): void {\n try {\n recorder?.close();\n } catch {\n /* never into the host page */\n } finally {\n recorder = null;\n }\n}\n\n/** The current session id, or null when not recording. */\nexport function getSessionId(): string | null {\n return recorder?.sessionId ?? null;\n}\n"]}
@@ -1,5 +1,138 @@
1
1
  import { NextRequest } from 'next/server';
2
2
 
3
+ /**
4
+ * Caught-and-logged errors reach Bugstack.
5
+ *
6
+ * A `catch` that writes `console.error("[billing] grant failed", err)` and
7
+ * carries on is the commonest way an application handles a failure, and a log
8
+ * line is something nobody reads. Uncaught-exception handlers never see these
9
+ * errors because nothing re-throws them. On Bugstack's own repository, 12 of 16
10
+ * loud bugs it missed in one month were errors caught, logged and carried on
11
+ * from.
12
+ *
13
+ * This module forwards them through the same client every other capture path
14
+ * uses (`ErrorCaptureClient.reportError`), so they get the same `beforeSend`,
15
+ * the same fingerprint dedup and the same transport. Three sources feed it:
16
+ *
17
+ * - `console.error`, wrapped once per process when a client is initialised
18
+ * (on by default; `captureConsoleErrors: false` turns it off);
19
+ * - pino, through `bugstackPinoHooks()` (error and fatal);
20
+ * - winston, through `bugstackWinstonFormat()` (error and above).
21
+ *
22
+ * Rules, each tested in test/logged-errors.test.ts:
23
+ *
24
+ * - THE CONSOLE LINE IS WRITTEN EXACTLY AS BEFORE, first, with the same
25
+ * arguments and `this`. Forwarding happens after, and never throws.
26
+ * - WHAT IS FORWARDED: a call carrying an Error (as an argument, or as the
27
+ * `err` / `error` field of an object argument, the pino shape), or a string
28
+ * holding a stack trace (`console.error("failed", err.stack)`). A plain
29
+ * message with neither is noise by default and stays a console line;
30
+ * `{ messages: true }` forwards it too, as its text.
31
+ * - NOT FORWARDED, counted per rule in `loggedErrorStats()`: the SDK's own
32
+ * `[BugStack…]` lines, Node's process warnings (`(node:1) [DEP0169]
33
+ * DeprecationWarning: …`, which Node writes through console.error), lines
34
+ * matching `ignore`, an error an adapter already reported
35
+ * (`markErrorReported`), the same site and message again within
36
+ * `repeatWindowMs`, and anything past `maxPerMinute`.
37
+ * - ANCHORED AT THE LOGGING SITE. The fingerprint is error type + route +
38
+ * first stack frame. A driver error has the same first frame wherever it
39
+ * was caught, so the report is a new `LoggedError` whose stack starts at
40
+ * the line that logged it. The original rides along as `cause` and, as
41
+ * `causeName` / `causeStack`, in metadata.
42
+ * - NEVER TWICE. Forwarding is deferred one macrotask, so a catch that logs
43
+ * and then calls `captureError` in the same tick sends once.
44
+ * - NEVER LOOPS. A console.error raised while reporting (by `beforeSend`, or
45
+ * by the SDK's own debug logging) is written and not forwarded.
46
+ * - REDACTED. The text of a logged line goes through the client's
47
+ * `redactFields` (`password=…`, `token: …`) and `Bearer …` is masked.
48
+ * Only message text and stacks are sent, never the other log arguments.
49
+ *
50
+ * State lives on `globalThis` under a registered symbol: each package entry
51
+ * point (`bugstack-sdk`, `bugstack-sdk/generic`, …) is bundled on its own, and
52
+ * there must still be one console wrap and one "already reported" set per
53
+ * process.
54
+ */
55
+
56
+ /** Options for `captureConsoleErrors`. Every field is optional. */
57
+ interface LoggedErrorOptions {
58
+ /**
59
+ * Also forward a console.error (or logger error) that carries no Error and
60
+ * no stack trace, as its message text. Off by default: many libraries write
61
+ * plain lines through console.error that are not failures of your app.
62
+ * @default false
63
+ */
64
+ messages?: boolean;
65
+ /**
66
+ * At most this many logged errors are forwarded per minute, per process.
67
+ * @default 20
68
+ */
69
+ maxPerMinute?: number;
70
+ /**
71
+ * The same logging site with the same message is forwarded at most once per
72
+ * this window (milliseconds). A message-only line repeats per site alone,
73
+ * because its text usually carries ids.
74
+ * @default 300000 (5 minutes)
75
+ */
76
+ repeatWindowMs?: number;
77
+ /**
78
+ * Lines whose text matches any of these stay console lines.
79
+ */
80
+ ignore?: Array<string | RegExp>;
81
+ }
82
+ /** Where a logged error came from. */
83
+ type LoggedErrorSource = "console-error" | "pino" | "winston";
84
+ /** Why a logged error was not forwarded, counted per rule. */
85
+ type LoggedErrorDropRule = "no_error_argument" | "sdk_line" | "node_warning" | "ignored" | "already_reported" | "repeat" | "rate_limited" | "no_client";
86
+ interface ResolvedLoggedErrorOptions {
87
+ console: boolean;
88
+ messages: boolean;
89
+ maxPerMinute: number;
90
+ repeatWindowMs: number;
91
+ ignore: Array<string | RegExp>;
92
+ }
93
+ /**
94
+ * Say this error was already sent to Bugstack, so a console line or logger
95
+ * call for the same error object is not sent again. The SDK's adapters call
96
+ * it; call it yourself if you report an error through your own wrapper.
97
+ */
98
+ declare function markErrorReported(error: unknown): void;
99
+ /** Forwarded and dropped counts since the process started, dropped counted per rule. */
100
+ declare function loggedErrorStats(): {
101
+ consoleInstalled: boolean;
102
+ forwarded: number;
103
+ messageOnly: number;
104
+ dropped: Record<LoggedErrorDropRule, number>;
105
+ };
106
+ /**
107
+ * pino `hooks` that forward error and fatal logs. Pass to pino:
108
+ *
109
+ * ```ts
110
+ * const logger = pino({ hooks: bugstackPinoHooks() });
111
+ * ```
112
+ *
113
+ * If you already use `hooks.logMethod`, call the returned `logMethod` from
114
+ * yours. The log line is written exactly as before.
115
+ */
116
+ declare function bugstackPinoHooks(): {
117
+ logMethod: (this: unknown, inputArgs: unknown[], method: (...a: unknown[]) => unknown, level: number) => unknown;
118
+ };
119
+ /**
120
+ * A winston format that forwards error-level logs. Put it first in your
121
+ * format chain:
122
+ *
123
+ * ```ts
124
+ * const logger = winston.createLogger({
125
+ * format: winston.format.combine(bugstackWinstonFormat(), winston.format.json()),
126
+ * transports: [new winston.transports.Console()],
127
+ * });
128
+ * ```
129
+ *
130
+ * It returns the log entry unchanged.
131
+ */
132
+ declare function bugstackWinstonFormat(): {
133
+ transform: (info: Record<string | symbol, unknown>) => Record<string | symbol, unknown>;
134
+ };
135
+
3
136
  /**
4
137
  * Configuration options for the BugStack error capture SDK
5
138
  */
@@ -114,6 +247,18 @@ interface ErrorCaptureConfig {
114
247
  * lives behind a different host/path for telemetry vs. main capture.
115
248
  */
116
249
  chunkErrorsEndpoint?: string;
250
+ /**
251
+ * Forward caught-and-logged errors: a `console.error` call that carries an
252
+ * Error (or a stack trace) is reported, anchored at the line that logged it.
253
+ * The console line is written exactly as before. On by default; `false`
254
+ * turns it off. Pass options to tune it, e.g. `{ messages: true }` to also
255
+ * forward console.error lines that carry only a message.
256
+ *
257
+ * pino and winston are covered through `bugstackPinoHooks()` and
258
+ * `bugstackWinstonFormat()`, which follow the same rules.
259
+ * @default true
260
+ */
261
+ captureConsoleErrors?: boolean | LoggedErrorOptions;
117
262
  }
118
263
  /**
119
264
  * Resolved configuration with all defaults applied
@@ -138,6 +283,7 @@ interface ResolvedConfig {
138
283
  beforeSend?: (error: CapturedError) => CapturedError | null;
139
284
  dropChunkErrors: boolean;
140
285
  chunkErrorsEndpoint: string;
286
+ captureConsoleErrors: ResolvedLoggedErrorOptions;
141
287
  }
142
288
  /**
143
289
  * Captured error data sent to the error service
@@ -576,6 +722,7 @@ declare class ErrorCaptureClient {
576
722
  private static instance;
577
723
  private deduplicator;
578
724
  private retryQueue;
725
+ private loggedErrorSink;
579
726
  constructor(config: ErrorCaptureConfig);
580
727
  /**
581
728
  * Initialize the singleton client instance
@@ -660,4 +807,4 @@ declare function isChunkLoadError(error: {
660
807
  message?: string;
661
808
  }): boolean;
662
809
 
663
- export { BugStackClient as B, type CapturedError as C, type ErrorCaptureConfig as E, type NextRouteHandler as N, type RouteContext as R, type StackFrame as S, ErrorCaptureClient as a, type RouteOptions as b, type BugStackConfig as c, ErrorDeduplicator as d, type ErrorReportPayload as e, type ResolvedConfig as f, RetryQueue as g, type SourceContext as h, isChunkLoadError as i };
810
+ export { BugStackClient as B, type CapturedError as C, type ErrorCaptureConfig as E, type LoggedErrorOptions as L, type NextRouteHandler as N, type RouteContext as R, type StackFrame as S, ErrorCaptureClient as a, bugstackPinoHooks as b, bugstackWinstonFormat as c, type RouteOptions as d, type BugStackConfig as e, ErrorDeduplicator as f, type ErrorReportPayload as g, type LoggedErrorDropRule as h, type LoggedErrorSource as i, type ResolvedConfig as j, RetryQueue as k, loggedErrorStats as l, markErrorReported as m, type SourceContext as n, isChunkLoadError as o };
@@ -1,5 +1,138 @@
1
1
  import { NextRequest } from 'next/server';
2
2
 
3
+ /**
4
+ * Caught-and-logged errors reach Bugstack.
5
+ *
6
+ * A `catch` that writes `console.error("[billing] grant failed", err)` and
7
+ * carries on is the commonest way an application handles a failure, and a log
8
+ * line is something nobody reads. Uncaught-exception handlers never see these
9
+ * errors because nothing re-throws them. On Bugstack's own repository, 12 of 16
10
+ * loud bugs it missed in one month were errors caught, logged and carried on
11
+ * from.
12
+ *
13
+ * This module forwards them through the same client every other capture path
14
+ * uses (`ErrorCaptureClient.reportError`), so they get the same `beforeSend`,
15
+ * the same fingerprint dedup and the same transport. Three sources feed it:
16
+ *
17
+ * - `console.error`, wrapped once per process when a client is initialised
18
+ * (on by default; `captureConsoleErrors: false` turns it off);
19
+ * - pino, through `bugstackPinoHooks()` (error and fatal);
20
+ * - winston, through `bugstackWinstonFormat()` (error and above).
21
+ *
22
+ * Rules, each tested in test/logged-errors.test.ts:
23
+ *
24
+ * - THE CONSOLE LINE IS WRITTEN EXACTLY AS BEFORE, first, with the same
25
+ * arguments and `this`. Forwarding happens after, and never throws.
26
+ * - WHAT IS FORWARDED: a call carrying an Error (as an argument, or as the
27
+ * `err` / `error` field of an object argument, the pino shape), or a string
28
+ * holding a stack trace (`console.error("failed", err.stack)`). A plain
29
+ * message with neither is noise by default and stays a console line;
30
+ * `{ messages: true }` forwards it too, as its text.
31
+ * - NOT FORWARDED, counted per rule in `loggedErrorStats()`: the SDK's own
32
+ * `[BugStack…]` lines, Node's process warnings (`(node:1) [DEP0169]
33
+ * DeprecationWarning: …`, which Node writes through console.error), lines
34
+ * matching `ignore`, an error an adapter already reported
35
+ * (`markErrorReported`), the same site and message again within
36
+ * `repeatWindowMs`, and anything past `maxPerMinute`.
37
+ * - ANCHORED AT THE LOGGING SITE. The fingerprint is error type + route +
38
+ * first stack frame. A driver error has the same first frame wherever it
39
+ * was caught, so the report is a new `LoggedError` whose stack starts at
40
+ * the line that logged it. The original rides along as `cause` and, as
41
+ * `causeName` / `causeStack`, in metadata.
42
+ * - NEVER TWICE. Forwarding is deferred one macrotask, so a catch that logs
43
+ * and then calls `captureError` in the same tick sends once.
44
+ * - NEVER LOOPS. A console.error raised while reporting (by `beforeSend`, or
45
+ * by the SDK's own debug logging) is written and not forwarded.
46
+ * - REDACTED. The text of a logged line goes through the client's
47
+ * `redactFields` (`password=…`, `token: …`) and `Bearer …` is masked.
48
+ * Only message text and stacks are sent, never the other log arguments.
49
+ *
50
+ * State lives on `globalThis` under a registered symbol: each package entry
51
+ * point (`bugstack-sdk`, `bugstack-sdk/generic`, …) is bundled on its own, and
52
+ * there must still be one console wrap and one "already reported" set per
53
+ * process.
54
+ */
55
+
56
+ /** Options for `captureConsoleErrors`. Every field is optional. */
57
+ interface LoggedErrorOptions {
58
+ /**
59
+ * Also forward a console.error (or logger error) that carries no Error and
60
+ * no stack trace, as its message text. Off by default: many libraries write
61
+ * plain lines through console.error that are not failures of your app.
62
+ * @default false
63
+ */
64
+ messages?: boolean;
65
+ /**
66
+ * At most this many logged errors are forwarded per minute, per process.
67
+ * @default 20
68
+ */
69
+ maxPerMinute?: number;
70
+ /**
71
+ * The same logging site with the same message is forwarded at most once per
72
+ * this window (milliseconds). A message-only line repeats per site alone,
73
+ * because its text usually carries ids.
74
+ * @default 300000 (5 minutes)
75
+ */
76
+ repeatWindowMs?: number;
77
+ /**
78
+ * Lines whose text matches any of these stay console lines.
79
+ */
80
+ ignore?: Array<string | RegExp>;
81
+ }
82
+ /** Where a logged error came from. */
83
+ type LoggedErrorSource = "console-error" | "pino" | "winston";
84
+ /** Why a logged error was not forwarded, counted per rule. */
85
+ type LoggedErrorDropRule = "no_error_argument" | "sdk_line" | "node_warning" | "ignored" | "already_reported" | "repeat" | "rate_limited" | "no_client";
86
+ interface ResolvedLoggedErrorOptions {
87
+ console: boolean;
88
+ messages: boolean;
89
+ maxPerMinute: number;
90
+ repeatWindowMs: number;
91
+ ignore: Array<string | RegExp>;
92
+ }
93
+ /**
94
+ * Say this error was already sent to Bugstack, so a console line or logger
95
+ * call for the same error object is not sent again. The SDK's adapters call
96
+ * it; call it yourself if you report an error through your own wrapper.
97
+ */
98
+ declare function markErrorReported(error: unknown): void;
99
+ /** Forwarded and dropped counts since the process started, dropped counted per rule. */
100
+ declare function loggedErrorStats(): {
101
+ consoleInstalled: boolean;
102
+ forwarded: number;
103
+ messageOnly: number;
104
+ dropped: Record<LoggedErrorDropRule, number>;
105
+ };
106
+ /**
107
+ * pino `hooks` that forward error and fatal logs. Pass to pino:
108
+ *
109
+ * ```ts
110
+ * const logger = pino({ hooks: bugstackPinoHooks() });
111
+ * ```
112
+ *
113
+ * If you already use `hooks.logMethod`, call the returned `logMethod` from
114
+ * yours. The log line is written exactly as before.
115
+ */
116
+ declare function bugstackPinoHooks(): {
117
+ logMethod: (this: unknown, inputArgs: unknown[], method: (...a: unknown[]) => unknown, level: number) => unknown;
118
+ };
119
+ /**
120
+ * A winston format that forwards error-level logs. Put it first in your
121
+ * format chain:
122
+ *
123
+ * ```ts
124
+ * const logger = winston.createLogger({
125
+ * format: winston.format.combine(bugstackWinstonFormat(), winston.format.json()),
126
+ * transports: [new winston.transports.Console()],
127
+ * });
128
+ * ```
129
+ *
130
+ * It returns the log entry unchanged.
131
+ */
132
+ declare function bugstackWinstonFormat(): {
133
+ transform: (info: Record<string | symbol, unknown>) => Record<string | symbol, unknown>;
134
+ };
135
+
3
136
  /**
4
137
  * Configuration options for the BugStack error capture SDK
5
138
  */
@@ -114,6 +247,18 @@ interface ErrorCaptureConfig {
114
247
  * lives behind a different host/path for telemetry vs. main capture.
115
248
  */
116
249
  chunkErrorsEndpoint?: string;
250
+ /**
251
+ * Forward caught-and-logged errors: a `console.error` call that carries an
252
+ * Error (or a stack trace) is reported, anchored at the line that logged it.
253
+ * The console line is written exactly as before. On by default; `false`
254
+ * turns it off. Pass options to tune it, e.g. `{ messages: true }` to also
255
+ * forward console.error lines that carry only a message.
256
+ *
257
+ * pino and winston are covered through `bugstackPinoHooks()` and
258
+ * `bugstackWinstonFormat()`, which follow the same rules.
259
+ * @default true
260
+ */
261
+ captureConsoleErrors?: boolean | LoggedErrorOptions;
117
262
  }
118
263
  /**
119
264
  * Resolved configuration with all defaults applied
@@ -138,6 +283,7 @@ interface ResolvedConfig {
138
283
  beforeSend?: (error: CapturedError) => CapturedError | null;
139
284
  dropChunkErrors: boolean;
140
285
  chunkErrorsEndpoint: string;
286
+ captureConsoleErrors: ResolvedLoggedErrorOptions;
141
287
  }
142
288
  /**
143
289
  * Captured error data sent to the error service
@@ -576,6 +722,7 @@ declare class ErrorCaptureClient {
576
722
  private static instance;
577
723
  private deduplicator;
578
724
  private retryQueue;
725
+ private loggedErrorSink;
579
726
  constructor(config: ErrorCaptureConfig);
580
727
  /**
581
728
  * Initialize the singleton client instance
@@ -660,4 +807,4 @@ declare function isChunkLoadError(error: {
660
807
  message?: string;
661
808
  }): boolean;
662
809
 
663
- export { BugStackClient as B, type CapturedError as C, type ErrorCaptureConfig as E, type NextRouteHandler as N, type RouteContext as R, type StackFrame as S, ErrorCaptureClient as a, type RouteOptions as b, type BugStackConfig as c, ErrorDeduplicator as d, type ErrorReportPayload as e, type ResolvedConfig as f, RetryQueue as g, type SourceContext as h, isChunkLoadError as i };
810
+ export { BugStackClient as B, type CapturedError as C, type ErrorCaptureConfig as E, type LoggedErrorOptions as L, type NextRouteHandler as N, type RouteContext as R, type StackFrame as S, ErrorCaptureClient as a, bugstackPinoHooks as b, bugstackWinstonFormat as c, type RouteOptions as d, type BugStackConfig as e, ErrorDeduplicator as f, type ErrorReportPayload as g, type LoggedErrorDropRule as h, type LoggedErrorSource as i, type ResolvedConfig as j, RetryQueue as k, loggedErrorStats as l, markErrorReported as m, type SourceContext as n, isChunkLoadError as o };
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as CapturedError, a as ErrorCaptureClient, S as StackFrame } from './client-DK_ItP55.mjs';
2
- export { B as BugStackClient, c as BugStackConfig, E as ErrorCaptureConfig, d as ErrorDeduplicator, e as ErrorReportPayload, N as NextRouteHandler, f as ResolvedConfig, g as RetryQueue, R as RouteContext, b as RouteOptions, h as SourceContext, i as isChunkLoadError } from './client-DK_ItP55.mjs';
1
+ import { C as CapturedError, a as ErrorCaptureClient, S as StackFrame } from './client-B9WaTEYj.mjs';
2
+ export { B as BugStackClient, e as BugStackConfig, E as ErrorCaptureConfig, f as ErrorDeduplicator, g as ErrorReportPayload, h as LoggedErrorDropRule, L as LoggedErrorOptions, i as LoggedErrorSource, N as NextRouteHandler, j as ResolvedConfig, k as RetryQueue, R as RouteContext, d as RouteOptions, n as SourceContext, b as bugstackPinoHooks, c as bugstackWinstonFormat, o as isChunkLoadError, l as loggedErrorStats, m as markErrorReported } from './client-B9WaTEYj.mjs';
3
3
  export { withBugStack, withErrorCapture } from './adapters/nextjs/index.mjs';
4
4
  import 'next/server';
5
5
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as CapturedError, a as ErrorCaptureClient, S as StackFrame } from './client-DK_ItP55.js';
2
- export { B as BugStackClient, c as BugStackConfig, E as ErrorCaptureConfig, d as ErrorDeduplicator, e as ErrorReportPayload, N as NextRouteHandler, f as ResolvedConfig, g as RetryQueue, R as RouteContext, b as RouteOptions, h as SourceContext, i as isChunkLoadError } from './client-DK_ItP55.js';
1
+ import { C as CapturedError, a as ErrorCaptureClient, S as StackFrame } from './client-B9WaTEYj.js';
2
+ export { B as BugStackClient, e as BugStackConfig, E as ErrorCaptureConfig, f as ErrorDeduplicator, g as ErrorReportPayload, h as LoggedErrorDropRule, L as LoggedErrorOptions, i as LoggedErrorSource, N as NextRouteHandler, j as ResolvedConfig, k as RetryQueue, R as RouteContext, d as RouteOptions, n as SourceContext, b as bugstackPinoHooks, c as bugstackWinstonFormat, o as isChunkLoadError, l as loggedErrorStats, m as markErrorReported } from './client-B9WaTEYj.js';
3
3
  export { withBugStack, withErrorCapture } from './adapters/nextjs/index.js';
4
4
  import 'next/server';
5
5