@blueking/open-telemetry 0.0.5 → 0.0.7

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
@@ -9,39 +9,85 @@ import { registerInstrumentations as p } from "@opentelemetry/instrumentation";
9
9
  import { resourceFromAttributes as m } from "@opentelemetry/resources";
10
10
  import { BatchLogRecordProcessor as h, LoggerProvider as g } from "@opentelemetry/sdk-logs";
11
11
  import { MeterProvider as _, PeriodicExportingMetricReader as v } from "@opentelemetry/sdk-metrics";
12
- import { BatchSpanProcessor as y, ParentBasedSampler as b, TraceIdRatioBasedSampler as x } from "@opentelemetry/sdk-trace-base";
13
- import { WebTracerProvider as S } from "@opentelemetry/sdk-trace-web";
12
+ import { BatchSpanProcessor as y, ParentBasedSampler as ee, SimpleSpanProcessor as te, TraceIdRatioBasedSampler as ne } from "@opentelemetry/sdk-trace-base";
13
+ import { WebTracerProvider as re } from "@opentelemetry/sdk-trace-web";
14
+ //#region src/schema/attributes.ts
15
+ var b = {
16
+ actionType: "action.type",
17
+ deploymentEnvironmentName: "deployment.environment.name",
18
+ browserName: "browser_name",
19
+ browserVersion: "browser_version",
20
+ cacheHit: "cache_hit",
21
+ deviceType: "device_type",
22
+ durationBucket: "duration_bucket",
23
+ errorType: "error_type",
24
+ eventLabel: "event_label",
25
+ exceptionFingerprint: "exception.fingerprint",
26
+ exceptionMessageShort: "exception.message_short",
27
+ exceptionStackTopFrame: "exception.stack_top_frame",
28
+ longtaskAttributionScript: "longtask.attribution_script",
29
+ longtaskBlockingDuration: "longtask.blocking_duration",
30
+ networkEffectiveType: "network.effective_type",
31
+ nextHopProtocol: "next_hop_protocol",
32
+ result: "result",
33
+ serviceName: "service.name",
34
+ serviceVersion: "service.version",
35
+ osName: "os_name",
36
+ sessionHasReplay: "session.has_replay",
37
+ sessionId: "session.id",
38
+ sessionStartTime: "session.start_time",
39
+ spanSubtype: "span_subtype",
40
+ spanType: "span_type",
41
+ statusClass: "status_class",
42
+ targetDomain: "target_domain",
43
+ targetLabel: "target_label",
44
+ targetPathTemplate: "target_path_template",
45
+ targetTag: "target.tag",
46
+ targetTextShort: "target.text_short",
47
+ targetValue: "target_value",
48
+ traceScene: "trace_scene",
49
+ transferSize: "transfer_size",
50
+ userId: "user.id",
51
+ vitalMetric: "vital.metric",
52
+ vitalRating: "vital.rating",
53
+ vitalValue: "vital.value",
54
+ viewId: "view.id",
55
+ viewLoadingType: "view.loading_type",
56
+ viewUrl: "view.url",
57
+ viewUrlPathGroup: "view.url_path_group"
58
+ };
59
+ //#endregion
14
60
  //#region \0@oxc-project+runtime@0.128.0/helpers/typeof.js
15
- function C(e) {
61
+ function x(e) {
16
62
  "@babel/helpers - typeof";
17
- return C = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(e) {
63
+ return x = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(e) {
18
64
  return typeof e;
19
65
  } : function(e) {
20
66
  return e && typeof Symbol == "function" && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e;
21
- }, C(e);
67
+ }, x(e);
22
68
  }
23
69
  //#endregion
24
70
  //#region \0@oxc-project+runtime@0.128.0/helpers/toPrimitive.js
25
- function w(e, t) {
26
- if (C(e) != "object" || !e) return e;
71
+ function S(e, t) {
72
+ if (x(e) != "object" || !e) return e;
27
73
  var n = e[Symbol.toPrimitive];
28
74
  if (n !== void 0) {
29
75
  var r = n.call(e, t || "default");
30
- if (C(r) != "object") return r;
76
+ if (x(r) != "object") return r;
31
77
  throw TypeError("@@toPrimitive must return a primitive value.");
32
78
  }
33
79
  return (t === "string" ? String : Number)(e);
34
80
  }
35
81
  //#endregion
36
82
  //#region \0@oxc-project+runtime@0.128.0/helpers/toPropertyKey.js
37
- function T(e) {
38
- var t = w(e, "string");
39
- return C(t) == "symbol" ? t : t + "";
83
+ function ie(e) {
84
+ var t = S(e, "string");
85
+ return x(t) == "symbol" ? t : t + "";
40
86
  }
41
87
  //#endregion
42
88
  //#region \0@oxc-project+runtime@0.128.0/helpers/defineProperty.js
43
- function E(e, t, n) {
44
- return (t = T(t)) in e ? Object.defineProperty(e, t, {
89
+ function C(e, t, n) {
90
+ return (t = ie(t)) in e ? Object.defineProperty(e, t, {
45
91
  value: n,
46
92
  enumerable: !0,
47
93
  configurable: !0,
@@ -50,7 +96,7 @@ function E(e, t, n) {
50
96
  }
51
97
  //#endregion
52
98
  //#region \0@oxc-project+runtime@0.128.0/helpers/objectSpread2.js
53
- function D(e, t) {
99
+ function w(e, t) {
54
100
  var n = Object.keys(e);
55
101
  if (Object.getOwnPropertySymbols) {
56
102
  var r = Object.getOwnPropertySymbols(e);
@@ -60,12 +106,12 @@ function D(e, t) {
60
106
  }
61
107
  return n;
62
108
  }
63
- function O(e) {
109
+ function T(e) {
64
110
  for (var t = 1; t < arguments.length; t++) {
65
111
  var n = arguments[t] == null ? {} : arguments[t];
66
- t % 2 ? D(Object(n), !0).forEach(function(t) {
67
- E(e, t, n[t]);
68
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : D(Object(n)).forEach(function(t) {
112
+ t % 2 ? w(Object(n), !0).forEach(function(t) {
113
+ C(e, t, n[t]);
114
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : w(Object(n)).forEach(function(t) {
69
115
  Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t));
70
116
  });
71
117
  }
@@ -73,90 +119,147 @@ function O(e) {
73
119
  }
74
120
  //#endregion
75
121
  //#region src/core/config.ts
76
- var k = "http://localhost:4318", ee = 60 * 1e3, A = (e) => e.replace(/\/+$/, ""), j = (e, t) => {
77
- let n = A(e || k);
122
+ var ae = "http://localhost:4318", oe = 60 * 1e3, se = "unknown_service", E = (e) => e.replace(/\/+$/, ""), ce = (e, t) => {
123
+ let n = E(e || ae);
78
124
  return n.endsWith(`/v1/${t}`) ? n : n.endsWith("/v1") ? `${n}/${t}` : `${n}/v1/${t}`;
79
- }, M = (e, t) => {
80
- var n, r, i, a;
81
- let o = e[t], s = (n = e.signalEndpoints) == null ? void 0 : n[t], c = e.token || e.headers || o != null && o.headers ? O(O(O({}, e.token ? { Authorization: `Bearer ${e.token}` } : {}), (r = e.headers) == null ? {} : r), (i = o == null ? void 0 : o.headers) == null ? {} : i) : void 0;
125
+ }, D = (e, t) => {
126
+ var n, r, i, a, o;
127
+ let s = e == null || (n = e.signals) == null ? void 0 : n[t], c = e == null || (r = e.signals) == null || (r = r.endpoints) == null ? void 0 : r[t], l = e != null && e.token || e != null && e.headers || s != null && s.headers ? T(T(T({}, e != null && e.token ? { Authorization: `Bearer ${e.token}` } : {}), (i = e == null ? void 0 : e.headers) == null ? {} : i), (a = s == null ? void 0 : s.headers) == null ? {} : a) : void 0;
82
128
  return {
83
- concurrencyLimit: o == null ? void 0 : o.concurrencyLimit,
84
- endpoint: s ? A(s) : j((a = o == null ? void 0 : o.endpoint) == null ? e.endpoint : a, t),
85
- headers: c,
86
- timeoutMillis: o == null ? void 0 : o.timeoutMillis
129
+ concurrencyLimit: s == null ? void 0 : s.concurrencyLimit,
130
+ endpoint: c ? E(c) : ce((o = s == null ? void 0 : s.endpoint) == null ? e == null ? void 0 : e.endpoint : o, t),
131
+ headers: l,
132
+ timeoutMillis: s == null ? void 0 : s.timeoutMillis
87
133
  };
88
- }, te = (e) => typeof e != "number" || !Number.isFinite(e) ? 1 : Math.max(0, Math.min(1, e)), N = (e, t) => typeof e == "number" && Number.isFinite(e) && e > 0 ? e : t, ne = (e, t) => typeof e == "number" && Number.isFinite(e) && e >= 0 ? e : t, re = (e, t) => typeof e != "number" || !Number.isFinite(e) ? t : Math.max(0, Math.min(1, e)), ie = (e) => e.body, ae = (e) => {
134
+ }, le = (e) => typeof e != "number" || !Number.isFinite(e) ? 1 : Math.max(0, Math.min(1, e)), O = (e, t) => typeof e == "number" && Number.isFinite(e) && e > 0 ? e : t, ue = (e, t) => typeof e == "number" && Number.isFinite(e) && e >= 0 ? e : t, de = (e, t) => typeof e != "number" || !Number.isFinite(e) ? t : Math.max(0, Math.min(1, e)), fe = (e) => e.body, k = () => ({ enabled: !1 }), A = (e) => T({ enabled: !0 }, e), j = (e) => e ? { enabled: !0 } : k(), pe = (e) => e === !1 ? k() : { enabled: !0 }, me = (e) => {
89
135
  var t;
90
- return e ? typeof e == "boolean" ? {
136
+ return e ? A(typeof e == "boolean" ? {
91
137
  maxBodySize: 10 * 1024,
92
- redact: ie
138
+ redact: fe
93
139
  } : {
94
- maxBodySize: N(e.maxBodySize, 10 * 1024),
95
- redact: (t = e.redact) == null ? ie : t
96
- } : !1;
97
- }, oe = (e) => {
98
- var t, n, r, i, a, o, s, c, l, u;
140
+ maxBodySize: O(e.maxBodySize, 10 * 1024),
141
+ redact: (t = e.redact) == null ? fe : t
142
+ }) : k();
143
+ }, he = (e) => {
144
+ var t;
99
145
  return {
100
- device: (t = e == null ? void 0 : e.device) == null ? !0 : t,
101
- httpBody: ae(e == null ? void 0 : e.httpBody),
102
- session: typeof (e == null ? void 0 : e.session) == "object" ? O(O({}, e.session), {}, { inactivityMs: N(e.session.inactivityMs, 1800 * 1e3) }) : (n = e == null ? void 0 : e.session) == null ? !0 : n,
103
- pageView: (r = e == null ? void 0 : e.pageView) == null ? !0 : r,
104
- error: typeof (e == null ? void 0 : e.error) == "object" ? O(O({}, e.error), {}, {
105
- maxPerWindow: N(e.error.maxPerWindow, 5),
106
- windowMs: N(e.error.windowMs, 6e4)
107
- }) : (i = e == null ? void 0 : e.error) == null ? !0 : i,
108
- webVitals: (a = e == null ? void 0 : e.webVitals) == null ? !0 : a,
109
- blankScreen: typeof (e == null ? void 0 : e.blankScreen) == "object" ? O(O({}, e.blankScreen), {}, {
110
- checkDelay: ne(e.blankScreen.checkDelay, 3e3),
111
- threshold: re(e.blankScreen.threshold, .8)
112
- }) : (o = e == null ? void 0 : e.blankScreen) == null ? !0 : o,
113
- websocket: (s = e == null ? void 0 : e.websocket) == null ? !0 : s,
114
- longTask: typeof (e == null ? void 0 : e.longTask) == "object" ? O(O({}, e.longTask), {}, { threshold: ne(e.longTask.threshold, 50) }) : (c = e == null ? void 0 : e.longTask) == null ? !1 : c,
115
- cspViolation: (l = e == null ? void 0 : e.cspViolation) == null ? !1 : l,
116
- routeTiming: (u = e == null ? void 0 : e.routeTiming) == null ? !1 : u
117
- };
118
- }, se = (e) => e, ce = (e) => e, le = (e) => {
119
- var t, n, r, i, a, o, s, c, l, u, d, f, p, m, h, g, _, v, y, b, x, S, C, w, T, E, D;
120
- let j = {
121
- "deployment.environment.name": (t = e.environment) == null ? "production" : t,
122
- "rum.provider": "blueking",
123
- "telemetry.sdk.language": "webjs"
146
+ action: typeof (e == null ? void 0 : e.action) == "object" ? A({ eventNames: (t = e.action.eventNames) == null ? [
147
+ "click",
148
+ "submit",
149
+ "keydown"
150
+ ] : t }) : e != null && e.action ? A({ eventNames: [
151
+ "click",
152
+ "submit",
153
+ "keydown"
154
+ ] }) : k(),
155
+ device: typeof (e == null ? void 0 : e.device) == "object" ? A({ storageKey: e.device.storageKey }) : (e == null ? void 0 : e.device) === !1 ? k() : A({}),
156
+ httpBody: me(e == null ? void 0 : e.httpBody),
157
+ session: typeof (e == null ? void 0 : e.session) == "object" ? A({
158
+ inactivityMs: O(e.session.inactivityMs, 1800 * 1e3),
159
+ maxLifetimeMs: O(e.session.maxLifetimeMs, 1440 * 60 * 1e3),
160
+ storageKey: e.session.storageKey
161
+ }) : (e == null ? void 0 : e.session) === !1 ? k() : A({
162
+ inactivityMs: 1800 * 1e3,
163
+ maxLifetimeMs: 1440 * 60 * 1e3
164
+ }),
165
+ pageView: pe(e == null ? void 0 : e.pageView),
166
+ resource: pe(e == null ? void 0 : e.resource),
167
+ error: typeof (e == null ? void 0 : e.error) == "object" ? A({
168
+ maxPerWindow: O(e.error.maxPerWindow, 5),
169
+ windowMs: O(e.error.windowMs, 6e4)
170
+ }) : (e == null ? void 0 : e.error) === !1 ? k() : A({
171
+ maxPerWindow: 5,
172
+ windowMs: 6e4
173
+ }),
174
+ webVitals: pe(e == null ? void 0 : e.webVitals),
175
+ blankScreen: typeof (e == null ? void 0 : e.blankScreen) == "object" ? A({
176
+ checkDelay: ue(e.blankScreen.checkDelay, 3e3),
177
+ ignoreSelectors: e.blankScreen.ignoreSelectors,
178
+ rootSelector: e.blankScreen.rootSelector,
179
+ threshold: de(e.blankScreen.threshold, .8)
180
+ }) : (e == null ? void 0 : e.blankScreen) === !1 ? k() : A({
181
+ checkDelay: 3e3,
182
+ threshold: .8
183
+ }),
184
+ websocket: j(e == null ? void 0 : e.websocket),
185
+ longTask: typeof (e == null ? void 0 : e.longTask) == "object" ? A({ threshold: ue(e.longTask.threshold, 50) }) : e != null && e.longTask ? A({ threshold: 50 }) : k(),
186
+ cspViolation: j(e == null ? void 0 : e.cspViolation),
187
+ routeTiming: j(e == null ? void 0 : e.routeTiming)
124
188
  };
125
- return O(O({}, e), {}, {
126
- debug: (n = e.debug) == null ? !1 : n,
127
- enabled: (r = e.enabled) == null ? !0 : r,
128
- environment: (i = e.environment) == null ? "production" : i,
129
- endpoint: A(e.endpoint || k),
130
- traces: M(e, "traces"),
131
- metrics: M(e, "metrics"),
132
- logs: M(e, "logs"),
133
- sampleRate: te(e.sampleRate),
134
- resourceAttributes: j,
135
- metricIntervalMillis: ee,
136
- instrumentations: (a = e.instrumentations) == null ? [] : a,
137
- commonInstrumentations: {
138
- documentLoad: (o = (s = e.rum) == null ? void 0 : s.documentLoad) == null ? !0 : o,
139
- fetch: (c = (l = e.rum) == null ? void 0 : l.fetch) == null ? !0 : c,
140
- xhr: (u = (d = e.rum) == null ? void 0 : d.xhr) == null ? !0 : u,
141
- userInteraction: (f = (p = e.rum) == null ? void 0 : p.userInteraction) == null ? !0 : f
189
+ }, ge = (e) => {
190
+ var t, n, r, i, a, o, s, c;
191
+ return {
192
+ instrumentations: {
193
+ documentLoad: (t = e == null || (n = e.instrumentations) == null ? void 0 : n.documentLoad) == null ? !0 : t,
194
+ fetch: (r = e == null || (i = e.instrumentations) == null ? void 0 : i.fetch) == null ? !0 : r,
195
+ xhr: (a = e == null || (o = e.instrumentations) == null ? void 0 : o.xhr) == null ? !0 : a,
196
+ userInteraction: (s = e == null || (c = e.instrumentations) == null ? void 0 : c.userInteraction) == null ? !0 : s
142
197
  },
143
- rum: oe(e.rum),
144
- plugins: (m = e.plugins) == null ? [] : m,
145
- autoStart: (h = e.autoStart) == null ? !0 : h,
146
- getPageAttributes: (g = (_ = e.attributes) == null ? void 0 : _.page) == null ? (() => ({
198
+ plugins: he(e == null ? void 0 : e.plugins)
199
+ };
200
+ }, _e = (e) => e, ve = (e) => e, ye = (e) => {
201
+ try {
202
+ return new URL(e, typeof location > "u" ? "http://localhost" : location.href).pathname || "/";
203
+ } catch (t) {
204
+ return e || "/";
205
+ }
206
+ }, be = (e) => {
207
+ var t, n;
208
+ return {
209
+ environment: (t = e == null ? void 0 : e.environment) == null ? "production" : t,
210
+ name: (n = e == null ? void 0 : e.name) == null ? se : n,
211
+ version: e == null ? void 0 : e.version
212
+ };
213
+ }, xe = (e) => T(T({
214
+ [b.deploymentEnvironmentName]: e.environment,
215
+ "rum.provider": "blueking",
216
+ [b.serviceName]: e.name
217
+ }, e.version ? { [b.serviceVersion]: e.version } : {}), {}, { "telemetry.sdk.language": "webjs" }), Se = (e) => ({
218
+ endpoint: E((e == null ? void 0 : e.endpoint) || ae),
219
+ traces: D(e, "traces"),
220
+ metrics: D(e, "metrics"),
221
+ logs: D(e, "logs")
222
+ }), Ce = (e) => ({ rate: le(e == null ? void 0 : e.rate) }), we = (e) => {
223
+ var t, n, r, i, a, o, s, c, l, u, d, f;
224
+ return {
225
+ getPageAttributes: (t = (n = e.attributes) == null ? void 0 : n.page) == null ? (() => ({
147
226
  "rum.page.host": typeof window > "u" ? "" : window.location.host,
148
227
  "rum.page.path": typeof window > "u" ? "" : window.location.pathname
149
- })) : g,
150
- getMetricAttributes: (v = (y = e.attributes) == null ? void 0 : y.metric) == null ? (() => ({})) : v,
151
- getErrorAttributes: (b = (x = e.attributes) == null ? void 0 : x.error) == null ? (() => ({})) : b,
152
- getCustomAttributes: (S = (C = e.attributes) == null ? void 0 : C.custom) == null ? (() => ({})) : S,
153
- redactAttributes: (w = (T = e.redact) == null ? void 0 : T.attributes) == null ? se : w,
154
- redactUrl: (E = (D = e.redact) == null ? void 0 : D.url) == null ? ce : E
155
- });
228
+ })) : t,
229
+ getMetricAttributes: (r = (i = e.attributes) == null ? void 0 : i.metric) == null ? (() => ({})) : r,
230
+ getErrorAttributes: (a = (o = e.attributes) == null ? void 0 : o.error) == null ? (() => ({})) : a,
231
+ getCustomAttributes: (s = (c = e.attributes) == null ? void 0 : c.custom) == null ? (() => ({})) : s,
232
+ getViewPathGroup: (t) => {
233
+ var n, r, i;
234
+ return (n = (r = e.route) == null || (i = r.getPathGroup) == null ? void 0 : i.call(r, t)) == null ? ye(t) : n;
235
+ },
236
+ redactAttributes: (l = (u = e.privacy) == null ? void 0 : u.redactAttributes) == null ? _e : l,
237
+ redactUrl: (d = (f = e.privacy) == null ? void 0 : f.redactUrl) == null ? ve : d
238
+ };
239
+ }, Te = (e) => {
240
+ var t, n, r, i, a, o;
241
+ let s = be(e.app);
242
+ return {
243
+ app: s,
244
+ autoStart: (t = e.autoStart) == null ? !0 : t,
245
+ debug: (n = e.debug) == null ? !1 : n,
246
+ enabled: (r = e.enabled) == null ? !0 : r,
247
+ hooks: we(e),
248
+ instrumentations: (i = e.instrumentations) == null ? [] : i,
249
+ metricIntervalMillis: oe,
250
+ plugins: (a = e.plugins) == null ? [] : a,
251
+ resourceAttributes: xe(s),
252
+ rum: ge(e.rum),
253
+ sampling: Ce(e.sampling),
254
+ spanBatch: e.spanBatch,
255
+ spanProcessor: (o = e.spanProcessor) == null ? "batch" : o,
256
+ transport: Se(e.transport),
257
+ user: e.user
258
+ };
156
259
  };
157
260
  //#endregion
158
261
  //#region \0@oxc-project+runtime@0.128.0/helpers/asyncToGenerator.js
159
- function ue(e, t, n, r, i, a, o) {
262
+ function Ee(e, t, n, r, i, a, o) {
160
263
  try {
161
264
  var s = e[a](o), c = s.value;
162
265
  } catch (e) {
@@ -165,16 +268,16 @@ function ue(e, t, n, r, i, a, o) {
165
268
  }
166
269
  s.done ? t(c) : Promise.resolve(c).then(r, i);
167
270
  }
168
- function P(e) {
271
+ function M(e) {
169
272
  return function() {
170
273
  var t = this, n = arguments;
171
274
  return new Promise(function(r, i) {
172
275
  var a = e.apply(t, n);
173
276
  function o(e) {
174
- ue(a, r, i, o, s, "next", e);
277
+ Ee(a, r, i, o, s, "next", e);
175
278
  }
176
279
  function s(e) {
177
- ue(a, r, i, o, s, "throw", e);
280
+ Ee(a, r, i, o, s, "throw", e);
178
281
  }
179
282
  o(void 0);
180
283
  });
@@ -182,13 +285,13 @@ function P(e) {
182
285
  }
183
286
  //#endregion
184
287
  //#region src/core/plugin.ts
185
- var de = (e, t) => typeof e.enabled == "function" ? e.enabled(t) : e.enabled !== !1, fe = (e) => e, pe = class {
288
+ var De = (e, t) => typeof e.enabled == "function" ? e.enabled(t) : e.enabled !== !1, Oe = (e) => e, ke = class {
186
289
  constructor(e) {
187
- E(this, "plugins", void 0), E(this, "startedPlugins", []), this.plugins = e;
290
+ C(this, "plugins", void 0), C(this, "startedPlugins", []), this.plugins = e;
188
291
  }
189
292
  flush() {
190
293
  var e = this;
191
- return P(function* () {
294
+ return M(function* () {
192
295
  yield Promise.all(e.startedPlugins.map((e) => Promise.resolve().then(() => {
193
296
  var t;
194
297
  return (t = e.flush) == null ? void 0 : t.call(e);
@@ -197,7 +300,7 @@ var de = (e, t) => typeof e.enabled == "function" ? e.enabled(t) : e.enabled !==
197
300
  }
198
301
  shutdown() {
199
302
  var e = this;
200
- return P(function* () {
303
+ return M(function* () {
201
304
  let t = [...e.startedPlugins].reverse();
202
305
  for (let e of t) {
203
306
  var n;
@@ -208,43 +311,46 @@ var de = (e, t) => typeof e.enabled == "function" ? e.enabled(t) : e.enabled !==
208
311
  }
209
312
  start(e) {
210
313
  var t = this;
211
- return P(function* () {
212
- try {
213
- for (let n of t.plugins) de(n, e.config) && (yield n.init(e), t.startedPlugins.push(n));
214
- } catch (e) {
215
- throw yield t.shutdown(), e;
314
+ return M(function* () {
315
+ for (let r of t.plugins) if (De(r, e.config)) try {
316
+ yield r.init(e), t.startedPlugins.push(r);
317
+ } catch (t) {
318
+ if (e.config.debug) {
319
+ var n;
320
+ (n = globalThis.console) == null || n.warn(`[bk-ot] plugin "${r.name}" init failed:`, t);
321
+ }
216
322
  }
217
323
  })();
218
324
  }
219
- }, F = () => typeof window > "u" ? "http://localhost" : window.location.origin, me = (e) => {
325
+ }, Ae = () => typeof window > "u" ? "http://localhost" : window.location.origin, je = (e) => {
220
326
  try {
221
- return new URL(e, F()).href;
327
+ return new URL(e, Ae()).href;
222
328
  } catch (t) {
223
329
  return e;
224
330
  }
225
- }, he = (e) => e.length > 1 ? e.replace(/\/+$/, "") : e, ge = (e, t) => {
226
- let n = (e) => he(e.replace(/[?#].*$/, ""));
331
+ }, Me = (e) => e.length > 1 ? e.replace(/\/+$/, "") : e, Ne = (e, t) => {
332
+ let n = (e) => Me(e.replace(/[?#].*$/, ""));
227
333
  return n(e) === n(t);
228
- }, _e = (e) => {
334
+ }, Pe = (e) => {
229
335
  try {
230
- return new URL(e, F()).origin === F();
336
+ return new URL(e, Ae()).origin === Ae();
231
337
  } catch (e) {
232
338
  return !1;
233
339
  }
234
- }, ve = (e, t) => {
235
- let n = me(t);
340
+ }, Fe = (e, t) => {
341
+ let n = je(t);
236
342
  return [
237
- e.traces.endpoint,
238
- e.metrics.endpoint,
239
- e.logs.endpoint
240
- ].some((e) => ge(n, me(e)));
241
- }, I = (e, t) => ve(e, t), ye = (e, t) => _e(t), be = ["http.url", "url.full"], xe = (e) => {
242
- for (let n of be) {
343
+ e.transport.traces.endpoint,
344
+ e.transport.metrics.endpoint,
345
+ e.transport.logs.endpoint
346
+ ].some((e) => Ne(n, je(e)));
347
+ }, N = (e, t) => Fe(e, t), Ie = (e, t) => Pe(t), Le = ["http.url", "url.full"], Re = (e) => {
348
+ for (let n of Le) {
243
349
  var t;
244
350
  let r = (t = e.attributes) == null ? void 0 : t[n];
245
351
  if (typeof r == "string") return r;
246
352
  }
247
- }, Se = class {
353
+ }, ze = class {
248
354
  constructor(e, t) {
249
355
  this.inner = e, this.config = t;
250
356
  }
@@ -252,8 +358,8 @@ var de = (e, t) => typeof e.enabled == "function" ? e.enabled(t) : e.enabled !==
252
358
  return this.inner.forceFlush();
253
359
  }
254
360
  onEnd(e) {
255
- let t = xe(e);
256
- t && ve(this.config, t) || this.inner.onEnd(e);
361
+ let t = Re(e);
362
+ t && Fe(this.config, t) || this.inner.onEnd(e);
257
363
  }
258
364
  onStart(e, t) {
259
365
  this.inner.onStart(e, t);
@@ -261,7 +367,137 @@ var de = (e, t) => typeof e.enabled == "function" ? e.enabled(t) : e.enabled !==
261
367
  shutdown() {
262
368
  return this.inner.shutdown();
263
369
  }
264
- }, Ce = "body", we = 3e3, Te = .8, Ee = [
370
+ }, Be = class {
371
+ constructor(e = {}, t) {
372
+ C(this, "attributes", {}), C(this, "setOptionalAttribute", (e, t) => {
373
+ if (t === void 0) {
374
+ delete this.attributes[e];
375
+ return;
376
+ }
377
+ this.attributes[e] = t;
378
+ }), C(this, "user", {}), C(this, "view", {}), C(this, "getAttributes", () => T({}, this.attributes)), C(this, "getUser", () => T({}, this.user)), C(this, "getView", () => T({}, this.view)), C(this, "setAttributes", (e) => {
379
+ for (let [t, n] of Object.entries(e)) {
380
+ if (n === void 0) {
381
+ delete this.attributes[t];
382
+ continue;
383
+ }
384
+ this.attributes[t] = n;
385
+ }
386
+ }), C(this, "setUser", (e) => {
387
+ if (this.user = T(T({}, this.user), e), "id" in e) {
388
+ if (e.id === void 0) {
389
+ delete this.attributes[b.userId];
390
+ return;
391
+ }
392
+ this.attributes[b.userId] = e.id;
393
+ }
394
+ }), C(this, "setView", (e) => {
395
+ this.view = T(T({}, this.view), e), this.setOptionalAttribute(b.viewId, e.id), this.setOptionalAttribute(b.viewUrl, e.url), this.setOptionalAttribute(b.viewUrlPathGroup, e.urlPathGroup), this.setOptionalAttribute(b.viewLoadingType, e.loadingType);
396
+ }), this.setAttributes(e), t && this.setUser(t);
397
+ }
398
+ }, P = {
399
+ abort: "abort",
400
+ error: "error",
401
+ success: "success",
402
+ timeout: "timeout",
403
+ warning: "warning"
404
+ }, F = {
405
+ action: "action",
406
+ custom: "custom",
407
+ document: "document",
408
+ error: "error",
409
+ http: "http",
410
+ longtask: "longtask",
411
+ resource: "resource",
412
+ route: "route",
413
+ vital: "vital"
414
+ }, Ve = (e) => e < 100 ? "<100ms" : e < 500 ? "100~500ms" : e < 2e3 ? "500ms~2s" : ">2s", He = (e) => `${Math.trunc(e / 100)}xx`, Ue = (e) => e === 408 || e === 504 ? P.timeout : typeof e == "number" && e >= 400 ? P.error : P.success, We = (e) => e === 408 || e === 504 ? "network_timeout" : typeof e != "number" || e < 400 ? "none" : e >= 500 ? "http_5xx" : "http_4xx", Ge = (e) => e === "good" ? P.success : P.warning, Ke = (e, t) => {
415
+ if (!e) return {};
416
+ try {
417
+ let n = new URL(e, typeof location > "u" ? "http://localhost" : location.href), r = t == null ? n.pathname : t;
418
+ return {
419
+ domain: n.host,
420
+ label: `${n.host}${r}`,
421
+ pathTemplate: r
422
+ };
423
+ } catch (n) {
424
+ return {
425
+ label: e,
426
+ pathTemplate: t == null ? e : t
427
+ };
428
+ }
429
+ }, I = ({ duration: e, errorType: t = "none", eventLabel: n, result: r = P.success, spanSubtype: i, spanType: a, targetLabel: o, targetValue: s, traceScene: c }) => T(T(T(T(T({
430
+ [b.spanType]: a,
431
+ [b.spanSubtype]: i,
432
+ [b.result]: r,
433
+ [b.errorType]: t
434
+ }, e === void 0 ? {} : { [b.durationBucket]: Ve(e) }), n === void 0 ? {} : { [b.eventLabel]: n }), o === void 0 ? {} : { [b.targetLabel]: o }), s === void 0 ? {} : { [b.targetValue]: s }), c === void 0 ? {} : { [b.traceScene]: c }), qe = ({ duration: e, method: t, statusCode: n, subtype: r, url: i, urlPathTemplate: a }) => {
435
+ let o = Ke(i, a);
436
+ return T(T(T(T(T({}, I({
437
+ duration: e,
438
+ errorType: We(n),
439
+ eventLabel: "API 调用",
440
+ result: Ue(n),
441
+ spanSubtype: r,
442
+ spanType: F.http,
443
+ targetLabel: o.label,
444
+ targetValue: n
445
+ })), t ? { "http.request.method": t.toUpperCase() } : {}), o.domain ? { [b.targetDomain]: o.domain } : {}), o.pathTemplate ? { [b.targetPathTemplate]: o.pathTemplate } : {}), typeof n == "number" ? {
446
+ "http.response.status_code": n,
447
+ [b.statusClass]: He(n)
448
+ } : {});
449
+ }, Je = ({ duration: e, initiatorType: t = "other", responseStatus: n, transferSize: r, url: i, urlPathTemplate: a }) => {
450
+ var o;
451
+ let s = Ke(i, a), c = typeof n == "number" ? Ue(n) : P.success;
452
+ return T(T(T(T({}, I({
453
+ duration: e,
454
+ errorType: typeof n == "number" ? We(n) : "none",
455
+ eventLabel: "静态资源",
456
+ result: c,
457
+ spanSubtype: t,
458
+ spanType: F.resource,
459
+ targetLabel: (o = s.label) == null ? i : o,
460
+ targetValue: r
461
+ })), s.domain ? { [b.targetDomain]: s.domain } : {}), s.pathTemplate ? { [b.targetPathTemplate]: s.pathTemplate } : {}), typeof n == "number" ? {
462
+ "http.response.status_code": n,
463
+ [b.statusClass]: He(n)
464
+ } : {});
465
+ }, Ye = (e) => e instanceof Element ? e : void 0, Xe = (e) => {
466
+ var t;
467
+ if (!e) return;
468
+ let n = ((t = e.textContent) == null ? void 0 : t.trim()) || e.getAttribute("aria-label") || e.getAttribute("title") || "";
469
+ return n ? n.slice(0, 32) : void 0;
470
+ }, Ze = (e) => {
471
+ let t = [];
472
+ return {
473
+ name: "action",
474
+ enabled: e.enabled,
475
+ init(n) {
476
+ if (typeof window > "u") return;
477
+ let r = {
478
+ capture: !0,
479
+ passive: !0
480
+ }, i = (e) => {
481
+ var t;
482
+ let r = Ye(e.target), i = Xe(r), a = r == null ? void 0 : r.tagName.toLowerCase();
483
+ n.startSpan(`action.${e.type}`, T(T(T(T({}, n.config.hooks.getPageAttributes()), I({
484
+ errorType: "none",
485
+ eventLabel: "用户操作",
486
+ spanSubtype: e.type,
487
+ spanType: F.action,
488
+ targetLabel: (t = i == null ? a : i) == null ? e.type : t
489
+ })), {}, { [b.actionType]: e.type }, i ? { [b.targetTextShort]: i } : {}), a ? { [b.targetTag]: a } : {})).end();
490
+ };
491
+ for (let n of e.enabled ? e.eventNames : []) window.addEventListener(n, i, r), t.push(() => window.removeEventListener(n, i, r));
492
+ },
493
+ shutdown() {
494
+ for (; t.length;) {
495
+ var e;
496
+ (e = t.pop()) == null || e();
497
+ }
498
+ }
499
+ };
500
+ }, Qe = "body", $e = 3e3, et = .8, tt = [
265
501
  "[data-loading=\"true\"]",
266
502
  "[aria-busy=\"true\"]",
267
503
  ".loading",
@@ -275,117 +511,170 @@ var de = (e, t) => typeof e.enabled == "function" ? e.enabled(t) : e.enabled !==
275
511
  [.75, .25],
276
512
  [.25, .75],
277
513
  [.75, .75]
278
- ], De = (e) => {
514
+ ], nt = (e) => {
279
515
  if (!e) return "";
280
516
  let t = e.tagName.toLowerCase();
281
517
  return e.id ? `${t}#${e.id}` : t;
282
- }, Oe = (e, t) => e ? t.some((t) => {
518
+ }, rt = (e, t) => e ? t.some((t) => {
283
519
  try {
284
520
  return e.matches(t) || !!e.closest(t);
285
521
  } catch (e) {
286
522
  return !1;
287
523
  }
288
- }) : !1, ke = (e) => {
289
- if (typeof document > "u") return;
290
- if (document.readyState === "complete" || document.readyState === "interactive") {
291
- e();
292
- return;
293
- }
524
+ }) : !1, it = (e) => {
525
+ if (typeof document > "u") return () => {};
526
+ if (document.readyState === "complete" || document.readyState === "interactive") return e(), () => {};
294
527
  let t = () => {
295
528
  document.removeEventListener("DOMContentLoaded", t), e();
296
529
  };
297
- document.addEventListener("DOMContentLoaded", t);
298
- }, Ae = (e) => {
299
- let t;
530
+ return document.addEventListener("DOMContentLoaded", t), () => document.removeEventListener("DOMContentLoaded", t);
531
+ }, at = (e) => {
532
+ let t, n, r = !1;
300
533
  return {
301
534
  name: "blank-screen",
302
- enabled: !!e,
303
- init(n) {
304
- var r, i, a, s;
535
+ enabled: e.enabled,
536
+ init(i) {
537
+ var a, s;
305
538
  if (typeof window > "u" || typeof document > "u") return;
306
- let c = typeof e == "object" ? e : {}, l = (r = c.rootSelector) == null ? Ce : r, u = (i = c.checkDelay) == null ? we : i, d = (a = c.threshold) == null ? Te : a, f = [...Ee, ...(s = c.ignoreSelectors) == null ? [] : s], p = n.meter.createCounter("browser.blank_screen.count", { description: "Number of suspected blank screen detections" });
307
- ke(() => {
308
- t = window.setTimeout(() => {
539
+ let c = e.enabled ? (a = e.rootSelector) == null ? Qe : a : Qe, l = e.enabled ? e.checkDelay : $e, u = e.enabled ? e.threshold : et, d = [...tt, ...e.enabled ? (s = e.ignoreSelectors) == null ? [] : s : []], f = i.meter.createCounter("browser.blank_screen.count", { description: "Number of suspected blank screen detections" }), p = () => {
540
+ try {
309
541
  var e, t;
310
- let r = document.querySelector(l), i = 0, a = 0;
542
+ let n = document.querySelector(c), r = 0, a = 0;
311
543
  for (let [e, t] of L) {
312
- let n = document.elementFromPoint(window.innerWidth * e, window.innerHeight * t);
313
- if (Oe(n, f)) {
544
+ let i = document.elementFromPoint(window.innerWidth * e, window.innerHeight * t);
545
+ if (rt(i, d)) {
314
546
  a += 1;
315
547
  continue;
316
548
  }
317
- (n === r || n === document.body || n === document.documentElement) && (i += 1);
549
+ (i === n || i === document.body || i === document.documentElement) && (r += 1);
318
550
  }
319
- let s = i / L.length;
320
- if (a === L.length) return;
321
- let c = s >= d, u = {
322
- "bk.rum.blank_screen.score": s,
323
- "bk.rum.blank_screen.threshold": d,
324
- "bk.rum.blank_screen.root": l,
325
- "bk.rum.blank_screen.detected": c,
326
- "bk.rum.blank_screen.center_element": De(document.elementFromPoint(window.innerWidth / 2, window.innerHeight / 2)),
327
- "bk.rum.blank_screen.dom_node_count": (e = (t = document.body) == null ? void 0 : t.getElementsByTagName("*").length) == null ? 0 : e
328
- };
329
- c && (p.add(1, n.applyRedact({ "bk.rum.blank_screen.root": l })), n.emitLog({
551
+ let s = L.length - a;
552
+ if (s === 0) return;
553
+ let l = r / s, p = l >= u, m = nt(document.elementFromPoint(window.innerWidth / 2, window.innerHeight / 2)), h = T(T({}, I({
554
+ errorType: p ? "blank_screen" : "none",
555
+ eventLabel: "白屏",
556
+ result: p ? P.error : P.success,
557
+ spanSubtype: "blank_screen",
558
+ spanType: F.error,
559
+ targetLabel: c,
560
+ targetValue: l
561
+ })), {}, {
562
+ "blank_screen.score": l,
563
+ "blank_screen.threshold": u,
564
+ "blank_screen.root": c,
565
+ "blank_screen.detected": p,
566
+ "blank_screen.sample_total": L.length,
567
+ "blank_screen.sample_valid": s,
568
+ "blank_screen.sample_loading": a,
569
+ "blank_screen.center_element": m,
570
+ "blank_screen.dom_node_count": (e = (t = document.body) == null ? void 0 : t.getElementsByTagName("*").length) == null ? 0 : e
571
+ });
572
+ p && (f.add(1, i.applyRedact({ "blank_screen.root": c })), i.emitLog({
330
573
  severityNumber: o.ERROR,
331
574
  severityText: "ERROR",
332
575
  body: "browser.blank_screen",
333
- attributes: u
576
+ attributes: h
334
577
  }));
335
- }, u);
578
+ } catch (e) {
579
+ if (i.config.debug) {
580
+ var n;
581
+ (n = globalThis.console) == null || n.warn("[bk-ot][blank-screen] detection failed:", e);
582
+ }
583
+ }
584
+ };
585
+ n = it(() => {
586
+ r || (t = window.setTimeout(p, l));
336
587
  });
337
588
  },
338
589
  shutdown() {
339
- t !== void 0 && typeof window < "u" && window.clearTimeout(t);
590
+ r = !0, n == null || n(), n = void 0, t !== void 0 && typeof window < "u" && (window.clearTimeout(t), t = void 0);
340
591
  }
341
592
  };
342
- }, je = ["http.url", "url.full"], Me = (e) => ({ test: e }), Ne = (e, t) => {
343
- t.setAttributes(e.applyRedact(e.config.getPageAttributes()));
344
- for (let r of je) {
345
- var n;
346
- let i = (n = t.attributes) == null ? void 0 : n[r];
347
- if (typeof i == "string") {
348
- let n = e.applyRedact({ [r]: e.config.redactUrl(i) })[r];
349
- typeof n == "string" && t.setAttribute(r, n);
593
+ }, ot = ["http.url", "url.full"], st = ["http.status_code", "http.response.status_code"], ct = ["http.method", "http.request.method"], lt = (e) => ({ test: e }), ut = (e, t, n) => {
594
+ var r;
595
+ t.setAttributes(e.applyRedact(e.config.hooks.getPageAttributes()));
596
+ let i;
597
+ for (let n of ot) {
598
+ var a;
599
+ let r = (a = t.attributes) == null ? void 0 : a[n];
600
+ if (typeof r == "string") {
601
+ let a = e.applyRedact({ [n]: e.config.hooks.redactUrl(r) })[n];
602
+ typeof a == "string" && (i = a, t.setAttribute(n, a));
350
603
  }
351
604
  }
352
- }, Pe = (e) => {
605
+ let o = st.map((e) => {
606
+ var n;
607
+ return (n = t.attributes) == null ? void 0 : n[e];
608
+ }).find((e) => typeof e == "number"), s = ct.map((e) => {
609
+ var n;
610
+ return (n = t.attributes) == null ? void 0 : n[e];
611
+ }).find((e) => typeof e == "string"), c = (r = i) == null ? ot.map((e) => {
612
+ var n;
613
+ return (n = t.attributes) == null ? void 0 : n[e];
614
+ }).find((e) => typeof e == "string") : r;
615
+ t.setAttributes(e.applyRedact(qe({
616
+ method: s,
617
+ statusCode: o,
618
+ subtype: n,
619
+ url: c,
620
+ urlPathTemplate: c ? e.config.hooks.getViewPathGroup(c) : void 0
621
+ })));
622
+ }, dt = (e, t, n) => {
623
+ t.setAttributes(e.applyRedact(T(T({}, e.config.hooks.getPageAttributes()), I({
624
+ errorType: "none",
625
+ eventLabel: "文档加载",
626
+ spanSubtype: n,
627
+ spanType: F.document,
628
+ targetLabel: e.config.hooks.getViewPathGroup(typeof location > "u" ? "" : location.href),
629
+ traceScene: "page_load"
630
+ }))));
631
+ }, ft = (e, t, n) => {
632
+ let r = e.config.hooks.redactUrl(n.name);
633
+ t.setAttributes(e.applyRedact(T(T(T({}, e.config.hooks.getPageAttributes()), Je({
634
+ duration: n.duration,
635
+ initiatorType: n.initiatorType || "other",
636
+ responseStatus: n.responseStatus,
637
+ transferSize: n.transferSize,
638
+ url: r,
639
+ urlPathTemplate: e.config.hooks.getViewPathGroup(n.name)
640
+ })), {}, { "url.full": r })));
641
+ }, pt = (e) => {
353
642
  let t = [];
354
643
  return {
355
644
  name: "official-instrumentations",
356
645
  enabled: !!(e.documentLoad || e.fetch || e.xhr || e.userInteraction),
357
646
  init(n) {
358
- return P(function* () {
359
- let r = [], i = [Me((e) => I(n.config, e))], a = [Me((e) => ye(n.config, e))];
360
- if (e.documentLoad) {
361
- let { DocumentLoadInstrumentation: e } = yield import("@opentelemetry/instrumentation-document-load");
362
- r.push(new e({ semconvStabilityOptIn: "http" }));
363
- }
364
- if (e.fetch) {
365
- let { FetchInstrumentation: e } = yield import("@opentelemetry/instrumentation-fetch");
366
- r.push(new e({
367
- applyCustomAttributesOnSpan: (e) => Ne(n, e),
368
- ignoreUrls: i,
369
- propagateTraceHeaderCorsUrls: a,
370
- semconvStabilityOptIn: "http",
371
- ignoreNetworkEvents: !1
372
- }));
373
- }
374
- if (e.xhr) {
375
- let { XMLHttpRequestInstrumentation: e } = yield import("@opentelemetry/instrumentation-xml-http-request");
376
- r.push(new e({
377
- applyCustomAttributesOnSpan: (e) => Ne(n, e),
378
- ignoreUrls: i,
379
- propagateTraceHeaderCorsUrls: a,
380
- semconvStabilityOptIn: "http",
381
- ignoreNetworkEvents: !1
382
- }));
383
- }
384
- if (e.userInteraction) {
385
- let { UserInteractionInstrumentation: t } = yield import("@opentelemetry/instrumentation-user-interaction"), n = typeof e.userInteraction == "object" ? { eventNames: e.userInteraction.eventNames } : void 0;
386
- r.push(new t(n));
647
+ return M(function* () {
648
+ let r = [lt((e) => N(n.config, e))], i = [lt((e) => Ie(n.config, e))], [a, o, s, c] = yield Promise.all([
649
+ e.documentLoad ? import("@opentelemetry/instrumentation-document-load") : Promise.resolve(null),
650
+ e.fetch ? import("@opentelemetry/instrumentation-fetch") : Promise.resolve(null),
651
+ e.xhr ? import("@opentelemetry/instrumentation-xml-http-request") : Promise.resolve(null),
652
+ e.userInteraction ? import("@opentelemetry/instrumentation-user-interaction") : Promise.resolve(null)
653
+ ]);
654
+ if (a && t.push(new a.DocumentLoadInstrumentation({
655
+ semconvStabilityOptIn: "http",
656
+ applyCustomAttributesOnSpan: {
657
+ documentLoad: (e) => dt(n, e, "navigate"),
658
+ documentFetch: (e) => dt(n, e, "document_fetch"),
659
+ resourceFetch: (e, t) => ft(n, e, t)
660
+ }
661
+ })), o && t.push(new o.FetchInstrumentation({
662
+ applyCustomAttributesOnSpan: (e) => ut(n, e, "fetch"),
663
+ ignoreUrls: r,
664
+ propagateTraceHeaderCorsUrls: i,
665
+ semconvStabilityOptIn: "http",
666
+ ignoreNetworkEvents: !1
667
+ })), s && t.push(new s.XMLHttpRequestInstrumentation({
668
+ applyCustomAttributesOnSpan: (e) => ut(n, e, "xhr"),
669
+ ignoreUrls: r,
670
+ propagateTraceHeaderCorsUrls: i,
671
+ semconvStabilityOptIn: "http",
672
+ ignoreNetworkEvents: !1
673
+ })), c) {
674
+ let n = e.userInteraction !== null && typeof e.userInteraction == "object" ? { eventNames: e.userInteraction.eventNames } : void 0;
675
+ t.push(new c.UserInteractionInstrumentation(n));
387
676
  }
388
- t.push(...r), p({ instrumentations: r });
677
+ p({ instrumentations: t });
389
678
  })();
390
679
  },
391
680
  shutdown() {
@@ -395,66 +684,182 @@ var de = (e, t) => typeof e.enabled == "function" ? e.enabled(t) : e.enabled !==
395
684
  }
396
685
  }
397
686
  };
398
- }, Fe = (e) => {
687
+ }, R = (e) => {
688
+ let t = 5381;
689
+ for (let n = 0; n < e.length; n++) t = t * 33 ^ e.charCodeAt(n);
690
+ return (t >>> 0).toString(36);
691
+ }, z = (e, t) => {
692
+ let n = /* @__PURE__ */ new Map(), r = 0, i = (t) => {
693
+ if (!(t - r < e)) {
694
+ r = t;
695
+ for (let [r, i] of n) t - i.windowStart > e && n.delete(r);
696
+ }
697
+ };
698
+ return { allow(r) {
699
+ let a = Date.now();
700
+ i(a);
701
+ let o = n.get(r);
702
+ return !o || a - o.windowStart > e ? (n.set(r, {
703
+ count: 1,
704
+ windowStart: a
705
+ }), {
706
+ allowed: !0,
707
+ count: 1
708
+ }) : (o.count += 1, {
709
+ allowed: o.count <= t,
710
+ count: o.count
711
+ });
712
+ } };
713
+ }, mt = 6e4, ht = 5, gt = /^https?:|^\/\//i, _t = (e, t) => {
714
+ if (t) return gt.test(t) ? e(t) : t;
715
+ }, vt = (e) => {
399
716
  let t;
400
717
  return {
401
718
  name: "csp-violation",
402
- enabled: !!e,
719
+ enabled: e.enabled,
403
720
  init(e) {
404
721
  if (typeof window > "u" || typeof document > "u") return;
405
- let n = (t) => {
722
+ let n = z(mt, ht), r = (t) => {
723
+ let r = R(`${t.violatedDirective}|${t.blockedURI}|${t.sourceFile}|${t.lineNumber}`), i = n.allow(r);
724
+ if (!i.allowed) return;
725
+ let a = _t(e.config.hooks.redactUrl, t.blockedURI), s = t.sourceFile ? e.config.hooks.redactUrl(t.sourceFile) : void 0, c = i.count === 1;
406
726
  e.emitLog({
407
727
  severityNumber: o.WARN,
408
728
  severityText: "WARN",
409
729
  body: "csp.violation",
410
- attributes: O(O({}, e.config.getPageAttributes()), {}, {
411
- "csp.blocked_uri": e.config.redactUrl(t.blockedURI || ""),
730
+ attributes: T(T(T({}, e.config.hooks.getPageAttributes()), I({
731
+ errorType: "csp",
732
+ eventLabel: "CSP 错误",
733
+ result: P.error,
734
+ spanSubtype: "csp",
735
+ spanType: F.error,
736
+ targetLabel: a == null ? t.effectiveDirective : a,
737
+ targetValue: t.statusCode
738
+ })), {}, {
739
+ "csp.blocked_uri": a,
412
740
  "csp.violated_directive": t.violatedDirective,
413
741
  "csp.effective_directive": t.effectiveDirective,
414
- "csp.original_policy": t.originalPolicy,
415
742
  "csp.disposition": t.disposition,
416
- "csp.source_file": e.config.redactUrl(t.sourceFile || ""),
743
+ "csp.source_file": s,
417
744
  "csp.line_number": t.lineNumber,
418
745
  "csp.column_number": t.columnNumber,
419
- "csp.status_code": t.statusCode
420
- })
746
+ "csp.status_code": t.statusCode,
747
+ "csp.fingerprint": r,
748
+ "csp.window_count": i.count,
749
+ [b.exceptionFingerprint]: r,
750
+ "error.source": "csp"
751
+ }, c ? { "csp.original_policy": t.originalPolicy } : {})
421
752
  });
422
753
  };
423
- document.addEventListener("securitypolicyviolation", n), t = () => document.removeEventListener("securitypolicyviolation", n);
754
+ document.addEventListener("securitypolicyviolation", r), t = () => document.removeEventListener("securitypolicyviolation", r);
424
755
  },
425
756
  shutdown() {
426
757
  t == null || t(), t = void 0;
427
758
  }
428
759
  };
429
- }, Ie = "bk_ot_session_id", R = () => typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `device-${Date.now()}-${Math.random().toString(16).slice(2)}`, Le = (e) => {
430
- try {
431
- let t = window.localStorage.getItem(e);
432
- if (t) return t;
433
- let n = R();
434
- return window.localStorage.setItem(e, n), n;
435
- } catch (e) {
436
- return R();
760
+ }, B = (e) => typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `${e}-${Date.now()}-${Math.random().toString(16).slice(2)}`, yt = "BK_RUM_DEVICE_ID", bt = 250, xt = () => navigator.connection, St = () => navigator.userAgentData, Ct = (e) => {
761
+ for (let [t, n] of [
762
+ ["Edge", /Edg\/([\d.]+)/],
763
+ ["Chrome", /Chrome\/([\d.]+)/],
764
+ ["Firefox", /Firefox\/([\d.]+)/],
765
+ ["Safari", /Version\/([\d.]+).*Safari/]
766
+ ]) {
767
+ let r = e.match(n);
768
+ if (r != null && r[1]) return {
769
+ name: t,
770
+ version: r[1].split(".")[0]
771
+ };
437
772
  }
438
- }, Re = () => {
439
- var e, t, n;
440
- if (typeof window > "u") return {};
441
- let r = navigator.connection;
442
773
  return {
774
+ name: "Other",
775
+ version: void 0
776
+ };
777
+ }, wt = (e, t) => {
778
+ let n = `${t == null ? "" : t} ${e}`;
779
+ return /iphone|ipad|ipod/i.test(n) ? "iOS" : /android/i.test(n) ? "Android" : /mac/i.test(n) ? "macOS" : /win/i.test(n) ? "Windows" : /linux/i.test(n) ? "Linux" : "Other";
780
+ }, Tt = (e) => {
781
+ let t = null;
782
+ try {
783
+ t = window.localStorage.getItem(e);
784
+ } catch (e) {}
785
+ if (t) return t;
786
+ let n = B("device");
787
+ try {
788
+ window.localStorage.setItem(e, n);
789
+ } catch (e) {}
790
+ return n;
791
+ }, Et = () => {
792
+ var e, t;
793
+ return typeof window > "u" ? {} : {
443
794
  "browser.viewport.width": window.innerWidth,
444
795
  "browser.viewport.height": window.innerHeight,
445
796
  "browser.screen.width": (e = window.screen) == null ? void 0 : e.width,
446
- "browser.screen.height": (t = window.screen) == null ? void 0 : t.height,
447
- "network.effective_type": (n = r == null ? void 0 : r.effectiveType) == null ? r == null ? void 0 : r.type : n
797
+ "browser.screen.height": (t = window.screen) == null ? void 0 : t.height
448
798
  };
449
- }, ze = (e) => ({
450
- name: "device",
451
- enabled: !!e,
452
- init(t) {
453
- var n;
454
- let r = typeof e == "object" ? (n = e.storageKey) == null ? Ie : n : Ie, i = typeof window > "u" ? R() : Le(r);
455
- t.setRuntimeAttributes(O({ "device.id": i }, Re()));
456
- }
457
- }), Be = 6e4, Ve = 5, He = (e) => {
799
+ }, Dt = () => {
800
+ let e = xt();
801
+ return e ? {
802
+ "network.effective_type": e.effectiveType,
803
+ "network.connection_type": e.type,
804
+ "network.downlink": e.downlink,
805
+ "network.rtt": e.rtt,
806
+ "network.save_data": e.saveData
807
+ } : {};
808
+ }, Ot = () => {
809
+ if (typeof navigator > "u") return {};
810
+ let e = St(), t = navigator.userAgent, n = Ct(t), r = wt(t, e == null ? void 0 : e.platform), i = e != null && e.mobile || /mobi|android|iphone|ipad|ipod/i.test(t) ? "mobile" : "desktop";
811
+ return {
812
+ "device.memory": navigator.deviceMemory,
813
+ "device.cpu_cores": navigator.hardwareConcurrency,
814
+ "device.platform": e == null ? void 0 : e.platform,
815
+ "device.mobile": e == null ? void 0 : e.mobile,
816
+ [b.browserName]: n.name,
817
+ [b.browserVersion]: n.version,
818
+ [b.deviceType]: i,
819
+ [b.osName]: r,
820
+ "user_agent.name": n.name,
821
+ "user_agent.version": n.version,
822
+ "user_agent.os.name": r
823
+ };
824
+ }, kt = (e, t) => {
825
+ let n;
826
+ return () => {
827
+ n !== void 0 && window.clearTimeout(n), n = window.setTimeout(() => {
828
+ n = void 0, e();
829
+ }, t);
830
+ };
831
+ }, At = (e) => {
832
+ let t = [];
833
+ return {
834
+ name: "device",
835
+ enabled: e.enabled,
836
+ init(n) {
837
+ var r;
838
+ let i = e.enabled ? (r = e.storageKey) == null ? yt : r : yt, a = typeof window > "u" ? B("device") : Tt(i);
839
+ if (n.setRuntimeAttributes(T(T(T({ "device.id": a }, Ot()), Et()), Dt())), typeof window > "u") return;
840
+ let o = kt(() => {
841
+ n.setRuntimeAttributes(Et());
842
+ }, bt);
843
+ window.addEventListener("resize", o), window.addEventListener("orientationchange", o), t.push(() => window.removeEventListener("resize", o), () => window.removeEventListener("orientationchange", o));
844
+ let s = xt();
845
+ if (s && typeof s.addEventListener == "function") {
846
+ let e = () => {
847
+ n.setRuntimeAttributes(Dt());
848
+ };
849
+ s.addEventListener("change", e), t.push(() => {
850
+ var t;
851
+ (t = s.removeEventListener) == null || t.call(s, "change", e);
852
+ });
853
+ }
854
+ },
855
+ shutdown() {
856
+ for (; t.length;) {
857
+ var e;
858
+ (e = t.pop()) == null || e();
859
+ }
860
+ }
861
+ };
862
+ }, jt = 6e4, Mt = 5, Nt = (e) => {
458
863
  if (e instanceof Error) return e.message;
459
864
  if (typeof e == "string") return e;
460
865
  try {
@@ -462,102 +867,103 @@ var de = (e, t) => typeof e.enabled == "function" ? e.enabled(t) : e.enabled !==
462
867
  } catch (t) {
463
868
  return String(e);
464
869
  }
465
- }, Ue = (e) => {
870
+ }, Pt = (e) => {
466
871
  var t;
467
872
  return e instanceof Error ? (t = e.stack) == null ? "" : t : "";
468
- }, We = (e) => {
469
- let t = 5381;
470
- for (let n = 0; n < e.length; n++) t = t * 33 ^ e.charCodeAt(n);
471
- return (t >>> 0).toString(36);
472
- }, Ge = (e, t) => {
473
- let n = /* @__PURE__ */ new Map();
474
- return { allow(r) {
475
- let i = Date.now(), a = n.get(r);
476
- return !a || i - a.windowStart > e ? (n.set(r, {
477
- count: 1,
478
- windowStart: i
479
- }), !0) : a.count >= t ? !1 : (a.count += 1, !0);
480
- } };
481
- }, z = ({ context: e, error: r, exceptionType: i, extra: s = {}, source: c, spanName: l, throttle: u }) => {
482
- let d = He(r), f = Ue(r), p = We(`${c}|${d}|${f.slice(0, 256)}`);
483
- if (!u.allow(p)) return;
484
- let m = a.getActiveSpan(), h = r instanceof Error ? r : {
873
+ }, Ft = (e) => e.slice(0, 80), It = (e) => {
874
+ var t, n;
875
+ return (t = (n = e.split("\n").find((e) => e.trim().startsWith("at "))) == null ? void 0 : n.trim()) == null ? "" : t;
876
+ }, Lt = (e) => e === "unhandledrejection" ? "promise" : e === "resource" ? "resource_load" : "js", V = ({ context: e, error: r, exceptionType: i, extra: s = {}, source: c, spanName: l, throttle: u }) => {
877
+ let d = Nt(r), f = Pt(r), p = R(`${c}|${d}|${f.slice(0, 256)}`), m = u.allow(p);
878
+ if (!m.allowed) return;
879
+ let h = a.getActiveSpan(), g = r instanceof Error ? r : {
485
880
  message: d,
486
881
  name: i == null ? c : i
487
- }, g = O(O(O({}, e.config.getPageAttributes()), e.config.getErrorAttributes()), {}, {
882
+ }, _ = T(T(T(T({}, e.config.hooks.getPageAttributes()), e.config.hooks.getErrorAttributes()), I({
883
+ errorType: Lt(c),
884
+ eventLabel: "错误",
885
+ result: P.error,
886
+ spanSubtype: Lt(c),
887
+ spanType: F.error,
888
+ targetLabel: r instanceof Error ? r.name : i == null ? c : i
889
+ })), {}, {
488
890
  "exception.message": d,
891
+ [b.exceptionMessageShort]: Ft(d),
489
892
  "exception.stacktrace": f,
893
+ [b.exceptionStackTopFrame]: It(f),
490
894
  "exception.type": r instanceof Error ? r.name : i == null ? c : i,
491
- "bk.rum.error.source": c,
492
- "bk.rum.error.fingerprint": p
493
- }, s), _ = () => e.emitLog({
895
+ [b.exceptionFingerprint]: p,
896
+ "error.handled": !1,
897
+ "error.source": c,
898
+ "error.window_count": m.count
899
+ }, s), v = () => e.emitLog({
494
900
  severityNumber: o.ERROR,
495
901
  severityText: "ERROR",
496
902
  body: d,
497
- attributes: g
903
+ attributes: _
498
904
  });
499
- if (m) {
500
- m.recordException(h), m.setStatus({
905
+ if (h) {
906
+ h.setAttributes(e.applyRedact(_)), h.recordException(g), h.setStatus({
501
907
  code: t.ERROR,
502
908
  message: d
503
- }), _();
909
+ }), v();
504
910
  return;
505
911
  }
506
- let v = e.startSpan(l, g);
507
- v.recordException(h), v.setStatus({
912
+ let y = e.startSpan(l, _);
913
+ y.recordException(g), y.setStatus({
508
914
  code: t.ERROR,
509
915
  message: d
510
- }), n.with(a.setSpan(n.active(), v), _), v.end();
511
- }, Ke = (e) => {
916
+ }), n.with(a.setSpan(n.active(), y), v), y.end();
917
+ }, Rt = (e) => {
512
918
  let t = [];
513
919
  return {
514
920
  name: "error",
515
- enabled: !!e,
921
+ enabled: e.enabled,
516
922
  init(n) {
517
- var r, i;
518
923
  if (typeof window > "u") return;
519
- let a = Ge(typeof e == "object" ? (r = e.windowMs) == null ? Be : r : Be, typeof e == "object" ? (i = e.maxPerWindow) == null ? Ve : i : Ve), o = (e) => {
924
+ let r = z(e.enabled ? e.windowMs : jt, e.enabled ? e.maxPerWindow : Mt), i = (e) => {
520
925
  var t;
521
- z({
926
+ let i = !e.error && !e.filename && e.message === "Script error.";
927
+ V({
522
928
  context: n,
523
- throttle: a,
929
+ throttle: r,
524
930
  spanName: "browser.error",
525
931
  source: "window.error",
526
932
  error: (t = e.error) == null ? e.message : t,
527
- extra: {
933
+ extra: T({
528
934
  "code.filepath": e.filename,
529
935
  "code.lineno": e.lineno,
530
936
  "code.column": e.colno
531
- }
937
+ }, i ? { "error.cross_origin": !0 } : {})
532
938
  });
533
- }, s = (e) => {
534
- z({
939
+ }, a = (e) => {
940
+ V({
535
941
  context: n,
536
- throttle: a,
942
+ throttle: r,
537
943
  spanName: "browser.unhandledrejection",
538
944
  source: "unhandledrejection",
539
945
  error: e.reason,
540
946
  exceptionType: e.reason instanceof Error ? e.reason.name : "UnhandledRejection"
541
947
  });
542
- }, c = (e) => {
543
- var t;
544
- let r = e.target;
545
- if (r === window) return;
546
- let i = r.src || r.href || "";
547
- z({
948
+ }, o = (e) => {
949
+ if (e instanceof ErrorEvent) return;
950
+ let t = e.target;
951
+ if (!(t instanceof Element)) return;
952
+ let i = t, a = i.src || i.href || t.currentSrc || "";
953
+ V({
548
954
  context: n,
549
- throttle: a,
955
+ throttle: r,
550
956
  spanName: "browser.resource_error",
551
957
  source: "resource",
552
- error: /* @__PURE__ */ Error(`Resource load failed: ${((t = r.tagName) == null ? void 0 : t.toLowerCase()) || "unknown"} ${i}`),
958
+ error: /* @__PURE__ */ Error(`Resource load failed: ${t.tagName.toLowerCase()} ${a}`),
553
959
  exceptionType: "ResourceError",
554
960
  extra: {
555
- "url.full": n.config.redactUrl(i),
556
- "html.tag": r.tagName || ""
961
+ "url.full": n.config.hooks.redactUrl(a),
962
+ "html.tag": t.tagName
557
963
  }
558
964
  });
559
965
  };
560
- window.addEventListener("error", o), window.addEventListener("unhandledrejection", s), window.addEventListener("error", c, !0), t.push(() => window.removeEventListener("error", o), () => window.removeEventListener("unhandledrejection", s), () => window.removeEventListener("error", c, !0));
966
+ window.addEventListener("error", i), window.addEventListener("unhandledrejection", a), window.addEventListener("error", o, !0), t.push(() => window.removeEventListener("error", i), () => window.removeEventListener("unhandledrejection", a), () => window.removeEventListener("error", o, !0));
561
967
  },
562
968
  shutdown() {
563
969
  for (; t.length;) {
@@ -566,13 +972,13 @@ var de = (e, t) => typeof e.enabled == "function" ? e.enabled(t) : e.enabled !==
566
972
  }
567
973
  }
568
974
  };
569
- }, qe = 10 * 1024, B = (e, t) => e.length <= t ? {
975
+ }, zt = 10 * 1024, Bt = 10, H = /* @__PURE__ */ new WeakMap(), U = (e, t) => e.length <= t ? {
570
976
  body: e,
571
977
  truncated: !1
572
978
  } : {
573
979
  body: e.slice(0, t),
574
980
  truncated: !0
575
- }, Je = (e, t) => {
981
+ }, Vt = (e, t) => {
576
982
  if (!e) return;
577
983
  if (e instanceof Headers) return e.get(t) || void 0;
578
984
  let n = t.toLowerCase();
@@ -582,30 +988,30 @@ var de = (e, t) => typeof e.enabled == "function" ? e.enabled(t) : e.enabled !==
582
988
  }
583
989
  let i = Object.keys(e).find((e) => e.toLowerCase() === n);
584
990
  return i ? e[i] : void 0;
585
- }, Ye = (e) => {
991
+ }, Ht = (e) => {
586
992
  let t = {};
587
993
  return e.forEach((e, n) => {
588
994
  t[n] = e instanceof File ? `[File name=${e.name} type=${e.type || "unknown"} size=${e.size}]` : e;
589
995
  }), JSON.stringify(t);
590
- }, Xe = function() {
591
- var e = P(function* (e) {
592
- return e == null ? "" : typeof e == "string" ? e : e instanceof URLSearchParams ? e.toString() : e instanceof FormData ? Ye(e) : e instanceof Blob ? e.text() : e instanceof ArrayBuffer || ArrayBuffer.isView(e) ? new TextDecoder().decode(e) : e instanceof Document ? new XMLSerializer().serializeToString(e) : String(e);
996
+ }, Ut = function() {
997
+ var e = M(function* (e) {
998
+ return e == null ? "" : typeof e == "string" ? e : e instanceof URLSearchParams ? e.toString() : e instanceof FormData ? Ht(e) : e instanceof Blob ? e.text() : e instanceof ArrayBuffer || ArrayBuffer.isView(e) ? new TextDecoder().decode(e) : e instanceof Document ? new XMLSerializer().serializeToString(e) : String(e);
593
999
  });
594
1000
  return function(t) {
595
1001
  return e.apply(this, arguments);
596
1002
  };
597
- }(), Ze = function() {
598
- var e = P(function* (e, t, n) {
599
- let r = yield Xe(e);
600
- if (r) return O(O({}, B(r, t)), {}, { contentType: n });
1003
+ }(), Wt = function() {
1004
+ var e = M(function* (e, t, n) {
1005
+ let r = yield Ut(e);
1006
+ if (r) return T(T({}, U(r, t)), {}, { contentType: n });
601
1007
  });
602
1008
  return function(t, n, r) {
603
1009
  return e.apply(this, arguments);
604
1010
  };
605
- }(), V = function() {
606
- var e = P(function* (e, t, n) {
1011
+ }(), W = function() {
1012
+ var e = M(function* (e, t, n) {
607
1013
  try {
608
- return yield Ze(e, t, n);
1014
+ return yield Wt(e, t, n);
609
1015
  } catch (e) {
610
1016
  return;
611
1017
  }
@@ -613,23 +1019,20 @@ var de = (e, t) => typeof e.enabled == "function" ? e.enabled(t) : e.enabled !==
613
1019
  return function(t, n, r) {
614
1020
  return e.apply(this, arguments);
615
1021
  };
616
- }(), Qe = (e) => e instanceof Request ? e.url : String(e), $e = (e, t) => t != null && t.method ? t.method : e instanceof Request ? e.method : "GET", et = function() {
617
- var e = P(function* (e, t, n) {
618
- if (t != null && t.body) return V(t.body, n, Je(t.headers, "content-type"));
619
- if (e instanceof Request) try {
620
- return V(yield e.clone().text(), n, e.headers.get("content-type") || void 0);
621
- } catch (e) {
622
- return;
623
- }
624
- });
625
- return function(t, n, r) {
626
- return e.apply(this, arguments);
627
- };
628
- }(), tt = function() {
629
- var e = P(function* (e, t) {
1022
+ }(), Gt = (e) => e instanceof Request ? e.url : String(e), Kt = (e, t) => t != null && t.method ? t.method : e instanceof Request ? e.method : "GET", qt = (e, t, n) => t != null && t.body ? () => W(t.body, n, Vt(t.headers, "content-type")) : (e instanceof Request, () => Promise.resolve(void 0)), Jt = function() {
1023
+ var e = M(function* (e, t) {
630
1024
  try {
631
- let n = e.clone();
632
- return V(n.body ? yield n.text() : "", t, e.headers.get("content-type") || void 0);
1025
+ let n = e.headers.get("content-type") || void 0, r = e.headers.get("content-length");
1026
+ if (r) {
1027
+ let e = Number(r);
1028
+ if (Number.isFinite(e) && e > t * Bt) return {
1029
+ body: "",
1030
+ contentType: n,
1031
+ truncated: !0
1032
+ };
1033
+ }
1034
+ let i = e.clone();
1035
+ return W(i.body ? yield i.text() : "", t, n);
633
1036
  } catch (e) {
634
1037
  return;
635
1038
  }
@@ -637,119 +1040,151 @@ var de = (e, t) => typeof e.enabled == "function" ? e.enabled(t) : e.enabled !==
637
1040
  return function(t, n) {
638
1041
  return e.apply(this, arguments);
639
1042
  };
640
- }(), nt = (e, t) => {
641
- if (e.responseType === "" || e.responseType === "text") return O(O({}, B(e.responseText || "", t)), {}, { contentType: e.getResponseHeader("content-type") || void 0 });
642
- if (e.responseType === "json") return O(O({}, B(JSON.stringify(e.response), t)), {}, { contentType: e.getResponseHeader("content-type") || void 0 });
643
- }, rt = (e, t, n) => {
644
- if (n) return e.redact(O(O({}, t), {}, {
1043
+ }(), Yt = (e, t) => {
1044
+ if (e.responseType === "" || e.responseType === "text") return T(T({}, U(e.responseText || "", t)), {}, { contentType: e.getResponseHeader("content-type") || void 0 });
1045
+ if (e.responseType === "json") return T(T({}, U(JSON.stringify(e.response), t)), {}, { contentType: e.getResponseHeader("content-type") || void 0 });
1046
+ }, Xt = (e, t, n) => {
1047
+ if (n) return e.redact(T(T({}, t), {}, {
645
1048
  body: n.body,
646
1049
  truncated: n.truncated
647
1050
  }));
648
- }, H = ({ context: e, duration: t, error: n, method: r, request: i, response: a, status: s, url: c }) => {
649
- let l = e.config.rum.httpBody;
650
- if (!l) return;
651
- let u = !!n || typeof s == "number" && s >= 400, d = r.toUpperCase(), f = u ? rt(l, {
1051
+ }, G = ({ context: e, duration: t, error: n, method: r, request: i, response: a, status: s, subtype: c, url: l }) => {
1052
+ let u = e.config.rum.plugins.httpBody;
1053
+ if (!u.enabled) return;
1054
+ let d = !!n || typeof s == "number" && s >= 400, f = r.toUpperCase(), p = d ? Xt(u, {
652
1055
  contentType: i == null ? void 0 : i.contentType,
653
- method: d,
1056
+ method: f,
654
1057
  status: s,
655
1058
  type: "request",
656
- url: c
657
- }, i) : void 0, p = u ? rt(l, {
1059
+ url: l
1060
+ }, i) : void 0, m = d ? Xt(u, {
658
1061
  contentType: a == null ? void 0 : a.contentType,
659
- method: d,
1062
+ method: f,
660
1063
  status: s,
661
1064
  type: "response",
662
- url: c
663
- }, a) : void 0, m = O(O({}, e.config.getPageAttributes()), {}, {
1065
+ url: l
1066
+ }, a) : void 0, h = T(T(T({}, e.config.hooks.getPageAttributes()), qe({
1067
+ duration: t,
1068
+ method: f,
1069
+ statusCode: s,
1070
+ subtype: c,
1071
+ url: e.config.hooks.redactUrl(l),
1072
+ urlPathTemplate: e.config.hooks.getViewPathGroup(l)
1073
+ })), {}, {
664
1074
  "http.duration": t,
665
- "http.request.method": d,
666
- "url.full": e.config.redactUrl(c)
1075
+ "http.request.method": f,
1076
+ "url.full": e.config.hooks.redactUrl(l)
667
1077
  });
668
- if (typeof s == "number" && (m["http.response.status_code"] = s), f != null && (m["http.request.body"] = f), p != null && (m["http.response.body"] = p), u) {
669
- var h, g;
670
- m["bk.rum.http_body.request.truncated"] = (h = i == null ? void 0 : i.truncated) == null ? !1 : h, m["bk.rum.http_body.response.truncated"] = (g = a == null ? void 0 : a.truncated) == null ? !1 : g;
1078
+ if (typeof s == "number" && (h["http.response.status_code"] = s), p != null && (h["http.request.body"] = p), m != null && (h["http.response.body"] = m), d) {
1079
+ var g, _;
1080
+ h["http_body.request.truncated"] = (g = i == null ? void 0 : i.truncated) == null ? !1 : g, h["http_body.response.truncated"] = (_ = a == null ? void 0 : a.truncated) == null ? !1 : _;
671
1081
  }
672
1082
  if (n instanceof Error) {
673
- var _;
674
- m["exception.message"] = n.message, m["exception.type"] = n.name, m["exception.stacktrace"] = (_ = n.stack) == null ? "" : _;
1083
+ var v;
1084
+ h["exception.message"] = n.message, h["exception.type"] = n.name, h["exception.stacktrace"] = (v = n.stack) == null ? "" : v;
675
1085
  }
676
1086
  e.emitLog({
677
- severityNumber: u ? o.ERROR : o.INFO,
678
- severityText: u ? "ERROR" : "INFO",
679
- body: u ? "HTTP request completed with error" : "HTTP request completed",
680
- attributes: m
1087
+ severityNumber: d ? o.ERROR : o.INFO,
1088
+ severityText: d ? "ERROR" : "INFO",
1089
+ body: d ? "HTTP request completed with error" : "HTTP request completed",
1090
+ attributes: h
681
1091
  });
682
- }, it = (e) => {
1092
+ }, Zt = (e) => {
683
1093
  let t = [];
684
1094
  return {
685
1095
  name: "http-body",
686
- enabled: !!e,
1096
+ enabled: e.enabled,
687
1097
  init(n) {
688
1098
  if (!e || typeof window > "u") return;
689
- let r = e.maxBodySize || qe, i = window.fetch;
690
- typeof i == "function" && (window.fetch = function() {
691
- var e = P(function* (e, t) {
692
- let a = Qe(e);
693
- if (I(n.config, a)) return i(e, t);
694
- let o = $e(e, t), s = yield et(e, t, r), c = performance.now();
695
- try {
696
- let l = yield i(e, t);
697
- return H({
698
- context: n,
699
- duration: performance.now() - c,
700
- method: o,
701
- request: s,
702
- response: l.status >= 400 ? yield tt(l, r) : void 0,
703
- status: l.status,
704
- url: a
705
- }), l;
706
- } catch (e) {
707
- throw H({
708
- context: n,
709
- duration: performance.now() - c,
710
- error: e,
711
- method: o,
712
- request: s,
713
- url: a
714
- }), e;
715
- }
1099
+ let r = e.enabled ? e.maxBodySize : zt, i = window.fetch;
1100
+ if (typeof i == "function") {
1101
+ let e = function() {
1102
+ var e = M(function* (e, t) {
1103
+ let a = Gt(e);
1104
+ if (N(n.config, a)) return i(e, t);
1105
+ let o = Kt(e, t), s = qt(e, t, r), c = performance.now();
1106
+ try {
1107
+ let l = yield i(e, t), u = performance.now() - c, d = l.status >= 400;
1108
+ return G({
1109
+ context: n,
1110
+ duration: u,
1111
+ method: o,
1112
+ request: d ? yield s() : void 0,
1113
+ response: d ? yield Jt(l, r) : void 0,
1114
+ status: l.status,
1115
+ subtype: "fetch",
1116
+ url: a
1117
+ }), l;
1118
+ } catch (e) {
1119
+ let t = yield s();
1120
+ throw G({
1121
+ context: n,
1122
+ duration: performance.now() - c,
1123
+ error: e,
1124
+ method: o,
1125
+ request: t,
1126
+ subtype: "fetch",
1127
+ url: a
1128
+ }), e;
1129
+ }
1130
+ });
1131
+ return function(t, n) {
1132
+ return e.apply(this, arguments);
1133
+ };
1134
+ }();
1135
+ window.fetch = e, t.push(() => {
1136
+ window.fetch === e && (window.fetch = i);
716
1137
  });
717
- return function(t, n) {
718
- return e.apply(this, arguments);
719
- };
720
- }(), t.push(() => {
721
- window.fetch = i;
722
- }));
723
- let a = XMLHttpRequest.prototype.open, o = XMLHttpRequest.prototype.send, s = XMLHttpRequest.prototype.setRequestHeader;
724
- XMLHttpRequest.prototype.open = function(e, t, ...n) {
1138
+ }
1139
+ let a = XMLHttpRequest.prototype.open, o = XMLHttpRequest.prototype.send, s = XMLHttpRequest.prototype.setRequestHeader, c = function(e, t, ...n) {
725
1140
  var r;
726
- return this.__bkOtHttpBodyMeta__ = {
1141
+ return H.set(this, {
727
1142
  method: e,
728
1143
  startTime: performance.now(),
729
1144
  url: String(t)
730
- }, a.call(this, e, t, (r = n[0]) == null ? !0 : r, n[1], n[2]);
731
- }, XMLHttpRequest.prototype.setRequestHeader = function(e, t) {
732
- var n;
733
- return this.__bkOtHttpBodyRequestHeaders__ = O(O({}, (n = this.__bkOtHttpBodyRequestHeaders__) == null ? {} : n), {}, { [e]: t }), s.call(this, e, t);
734
- }, XMLHttpRequest.prototype.send = function(e) {
735
- return V(e, r, Je(this.__bkOtHttpBodyRequestHeaders__, "content-type")).then((e) => {
736
- this.__bkOtHttpBodyRequest__ = e;
737
- }), this.addEventListener("loadend", () => {
738
- let e = this.__bkOtHttpBodyMeta__;
739
- if (!e || I(n.config, e.url)) return;
740
- let t = this.status >= 400 ? nt(this, r) : void 0;
741
- H({
742
- context: n,
743
- duration: performance.now() - e.startTime,
744
- method: e.method,
745
- request: this.__bkOtHttpBodyRequest__,
746
- response: t,
747
- status: this.status,
748
- url: e.url
749
- });
750
- }), o.call(this, e);
751
- }, t.push(() => {
752
- XMLHttpRequest.prototype.open = a, XMLHttpRequest.prototype.send = o, XMLHttpRequest.prototype.setRequestHeader = s;
1145
+ }), a.call(this, e, t, (r = n[0]) == null ? !0 : r, n[1], n[2]);
1146
+ }, l = function(e, t) {
1147
+ let n = H.get(this);
1148
+ if (n) {
1149
+ var r;
1150
+ let i = e.toLowerCase(), a = (r = n.requestHeaders) == null ? {} : r, o = a[i];
1151
+ a[i] = o ? `${o}, ${t}` : t, n.requestHeaders = a;
1152
+ }
1153
+ return s.call(this, e, t);
1154
+ }, u = function(e) {
1155
+ var t = this;
1156
+ let i = H.get(this);
1157
+ if (i) {
1158
+ var a;
1159
+ i.requestBody = e, i.requestContentType = (a = i.requestHeaders) == null ? void 0 : a["content-type"];
1160
+ }
1161
+ return this.addEventListener("abort", () => {
1162
+ let e = H.get(this);
1163
+ e && (e.aborted = !0);
1164
+ }, { once: !0 }), this.addEventListener("error", () => {
1165
+ let e = H.get(this);
1166
+ e && (e.networkError = !0);
1167
+ }, { once: !0 }), this.addEventListener("loadend", () => {
1168
+ M(function* () {
1169
+ let e = H.get(t);
1170
+ if (!e || N(n.config, e.url) || e.aborted) return;
1171
+ let i = e.networkError || t.status >= 400, a = i ? Yt(t, r) : void 0, o = i ? yield W(e.requestBody, r, e.requestContentType) : void 0;
1172
+ G({
1173
+ context: n,
1174
+ duration: performance.now() - e.startTime,
1175
+ error: e.networkError ? /* @__PURE__ */ Error("XHR network error") : void 0,
1176
+ method: e.method,
1177
+ request: o,
1178
+ response: a,
1179
+ status: t.status,
1180
+ subtype: "xhr",
1181
+ url: e.url
1182
+ });
1183
+ })();
1184
+ }, { once: !0 }), o.call(this, e);
1185
+ };
1186
+ XMLHttpRequest.prototype.open = c, XMLHttpRequest.prototype.setRequestHeader = l, XMLHttpRequest.prototype.send = u, t.push(() => {
1187
+ XMLHttpRequest.prototype.open === c && (XMLHttpRequest.prototype.open = a), XMLHttpRequest.prototype.setRequestHeader === l && (XMLHttpRequest.prototype.setRequestHeader = s), XMLHttpRequest.prototype.send === u && (XMLHttpRequest.prototype.send = o);
753
1188
  });
754
1189
  },
755
1190
  shutdown() {
@@ -759,30 +1194,38 @@ var de = (e, t) => typeof e.enabled == "function" ? e.enabled(t) : e.enabled !==
759
1194
  }
760
1195
  }
761
1196
  };
762
- }, at = 50, ot = (e) => {
1197
+ }, Qt = 50, $t = (e) => {
763
1198
  let t;
764
1199
  return {
765
1200
  name: "long-task",
766
- enabled: !!e,
1201
+ enabled: e.enabled,
767
1202
  init(n) {
768
1203
  var r;
769
- if (typeof PerformanceObserver > "u") return;
770
- let i = PerformanceObserver.supportedEntryTypes;
771
- if (!(i != null && i.includes("longtask"))) return;
772
- let a = typeof e == "object" ? (r = e.threshold) == null ? at : r : at, o = n.meter.createCounter("browser.long_task.count", { description: "Number of long tasks observed (duration >= threshold)" }), s = n.meter.createHistogram("browser.long_task.duration", {
1204
+ if (typeof PerformanceObserver > "u" || !((r = PerformanceObserver.supportedEntryTypes) != null && r.includes("longtask"))) return;
1205
+ let i = e.enabled ? e.threshold : Qt, a = n.meter.createCounter("browser.long_task.count", { description: "Number of long tasks observed (duration >= threshold)" }), o = n.meter.createHistogram("browser.long_task.duration", {
773
1206
  unit: "ms",
774
1207
  description: "Duration of long tasks"
775
1208
  });
776
1209
  try {
777
1210
  t = new PerformanceObserver((e) => {
778
- for (let i of e.getEntries()) {
779
- var t, r;
780
- if (i.duration < a) continue;
781
- let e = (t = i.attribution) == null ? void 0 : t[0], c = n.applyRedact(O(O(O({}, n.config.getPageAttributes()), n.config.getMetricAttributes()), {}, {
782
- "long_task.name": i.name,
783
- "long_task.attribution": (r = e == null ? void 0 : e.name) == null ? "unknown" : r
784
- }));
785
- o.add(1, c), s.record(i.duration, c);
1211
+ let t = n.applyRedact(T(T({}, n.config.hooks.getPageAttributes()), n.config.hooks.getMetricAttributes()));
1212
+ for (let h of e.getEntries()) {
1213
+ var r, s, c, l, u, d, f, p, m;
1214
+ if (h.duration < i) continue;
1215
+ let e = (r = h.attribution) == null ? void 0 : r[0], g = T(T({}, t), {}, { [b.longtaskAttributionScript]: (s = (c = e == null ? void 0 : e.containerSrc) == null ? e == null ? void 0 : e.name : c) == null ? "unknown" : s }), _ = h.duration > 100 ? P.warning : P.success;
1216
+ n.startSpan("browser.long_task", T(T(T({}, t), I({
1217
+ duration: h.duration,
1218
+ errorType: _ === P.warning ? "longtask_blocking" : "none",
1219
+ eventLabel: "长任务",
1220
+ result: _,
1221
+ spanSubtype: (l = e == null ? void 0 : e.name) == null ? "unknown" : l,
1222
+ spanType: F.longtask,
1223
+ targetLabel: (u = (d = (f = e == null ? void 0 : e.containerSrc) == null ? e == null ? void 0 : e.containerName : f) == null ? e == null ? void 0 : e.name : d) == null ? "unknown" : u,
1224
+ targetValue: h.duration
1225
+ })), {}, {
1226
+ [b.longtaskBlockingDuration]: h.duration,
1227
+ [b.longtaskAttributionScript]: (p = (m = e == null ? void 0 : e.containerSrc) == null ? e == null ? void 0 : e.name : m) == null ? "unknown" : p
1228
+ }), { startTime: performance.timeOrigin + h.startTime }).end(performance.timeOrigin + h.startTime + h.duration), a.add(1, g), o.record(h.duration, g);
786
1229
  }
787
1230
  }), t.observe({
788
1231
  type: "longtask",
@@ -796,58 +1239,81 @@ var de = (e, t) => typeof e.enabled == "function" ? e.enabled(t) : e.enabled !==
796
1239
  t == null || t.disconnect(), t = void 0;
797
1240
  }
798
1241
  };
799
- }, U = /* @__PURE__ */ new Set(), W = "", G, K, q = !1, J = () => typeof location > "u" ? "" : location.href, Y = (e, t) => {
800
- let n = J();
801
- W = n;
1242
+ }, K = /* @__PURE__ */ new Set(), q = "", J, Y, X = !1, Z = () => typeof location > "u" ? "" : location.href, Q = (e, t) => {
1243
+ let n = Z();
1244
+ q = n;
802
1245
  let r = {
803
1246
  fromUrl: t,
804
1247
  source: e,
805
1248
  toUrl: n
806
1249
  };
807
- for (let e of Array.from(U)) e(r);
808
- }, st = () => {
809
- Y("popstate", W || J());
810
- }, ct = () => {
811
- Y("hashchange", W || J());
812
- }, lt = () => {
813
- q || typeof window > "u" || typeof history > "u" || (q = !0, W = J(), G = history.pushState, K = history.replaceState, history.pushState = function(e, t, n) {
814
- let r = W || J(), i = G == null ? void 0 : G.apply(this, [
1250
+ for (let e of Array.from(K)) e(r);
1251
+ }, en = () => {
1252
+ Q("popstate", q || Z());
1253
+ }, tn = () => {
1254
+ Q("hashchange", q || Z());
1255
+ }, nn = () => {
1256
+ X || typeof window > "u" || typeof history > "u" || (X = !0, q = Z(), J = history.pushState, Y = history.replaceState, history.pushState = function(e, t, n) {
1257
+ let r = q || Z(), i = J == null ? void 0 : J.apply(this, [
815
1258
  e,
816
1259
  t,
817
1260
  n
818
1261
  ]);
819
- return Y("pushState", r), i;
1262
+ return Q("pushState", r), i;
820
1263
  }, history.replaceState = function(e, t, n) {
821
- let r = W || J(), i = K == null ? void 0 : K.apply(this, [
1264
+ let r = q || Z(), i = Y == null ? void 0 : Y.apply(this, [
822
1265
  e,
823
1266
  t,
824
1267
  n
825
1268
  ]);
826
- return Y("replaceState", r), i;
827
- }, window.addEventListener("popstate", st), window.addEventListener("hashchange", ct));
828
- }, ut = () => {
829
- !q || typeof window > "u" || typeof history > "u" || (G && (history.pushState = G), K && (history.replaceState = K), window.removeEventListener("popstate", st), window.removeEventListener("hashchange", ct), G = void 0, K = void 0, q = !1, W = "");
830
- }, dt = (e) => typeof window > "u" || typeof history > "u" ? () => {} : (lt(), U.add(e), () => {
831
- U.delete(e), U.size === 0 && ut();
832
- }), ft = () => typeof location > "u" ? "" : location.href, pt = (e) => {
1269
+ return Q("replaceState", r), i;
1270
+ }, window.addEventListener("popstate", en), window.addEventListener("hashchange", tn));
1271
+ }, rn = () => {
1272
+ !X || typeof window > "u" || typeof history > "u" || (J && (history.pushState = J), Y && (history.replaceState = Y), window.removeEventListener("popstate", en), window.removeEventListener("hashchange", tn), J = void 0, Y = void 0, X = !1, q = "");
1273
+ }, an = (e) => typeof window > "u" || typeof history > "u" ? () => {} : (nn(), K.add(e), () => {
1274
+ K.delete(e), K.size === 0 && rn();
1275
+ }), on = () => typeof location > "u" ? "" : location.href, sn = (e) => {
833
1276
  let t = [];
834
1277
  return {
835
1278
  name: "page-view",
836
- enabled: !!e,
1279
+ enabled: e.enabled,
837
1280
  init(e) {
838
1281
  if (typeof window > "u") return;
839
- let n = "", r = (t, r = n) => {
840
- let i = ft();
841
- i !== n && (n = i, e.startSpan("browser.page_view", O(O({}, e.config.getPageAttributes()), {}, {
842
- "url.full": e.config.redactUrl(i),
843
- "url.previous": e.config.redactUrl(r),
844
- "document.referrer": e.config.redactUrl(document.referrer || ""),
845
- "bk.rum.event.source": t
846
- })).end());
847
- }, i = dt((e) => {
848
- r(e.source, e.fromUrl);
1282
+ let n = "", r, i = (t, i = n) => {
1283
+ let a = on();
1284
+ if (a === n) return;
1285
+ r == null || r.setAttribute("view.end_reason", t), r == null || r.end(), n = a;
1286
+ let o = B("view"), s = e.config.hooks.getViewPathGroup(a), c = t === "load" ? "initial_load" : "route_change", l = e.config.hooks.redactUrl(a), u = e.config.hooks.redactUrl(i);
1287
+ e.setView({
1288
+ id: o,
1289
+ loadingType: c,
1290
+ url: l,
1291
+ urlPathGroup: s
1292
+ });
1293
+ let d = t === "load", f = T(T(T({}, e.config.hooks.getPageAttributes()), I({
1294
+ errorType: "none",
1295
+ eventLabel: d ? "文档加载" : "路由切换",
1296
+ spanSubtype: d ? "navigate" : t,
1297
+ spanType: d ? F.document : F.route,
1298
+ targetLabel: s,
1299
+ traceScene: d ? "page_load" : "route_change"
1300
+ })), {}, {
1301
+ [b.viewId]: o,
1302
+ [b.viewUrl]: l,
1303
+ [b.viewUrlPathGroup]: s,
1304
+ [b.viewLoadingType]: c,
1305
+ "url.previous": u,
1306
+ "event.source": t
1307
+ }, d ? { "document.referrer": e.config.hooks.redactUrl(document.referrer || "") } : {});
1308
+ r = e.startSpan("browser.view", f), e.startSpan("browser.page_view", T({}, f)).end();
1309
+ }, a = an((e) => {
1310
+ i(e.source, e.fromUrl);
849
1311
  });
850
- r("load"), t.push(i);
1312
+ i("load");
1313
+ let o = () => {
1314
+ r == null || r.setAttribute("view.end_reason", "shutdown"), r == null || r.end(), r = void 0;
1315
+ };
1316
+ window.addEventListener("pagehide", o), t.push(a, () => window.removeEventListener("pagehide", o), o);
851
1317
  },
852
1318
  shutdown() {
853
1319
  for (; t.length;) {
@@ -856,256 +1322,525 @@ var de = (e, t) => typeof e.enabled == "function" ? e.enabled(t) : e.enabled !==
856
1322
  }
857
1323
  }
858
1324
  };
859
- }, mt = (e) => {
860
- let t = [];
1325
+ }, cn = (e) => e.transferSize === 0 && e.decodedBodySize > 0 ? !0 : void 0, ln = (e) => {
1326
+ let t, n = /* @__PURE__ */ new Set();
1327
+ return {
1328
+ name: "resource",
1329
+ enabled: e.enabled,
1330
+ init(e) {
1331
+ var r;
1332
+ if (typeof PerformanceObserver > "u" || !((r = PerformanceObserver.supportedEntryTypes) != null && r.includes("resource"))) return;
1333
+ let i = (t) => {
1334
+ if (!t.name || N(e.config, t.name)) return;
1335
+ let r = `${t.name}|${t.startTime}`;
1336
+ if (n.has(r)) return;
1337
+ n.add(r);
1338
+ let i = e.config.hooks.redactUrl(t.name), a = t.duration;
1339
+ e.startSpan("browser.resource", T(T(T({}, e.config.hooks.getPageAttributes()), Je({
1340
+ duration: a,
1341
+ initiatorType: t.initiatorType || "other",
1342
+ responseStatus: t.responseStatus,
1343
+ transferSize: t.transferSize,
1344
+ url: i,
1345
+ urlPathTemplate: e.config.hooks.getViewPathGroup(t.name)
1346
+ })), {}, {
1347
+ "url.full": i,
1348
+ [b.transferSize]: t.transferSize,
1349
+ [b.cacheHit]: cn(t),
1350
+ [b.nextHopProtocol]: t.nextHopProtocol,
1351
+ initiator_type: t.initiatorType || "other",
1352
+ "resource.encoded_body_size": t.encodedBodySize,
1353
+ "resource.decoded_body_size": t.decodedBodySize
1354
+ }), { startTime: performance.timeOrigin + t.startTime }).end(performance.timeOrigin + t.startTime + a);
1355
+ };
1356
+ try {
1357
+ t = new PerformanceObserver((e) => {
1358
+ for (let t of e.getEntries()) i(t);
1359
+ }), t.observe({
1360
+ type: "resource",
1361
+ buffered: !0
1362
+ });
1363
+ } catch (e) {
1364
+ t = void 0;
1365
+ }
1366
+ },
1367
+ shutdown() {
1368
+ t == null || t.disconnect(), t = void 0, n.clear();
1369
+ }
1370
+ };
1371
+ }, un = (e) => {
1372
+ let t = [], n = !1;
861
1373
  return {
862
1374
  name: "route-timing",
863
- enabled: !!e,
1375
+ enabled: e.enabled,
864
1376
  init(e) {
865
1377
  if (typeof window > "u" || typeof history > "u") return;
866
- let n = e.meter.createHistogram("browser.route_change.duration", {
1378
+ let r = e.meter.createHistogram("browser.route_change.duration", {
867
1379
  unit: "ms",
868
1380
  description: "Estimated SPA route change duration (route start to next idle)"
869
- }), r = (t, r, i) => {
870
- let a = performance.now(), o = () => {
871
- let o = performance.now() - a, s = e.applyRedact(O(O(O({}, e.config.getPageAttributes()), e.config.getMetricAttributes()), {}, { "route.change.source": t }));
872
- n.record(o, s), e.startSpan("browser.route_change", O(O({}, s), {}, {
873
- "url.full": e.config.redactUrl(i),
874
- "url.previous": e.config.redactUrl(r),
875
- "route.change.duration_ms": o
876
- })).end();
1381
+ }), i = (t, i, a) => {
1382
+ if (n) return;
1383
+ let o = performance.now(), s = performance.timeOrigin + o, c = () => {
1384
+ if (n || typeof document < "u" && document.visibilityState === "hidden") return;
1385
+ let c = performance.now() - o, l = c > 500 ? P.warning : P.success, u = e.applyRedact(T(T(T({}, e.config.hooks.getPageAttributes()), e.config.hooks.getMetricAttributes()), {}, { "route.change.source": t }));
1386
+ r.record(c, u), e.startSpan("browser.route_change", T(T(T({}, u), I({
1387
+ duration: c,
1388
+ errorType: l === P.warning ? "slow" : "none",
1389
+ eventLabel: "路由切换",
1390
+ result: l,
1391
+ spanSubtype: t,
1392
+ spanType: F.route,
1393
+ targetLabel: e.config.hooks.getViewPathGroup(a),
1394
+ targetValue: c,
1395
+ traceScene: "route_change"
1396
+ })), {}, {
1397
+ "url.full": e.config.hooks.redactUrl(a),
1398
+ "url.previous": e.config.hooks.redactUrl(i)
1399
+ }), { startTime: s }).end();
877
1400
  };
878
- requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(o, 0)));
879
- }, i = dt((e) => {
880
- e.fromUrl !== e.toUrl && r(e.source, e.fromUrl, e.toUrl);
1401
+ requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(c, 0)));
1402
+ }, a = an((e) => {
1403
+ e.fromUrl !== e.toUrl && i(e.source, e.fromUrl, e.toUrl);
881
1404
  });
882
- t.push(i);
1405
+ t.push(a);
883
1406
  },
884
1407
  shutdown() {
885
- for (; t.length;) {
1408
+ for (n = !0; t.length;) {
886
1409
  var e;
887
1410
  (e = t.pop()) == null || e();
888
1411
  }
889
1412
  }
890
1413
  };
891
- }, ht = "bk_ot_session", gt = 1800 * 1e3, _t = () => typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `session-${Date.now()}-${Math.random().toString(16).slice(2)}`, vt = (e) => {
1414
+ }, dn = 1800 * 1e3, fn = 1440 * 60 * 1e3, pn = 6e4, mn = 5e3, hn = [
1415
+ "click",
1416
+ "keydown",
1417
+ "scroll",
1418
+ "mousemove",
1419
+ "touchstart"
1420
+ ], gn = (e, t) => typeof e == "number" && Number.isFinite(e) && e > 0 && e <= t + mn, _n = (e, t) => {
1421
+ if (!e) return null;
892
1422
  try {
893
- var t;
894
- let n = (t = window.sessionStorage.getItem(e)) == null ? window.localStorage.getItem(e) : t;
895
- if (!n) return null;
896
- let r = JSON.parse(n);
897
- return typeof (r == null ? void 0 : r.id) == "string" && typeof (r == null ? void 0 : r.ts) == "number" ? r : null;
898
- } catch (e) {
899
- return null;
900
- }
901
- }, yt = (e, t) => {
1423
+ let n = JSON.parse(e);
1424
+ if (typeof (n == null ? void 0 : n.id) == "string" && gn(n.ts, t) && gn(n.startedAt, t)) return n;
1425
+ } catch (e) {}
1426
+ return null;
1427
+ }, vn = (e, t) => {
1428
+ if (typeof window > "u") return null;
1429
+ let n = null;
902
1430
  try {
903
- let n = JSON.stringify(t);
904
- window.sessionStorage.setItem(e, n), window.localStorage.setItem(e, n);
1431
+ n = window.localStorage.getItem(e);
905
1432
  } catch (e) {}
906
- }, bt = (e, t) => {
907
- let n = Date.now(), r = vt(e);
908
- if (r && n - r.ts < t) {
909
- let t = {
910
- id: r.id,
911
- ts: n
1433
+ let r = _n(n, t);
1434
+ if (r) return r;
1435
+ try {
1436
+ n = window.sessionStorage.getItem(e);
1437
+ } catch (e) {}
1438
+ return r = _n(n, t), r;
1439
+ }, yn = (e, t) => {
1440
+ if (typeof window > "u") return;
1441
+ let n = JSON.stringify(t);
1442
+ try {
1443
+ window.sessionStorage.setItem(e, n);
1444
+ } catch (e) {}
1445
+ try {
1446
+ window.localStorage.setItem(e, n);
1447
+ } catch (e) {}
1448
+ }, bn = (e, t, n) => {
1449
+ let r = Date.now(), i = vn(e, r);
1450
+ if (i) {
1451
+ let a = r - i.ts >= t, o = r - i.startedAt >= n;
1452
+ if (!a && !o) {
1453
+ let t = T(T({}, i), {}, { ts: r });
1454
+ return yn(e, t), {
1455
+ id: t.id,
1456
+ rotated: !1
1457
+ };
1458
+ }
1459
+ let s = a ? "inactivity" : "maxLifetime", c = {
1460
+ id: B("session"),
1461
+ startedAt: r,
1462
+ ts: r
1463
+ };
1464
+ return yn(e, c), {
1465
+ id: c.id,
1466
+ prevId: i.id,
1467
+ reason: s,
1468
+ rotated: !0
912
1469
  };
913
- return yt(e, t), t.id;
914
1470
  }
915
- let i = {
916
- id: _t(),
917
- ts: n
1471
+ let a = {
1472
+ id: B("session"),
1473
+ startedAt: r,
1474
+ ts: r
918
1475
  };
919
- return yt(e, i), i.id;
920
- }, xt = (e) => {
921
- let t;
1476
+ return yn(e, a), {
1477
+ id: a.id,
1478
+ reason: "init",
1479
+ rotated: !0
1480
+ };
1481
+ }, xn = (e) => {
1482
+ let t = "";
1483
+ try {
1484
+ t = new URL(e).host;
1485
+ } catch (n) {
1486
+ t = e;
1487
+ }
1488
+ return `bk_ot_session__${R(t || "default")}`;
1489
+ }, Sn = (e, t) => {
1490
+ if (!t.rotated || !t.reason) return;
1491
+ let n = Date.now();
1492
+ e.emitLog({
1493
+ severityNumber: o.INFO,
1494
+ severityText: "INFO",
1495
+ body: t.reason === "init" ? "session.start" : "session.rotate",
1496
+ attributes: T(T({}, e.config.hooks.getPageAttributes()), {}, {
1497
+ [b.sessionHasReplay]: !1,
1498
+ [b.sessionId]: t.id,
1499
+ [b.sessionStartTime]: n,
1500
+ "session.rotate.reason": t.reason
1501
+ }, t.prevId ? { "session.previous_id": t.prevId } : {})
1502
+ });
1503
+ }, Cn = (e) => {
1504
+ let t = [];
922
1505
  return {
923
1506
  name: "session",
924
- enabled: !!e,
1507
+ enabled: e.enabled,
925
1508
  init(n) {
926
- var r, i;
927
- let a = typeof e == "object" ? (r = e.storageKey) == null ? ht : r : ht, o = typeof e == "object" ? (i = e.inactivityMs) == null ? gt : i : gt, s = () => {
928
- let e = typeof window > "u" ? _t() : bt(a, o);
929
- n.setRuntimeAttributes({ "session.id": e });
1509
+ var r;
1510
+ let i = e.enabled ? (r = e.storageKey) == null ? xn(n.config.transport.endpoint) : r : xn(n.config.transport.endpoint), a = e.enabled ? e.inactivityMs : dn, o = e.enabled ? e.maxLifetimeMs : fn, s = "", c = () => {
1511
+ if (typeof window > "u") {
1512
+ s || (s = B("session"), n.setRuntimeAttributes({
1513
+ [b.sessionHasReplay]: !1,
1514
+ [b.sessionId]: s
1515
+ }));
1516
+ return;
1517
+ }
1518
+ let e = bn(i, a, o);
1519
+ n.setRuntimeAttributes({
1520
+ [b.sessionHasReplay]: !1,
1521
+ [b.sessionId]: e.id
1522
+ }), e.id !== s && (s = e.id, Sn(n, e));
1523
+ };
1524
+ if (c(), typeof window > "u" || typeof document > "u") return;
1525
+ let l = Date.now(), u = () => {
1526
+ let e = Date.now();
1527
+ e - l < pn || (l = e, c());
1528
+ }, d = {
1529
+ capture: !0,
1530
+ passive: !0
1531
+ };
1532
+ hn.forEach((e) => {
1533
+ window.addEventListener(e, u, d);
1534
+ }), t.push(() => {
1535
+ hn.forEach((e) => {
1536
+ window.removeEventListener(e, u, d);
1537
+ });
1538
+ });
1539
+ let f = () => {
1540
+ document.visibilityState === "visible" && c();
930
1541
  };
931
- if (s(), typeof window > "u" || typeof document > "u") return;
932
- let c = () => {
933
- document.visibilityState === "visible" && s();
1542
+ document.addEventListener("visibilitychange", f), t.push(() => document.removeEventListener("visibilitychange", f));
1543
+ let p = (e) => {
1544
+ if (e.storageArea !== window.localStorage || e.key !== i || !e.newValue) return;
1545
+ let t = Date.now(), r = _n(e.newValue, t);
1546
+ if (!(!r || r.id === s)) {
1547
+ s = r.id;
1548
+ try {
1549
+ window.sessionStorage.setItem(i, e.newValue);
1550
+ } catch (e) {}
1551
+ n.setRuntimeAttributes({ [b.sessionId]: r.id });
1552
+ }
934
1553
  };
935
- document.addEventListener("visibilitychange", c), t = () => document.removeEventListener("visibilitychange", c);
1554
+ window.addEventListener("storage", p), t.push(() => window.removeEventListener("storage", p));
936
1555
  },
937
1556
  shutdown() {
938
- t == null || t(), t = void 0;
1557
+ for (; t.length;) {
1558
+ var e;
1559
+ (e = t.pop()) == null || e();
1560
+ }
939
1561
  }
940
1562
  };
941
- }, St = () => {
1563
+ }, wn = "unknown", Tn = (e) => e ? e.replace(/_/g, "-") : wn, En = () => {
1564
+ if (typeof performance > "u") return wn;
942
1565
  let e = performance.getEntriesByType("navigation")[0];
943
- return (e == null ? void 0 : e.type) || "unknown";
944
- }, X = (e) => ({
945
- "rum.navigation.type": St(),
946
- "web_vital.name": e.name,
947
- "web_vital.rating": e.rating
948
- }), Ct = (e, t) => {
1566
+ return Tn(e == null ? void 0 : e.type);
1567
+ }, Dn = (e, t) => {
1568
+ var n;
1569
+ return {
1570
+ "rum.navigation.type": (n = e.navigationType) == null ? t : n,
1571
+ [b.vitalMetric]: e.name.toLowerCase(),
1572
+ [b.vitalRating]: e.rating
1573
+ };
1574
+ }, On = (e, t) => {
949
1575
  var n;
950
1576
  let r = (n = e.attribution) == null ? {} : n, i = {}, a = (e) => r[e], o = (e, t, n) => {
951
1577
  t != null && (typeof t == "string" || typeof t == "number" || typeof t == "boolean") && (i[e] = typeof t == "string" && n ? n(t) : t);
952
1578
  };
953
1579
  switch (e.name) {
954
1580
  case "LCP":
955
- o("web_vital.lcp.url", a("url"), t), o("web_vital.lcp.target", a("target")), o("web_vital.lcp.element_render_delay", a("elementRenderDelay")), o("web_vital.lcp.resource_load_duration", a("resourceLoadDuration")), o("web_vital.lcp.time_to_first_byte", a("timeToFirstByte"));
1581
+ o("vital.lcp.url", a("url"), t), o("vital.lcp.target", a("target")), o("vital.lcp.element_render_delay", a("elementRenderDelay")), o("vital.lcp.resource_load_duration", a("resourceLoadDuration")), o("vital.lcp.time_to_first_byte", a("timeToFirstByte"));
956
1582
  break;
957
1583
  case "CLS":
958
- o("web_vital.cls.largest_shift_target", a("largestShiftTarget")), o("web_vital.cls.largest_shift_value", a("largestShiftValue")), o("web_vital.cls.load_state", a("loadState"));
1584
+ o("vital.cls.largest_shift_target", a("largestShiftTarget")), o("vital.cls.largest_shift_value", a("largestShiftValue")), o("vital.cls.load_state", a("loadState"));
959
1585
  break;
960
1586
  case "INP":
961
- o("web_vital.inp.interaction_target", a("interactionTarget")), o("web_vital.inp.interaction_type", a("interactionType")), o("web_vital.inp.input_delay", a("inputDelay")), o("web_vital.inp.processing_duration", a("processingDuration")), o("web_vital.inp.presentation_delay", a("presentationDelay"));
1587
+ o("vital.inp.interaction_target", a("interactionTarget")), o("vital.inp.interaction_type", a("interactionType")), o("vital.inp.input_delay", a("inputDelay")), o("vital.inp.processing_duration", a("processingDuration")), o("vital.inp.presentation_delay", a("presentationDelay"));
962
1588
  break;
963
1589
  case "FCP":
964
- o("web_vital.fcp.time_to_first_byte", a("timeToFirstByte")), o("web_vital.fcp.load_state", a("loadState"));
1590
+ o("vital.fcp.time_to_first_byte", a("timeToFirstByte")), o("vital.fcp.load_state", a("loadState"));
965
1591
  break;
966
1592
  case "TTFB":
967
- o("web_vital.ttfb.waiting_duration", a("waitingDuration")), o("web_vital.ttfb.dns_duration", a("dnsDuration")), o("web_vital.ttfb.connection_duration", a("connectionDuration")), o("web_vital.ttfb.request_duration", a("requestDuration"));
1593
+ o("vital.ttfb.waiting_duration", a("waitingDuration")), o("vital.ttfb.dns_duration", a("dnsDuration")), o("vital.ttfb.connection_duration", a("connectionDuration")), o("vital.ttfb.request_duration", a("requestDuration"));
968
1594
  break;
969
1595
  default: break;
970
1596
  }
971
1597
  return i;
972
- }, wt = (e) => ({
973
- name: "web-vitals",
974
- enabled: !!e,
975
- init(e) {
976
- return P(function* () {
977
- if (typeof window > "u") return;
978
- let { onCLS: t, onFCP: n, onINP: r, onLCP: i, onTTFB: a } = yield import("web-vitals/attribution"), o = e.meter.createHistogram("browser.web_vital.cls", {
979
- unit: "1",
980
- description: "Cumulative Layout Shift"
981
- }), s = e.meter.createHistogram("browser.web_vital.duration", {
982
- unit: "ms",
983
- description: "Web Vitals duration metrics, including FCP, INP, LCP and TTFB"
984
- }), c = (t) => {
985
- e.startSpan("browser.web_vital", O(O(O(O({}, e.config.getPageAttributes()), e.config.getMetricAttributes()), X(t)), {}, {
986
- "web_vital.id": t.id,
987
- "web_vital.value": t.value
988
- }, Ct(t, e.config.redactUrl))).end();
989
- }, l = (t) => {
990
- s.record(t.value, e.applyRedact(O(O(O({}, e.config.getPageAttributes()), e.config.getMetricAttributes()), X(t)))), c(t);
991
- };
992
- t((t) => {
993
- o.record(t.value, e.applyRedact(O(O(O({}, e.config.getPageAttributes()), e.config.getMetricAttributes()), X(t)))), c(t);
994
- }), n(l), r(l), i(l), a(l);
995
- })();
996
- }
997
- }), Tt = (e) => e == null ? 0 : typeof e == "string" ? typeof TextEncoder > "u" ? e.length : new TextEncoder().encode(e).byteLength : e instanceof ArrayBuffer || ArrayBuffer.isView(e) ? e.byteLength : typeof Blob < "u" && e instanceof Blob ? e.size : 0, Et = (e, t) => {
998
- let n = {
999
- "url.full": t(e),
1000
- "network.protocol.name": "websocket"
1598
+ }, kn = (e) => {
1599
+ let t = !1;
1600
+ return {
1601
+ name: "web-vitals",
1602
+ enabled: e.enabled,
1603
+ init(e) {
1604
+ return M(function* () {
1605
+ if (typeof window > "u") return;
1606
+ let n;
1607
+ try {
1608
+ n = yield import("web-vitals/attribution");
1609
+ } catch (t) {
1610
+ if (e.config.debug) {
1611
+ var r;
1612
+ (r = globalThis.console) == null || r.warn("[bk-ot] web-vitals load failed:", t);
1613
+ }
1614
+ return;
1615
+ }
1616
+ if (t) return;
1617
+ let { onCLS: i, onFCP: a, onINP: o, onLCP: s, onTTFB: c } = n, l = En(), u = e.meter.createHistogram("browser.web_vital.cls", {
1618
+ unit: "1",
1619
+ description: "Cumulative Layout Shift"
1620
+ }), d = e.meter.createHistogram("browser.web_vital.duration", {
1621
+ unit: "ms",
1622
+ description: "Web Vitals duration metrics, including FCP, INP, LCP and TTFB"
1623
+ }), f = (t) => {
1624
+ let n = t.name.toLowerCase();
1625
+ e.startSpan("browser.web_vital", T(T(T(T(T({}, e.config.hooks.getPageAttributes()), e.config.hooks.getMetricAttributes()), Dn(t, l)), I({
1626
+ duration: t.name === "CLS" ? void 0 : t.value,
1627
+ errorType: t.rating === "good" ? "none" : "slow",
1628
+ eventLabel: "Web 指标",
1629
+ result: Ge(t.rating),
1630
+ spanSubtype: n,
1631
+ spanType: F.vital,
1632
+ targetLabel: n,
1633
+ targetValue: t.value
1634
+ })), {}, {
1635
+ [b.vitalMetric]: n,
1636
+ [b.vitalValue]: t.value,
1637
+ [b.vitalRating]: t.rating,
1638
+ "vital.id": t.id
1639
+ }, On(t, e.config.hooks.redactUrl))).end();
1640
+ }, p = (n) => {
1641
+ t || !Number.isFinite(n.value) || (d.record(n.value, e.applyRedact(T(T(T({}, e.config.hooks.getPageAttributes()), e.config.hooks.getMetricAttributes()), Dn(n, l)))), f(n));
1642
+ };
1643
+ i((n) => {
1644
+ t || !Number.isFinite(n.value) || (u.record(n.value, e.applyRedact(T(T(T({}, e.config.hooks.getPageAttributes()), e.config.hooks.getMetricAttributes()), Dn(n, l)))), f(n));
1645
+ }), a(p), o(p), s(p), c(p);
1646
+ })();
1647
+ },
1648
+ shutdown() {
1649
+ t = !0;
1650
+ }
1001
1651
  };
1652
+ }, An = 64 * 1024, jn = 6e4, Mn = 5, Nn = (e) => e == null ? 0 : typeof e == "string" ? e.length > An || typeof TextEncoder > "u" ? e.length : new TextEncoder().encode(e).byteLength : e instanceof ArrayBuffer || ArrayBuffer.isView(e) ? e.byteLength : typeof Blob < "u" && e instanceof Blob ? e.size : 0, Pn = (e, t) => {
1653
+ let n = {
1654
+ "network.protocol.name": "websocket",
1655
+ "url.full": t(e)
1656
+ }, r = { "network.protocol.name": "websocket" };
1002
1657
  try {
1003
- n["server.address"] = new URL(e, typeof location > "u" ? "http://localhost" : location.href).host;
1658
+ let t = new URL(e, typeof location > "u" ? "http://localhost" : location.href);
1659
+ n["server.address"] = t.host, n["url.scheme"] = t.protocol.replace(":", ""), r["server.address"] = t.host, r["url.scheme"] = n["url.scheme"];
1004
1660
  } catch (e) {}
1005
1661
  return {
1006
- spanAttributes: n,
1007
- metricAttributes: { "network.protocol.name": "websocket" }
1662
+ metricAttributes: r,
1663
+ spanAttributes: n
1008
1664
  };
1009
- }, Dt = (e) => {
1010
- let n;
1665
+ }, Fn = (e, n) => {
1666
+ var r;
1667
+ let { bytesCounter: i, connectDurationHistogram: a, context: s, errorCounter: c, errorThrottle: l, isDisposed: u, messageCounter: d, url: f } = n, { metricAttributes: p, spanAttributes: m } = Pn(f, s.config.hooks.redactUrl), h = (r = m["server.address"]) == null ? m["url.full"] : r, g = s.startSpan("websocket.connect", T(T(T({}, m), I({
1668
+ errorType: "none",
1669
+ eventLabel: "WebSocket",
1670
+ spanSubtype: "websocket",
1671
+ spanType: F.custom,
1672
+ targetLabel: h
1673
+ })), m["server.address"] ? { [b.targetDomain]: m["server.address"] } : {})), _ = performance.now(), v = !1, y = (e) => {
1674
+ if (v) return;
1675
+ v = !0;
1676
+ let n = performance.now() - _;
1677
+ e === "error" && g.setStatus({
1678
+ code: t.ERROR,
1679
+ message: "websocket connect failed"
1680
+ }), g.setAttributes(I({
1681
+ duration: n,
1682
+ errorType: e === "error" ? "network" : "none",
1683
+ eventLabel: "WebSocket",
1684
+ result: e === "error" ? P.error : P.success,
1685
+ spanSubtype: "websocket",
1686
+ spanType: F.custom,
1687
+ targetLabel: h,
1688
+ targetValue: n
1689
+ })), g.end(), e === "opened" && !u() && a.record(n, p);
1690
+ };
1691
+ e.addEventListener("open", () => {
1692
+ u() || y("opened");
1693
+ }), e.addEventListener("message", (e) => {
1694
+ if (u()) return;
1695
+ let t = T(T({}, p), {}, { "websocket.direction": "in" });
1696
+ d.add(1, t), i.add(Nn(e.data), t);
1697
+ }), e.addEventListener("error", () => {
1698
+ if (u()) return;
1699
+ let e = v ? "runtime" : "connect";
1700
+ c.add(1, T(T({}, p), {}, { "websocket.error.phase": e })), y("error");
1701
+ let t = l.allow(`ws:error:${f}`);
1702
+ t.allowed && s.emitLog({
1703
+ severityNumber: o.ERROR,
1704
+ severityText: "ERROR",
1705
+ body: "websocket.error",
1706
+ attributes: T(T(T({}, m), I({
1707
+ errorType: "network",
1708
+ eventLabel: "WebSocket 错误",
1709
+ result: P.error,
1710
+ spanSubtype: "websocket",
1711
+ spanType: F.custom,
1712
+ targetLabel: h
1713
+ })), {}, {
1714
+ "websocket.error.phase": e,
1715
+ "websocket.error.window_count": t.count
1716
+ })
1717
+ });
1718
+ }), e.addEventListener("close", (e) => {
1719
+ u() || (v || y("error"), s.emitLog({
1720
+ severityNumber: o.INFO,
1721
+ severityText: "INFO",
1722
+ body: "websocket.close",
1723
+ attributes: T(T(T({}, m), I({
1724
+ errorType: e.wasClean ? "none" : "network",
1725
+ eventLabel: "WebSocket 关闭",
1726
+ result: e.wasClean ? P.success : P.warning,
1727
+ spanSubtype: "websocket",
1728
+ spanType: F.custom,
1729
+ targetLabel: h,
1730
+ targetValue: e.code
1731
+ })), {}, {
1732
+ "websocket.close.code": e.code,
1733
+ "websocket.close.reason": e.reason,
1734
+ "websocket.close.was_clean": e.wasClean
1735
+ })
1736
+ }));
1737
+ });
1738
+ let ee = e.send.bind(e);
1739
+ e.send = (e) => {
1740
+ if (!u()) {
1741
+ let t = T(T({}, p), {}, { "websocket.direction": "out" });
1742
+ d.add(1, t), i.add(Nn(e), t);
1743
+ }
1744
+ return ee(e);
1745
+ };
1746
+ }, In = (e) => {
1747
+ let t, n, r = !1;
1011
1748
  return {
1012
1749
  name: "websocket",
1013
- enabled: !!e,
1750
+ enabled: e.enabled,
1014
1751
  init(e) {
1015
1752
  if (typeof window > "u" || window.WebSocket === void 0) return;
1016
- let r = window.WebSocket;
1017
- n = r;
1018
- let i = e.meter.createCounter("browser.websocket.message.count", { description: "Total number of WebSocket messages observed" }), a = e.meter.createCounter("browser.websocket.message.bytes", {
1753
+ let i = window.WebSocket;
1754
+ t = i;
1755
+ let a = e.meter.createCounter("browser.websocket.message.count", { description: "Total number of WebSocket messages observed" }), o = e.meter.createCounter("browser.websocket.message.bytes", {
1019
1756
  unit: "By",
1020
1757
  description: "Total bytes transferred over WebSocket (best-effort)"
1021
- }), s = e.meter.createCounter("browser.websocket.error.count", { description: "Total number of WebSocket error events" }), c = function(n, c) {
1022
- let l = n.toString();
1023
- if (I(e.config, l)) return c === void 0 ? new r(n) : new r(n, c);
1024
- let { metricAttributes: u, spanAttributes: d } = Et(l, e.config.redactUrl), f = e.startSpan("websocket.connect", d), p = performance.now(), m = c === void 0 ? new r(n) : new r(n, c), h = !1, g = (e) => {
1025
- h || (h = !0, e === "error" && f.setStatus({
1026
- code: t.ERROR,
1027
- message: "websocket connect failed"
1028
- }), f.setAttribute("websocket.connect.duration_ms", performance.now() - p), f.end());
1029
- };
1030
- m.addEventListener("open", () => g("opened")), m.addEventListener("message", (e) => {
1031
- i.add(1, O(O({}, u), {}, { "websocket.direction": "in" })), a.add(Tt(e.data), O(O({}, u), {}, { "websocket.direction": "in" }));
1032
- }), m.addEventListener("error", () => {
1033
- s.add(1, u), g("error"), e.emitLog({
1034
- severityNumber: o.ERROR,
1035
- severityText: "ERROR",
1036
- body: "websocket.error",
1037
- attributes: d
1038
- });
1039
- }), m.addEventListener("close", (t) => {
1040
- g("opened"), e.emitLog({
1041
- severityNumber: o.INFO,
1042
- severityText: "INFO",
1043
- body: "websocket.close",
1044
- attributes: O(O({}, d), {}, {
1045
- "websocket.close.code": t.code,
1046
- "websocket.close.reason": t.reason,
1047
- "websocket.close.was_clean": t.wasClean
1048
- })
1049
- });
1050
- });
1051
- let _ = m.send.bind(m);
1052
- return m.send = (e) => (i.add(1, O(O({}, u), {}, { "websocket.direction": "out" })), a.add(Tt(e), O(O({}, u), {}, { "websocket.direction": "out" })), _(e)), m;
1053
- };
1054
- c.prototype = r.prototype, Object.assign(c, r), window.WebSocket = c;
1758
+ }), s = e.meter.createCounter("browser.websocket.error.count", { description: "Total number of WebSocket error events" }), c = e.meter.createHistogram("browser.websocket.connect.duration", {
1759
+ unit: "ms",
1760
+ description: "WebSocket connection establishment duration (only successful connects)"
1761
+ }), l = z(jn, Mn), u = () => r;
1762
+ n = new Proxy(i, { construct(t, n, i) {
1763
+ let d = Reflect.construct(t, n, i);
1764
+ if (r) return d;
1765
+ let f = n[0] == null ? "" : String(n[0]);
1766
+ return !f || N(e.config, f) || Fn(d, {
1767
+ bytesCounter: o,
1768
+ connectDurationHistogram: c,
1769
+ context: e,
1770
+ errorCounter: s,
1771
+ errorThrottle: l,
1772
+ isDisposed: u,
1773
+ messageCounter: a,
1774
+ url: f
1775
+ }), d;
1776
+ } }), window.WebSocket = n;
1055
1777
  },
1056
1778
  shutdown() {
1057
- n && typeof window < "u" && (window.WebSocket = n);
1779
+ r = !0, typeof window < "u" && t && window.WebSocket === n && (window.WebSocket = t), n = void 0, t = void 0;
1058
1780
  }
1059
1781
  };
1060
- }, Z = "__bk_ot_sampled__", Ot = /* @__PURE__ */ new Map(), kt = (e) => Ot.get(e), At = (e, t) => (Ot.set(e, t), t), jt = ({ sampleRate: e }) => {
1061
- if (e <= 0) return !1;
1062
- if (e >= 1) return !0;
1782
+ }, $ = "BK_RUM_SAMPLING", Ln = /* @__PURE__ */ new Map(), Rn = (e) => Ln.get(e), zn = (e, t) => (Ln.set(e, t), t), Bn = ({ sampling: e }) => {
1783
+ if (e.rate <= 0) return !1;
1784
+ if (e.rate >= 1) return !0;
1063
1785
  try {
1064
- let t = sessionStorage.getItem(Z);
1786
+ let t = sessionStorage.getItem($);
1065
1787
  if (t) return t === "1";
1066
- let n = Math.random() < e;
1067
- return sessionStorage.setItem(Z, n ? "1" : "0"), At(Z, n), n;
1788
+ let n = Math.random() < e.rate;
1789
+ return sessionStorage.setItem($, n ? "1" : "0"), zn($, n), n;
1068
1790
  } catch (t) {
1069
- let n = kt(Z);
1070
- return typeof n == "boolean" ? n : At(Z, Math.random() < e);
1791
+ let n = Rn($);
1792
+ return typeof n == "boolean" ? n : zn($, Math.random() < e.rate);
1071
1793
  }
1072
- }, Q = (e) => ({
1794
+ }, Vn = (e) => ({
1073
1795
  url: e.endpoint,
1074
1796
  headers: e.headers,
1075
1797
  concurrencyLimit: e.concurrencyLimit,
1076
1798
  timeoutMillis: e.timeoutMillis
1077
- }), $ = "bk-rum", Mt = (e, t, n) => n ? new Proxy(e, { get(e, n, r) {
1799
+ }), Hn = "bk-rum", Un = (e, t, n) => n ? new Proxy(e, { get(e, n, r) {
1078
1800
  if (n === "export") return (n, r) => {
1079
1801
  var i;
1080
1802
  return (i = globalThis.console) == null || i.log(`[bk-ot][${t}]`, n), e.export(n, r);
1081
1803
  };
1082
1804
  let i = Reflect.get(e, n, r);
1083
1805
  return typeof i == "function" ? i.bind(e) : i;
1084
- } }) : e, Nt = (e) => [Pe(e.commonInstrumentations)], Pt = (e) => [
1085
- ze(e.rum.device),
1086
- it(e.rum.httpBody),
1087
- xt(e.rum.session),
1088
- pt(e.rum.pageView),
1089
- Ke(e.rum.error),
1090
- wt(e.rum.webVitals),
1091
- Ae(e.rum.blankScreen),
1092
- Dt(e.rum.websocket),
1093
- ot(e.rum.longTask),
1094
- Fe(e.rum.cspViolation),
1095
- mt(e.rum.routeTiming)
1096
- ], Ft = class {
1806
+ } }) : e, Wn = (e) => [pt(e.rum.instrumentations)], Gn = (e) => [
1807
+ Ze(e.rum.plugins.action),
1808
+ At(e.rum.plugins.device),
1809
+ Zt(e.rum.plugins.httpBody),
1810
+ Cn(e.rum.plugins.session),
1811
+ sn(e.rum.plugins.pageView),
1812
+ Rt(e.rum.plugins.error),
1813
+ kn(e.rum.plugins.webVitals),
1814
+ ln(e.rum.plugins.resource),
1815
+ at(e.rum.plugins.blankScreen),
1816
+ In(e.rum.plugins.websocket),
1817
+ $t(e.rum.plugins.longTask),
1818
+ vt(e.rum.plugins.cspViolation),
1819
+ un(e.rum.plugins.routeTiming)
1820
+ ], Kn = class {
1097
1821
  assertBeforeStart(e) {
1098
1822
  if (this.phase !== "idle") throw Error(`[bk-ot] ${e}() must be called before start(); set autoStart: false before registration.`);
1099
1823
  }
1100
1824
  constructor(o) {
1101
- var C = this;
1102
- E(this, "loggerProvider", void 0), E(this, "meterProvider", void 0), E(this, "phase", "idle"), E(this, "pluginManager", void 0), E(this, "plugins", void 0), E(this, "registeredInstrumentations", void 0), E(this, "runtimeAttributes", void 0), E(this, "sampled", void 0), E(this, "teardownCallbacks", []), E(this, "tracerProvider", void 0), E(this, "applyRedact", (e) => this.config.redactAttributes(e)), E(this, "config", void 0), E(this, "emitLog", (e) => {
1825
+ var x = this;
1826
+ C(this, "loggerProvider", void 0), C(this, "meterProvider", void 0), C(this, "phase", "idle"), C(this, "pluginManager", void 0), C(this, "plugins", void 0), C(this, "registeredInstrumentations", void 0), C(this, "runtimeContext", void 0), C(this, "sampled", void 0), C(this, "teardownCallbacks", []), C(this, "tracerProvider", void 0), C(this, "applyRedact", (e) => this.config.hooks.redactAttributes(e)), C(this, "config", void 0), C(this, "emitLog", (e) => {
1103
1827
  var t;
1104
- let n = O(O({}, e), {}, { attributes: this.applyRedact(O(O({}, this.getRuntimeAttributes()), (t = e.attributes) == null ? {} : t)) });
1828
+ let n = T(T({}, e), {}, { attributes: this.applyRedact(T(T({}, this.getRuntimeAttributes()), (t = e.attributes) == null ? {} : t)) });
1105
1829
  this.logger.emit(n);
1106
- }), E(this, "flush", P(function* () {
1107
- yield C.pluginManager.flush(), yield C.tracerProvider.forceFlush(), yield C.meterProvider.forceFlush(), yield C.loggerProvider.forceFlush();
1108
- })), E(this, "getRuntimeAttributes", () => O({}, this.runtimeAttributes)), E(this, "logger", void 0), E(this, "meter", void 0), E(this, "reportCustomEvent", ({ attributes: e = {}, error: n, name: r }) => {
1830
+ }), C(this, "flush", M(function* () {
1831
+ yield x.pluginManager.flush(), yield x.tracerProvider.forceFlush(), yield x.meterProvider.forceFlush(), yield x.loggerProvider.forceFlush();
1832
+ })), C(this, "getRuntimeAttributes", () => this.runtimeContext.getAttributes()), C(this, "logger", void 0), C(this, "meter", void 0), C(this, "reportAction", ({ attributes: e = {}, targetTag: t, targetText: n, type: r }) => {
1833
+ var i;
1834
+ if (!this.sampled) return;
1835
+ let a = n == null ? void 0 : n.slice(0, 32);
1836
+ this.startSpan(`action.${r}`, T(T(T(T(T({}, this.config.hooks.getPageAttributes()), I({
1837
+ errorType: "none",
1838
+ eventLabel: "用户操作",
1839
+ spanSubtype: r,
1840
+ spanType: F.action,
1841
+ targetLabel: (i = a == null ? t : a) == null ? r : i
1842
+ })), {}, { [b.actionType]: r }, a ? { [b.targetTextShort]: a } : {}), t ? { [b.targetTag]: t } : {}), e)).end();
1843
+ }), C(this, "reportCustomEvent", ({ attributes: e = {}, error: n, name: r }) => {
1109
1844
  if (!this.sampled) {
1110
1845
  if (this.config.debug) {
1111
1846
  var i;
@@ -1113,83 +1848,95 @@ var de = (e, t) => typeof e.enabled == "function" ? e.enabled(t) : e.enabled !==
1113
1848
  }
1114
1849
  return;
1115
1850
  }
1116
- let a = this.startSpan(`custom.${r}`, O(O(O(O({}, this.config.getPageAttributes()), this.config.getCustomAttributes()), e), {}, { "rum.custom.name": r }));
1851
+ let a = this.startSpan(`custom.${r}`, T(T(T(T(T({}, this.config.hooks.getPageAttributes()), this.config.hooks.getCustomAttributes()), I({
1852
+ errorType: n ? "custom" : "none",
1853
+ eventLabel: "自定义事件",
1854
+ result: n ? P.error : P.success,
1855
+ spanSubtype: r,
1856
+ spanType: F.custom,
1857
+ targetLabel: r
1858
+ })), e), {}, { "rum.custom.name": r }));
1117
1859
  n && (a.recordException(n), a.setStatus({
1118
1860
  code: t.ERROR,
1119
1861
  message: n.message
1120
1862
  })), a.end();
1121
- }), E(this, "setRuntimeAttributes", (e) => {
1122
- Object.assign(this.runtimeAttributes, e);
1123
- }), E(this, "shutdown", P(function* () {
1124
- if (C.phase !== "stopped") {
1125
- for (yield C.flush(); C.teardownCallbacks.length;) {
1863
+ }), C(this, "setRuntimeAttributes", (e) => {
1864
+ this.runtimeContext.setAttributes(e);
1865
+ }), C(this, "setUser", (e) => {
1866
+ this.runtimeContext.setUser(e);
1867
+ }), C(this, "setView", (e) => {
1868
+ this.runtimeContext.setView(e);
1869
+ }), C(this, "shutdown", M(function* () {
1870
+ if (x.phase !== "stopped") {
1871
+ for (yield x.flush(); x.teardownCallbacks.length;) {
1126
1872
  var e;
1127
- (e = C.teardownCallbacks.pop()) == null || e();
1873
+ (e = x.teardownCallbacks.pop()) == null || e();
1128
1874
  }
1129
- for (yield C.pluginManager.shutdown(); C.registeredInstrumentations.length;) {
1875
+ for (yield x.pluginManager.shutdown(); x.registeredInstrumentations.length;) {
1130
1876
  var t, i;
1131
- (t = C.registeredInstrumentations.pop()) == null || (i = t.disable) == null || i.call(t);
1877
+ (t = x.registeredInstrumentations.pop()) == null || (i = t.disable) == null || i.call(t);
1132
1878
  }
1133
- yield C.tracerProvider.shutdown(), yield C.meterProvider.shutdown(), yield C.loggerProvider.shutdown(), a.disable(), r.disable(), n.disable(), C.phase = "stopped";
1879
+ yield x.tracerProvider.shutdown(), yield x.meterProvider.shutdown(), yield x.loggerProvider.shutdown(), a.disable(), r.disable(), n.disable(), x.phase = "stopped";
1134
1880
  }
1135
- })), E(this, "start", P(function* () {
1136
- if (!(C.phase === "started" || C.phase === "starting")) {
1137
- if (C.phase === "stopped") throw Error("[bk-ot] instance has been shut down and cannot be restarted; create a new instance instead.");
1138
- if (!C.config.enabled) {
1139
- C.phase = "started";
1881
+ })), C(this, "start", M(function* () {
1882
+ if (!(x.phase === "started" || x.phase === "starting")) {
1883
+ if (x.phase === "stopped") throw Error("[bk-ot] instance has been shut down and cannot be restarted; create a new instance instead.");
1884
+ if (!x.config.enabled) {
1885
+ x.phase = "started";
1140
1886
  return;
1141
1887
  }
1142
- C.phase = "starting", i.setGlobalPropagator(new l()), C.tracerProvider.register({ contextManager: new c() }), r.setGlobalMeterProvider(C.meterProvider), s.setGlobalLoggerProvider(C.loggerProvider);
1888
+ x.phase = "starting", i.setGlobalPropagator(new l()), x.tracerProvider.register({ contextManager: new c() }), r.setGlobalMeterProvider(x.meterProvider), s.setGlobalLoggerProvider(x.loggerProvider);
1143
1889
  try {
1144
- if (C.registeredInstrumentations.length && p({
1145
- instrumentations: C.registeredInstrumentations,
1146
- meterProvider: C.meterProvider,
1147
- tracerProvider: C.tracerProvider
1148
- }), yield C.pluginManager.start(C), typeof window < "u" && typeof document < "u") {
1890
+ if (x.registeredInstrumentations.length && p({
1891
+ instrumentations: x.registeredInstrumentations,
1892
+ meterProvider: x.meterProvider,
1893
+ tracerProvider: x.tracerProvider
1894
+ }), yield x.pluginManager.start(x), typeof window < "u" && typeof document < "u") {
1149
1895
  let e = () => {
1150
- C.flush();
1896
+ x.flush();
1151
1897
  }, t = () => {
1152
- document.visibilityState === "hidden" && C.flush();
1898
+ document.visibilityState === "hidden" && x.flush();
1153
1899
  };
1154
- window.addEventListener("pagehide", e), document.addEventListener("visibilitychange", t), C.teardownCallbacks.push(() => window.removeEventListener("pagehide", e), () => document.removeEventListener("visibilitychange", t));
1900
+ window.addEventListener("pagehide", e), document.addEventListener("visibilitychange", t), x.teardownCallbacks.push(() => window.removeEventListener("pagehide", e), () => document.removeEventListener("visibilitychange", t));
1155
1901
  }
1156
1902
  } catch (i) {
1157
- for (; C.teardownCallbacks.length;) {
1903
+ for (; x.teardownCallbacks.length;) {
1158
1904
  var e;
1159
- (e = C.teardownCallbacks.pop()) == null || e();
1905
+ (e = x.teardownCallbacks.pop()) == null || e();
1160
1906
  }
1161
- yield C.pluginManager.shutdown();
1162
- for (let e of C.registeredInstrumentations) {
1907
+ yield x.pluginManager.shutdown();
1908
+ for (let e of x.registeredInstrumentations) {
1163
1909
  var t;
1164
1910
  (t = e.disable) == null || t.call(e);
1165
1911
  }
1166
- throw a.disable(), r.disable(), n.disable(), C.phase = "idle", i;
1912
+ throw a.disable(), r.disable(), n.disable(), x.phase = "idle", i;
1167
1913
  }
1168
- C.phase = "started";
1914
+ x.phase = "started";
1169
1915
  }
1170
- })), E(this, "startSpan", (t, n = {}) => this.tracer.startSpan(t, {
1916
+ })), C(this, "startSpan", (t, n = {}, r) => this.tracer.startSpan(t, {
1171
1917
  kind: e.INTERNAL,
1172
- attributes: this.applyRedact(O(O({}, this.getRuntimeAttributes()), n))
1173
- })), E(this, "tracer", void 0), E(this, "use", (e) => (this.assertBeforeStart("use"), this.sampled && this.plugins.push(e), this)), E(this, "useInstrumentation", (e) => (this.assertBeforeStart("useInstrumentation"), this.config.enabled && this.registeredInstrumentations.push(e), this)), this.config = le(o), this.sampled = this.config.enabled && jt(this.config);
1174
- let w = m(this.config.resourceAttributes), T = Mt(new f(Q(this.config.traces)), "traces", this.config.debug), D = Mt(new d(Q(this.config.metrics)), "metrics", this.config.debug), k = Mt(new u(Q(this.config.logs)), "logs", this.config.debug), ee = new Se(new y(T, this.config.spanBatch), this.config), A = new v({
1175
- exporter: D,
1918
+ startTime: r == null ? void 0 : r.startTime,
1919
+ attributes: this.applyRedact(T(T({}, this.getRuntimeAttributes()), n))
1920
+ })), C(this, "tracer", void 0), C(this, "use", (e) => (this.assertBeforeStart("use"), this.sampled && this.plugins.push(e), this)), C(this, "useInstrumentation", (e) => (this.assertBeforeStart("useInstrumentation"), this.config.enabled && this.registeredInstrumentations.push(e), this)), this.config = Te(o), this.sampled = this.config.enabled && Bn(this.config);
1921
+ let S = m(this.config.resourceAttributes), ie = Un(new f(Vn(this.config.transport.traces)), "traces", this.config.debug), w = Un(new d(Vn(this.config.transport.metrics)), "metrics", this.config.debug), ae = Un(new u(Vn(this.config.transport.logs)), "logs", this.config.debug), oe = new ze(this.config.spanProcessor === "simple" ? new te(ie) : new y(ie, this.config.spanBatch), this.config), se = new v({
1922
+ exporter: w,
1176
1923
  exportIntervalMillis: this.config.metricIntervalMillis
1177
- }), j = new h(k);
1178
- this.tracerProvider = new S({
1179
- resource: w,
1180
- sampler: new b({ root: new x(+!!this.sampled) }),
1181
- spanProcessors: [ee]
1924
+ }), E = new h(ae);
1925
+ this.tracerProvider = new re({
1926
+ resource: S,
1927
+ sampler: new ee({ root: new ne(+!!this.sampled) }),
1928
+ spanProcessors: [oe]
1182
1929
  }), this.meterProvider = new _({
1183
- resource: w,
1184
- readers: [A]
1930
+ resource: S,
1931
+ readers: [se]
1185
1932
  }), this.loggerProvider = new g({
1186
- resource: w,
1187
- processors: [j]
1188
- }), this.tracer = this.tracerProvider.getTracer($), this.meter = this.meterProvider.getMeter($), this.logger = this.loggerProvider.getLogger($), this.runtimeAttributes = { "bk.rum.sampled": this.sampled }, this.registeredInstrumentations = this.config.enabled ? [...this.config.instrumentations] : [], this.plugins = [...this.config.enabled ? Nt(this.config) : [], ...this.sampled ? [...Pt(this.config), ...this.config.plugins] : []], this.pluginManager = new pe(this.plugins), this.config.autoStart && this.start().catch((e) => {
1933
+ resource: S,
1934
+ processors: [E]
1935
+ }), this.tracer = this.tracerProvider.getTracer(Hn), this.meter = this.meterProvider.getMeter(Hn), this.logger = this.loggerProvider.getLogger(Hn), this.runtimeContext = new Be({ "rum.sampled": this.sampled }, this.config.user), this.registeredInstrumentations = this.config.enabled ? [...this.config.instrumentations] : [], this.plugins = [...this.config.enabled ? Wn(this.config) : [], ...this.sampled ? [...Gn(this.config), ...this.config.plugins] : []], this.pluginManager = new ke(this.plugins), this.config.autoStart && this.start().catch((e) => {
1189
1936
  var t;
1190
1937
  (t = globalThis.console) == null || t.warn("[bk-ot] auto start failed:", e);
1191
1938
  });
1192
1939
  }
1193
1940
  };
1194
1941
  //#endregion
1195
- export { Ft as BkOpenTelemetry, Se as FilteringSpanProcessor, Ae as createBlankScreenPlugin, Pe as createCommonInstrumentationsPlugin, Fe as createCspViolationPlugin, ze as createDevicePlugin, Ke as createErrorPlugin, it as createHttpBodyPlugin, ot as createLongTaskPlugin, pt as createPageViewPlugin, fe as createPlugin, mt as createRouteTimingPlugin, xt as createSessionPlugin, Dt as createWebSocketPlugin, wt as createWebVitalsPlugin, le as normalizeConfig };
1942
+ export { Kn as BkOpenTelemetry, ze as FilteringSpanProcessor, b as RUM_ATTRIBUTES, P as RUM_SPAN_RESULT, F as RUM_SPAN_TYPE, Be as RumRuntimeContext, I as buildRumSpanAttributes, Ze as createActionPlugin, at as createBlankScreenPlugin, pt as createCommonInstrumentationsPlugin, vt as createCspViolationPlugin, At as createDevicePlugin, Rt as createErrorPlugin, Zt as createHttpBodyPlugin, $t as createLongTaskPlugin, sn as createPageViewPlugin, Oe as createPlugin, ln as createResourcePlugin, un as createRouteTimingPlugin, Cn as createSessionPlugin, In as createWebSocketPlugin, kn as createWebVitalsPlugin, Ve as getDurationBucket, Te as resolveConfig };