miaoda-react-devkit 0.1.1-beta.7 → 0.1.1-beta.9

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/index.cjs CHANGED
@@ -30,18 +30,14 @@ __export(src_exports, {
30
30
  DEFAULT_PGREST_WHITELIST_CODES: () => DEFAULT_PGREST_WHITELIST_CODES,
31
31
  SentryCapture: () => SentryCapture,
32
32
  createNoopSubscriber: () => createNoopSubscriber,
33
- createPostMessageSubscriber: () => createPostMessageSubscriber
33
+ createPostMessageSubscriber: () => createPostMessageSubscriber,
34
+ createSentryEventSubscriber: () => createSentryEventSubscriber
34
35
  });
35
36
  module.exports = __toCommonJS(src_exports);
36
37
 
37
38
  // src/capture/console.ts
38
39
  var import_core = require("@sentry/core");
39
- var DEFAULT_CONSOLE_FILTER_KEYWORDS = [
40
- "Sentry initialized successfully",
41
- "[vite] ",
42
- "Download the React DevTools for a better development experience"
43
- ];
44
- function serializeArg(arg) {
40
+ function formatConsoleArg(arg) {
45
41
  if (typeof arg === "string") return arg;
46
42
  if (arg instanceof Error) return arg.message;
47
43
  try {
@@ -50,9 +46,17 @@ function serializeArg(arg) {
50
46
  return String(arg);
51
47
  }
52
48
  }
49
+ function formatConsoleArgs(args) {
50
+ return args.map(formatConsoleArg).join(" ");
51
+ }
52
+ var DEFAULT_CONSOLE_FILTER_KEYWORDS = [
53
+ "Sentry initialized successfully",
54
+ "[vite] ",
55
+ "Download the React DevTools for a better development experience"
56
+ ];
53
57
  function shouldFilterConsole(args, keywords) {
54
58
  if (keywords.length === 0) return false;
55
- const text = args.map(serializeArg).join(" ");
59
+ const text = formatConsoleArgs(args);
56
60
  return keywords.some((kw) => text.includes(kw));
57
61
  }
58
62
  function shouldFilterConsoleMessage(message, keywords) {
@@ -68,9 +72,20 @@ function createConsoleObserver(keywords, subscribers) {
68
72
  for (const sub of subscribers) sub.onConsole(info);
69
73
  });
70
74
  },
71
- beforeBreadcrumb(breadcrumb, _hint) {
75
+ beforeBreadcrumb(breadcrumb, hint) {
72
76
  if (breadcrumb.category === "console" && breadcrumb.message != null) {
73
77
  if (shouldFilterConsoleMessage(breadcrumb.message, keywords)) return null;
78
+ const h = hint;
79
+ const consoleType = h?.level ?? "log";
80
+ const stacks = (h?.input ?? []).filter((arg) => arg instanceof Error && arg.stack != null).map((err) => err.stack);
81
+ const originalMessage = breadcrumb.message;
82
+ breadcrumb.message = `[${consoleType}]${originalMessage}`;
83
+ breadcrumb.data = {
84
+ ...breadcrumb.data ?? {},
85
+ consoleType,
86
+ message: originalMessage,
87
+ ...stacks.length > 0 ? { stack: stacks.join("\n\n") } : {}
88
+ };
74
89
  }
75
90
  return breadcrumb;
76
91
  }
@@ -116,6 +131,16 @@ function getFetchRequestArgBody(fetchArgs = []) {
116
131
  return fetchArgs[1].body;
117
132
  }
118
133
 
134
+ // src/utils.ts
135
+ function stripUrlOrigin(url) {
136
+ try {
137
+ const u = new URL(url);
138
+ return u.pathname + u.search + u.hash;
139
+ } catch {
140
+ return url;
141
+ }
142
+ }
143
+
119
144
  // src/capture/pgrest.ts
120
145
  var DEFAULT_PGREST_URL_PATTERNS = [/\/rest\/v1\//];
121
146
  var DEFAULT_PGREST_WHITELIST_CODES = [
@@ -194,6 +219,10 @@ function parseAuthErrorBody(body) {
194
219
 
195
220
  // src/capture/network.ts
196
221
  var BODY_TRUNCATE_LIMIT = 2e3;
222
+ function calcDuration(hint) {
223
+ if (hint?.startTimestamp == null || hint?.endTimestamp == null) return void 0;
224
+ return Math.round((hint.endTimestamp - hint.startTimestamp) * 1e3);
225
+ }
197
226
  var DEFAULT_IGNORE_URLS = [
198
227
  /\.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot|map)(\?.*)?$/,
199
228
  /\.chunk\./,
@@ -243,7 +272,15 @@ function handleXhrBreadcrumb(breadcrumb, hint, handler) {
243
272
  breadcrumb.data["requestBody"] = requestBody;
244
273
  breadcrumb.data["responseBody"] = responseBody;
245
274
  }
246
- void handler({ type: "xhr", method, url, statusCode, requestBody, responseBody, isError });
275
+ const duration = calcDuration(hint);
276
+ const relativeUrl = stripUrlOrigin(url);
277
+ const statusStr = statusCode != null ? String(statusCode) : "failed";
278
+ const durationStr = duration != null ? ` (${duration}ms)` : "";
279
+ breadcrumb.message = `XHR ${method} ${relativeUrl} -> ${statusStr}${durationStr}`;
280
+ if (breadcrumb.data) {
281
+ breadcrumb.data["duration"] = duration;
282
+ }
283
+ void handler({ type: "xhr", method, url, statusCode, requestBody, responseBody, isError, duration });
247
284
  }
248
285
  async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
249
286
  const data = breadcrumb.data;
@@ -253,19 +290,24 @@ async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
253
290
  const isError = hint?.data != null;
254
291
  const response = hint?.response;
255
292
  const cause = hint?.data instanceof Error ? hint.data : void 0;
256
- const fetchArgs = hint?.input;
257
- const reqBody = getFetchRequestArgBody(fetchArgs ?? []);
293
+ const reqBody = getFetchRequestArgBody(hint?.input ?? []);
258
294
  const [rawRequestBody] = getBodyString(reqBody);
259
295
  const requestBody = rawRequestBody != null ? truncateBody(rawRequestBody) : void 0;
296
+ const duration = calcDuration(hint);
297
+ const relativeUrl = stripUrlOrigin(url);
298
+ const statusStr = statusCode != null ? String(statusCode) : "failed";
299
+ const durationStr = duration != null ? ` (${duration}ms)` : "";
300
+ breadcrumb.message = `Fetch ${method} ${relativeUrl} -> ${statusStr}${durationStr}`;
260
301
  if (breadcrumb.data) {
261
302
  breadcrumb.data["requestBody"] = requestBody;
303
+ breadcrumb.data["duration"] = duration;
262
304
  }
263
305
  const contentType = response?.headers?.get("content-type") ?? "";
264
306
  if (isStreamByContentType(contentType)) {
265
307
  if (breadcrumb.data) {
266
308
  breadcrumb.data["responseBody"] = "[streaming response - not captured]";
267
309
  }
268
- await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody: "[streaming response - not captured]", isError, cause });
310
+ await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody: "[streaming response - not captured]", isError, cause, duration });
269
311
  return;
270
312
  }
271
313
  let responseBody;
@@ -285,7 +327,7 @@ async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
285
327
  if (breadcrumb.data) {
286
328
  breadcrumb.data["responseBody"] = responseBody;
287
329
  }
288
- await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody, isError, cause });
330
+ await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody, isError, cause, duration });
289
331
  }
290
332
  function createNetworkObserver(opts, subscribers) {
291
333
  const shouldIgnore = createUrlMatcher(opts.ignoreUrls);
@@ -365,10 +407,11 @@ function createNetworkObserver(opts, subscribers) {
365
407
  const fetchHandler = makeHandler("fetch");
366
408
  client.on("beforeAddBreadcrumb", (breadcrumb, hint) => {
367
409
  const url = breadcrumb.data?.url ?? "";
368
- if (shouldIgnore(url)) return;
369
410
  if (breadcrumb.category === "xhr") {
411
+ if (shouldIgnore(url)) return;
370
412
  handleXhrBreadcrumb(breadcrumb, hint, xhrHandler);
371
413
  } else if (breadcrumb.category === "fetch") {
414
+ if (shouldIgnore(url)) return;
372
415
  void handleFetchBreadcrumb(breadcrumb, hint, fetchHandler);
373
416
  }
374
417
  });
@@ -464,7 +507,7 @@ var PostMessageSubscriber = class {
464
507
  // postMessage 场景不需要上报 network 日志
465
508
  onNetworkRequest(_info) {
466
509
  }
467
- onPgRestWhitelistError({ type, method, url, statusCode, pgRestError, requestBody, responseBody }) {
510
+ onPgRestWhitelistError({ type, method, url, statusCode, pgRestError, requestBody, responseBody, precedingBreadcrumbs }) {
468
511
  const urlPath = extractUrlPath(url);
469
512
  const code = pgRestError.code;
470
513
  const errorMessage = `${method} ${urlPath} -> ${statusCode} [PgRest:${code}]`;
@@ -487,12 +530,13 @@ var PostMessageSubscriber = class {
487
530
  pgRestCode: code,
488
531
  pgRestDetails: pgRestError.details ?? void 0,
489
532
  pgRestHint: pgRestError.hint ?? void 0,
490
- requestType: type
533
+ requestType: type,
534
+ precedingBreadcrumbs
491
535
  }
492
536
  };
493
537
  this.send(msg, "*");
494
538
  }
495
- onAuthWhitelistError({ type, method, url, statusCode, authError, requestBody, responseBody }) {
539
+ onAuthWhitelistError({ type, method, url, statusCode, authError, requestBody, responseBody, precedingBreadcrumbs }) {
496
540
  const urlPath = extractUrlPath(url);
497
541
  const code = authError.code;
498
542
  const errorMessage = `${method} ${urlPath} -> ${statusCode} [Auth:${code}]`;
@@ -514,7 +558,8 @@ var PostMessageSubscriber = class {
514
558
  responseBody,
515
559
  authCode: code,
516
560
  authRequestId: authError.requestId ?? void 0,
517
- requestType: type
561
+ requestType: type,
562
+ precedingBreadcrumbs
518
563
  }
519
564
  };
520
565
  this.send(msg, "*");
@@ -539,6 +584,75 @@ function createNoopSubscriber() {
539
584
  }
540
585
  };
541
586
  }
587
+
588
+ // src/subscribers/sentryEventSubscriber.ts
589
+ var import_core4 = require("@sentry/core");
590
+ function toSentryLevel(consoleLevel) {
591
+ switch (consoleLevel) {
592
+ case "error":
593
+ return "error";
594
+ case "warn":
595
+ return "warning";
596
+ case "debug":
597
+ return "debug";
598
+ case "info":
599
+ return "info";
600
+ default:
601
+ return "log";
602
+ }
603
+ }
604
+ var SentryEventSubscriber = class {
605
+ constructor(opts = {}) {
606
+ __publicField(this, "captureAllNetworkRequests");
607
+ this.captureAllNetworkRequests = opts.captureAllNetworkRequests ?? true;
608
+ }
609
+ onConsole(info) {
610
+ const { level, args } = info;
611
+ const formattedMessage = formatConsoleArgs(args);
612
+ const sentryLevel = toSentryLevel(level);
613
+ (0, import_core4.captureEvent)({
614
+ message: `[${level}]${formattedMessage}`,
615
+ level: sentryLevel,
616
+ // 按 level + 消息内容前 100 字符分组,同一类日志聚合为同一个 Issue
617
+ fingerprint: ["console", level, formattedMessage.slice(0, 100)],
618
+ tags: {
619
+ type: "console"
620
+ },
621
+ extra: { consoleType: level, args }
622
+ });
623
+ }
624
+ // Sentry 已自动捕获 JS 错误,不重复上报
625
+ onError(_info) {
626
+ }
627
+ onNetworkRequest(info) {
628
+ const { type, method, url, statusCode, requestBody, responseBody, isError, duration } = info;
629
+ const shouldCapture = this.captureAllNetworkRequests || isError || statusCode != null && statusCode >= 400;
630
+ if (!shouldCapture) return;
631
+ const urlPath = stripUrlOrigin(url);
632
+ const requestTypeLabel = type === "xhr" ? "XHR" : "Fetch";
633
+ const statusStr = statusCode != null ? String(statusCode) : "failed";
634
+ const durationStr = duration != null ? ` (${duration}ms)` : "";
635
+ const message = `${requestTypeLabel} ${method} ${urlPath} -> ${statusStr}${durationStr}`;
636
+ const level = isError ? "error" : statusCode != null && statusCode >= 400 ? "warning" : "info";
637
+ (0, import_core4.captureEvent)({
638
+ message,
639
+ level,
640
+ // 按 method + url 路径固定分组,同一接口的多次报错聚合为同一个 Issue
641
+ fingerprint: ["network", method, urlPath],
642
+ tags: {
643
+ type: "network"
644
+ },
645
+ extra: { url, method, statusCode, duration, requestBody, responseBody }
646
+ });
647
+ }
648
+ onPgRestWhitelistError(_info) {
649
+ }
650
+ onAuthWhitelistError(_info) {
651
+ }
652
+ };
653
+ function createSentryEventSubscriber(opts) {
654
+ return new SentryEventSubscriber(opts);
655
+ }
542
656
  // Annotate the CommonJS export names for ESM import in node:
543
657
  0 && (module.exports = {
544
658
  DEFAULT_AUTH_URL_PATTERNS,
@@ -549,5 +663,6 @@ function createNoopSubscriber() {
549
663
  DEFAULT_PGREST_WHITELIST_CODES,
550
664
  SentryCapture,
551
665
  createNoopSubscriber,
552
- createPostMessageSubscriber
666
+ createPostMessageSubscriber,
667
+ createSentryEventSubscriber
553
668
  });
package/dist/index.d.cts CHANGED
@@ -91,6 +91,11 @@ interface INetworkRequestInfo {
91
91
  * XHR 网络失败时 Sentry hint 中不携带 Error 对象,此字段为 undefined。
92
92
  */
93
93
  cause?: Error;
94
+ /**
95
+ * 请求持续时间(毫秒),由 hint.startTimestamp / hint.endTimestamp 计算。
96
+ * 无法获取时间信息时为 undefined。
97
+ */
98
+ duration?: number;
94
99
  }
95
100
  /**
96
101
  * 捕获到 PostgREST 白名单错误时的事件数据。
@@ -237,6 +242,7 @@ interface GlobalErrorMessage {
237
242
  /** AuthWhitelistError 专属字段 */
238
243
  authCode?: string;
239
244
  authRequestId?: string;
245
+ precedingBreadcrumbs?: Breadcrumb[];
240
246
  };
241
247
  }
242
248
  type PostMessageFn = (message: GlobalErrorMessage, targetOrigin: string) => void;
@@ -294,4 +300,36 @@ declare function createPostMessageSubscriber(send?: PostMessageFn): ICaptureSubs
294
300
  /** 创建一个什么都不做的订阅者,方便测试时按需 spy 或替换单个方法。 */
295
301
  declare function createNoopSubscriber(): ICaptureSubscriber;
296
302
 
297
- export { DEFAULT_AUTH_URL_PATTERNS, DEFAULT_AUTH_WHITELIST_CODES, DEFAULT_CONSOLE_FILTER_KEYWORDS, DEFAULT_IGNORE_URLS, DEFAULT_PGREST_URL_PATTERNS, DEFAULT_PGREST_WHITELIST_CODES, type GlobalErrorMessage, type IAuthErrorBody, type IAuthWhitelistErrorInfo, type ICaptureSubscriber, type IConsoleCaptureInfo, type IErrorCaptureInfo, type INetworkRequestInfo, type IPgRestErrorBody, type IPgRestWhitelistErrorInfo, type ISentryCaptureOptions, type PostMessageFn, SentryCapture, createNoopSubscriber, createPostMessageSubscriber };
303
+ /**
304
+ * 通过 Sentry.captureEvent 为每条 console 日志和网络请求创建独立 Sentry Event 的订阅者。
305
+ *
306
+ * - console.* → 一条 Sentry Event,level 与 console 级别对应
307
+ * - 网络请求 → 一条 Sentry Event,message 格式为 "Fetch POST /path -> 409 (32ms)"
308
+ *
309
+ * onError 不处理,Sentry 已自动捕获并上报 JS 错误,无需重复 captureEvent。
310
+ */
311
+
312
+ interface ISentryEventSubscriberOptions {
313
+ /**
314
+ * 是否为所有网络请求(包括 2xx/3xx)创建 Sentry Event。
315
+ * 默认 true(与 vite-plugin-monitor 旧版行为一致)。
316
+ * 设为 false 时仅为 4xx、5xx 以及网络层失败创建 Event。
317
+ */
318
+ captureAllNetworkRequests?: boolean;
319
+ }
320
+ /**
321
+ * 为每条 console 日志和网络请求创建独立 Sentry Event 的订阅者。
322
+ *
323
+ * @example
324
+ * ```ts
325
+ * const capture = new SentryCapture({
326
+ * consoleFilterKeywords: DEFAULT_CONSOLE_FILTER_KEYWORDS,
327
+ * ignoreUrls: DEFAULT_IGNORE_URLS,
328
+ * });
329
+ * capture.addSubscriber(createSentryEventSubscriber());
330
+ * capture.addSubscriber(createPostMessageSubscriber());
331
+ * ```
332
+ */
333
+ declare function createSentryEventSubscriber(opts?: ISentryEventSubscriberOptions): ICaptureSubscriber;
334
+
335
+ export { DEFAULT_AUTH_URL_PATTERNS, DEFAULT_AUTH_WHITELIST_CODES, DEFAULT_CONSOLE_FILTER_KEYWORDS, DEFAULT_IGNORE_URLS, DEFAULT_PGREST_URL_PATTERNS, DEFAULT_PGREST_WHITELIST_CODES, type GlobalErrorMessage, type IAuthErrorBody, type IAuthWhitelistErrorInfo, type ICaptureSubscriber, type IConsoleCaptureInfo, type IErrorCaptureInfo, type INetworkRequestInfo, type IPgRestErrorBody, type IPgRestWhitelistErrorInfo, type ISentryCaptureOptions, type ISentryEventSubscriberOptions, type PostMessageFn, SentryCapture, createNoopSubscriber, createPostMessageSubscriber, createSentryEventSubscriber };
package/dist/index.d.ts CHANGED
@@ -91,6 +91,11 @@ interface INetworkRequestInfo {
91
91
  * XHR 网络失败时 Sentry hint 中不携带 Error 对象,此字段为 undefined。
92
92
  */
93
93
  cause?: Error;
94
+ /**
95
+ * 请求持续时间(毫秒),由 hint.startTimestamp / hint.endTimestamp 计算。
96
+ * 无法获取时间信息时为 undefined。
97
+ */
98
+ duration?: number;
94
99
  }
95
100
  /**
96
101
  * 捕获到 PostgREST 白名单错误时的事件数据。
@@ -237,6 +242,7 @@ interface GlobalErrorMessage {
237
242
  /** AuthWhitelistError 专属字段 */
238
243
  authCode?: string;
239
244
  authRequestId?: string;
245
+ precedingBreadcrumbs?: Breadcrumb[];
240
246
  };
241
247
  }
242
248
  type PostMessageFn = (message: GlobalErrorMessage, targetOrigin: string) => void;
@@ -294,4 +300,36 @@ declare function createPostMessageSubscriber(send?: PostMessageFn): ICaptureSubs
294
300
  /** 创建一个什么都不做的订阅者,方便测试时按需 spy 或替换单个方法。 */
295
301
  declare function createNoopSubscriber(): ICaptureSubscriber;
296
302
 
297
- export { DEFAULT_AUTH_URL_PATTERNS, DEFAULT_AUTH_WHITELIST_CODES, DEFAULT_CONSOLE_FILTER_KEYWORDS, DEFAULT_IGNORE_URLS, DEFAULT_PGREST_URL_PATTERNS, DEFAULT_PGREST_WHITELIST_CODES, type GlobalErrorMessage, type IAuthErrorBody, type IAuthWhitelistErrorInfo, type ICaptureSubscriber, type IConsoleCaptureInfo, type IErrorCaptureInfo, type INetworkRequestInfo, type IPgRestErrorBody, type IPgRestWhitelistErrorInfo, type ISentryCaptureOptions, type PostMessageFn, SentryCapture, createNoopSubscriber, createPostMessageSubscriber };
303
+ /**
304
+ * 通过 Sentry.captureEvent 为每条 console 日志和网络请求创建独立 Sentry Event 的订阅者。
305
+ *
306
+ * - console.* → 一条 Sentry Event,level 与 console 级别对应
307
+ * - 网络请求 → 一条 Sentry Event,message 格式为 "Fetch POST /path -> 409 (32ms)"
308
+ *
309
+ * onError 不处理,Sentry 已自动捕获并上报 JS 错误,无需重复 captureEvent。
310
+ */
311
+
312
+ interface ISentryEventSubscriberOptions {
313
+ /**
314
+ * 是否为所有网络请求(包括 2xx/3xx)创建 Sentry Event。
315
+ * 默认 true(与 vite-plugin-monitor 旧版行为一致)。
316
+ * 设为 false 时仅为 4xx、5xx 以及网络层失败创建 Event。
317
+ */
318
+ captureAllNetworkRequests?: boolean;
319
+ }
320
+ /**
321
+ * 为每条 console 日志和网络请求创建独立 Sentry Event 的订阅者。
322
+ *
323
+ * @example
324
+ * ```ts
325
+ * const capture = new SentryCapture({
326
+ * consoleFilterKeywords: DEFAULT_CONSOLE_FILTER_KEYWORDS,
327
+ * ignoreUrls: DEFAULT_IGNORE_URLS,
328
+ * });
329
+ * capture.addSubscriber(createSentryEventSubscriber());
330
+ * capture.addSubscriber(createPostMessageSubscriber());
331
+ * ```
332
+ */
333
+ declare function createSentryEventSubscriber(opts?: ISentryEventSubscriberOptions): ICaptureSubscriber;
334
+
335
+ export { DEFAULT_AUTH_URL_PATTERNS, DEFAULT_AUTH_WHITELIST_CODES, DEFAULT_CONSOLE_FILTER_KEYWORDS, DEFAULT_IGNORE_URLS, DEFAULT_PGREST_URL_PATTERNS, DEFAULT_PGREST_WHITELIST_CODES, type GlobalErrorMessage, type IAuthErrorBody, type IAuthWhitelistErrorInfo, type ICaptureSubscriber, type IConsoleCaptureInfo, type IErrorCaptureInfo, type INetworkRequestInfo, type IPgRestErrorBody, type IPgRestWhitelistErrorInfo, type ISentryCaptureOptions, type ISentryEventSubscriberOptions, type PostMessageFn, SentryCapture, createNoopSubscriber, createPostMessageSubscriber, createSentryEventSubscriber };
package/dist/index.js CHANGED
@@ -4,12 +4,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
4
4
 
5
5
  // src/capture/console.ts
6
6
  import { addConsoleInstrumentationHandler } from "@sentry/core";
7
- var DEFAULT_CONSOLE_FILTER_KEYWORDS = [
8
- "Sentry initialized successfully",
9
- "[vite] ",
10
- "Download the React DevTools for a better development experience"
11
- ];
12
- function serializeArg(arg) {
7
+ function formatConsoleArg(arg) {
13
8
  if (typeof arg === "string") return arg;
14
9
  if (arg instanceof Error) return arg.message;
15
10
  try {
@@ -18,9 +13,17 @@ function serializeArg(arg) {
18
13
  return String(arg);
19
14
  }
20
15
  }
16
+ function formatConsoleArgs(args) {
17
+ return args.map(formatConsoleArg).join(" ");
18
+ }
19
+ var DEFAULT_CONSOLE_FILTER_KEYWORDS = [
20
+ "Sentry initialized successfully",
21
+ "[vite] ",
22
+ "Download the React DevTools for a better development experience"
23
+ ];
21
24
  function shouldFilterConsole(args, keywords) {
22
25
  if (keywords.length === 0) return false;
23
- const text = args.map(serializeArg).join(" ");
26
+ const text = formatConsoleArgs(args);
24
27
  return keywords.some((kw) => text.includes(kw));
25
28
  }
26
29
  function shouldFilterConsoleMessage(message, keywords) {
@@ -36,9 +39,20 @@ function createConsoleObserver(keywords, subscribers) {
36
39
  for (const sub of subscribers) sub.onConsole(info);
37
40
  });
38
41
  },
39
- beforeBreadcrumb(breadcrumb, _hint) {
42
+ beforeBreadcrumb(breadcrumb, hint) {
40
43
  if (breadcrumb.category === "console" && breadcrumb.message != null) {
41
44
  if (shouldFilterConsoleMessage(breadcrumb.message, keywords)) return null;
45
+ const h = hint;
46
+ const consoleType = h?.level ?? "log";
47
+ const stacks = (h?.input ?? []).filter((arg) => arg instanceof Error && arg.stack != null).map((err) => err.stack);
48
+ const originalMessage = breadcrumb.message;
49
+ breadcrumb.message = `[${consoleType}]${originalMessage}`;
50
+ breadcrumb.data = {
51
+ ...breadcrumb.data ?? {},
52
+ consoleType,
53
+ message: originalMessage,
54
+ ...stacks.length > 0 ? { stack: stacks.join("\n\n") } : {}
55
+ };
42
56
  }
43
57
  return breadcrumb;
44
58
  }
@@ -84,6 +98,16 @@ function getFetchRequestArgBody(fetchArgs = []) {
84
98
  return fetchArgs[1].body;
85
99
  }
86
100
 
101
+ // src/utils.ts
102
+ function stripUrlOrigin(url) {
103
+ try {
104
+ const u = new URL(url);
105
+ return u.pathname + u.search + u.hash;
106
+ } catch {
107
+ return url;
108
+ }
109
+ }
110
+
87
111
  // src/capture/pgrest.ts
88
112
  var DEFAULT_PGREST_URL_PATTERNS = [/\/rest\/v1\//];
89
113
  var DEFAULT_PGREST_WHITELIST_CODES = [
@@ -162,6 +186,10 @@ function parseAuthErrorBody(body) {
162
186
 
163
187
  // src/capture/network.ts
164
188
  var BODY_TRUNCATE_LIMIT = 2e3;
189
+ function calcDuration(hint) {
190
+ if (hint?.startTimestamp == null || hint?.endTimestamp == null) return void 0;
191
+ return Math.round((hint.endTimestamp - hint.startTimestamp) * 1e3);
192
+ }
165
193
  var DEFAULT_IGNORE_URLS = [
166
194
  /\.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot|map)(\?.*)?$/,
167
195
  /\.chunk\./,
@@ -211,7 +239,15 @@ function handleXhrBreadcrumb(breadcrumb, hint, handler) {
211
239
  breadcrumb.data["requestBody"] = requestBody;
212
240
  breadcrumb.data["responseBody"] = responseBody;
213
241
  }
214
- void handler({ type: "xhr", method, url, statusCode, requestBody, responseBody, isError });
242
+ const duration = calcDuration(hint);
243
+ const relativeUrl = stripUrlOrigin(url);
244
+ const statusStr = statusCode != null ? String(statusCode) : "failed";
245
+ const durationStr = duration != null ? ` (${duration}ms)` : "";
246
+ breadcrumb.message = `XHR ${method} ${relativeUrl} -> ${statusStr}${durationStr}`;
247
+ if (breadcrumb.data) {
248
+ breadcrumb.data["duration"] = duration;
249
+ }
250
+ void handler({ type: "xhr", method, url, statusCode, requestBody, responseBody, isError, duration });
215
251
  }
216
252
  async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
217
253
  const data = breadcrumb.data;
@@ -221,19 +257,24 @@ async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
221
257
  const isError = hint?.data != null;
222
258
  const response = hint?.response;
223
259
  const cause = hint?.data instanceof Error ? hint.data : void 0;
224
- const fetchArgs = hint?.input;
225
- const reqBody = getFetchRequestArgBody(fetchArgs ?? []);
260
+ const reqBody = getFetchRequestArgBody(hint?.input ?? []);
226
261
  const [rawRequestBody] = getBodyString(reqBody);
227
262
  const requestBody = rawRequestBody != null ? truncateBody(rawRequestBody) : void 0;
263
+ const duration = calcDuration(hint);
264
+ const relativeUrl = stripUrlOrigin(url);
265
+ const statusStr = statusCode != null ? String(statusCode) : "failed";
266
+ const durationStr = duration != null ? ` (${duration}ms)` : "";
267
+ breadcrumb.message = `Fetch ${method} ${relativeUrl} -> ${statusStr}${durationStr}`;
228
268
  if (breadcrumb.data) {
229
269
  breadcrumb.data["requestBody"] = requestBody;
270
+ breadcrumb.data["duration"] = duration;
230
271
  }
231
272
  const contentType = response?.headers?.get("content-type") ?? "";
232
273
  if (isStreamByContentType(contentType)) {
233
274
  if (breadcrumb.data) {
234
275
  breadcrumb.data["responseBody"] = "[streaming response - not captured]";
235
276
  }
236
- await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody: "[streaming response - not captured]", isError, cause });
277
+ await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody: "[streaming response - not captured]", isError, cause, duration });
237
278
  return;
238
279
  }
239
280
  let responseBody;
@@ -253,7 +294,7 @@ async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
253
294
  if (breadcrumb.data) {
254
295
  breadcrumb.data["responseBody"] = responseBody;
255
296
  }
256
- await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody, isError, cause });
297
+ await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody, isError, cause, duration });
257
298
  }
258
299
  function createNetworkObserver(opts, subscribers) {
259
300
  const shouldIgnore = createUrlMatcher(opts.ignoreUrls);
@@ -333,10 +374,11 @@ function createNetworkObserver(opts, subscribers) {
333
374
  const fetchHandler = makeHandler("fetch");
334
375
  client.on("beforeAddBreadcrumb", (breadcrumb, hint) => {
335
376
  const url = breadcrumb.data?.url ?? "";
336
- if (shouldIgnore(url)) return;
337
377
  if (breadcrumb.category === "xhr") {
378
+ if (shouldIgnore(url)) return;
338
379
  handleXhrBreadcrumb(breadcrumb, hint, xhrHandler);
339
380
  } else if (breadcrumb.category === "fetch") {
381
+ if (shouldIgnore(url)) return;
340
382
  void handleFetchBreadcrumb(breadcrumb, hint, fetchHandler);
341
383
  }
342
384
  });
@@ -432,7 +474,7 @@ var PostMessageSubscriber = class {
432
474
  // postMessage 场景不需要上报 network 日志
433
475
  onNetworkRequest(_info) {
434
476
  }
435
- onPgRestWhitelistError({ type, method, url, statusCode, pgRestError, requestBody, responseBody }) {
477
+ onPgRestWhitelistError({ type, method, url, statusCode, pgRestError, requestBody, responseBody, precedingBreadcrumbs }) {
436
478
  const urlPath = extractUrlPath(url);
437
479
  const code = pgRestError.code;
438
480
  const errorMessage = `${method} ${urlPath} -> ${statusCode} [PgRest:${code}]`;
@@ -455,12 +497,13 @@ var PostMessageSubscriber = class {
455
497
  pgRestCode: code,
456
498
  pgRestDetails: pgRestError.details ?? void 0,
457
499
  pgRestHint: pgRestError.hint ?? void 0,
458
- requestType: type
500
+ requestType: type,
501
+ precedingBreadcrumbs
459
502
  }
460
503
  };
461
504
  this.send(msg, "*");
462
505
  }
463
- onAuthWhitelistError({ type, method, url, statusCode, authError, requestBody, responseBody }) {
506
+ onAuthWhitelistError({ type, method, url, statusCode, authError, requestBody, responseBody, precedingBreadcrumbs }) {
464
507
  const urlPath = extractUrlPath(url);
465
508
  const code = authError.code;
466
509
  const errorMessage = `${method} ${urlPath} -> ${statusCode} [Auth:${code}]`;
@@ -482,7 +525,8 @@ var PostMessageSubscriber = class {
482
525
  responseBody,
483
526
  authCode: code,
484
527
  authRequestId: authError.requestId ?? void 0,
485
- requestType: type
528
+ requestType: type,
529
+ precedingBreadcrumbs
486
530
  }
487
531
  };
488
532
  this.send(msg, "*");
@@ -507,6 +551,75 @@ function createNoopSubscriber() {
507
551
  }
508
552
  };
509
553
  }
554
+
555
+ // src/subscribers/sentryEventSubscriber.ts
556
+ import { captureEvent } from "@sentry/core";
557
+ function toSentryLevel(consoleLevel) {
558
+ switch (consoleLevel) {
559
+ case "error":
560
+ return "error";
561
+ case "warn":
562
+ return "warning";
563
+ case "debug":
564
+ return "debug";
565
+ case "info":
566
+ return "info";
567
+ default:
568
+ return "log";
569
+ }
570
+ }
571
+ var SentryEventSubscriber = class {
572
+ constructor(opts = {}) {
573
+ __publicField(this, "captureAllNetworkRequests");
574
+ this.captureAllNetworkRequests = opts.captureAllNetworkRequests ?? true;
575
+ }
576
+ onConsole(info) {
577
+ const { level, args } = info;
578
+ const formattedMessage = formatConsoleArgs(args);
579
+ const sentryLevel = toSentryLevel(level);
580
+ captureEvent({
581
+ message: `[${level}]${formattedMessage}`,
582
+ level: sentryLevel,
583
+ // 按 level + 消息内容前 100 字符分组,同一类日志聚合为同一个 Issue
584
+ fingerprint: ["console", level, formattedMessage.slice(0, 100)],
585
+ tags: {
586
+ type: "console"
587
+ },
588
+ extra: { consoleType: level, args }
589
+ });
590
+ }
591
+ // Sentry 已自动捕获 JS 错误,不重复上报
592
+ onError(_info) {
593
+ }
594
+ onNetworkRequest(info) {
595
+ const { type, method, url, statusCode, requestBody, responseBody, isError, duration } = info;
596
+ const shouldCapture = this.captureAllNetworkRequests || isError || statusCode != null && statusCode >= 400;
597
+ if (!shouldCapture) return;
598
+ const urlPath = stripUrlOrigin(url);
599
+ const requestTypeLabel = type === "xhr" ? "XHR" : "Fetch";
600
+ const statusStr = statusCode != null ? String(statusCode) : "failed";
601
+ const durationStr = duration != null ? ` (${duration}ms)` : "";
602
+ const message = `${requestTypeLabel} ${method} ${urlPath} -> ${statusStr}${durationStr}`;
603
+ const level = isError ? "error" : statusCode != null && statusCode >= 400 ? "warning" : "info";
604
+ captureEvent({
605
+ message,
606
+ level,
607
+ // 按 method + url 路径固定分组,同一接口的多次报错聚合为同一个 Issue
608
+ fingerprint: ["network", method, urlPath],
609
+ tags: {
610
+ type: "network"
611
+ },
612
+ extra: { url, method, statusCode, duration, requestBody, responseBody }
613
+ });
614
+ }
615
+ onPgRestWhitelistError(_info) {
616
+ }
617
+ onAuthWhitelistError(_info) {
618
+ }
619
+ };
620
+ function createSentryEventSubscriber(opts) {
621
+ return new SentryEventSubscriber(opts);
622
+ }
510
623
  export {
511
624
  DEFAULT_AUTH_URL_PATTERNS,
512
625
  DEFAULT_AUTH_WHITELIST_CODES,
@@ -516,5 +629,6 @@ export {
516
629
  DEFAULT_PGREST_WHITELIST_CODES,
517
630
  SentryCapture,
518
631
  createNoopSubscriber,
519
- createPostMessageSubscriber
632
+ createPostMessageSubscriber,
633
+ createSentryEventSubscriber
520
634
  };
@@ -0,0 +1,78 @@
1
+ // src/stubs/sentry-react-noop-stub.ts
2
+ var init = (_options) => {
3
+ };
4
+ var browserTracingIntegration = () => ({});
5
+ var captureException = (_err) => "";
6
+ var captureMessage = (_msg) => "";
7
+ var captureEvent = (_event) => "";
8
+ var addBreadcrumb = (_breadcrumb) => {
9
+ };
10
+ var setUser = (_user) => {
11
+ };
12
+ var setTag = (_key, _value) => {
13
+ };
14
+ var setTags = (_tags) => {
15
+ };
16
+ var setContext = (_key, _ctx) => {
17
+ };
18
+ var setExtra = (_key, _value) => {
19
+ };
20
+ var setExtras = (_extras) => {
21
+ };
22
+ var withScope = (cb) => {
23
+ cb({});
24
+ };
25
+ var withIsolationScope = (cb) => {
26
+ cb({});
27
+ };
28
+ var startSpan = (_opts, cb) => cb();
29
+ var getClient = () => void 0;
30
+ var flush = () => Promise.resolve(true);
31
+ var close = () => Promise.resolve(true);
32
+ var lastEventId = () => void 0;
33
+ var SDK_VERSION = "0.0.0-stub";
34
+ var ErrorBoundary = ({ children }) => children ?? null;
35
+ var withErrorBoundary = (Component) => Component;
36
+ var withProfiler = (Component) => Component;
37
+ var useProfiler = (_name) => {
38
+ };
39
+ var Profiler = ({ children }) => children ?? null;
40
+ var withSentryRouting = (Component) => Component;
41
+ var withSentryReactRouterV6Routing = (Component) => Component;
42
+ var wrapCreateBrowserRouterV6 = (fn) => fn;
43
+ var wrapCreateBrowserRouterV7 = (fn) => fn;
44
+ var reactRouterV6BrowserTracingIntegration = () => ({});
45
+ var reactRouterV7BrowserTracingIntegration = () => ({});
46
+ export {
47
+ ErrorBoundary,
48
+ Profiler,
49
+ SDK_VERSION,
50
+ addBreadcrumb,
51
+ browserTracingIntegration,
52
+ captureEvent,
53
+ captureException,
54
+ captureMessage,
55
+ close,
56
+ flush,
57
+ getClient,
58
+ init,
59
+ lastEventId,
60
+ reactRouterV6BrowserTracingIntegration,
61
+ reactRouterV7BrowserTracingIntegration,
62
+ setContext,
63
+ setExtra,
64
+ setExtras,
65
+ setTag,
66
+ setTags,
67
+ setUser,
68
+ startSpan,
69
+ useProfiler,
70
+ withErrorBoundary,
71
+ withIsolationScope,
72
+ withProfiler,
73
+ withScope,
74
+ withSentryReactRouterV6Routing,
75
+ withSentryRouting,
76
+ wrapCreateBrowserRouterV6,
77
+ wrapCreateBrowserRouterV7
78
+ };
@@ -7,12 +7,7 @@ import * as RealSentry from "@sentry/react";
7
7
 
8
8
  // src/capture/console.ts
9
9
  import { addConsoleInstrumentationHandler } from "@sentry/core";
10
- var DEFAULT_CONSOLE_FILTER_KEYWORDS = [
11
- "Sentry initialized successfully",
12
- "[vite] ",
13
- "Download the React DevTools for a better development experience"
14
- ];
15
- function serializeArg(arg) {
10
+ function formatConsoleArg(arg) {
16
11
  if (typeof arg === "string") return arg;
17
12
  if (arg instanceof Error) return arg.message;
18
13
  try {
@@ -21,9 +16,17 @@ function serializeArg(arg) {
21
16
  return String(arg);
22
17
  }
23
18
  }
19
+ function formatConsoleArgs(args) {
20
+ return args.map(formatConsoleArg).join(" ");
21
+ }
22
+ var DEFAULT_CONSOLE_FILTER_KEYWORDS = [
23
+ "Sentry initialized successfully",
24
+ "[vite] ",
25
+ "Download the React DevTools for a better development experience"
26
+ ];
24
27
  function shouldFilterConsole(args, keywords) {
25
28
  if (keywords.length === 0) return false;
26
- const text = args.map(serializeArg).join(" ");
29
+ const text = formatConsoleArgs(args);
27
30
  return keywords.some((kw) => text.includes(kw));
28
31
  }
29
32
  function shouldFilterConsoleMessage(message, keywords) {
@@ -39,9 +42,20 @@ function createConsoleObserver(keywords, subscribers) {
39
42
  for (const sub of subscribers) sub.onConsole(info);
40
43
  });
41
44
  },
42
- beforeBreadcrumb(breadcrumb, _hint) {
45
+ beforeBreadcrumb(breadcrumb, hint) {
43
46
  if (breadcrumb.category === "console" && breadcrumb.message != null) {
44
47
  if (shouldFilterConsoleMessage(breadcrumb.message, keywords)) return null;
48
+ const h = hint;
49
+ const consoleType = h?.level ?? "log";
50
+ const stacks = (h?.input ?? []).filter((arg) => arg instanceof Error && arg.stack != null).map((err) => err.stack);
51
+ const originalMessage = breadcrumb.message;
52
+ breadcrumb.message = `[${consoleType}]${originalMessage}`;
53
+ breadcrumb.data = {
54
+ ...breadcrumb.data ?? {},
55
+ consoleType,
56
+ message: originalMessage,
57
+ ...stacks.length > 0 ? { stack: stacks.join("\n\n") } : {}
58
+ };
45
59
  }
46
60
  return breadcrumb;
47
61
  }
@@ -87,6 +101,16 @@ function getFetchRequestArgBody(fetchArgs = []) {
87
101
  return fetchArgs[1].body;
88
102
  }
89
103
 
104
+ // src/utils.ts
105
+ function stripUrlOrigin(url) {
106
+ try {
107
+ const u = new URL(url);
108
+ return u.pathname + u.search + u.hash;
109
+ } catch {
110
+ return url;
111
+ }
112
+ }
113
+
90
114
  // src/capture/pgrest.ts
91
115
  var DEFAULT_PGREST_URL_PATTERNS = [/\/rest\/v1\//];
92
116
  var DEFAULT_PGREST_WHITELIST_CODES = [
@@ -165,6 +189,10 @@ function parseAuthErrorBody(body) {
165
189
 
166
190
  // src/capture/network.ts
167
191
  var BODY_TRUNCATE_LIMIT = 2e3;
192
+ function calcDuration(hint) {
193
+ if (hint?.startTimestamp == null || hint?.endTimestamp == null) return void 0;
194
+ return Math.round((hint.endTimestamp - hint.startTimestamp) * 1e3);
195
+ }
168
196
  var DEFAULT_IGNORE_URLS = [
169
197
  /\.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot|map)(\?.*)?$/,
170
198
  /\.chunk\./,
@@ -214,7 +242,15 @@ function handleXhrBreadcrumb(breadcrumb, hint, handler) {
214
242
  breadcrumb.data["requestBody"] = requestBody;
215
243
  breadcrumb.data["responseBody"] = responseBody;
216
244
  }
217
- void handler({ type: "xhr", method, url, statusCode, requestBody, responseBody, isError });
245
+ const duration = calcDuration(hint);
246
+ const relativeUrl = stripUrlOrigin(url);
247
+ const statusStr = statusCode != null ? String(statusCode) : "failed";
248
+ const durationStr = duration != null ? ` (${duration}ms)` : "";
249
+ breadcrumb.message = `XHR ${method} ${relativeUrl} -> ${statusStr}${durationStr}`;
250
+ if (breadcrumb.data) {
251
+ breadcrumb.data["duration"] = duration;
252
+ }
253
+ void handler({ type: "xhr", method, url, statusCode, requestBody, responseBody, isError, duration });
218
254
  }
219
255
  async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
220
256
  const data = breadcrumb.data;
@@ -224,19 +260,24 @@ async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
224
260
  const isError = hint?.data != null;
225
261
  const response = hint?.response;
226
262
  const cause = hint?.data instanceof Error ? hint.data : void 0;
227
- const fetchArgs = hint?.input;
228
- const reqBody = getFetchRequestArgBody(fetchArgs ?? []);
263
+ const reqBody = getFetchRequestArgBody(hint?.input ?? []);
229
264
  const [rawRequestBody] = getBodyString(reqBody);
230
265
  const requestBody = rawRequestBody != null ? truncateBody(rawRequestBody) : void 0;
266
+ const duration = calcDuration(hint);
267
+ const relativeUrl = stripUrlOrigin(url);
268
+ const statusStr = statusCode != null ? String(statusCode) : "failed";
269
+ const durationStr = duration != null ? ` (${duration}ms)` : "";
270
+ breadcrumb.message = `Fetch ${method} ${relativeUrl} -> ${statusStr}${durationStr}`;
231
271
  if (breadcrumb.data) {
232
272
  breadcrumb.data["requestBody"] = requestBody;
273
+ breadcrumb.data["duration"] = duration;
233
274
  }
234
275
  const contentType = response?.headers?.get("content-type") ?? "";
235
276
  if (isStreamByContentType(contentType)) {
236
277
  if (breadcrumb.data) {
237
278
  breadcrumb.data["responseBody"] = "[streaming response - not captured]";
238
279
  }
239
- await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody: "[streaming response - not captured]", isError, cause });
280
+ await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody: "[streaming response - not captured]", isError, cause, duration });
240
281
  return;
241
282
  }
242
283
  let responseBody;
@@ -256,7 +297,7 @@ async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
256
297
  if (breadcrumb.data) {
257
298
  breadcrumb.data["responseBody"] = responseBody;
258
299
  }
259
- await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody, isError, cause });
300
+ await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody, isError, cause, duration });
260
301
  }
261
302
  function createNetworkObserver(opts, subscribers) {
262
303
  const shouldIgnore = createUrlMatcher(opts.ignoreUrls);
@@ -336,10 +377,11 @@ function createNetworkObserver(opts, subscribers) {
336
377
  const fetchHandler = makeHandler("fetch");
337
378
  client.on("beforeAddBreadcrumb", (breadcrumb, hint) => {
338
379
  const url = breadcrumb.data?.url ?? "";
339
- if (shouldIgnore(url)) return;
340
380
  if (breadcrumb.category === "xhr") {
381
+ if (shouldIgnore(url)) return;
341
382
  handleXhrBreadcrumb(breadcrumb, hint, xhrHandler);
342
383
  } else if (breadcrumb.category === "fetch") {
384
+ if (shouldIgnore(url)) return;
343
385
  void handleFetchBreadcrumb(breadcrumb, hint, fetchHandler);
344
386
  }
345
387
  });
@@ -435,7 +477,7 @@ var PostMessageSubscriber = class {
435
477
  // postMessage 场景不需要上报 network 日志
436
478
  onNetworkRequest(_info) {
437
479
  }
438
- onPgRestWhitelistError({ type, method, url, statusCode, pgRestError, requestBody, responseBody }) {
480
+ onPgRestWhitelistError({ type, method, url, statusCode, pgRestError, requestBody, responseBody, precedingBreadcrumbs }) {
439
481
  const urlPath = extractUrlPath(url);
440
482
  const code = pgRestError.code;
441
483
  const errorMessage = `${method} ${urlPath} -> ${statusCode} [PgRest:${code}]`;
@@ -458,12 +500,13 @@ var PostMessageSubscriber = class {
458
500
  pgRestCode: code,
459
501
  pgRestDetails: pgRestError.details ?? void 0,
460
502
  pgRestHint: pgRestError.hint ?? void 0,
461
- requestType: type
503
+ requestType: type,
504
+ precedingBreadcrumbs
462
505
  }
463
506
  };
464
507
  this.send(msg, "*");
465
508
  }
466
- onAuthWhitelistError({ type, method, url, statusCode, authError, requestBody, responseBody }) {
509
+ onAuthWhitelistError({ type, method, url, statusCode, authError, requestBody, responseBody, precedingBreadcrumbs }) {
467
510
  const urlPath = extractUrlPath(url);
468
511
  const code = authError.code;
469
512
  const errorMessage = `${method} ${urlPath} -> ${statusCode} [Auth:${code}]`;
@@ -485,7 +528,8 @@ var PostMessageSubscriber = class {
485
528
  responseBody,
486
529
  authCode: code,
487
530
  authRequestId: authError.requestId ?? void 0,
488
- requestType: type
531
+ requestType: type,
532
+ precedingBreadcrumbs
489
533
  }
490
534
  };
491
535
  this.send(msg, "*");
@@ -498,7 +542,8 @@ function createPostMessageSubscriber(send) {
498
542
  // src/stubs/sentry-react-stub.ts
499
543
  export * from "@sentry/react";
500
544
  var STUB_DSN = "https://stubPublicKey@o0.ingest.sentry.io/0";
501
- var OVERRIDE_DSN = typeof process !== "undefined" && process.env["SENTRY_OVERRIDE_DSN"] ? process.env["SENTRY_OVERRIDE_DSN"] : STUB_DSN;
545
+ var OVERRIDE_DSN = import.meta.env.VITE_SENTRY_DSN || STUB_DSN;
546
+ var OVERRIDE_ENVIRONMENT = import.meta.env.VITE_SENTRY_ENV;
502
547
  var _subscribers = [createPostMessageSubscriber()];
503
548
  function configureStubSubscribers(subscribers) {
504
549
  _subscribers = subscribers;
@@ -516,6 +561,7 @@ var init2 = (options) => {
516
561
  const result = RealSentry.init({
517
562
  ...options,
518
563
  dsn: OVERRIDE_DSN,
564
+ environment: OVERRIDE_ENVIRONMENT,
519
565
  beforeSend(event, hint) {
520
566
  const processed = capture.beforeSend(event, hint);
521
567
  return upstreamBeforeSend ? upstreamBeforeSend(processed, hint) : processed;
@@ -526,6 +572,15 @@ var init2 = (options) => {
526
572
  return upstreamBeforeBreadcrumb ? upstreamBeforeBreadcrumb(processed, hint) : processed;
527
573
  }
528
574
  });
575
+ const stubTags = {
576
+ app_id: import.meta.env.VITE_APP_ID,
577
+ environment: OVERRIDE_ENVIRONMENT
578
+ };
579
+ for (const [key, value] of Object.entries(stubTags)) {
580
+ if (value) {
581
+ RealSentry.setTag(key, value);
582
+ }
583
+ }
529
584
  capture.installNetworkObserver();
530
585
  capture.installConsoleObserver();
531
586
  return result;
@@ -31,6 +31,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var vite_exports = {};
32
32
  __export(vite_exports, {
33
33
  hmrTogglePlugin: () => hmrTogglePlugin,
34
+ withSentryBuild: () => withSentryBuild,
34
35
  withSentryStub: () => withSentryStub
35
36
  });
36
37
  module.exports = __toCommonJS(vite_exports);
@@ -60,6 +61,24 @@ function withSentryStub() {
60
61
  };
61
62
  }
62
63
 
64
+ // src/vite/withSentryBuild.ts
65
+ var import_node_path2 = __toESM(require("path"), 1);
66
+ var import_node_url2 = require("url");
67
+ var SENTRY_MODULE2 = "@sentry/react";
68
+ var _dirname2 = import_node_path2.default.dirname((0, import_node_url2.fileURLToPath)(importMetaUrl));
69
+ var STUB_PATH2 = import_node_path2.default.resolve(_dirname2, "../stubs/sentry-react-noop-stub.js");
70
+ function withSentryBuild() {
71
+ return {
72
+ name: "miaoda-devkit:sentry-build",
73
+ enforce: "pre",
74
+ apply: "build",
75
+ resolveId(id) {
76
+ if (id === SENTRY_MODULE2) return STUB_PATH2;
77
+ return null;
78
+ }
79
+ };
80
+ }
81
+
63
82
  // src/vite/hmrTogglePlugin.ts
64
83
  function hmrTogglePlugin() {
65
84
  return {
@@ -120,5 +139,6 @@ function hmrTogglePlugin() {
120
139
  // Annotate the CommonJS export names for ESM import in node:
121
140
  0 && (module.exports = {
122
141
  hmrTogglePlugin,
142
+ withSentryBuild,
123
143
  withSentryStub
124
144
  });
@@ -9,6 +9,8 @@ import { Plugin } from 'vite';
9
9
 
10
10
  declare function withSentryStub(): Plugin;
11
11
 
12
+ declare function withSentryBuild(): Plugin;
13
+
12
14
  /**
13
15
  * 云端 dev server 专用:HMR 开关 + 手动 reload 控制接口。
14
16
  *
@@ -21,4 +23,4 @@ declare function withSentryStub(): Plugin;
21
23
  */
22
24
  declare function hmrTogglePlugin(): Plugin;
23
25
 
24
- export { hmrTogglePlugin, withSentryStub };
26
+ export { hmrTogglePlugin, withSentryBuild, withSentryStub };
@@ -9,6 +9,8 @@ import { Plugin } from 'vite';
9
9
 
10
10
  declare function withSentryStub(): Plugin;
11
11
 
12
+ declare function withSentryBuild(): Plugin;
13
+
12
14
  /**
13
15
  * 云端 dev server 专用:HMR 开关 + 手动 reload 控制接口。
14
16
  *
@@ -21,4 +23,4 @@ declare function withSentryStub(): Plugin;
21
23
  */
22
24
  declare function hmrTogglePlugin(): Plugin;
23
25
 
24
- export { hmrTogglePlugin, withSentryStub };
26
+ export { hmrTogglePlugin, withSentryBuild, withSentryStub };
@@ -19,6 +19,24 @@ function withSentryStub() {
19
19
  };
20
20
  }
21
21
 
22
+ // src/vite/withSentryBuild.ts
23
+ import path2 from "path";
24
+ import { fileURLToPath as fileURLToPath2 } from "url";
25
+ var SENTRY_MODULE2 = "@sentry/react";
26
+ var _dirname2 = path2.dirname(fileURLToPath2(import.meta.url));
27
+ var STUB_PATH2 = path2.resolve(_dirname2, "../stubs/sentry-react-noop-stub.js");
28
+ function withSentryBuild() {
29
+ return {
30
+ name: "miaoda-devkit:sentry-build",
31
+ enforce: "pre",
32
+ apply: "build",
33
+ resolveId(id) {
34
+ if (id === SENTRY_MODULE2) return STUB_PATH2;
35
+ return null;
36
+ }
37
+ };
38
+ }
39
+
22
40
  // src/vite/hmrTogglePlugin.ts
23
41
  function hmrTogglePlugin() {
24
42
  return {
@@ -78,5 +96,6 @@ function hmrTogglePlugin() {
78
96
  }
79
97
  export {
80
98
  hmrTogglePlugin,
99
+ withSentryBuild,
81
100
  withSentryStub
82
101
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "miaoda-react-devkit",
3
- "version": "0.1.1-beta.7",
3
+ "version": "0.1.1-beta.9",
4
4
  "description": "React admin 应用开发工具集",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/README.md DELETED
@@ -1,181 +0,0 @@
1
- # miaoda-react-devkit
2
-
3
- React 管理后台开发工具集。提供 Sentry 开发环境 stub、错误桥接上报,以及云端 dev server 的 vite 配置。
4
-
5
- ## 功能
6
-
7
- 开发模式下,`@sentry/react` 会被自动替换为 stub:
8
-
9
- - DSN 替换为无害的 stub 端点(project id = 0),错误不会上报到真实 Sentry
10
- - 捕获到错误时在控制台打印 `[SentryStub]` 前缀的 warn,含错误消息、错误类型和调用栈
11
- - 每个 fetch / XHR 请求完成后触发 `onNetworkRequest` 回调,可拿到请求体和响应体文本
12
- - 4xx 请求和网络层失败(fetch 抛出异常)通过 `window.parent.postMessage` 向父窗口发送 `GLOBAL_ERROR` 消息
13
- - 每次 `console.xxx` 调用触发 `onConsole` 回调,原始输出不受影响,无递归风险
14
- - 用户传入的 `beforeSend` / `beforeBreadcrumb` 回调仍会被链式调用
15
- - SSE / 流式响应自动跳过,不消费原始 stream,不影响业务代码
16
- - 生产构建时插件不生效,恢复正常上报
17
-
18
- ## 目录结构
19
-
20
- ```
21
- packages/devkit/
22
- ├── src/
23
- │ ├── index.ts 主入口,导出所有公共 API
24
- │ ├── sentry/ Sentry 事件捕获核心
25
- │ │ ├── SentryCapture.ts SentryCapture 类,协调三类观测器
26
- │ │ ├── consoleObserver.ts 控制台日志捕获与过滤
27
- │ │ ├── networkObserver.ts 网络请求捕获(fetch / XHR)
28
- │ │ └── types.ts 共享类型定义(IErrorCaptureInfo 等)
29
- │ ├── bridge/ 错误桥接:向父窗口发送 postMessage
30
- │ │ └── errorBridge.ts createErrorBridge,格式对齐 vite-plugin-monitor
31
- │ ├── vite/ Vite 插件
32
- │ │ ├── index.ts vite 插件导出
33
- │ │ ├── withSentryStub.ts dev 模式下将 @sentry/react 重定向到 stub
34
- │ │ └── hmrTogglePlugin.ts HMR 开关及手动 reload 控制接口
35
- │ └── stubs/
36
- │ └── sentry-react-stub.ts dev 模式 stub,透传真实 Sentry API
37
- └── cloud/
38
- └── vite.config.ts 云端 dev server 专用 vite 配置
39
- ```
40
-
41
- ## 使用
42
-
43
- ### 本地开发
44
-
45
- 在项目 `vite.config.ts` 中注册插件(需放在第一位):
46
-
47
- ```ts
48
- import { withSentryStub } from 'miaoda-react-devkit/vite';
49
-
50
- export default defineConfig({
51
- plugins: [withSentryStub(), react()],
52
- });
53
- ```
54
-
55
- 应用代码中正常使用 `@sentry/react`,无需任何改动。
56
-
57
- ### 云端 dev server
58
-
59
- 云端 dev server 指定 `cloud/vite.config.ts` 启动,项目自身的 `vite.config.ts` 无需改动:
60
-
61
- ```bash
62
- vite --config node_modules/miaoda-react-devkit/cloud/vite.config.ts
63
- ```
64
-
65
- `cloud/vite.config.ts` 通过 `loadConfigFromFile` 加载项目的 `vite.config.ts`,再用 `mergeConfig` 追加云端专用插件:
66
-
67
- | 插件 | 说明 |
68
- |------|------|
69
- | `withSentryStub` **或** `monitorPlugin` | 二选一,见下方说明 |
70
- | `makeTagger` | DOM 节点打标(仅 web 类型) |
71
- | `injectedGuiListenerPlugin` | 注入云端 GUI 监听脚本 |
72
- | `injectOnErrorPlugin` | 全局错误捕获 |
73
- | `hmrTogglePlugin` | HMR 开关及手动 reload 控制接口 |
74
-
75
- **Sentry 插件自动选择**:启动时扫描项目入口文件(`src/main.tsx` 等),若检测到 `import ... from '@sentry/react'`,则使用 `withSentryStub`(新架构:项目自行调用 `Sentry.init()`,stub 拦截 dev 上报);否则使用 `monitorPlugin`(旧架构:通过 CDN 脚本注入 Sentry)。两者互斥,不会同时生效。
76
-
77
- 启动前由 `ViteDevServerStrategy` 通过环境变量传入参数:
78
-
79
- | 环境变量 | 说明 |
80
- |----------|------|
81
- | `DEVKIT_APP_TYPE` | `'web'` 或 `'freestyle'`,决定是否注入 `makeTagger()` |
82
- | `DEVKIT_CDN_HOST` | CDN 域名 |
83
- | `DEVKIT_ENV` | 部署环境(`'online'` \| `'dev'` \| `'qa'` 等) |
84
- | `DEVKIT_SENTRY_DSN` | 云端 Sentry DSN |
85
- | `DEVKIT_MIAODA_ENV` | miaoda 环境标识 |
86
- | `DEVKIT_APP_ID` | 应用 ID |
87
-
88
- ### 自定义观测回调(可选)
89
-
90
- ```ts
91
- import * as Sentry from '@sentry/react';
92
- import { SentryCapture, DEFAULT_CONSOLE_FILTER_KEYWORDS, DEFAULT_IGNORE_URLS } from 'miaoda-react-devkit';
93
-
94
- const capture = new SentryCapture({
95
- consoleFilterKeywords: DEFAULT_CONSOLE_FILTER_KEYWORDS,
96
- ignoreUrls: DEFAULT_IGNORE_URLS,
97
- onError(info) {
98
- console.warn('错误:', info.errorName, info.message);
99
- console.warn('位置:', info.fileName, info.lineNumber, info.columnNumber);
100
- },
101
- onNetworkRequest(info) {
102
- console.log(`[${info.type}] ${info.method} ${info.url} → ${info.statusCode}`);
103
- if (info.requestBody) console.log('请求体:', info.requestBody);
104
- if (info.responseBody) console.log('响应体:', info.responseBody);
105
- if (info.cause) console.error('网络失败:', info.cause);
106
- },
107
- onConsole({ level, args }) {
108
- console.debug(`[console.${level}]`, ...args);
109
- },
110
- });
111
-
112
- Sentry.init({
113
- dsn: '...',
114
- beforeSend: capture.beforeSend,
115
- beforeBreadcrumb: capture.beforeBreadcrumb,
116
- });
117
-
118
- capture.installNetworkObserver();
119
- capture.installConsoleObserver();
120
- ```
121
-
122
- ### 单独使用 ErrorBridge
123
-
124
- `createErrorBridge` 可独立于 `SentryCapture` 使用,也可注入自定义 `send` 函数便于测试:
125
-
126
- ```ts
127
- import { createErrorBridge } from 'miaoda-react-devkit';
128
-
129
- // 默认:window.parent.postMessage
130
- const bridge = createErrorBridge();
131
-
132
- // 自定义(测试或特殊宿主环境)
133
- const bridge = createErrorBridge((msg, origin) => {
134
- customChannel.send(msg);
135
- });
136
- ```
137
-
138
- `IGlobalErrorMessage` 格式与 `vite-plugin-monitor` 保持一致,接收端可统一处理两种来源的错误消息。
139
-
140
- ## 类型参考
141
-
142
- ### IErrorCaptureInfo
143
-
144
- | 字段 | 类型 | 说明 |
145
- |------|------|------|
146
- | `message` | `string` | 错误消息 |
147
- | `stack` | `string \| undefined` | 完整调用栈文本 |
148
- | `errorName` | `string \| undefined` | 错误类型名,如 `'TypeError'`、`'RangeError'` |
149
- | `fileName` | `string \| undefined` | 抛出错误的文件路径(来自 Sentry stack frame) |
150
- | `lineNumber` | `number \| undefined` | 行号 |
151
- | `columnNumber` | `number \| undefined` | 列号 |
152
- | `componentStack` | `string \| undefined` | React 组件调用栈(ErrorBoundary 提供) |
153
- | `mechanismType` | `string \| null \| undefined` | 捕获方式,如 `'instrument'`、`'onerror'` |
154
-
155
- ### INetworkRequestInfo
156
-
157
- | 字段 | 类型 | 说明 |
158
- |------|------|------|
159
- | `type` | `'fetch' \| 'xhr'` | 请求类型 |
160
- | `method` | `string` | HTTP 方法 |
161
- | `url` | `string` | 请求 URL |
162
- | `statusCode` | `number \| null` | HTTP 状态码,网络层失败时为 null |
163
- | `requestBody` | `string \| undefined` | 请求体文本,Blob/ArrayBuffer 等二进制类型为 undefined |
164
- | `responseBody` | `string \| undefined` | 响应体文本,SSE 流式响应为 `'[streaming response - not captured]'` |
165
- | `isError` | `boolean` | 网络层失败(未收到 HTTP 响应)时为 true |
166
- | `cause` | `Error \| undefined` | 网络层失败时的原始 Error(仅 fetch 可用;XHR 无法获取) |
167
-
168
- ## 其他环境变量
169
-
170
- | 变量 | 说明 |
171
- |------|------|
172
- | `SENTRY_OVERRIDE_DSN` | 覆盖 stub DSN,可指向本地 Sentry Relay |
173
- | `VITE_SENTRY_STUB_LOG` | 设为 `'true'` 时开启 stub 日志输出(仅 E2E 测试使用) |
174
-
175
- ## 构建
176
-
177
- ```bash
178
- pnpm build
179
- ```
180
-
181
- E2E 测试见 `../devkit-e2e`。