@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/rum.d.ts ADDED
@@ -0,0 +1,57 @@
1
+ import { RumPlugin } from './index.js';
2
+
3
+ /** A page view as sent to Collector (protocol v1, "Page views"). */
4
+ interface PageView {
5
+ id: string;
6
+ /** ISO 8601, when it started. */
7
+ at: string;
8
+ /** The path only: no query or fragment. */
9
+ path: string;
10
+ route?: string;
11
+ navigation: "hard" | "soft";
12
+ vitals?: {
13
+ lcp?: number;
14
+ inp?: number;
15
+ cls?: number;
16
+ ttfb?: number;
17
+ fcp?: number;
18
+ nav?: number;
19
+ };
20
+ requests?: {
21
+ method: string;
22
+ url: string;
23
+ status: number;
24
+ start: number;
25
+ duration: number;
26
+ }[];
27
+ waterfall?: {
28
+ name: string;
29
+ type: string;
30
+ start: number;
31
+ duration: number;
32
+ size?: number;
33
+ }[];
34
+ }
35
+
36
+ interface RumOptions {
37
+ /** Share of tabs to measure, `0 < sampleRate ≤ 1`, decided once per tab. `0.1` is a good start. */
38
+ sampleRate: number;
39
+ /** Your app's route name for a URL, e.g. `/products/:id`. `setRoute()` wins over it. */
40
+ route?: (location: Location) => string | undefined;
41
+ /** Last chance to edit or drop a page view: return it, changed or not, or `null`. */
42
+ beforeSendPageview?: (pageview: PageView) => PageView | null;
43
+ }
44
+ /**
45
+ * Real User Monitoring: how fast your pages are for the people using them.
46
+ *
47
+ * ```ts
48
+ * import * as Collector from "@chrom-ar/collector";
49
+ * import { rum } from "@chrom-ar/collector/rum";
50
+ *
51
+ * Collector.init({ dsn: "…", rum: rum({ sampleRate: 0.1 }) });
52
+ * ```
53
+ */
54
+ declare function rum(options: RumOptions): RumPlugin;
55
+
56
+ export { rum };
57
+ export type { PageView, RumOptions };
package/dist/rum.js ADDED
@@ -0,0 +1,591 @@
1
+ import { uuid4, stripUrl, rumUrl } from './chunk-YN5N3X7X.js';
2
+
3
+ // src/rum/pageviews.ts
4
+ var QUIET_MS = 500;
5
+ var NAV_CAP_MS = 1e4;
6
+ var CLICK_WINDOW_MS = 1e3;
7
+ var MAX_REQUESTS = 50;
8
+ var MAX_WATERFALL = 30;
9
+ var MAX_RESOURCES = 300;
10
+ var POOR = { lcp: 4e3, inp: 500, nav: 2500 };
11
+ var keyOf = () => location.pathname;
12
+ var Tracker = class {
13
+ constructor(options) {
14
+ this.options = options;
15
+ this.finished = [];
16
+ this.lastKey = keyOf();
17
+ this.lastClick = -Infinity;
18
+ this.closed = false;
19
+ this.resources = [];
20
+ this.cleanups = [];
21
+ if (options.first) {
22
+ this.current = this.begin("hard", 0);
23
+ if (options.hardId !== void 0) this.current.id = options.hardId;
24
+ }
25
+ const onClick = () => {
26
+ this.lastClick = performance.now();
27
+ };
28
+ const onShow = (event) => {
29
+ if (event.persisted) this.next(performance.now());
30
+ };
31
+ document.addEventListener("click", onClick, true);
32
+ window.addEventListener("pageshow", onShow);
33
+ this.cleanups.push(() => {
34
+ document.removeEventListener("click", onClick, true);
35
+ window.removeEventListener("pageshow", onShow);
36
+ });
37
+ try {
38
+ if (typeof PerformanceObserver !== "undefined" && PerformanceObserver.supportedEntryTypes.includes("resource")) {
39
+ const observer = new PerformanceObserver((list) => {
40
+ for (const e of list.getEntries()) {
41
+ this.resources.push({ name: e.name, type: e.initiatorType, start: e.startTime, duration: e.duration, size: e.transferSize });
42
+ }
43
+ if (this.resources.length > MAX_RESOURCES) this.resources.splice(0, this.resources.length - MAX_RESOURCES);
44
+ });
45
+ observer.observe({ type: "resource", buffered: true });
46
+ this.cleanups.push(() => {
47
+ observer.disconnect();
48
+ });
49
+ }
50
+ } catch {
51
+ }
52
+ }
53
+ /** The URL may have changed: a new path or query starts a soft page view. */
54
+ navigate() {
55
+ if (this.closed || keyOf() === this.lastKey) return;
56
+ const now = performance.now();
57
+ const click = this.lastClick >= (this.current?.start ?? -Infinity) && now - this.lastClick <= CLICK_WINDOW_MS ? this.lastClick : now;
58
+ this.lastClick = -Infinity;
59
+ this.next(click);
60
+ }
61
+ /** A request started on the current page view; pass the result back to `request()`. */
62
+ requestStart() {
63
+ if (this.current) this.current.pending += 1;
64
+ return this.current;
65
+ }
66
+ /** A request ended. It belongs to the page view it started in, if that hasn't been handed over. */
67
+ request(timing, token) {
68
+ const lives = [this.current, ...this.finished].filter((p) => p !== void 0);
69
+ const owner = token === void 0 ? lives.filter((p) => p.start <= timing.start).sort((a, b) => b.start - a.start)[0] : lives.find((p) => p === token);
70
+ if (!owner) return;
71
+ owner.pending = Math.max(0, owner.pending - 1);
72
+ if (owner.requests.length < MAX_REQUESTS) owner.requests.push(timing);
73
+ if (owner === this.current) this.settle?.();
74
+ }
75
+ setRoute(name) {
76
+ if (this.current) this.current.route = name === void 0 ? void 0 : stripUrl(name);
77
+ }
78
+ /** The id of the page view in progress, if any. */
79
+ currentId() {
80
+ return this.current?.id;
81
+ }
82
+ /** How many finished page views are waiting to be sent. */
83
+ finishedCount() {
84
+ return this.finished.length;
85
+ }
86
+ /** Finished page views, handed over once. */
87
+ takeFinished() {
88
+ const taken = this.finished.splice(0).map((live) => this.toPageView(live));
89
+ if (taken.length > 0 && this.current) this.options.vitals()?.prune(this.current.start);
90
+ return taken;
91
+ }
92
+ /** Finished page views plus the current one, which may be sent again later. */
93
+ snapshot() {
94
+ const all = [...this.finished, ...this.current ? [this.current] : []];
95
+ return all.map((live) => this.toPageView(live));
96
+ }
97
+ close() {
98
+ this.closed = true;
99
+ this.settle = void 0;
100
+ for (const cleanup of this.cleanups.splice(0)) cleanup();
101
+ }
102
+ next(start2) {
103
+ if (this.closed) return;
104
+ if (this.current) {
105
+ this.current.end = start2;
106
+ this.finished.push(this.current);
107
+ }
108
+ this.current = this.begin("soft", start2);
109
+ this.watch(this.current);
110
+ }
111
+ begin(navigation, start2) {
112
+ this.lastKey = keyOf();
113
+ let route;
114
+ try {
115
+ route = this.options.route?.(location);
116
+ } catch {
117
+ }
118
+ return { id: uuid4(), key: this.lastKey, path: location.pathname, navigation, start: start2, route: route === void 0 ? void 0 : stripUrl(route), requests: [], pending: 0 };
119
+ }
120
+ /** Measures how long an in-app navigation takes to settle. */
121
+ watch(live) {
122
+ this.settle?.();
123
+ let last = live.start;
124
+ let quiet;
125
+ let observer;
126
+ const done = (nav) => {
127
+ clearTimeout(quiet);
128
+ clearTimeout(cap);
129
+ observer?.disconnect();
130
+ if (this.settle === activity) this.settle = void 0;
131
+ live.nav = Math.round(nav);
132
+ };
133
+ const check = () => {
134
+ if (live.pending === 0) done(last - live.start);
135
+ };
136
+ const activity = () => {
137
+ last = performance.now();
138
+ clearTimeout(quiet);
139
+ quiet = setTimeout(check, QUIET_MS);
140
+ };
141
+ const cap = setTimeout(() => {
142
+ done(NAV_CAP_MS);
143
+ }, NAV_CAP_MS);
144
+ try {
145
+ observer = new MutationObserver(activity);
146
+ observer.observe(document.documentElement, { childList: true, subtree: true, attributes: true, characterData: true });
147
+ } catch {
148
+ }
149
+ this.settle = () => {
150
+ if (live !== this.current || this.closed) {
151
+ clearTimeout(quiet);
152
+ clearTimeout(cap);
153
+ observer?.disconnect();
154
+ return;
155
+ }
156
+ activity();
157
+ };
158
+ quiet = setTimeout(check, QUIET_MS);
159
+ }
160
+ toPageView(live) {
161
+ const vitals = this.options.vitals();
162
+ const to = live.end ?? performance.now();
163
+ const values = {
164
+ ...live.navigation === "hard" ? vitals?.hard() : {},
165
+ ...vitals?.span(live.start, to),
166
+ ...live.nav === void 0 ? {} : { nav: live.nav }
167
+ };
168
+ const pv = { id: live.id, at: new Date(performance.timeOrigin + live.start).toISOString(), path: live.path, navigation: live.navigation };
169
+ if (live.route !== void 0 && live.route !== "") pv.route = live.route;
170
+ if (Object.keys(values).length > 0) pv.vitals = values;
171
+ if (live.requests.length > 0) {
172
+ pv.requests = live.requests.map((r) => ({ method: r.method, url: r.url, status: r.status, start: Math.max(0, Math.round(r.start - live.start)), duration: Math.round(r.end - r.start) }));
173
+ }
174
+ const poor = (values.lcp ?? 0) > POOR.lcp || (values.inp ?? 0) > POOR.inp || (values.nav ?? 0) > POOR.nav;
175
+ if (poor) {
176
+ const named = this.resources.flatMap((r) => {
177
+ const name = rumUrl(location.href, r.name);
178
+ const inSpan = r.start >= live.start && (live.end === void 0 || r.start < live.end);
179
+ return name !== void 0 && inSpan && !this.options.own(r.name) ? [{ ...r, name }] : [];
180
+ });
181
+ const longest = named.sort((a, b) => b.duration - a.duration).slice(0, MAX_WATERFALL);
182
+ if (longest.length > 0) {
183
+ pv.waterfall = longest.map((r) => ({ name: r.name, type: r.type, start: Math.round(r.start - live.start), duration: Math.round(r.duration), ...r.size > 0 ? { size: r.size } : {} }));
184
+ }
185
+ }
186
+ return pv;
187
+ }
188
+ };
189
+
190
+ // src/rum/send.ts
191
+ var BATCH_LIMIT = 32e3;
192
+ var UNLOAD_LIMIT = 48e3;
193
+ var GZIP_OVER = 1024;
194
+ var DEFAULT_PAUSE_S = 60;
195
+ var REMEMBERED = 200;
196
+ var TEXT = "text/plain;charset=UTF-8";
197
+ var encoder = new TextEncoder();
198
+ var size = (s) => encoder.encode(s).length;
199
+ var Sender = class {
200
+ constructor(options) {
201
+ this.options = options;
202
+ /** Collector rejected RUM for this page (401, 403 or 404). */
203
+ this.stopped = false;
204
+ this.pausedUntil = 0;
205
+ // Batches waiting on gzip: if the page unloads first, they go plain.
206
+ this.compressing = /* @__PURE__ */ new Set();
207
+ // What each page view looked like when last dispatched: an unchanged one isn't sent again.
208
+ this.sent = /* @__PURE__ */ new Map();
209
+ }
210
+ /** Page views of batches still being compressed, which an unloading page should send plain. */
211
+ undispatched() {
212
+ return [...this.compressing].flatMap((b) => b.pageviews);
213
+ }
214
+ async send(pageviews, how) {
215
+ if (this.stopped || Date.now() < this.pausedUntil) return;
216
+ const fresh = pageviews.flatMap((pv) => this.prepare(pv)).filter((pv) => this.sent.get(pv.id) !== JSON.stringify(pv));
217
+ let batches = this.batches(fresh);
218
+ if (how !== "visible") batches = newestWithin(batches, UNLOAD_LIMIT, this.options.logger);
219
+ if (how === "pagehide") {
220
+ for (const batch of batches) this.unload(batch);
221
+ return;
222
+ }
223
+ if (how === "hidden") {
224
+ await Promise.all(batches.map(async (batch) => this.post(batch, how)));
225
+ return;
226
+ }
227
+ for (const batch of batches) await this.post(batch, how);
228
+ }
229
+ prepare(pageview) {
230
+ const hook = this.options.beforeSendPageview;
231
+ if (!hook) return [pageview];
232
+ let result;
233
+ try {
234
+ result = hook(pageview);
235
+ } catch (error) {
236
+ this.options.logger.debug("beforeSendPageview threw; sending the page view unchanged", error);
237
+ return [pageview];
238
+ }
239
+ if (result === null) return [];
240
+ if (typeof result === "object" && "then" in result) {
241
+ this.options.logger.warnOnce("beforeSendPageview returned a Promise, so the page view was dropped. It must return the page view (or null) right away, not async.");
242
+ return [];
243
+ }
244
+ return [result];
245
+ }
246
+ batches(pageviews) {
247
+ const { sdk, environment, release, session, sampleRate } = this.options;
248
+ const make = (list) => {
249
+ const body = JSON.stringify({ v: 1, sdk, environment, release, session, sample_rate: sampleRate, pageviews: list });
250
+ return { body, pageviews: list, bytes: size(body) };
251
+ };
252
+ const out = [];
253
+ let current = [];
254
+ for (const pv of pageviews) {
255
+ if (make([...current, pv]).bytes <= BATCH_LIMIT) {
256
+ current.push(pv);
257
+ continue;
258
+ }
259
+ if (current.length > 0) out.push(make(current));
260
+ current = [pv];
261
+ if (make(current).bytes > BATCH_LIMIT) {
262
+ this.options.logger.debug("dropped a page view that is too big to send", pv.id);
263
+ current = [];
264
+ }
265
+ }
266
+ if (current.length > 0) out.push(make(current));
267
+ return out;
268
+ }
269
+ dispatched(batch) {
270
+ for (const pv of batch.pageviews) {
271
+ this.sent.delete(pv.id);
272
+ this.sent.set(pv.id, JSON.stringify(pv));
273
+ }
274
+ for (const id of [...this.sent.keys()].slice(0, Math.max(0, this.sent.size - REMEMBERED))) this.sent.delete(id);
275
+ }
276
+ /** The page is going away: a beacon, which the browser sends after the page is gone. */
277
+ unload(batch) {
278
+ this.dispatched(batch);
279
+ let queued = false;
280
+ try {
281
+ queued = navigator.sendBeacon(this.options.url, new Blob([batch.body], { type: TEXT }));
282
+ } catch {
283
+ }
284
+ if (queued) return;
285
+ try {
286
+ this.options.fetch(this.options.url, { method: "POST", body: batch.body, headers: { "Content-Type": TEXT }, keepalive: true, credentials: "omit" }).catch(() => void 0);
287
+ } catch {
288
+ }
289
+ }
290
+ async post(batch, how) {
291
+ const { url, fetch, logger } = this.options;
292
+ const headers = { "Content-Type": TEXT };
293
+ let payload = batch.body;
294
+ if (batch.bytes > GZIP_OVER && typeof CompressionStream === "function") {
295
+ this.compressing.add(batch);
296
+ try {
297
+ payload = await gzip(batch.body);
298
+ headers["Content-Encoding"] = "gzip";
299
+ } catch {
300
+ payload = batch.body;
301
+ } finally {
302
+ this.compressing.delete(batch);
303
+ }
304
+ }
305
+ this.dispatched(batch);
306
+ let response;
307
+ try {
308
+ response = await fetch(url, { method: "POST", body: payload, headers, keepalive: true, credentials: "omit" });
309
+ } catch (error) {
310
+ if (how === "hidden") this.unload(batch);
311
+ else logger.debug("page views not sent", error);
312
+ return;
313
+ }
314
+ const { status } = response;
315
+ if (status === 401 || status === 403 || status === 404) {
316
+ this.stopped = true;
317
+ logger.debug(`Collector turned RUM down (HTTP ${String(status)}): no more page views from this page`);
318
+ } else if (status === 429) {
319
+ const seconds = Number.parseInt(response.headers.get("Retry-After") ?? "", 10);
320
+ this.pausedUntil = Date.now() + (seconds >= 0 ? seconds : DEFAULT_PAUSE_S) * 1e3;
321
+ } else if (status < 200 || status >= 300) {
322
+ logger.debug(`page views dropped (HTTP ${String(status)})`);
323
+ }
324
+ }
325
+ };
326
+ function newestWithin(batches, limit, logger) {
327
+ const kept = [];
328
+ let total = 0;
329
+ for (const batch of [...batches].reverse()) {
330
+ if (total + batch.bytes > limit) {
331
+ logger.debug("an unloading page can't send this much; dropped the oldest page views");
332
+ break;
333
+ }
334
+ total += batch.bytes;
335
+ kept.unshift(batch);
336
+ }
337
+ return kept;
338
+ }
339
+ async function gzip(text) {
340
+ const stream = new Response(text).body;
341
+ if (!stream) throw new Error("no stream");
342
+ return new Response(stream.pipeThrough(new CompressionStream("gzip"))).arrayBuffer();
343
+ }
344
+
345
+ // src/rum/session.ts
346
+ var KEY = "collector:rum";
347
+ var memory;
348
+ function read() {
349
+ let raw;
350
+ try {
351
+ raw = sessionStorage.getItem(KEY);
352
+ } catch {
353
+ return memory;
354
+ }
355
+ if (raw === null) return void 0;
356
+ try {
357
+ const value = JSON.parse(raw);
358
+ if (typeof value === "object" && value !== null && "session" in value && "rate" in value && "sampled" in value) {
359
+ const { session, rate, sampled } = value;
360
+ if (typeof session === "string" && typeof rate === "number" && typeof sampled === "boolean") return { session, rate, sampled };
361
+ }
362
+ } catch {
363
+ }
364
+ return void 0;
365
+ }
366
+ function sessionFor(rate, random = Math.random) {
367
+ const stored = read();
368
+ if (stored?.rate === rate) return { id: stored.session, sampled: stored.sampled };
369
+ const valid = rate > 0 && rate <= 1;
370
+ const next = { session: uuid4(), rate, sampled: valid && random() < rate };
371
+ memory = next;
372
+ try {
373
+ sessionStorage.setItem(KEY, JSON.stringify(next));
374
+ } catch {
375
+ }
376
+ return { id: next.session, sampled: next.sampled };
377
+ }
378
+
379
+ // src/rum/vitals.ts
380
+ var MAX_ENTRIES = 5e3;
381
+ function num(entry, key) {
382
+ const value = entry === void 0 ? void 0 : Reflect.get(entry, key);
383
+ return typeof value === "number" ? value : void 0;
384
+ }
385
+ var CLS_GAP = 1e3;
386
+ var CLS_WINDOW = 5e3;
387
+ function observeVitals() {
388
+ const nav = performance.getEntriesByType("navigation")[0];
389
+ const activation = num(nav, "activationStart") ?? 0;
390
+ const responseStart = num(nav, "responseStart");
391
+ const ttfb = responseStart === void 0 ? void 0 : Math.max(0, responseStart - activation);
392
+ let firstHidden = document.visibilityState === "hidden" && Reflect.get(document, "prerendering") !== true ? 0 : Infinity;
393
+ let firstInput = Infinity;
394
+ let lcp;
395
+ let fcp;
396
+ const shifts = [];
397
+ const interactions = [];
398
+ const onHidden = () => {
399
+ if (document.visibilityState === "hidden") firstHidden = Math.min(firstHidden, performance.now());
400
+ };
401
+ document.addEventListener("visibilitychange", onHidden, true);
402
+ const observers = [];
403
+ const observe = (type, handle, extra) => {
404
+ try {
405
+ if (typeof PerformanceObserver === "undefined" || !PerformanceObserver.supportedEntryTypes.includes(type)) return;
406
+ const observer = new PerformanceObserver((list) => {
407
+ try {
408
+ handle(list.getEntries());
409
+ } catch {
410
+ }
411
+ });
412
+ observer.observe({ type, buffered: true, ...extra });
413
+ observers.push(observer);
414
+ } catch {
415
+ }
416
+ };
417
+ const addInteractions = (entries) => {
418
+ for (const e of entries) {
419
+ const id = num(e, "interactionId") ?? 0;
420
+ if (id > 0 && interactions.length < MAX_ENTRIES) interactions.push({ id, t: e.startTime, d: e.duration });
421
+ }
422
+ };
423
+ observe("first-input", (entries) => {
424
+ for (const e of entries) firstInput = Math.min(firstInput, e.startTime);
425
+ addInteractions(entries);
426
+ });
427
+ observe("paint", (entries) => {
428
+ for (const e of entries) if (e.name === "first-contentful-paint" && e.startTime < firstHidden) fcp = e.startTime;
429
+ });
430
+ observe("largest-contentful-paint", (entries) => {
431
+ for (const e of entries) if (e.startTime < Math.min(firstHidden, firstInput)) lcp = e.startTime;
432
+ });
433
+ observe("layout-shift", (entries) => {
434
+ for (const e of entries) {
435
+ const value = num(e, "value");
436
+ if (value !== void 0 && Reflect.get(e, "hadRecentInput") !== true && shifts.length < MAX_ENTRIES) shifts.push({ t: e.startTime, v: value });
437
+ }
438
+ });
439
+ observe("event", addInteractions, { durationThreshold: 16 });
440
+ const since = (t) => t === void 0 ? void 0 : Math.round(Math.max(0, t - activation));
441
+ const inSpan = (from, to) => (x) => x.t >= from && x.t < to;
442
+ return {
443
+ hard() {
444
+ const out = {};
445
+ const l = since(lcp);
446
+ const f = since(fcp);
447
+ if (l !== void 0) out.lcp = l;
448
+ if (f !== void 0) out.fcp = f;
449
+ if (ttfb !== void 0) out.ttfb = Math.round(ttfb);
450
+ return out;
451
+ },
452
+ span(from, to) {
453
+ const out = {};
454
+ let cls = 0;
455
+ let windowValue = 0;
456
+ let windowStart = -Infinity;
457
+ let last = -Infinity;
458
+ let any = false;
459
+ for (const { t, v } of shifts.filter(inSpan(from, to)).sort((a, b) => a.t - b.t)) {
460
+ any = true;
461
+ if (t - last > CLS_GAP || t - windowStart >= CLS_WINDOW) {
462
+ windowStart = t;
463
+ windowValue = 0;
464
+ }
465
+ windowValue += v;
466
+ last = t;
467
+ cls = Math.max(cls, windowValue);
468
+ }
469
+ if (any) out.cls = cls;
470
+ const longest = /* @__PURE__ */ new Map();
471
+ for (const { id, d } of interactions.filter(inSpan(from, to))) longest.set(id, Math.max(longest.get(id) ?? 0, d));
472
+ const durations = [...longest.values()].sort((a, b) => b - a);
473
+ const inp = durations[Math.min(durations.length - 1, Math.floor(durations.length / 50))];
474
+ if (inp !== void 0) out.inp = Math.round(inp);
475
+ return out;
476
+ },
477
+ prune(t) {
478
+ const keep = (list) => {
479
+ const kept = list.filter((x) => x.t >= t);
480
+ list.splice(0, list.length, ...kept);
481
+ };
482
+ keep(shifts);
483
+ keep(interactions);
484
+ },
485
+ stop() {
486
+ for (const o of observers) o.disconnect();
487
+ document.removeEventListener("visibilitychange", onHidden, true);
488
+ }
489
+ };
490
+ }
491
+
492
+ // src/rum/index.ts
493
+ var SEND_EVERY = 10;
494
+ var SEND_INTERVAL_MS = 5 * 6e4;
495
+ var load;
496
+ function rum(options) {
497
+ return { start: (ctx) => start(ctx, options) };
498
+ }
499
+ function start(ctx, options) {
500
+ const { id, sampled } = sessionFor(options.sampleRate);
501
+ if (!sampled) {
502
+ ctx.logger.debug("RUM: this tab wasn't sampled");
503
+ const nothing = () => void 0;
504
+ return { session: void 0, requestStart: nothing, request: nothing, navigate: nothing, setRoute: nothing, close: nothing };
505
+ }
506
+ const base = ctx.url.slice(0, ctx.url.indexOf("/api/pageviews"));
507
+ const vitals = observeVitals();
508
+ const tracker = new Tracker({ vitals: () => vitals, route: options.route, own: (url) => url.startsWith(`${base}/`), first: load?.open ?? true, hardId: load?.id });
509
+ const opened = tracker.currentId();
510
+ load ?? (load = { id: opened ?? "", open: opened !== void 0 });
511
+ const sender = new Sender({
512
+ url: ctx.url,
513
+ fetch: ctx.fetch,
514
+ logger: ctx.logger,
515
+ sdk: ctx.sdk,
516
+ session: id,
517
+ sampleRate: options.sampleRate,
518
+ environment: ctx.environment,
519
+ release: ctx.release,
520
+ beforeSendPageview: options.beforeSendPageview
521
+ });
522
+ let closed = false;
523
+ let timer;
524
+ const stop = () => {
525
+ closed = true;
526
+ clearTimeout(timer);
527
+ tracker.close();
528
+ vitals.stop();
529
+ document.removeEventListener("visibilitychange", onVisibility);
530
+ window.removeEventListener("pagehide", onPageHide);
531
+ };
532
+ const send = (pageviews, how) => {
533
+ if (pageviews.length === 0) return;
534
+ sender.send(pageviews, how).then(
535
+ () => {
536
+ if (sender.stopped && !closed) stop();
537
+ },
538
+ () => void 0
539
+ );
540
+ };
541
+ const sendAll = (how) => {
542
+ send([...tracker.takeFinished(), ...tracker.snapshot()], how);
543
+ };
544
+ const sendFinished = () => {
545
+ clearTimeout(timer);
546
+ timer = void 0;
547
+ send(tracker.takeFinished(), "visible");
548
+ };
549
+ const onVisibility = () => {
550
+ if (document.visibilityState === "hidden") sendAll("hidden");
551
+ };
552
+ const onPageHide = () => {
553
+ const all = [...sender.undispatched(), ...tracker.takeFinished(), ...tracker.snapshot()];
554
+ send([...new Map(all.map((pv) => [pv.id, pv])).values()], "pagehide");
555
+ };
556
+ document.addEventListener("visibilitychange", onVisibility);
557
+ window.addEventListener("pagehide", onPageHide);
558
+ const guard = (fn) => (...args) => {
559
+ if (closed) return;
560
+ try {
561
+ fn(...args);
562
+ } catch (error) {
563
+ ctx.logger.debug("RUM error", error);
564
+ }
565
+ };
566
+ return {
567
+ session: id,
568
+ requestStart: guard(() => {
569
+ tracker.requestStart();
570
+ }),
571
+ request: guard((timing) => {
572
+ tracker.request(timing);
573
+ }),
574
+ navigate: guard(() => {
575
+ tracker.navigate();
576
+ if (load && tracker.currentId() !== load.id) load.open = false;
577
+ const waiting = tracker.finishedCount();
578
+ if (waiting >= SEND_EVERY) sendFinished();
579
+ else if (waiting > 0) timer ?? (timer = setTimeout(sendFinished, SEND_INTERVAL_MS));
580
+ }),
581
+ setRoute: guard((name) => {
582
+ tracker.setRoute(name);
583
+ }),
584
+ close: guard(() => {
585
+ sendAll("visible");
586
+ stop();
587
+ })
588
+ };
589
+ }
590
+
591
+ export { rum };