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