@omaralex24/zenith-browser 0.0.0-stage → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/flight.js ADDED
@@ -0,0 +1,907 @@
1
+ import { generateTraceContext } from "./uuidv7.js";
2
+ import { isSensitiveElement, redactObject, redactSensitiveString } from "./scrub.js";
3
+ const DEFAULT_MAX_BYTES = 28 * 1024;
4
+ const DEFAULT_BUDGET_WINDOW_MS = 60_000;
5
+ const MAX_RECORD_BYTES = 8 * 1024;
6
+ const ACTIONABLE_SELECTOR = "button,a[href],input,select,textarea,[role='button'],[role='link'],[data-testid]";
7
+ const UUID_SEGMENT_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8
+ const TRACEPARENT_RE = /^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/i;
9
+ const DEFAULT_IGNORED_TELEMETRY_PATH_RE = /^\/(?:otlp\/)?v1\/(?:traces|metrics|logs)\/?$/i;
10
+ const UI_TRIGGER_WINDOW_MS = 2_500;
11
+ function compactObject(input) {
12
+ const output = {};
13
+ for (const [key, value] of Object.entries(input)) {
14
+ if (value !== undefined)
15
+ output[key] = value;
16
+ }
17
+ return output;
18
+ }
19
+ function truncateString(value, maxLength) {
20
+ if (value.length <= maxLength)
21
+ return value;
22
+ return `${value.slice(0, Math.max(0, maxLength - 1))}…`;
23
+ }
24
+ function truncateJsonValue(value, depth = 0) {
25
+ if (typeof value === "string")
26
+ return truncateString(redactSensitiveString(value), 400);
27
+ if (value === null || typeof value === "number" || typeof value === "boolean" || value === undefined) {
28
+ return value;
29
+ }
30
+ if (depth > 5)
31
+ return "[TRUNCATED]";
32
+ if (Array.isArray(value)) {
33
+ return value.slice(0, 20).map((item) => truncateJsonValue(item, depth + 1) ?? null);
34
+ }
35
+ const output = {};
36
+ let count = 0;
37
+ for (const [key, item] of Object.entries(value)) {
38
+ if (count >= 40)
39
+ break;
40
+ count += 1;
41
+ output[key] = truncateJsonValue(item, depth + 1);
42
+ }
43
+ return output;
44
+ }
45
+ function safeDescribe(value) {
46
+ if (typeof value === "string")
47
+ return truncateString(redactSensitiveString(value), 240);
48
+ if (value instanceof Error) {
49
+ return truncateString(redactSensitiveString(value.message || value.name), 240);
50
+ }
51
+ try {
52
+ const serialized = JSON.stringify(redactObject(value));
53
+ return truncateString(serialized ?? String(value), 240);
54
+ }
55
+ catch {
56
+ return truncateString(redactSensitiveString(String(value)), 240);
57
+ }
58
+ }
59
+ function errorDetails(error) {
60
+ if (error instanceof Error) {
61
+ return {
62
+ name: error.name,
63
+ message: redactSensitiveString(error.message),
64
+ stack: error.stack ? redactSensitiveString(error.stack) : undefined,
65
+ };
66
+ }
67
+ return {
68
+ name: "Error",
69
+ message: safeDescribe(error),
70
+ };
71
+ }
72
+ function normalizePathSegment(segment) {
73
+ if (!segment)
74
+ return segment;
75
+ if (/^\d{4,}$/.test(segment) || UUID_SEGMENT_RE.test(segment) || segment.length > 48) {
76
+ return ":id";
77
+ }
78
+ return redactSensitiveString(segment);
79
+ }
80
+ export function normalizeEndpointPath(rawUrl, baseUrl) {
81
+ try {
82
+ const url = new URL(rawUrl, baseUrl ?? "http://localhost/");
83
+ const normalized = url.pathname
84
+ .split("/")
85
+ .map((segment) => normalizePathSegment(segment))
86
+ .join("/");
87
+ return truncateString(normalized || "/", 240);
88
+ }
89
+ catch {
90
+ const withoutQuery = rawUrl.split(/[?#]/, 1)[0] || "/";
91
+ return truncateString(redactSensitiveString(withoutQuery), 240);
92
+ }
93
+ }
94
+ function pathAndSearchType(win) {
95
+ return `${win.location?.pathname ?? "/"}${win.location?.search ?? ""}${win.location?.hash ?? ""}`;
96
+ }
97
+ function queryPart(locationKey) {
98
+ const queryStart = locationKey.indexOf("?");
99
+ if (queryStart < 0)
100
+ return "";
101
+ const hashStart = locationKey.indexOf("#", queryStart);
102
+ return locationKey.slice(queryStart + 1, hashStart >= 0 ? hashStart : undefined);
103
+ }
104
+ function hashPart(locationKey) {
105
+ const hashStart = locationKey.indexOf("#");
106
+ return hashStart < 0 ? "" : locationKey.slice(hashStart + 1);
107
+ }
108
+ function routeFromWindow(win) {
109
+ if (!win?.location)
110
+ return undefined;
111
+ return normalizeEndpointPath(win.location.pathname || "/", win.location.href);
112
+ }
113
+ function requestLike(value) {
114
+ return Boolean(value &&
115
+ typeof value === "object" &&
116
+ typeof value.url === "string" &&
117
+ typeof value.method === "string" &&
118
+ value.headers);
119
+ }
120
+ function headerEntries(value) {
121
+ if (!value)
122
+ return undefined;
123
+ try {
124
+ return new Headers(value);
125
+ }
126
+ catch {
127
+ return undefined;
128
+ }
129
+ }
130
+ function copyHeaders(input, init) {
131
+ const merged = new Headers();
132
+ if (requestLike(input)) {
133
+ input.headers.forEach((value, key) => merged.set(key, value));
134
+ }
135
+ const extra = headerEntries(init?.headers);
136
+ extra?.forEach((value, key) => merged.set(key, value));
137
+ return merged;
138
+ }
139
+ function extractTraceId(traceparent) {
140
+ if (!traceparent)
141
+ return undefined;
142
+ const match = TRACEPARENT_RE.exec(traceparent.trim());
143
+ return match?.[1]?.toLowerCase();
144
+ }
145
+ function estimateRecordBytes(record) {
146
+ try {
147
+ return JSON.stringify(record).length;
148
+ }
149
+ catch {
150
+ return 240;
151
+ }
152
+ }
153
+ function capFlightRecordSize(record, maxBytes) {
154
+ let estimatedBytes = estimateRecordBytes(record);
155
+ if (estimatedBytes <= maxBytes)
156
+ return { record, estimatedBytes };
157
+ const capped = {
158
+ ...record,
159
+ summary: record.summary ? truncateString(record.summary, 160) : record.summary,
160
+ target: record.target ? truncateString(record.target, 160) : record.target,
161
+ route: record.route ? truncateString(record.route, 160) : record.route,
162
+ };
163
+ estimatedBytes = estimateRecordBytes(capped);
164
+ if (estimatedBytes <= maxBytes)
165
+ return { record: capped, estimatedBytes };
166
+ let payloadText = "";
167
+ try {
168
+ payloadText = JSON.stringify(capped.payload ?? {}) ?? "";
169
+ }
170
+ catch {
171
+ payloadText = "";
172
+ }
173
+ const base = { ...capped, payload: {} };
174
+ const baseBytes = estimateRecordBytes(base);
175
+ const excerpt = truncateString(payloadText, Math.max(0, maxBytes - baseBytes - 96));
176
+ const truncatedPayload = {
177
+ truncated: true,
178
+ original_bytes: estimatedBytes,
179
+ };
180
+ if (excerpt)
181
+ truncatedPayload.excerpt = excerpt;
182
+ capped.payload = truncatedPayload;
183
+ estimatedBytes = estimateRecordBytes(capped);
184
+ if (estimatedBytes > maxBytes) {
185
+ capped.summary = capped.summary ? truncateString(capped.summary, 80) : capped.summary;
186
+ capped.target = capped.target ? truncateString(capped.target, 80) : capped.target;
187
+ capped.route = capped.route ? truncateString(capped.route, 80) : capped.route;
188
+ capped.payload = { truncated: true };
189
+ estimatedBytes = estimateRecordBytes(capped);
190
+ }
191
+ return { record: capped, estimatedBytes };
192
+ }
193
+ function pathPrefixMatches(pathname, targetPath) {
194
+ if (targetPath === "/")
195
+ return true;
196
+ return pathname === targetPath || pathname.startsWith(targetPath.endsWith("/") ? targetPath : `${targetPath}/`);
197
+ }
198
+ function stringTargetMatches(url, target, currentOrigin) {
199
+ const trimmed = target.trim();
200
+ if (!trimmed)
201
+ return false;
202
+ if (trimmed.startsWith("/")) {
203
+ return Boolean(currentOrigin && url.origin === currentOrigin && pathPrefixMatches(url.pathname, trimmed));
204
+ }
205
+ let parsed;
206
+ try {
207
+ parsed = new URL(trimmed);
208
+ }
209
+ catch {
210
+ return false;
211
+ }
212
+ if (url.origin !== parsed.origin)
213
+ return false;
214
+ if (!pathPrefixMatches(url.pathname, parsed.pathname))
215
+ return false;
216
+ if (parsed.search && url.search !== parsed.search && !url.search.startsWith(`${parsed.search}&`))
217
+ return false;
218
+ if (parsed.hash && url.hash !== parsed.hash)
219
+ return false;
220
+ return true;
221
+ }
222
+ function targetMatches(url, targets, currentOrigin) {
223
+ const href = url.href;
224
+ const path = `${url.pathname}${url.search}`;
225
+ for (const target of targets) {
226
+ if (typeof target === "string") {
227
+ if (stringTargetMatches(url, target, currentOrigin))
228
+ return true;
229
+ continue;
230
+ }
231
+ target.lastIndex = 0;
232
+ if (target.test(href) || target.test(path))
233
+ return true;
234
+ }
235
+ return false;
236
+ }
237
+ function nowPrecision(win) {
238
+ try {
239
+ return win?.performance?.now?.() ?? Date.now();
240
+ }
241
+ catch {
242
+ return Date.now();
243
+ }
244
+ }
245
+ function selectorAttribute(value) {
246
+ return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
247
+ }
248
+ function implicitRole(element) {
249
+ const explicit = element.getAttribute("role");
250
+ if (explicit)
251
+ return explicit;
252
+ const tag = element.tagName.toLowerCase();
253
+ if (tag === "button")
254
+ return "button";
255
+ if (tag === "a")
256
+ return "link";
257
+ if (tag === "select")
258
+ return "combobox";
259
+ if (tag === "textarea")
260
+ return "textbox";
261
+ if (tag === "input") {
262
+ const type = (element.getAttribute("type") ?? "text").toLowerCase();
263
+ if (type === "checkbox")
264
+ return "checkbox";
265
+ if (type === "radio")
266
+ return "radio";
267
+ if (type === "button" || type === "submit" || type === "reset")
268
+ return "button";
269
+ return "textbox";
270
+ }
271
+ return tag;
272
+ }
273
+ function shortSelector(element) {
274
+ const tag = element.tagName.toLowerCase();
275
+ const testId = element.getAttribute("data-testid");
276
+ if (testId)
277
+ return truncateString(`${tag}[data-testid="${selectorAttribute(testId)}"]`, 160);
278
+ const ariaLabel = element.getAttribute("aria-label");
279
+ if (ariaLabel)
280
+ return truncateString(`${tag}[aria-label="${selectorAttribute(ariaLabel)}"]`, 160);
281
+ const id = element.getAttribute("id");
282
+ if (id)
283
+ return truncateString(`${tag}#${id.replace(/[^\w-]/g, "")}`, 160);
284
+ const name = element.getAttribute("name");
285
+ if (name)
286
+ return truncateString(`${tag}[name="${selectorAttribute(name)}"]`, 160);
287
+ const classes = (element.getAttribute("class") ?? "")
288
+ .split(/\s+/)
289
+ .filter(Boolean)
290
+ .slice(0, 2)
291
+ .map((klass) => `.${klass.replace(/[^\w-]/g, "")}`)
292
+ .join("");
293
+ return truncateString(`${tag}${classes}`, 160);
294
+ }
295
+ function elementText(element) {
296
+ const tag = element.tagName.toLowerCase();
297
+ if (tag === "input" || tag === "textarea")
298
+ return undefined;
299
+ const raw = (element.textContent ?? "").replace(/\s+/g, " ").trim();
300
+ if (!raw)
301
+ return undefined;
302
+ return truncateString(redactSensitiveString(raw), 80);
303
+ }
304
+ function closestActionable(target) {
305
+ if (typeof target.closest !== "function")
306
+ return null;
307
+ try {
308
+ return target.closest(ACTIONABLE_SELECTOR);
309
+ }
310
+ catch {
311
+ return null;
312
+ }
313
+ }
314
+ class BrowserFlightRecorder {
315
+ onRecord;
316
+ targets;
317
+ ignoreUrls;
318
+ win;
319
+ maxBytes;
320
+ budgetWindowMs;
321
+ now;
322
+ bytesUsed = 0;
323
+ budgetWindowStartedAt;
324
+ detached = false;
325
+ originalFetch;
326
+ originalXhrOpen;
327
+ originalXhrSend;
328
+ originalXhrSetRequestHeader;
329
+ originalWarn;
330
+ originalError;
331
+ originalOnError = null;
332
+ originalOnUnhandledRejection = null;
333
+ originalPushState;
334
+ originalReplaceState;
335
+ clickListener;
336
+ popstateListener;
337
+ hashchangeListener;
338
+ lastLocationKey = "";
339
+ lastUiAction;
340
+ constructor(options) {
341
+ this.onRecord = options.onRecord;
342
+ this.targets = options.tracePropagationTargets ?? [];
343
+ this.ignoreUrls = options.ignoreUrls ?? [];
344
+ this.win = options.window ?? (typeof window === "undefined" ? undefined : window);
345
+ this.maxBytes = Math.max(1, options.maxBytes ?? DEFAULT_MAX_BYTES);
346
+ this.budgetWindowMs = Math.max(1, options.budgetWindowMs ?? DEFAULT_BUDGET_WINDOW_MS);
347
+ this.now = options.now ?? (() => Date.now());
348
+ this.budgetWindowStartedAt = this.now();
349
+ this.lastLocationKey = this.win ? pathAndSearchType(this.win) : "";
350
+ this.attachConsole();
351
+ this.attachNetwork();
352
+ this.attachDom();
353
+ this.attachErrors();
354
+ this.attachNavigation();
355
+ }
356
+ detach() {
357
+ if (this.detached)
358
+ return;
359
+ this.detached = true;
360
+ this.lastUiAction = undefined;
361
+ const win = this.win;
362
+ if (win && this.originalFetch) {
363
+ try {
364
+ win.fetch = this.originalFetch;
365
+ }
366
+ catch {
367
+ }
368
+ }
369
+ const xhrProto = win?.XMLHttpRequest?.prototype;
370
+ if (xhrProto && this.originalXhrOpen && this.originalXhrSend && this.originalXhrSetRequestHeader) {
371
+ try {
372
+ xhrProto.open = this.originalXhrOpen;
373
+ xhrProto.send = this.originalXhrSend;
374
+ xhrProto.setRequestHeader = this.originalXhrSetRequestHeader;
375
+ }
376
+ catch {
377
+ }
378
+ }
379
+ const consoleRef = win?.console ?? globalThis.console;
380
+ if (this.originalWarn)
381
+ consoleRef.warn = this.originalWarn;
382
+ if (this.originalError)
383
+ consoleRef.error = this.originalError;
384
+ if (win?.document && this.clickListener) {
385
+ win.document.removeEventListener("click", this.clickListener, true);
386
+ }
387
+ if (win) {
388
+ if (typeof win.removeEventListener === "function") {
389
+ if (this.popstateListener)
390
+ win.removeEventListener("popstate", this.popstateListener);
391
+ if (this.hashchangeListener)
392
+ win.removeEventListener("hashchange", this.hashchangeListener);
393
+ }
394
+ win.onerror = this.originalOnError;
395
+ win.onunhandledrejection = this.originalOnUnhandledRejection;
396
+ if (win.history && this.originalPushState)
397
+ win.history.pushState = this.originalPushState;
398
+ if (win.history && this.originalReplaceState)
399
+ win.history.replaceState = this.originalReplaceState;
400
+ }
401
+ }
402
+ resetBudget() {
403
+ this.bytesUsed = 0;
404
+ this.budgetWindowStartedAt = this.now();
405
+ this.lastUiAction = undefined;
406
+ }
407
+ refreshBudgetWindow() {
408
+ const now = this.now();
409
+ if (now - this.budgetWindowStartedAt >= this.budgetWindowMs) {
410
+ this.bytesUsed = 0;
411
+ this.budgetWindowStartedAt = now;
412
+ }
413
+ }
414
+ emit(record) {
415
+ if (this.detached)
416
+ return;
417
+ const sanitized = {
418
+ ...record,
419
+ summary: truncateString(redactSensitiveString(record.summary ?? record.kind), 240),
420
+ target: record.target ? truncateString(redactSensitiveString(record.target), 240) : undefined,
421
+ route: record.route ? truncateString(redactSensitiveString(record.route), 240) : undefined,
422
+ payload: truncateJsonValue(redactObject(record.payload ?? {})) ?? {},
423
+ };
424
+ const capped = capFlightRecordSize(sanitized, MAX_RECORD_BYTES);
425
+ const estimatedBytes = capped.estimatedBytes;
426
+ this.refreshBudgetWindow();
427
+ const level = capped.record.level ?? "info";
428
+ const critical = level === "error" || capped.record.kind === "exception";
429
+ if (!critical) {
430
+ if (level === "info" && this.bytesUsed + estimatedBytes > this.maxBytes)
431
+ return;
432
+ if (this.bytesUsed + estimatedBytes > this.maxBytes * 1.5)
433
+ return;
434
+ }
435
+ this.bytesUsed += estimatedBytes;
436
+ try {
437
+ this.onRecord(capped.record);
438
+ }
439
+ catch {
440
+ }
441
+ }
442
+ attachConsole() {
443
+ const consoleRef = this.win?.console ?? globalThis.console;
444
+ if (!consoleRef)
445
+ return;
446
+ this.originalWarn = consoleRef.warn;
447
+ this.originalError = consoleRef.error;
448
+ const originalWarn = this.originalWarn;
449
+ const originalError = this.originalError;
450
+ consoleRef.warn = (...args) => {
451
+ this.captureConsole("warn", args);
452
+ return originalWarn?.apply(consoleRef, args);
453
+ };
454
+ consoleRef.error = (...args) => {
455
+ this.captureConsole("error", args);
456
+ return originalError?.apply(consoleRef, args);
457
+ };
458
+ }
459
+ captureConsole(level, args) {
460
+ const rendered = args.map((arg) => safeDescribe(arg)).join(" ");
461
+ this.emit({
462
+ kind: "console",
463
+ level,
464
+ route: routeFromWindow(this.win),
465
+ summary: truncateString(`console.${level}: ${rendered}`, 240),
466
+ payload: {
467
+ arguments: args.slice(0, 8).map((arg) => {
468
+ if (arg instanceof Error) {
469
+ const details = errorDetails(arg);
470
+ return truncateJsonValue({
471
+ name: details.name,
472
+ message: details.message,
473
+ stack: details.stack,
474
+ }) ?? null;
475
+ }
476
+ return truncateJsonValue(redactObject(arg)) ?? null;
477
+ }),
478
+ },
479
+ });
480
+ }
481
+ attachNetwork() {
482
+ const win = this.win;
483
+ if (!win)
484
+ return;
485
+ this.attachXhrNetwork(win);
486
+ if (typeof win.fetch !== "function")
487
+ return;
488
+ this.originalFetch = win.fetch;
489
+ const originalFetch = this.originalFetch;
490
+ win.fetch = (async (input, init) => {
491
+ const started = nowPrecision(win);
492
+ const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.href : requestLike(input) ? input.url : String(input);
493
+ let url;
494
+ try {
495
+ url = new URL(rawUrl, win.location?.href ?? "http://localhost/");
496
+ }
497
+ catch {
498
+ url = undefined;
499
+ }
500
+ if (url && this.shouldIgnoreNetworkUrl(url)) {
501
+ return originalFetch(input, init);
502
+ }
503
+ let traceId;
504
+ let fetchInput = input;
505
+ let fetchInit = init;
506
+ if (url && this.shouldPropagateTrace(url)) {
507
+ const headers = copyHeaders(input, init);
508
+ const existing = headers.get("traceparent");
509
+ const existingTraceId = existing ? extractTraceId(existing) : undefined;
510
+ if (existingTraceId) {
511
+ traceId = existingTraceId;
512
+ }
513
+ else {
514
+ const generated = generateTraceContext();
515
+ traceId = generated.traceId;
516
+ headers.set("traceparent", generated.traceparent);
517
+ }
518
+ if (requestLike(input) && typeof Request !== "undefined") {
519
+ try {
520
+ fetchInput = new Request(input, { headers });
521
+ }
522
+ catch {
523
+ fetchInput = input;
524
+ fetchInit = { ...init, headers };
525
+ }
526
+ }
527
+ else {
528
+ fetchInit = { ...init, headers };
529
+ }
530
+ }
531
+ const method = (init?.method ?? (requestLike(input) ? input.method : "GET")).toUpperCase();
532
+ const endpoint = url ? normalizeEndpointPath(url.href, win.location?.href) : normalizeEndpointPath(rawUrl, win.location?.href);
533
+ const route = routeFromWindow(win);
534
+ const uiTrigger = this.currentUiTrigger(route);
535
+ try {
536
+ const response = await originalFetch(fetchInput, fetchInit);
537
+ const duration = Math.max(0, Math.round(nowPrecision(win) - started));
538
+ const status = typeof response.status === "number" ? response.status : 0;
539
+ const level = status >= 500 ? "error" : status >= 400 ? "warn" : "info";
540
+ this.emitNetworkRecord({
541
+ kind: "network",
542
+ level,
543
+ route,
544
+ target: endpoint,
545
+ method,
546
+ status_code: status,
547
+ duration_ms: duration,
548
+ trace_id: traceId,
549
+ summary: `${method} ${endpoint} -> ${status}`,
550
+ payload: compactObject({
551
+ origin: url?.origin,
552
+ path: endpoint,
553
+ }),
554
+ }, uiTrigger);
555
+ return response;
556
+ }
557
+ catch (error) {
558
+ const duration = Math.max(0, Math.round(nowPrecision(win) - started));
559
+ const details = errorDetails(error);
560
+ this.emitNetworkRecord({
561
+ kind: "network",
562
+ level: "error",
563
+ route,
564
+ target: endpoint,
565
+ method,
566
+ duration_ms: duration,
567
+ trace_id: traceId,
568
+ summary: `${method} ${endpoint} failed: ${details.message}`,
569
+ payload: compactObject({
570
+ origin: url?.origin,
571
+ path: endpoint,
572
+ error_name: details.name,
573
+ error_message: details.message,
574
+ }),
575
+ }, uiTrigger);
576
+ throw error;
577
+ }
578
+ });
579
+ }
580
+ attachXhrNetwork(win) {
581
+ const ctor = win.XMLHttpRequest;
582
+ if (typeof ctor !== "function")
583
+ return;
584
+ const proto = ctor.prototype;
585
+ if (!proto || typeof proto.open !== "function" || typeof proto.send !== "function")
586
+ return;
587
+ this.originalXhrOpen = proto.open;
588
+ this.originalXhrSend = proto.send;
589
+ this.originalXhrSetRequestHeader = proto.setRequestHeader;
590
+ const originalOpen = this.originalXhrOpen;
591
+ const originalSend = this.originalXhrSend;
592
+ const originalSetRequestHeader = this.originalXhrSetRequestHeader;
593
+ const recorder = this;
594
+ proto.open = function open(method, url, async = true, username, password) {
595
+ const xhr = this;
596
+ xhr.__zenithFlight = {
597
+ method: String(method || "GET").toUpperCase(),
598
+ rawUrl: String(url),
599
+ };
600
+ return originalOpen.call(this, method, url, async, username, password);
601
+ };
602
+ proto.setRequestHeader = function setRequestHeader(name, value) {
603
+ const xhr = this;
604
+ if (name.toLowerCase() === "traceparent" && xhr.__zenithFlight) {
605
+ xhr.__zenithFlight.traceparent = value;
606
+ }
607
+ return originalSetRequestHeader.call(this, name, value);
608
+ };
609
+ proto.send = function send(body) {
610
+ const xhr = this;
611
+ const state = xhr.__zenithFlight;
612
+ if (!state || state.started !== undefined) {
613
+ return originalSend.call(this, body);
614
+ }
615
+ let url;
616
+ try {
617
+ url = new URL(state.rawUrl, win.location?.href ?? "http://localhost/");
618
+ }
619
+ catch {
620
+ url = undefined;
621
+ }
622
+ if (url && recorder.shouldIgnoreNetworkUrl(url)) {
623
+ return originalSend.call(this, body);
624
+ }
625
+ if (url && recorder.shouldPropagateTrace(url)) {
626
+ const existingTraceId = state.traceparent ? extractTraceId(state.traceparent) : undefined;
627
+ if (existingTraceId) {
628
+ state.traceId = existingTraceId;
629
+ }
630
+ else {
631
+ const generated = generateTraceContext();
632
+ state.traceId = generated.traceId;
633
+ try {
634
+ originalSetRequestHeader.call(this, "traceparent", generated.traceparent);
635
+ }
636
+ catch {
637
+ }
638
+ }
639
+ }
640
+ state.started = nowPrecision(win);
641
+ const endpoint = url ? normalizeEndpointPath(url.href, win.location?.href) : normalizeEndpointPath(state.rawUrl, win.location?.href);
642
+ const route = routeFromWindow(win);
643
+ const uiTrigger = recorder.currentUiTrigger(route);
644
+ let emitted = false;
645
+ const emitDone = (failed) => {
646
+ if (emitted)
647
+ return;
648
+ emitted = true;
649
+ const duration = Math.max(0, Math.round(nowPrecision(win) - (state.started ?? 0)));
650
+ const status = failed ? 0 : typeof xhr.status === "number" ? xhr.status : 0;
651
+ const level = failed || status >= 500 ? "error" : status >= 400 ? "warn" : "info";
652
+ recorder.emitNetworkRecord({
653
+ kind: "network",
654
+ level,
655
+ route,
656
+ target: endpoint,
657
+ method: state.method,
658
+ status_code: status,
659
+ duration_ms: duration,
660
+ trace_id: state.traceId,
661
+ summary: failed ? `${state.method} ${endpoint} failed` : `${state.method} ${endpoint} -> ${status}`,
662
+ payload: compactObject({
663
+ origin: url?.origin,
664
+ path: endpoint,
665
+ error_name: failed ? "XHR Error" : undefined,
666
+ }),
667
+ }, uiTrigger);
668
+ };
669
+ try {
670
+ xhr.addEventListener("loadend", () => emitDone(false), { once: true });
671
+ xhr.addEventListener("error", () => emitDone(true), { once: true });
672
+ xhr.addEventListener("timeout", () => emitDone(true), { once: true });
673
+ xhr.addEventListener("abort", () => emitDone(true), { once: true });
674
+ }
675
+ catch {
676
+ }
677
+ return originalSend.call(this, body);
678
+ };
679
+ }
680
+ emitNetworkRecord(record, trigger) {
681
+ this.emit({
682
+ ...record,
683
+ payload: this.payloadWithUiTrigger(record.payload, trigger),
684
+ });
685
+ }
686
+ payloadWithUiTrigger(payload, trigger) {
687
+ if (!trigger)
688
+ return payload ?? {};
689
+ return compactObject({
690
+ ...(payload ?? {}),
691
+ trigger_target: trigger.target,
692
+ trigger_summary: trigger.summary,
693
+ trigger_route: trigger.route,
694
+ trigger_delta_ms: trigger.deltaMs,
695
+ });
696
+ }
697
+ currentUiTrigger(route) {
698
+ const action = this.lastUiAction;
699
+ if (!action)
700
+ return undefined;
701
+ const deltaMs = this.now() - action.ts;
702
+ if (deltaMs < 0 || deltaMs > UI_TRIGGER_WINDOW_MS) {
703
+ this.lastUiAction = undefined;
704
+ return undefined;
705
+ }
706
+ if (action.route && route && action.route !== route && !action.navigates) {
707
+ return undefined;
708
+ }
709
+ return {
710
+ target: action.target,
711
+ summary: action.summary,
712
+ route: action.route,
713
+ deltaMs: Math.max(0, Math.round(deltaMs)),
714
+ };
715
+ }
716
+ shouldIgnoreNetworkUrl(url) {
717
+ if (DEFAULT_IGNORED_TELEMETRY_PATH_RE.test(url.pathname))
718
+ return true;
719
+ if (this.ignoreUrls.length === 0)
720
+ return false;
721
+ let origin = this.win?.location?.origin;
722
+ if (!origin && this.win?.location?.href) {
723
+ try {
724
+ origin = new URL(this.win.location.href).origin;
725
+ }
726
+ catch {
727
+ origin = undefined;
728
+ }
729
+ }
730
+ return targetMatches(url, this.ignoreUrls, origin);
731
+ }
732
+ shouldPropagateTrace(url) {
733
+ let origin = this.win?.location?.origin;
734
+ if (!origin && this.win?.location?.href) {
735
+ try {
736
+ origin = new URL(this.win.location.href).origin;
737
+ }
738
+ catch {
739
+ origin = undefined;
740
+ }
741
+ }
742
+ if (origin && url.origin === origin)
743
+ return true;
744
+ return targetMatches(url, this.targets, origin);
745
+ }
746
+ attachDom() {
747
+ const win = this.win;
748
+ if (!win?.document || typeof win.document.addEventListener !== "function")
749
+ return;
750
+ this.clickListener = (event) => {
751
+ const target = event.target;
752
+ if (!target || typeof target !== "object" || isSensitiveElement(target))
753
+ return;
754
+ let element = target;
755
+ if (typeof element.closest !== "function") {
756
+ const parent = target.parentElement;
757
+ if (!parent)
758
+ return;
759
+ element = parent;
760
+ }
761
+ const actionable = closestActionable(element);
762
+ if (!actionable || isSensitiveElement(actionable))
763
+ return;
764
+ const selector = shortSelector(actionable);
765
+ const role = implicitRole(actionable);
766
+ const ariaLabel = actionable.getAttribute("aria-label") ?? undefined;
767
+ const testId = actionable.getAttribute("data-testid") ?? undefined;
768
+ const text = elementText(actionable);
769
+ const label = ariaLabel ?? text ?? testId ?? selector;
770
+ const route = routeFromWindow(win);
771
+ const targetSelector = truncateString(redactSensitiveString(selector), 240);
772
+ const summary = truncateString(redactSensitiveString(`click ${role} "${label}"`), 240);
773
+ const tag = actionable.tagName.toLowerCase();
774
+ const inputType = (actionable.getAttribute("type") ?? "").toLowerCase();
775
+ const navigates = (tag === "a" && actionable.getAttribute("href") !== null) ||
776
+ role === "link" ||
777
+ (tag === "input" && inputType === "submit") ||
778
+ (tag === "button" && inputType === "submit");
779
+ this.lastUiAction = {
780
+ target: targetSelector,
781
+ summary,
782
+ route,
783
+ navigates,
784
+ ts: this.now(),
785
+ };
786
+ this.emit({
787
+ kind: "ui_action",
788
+ level: "info",
789
+ route,
790
+ target: targetSelector,
791
+ summary,
792
+ payload: compactObject({
793
+ role,
794
+ aria_label: ariaLabel ? truncateString(redactSensitiveString(ariaLabel), 120) : undefined,
795
+ data_testid: testId,
796
+ text,
797
+ tag: actionable.tagName.toLowerCase(),
798
+ }),
799
+ });
800
+ };
801
+ win.document.addEventListener("click", this.clickListener, true);
802
+ }
803
+ attachErrors() {
804
+ const win = this.win;
805
+ if (!win)
806
+ return;
807
+ this.originalOnError = win.onerror ?? null;
808
+ this.originalOnUnhandledRejection = win.onunhandledrejection ?? null;
809
+ const previousOnError = this.originalOnError;
810
+ const previousRejection = this.originalOnUnhandledRejection;
811
+ win.onerror = (message, source, lineno, colno, error) => {
812
+ this.captureException(error ?? message, "window.onerror", {
813
+ source: typeof source === "string" ? source : undefined,
814
+ lineno: typeof lineno === "number" ? lineno : undefined,
815
+ colno: typeof colno === "number" ? colno : undefined,
816
+ });
817
+ if (typeof previousOnError === "function") {
818
+ return previousOnError.call(win, message, source, lineno, colno, error);
819
+ }
820
+ return false;
821
+ };
822
+ win.onunhandledrejection = (event) => {
823
+ this.captureException(event?.reason ?? event, "unhandledrejection", {});
824
+ if (typeof previousRejection === "function") {
825
+ return previousRejection.call(win, event);
826
+ }
827
+ return undefined;
828
+ };
829
+ }
830
+ captureException(error, source, extra) {
831
+ const details = errorDetails(error);
832
+ this.emit({
833
+ kind: "exception",
834
+ level: "error",
835
+ route: routeFromWindow(this.win),
836
+ summary: truncateString(`${details.name}: ${details.message}`, 240),
837
+ payload: compactObject({
838
+ name: details.name,
839
+ message: details.message,
840
+ stack: details.stack ? truncateString(details.stack, 1200) : undefined,
841
+ capture_source: source,
842
+ ...extra,
843
+ }),
844
+ });
845
+ }
846
+ attachNavigation() {
847
+ const win = this.win;
848
+ if (!win?.history)
849
+ return;
850
+ if (typeof win.history.pushState === "function") {
851
+ this.originalPushState = win.history.pushState;
852
+ const originalPush = this.originalPushState;
853
+ win.history.pushState = (data, unused, url) => {
854
+ const result = originalPush.call(win.history, data, unused, url);
855
+ this.recordNavigationIfChanged("push_state");
856
+ return result;
857
+ };
858
+ }
859
+ if (typeof win.history.replaceState === "function") {
860
+ this.originalReplaceState = win.history.replaceState;
861
+ const originalReplace = this.originalReplaceState;
862
+ win.history.replaceState = (data, unused, url) => {
863
+ const result = originalReplace.call(win.history, data, unused, url);
864
+ this.recordNavigationIfChanged("replace_state");
865
+ return result;
866
+ };
867
+ }
868
+ if (typeof win.addEventListener === "function") {
869
+ this.popstateListener = () => this.recordNavigationIfChanged("popstate");
870
+ this.hashchangeListener = () => this.recordNavigationIfChanged("hashchange");
871
+ win.addEventListener("popstate", this.popstateListener);
872
+ win.addEventListener("hashchange", this.hashchangeListener);
873
+ }
874
+ }
875
+ recordNavigationIfChanged(trigger) {
876
+ const win = this.win;
877
+ if (!win?.location)
878
+ return;
879
+ const nextKey = pathAndSearchType(win);
880
+ if (nextKey === this.lastLocationKey)
881
+ return;
882
+ const previousKey = this.lastLocationKey;
883
+ this.lastLocationKey = nextKey;
884
+ const to = routeFromWindow(win);
885
+ const fromPath = previousKey.split(/[?#]/, 1)[0] || undefined;
886
+ const searchChanged = queryPart(previousKey) !== queryPart(nextKey);
887
+ const hashChanged = hashPart(previousKey) !== hashPart(nextKey);
888
+ this.emit({
889
+ kind: "navigation",
890
+ level: "info",
891
+ route: to,
892
+ target: to,
893
+ summary: `navigate ${fromPath ?? "unknown"} -> ${to ?? "unknown"}`,
894
+ payload: compactObject({
895
+ from: fromPath,
896
+ to,
897
+ trigger,
898
+ search_changed: searchChanged,
899
+ hash_changed: hashChanged,
900
+ }),
901
+ });
902
+ }
903
+ }
904
+ export function attachFlightRecorder(options) {
905
+ return new BrowserFlightRecorder(options);
906
+ }
907
+ //# sourceMappingURL=flight.js.map