miaoda-react-devkit 0.1.1-beta.0 → 0.1.1-beta.10

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.
@@ -5,126 +5,587 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
5
5
  // src/stubs/sentry-react-stub.ts
6
6
  import * as RealSentry from "@sentry/react";
7
7
 
8
- // src/capture.ts
9
- import {
10
- addFetchInstrumentationHandler
11
- } from "@sentry/core";
8
+ // src/capture/console.ts
9
+ import { addConsoleInstrumentationHandler } from "@sentry/core";
10
+ function formatConsoleArg(arg) {
11
+ if (typeof arg === "string") return arg;
12
+ if (arg instanceof Error) return arg.message;
13
+ try {
14
+ return JSON.stringify(arg);
15
+ } catch {
16
+ return String(arg);
17
+ }
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
+ ];
27
+ function shouldFilterConsole(args, keywords) {
28
+ if (keywords.length === 0) return false;
29
+ const text = formatConsoleArgs(args);
30
+ return keywords.some((kw) => text.includes(kw));
31
+ }
32
+ function shouldFilterConsoleMessage(message, keywords) {
33
+ return keywords.some((kw) => message.includes(kw));
34
+ }
35
+ function createConsoleObserver(keywords, subscribers) {
36
+ return {
37
+ install() {
38
+ if (subscribers.length === 0) return;
39
+ addConsoleInstrumentationHandler(({ args, level }) => {
40
+ if (shouldFilterConsole(args, keywords)) return;
41
+ const info = { level, args };
42
+ for (const sub of subscribers) sub.onConsole(info);
43
+ });
44
+ },
45
+ beforeBreadcrumb(breadcrumb, hint) {
46
+ if (breadcrumb.category === "console" && breadcrumb.message != null) {
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
+ };
59
+ }
60
+ return breadcrumb;
61
+ }
62
+ };
63
+ }
64
+
65
+ // src/capture/network.ts
66
+ import { getClient, getIsolationScope } from "@sentry/core";
67
+
68
+ // ../../node_modules/.pnpm/@sentry-internal+browser-utils@9.47.1/node_modules/@sentry-internal/browser-utils/build/esm/debug-build.js
69
+ var DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
70
+
71
+ // ../../node_modules/.pnpm/@sentry-internal+browser-utils@9.47.1/node_modules/@sentry-internal/browser-utils/build/esm/networkUtils.js
72
+ import { debug } from "@sentry/core";
73
+ function serializeFormData(formData) {
74
+ return new URLSearchParams(formData).toString();
75
+ }
76
+ function getBodyString(body, _debug = debug) {
77
+ try {
78
+ if (typeof body === "string") {
79
+ return [body];
80
+ }
81
+ if (body instanceof URLSearchParams) {
82
+ return [body.toString()];
83
+ }
84
+ if (body instanceof FormData) {
85
+ return [serializeFormData(body)];
86
+ }
87
+ if (!body) {
88
+ return [void 0];
89
+ }
90
+ } catch (error) {
91
+ DEBUG_BUILD && _debug.error(error, "Failed to serialize body", body);
92
+ return [void 0, "BODY_PARSE_ERROR"];
93
+ }
94
+ DEBUG_BUILD && _debug.log("Skipping network body because of body type", body);
95
+ return [void 0, "UNPARSEABLE_BODY_TYPE"];
96
+ }
97
+ function getFetchRequestArgBody(fetchArgs = []) {
98
+ if (fetchArgs.length !== 2 || typeof fetchArgs[1] !== "object") {
99
+ return void 0;
100
+ }
101
+ return fetchArgs[1].body;
102
+ }
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
+
114
+ // src/capture/pgrest.ts
115
+ var DEFAULT_PGREST_URL_PATTERNS = [/\/rest\/v1\//];
116
+ var DEFAULT_PGREST_WHITELIST_CODES = [
117
+ "22P02",
118
+ // 无效的文本表示(如类型转换失败)
119
+ "42703",
120
+ // 未定义的列
121
+ "42P01",
122
+ // 未定义的表
123
+ "42501",
124
+ // 权限不足
125
+ "23503",
126
+ // 外键约束失败
127
+ "42P17",
128
+ // 对象已存在
129
+ "22008",
130
+ // 日期时间字段值超出范围
131
+ "23505",
132
+ // 唯一键冲突
133
+ "PGRST116",
134
+ // 期望单行但返回多行
135
+ "PGRST200",
136
+ // 外键关系查找失败
137
+ "PGRST204"
138
+ // 响应中找不到列
139
+ ];
140
+ function isPgRestRequest(url, patterns) {
141
+ return patterns.some((p) => (typeof p === "string" ? new RegExp(p) : p).test(url));
142
+ }
143
+ function parsePgRestErrorBody(body) {
144
+ if (!body) return null;
145
+ let parsed;
146
+ try {
147
+ parsed = JSON.parse(body);
148
+ } catch {
149
+ return null;
150
+ }
151
+ if (typeof parsed !== "object") return null;
152
+ if (parsed === null) return null;
153
+ const p = parsed;
154
+ if (typeof p["code"] !== "string") return null;
155
+ if (typeof p["message"] !== "string") return null;
156
+ return {
157
+ code: p["code"],
158
+ message: p["message"],
159
+ details: typeof p["details"] === "string" ? p["details"] : null,
160
+ hint: typeof p["hint"] === "string" ? p["hint"] : null
161
+ };
162
+ }
163
+
164
+ // src/capture/auth.ts
165
+ var DEFAULT_AUTH_URL_PATTERNS = [/\/auth\/v1\//];
166
+ var DEFAULT_AUTH_WHITELIST_CODES = ["unexpected_failure"];
167
+ function isAuthRequest(url, patterns) {
168
+ return patterns.some((p) => (typeof p === "string" ? new RegExp(p) : p).test(url));
169
+ }
170
+ function parseAuthErrorBody(body) {
171
+ if (!body) return null;
172
+ let parsed;
173
+ try {
174
+ parsed = JSON.parse(body);
175
+ } catch {
176
+ return null;
177
+ }
178
+ if (typeof parsed !== "object") return null;
179
+ if (parsed === null) return null;
180
+ const p = parsed;
181
+ if (typeof p["code"] !== "string") return null;
182
+ if (typeof p["message"] !== "string") return null;
183
+ return {
184
+ code: p["code"],
185
+ message: p["message"],
186
+ requestId: typeof p["requestId"] === "string" ? p["requestId"] : null
187
+ };
188
+ }
189
+
190
+ // src/capture/network.ts
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
+ }
196
+ var DEFAULT_IGNORE_URLS = [
197
+ /\.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot|map)(\?.*)?$/,
198
+ /\.chunk\./,
199
+ /\/static\//,
200
+ /\/assets\//
201
+ ];
202
+ function createUrlMatcher(patterns) {
203
+ const regexes = patterns.map((p) => typeof p === "string" ? new RegExp(p) : p);
204
+ return (url) => regexes.some((re) => re.test(url));
205
+ }
206
+ function truncateBody(body) {
207
+ return body.length > BODY_TRUNCATE_LIMIT ? body.slice(0, BODY_TRUNCATE_LIMIT) + "... (truncated)" : body;
208
+ }
209
+ function isStreamByContentType(contentType) {
210
+ return contentType.includes("text/event-stream") || contentType.includes("application/stream+json");
211
+ }
212
+ function handleXhrBreadcrumb(breadcrumb, hint, handler) {
213
+ const data = breadcrumb.data;
214
+ const method = data?.method ?? "GET";
215
+ const url = data?.url ?? "";
216
+ const statusCode = data?.status_code != null && data.status_code > 0 ? data.status_code : null;
217
+ const isError = statusCode === null;
218
+ const xhr = hint?.xhr;
219
+ const [rawRequestBody] = getBodyString(hint?.input);
220
+ const requestBody = rawRequestBody != null ? truncateBody(rawRequestBody) : void 0;
221
+ let responseBody;
222
+ if (xhr) {
223
+ const contentType = xhr.getResponseHeader("content-type") ?? "";
224
+ if (isStreamByContentType(contentType)) {
225
+ responseBody = "[streaming response - not captured]";
226
+ } else if (xhr.responseType === "" || xhr.responseType === "text") {
227
+ try {
228
+ responseBody = xhr.responseText != null ? truncateBody(xhr.responseText) : void 0;
229
+ } catch {
230
+ }
231
+ } else if (xhr.responseType === "json") {
232
+ try {
233
+ responseBody = truncateBody(JSON.stringify(xhr.response));
234
+ } catch {
235
+ responseBody = "[json response parse failed]";
236
+ }
237
+ } else {
238
+ responseBody = "[non-text response]";
239
+ }
240
+ }
241
+ if (breadcrumb.data) {
242
+ breadcrumb.data["requestBody"] = requestBody;
243
+ breadcrumb.data["responseBody"] = responseBody;
244
+ }
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 });
254
+ }
255
+ async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
256
+ const data = breadcrumb.data;
257
+ const method = data?.method ?? "GET";
258
+ const url = data?.url ?? "";
259
+ const statusCode = data?.status_code ?? null;
260
+ const isError = hint?.data != null;
261
+ const response = hint?.response;
262
+ const cause = hint?.data instanceof Error ? hint.data : void 0;
263
+ const reqBody = getFetchRequestArgBody(hint?.input ?? []);
264
+ const [rawRequestBody] = getBodyString(reqBody);
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}`;
271
+ if (breadcrumb.data) {
272
+ breadcrumb.data["requestBody"] = requestBody;
273
+ breadcrumb.data["duration"] = duration;
274
+ }
275
+ const contentType = response?.headers?.get("content-type") ?? "";
276
+ if (isStreamByContentType(contentType)) {
277
+ if (breadcrumb.data) {
278
+ breadcrumb.data["responseBody"] = "[streaming response - not captured]";
279
+ }
280
+ await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody: "[streaming response - not captured]", isError, cause, duration });
281
+ return;
282
+ }
283
+ let responseBody;
284
+ if (response) {
285
+ try {
286
+ const text = await Promise.race([
287
+ response.clone().text(),
288
+ new Promise(
289
+ (_, reject) => setTimeout(() => reject(new Error("timeout")), 500)
290
+ )
291
+ ]);
292
+ responseBody = truncateBody(text);
293
+ } catch {
294
+ responseBody = void 0;
295
+ }
296
+ }
297
+ if (breadcrumb.data) {
298
+ breadcrumb.data["responseBody"] = responseBody;
299
+ }
300
+ await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody, isError, cause, duration });
301
+ }
302
+ function createNetworkObserver(opts, subscribers) {
303
+ const shouldIgnore = createUrlMatcher(opts.ignoreUrls);
304
+ const pgRestPatterns = opts.pgRestUrlPatterns ?? DEFAULT_PGREST_URL_PATTERNS;
305
+ const pgRestWhitelistCodes = opts.pgRestWhitelistCodes ?? DEFAULT_PGREST_WHITELIST_CODES;
306
+ const precedingBreadcrumbsLimit = opts.precedingBreadcrumbsLimit;
307
+ const authPatterns = opts.authUrlPatterns ?? DEFAULT_AUTH_URL_PATTERNS;
308
+ const authWhitelistCodes = opts.authWhitelistCodes ?? DEFAULT_AUTH_WHITELIST_CODES;
309
+ function tryDispatchPgRestWhitelistError(requestType, method, url, statusCode, requestBody, responseBody) {
310
+ if (statusCode == null) return;
311
+ if (!isPgRestRequest(url, pgRestPatterns)) return;
312
+ const pgRestError = parsePgRestErrorBody(responseBody);
313
+ if (!pgRestError) return;
314
+ if (pgRestWhitelistCodes.length > 0 && !pgRestWhitelistCodes.includes(pgRestError.code)) return;
315
+ const allBreadcrumbs = getIsolationScope().getScopeData().breadcrumbs;
316
+ const precedingBreadcrumbs = precedingBreadcrumbsLimit != null ? allBreadcrumbs.slice(-precedingBreadcrumbsLimit) : allBreadcrumbs.slice();
317
+ const info = {
318
+ type: requestType,
319
+ method,
320
+ url,
321
+ statusCode,
322
+ pgRestError,
323
+ requestBody,
324
+ responseBody,
325
+ precedingBreadcrumbs
326
+ };
327
+ for (const sub of subscribers) sub.onPgRestWhitelistError(info);
328
+ }
329
+ function tryDispatchAuthWhitelistError(requestType, method, url, statusCode, requestBody, responseBody) {
330
+ if (statusCode == null) return;
331
+ if (!isAuthRequest(url, authPatterns)) return;
332
+ const authError = parseAuthErrorBody(responseBody);
333
+ if (!authError) return;
334
+ if (authWhitelistCodes.length > 0 && !authWhitelistCodes.includes(authError.code)) return;
335
+ const allBreadcrumbs = getIsolationScope().getScopeData().breadcrumbs;
336
+ const precedingBreadcrumbs = precedingBreadcrumbsLimit != null ? allBreadcrumbs.slice(-precedingBreadcrumbsLimit) : allBreadcrumbs.slice();
337
+ const info = {
338
+ type: requestType,
339
+ method,
340
+ url,
341
+ statusCode,
342
+ authError,
343
+ requestBody,
344
+ responseBody,
345
+ precedingBreadcrumbs
346
+ };
347
+ for (const sub of subscribers) sub.onAuthWhitelistError(info);
348
+ }
349
+ function makeHandler(requestType) {
350
+ return (info) => {
351
+ for (const sub of subscribers) void sub.onNetworkRequest(info);
352
+ tryDispatchPgRestWhitelistError(
353
+ requestType,
354
+ info.method,
355
+ info.url,
356
+ info.statusCode,
357
+ info.requestBody,
358
+ info.responseBody
359
+ );
360
+ tryDispatchAuthWhitelistError(
361
+ requestType,
362
+ info.method,
363
+ info.url,
364
+ info.statusCode,
365
+ info.requestBody,
366
+ info.responseBody
367
+ );
368
+ };
369
+ }
370
+ return {
371
+ shouldIgnore,
372
+ install() {
373
+ if (subscribers.length === 0) return;
374
+ const client = getClient();
375
+ if (!client) return;
376
+ const xhrHandler = makeHandler("xhr");
377
+ const fetchHandler = makeHandler("fetch");
378
+ client.on("beforeAddBreadcrumb", (breadcrumb, hint) => {
379
+ const url = breadcrumb.data?.url ?? "";
380
+ if (breadcrumb.category === "xhr") {
381
+ if (shouldIgnore(url)) return;
382
+ handleXhrBreadcrumb(breadcrumb, hint, xhrHandler);
383
+ } else if (breadcrumb.category === "fetch") {
384
+ if (shouldIgnore(url)) return;
385
+ void handleFetchBreadcrumb(breadcrumb, hint, fetchHandler);
386
+ }
387
+ });
388
+ }
389
+ };
390
+ }
391
+
392
+ // src/capture/capture.ts
12
393
  var SentryCapture = class {
13
- constructor({ onError, onNetwork, onRequest } = {}) {
14
- __publicField(this, "onError");
15
- __publicField(this, "onNetwork");
16
- __publicField(this, "onRequest");
17
- this.onError = onError;
18
- this.onNetwork = onNetwork;
19
- this.onRequest = onRequest;
394
+ constructor(opts, subscribers = []) {
395
+ __publicField(this, "subscribers");
396
+ __publicField(this, "console");
397
+ __publicField(this, "network");
398
+ this.subscribers = subscribers;
399
+ this.console = createConsoleObserver(opts.consoleFilterKeywords, subscribers);
400
+ this.network = createNetworkObserver(opts, subscribers);
20
401
  this.beforeSend = this.beforeSend.bind(this);
21
402
  this.beforeBreadcrumb = this.beforeBreadcrumb.bind(this);
22
403
  }
23
- /**
24
- * 注册 Sentry fetch 监听器,观测所有非 SSE 请求的开始与结束。
25
- * 在 Sentry.init() 后调用一次,复用 Sentry 已打补丁的 fetch,不会二次代理。
26
- */
27
- installFetchObserver() {
28
- if (!this.onRequest) return;
29
- const handler = this.onRequest;
30
- addFetchInstrumentationHandler((data) => {
31
- const { method, url } = data.fetchData;
32
- const responseContentType = data.response?.headers?.get?.("content-type") ?? "";
33
- if (responseContentType.includes("text/event-stream")) return;
34
- if (!data.endTimestamp) {
35
- handler({ method, url, statusCode: null, isEnd: false, isError: false });
36
- return;
37
- }
38
- const statusCode = data.response?.status ?? null;
39
- const isError = data.error != null;
40
- handler({ method, url, statusCode, isEnd: true, isError });
41
- });
404
+ /** 在 Sentry.init() 完成后调用一次,注册网络请求观测器。 */
405
+ installNetworkObserver() {
406
+ this.network.install();
42
407
  }
43
- /**
44
- * 在 Sentry 上报前调用,提取错误信息触发 onError 回调。
45
- * BrowserOptions.beforeSend 要求 ErrorEvent(Event & { type: undefined }),类型需精确匹配。
46
- */
408
+ /** 注册控制台日志观测器,可在 Sentry.init() 前后调用均可。 */
409
+ installConsoleObserver() {
410
+ this.console.install();
411
+ }
412
+ /** 传入 Sentry.init({ beforeSend }) —— 提取错误信息触发 onError 回调。 */
47
413
  beforeSend(event, hint) {
48
- const message = event.exception?.values?.[0]?.value ?? event.message ?? "(unknown)";
414
+ const exceptionValue = event.exception?.values?.[0];
415
+ const message = exceptionValue?.value ?? event.message ?? "(unknown)";
49
416
  const componentStack = event.contexts?.["react"]?.["componentStack"] ?? void 0;
50
- const mechanismType = event.exception?.values?.[0]?.mechanism?.type ?? null;
417
+ const mechanismType = exceptionValue?.mechanism?.type ?? null;
51
418
  const stack = hint.originalException instanceof Error ? hint.originalException.stack : void 0;
52
- this.onError?.({ message, stack, componentStack, mechanismType });
419
+ const errorName = exceptionValue?.type ?? (hint.originalException instanceof Error ? hint.originalException.name : void 0);
420
+ const frames = exceptionValue?.stacktrace?.frames;
421
+ const innerFrame = frames?.length ? frames[frames.length - 1] : void 0;
422
+ const fileName = innerFrame?.filename ?? innerFrame?.abs_path;
423
+ const lineNumber = innerFrame?.lineno;
424
+ const columnNumber = innerFrame?.colno;
425
+ const info = { message, stack, componentStack, mechanismType, errorName, fileName, lineNumber, columnNumber };
426
+ for (const sub of this.subscribers) sub.onError(info);
53
427
  return event;
54
428
  }
55
429
  /**
56
- * 在 Sentry 记录面包屑前调用,提取网络请求信息触发 onNetwork 回调。
430
+ * 传入 Sentry.init({ beforeBreadcrumb })。
431
+ * - console:过滤噪音关键词
432
+ * - fetch/xhr:过滤 ignoreUrls 匹配的静态资源请求
57
433
  */
58
- beforeBreadcrumb(breadcrumb, _hint) {
59
- if (breadcrumb.type === "http") {
60
- const data = breadcrumb.data;
61
- this.onNetwork?.({
62
- method: data?.method ?? null,
63
- url: data?.url ?? null,
64
- statusCode: data?.status_code ?? null
65
- });
434
+ beforeBreadcrumb(breadcrumb, hint) {
435
+ if (breadcrumb.category === "fetch" || breadcrumb.category === "xhr") {
436
+ const url = breadcrumb.data?.url ?? "";
437
+ if (this.network.shouldIgnore(url)) return null;
66
438
  }
67
- return breadcrumb;
439
+ return this.console.beforeBreadcrumb(breadcrumb, hint);
68
440
  }
69
441
  };
70
442
 
443
+ // src/subscribers/postMessageSubscriber.ts
444
+ function extractUrlPath(url) {
445
+ try {
446
+ const u = new URL(url);
447
+ return u.pathname + u.search + u.hash;
448
+ } catch {
449
+ return url;
450
+ }
451
+ }
452
+ var PostMessageSubscriber = class {
453
+ constructor(send = (msg, origin) => window.parent.postMessage(msg, origin)) {
454
+ __publicField(this, "send");
455
+ this.send = send;
456
+ }
457
+ // postMessage 场景不需要上报 console 日志
458
+ onConsole(_info) {
459
+ }
460
+ onError({ message, stack, errorName, fileName, lineNumber, columnNumber }) {
461
+ const name = errorName ?? "Error";
462
+ const msg = {
463
+ type: "GLOBAL_ERROR",
464
+ message,
465
+ error: stack != null ? { name, message, stack } : null,
466
+ errorData: {
467
+ name,
468
+ message,
469
+ stack,
470
+ fileName: fileName ?? "unknown",
471
+ lineNumber: lineNumber ?? 0,
472
+ columnNumber: columnNumber ?? 0
473
+ }
474
+ };
475
+ this.send(msg, "*");
476
+ }
477
+ // postMessage 场景不需要上报 network 日志
478
+ onNetworkRequest(_info) {
479
+ }
480
+ onPgRestWhitelistError({ type, method, url, statusCode, pgRestError, requestBody, responseBody, precedingBreadcrumbs }) {
481
+ const urlPath = extractUrlPath(url);
482
+ const code = pgRestError.code;
483
+ const errorMessage = `${method} ${urlPath} -> ${statusCode} [PgRest:${code}]`;
484
+ const msg = {
485
+ type: "GLOBAL_ERROR",
486
+ message: errorMessage,
487
+ error: null,
488
+ errorData: {
489
+ name: "PgRestWhitelistError",
490
+ message: pgRestError.message,
491
+ stack: null,
492
+ fileName: url,
493
+ lineNumber: 0,
494
+ columnNumber: 0,
495
+ httpPath: urlPath,
496
+ httpStatus: statusCode,
497
+ httpMethod: method,
498
+ requestBody: requestBody ?? "",
499
+ responseBody,
500
+ pgRestCode: code,
501
+ pgRestDetails: pgRestError.details ?? void 0,
502
+ pgRestHint: pgRestError.hint ?? void 0,
503
+ requestType: type,
504
+ precedingBreadcrumbs
505
+ }
506
+ };
507
+ this.send(msg, "*");
508
+ }
509
+ onAuthWhitelistError({ type, method, url, statusCode, authError, requestBody, responseBody, precedingBreadcrumbs }) {
510
+ const urlPath = extractUrlPath(url);
511
+ const code = authError.code;
512
+ const errorMessage = `${method} ${urlPath} -> ${statusCode} [Auth:${code}]`;
513
+ const msg = {
514
+ type: "GLOBAL_ERROR",
515
+ message: errorMessage,
516
+ error: null,
517
+ errorData: {
518
+ name: "AuthWhitelistError",
519
+ message: authError.message,
520
+ stack: null,
521
+ fileName: url,
522
+ lineNumber: 0,
523
+ columnNumber: 0,
524
+ httpPath: urlPath,
525
+ httpStatus: statusCode,
526
+ httpMethod: method,
527
+ requestBody: requestBody ?? "",
528
+ responseBody,
529
+ authCode: code,
530
+ authRequestId: authError.requestId ?? void 0,
531
+ requestType: type,
532
+ precedingBreadcrumbs
533
+ }
534
+ };
535
+ this.send(msg, "*");
536
+ }
537
+ };
538
+ function createPostMessageSubscriber(send) {
539
+ return new PostMessageSubscriber(send);
540
+ }
541
+
71
542
  // src/stubs/sentry-react-stub.ts
72
543
  export * from "@sentry/react";
73
544
  var STUB_DSN = "https://stubPublicKey@o0.ingest.sentry.io/0";
74
- var OVERRIDE_DSN = typeof process !== "undefined" && process.env["SENTRY_OVERRIDE_DSN"] ? process.env["SENTRY_OVERRIDE_DSN"] : STUB_DSN;
75
- var _capture = new SentryCapture({
76
- onError(info) {
77
- console.warn("[SentryStub] \u6355\u83B7\u5230\u9519\u8BEF\uFF1A", info.message);
78
- if (info.stack) {
79
- console.warn(
80
- "[SentryStub] \u8C03\u7528\u6808\uFF1A",
81
- info.stack.split("\n").slice(0, 4).join("\n")
82
- );
83
- }
84
- if (info.componentStack) {
85
- console.warn(
86
- "[SentryStub] \u7EC4\u4EF6\u6808\uFF1A",
87
- info.componentStack.split("\n").slice(0, 4).join("\n")
88
- );
89
- }
90
- },
91
- onNetwork(info) {
92
- if (info.statusCode != null && info.statusCode >= 400) {
93
- console.warn(
94
- `[SentryStub] \u7F51\u7EDC\u9519\u8BEF\uFF1A${info.method} ${info.url} \u2192 ${info.statusCode}`
95
- );
96
- }
97
- },
98
- onRequest(info) {
99
- if (!info.isEnd) return;
100
- if (info.isError) {
101
- console.warn(`[SentryStub] \u8BF7\u6C42\u5931\u8D25\uFF08\u7F51\u7EDC\u5C42\uFF09\uFF1A${info.method} ${info.url}`);
102
- } else if (info.statusCode != null && info.statusCode >= 400) {
103
- console.warn(`[SentryStub] \u8BF7\u6C42\u5F02\u5E38\uFF1A${info.method} ${info.url} \u2192 ${info.statusCode}`);
104
- } else {
105
- console.debug(`[SentryStub] \u8BF7\u6C42\u5B8C\u6210\uFF1A${info.method} ${info.url} \u2192 ${info.statusCode}`);
106
- }
107
- }
108
- });
545
+ var OVERRIDE_DSN = import.meta.env.VITE_SENTRY_DSN || STUB_DSN;
546
+ var OVERRIDE_ENVIRONMENT = import.meta.env.VITE_SENTRY_ENV;
547
+ var _subscribers = [createPostMessageSubscriber()];
548
+ function configureStubSubscribers(subscribers) {
549
+ _subscribers = subscribers;
550
+ }
109
551
  var init2 = (options) => {
110
552
  const upstreamBeforeSend = options?.beforeSend;
111
553
  const upstreamBeforeBreadcrumb = options?.beforeBreadcrumb;
554
+ const capture = new SentryCapture(
555
+ {
556
+ consoleFilterKeywords: DEFAULT_CONSOLE_FILTER_KEYWORDS,
557
+ ignoreUrls: DEFAULT_IGNORE_URLS
558
+ },
559
+ _subscribers
560
+ );
112
561
  const result = RealSentry.init({
113
562
  ...options,
114
563
  dsn: OVERRIDE_DSN,
564
+ environment: OVERRIDE_ENVIRONMENT,
115
565
  beforeSend(event, hint) {
116
- const processed = _capture.beforeSend(event, hint);
566
+ const processed = capture.beforeSend(event, hint);
117
567
  return upstreamBeforeSend ? upstreamBeforeSend(processed, hint) : processed;
118
568
  },
119
569
  beforeBreadcrumb(breadcrumb, hint) {
120
- const processed = _capture.beforeBreadcrumb(breadcrumb, hint);
570
+ const processed = capture.beforeBreadcrumb(breadcrumb, hint);
571
+ if (processed === null) return null;
121
572
  return upstreamBeforeBreadcrumb ? upstreamBeforeBreadcrumb(processed, hint) : processed;
122
573
  }
123
574
  });
124
- _capture.installFetchObserver();
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
+ }
584
+ capture.installNetworkObserver();
585
+ capture.installConsoleObserver();
125
586
  return result;
126
587
  };
127
588
  export {
589
+ configureStubSubscribers,
128
590
  init2 as init
129
591
  };
130
- //# sourceMappingURL=sentry-react-stub.js.map