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

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.js CHANGED
@@ -2,69 +2,452 @@ var __defProp = Object.defineProperty;
2
2
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
3
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
4
 
5
- // src/capture.ts
6
- import {
7
- addFetchInstrumentationHandler
8
- } from "@sentry/core";
5
+ // src/capture/console.ts
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) {
13
+ if (typeof arg === "string") return arg;
14
+ if (arg instanceof Error) return arg.message;
15
+ try {
16
+ return JSON.stringify(arg);
17
+ } catch {
18
+ return String(arg);
19
+ }
20
+ }
21
+ function shouldFilterConsole(args, keywords) {
22
+ if (keywords.length === 0) return false;
23
+ const text = args.map(serializeArg).join(" ");
24
+ return keywords.some((kw) => text.includes(kw));
25
+ }
26
+ function shouldFilterConsoleMessage(message, keywords) {
27
+ return keywords.some((kw) => message.includes(kw));
28
+ }
29
+ function createConsoleObserver(keywords, subscribers) {
30
+ return {
31
+ install() {
32
+ if (subscribers.length === 0) return;
33
+ addConsoleInstrumentationHandler(({ args, level }) => {
34
+ if (shouldFilterConsole(args, keywords)) return;
35
+ const info = { level, args };
36
+ for (const sub of subscribers) sub.onConsole(info);
37
+ });
38
+ },
39
+ beforeBreadcrumb(breadcrumb, _hint) {
40
+ if (breadcrumb.category === "console" && breadcrumb.message != null) {
41
+ if (shouldFilterConsoleMessage(breadcrumb.message, keywords)) return null;
42
+ }
43
+ return breadcrumb;
44
+ }
45
+ };
46
+ }
47
+
48
+ // src/capture/network.ts
49
+ import { getClient } from "@sentry/core";
50
+
51
+ // ../../node_modules/.pnpm/@sentry-internal+browser-utils@9.47.1/node_modules/@sentry-internal/browser-utils/build/esm/debug-build.js
52
+ var DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
53
+
54
+ // ../../node_modules/.pnpm/@sentry-internal+browser-utils@9.47.1/node_modules/@sentry-internal/browser-utils/build/esm/networkUtils.js
55
+ import { debug } from "@sentry/core";
56
+ function serializeFormData(formData) {
57
+ return new URLSearchParams(formData).toString();
58
+ }
59
+ function getBodyString(body, _debug = debug) {
60
+ try {
61
+ if (typeof body === "string") {
62
+ return [body];
63
+ }
64
+ if (body instanceof URLSearchParams) {
65
+ return [body.toString()];
66
+ }
67
+ if (body instanceof FormData) {
68
+ return [serializeFormData(body)];
69
+ }
70
+ if (!body) {
71
+ return [void 0];
72
+ }
73
+ } catch (error) {
74
+ DEBUG_BUILD && _debug.error(error, "Failed to serialize body", body);
75
+ return [void 0, "BODY_PARSE_ERROR"];
76
+ }
77
+ DEBUG_BUILD && _debug.log("Skipping network body because of body type", body);
78
+ return [void 0, "UNPARSEABLE_BODY_TYPE"];
79
+ }
80
+ function getFetchRequestArgBody(fetchArgs = []) {
81
+ if (fetchArgs.length !== 2 || typeof fetchArgs[1] !== "object") {
82
+ return void 0;
83
+ }
84
+ return fetchArgs[1].body;
85
+ }
86
+
87
+ // src/capture/pgrest.ts
88
+ var DEFAULT_PGREST_URL_PATTERNS = [/\/rest\/v1\//];
89
+ var DEFAULT_PGREST_WHITELIST_CODES = [];
90
+ function isPgRestRequest(url, patterns) {
91
+ return patterns.some((p) => (typeof p === "string" ? new RegExp(p) : p).test(url));
92
+ }
93
+ function parsePgRestErrorBody(body) {
94
+ if (!body) return null;
95
+ let parsed;
96
+ try {
97
+ parsed = JSON.parse(body);
98
+ } catch {
99
+ return null;
100
+ }
101
+ if (typeof parsed !== "object") return null;
102
+ if (parsed === null) return null;
103
+ const p = parsed;
104
+ if (typeof p["code"] !== "string") return null;
105
+ if (typeof p["message"] !== "string") return null;
106
+ return {
107
+ code: p["code"],
108
+ message: p["message"],
109
+ details: typeof p["details"] === "string" ? p["details"] : null,
110
+ hint: typeof p["hint"] === "string" ? p["hint"] : null
111
+ };
112
+ }
113
+
114
+ // src/capture/network.ts
115
+ var BODY_TRUNCATE_LIMIT = 2e3;
116
+ var DEFAULT_IGNORE_URLS = [
117
+ /\.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot|map)(\?.*)?$/,
118
+ /\.chunk\./,
119
+ /\/static\//,
120
+ /\/assets\//
121
+ ];
122
+ function createUrlMatcher(patterns) {
123
+ const regexes = patterns.map((p) => typeof p === "string" ? new RegExp(p) : p);
124
+ return (url) => regexes.some((re) => re.test(url));
125
+ }
126
+ function truncateBody(body) {
127
+ return body.length > BODY_TRUNCATE_LIMIT ? body.slice(0, BODY_TRUNCATE_LIMIT) + "... (truncated)" : body;
128
+ }
129
+ function isStreamByContentType(contentType) {
130
+ return contentType.includes("text/event-stream") || contentType.includes("application/stream+json");
131
+ }
132
+ function handleXhrBreadcrumb(breadcrumb, hint, handler) {
133
+ const data = breadcrumb.data;
134
+ const method = data?.method ?? "GET";
135
+ const url = data?.url ?? "";
136
+ const statusCode = data?.status_code != null && data.status_code > 0 ? data.status_code : null;
137
+ const isError = statusCode === null;
138
+ const xhr = hint?.xhr;
139
+ const [rawRequestBody] = getBodyString(hint?.input);
140
+ const requestBody = rawRequestBody != null ? truncateBody(rawRequestBody) : void 0;
141
+ let responseBody;
142
+ if (xhr) {
143
+ const contentType = xhr.getResponseHeader("content-type") ?? "";
144
+ if (isStreamByContentType(contentType)) {
145
+ responseBody = "[streaming response - not captured]";
146
+ } else if (xhr.responseType === "" || xhr.responseType === "text") {
147
+ try {
148
+ responseBody = xhr.responseText != null ? truncateBody(xhr.responseText) : void 0;
149
+ } catch {
150
+ }
151
+ } else if (xhr.responseType === "json") {
152
+ try {
153
+ responseBody = truncateBody(JSON.stringify(xhr.response));
154
+ } catch {
155
+ responseBody = "[json response parse failed]";
156
+ }
157
+ } else {
158
+ responseBody = "[non-text response]";
159
+ }
160
+ }
161
+ if (breadcrumb.data) {
162
+ breadcrumb.data["requestBody"] = requestBody;
163
+ breadcrumb.data["responseBody"] = responseBody;
164
+ }
165
+ void handler({ type: "xhr", method, url, statusCode, requestBody, responseBody, isError });
166
+ }
167
+ async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
168
+ const data = breadcrumb.data;
169
+ const method = data?.method ?? "GET";
170
+ const url = data?.url ?? "";
171
+ const statusCode = data?.status_code ?? null;
172
+ const isError = hint?.data != null;
173
+ const response = hint?.response;
174
+ const cause = hint?.data instanceof Error ? hint.data : void 0;
175
+ const fetchArgs = hint?.input;
176
+ const reqBody = getFetchRequestArgBody(fetchArgs ?? []);
177
+ const [rawRequestBody] = getBodyString(reqBody);
178
+ const requestBody = rawRequestBody != null ? truncateBody(rawRequestBody) : void 0;
179
+ if (breadcrumb.data) {
180
+ breadcrumb.data["requestBody"] = requestBody;
181
+ }
182
+ const contentType = response?.headers?.get("content-type") ?? "";
183
+ if (isStreamByContentType(contentType)) {
184
+ if (breadcrumb.data) {
185
+ breadcrumb.data["responseBody"] = "[streaming response - not captured]";
186
+ }
187
+ await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody: "[streaming response - not captured]", isError, cause });
188
+ return;
189
+ }
190
+ let responseBody;
191
+ if (response) {
192
+ try {
193
+ const text = await Promise.race([
194
+ response.clone().text(),
195
+ new Promise(
196
+ (_, reject) => setTimeout(() => reject(new Error("timeout")), 500)
197
+ )
198
+ ]);
199
+ responseBody = truncateBody(text);
200
+ } catch {
201
+ responseBody = void 0;
202
+ }
203
+ }
204
+ if (breadcrumb.data) {
205
+ breadcrumb.data["responseBody"] = responseBody;
206
+ }
207
+ await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody, isError, cause });
208
+ }
209
+ function createNetworkObserver(opts, subscribers) {
210
+ const shouldIgnore = createUrlMatcher(opts.ignoreUrls);
211
+ const pgRestPatterns = opts.pgRestUrlPatterns ?? DEFAULT_PGREST_URL_PATTERNS;
212
+ const pgRestWhitelistCodes = opts.pgRestWhitelistCodes ?? DEFAULT_PGREST_WHITELIST_CODES;
213
+ function tryDispatchPgRestWhitelistError(requestType, method, url, statusCode, requestBody, responseBody) {
214
+ if (statusCode == null) return;
215
+ if (!isPgRestRequest(url, pgRestPatterns)) return;
216
+ const pgRestError = parsePgRestErrorBody(responseBody);
217
+ if (!pgRestError) return;
218
+ if (pgRestWhitelistCodes.length > 0 && !pgRestWhitelistCodes.includes(pgRestError.code)) return;
219
+ const info = {
220
+ type: requestType,
221
+ method,
222
+ url,
223
+ statusCode,
224
+ pgRestError,
225
+ requestBody,
226
+ responseBody
227
+ };
228
+ for (const sub of subscribers) sub.onPgRestWhitelistError(info);
229
+ }
230
+ function makeHandler(requestType) {
231
+ return (info) => {
232
+ for (const sub of subscribers) void sub.onNetworkRequest(info);
233
+ tryDispatchPgRestWhitelistError(
234
+ requestType,
235
+ info.method,
236
+ info.url,
237
+ info.statusCode,
238
+ info.requestBody,
239
+ info.responseBody
240
+ );
241
+ };
242
+ }
243
+ return {
244
+ shouldIgnore,
245
+ install() {
246
+ if (subscribers.length === 0) return;
247
+ const client = getClient();
248
+ if (!client) return;
249
+ const xhrHandler = makeHandler("xhr");
250
+ const fetchHandler = makeHandler("fetch");
251
+ client.on("beforeAddBreadcrumb", (breadcrumb, hint) => {
252
+ const url = breadcrumb.data?.url ?? "";
253
+ if (shouldIgnore(url)) return;
254
+ if (breadcrumb.category === "xhr") {
255
+ handleXhrBreadcrumb(breadcrumb, hint, xhrHandler);
256
+ } else if (breadcrumb.category === "fetch") {
257
+ void handleFetchBreadcrumb(breadcrumb, hint, fetchHandler);
258
+ }
259
+ });
260
+ }
261
+ };
262
+ }
263
+
264
+ // src/capture/capture.ts
9
265
  var SentryCapture = class {
10
- constructor({ onError, onNetwork, onRequest } = {}) {
11
- __publicField(this, "onError");
12
- __publicField(this, "onNetwork");
13
- __publicField(this, "onRequest");
14
- this.onError = onError;
15
- this.onNetwork = onNetwork;
16
- this.onRequest = onRequest;
266
+ constructor(opts, subscribers = []) {
267
+ __publicField(this, "subscribers");
268
+ __publicField(this, "console");
269
+ __publicField(this, "network");
270
+ this.subscribers = subscribers;
271
+ this.console = createConsoleObserver(opts.consoleFilterKeywords, subscribers);
272
+ this.network = createNetworkObserver(opts, subscribers);
17
273
  this.beforeSend = this.beforeSend.bind(this);
18
274
  this.beforeBreadcrumb = this.beforeBreadcrumb.bind(this);
19
275
  }
20
- /**
21
- * 注册 Sentry fetch 监听器,观测所有非 SSE 请求的开始与结束。
22
- * 在 Sentry.init() 后调用一次,复用 Sentry 已打补丁的 fetch,不会二次代理。
23
- */
24
- installFetchObserver() {
25
- if (!this.onRequest) return;
26
- const handler = this.onRequest;
27
- addFetchInstrumentationHandler((data) => {
28
- const { method, url } = data.fetchData;
29
- const responseContentType = data.response?.headers?.get?.("content-type") ?? "";
30
- if (responseContentType.includes("text/event-stream")) return;
31
- if (!data.endTimestamp) {
32
- handler({ method, url, statusCode: null, isEnd: false, isError: false });
33
- return;
34
- }
35
- const statusCode = data.response?.status ?? null;
36
- const isError = data.error != null;
37
- handler({ method, url, statusCode, isEnd: true, isError });
38
- });
276
+ /** 在 Sentry.init() 完成后调用一次,注册网络请求观测器。 */
277
+ installNetworkObserver() {
278
+ this.network.install();
39
279
  }
40
- /**
41
- * 在 Sentry 上报前调用,提取错误信息触发 onError 回调。
42
- * BrowserOptions.beforeSend 要求 ErrorEvent(Event & { type: undefined }),类型需精确匹配。
43
- */
280
+ /** 注册控制台日志观测器,可在 Sentry.init() 前后调用均可。 */
281
+ installConsoleObserver() {
282
+ this.console.install();
283
+ }
284
+ /** 传入 Sentry.init({ beforeSend }) —— 提取错误信息触发 onError 回调。 */
44
285
  beforeSend(event, hint) {
45
- const message = event.exception?.values?.[0]?.value ?? event.message ?? "(unknown)";
286
+ const exceptionValue = event.exception?.values?.[0];
287
+ const message = exceptionValue?.value ?? event.message ?? "(unknown)";
46
288
  const componentStack = event.contexts?.["react"]?.["componentStack"] ?? void 0;
47
- const mechanismType = event.exception?.values?.[0]?.mechanism?.type ?? null;
289
+ const mechanismType = exceptionValue?.mechanism?.type ?? null;
48
290
  const stack = hint.originalException instanceof Error ? hint.originalException.stack : void 0;
49
- this.onError?.({ message, stack, componentStack, mechanismType });
291
+ const errorName = exceptionValue?.type ?? (hint.originalException instanceof Error ? hint.originalException.name : void 0);
292
+ const frames = exceptionValue?.stacktrace?.frames;
293
+ const innerFrame = frames?.length ? frames[frames.length - 1] : void 0;
294
+ const fileName = innerFrame?.filename ?? innerFrame?.abs_path;
295
+ const lineNumber = innerFrame?.lineno;
296
+ const columnNumber = innerFrame?.colno;
297
+ const info = { message, stack, componentStack, mechanismType, errorName, fileName, lineNumber, columnNumber };
298
+ for (const sub of this.subscribers) sub.onError(info);
50
299
  return event;
51
300
  }
52
301
  /**
53
- * 在 Sentry 记录面包屑前调用,提取网络请求信息触发 onNetwork 回调。
302
+ * 传入 Sentry.init({ beforeBreadcrumb })。
303
+ * - console:过滤噪音关键词
304
+ * - fetch/xhr:过滤 ignoreUrls 匹配的静态资源请求
54
305
  */
55
- beforeBreadcrumb(breadcrumb, _hint) {
56
- if (breadcrumb.type === "http") {
57
- const data = breadcrumb.data;
58
- this.onNetwork?.({
59
- method: data?.method ?? null,
60
- url: data?.url ?? null,
61
- statusCode: data?.status_code ?? null
62
- });
306
+ beforeBreadcrumb(breadcrumb, hint) {
307
+ if (breadcrumb.category === "fetch" || breadcrumb.category === "xhr") {
308
+ const url = breadcrumb.data?.url ?? "";
309
+ if (this.network.shouldIgnore(url)) return null;
63
310
  }
64
- return breadcrumb;
311
+ return this.console.beforeBreadcrumb(breadcrumb, hint);
65
312
  }
66
313
  };
314
+
315
+ // src/subscribers/postMessageSubscriber.ts
316
+ function extractUrlPath(url) {
317
+ try {
318
+ const u = new URL(url);
319
+ return u.pathname + u.search + u.hash;
320
+ } catch {
321
+ return url;
322
+ }
323
+ }
324
+ var PostMessageSubscriber = class {
325
+ constructor(send = (msg, origin) => window.parent.postMessage(msg, origin)) {
326
+ __publicField(this, "send");
327
+ this.send = send;
328
+ }
329
+ // postMessage 场景不需要上报 console 日志
330
+ onConsole(_info) {
331
+ }
332
+ onError({ message, stack, errorName, fileName, lineNumber, columnNumber }) {
333
+ const name = errorName ?? "Error";
334
+ const msg = {
335
+ type: "GLOBAL_ERROR",
336
+ message,
337
+ error: stack != null ? { name, message, stack } : null,
338
+ errorData: {
339
+ name,
340
+ message,
341
+ stack,
342
+ fileName: fileName ?? "unknown",
343
+ lineNumber: lineNumber ?? 0,
344
+ columnNumber: columnNumber ?? 0
345
+ }
346
+ };
347
+ this.send(msg, "*");
348
+ }
349
+ onNetworkRequest({ method, url, statusCode, requestBody, responseBody, isError, cause }) {
350
+ const isClientError = statusCode != null && statusCode >= 400 && statusCode < 500;
351
+ if (!isError && !isClientError) return;
352
+ const urlPath = extractUrlPath(url);
353
+ if (isError) {
354
+ const causeDesc = cause != null ? String(cause) : "NetworkError";
355
+ const errorMessage = `${method} ${urlPath} failed: ${causeDesc}`;
356
+ const msg = {
357
+ type: "GLOBAL_ERROR",
358
+ message: errorMessage,
359
+ error: cause != null ? { name: cause.name, message: cause.message, stack: cause.stack } : null,
360
+ errorData: {
361
+ name: cause?.name ?? "NetworkError",
362
+ message: cause?.message ?? causeDesc,
363
+ stack: cause?.stack ?? null,
364
+ fileName: url,
365
+ lineNumber: 0,
366
+ columnNumber: 0,
367
+ httpPath: urlPath,
368
+ httpStatus: 0,
369
+ httpMethod: method,
370
+ requestBody: requestBody ?? "",
371
+ responseBody: ""
372
+ }
373
+ };
374
+ this.send(msg, "*");
375
+ } else {
376
+ const errorMessage = `${method} ${urlPath} -> ${statusCode}`;
377
+ const msg = {
378
+ type: "GLOBAL_ERROR",
379
+ message: errorMessage,
380
+ error: null,
381
+ errorData: {
382
+ name: "HTTPClientError",
383
+ message: errorMessage,
384
+ stack: null,
385
+ fileName: url,
386
+ lineNumber: 0,
387
+ columnNumber: 0,
388
+ httpPath: urlPath,
389
+ httpStatus: statusCode,
390
+ httpMethod: method,
391
+ requestBody: requestBody ?? "",
392
+ responseBody: responseBody ?? ""
393
+ }
394
+ };
395
+ this.send(msg, "*");
396
+ }
397
+ }
398
+ onPgRestWhitelistError({ type, method, url, statusCode, pgRestError, requestBody, responseBody }) {
399
+ const urlPath = extractUrlPath(url);
400
+ const code = pgRestError.code;
401
+ const errorMessage = `${method} ${urlPath} -> ${statusCode} [PgRest:${code}]`;
402
+ const msg = {
403
+ type: "GLOBAL_ERROR",
404
+ message: errorMessage,
405
+ error: null,
406
+ errorData: {
407
+ name: "PgRestWhitelistError",
408
+ message: pgRestError.message,
409
+ stack: null,
410
+ fileName: url,
411
+ lineNumber: 0,
412
+ columnNumber: 0,
413
+ httpPath: urlPath,
414
+ httpStatus: statusCode,
415
+ httpMethod: method,
416
+ requestBody: requestBody ?? "",
417
+ responseBody,
418
+ pgRestCode: code,
419
+ pgRestDetails: pgRestError.details ?? void 0,
420
+ pgRestHint: pgRestError.hint ?? void 0,
421
+ requestType: type
422
+ }
423
+ };
424
+ this.send(msg, "*");
425
+ }
426
+ };
427
+ function createPostMessageSubscriber(send) {
428
+ return new PostMessageSubscriber(send);
429
+ }
430
+
431
+ // src/subscribers/noopSubscriber.ts
432
+ function createNoopSubscriber() {
433
+ return {
434
+ onConsole() {
435
+ },
436
+ onError() {
437
+ },
438
+ onNetworkRequest() {
439
+ },
440
+ onPgRestWhitelistError() {
441
+ }
442
+ };
443
+ }
67
444
  export {
68
- SentryCapture
445
+ DEFAULT_CONSOLE_FILTER_KEYWORDS,
446
+ DEFAULT_IGNORE_URLS,
447
+ DEFAULT_PGREST_URL_PATTERNS,
448
+ DEFAULT_PGREST_WHITELIST_CODES,
449
+ SentryCapture,
450
+ createNoopSubscriber,
451
+ createPostMessageSubscriber
69
452
  };
70
453
  //# sourceMappingURL=index.js.map