bugstack-sdk 2.2.2 → 2.3.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.
@@ -430,8 +430,395 @@ var RetryQueue = class {
430
430
  }
431
431
  };
432
432
 
433
+ // src/core/utils/stack-parser.ts
434
+ var V8_STACK_FRAME_REGEX = /^\s*at\s+(?:async\s+)?(?:(.+?)\s+\()?(?:(.+?):(\d+):(\d+))\)?$/;
435
+ function isNodeModule(filePath) {
436
+ return filePath.includes("node_modules");
437
+ }
438
+ function isInternalCode(filePath) {
439
+ return filePath.startsWith("node:") || filePath.startsWith("internal/") || // A bare name ("native", "<anonymous>") has no directory. A Windows
440
+ // path has backslashes and is app code.
441
+ !filePath.includes("/") && !filePath.includes("\\");
442
+ }
443
+ function cleanFunctionName(name) {
444
+ if (!name) return void 0;
445
+ return name.replace(/^Object\./, "").replace(/^Module\./, "").replace(/^__webpack_require__\./, "").replace(/^webpack_require\./, "").trim();
446
+ }
447
+ function parseStackTrace(stack) {
448
+ if (!stack) return [];
449
+ const lines = stack.split("\n");
450
+ const frames = [];
451
+ for (const line of lines) {
452
+ const match = V8_STACK_FRAME_REGEX.exec(line);
453
+ if (match) {
454
+ const [, functionName, file, lineStr, columnStr] = match;
455
+ const frame = {
456
+ function: cleanFunctionName(functionName),
457
+ file: file ?? void 0,
458
+ line: lineStr ? parseInt(lineStr, 10) : void 0,
459
+ column: columnStr ? parseInt(columnStr, 10) : void 0
460
+ };
461
+ if (frame.file) {
462
+ frame.isNodeModule = isNodeModule(frame.file);
463
+ frame.isInternal = isInternalCode(frame.file);
464
+ }
465
+ frames.push(frame);
466
+ }
467
+ }
468
+ return frames;
469
+ }
470
+ function getFirstAppFrame(frames) {
471
+ return frames.find((frame) => !frame.isNodeModule && !frame.isInternal);
472
+ }
473
+
433
474
  // src/core/sdk-version.ts
434
- var SDK_VERSION = "2.2.2" ;
475
+ var SDK_VERSION = "2.3.0" ;
476
+
477
+ // src/core/logged-errors.ts
478
+ var DEFAULT_MAX_PER_MINUTE = 20;
479
+ var DEFAULT_REPEAT_WINDOW_MS = 5 * 6e4;
480
+ var MAX_REMEMBERED = 500;
481
+ var MESSAGE_MAX = 300;
482
+ var ANCHORED_MESSAGE_MAX = 500;
483
+ var CAUSE_STACK_MAX = 2e3;
484
+ function resolveLoggedErrorOptions(value) {
485
+ const opts = typeof value === "object" && value !== null ? value : {};
486
+ return {
487
+ console: value !== false,
488
+ messages: opts.messages ?? false,
489
+ maxPerMinute: opts.maxPerMinute ?? DEFAULT_MAX_PER_MINUTE,
490
+ repeatWindowMs: opts.repeatWindowMs ?? DEFAULT_REPEAT_WINDOW_MS,
491
+ ignore: opts.ignore ?? []
492
+ };
493
+ }
494
+ var SHARED_KEY = /* @__PURE__ */ Symbol.for("bugstack-sdk.logged-errors");
495
+ function emptyStats() {
496
+ return {
497
+ forwarded: 0,
498
+ messageOnly: 0,
499
+ dropped: {
500
+ no_error_argument: 0,
501
+ sdk_line: 0,
502
+ node_warning: 0,
503
+ ignored: 0,
504
+ already_reported: 0,
505
+ repeat: 0,
506
+ rate_limited: 0,
507
+ no_client: 0
508
+ }
509
+ };
510
+ }
511
+ function shared() {
512
+ const g = globalThis;
513
+ let s = g[SHARED_KEY];
514
+ if (!s) {
515
+ s = {
516
+ reported: /* @__PURE__ */ new WeakSet(),
517
+ sink: null,
518
+ consoleOriginal: null,
519
+ consoleWrapper: null,
520
+ busy: false,
521
+ windowStart: 0,
522
+ inWindow: 0,
523
+ lastSent: /* @__PURE__ */ new Map(),
524
+ stats: emptyStats(),
525
+ now: Date.now
526
+ };
527
+ g[SHARED_KEY] = s;
528
+ }
529
+ return s;
530
+ }
531
+ var defer = typeof setImmediate === "function" ? (fn) => void setImmediate(fn) : (fn) => void setTimeout(fn, 0);
532
+ function markErrorReported(error) {
533
+ try {
534
+ if (error !== null && typeof error === "object") shared().reported.add(error);
535
+ } catch {
536
+ }
537
+ }
538
+ function isError(value) {
539
+ if (value instanceof Error) return true;
540
+ if (value === null || typeof value !== "object") return false;
541
+ try {
542
+ const v = value;
543
+ return typeof v.message === "string" && typeof v.stack === "string";
544
+ } catch {
545
+ return false;
546
+ }
547
+ }
548
+ function findError(args) {
549
+ for (const a of args) if (isError(a)) return a;
550
+ for (const a of args) {
551
+ if (a === null || typeof a !== "object" || Array.isArray(a)) continue;
552
+ try {
553
+ const o = a;
554
+ for (const k of ["err", "error", "cause"]) if (isError(o[k])) return o[k];
555
+ } catch {
556
+ }
557
+ }
558
+ return void 0;
559
+ }
560
+ var STACK_TEXT = /(^|\n)\s*([A-Za-z_$][\w$.]*(?:Error|Exception)\b[^\n]*)\n\s+at \S/;
561
+ function findStackText(args) {
562
+ for (const a of args) {
563
+ if (typeof a !== "string") continue;
564
+ const m = STACK_TEXT.exec(a);
565
+ if (!m) continue;
566
+ const header = m[2].trim();
567
+ const colon = header.indexOf(":");
568
+ const err = new Error(colon > 0 ? header.slice(colon + 1).trim() : header);
569
+ err.name = colon > 0 ? header.slice(0, colon).trim() : "Error";
570
+ err.stack = a.slice(m.index + m[1].length).trim();
571
+ return err;
572
+ }
573
+ return void 0;
574
+ }
575
+ function messageOfArgs(args) {
576
+ const parts = [];
577
+ for (const a of args) {
578
+ if (typeof a === "string") parts.push(a);
579
+ else if (typeof a === "number" || typeof a === "boolean") parts.push(String(a));
580
+ else if (a !== null && typeof a === "object" && !Array.isArray(a) && !isError(a)) {
581
+ try {
582
+ const o = a;
583
+ for (const k of ["error", "message", "reason", "err", "msg"]) {
584
+ if (typeof o[k] === "string" && o[k].length > 0) {
585
+ parts.push(o[k]);
586
+ break;
587
+ }
588
+ }
589
+ } catch {
590
+ }
591
+ }
592
+ }
593
+ return parts.join(" ").replace(/\s+/g, " ").trim().slice(0, MESSAGE_MAX);
594
+ }
595
+ function logRoute(label) {
596
+ const tag = label?.match(/^\s*\[([A-Za-z0-9_.:/-]{1,60})\]/)?.[1];
597
+ return tag ? `log:${tag}` : "log";
598
+ }
599
+ var SDK_LINE = /^\s*\[bugstack[^\]]*\]/i;
600
+ var NODE_WARNING_LINE = /^\s*\(node:\d+\)\s+(?:\[[A-Z0-9_]+\]\s+)?\w*Warning:/;
601
+ function escapeRegExp(s) {
602
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
603
+ }
604
+ function redactText(text, redactFields) {
605
+ let out = text.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "$1 [REDACTED]");
606
+ if (redactFields.length > 0) {
607
+ const names = redactFields.filter((f) => f.length > 0).map(escapeRegExp).join("|");
608
+ if (names) {
609
+ const re = new RegExp(
610
+ `(["']?\\b\\w*(?:${names})\\w*["']?\\s*[=:]\\s*)("[^"]*"|'[^']*'|[^\\s,;&)}\\]]+)`,
611
+ "gi"
612
+ );
613
+ out = out.replace(re, "$1[REDACTED]");
614
+ }
615
+ }
616
+ return out;
617
+ }
618
+ function firstFrame(stack) {
619
+ return (stack ?? "").split("\n").find((l) => /^\s+at /.test(l))?.trim() ?? "";
620
+ }
621
+ function trimLibraryFrames(stack) {
622
+ const lines = stack.split("\n");
623
+ const header = [];
624
+ let i = 0;
625
+ while (i < lines.length && !/^\s+at /.test(lines[i])) header.push(lines[i++]);
626
+ let j = i;
627
+ while (j < lines.length && /node_modules|[/\\]bugstack-sdk[/\\]|\(node:internal|^\s+at node:internal/.test(lines[j])) j++;
628
+ if (j >= lines.length) return stack;
629
+ return [...header, ...lines.slice(j)].join("\n");
630
+ }
631
+ function siteOf(label, cause) {
632
+ if (label === void 0) return "";
633
+ const first = label.split("\n")[0].trim();
634
+ if (!first || first === cause.message || first === `${cause.name}: ${cause.message}`) return "";
635
+ return first.slice(0, 200);
636
+ }
637
+ function matchesIgnore(text, ignore) {
638
+ for (const p of ignore) {
639
+ try {
640
+ if (typeof p === "string" ? text.includes(p) : p.test(text)) return true;
641
+ } catch {
642
+ }
643
+ }
644
+ return false;
645
+ }
646
+ function captureLoggedCall(args, source, boundary) {
647
+ const s = shared();
648
+ if (s.busy) return;
649
+ try {
650
+ const sink = s.sink;
651
+ if (!sink) {
652
+ s.stats.dropped.no_client += 1;
653
+ return;
654
+ }
655
+ const label = args.find((a) => typeof a === "string");
656
+ if (label !== void 0 && SDK_LINE.test(label)) {
657
+ s.stats.dropped.sdk_line += 1;
658
+ return;
659
+ }
660
+ if (label !== void 0 && NODE_WARNING_LINE.test(label)) {
661
+ s.stats.dropped.node_warning += 1;
662
+ return;
663
+ }
664
+ const cause = findError(args) ?? findStackText(args) ?? null;
665
+ if (sink.options.ignore.length > 0 && matchesIgnore(`${messageOfArgs(args)} ${cause ? `${cause.name}: ${cause.message}` : ""}`, sink.options.ignore)) {
666
+ s.stats.dropped.ignored += 1;
667
+ return;
668
+ }
669
+ let message;
670
+ if (cause) {
671
+ message = `${siteOf(label, cause) || source}: ${cause.message}`;
672
+ } else {
673
+ message = sink.options.messages ? messageOfArgs(args) : "";
674
+ if (!message) {
675
+ s.stats.dropped.no_error_argument += 1;
676
+ return;
677
+ }
678
+ }
679
+ const anchored = new Error(redactText(message, sink.redactFields).slice(0, ANCHORED_MESSAGE_MAX));
680
+ anchored.name = "LoggedError";
681
+ const capture = Error.captureStackTrace;
682
+ if (capture) capture(anchored, boundary);
683
+ if (anchored.stack) anchored.stack = trimLibraryFrames(anchored.stack);
684
+ if (cause) anchored.cause = cause;
685
+ const pending = { anchored, cause, label, source, messageOnly: !cause };
686
+ defer(() => forward(pending));
687
+ } catch {
688
+ }
689
+ }
690
+ function forward(p) {
691
+ const s = shared();
692
+ const sink = s.sink;
693
+ if (!sink) {
694
+ s.stats.dropped.no_client += 1;
695
+ return;
696
+ }
697
+ try {
698
+ if (p.cause && s.reported.has(p.cause)) {
699
+ s.stats.dropped.already_reported += 1;
700
+ return;
701
+ }
702
+ const now = s.now();
703
+ const key = p.messageOnly ? `${firstFrame(p.anchored.stack)}|message-only` : `${firstFrame(p.anchored.stack)}|${p.anchored.message}`;
704
+ const last = s.lastSent.get(key);
705
+ if (last !== void 0 && now - last < sink.options.repeatWindowMs) {
706
+ s.stats.dropped.repeat += 1;
707
+ return;
708
+ }
709
+ if (now - s.windowStart >= 6e4) {
710
+ s.windowStart = now;
711
+ s.inWindow = 0;
712
+ }
713
+ if (s.inWindow >= sink.options.maxPerMinute) {
714
+ s.stats.dropped.rate_limited += 1;
715
+ return;
716
+ }
717
+ s.inWindow += 1;
718
+ s.lastSent.set(key, now);
719
+ if (s.lastSent.size > MAX_REMEMBERED) {
720
+ const oldest = s.lastSent.keys().next().value;
721
+ if (oldest !== void 0) s.lastSent.delete(oldest);
722
+ }
723
+ if (p.cause) s.reported.add(p.cause);
724
+ const captured = buildLoggedCapturedError(p, sink);
725
+ s.busy = true;
726
+ try {
727
+ const result = sink.report(captured);
728
+ if (result && typeof result.catch === "function") {
729
+ result.catch(() => {
730
+ });
731
+ }
732
+ s.stats.forwarded += 1;
733
+ if (p.messageOnly) s.stats.messageOnly += 1;
734
+ } finally {
735
+ s.busy = false;
736
+ }
737
+ } catch {
738
+ }
739
+ }
740
+ function nodeVersion() {
741
+ try {
742
+ return typeof process !== "undefined" && process.version ? process.version : "unknown";
743
+ } catch {
744
+ return "unknown";
745
+ }
746
+ }
747
+ function buildLoggedCapturedError(p, sink) {
748
+ const stackFrames = parseStackTrace(p.anchored.stack);
749
+ const firstAppFrame = getFirstAppFrame(stackFrames);
750
+ const route = logRoute(p.label);
751
+ const metadata = {
752
+ source: p.source,
753
+ handled: true,
754
+ ...firstAppFrame && {
755
+ sourceLocation: {
756
+ file: firstAppFrame.file,
757
+ line: firstAppFrame.line,
758
+ column: firstAppFrame.column,
759
+ function: firstAppFrame.function
760
+ }
761
+ }
762
+ };
763
+ if (p.cause) {
764
+ metadata.causeName = p.cause.name;
765
+ if (p.cause.stack) metadata.causeStack = redactText(p.cause.stack, sink.redactFields).slice(0, CAUSE_STACK_MAX);
766
+ } else {
767
+ metadata.messageOnly = true;
768
+ }
769
+ return {
770
+ id: `err_${Date.now().toString(36)}_${Math.random().toString(36).substring(2, 9)}`,
771
+ name: p.anchored.name,
772
+ message: p.anchored.message,
773
+ stack: p.anchored.stack,
774
+ stackFrames,
775
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
776
+ route,
777
+ method: "LOG",
778
+ statusCode: 500,
779
+ url: route,
780
+ environment: sink.environment,
781
+ projectId: sink.projectId,
782
+ sdkVersion: SDK_VERSION,
783
+ nodeVersion: nodeVersion(),
784
+ metadata
785
+ };
786
+ }
787
+ function attachLoggedErrorSink(sink) {
788
+ try {
789
+ const s = shared();
790
+ s.sink = sink;
791
+ if (sink.options.console) installConsoleWrapper(s);
792
+ } catch {
793
+ }
794
+ }
795
+ function detachLoggedErrorSink(sink) {
796
+ try {
797
+ const s = shared();
798
+ if (s.sink !== sink) return;
799
+ s.sink = null;
800
+ if (s.consoleWrapper && typeof console !== "undefined" && console.error === s.consoleWrapper && s.consoleOriginal) {
801
+ console.error = s.consoleOriginal;
802
+ s.consoleWrapper = null;
803
+ s.consoleOriginal = null;
804
+ }
805
+ } catch {
806
+ }
807
+ }
808
+ function installConsoleWrapper(s) {
809
+ if (typeof console === "undefined" || typeof console.error !== "function") return;
810
+ if (s.consoleWrapper && console.error === s.consoleWrapper) return;
811
+ const original = console.error;
812
+ const wrapper = function consoleErrorCapturedByBugstack(...args) {
813
+ original.apply(this === void 0 ? console : this, args);
814
+ const st = shared();
815
+ if (!st.sink || !st.sink.options.console) return;
816
+ captureLoggedCall(args, "console-error", wrapper);
817
+ };
818
+ s.consoleOriginal = original;
819
+ s.consoleWrapper = wrapper;
820
+ console.error = wrapper;
821
+ }
435
822
 
436
823
  // src/core/client.ts
437
824
  var DEFAULT_ENDPOINT = "https://dashboard.bugstack.ai/api/ingest/sdk";
@@ -461,6 +848,7 @@ var ErrorCaptureClient = class _ErrorCaptureClient {
461
848
  static instance = null;
462
849
  deduplicator;
463
850
  retryQueue;
851
+ loggedErrorSink = null;
464
852
  constructor(config) {
465
853
  const isProduction = process.env.NODE_ENV === "production";
466
854
  this.config = {
@@ -487,7 +875,8 @@ var ErrorCaptureClient = class _ErrorCaptureClient {
487
875
  dropChunkErrors: config.dropChunkErrors ?? false,
488
876
  chunkErrorsEndpoint: config.chunkErrorsEndpoint ?? deriveChunkErrorsEndpoint(
489
877
  config.endpoint ?? process.env.BUGSTACK_ENDPOINT ?? DEFAULT_ENDPOINT
490
- )
878
+ ),
879
+ captureConsoleErrors: resolveLoggedErrorOptions(config.captureConsoleErrors)
491
880
  };
492
881
  this.deduplicator = new ErrorDeduplicator(this.config.deduplicationWindow);
493
882
  this.retryQueue = new RetryQueue(
@@ -499,12 +888,23 @@ var ErrorCaptureClient = class _ErrorCaptureClient {
499
888
  debug: this.config.debug
500
889
  }
501
890
  );
891
+ if (this.config.enabled) {
892
+ this.loggedErrorSink = {
893
+ options: this.config.captureConsoleErrors,
894
+ environment: this.config.environment,
895
+ projectId: this.config.projectId,
896
+ redactFields: this.config.redactFields,
897
+ report: (error) => this.reportError(error)
898
+ };
899
+ attachLoggedErrorSink(this.loggedErrorSink);
900
+ }
502
901
  this.log("BugStack client initialized", {
503
902
  endpoint: this.config.endpoint,
504
903
  projectId: this.config.projectId,
505
904
  environment: this.config.environment,
506
905
  autoFix: this.config.autoFix,
507
- deduplicationWindow: this.config.deduplicationWindow
906
+ deduplicationWindow: this.config.deduplicationWindow,
907
+ captureConsoleErrors: this.config.captureConsoleErrors.console
508
908
  });
509
909
  }
510
910
  /**
@@ -703,6 +1103,10 @@ var ErrorCaptureClient = class _ErrorCaptureClient {
703
1103
  * Should be called when shutting down to prevent memory leaks
704
1104
  */
705
1105
  destroy() {
1106
+ if (this.loggedErrorSink) {
1107
+ detachLoggedErrorSink(this.loggedErrorSink);
1108
+ this.loggedErrorSink = null;
1109
+ }
706
1110
  this.deduplicator.destroy();
707
1111
  this.retryQueue.destroy();
708
1112
  }
@@ -897,45 +1301,6 @@ async function safeParseBody(request, maxSize, client) {
897
1301
  }
898
1302
  }
899
1303
 
900
- // src/core/utils/stack-parser.ts
901
- var V8_STACK_FRAME_REGEX = /^\s*at\s+(?:async\s+)?(?:(.+?)\s+\()?(?:(.+?):(\d+):(\d+))\)?$/;
902
- function isNodeModule(filePath) {
903
- return filePath.includes("node_modules");
904
- }
905
- function isInternalCode(filePath) {
906
- return filePath.startsWith("node:") || filePath.startsWith("internal/") || !filePath.includes("/");
907
- }
908
- function cleanFunctionName(name) {
909
- if (!name) return void 0;
910
- return name.replace(/^Object\./, "").replace(/^Module\./, "").replace(/^__webpack_require__\./, "").replace(/^webpack_require\./, "").trim();
911
- }
912
- function parseStackTrace(stack) {
913
- if (!stack) return [];
914
- const lines = stack.split("\n");
915
- const frames = [];
916
- for (const line of lines) {
917
- const match = V8_STACK_FRAME_REGEX.exec(line);
918
- if (match) {
919
- const [, functionName, file, lineStr, columnStr] = match;
920
- const frame = {
921
- function: cleanFunctionName(functionName),
922
- file: file ?? void 0,
923
- line: lineStr ? parseInt(lineStr, 10) : void 0,
924
- column: columnStr ? parseInt(columnStr, 10) : void 0
925
- };
926
- if (frame.file) {
927
- frame.isNodeModule = isNodeModule(frame.file);
928
- frame.isInternal = isInternalCode(frame.file);
929
- }
930
- frames.push(frame);
931
- }
932
- }
933
- return frames;
934
- }
935
- function getFirstAppFrame(frames) {
936
- return frames.find((frame) => !frame.isNodeModule && !frame.isInternal);
937
- }
938
-
939
1304
  // src/adapters/nextjs/index.ts
940
1305
  function generateErrorId() {
941
1306
  const timestamp = Date.now().toString(36);
@@ -1040,6 +1405,7 @@ function withErrorCapture(handler, config, routeOptions) {
1040
1405
  const response = await handler(request, context);
1041
1406
  return response;
1042
1407
  } catch (error) {
1408
+ markErrorReported(error);
1043
1409
  const err = error instanceof Error ? error : new Error(String(error));
1044
1410
  if (client) {
1045
1411
  const clientConfig = client.getConfig();