@chrom-ar/collector 0.3.0 → 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/CHANGELOG.md CHANGED
@@ -1,6 +1,24 @@
1
1
  # Changelog
2
2
 
3
- ## 0.3.0 (unreleased)
3
+ ## 0.4.0 (2026-11-09)
4
+
5
+ - Page speed (RUM), opt-in and in its own import:
6
+ `import { rum } from "@chrom-ar/collector/rum"`, then
7
+ `init({ rum: rum({ sampleRate: 0.1 }) })`. It measures Web Vitals,
8
+ in-app navigation time, requests and slow resources, and sends page views
9
+ in batches (gzipped over 1 KB) when the tab is hidden. Apps without it
10
+ don't ship it.
11
+ - `setRoute(name)` names the current page for RUM.
12
+ - Errors from tabs RUM measures carry the visit's `session`.
13
+
14
+ ## 0.3.1 (2026-11-07)
15
+
16
+ - `Collector.test()` sends one test error and resolves to `{ ok: true, id }`
17
+ or `{ ok: false, reason }`, logging one console line either way. With
18
+ `debug: true`, it's also `window.__collector.test()` for the browser
19
+ console.
20
+
21
+ ## 0.3.0 (2026-11-07)
4
22
 
5
23
  - Heartbeats: once a day per release and environment, a few seconds after
6
24
  `init()`, the SDK tells Collector the app is running, so a healthy app
package/README.md CHANGED
@@ -66,6 +66,24 @@ browser console:
66
66
 
67
67
  - **Vue:** add `app.config.errorHandler = (error) => Collector.captureException(error);`
68
68
 
69
+ ## Checking your setup
70
+
71
+ Send one test error and see what Collector answered:
72
+
73
+ ```ts
74
+ const result = await Collector.test();
75
+ // { ok: true, id: "…" } or { ok: false, reason: "Collector rejected the key (HTTP 401)…" }
76
+ ```
77
+
78
+ It also logs one line to the console, `[collector] Test event sent (202)…`
79
+ or why it wasn't. The event is a `CollectorTest` error tagged
80
+ `collector.test: "true"`, and every test groups into one issue. It skips
81
+ `ignoreErrors`, duplicate detection and the rate cap; `beforeSend` edits
82
+ apply, but if `beforeSend` drops it, it's sent anyway.
83
+
84
+ With `debug: true`, it's also on `window.__collector.test()`, so you can
85
+ run it from the browser's console without importing anything.
86
+
69
87
  ## Reporting things yourself
70
88
 
71
89
  ```ts
@@ -147,6 +165,53 @@ Other functions: `setTags(tags)`, `addBreadcrumb({ message, category?, level? })
147
165
  `flush(timeoutMs?)` (waits until queued events are sent) and `close()`
148
166
  (removes everything the SDK installed).
149
167
 
168
+ ## Page speed (RUM)
169
+
170
+ Real User Monitoring shows how fast your pages are for the people using
171
+ them: Web Vitals per page, the slow requests pages make, and single
172
+ visits. It's off by default and ships as a separate import, so apps that
173
+ don't use it don't download it (about 4.5 KB gzipped):
174
+
175
+ ```ts
176
+ import * as Collector from "@chrom-ar/collector";
177
+ import { rum } from "@chrom-ar/collector/rum";
178
+
179
+ Collector.init({ dsn: "…", rum: rum({ sampleRate: 0.1 }) });
180
+ ```
181
+
182
+ - **Sampling:** `sampleRate` is the share of browser tabs measured,
183
+ decided once per tab. A measured tab sends all its page views.
184
+ - **What's measured:** for page loads, LCP, INP, CLS, TTFB and FCP; for
185
+ in-app navigations to a new path (pushState, LiveView; a new query
186
+ string alone, like a filter or a search box, stays the same page view),
187
+ INP, CLS and a navigation
188
+ time, from the click until the page's requests have finished and the DOM
189
+ has been quiet for half a second (at most 10 s). Plus the page's fetch
190
+ and XHR calls, and for slow pages the slowest resources it loaded.
191
+ - **When it sends:** in batches, when the tab is hidden or closed, and
192
+ every 10 page views or 5 minutes while it stays open. Batches over 1 KB
193
+ are gzipped. If Collector is down or slow, page views are dropped
194
+ quietly; nothing is retried.
195
+ - **Privacy:** no cookies, no user id, no query strings or fragments. A
196
+ random id for the tab's visit, and the tab's sampling decision, are kept
197
+ in `sessionStorage` (key `collector:rum`) and end with the tab. Errors
198
+ from a measured tab carry the visit's id, so an issue links to the visit.
199
+ Collector derives the country and browser and doesn't store the IP or
200
+ user agent. Whether you need consent for analytics is your call.
201
+ - **Routes:** Collector groups pages by guessing which path segments are
202
+ ids (`/orders/81` → `/orders/:id`). If your router knows the route, say
203
+ it after each navigation:
204
+
205
+ ```ts
206
+ Collector.setRoute("/orders/:id");
207
+ ```
208
+
209
+ or pass `route: (location) => …` to `rum()`. Apps that route in the
210
+ `#hash` need this: fragments are never sent, so every page would
211
+ otherwise be `/`.
212
+ - **Editing or dropping page views:** `rum({ sampleRate, beforeSendPageview(pv) { … return pv; } })`;
213
+ return `null` to drop one.
214
+
150
215
  ## How errors are grouped
151
216
 
152
217
  Collector groups events into issues by the error type and the functions
@@ -0,0 +1,56 @@
1
+ // src/util.ts
2
+ function uuid4() {
3
+ if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
4
+ const b = crypto.getRandomValues(new Uint8Array(16));
5
+ b[6] = (b[6] ?? 0) & 15 | 64;
6
+ b[8] = (b[8] ?? 0) & 63 | 128;
7
+ const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
8
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
9
+ }
10
+ function truncate(s, max) {
11
+ if (s.length <= max) return s;
12
+ const last = s.charCodeAt(max - 1);
13
+ return s.slice(0, last >= 55296 && last <= 56319 ? max - 1 : max);
14
+ }
15
+ function safeStringify(value, max = 8192) {
16
+ return truncate(stringify(value), max);
17
+ }
18
+ function stringify(value) {
19
+ if (typeof value === "string") return value;
20
+ if (value === void 0 || typeof value === "function" || typeof value === "symbol" || typeof value === "bigint") {
21
+ return String(value);
22
+ }
23
+ const seen = /* @__PURE__ */ new WeakSet();
24
+ try {
25
+ return JSON.stringify(value, (_key, v) => {
26
+ if (typeof v === "bigint") return v.toString();
27
+ if (typeof v === "object" && v !== null) {
28
+ if (seen.has(v)) return "[Circular]";
29
+ seen.add(v);
30
+ }
31
+ return v;
32
+ });
33
+ } catch {
34
+ try {
35
+ return String(value);
36
+ } catch {
37
+ return "[unserializable]";
38
+ }
39
+ }
40
+ }
41
+ function stripUrl(url) {
42
+ const i = url.search(/[?#]/);
43
+ return i === -1 ? url : url.slice(0, i);
44
+ }
45
+ var MAX_URL = 500;
46
+ function rumUrl(base, url) {
47
+ try {
48
+ const parsed = new URL(url, base);
49
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return void 0;
50
+ return (parsed.origin + parsed.pathname).slice(0, MAX_URL);
51
+ } catch {
52
+ return void 0;
53
+ }
54
+ }
55
+
56
+ export { rumUrl, safeStringify, stripUrl, truncate, uuid4 };
package/dist/index.cjs CHANGED
@@ -11,7 +11,7 @@ function parseDsn(dsn) {
11
11
  if (parsed.protocol !== "https:" && parsed.protocol !== "http:" || parsed.username === "") return null;
12
12
  const base = parsed.origin + parsed.pathname.replace(/\/+$/, "");
13
13
  const key = parsed.username;
14
- return { url: `${base}/api/events?key=${key}`, heartbeatUrl: `${base}/api/heartbeats?key=${key}`, base, key };
14
+ return { url: `${base}/api/events?key=${key}`, heartbeatUrl: `${base}/api/heartbeats?key=${key}`, pageviewsUrl: `${base}/api/pageviews?key=${key}`, base, key };
15
15
  }
16
16
 
17
17
  // src/util.ts
@@ -58,6 +58,16 @@ function stripUrl(url) {
58
58
  const i = url.search(/[?#]/);
59
59
  return i === -1 ? url : url.slice(0, i);
60
60
  }
61
+ var MAX_URL = 500;
62
+ function rumUrl(base, url) {
63
+ try {
64
+ const parsed = new URL(url, base);
65
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return void 0;
66
+ return (parsed.origin + parsed.pathname).slice(0, MAX_URL);
67
+ } catch {
68
+ return void 0;
69
+ }
70
+ }
61
71
 
62
72
  // src/stacktrace.ts
63
73
  var MAX_FRAMES = 250;
@@ -211,7 +221,7 @@ function releaseOf(options) {
211
221
  function environmentOf(options) {
212
222
  return typeof options.environment === "string" && options.environment !== "" ? options.environment : void 0;
213
223
  }
214
- function baseEvent({ options, scope: scope2, href, userAgent }, ctx = {}) {
224
+ function baseEvent({ options, scope: scope2, href, userAgent, session }, ctx = {}) {
215
225
  const event = {
216
226
  v: 1,
217
227
  uuid: uuid4(),
@@ -219,12 +229,13 @@ function baseEvent({ options, scope: scope2, href, userAgent }, ctx = {}) {
219
229
  platform: "javascript",
220
230
  level: toLevel(ctx.level),
221
231
  request: { url: options.stripQuery === false ? href : stripUrl(href), headers: { "user-agent": userAgent } },
222
- sdk: { name: SDK_NAME, version: "0.3.0" }
232
+ sdk: { name: SDK_NAME, version: "0.4.0" }
223
233
  };
224
234
  const environment = environmentOf(options);
225
235
  if (environment !== void 0) event.environment = environment;
226
236
  const release = releaseOf(options);
227
237
  if (release !== void 0) event.release = release;
238
+ if (session !== void 0) event.session = session;
228
239
  if (ctx.fingerprint && ctx.fingerprint.length > 0) event.fingerprint = ctx.fingerprint.map(String);
229
240
  const user = ctx.user ? { id: String(ctx.user.id) } : scope2.user;
230
241
  if (user) event.user = user;
@@ -348,7 +359,7 @@ async function beat({ url, key, fetch, options, logger }) {
348
359
  if (storedMark(storageKey) === mark || sentThisPage.has(storageKey + mark)) return;
349
360
  let status;
350
361
  try {
351
- const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.3.0" }, environment, release });
362
+ const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.4.0" }, environment, release });
352
363
  const response = await fetch(url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive: true, credentials: "omit" });
353
364
  ({ status } = response);
354
365
  } catch (error) {
@@ -394,6 +405,15 @@ function displayUrl(win, url, stripQuery) {
394
405
  }
395
406
  return stripQuery ? stripUrl(shown) : shown;
396
407
  }
408
+ function timeRequest(opts, win, method, url) {
409
+ const target = opts.onRequest ? rumUrl(win.location.href, url) : void 0;
410
+ if (target === void 0) return () => void 0;
411
+ const start = performance.now();
412
+ const token = opts.onRequestStart?.();
413
+ return (status) => {
414
+ opts.onRequest?.({ method: method.toUpperCase(), url: target, status: status ?? 0, start, end: performance.now() }, token);
415
+ };
416
+ }
397
417
  function absoluteUrl(win, url) {
398
418
  try {
399
419
  return new URL(url, win.location.href).href;
@@ -504,8 +524,10 @@ function instrumentFetch(win, record, opts) {
504
524
  const { method, url } = describe2(input, init2);
505
525
  if (opts.skipUrl(absoluteUrl(win, url))) return;
506
526
  const shown = displayUrl(win, url, opts.stripQuery);
527
+ const timing = timeRequest(opts, win, method, url);
507
528
  done = (status) => {
508
529
  safeRecord(() => {
530
+ timing(status);
509
531
  record({ category: "fetch", level: levelForStatus(status), message: requestMessage(method, shown, status) });
510
532
  });
511
533
  };
@@ -547,14 +569,24 @@ function instrumentHistory(win, record, opts) {
547
569
  (original) => function __collectorWrapped(...args) {
548
570
  original.apply(this, args);
549
571
  moved();
572
+ navigated();
550
573
  }
551
574
  );
575
+ const navigated = () => {
576
+ safeRecord(() => {
577
+ opts.onNavigate?.();
578
+ });
579
+ };
580
+ const popped = () => {
581
+ moved();
582
+ navigated();
583
+ };
552
584
  const restores = [wrapState("pushState"), wrapState("replaceState")];
553
- win.addEventListener("popstate", moved);
585
+ win.addEventListener("popstate", popped);
554
586
  win.addEventListener("hashchange", moved);
555
587
  return () => {
556
588
  if (!restores.map((restore) => restore()).every(Boolean)) return false;
557
- win.removeEventListener("popstate", moved);
589
+ win.removeEventListener("popstate", popped);
558
590
  win.removeEventListener("hashchange", moved);
559
591
  return true;
560
592
  };
@@ -585,9 +617,11 @@ function instrumentXhr(win, record, opts) {
585
617
  const request = requests.get(this);
586
618
  if (!request || opts.skipUrl(absoluteUrl(win, request.url))) return;
587
619
  const shown = displayUrl(win, request.url, opts.stripQuery);
620
+ const timing = timeRequest(opts, win, request.method, request.url);
588
621
  this.addEventListener("loadend", () => {
589
622
  safeRecord(() => {
590
623
  const status = this.status !== 0 ? this.status : void 0;
624
+ timing(status);
591
625
  record({ category: "xhr", level: levelForStatus(status), message: requestMessage(request.method, shown, status) });
592
626
  });
593
627
  }, { once: true });
@@ -601,7 +635,7 @@ function instrumentXhr(win, record, opts) {
601
635
  // src/logger.ts
602
636
  function createLogger(isDebug) {
603
637
  const warned = /* @__PURE__ */ new Set();
604
- const { debug, warn } = console;
638
+ const { debug, info, warn } = console;
605
639
  return {
606
640
  debug(...args) {
607
641
  if (isDebug()) debug.call(console, "[collector]", ...args);
@@ -610,6 +644,12 @@ function createLogger(isDebug) {
610
644
  if (warned.has(message)) return;
611
645
  warned.add(message);
612
646
  warn.call(console, `[collector] ${message}`);
647
+ },
648
+ info(message) {
649
+ info.call(console, `[collector] ${message}`);
650
+ },
651
+ warn(message) {
652
+ warn.call(console, `[collector] ${message}`);
613
653
  }
614
654
  };
615
655
  }
@@ -651,6 +691,11 @@ var Scope = class {
651
691
  };
652
692
 
653
693
  // src/transport.ts
694
+ function answer(pending, result) {
695
+ const { onAnswer } = pending;
696
+ pending.onAnswer = void 0;
697
+ onAnswer?.(result);
698
+ }
654
699
  var FIRST_BACKOFF = 1e3;
655
700
  var MAX_BACKOFF = 6e4;
656
701
  var MAX_ATTEMPTS = 8;
@@ -672,14 +717,15 @@ var Transport = class {
672
717
  this.idleWaiters = [];
673
718
  this.maxQueue = deps.maxQueue ?? 30;
674
719
  }
675
- /** Queues the event. Never blocks, never throws. */
676
- send(event) {
720
+ /** Queues the event. Never blocks, never throws. `onAnswer` gets the first attempt's answer. */
721
+ send(event, onAnswer) {
677
722
  if (this.disabled) return;
678
723
  if (this.queue.length >= this.maxQueue) {
679
- this.queue.shift();
724
+ const dropped = this.queue.shift();
725
+ if (dropped) answer(dropped, { error: new Error("dropped: too many events queued") });
680
726
  this.deps.logger.debug("queue full, dropped the oldest event");
681
727
  }
682
- this.queue.push({ event, attempts: 0 });
728
+ this.queue.push({ event, attempts: 0, ...onAnswer ? { onAnswer } : {} });
683
729
  this.dispatch();
684
730
  }
685
731
  /** Resolves `true` once everything queued has been sent (or given up on), `false` after `timeoutMs`. */
@@ -729,6 +775,7 @@ var Transport = class {
729
775
  const body = encode(pending.event);
730
776
  if (body === void 0) {
731
777
  this.deps.logger.debug("dropped an event that is over 1 MB or not JSON-encodable", pending.event.uuid);
778
+ answer(pending, { error: new Error("dropped: over 1 MB or not JSON-encodable") });
732
779
  this.dispatch();
733
780
  return;
734
781
  }
@@ -761,6 +808,7 @@ var Transport = class {
761
808
  this.inFlight = false;
762
809
  this.inFlightKeepaliveBytes = 0;
763
810
  const { status } = response;
811
+ answer(pending, { status });
764
812
  if (status >= 200 && status < 300) {
765
813
  this.backoff = FIRST_BACKOFF;
766
814
  } else if (status === 429) {
@@ -785,6 +833,7 @@ var Transport = class {
785
833
  this.dispatch();
786
834
  }
787
835
  retry(pending, error) {
836
+ answer(pending, { error });
788
837
  this.inFlight = false;
789
838
  this.inFlightKeepaliveBytes = 0;
790
839
  pending.attempts += 1;
@@ -807,7 +856,7 @@ var Transport = class {
807
856
  }
808
857
  disable(status) {
809
858
  this.disabled = true;
810
- this.queue = [];
859
+ for (const pending of this.queue.splice(0)) answer(pending, { error: new Error(`dropped: Collector rejected this DSN (HTTP ${String(status)})`) });
811
860
  this.deps.onDisable?.();
812
861
  const where = this.deps.origin ?? "unknown origin";
813
862
  this.deps.logger.warnOnce(
@@ -856,14 +905,36 @@ var INSTRUMENTS = {
856
905
  history: instrumentHistory
857
906
  };
858
907
  var DEFAULT_MAX_BREADCRUMBS = 50;
908
+ var TEST_TIMEOUT_MS = 1e4;
909
+ function testFailure(result) {
910
+ if ("error" in result) {
911
+ const message = result.error instanceof Error ? result.error.message : String(result.error);
912
+ return `couldn't reach Collector (${message}). Check the DSN's host, your network, and your Content-Security-Policy's connect-src.`;
913
+ }
914
+ const { status } = result;
915
+ if (status >= 200 && status < 300) return void 0;
916
+ if (status === 401) return "Collector rejected the key (HTTP 401). Check the DSN on your project's setup page.";
917
+ if (status === 403) return "this site's domain is blocked for the project (HTTP 403). A project admin can unblock it in the project's settings.";
918
+ if (status === 429) return "Collector asked to slow down (HTTP 429). Try again in a minute.";
919
+ if (status >= 500) return `Collector had an error (HTTP ${String(status)}). The event will be retried.`;
920
+ return `Collector rejected the event (HTTP ${String(status)}).`;
921
+ }
859
922
  var active;
860
923
  var installed = /* @__PURE__ */ new Map();
861
924
  var sharedOptions = {
862
925
  skipUrl: (url) => active?.isOwnUrl(url) ?? false,
863
926
  get stripQuery() {
864
927
  return active?.options.stripQuery !== false;
928
+ },
929
+ onRequestStart: () => active?.rum?.requestStart(),
930
+ onRequest: (timing, token) => {
931
+ active?.rum?.request(timing, token);
932
+ },
933
+ onNavigate: () => {
934
+ active?.rum?.navigate();
865
935
  }
866
936
  };
937
+ var RUM_KINDS = /* @__PURE__ */ new Set(["fetch", "xhr", "history"]);
867
938
  var rejected = /* @__PURE__ */ new Set();
868
939
  var recorderFor = (kind) => (crumb) => {
869
940
  if (active && active.options.breadcrumbs?.[kind] !== false) active.addBreadcrumb(crumb);
@@ -884,15 +955,18 @@ var Client = class {
884
955
  this.ignore = [...DEFAULT_IGNORE, ...options.ignoreErrors ?? []];
885
956
  if (options.enabled === false) {
886
957
  this.logger.debug("disabled (enabled: false): nothing will be sent");
958
+ this.inactive = "the SDK is off (enabled: false).";
887
959
  return;
888
960
  }
889
961
  if (typeof options.dsn !== "string" || options.dsn === "") {
890
962
  this.logger.debug("no DSN given: nothing will be sent");
963
+ this.inactive = "no DSN given to init().";
891
964
  return;
892
965
  }
893
966
  const endpoint = parseDsn(options.dsn);
894
967
  if (!endpoint) {
895
968
  this.logger.debug("invalid DSN: nothing will be sent", options.dsn);
969
+ this.inactive = "invalid DSN. Copy it from your project's setup page.";
896
970
  return;
897
971
  }
898
972
  this.endpointBase = endpoint.base;
@@ -915,9 +989,17 @@ var Client = class {
915
989
  )
916
990
  );
917
991
  }
992
+ if (options.rum && !this.transport.disabled) {
993
+ try {
994
+ 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) });
995
+ } catch (error) {
996
+ this.logger.debug("RUM didn't start", error);
997
+ }
998
+ }
918
999
  active = this;
919
1000
  for (const [kind, instrument] of Object.entries(INSTRUMENTS)) {
920
- if (options.breadcrumbs?.[kind] === false || installed.has(kind)) continue;
1001
+ const needed = options.breadcrumbs?.[kind] !== false || this.rum !== void 0 && RUM_KINDS.has(kind);
1002
+ if (!needed || installed.has(kind)) continue;
921
1003
  try {
922
1004
  installed.set(kind, instrument(win, recorderFor(kind), sharedOptions));
923
1005
  } catch (error) {
@@ -939,12 +1021,62 @@ var Client = class {
939
1021
  const context = typeof ctx === "string" ? { level: ctx } : ctx;
940
1022
  return this.capture(() => eventFromMessage(message, this.env(), context));
941
1023
  }
1024
+ /**
1025
+ * Sends one test error to check the setup end to end. Skips the filters
1026
+ * (ignoreErrors, duplicates, the rate cap); `beforeSend` edits apply, but
1027
+ * if it drops the event the original is sent anyway.
1028
+ */
1029
+ async test() {
1030
+ const fail = (reason) => {
1031
+ this.logger.warn(`Test event not sent: ${reason}`);
1032
+ return { ok: false, reason };
1033
+ };
1034
+ const { transport } = this;
1035
+ if (this.closed) return Promise.resolve(fail("the SDK was closed."));
1036
+ if (!transport) return Promise.resolve(fail(this.inactive ?? "the SDK isn't sending."));
1037
+ if (transport.disabled) return Promise.resolve(fail("Collector already rejected this DSN on this page (HTTP 401/403)."));
1038
+ let event;
1039
+ try {
1040
+ const error = new Error("Test event from Collector.test(). If you can see it in Collector, your setup works.");
1041
+ error.name = "CollectorTest";
1042
+ throw error;
1043
+ } catch (error) {
1044
+ event = eventFromException(error, this.env(), { tags: { "collector.test": "true" }, fingerprint: ["collector.test"] });
1045
+ }
1046
+ const final = this.beforeSend(event) ?? event;
1047
+ return new Promise((resolve) => {
1048
+ let settled = false;
1049
+ const settle = (result) => {
1050
+ if (settled) return;
1051
+ settled = true;
1052
+ clearTimeout(timer);
1053
+ resolve(result);
1054
+ };
1055
+ const timer = setTimeout(() => {
1056
+ settle(fail(`no answer from Collector within ${String(TEST_TIMEOUT_MS / 1e3)} s.`));
1057
+ }, TEST_TIMEOUT_MS);
1058
+ transport.send(final, (answer2) => {
1059
+ if (settled) return;
1060
+ const reason = testFailure(answer2);
1061
+ if (reason !== void 0) {
1062
+ settle(fail(reason));
1063
+ return;
1064
+ }
1065
+ this.logger.info(`Test event sent (${"status" in answer2 ? String(answer2.status) : "?"}). Look for "CollectorTest" in your project: ${final.uuid}`);
1066
+ settle({ ok: true, id: final.uuid });
1067
+ });
1068
+ });
1069
+ }
942
1070
  addBreadcrumb(crumb) {
943
1071
  this.scope.addBreadcrumb(crumb, this.options.maxBreadcrumbs ?? DEFAULT_MAX_BREADCRUMBS);
944
1072
  }
945
1073
  async flush(timeoutMs) {
946
1074
  return this.transport ? this.transport.flush(timeoutMs) : Promise.resolve(true);
947
1075
  }
1076
+ /** Names the current RUM page view. Does nothing without RUM. */
1077
+ setRoute(name) {
1078
+ this.rum?.setRoute(name);
1079
+ }
948
1080
  /** True for requests to Collector itself. */
949
1081
  isOwnUrl(url) {
950
1082
  return this.endpointBase !== void 0 && url.startsWith(`${this.endpointBase}/`);
@@ -952,6 +1084,11 @@ var Client = class {
952
1084
  /** Removes every listener and wrapper it can. Events already queued still go out. */
953
1085
  close() {
954
1086
  this.closed = true;
1087
+ try {
1088
+ this.rum?.close();
1089
+ } catch (error) {
1090
+ this.logger.debug("RUM didn't close cleanly", error);
1091
+ }
955
1092
  if (active === this) {
956
1093
  active = void 0;
957
1094
  for (const [kind, restore] of installed) {
@@ -976,7 +1113,8 @@ var Client = class {
976
1113
  scope: this.scope,
977
1114
  origin: win.location.origin,
978
1115
  href: win.location.href,
979
- userAgent: win.navigator.userAgent
1116
+ userAgent: win.navigator.userAgent,
1117
+ session: this.rum?.session
980
1118
  };
981
1119
  }
982
1120
  capture(build) {
@@ -1022,8 +1160,9 @@ var Client = class {
1022
1160
  };
1023
1161
 
1024
1162
  // src/index.ts
1025
- var SDK_VERSION = "0.3.0";
1163
+ var SDK_VERSION = "0.4.0";
1026
1164
  var client;
1165
+ var pendingRoute;
1027
1166
  var pendingScope = new Scope();
1028
1167
  function scope() {
1029
1168
  return client?.scope ?? pendingScope;
@@ -1042,8 +1181,21 @@ function init(options) {
1042
1181
  const kept = scope();
1043
1182
  client?.close();
1044
1183
  client = new Client(options, window, kept);
1184
+ if (pendingRoute) client.setRoute(pendingRoute.name);
1185
+ pendingRoute = void 0;
1186
+ if (options.debug === true) Object.defineProperty(window, CONSOLE_HANDLE, { value: { test }, configurable: true, writable: true });
1187
+ else Reflect.deleteProperty(window, CONSOLE_HANDLE);
1045
1188
  }, void 0);
1046
1189
  }
1190
+ var CONSOLE_HANDLE = "__collector";
1191
+ async function test() {
1192
+ const notInitialized = () => {
1193
+ const reason = "init() hasn't run on this page (or this isn't a browser).";
1194
+ console.warn(`[collector] Test event not sent: ${reason}`);
1195
+ return { ok: false, reason };
1196
+ };
1197
+ return safely(async () => client ? client.test() : Promise.resolve(notInitialized()), Promise.resolve({ ok: false, reason: "internal error." }));
1198
+ }
1047
1199
  function captureException(error, context) {
1048
1200
  return safely(() => client?.captureException(error, context), void 0);
1049
1201
  }
@@ -1074,11 +1226,19 @@ function addBreadcrumb(crumb) {
1074
1226
  async function flush(timeoutMs) {
1075
1227
  return safely(async () => client?.flush(timeoutMs) ?? Promise.resolve(true), Promise.resolve(false));
1076
1228
  }
1229
+ function setRoute(name) {
1230
+ safely(() => {
1231
+ if (client) client.setRoute(name);
1232
+ else pendingRoute = { name };
1233
+ }, void 0);
1234
+ }
1077
1235
  function close() {
1078
1236
  safely(() => {
1079
1237
  client?.close();
1080
1238
  client = void 0;
1081
1239
  pendingScope = new Scope();
1240
+ pendingRoute = void 0;
1241
+ if (typeof window !== "undefined") Reflect.deleteProperty(window, CONSOLE_HANDLE);
1082
1242
  }, void 0);
1083
1243
  }
1084
1244
 
@@ -1089,6 +1249,8 @@ exports.captureMessage = captureMessage;
1089
1249
  exports.close = close;
1090
1250
  exports.flush = flush;
1091
1251
  exports.init = init;
1252
+ exports.setRoute = setRoute;
1092
1253
  exports.setTag = setTag;
1093
1254
  exports.setTags = setTags;
1094
1255
  exports.setUser = setUser;
1256
+ exports.test = test;