@chrom-ar/collector 0.3.1 → 0.5.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.d.ts CHANGED
@@ -1,120 +1,5 @@
1
- /** How bad an event is. Collector accepts exactly these four. */
2
- type Level = "fatal" | "error" | "warning" | "info";
3
- /** One stack frame, innermost first, as the protocol defines it. */
4
- interface Frame {
5
- /** Script path with content hashes removed, e.g. `/assets/index.js`. Used for grouping. */
6
- module: string;
7
- /** Function name, or `"?"` for anonymous functions. */
8
- function: string;
9
- /** Script path as loaded, e.g. `/assets/index-a1b2c3d4.js`. Shown, not grouped on. */
10
- file: string;
11
- line?: number;
12
- column?: number;
13
- /** True for the app's own code; this decides how errors group into issues. */
14
- in_app: boolean;
15
- }
16
- /** Something that happened before an error: a click, a request, a log line. */
17
- interface Breadcrumb {
18
- /** ISO 8601; set to now when missing. */
19
- timestamp?: string;
20
- level?: Level;
21
- /** e.g. `ui.click`, `fetch`, `xhr`, `navigation`, `console`. */
22
- category?: string;
23
- message: string;
24
- }
25
- /** An event as sent to Collector (protocol v1). */
26
- interface CollectorEvent {
27
- v: 1;
28
- uuid: string;
29
- timestamp: string;
30
- platform: "javascript";
31
- level: Level;
32
- environment?: string;
33
- release?: string;
34
- exception?: {
35
- type: string;
36
- message?: string;
37
- frames?: Frame[];
38
- };
39
- message?: string;
40
- fingerprint?: string[];
41
- request?: {
42
- url: string;
43
- headers: Record<string, string>;
44
- };
45
- user?: {
46
- id: string;
47
- };
48
- tags?: Record<string, string>;
49
- breadcrumbs?: Breadcrumb[];
50
- sdk: {
51
- name: string;
52
- version: string;
53
- };
54
- }
55
- /** Extra details for one captured event. They merge over what `setUser`/`setTag` set. */
56
- interface CaptureContext {
57
- level?: Level;
58
- tags?: Record<string, string>;
59
- /** Overrides how Collector groups this event into an issue. */
60
- fingerprint?: string[];
61
- user?: {
62
- id: string | number;
63
- };
64
- }
65
- /** What `test()` resolves to: the event's id, or why it wasn't accepted. */
66
- type TestResult = {
67
- ok: true;
68
- id: string;
69
- } | {
70
- ok: false;
71
- reason: string;
72
- };
73
- type BreadcrumbKind = "console" | "dom" | "fetch" | "xhr" | "history";
74
- interface CollectorOptions {
75
- /** Your project's DSN, from its setup page in Collector. Without it, nothing is sent. */
76
- dsn?: string;
77
- /** e.g. `"production"`, `"staging"`. Issues are counted per environment. */
78
- environment?: string;
79
- /** Your app's version or git sha, e.g. `"web@1.4.2"`. */
80
- release?: string;
81
- /** Logs what the SDK does to the console, prefixed `[collector]`. Default `false`. */
82
- debug?: boolean;
83
- /** Set to `false` to turn the SDK off entirely. Default `true`. */
84
- enabled?: boolean;
85
- /**
86
- * Last chance to edit or drop an event before it's sent. Return the event
87
- * (changed or not) to send it, or `null` to drop it.
88
- */
89
- beforeSend?: (event: CollectorEvent) => CollectorEvent | null;
90
- /**
91
- * Errors to ignore: strings match anywhere in `"Type: message"`, regexps are
92
- * tested against it. Added to the built-in list of well-known browser noise.
93
- */
94
- ignoreErrors?: (string | RegExp)[];
95
- /**
96
- * Which script URLs are your app's own code. When set, a frame is in-app only
97
- * if its URL matches. Default: same origin as the page, except vendor chunks.
98
- */
99
- inAppUrls?: (string | RegExp)[];
100
- /** Remove `?query` and `#hash` from URLs sent to Collector. Default `true`. */
101
- stripQuery?: boolean;
102
- /** Which breadcrumbs to record automatically. All on by default. */
103
- breadcrumbs?: Partial<Record<BreadcrumbKind, boolean>>;
104
- /** How many breadcrumbs to keep. Default `50`. */
105
- maxBreadcrumbs?: number;
106
- /**
107
- * Tell Collector once a day that the app is running (its release and
108
- * environment, nothing about the user), so it shows as set up before any
109
- * error. Default `true`.
110
- */
111
- heartbeat?: boolean;
112
- /** Report uncaught errors and unhandled promise rejections. Default: both on. */
113
- autoCapture?: false | {
114
- onerror?: boolean;
115
- onunhandledrejection?: boolean;
116
- };
117
- }
1
+ import { B as Breadcrumb, C as CaptureContext, L as Level, a as CollectorOptions, T as TestResult } from './types-ml-o_-mr.js';
2
+ export { b as BreadcrumbKind, c as CollectorEvent, F as Frame, R as RequestTiming, d as RumContext, e as RumHandle, f as RumPlugin } from './types-ml-o_-mr.js';
118
3
 
119
4
  /** The version of this SDK, as sent in every event's `sdk.version`. */
120
5
  declare const SDK_VERSION: string;
@@ -128,10 +13,14 @@ declare const SDK_VERSION: string;
128
13
  * Collector.init({ dsn: "https://clt_…@app.clt.chrom.ar" });
129
14
  * ```
130
15
  *
16
+ * Without options, it reads them from the page's meta tags:
17
+ * `<meta name="collector-dsn">`, `collector-environment` and
18
+ * `collector-release`. Options you pass win over the tags.
19
+ *
131
20
  * Without a `dsn`, nothing is captured or sent. Calling it again replaces the
132
21
  * options. Safe to import during server-side rendering: it does nothing there.
133
22
  */
134
- declare function init(options: CollectorOptions): void;
23
+ declare function init(options?: CollectorOptions): void;
135
24
  /**
136
25
  * Sends one test error, to check your setup end to end. Resolves to
137
26
  * `{ ok: true, id }` once Collector accepts it, or `{ ok: false, reason }`,
@@ -146,7 +35,10 @@ declare function test(): Promise<TestResult>;
146
35
  declare function captureException(error: unknown, context?: CaptureContext): string | undefined;
147
36
  /** Reports something that isn't an error: `captureMessage("Payment slow", "warning")`. */
148
37
  declare function captureMessage(message: string, context?: CaptureContext | Level): string | undefined;
149
- /** Attaches your user's id to the following events. An id, not personal data. `null` clears it. */
38
+ /**
39
+ * Attaches your user's id to the following events. An id, not personal data. `null` clears it.
40
+ * From then on, the `collector-user` meta tag is ignored.
41
+ */
150
42
  declare function setUser(user: {
151
43
  id: string | number;
152
44
  } | null): void;
@@ -158,8 +50,13 @@ declare function setTags(tags: Record<string, string>): void;
158
50
  declare function addBreadcrumb(crumb: Breadcrumb): void;
159
51
  /** Waits until queued events are sent. Resolves `false` if `timeoutMs` (default 2000) passes first. */
160
52
  declare function flush(timeoutMs?: number): Promise<boolean>;
53
+ /**
54
+ * Names the current page for RUM, e.g. `setRoute("/products/:id")`, so
55
+ * pages group by route instead of by Collector's guess. Call it after the
56
+ * URL changes; it names that page view only. Does nothing without RUM.
57
+ */
58
+ declare function setRoute(name: string | undefined): void;
161
59
  /** Stops capturing and removes everything the SDK installed. */
162
60
  declare function close(): void;
163
61
 
164
- export { SDK_VERSION, addBreadcrumb, captureException, captureMessage, close, flush, init, setTag, setTags, setUser, test };
165
- export type { Breadcrumb, BreadcrumbKind, CaptureContext, CollectorEvent, CollectorOptions, Frame, Level, TestResult };
62
+ export { Breadcrumb, CaptureContext, CollectorOptions, Level, SDK_VERSION, TestResult, addBreadcrumb, captureException, captureMessage, close, flush, init, setRoute, setTag, setTags, setUser, test };
package/dist/index.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { readMeta, truncate, safeStringify, stripUrl, uuid4, rumUrl } from './chunk-42XODVHT.js';
2
+
1
3
  // src/dsn.ts
2
4
  function parseDsn(dsn) {
3
5
  let parsed;
@@ -9,53 +11,12 @@ 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 };
14
+ return { url: `${base}/api/events?key=${key}`, heartbeatUrl: `${base}/api/heartbeats?key=${key}`, pageviewsUrl: `${base}/api/pageviews?key=${key}`, base, key };
13
15
  }
14
16
 
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);
58
- }
17
+ // src/self.ts
18
+ var file;
19
+ var sdkFile = () => file;
59
20
 
60
21
  // src/stacktrace.ts
61
22
  var MAX_FRAMES = 250;
@@ -142,7 +103,7 @@ function toFrames(raw, opts) {
142
103
  }
143
104
  return frames;
144
105
  }
145
- function toFrame(raw, { origin, inAppUrls }) {
106
+ function toFrame(raw, { origin, inAppUrls, classify, sdkFile: sdkFile2 }) {
146
107
  let url;
147
108
  try {
148
109
  url = new URL(raw.url, origin);
@@ -151,10 +112,16 @@ function toFrame(raw, { origin, inAppUrls }) {
151
112
  }
152
113
  const webpackInternal = raw.url.startsWith("webpack-internal://");
153
114
  const sameOrigin = url?.origin === origin || webpackInternal;
154
- let file = stripUrl(raw.url);
155
- if (url && !webpackInternal) file = sameOrigin ? url.pathname : stripUrl(url.href);
156
- const inApp = inAppUrls ? inAppUrls.some((p) => typeof p === "string" ? raw.url.includes(p) : p.test(raw.url)) : sameOrigin && !isExtensionUrl(raw.url) && !VENDOR_PATTERNS.some((p) => p.test(file));
157
- const frame = { module: normalizeModule(file), function: raw.function ?? "?", file, in_app: inApp };
115
+ let file2 = stripUrl(raw.url);
116
+ if (url && !webpackInternal) file2 = sameOrigin ? url.pathname : stripUrl(url.href);
117
+ const inApp = isInApp();
118
+ function isInApp() {
119
+ if (inAppUrls) return inAppUrls.some((p) => typeof p === "string" ? raw.url.includes(p) : p.test(raw.url));
120
+ const verdict = url === void 0 ? void 0 : classify?.(url.href);
121
+ if (verdict !== void 0) return verdict === "app";
122
+ return sameOrigin && !isExtensionUrl(raw.url) && !VENDOR_PATTERNS.some((p) => p.test(file2));
123
+ }
124
+ const frame = { module: normalizeModule(file2), function: raw.function ?? "?", file: file2, in_app: inApp };
158
125
  if (raw.line !== void 0) frame.line = raw.line;
159
126
  if (raw.column !== void 0) frame.column = raw.column;
160
127
  return frame;
@@ -183,7 +150,7 @@ function errorType(error) {
183
150
  function eventFromException(error, env, ctx, mechanism = "manual") {
184
151
  const event = baseEvent(env, ctx);
185
152
  if (isErrorLike(error)) {
186
- const frames = typeof error.stack === "string" ? toFrames(parseStack(error.stack), { origin: env.origin, inAppUrls: env.options.inAppUrls }) : [];
153
+ const frames = typeof error.stack === "string" ? toFrames(parseStack(error.stack), { origin: env.origin, inAppUrls: env.options.inAppUrls, classify: env.classify, sdkFile: sdkFile() }) : [];
187
154
  event.exception = { type: errorType(error), message: truncate(String(error.message), MAX_MESSAGE) };
188
155
  if (frames.length > 0) event.exception.frames = frames;
189
156
  } else {
@@ -209,7 +176,7 @@ function releaseOf(options) {
209
176
  function environmentOf(options) {
210
177
  return typeof options.environment === "string" && options.environment !== "" ? options.environment : void 0;
211
178
  }
212
- function baseEvent({ options, scope: scope2, href, userAgent }, ctx = {}) {
179
+ function baseEvent({ options, scope: scope2, href, userAgent, session }, ctx = {}) {
213
180
  const event = {
214
181
  v: 1,
215
182
  uuid: uuid4(),
@@ -217,12 +184,13 @@ function baseEvent({ options, scope: scope2, href, userAgent }, ctx = {}) {
217
184
  platform: "javascript",
218
185
  level: toLevel(ctx.level),
219
186
  request: { url: options.stripQuery === false ? href : stripUrl(href), headers: { "user-agent": userAgent } },
220
- sdk: { name: SDK_NAME, version: "0.3.1" }
187
+ sdk: { name: SDK_NAME, version: "0.5.0" }
221
188
  };
222
189
  const environment = environmentOf(options);
223
190
  if (environment !== void 0) event.environment = environment;
224
191
  const release = releaseOf(options);
225
192
  if (release !== void 0) event.release = release;
193
+ if (session !== void 0) event.session = session;
226
194
  if (ctx.fingerprint && ctx.fingerprint.length > 0) event.fingerprint = ctx.fingerprint.map(String);
227
195
  const user = ctx.user ? { id: String(ctx.user.id) } : scope2.user;
228
196
  if (user) event.user = user;
@@ -313,6 +281,45 @@ function errorFromLocation(e) {
313
281
  return error;
314
282
  }
315
283
 
284
+ // src/importmap.ts
285
+ var isBare = (specifier) => !/^(?:\.{0,2}\/|[a-z][a-z\d+.-]*:)/i.test(specifier);
286
+ function pinsOf(doc) {
287
+ const script = doc.querySelector('script[type="importmap"]');
288
+ const text = script?.textContent;
289
+ if (text === void 0 || text === "") return void 0;
290
+ let map;
291
+ try {
292
+ map = JSON.parse(text);
293
+ } catch {
294
+ return void 0;
295
+ }
296
+ const imports = typeof map === "object" && map !== null && "imports" in map ? map.imports : void 0;
297
+ if (typeof imports !== "object" || imports === null) return void 0;
298
+ const pins = [];
299
+ for (const [specifier, target] of Object.entries(imports)) {
300
+ if (typeof target !== "string" || !isBare(specifier)) continue;
301
+ try {
302
+ pins.push({ specifier, url: stripUrl(new URL(target, doc.baseURI).href), prefix: specifier.endsWith("/") });
303
+ } catch {
304
+ }
305
+ }
306
+ return pins.sort((a, b) => a.prefix === b.prefix ? b.url.length - a.url.length : Number(a.prefix) - Number(b.prefix));
307
+ }
308
+ var listed = (list, specifier) => list.some((entry) => entry === specifier || entry.endsWith("/") && specifier.startsWith(entry));
309
+ function importMapClassifier(doc, origin) {
310
+ const pins = pinsOf(doc);
311
+ if (!pins || pins.length === 0) return void 0;
312
+ const own = readMeta("collector-in-app")?.split(/[\s,]+/).filter((entry) => entry !== "");
313
+ return (url) => {
314
+ const clean = stripUrl(url);
315
+ const pin = pins.find((p) => p.prefix ? clean.startsWith(p.url) : clean === p.url);
316
+ if (!pin) return void 0;
317
+ const specifier = pin.prefix ? pin.specifier + clean.slice(pin.url.length) : pin.specifier;
318
+ if (own) return listed(own, specifier) ? "app" : "dependency";
319
+ return specifier.startsWith("@") || !pin.url.startsWith(`${origin}/`) ? "dependency" : void 0;
320
+ };
321
+ }
322
+
316
323
  // src/heartbeat.ts
317
324
  var HEARTBEAT_DELAY_MS = 5e3;
318
325
  var STORAGE_PREFIX = "collector:heartbeat:";
@@ -346,7 +353,7 @@ async function beat({ url, key, fetch, options, logger }) {
346
353
  if (storedMark(storageKey) === mark || sentThisPage.has(storageKey + mark)) return;
347
354
  let status;
348
355
  try {
349
- const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.3.1" }, environment, release });
356
+ const body = JSON.stringify({ v: 1, sdk: { name: SDK_NAME, version: "0.5.0" }, environment, release });
350
357
  const response = await fetch(url, { method: "POST", body, headers: { "Content-Type": "text/plain;charset=UTF-8" }, keepalive: true, credentials: "omit" });
351
358
  ({ status } = response);
352
359
  } catch (error) {
@@ -361,6 +368,33 @@ async function beat({ url, key, fetch, options, logger }) {
361
368
  }
362
369
  }
363
370
 
371
+ // src/describe.ts
372
+ var MAX_KEYS = 10;
373
+ var MAX_STRING = 100;
374
+ function describeValue(value, nested = false) {
375
+ if (typeof value === "string") return nested ? JSON.stringify(truncate(value, MAX_STRING)) : value;
376
+ if (value === null || typeof value !== "object") {
377
+ return typeof value === "function" ? `[Function ${value.name !== "" ? value.name : "anonymous"}]` : String(value);
378
+ }
379
+ const v = value;
380
+ if (value instanceof Error || typeof v.message === "string" && typeof v.name === "string") {
381
+ return `${String(v.name)}: ${String(v.message)}`;
382
+ }
383
+ if (typeof v.nodeType === "number") return typeof v.tagName === "string" ? `<${v.tagName.toLowerCase()}>` : "[Node]";
384
+ if (nested) return Array.isArray(value) ? `[Array(${String(value.length)})]` : "{\u2026}";
385
+ if (Array.isArray(value)) {
386
+ const items = value.slice(0, MAX_KEYS).map((x) => describeValue(x, true));
387
+ return `[${items.join(", ")}${value.length > MAX_KEYS ? ", \u2026" : ""}]`;
388
+ }
389
+ try {
390
+ const keys = Object.keys(value);
391
+ const shown = keys.slice(0, MAX_KEYS).map((k) => `${k}: ${describeValue(value[k], true)}`);
392
+ return `{${shown.join(", ")}${keys.length > MAX_KEYS ? ", \u2026" : ""}}`;
393
+ } catch {
394
+ return "{\u2026}";
395
+ }
396
+ }
397
+
364
398
  // src/instrument/common.ts
365
399
  var ORIGINAL = "__collector_original__";
366
400
  function wrap(obj, name, make) {
@@ -392,6 +426,15 @@ function displayUrl(win, url, stripQuery) {
392
426
  }
393
427
  return stripQuery ? stripUrl(shown) : shown;
394
428
  }
429
+ function timeRequest(opts, win, method, url) {
430
+ const target = opts.onRequest ? rumUrl(win.location.href, url) : void 0;
431
+ if (target === void 0) return () => void 0;
432
+ const start = performance.now();
433
+ const token = opts.onRequestStart?.();
434
+ return (status) => {
435
+ opts.onRequest?.({ method: method.toUpperCase(), url: target, status: status ?? 0, start, end: performance.now() }, token);
436
+ };
437
+ }
395
438
  function absoluteUrl(win, url) {
396
439
  try {
397
440
  return new URL(url, win.location.href).href;
@@ -409,31 +452,6 @@ function requestMessage(method, url, status) {
409
452
 
410
453
  // src/instrument/console.ts
411
454
  var LEVELS2 = { error: "error", warn: "warning", log: "info", info: "info" };
412
- var MAX_KEYS = 10;
413
- var MAX_STRING = 100;
414
- function describeValue(value, nested = false) {
415
- if (typeof value === "string") return nested ? JSON.stringify(truncate(value, MAX_STRING)) : value;
416
- if (value === null || typeof value !== "object") {
417
- return typeof value === "function" ? `[Function ${value.name !== "" ? value.name : "anonymous"}]` : String(value);
418
- }
419
- const v = value;
420
- if (value instanceof Error || typeof v.message === "string" && typeof v.name === "string") {
421
- return `${String(v.name)}: ${String(v.message)}`;
422
- }
423
- if (typeof v.nodeType === "number") return typeof v.tagName === "string" ? `<${v.tagName.toLowerCase()}>` : "[Node]";
424
- if (nested) return Array.isArray(value) ? `[Array(${String(value.length)})]` : "{\u2026}";
425
- if (Array.isArray(value)) {
426
- const items = value.slice(0, MAX_KEYS).map((x) => describeValue(x, true));
427
- return `[${items.join(", ")}${value.length > MAX_KEYS ? ", \u2026" : ""}]`;
428
- }
429
- try {
430
- const keys = Object.keys(value);
431
- const shown = keys.slice(0, MAX_KEYS).map((k) => `${k}: ${describeValue(value[k], true)}`);
432
- return `{${shown.join(", ")}${keys.length > MAX_KEYS ? ", \u2026" : ""}}`;
433
- } catch {
434
- return "{\u2026}";
435
- }
436
- }
437
455
  function instrumentConsole(win, record, _opts) {
438
456
  const target = win.console;
439
457
  const restores = Object.keys(LEVELS2).map(
@@ -502,8 +520,10 @@ function instrumentFetch(win, record, opts) {
502
520
  const { method, url } = describe2(input, init2);
503
521
  if (opts.skipUrl(absoluteUrl(win, url))) return;
504
522
  const shown = displayUrl(win, url, opts.stripQuery);
523
+ const timing = timeRequest(opts, win, method, url);
505
524
  done = (status) => {
506
525
  safeRecord(() => {
526
+ timing(status);
507
527
  record({ category: "fetch", level: levelForStatus(status), message: requestMessage(method, shown, status) });
508
528
  });
509
529
  };
@@ -545,14 +565,24 @@ function instrumentHistory(win, record, opts) {
545
565
  (original) => function __collectorWrapped(...args) {
546
566
  original.apply(this, args);
547
567
  moved();
568
+ navigated();
548
569
  }
549
570
  );
571
+ const navigated = () => {
572
+ safeRecord(() => {
573
+ opts.onNavigate?.();
574
+ });
575
+ };
576
+ const popped = () => {
577
+ moved();
578
+ navigated();
579
+ };
550
580
  const restores = [wrapState("pushState"), wrapState("replaceState")];
551
- win.addEventListener("popstate", moved);
581
+ win.addEventListener("popstate", popped);
552
582
  win.addEventListener("hashchange", moved);
553
583
  return () => {
554
584
  if (!restores.map((restore) => restore()).every(Boolean)) return false;
555
- win.removeEventListener("popstate", moved);
585
+ win.removeEventListener("popstate", popped);
556
586
  win.removeEventListener("hashchange", moved);
557
587
  return true;
558
588
  };
@@ -583,9 +613,11 @@ function instrumentXhr(win, record, opts) {
583
613
  const request = requests.get(this);
584
614
  if (!request || opts.skipUrl(absoluteUrl(win, request.url))) return;
585
615
  const shown = displayUrl(win, request.url, opts.stripQuery);
616
+ const timing = timeRequest(opts, win, request.method, request.url);
586
617
  this.addEventListener("loadend", () => {
587
618
  safeRecord(() => {
588
619
  const status = this.status !== 0 ? this.status : void 0;
620
+ timing(status);
589
621
  record({ category: "xhr", level: levelForStatus(status), message: requestMessage(request.method, shown, status) });
590
622
  });
591
623
  }, { once: true });
@@ -889,8 +921,16 @@ var sharedOptions = {
889
921
  skipUrl: (url) => active?.isOwnUrl(url) ?? false,
890
922
  get stripQuery() {
891
923
  return active?.options.stripQuery !== false;
924
+ },
925
+ onRequestStart: () => active?.rum?.requestStart(),
926
+ onRequest: (timing, token) => {
927
+ active?.rum?.request(timing, token);
928
+ },
929
+ onNavigate: () => {
930
+ active?.rum?.navigate();
892
931
  }
893
932
  };
933
+ var RUM_KINDS = /* @__PURE__ */ new Set(["fetch", "xhr", "history"]);
894
934
  var rejected = /* @__PURE__ */ new Set();
895
935
  var recorderFor = (kind) => (crumb) => {
896
936
  if (active && active.options.breadcrumbs?.[kind] !== false) active.addBreadcrumb(crumb);
@@ -945,9 +985,17 @@ var Client = class {
945
985
  )
946
986
  );
947
987
  }
988
+ if (options.rum && !this.transport.disabled) {
989
+ try {
990
+ this.rum = options.rum.start({ win, url: endpoint.pageviewsUrl, fetch: fetchFn, logger: this.logger, options, sdk: { name: SDK_NAME, version: "0.5.0" }, environment: environmentOf(options), release: releaseOf(options) });
991
+ } catch (error) {
992
+ this.logger.debug("RUM didn't start", error);
993
+ }
994
+ }
948
995
  active = this;
949
996
  for (const [kind, instrument] of Object.entries(INSTRUMENTS)) {
950
- if (options.breadcrumbs?.[kind] === false || installed.has(kind)) continue;
997
+ const needed = options.breadcrumbs?.[kind] !== false || this.rum !== void 0 && RUM_KINDS.has(kind);
998
+ if (!needed || installed.has(kind)) continue;
951
999
  try {
952
1000
  installed.set(kind, instrument(win, recorderFor(kind), sharedOptions));
953
1001
  } catch (error) {
@@ -1021,6 +1069,10 @@ var Client = class {
1021
1069
  async flush(timeoutMs) {
1022
1070
  return this.transport ? this.transport.flush(timeoutMs) : Promise.resolve(true);
1023
1071
  }
1072
+ /** Names the current RUM page view. Does nothing without RUM. */
1073
+ setRoute(name) {
1074
+ this.rum?.setRoute(name);
1075
+ }
1024
1076
  /** True for requests to Collector itself. */
1025
1077
  isOwnUrl(url) {
1026
1078
  return this.endpointBase !== void 0 && url.startsWith(`${this.endpointBase}/`);
@@ -1028,6 +1080,11 @@ var Client = class {
1028
1080
  /** Removes every listener and wrapper it can. Events already queued still go out. */
1029
1081
  close() {
1030
1082
  this.closed = true;
1083
+ try {
1084
+ this.rum?.close();
1085
+ } catch (error) {
1086
+ this.logger.debug("RUM didn't close cleanly", error);
1087
+ }
1031
1088
  if (active === this) {
1032
1089
  active = void 0;
1033
1090
  for (const [kind, restore] of installed) {
@@ -1047,12 +1104,15 @@ var Client = class {
1047
1104
  }
1048
1105
  env() {
1049
1106
  const { win } = this;
1107
+ this.classify ?? (this.classify = { fn: importMapClassifier(win.document, win.location.origin) });
1050
1108
  return {
1051
1109
  options: this.options,
1052
1110
  scope: this.scope,
1053
1111
  origin: win.location.origin,
1054
1112
  href: win.location.href,
1055
- userAgent: win.navigator.userAgent
1113
+ userAgent: win.navigator.userAgent,
1114
+ session: this.rum?.session,
1115
+ classify: this.classify.fn
1056
1116
  };
1057
1117
  }
1058
1118
  capture(build) {
@@ -1098,9 +1158,12 @@ var Client = class {
1098
1158
  };
1099
1159
 
1100
1160
  // src/index.ts
1101
- var SDK_VERSION = "0.3.1";
1161
+ var SDK_VERSION = "0.5.0";
1102
1162
  var client;
1163
+ var pendingRoute;
1103
1164
  var pendingScope = new Scope();
1165
+ var userFromApp = false;
1166
+ var stopPageListener;
1104
1167
  function scope() {
1105
1168
  return client?.scope ?? pendingScope;
1106
1169
  }
@@ -1112,17 +1175,43 @@ function safely(fn, fallback) {
1112
1175
  return fallback;
1113
1176
  }
1114
1177
  }
1115
- function init(options) {
1178
+ function init(options = {}) {
1116
1179
  safely(() => {
1117
1180
  if (typeof window === "undefined") return;
1118
1181
  const kept = scope();
1119
1182
  client?.close();
1120
- client = new Client(options, window, kept);
1183
+ stopPageListener?.();
1184
+ client = new Client(withMeta(options), window, kept);
1185
+ userFromMeta();
1186
+ const onPageLoad = () => {
1187
+ safely(userFromMeta, void 0);
1188
+ };
1189
+ document.addEventListener("turbo:load", onPageLoad);
1190
+ stopPageListener = () => {
1191
+ document.removeEventListener("turbo:load", onPageLoad);
1192
+ };
1193
+ if (pendingRoute) client.setRoute(pendingRoute.name);
1194
+ pendingRoute = void 0;
1121
1195
  if (options.debug === true) Object.defineProperty(window, CONSOLE_HANDLE, { value: { test }, configurable: true, writable: true });
1122
1196
  else Reflect.deleteProperty(window, CONSOLE_HANDLE);
1123
1197
  }, void 0);
1124
1198
  }
1125
1199
  var CONSOLE_HANDLE = "__collector";
1200
+ function withMeta(options) {
1201
+ const resolved = { ...options };
1202
+ const dsn = options.dsn ?? readMeta("collector-dsn");
1203
+ const environment = options.environment ?? readMeta("collector-environment");
1204
+ const release = options.release ?? readMeta("collector-release");
1205
+ if (dsn !== void 0) resolved.dsn = dsn;
1206
+ if (environment !== void 0) resolved.environment = environment;
1207
+ if (release !== void 0) resolved.release = release;
1208
+ return resolved;
1209
+ }
1210
+ function userFromMeta() {
1211
+ if (userFromApp) return;
1212
+ const id = readMeta("collector-user");
1213
+ scope().setUser(id === void 0 ? null : { id });
1214
+ }
1126
1215
  async function test() {
1127
1216
  const notInitialized = () => {
1128
1217
  const reason = "init() hasn't run on this page (or this isn't a browser).";
@@ -1139,6 +1228,7 @@ function captureMessage(message, context) {
1139
1228
  }
1140
1229
  function setUser(user) {
1141
1230
  safely(() => {
1231
+ userFromApp = true;
1142
1232
  scope().setUser(user);
1143
1233
  }, void 0);
1144
1234
  }
@@ -1161,13 +1251,23 @@ function addBreadcrumb(crumb) {
1161
1251
  async function flush(timeoutMs) {
1162
1252
  return safely(async () => client?.flush(timeoutMs) ?? Promise.resolve(true), Promise.resolve(false));
1163
1253
  }
1254
+ function setRoute(name) {
1255
+ safely(() => {
1256
+ if (client) client.setRoute(name);
1257
+ else pendingRoute = { name };
1258
+ }, void 0);
1259
+ }
1164
1260
  function close() {
1165
1261
  safely(() => {
1166
1262
  client?.close();
1167
1263
  client = void 0;
1264
+ stopPageListener?.();
1265
+ stopPageListener = void 0;
1168
1266
  pendingScope = new Scope();
1267
+ pendingRoute = void 0;
1268
+ userFromApp = false;
1169
1269
  if (typeof window !== "undefined") Reflect.deleteProperty(window, CONSOLE_HANDLE);
1170
1270
  }, void 0);
1171
1271
  }
1172
1272
 
1173
- export { SDK_VERSION, addBreadcrumb, captureException, captureMessage, close, flush, init, setTag, setTags, setUser, test };
1273
+ export { SDK_VERSION, addBreadcrumb, captureException, captureMessage, close, flush, init, setRoute, setTag, setTags, setUser, test };