@inkronik/browser-sdk 2.0.0 → 2.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.
@@ -0,0 +1,864 @@
1
+ // src/constants.ts
2
+ var DEFAULT_BATCH_SIZE = 20;
3
+ var DEFAULT_MAX_QUEUE_SIZE = 200;
4
+ var DEFAULT_FLUSH_INTERVAL_MS = 5000;
5
+ var DEFAULT_MAX_RETRIES = 2;
6
+ var DEFAULT_RETRY_BASE_MS = 250;
7
+ var DEFAULT_SAMPLE_RATE = 1;
8
+ var SDK_NAME = "@inkronik/browser-sdk";
9
+ var SDK_VERSION = "2.1.0";
10
+ var DEFAULT_SESSION_INACTIVITY_MS = 30 * 60 * 1000;
11
+ var DEFAULT_SESSION_MAX_DURATION_MS = 30 * 60 * 1000;
12
+ var BROWSER_SESSION_STORAGE_KEY = "inkronik.browser.session";
13
+ var REDACTED_VALUE = "[REDACTED]";
14
+ var MAX_ATTRIBUTES = 32;
15
+ var MAX_ATTRIBUTE_KEY_LENGTH = 64;
16
+ var MAX_ATTRIBUTE_VALUE_LENGTH = 512;
17
+ var MAX_EVENT_MESSAGE_LENGTH = 1024;
18
+ var MAX_ERROR_VALUE_LENGTH = 4096;
19
+ var INKRONIK_ORIGINAL_BROWSER_FETCH = Symbol.for("inkronik.browser.originalFetch");
20
+ var SENSITIVE_KEY_FRAGMENTS = [
21
+ "password",
22
+ "passwd",
23
+ "secret",
24
+ "token",
25
+ "authorization",
26
+ "cookie",
27
+ "api_key",
28
+ "apikey",
29
+ "credential",
30
+ "session",
31
+ "card",
32
+ "cvv",
33
+ "cvc",
34
+ "email",
35
+ "phone",
36
+ "ssn",
37
+ "input",
38
+ "value"
39
+ ];
40
+ var EMAIL_PATTERN = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi;
41
+ var PHONE_PATTERN = /\b(?:\+?\d[\d .()-]{7,}\d)\b/g;
42
+ var CARD_PATTERN = /\b(?:\d[ -]*?){13,19}\b/g;
43
+ var TOKEN_PATTERN = /\b(?:Bearer\s+)?(?:ik_(?:live|pub)_[A-Za-z0-9_-]+|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)\b/g;
44
+ var ROUTE_UUID_SEGMENT_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
45
+ var ROUTE_ULID_SEGMENT_PATTERN = /^[0-9A-HJKMNP-TV-Z]{26}$/iu;
46
+ var ROUTE_OBJECT_ID_SEGMENT_PATTERN = /^[0-9a-f]{24}$/iu;
47
+ var ROUTE_NUMERIC_SEGMENT_PATTERN = /^\d+$/u;
48
+
49
+ // src/sanitizer.ts
50
+ var normalizeKey = (value) => value.toLowerCase().replaceAll(/[^a-z0-9]+/g, "_");
51
+ var freeformSecretPattern = /((?:password|passwd|passphrase|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|client[_-]?secret|refresh[_-]?token|id[_-]?token|jwt|credential|signature|session|cookie|card[_-]?number|credit[_-]?card|cvv|cvc|ssn)\s*[:=]\s*)([^&\s,"'}]+)/gi;
52
+ var isSensitiveBrowserKey = (key) => {
53
+ const normalized = normalizeKey(key);
54
+ return SENSITIVE_KEY_FRAGMENTS.some((fragment) => normalized.includes(fragment));
55
+ };
56
+ var redactBrowserValue = (value) => value.replaceAll(TOKEN_PATTERN, REDACTED_VALUE).replaceAll(EMAIL_PATTERN, REDACTED_VALUE).replaceAll(PHONE_PATTERN, REDACTED_VALUE).replaceAll(CARD_PATTERN, REDACTED_VALUE);
57
+ var redactBrowserErrorValue = (value) => redactBrowserValue(value).replaceAll(freeformSecretPattern, `$1${REDACTED_VALUE}`);
58
+ var sanitizeValue = ({ key, value }) => {
59
+ const isFreeformErrorValue = key === "message" || key === "stack" || key === "reason";
60
+ if (isSensitiveBrowserKey(key) || isFreeformErrorValue) {
61
+ return REDACTED_VALUE;
62
+ }
63
+ if (typeof value !== "string") {
64
+ return value;
65
+ }
66
+ const isUrlValue = key === "file" || key === "url" || key.endsWith("_url");
67
+ if (isUrlValue) {
68
+ try {
69
+ return sanitizeBrowserUrl(value).slice(0, MAX_ATTRIBUTE_VALUE_LENGTH);
70
+ } catch {
71
+ return REDACTED_VALUE;
72
+ }
73
+ }
74
+ return redactBrowserValue(value.slice(0, MAX_ATTRIBUTE_VALUE_LENGTH));
75
+ };
76
+ var sanitizeBrowserAttributes = (attributes) => Object.fromEntries(Object.entries(attributes).slice(0, MAX_ATTRIBUTES).filter(([key]) => key.length <= MAX_ATTRIBUTE_KEY_LENGTH).map(([key, value]) => [key, sanitizeValue({ key, value })]));
77
+ var sanitizeBrowserUrl = (value) => {
78
+ const parsed = new URL(value);
79
+ const isSupportedProtocol = parsed.protocol === "http:" || parsed.protocol === "https:";
80
+ if (!isSupportedProtocol) {
81
+ return "";
82
+ }
83
+ return `${parsed.origin}${sanitizeBrowserRoute(parsed.pathname)}`;
84
+ };
85
+ var createPrivacyPreservingUrlSanitizer = (customSanitizer) => (url) => {
86
+ try {
87
+ const baselineUrl = sanitizeBrowserUrl(url.toString());
88
+ if (customSanitizer === undefined) {
89
+ return baselineUrl;
90
+ }
91
+ return sanitizeBrowserUrl(customSanitizer(new URL(baselineUrl)));
92
+ } catch {
93
+ return "";
94
+ }
95
+ };
96
+ var isIdentifierRouteSegment = (segment) => ROUTE_UUID_SEGMENT_PATTERN.test(segment) || ROUTE_ULID_SEGMENT_PATTERN.test(segment) || ROUTE_OBJECT_ID_SEGMENT_PATTERN.test(segment) || ROUTE_NUMERIC_SEGMENT_PATTERN.test(segment);
97
+ var sanitizeBrowserRoute = (value) => {
98
+ const path = value.split(/[?#]/u).at(0)?.slice(0, 500) ?? "";
99
+ return path.split("/").map((segment) => isIdentifierRouteSegment(segment) ? ":id" : segment).join("/");
100
+ };
101
+
102
+ // src/browser-instrumentation.ts
103
+ var safeUrl = (value) => {
104
+ try {
105
+ return sanitizeBrowserUrl(value);
106
+ } catch {
107
+ return "";
108
+ }
109
+ };
110
+ var installNavigationInstrumentation = (input) => {
111
+ if (!input.enableNavigationTracking) {
112
+ return () => {
113
+ return;
114
+ };
115
+ }
116
+ const originalPushState = input.environment.history.pushState;
117
+ const originalReplaceState = input.environment.history.replaceState;
118
+ const captureNavigation = () => input.beginView("navigation");
119
+ const onPopState = () => captureNavigation();
120
+ input.environment.history.pushState = (...arguments_) => {
121
+ const previousUrl = input.environment.location.href;
122
+ originalPushState.apply(input.environment.history, arguments_);
123
+ if (input.environment.location.href !== previousUrl) {
124
+ captureNavigation();
125
+ }
126
+ };
127
+ input.environment.history.replaceState = (...arguments_) => {
128
+ const previousUrl = input.environment.location.href;
129
+ originalReplaceState.apply(input.environment.history, arguments_);
130
+ if (input.environment.location.href !== previousUrl) {
131
+ captureNavigation();
132
+ }
133
+ };
134
+ input.environment.window.addEventListener("popstate", onPopState);
135
+ return () => {
136
+ input.environment.history.pushState = originalPushState;
137
+ input.environment.history.replaceState = originalReplaceState;
138
+ input.environment.window.removeEventListener("popstate", onPopState);
139
+ };
140
+ };
141
+ var installFetchInstrumentation = (input) => {
142
+ if (!input.enableFetchTracing) {
143
+ return () => {
144
+ return;
145
+ };
146
+ }
147
+ const currentFetch = input.environment.window.fetch;
148
+ if (Reflect.get(currentFetch, INKRONIK_ORIGINAL_BROWSER_FETCH) !== undefined) {
149
+ return () => {
150
+ return;
151
+ };
152
+ }
153
+ Reflect.defineProperty(input.traceFetch, INKRONIK_ORIGINAL_BROWSER_FETCH, { value: currentFetch });
154
+ input.environment.window.fetch = input.traceFetch;
155
+ return () => {
156
+ if (input.environment.window.fetch === input.traceFetch) {
157
+ input.environment.window.fetch = currentFetch;
158
+ }
159
+ };
160
+ };
161
+ var installErrorInstrumentation = (input) => {
162
+ const onError = (event) => {
163
+ input.capture({
164
+ eventType: "javascript_error",
165
+ name: event.error instanceof Error ? event.error.name : "Error",
166
+ attributes: {
167
+ message: event.message,
168
+ stack: event.error instanceof Error ? event.error.stack ?? "" : "",
169
+ file: safeUrl(event.filename),
170
+ line: event.lineno,
171
+ column: event.colno
172
+ }
173
+ });
174
+ };
175
+ const onUnhandledRejection = (event) => {
176
+ const reason = event.reason;
177
+ const isError = reason instanceof Error;
178
+ input.capture({
179
+ eventType: "unhandled_rejection",
180
+ name: isError ? reason.name : "UnhandledRejection",
181
+ attributes: {
182
+ reason: isError ? reason.message : typeof reason === "string" ? reason : "[non-error rejection]",
183
+ stack: isError ? reason.stack ?? "" : ""
184
+ }
185
+ });
186
+ };
187
+ input.environment.window.addEventListener("error", onError);
188
+ input.environment.window.addEventListener("unhandledrejection", onUnhandledRejection);
189
+ return () => {
190
+ input.environment.window.removeEventListener("error", onError);
191
+ input.environment.window.removeEventListener("unhandledrejection", onUnhandledRejection);
192
+ };
193
+ };
194
+ var observe = ({
195
+ capture,
196
+ entryTypes
197
+ }) => {
198
+ if (typeof PerformanceObserver === "undefined") {
199
+ return () => {
200
+ return;
201
+ };
202
+ }
203
+ const observer = new PerformanceObserver((list) => list.getEntries().forEach(capture));
204
+ entryTypes.forEach((type) => {
205
+ try {
206
+ observer.observe({ type, buffered: true });
207
+ } catch {}
208
+ });
209
+ return () => observer.disconnect();
210
+ };
211
+ var installWebVitalsInstrumentation = (input) => {
212
+ const cleanupObservers = [
213
+ observe({
214
+ entryTypes: ["largest-contentful-paint"],
215
+ capture: (entry) => input.capture({ eventType: "web_vital", name: "LCP", measurements: { value: entry.startTime }, attributes: { unit: "ms" } })
216
+ }),
217
+ observe({
218
+ entryTypes: ["layout-shift"],
219
+ capture: (entry) => {
220
+ const layoutShift = entry;
221
+ if (!layoutShift.hadRecentInput) {
222
+ input.capture({ eventType: "web_vital", name: "CLS", measurements: { value: layoutShift.value }, attributes: { unit: "score" } });
223
+ }
224
+ }
225
+ }),
226
+ observe({
227
+ entryTypes: ["event"],
228
+ capture: (entry) => {
229
+ const interaction = entry;
230
+ if (interaction.interactionId > 0) {
231
+ input.capture({ eventType: "web_vital", name: "INP", measurements: { value: interaction.duration }, attributes: { unit: "ms" } });
232
+ }
233
+ }
234
+ }),
235
+ observe({
236
+ entryTypes: ["paint"],
237
+ capture: (entry) => {
238
+ if (entry.name === "first-contentful-paint") {
239
+ input.capture({ eventType: "web_vital", name: "FCP", measurements: { value: entry.startTime }, attributes: { unit: "ms" } });
240
+ }
241
+ }
242
+ })
243
+ ];
244
+ const navigation = input.environment.performance.getEntriesByType("navigation").at(0);
245
+ if (navigation !== undefined) {
246
+ input.capture({
247
+ eventType: "web_vital",
248
+ name: "TTFB",
249
+ measurements: { value: Math.max(0, navigation.responseStart - navigation.requestStart) },
250
+ attributes: { unit: "ms" }
251
+ });
252
+ }
253
+ return () => cleanupObservers.forEach((cleanup) => cleanup());
254
+ };
255
+ var installBrowserInstrumentation = (input) => {
256
+ const cleanups = [
257
+ installNavigationInstrumentation(input),
258
+ installFetchInstrumentation(input),
259
+ installErrorInstrumentation(input),
260
+ installWebVitalsInstrumentation(input)
261
+ ];
262
+ return () => cleanups.forEach((cleanup) => cleanup());
263
+ };
264
+
265
+ // src/utils.ts
266
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
267
+ var safeString = (value) => {
268
+ try {
269
+ return String(value);
270
+ } catch {
271
+ return "[unserializable thrown value]";
272
+ }
273
+ };
274
+ var errorProperty = ({ error, property }) => {
275
+ if (!isRecord(error)) {
276
+ return "";
277
+ }
278
+ const value = (() => {
279
+ try {
280
+ return Reflect.get(error, property);
281
+ } catch {
282
+ return;
283
+ }
284
+ })();
285
+ return typeof value === "string" || typeof value === "number" ? safeString(value) : "";
286
+ };
287
+ var normalizeCapturedBrowserError = (error) => {
288
+ const capturedType = errorProperty({ error, property: "name" });
289
+ const capturedMessage = errorProperty({ error, property: "message" });
290
+ const errorType = capturedType === "" ? error instanceof Error ? "Error" : "NonError" : capturedType;
291
+ const errorMessage = capturedMessage === "" ? safeString(error) : capturedMessage;
292
+ const errorStack = errorProperty({ error, property: "stack" });
293
+ return {
294
+ type: redactBrowserValue(errorType.slice(0, 255)),
295
+ message: redactBrowserErrorValue(errorMessage.slice(0, MAX_ERROR_VALUE_LENGTH)),
296
+ stack: redactBrowserErrorValue(errorStack.slice(0, MAX_ERROR_VALUE_LENGTH)),
297
+ code: redactBrowserValue(errorProperty({ error, property: "code" }).slice(0, 255)),
298
+ handled: true
299
+ };
300
+ };
301
+ var createUuid = () => crypto.randomUUID();
302
+ var trimTrailingSlashes = (value) => {
303
+ let endIndex = value.length;
304
+ while (endIndex > 0 && value.at(endIndex - 1) === "/") {
305
+ endIndex -= 1;
306
+ }
307
+ return value.slice(0, endIndex);
308
+ };
309
+ var normalizeCollectorUrl = trimTrailingSlashes;
310
+ var ENVIRONMENT_MAX_LENGTH = 63;
311
+ var ENVIRONMENT_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
312
+ var normalizeTelemetryEnvironment = (value) => {
313
+ const environment = value.trim().toLowerCase();
314
+ if (environment.length === 0 || environment.length > ENVIRONMENT_MAX_LENGTH || !ENVIRONMENT_PATTERN.test(environment)) {
315
+ throw new TypeError("Inkronik environment must be a canonical slug containing only lowercase letters, numbers, dots, underscores, or dashes");
316
+ }
317
+ return environment;
318
+ };
319
+ var resolveTracePropagationOrigins = ({ environment, configuredOrigins }) => new Set([...environment === null ? [] : [environment.location.origin], ...(configuredOrigins ?? []).map((origin) => new URL(origin).origin)]);
320
+ var shouldTraceBrowserRequest = ({ collectorUrl, requestUrl, tracePropagationOrigins }) => {
321
+ const collector = new URL(collectorUrl);
322
+ const collectorPath = trimTrailingSlashes(collector.pathname);
323
+ const isCollectorRequest = requestUrl.origin === collector.origin && requestUrl.pathname.startsWith(`${collectorPath}/v1/browser`);
324
+ return !isCollectorRequest && tracePropagationOrigins.has(requestUrl.origin);
325
+ };
326
+ var resolveBrowserEnvironment = () => {
327
+ if (typeof window === "undefined" || typeof document === "undefined" || typeof navigator === "undefined") {
328
+ return null;
329
+ }
330
+ return { window, document, navigator, history: window.history, location: window.location, performance: window.performance };
331
+ };
332
+ var resolveBrowserFetch = ({ configuredFetch, environment }) => {
333
+ if (configuredFetch !== undefined) {
334
+ return configuredFetch.bind(environment?.window ?? globalThis);
335
+ }
336
+ if (environment !== null) {
337
+ return environment.window.fetch.bind(environment.window);
338
+ }
339
+ return globalThis.fetch.bind(globalThis);
340
+ };
341
+ var normalizeBrowserUserContext = (input) => ({
342
+ id: redactBrowserValue(input.id.slice(0, 255)),
343
+ attributes: sanitizeBrowserAttributes(Object.fromEntries(Object.entries(input.attributes ?? {}).map(([key, value]) => [`user.${key}`, value])))
344
+ });
345
+ var deterministicSample = ({ sampleRate, sessionId }) => {
346
+ const normalizedRate = Math.min(1, Math.max(0, sampleRate));
347
+ const hash = Array.from(sessionId).reduce((value, character) => (value * 31 + character.charCodeAt(0)) % 4294967296, 2166136261);
348
+ return hash / 4294967295 <= normalizedRate;
349
+ };
350
+ var buildBrowserEvent = ({
351
+ attributes,
352
+ defaultAttributes,
353
+ eventType,
354
+ error,
355
+ level,
356
+ message,
357
+ measurements,
358
+ name,
359
+ pageUrl,
360
+ route,
361
+ sessionId,
362
+ userId,
363
+ viewId,
364
+ traceId,
365
+ spanId
366
+ }) => ({
367
+ event_id: createUuid(),
368
+ event_type: eventType,
369
+ name: name.slice(0, 100),
370
+ level: level ?? (eventType === "javascript_error" || eventType === "unhandled_rejection" ? "error" : "info"),
371
+ message: redactBrowserErrorValue((message ?? "").slice(0, MAX_EVENT_MESSAGE_LENGTH)),
372
+ timestamp: new Date().toISOString(),
373
+ session_id: sessionId,
374
+ view_id: viewId,
375
+ page_url: pageUrl,
376
+ route: sanitizeBrowserRoute(route),
377
+ user_id: redactBrowserValue(userId.slice(0, 255)),
378
+ trace_id: traceId,
379
+ span_id: spanId,
380
+ error_type: error?.type ?? "",
381
+ error_message: error?.message ?? "",
382
+ error_stack: error?.stack ?? "",
383
+ error_code: error?.code ?? "",
384
+ error_handled: error?.handled ?? false,
385
+ attributes: sanitizeBrowserAttributes({ ...defaultAttributes, ...attributes }),
386
+ measurements: Object.fromEntries(Object.entries(measurements ?? {}).filter(([, value]) => Number.isFinite(value)).slice(0, 16))
387
+ });
388
+ var buildBrowserSpan = ({
389
+ attributes,
390
+ context,
391
+ durationUs,
392
+ endTime,
393
+ httpMethod,
394
+ httpStatusCode,
395
+ httpUrl,
396
+ name,
397
+ pageUrl,
398
+ route,
399
+ sessionId,
400
+ spanCategory,
401
+ spanKind,
402
+ statusCode,
403
+ statusMessage,
404
+ timestamp,
405
+ userId,
406
+ viewId
407
+ }) => ({
408
+ trace_id: context.traceId,
409
+ span_id: context.spanId,
410
+ parent_span_id: context.parentSpanId,
411
+ name: redactBrowserValue(name.slice(0, 100)),
412
+ timestamp,
413
+ end_time: endTime,
414
+ duration_us: Math.max(0, Math.round(durationUs)),
415
+ span_kind: spanKind,
416
+ span_category: spanCategory,
417
+ status_code: statusCode,
418
+ status_message: statusMessage === undefined ? "" : redactBrowserValue(statusMessage.slice(0, 512)),
419
+ session_id: sessionId,
420
+ view_id: viewId,
421
+ page_url: pageUrl,
422
+ route: sanitizeBrowserRoute(route),
423
+ user_id: redactBrowserValue(userId.slice(0, 255)),
424
+ http_method: httpMethod?.slice(0, 16) ?? "",
425
+ http_url: httpUrl === undefined ? "" : sanitizeBrowserUrl(httpUrl),
426
+ http_status_code: httpStatusCode ?? 0,
427
+ attributes: sanitizeBrowserAttributes(attributes ?? {})
428
+ });
429
+
430
+ // src/session.ts
431
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
432
+ var readSession = (storage) => {
433
+ if (storage === null) {
434
+ return null;
435
+ }
436
+ try {
437
+ const value = storage.getItem(BROWSER_SESSION_STORAGE_KEY);
438
+ if (value === null) {
439
+ return null;
440
+ }
441
+ const parsed = JSON.parse(value);
442
+ const isValid = typeof parsed.id === "string" && UUID_PATTERN.test(parsed.id) && typeof parsed.startedAt === "number" && Number.isFinite(parsed.startedAt) && typeof parsed.lastActivityAt === "number" && Number.isFinite(parsed.lastActivityAt);
443
+ return isValid ? parsed : null;
444
+ } catch {
445
+ return null;
446
+ }
447
+ };
448
+ var writeSession = ({ record, storage }) => {
449
+ if (storage === null) {
450
+ return;
451
+ }
452
+ try {
453
+ storage.setItem(BROWSER_SESSION_STORAGE_KEY, JSON.stringify(record));
454
+ } catch {}
455
+ };
456
+ var canReuseSession = ({ inactivityMs, maxDurationMs, now, record }) => now >= record.lastActivityAt && now - record.lastActivityAt <= inactivityMs && now - record.startedAt <= maxDurationMs;
457
+ var resolveBrowserStorage = (environmentWindow) => {
458
+ if (environmentWindow === null) {
459
+ return null;
460
+ }
461
+ try {
462
+ return environmentWindow.localStorage;
463
+ } catch {
464
+ return null;
465
+ }
466
+ };
467
+ var resolveBrowserSession = ({
468
+ storage,
469
+ now = Date.now(),
470
+ inactivityMs = DEFAULT_SESSION_INACTIVITY_MS,
471
+ maxDurationMs = DEFAULT_SESSION_MAX_DURATION_MS
472
+ }) => {
473
+ const existing = readSession(storage);
474
+ const initialRecord = existing !== null && canReuseSession({ record: existing, now, inactivityMs, maxDurationMs }) ? existing : { id: createUuid(), startedAt: now, lastActivityAt: now };
475
+ const state = { record: initialRecord };
476
+ const persistActivity = () => {
477
+ const activityAt = Date.now();
478
+ const nextRecord = canReuseSession({ record: state.record, now: activityAt, inactivityMs, maxDurationMs }) ? { ...state.record, lastActivityAt: activityAt } : { id: createUuid(), startedAt: activityAt, lastActivityAt: activityAt };
479
+ state.record = nextRecord;
480
+ writeSession({ record: nextRecord, storage });
481
+ return nextRecord.id;
482
+ };
483
+ writeSession({ record: initialRecord, storage });
484
+ return { currentId: () => state.record.id, touch: persistActivity };
485
+ };
486
+
487
+ // src/trace-context.ts
488
+ var createHexIdentifier = (byteLength) => {
489
+ const value = Array.from(crypto.getRandomValues(new Uint8Array(byteLength)), (byte) => byte.toString(16).padStart(2, "0")).join("");
490
+ return /^0+$/u.test(value) ? createHexIdentifier(byteLength) : value;
491
+ };
492
+ var createRootBrowserTraceContext = () => ({
493
+ traceId: createHexIdentifier(16),
494
+ spanId: createHexIdentifier(8),
495
+ parentSpanId: ""
496
+ });
497
+ var toBrowserTraceparent = (context) => `00-${context.traceId}-${context.spanId}-01`;
498
+
499
+ // src/transport.ts
500
+ var delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
501
+ var postBatch = async (input) => {
502
+ const body = JSON.stringify({ public_key: input.publicKey, environment: input.environment, events: input.events, spans: input.spans });
503
+ if (input.useBeacon && typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") {
504
+ const delivered = navigator.sendBeacon(`${input.collectorUrl}/v1/browser`, new Blob([body], { type: "text/plain;charset=UTF-8" }));
505
+ return { delivered };
506
+ }
507
+ const response = await input.fetchImpl(`${input.collectorUrl}/v1/browser`, {
508
+ method: "POST",
509
+ headers: { "Content-Type": "application/json" },
510
+ body,
511
+ keepalive: true,
512
+ credentials: "omit"
513
+ });
514
+ if (!response.ok) {
515
+ throw new Error(`Inkronik browser ingest failed with status ${response.status}`);
516
+ }
517
+ return { delivered: true };
518
+ };
519
+ var sendBrowserBatch = async (input) => {
520
+ const attempts = Array.from({ length: input.useBeacon ? 1 : input.maxRetries + 1 }, (_, index) => index);
521
+ return attempts.reduce(async (previous, attempt) => {
522
+ const previousResult = await previous;
523
+ if (previousResult.delivered) {
524
+ return previousResult;
525
+ }
526
+ if (attempt > 0) {
527
+ const jitter = Math.floor(Math.random() * DEFAULT_RETRY_BASE_MS);
528
+ await delay(DEFAULT_RETRY_BASE_MS * 2 ** (attempt - 1) + jitter);
529
+ }
530
+ return postBatch(input).catch((error) => {
531
+ if (attempt === attempts.length - 1) {
532
+ input.onError(error instanceof Error ? error : new Error(String(error)));
533
+ }
534
+ return { delivered: false };
535
+ });
536
+ }, Promise.resolve({ delivered: false }));
537
+ };
538
+
539
+ // src/client.ts
540
+ var getBrowserAttributes = (userAgent) => {
541
+ const browserMatch = userAgent.match(/(?:Edg|Chrome|Firefox|Version)\/([\d.]+)/u);
542
+ const browserName = userAgent.includes("Edg/") ? "Edge" : userAgent.includes("Chrome/") ? "Chrome" : userAgent.includes("Firefox/") ? "Firefox" : userAgent.includes("Safari/") ? "Safari" : "Other";
543
+ const osName = userAgent.includes("Windows") ? "Windows" : userAgent.includes("Android") ? "Android" : userAgent.includes("iPhone") || userAgent.includes("iPad") ? "iOS" : userAgent.includes("Mac OS") ? "macOS" : userAgent.includes("Linux") ? "Linux" : "Other";
544
+ return {
545
+ browser_name: browserName,
546
+ browser_version: browserMatch?.at(1) ?? "",
547
+ os_name: osName,
548
+ device_type: /Mobi|Android|iPhone|iPad/u.test(userAgent) ? "mobile" : "desktop",
549
+ sdk_name: SDK_NAME,
550
+ sdk_version: SDK_VERSION
551
+ };
552
+ };
553
+
554
+ class InkronikBrowserClient {
555
+ publicKey;
556
+ collectorUrl;
557
+ telemetryEnvironment;
558
+ sampleRate;
559
+ defaultAttributes;
560
+ maxBatchSize;
561
+ maxQueueSize;
562
+ maxRetries;
563
+ fetchImpl;
564
+ onError;
565
+ getRoute;
566
+ sanitizeUrl;
567
+ enableFetchTracing;
568
+ enableNavigationTracking;
569
+ tracePropagationOrigins;
570
+ environment = resolveBrowserEnvironment();
571
+ session = resolveBrowserSession({ storage: resolveBrowserStorage(this.environment?.window ?? null) });
572
+ flushTimer;
573
+ cleanupInstrumentation;
574
+ cleanupLifecycle;
575
+ sampled;
576
+ queue = [];
577
+ flushing = null;
578
+ viewContext;
579
+ userId = "";
580
+ userAttributes = {};
581
+ closed = false;
582
+ constructor(options) {
583
+ this.publicKey = options.publicKey;
584
+ this.collectorUrl = normalizeCollectorUrl(options.collectorUrl);
585
+ this.telemetryEnvironment = normalizeTelemetryEnvironment(options.environment);
586
+ this.sampleRate = options.sampleRate ?? DEFAULT_SAMPLE_RATE;
587
+ this.defaultAttributes = {
588
+ ...this.environment === null ? {} : getBrowserAttributes(this.environment.navigator.userAgent),
589
+ ...options.defaultAttributes
590
+ };
591
+ this.maxBatchSize = Math.max(1, options.maxBatchSize ?? DEFAULT_BATCH_SIZE);
592
+ this.maxQueueSize = Math.max(1, options.maxQueueSize ?? DEFAULT_MAX_QUEUE_SIZE);
593
+ this.maxRetries = Math.max(0, options.maxRetries ?? DEFAULT_MAX_RETRIES);
594
+ this.fetchImpl = resolveBrowserFetch({ configuredFetch: options.fetchImpl, environment: this.environment });
595
+ this.onError = options.onError ?? (() => {
596
+ return;
597
+ });
598
+ this.getRoute = options.getRoute ?? (() => this.environment?.location.pathname ?? "");
599
+ this.sanitizeUrl = createPrivacyPreservingUrlSanitizer(options.sanitizeUrl);
600
+ this.enableFetchTracing = options.enableFetchTracing ?? true;
601
+ this.enableNavigationTracking = options.enableNavigationTracking ?? true;
602
+ this.tracePropagationOrigins = resolveTracePropagationOrigins({
603
+ environment: this.environment,
604
+ configuredOrigins: options.tracePropagationOrigins
605
+ });
606
+ this.sampled = deterministicSample({ sampleRate: this.sampleRate, sessionId: this.session.currentId() });
607
+ this.viewContext = { ...createRootBrowserTraceContext(), viewId: createUuid() };
608
+ if (options.user !== undefined) {
609
+ this.setUser(options.user);
610
+ }
611
+ this.flushTimer = this.environment === null ? null : setInterval(() => void this.flush(), options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS);
612
+ this.cleanupInstrumentation = this.installInstrumentation();
613
+ this.cleanupLifecycle = this.installLifecycle();
614
+ this.startView({ eventType: "page_view", name: "page_view" });
615
+ }
616
+ capture(input) {
617
+ this.enqueue({
618
+ eventType: "custom",
619
+ name: input.name,
620
+ level: input.level,
621
+ message: input.message,
622
+ attributes: input.attributes,
623
+ measurements: input.measurements
624
+ });
625
+ }
626
+ captureError(error, options) {
627
+ this.enqueue({
628
+ eventType: "custom",
629
+ name: options.name,
630
+ level: "error",
631
+ message: options.message,
632
+ error: normalizeCapturedBrowserError(error),
633
+ attributes: options.attributes,
634
+ measurements: options.measurements
635
+ });
636
+ }
637
+ setUser(input) {
638
+ const context = normalizeBrowserUserContext(input);
639
+ this.userId = context.id;
640
+ this.userAttributes = context.attributes;
641
+ }
642
+ clearUser() {
643
+ this.userId = "";
644
+ this.userAttributes = {};
645
+ }
646
+ captureNavigation(input) {
647
+ this.startView({ eventType: "navigation", name: input.navigationType, url: input.url });
648
+ }
649
+ flush() {
650
+ return this.flushBatch(false);
651
+ }
652
+ async shutdown() {
653
+ if (this.closed) {
654
+ return;
655
+ }
656
+ this.closed = true;
657
+ if (this.flushTimer !== null) {
658
+ clearInterval(this.flushTimer);
659
+ }
660
+ this.cleanupInstrumentation();
661
+ this.cleanupLifecycle();
662
+ await this.flushBatch(true);
663
+ }
664
+ beginView(name) {
665
+ this.startView({ eventType: "navigation", name });
666
+ }
667
+ startView(input) {
668
+ this.viewContext = { ...createRootBrowserTraceContext(), viewId: createUuid() };
669
+ if (this.environment === null) {
670
+ return;
671
+ }
672
+ const timestamp = new Date().toISOString();
673
+ const sessionId = this.session.touch();
674
+ const viewUrl = new URL(input.url ?? this.environment.location.href, this.environment.location.href);
675
+ const pageUrl = this.sanitizeUrl(viewUrl);
676
+ const route = sanitizeBrowserRoute(input.url === undefined ? this.getRoute() : viewUrl.pathname);
677
+ const attributes = { ...this.defaultAttributes, ...this.userAttributes };
678
+ this.enqueueSpan(buildBrowserSpan({
679
+ context: this.viewContext,
680
+ name: `${input.eventType} ${route}`,
681
+ timestamp,
682
+ endTime: timestamp,
683
+ durationUs: 0,
684
+ spanKind: "internal",
685
+ spanCategory: "navigation",
686
+ statusCode: "ok",
687
+ sessionId,
688
+ viewId: this.viewContext.viewId,
689
+ pageUrl,
690
+ route,
691
+ userId: this.userId,
692
+ attributes
693
+ }));
694
+ this.enqueue({ eventType: input.eventType, name: input.name, context: { pageUrl, route } });
695
+ }
696
+ enqueue(input) {
697
+ if (!this.sampled || this.closed || this.environment === null) {
698
+ return;
699
+ }
700
+ const sessionId = this.session.touch();
701
+ const { context, ...eventInput } = input;
702
+ const pageUrl = context?.pageUrl ?? this.sanitizeUrl(new URL(this.environment.location.href));
703
+ const event = buildBrowserEvent({
704
+ ...eventInput,
705
+ defaultAttributes: { ...this.defaultAttributes, ...this.userAttributes },
706
+ pageUrl,
707
+ route: context?.route ?? this.getRoute(),
708
+ sessionId,
709
+ userId: this.userId,
710
+ viewId: this.viewContext.viewId,
711
+ traceId: this.viewContext.traceId,
712
+ spanId: this.viewContext.spanId
713
+ });
714
+ this.enqueueItem({ itemType: "event", event });
715
+ }
716
+ enqueueSpan(span) {
717
+ this.enqueueItem({ itemType: "span", span });
718
+ }
719
+ enqueueItem(item) {
720
+ if (!this.sampled || this.closed || this.environment === null) {
721
+ return;
722
+ }
723
+ this.queue = [...this.queue.slice(-(this.maxQueueSize - 1)), item];
724
+ if (this.queue.length >= this.maxBatchSize) {
725
+ this.flush();
726
+ }
727
+ }
728
+ flushBatch(useBeacon) {
729
+ if (this.flushing !== null) {
730
+ return this.flushing;
731
+ }
732
+ const batch = this.queue.slice(0, this.maxBatchSize);
733
+ if (batch.length === 0) {
734
+ return Promise.resolve();
735
+ }
736
+ this.queue = this.queue.slice(batch.length);
737
+ const transportBatch = {
738
+ events: batch.flatMap((item) => item.itemType === "event" ? [item.event] : []),
739
+ spans: batch.flatMap((item) => item.itemType === "span" ? [item.span] : [])
740
+ };
741
+ const operation = sendBrowserBatch({
742
+ collectorUrl: this.collectorUrl,
743
+ publicKey: this.publicKey,
744
+ environment: this.telemetryEnvironment,
745
+ ...transportBatch,
746
+ useBeacon,
747
+ fetchImpl: this.fetchImpl,
748
+ maxRetries: this.maxRetries,
749
+ onError: this.onError
750
+ }).then((result) => {
751
+ if (!result.delivered) {
752
+ this.queue = [...batch, ...this.queue].slice(0, this.maxQueueSize);
753
+ }
754
+ }).finally(() => {
755
+ this.flushing = null;
756
+ });
757
+ this.flushing = operation;
758
+ return operation;
759
+ }
760
+ installInstrumentation() {
761
+ if (this.environment === null) {
762
+ return () => {
763
+ return;
764
+ };
765
+ }
766
+ return installBrowserInstrumentation({
767
+ environment: this.environment,
768
+ capture: (input) => this.enqueue(input),
769
+ beginView: (name) => this.beginView(name),
770
+ traceFetch: this.traceFetch,
771
+ enableFetchTracing: this.enableFetchTracing,
772
+ enableNavigationTracking: this.enableNavigationTracking
773
+ });
774
+ }
775
+ traceFetch = async (input, init) => {
776
+ if (this.environment === null || !this.sampled || this.closed) {
777
+ return this.fetchImpl(input, init);
778
+ }
779
+ const request = new Request(input, init);
780
+ const requestUrl = new URL(request.url, this.environment.location.href);
781
+ if (!shouldTraceBrowserRequest({
782
+ collectorUrl: this.collectorUrl,
783
+ requestUrl,
784
+ tracePropagationOrigins: this.tracePropagationOrigins
785
+ })) {
786
+ return this.fetchImpl(input, init);
787
+ }
788
+ const context = createRootBrowserTraceContext();
789
+ const sessionId = this.session.touch();
790
+ const headers = new Headers(request.headers);
791
+ headers.set("traceparent", toBrowserTraceparent(context));
792
+ const tracedRequest = new Request(request, { headers });
793
+ const completionInput = {
794
+ context,
795
+ viewContext: this.viewContext,
796
+ request: tracedRequest,
797
+ startedAt: this.environment.performance.now(),
798
+ timestamp: new Date().toISOString(),
799
+ pageUrl: this.sanitizeUrl(new URL(this.environment.location.href)),
800
+ route: this.getRoute(),
801
+ userId: this.userId,
802
+ sessionId,
803
+ attributes: { ...this.defaultAttributes, ...this.userAttributes }
804
+ };
805
+ return this.fetchImpl(tracedRequest).then((response) => {
806
+ this.completeFetchSpan({ ...completionInput, response });
807
+ return response;
808
+ }, (error) => {
809
+ this.completeFetchSpan({ ...completionInput, error });
810
+ throw error;
811
+ });
812
+ };
813
+ completeFetchSpan(input) {
814
+ const requestUrl = new URL(input.request.url);
815
+ const statusCode = input.response?.status ?? 0;
816
+ const hasError = input.error !== undefined || statusCode >= 500;
817
+ this.enqueueSpan(buildBrowserSpan({
818
+ context: input.context,
819
+ name: `${input.request.method} ${requestUrl.pathname}`,
820
+ timestamp: input.timestamp,
821
+ endTime: new Date().toISOString(),
822
+ durationUs: Math.max(0, (this.environment?.performance.now() ?? input.startedAt) - input.startedAt) * 1000,
823
+ spanKind: "client",
824
+ spanCategory: "http",
825
+ statusCode: hasError ? "error" : "ok",
826
+ statusMessage: input.error === undefined ? "" : "FetchError",
827
+ sessionId: input.sessionId,
828
+ viewId: input.viewContext.viewId,
829
+ pageUrl: input.pageUrl,
830
+ route: input.route,
831
+ userId: input.userId,
832
+ httpMethod: input.request.method,
833
+ httpUrl: requestUrl.toString(),
834
+ httpStatusCode: statusCode,
835
+ attributes: input.attributes
836
+ }));
837
+ }
838
+ installLifecycle() {
839
+ if (this.environment === null) {
840
+ return () => {
841
+ return;
842
+ };
843
+ }
844
+ const flushOnHide = () => void this.flushBatch(true);
845
+ const onVisibilityChange = () => {
846
+ if (this.environment?.document.visibilityState === "hidden") {
847
+ flushOnHide();
848
+ }
849
+ };
850
+ this.environment.window.addEventListener("pagehide", flushOnHide);
851
+ this.environment.document.addEventListener("visibilitychange", onVisibilityChange);
852
+ return () => {
853
+ this.environment?.window.removeEventListener("pagehide", flushOnHide);
854
+ this.environment?.document.removeEventListener("visibilitychange", onVisibilityChange);
855
+ };
856
+ }
857
+ }
858
+ // src/index.ts
859
+ var createInkronikBrowser = (options) => new InkronikBrowserClient(options);
860
+
861
+ export { sanitizeBrowserAttributes, sanitizeBrowserUrl, InkronikBrowserClient, createInkronikBrowser };
862
+
863
+ //# debugId=ADE6A4AFBACF190364756E2164756E21
864
+ //# sourceMappingURL=index-z0hb108t.js.map