@plasius/analytics 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -31,11 +31,172 @@ __export(index_exports, {
31
31
  module.exports = __toCommonJS(index_exports);
32
32
 
33
33
  // src/core/client.ts
34
+ var import_schema = require("@plasius/schema");
34
35
  var DEFAULT_FLUSH_INTERVAL_MS = 5e3;
35
36
  var DEFAULT_BATCH_SIZE = 20;
36
37
  var DEFAULT_MAX_QUEUE_SIZE = 500;
37
38
  var DEFAULT_STORAGE_KEY_PREFIX = "plasius.analytics.local-space.queue";
39
+ var DEFAULT_ERROR_MESSAGE_LENGTH = 240;
40
+ var DEFAULT_ERROR_STACK_LENGTH = 1800;
41
+ var DEFAULT_ERROR_COMPONENT_STACK_LENGTH = 1800;
42
+ var DEFAULT_ERROR_CONTEXT_DEPTH = 4;
43
+ var DEFAULT_ERROR_CONTEXT_BREADTH = 20;
44
+ var DEFAULT_ERROR_TAG_COUNT = 10;
45
+ var DEFAULT_ERROR_THRESHOLD_COUNT = 5;
46
+ var DEFAULT_ERROR_THRESHOLD_WINDOW_MS = 5 * 60 * 1e3;
47
+ var DEFAULT_ERROR_REDACT_KEYS = [
48
+ "email",
49
+ "phone",
50
+ "name",
51
+ "address",
52
+ "token",
53
+ "password",
54
+ "secret",
55
+ "cookie",
56
+ "session",
57
+ "auth",
58
+ "ssn",
59
+ "dob",
60
+ "user"
61
+ ];
38
62
  var JSON_CONTENT_TYPE_HEADER = "application/json";
63
+ var LOCALHOST_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1"]);
64
+ var PlainLogValueSchema = (0, import_schema.createSchema)(
65
+ {
66
+ value: import_schema.field.generalText().PID({
67
+ classification: "none",
68
+ action: "none",
69
+ logHandling: "plain",
70
+ purpose: "analytics log-safe value"
71
+ })
72
+ },
73
+ "analytics-log-safe-value",
74
+ { version: "1.0.0", piiEnforcement: "none" }
75
+ );
76
+ var SensitiveLogValueSchema = (0, import_schema.createSchema)(
77
+ {
78
+ value: import_schema.field.generalText().PID({
79
+ classification: "high",
80
+ action: "none",
81
+ logHandling: "redact",
82
+ purpose: "analytics private value"
83
+ })
84
+ },
85
+ "analytics-private-log-value",
86
+ { version: "1.0.0", piiEnforcement: "none" }
87
+ );
88
+ function applySchemaLogHandling(value, sensitive) {
89
+ const schema = sensitive ? SensitiveLogValueSchema : PlainLogValueSchema;
90
+ const sanitized = schema.sanitizeForLog({ value }, (input) => `p(${String(input ?? "")})`);
91
+ return typeof sanitized.value === "string" ? sanitized.value : "";
92
+ }
93
+ var REDACTED_VALUE = applySchemaLogHandling("sensitive", true) || "[REDACTED]";
94
+ var CrashIdentitySchema = (0, import_schema.createSchema)(
95
+ {
96
+ source: import_schema.field.generalText().PID({
97
+ classification: "none",
98
+ action: "none",
99
+ logHandling: "plain",
100
+ purpose: "analytics source identifier"
101
+ }).optional(),
102
+ channel: import_schema.field.generalText().PID({
103
+ classification: "none",
104
+ action: "none",
105
+ logHandling: "plain",
106
+ purpose: "analytics channel identifier"
107
+ }).optional(),
108
+ runtime: import_schema.field.generalText().PID({
109
+ classification: "none",
110
+ action: "none",
111
+ logHandling: "plain",
112
+ purpose: "analytics runtime identifier"
113
+ }).optional(),
114
+ sessionId: import_schema.field.generalText().PID({
115
+ classification: "high",
116
+ action: "hash",
117
+ logHandling: "redact",
118
+ purpose: "client session identifier"
119
+ }).optional(),
120
+ userAgent: import_schema.field.generalText().PID({
121
+ classification: "low",
122
+ action: "hash",
123
+ logHandling: "pseudonym",
124
+ purpose: "browser user agent"
125
+ }).optional(),
126
+ platform: import_schema.field.generalText().PID({
127
+ classification: "low",
128
+ action: "hash",
129
+ logHandling: "pseudonym",
130
+ purpose: "client platform"
131
+ }).optional(),
132
+ language: import_schema.field.generalText().PID({
133
+ classification: "low",
134
+ action: "hash",
135
+ logHandling: "pseudonym",
136
+ purpose: "client language"
137
+ }).optional(),
138
+ timezone: import_schema.field.generalText().PID({
139
+ classification: "low",
140
+ action: "hash",
141
+ logHandling: "pseudonym",
142
+ purpose: "client timezone"
143
+ }).optional(),
144
+ origin: import_schema.field.generalText().PID({
145
+ classification: "low",
146
+ action: "hash",
147
+ logHandling: "pseudonym",
148
+ purpose: "client origin"
149
+ }).optional(),
150
+ pathname: import_schema.field.generalText().PID({
151
+ classification: "low",
152
+ action: "hash",
153
+ logHandling: "pseudonym",
154
+ purpose: "client route path"
155
+ }).optional(),
156
+ screenWidth: import_schema.field.number().PID({
157
+ classification: "none",
158
+ action: "none",
159
+ logHandling: "plain",
160
+ purpose: "viewport width"
161
+ }).optional(),
162
+ screenHeight: import_schema.field.number().PID({
163
+ classification: "none",
164
+ action: "none",
165
+ logHandling: "plain",
166
+ purpose: "viewport height"
167
+ }).optional(),
168
+ colorDepth: import_schema.field.number().PID({
169
+ classification: "none",
170
+ action: "none",
171
+ logHandling: "plain",
172
+ purpose: "screen color depth"
173
+ }).optional(),
174
+ hardwareConcurrency: import_schema.field.number().PID({
175
+ classification: "none",
176
+ action: "none",
177
+ logHandling: "plain",
178
+ purpose: "cpu concurrency"
179
+ }).optional(),
180
+ identifiers: import_schema.field.array(
181
+ import_schema.field.object({
182
+ key: import_schema.field.generalText().PID({
183
+ classification: "none",
184
+ action: "none",
185
+ logHandling: "plain",
186
+ purpose: "identifier field key"
187
+ }),
188
+ value: import_schema.field.generalText().PID({
189
+ classification: "high",
190
+ action: "hash",
191
+ logHandling: "redact",
192
+ purpose: "identifier value"
193
+ })
194
+ })
195
+ ).optional()
196
+ },
197
+ "analytics-crash-identity",
198
+ { version: "1.0.0", piiEnforcement: "none" }
199
+ );
39
200
  function createId(prefix) {
40
201
  return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
41
202
  }
@@ -108,6 +269,9 @@ function toPositiveInteger(value, fallback) {
108
269
  const rounded = Math.floor(value);
109
270
  return rounded > 0 ? rounded : fallback;
110
271
  }
272
+ function toNumberWithMinimum(value, fallback, minimum) {
273
+ return Math.max(toPositiveInteger(value, fallback), minimum);
274
+ }
111
275
  function resolveSessionId(configSessionId, previousSessionId) {
112
276
  const explicitSessionId = configSessionId?.trim();
113
277
  if (explicitSessionId) {
@@ -118,6 +282,62 @@ function resolveSessionId(configSessionId, previousSessionId) {
118
282
  }
119
283
  return createId("session");
120
284
  }
285
+ function normalizeRedactKeys(keys, previousKeys) {
286
+ const values = keys ?? previousKeys ?? DEFAULT_ERROR_REDACT_KEYS;
287
+ const normalized = values.map((value) => value.trim().toLowerCase()).filter((value) => value.length > 0);
288
+ if (normalized.length === 0) {
289
+ return [...DEFAULT_ERROR_REDACT_KEYS];
290
+ }
291
+ return Array.from(new Set(normalized));
292
+ }
293
+ function resolveErrorReportingConfig(config, previous) {
294
+ return {
295
+ enabled: config?.enabled ?? previous?.enabled ?? true,
296
+ secureEndpointOnly: config?.secureEndpointOnly ?? previous?.secureEndpointOnly ?? true,
297
+ maxMessageLength: toNumberWithMinimum(
298
+ config?.maxMessageLength ?? previous?.maxMessageLength,
299
+ DEFAULT_ERROR_MESSAGE_LENGTH,
300
+ 16
301
+ ),
302
+ maxStackLength: toNumberWithMinimum(
303
+ config?.maxStackLength ?? previous?.maxStackLength,
304
+ DEFAULT_ERROR_STACK_LENGTH,
305
+ 32
306
+ ),
307
+ maxComponentStackLength: toNumberWithMinimum(
308
+ config?.maxComponentStackLength ?? previous?.maxComponentStackLength,
309
+ DEFAULT_ERROR_COMPONENT_STACK_LENGTH,
310
+ 32
311
+ ),
312
+ maxContextDepth: toNumberWithMinimum(
313
+ config?.maxContextDepth ?? previous?.maxContextDepth,
314
+ DEFAULT_ERROR_CONTEXT_DEPTH,
315
+ 1
316
+ ),
317
+ maxContextBreadth: toNumberWithMinimum(
318
+ config?.maxContextBreadth ?? previous?.maxContextBreadth,
319
+ DEFAULT_ERROR_CONTEXT_BREADTH,
320
+ 1
321
+ ),
322
+ maxTagCount: toNumberWithMinimum(
323
+ config?.maxTagCount ?? previous?.maxTagCount,
324
+ DEFAULT_ERROR_TAG_COUNT,
325
+ 1
326
+ ),
327
+ thresholdCount: toNumberWithMinimum(
328
+ config?.thresholdCount ?? previous?.thresholdCount,
329
+ DEFAULT_ERROR_THRESHOLD_COUNT,
330
+ 1
331
+ ),
332
+ thresholdWindowMs: toNumberWithMinimum(
333
+ config?.thresholdWindowMs ?? previous?.thresholdWindowMs,
334
+ DEFAULT_ERROR_THRESHOLD_WINDOW_MS,
335
+ 1e3
336
+ ),
337
+ redactKeys: normalizeRedactKeys(config?.redactKeys, previous?.redactKeys),
338
+ onThresholdReached: config?.onThresholdReached ?? previous?.onThresholdReached
339
+ };
340
+ }
121
341
  function resolveConfig(config, previous) {
122
342
  const source = (config.source ?? previous?.source ?? "").trim();
123
343
  if (!source) {
@@ -148,12 +368,19 @@ function resolveConfig(config, previous) {
148
368
  config.flushIntervalMs ?? previous?.flushIntervalMs,
149
369
  DEFAULT_FLUSH_INTERVAL_MS
150
370
  ),
151
- batchSize: toPositiveInteger(config.batchSize ?? previous?.batchSize, DEFAULT_BATCH_SIZE),
371
+ batchSize: toPositiveInteger(
372
+ config.batchSize ?? previous?.batchSize,
373
+ DEFAULT_BATCH_SIZE
374
+ ),
152
375
  maxQueueSize: toPositiveInteger(
153
376
  config.maxQueueSize ?? previous?.maxQueueSize,
154
377
  DEFAULT_MAX_QUEUE_SIZE
155
378
  ),
156
379
  storageKey: resolveStorageKey(config.storageKey, source, channel, previous),
380
+ errorReporting: resolveErrorReportingConfig(
381
+ config.errorReporting,
382
+ previous?.errorReporting
383
+ ),
157
384
  transport: config.transport ?? previous?.transport ?? defaultTransport,
158
385
  onError: config.onError ?? previous?.onError
159
386
  };
@@ -165,15 +392,339 @@ function isStoredRecordCandidate(value) {
165
392
  const candidate = value;
166
393
  return typeof candidate.id === "string" && typeof candidate.component === "string" && typeof candidate.action === "string" && typeof candidate.source === "string" && typeof candidate.sessionId === "string" && typeof candidate.timestamp === "number";
167
394
  }
395
+ function isErrorDetailsCandidate(value) {
396
+ if (!value || typeof value !== "object") {
397
+ return false;
398
+ }
399
+ const candidate = value;
400
+ return typeof candidate.boundary === "string" && typeof candidate.name === "string" && typeof candidate.message === "string" && typeof candidate.fingerprint === "string";
401
+ }
402
+ function redactSensitiveText(value) {
403
+ return value.replace(
404
+ /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,
405
+ REDACTED_VALUE
406
+ ).replace(/\bBearer\s+[A-Za-z0-9._-]+\b/gi, `Bearer ${REDACTED_VALUE}`).replace(/\b[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g, REDACTED_VALUE).replace(/\b\d{9,}\b/g, REDACTED_VALUE).replace(
407
+ /([?&](?:token|email|phone|name|user|auth|session|password)=)[^&#\s]*/gi,
408
+ `$1${REDACTED_VALUE}`
409
+ );
410
+ }
411
+ function sanitizeSingleLine(value, maxLength) {
412
+ const raw = typeof value === "string" ? value : String(value ?? "");
413
+ const flattened = raw.replace(/[\u0000-\u001F\u007F]/g, " ").replace(/\s+/g, " ").trim();
414
+ if (!flattened) {
415
+ return "";
416
+ }
417
+ const redacted = redactSensitiveText(flattened).slice(0, maxLength);
418
+ return applySchemaLogHandling(redacted, false).slice(0, maxLength);
419
+ }
420
+ function sanitizeMultiline(value, maxLength) {
421
+ const raw = typeof value === "string" ? value : String(value ?? "");
422
+ const normalized = raw.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
423
+ const sanitized = redactSensitiveText(normalized).split("\n").map((line) => line.trim()).filter((line) => line.length > 0).join("\n");
424
+ if (!sanitized) {
425
+ return "";
426
+ }
427
+ const schemaHandled = applySchemaLogHandling(sanitized, false);
428
+ return schemaHandled.slice(0, maxLength);
429
+ }
430
+ function isPlainObject(value) {
431
+ return value !== null && typeof value === "object" && !Array.isArray(value);
432
+ }
433
+ function shouldRedactContextKey(key, resolvedErrorReporting) {
434
+ const loweredKey = key.trim().toLowerCase();
435
+ if (!loweredKey) {
436
+ return false;
437
+ }
438
+ return resolvedErrorReporting.redactKeys.some(
439
+ (candidate) => loweredKey === candidate || loweredKey.includes(candidate)
440
+ );
441
+ }
442
+ function toIdentifierValue(value, maxLength) {
443
+ if (value === null || value === void 0) {
444
+ return "null";
445
+ }
446
+ if (typeof value === "string") {
447
+ return sanitizeSingleLine(value, maxLength) || "empty";
448
+ }
449
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
450
+ return sanitizeSingleLine(String(value), maxLength) || "empty";
451
+ }
452
+ if (value instanceof Date) {
453
+ return value.toISOString();
454
+ }
455
+ return sanitizeSingleLine(safeSerialize(value), maxLength) || "empty";
456
+ }
457
+ function pushIdentifier(identifiers, keyPath, value, maxLength) {
458
+ if (!keyPath.trim()) {
459
+ return;
460
+ }
461
+ identifiers.push({
462
+ key: sanitizeSingleLine(keyPath, 160),
463
+ value: toIdentifierValue(value, maxLength)
464
+ });
465
+ }
466
+ function sanitizeContextValue(value, resolvedErrorReporting, depth, seen, identifiers, keyPath) {
467
+ if (value === null || value === void 0) {
468
+ return null;
469
+ }
470
+ if (typeof value === "string") {
471
+ return sanitizeSingleLine(value, resolvedErrorReporting.maxMessageLength);
472
+ }
473
+ if (typeof value === "number") {
474
+ return Number.isFinite(value) ? value : null;
475
+ }
476
+ if (typeof value === "boolean") {
477
+ return value;
478
+ }
479
+ if (typeof value === "bigint") {
480
+ return sanitizeSingleLine(value.toString(), resolvedErrorReporting.maxMessageLength);
481
+ }
482
+ if (value instanceof Date) {
483
+ return value.toISOString();
484
+ }
485
+ if (Array.isArray(value)) {
486
+ if (seen.has(value)) {
487
+ return "[circular]";
488
+ }
489
+ seen.add(value);
490
+ if (depth >= resolvedErrorReporting.maxContextDepth) {
491
+ return "[truncated]";
492
+ }
493
+ return value.slice(0, resolvedErrorReporting.maxContextBreadth).map(
494
+ (item) => sanitizeContextValue(
495
+ item,
496
+ resolvedErrorReporting,
497
+ depth + 1,
498
+ seen,
499
+ identifiers,
500
+ `${keyPath}[]`
501
+ )
502
+ );
503
+ }
504
+ if (isPlainObject(value)) {
505
+ if (seen.has(value)) {
506
+ return "[circular]";
507
+ }
508
+ seen.add(value);
509
+ if (depth >= resolvedErrorReporting.maxContextDepth) {
510
+ return "[truncated]";
511
+ }
512
+ const sanitized = {};
513
+ const entries = Object.entries(value).slice(0, resolvedErrorReporting.maxContextBreadth);
514
+ for (const [key, nestedValue] of entries) {
515
+ const childPath = keyPath ? `${keyPath}.${key}` : key;
516
+ if (shouldRedactContextKey(key, resolvedErrorReporting)) {
517
+ sanitized[key] = applySchemaLogHandling(String(nestedValue ?? ""), true) || REDACTED_VALUE;
518
+ pushIdentifier(
519
+ identifiers,
520
+ childPath,
521
+ nestedValue,
522
+ resolvedErrorReporting.maxMessageLength
523
+ );
524
+ continue;
525
+ }
526
+ sanitized[key] = sanitizeContextValue(
527
+ nestedValue,
528
+ resolvedErrorReporting,
529
+ depth + 1,
530
+ seen,
531
+ identifiers,
532
+ childPath
533
+ );
534
+ }
535
+ return sanitized;
536
+ }
537
+ return sanitizeSingleLine(value, resolvedErrorReporting.maxMessageLength);
538
+ }
539
+ function sanitizeErrorContext(context, resolvedErrorReporting) {
540
+ if (!context || !isPlainObject(context)) {
541
+ return { context: {}, identifiers: [] };
542
+ }
543
+ const sanitized = {};
544
+ const identifiers = [];
545
+ const seen = /* @__PURE__ */ new WeakSet();
546
+ const entries = Object.entries(context).slice(0, resolvedErrorReporting.maxContextBreadth);
547
+ for (const [key, value] of entries) {
548
+ if (shouldRedactContextKey(key, resolvedErrorReporting)) {
549
+ sanitized[key] = applySchemaLogHandling(String(value ?? ""), true) || REDACTED_VALUE;
550
+ pushIdentifier(identifiers, key, value, resolvedErrorReporting.maxMessageLength);
551
+ continue;
552
+ }
553
+ sanitized[key] = sanitizeContextValue(
554
+ value,
555
+ resolvedErrorReporting,
556
+ 1,
557
+ seen,
558
+ identifiers,
559
+ key
560
+ );
561
+ }
562
+ return {
563
+ context: sanitized,
564
+ identifiers
565
+ };
566
+ }
567
+ function hashString(input) {
568
+ let hash = 5381;
569
+ for (let index = 0; index < input.length; index += 1) {
570
+ hash = hash * 33 ^ input.charCodeAt(index);
571
+ }
572
+ return hash >>> 0;
573
+ }
574
+ function hashForStorage(value) {
575
+ const normalized = typeof value === "string" ? value : safeSerialize(value);
576
+ return `hash_${hashString(normalized).toString(16)}`;
577
+ }
578
+ function encryptForStorage(value) {
579
+ return `enc_${hashForStorage(value)}`;
580
+ }
581
+ function buildCrashIdentityPayload(config, identifiers) {
582
+ const payload = {
583
+ source: config.source,
584
+ channel: config.channel,
585
+ runtime: config.runtime,
586
+ sessionId: config.sessionId
587
+ };
588
+ if (isBrowserEnvironment()) {
589
+ if (typeof navigator !== "undefined") {
590
+ payload.userAgent = navigator.userAgent;
591
+ payload.platform = navigator.platform;
592
+ payload.language = navigator.language;
593
+ payload.hardwareConcurrency = navigator.hardwareConcurrency;
594
+ }
595
+ if (typeof Intl !== "undefined" && typeof Intl.DateTimeFormat === "function") {
596
+ payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
597
+ }
598
+ if (typeof window !== "undefined") {
599
+ payload.origin = window.location.origin;
600
+ payload.pathname = window.location.pathname;
601
+ }
602
+ if (typeof screen !== "undefined") {
603
+ payload.screenWidth = screen.width;
604
+ payload.screenHeight = screen.height;
605
+ payload.colorDepth = screen.colorDepth;
606
+ }
607
+ }
608
+ if (identifiers.length > 0) {
609
+ payload.identifiers = identifiers.slice(0, config.errorReporting.maxContextBreadth);
610
+ }
611
+ return payload;
612
+ }
613
+ function prepareCrashIdentityForStorage(payload) {
614
+ return CrashIdentitySchema.prepareForStorage(
615
+ payload,
616
+ encryptForStorage,
617
+ hashForStorage
618
+ );
619
+ }
620
+ function normalizeTags(tags, maxTagCount, maxTagLength) {
621
+ if (!Array.isArray(tags) || tags.length === 0) {
622
+ return void 0;
623
+ }
624
+ const normalized = tags.map((tag) => sanitizeSingleLine(tag, maxTagLength)).filter((tag) => tag.length > 0);
625
+ if (normalized.length === 0) {
626
+ return void 0;
627
+ }
628
+ return Array.from(new Set(normalized)).slice(0, maxTagCount);
629
+ }
630
+ function safeSerialize(value) {
631
+ try {
632
+ return JSON.stringify(value);
633
+ } catch {
634
+ return "[unserializable]";
635
+ }
636
+ }
637
+ function extractErrorDetails(error) {
638
+ if (error instanceof Error) {
639
+ return {
640
+ name: error.name || "Error",
641
+ message: error.message || "Unknown error",
642
+ stack: error.stack
643
+ };
644
+ }
645
+ if (typeof error === "string") {
646
+ return {
647
+ name: "Error",
648
+ message: error
649
+ };
650
+ }
651
+ if (isPlainObject(error)) {
652
+ const name = typeof error.name === "string" && error.name.trim() ? error.name : "Error";
653
+ const message = typeof error.message === "string" && error.message.trim() ? error.message : sanitizeSingleLine(safeSerialize(error), DEFAULT_ERROR_MESSAGE_LENGTH);
654
+ return {
655
+ name,
656
+ message,
657
+ stack: typeof error.stack === "string" ? error.stack : void 0
658
+ };
659
+ }
660
+ return {
661
+ name: "UnknownError",
662
+ message: sanitizeSingleLine(error, DEFAULT_ERROR_MESSAGE_LENGTH) || "Unknown error"
663
+ };
664
+ }
665
+ function normalizeErrorReport(report, resolvedErrorReporting, existingFingerprint) {
666
+ const extractedError = extractErrorDetails(report.error);
667
+ const boundary = sanitizeSingleLine(report.boundary, 100) || "UnknownErrorBoundary";
668
+ const name = sanitizeSingleLine(extractedError.name, 80) || "Error";
669
+ const message = sanitizeSingleLine(extractedError.message, resolvedErrorReporting.maxMessageLength) || "Unknown error";
670
+ const stack = extractedError.stack ? sanitizeMultiline(extractedError.stack, resolvedErrorReporting.maxStackLength) : void 0;
671
+ const componentStack = report.componentStack ? sanitizeMultiline(
672
+ report.componentStack,
673
+ resolvedErrorReporting.maxComponentStackLength
674
+ ) : void 0;
675
+ const severity = report.severity === "fatal" ? "fatal" : "error";
676
+ const handled = report.handled ?? true;
677
+ const tags = normalizeTags(
678
+ report.tags,
679
+ resolvedErrorReporting.maxTagCount,
680
+ resolvedErrorReporting.maxMessageLength
681
+ );
682
+ const fingerprintBase = `${boundary}|${name}|${message}|${stack?.split("\n")[0] ?? ""}|${severity}`;
683
+ const fallbackFingerprint = `err_${hashString(fingerprintBase).toString(16)}`;
684
+ const fingerprint = sanitizeSingleLine(existingFingerprint, 120) || fallbackFingerprint;
685
+ return {
686
+ boundary,
687
+ name,
688
+ message,
689
+ fingerprint,
690
+ handled,
691
+ severity,
692
+ stack,
693
+ componentStack,
694
+ tags
695
+ };
696
+ }
697
+ function normalizeStoredErrorDetails(value, resolvedErrorReporting) {
698
+ return normalizeErrorReport(
699
+ {
700
+ boundary: value.boundary,
701
+ error: {
702
+ name: value.name,
703
+ message: value.message,
704
+ stack: value.stack
705
+ },
706
+ componentStack: value.componentStack,
707
+ handled: value.handled,
708
+ severity: value.severity,
709
+ tags: value.tags
710
+ },
711
+ resolvedErrorReporting,
712
+ value.fingerprint
713
+ );
714
+ }
168
715
  function normalizeStoredRecord(value, fallbackConfig) {
169
716
  const context = value.context && typeof value.context === "object" && !Array.isArray(value.context) ? value.context : {};
170
717
  const channel = value.channel === "frontend" || value.channel === "backend" ? value.channel : fallbackConfig.channel;
171
718
  const runtime = value.runtime === "browser" || value.runtime === "server" ? value.runtime : fallbackConfig.runtime;
719
+ const kind = value.kind === "error" ? "error" : "interaction";
720
+ const errorDetails = kind === "error" && isErrorDetailsCandidate(value.error) ? normalizeStoredErrorDetails(value.error, fallbackConfig.errorReporting) : void 0;
172
721
  return {
173
722
  ...value,
723
+ kind,
174
724
  channel,
175
725
  runtime,
176
- context
726
+ context,
727
+ error: errorDetails
177
728
  };
178
729
  }
179
730
  function readQueue(storageKey, fallbackConfig) {
@@ -231,6 +782,25 @@ function createMergedContext(config, eventChannel, eventContext) {
231
782
  }
232
783
  return mergedContext;
233
784
  }
785
+ function isSecureEndpoint(endpoint) {
786
+ const trimmedEndpoint = endpoint.trim();
787
+ if (!trimmedEndpoint) {
788
+ return false;
789
+ }
790
+ if (trimmedEndpoint.startsWith("/")) {
791
+ return true;
792
+ }
793
+ try {
794
+ const baseUrl = isBrowserEnvironment() ? window.location.origin : "https://localhost";
795
+ const parsedUrl = new URL(trimmedEndpoint, baseUrl);
796
+ if (parsedUrl.protocol === "https:") {
797
+ return true;
798
+ }
799
+ return parsedUrl.protocol === "http:" && LOCALHOST_HOSTS.has(parsedUrl.hostname);
800
+ } catch {
801
+ return false;
802
+ }
803
+ }
234
804
  function createLocalSpaceAnalyticsClient(config) {
235
805
  let resolvedConfig = resolveConfig(config);
236
806
  let queue = readQueue(resolvedConfig.storageKey, resolvedConfig).slice(
@@ -240,6 +810,7 @@ function createLocalSpaceAnalyticsClient(config) {
240
810
  let isFlushing = false;
241
811
  let flushQueuedAfterCurrent = false;
242
812
  let isDestroyed = false;
813
+ const issueAggregates = /* @__PURE__ */ new Map();
243
814
  const persistQueue = () => writeQueue(resolvedConfig.storageKey, queue);
244
815
  const trimQueue = () => {
245
816
  if (queue.length <= resolvedConfig.maxQueueSize) {
@@ -247,6 +818,117 @@ function createLocalSpaceAnalyticsClient(config) {
247
818
  }
248
819
  queue = queue.slice(queue.length - resolvedConfig.maxQueueSize);
249
820
  };
821
+ const pruneIssueState = (state, now) => {
822
+ const windowStart = now - resolvedConfig.errorReporting.thresholdWindowMs;
823
+ state.timestamps = state.timestamps.filter((timestamp) => timestamp >= windowStart);
824
+ };
825
+ const buildIssueReport = (fingerprint, state) => {
826
+ if (state.timestamps.length === 0) {
827
+ return null;
828
+ }
829
+ const sortedTimestamps = [...state.timestamps].sort((a, b) => a - b);
830
+ return {
831
+ fingerprint,
832
+ boundary: state.sample.boundary,
833
+ count: sortedTimestamps.length,
834
+ firstSeen: sortedTimestamps[0] ?? Date.now(),
835
+ lastSeen: sortedTimestamps[sortedTimestamps.length - 1] ?? Date.now(),
836
+ severity: state.sample.severity,
837
+ sample: state.sample
838
+ };
839
+ };
840
+ const recordIssue = (details, timestamp, triggerThreshold) => {
841
+ const existingState = issueAggregates.get(details.fingerprint);
842
+ if (!existingState) {
843
+ issueAggregates.set(details.fingerprint, {
844
+ timestamps: [timestamp],
845
+ sample: details
846
+ });
847
+ } else {
848
+ existingState.timestamps.push(timestamp);
849
+ existingState.sample = details;
850
+ }
851
+ const state = issueAggregates.get(details.fingerprint);
852
+ if (!state) {
853
+ return;
854
+ }
855
+ pruneIssueState(state, timestamp);
856
+ if (state.timestamps.length === 0) {
857
+ issueAggregates.delete(details.fingerprint);
858
+ return;
859
+ }
860
+ if (!triggerThreshold) {
861
+ return;
862
+ }
863
+ const thresholdCallback = resolvedConfig.errorReporting.onThresholdReached;
864
+ if (!thresholdCallback) {
865
+ return;
866
+ }
867
+ if (state.timestamps.length < resolvedConfig.errorReporting.thresholdCount) {
868
+ return;
869
+ }
870
+ const lastTriggeredAt = state.lastTriggeredAt;
871
+ if (lastTriggeredAt !== void 0 && timestamp - lastTriggeredAt < resolvedConfig.errorReporting.thresholdWindowMs) {
872
+ return;
873
+ }
874
+ state.lastTriggeredAt = timestamp;
875
+ const report = buildIssueReport(details.fingerprint, state);
876
+ if (!report) {
877
+ return;
878
+ }
879
+ try {
880
+ thresholdCallback({
881
+ source: resolvedConfig.source,
882
+ channel: resolvedConfig.channel,
883
+ runtime: resolvedConfig.runtime,
884
+ thresholdCount: resolvedConfig.errorReporting.thresholdCount,
885
+ windowMs: resolvedConfig.errorReporting.thresholdWindowMs,
886
+ report
887
+ });
888
+ } catch (error) {
889
+ resolvedConfig.onError?.(error);
890
+ }
891
+ };
892
+ const getIssueReports = () => {
893
+ const now = Date.now();
894
+ for (const [fingerprint, state] of issueAggregates.entries()) {
895
+ pruneIssueState(state, now);
896
+ if (state.timestamps.length === 0) {
897
+ issueAggregates.delete(fingerprint);
898
+ }
899
+ }
900
+ return Array.from(issueAggregates.entries()).map(([fingerprint, state]) => buildIssueReport(fingerprint, state)).filter((report) => report !== null).sort((left, right) => {
901
+ if (right.count !== left.count) {
902
+ return right.count - left.count;
903
+ }
904
+ return right.lastSeen - left.lastSeen;
905
+ });
906
+ };
907
+ const enqueueRecord = (record) => {
908
+ queue.push(record);
909
+ trimQueue();
910
+ persistQueue();
911
+ if (record.kind === "error" && record.error) {
912
+ recordIssue(record.error, record.timestamp, true);
913
+ }
914
+ if (queue.length >= resolvedConfig.batchSize) {
915
+ void flush();
916
+ }
917
+ };
918
+ const canSendBatchToEndpoint = (events) => {
919
+ if (!resolvedConfig.endpoint || !resolvedConfig.errorReporting.secureEndpointOnly || isSecureEndpoint(resolvedConfig.endpoint)) {
920
+ return true;
921
+ }
922
+ if (!events.some((event) => event.kind === "error")) {
923
+ return true;
924
+ }
925
+ resolvedConfig.onError?.(
926
+ new Error(
927
+ `Error reporting requires an https or localhost endpoint. Refused endpoint: ${resolvedConfig.endpoint}`
928
+ )
929
+ );
930
+ return false;
931
+ };
250
932
  const flushWithBeacon = () => {
251
933
  if (!resolvedConfig.endpoint || queue.length === 0) {
252
934
  return false;
@@ -255,6 +937,9 @@ function createLocalSpaceAnalyticsClient(config) {
255
937
  return false;
256
938
  }
257
939
  const events = queue.slice(0, resolvedConfig.batchSize);
940
+ if (!canSendBatchToEndpoint(events)) {
941
+ return false;
942
+ }
258
943
  try {
259
944
  const body = createPayload(resolvedConfig, events);
260
945
  const blob = new Blob([body], { type: JSON_CONTENT_TYPE_HEADER });
@@ -280,6 +965,9 @@ function createLocalSpaceAnalyticsClient(config) {
280
965
  return;
281
966
  }
282
967
  const events = queue.slice(0, resolvedConfig.batchSize);
968
+ if (!canSendBatchToEndpoint(events)) {
969
+ return;
970
+ }
283
971
  const body = createPayload(resolvedConfig, events);
284
972
  isFlushing = true;
285
973
  try {
@@ -335,6 +1023,11 @@ function createLocalSpaceAnalyticsClient(config) {
335
1023
  document.addEventListener("visibilitychange", handleVisibilityChange);
336
1024
  window.addEventListener("pagehide", handlePageHide);
337
1025
  }
1026
+ for (const record of queue) {
1027
+ if (record.kind === "error" && record.error) {
1028
+ recordIssue(record.error, record.timestamp, false);
1029
+ }
1030
+ }
338
1031
  startFlushTimer();
339
1032
  const trackWithChannel = (event, channel) => {
340
1033
  const trackableEvent = {
@@ -349,10 +1042,13 @@ function createLocalSpaceAnalyticsClient(config) {
349
1042
  }
350
1043
  const eventChannel = event.channel ?? resolvedConfig.channel;
351
1044
  const requestId = typeof event.requestId === "string" && event.requestId.trim() ? event.requestId.trim() : void 0;
1045
+ const kind = event.kind === "error" ? "error" : "interaction";
1046
+ const normalizedError = kind === "error" && isErrorDetailsCandidate(event.error) ? normalizeStoredErrorDetails(event.error, resolvedConfig.errorReporting) : void 0;
352
1047
  const record = {
353
1048
  id: createId("event"),
354
1049
  component: event.component,
355
1050
  action: event.action,
1051
+ kind,
356
1052
  channel: eventChannel,
357
1053
  runtime: resolvedConfig.runtime,
358
1054
  label: event.label,
@@ -362,14 +1058,58 @@ function createLocalSpaceAnalyticsClient(config) {
362
1058
  source: resolvedConfig.source,
363
1059
  sessionId: resolvedConfig.sessionId,
364
1060
  timestamp: event.timestamp ?? Date.now(),
365
- context: createMergedContext(resolvedConfig, eventChannel, event.context)
1061
+ context: createMergedContext(resolvedConfig, eventChannel, event.context),
1062
+ error: normalizedError
366
1063
  };
367
- queue.push(record);
368
- trimQueue();
369
- persistQueue();
370
- if (queue.length >= resolvedConfig.batchSize) {
371
- void flush();
1064
+ enqueueRecord(record);
1065
+ };
1066
+ const reportError = (report) => {
1067
+ if (isDestroyed || !resolvedConfig.enabled) {
1068
+ return;
1069
+ }
1070
+ if (!resolvedConfig.errorReporting.enabled) {
1071
+ return;
372
1072
  }
1073
+ if (resolvedConfig.errorReporting.secureEndpointOnly && resolvedConfig.endpoint && !isSecureEndpoint(resolvedConfig.endpoint)) {
1074
+ resolvedConfig.onError?.(
1075
+ new Error(
1076
+ `Error reporting requires an https or localhost endpoint. Refused endpoint: ${resolvedConfig.endpoint}`
1077
+ )
1078
+ );
1079
+ return;
1080
+ }
1081
+ const eventChannel = report.channel ?? resolvedConfig.channel;
1082
+ const timestamp = report.timestamp ?? Date.now();
1083
+ const normalizedError = normalizeErrorReport(report, resolvedConfig.errorReporting);
1084
+ const {
1085
+ context: errorContext,
1086
+ identifiers
1087
+ } = sanitizeErrorContext(report.context, resolvedConfig.errorReporting);
1088
+ errorContext.errorFingerprint = normalizedError.fingerprint;
1089
+ errorContext.errorBoundary = normalizedError.boundary;
1090
+ errorContext.errorSeverity = normalizedError.severity;
1091
+ errorContext.errorHandled = normalizedError.handled;
1092
+ errorContext.clientIdentity = prepareCrashIdentityForStorage(
1093
+ buildCrashIdentityPayload(resolvedConfig, identifiers)
1094
+ );
1095
+ if (normalizedError.tags && normalizedError.tags.length > 0) {
1096
+ errorContext.errorTags = normalizedError.tags;
1097
+ }
1098
+ const record = {
1099
+ id: createId("event"),
1100
+ component: normalizedError.boundary,
1101
+ action: normalizedError.handled ? "error_boundary_caught" : "unhandled_error",
1102
+ kind: "error",
1103
+ channel: eventChannel,
1104
+ runtime: resolvedConfig.runtime,
1105
+ label: normalizedError.fingerprint,
1106
+ source: resolvedConfig.source,
1107
+ sessionId: resolvedConfig.sessionId,
1108
+ timestamp,
1109
+ context: createMergedContext(resolvedConfig, eventChannel, errorContext),
1110
+ error: normalizedError
1111
+ };
1112
+ enqueueRecord(record);
373
1113
  };
374
1114
  return {
375
1115
  get source() {
@@ -385,6 +1125,8 @@ function createLocalSpaceAnalyticsClient(config) {
385
1125
  trackBackend(event) {
386
1126
  trackWithChannel(event, "backend");
387
1127
  },
1128
+ reportError,
1129
+ getIssueReports,
388
1130
  flush,
389
1131
  updateConfig(nextConfig) {
390
1132
  if (isDestroyed) {
@@ -458,6 +1200,7 @@ function createNoopLocalSpaceAnalyticsClient(source = "noop", channel = "fronten
458
1200
  batchSize: DEFAULT_BATCH_SIZE,
459
1201
  maxQueueSize: DEFAULT_MAX_QUEUE_SIZE,
460
1202
  storageKey: buildDefaultStorageKey(source, channel),
1203
+ errorReporting: resolveErrorReportingConfig(void 0),
461
1204
  transport: async () => void 0,
462
1205
  onError: void 0
463
1206
  };
@@ -467,6 +1210,8 @@ function createNoopLocalSpaceAnalyticsClient(source = "noop", channel = "fronten
467
1210
  track: () => void 0,
468
1211
  trackFrontend: () => void 0,
469
1212
  trackBackend: () => void 0,
1213
+ reportError: () => void 0,
1214
+ getIssueReports: () => [],
470
1215
  flush: async () => void 0,
471
1216
  updateConfig: () => void 0,
472
1217
  getConfig: () => noopConfig,