bugwatch 0.4.1 → 0.5.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 ADDED
@@ -0,0 +1,793 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target2, all) => {
7
+ for (var name in all)
8
+ __defProp(target2, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/node/index.ts
21
+ var node_exports = {};
22
+ __export(node_exports, {
23
+ Bugwatch: () => Bugwatch,
24
+ default: () => node_default
25
+ });
26
+ module.exports = __toCommonJS(node_exports);
27
+
28
+ // src/node/client.ts
29
+ var import_node_async_hooks = require("async_hooks");
30
+
31
+ // src/shared.ts
32
+ var DEFAULT_ENDPOINT = "https://sentry-like.vercel.app/api/ingest";
33
+ var MAX_MESSAGE = 2e3;
34
+ var MAX_STACK = 5e4;
35
+ var MAX_URL = 2e3;
36
+ var MAX_USER_FIELD = 200;
37
+ var MAX_RELEASE = 200;
38
+ var MAX_BREADCRUMB_BYTES = 20 * 1024;
39
+ var RELEASE_CHARS = /^[^\s\u0000-\u001f\u007f-\u009f]+$/;
40
+ var ENVIRONMENT_FORMAT = /^[A-Za-z0-9_.-]{1,64}$/;
41
+ function asRecord(value) {
42
+ return typeof value === "object" && value !== null ? value : null;
43
+ }
44
+ function readString(value, limit, scrub) {
45
+ if (typeof value !== "string") {
46
+ return void 0;
47
+ }
48
+ const trimmed = value.trim();
49
+ if (!trimmed) {
50
+ return void 0;
51
+ }
52
+ return scrub(trimmed).slice(0, limit);
53
+ }
54
+ function readStack(value, scrub) {
55
+ if (typeof value === "string") {
56
+ return readString(value, MAX_STACK, scrub);
57
+ }
58
+ if (Array.isArray(value)) {
59
+ const lines = value.filter((line) => typeof line === "string");
60
+ return readString(lines.join("\n"), MAX_STACK, scrub);
61
+ }
62
+ return void 0;
63
+ }
64
+ function isValidRelease(value) {
65
+ return value.length <= MAX_RELEASE && RELEASE_CHARS.test(value) && value !== "." && value !== "..";
66
+ }
67
+ function isValidEnvironment(value) {
68
+ return ENVIRONMENT_FORMAT.test(value);
69
+ }
70
+ var RELEASE_RULE = "1-200 characters, no spaces or control characters, not . or ..";
71
+ var ENVIRONMENT_RULE = "letters, digits, _ . - only, max 64 characters";
72
+ function readOption(name, value, isValid, rule, warn) {
73
+ if (value === void 0 || value === null) {
74
+ return void 0;
75
+ }
76
+ const trimmed = typeof value === "string" ? value.trim() : void 0;
77
+ if (trimmed === "") {
78
+ return void 0;
79
+ }
80
+ if (trimmed !== void 0 && isValid(trimmed)) {
81
+ return trimmed;
82
+ }
83
+ warn(`[Bugwatch] Ignoring invalid ${name} option: ${rule}`);
84
+ return void 0;
85
+ }
86
+ function describe(value, scrub) {
87
+ const record = asRecord(value);
88
+ const message = record ? readString(record.message, MAX_MESSAGE, scrub) : void 0;
89
+ if (message) {
90
+ return {
91
+ message,
92
+ type: record ? readString(record.name, MAX_USER_FIELD, scrub) : void 0,
93
+ stack: record ? readStack(record.stack, scrub) : void 0
94
+ };
95
+ }
96
+ if (typeof value === "string") {
97
+ return { message: readString(value, MAX_MESSAGE, scrub) };
98
+ }
99
+ if (value !== void 0 && value !== null) {
100
+ try {
101
+ return { message: readString(String(value), MAX_MESSAGE, scrub) };
102
+ } catch {
103
+ }
104
+ }
105
+ return {};
106
+ }
107
+ function byteLength(value) {
108
+ try {
109
+ return new TextEncoder().encode(value).length;
110
+ } catch {
111
+ return value.length;
112
+ }
113
+ }
114
+ var HTTP_ERROR_INTERVAL_MS = 6e4;
115
+ var MAX_HTTP_ERROR_KEYS = 100;
116
+ function readHttpErrors(option) {
117
+ if (!option) {
118
+ return null;
119
+ }
120
+ const record = asRecord(option) ?? {};
121
+ let statuses = [[500, 599]];
122
+ if (Array.isArray(record.statuses)) {
123
+ statuses = [];
124
+ for (const entry of record.statuses) {
125
+ if (typeof entry === "number") {
126
+ statuses.push([entry, entry]);
127
+ } else if (Array.isArray(entry) && typeof entry[0] === "number" && typeof entry[1] === "number") {
128
+ statuses.push([entry[0], entry[1]]);
129
+ }
130
+ }
131
+ }
132
+ return {
133
+ statuses,
134
+ networkErrors: record.networkErrors === true,
135
+ ignoreUrls: Array.isArray(record.ignoreUrls) ? record.ignoreUrls.filter(
136
+ (entry) => typeof entry === "string" || entry instanceof RegExp
137
+ ) : []
138
+ };
139
+ }
140
+ function isIgnoredUrl(url, patterns) {
141
+ return patterns.some((pattern) => {
142
+ if (typeof pattern === "string") {
143
+ return url.includes(pattern);
144
+ }
145
+ pattern.lastIndex = 0;
146
+ return pattern.test(url);
147
+ });
148
+ }
149
+ var 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;
150
+ function urlForMessage(url) {
151
+ const parts = (url.split(/[?#]/)[0] || url).split("/");
152
+ const first = /^[a-z][a-z0-9+.-]*:$/i.test(parts[0] ?? "") && parts[1] === "" ? 3 : 0;
153
+ return parts.map((part, index) => index >= first && ID_SEGMENT.test(part) ? ":id" : part).join("/");
154
+ }
155
+ function httpErrorEvent(config2, sentAt, method, url, status, failure) {
156
+ if (!config2 || isIgnoredUrl(url, config2.ignoreUrls)) {
157
+ return null;
158
+ }
159
+ const target2 = `${method.toUpperCase()} ${urlForMessage(url)}`;
160
+ let message;
161
+ let type;
162
+ if (failure) {
163
+ if (failure === "abort" || !config2.networkErrors) {
164
+ return null;
165
+ }
166
+ message = `Network error: ${target2}`;
167
+ type = "NetworkError";
168
+ } else if (config2.statuses.some(([min, max]) => status >= min && status <= max)) {
169
+ message = `HTTP ${status}: ${target2}`;
170
+ type = "HttpError";
171
+ } else {
172
+ return null;
173
+ }
174
+ const now = Date.now();
175
+ const last = sentAt.get(message);
176
+ if (last !== void 0 && now - last < HTTP_ERROR_INTERVAL_MS) {
177
+ return null;
178
+ }
179
+ sentAt.delete(message);
180
+ sentAt.set(message, now);
181
+ if (sentAt.size > MAX_HTTP_ERROR_KEYS) {
182
+ sentAt.delete(sentAt.keys().next().value);
183
+ }
184
+ return { message, type };
185
+ }
186
+
187
+ // src/node/stack.ts
188
+ function relativeStack(stack, root) {
189
+ if (!root) return stack;
190
+ const trimmed = root.replace(/[\\/]+$/, "");
191
+ if (!trimmed) return stack;
192
+ const forward = trimmed.replace(/\\/g, "/");
193
+ const fileUrl = `file://${forward.startsWith("/") ? "" : "/"}${forward}`;
194
+ const prefixes = [.../* @__PURE__ */ new Set([`${fileUrl}/`, `${encodeURI(fileUrl)}/`, `${trimmed}/`, `${trimmed}\\`, `${forward}/`])].sort(
195
+ (a, b) => b.length - a.length
196
+ );
197
+ let result = stack;
198
+ for (const prefix of prefixes) {
199
+ if (result.includes(prefix)) result = result.split(prefix).join("");
200
+ }
201
+ return result;
202
+ }
203
+
204
+ // src/node/version.ts
205
+ var SDK_NAME = "bugwatch-node";
206
+ var SDK_VERSION = "0.5.0";
207
+
208
+ // src/node/client.ts
209
+ var MAX_BREADCRUMBS = 50;
210
+ var SEND_TIMEOUT_MS = 5e3;
211
+ var PAUSE_AFTER_429_MS = 6e4;
212
+ var MAX_BODY_BYTES = 100 * 1024 - 512;
213
+ var ORIGINAL_FETCH = /* @__PURE__ */ Symbol.for("bugwatch.originalFetch");
214
+ var nativeFetch = (() => {
215
+ if (typeof fetch !== "function") return void 0;
216
+ const original = fetch[ORIGINAL_FETCH] ?? fetch;
217
+ return original.bind(globalThis);
218
+ })();
219
+ var config = null;
220
+ var defaultUser;
221
+ var storage = new import_node_async_hooks.AsyncLocalStorage();
222
+ var pending = /* @__PURE__ */ new Set();
223
+ var pausedUntil = 0;
224
+ var rejectedKey = false;
225
+ var warned = /* @__PURE__ */ new Set();
226
+ function getConfig() {
227
+ return config;
228
+ }
229
+ function warnOnce(message) {
230
+ if (warned.has(message)) return;
231
+ warned.add(message);
232
+ try {
233
+ console.warn(message);
234
+ } catch {
235
+ }
236
+ }
237
+ function debugLog(message) {
238
+ if (config?.debug) warnOnce(`[Bugwatch] ${message}`);
239
+ }
240
+ function env(name) {
241
+ try {
242
+ const value = process.env[name];
243
+ return value && value.trim() ? value.trim() : void 0;
244
+ } catch {
245
+ return void 0;
246
+ }
247
+ }
248
+ function hostName() {
249
+ try {
250
+ const getBuiltin = process.getBuiltinModule;
251
+ const os = getBuiltin?.("node:os");
252
+ const name = os?.hostname?.() ?? env("HOSTNAME");
253
+ return name ? name.slice(0, 200) : void 0;
254
+ } catch {
255
+ return void 0;
256
+ }
257
+ }
258
+ function currentRoot(option) {
259
+ if (option !== void 0) return option.trim() || void 0;
260
+ try {
261
+ return process.cwd();
262
+ } catch {
263
+ return void 0;
264
+ }
265
+ }
266
+ function configure(options = {}) {
267
+ const apiKey = (typeof options.apiKey === "string" ? options.apiKey.trim() : "") || env("BUGWATCH_API_KEY") || "";
268
+ if (!apiKey) {
269
+ config = null;
270
+ return false;
271
+ }
272
+ const endpoint = (typeof options.endpoint === "string" ? options.endpoint.trim() : "") || DEFAULT_ENDPOINT;
273
+ const warn = (message) => warnOnce(message);
274
+ config = {
275
+ apiKey,
276
+ endpoint,
277
+ release: readOption("release", options.release ?? env("BUGWATCH_RELEASE"), isValidRelease, RELEASE_RULE, warn),
278
+ environment: readOption(
279
+ "environment",
280
+ options.environment ?? env("BUGWATCH_ENVIRONMENT"),
281
+ isValidEnvironment,
282
+ ENVIRONMENT_RULE,
283
+ warn
284
+ ),
285
+ serverName: options.serverName === false ? void 0 : typeof options.serverName === "string" && options.serverName.trim() ? options.serverName.trim().slice(0, 200) : hostName(),
286
+ root: currentRoot(options.root),
287
+ httpErrors: readHttpErrors(options.captureHttpErrors),
288
+ onFatalError: options.onFatalError === "keep-running" ? "keep-running" : "exit",
289
+ debug: options.debug === true
290
+ };
291
+ rejectedKey = false;
292
+ pausedUntil = 0;
293
+ return true;
294
+ }
295
+ function scrubSecret(value) {
296
+ const key = config?.apiKey;
297
+ return key && value.includes(key) ? value.split(key).join("[Filtered]") : value;
298
+ }
299
+ function isOwnRequest(url) {
300
+ const endpoint = config?.endpoint;
301
+ return Boolean(url && endpoint) && url.split("?")[0] === endpoint.split("?")[0];
302
+ }
303
+ function currentScope() {
304
+ try {
305
+ return storage.getStore();
306
+ } catch {
307
+ return void 0;
308
+ }
309
+ }
310
+ function runInScope(fn, init = {}) {
311
+ const parent = currentScope();
312
+ const scope = {
313
+ user: parent?.user,
314
+ request: parent?.request,
315
+ userAgent: parent?.userAgent,
316
+ ...init,
317
+ breadcrumbs: []
318
+ };
319
+ return storage.run(scope, fn);
320
+ }
321
+ function setUser(next) {
322
+ let value;
323
+ if (next && typeof next === "object") {
324
+ const id = readString(next.id, MAX_USER_FIELD, (text) => text);
325
+ const email = readString(next.email, MAX_USER_FIELD, (text) => text);
326
+ value = id || email ? { ...id ? { id } : {}, ...email ? { email } : {} } : void 0;
327
+ }
328
+ const scope = currentScope();
329
+ if (scope) scope.user = value;
330
+ else defaultUser = value;
331
+ }
332
+ function recordBreadcrumb(crumb) {
333
+ const scope = currentScope();
334
+ if (!scope) return;
335
+ scope.breadcrumbs.push({ ...crumb, timestamp: Date.now() });
336
+ if (scope.breadcrumbs.length > MAX_BREADCRUMBS) scope.breadcrumbs.shift();
337
+ }
338
+ function setRoute(route) {
339
+ const scope = currentScope();
340
+ if (scope?.request && route) scope.request = { ...scope.request, route };
341
+ }
342
+ function cleanRequest(request) {
343
+ if (!request || typeof request !== "object") return void 0;
344
+ const method = readString(request.method, 10, scrubSecret);
345
+ const url = readString(request.url, MAX_URL, scrubSecret);
346
+ if (!method || !url) return void 0;
347
+ const route = readString(request.route, 200, scrubSecret);
348
+ return { method: method.toUpperCase(), url, ...route ? { route } : {} };
349
+ }
350
+ function breadcrumbsForEvent(scope) {
351
+ const list = (scope?.breadcrumbs ?? []).map((crumb) => {
352
+ const copy = { ...crumb };
353
+ if (copy.message) copy.message = scrubSecret(copy.message);
354
+ if (copy.data?.url) copy.data = { ...copy.data, url: scrubSecret(copy.data.url) };
355
+ return copy;
356
+ });
357
+ while (list.length > 0 && byteLength(JSON.stringify(list)) > MAX_BREADCRUMB_BYTES) list.shift();
358
+ return list;
359
+ }
360
+ function buildEvent(error, options = {}) {
361
+ const current = config;
362
+ if (!current) return null;
363
+ const description = describe(error, scrubSecret);
364
+ if (!description.message) return null;
365
+ return buildPayload(current, { ...description, message: description.message }, options);
366
+ }
367
+ function buildMessageEvent(message, type, options = {}) {
368
+ const current = config;
369
+ const text = readString(message, MAX_MESSAGE, scrubSecret);
370
+ if (!current || !text) return null;
371
+ return buildPayload(current, { message: text, type }, options);
372
+ }
373
+ function buildPayload(current, description, options) {
374
+ const scope = currentScope();
375
+ const user = scope ? scope.user : defaultUser;
376
+ const request = cleanRequest(options.request) ?? cleanRequest(scope?.request);
377
+ const userAgent = readString(scope?.userAgent, MAX_URL, scrubSecret);
378
+ const payload = {
379
+ key: current.apiKey,
380
+ message: description.message,
381
+ level: options.level ?? "error",
382
+ platform: "node",
383
+ runtime: { name: "node", version: (process.versions?.node ?? "").slice(0, 50) || "unknown" },
384
+ sdk: { name: SDK_NAME, version: SDK_VERSION },
385
+ timestamp: Date.now()
386
+ };
387
+ if (description.type) payload.type = description.type;
388
+ if (description.stack) payload.stack = relativeStack(description.stack, current.root);
389
+ if (current.serverName) payload.serverName = current.serverName;
390
+ if (request) payload.request = request;
391
+ if (userAgent) payload.userAgent = userAgent;
392
+ if (user) {
393
+ payload.user = {
394
+ ...user.id ? { id: scrubSecret(user.id) } : {},
395
+ ...user.email ? { email: scrubSecret(user.email) } : {}
396
+ };
397
+ }
398
+ if (current.release) payload.release = current.release;
399
+ if (current.environment) payload.environment = current.environment;
400
+ const breadcrumbs = breadcrumbsForEvent(scope);
401
+ if (breadcrumbs.length > 0) payload.breadcrumbs = breadcrumbs;
402
+ return payload;
403
+ }
404
+ function serialize(payload) {
405
+ let body = JSON.stringify(payload);
406
+ if (byteLength(body) <= MAX_BODY_BYTES) return body;
407
+ delete payload.breadcrumbs;
408
+ body = JSON.stringify(payload);
409
+ if (byteLength(body) <= MAX_BODY_BYTES || !payload.stack) return body;
410
+ payload.stack = payload.stack.slice(0, 2e4);
411
+ return JSON.stringify(payload);
412
+ }
413
+ function send(payload) {
414
+ try {
415
+ const current = config;
416
+ if (!payload || !current) return;
417
+ if (rejectedKey) return debugLog("Not sending: the API key was rejected (401). Check apiKey, then call init again");
418
+ if (Date.now() < pausedUntil) return debugLog("Not sending: the monthly event limit was reached (429); paused for a minute");
419
+ if (!nativeFetch) return debugLog("Not sending: this runtime has no global fetch (Node 20+ is required)");
420
+ const task = (async () => {
421
+ try {
422
+ const response = await nativeFetch(current.endpoint, {
423
+ method: "POST",
424
+ headers: { "Content-Type": "application/json", "User-Agent": `${SDK_NAME}/${SDK_VERSION}` },
425
+ body: serialize(payload),
426
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS)
427
+ });
428
+ if (response.status === 401) {
429
+ rejectedKey = true;
430
+ warnOnce("[Bugwatch] The API key was rejected (401). Events are not sent until init is called with a valid key");
431
+ } else if (response.status === 429) {
432
+ pausedUntil = Date.now() + PAUSE_AFTER_429_MS;
433
+ debugLog("The monthly event limit was reached (429); pausing for a minute");
434
+ } else if (!response.ok) {
435
+ debugLog(`Bugwatch answered ${response.status}`);
436
+ }
437
+ await response.arrayBuffer().catch(() => void 0);
438
+ } catch (error) {
439
+ debugLog(`Could not reach Bugwatch: ${error instanceof Error ? error.message : String(error)}`);
440
+ }
441
+ })();
442
+ pending.add(task);
443
+ void task.finally(() => pending.delete(task));
444
+ } catch {
445
+ }
446
+ }
447
+ async function flush(timeoutMs = 2e3) {
448
+ try {
449
+ if (pending.size === 0) return true;
450
+ let timer;
451
+ const timeout = new Promise((resolve) => {
452
+ timer = setTimeout(() => resolve(false), Math.max(0, timeoutMs));
453
+ timer.unref?.();
454
+ });
455
+ const done = Promise.allSettled([...pending]).then(() => true);
456
+ const result = await Promise.race([done, timeout]);
457
+ if (timer) clearTimeout(timer);
458
+ return result;
459
+ } catch {
460
+ return false;
461
+ }
462
+ }
463
+ var reported = /* @__PURE__ */ new WeakSet();
464
+ function markReported(value) {
465
+ if (typeof value === "object" && value !== null) reported.add(value);
466
+ }
467
+ function wasReported(value) {
468
+ return typeof value === "object" && value !== null && reported.has(value);
469
+ }
470
+ function captureError(error, options = {}) {
471
+ try {
472
+ if (wasReported(error)) return;
473
+ markReported(error);
474
+ send(buildEvent(error, options));
475
+ } catch {
476
+ }
477
+ }
478
+
479
+ // src/node/fetch.ts
480
+ var MAX_CRUMB_URL = 500;
481
+ var httpErrorSentAt = /* @__PURE__ */ new Map();
482
+ var patched = false;
483
+ function target(input, init) {
484
+ let method = "GET";
485
+ let url = "";
486
+ try {
487
+ if (typeof input === "string") url = input;
488
+ else if (input instanceof URL) url = input.href;
489
+ else if (input && typeof input.url === "string") url = input.url;
490
+ const requestMethod = input?.method;
491
+ if (typeof requestMethod === "string") method = requestMethod;
492
+ const initMethod = init?.method;
493
+ if (typeof initMethod === "string") method = initMethod;
494
+ } catch {
495
+ }
496
+ return { method: method.toUpperCase(), url };
497
+ }
498
+ function failureOf(error) {
499
+ return error?.name === "AbortError" ? "abort" : "network";
500
+ }
501
+ function onResult(method, url, status, startedAt, failure) {
502
+ try {
503
+ if (!url || isOwnRequest(url)) return;
504
+ recordBreadcrumb({
505
+ type: "http",
506
+ level: failure || status >= 500 ? "error" : status >= 400 ? "warning" : "info",
507
+ data: {
508
+ method: method.slice(0, 10),
509
+ url: url.slice(0, MAX_CRUMB_URL),
510
+ status,
511
+ durationMs: Math.max(0, Date.now() - startedAt)
512
+ }
513
+ });
514
+ const event = httpErrorEvent(getConfig()?.httpErrors ?? null, httpErrorSentAt, method, url, status, failure);
515
+ if (event) send(buildMessageEvent(event.message, event.type));
516
+ } catch {
517
+ }
518
+ }
519
+ function patchFetch() {
520
+ if (patched || typeof globalThis.fetch !== "function") return;
521
+ const original = globalThis.fetch;
522
+ const wrapped = function(...args) {
523
+ const { method, url } = target(args[0], args[1]);
524
+ const startedAt = Date.now();
525
+ const result = original.apply(this, args);
526
+ try {
527
+ result.then(
528
+ (response) => onResult(method, url, response.status, startedAt),
529
+ (error) => onResult(method, url, 0, startedAt, failureOf(error))
530
+ );
531
+ } catch {
532
+ }
533
+ return result;
534
+ };
535
+ for (const key of Reflect.ownKeys(original)) {
536
+ if (key === "length" || key === "name" || key === "prototype") continue;
537
+ try {
538
+ const descriptor = Object.getOwnPropertyDescriptor(original, key);
539
+ if (descriptor) Object.defineProperty(wrapped, key, descriptor);
540
+ } catch {
541
+ }
542
+ }
543
+ wrapped[ORIGINAL_FETCH] = original[ORIGINAL_FETCH] ?? original;
544
+ globalThis.fetch = wrapped;
545
+ patched = true;
546
+ }
547
+
548
+ // src/node/frameworks.ts
549
+ var NEXT_FLUSH_MS = 2e3;
550
+ function header(headers, name) {
551
+ const value = headers?.[name];
552
+ return Array.isArray(value) ? value[0] : value;
553
+ }
554
+ function expressUrl(req) {
555
+ const path = req.originalUrl || req.url || "/";
556
+ const host = header(req.headers, "host");
557
+ if (!host) return path;
558
+ const protocol = req.protocol || "http";
559
+ return `${protocol}://${host}${path}`;
560
+ }
561
+ function expressRoute(req) {
562
+ const path = req.route?.path;
563
+ return typeof path === "string" ? `${req.baseUrl ?? ""}${path}` || void 0 : void 0;
564
+ }
565
+ function expressRequest(req) {
566
+ const route = expressRoute(req);
567
+ return { method: req.method || "GET", url: expressUrl(req), ...route ? { route } : {} };
568
+ }
569
+ function expressRequestHandler() {
570
+ return function bugwatchRequestHandler(req, _res, next) {
571
+ let request;
572
+ let userAgent;
573
+ try {
574
+ request = expressRequest(req);
575
+ userAgent = header(req.headers, "user-agent");
576
+ } catch {
577
+ }
578
+ runInScope(() => next(), { request, userAgent });
579
+ };
580
+ }
581
+ function errorStatus(error) {
582
+ const record = error;
583
+ const status = record?.status ?? record?.statusCode;
584
+ return typeof status === "number" ? status : void 0;
585
+ }
586
+ function expressErrorHandler() {
587
+ return function bugwatchErrorHandler(error, req, _res, next) {
588
+ try {
589
+ const status = errorStatus(error);
590
+ if (status === void 0 || status >= 500) {
591
+ const request = expressRequest(req);
592
+ if (currentScope()) {
593
+ setRoute(request.route);
594
+ captureError(error, { request });
595
+ } else {
596
+ runInScope(() => captureError(error, { request }), {
597
+ request,
598
+ userAgent: header(req.headers, "user-agent")
599
+ });
600
+ }
601
+ }
602
+ } catch {
603
+ }
604
+ next(error);
605
+ };
606
+ }
607
+ var NEXT_CONTROL_FLOW = [
608
+ "NEXT_REDIRECT",
609
+ "NEXT_NOT_FOUND",
610
+ "NEXT_HTTP_ERROR_FALLBACK",
611
+ "DYNAMIC_SERVER_USAGE",
612
+ "BAILOUT_TO_CLIENT_SIDE_RENDERING",
613
+ "NEXT_PRERENDER_INTERRUPTED",
614
+ "HANGING_PROMISE_REJECTION"
615
+ ];
616
+ function isNextControlFlow(error) {
617
+ const record = error;
618
+ const digest = typeof record?.digest === "string" ? record.digest : "";
619
+ const message = typeof record?.message === "string" ? record.message : "";
620
+ return NEXT_CONTROL_FLOW.some((prefix) => digest.startsWith(prefix) || message === prefix);
621
+ }
622
+ function nextUrl(request) {
623
+ const path = request.path || "/";
624
+ const host = header(request.headers, "x-forwarded-host") || header(request.headers, "host");
625
+ if (!host) return path;
626
+ const protocol = (header(request.headers, "x-forwarded-proto") || "https").split(",")[0].trim();
627
+ return `${protocol}://${host}${path}`;
628
+ }
629
+ async function nextOnRequestError(error, request = {}, context = {}) {
630
+ try {
631
+ if (!getConfig() || isNextControlFlow(error) || wasReported(error)) return;
632
+ const info = {
633
+ method: request.method || "GET",
634
+ url: nextUrl(request),
635
+ ...context.routePath ? { route: context.routePath } : {}
636
+ };
637
+ runInScope(() => captureError(error, { request: info }), {
638
+ request: info,
639
+ userAgent: header(request.headers, "user-agent")
640
+ });
641
+ await flush(NEXT_FLUSH_MS);
642
+ } catch {
643
+ }
644
+ }
645
+
646
+ // src/node/process.ts
647
+ var FATAL_FLUSH_MS = 2e3;
648
+ var installed = false;
649
+ var exiting = false;
650
+ function rejectionMode() {
651
+ try {
652
+ const args = [...process.execArgv, ...(process.env.NODE_OPTIONS ?? "").split(/\s+/)];
653
+ let mode = "throw";
654
+ for (const arg of args) {
655
+ const match = /^--unhandled-rejections=(.+)$/.exec(arg);
656
+ if (match) mode = match[1];
657
+ }
658
+ return mode;
659
+ } catch {
660
+ return "throw";
661
+ }
662
+ }
663
+ function printFatal(error) {
664
+ try {
665
+ const text = error instanceof Error ? error.stack ?? `${error.name}: ${error.message}` : `Uncaught ${String(error)}`;
666
+ process.stderr.write(`${text}
667
+
668
+ Node.js ${process.version}
669
+ `);
670
+ } catch {
671
+ }
672
+ }
673
+ function exitAfterFlush(error) {
674
+ if (exiting) return;
675
+ exiting = true;
676
+ void flush(FATAL_FLUSH_MS).then(() => {
677
+ printFatal(error);
678
+ process.exit(1);
679
+ });
680
+ }
681
+ function onUncaughtException(error) {
682
+ try {
683
+ if (!wasReported(error)) {
684
+ markReported(error);
685
+ send(buildEvent(error, { level: "fatal" }));
686
+ }
687
+ const onlyOurs = process.listenerCount("uncaughtException") === 1;
688
+ if (onlyOurs && (getConfig()?.onFatalError ?? "exit") === "exit") exitAfterFlush(error);
689
+ } catch {
690
+ }
691
+ }
692
+ function rejectionError(reason) {
693
+ let text;
694
+ try {
695
+ text = String(reason);
696
+ } catch {
697
+ text = "[unprintable]";
698
+ }
699
+ const error = new Error(
700
+ `This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "${text}".`
701
+ );
702
+ error.code = "ERR_UNHANDLED_REJECTION";
703
+ return error;
704
+ }
705
+ function onUnhandledRejection(reason) {
706
+ try {
707
+ const mode = rejectionMode();
708
+ if (!wasReported(reason)) {
709
+ markReported(reason);
710
+ send(buildEvent(reason, { level: "error" }));
711
+ }
712
+ if (mode === "warn-with-error-code") process.exitCode = 1;
713
+ const onlyOurs = process.listenerCount("unhandledRejection") === 1;
714
+ if (mode === "throw" && onlyOurs) {
715
+ const error = reason instanceof Error ? reason : rejectionError(reason);
716
+ markReported(error);
717
+ process.nextTick(() => {
718
+ throw error;
719
+ });
720
+ }
721
+ } catch {
722
+ }
723
+ }
724
+ function installProcessHandlers() {
725
+ if (installed) return;
726
+ installed = true;
727
+ process.on("uncaughtException", onUncaughtException);
728
+ process.on("unhandledRejection", onUnhandledRejection);
729
+ }
730
+
731
+ // src/node/index.ts
732
+ function isSupportedRuntime() {
733
+ try {
734
+ if (typeof process === "undefined" || typeof process.on !== "function") return false;
735
+ if (process.env.NEXT_RUNTIME === "edge") return false;
736
+ return typeof globalThis.EdgeRuntime === "undefined";
737
+ } catch {
738
+ return false;
739
+ }
740
+ }
741
+ var Bugwatch = {
742
+ /**
743
+ * Starts reporting. The API key comes from `apiKey` or `$BUGWATCH_API_KEY`;
744
+ * without one, nothing is sent. Safe to call again: a later call replaces
745
+ * the options (process listeners are added once).
746
+ */
747
+ init(options = {}) {
748
+ try {
749
+ if (!isSupportedRuntime()) return;
750
+ if (!configure(options)) return;
751
+ installProcessHandlers();
752
+ patchFetch();
753
+ } catch {
754
+ }
755
+ },
756
+ /** Reports an error, e.g. one you caught. Optional `level` and `request`. */
757
+ captureError(error, options) {
758
+ captureError(error, options);
759
+ },
760
+ /**
761
+ * Sets the user for later events. Inside a request (or `withScope`) only
762
+ * that request gets it; outside, it is the default. `null` clears it.
763
+ */
764
+ setUser(user) {
765
+ try {
766
+ setUser(user);
767
+ } catch {
768
+ }
769
+ },
770
+ /** Runs `fn` with its own user and breadcrumbs (the integrations do this per request). */
771
+ withScope(fn) {
772
+ return runInScope(fn);
773
+ },
774
+ /**
775
+ * Waits for events in flight, e.g. before a serverless function returns or
776
+ * a script exits. Resolves `true` when all were sent within `timeoutMs`.
777
+ */
778
+ flush(timeoutMs) {
779
+ return flush(timeoutMs);
780
+ },
781
+ /** Express: `app.use(Bugwatch.expressRequestHandler())` before your routes. */
782
+ expressRequestHandler,
783
+ /** Express: `app.use(Bugwatch.expressErrorHandler())` after your routes; reports 5xx errors. */
784
+ expressErrorHandler,
785
+ /** Next.js: `export const onRequestError = Bugwatch.nextOnRequestError;` in `instrumentation.ts`. */
786
+ nextOnRequestError
787
+ };
788
+ var node_default = Bugwatch;
789
+ // Annotate the CommonJS export names for ESM import in node:
790
+ 0 && (module.exports = {
791
+ Bugwatch
792
+ });
793
+ //# sourceMappingURL=node.cjs.map