@chrom-ar/collector 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { truncate, safeStringify, stripUrl, uuid4, rumUrl } from './chunk-YN5N3X7X.js';
2
+
1
3
  // src/dsn.ts
2
4
  function parseDsn(dsn) {
3
5
  let parsed;
@@ -9,52 +11,7 @@ function parseDsn(dsn) {
9
11
  if (parsed.protocol !== "https:" && parsed.protocol !== "http:" || parsed.username === "") return null;
10
12
  const base = parsed.origin + parsed.pathname.replace(/\/+$/, "");
11
13
  const key = parsed.username;
12
- return { url: `${base}/api/events?key=${key}`, heartbeatUrl: `${base}/api/heartbeats?key=${key}`, base, key };
13
- }
14
-
15
- // src/util.ts
16
- function uuid4() {
17
- if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
18
- const b = crypto.getRandomValues(new Uint8Array(16));
19
- b[6] = (b[6] ?? 0) & 15 | 64;
20
- b[8] = (b[8] ?? 0) & 63 | 128;
21
- const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
22
- return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
23
- }
24
- function truncate(s, max) {
25
- if (s.length <= max) return s;
26
- const last = s.charCodeAt(max - 1);
27
- return s.slice(0, last >= 55296 && last <= 56319 ? max - 1 : max);
28
- }
29
- function safeStringify(value, max = 8192) {
30
- return truncate(stringify(value), max);
31
- }
32
- function stringify(value) {
33
- if (typeof value === "string") return value;
34
- if (value === void 0 || typeof value === "function" || typeof value === "symbol" || typeof value === "bigint") {
35
- return String(value);
36
- }
37
- const seen = /* @__PURE__ */ new WeakSet();
38
- try {
39
- return JSON.stringify(value, (_key, v) => {
40
- if (typeof v === "bigint") return v.toString();
41
- if (typeof v === "object" && v !== null) {
42
- if (seen.has(v)) return "[Circular]";
43
- seen.add(v);
44
- }
45
- return v;
46
- });
47
- } catch {
48
- try {
49
- return String(value);
50
- } catch {
51
- return "[unserializable]";
52
- }
53
- }
54
- }
55
- function stripUrl(url) {
56
- const i = url.search(/[?#]/);
57
- return i === -1 ? url : url.slice(0, i);
14
+ return { url: `${base}/api/events?key=${key}`, heartbeatUrl: `${base}/api/heartbeats?key=${key}`, pageviewsUrl: `${base}/api/pageviews?key=${key}`, base, key };
58
15
  }
59
16
 
60
17
  // src/stacktrace.ts
@@ -209,7 +166,7 @@ function releaseOf(options) {
209
166
  function environmentOf(options) {
210
167
  return typeof options.environment === "string" && options.environment !== "" ? options.environment : void 0;
211
168
  }
212
- function baseEvent({ options, scope: scope2, href, userAgent }, ctx = {}) {
169
+ function baseEvent({ options, scope: scope2, href, userAgent, session }, ctx = {}) {
213
170
  const event = {
214
171
  v: 1,
215
172
  uuid: uuid4(),
@@ -217,12 +174,13 @@ function baseEvent({ options, scope: scope2, href, userAgent }, ctx = {}) {
217
174
  platform: "javascript",
218
175
  level: toLevel(ctx.level),
219
176
  request: { url: options.stripQuery === false ? href : stripUrl(href), headers: { "user-agent": userAgent } },
220
- sdk: { name: SDK_NAME, version: "0.3.1" }
177
+ sdk: { name: SDK_NAME, version: "0.4.0" }
221
178
  };
222
179
  const environment = environmentOf(options);
223
180
  if (environment !== void 0) event.environment = environment;
224
181
  const release = releaseOf(options);
225
182
  if (release !== void 0) event.release = release;
183
+ if (session !== void 0) event.session = session;
226
184
  if (ctx.fingerprint && ctx.fingerprint.length > 0) event.fingerprint = ctx.fingerprint.map(String);
227
185
  const user = ctx.user ? { id: String(ctx.user.id) } : scope2.user;
228
186
  if (user) event.user = user;
@@ -346,7 +304,7 @@ async function beat({ url, key, fetch, options, logger }) {
346
304
  if (storedMark(storageKey) === mark || sentThisPage.has(storageKey + mark)) return;
347
305
  let status;
348
306
  try {
349
- const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.3.1" }, environment, release });
307
+ const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.4.0" }, environment, release });
350
308
  const response = await fetch(url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive: true, credentials: "omit" });
351
309
  ({ status } = response);
352
310
  } catch (error) {
@@ -392,6 +350,15 @@ function displayUrl(win, url, stripQuery) {
392
350
  }
393
351
  return stripQuery ? stripUrl(shown) : shown;
394
352
  }
353
+ function timeRequest(opts, win, method, url) {
354
+ const target = opts.onRequest ? rumUrl(win.location.href, url) : void 0;
355
+ if (target === void 0) return () => void 0;
356
+ const start = performance.now();
357
+ const token = opts.onRequestStart?.();
358
+ return (status) => {
359
+ opts.onRequest?.({ method: method.toUpperCase(), url: target, status: status ?? 0, start, end: performance.now() }, token);
360
+ };
361
+ }
395
362
  function absoluteUrl(win, url) {
396
363
  try {
397
364
  return new URL(url, win.location.href).href;
@@ -502,8 +469,10 @@ function instrumentFetch(win, record, opts) {
502
469
  const { method, url } = describe2(input, init2);
503
470
  if (opts.skipUrl(absoluteUrl(win, url))) return;
504
471
  const shown = displayUrl(win, url, opts.stripQuery);
472
+ const timing = timeRequest(opts, win, method, url);
505
473
  done = (status) => {
506
474
  safeRecord(() => {
475
+ timing(status);
507
476
  record({ category: "fetch", level: levelForStatus(status), message: requestMessage(method, shown, status) });
508
477
  });
509
478
  };
@@ -545,14 +514,24 @@ function instrumentHistory(win, record, opts) {
545
514
  (original) => function __collectorWrapped(...args) {
546
515
  original.apply(this, args);
547
516
  moved();
517
+ navigated();
548
518
  }
549
519
  );
520
+ const navigated = () => {
521
+ safeRecord(() => {
522
+ opts.onNavigate?.();
523
+ });
524
+ };
525
+ const popped = () => {
526
+ moved();
527
+ navigated();
528
+ };
550
529
  const restores = [wrapState("pushState"), wrapState("replaceState")];
551
- win.addEventListener("popstate", moved);
530
+ win.addEventListener("popstate", popped);
552
531
  win.addEventListener("hashchange", moved);
553
532
  return () => {
554
533
  if (!restores.map((restore) => restore()).every(Boolean)) return false;
555
- win.removeEventListener("popstate", moved);
534
+ win.removeEventListener("popstate", popped);
556
535
  win.removeEventListener("hashchange", moved);
557
536
  return true;
558
537
  };
@@ -583,9 +562,11 @@ function instrumentXhr(win, record, opts) {
583
562
  const request = requests.get(this);
584
563
  if (!request || opts.skipUrl(absoluteUrl(win, request.url))) return;
585
564
  const shown = displayUrl(win, request.url, opts.stripQuery);
565
+ const timing = timeRequest(opts, win, request.method, request.url);
586
566
  this.addEventListener("loadend", () => {
587
567
  safeRecord(() => {
588
568
  const status = this.status !== 0 ? this.status : void 0;
569
+ timing(status);
589
570
  record({ category: "xhr", level: levelForStatus(status), message: requestMessage(request.method, shown, status) });
590
571
  });
591
572
  }, { once: true });
@@ -889,8 +870,16 @@ var sharedOptions = {
889
870
  skipUrl: (url) => active?.isOwnUrl(url) ?? false,
890
871
  get stripQuery() {
891
872
  return active?.options.stripQuery !== false;
873
+ },
874
+ onRequestStart: () => active?.rum?.requestStart(),
875
+ onRequest: (timing, token) => {
876
+ active?.rum?.request(timing, token);
877
+ },
878
+ onNavigate: () => {
879
+ active?.rum?.navigate();
892
880
  }
893
881
  };
882
+ var RUM_KINDS = /* @__PURE__ */ new Set(["fetch", "xhr", "history"]);
894
883
  var rejected = /* @__PURE__ */ new Set();
895
884
  var recorderFor = (kind) => (crumb) => {
896
885
  if (active && active.options.breadcrumbs?.[kind] !== false) active.addBreadcrumb(crumb);
@@ -945,9 +934,17 @@ var Client = class {
945
934
  )
946
935
  );
947
936
  }
937
+ if (options.rum && !this.transport.disabled) {
938
+ try {
939
+ this.rum = options.rum.start({ win, url: endpoint.pageviewsUrl, fetch: fetchFn, logger: this.logger, options, sdk: { name: SDK_NAME, version: "0.4.0" }, environment: environmentOf(options), release: releaseOf(options) });
940
+ } catch (error) {
941
+ this.logger.debug("RUM didn't start", error);
942
+ }
943
+ }
948
944
  active = this;
949
945
  for (const [kind, instrument] of Object.entries(INSTRUMENTS)) {
950
- if (options.breadcrumbs?.[kind] === false || installed.has(kind)) continue;
946
+ const needed = options.breadcrumbs?.[kind] !== false || this.rum !== void 0 && RUM_KINDS.has(kind);
947
+ if (!needed || installed.has(kind)) continue;
951
948
  try {
952
949
  installed.set(kind, instrument(win, recorderFor(kind), sharedOptions));
953
950
  } catch (error) {
@@ -1021,6 +1018,10 @@ var Client = class {
1021
1018
  async flush(timeoutMs) {
1022
1019
  return this.transport ? this.transport.flush(timeoutMs) : Promise.resolve(true);
1023
1020
  }
1021
+ /** Names the current RUM page view. Does nothing without RUM. */
1022
+ setRoute(name) {
1023
+ this.rum?.setRoute(name);
1024
+ }
1024
1025
  /** True for requests to Collector itself. */
1025
1026
  isOwnUrl(url) {
1026
1027
  return this.endpointBase !== void 0 && url.startsWith(`${this.endpointBase}/`);
@@ -1028,6 +1029,11 @@ var Client = class {
1028
1029
  /** Removes every listener and wrapper it can. Events already queued still go out. */
1029
1030
  close() {
1030
1031
  this.closed = true;
1032
+ try {
1033
+ this.rum?.close();
1034
+ } catch (error) {
1035
+ this.logger.debug("RUM didn't close cleanly", error);
1036
+ }
1031
1037
  if (active === this) {
1032
1038
  active = void 0;
1033
1039
  for (const [kind, restore] of installed) {
@@ -1052,7 +1058,8 @@ var Client = class {
1052
1058
  scope: this.scope,
1053
1059
  origin: win.location.origin,
1054
1060
  href: win.location.href,
1055
- userAgent: win.navigator.userAgent
1061
+ userAgent: win.navigator.userAgent,
1062
+ session: this.rum?.session
1056
1063
  };
1057
1064
  }
1058
1065
  capture(build) {
@@ -1098,8 +1105,9 @@ var Client = class {
1098
1105
  };
1099
1106
 
1100
1107
  // src/index.ts
1101
- var SDK_VERSION = "0.3.1";
1108
+ var SDK_VERSION = "0.4.0";
1102
1109
  var client;
1110
+ var pendingRoute;
1103
1111
  var pendingScope = new Scope();
1104
1112
  function scope() {
1105
1113
  return client?.scope ?? pendingScope;
@@ -1118,6 +1126,8 @@ function init(options) {
1118
1126
  const kept = scope();
1119
1127
  client?.close();
1120
1128
  client = new Client(options, window, kept);
1129
+ if (pendingRoute) client.setRoute(pendingRoute.name);
1130
+ pendingRoute = void 0;
1121
1131
  if (options.debug === true) Object.defineProperty(window, CONSOLE_HANDLE, { value: { test }, configurable: true, writable: true });
1122
1132
  else Reflect.deleteProperty(window, CONSOLE_HANDLE);
1123
1133
  }, void 0);
@@ -1161,13 +1171,20 @@ function addBreadcrumb(crumb) {
1161
1171
  async function flush(timeoutMs) {
1162
1172
  return safely(async () => client?.flush(timeoutMs) ?? Promise.resolve(true), Promise.resolve(false));
1163
1173
  }
1174
+ function setRoute(name) {
1175
+ safely(() => {
1176
+ if (client) client.setRoute(name);
1177
+ else pendingRoute = { name };
1178
+ }, void 0);
1179
+ }
1164
1180
  function close() {
1165
1181
  safely(() => {
1166
1182
  client?.close();
1167
1183
  client = void 0;
1168
1184
  pendingScope = new Scope();
1185
+ pendingRoute = void 0;
1169
1186
  if (typeof window !== "undefined") Reflect.deleteProperty(window, CONSOLE_HANDLE);
1170
1187
  }, void 0);
1171
1188
  }
1172
1189
 
1173
- export { SDK_VERSION, addBreadcrumb, captureException, captureMessage, close, flush, init, setTag, setTags, setUser, test };
1190
+ export { SDK_VERSION, addBreadcrumb, captureException, captureMessage, close, flush, init, setRoute, setTag, setTags, setUser, test };