@sypnia/browser 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +16 -2
- package/dist/chunk-SLX7QGK4.js +487 -0
- package/dist/index.d.ts +275 -0
- package/dist/index.js +2290 -0
- package/dist/recorder.js +1199 -0
- package/dist/script/sdk-recorder.js +152 -0
- package/dist/script/sdk.js +3 -0
- package/package.json +34 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,2290 @@
|
|
|
1
|
+
import { safe, CHARS, writeStorage, STORAGE_KEYS, removeStorage, isBrowser, isHidden, currentPath, whenIdle, pathnameOf, viewport, matchesRoute, pageRefOf, pageLanguage, readDecision, decisionFrom, fallbackDecision, writeDecision, routeOf, baseUrl, readStorage, SESSION_IDLE_MS, randomHex, isHexId, QUEUE_MAX_EVENTS, FLUSH_AT_EVENTS, FLUSH_INTERVAL_MS, beacon, encode, MAX_RETRY_AFTER_MS, RETRY_DELAYS_MS, KEEPALIVE_MAX_CHARS, outcomeOf, matchesText, scrubEmails, errorFingerprint, ERRORS_PER_MINUTE, ERROR_DEDUPE_MS, RAGE_WINDOW_MS, RAGE_RADIUS_PX, RAGE_MIN_CLICKS, DEAD_DEDUPE_MS, DEAD_WAIT_MS, FORM_INVALID_DEDUPE_MS, matchesUrl, newTraceId, newSpanId, TRACEPARENT_HEADER, formatTraceparent, UNANSWERED_GRACE_MS, hash64, CUSTOM_PROPS_MAX, SESSION_HEADER, BATCH_CHARS, EVENTS_PER_BATCH } from './chunk-SLX7QGK4.js';
|
|
2
|
+
|
|
3
|
+
// src/options.ts
|
|
4
|
+
function list(value) {
|
|
5
|
+
return Array.isArray(value) ? value.filter((item) => typeof item === "string" || item instanceof RegExp) : [];
|
|
6
|
+
}
|
|
7
|
+
function text(value, max) {
|
|
8
|
+
return typeof value === "string" && value.trim() ? value.trim().slice(0, max) : null;
|
|
9
|
+
}
|
|
10
|
+
function resolveOptions(options) {
|
|
11
|
+
const capture = options.capture ?? {};
|
|
12
|
+
const on = (value) => value !== false;
|
|
13
|
+
return {
|
|
14
|
+
project: options.project.trim(),
|
|
15
|
+
endpoint: baseUrl(options.endpoint),
|
|
16
|
+
environment: text(options.environment, CHARS.env) ?? "production",
|
|
17
|
+
release: text(options.release, CHARS.release),
|
|
18
|
+
debug: options.debug === true,
|
|
19
|
+
ignoreRoutes: list(options.ignoreRoutes),
|
|
20
|
+
allowRoutes: list(options.allowRoutes),
|
|
21
|
+
routeFor: typeof options.routeFor === "function" ? options.routeFor : routeOf,
|
|
22
|
+
hashRouting: options.hashRouting === true,
|
|
23
|
+
capture: {
|
|
24
|
+
errors: on(capture.errors),
|
|
25
|
+
clicks: on(capture.clicks),
|
|
26
|
+
requests: on(capture.requests),
|
|
27
|
+
requestFailureDetail: on(capture.requestFailureDetail),
|
|
28
|
+
vitals: on(capture.vitals),
|
|
29
|
+
forms: on(capture.forms)
|
|
30
|
+
},
|
|
31
|
+
traceTargets: list(options.traceTargets),
|
|
32
|
+
recordTargets: list(options.recordTargets),
|
|
33
|
+
ignoreRequests: list(options.ignoreRequests),
|
|
34
|
+
ignoreErrors: list(options.ignoreErrors),
|
|
35
|
+
appFrames: list(options.appFrames),
|
|
36
|
+
maskAllText: options.maskAllText === true,
|
|
37
|
+
maskSelector: text(options.maskSelector, 2e3),
|
|
38
|
+
blockSelector: text(options.blockSelector, 2e3),
|
|
39
|
+
replay: options.replay === false ? false : { blockedRoutes: list(options.replay?.blockedRoutes) },
|
|
40
|
+
snapshots: options.snapshots !== false,
|
|
41
|
+
beforeSend: typeof options.beforeSend === "function" ? options.beforeSend : null
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// src/events.ts
|
|
46
|
+
var SCHEMA_VERSION = 1;
|
|
47
|
+
|
|
48
|
+
// src/session.ts
|
|
49
|
+
var TOUCH_EVERY_MS = 5e3;
|
|
50
|
+
var REREAD_EVERY_MS = 1e3;
|
|
51
|
+
var memoryDevice = null;
|
|
52
|
+
function deviceId() {
|
|
53
|
+
const stored = readStorage(STORAGE_KEYS.device);
|
|
54
|
+
if (isHexId(stored)) return stored;
|
|
55
|
+
memoryDevice ??= randomHex(32);
|
|
56
|
+
writeStorage(STORAGE_KEYS.device, memoryDevice);
|
|
57
|
+
return memoryDevice;
|
|
58
|
+
}
|
|
59
|
+
function personKey(personId) {
|
|
60
|
+
return hash64(`person:${personId}`);
|
|
61
|
+
}
|
|
62
|
+
function readStoredSession() {
|
|
63
|
+
const raw = readStorage(STORAGE_KEYS.session);
|
|
64
|
+
if (!raw) return null;
|
|
65
|
+
try {
|
|
66
|
+
const parsed = JSON.parse(raw);
|
|
67
|
+
if (!isHexId(parsed.sid) || typeof parsed.last !== "number") return null;
|
|
68
|
+
return { sid: parsed.sid, last: parsed.last, p: typeof parsed.p === "string" && parsed.p ? parsed.p : null };
|
|
69
|
+
} catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
var SessionStore = class {
|
|
74
|
+
constructor(now, idleMs = SESSION_IDLE_MS) {
|
|
75
|
+
this.now = now;
|
|
76
|
+
this.idleMs = idleMs;
|
|
77
|
+
this.sid = null;
|
|
78
|
+
this.last = 0;
|
|
79
|
+
this.person = null;
|
|
80
|
+
this.readAt = Number.NEGATIVE_INFINITY;
|
|
81
|
+
/** The store could not be written: each page load is a new session (debug says so). */
|
|
82
|
+
this.storageFailed = false;
|
|
83
|
+
}
|
|
84
|
+
/** Activity: the live session, or a new one when it went idle. Refreshes `last`. */
|
|
85
|
+
touch() {
|
|
86
|
+
const now = this.now();
|
|
87
|
+
this.sync(now);
|
|
88
|
+
if (!this.alive(now)) return { sid: this.create(now, this.person), isNew: true };
|
|
89
|
+
if (now - this.last >= TOUCH_EVERY_MS) this.write(now);
|
|
90
|
+
return { sid: this.sid, isNew: false };
|
|
91
|
+
}
|
|
92
|
+
/** Background work: the live session's id without refreshing it, or null. */
|
|
93
|
+
peek() {
|
|
94
|
+
const now = this.now();
|
|
95
|
+
this.sync(now);
|
|
96
|
+
return this.alive(now) ? this.sid : null;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* `identify()` was called: `key` is the person's key, null for a sign-out.
|
|
100
|
+
* The same person, or a first person in an anonymous session, keeps it;
|
|
101
|
+
* another person, or a sign-out of an identified session, ends it.
|
|
102
|
+
*/
|
|
103
|
+
identify(key) {
|
|
104
|
+
const now = this.now();
|
|
105
|
+
this.sync(now);
|
|
106
|
+
if (key === this.person) return;
|
|
107
|
+
if (this.person === null && this.alive(now)) {
|
|
108
|
+
this.person = key;
|
|
109
|
+
this.write(now);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
this.end(key);
|
|
113
|
+
}
|
|
114
|
+
/** The id this store last knew of, alive or not. */
|
|
115
|
+
known() {
|
|
116
|
+
return this.sid;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Ends the session in every tab: it is stored as idle, with the person who
|
|
120
|
+
* comes next, so the next activity of any tab starts that person's session.
|
|
121
|
+
*/
|
|
122
|
+
end(person) {
|
|
123
|
+
this.person = person;
|
|
124
|
+
this.last = 0;
|
|
125
|
+
this.readAt = this.now();
|
|
126
|
+
writeStorage(STORAGE_KEYS.session, JSON.stringify({ sid: this.sid, last: 0, p: person }));
|
|
127
|
+
}
|
|
128
|
+
/** Adopts what another tab stored (a new session or a fresher `last`), at most every REREAD_EVERY_MS. */
|
|
129
|
+
sync(now) {
|
|
130
|
+
if (this.sid && now - this.readAt < REREAD_EVERY_MS) return;
|
|
131
|
+
this.readAt = now;
|
|
132
|
+
const stored = readStoredSession();
|
|
133
|
+
if (!stored) return;
|
|
134
|
+
if (stored.sid !== this.sid ? stored.last >= this.last : stored.last > this.last) {
|
|
135
|
+
this.sid = stored.sid;
|
|
136
|
+
this.last = stored.last;
|
|
137
|
+
this.person = stored.p;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
alive(now) {
|
|
141
|
+
return this.sid !== null && now - this.last <= this.idleMs;
|
|
142
|
+
}
|
|
143
|
+
create(now, person) {
|
|
144
|
+
this.sid = randomHex(32);
|
|
145
|
+
this.person = person;
|
|
146
|
+
this.write(now);
|
|
147
|
+
return this.sid;
|
|
148
|
+
}
|
|
149
|
+
write(now) {
|
|
150
|
+
this.last = now;
|
|
151
|
+
this.readAt = now;
|
|
152
|
+
this.storageFailed = !writeStorage(STORAGE_KEYS.session, JSON.stringify({ sid: this.sid, last: now, p: this.person }));
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
// src/version.ts
|
|
157
|
+
var SDK_NAME = "@sypnia/browser";
|
|
158
|
+
var SDK_VERSION = "0.1.0";
|
|
159
|
+
|
|
160
|
+
// src/transport.ts
|
|
161
|
+
function uuid() {
|
|
162
|
+
const hex = randomHex(32);
|
|
163
|
+
const variant = (parseInt(hex.charAt(16), 16) & 3 | 8).toString(16);
|
|
164
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
|
|
165
|
+
}
|
|
166
|
+
function splitBatches(events) {
|
|
167
|
+
const batches = [];
|
|
168
|
+
let current = [];
|
|
169
|
+
let chars = 0;
|
|
170
|
+
for (const event of events) {
|
|
171
|
+
const size = JSON.stringify(event).length + 1;
|
|
172
|
+
if (current.length > 0 && (chars + size > BATCH_CHARS || current.length >= EVENTS_PER_BATCH)) {
|
|
173
|
+
batches.push(current);
|
|
174
|
+
current = [];
|
|
175
|
+
chars = 0;
|
|
176
|
+
}
|
|
177
|
+
current.push(event);
|
|
178
|
+
chars += size;
|
|
179
|
+
}
|
|
180
|
+
if (current.length > 0) batches.push(current);
|
|
181
|
+
return batches;
|
|
182
|
+
}
|
|
183
|
+
function dropIndex(queue) {
|
|
184
|
+
let firstNonError = -1;
|
|
185
|
+
for (let i = 0; i < queue.length; i++) {
|
|
186
|
+
const type = queue[i]?.type;
|
|
187
|
+
if (type === "click") return i;
|
|
188
|
+
if (firstNonError < 0 && type !== "error") firstNonError = i;
|
|
189
|
+
}
|
|
190
|
+
return Math.max(0, firstNonError);
|
|
191
|
+
}
|
|
192
|
+
var Transport = class {
|
|
193
|
+
constructor(options) {
|
|
194
|
+
this.options = options;
|
|
195
|
+
this.queue = [];
|
|
196
|
+
this.timer = null;
|
|
197
|
+
this.refused = false;
|
|
198
|
+
/** Events dropped because the queue was full (debug). */
|
|
199
|
+
this.overflowed = 0;
|
|
200
|
+
}
|
|
201
|
+
get size() {
|
|
202
|
+
return this.queue.length;
|
|
203
|
+
}
|
|
204
|
+
/** A copy of what waits (tests and debug). */
|
|
205
|
+
peek() {
|
|
206
|
+
return this.queue.slice();
|
|
207
|
+
}
|
|
208
|
+
enqueue(event) {
|
|
209
|
+
if (this.refused) return;
|
|
210
|
+
this.queue.push(event);
|
|
211
|
+
while (this.queue.length > QUEUE_MAX_EVENTS) {
|
|
212
|
+
this.queue.splice(dropIndex(this.queue), 1);
|
|
213
|
+
this.overflowed++;
|
|
214
|
+
}
|
|
215
|
+
if (this.queue.length >= FLUSH_AT_EVENTS) void this.flush("fetch");
|
|
216
|
+
}
|
|
217
|
+
/** Keeps only the waiting events that `keep` accepts (a `slow_down` arrived). */
|
|
218
|
+
retain(keep) {
|
|
219
|
+
this.queue = this.queue.filter(keep);
|
|
220
|
+
}
|
|
221
|
+
start() {
|
|
222
|
+
this.timer ??= setInterval(() => void this.flush("fetch"), FLUSH_INTERVAL_MS);
|
|
223
|
+
}
|
|
224
|
+
stop() {
|
|
225
|
+
if (this.timer) clearInterval(this.timer);
|
|
226
|
+
this.timer = null;
|
|
227
|
+
}
|
|
228
|
+
/** Sends everything waiting. `beacon` while the page closes. Never throws. */
|
|
229
|
+
async flush(mode) {
|
|
230
|
+
try {
|
|
231
|
+
if (this.queue.length === 0 || this.refused) return;
|
|
232
|
+
const events = this.queue;
|
|
233
|
+
this.queue = [];
|
|
234
|
+
const sends = splitBatches(events).map((group) => {
|
|
235
|
+
const batch = { id: uuid(), events: group };
|
|
236
|
+
return mode === "beacon" && this.sendBeacon(batch) ? Promise.resolve() : this.send(batch, 0);
|
|
237
|
+
});
|
|
238
|
+
await Promise.all(sends);
|
|
239
|
+
} catch {
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
body(batch) {
|
|
243
|
+
return JSON.stringify({
|
|
244
|
+
batch_id: batch.id,
|
|
245
|
+
sent_at: new Date(this.options.now()).toISOString().replace(/\.\d{3}Z$/, "Z"),
|
|
246
|
+
sdk: { name: SDK_NAME, version: SDK_VERSION },
|
|
247
|
+
events: batch.events
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
sendBeacon(batch) {
|
|
251
|
+
const sent = beacon(this.options.url, this.options.project, this.body(batch));
|
|
252
|
+
if (sent) this.options.debug(`sent ${batch.events.length} events (beacon)`);
|
|
253
|
+
return sent;
|
|
254
|
+
}
|
|
255
|
+
async send(batch, attempt) {
|
|
256
|
+
const body = this.body(batch);
|
|
257
|
+
const payload = await encode(body);
|
|
258
|
+
const outcome = await this.post(payload);
|
|
259
|
+
switch (outcome.kind) {
|
|
260
|
+
case "stored":
|
|
261
|
+
return;
|
|
262
|
+
case "limit":
|
|
263
|
+
if (outcome.slowDown) this.options.onAnswer({ accepted: 0, dropped: batch.events.length, slow_down: outcome.slowDown });
|
|
264
|
+
return;
|
|
265
|
+
case "refused":
|
|
266
|
+
this.refused = true;
|
|
267
|
+
this.queue = [];
|
|
268
|
+
this.stop();
|
|
269
|
+
return;
|
|
270
|
+
case "retry":
|
|
271
|
+
return this.retry(batch, attempt, outcome);
|
|
272
|
+
default:
|
|
273
|
+
this.options.debug(`batch of ${batch.events.length} events refused (${outcome.kind})`);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
retry(batch, attempt, outcome) {
|
|
277
|
+
const delay = outcome.throttled ? attempt === 0 ? Math.min(MAX_RETRY_AFTER_MS, outcome.retryAfterMs ?? RETRY_DELAYS_MS[0] ?? 1e3) : void 0 : RETRY_DELAYS_MS[attempt];
|
|
278
|
+
if (delay === void 0) {
|
|
279
|
+
this.options.debug(`batch of ${batch.events.length} events dropped after ${attempt + 1} tries`);
|
|
280
|
+
return Promise.resolve();
|
|
281
|
+
}
|
|
282
|
+
return new Promise((resolve) => {
|
|
283
|
+
setTimeout(() => void this.send(batch, attempt + 1).then(resolve, resolve), delay);
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
async post(payload) {
|
|
287
|
+
try {
|
|
288
|
+
const response = await this.options.fetch(this.options.url, {
|
|
289
|
+
method: "POST",
|
|
290
|
+
keepalive: (typeof payload === "string" ? payload.length : payload.byteLength) <= KEEPALIVE_MAX_CHARS,
|
|
291
|
+
credentials: "omit",
|
|
292
|
+
headers: { authorization: `Bearer ${this.options.project}`, "content-type": "application/json" },
|
|
293
|
+
body: payload
|
|
294
|
+
});
|
|
295
|
+
if (response.ok) {
|
|
296
|
+
const answer = await response.clone().json().catch(() => ({}));
|
|
297
|
+
this.options.debug(`sent: ${JSON.stringify(answer)}`);
|
|
298
|
+
this.options.onAnswer(answer);
|
|
299
|
+
} else if (response.status === 401 || response.status === 403) {
|
|
300
|
+
this.options.onRefused(response.status);
|
|
301
|
+
}
|
|
302
|
+
return await outcomeOf(response, this.options.now());
|
|
303
|
+
} catch {
|
|
304
|
+
return { kind: "retry", retryAfterMs: null, throttled: false };
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
// src/slow-down.ts
|
|
310
|
+
var KEPT_WHEN_FAILURES_ONLY = /* @__PURE__ */ new Set([
|
|
311
|
+
"error",
|
|
312
|
+
"session_start",
|
|
313
|
+
"page_view",
|
|
314
|
+
"identify",
|
|
315
|
+
"replay_chunk",
|
|
316
|
+
"replay_gap",
|
|
317
|
+
"page_snapshot"
|
|
318
|
+
]);
|
|
319
|
+
function isFailedCall(status) {
|
|
320
|
+
return status === 0 || status === 400 || status >= 500;
|
|
321
|
+
}
|
|
322
|
+
function isActiveSlowDown(slowDown, now) {
|
|
323
|
+
if (!slowDown) return false;
|
|
324
|
+
const until = slowDown.until ? Date.parse(slowDown.until) : Number.NaN;
|
|
325
|
+
if (Number.isFinite(until) && until <= now) return false;
|
|
326
|
+
return slowDown.send === "failures" || slowDown.send === "none" || slowDown.replay === false;
|
|
327
|
+
}
|
|
328
|
+
function isBlockedBySlowDown(event, slowDown, now) {
|
|
329
|
+
if (!isActiveSlowDown(slowDown, now)) return false;
|
|
330
|
+
if (slowDown.send === "none") return true;
|
|
331
|
+
if (slowDown.send !== "failures") return false;
|
|
332
|
+
if (event.type === "request") return !isFailedCall(event.status);
|
|
333
|
+
return !KEPT_WHEN_FAILURES_ONLY.has(event.type);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// src/capture/describe.ts
|
|
337
|
+
var CONTROL_SELECTOR = 'button, a, summary, label, input, select, textarea, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="menuitemcheckbox"], [role="menuitemradio"], [role="option"], [role="treeitem"], [role="checkbox"], [role="radio"], [role="switch"], [role="combobox"], [contenteditable=""], [contenteditable="true"], [contenteditable="plaintext-only"]';
|
|
338
|
+
var ACTIONABLE_SELECTOR = 'button, a[href], summary, input[type="submit"], input[type="button"], [role="button"], [role="tab"], [role="menuitem"], [role="menuitemcheckbox"], [role="menuitemradio"], [role="link"], [role="option"], [role="switch"], [role="checkbox"]';
|
|
339
|
+
var OVERLAY_SELECTOR = '[role="dialog"], [role="alertdialog"], dialog[open], [aria-modal="true"], [role="menu"], [role="listbox"]';
|
|
340
|
+
var TITLED_BY_HEADING_SELECTOR = '[role="dialog"], [role="alertdialog"], dialog, [aria-modal="true"]';
|
|
341
|
+
var HEADING_SELECTOR = 'h1, h2, h3, h4, [role="heading"]';
|
|
342
|
+
var ANY_HEADING_SELECTOR = 'h1, h2, h3, h4, h5, h6, [role="heading"]';
|
|
343
|
+
var LANDMARK_SELECTOR = 'nav, aside, header, [role="navigation"], [role="banner"], [role="complementary"]';
|
|
344
|
+
var MASK_ATTRIBUTE_SELECTOR = "[data-sypnia-mask]";
|
|
345
|
+
var SKIP_TEXT_BASE = 'script, style, template, noscript, select, textarea, option, datalist, [hidden], [aria-hidden="true"]';
|
|
346
|
+
var SKIP_IN_LABEL_EXTRA = 'input, [role="combobox"], [role="listbox"], [role="textbox"], [contenteditable=""], [contenteditable="true"], [contenteditable="plaintext-only"]';
|
|
347
|
+
var config = configFor(null, false, (path) => path);
|
|
348
|
+
function configFor(maskSelector, maskAllText, routeFor) {
|
|
349
|
+
const mask = maskSelector ? `${MASK_ATTRIBUTE_SELECTOR}, ${maskSelector}` : MASK_ATTRIBUTE_SELECTOR;
|
|
350
|
+
const skipText = `${SKIP_TEXT_BASE}, ${mask}`;
|
|
351
|
+
return { mask, skipText, skipInLabel: `${skipText}, ${SKIP_IN_LABEL_EXTRA}`, maskAllText, routeFor };
|
|
352
|
+
}
|
|
353
|
+
function configureDescriber(options) {
|
|
354
|
+
config = configFor(options.maskSelector, options.maskAllText, options.routeFor);
|
|
355
|
+
}
|
|
356
|
+
var TEXT_TAGS = /* @__PURE__ */ new Set([
|
|
357
|
+
"p",
|
|
358
|
+
"span",
|
|
359
|
+
"li",
|
|
360
|
+
"dd",
|
|
361
|
+
"dt",
|
|
362
|
+
"small",
|
|
363
|
+
"strong",
|
|
364
|
+
"em",
|
|
365
|
+
"b",
|
|
366
|
+
"i",
|
|
367
|
+
"blockquote",
|
|
368
|
+
"code",
|
|
369
|
+
"pre"
|
|
370
|
+
]);
|
|
371
|
+
var BUTTON_INPUT_TYPES = /* @__PURE__ */ new Set(["button", "submit", "reset", "image", "file"]);
|
|
372
|
+
var FIELD_ROLES = /* @__PURE__ */ new Set(["select", "input", "textarea"]);
|
|
373
|
+
var ARIA_ROLES = {
|
|
374
|
+
button: "button",
|
|
375
|
+
link: "link",
|
|
376
|
+
tab: "tab",
|
|
377
|
+
menuitem: "menuitem",
|
|
378
|
+
menuitemcheckbox: "menuitem",
|
|
379
|
+
menuitemradio: "menuitem",
|
|
380
|
+
option: "option",
|
|
381
|
+
treeitem: "option",
|
|
382
|
+
checkbox: "checkbox",
|
|
383
|
+
radio: "radio",
|
|
384
|
+
switch: "switch",
|
|
385
|
+
combobox: "select",
|
|
386
|
+
listbox: "select",
|
|
387
|
+
textbox: "input",
|
|
388
|
+
searchbox: "input",
|
|
389
|
+
row: "row",
|
|
390
|
+
cell: "cell",
|
|
391
|
+
gridcell: "cell",
|
|
392
|
+
columnheader: "cell",
|
|
393
|
+
rowheader: "cell",
|
|
394
|
+
heading: "heading",
|
|
395
|
+
img: "image",
|
|
396
|
+
image: "image"
|
|
397
|
+
};
|
|
398
|
+
var CELL_SELECTOR = 'td, th, [role="cell"], [role="gridcell"], [role="columnheader"], [role="rowheader"]';
|
|
399
|
+
var MAX_DEPTH = 5;
|
|
400
|
+
var MAX_TEXT_NODES = 400;
|
|
401
|
+
var MAX_HEADINGS = 300;
|
|
402
|
+
function interactiveTarget(el) {
|
|
403
|
+
try {
|
|
404
|
+
return el.closest(CONTROL_SELECTOR);
|
|
405
|
+
} catch {
|
|
406
|
+
return null;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
function isStableId(id) {
|
|
410
|
+
if (!id || id.length > 64) return false;
|
|
411
|
+
if (/[:\u00AB\u00BB\s]/.test(id)) return false;
|
|
412
|
+
if (/^\d/.test(id)) return false;
|
|
413
|
+
if (/(^|[-_])\d+$/.test(id)) return false;
|
|
414
|
+
if (/[0-9a-f]{8,}/i.test(id)) return false;
|
|
415
|
+
if (/^(radix|headlessui|react-select|downshift|mui|floating-ui)[-_]/i.test(id)) return false;
|
|
416
|
+
return true;
|
|
417
|
+
}
|
|
418
|
+
function escapeAttr(value) {
|
|
419
|
+
return value.replace(/["\\]/g, "\\$&");
|
|
420
|
+
}
|
|
421
|
+
function escapeId(id) {
|
|
422
|
+
try {
|
|
423
|
+
if (typeof CSS !== "undefined" && typeof CSS.escape === "function") return CSS.escape(id);
|
|
424
|
+
} catch {
|
|
425
|
+
}
|
|
426
|
+
return id.replace(/([^\w-])/g, "\\$1");
|
|
427
|
+
}
|
|
428
|
+
function buildSelector(el) {
|
|
429
|
+
const parts = [];
|
|
430
|
+
let node = el;
|
|
431
|
+
let depth = 0;
|
|
432
|
+
while (node && depth < MAX_DEPTH) {
|
|
433
|
+
const tag = node.tagName.toLowerCase();
|
|
434
|
+
if (tag === "html" || tag === "body") break;
|
|
435
|
+
const testId = node.getAttribute("data-testid");
|
|
436
|
+
if (testId) {
|
|
437
|
+
parts.unshift(`[data-testid="${escapeAttr(testId)}"]`);
|
|
438
|
+
break;
|
|
439
|
+
}
|
|
440
|
+
if (node.id && isStableId(node.id)) {
|
|
441
|
+
parts.unshift(`#${escapeId(node.id)}`);
|
|
442
|
+
break;
|
|
443
|
+
}
|
|
444
|
+
let segment = tag;
|
|
445
|
+
const role = node.getAttribute("role");
|
|
446
|
+
if (role && /^[a-z-]+$/i.test(role)) segment += `[role="${role}"]`;
|
|
447
|
+
const parent = node.parentElement;
|
|
448
|
+
if (parent) {
|
|
449
|
+
let index = 0;
|
|
450
|
+
let count = 0;
|
|
451
|
+
for (let i = 0; i < parent.children.length; i++) {
|
|
452
|
+
const child = parent.children[i];
|
|
453
|
+
if (!child || child.tagName !== node.tagName) continue;
|
|
454
|
+
count++;
|
|
455
|
+
if (child === node) index = count;
|
|
456
|
+
}
|
|
457
|
+
if (count > 1) segment += `:nth-of-type(${index})`;
|
|
458
|
+
}
|
|
459
|
+
parts.unshift(segment);
|
|
460
|
+
node = parent;
|
|
461
|
+
depth++;
|
|
462
|
+
}
|
|
463
|
+
return parts.join(" > ").slice(0, CHARS.selector);
|
|
464
|
+
}
|
|
465
|
+
function vitalTarget(node) {
|
|
466
|
+
try {
|
|
467
|
+
if (!node) return void 0;
|
|
468
|
+
const el = node.nodeType === 1 ? node : node.parentElement;
|
|
469
|
+
if (!el) return void 0;
|
|
470
|
+
return buildSelector(el) || void 0;
|
|
471
|
+
} catch {
|
|
472
|
+
return void 0;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
function hrefFor(el) {
|
|
476
|
+
if (el.tagName.toLowerCase() !== "a") return null;
|
|
477
|
+
const raw = el.getAttribute("href");
|
|
478
|
+
if (!raw) return null;
|
|
479
|
+
const trimmed = raw.trim();
|
|
480
|
+
if (/^(mailto:|tel:|javascript:|#)/i.test(trimmed)) return null;
|
|
481
|
+
try {
|
|
482
|
+
const url = new URL(trimmed, window.location.href);
|
|
483
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
|
|
484
|
+
return config.routeFor(url.pathname).slice(0, CHARS.path);
|
|
485
|
+
} catch {
|
|
486
|
+
return null;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
function clipText(text3, max) {
|
|
490
|
+
if (typeof text3 !== "string") return null;
|
|
491
|
+
const clean = text3.replace(/\s+/g, " ").trim();
|
|
492
|
+
if (!clean) return null;
|
|
493
|
+
if (clean.length <= max) return clean;
|
|
494
|
+
return `${clean.slice(0, Math.max(1, max - 1)).trimEnd()}\u2026`;
|
|
495
|
+
}
|
|
496
|
+
function tagOf(el) {
|
|
497
|
+
return el.tagName.toLowerCase();
|
|
498
|
+
}
|
|
499
|
+
function isMasked(el) {
|
|
500
|
+
try {
|
|
501
|
+
return el.closest(config.mask) !== null;
|
|
502
|
+
} catch {
|
|
503
|
+
return true;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
function visibleText(el, max, skip = config.skipText) {
|
|
507
|
+
const doc = el.ownerDocument;
|
|
508
|
+
if (!doc || typeof doc.createTreeWalker !== "function") return "";
|
|
509
|
+
if (isMasked(el)) return "";
|
|
510
|
+
const walker = doc.createTreeWalker(el, 1 | 4, {
|
|
511
|
+
acceptNode(node) {
|
|
512
|
+
if (node.nodeType === 3) return 1;
|
|
513
|
+
try {
|
|
514
|
+
return node.matches(skip) ? 2 : 3;
|
|
515
|
+
} catch {
|
|
516
|
+
return 2;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
});
|
|
520
|
+
let text3 = "";
|
|
521
|
+
let visited = 0;
|
|
522
|
+
for (let node = walker.nextNode(); node && visited < MAX_TEXT_NODES; node = walker.nextNode()) {
|
|
523
|
+
visited++;
|
|
524
|
+
const value = node.nodeValue;
|
|
525
|
+
if (!value || !/\S/.test(value)) continue;
|
|
526
|
+
text3 += ` ${value}`;
|
|
527
|
+
if (text3.length > max * 2 + 1) break;
|
|
528
|
+
}
|
|
529
|
+
const clean = text3.replace(/\s+/g, " ").trim();
|
|
530
|
+
return clean.length > max + 1 ? clean.slice(0, max + 1) : clean;
|
|
531
|
+
}
|
|
532
|
+
function isEditableHost(el) {
|
|
533
|
+
const value = el.getAttribute("contenteditable");
|
|
534
|
+
return value !== null && (value === "" || value === "true" || value === "plaintext-only");
|
|
535
|
+
}
|
|
536
|
+
function hasOwnText(el) {
|
|
537
|
+
for (const child of Array.from(el.childNodes)) {
|
|
538
|
+
if (child.nodeType === 3 && /\S/.test(child.nodeValue || "")) return true;
|
|
539
|
+
}
|
|
540
|
+
return false;
|
|
541
|
+
}
|
|
542
|
+
function clickRole(el) {
|
|
543
|
+
try {
|
|
544
|
+
const explicit = (el.getAttribute("role") || "").trim().toLowerCase().split(/\s+/)[0];
|
|
545
|
+
if (explicit === "textbox" && el.getAttribute("aria-multiline") === "true") return "textarea";
|
|
546
|
+
const aria = explicit ? ARIA_ROLES[explicit] : void 0;
|
|
547
|
+
if (aria && Object.prototype.hasOwnProperty.call(ARIA_ROLES, explicit)) return aria;
|
|
548
|
+
const tag = tagOf(el);
|
|
549
|
+
switch (tag) {
|
|
550
|
+
case "button":
|
|
551
|
+
case "summary":
|
|
552
|
+
return "button";
|
|
553
|
+
case "a":
|
|
554
|
+
return "link";
|
|
555
|
+
case "select":
|
|
556
|
+
return "select";
|
|
557
|
+
case "textarea":
|
|
558
|
+
return "textarea";
|
|
559
|
+
case "input": {
|
|
560
|
+
const type = (el.type || el.getAttribute("type") || "text").toLowerCase();
|
|
561
|
+
if (BUTTON_INPUT_TYPES.has(type)) return "button";
|
|
562
|
+
if (type === "checkbox") return "checkbox";
|
|
563
|
+
if (type === "radio") return "radio";
|
|
564
|
+
return "input";
|
|
565
|
+
}
|
|
566
|
+
case "label": {
|
|
567
|
+
const control = el.control;
|
|
568
|
+
return control && control !== el ? clickRole(control) : "text";
|
|
569
|
+
}
|
|
570
|
+
case "img":
|
|
571
|
+
case "picture":
|
|
572
|
+
return "image";
|
|
573
|
+
case "tr":
|
|
574
|
+
return "row";
|
|
575
|
+
case "svg":
|
|
576
|
+
return "icon";
|
|
577
|
+
}
|
|
578
|
+
if (isEditableHost(el)) return "textarea";
|
|
579
|
+
if (/^h[1-6]$/.test(tag) || el.closest(ANY_HEADING_SELECTOR)) return "heading";
|
|
580
|
+
if (tag === "td" || tag === "th" || el.closest(CELL_SELECTOR)) return "cell";
|
|
581
|
+
if (el.closest("svg")) return "icon";
|
|
582
|
+
if (TEXT_TAGS.has(tag) || tag === "div" && hasOwnText(el)) return "text";
|
|
583
|
+
return "other";
|
|
584
|
+
} catch {
|
|
585
|
+
return "other";
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
function textOfIds(el, ids, max) {
|
|
589
|
+
if (!ids) return null;
|
|
590
|
+
const doc = el.ownerDocument;
|
|
591
|
+
const parts = [];
|
|
592
|
+
for (const id of ids.trim().split(/\s+/)) {
|
|
593
|
+
if (!id) continue;
|
|
594
|
+
const target = doc.getElementById(id);
|
|
595
|
+
if (!target || isMasked(target)) continue;
|
|
596
|
+
const text3 = visibleText(target, max, config.skipInLabel) || target.getAttribute("aria-label") || "";
|
|
597
|
+
if (text3) parts.push(text3);
|
|
598
|
+
if (parts.join(" ").length > max) break;
|
|
599
|
+
}
|
|
600
|
+
return clipText(parts.join(" "), max);
|
|
601
|
+
}
|
|
602
|
+
function isField(el, role) {
|
|
603
|
+
const tag = tagOf(el);
|
|
604
|
+
if (tag === "label") return false;
|
|
605
|
+
if (tag === "select" || tag === "textarea") return true;
|
|
606
|
+
if (tag === "input") return !BUTTON_INPUT_TYPES.has((el.type || "").toLowerCase());
|
|
607
|
+
return isEditableHost(el) || FIELD_ROLES.has(role);
|
|
608
|
+
}
|
|
609
|
+
function labelText(el, max) {
|
|
610
|
+
const labels = el.labels;
|
|
611
|
+
let label = labels?.[0] ?? null;
|
|
612
|
+
if (!label && el.id) {
|
|
613
|
+
try {
|
|
614
|
+
label = el.ownerDocument.querySelector(`label[for="${escapeAttr(el.id)}"]`);
|
|
615
|
+
} catch {
|
|
616
|
+
label = null;
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
if (!label || isMasked(label)) return null;
|
|
620
|
+
return clipText(visibleText(label, max, config.skipInLabel), max);
|
|
621
|
+
}
|
|
622
|
+
function fieldName(el, max) {
|
|
623
|
+
return labelText(el, max) ?? clipText(el.getAttribute("placeholder"), max) ?? clipText(el.getAttribute("aria-placeholder"), max) ?? clipText(el.getAttribute("data-placeholder"), max) ?? clipText(el.getAttribute("title"), max);
|
|
624
|
+
}
|
|
625
|
+
function svgName(svg, max) {
|
|
626
|
+
if (isMasked(svg)) return null;
|
|
627
|
+
const aria = clipText(svg.getAttribute("aria-label"), max);
|
|
628
|
+
if (aria) return aria;
|
|
629
|
+
const title = svg.querySelector("title");
|
|
630
|
+
return title && !isMasked(title) ? clipText(title.textContent, max) : null;
|
|
631
|
+
}
|
|
632
|
+
function firstUnmasked(el, selector) {
|
|
633
|
+
const found = el.querySelectorAll(selector);
|
|
634
|
+
for (let i = 0; i < found.length && i < MAX_DEPTH * 4; i++) {
|
|
635
|
+
const candidate = found[i];
|
|
636
|
+
if (candidate && !isMasked(candidate)) return candidate;
|
|
637
|
+
}
|
|
638
|
+
return null;
|
|
639
|
+
}
|
|
640
|
+
function mediaName(el, max) {
|
|
641
|
+
const img = firstUnmasked(el, "img[alt]");
|
|
642
|
+
const alt = img ? clipText(img.getAttribute("alt"), max) : null;
|
|
643
|
+
if (alt) return alt;
|
|
644
|
+
const svg = firstUnmasked(el, "svg");
|
|
645
|
+
return svg ? svgName(svg, max) : null;
|
|
646
|
+
}
|
|
647
|
+
function nameHost(el, role) {
|
|
648
|
+
if (role === "cell") return el.closest(CELL_SELECTOR) ?? el;
|
|
649
|
+
if (role === "row") return el.closest('tr, [role="row"]') ?? el;
|
|
650
|
+
if (role === "heading") return el.closest(ANY_HEADING_SELECTOR) ?? el;
|
|
651
|
+
if (role === "icon") return el.closest("svg") ?? el;
|
|
652
|
+
return el;
|
|
653
|
+
}
|
|
654
|
+
function rowText(row, max) {
|
|
655
|
+
const parts = [];
|
|
656
|
+
let length = 0;
|
|
657
|
+
for (const cell of Array.from(row.children)) {
|
|
658
|
+
const text3 = clipText(visibleText(cell, max), max);
|
|
659
|
+
if (!text3) continue;
|
|
660
|
+
parts.push(text3);
|
|
661
|
+
length += text3.length + 3;
|
|
662
|
+
if (length > max) break;
|
|
663
|
+
}
|
|
664
|
+
return clipText(parts.join(" \xB7 "), max);
|
|
665
|
+
}
|
|
666
|
+
function accessibleName(el, role = clickRole(el)) {
|
|
667
|
+
try {
|
|
668
|
+
const max = CHARS.label;
|
|
669
|
+
if (isMasked(el)) return null;
|
|
670
|
+
const tag = tagOf(el);
|
|
671
|
+
if (tag === "html" || tag === "body" || tag === "main" || el.getAttribute("role") === "main") return null;
|
|
672
|
+
const host = nameHost(el, role);
|
|
673
|
+
const labelled = textOfIds(host, host.getAttribute("aria-labelledby"), max);
|
|
674
|
+
if (labelled) return labelled;
|
|
675
|
+
const aria = clipText(host.getAttribute("aria-label"), max);
|
|
676
|
+
if (aria) return aria;
|
|
677
|
+
if (tag === "input") {
|
|
678
|
+
const type = (el.type || "").toLowerCase();
|
|
679
|
+
if (type === "button" || type === "submit" || type === "reset") {
|
|
680
|
+
return clipText(el.getAttribute("value"), max) ?? clipText(el.getAttribute("title"), max);
|
|
681
|
+
}
|
|
682
|
+
if (type === "image") return clipText(el.getAttribute("alt"), max) ?? clipText(el.getAttribute("title"), max);
|
|
683
|
+
}
|
|
684
|
+
if (isField(el, role)) return fieldName(el, max);
|
|
685
|
+
if (tag === "img") return clipText(el.getAttribute("alt"), max) ?? clipText(el.getAttribute("title"), max);
|
|
686
|
+
if (role === "icon") return svgName(host, max) ?? clipText(host.getAttribute("title"), max);
|
|
687
|
+
if (role === "row") {
|
|
688
|
+
const text3 = rowText(host, max);
|
|
689
|
+
if (text3) return text3;
|
|
690
|
+
} else {
|
|
691
|
+
const raw = visibleText(host, max, tag === "label" ? config.skipInLabel : config.skipText);
|
|
692
|
+
if (role === "other" && raw.length > max) return null;
|
|
693
|
+
const text3 = clipText(raw, max);
|
|
694
|
+
if (text3) return text3;
|
|
695
|
+
}
|
|
696
|
+
return clipText(host.getAttribute("title"), max) ?? mediaName(host, max) ?? labelText(host, max);
|
|
697
|
+
} catch {
|
|
698
|
+
return null;
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
function overlayTitle(overlay, max) {
|
|
702
|
+
const labelled = textOfIds(overlay, overlay.getAttribute("aria-labelledby"), max);
|
|
703
|
+
if (labelled) return labelled;
|
|
704
|
+
const aria = clipText(overlay.getAttribute("aria-label"), max);
|
|
705
|
+
if (aria) return aria;
|
|
706
|
+
if (!overlay.matches(TITLED_BY_HEADING_SELECTOR)) return null;
|
|
707
|
+
const heading = overlay.querySelector(HEADING_SELECTOR);
|
|
708
|
+
return heading && !isMasked(heading) ? clipText(visibleText(heading, max), max) : null;
|
|
709
|
+
}
|
|
710
|
+
function clickContext(el) {
|
|
711
|
+
try {
|
|
712
|
+
const max = CHARS.label;
|
|
713
|
+
const own = el.closest(OVERLAY_SELECTOR);
|
|
714
|
+
let untitled = null;
|
|
715
|
+
for (let overlay = own; overlay; overlay = overlay.parentElement?.closest(OVERLAY_SELECTOR) ?? null) {
|
|
716
|
+
if (isMasked(overlay)) {
|
|
717
|
+
untitled ??= overlay;
|
|
718
|
+
continue;
|
|
719
|
+
}
|
|
720
|
+
const title = overlayTitle(overlay, max);
|
|
721
|
+
if (title) return title;
|
|
722
|
+
untitled ??= overlay;
|
|
723
|
+
}
|
|
724
|
+
const landmark = el.closest(LANDMARK_SELECTOR);
|
|
725
|
+
const boundary = untitled ?? el.closest('main, [role="main"]') ?? landmark ?? el.ownerDocument.body;
|
|
726
|
+
if (!boundary) return null;
|
|
727
|
+
const headings = boundary.querySelectorAll(HEADING_SELECTOR);
|
|
728
|
+
const stop = Math.max(0, headings.length - MAX_HEADINGS);
|
|
729
|
+
for (let i = headings.length - 1; i >= stop; i--) {
|
|
730
|
+
const heading = headings[i];
|
|
731
|
+
if (!heading || heading === el || heading.contains(el)) continue;
|
|
732
|
+
if (!(heading.compareDocumentPosition(el) & 4)) continue;
|
|
733
|
+
if (heading.closest(OVERLAY_SELECTOR) !== own) continue;
|
|
734
|
+
if (isMasked(heading)) continue;
|
|
735
|
+
const text3 = clipText(visibleText(heading, max), max);
|
|
736
|
+
if (text3) return text3;
|
|
737
|
+
}
|
|
738
|
+
if (boundary === landmark && landmark) return clipText(landmark.getAttribute("aria-label"), max);
|
|
739
|
+
return null;
|
|
740
|
+
} catch {
|
|
741
|
+
return null;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
function describeElement(el, origin) {
|
|
745
|
+
const crole = clickRole(el);
|
|
746
|
+
const hidden = config.maskAllText || !!origin && origin !== el && isMasked(origin);
|
|
747
|
+
return {
|
|
748
|
+
sel: buildSelector(el),
|
|
749
|
+
tag: el.tagName.toLowerCase().slice(0, 20),
|
|
750
|
+
txt: hidden ? null : accessibleName(el, crole),
|
|
751
|
+
href: hrefFor(el),
|
|
752
|
+
crole,
|
|
753
|
+
ctx: config.maskAllText ? null : clickContext(el)
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
var NON_TEXT_INPUT_TYPES = /* @__PURE__ */ new Set(["button", "submit", "reset", "checkbox", "radio", "file", "image", "color", "range", "hidden"]);
|
|
757
|
+
function isTextEntry(el) {
|
|
758
|
+
const tag = el.tagName.toLowerCase();
|
|
759
|
+
if (tag === "textarea") return true;
|
|
760
|
+
if (tag === "input") {
|
|
761
|
+
return !NON_TEXT_INPUT_TYPES.has((el.getAttribute("type") || "text").toLowerCase());
|
|
762
|
+
}
|
|
763
|
+
return el.isContentEditable === true || el.getAttribute("contenteditable") === "true";
|
|
764
|
+
}
|
|
765
|
+
function isAlreadySelected(el) {
|
|
766
|
+
if (el.getAttribute("aria-pressed") === "true" || el.getAttribute("aria-selected") === "true") return true;
|
|
767
|
+
const current = el.getAttribute("aria-current");
|
|
768
|
+
if (current && current !== "false") return true;
|
|
769
|
+
if (el.tagName.toLowerCase() !== "a") return false;
|
|
770
|
+
const href = (el.getAttribute("href") || "").trim();
|
|
771
|
+
if (!href) return false;
|
|
772
|
+
try {
|
|
773
|
+
const here = window.location;
|
|
774
|
+
const target = new URL(href, here.href);
|
|
775
|
+
return target.origin === here.origin && target.pathname === here.pathname && target.search === here.search;
|
|
776
|
+
} catch {
|
|
777
|
+
return false;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
function isActionable(el) {
|
|
781
|
+
try {
|
|
782
|
+
if (!el.matches(ACTIONABLE_SELECTOR)) return false;
|
|
783
|
+
} catch {
|
|
784
|
+
return false;
|
|
785
|
+
}
|
|
786
|
+
if (el.hasAttribute("disabled") || el.getAttribute("aria-disabled") === "true") return false;
|
|
787
|
+
if (el.tagName.toLowerCase() === "a") {
|
|
788
|
+
const href = (el.getAttribute("href") || "").trim();
|
|
789
|
+
if (el.getAttribute("target") === "_blank" || el.hasAttribute("download")) return false;
|
|
790
|
+
if (/^(mailto:|tel:)/i.test(href)) return false;
|
|
791
|
+
}
|
|
792
|
+
if (isAlreadySelected(el)) return false;
|
|
793
|
+
return true;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
// src/capture/clicks.ts
|
|
797
|
+
var LABEL_FORWARD_MS = 100;
|
|
798
|
+
var NATIVE_PICKER_INPUTS = /* @__PURE__ */ new Set(["file", "date", "time", "datetime-local", "month", "week", "color"]);
|
|
799
|
+
function isElement(node) {
|
|
800
|
+
return !!node && typeof node === "object" && node.nodeType === 1;
|
|
801
|
+
}
|
|
802
|
+
function opensNativePicker(el) {
|
|
803
|
+
return el.tagName === "SELECT" || el.tagName === "INPUT" && NATIVE_PICKER_INPUTS.has(el.type);
|
|
804
|
+
}
|
|
805
|
+
function opensOutsideThePage(el) {
|
|
806
|
+
if (!el) return false;
|
|
807
|
+
try {
|
|
808
|
+
if (opensNativePicker(el) || el.closest("select")) return true;
|
|
809
|
+
if (el.tagName === "LABEL") {
|
|
810
|
+
const control = el.control;
|
|
811
|
+
if (control && opensNativePicker(control)) return true;
|
|
812
|
+
}
|
|
813
|
+
const anchor = el.closest("a");
|
|
814
|
+
if (!anchor) return false;
|
|
815
|
+
if (anchor.hasAttribute("download")) return true;
|
|
816
|
+
const target = (anchor.getAttribute("target") || "").toLowerCase();
|
|
817
|
+
if (target && target !== "_self" && target !== "_parent" && target !== "_top") return true;
|
|
818
|
+
const href = anchor.getAttribute("href") || "";
|
|
819
|
+
if (/^(?:mailto|tel|sms|whatsapp|intent):/i.test(href)) return true;
|
|
820
|
+
if (/^https?:\/\//i.test(href)) return new URL(href, window.location.href).origin !== window.location.origin;
|
|
821
|
+
} catch {
|
|
822
|
+
}
|
|
823
|
+
return false;
|
|
824
|
+
}
|
|
825
|
+
function alreadyActive(el) {
|
|
826
|
+
const control = el.closest("[aria-pressed],[aria-selected],[aria-checked],[aria-current],[aria-disabled]") ?? el;
|
|
827
|
+
if (control.disabled) return true;
|
|
828
|
+
for (const name of ["aria-pressed", "aria-selected", "aria-checked", "aria-disabled"]) {
|
|
829
|
+
if (control.getAttribute(name) === "true") return true;
|
|
830
|
+
}
|
|
831
|
+
const current = control.getAttribute("aria-current");
|
|
832
|
+
return current !== null && current !== "false";
|
|
833
|
+
}
|
|
834
|
+
function selectsText(event, el) {
|
|
835
|
+
if (event.detail < 2) return false;
|
|
836
|
+
const selection = safe(() => window.getSelection());
|
|
837
|
+
if (!selection || selection.isCollapsed || !selection.toString().trim()) return false;
|
|
838
|
+
const anchor = selection.anchorNode;
|
|
839
|
+
return !!anchor && (el.contains(anchor) || anchor.contains(el));
|
|
840
|
+
}
|
|
841
|
+
var round = Math.round;
|
|
842
|
+
var ClickCapture = class {
|
|
843
|
+
constructor(options) {
|
|
844
|
+
this.options = options;
|
|
845
|
+
/** Last DOM change (epoch ms, -1 when none). Snapshots wait for a quiet page too. */
|
|
846
|
+
this.lastMutationAt = -1;
|
|
847
|
+
this.lastExternalAt = -1;
|
|
848
|
+
this.lastScrollAt = -1;
|
|
849
|
+
this.burst = null;
|
|
850
|
+
this.lastDead = null;
|
|
851
|
+
this.lastLabel = null;
|
|
852
|
+
this.mutations = null;
|
|
853
|
+
this.restores = [];
|
|
854
|
+
}
|
|
855
|
+
/** The click listener and the hooks that notice answers outside the page. Cheap: run at `init`. */
|
|
856
|
+
install() {
|
|
857
|
+
const listen = (target, type, handler, capture) => {
|
|
858
|
+
target.addEventListener(type, handler, capture);
|
|
859
|
+
this.restores.push(() => target.removeEventListener(type, handler, capture));
|
|
860
|
+
};
|
|
861
|
+
listen(document, "click", (event) => this.onClick(event), true);
|
|
862
|
+
listen(window, "blur", () => this.noteExternal(), false);
|
|
863
|
+
listen(document, "visibilitychange", () => this.noteExternal(), false);
|
|
864
|
+
this.hookClicksOutsideTheDocument();
|
|
865
|
+
}
|
|
866
|
+
/** The DOM watch that dead clicks need: on idle, it is the heaviest part. */
|
|
867
|
+
watchMutations() {
|
|
868
|
+
if (this.mutations || typeof MutationObserver !== "function" || !document.body) return;
|
|
869
|
+
this.mutations = new MutationObserver(() => {
|
|
870
|
+
this.lastMutationAt = this.options.now();
|
|
871
|
+
});
|
|
872
|
+
this.mutations.observe(document.body, { childList: true, subtree: true, attributes: true, characterData: true });
|
|
873
|
+
}
|
|
874
|
+
/** A form's `invalid` bubble is an answer too. */
|
|
875
|
+
noteMutation() {
|
|
876
|
+
this.lastMutationAt = this.options.now();
|
|
877
|
+
}
|
|
878
|
+
uninstall() {
|
|
879
|
+
for (const restore of this.restores.splice(0)) safe(restore);
|
|
880
|
+
safe(() => this.mutations?.disconnect());
|
|
881
|
+
this.mutations = null;
|
|
882
|
+
this.dropRage();
|
|
883
|
+
}
|
|
884
|
+
/** The page is left: a burst in progress is reported now. */
|
|
885
|
+
flushRage() {
|
|
886
|
+
const burst = this.burst;
|
|
887
|
+
if (!burst) return;
|
|
888
|
+
this.dropRage();
|
|
889
|
+
if (burst.qualified) this.emitRage(burst);
|
|
890
|
+
}
|
|
891
|
+
noteExternal() {
|
|
892
|
+
this.lastExternalAt = this.options.now();
|
|
893
|
+
}
|
|
894
|
+
onClick(event) {
|
|
895
|
+
try {
|
|
896
|
+
const raw = event.target;
|
|
897
|
+
const element = isElement(raw) ? raw : raw?.parentElement ?? null;
|
|
898
|
+
if (!element) return;
|
|
899
|
+
const now = this.options.now();
|
|
900
|
+
const label = this.lastLabel;
|
|
901
|
+
this.lastLabel = null;
|
|
902
|
+
if (label?.control && now - label.at <= LABEL_FORWARD_MS && (label.control === element || label.control.contains(element))) return;
|
|
903
|
+
const subject = interactiveTarget(element) ?? element;
|
|
904
|
+
if (subject.tagName === "LABEL") {
|
|
905
|
+
this.lastLabel = { control: safe(() => subject.control) ?? null, at: now };
|
|
906
|
+
}
|
|
907
|
+
if (opensOutsideThePage(element)) this.lastExternalAt = now;
|
|
908
|
+
const snapshot = { info: describeElement(subject, element), coords: this.coordsOf(event, subject) };
|
|
909
|
+
this.options.emit({ type: "click", ...snapshot.info, ...snapshot.coords });
|
|
910
|
+
if (selectsText(event, subject)) this.dropRage();
|
|
911
|
+
else if (!isTextEntry(subject)) this.trackRage(snapshot);
|
|
912
|
+
this.trackDead(subject, snapshot);
|
|
913
|
+
} catch {
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
coordsOf(event, el) {
|
|
917
|
+
const rect = safe(() => el.getBoundingClientRect()) ?? { left: 0, top: 0, width: 0, height: 0 };
|
|
918
|
+
const scrollX = window.scrollX || 0;
|
|
919
|
+
const scrollY = window.scrollY || 0;
|
|
920
|
+
const keyboard = event.detail === 0 && event.clientX === 0 && event.clientY === 0;
|
|
921
|
+
const clientX = keyboard ? rect.left + rect.width / 2 : event.clientX;
|
|
922
|
+
const clientY = keyboard ? rect.top + rect.height / 2 : event.clientY;
|
|
923
|
+
const vw = window.innerWidth || 1;
|
|
924
|
+
return {
|
|
925
|
+
x: round(clientX + scrollX),
|
|
926
|
+
y: round(clientY + scrollY),
|
|
927
|
+
rx: Math.min(1, Math.max(0, round(clientX / vw * 1e3) / 1e3)),
|
|
928
|
+
ry: round(clientY + scrollY),
|
|
929
|
+
ex: round(rect.left + scrollX),
|
|
930
|
+
ey: round(rect.top + scrollY),
|
|
931
|
+
ew: round(rect.width),
|
|
932
|
+
eh: round(rect.height)
|
|
933
|
+
};
|
|
934
|
+
}
|
|
935
|
+
trackRage(snapshot) {
|
|
936
|
+
const now = this.options.now();
|
|
937
|
+
const { x, y } = snapshot.coords;
|
|
938
|
+
const current = this.burst;
|
|
939
|
+
const lastAt = current?.times[current.times.length - 1] ?? Number.NEGATIVE_INFINITY;
|
|
940
|
+
if (current && now - lastAt <= RAGE_WINDOW_MS && Math.hypot(x - current.x, y - current.y) <= RAGE_RADIUS_PX) {
|
|
941
|
+
current.times.push(now);
|
|
942
|
+
current.last = snapshot;
|
|
943
|
+
} else {
|
|
944
|
+
this.flushRage();
|
|
945
|
+
this.burst = { x, y, times: [now], last: snapshot, qualified: false, timer: null };
|
|
946
|
+
}
|
|
947
|
+
const burst = this.burst;
|
|
948
|
+
if (burst.times.filter((at) => now - at <= RAGE_WINDOW_MS).length >= RAGE_MIN_CLICKS) burst.qualified = true;
|
|
949
|
+
if (!burst.qualified) return;
|
|
950
|
+
if (burst.timer) clearTimeout(burst.timer);
|
|
951
|
+
burst.timer = setTimeout(() => {
|
|
952
|
+
if (this.burst !== burst) return;
|
|
953
|
+
this.burst = null;
|
|
954
|
+
this.emitRage(burst);
|
|
955
|
+
}, RAGE_WINDOW_MS);
|
|
956
|
+
}
|
|
957
|
+
dropRage() {
|
|
958
|
+
if (this.burst?.timer) clearTimeout(this.burst.timer);
|
|
959
|
+
this.burst = null;
|
|
960
|
+
}
|
|
961
|
+
emitRage(burst) {
|
|
962
|
+
this.options.emit({ type: "rage_click", ...burst.last.info, ...burst.last.coords, n: burst.times.length });
|
|
963
|
+
this.options.onTrouble();
|
|
964
|
+
}
|
|
965
|
+
trackDead(el, snapshot) {
|
|
966
|
+
if (!this.mutations || !isActionable(el) || alreadyActive(el)) return;
|
|
967
|
+
const at = this.options.now();
|
|
968
|
+
if (opensOutsideThePage(el)) {
|
|
969
|
+
this.lastExternalAt = at;
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
setTimeout(() => {
|
|
973
|
+
try {
|
|
974
|
+
const answered = this.lastMutationAt >= at || this.options.lastRequestAt() >= at || this.options.lastNavigationAt() >= at || this.lastScrollAt >= at || this.lastExternalAt >= at || safe(() => document.visibilityState) === "hidden";
|
|
975
|
+
if (answered) return;
|
|
976
|
+
const last = this.lastDead;
|
|
977
|
+
if (last && last.sel === snapshot.info.sel && at - last.at < DEAD_DEDUPE_MS) return;
|
|
978
|
+
this.lastDead = { sel: snapshot.info.sel, at };
|
|
979
|
+
this.options.emit({ type: "dead_click", ...snapshot.info, ...snapshot.coords, n: DEAD_WAIT_MS });
|
|
980
|
+
this.options.onTrouble();
|
|
981
|
+
} catch {
|
|
982
|
+
}
|
|
983
|
+
}, DEAD_WAIT_MS);
|
|
984
|
+
}
|
|
985
|
+
/**
|
|
986
|
+
* `input.click()` on a detached file input, `a.click()` on an anchor made
|
|
987
|
+
* for a download, `showPicker()` and scrolling by code never reach the
|
|
988
|
+
* document, so the click that caused them would look dead. The prototypes'
|
|
989
|
+
* methods are wrapped, only to note the time, and restored by `uninstall`.
|
|
990
|
+
*/
|
|
991
|
+
hookClicksOutsideTheDocument() {
|
|
992
|
+
const wrap = (owner, name, note) => {
|
|
993
|
+
const target = owner;
|
|
994
|
+
const original = target?.[name];
|
|
995
|
+
if (!target || typeof original !== "function") return;
|
|
996
|
+
let enabled = true;
|
|
997
|
+
const wrapped = function(...args) {
|
|
998
|
+
if (enabled) safe(() => note(this));
|
|
999
|
+
return original.apply(this, args);
|
|
1000
|
+
};
|
|
1001
|
+
target[name] = wrapped;
|
|
1002
|
+
this.restores.push(() => {
|
|
1003
|
+
enabled = false;
|
|
1004
|
+
if (target[name] === wrapped) target[name] = original;
|
|
1005
|
+
});
|
|
1006
|
+
};
|
|
1007
|
+
const external = () => this.noteExternal();
|
|
1008
|
+
const scrolled = () => {
|
|
1009
|
+
this.lastScrollAt = this.options.now();
|
|
1010
|
+
};
|
|
1011
|
+
wrap(window.HTMLInputElement?.prototype, "click", (self) => {
|
|
1012
|
+
if (self.type === "file") external();
|
|
1013
|
+
});
|
|
1014
|
+
wrap(window.HTMLAnchorElement?.prototype, "click", (self) => {
|
|
1015
|
+
if (opensOutsideThePage(self)) external();
|
|
1016
|
+
});
|
|
1017
|
+
wrap(window.HTMLInputElement?.prototype, "showPicker", external);
|
|
1018
|
+
wrap(window.HTMLSelectElement?.prototype, "showPicker", external);
|
|
1019
|
+
for (const name of ["scrollIntoView", "scrollTo", "scrollBy"]) wrap(window.Element?.prototype, name, scrolled);
|
|
1020
|
+
for (const name of ["scrollTo", "scrollBy"]) wrap(window, name, scrolled);
|
|
1021
|
+
}
|
|
1022
|
+
};
|
|
1023
|
+
|
|
1024
|
+
// src/capture/errors.ts
|
|
1025
|
+
var FRAME_URL_RE = /(?:\(|@|\bat\s)((?:[a-z][a-z0-9+.-]*:\/\/|\[project\]|\[turbopack\]|webpack-internal:)[^\s)]*?)(?::\d+){1,2}\)?\s*$/i;
|
|
1026
|
+
var EXTENSION_RE = /^(?:chrome|moz|safari-web|safari|ms-browser)-extension:\/\//i;
|
|
1027
|
+
var WEB_URL_RE = /^https?:\/\//i;
|
|
1028
|
+
var FOREIGN_MESSAGE_RE = /\bethereum\b|__gCrWeb|webkit\.messageHandlers/;
|
|
1029
|
+
var IGNORED_MESSAGE_RE = /ResizeObserver loop|^Script error\.?$/;
|
|
1030
|
+
var CONTROL_FLOW_DIGEST = "NEXT_";
|
|
1031
|
+
var SEEN_CAP = 200;
|
|
1032
|
+
function stackFrameUrls(stack) {
|
|
1033
|
+
if (!stack) return [];
|
|
1034
|
+
const urls = [];
|
|
1035
|
+
for (const line of stack.split("\n").slice(0, 50)) {
|
|
1036
|
+
const url = FRAME_URL_RE.exec(line.trim())?.[1];
|
|
1037
|
+
if (url) urls.push(url);
|
|
1038
|
+
}
|
|
1039
|
+
return urls;
|
|
1040
|
+
}
|
|
1041
|
+
function isAppFrame(url, page, appFrames) {
|
|
1042
|
+
if (matchesUrl(url, appFrames)) return true;
|
|
1043
|
+
if (!url.startsWith(`${page.origin}/`)) return false;
|
|
1044
|
+
const path = url.slice(page.origin.length).replace(/[?#].*$/, "");
|
|
1045
|
+
return path !== page.pathname;
|
|
1046
|
+
}
|
|
1047
|
+
function isForeignError(report, page, appFrames) {
|
|
1048
|
+
if (report.src !== "window" && report.src !== "promise") return false;
|
|
1049
|
+
if (FOREIGN_MESSAGE_RE.test(report.msg)) return true;
|
|
1050
|
+
const urls = stackFrameUrls(report.stack);
|
|
1051
|
+
if (urls.length === 0) return false;
|
|
1052
|
+
if (urls.some((url) => EXTENSION_RE.test(url))) return true;
|
|
1053
|
+
return urls.every((url) => WEB_URL_RE.test(url) && !isAppFrame(url, page, appFrames));
|
|
1054
|
+
}
|
|
1055
|
+
function text2(value) {
|
|
1056
|
+
if (value === void 0 || value === null) return "";
|
|
1057
|
+
if (typeof value === "string") return value;
|
|
1058
|
+
try {
|
|
1059
|
+
return JSON.stringify(value) ?? String(value);
|
|
1060
|
+
} catch {
|
|
1061
|
+
return String(value);
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
function readError(value) {
|
|
1065
|
+
if (value && typeof value === "object" && typeof value.message === "string") {
|
|
1066
|
+
const error = value;
|
|
1067
|
+
return {
|
|
1068
|
+
name: typeof error.name === "string" && error.name ? error.name : "Error",
|
|
1069
|
+
msg: error.message,
|
|
1070
|
+
stack: typeof error.stack === "string" ? error.stack : null,
|
|
1071
|
+
digest: typeof error.digest === "string" && error.digest ? error.digest : null
|
|
1072
|
+
};
|
|
1073
|
+
}
|
|
1074
|
+
return { name: "Error", msg: text2(value), stack: null, digest: null };
|
|
1075
|
+
}
|
|
1076
|
+
var ErrorFilter = class {
|
|
1077
|
+
constructor(options) {
|
|
1078
|
+
this.options = options;
|
|
1079
|
+
this.seen = /* @__PURE__ */ new Map();
|
|
1080
|
+
this.times = [];
|
|
1081
|
+
}
|
|
1082
|
+
/** The event's fields, or null when the error is not sent. */
|
|
1083
|
+
accept(report) {
|
|
1084
|
+
const { debug } = this.options;
|
|
1085
|
+
if (report.digest?.startsWith(CONTROL_FLOW_DIGEST)) return null;
|
|
1086
|
+
if (report.src === "window" && (!report.msg || IGNORED_MESSAGE_RE.test(report.msg))) return null;
|
|
1087
|
+
if (isForeignError(report, this.options.location(), this.options.appFrames)) {
|
|
1088
|
+
debug(`error not sent, not the app's: ${report.msg}`);
|
|
1089
|
+
return null;
|
|
1090
|
+
}
|
|
1091
|
+
if (matchesText(report.msg, this.options.ignoreErrors)) {
|
|
1092
|
+
debug(`error not sent, in ignoreErrors: ${report.msg}`);
|
|
1093
|
+
return null;
|
|
1094
|
+
}
|
|
1095
|
+
const name = report.name.slice(0, CHARS.name) || "Error";
|
|
1096
|
+
const msg = scrubEmails(report.msg).slice(0, CHARS.message);
|
|
1097
|
+
const stack = report.stack ? scrubEmails(report.stack).slice(0, CHARS.stack) : null;
|
|
1098
|
+
const digest = report.digest ? report.digest.slice(0, CHARS.digest) : null;
|
|
1099
|
+
const fp = errorFingerprint({ name, message: msg, stack, digest });
|
|
1100
|
+
if (!this.admit(fp)) {
|
|
1101
|
+
debug(`error not sent, repeated or over ${ERRORS_PER_MINUTE} a minute: ${msg}`);
|
|
1102
|
+
return null;
|
|
1103
|
+
}
|
|
1104
|
+
return { type: "error", name, msg, stack, digest, src: report.src, fp };
|
|
1105
|
+
}
|
|
1106
|
+
/** Once per fingerprint per 5 s, and 20 a minute. */
|
|
1107
|
+
admit(fp) {
|
|
1108
|
+
const now = this.options.now();
|
|
1109
|
+
const last = this.seen.get(fp);
|
|
1110
|
+
if (last !== void 0 && now - last < ERROR_DEDUPE_MS) return false;
|
|
1111
|
+
this.times = this.times.filter((at) => now - at < 6e4);
|
|
1112
|
+
if (this.times.length >= ERRORS_PER_MINUTE) return false;
|
|
1113
|
+
this.seen.set(fp, now);
|
|
1114
|
+
this.times.push(now);
|
|
1115
|
+
if (this.seen.size > SEEN_CAP) {
|
|
1116
|
+
for (const [key, at] of this.seen) if (now - at >= ERROR_DEDUPE_MS) this.seen.delete(key);
|
|
1117
|
+
}
|
|
1118
|
+
return true;
|
|
1119
|
+
}
|
|
1120
|
+
};
|
|
1121
|
+
|
|
1122
|
+
// src/capture/forms.ts
|
|
1123
|
+
var VALIDITY_KEYS = [
|
|
1124
|
+
"valueMissing",
|
|
1125
|
+
"typeMismatch",
|
|
1126
|
+
"patternMismatch",
|
|
1127
|
+
"tooShort",
|
|
1128
|
+
"tooLong",
|
|
1129
|
+
"rangeUnderflow",
|
|
1130
|
+
"rangeOverflow",
|
|
1131
|
+
"stepMismatch",
|
|
1132
|
+
"badInput",
|
|
1133
|
+
"customError"
|
|
1134
|
+
];
|
|
1135
|
+
var FormCapture = class {
|
|
1136
|
+
constructor(options) {
|
|
1137
|
+
this.options = options;
|
|
1138
|
+
this.lastAt = Number.NEGATIVE_INFINITY;
|
|
1139
|
+
this.remove = null;
|
|
1140
|
+
}
|
|
1141
|
+
install() {
|
|
1142
|
+
const handler = (event) => this.onInvalid(event);
|
|
1143
|
+
document.addEventListener("invalid", handler, true);
|
|
1144
|
+
this.remove = () => document.removeEventListener("invalid", handler, true);
|
|
1145
|
+
}
|
|
1146
|
+
uninstall() {
|
|
1147
|
+
this.remove?.();
|
|
1148
|
+
this.remove = null;
|
|
1149
|
+
}
|
|
1150
|
+
onInvalid(event) {
|
|
1151
|
+
try {
|
|
1152
|
+
const el = event.target;
|
|
1153
|
+
if (!(el instanceof Element)) return;
|
|
1154
|
+
this.options.onAnswer();
|
|
1155
|
+
const now = this.options.now();
|
|
1156
|
+
if (now - this.lastAt < FORM_INVALID_DEDUPE_MS) return;
|
|
1157
|
+
this.lastAt = now;
|
|
1158
|
+
const info = describeElement(el);
|
|
1159
|
+
const validity = el.validity;
|
|
1160
|
+
const reason = validity ? VALIDITY_KEYS.find((key) => validity[key]) ?? null : null;
|
|
1161
|
+
this.options.emit({ type: "form_invalid", field: info.txt, ctx: info.ctx, reason, sel: info.sel });
|
|
1162
|
+
} catch {
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
};
|
|
1166
|
+
|
|
1167
|
+
// src/capture/navigation.ts
|
|
1168
|
+
var PENDING_MS = 5e3;
|
|
1169
|
+
var NavigationWatch = class {
|
|
1170
|
+
constructor(now, hashRouting) {
|
|
1171
|
+
this.now = now;
|
|
1172
|
+
this.hashRouting = hashRouting;
|
|
1173
|
+
this.restores = [];
|
|
1174
|
+
this.pending = null;
|
|
1175
|
+
}
|
|
1176
|
+
/** Calls `listener` after each `pushState`, `replaceState`, back or forward (and hash change for hash routers). */
|
|
1177
|
+
install(listener) {
|
|
1178
|
+
const history = safe(() => window.history);
|
|
1179
|
+
if (history) {
|
|
1180
|
+
for (const [name, kind] of [["pushState", "push"], ["replaceState", "replace"]]) {
|
|
1181
|
+
const original = history[name];
|
|
1182
|
+
let enabled = true;
|
|
1183
|
+
const wrapped = function(...args) {
|
|
1184
|
+
const result = original.apply(this, args);
|
|
1185
|
+
if (enabled) safe(() => listener(kind));
|
|
1186
|
+
return result;
|
|
1187
|
+
};
|
|
1188
|
+
history[name] = wrapped;
|
|
1189
|
+
this.restores.push(() => {
|
|
1190
|
+
enabled = false;
|
|
1191
|
+
if (history[name] === wrapped) history[name] = original;
|
|
1192
|
+
});
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
const traverse = () => listener("traverse");
|
|
1196
|
+
window.addEventListener("popstate", traverse);
|
|
1197
|
+
this.restores.push(() => window.removeEventListener("popstate", traverse));
|
|
1198
|
+
if (this.hashRouting) {
|
|
1199
|
+
const hash = () => listener("push");
|
|
1200
|
+
window.addEventListener("hashchange", hash);
|
|
1201
|
+
this.restores.push(() => window.removeEventListener("hashchange", hash));
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
uninstall() {
|
|
1205
|
+
for (const restore of this.restores.splice(0)) safe(restore);
|
|
1206
|
+
this.pending = null;
|
|
1207
|
+
}
|
|
1208
|
+
/** A framework announced `path` before the address changed. */
|
|
1209
|
+
announce(path, addressNow) {
|
|
1210
|
+
this.pending = path === addressNow ? null : { path, since: this.now() };
|
|
1211
|
+
}
|
|
1212
|
+
/**
|
|
1213
|
+
* The path the page is on: the announced one while it has not landed (and
|
|
1214
|
+
* is recent), else the address bar's.
|
|
1215
|
+
*/
|
|
1216
|
+
resolve(address) {
|
|
1217
|
+
const pending = this.pending;
|
|
1218
|
+
if (!pending) return address;
|
|
1219
|
+
if (pending.path === address || this.now() - pending.since >= PENDING_MS) {
|
|
1220
|
+
this.pending = null;
|
|
1221
|
+
return address;
|
|
1222
|
+
}
|
|
1223
|
+
return pending.path;
|
|
1224
|
+
}
|
|
1225
|
+
};
|
|
1226
|
+
|
|
1227
|
+
// src/capture/failure-detail.ts
|
|
1228
|
+
var CODE_RE = /^[A-Za-z][A-Za-z0-9_.:-]*$/;
|
|
1229
|
+
function clamp(value, max) {
|
|
1230
|
+
const clean = value.replace(/\s+/g, " ").trim();
|
|
1231
|
+
return clean.length > max ? `${clean.slice(0, max - 1)}\u2026` : clean;
|
|
1232
|
+
}
|
|
1233
|
+
function asText(value) {
|
|
1234
|
+
return typeof value === "string" && value.trim() ? value : null;
|
|
1235
|
+
}
|
|
1236
|
+
function failureDetailFrom(body) {
|
|
1237
|
+
if (!body || typeof body !== "object") return null;
|
|
1238
|
+
const record = body;
|
|
1239
|
+
const error = asText(record.error);
|
|
1240
|
+
const message = asText(record.message);
|
|
1241
|
+
let code = asText(record.code) ?? asText(record.error_code);
|
|
1242
|
+
let msg = error ?? message;
|
|
1243
|
+
if (!code && error && CODE_RE.test(error) && error.toUpperCase() === error && error.includes("_")) {
|
|
1244
|
+
code = error;
|
|
1245
|
+
msg = message;
|
|
1246
|
+
}
|
|
1247
|
+
if (code && !CODE_RE.test(code)) code = null;
|
|
1248
|
+
if (!code && !msg) return null;
|
|
1249
|
+
return {
|
|
1250
|
+
code: code ? clamp(code, CHARS.code) : null,
|
|
1251
|
+
msg: msg ? clamp(scrubEmails(msg), CHARS.failureMessage) : null
|
|
1252
|
+
};
|
|
1253
|
+
}
|
|
1254
|
+
function failureDetailOfText(contentType, body) {
|
|
1255
|
+
if (!contentType?.includes("json")) return null;
|
|
1256
|
+
try {
|
|
1257
|
+
return failureDetailFrom(JSON.parse(body));
|
|
1258
|
+
} catch {
|
|
1259
|
+
return null;
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
// src/capture/requests.ts
|
|
1264
|
+
var RequestCapture = class {
|
|
1265
|
+
constructor(options, onCall) {
|
|
1266
|
+
this.options = options;
|
|
1267
|
+
this.onCall = onCall;
|
|
1268
|
+
this.restores = [];
|
|
1269
|
+
}
|
|
1270
|
+
/** How a call to `rawUrl` is treated, or null when it is not recorded. */
|
|
1271
|
+
plan(rawUrl) {
|
|
1272
|
+
const url = safe(() => new URL(rawUrl, window.location.href));
|
|
1273
|
+
if (!url || url.protocol !== "http:" && url.protocol !== "https:") return null;
|
|
1274
|
+
const href = url.href;
|
|
1275
|
+
if (href.startsWith(this.options.sypniaUrl())) return null;
|
|
1276
|
+
if (matchesUrl(href, this.options.ignoreRequests)) return null;
|
|
1277
|
+
const own = url.origin === window.location.origin;
|
|
1278
|
+
const traced = own || matchesUrl(href, this.options.traceTargets);
|
|
1279
|
+
if (!traced && !matchesUrl(href, this.options.recordTargets)) return null;
|
|
1280
|
+
let path;
|
|
1281
|
+
try {
|
|
1282
|
+
path = this.options.routeFor(url.pathname) || url.pathname;
|
|
1283
|
+
} catch {
|
|
1284
|
+
path = url.pathname;
|
|
1285
|
+
}
|
|
1286
|
+
return { headers: traced, host: own ? null : url.host.slice(0, CHARS.host), path: path.slice(0, CHARS.path) };
|
|
1287
|
+
}
|
|
1288
|
+
/** Starts recording a call, or null when it is not recorded. */
|
|
1289
|
+
start(rawUrl, rawMethod) {
|
|
1290
|
+
const plan = this.plan(rawUrl);
|
|
1291
|
+
if (!plan) return null;
|
|
1292
|
+
const sid = this.options.session();
|
|
1293
|
+
if (!sid) return null;
|
|
1294
|
+
const tid = newTraceId();
|
|
1295
|
+
const span = newSpanId();
|
|
1296
|
+
const method = (rawMethod || "GET").toUpperCase().slice(0, 10);
|
|
1297
|
+
const startedAt = this.options.now();
|
|
1298
|
+
const headers = plan.headers ? { [TRACEPARENT_HEADER]: formatTraceparent(tid, span), [SESSION_HEADER]: sid } : {};
|
|
1299
|
+
let done = false;
|
|
1300
|
+
this.onCall("start", tid);
|
|
1301
|
+
const finish = () => {
|
|
1302
|
+
if (done) return false;
|
|
1303
|
+
done = true;
|
|
1304
|
+
this.onCall("end", tid);
|
|
1305
|
+
return true;
|
|
1306
|
+
};
|
|
1307
|
+
const record = (status, endedAt, detail) => this.options.emit(
|
|
1308
|
+
{
|
|
1309
|
+
type: "request",
|
|
1310
|
+
method,
|
|
1311
|
+
host: plan.host,
|
|
1312
|
+
path: plan.path,
|
|
1313
|
+
status,
|
|
1314
|
+
dur: Math.max(0, Math.round(endedAt - startedAt)),
|
|
1315
|
+
tid,
|
|
1316
|
+
span,
|
|
1317
|
+
...status >= 400 && detail?.code ? { code: detail.code } : {},
|
|
1318
|
+
...status >= 400 && detail?.msg ? { msg: detail.msg } : {}
|
|
1319
|
+
},
|
|
1320
|
+
// The session the server saw in the header, even if it changed meanwhile.
|
|
1321
|
+
{ sid, ts: startedAt }
|
|
1322
|
+
);
|
|
1323
|
+
return {
|
|
1324
|
+
headers,
|
|
1325
|
+
abort: () => void finish(),
|
|
1326
|
+
end: (status, detail = null) => {
|
|
1327
|
+
if (!finish()) return;
|
|
1328
|
+
const endedAt = this.options.now();
|
|
1329
|
+
if (status > 0) {
|
|
1330
|
+
record(status, endedAt, detail);
|
|
1331
|
+
return;
|
|
1332
|
+
}
|
|
1333
|
+
setTimeout(() => {
|
|
1334
|
+
if (this.options.lastPageHideAt() < startedAt) safe(() => record(0, endedAt, null));
|
|
1335
|
+
}, UNANSWERED_GRACE_MS);
|
|
1336
|
+
}
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
install() {
|
|
1340
|
+
safe(() => this.installFetch());
|
|
1341
|
+
safe(() => this.installXhr());
|
|
1342
|
+
}
|
|
1343
|
+
uninstall() {
|
|
1344
|
+
for (const restore of this.restores.splice(0)) safe(restore);
|
|
1345
|
+
}
|
|
1346
|
+
installFetch() {
|
|
1347
|
+
const original = window.fetch;
|
|
1348
|
+
if (typeof original !== "function") return;
|
|
1349
|
+
let enabled = true;
|
|
1350
|
+
const capture = this;
|
|
1351
|
+
const wrapped = function(input, init2) {
|
|
1352
|
+
const traced = enabled ? safe(() => capture.traceFetch(input, init2)) : void 0;
|
|
1353
|
+
if (!traced) return original.call(window, input, init2);
|
|
1354
|
+
const promise = original.call(window, traced.input, traced.init);
|
|
1355
|
+
capture.observeFetch(promise, traced.trace, traced.signal);
|
|
1356
|
+
return promise;
|
|
1357
|
+
};
|
|
1358
|
+
window.fetch = wrapped;
|
|
1359
|
+
this.restores.push(() => {
|
|
1360
|
+
enabled = false;
|
|
1361
|
+
if (window.fetch === wrapped) window.fetch = original;
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
/** The traced arguments of a `fetch`, or null when the call is not recorded. */
|
|
1365
|
+
traceFetch(input, init2) {
|
|
1366
|
+
const request = typeof Request === "function" && input instanceof Request ? input : null;
|
|
1367
|
+
const url = request ? request.url : input instanceof URL ? input.href : String(input);
|
|
1368
|
+
const trace = this.start(url, init2?.method ?? request?.method);
|
|
1369
|
+
if (!trace) return null;
|
|
1370
|
+
const signal = init2?.signal ?? request?.signal ?? null;
|
|
1371
|
+
if (Object.keys(trace.headers).length === 0) return { input, init: init2, trace, signal };
|
|
1372
|
+
const headers = new Headers(init2?.headers ?? request?.headers);
|
|
1373
|
+
for (const [name, value] of Object.entries(trace.headers)) if (!headers.has(name)) headers.set(name, value);
|
|
1374
|
+
return request && !init2 ? { input: new Request(request, { headers }), init: init2, trace, signal } : { input, init: { ...init2, headers }, trace, signal };
|
|
1375
|
+
}
|
|
1376
|
+
observeFetch(promise, trace, signal) {
|
|
1377
|
+
promise.then(
|
|
1378
|
+
(response) => {
|
|
1379
|
+
if (response.status < 400 || !this.options.failureDetail) {
|
|
1380
|
+
trace.end(response.status);
|
|
1381
|
+
return;
|
|
1382
|
+
}
|
|
1383
|
+
const copy = safe(() => response.clone());
|
|
1384
|
+
const type = safe(() => response.headers.get("content-type")) ?? null;
|
|
1385
|
+
if (!copy || !type?.includes("json")) {
|
|
1386
|
+
trace.end(response.status);
|
|
1387
|
+
return;
|
|
1388
|
+
}
|
|
1389
|
+
copy.json().then(
|
|
1390
|
+
(body) => trace.end(response.status, failureDetailFrom(body)),
|
|
1391
|
+
() => trace.end(response.status)
|
|
1392
|
+
);
|
|
1393
|
+
},
|
|
1394
|
+
(error) => {
|
|
1395
|
+
const aborted = signal?.aborted === true || error?.name === "AbortError";
|
|
1396
|
+
if (aborted) trace.abort();
|
|
1397
|
+
else trace.end(0);
|
|
1398
|
+
}
|
|
1399
|
+
);
|
|
1400
|
+
}
|
|
1401
|
+
installXhr() {
|
|
1402
|
+
const proto = window.XMLHttpRequest?.prototype;
|
|
1403
|
+
if (!proto) return;
|
|
1404
|
+
const { open, send, setRequestHeader } = proto;
|
|
1405
|
+
const calls = /* @__PURE__ */ new WeakMap();
|
|
1406
|
+
let enabled = true;
|
|
1407
|
+
const capture = this;
|
|
1408
|
+
proto.open = function(method, url, ...rest) {
|
|
1409
|
+
safe(() => calls.set(this, { method, url: String(url), set: /* @__PURE__ */ new Set() }));
|
|
1410
|
+
return open.call(this, method, url, ...rest);
|
|
1411
|
+
};
|
|
1412
|
+
proto.setRequestHeader = function(name, value) {
|
|
1413
|
+
safe(() => calls.get(this)?.set.add(name.toLowerCase()));
|
|
1414
|
+
return setRequestHeader.call(this, name, value);
|
|
1415
|
+
};
|
|
1416
|
+
proto.send = function(body) {
|
|
1417
|
+
const call = calls.get(this);
|
|
1418
|
+
const trace = enabled && call ? safe(() => capture.start(call.url, call.method)) : void 0;
|
|
1419
|
+
if (trace && call) {
|
|
1420
|
+
for (const [name, value] of Object.entries(trace.headers)) {
|
|
1421
|
+
if (!call.set.has(name)) safe(() => setRequestHeader.call(this, name, value));
|
|
1422
|
+
}
|
|
1423
|
+
capture.observeXhr(this, trace);
|
|
1424
|
+
}
|
|
1425
|
+
return send.call(this, body);
|
|
1426
|
+
};
|
|
1427
|
+
this.restores.push(() => {
|
|
1428
|
+
enabled = false;
|
|
1429
|
+
proto.open = open;
|
|
1430
|
+
proto.send = send;
|
|
1431
|
+
proto.setRequestHeader = setRequestHeader;
|
|
1432
|
+
});
|
|
1433
|
+
}
|
|
1434
|
+
observeXhr(xhr, trace) {
|
|
1435
|
+
let aborted = false;
|
|
1436
|
+
xhr.addEventListener("abort", () => {
|
|
1437
|
+
aborted = true;
|
|
1438
|
+
trace.abort();
|
|
1439
|
+
});
|
|
1440
|
+
xhr.addEventListener("loadend", () => {
|
|
1441
|
+
if (aborted) return;
|
|
1442
|
+
const status = xhr.status;
|
|
1443
|
+
trace.end(status, status >= 400 && this.options.failureDetail ? this.xhrDetail(xhr) : null);
|
|
1444
|
+
});
|
|
1445
|
+
}
|
|
1446
|
+
xhrDetail(xhr) {
|
|
1447
|
+
return safe(() => {
|
|
1448
|
+
const type = xhr.getResponseHeader("content-type");
|
|
1449
|
+
if (xhr.responseType === "json") return type?.includes("json") ? failureDetailFrom(xhr.response) : null;
|
|
1450
|
+
if (xhr.responseType !== "" && xhr.responseType !== "text") return null;
|
|
1451
|
+
return failureDetailOfText(type, xhr.responseText);
|
|
1452
|
+
}) ?? null;
|
|
1453
|
+
}
|
|
1454
|
+
};
|
|
1455
|
+
|
|
1456
|
+
// src/capture/vitals.ts
|
|
1457
|
+
var MAX = { LCP: 12e4, FCP: 12e4, TTFB: 12e4, INP: 6e4, CLS: 10 };
|
|
1458
|
+
var THRESHOLDS = {
|
|
1459
|
+
LCP: [2500, 4e3],
|
|
1460
|
+
INP: [200, 500],
|
|
1461
|
+
CLS: [0.1, 0.25],
|
|
1462
|
+
TTFB: [800, 1800],
|
|
1463
|
+
FCP: [1800, 3e3]
|
|
1464
|
+
};
|
|
1465
|
+
var SHIFT_GAP_MS = 1e3;
|
|
1466
|
+
var SHIFT_WINDOW_MS = 5e3;
|
|
1467
|
+
var INTERACTIONS_KEPT = 10;
|
|
1468
|
+
function isPlausibleVital(name, value) {
|
|
1469
|
+
return Number.isFinite(value) && value >= 0 && value <= MAX[name];
|
|
1470
|
+
}
|
|
1471
|
+
function ratingOf(name, value) {
|
|
1472
|
+
const [good, poor] = THRESHOLDS[name];
|
|
1473
|
+
return value <= good ? "good" : value <= poor ? "needs-improvement" : "poor";
|
|
1474
|
+
}
|
|
1475
|
+
function targetOf(node, kind) {
|
|
1476
|
+
const sel = vitalTarget(node);
|
|
1477
|
+
return { ...sel ? { sel } : {}, ...kind ? { kind } : {} };
|
|
1478
|
+
}
|
|
1479
|
+
function movedArea(source) {
|
|
1480
|
+
const area = (rect) => Math.max(0, rect.width) * Math.max(0, rect.height);
|
|
1481
|
+
return Math.max(area(source.previousRect), area(source.currentRect));
|
|
1482
|
+
}
|
|
1483
|
+
var VitalsCapture = class {
|
|
1484
|
+
constructor(options) {
|
|
1485
|
+
this.options = options;
|
|
1486
|
+
this.perPage = null;
|
|
1487
|
+
this.observers = [];
|
|
1488
|
+
this.lcp = null;
|
|
1489
|
+
this.lcpDone = false;
|
|
1490
|
+
/** When the tab was first hidden: load values after it are not the person's experience. */
|
|
1491
|
+
this.firstHiddenAt = Number.POSITIVE_INFINITY;
|
|
1492
|
+
this.started = false;
|
|
1493
|
+
}
|
|
1494
|
+
/** Starts observing, when the browser is idle. Entries before it are read from the buffer. */
|
|
1495
|
+
start() {
|
|
1496
|
+
if (this.started || typeof PerformanceObserver !== "function") return;
|
|
1497
|
+
this.started = true;
|
|
1498
|
+
if (safe(() => document.visibilityState) === "hidden") this.firstHiddenAt = 0;
|
|
1499
|
+
const endLcp = () => this.finishLcp();
|
|
1500
|
+
for (const type of ["keydown", "click"]) addEventListener(type, endLcp, { once: true, capture: true });
|
|
1501
|
+
this.observe("largest-contentful-paint", (entries) => this.onLcp(entries));
|
|
1502
|
+
this.observe("layout-shift", (entries) => this.onShifts(entries));
|
|
1503
|
+
this.observe("event", (entries) => this.onInteractions(entries), { durationThreshold: 40 });
|
|
1504
|
+
this.observe("first-input", (entries) => this.onInteractions(entries));
|
|
1505
|
+
this.reportLoad();
|
|
1506
|
+
}
|
|
1507
|
+
stop() {
|
|
1508
|
+
for (const observer of this.observers.splice(0)) safe(() => observer.disconnect());
|
|
1509
|
+
}
|
|
1510
|
+
/** A page became current: its INP and CLS start from nothing. */
|
|
1511
|
+
pageStarted(page) {
|
|
1512
|
+
this.perPage = { page, interactions: [], count: 0, cls: 0, clsTarget: {}, window: null, inpSent: -1, clsSent: -1 };
|
|
1513
|
+
}
|
|
1514
|
+
/** The page is left or the tab hidden: the load's LCP closes, the page's INP and CLS go when they got worse. */
|
|
1515
|
+
pageLeft(page) {
|
|
1516
|
+
if (safe(() => document.visibilityState) === "hidden") this.firstHiddenAt = Math.min(this.firstHiddenAt, performance.now());
|
|
1517
|
+
this.takeRecords();
|
|
1518
|
+
this.finishLcp();
|
|
1519
|
+
const state = this.perPage;
|
|
1520
|
+
if (!this.started || !state || state.page.url !== page.url) return;
|
|
1521
|
+
const inp = this.inpOf(state);
|
|
1522
|
+
if (inp && inp.duration > state.inpSent) {
|
|
1523
|
+
state.inpSent = inp.duration;
|
|
1524
|
+
this.send("INP", Math.round(inp.duration), inp.target, page);
|
|
1525
|
+
}
|
|
1526
|
+
if (state.cls > state.clsSent || state.clsSent < 0 && this.supports("layout-shift")) {
|
|
1527
|
+
state.clsSent = state.cls;
|
|
1528
|
+
this.send("CLS", Math.round(state.cls * 1e4) / 1e4, state.clsTarget, page);
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
supports(type) {
|
|
1532
|
+
return safe(() => PerformanceObserver.supportedEntryTypes?.includes(type)) === true;
|
|
1533
|
+
}
|
|
1534
|
+
observe(type, handle, extra = {}) {
|
|
1535
|
+
if (!this.supports(type)) return;
|
|
1536
|
+
safe(() => {
|
|
1537
|
+
const observer = new PerformanceObserver((list2) => safe(() => handle(list2.getEntries())));
|
|
1538
|
+
observer.observe({ type, buffered: true, ...extra });
|
|
1539
|
+
this.observers.push(observer);
|
|
1540
|
+
});
|
|
1541
|
+
}
|
|
1542
|
+
/** Reads what the observers hold but have not delivered yet (the tab is going away). */
|
|
1543
|
+
takeRecords() {
|
|
1544
|
+
for (const observer of this.observers) {
|
|
1545
|
+
const entries = safe(() => observer.takeRecords()) ?? [];
|
|
1546
|
+
if (entries.length === 0) continue;
|
|
1547
|
+
const type = entries[0]?.entryType;
|
|
1548
|
+
if (type === "largest-contentful-paint") this.onLcp(entries);
|
|
1549
|
+
else if (type === "layout-shift") this.onShifts(entries);
|
|
1550
|
+
else this.onInteractions(entries);
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
activationStart() {
|
|
1554
|
+
const navigation = safe(() => performance.getEntriesByType("navigation")[0]);
|
|
1555
|
+
return navigation?.activationStart ?? 0;
|
|
1556
|
+
}
|
|
1557
|
+
/** TTFB and FCP of the load. */
|
|
1558
|
+
reportLoad() {
|
|
1559
|
+
const page = this.options.landing();
|
|
1560
|
+
if (!page) return;
|
|
1561
|
+
const activation = this.activationStart();
|
|
1562
|
+
const navigation = safe(() => performance.getEntriesByType("navigation")[0]);
|
|
1563
|
+
if (navigation && navigation.responseStart > 0) this.send("TTFB", Math.max(0, Math.round(navigation.responseStart - activation)), {}, page);
|
|
1564
|
+
const report = (entries) => {
|
|
1565
|
+
const fcp = entries.find((entry) => entry.name === "first-contentful-paint");
|
|
1566
|
+
if (fcp && fcp.startTime < this.firstHiddenAt) this.send("FCP", Math.max(0, Math.round(fcp.startTime - activation)), {}, page);
|
|
1567
|
+
};
|
|
1568
|
+
const buffered = safe(() => performance.getEntriesByType("paint")) ?? [];
|
|
1569
|
+
if (buffered.some((entry) => entry.name === "first-contentful-paint")) report(buffered);
|
|
1570
|
+
else this.observe("paint", report);
|
|
1571
|
+
}
|
|
1572
|
+
onLcp(entries) {
|
|
1573
|
+
if (this.lcpDone) return;
|
|
1574
|
+
const last = entries[entries.length - 1];
|
|
1575
|
+
if (!last || last.startTime >= this.firstHiddenAt) return;
|
|
1576
|
+
const kind = last.url ? "image" : "text";
|
|
1577
|
+
this.lcp = { value: Math.max(0, last.startTime - this.activationStart()), target: targetOf(last.element, kind) };
|
|
1578
|
+
}
|
|
1579
|
+
finishLcp() {
|
|
1580
|
+
if (this.lcpDone || !this.started) return;
|
|
1581
|
+
this.takeRecords();
|
|
1582
|
+
this.lcpDone = true;
|
|
1583
|
+
const page = this.options.landing();
|
|
1584
|
+
if (this.lcp && page) this.send("LCP", Math.round(this.lcp.value), this.lcp.target, page);
|
|
1585
|
+
}
|
|
1586
|
+
onShifts(entries) {
|
|
1587
|
+
const state = this.perPage;
|
|
1588
|
+
if (!state) return;
|
|
1589
|
+
for (const entry of entries) {
|
|
1590
|
+
if (entry.hadRecentInput) continue;
|
|
1591
|
+
const source = (entry.sources ?? []).reduce((best, item) => {
|
|
1592
|
+
const area = movedArea(item);
|
|
1593
|
+
return !best || area > best.area ? { node: item.node, area } : best;
|
|
1594
|
+
}, null);
|
|
1595
|
+
const current = state.window;
|
|
1596
|
+
const joins = current && entry.startTime - current.last < SHIFT_GAP_MS && entry.startTime - current.first < SHIFT_WINDOW_MS;
|
|
1597
|
+
if (!current || !joins) {
|
|
1598
|
+
state.window = { value: 0, first: entry.startTime, last: entry.startTime, largest: 0, target: {} };
|
|
1599
|
+
}
|
|
1600
|
+
const window2 = state.window;
|
|
1601
|
+
window2.value += entry.value;
|
|
1602
|
+
window2.last = entry.startTime;
|
|
1603
|
+
if (entry.value > window2.largest) {
|
|
1604
|
+
window2.largest = entry.value;
|
|
1605
|
+
window2.target = targetOf(source?.node);
|
|
1606
|
+
}
|
|
1607
|
+
if (window2.value > state.cls) {
|
|
1608
|
+
state.cls = window2.value;
|
|
1609
|
+
state.clsTarget = window2.target;
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
onInteractions(entries) {
|
|
1614
|
+
const state = this.perPage;
|
|
1615
|
+
if (!state) return;
|
|
1616
|
+
for (const entry of entries) {
|
|
1617
|
+
const id = entry.interactionId ?? 0;
|
|
1618
|
+
if (!id) continue;
|
|
1619
|
+
const known = state.interactions.find((item) => item.id === id);
|
|
1620
|
+
if (known) {
|
|
1621
|
+
if (entry.duration > known.duration) known.duration = entry.duration;
|
|
1622
|
+
continue;
|
|
1623
|
+
}
|
|
1624
|
+
state.count++;
|
|
1625
|
+
const kind = /^key/.test(entry.name) ? "keyboard" : "pointer";
|
|
1626
|
+
state.interactions.push({ id, duration: entry.duration, target: targetOf(entry.target, kind) });
|
|
1627
|
+
state.interactions.sort((a, b) => b.duration - a.duration);
|
|
1628
|
+
state.interactions.length = Math.min(state.interactions.length, INTERACTIONS_KEPT);
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
/** The interaction at the 98th percentile: the worst, skipping one per fifty interactions. */
|
|
1632
|
+
inpOf(state) {
|
|
1633
|
+
const index = Math.min(state.interactions.length - 1, Math.floor(state.count / 50));
|
|
1634
|
+
return state.interactions[index] ?? null;
|
|
1635
|
+
}
|
|
1636
|
+
send(name, value, target, page) {
|
|
1637
|
+
if (!isPlausibleVital(name, value)) return;
|
|
1638
|
+
this.options.emit({ type: "vital", name, value, rating: ratingOf(name, value), ...target }, { page });
|
|
1639
|
+
}
|
|
1640
|
+
};
|
|
1641
|
+
|
|
1642
|
+
// src/runtime.ts
|
|
1643
|
+
var ACTIVITY = /* @__PURE__ */ new Set(["page_view", "click", "rage_click", "dead_click", "identify"]);
|
|
1644
|
+
var URGENT_WHEN_HIDDEN = /* @__PURE__ */ new Set(["vital", "page_leave", "error"]);
|
|
1645
|
+
var INPUT_TOUCH_EVERY_MS = 1e3;
|
|
1646
|
+
var CONFIG_TIMEOUT_MS = 4e3;
|
|
1647
|
+
var Runtime = class {
|
|
1648
|
+
constructor(options, deps) {
|
|
1649
|
+
this.options = options;
|
|
1650
|
+
this.deps = deps;
|
|
1651
|
+
this.identity = null;
|
|
1652
|
+
/** The identify event last sent, per session: the same one again sends nothing. */
|
|
1653
|
+
this.identifySent = null;
|
|
1654
|
+
this.page = null;
|
|
1655
|
+
this.landing = null;
|
|
1656
|
+
this.lang = null;
|
|
1657
|
+
this.lastSid = null;
|
|
1658
|
+
this.decision = null;
|
|
1659
|
+
this.slowDown = null;
|
|
1660
|
+
this.recorder = null;
|
|
1661
|
+
this.recorderLoading = false;
|
|
1662
|
+
this.active = false;
|
|
1663
|
+
this.idleReady = false;
|
|
1664
|
+
this.cleanups = [];
|
|
1665
|
+
this.inflight = /* @__PURE__ */ new Set();
|
|
1666
|
+
this.lastRequestAt = -1;
|
|
1667
|
+
this.lastNavigationAt = -1;
|
|
1668
|
+
this.lastPageHideAt = -1;
|
|
1669
|
+
this.lastInputAt = Number.NEGATIVE_INFINITY;
|
|
1670
|
+
this.flushScheduled = false;
|
|
1671
|
+
this.scrollScheduled = false;
|
|
1672
|
+
/** Resolves once the idle work of `start()` is done (tests). */
|
|
1673
|
+
this.ready = Promise.resolve();
|
|
1674
|
+
this.now = deps.now ?? Date.now;
|
|
1675
|
+
this.random = deps.random ?? Math.random;
|
|
1676
|
+
this.fetch = window.fetch.bind(window);
|
|
1677
|
+
this.sessions = new SessionStore(this.now);
|
|
1678
|
+
this.did = deviceId();
|
|
1679
|
+
configureDescriber({ maskSelector: options.maskSelector, maskAllText: options.maskAllText, routeFor: options.routeFor });
|
|
1680
|
+
this.transport = new Transport({
|
|
1681
|
+
url: `${options.endpoint}/v1/ingest/events`,
|
|
1682
|
+
project: options.project,
|
|
1683
|
+
now: this.now,
|
|
1684
|
+
fetch: (input, init2) => this.fetch(input, init2),
|
|
1685
|
+
onAnswer: (answer) => this.onAnswer(answer),
|
|
1686
|
+
onRefused: (status) => this.warn(`the engine refused the key (${status}): nothing is sent from this page`),
|
|
1687
|
+
debug: (message) => this.debug(message)
|
|
1688
|
+
});
|
|
1689
|
+
const emit = (fields, emitOptions) => this.emit(fields, emitOptions);
|
|
1690
|
+
this.errors = new ErrorFilter({
|
|
1691
|
+
now: this.now,
|
|
1692
|
+
location: () => ({ origin: window.location.origin, pathname: window.location.pathname }),
|
|
1693
|
+
ignoreErrors: options.ignoreErrors,
|
|
1694
|
+
appFrames: options.appFrames,
|
|
1695
|
+
debug: (message) => this.debug(message)
|
|
1696
|
+
});
|
|
1697
|
+
this.clicks = new ClickCapture({
|
|
1698
|
+
now: this.now,
|
|
1699
|
+
emit,
|
|
1700
|
+
onTrouble: () => this.onTrouble(),
|
|
1701
|
+
lastRequestAt: () => this.lastRequestAt,
|
|
1702
|
+
lastNavigationAt: () => this.lastNavigationAt
|
|
1703
|
+
});
|
|
1704
|
+
this.forms = new FormCapture({ now: this.now, emit, onAnswer: () => this.clicks.noteMutation() });
|
|
1705
|
+
this.requests = new RequestCapture(
|
|
1706
|
+
{
|
|
1707
|
+
sypniaUrl: () => new URL(`${options.endpoint}/v1/`, window.location.href).href,
|
|
1708
|
+
traceTargets: options.traceTargets,
|
|
1709
|
+
recordTargets: options.recordTargets,
|
|
1710
|
+
ignoreRequests: options.ignoreRequests,
|
|
1711
|
+
failureDetail: options.capture.requestFailureDetail,
|
|
1712
|
+
routeFor: options.routeFor,
|
|
1713
|
+
now: this.now,
|
|
1714
|
+
session: () => isHidden() || this.ignored() ? null : this.session(false),
|
|
1715
|
+
lastPageHideAt: () => this.lastPageHideAt,
|
|
1716
|
+
emit
|
|
1717
|
+
},
|
|
1718
|
+
(state, traceId) => {
|
|
1719
|
+
if (state === "start") {
|
|
1720
|
+
this.lastRequestAt = this.now();
|
|
1721
|
+
this.inflight.add(traceId);
|
|
1722
|
+
} else {
|
|
1723
|
+
this.inflight.delete(traceId);
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
);
|
|
1727
|
+
this.vitals = new VitalsCapture({ emit, landing: () => this.landing });
|
|
1728
|
+
this.navigation = new NavigationWatch(this.now, options.hashRouting);
|
|
1729
|
+
}
|
|
1730
|
+
// ---------------------------------------------------------------- lifecycle
|
|
1731
|
+
/** Installs the listeners, sends the page view, and leaves the rest for when the browser is idle. */
|
|
1732
|
+
start() {
|
|
1733
|
+
if (this.active) return;
|
|
1734
|
+
this.active = true;
|
|
1735
|
+
const { capture } = this.options;
|
|
1736
|
+
this.debug(
|
|
1737
|
+
`started: ${this.options.project.slice(0, 12)}\u2026 \u2192 ${this.options.endpoint}, environment ${this.options.environment}, release ${this.options.release ?? "none"}`
|
|
1738
|
+
);
|
|
1739
|
+
this.installListeners();
|
|
1740
|
+
if (capture.clicks) this.clicks.install();
|
|
1741
|
+
if (capture.forms) this.forms.install();
|
|
1742
|
+
if (capture.requests) this.requests.install();
|
|
1743
|
+
this.navigation.install((kind) => this.onAddressChange(kind));
|
|
1744
|
+
this.transport.start();
|
|
1745
|
+
this.enterPage(currentPath(this.options.hashRouting), "load", null);
|
|
1746
|
+
this.landing = this.currentPage();
|
|
1747
|
+
if (this.sessions.storageFailed) this.debug("storage unavailable, session kept in memory");
|
|
1748
|
+
this.ready = new Promise((resolve) => whenIdle(() => void this.onIdle().then(resolve, resolve)));
|
|
1749
|
+
}
|
|
1750
|
+
/** Removes every listener and hook. What waits is sent first. */
|
|
1751
|
+
stop() {
|
|
1752
|
+
if (!this.active) return;
|
|
1753
|
+
safe(() => this.leavePage());
|
|
1754
|
+
void this.transport.flush("fetch");
|
|
1755
|
+
this.active = false;
|
|
1756
|
+
this.transport.stop();
|
|
1757
|
+
safe(() => this.recorder?.stop());
|
|
1758
|
+
safe(() => this.vitals.stop());
|
|
1759
|
+
for (const cleanup of this.cleanups.splice(0)) safe(cleanup);
|
|
1760
|
+
safe(() => this.clicks.uninstall());
|
|
1761
|
+
safe(() => this.forms.uninstall());
|
|
1762
|
+
safe(() => this.requests.uninstall());
|
|
1763
|
+
safe(() => this.navigation.uninstall());
|
|
1764
|
+
this.page = null;
|
|
1765
|
+
}
|
|
1766
|
+
/** Stops and drops what waits (`optOut`). */
|
|
1767
|
+
discard() {
|
|
1768
|
+
this.transport.retain(() => false);
|
|
1769
|
+
this.stop();
|
|
1770
|
+
}
|
|
1771
|
+
isActive() {
|
|
1772
|
+
return this.active;
|
|
1773
|
+
}
|
|
1774
|
+
async onIdle() {
|
|
1775
|
+
if (!this.active) return;
|
|
1776
|
+
if (this.options.capture.clicks) safe(() => this.clicks.watchMutations());
|
|
1777
|
+
this.idleReady = true;
|
|
1778
|
+
if (this.options.capture.vitals) safe(() => this.vitals.start());
|
|
1779
|
+
await this.prepareSession();
|
|
1780
|
+
}
|
|
1781
|
+
// ------------------------------------------------------------------ public
|
|
1782
|
+
identify(who) {
|
|
1783
|
+
if (!this.active) return;
|
|
1784
|
+
this.sessions.identify(who ? personKey(who.person.id) : null);
|
|
1785
|
+
this.identity = who;
|
|
1786
|
+
if (!who) return;
|
|
1787
|
+
const sid = this.sessions.peek();
|
|
1788
|
+
if (sid && this.identifySent?.sid === sid && this.identifySent.json === JSON.stringify([who.person, who.account])) return;
|
|
1789
|
+
this.emit({ type: "identify", person: who.person, account: who.account });
|
|
1790
|
+
}
|
|
1791
|
+
track(name, props) {
|
|
1792
|
+
const clean = String(name).trim().slice(0, CHARS.customName);
|
|
1793
|
+
if (!clean) return;
|
|
1794
|
+
const cleanProps = sanitizeProps(props);
|
|
1795
|
+
this.emit({ type: "custom", name: clean, ...cleanProps ? { props: cleanProps } : {} }, { activity: !this.sessions.peek() });
|
|
1796
|
+
}
|
|
1797
|
+
reportError(error, info = {}) {
|
|
1798
|
+
const read = readError(error);
|
|
1799
|
+
const digest = typeof info.digest === "string" && info.digest ? info.digest : read.digest;
|
|
1800
|
+
this.report({ ...read, digest, src: info.source === "boundary" ? "boundary" : "manual" });
|
|
1801
|
+
}
|
|
1802
|
+
async flush(mode = "fetch") {
|
|
1803
|
+
safe(() => this.recorder?.flush(mode));
|
|
1804
|
+
await this.transport.flush(mode);
|
|
1805
|
+
}
|
|
1806
|
+
sessionId() {
|
|
1807
|
+
return this.sessions.peek() ?? this.lastSid;
|
|
1808
|
+
}
|
|
1809
|
+
/** A framework announced a navigation before the address changed. */
|
|
1810
|
+
announceNavigation(rawUrl, kind) {
|
|
1811
|
+
const path = pathnameOf(this.options.hashRouting ? rawUrl.replace(/^[^#]*#!?/, "") || "/" : rawUrl);
|
|
1812
|
+
this.navigation.announce(path, currentPath(this.options.hashRouting));
|
|
1813
|
+
this.goTo(path, kind);
|
|
1814
|
+
}
|
|
1815
|
+
// ------------------------------------------------------------------ events
|
|
1816
|
+
emit(fields, options = {}) {
|
|
1817
|
+
if (!this.active) return;
|
|
1818
|
+
try {
|
|
1819
|
+
if (!options.page) this.syncAddress();
|
|
1820
|
+
const page = options.page ?? this.currentPage();
|
|
1821
|
+
if (!page || this.isIgnored(page.url)) return;
|
|
1822
|
+
const sid = options.sid ?? this.session(options.activity ?? ACTIVITY.has(fields.type), page, fields.type === "identify");
|
|
1823
|
+
if (!sid) return;
|
|
1824
|
+
const event = { ...this.base(fields.type, sid, page), ...fields };
|
|
1825
|
+
if (options.ts !== void 0) event.ts = options.ts;
|
|
1826
|
+
this.queue(event);
|
|
1827
|
+
} catch {
|
|
1828
|
+
}
|
|
1829
|
+
}
|
|
1830
|
+
/** The last gates of every event: the `slow_down` in force, `beforeSend`, and the queue. */
|
|
1831
|
+
queue(event) {
|
|
1832
|
+
if (isBlockedBySlowDown(event, this.slowDown, this.now())) {
|
|
1833
|
+
this.debug(`not sent, the project reached a limit: ${event.type}`);
|
|
1834
|
+
return;
|
|
1835
|
+
}
|
|
1836
|
+
let final = event;
|
|
1837
|
+
if (this.options.beforeSend) {
|
|
1838
|
+
try {
|
|
1839
|
+
final = this.options.beforeSend(event);
|
|
1840
|
+
} catch {
|
|
1841
|
+
final = event;
|
|
1842
|
+
}
|
|
1843
|
+
if (!final) {
|
|
1844
|
+
this.debug(`not sent, beforeSend dropped it: ${event.type}`);
|
|
1845
|
+
return;
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
if (this.options.debug) safe(() => console.debug("[sypnia]", final));
|
|
1849
|
+
if (final.type === "identify") this.identifySent = { sid: final.sid, json: identityKey(final) };
|
|
1850
|
+
this.transport.enqueue(final);
|
|
1851
|
+
if (URGENT_WHEN_HIDDEN.has(final.type) && isHidden()) this.flushSoon();
|
|
1852
|
+
}
|
|
1853
|
+
base(type, sid, page) {
|
|
1854
|
+
return {
|
|
1855
|
+
v: SCHEMA_VERSION,
|
|
1856
|
+
type,
|
|
1857
|
+
ts: this.now(),
|
|
1858
|
+
sid,
|
|
1859
|
+
did: this.did,
|
|
1860
|
+
env: this.options.environment,
|
|
1861
|
+
ver: this.options.release,
|
|
1862
|
+
person: this.identity ? { id: this.identity.person.id } : null,
|
|
1863
|
+
account: this.identity?.account ? { id: this.identity.account.id } : null,
|
|
1864
|
+
url: page.url,
|
|
1865
|
+
route: page.route,
|
|
1866
|
+
...viewport(),
|
|
1867
|
+
lang: this.lang
|
|
1868
|
+
};
|
|
1869
|
+
}
|
|
1870
|
+
/**
|
|
1871
|
+
* The session of a new event. Activity keeps it alive or starts a new one;
|
|
1872
|
+
* background work only reads it. When the id differs from the one this
|
|
1873
|
+
* document used last, `session_start` goes first, then the person's
|
|
1874
|
+
* `identify`, and the session's decision is asked for.
|
|
1875
|
+
*/
|
|
1876
|
+
session(activity, page = this.currentPage(), identifying = false) {
|
|
1877
|
+
const sid = activity ? this.sessions.touch().sid : this.sessions.peek();
|
|
1878
|
+
if (!sid || sid === this.lastSid) return sid;
|
|
1879
|
+
this.lastSid = sid;
|
|
1880
|
+
if (page) {
|
|
1881
|
+
this.queue({ ...this.base("session_start", sid, page), ...sessionStartFields() });
|
|
1882
|
+
const who = this.identity;
|
|
1883
|
+
if (who && !identifying && this.identifySent?.sid !== sid) {
|
|
1884
|
+
this.queue({ ...this.base("identify", sid, page), person: who.person, account: who.account });
|
|
1885
|
+
}
|
|
1886
|
+
}
|
|
1887
|
+
if (this.idleReady) void this.prepareSession();
|
|
1888
|
+
return sid;
|
|
1889
|
+
}
|
|
1890
|
+
report(report) {
|
|
1891
|
+
if (!this.active) return;
|
|
1892
|
+
const fields = this.errors.accept(report);
|
|
1893
|
+
if (!fields) return;
|
|
1894
|
+
this.emit(fields, { activity: !this.sessions.peek() });
|
|
1895
|
+
this.onTrouble();
|
|
1896
|
+
}
|
|
1897
|
+
onTrouble() {
|
|
1898
|
+
safe(() => this.recorder?.onTrouble());
|
|
1899
|
+
}
|
|
1900
|
+
// ------------------------------------------------------------------- pages
|
|
1901
|
+
currentPage() {
|
|
1902
|
+
return this.page ? { url: this.page.url, route: this.page.route } : null;
|
|
1903
|
+
}
|
|
1904
|
+
/** Outside `allowRoutes` (when it is set), or in `ignoreRoutes`: the SDK captures nothing there. */
|
|
1905
|
+
isIgnored(path) {
|
|
1906
|
+
const { allowRoutes, ignoreRoutes } = this.options;
|
|
1907
|
+
if (allowRoutes.length > 0 && !matchesRoute(path, allowRoutes)) return true;
|
|
1908
|
+
return matchesRoute(path, ignoreRoutes);
|
|
1909
|
+
}
|
|
1910
|
+
ignored() {
|
|
1911
|
+
return !this.page || this.isIgnored(this.page.url);
|
|
1912
|
+
}
|
|
1913
|
+
onAddressChange(kind) {
|
|
1914
|
+
this.goTo(this.navigation.resolve(currentPath(this.options.hashRouting)), kind);
|
|
1915
|
+
}
|
|
1916
|
+
/** The address changed without the router saying so (a redirect, another library's pushState). */
|
|
1917
|
+
syncAddress() {
|
|
1918
|
+
const path = this.navigation.resolve(currentPath(this.options.hashRouting));
|
|
1919
|
+
if (this.page && path !== this.page.url) this.goTo(path, "replace");
|
|
1920
|
+
}
|
|
1921
|
+
goTo(path, kind) {
|
|
1922
|
+
if (!this.active || this.page && path === this.page.url) return;
|
|
1923
|
+
const from = this.page?.route ?? null;
|
|
1924
|
+
this.lastNavigationAt = this.now();
|
|
1925
|
+
this.leavePage();
|
|
1926
|
+
this.enterPage(path, kind, from);
|
|
1927
|
+
}
|
|
1928
|
+
enterPage(path, nav, from) {
|
|
1929
|
+
const ref = pageRefOf(path, this.options.routeFor);
|
|
1930
|
+
this.lang = pageLanguage();
|
|
1931
|
+
this.page = { ...ref, startedAt: this.now(), maxScroll: 0, leaveSent: false };
|
|
1932
|
+
this.measureScroll();
|
|
1933
|
+
this.vitals.pageStarted(ref);
|
|
1934
|
+
this.emit({ type: "page_view", nav, from }, { page: ref });
|
|
1935
|
+
safe(() => this.recorder?.onPage(ref));
|
|
1936
|
+
}
|
|
1937
|
+
leavePage() {
|
|
1938
|
+
const page = this.page;
|
|
1939
|
+
if (!page || page.leaveSent) return;
|
|
1940
|
+
page.leaveSent = true;
|
|
1941
|
+
this.clicks.flushRage();
|
|
1942
|
+
this.measureScroll();
|
|
1943
|
+
const ref = { url: page.url, route: page.route };
|
|
1944
|
+
this.emit({ type: "page_leave", dur: Math.max(0, Math.round(this.now() - page.startedAt)), scroll: page.maxScroll }, { page: ref });
|
|
1945
|
+
this.vitals.pageLeft(ref);
|
|
1946
|
+
}
|
|
1947
|
+
measureScroll() {
|
|
1948
|
+
const page = this.page;
|
|
1949
|
+
if (!page) return;
|
|
1950
|
+
safe(() => {
|
|
1951
|
+
const height = Math.max(document.documentElement?.scrollHeight || 0, document.body?.scrollHeight || 0);
|
|
1952
|
+
const screen = window.innerHeight || 0;
|
|
1953
|
+
if (height <= 0 || screen <= 0) return;
|
|
1954
|
+
const depth = height <= screen ? 100 : Math.min(100, Math.round(((window.scrollY || 0) + screen) / height * 100));
|
|
1955
|
+
page.maxScroll = Math.max(page.maxScroll, depth);
|
|
1956
|
+
});
|
|
1957
|
+
}
|
|
1958
|
+
// --------------------------------------------------------------- listeners
|
|
1959
|
+
listen(target, type, handler, options) {
|
|
1960
|
+
const guarded = (event) => safe(() => handler(event));
|
|
1961
|
+
target.addEventListener(type, guarded, options);
|
|
1962
|
+
this.cleanups.push(() => target.removeEventListener(type, guarded, options));
|
|
1963
|
+
}
|
|
1964
|
+
installListeners() {
|
|
1965
|
+
if (this.options.capture.errors) {
|
|
1966
|
+
this.listen(window, "error", (event) => {
|
|
1967
|
+
const error = event;
|
|
1968
|
+
const read = readError(error.error);
|
|
1969
|
+
this.report({ ...read, msg: read.msg || (typeof error.message === "string" ? error.message : ""), src: "window" });
|
|
1970
|
+
});
|
|
1971
|
+
this.listen(window, "unhandledrejection", (event) => {
|
|
1972
|
+
const reason = event.reason;
|
|
1973
|
+
const read = readError(reason);
|
|
1974
|
+
const isError = !!reason && typeof reason === "object" && "message" in reason;
|
|
1975
|
+
this.report({ ...read, name: isError ? read.name : "UnhandledRejection", src: "promise" });
|
|
1976
|
+
});
|
|
1977
|
+
}
|
|
1978
|
+
this.listen(window, "scroll", () => this.onScroll(), { passive: true });
|
|
1979
|
+
for (const type of ["keydown", "wheel", "pointerdown", "touchstart"]) {
|
|
1980
|
+
this.listen(document, type, () => this.onInput(), { passive: true, capture: true });
|
|
1981
|
+
}
|
|
1982
|
+
this.listen(document, "visibilitychange", () => isHidden() ? this.onHidden() : this.onVisible());
|
|
1983
|
+
this.listen(window, "pagehide", () => this.onPageHide());
|
|
1984
|
+
this.listen(window, "pageshow", (event) => {
|
|
1985
|
+
if (event.persisted) this.onVisible();
|
|
1986
|
+
});
|
|
1987
|
+
}
|
|
1988
|
+
onScroll() {
|
|
1989
|
+
if (this.scrollScheduled) return;
|
|
1990
|
+
this.scrollScheduled = true;
|
|
1991
|
+
const run = () => {
|
|
1992
|
+
this.scrollScheduled = false;
|
|
1993
|
+
this.measureScroll();
|
|
1994
|
+
};
|
|
1995
|
+
if (typeof requestAnimationFrame === "function") requestAnimationFrame(run);
|
|
1996
|
+
else setTimeout(run, 0);
|
|
1997
|
+
}
|
|
1998
|
+
onInput() {
|
|
1999
|
+
const now = this.now();
|
|
2000
|
+
if (now - this.lastInputAt < INPUT_TOUCH_EVERY_MS || this.ignored()) return;
|
|
2001
|
+
this.lastInputAt = now;
|
|
2002
|
+
this.session(true);
|
|
2003
|
+
}
|
|
2004
|
+
onHidden() {
|
|
2005
|
+
this.leavePage();
|
|
2006
|
+
void this.transport.flush("beacon");
|
|
2007
|
+
safe(() => this.recorder?.flush("fetch"));
|
|
2008
|
+
}
|
|
2009
|
+
onVisible() {
|
|
2010
|
+
if (this.page) {
|
|
2011
|
+
this.page.startedAt = this.now();
|
|
2012
|
+
this.page.leaveSent = false;
|
|
2013
|
+
}
|
|
2014
|
+
if (!this.ignored()) this.session(true);
|
|
2015
|
+
}
|
|
2016
|
+
onPageHide() {
|
|
2017
|
+
this.lastPageHideAt = this.now();
|
|
2018
|
+
this.leavePage();
|
|
2019
|
+
void this.transport.flush("beacon");
|
|
2020
|
+
safe(() => this.recorder?.flush("beacon"));
|
|
2021
|
+
}
|
|
2022
|
+
flushSoon() {
|
|
2023
|
+
if (this.flushScheduled) return;
|
|
2024
|
+
this.flushScheduled = true;
|
|
2025
|
+
queueMicrotask(() => {
|
|
2026
|
+
this.flushScheduled = false;
|
|
2027
|
+
void this.transport.flush("beacon");
|
|
2028
|
+
});
|
|
2029
|
+
}
|
|
2030
|
+
// ------------------------------------------------- session decision, replay
|
|
2031
|
+
/** Asks for the decision of the session this document uses (once per session, any tab), then starts the recorder. */
|
|
2032
|
+
async prepareSession() {
|
|
2033
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
2034
|
+
const sid = this.lastSid;
|
|
2035
|
+
if (!sid || !this.active) return;
|
|
2036
|
+
if (this.decision?.sid === sid) return;
|
|
2037
|
+
const decision = readDecision(sid) ?? await this.askDecision(sid);
|
|
2038
|
+
if (this.lastSid !== sid) continue;
|
|
2039
|
+
this.decision = decision;
|
|
2040
|
+
if (decision.slowDown) this.applySlowDown(decision.slowDown, false);
|
|
2041
|
+
this.debug(`replay: ${decision.mode}, snapshots: ${decision.snapshots ? "on" : "off"}`);
|
|
2042
|
+
await this.startRecorder(decision);
|
|
2043
|
+
return;
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
async askDecision(sid) {
|
|
2047
|
+
const params = new URLSearchParams({ sid });
|
|
2048
|
+
if (this.identity) params.set("person", this.identity.person.id);
|
|
2049
|
+
if (this.identity?.account) params.set("account", this.identity.account.id);
|
|
2050
|
+
const controller = typeof AbortController === "function" ? new AbortController() : null;
|
|
2051
|
+
const timer = setTimeout(() => controller?.abort(), CONFIG_TIMEOUT_MS);
|
|
2052
|
+
try {
|
|
2053
|
+
const response = await this.fetch(`${this.options.endpoint}/v1/ingest/config?${params.toString()}`, {
|
|
2054
|
+
headers: { authorization: `Bearer ${this.options.project}` },
|
|
2055
|
+
credentials: "omit",
|
|
2056
|
+
...controller ? { signal: controller.signal } : {}
|
|
2057
|
+
});
|
|
2058
|
+
const config2 = response.ok ? await response.json() : null;
|
|
2059
|
+
const decision = config2 ? decisionFrom(sid, config2, this.random) : fallbackDecision(sid, this.random() < 0.5);
|
|
2060
|
+
writeDecision(decision);
|
|
2061
|
+
return readDecision(sid) ?? decision;
|
|
2062
|
+
} catch {
|
|
2063
|
+
return fallbackDecision(sid, this.random() < 0.5);
|
|
2064
|
+
} finally {
|
|
2065
|
+
clearTimeout(timer);
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
2068
|
+
wantsRecorder(decision) {
|
|
2069
|
+
const replay = this.options.replay !== false && decision.mode !== "off";
|
|
2070
|
+
const snapshots = this.options.snapshots && decision.snapshots;
|
|
2071
|
+
return replay || snapshots;
|
|
2072
|
+
}
|
|
2073
|
+
async startRecorder(decision) {
|
|
2074
|
+
if (!this.wantsRecorder(decision)) {
|
|
2075
|
+
safe(() => this.recorder?.stop());
|
|
2076
|
+
return;
|
|
2077
|
+
}
|
|
2078
|
+
if (!this.recorder && !this.recorderLoading) {
|
|
2079
|
+
this.recorderLoading = true;
|
|
2080
|
+
try {
|
|
2081
|
+
const create = await this.deps.loadRecorder();
|
|
2082
|
+
this.recorder = create(this.recorderHost());
|
|
2083
|
+
} catch (error) {
|
|
2084
|
+
this.debug(`the recorder could not be loaded (${String(error)}): no replay on this page`);
|
|
2085
|
+
} finally {
|
|
2086
|
+
this.recorderLoading = false;
|
|
2087
|
+
}
|
|
2088
|
+
}
|
|
2089
|
+
if (this.active && this.decision === decision) safe(() => this.recorder?.start(decision));
|
|
2090
|
+
}
|
|
2091
|
+
recorderHost() {
|
|
2092
|
+
const { options } = this;
|
|
2093
|
+
const mark = (fields, sid) => this.emit(fields, { sid });
|
|
2094
|
+
return {
|
|
2095
|
+
endpoint: options.endpoint,
|
|
2096
|
+
project: options.project,
|
|
2097
|
+
environment: options.environment,
|
|
2098
|
+
now: this.now,
|
|
2099
|
+
page: () => this.active ? this.currentPage() : null,
|
|
2100
|
+
maskAllText: options.maskAllText,
|
|
2101
|
+
maskSelector: options.maskSelector,
|
|
2102
|
+
blockSelector: options.blockSelector,
|
|
2103
|
+
// Nothing at all is recorded where the SDK is inactive.
|
|
2104
|
+
blockedRoutes: [...options.replay ? options.replay.blockedRoutes : [], ...options.ignoreRoutes],
|
|
2105
|
+
allowRoutes: options.allowRoutes,
|
|
2106
|
+
replay: options.replay !== false,
|
|
2107
|
+
snapshots: options.snapshots,
|
|
2108
|
+
lastMutationAt: () => this.clicks.lastMutationAt,
|
|
2109
|
+
pendingRequests: () => this.inflight.size,
|
|
2110
|
+
onChunk: ({ sid, seq, bytes, mask, full }) => mark({ type: "replay_chunk", seq, bytes, mask, ...full ? { full } : {} }, sid),
|
|
2111
|
+
onGap: ({ sid, seq, reason, mask }) => mark({ type: "replay_gap", seq, reason, mask }, sid),
|
|
2112
|
+
onSnapshot: ({ sid, bytes, mask, skipped }) => mark({ type: "page_snapshot", bytes, mask, ...skipped ? { skipped } : {} }, sid),
|
|
2113
|
+
onSlowDown: (slowDown) => this.applySlowDown(slowDown, true),
|
|
2114
|
+
debug: (message) => this.debug(message)
|
|
2115
|
+
};
|
|
2116
|
+
}
|
|
2117
|
+
// --------------------------------------------------------------- slow down
|
|
2118
|
+
onAnswer(answer) {
|
|
2119
|
+
if (answer.slow_down) this.applySlowDown(answer.slow_down, true);
|
|
2120
|
+
}
|
|
2121
|
+
/** Obeys a `slow_down` at once, and keeps it with the session's decision so every tab does. */
|
|
2122
|
+
applySlowDown(slowDown, store) {
|
|
2123
|
+
if (!isActiveSlowDown(slowDown, this.now())) {
|
|
2124
|
+
this.slowDown = null;
|
|
2125
|
+
return;
|
|
2126
|
+
}
|
|
2127
|
+
this.slowDown = slowDown;
|
|
2128
|
+
this.debug(`slow down: send ${slowDown.send ?? "all"}, replay ${slowDown.replay === false ? "off" : "on"} until ${slowDown.until ?? "?"}`);
|
|
2129
|
+
const now = this.now();
|
|
2130
|
+
this.transport.retain((event) => !isBlockedBySlowDown(event, slowDown, now));
|
|
2131
|
+
if (slowDown.replay === false) safe(() => this.recorder?.onReplayLimit());
|
|
2132
|
+
if (store && this.decision) {
|
|
2133
|
+
this.decision.slowDown = slowDown;
|
|
2134
|
+
writeDecision(this.decision);
|
|
2135
|
+
}
|
|
2136
|
+
}
|
|
2137
|
+
// ------------------------------------------------------------------- debug
|
|
2138
|
+
debug(message) {
|
|
2139
|
+
if (this.options.debug) safe(() => console.debug(`[sypnia] ${message}`));
|
|
2140
|
+
}
|
|
2141
|
+
warn(message) {
|
|
2142
|
+
safe(() => console.warn(`[sypnia] ${message}`));
|
|
2143
|
+
}
|
|
2144
|
+
};
|
|
2145
|
+
function sessionStartFields() {
|
|
2146
|
+
return {
|
|
2147
|
+
ua: (safe(() => navigator.userAgent) ?? "").slice(0, CHARS.userAgent),
|
|
2148
|
+
ref: referrerOf(safe(() => document.referrer) ?? ""),
|
|
2149
|
+
sw: safe(() => window.screen.width) || 0,
|
|
2150
|
+
sh: safe(() => window.screen.height) || 0,
|
|
2151
|
+
tz: (safe(() => Intl.DateTimeFormat().resolvedOptions().timeZone) ?? "").slice(0, 64)
|
|
2152
|
+
};
|
|
2153
|
+
}
|
|
2154
|
+
function referrerOf(referrer) {
|
|
2155
|
+
if (!referrer) return null;
|
|
2156
|
+
try {
|
|
2157
|
+
const url = new URL(referrer);
|
|
2158
|
+
return `${url.origin}${pathnameOf(url.pathname)}`.slice(0, CHARS.path);
|
|
2159
|
+
} catch {
|
|
2160
|
+
return null;
|
|
2161
|
+
}
|
|
2162
|
+
}
|
|
2163
|
+
function identityKey(event) {
|
|
2164
|
+
return JSON.stringify([event.person, event.account]);
|
|
2165
|
+
}
|
|
2166
|
+
function sanitizeProps(props) {
|
|
2167
|
+
if (!props || typeof props !== "object") return null;
|
|
2168
|
+
const out = {};
|
|
2169
|
+
let count = 0;
|
|
2170
|
+
for (const key of Object.keys(props)) {
|
|
2171
|
+
if (count >= CUSTOM_PROPS_MAX) break;
|
|
2172
|
+
const value = props[key];
|
|
2173
|
+
const name = key.slice(0, CHARS.propName);
|
|
2174
|
+
if (value === null || typeof value === "boolean") out[name] = value;
|
|
2175
|
+
else if (typeof value === "number" && Number.isFinite(value)) out[name] = value;
|
|
2176
|
+
else if (typeof value === "string") out[name] = value.slice(0, CHARS.propValue);
|
|
2177
|
+
else continue;
|
|
2178
|
+
count++;
|
|
2179
|
+
}
|
|
2180
|
+
return count > 0 ? out : null;
|
|
2181
|
+
}
|
|
2182
|
+
function isOptedOut() {
|
|
2183
|
+
return readStorage(STORAGE_KEYS.off) !== null;
|
|
2184
|
+
}
|
|
2185
|
+
|
|
2186
|
+
// src/api.ts
|
|
2187
|
+
var GLOBAL_KEY = "__sypnia";
|
|
2188
|
+
function holder() {
|
|
2189
|
+
if (!isBrowser()) return null;
|
|
2190
|
+
const w = window;
|
|
2191
|
+
w[GLOBAL_KEY] ??= { runtime: null, started: false };
|
|
2192
|
+
return w[GLOBAL_KEY];
|
|
2193
|
+
}
|
|
2194
|
+
function runtime() {
|
|
2195
|
+
return holder()?.runtime ?? null;
|
|
2196
|
+
}
|
|
2197
|
+
function off(reason) {
|
|
2198
|
+
safe(() => console.warn(`[sypnia] off: ${reason}`));
|
|
2199
|
+
}
|
|
2200
|
+
function startSdk(options, loadRecorder2) {
|
|
2201
|
+
try {
|
|
2202
|
+
const h = holder();
|
|
2203
|
+
if (!h || h.started) return;
|
|
2204
|
+
if (!options || typeof options.project !== "string" || !options.project.trim()) {
|
|
2205
|
+
off("no project");
|
|
2206
|
+
return;
|
|
2207
|
+
}
|
|
2208
|
+
if (options.enabled === false) {
|
|
2209
|
+
if (options.debug) off("disabled");
|
|
2210
|
+
return;
|
|
2211
|
+
}
|
|
2212
|
+
h.started = true;
|
|
2213
|
+
h.runtime = new Runtime(resolveOptions(options), { loadRecorder: loadRecorder2 });
|
|
2214
|
+
if (isOptedOut()) {
|
|
2215
|
+
if (options.debug) off("opted out");
|
|
2216
|
+
return;
|
|
2217
|
+
}
|
|
2218
|
+
h.runtime.start();
|
|
2219
|
+
} catch {
|
|
2220
|
+
}
|
|
2221
|
+
}
|
|
2222
|
+
function idOf(value) {
|
|
2223
|
+
if (value === void 0 || value === null) return null;
|
|
2224
|
+
const id = String(value).trim();
|
|
2225
|
+
return id ? id.slice(0, CHARS.personId) : null;
|
|
2226
|
+
}
|
|
2227
|
+
function optionalText(value, max) {
|
|
2228
|
+
return typeof value === "string" && value.trim() ? value.trim().slice(0, max) : null;
|
|
2229
|
+
}
|
|
2230
|
+
function identify(who) {
|
|
2231
|
+
try {
|
|
2232
|
+
const sdk = runtime();
|
|
2233
|
+
if (!sdk) return;
|
|
2234
|
+
if (who === null) {
|
|
2235
|
+
sdk.identify(null);
|
|
2236
|
+
return;
|
|
2237
|
+
}
|
|
2238
|
+
const id = idOf(who?.person?.id);
|
|
2239
|
+
if (!id) {
|
|
2240
|
+
safe(() => console.warn("[sypnia] identify: person.id is required"));
|
|
2241
|
+
return;
|
|
2242
|
+
}
|
|
2243
|
+
const accountId = idOf(who.account?.id);
|
|
2244
|
+
const identity = {
|
|
2245
|
+
person: { id, name: optionalText(who.person.name, CHARS.personName), email: optionalText(who.person.email, CHARS.email) },
|
|
2246
|
+
account: accountId ? { id: accountId, name: optionalText(who.account?.name, CHARS.personName) } : null
|
|
2247
|
+
};
|
|
2248
|
+
sdk.identify(identity);
|
|
2249
|
+
} catch {
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2252
|
+
function track(name, props) {
|
|
2253
|
+
safe(() => runtime()?.track(name, props));
|
|
2254
|
+
}
|
|
2255
|
+
function reportError(error, info) {
|
|
2256
|
+
safe(() => runtime()?.reportError(error, info));
|
|
2257
|
+
}
|
|
2258
|
+
async function flush() {
|
|
2259
|
+
try {
|
|
2260
|
+
await runtime()?.flush("fetch");
|
|
2261
|
+
} catch {
|
|
2262
|
+
}
|
|
2263
|
+
}
|
|
2264
|
+
function getSessionId() {
|
|
2265
|
+
return safe(() => runtime()?.isActive() ? runtime()?.sessionId() : null) ?? null;
|
|
2266
|
+
}
|
|
2267
|
+
function optOut() {
|
|
2268
|
+
safe(() => {
|
|
2269
|
+
writeStorage(STORAGE_KEYS.off, "1");
|
|
2270
|
+
runtime()?.discard();
|
|
2271
|
+
});
|
|
2272
|
+
}
|
|
2273
|
+
function optIn() {
|
|
2274
|
+
safe(() => {
|
|
2275
|
+
removeStorage(STORAGE_KEYS.off);
|
|
2276
|
+
const sdk = runtime();
|
|
2277
|
+
if (sdk && !sdk.isActive()) sdk.start();
|
|
2278
|
+
});
|
|
2279
|
+
}
|
|
2280
|
+
function notifyNavigation(url, kind) {
|
|
2281
|
+
safe(() => runtime()?.announceNavigation(url, kind === "replace" || kind === "traverse" ? kind : "push"));
|
|
2282
|
+
}
|
|
2283
|
+
|
|
2284
|
+
// src/index.ts
|
|
2285
|
+
var loadRecorder = () => import('./recorder.js').then((module) => module.createRecorder);
|
|
2286
|
+
function init(options) {
|
|
2287
|
+
startSdk(options, loadRecorder);
|
|
2288
|
+
}
|
|
2289
|
+
|
|
2290
|
+
export { flush, getSessionId, identify, init, notifyNavigation, optIn, optOut, reportError, track };
|