@mushi-mushi/web 1.26.0 → 1.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { mushiPalette, resolveWidgetAccent, MUSHI_REPORTER_STATUS, MUSHI_GEOMETRY, MUSHI_Z, MUSHI_MOTION, MUSHI_TYPE, MUSHI_BANNER_BRAND_BORDER, MUSHI_BANNER_NEON, MUSHI_INVERSE, MUSHI_ON_ACCENT, MUSHI_ACCENT_SHADOW, MUSHI_TIER_COLORS, readPageFaviconHref, resolveEnvConfig, diagnoseEnvConfig, validateConfig, expandPreset, createLogger, noopLogger, createApiClient, initSessionTracker, getReporterToken, createPreFilter, createOfflineQueue, createRateLimiter, createPiiScrubber, createBreadcrumbBuffer, getDeviceFingerprintHash, MAX_SCREENSHOT_DATA_URL_BYTES, captureEnvironment, getSessionId, newUuid, DEFAULT_API_ENDPOINT, MUSHI_DURATION, MUSHI_SPACING, MUSHI_RADIUS, isLikelyGenericFavicon, MUSHI_INTERNAL_INIT_MARKER, MUSHI_INTERNAL_HEADER, MUSHI_COLORS_LIGHT, parseIdentityToken, updateSessionIdentity, normaliseThrown, destroySessionTracker, resolveProjectDomain, projectInitials, projectFaviconUrlCandidates, sha256Hex } from '@mushi-mushi/core';
1
+ import { mushiPalette, resolveWidgetAccent, MUSHI_REPORTER_STATUS, MUSHI_GEOMETRY, MUSHI_Z, MUSHI_MOTION, MUSHI_TYPE, MUSHI_BANNER_BRAND_BORDER, MUSHI_BANNER_NEON, MUSHI_INVERSE, MUSHI_ON_ACCENT, MUSHI_ACCENT_SHADOW, MUSHI_TIER_COLORS, readPageFaviconHref, scrubUrl, resolveEnvConfig, diagnoseEnvConfig, validateConfig, expandPreset, createLogger, noopLogger, createApiClient, initSessionTracker, getReporterToken, createPreFilter, createOfflineQueue, createRateLimiter, createPiiScrubber, createBreadcrumbBuffer, getDeviceFingerprintHash, MAX_SCREENSHOT_DATA_URL_BYTES, captureEnvironment, getSessionId, newUuid, markPageUnloading, flushLastOutboundOnUnload, DEFAULT_API_ENDPOINT, shouldDropCapturedError, MUSHI_DURATION, MUSHI_SPACING, MUSHI_RADIUS, isLikelyGenericFavicon, MUSHI_INTERNAL_INIT_MARKER, MUSHI_INTERNAL_HEADER, MUSHI_COLORS_LIGHT, parseIdentityToken, updateSessionIdentity, normaliseThrown, destroySessionTracker, resolveProjectDomain, projectInitials, projectFaviconUrlCandidates, sha256Hex } from '@mushi-mushi/core';
2
2
 
3
3
  // src/capture/compress-screenshot.ts
4
4
  async function compressScreenshotDataUrl(dataUrl, maxBytes = MAX_SCREENSHOT_DATA_URL_BYTES) {
@@ -75,7 +75,9 @@ var en = {
75
75
  visual: "Layout, styling, or display problem",
76
76
  confusing: "Hard to understand or navigate",
77
77
  other: "Something else"
78
- }
78
+ },
79
+ moreCategoriesLabel: "More issue types",
80
+ moreCategoriesCount: "{n} more"
79
81
  },
80
82
  step2: {
81
83
  heading: "What happened?",
@@ -212,6 +214,14 @@ var en = {
212
214
  label: "Feature request",
213
215
  description: "Suggest a change"
214
216
  },
217
+ betaStrip: {
218
+ defaultMessage: "{appName} is in early development",
219
+ contactHint: "Reports go to {email} \xB7 reviewed by the team",
220
+ ariaLabel: "Beta status"
221
+ },
222
+ changelog: {
223
+ whatsNew: "What's new in {version}"
224
+ },
215
225
  poweredBy: "Powered by Mushi v{version}"
216
226
  }
217
227
  };
@@ -255,7 +265,9 @@ var ja = {
255
265
  visual: "\u30EC\u30A4\u30A2\u30A6\u30C8\u3001\u30C7\u30B6\u30A4\u30F3\u3001\u8868\u793A\u306E\u554F\u984C",
256
266
  confusing: "\u7406\u89E3\u3057\u306B\u304F\u3044\u3001\u64CD\u4F5C\u304C\u308F\u304B\u308A\u306B\u304F\u3044",
257
267
  other: "\u305D\u306E\u4ED6\u306E\u554F\u984C"
258
- }
268
+ },
269
+ moreCategoriesLabel: "\u305D\u306E\u4ED6\u306E\u554F\u984C\u306E\u7A2E\u985E",
270
+ moreCategoriesCount: "\u4ED6{n}\u4EF6"
259
271
  },
260
272
  step2: {
261
273
  heading: "\u4F55\u304C\u8D77\u304D\u307E\u3057\u305F\u304B\uFF1F",
@@ -392,6 +404,14 @@ var ja = {
392
404
  label: "\u6A5F\u80FD\u30EA\u30AF\u30A8\u30B9\u30C8",
393
405
  description: "\u5909\u66F4\u3092\u63D0\u6848"
394
406
  },
407
+ betaStrip: {
408
+ defaultMessage: "{appName}\u306F\u958B\u767A\u521D\u671F\u6BB5\u968E\u3067\u3059",
409
+ contactHint: "\u30EC\u30DD\u30FC\u30C8\u306F {email} \u306B\u5C4A\u304D\u3001\u30C1\u30FC\u30E0\u304C\u78BA\u8A8D\u3057\u307E\u3059",
410
+ ariaLabel: "\u30D9\u30FC\u30BF\u7248\u306E\u304A\u77E5\u3089\u305B"
411
+ },
412
+ changelog: {
413
+ whatsNew: "{version} \u306E\u65B0\u6A5F\u80FD"
414
+ },
395
415
  poweredBy: "Mushi v{version}"
396
416
  }
397
417
  };
@@ -435,7 +455,9 @@ var th = {
435
455
  visual: "\u0E1B\u0E31\u0E0D\u0E2B\u0E32\u0E40\u0E25\u0E22\u0E4C\u0E40\u0E2D\u0E32\u0E15\u0E4C \u0E2A\u0E44\u0E15\u0E25\u0E4C \u0E2B\u0E23\u0E37\u0E2D\u0E01\u0E32\u0E23\u0E41\u0E2A\u0E14\u0E07\u0E1C\u0E25",
436
456
  confusing: "\u0E40\u0E02\u0E49\u0E32\u0E43\u0E08\u0E22\u0E32\u0E01\u0E2B\u0E23\u0E37\u0E2D\u0E19\u0E33\u0E17\u0E32\u0E07\u0E22\u0E32\u0E01",
437
457
  other: "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E2D\u0E37\u0E48\u0E19"
438
- }
458
+ },
459
+ moreCategoriesLabel: "\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E1B\u0E31\u0E0D\u0E2B\u0E32\u0E2D\u0E37\u0E48\u0E19 \u0E46",
460
+ moreCategoriesCount: "\u0E2D\u0E35\u0E01 {n} \u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"
439
461
  },
440
462
  step2: {
441
463
  heading: "\u0E40\u0E01\u0E34\u0E14\u0E2D\u0E30\u0E44\u0E23\u0E02\u0E36\u0E49\u0E19?",
@@ -572,6 +594,14 @@ var th = {
572
594
  label: "\u0E02\u0E2D\u0E1F\u0E35\u0E40\u0E08\u0E2D\u0E23\u0E4C",
573
595
  description: "\u0E40\u0E2A\u0E19\u0E2D\u0E01\u0E32\u0E23\u0E40\u0E1B\u0E25\u0E35\u0E48\u0E22\u0E19\u0E41\u0E1B\u0E25\u0E07"
574
596
  },
597
+ betaStrip: {
598
+ defaultMessage: "{appName} \u0E2D\u0E22\u0E39\u0E48\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E01\u0E32\u0E23\u0E1E\u0E31\u0E12\u0E19\u0E32\u0E0A\u0E48\u0E27\u0E07\u0E15\u0E49\u0E19",
599
+ contactHint: "\u0E23\u0E32\u0E22\u0E07\u0E32\u0E19\u0E08\u0E30\u0E2A\u0E48\u0E07\u0E44\u0E1B\u0E17\u0E35\u0E48 {email} \xB7 \u0E17\u0E35\u0E21\u0E07\u0E32\u0E19\u0E15\u0E23\u0E27\u0E08\u0E2A\u0E2D\u0E1A\u0E17\u0E38\u0E01\u0E09\u0E1A\u0E31\u0E1A",
600
+ ariaLabel: "\u0E2A\u0E16\u0E32\u0E19\u0E30\u0E40\u0E1A\u0E15\u0E49\u0E32"
601
+ },
602
+ changelog: {
603
+ whatsNew: "\u0E21\u0E35\u0E2D\u0E30\u0E44\u0E23\u0E43\u0E2B\u0E21\u0E48\u0E43\u0E19 {version}"
604
+ },
575
605
  poweredBy: "Powered by Mushi v{version}"
576
606
  }
577
607
  };
@@ -615,7 +645,9 @@ var es = {
615
645
  visual: "Problema de dise\xF1o, estilo o visualizaci\xF3n",
616
646
  confusing: "Dif\xEDcil de entender o navegar",
617
647
  other: "Otro problema"
618
- }
648
+ },
649
+ moreCategoriesLabel: "M\xE1s tipos de problemas",
650
+ moreCategoriesCount: "{n} m\xE1s"
619
651
  },
620
652
  step2: {
621
653
  heading: "\xBFQu\xE9 pas\xF3?",
@@ -752,6 +784,14 @@ var es = {
752
784
  label: "Solicitud de funci\xF3n",
753
785
  description: "Sugerir un cambio"
754
786
  },
787
+ betaStrip: {
788
+ defaultMessage: "{appName} est\xE1 en desarrollo temprano",
789
+ contactHint: "Los reportes van a {email} \xB7 revisados por el equipo",
790
+ ariaLabel: "Estado beta"
791
+ },
792
+ changelog: {
793
+ whatsNew: "Novedades de {version}"
794
+ },
755
795
  poweredBy: "Con tecnolog\xEDa de Mushi v{version}"
756
796
  }
757
797
  };
@@ -2673,7 +2713,7 @@ function getWidgetStyles(theme, accent = "", accentText = "") {
2673
2713
 
2674
2714
  // src/version.ts
2675
2715
  var MUSHI_SDK_PACKAGE = "@mushi-mushi/web";
2676
- var MUSHI_SDK_VERSION = "1.26.0" ;
2716
+ var MUSHI_SDK_VERSION = "1.28.0" ;
2677
2717
  var ASSISTANT_SESSION_STORAGE_KEY = "mushi-assistant-session-v1";
2678
2718
  function loadAssistantSession() {
2679
2719
  try {
@@ -3101,8 +3141,8 @@ function renderCategoryStep(ctx) {
3101
3141
  const primaryCategories = primaryEntries.map(renderEntry).join("");
3102
3142
  const secondaryCategories = secondaryEntries.map(renderEntry).join("");
3103
3143
  const secondaryHtml = hasMore ? ctx.showAllCategories ? `<div class="mushi-categories-expanded">${secondaryCategories}</div>` : `<button type="button" class="mushi-more-toggle" data-action="show-all-categories">
3104
- <span class="mushi-more-toggle-text">More issue types</span>
3105
- <span class="mushi-more-toggle-count">${secondaryEntries.length} more</span>
3144
+ <span class="mushi-more-toggle-text">${escapeHtml(t.step1.moreCategoriesLabel)}</span>
3145
+ <span class="mushi-more-toggle-count">${escapeHtml(t.step1.moreCategoriesCount.replace("{n}", String(secondaryEntries.length)))}</span>
3106
3146
  <span class="mushi-more-toggle-arrow" aria-hidden="true">\u2192</span>
3107
3147
  </button>` : "";
3108
3148
  return `
@@ -3145,7 +3185,10 @@ function renderBetaChangelog(ctx) {
3145
3185
  if (!entries?.length) return "";
3146
3186
  const latest = entries[0];
3147
3187
  const items = latest.items.map((item) => `<li>\u2022 ${escapeHtml(item)}</li>`).join("");
3148
- const label = latest.date ? `What\u2019s new in ${escapeHtml(latest.version)} \xB7 ${escapeHtml(latest.date)}` : `What\u2019s new in ${escapeHtml(latest.version)}`;
3188
+ const whatsNew = escapeHtml(
3189
+ ctx.locale.flows.changelog.whatsNew.replace("{version}", latest.version)
3190
+ );
3191
+ const label = latest.date ? `${whatsNew} \xB7 ${escapeHtml(latest.date)}` : whatsNew;
3149
3192
  return `
3150
3193
  <details class="mushi-changelog">
3151
3194
  <summary class="mushi-changelog-summary">${label}</summary>
@@ -3155,17 +3198,18 @@ function renderBetaChangelog(ctx) {
3155
3198
  }
3156
3199
  function renderBetaStrip(ctx) {
3157
3200
  const beta = ctx.config.betaMode;
3201
+ const strip = ctx.locale.flows.betaStrip;
3158
3202
  const appName = escapeHtml(beta.appName ?? "This app");
3159
- const message = beta.message ? escapeHtml(beta.message) : `${appName} is in early development`;
3203
+ const message = beta.message ? escapeHtml(beta.message) : escapeHtml(strip.defaultMessage).replace("{appName}", appName);
3160
3204
  const email = beta.contactEmail ? escapeHtml(beta.contactEmail) : null;
3161
3205
  const perks = beta.perks ?? [];
3162
3206
  return `
3163
- <div class="mushi-beta-strip" role="note" aria-label="Beta status">
3207
+ <div class="mushi-beta-strip" role="note" aria-label="${escapeHtml(strip.ariaLabel)}">
3164
3208
  <div class="mushi-beta-strip-row">
3165
3209
  <span class="mushi-beta-tag" aria-hidden="true">BETA</span>
3166
3210
  <span class="mushi-beta-msg">${message}</span>
3167
3211
  </div>
3168
- ${email ? `<div class="mushi-beta-contact-hint">Reports go to ${email} \xB7 reviewed by the team</div>` : ""}
3212
+ ${email ? `<div class="mushi-beta-contact-hint">${escapeHtml(strip.contactHint).replace("{email}", email)}</div>` : ""}
3169
3213
  ${perks.length > 0 ? `
3170
3214
  <ul class="mushi-beta-perks" aria-label="Beta tester perks">
3171
3215
  ${perks.map((p) => `<li>\u2713 ${escapeHtml(p)}</li>`).join("")}
@@ -6333,59 +6377,6 @@ function renderConsentBanner(projectId, config) {
6333
6377
  });
6334
6378
  document.body.appendChild(consentHost);
6335
6379
  }
6336
-
6337
- // src/capture/console.ts
6338
- var MAX_ENTRIES = 50;
6339
- var MAX_MESSAGE_LENGTH = 500;
6340
- function createConsoleCapture() {
6341
- const entries = [];
6342
- const originals = {};
6343
- const wrappers = {};
6344
- const levels = ["log", "warn", "error", "info", "debug"];
6345
- for (const level of levels) {
6346
- const original = console[level];
6347
- originals[level] = original;
6348
- const wrapper = (...args) => {
6349
- const message = args.map((arg) => {
6350
- try {
6351
- return typeof arg === "string" ? arg : JSON.stringify(arg);
6352
- } catch {
6353
- return String(arg);
6354
- }
6355
- }).join(" ").slice(0, MAX_MESSAGE_LENGTH);
6356
- const entry = {
6357
- level,
6358
- message,
6359
- timestamp: Date.now()
6360
- };
6361
- if (level === "error" && args[0] instanceof Error) {
6362
- entry.stack = args[0].stack?.slice(0, 1e3);
6363
- }
6364
- entries.push(entry);
6365
- if (entries.length > MAX_ENTRIES) {
6366
- entries.shift();
6367
- }
6368
- original.call(console, ...args);
6369
- };
6370
- wrappers[level] = wrapper;
6371
- console[level] = wrapper;
6372
- }
6373
- return {
6374
- getEntries() {
6375
- return [...entries];
6376
- },
6377
- clear() {
6378
- entries.length = 0;
6379
- },
6380
- destroy() {
6381
- for (const level of levels) {
6382
- if (originals[level] && console[level] === wrappers[level]) {
6383
- console[level] = originals[level];
6384
- }
6385
- }
6386
- }
6387
- };
6388
- }
6389
6380
  var DEFAULT_INTERNAL_URL_MATCHERS = [
6390
6381
  /\/v1\/sdk(?:\/|$)/,
6391
6382
  /\/v1\/reports(?:\/|$)/,
@@ -6449,7 +6440,7 @@ function readHeader(headers, name) {
6449
6440
  }
6450
6441
 
6451
6442
  // src/capture/network.ts
6452
- var MAX_ENTRIES2 = 30;
6443
+ var MAX_ENTRIES = 30;
6453
6444
  var TRACEPARENT_VERSION = "00";
6454
6445
  function generateTraceparent() {
6455
6446
  const traceBytes = crypto.getRandomValues(new Uint8Array(16));
@@ -6473,17 +6464,29 @@ function matchesCorsUrls(url, corsUrls) {
6473
6464
  }
6474
6465
  return false;
6475
6466
  }
6467
+ var _activeCorrelationStack = [];
6468
+ function getActiveCorrelationId() {
6469
+ return _activeCorrelationStack[_activeCorrelationStack.length - 1];
6470
+ }
6471
+ function generateCorrelationId() {
6472
+ const bytes = crypto.getRandomValues(new Uint8Array(4));
6473
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
6474
+ }
6476
6475
  function createNetworkCapture(options = {}) {
6477
6476
  const entries = [];
6478
6477
  const originalFetch = globalThis.fetch;
6478
+ const OriginalXHR = typeof XMLHttpRequest !== "undefined" ? XMLHttpRequest : null;
6479
+ const originalXhrOpen = OriginalXHR ? XMLHttpRequest.prototype.open : null;
6480
+ const originalXhrSend = OriginalXHR ? XMLHttpRequest.prototype.send : null;
6481
+ const originalXhrSetRequestHeader = OriginalXHR ? XMLHttpRequest.prototype.setRequestHeader : null;
6479
6482
  let activeOptions = options;
6480
- let fetchWrapper;
6481
- globalThis.fetch = fetchWrapper = async function mushiFetchInterceptor(input, init) {
6483
+ const fetchWrapper = async function mushiFetchInterceptor(input, init) {
6482
6484
  const startTime = Date.now();
6483
6485
  const method = init?.method?.toUpperCase() ?? "GET";
6484
6486
  const url = getRequestUrl(input);
6485
6487
  const internalKind = getInternalRequestKind(input, init);
6486
6488
  const shouldRecord = !internalKind && !shouldIgnoreMushiUrl(url, activeOptions);
6489
+ const correlationId = shouldRecord ? generateCorrelationId() : void 0;
6487
6490
  let traceId;
6488
6491
  let patchedInit = init;
6489
6492
  const tp = activeOptions.tracePropagation;
@@ -6497,6 +6500,7 @@ function createNetworkCapture(options = {}) {
6497
6500
  }
6498
6501
  patchedInit = { ...init, headers: existingHeaders };
6499
6502
  }
6503
+ if (correlationId) _activeCorrelationStack.push(correlationId);
6500
6504
  try {
6501
6505
  const response = await originalFetch.call(globalThis, input, patchedInit);
6502
6506
  if (shouldRecord) {
@@ -6506,7 +6510,9 @@ function createNetworkCapture(options = {}) {
6506
6510
  status: response.status,
6507
6511
  duration: Date.now() - startTime,
6508
6512
  timestamp: startTime,
6509
- ...traceId ? { traceId } : {}
6513
+ captureMethod: "fetch",
6514
+ ...traceId ? { traceId } : {},
6515
+ ...correlationId ? { correlationId } : {}
6510
6516
  });
6511
6517
  }
6512
6518
  return response;
@@ -6519,15 +6525,100 @@ function createNetworkCapture(options = {}) {
6519
6525
  duration: Date.now() - startTime,
6520
6526
  timestamp: startTime,
6521
6527
  error: error instanceof Error ? error.message : "Network error",
6522
- ...traceId ? { traceId } : {}
6528
+ captureMethod: "fetch",
6529
+ ...traceId ? { traceId } : {},
6530
+ ...correlationId ? { correlationId } : {}
6523
6531
  });
6524
6532
  }
6525
6533
  throw error;
6534
+ } finally {
6535
+ if (correlationId) {
6536
+ const idx = _activeCorrelationStack.lastIndexOf(correlationId);
6537
+ if (idx !== -1) _activeCorrelationStack.splice(idx, 1);
6538
+ }
6526
6539
  }
6527
6540
  };
6541
+ globalThis.fetch = fetchWrapper;
6542
+ const xhrStateMap = typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : null;
6543
+ if (OriginalXHR && originalXhrOpen && originalXhrSend && originalXhrSetRequestHeader && xhrStateMap) {
6544
+ const _originalOpen = originalXhrOpen;
6545
+ XMLHttpRequest.prototype.open = function mushiXhrOpen(...args) {
6546
+ const [method, url] = args;
6547
+ const urlStr = typeof url === "string" ? url : String(url);
6548
+ const shouldRecord = !shouldIgnoreMushiUrl(urlStr, activeOptions);
6549
+ const correlationId = shouldRecord ? generateCorrelationId() : void 0;
6550
+ let traceId;
6551
+ let storedTraceparent;
6552
+ const tp = activeOptions.tracePropagation;
6553
+ if (shouldRecord && tp?.enabled && tp.corsUrls?.length && matchesCorsUrls(urlStr, tp.corsUrls)) {
6554
+ const generated = generateTraceparent();
6555
+ traceId = generated.traceId;
6556
+ storedTraceparent = generated.traceparent;
6557
+ }
6558
+ const _prevXhrState = xhrStateMap.get(this);
6559
+ if (_prevXhrState?._listener) {
6560
+ this.removeEventListener("readystatechange", _prevXhrState._listener);
6561
+ }
6562
+ xhrStateMap.set(this, {
6563
+ method: String(method).toUpperCase(),
6564
+ url: truncateUrl(urlStr),
6565
+ startTime: 0,
6566
+ // set in .send()
6567
+ shouldRecord,
6568
+ ...traceId ? { traceId } : {},
6569
+ ...correlationId ? { correlationId } : {},
6570
+ // Attach the traceparent string as an extra prop for injection in .send().
6571
+ ...storedTraceparent ? { _traceparent: storedTraceparent } : {}
6572
+ });
6573
+ _originalOpen.apply(this, args);
6574
+ };
6575
+ XMLHttpRequest.prototype.send = function mushiXhrSend(body) {
6576
+ const state = xhrStateMap.get(this);
6577
+ if (state) {
6578
+ state.startTime = Date.now();
6579
+ const xhrTraceparent = state._traceparent;
6580
+ if (xhrTraceparent) {
6581
+ originalXhrSetRequestHeader.call(this, "traceparent", xhrTraceparent);
6582
+ if (activeOptions.sessionId) {
6583
+ originalXhrSetRequestHeader.call(this, "x-mushi-session", activeOptions.sessionId);
6584
+ }
6585
+ }
6586
+ if (state.correlationId) _activeCorrelationStack.push(state.correlationId);
6587
+ const _readystateHandler = () => {
6588
+ if (this.readyState !== 4) return;
6589
+ if (state.shouldRecord) {
6590
+ const duration = Date.now() - state.startTime;
6591
+ const entry = {
6592
+ method: state.method,
6593
+ url: state.url,
6594
+ status: this.status,
6595
+ duration,
6596
+ timestamp: state.startTime,
6597
+ captureMethod: "xhr",
6598
+ ...state.traceId ? { traceId: state.traceId } : {},
6599
+ ...state.correlationId ? { correlationId: state.correlationId } : {}
6600
+ };
6601
+ if (this.status === 0) {
6602
+ entry.error = "XHR network error or aborted";
6603
+ }
6604
+ addEntry(entry);
6605
+ }
6606
+ if (state.correlationId) {
6607
+ const idx = _activeCorrelationStack.lastIndexOf(state.correlationId);
6608
+ if (idx !== -1) _activeCorrelationStack.splice(idx, 1);
6609
+ }
6610
+ };
6611
+ state._listener = _readystateHandler;
6612
+ this.addEventListener("readystatechange", _readystateHandler);
6613
+ }
6614
+ originalXhrSend.call(this, body);
6615
+ };
6616
+ }
6617
+ const xhrOpenWrapper = OriginalXHR ? XMLHttpRequest.prototype.open : null;
6618
+ const xhrSendWrapper = OriginalXHR ? XMLHttpRequest.prototype.send : null;
6528
6619
  function addEntry(entry) {
6529
6620
  entries.push(entry);
6530
- if (entries.length > MAX_ENTRIES2) {
6621
+ if (entries.length > MAX_ENTRIES) {
6531
6622
  entries.shift();
6532
6623
  }
6533
6624
  }
@@ -6545,22 +6636,86 @@ function createNetworkCapture(options = {}) {
6545
6636
  if (globalThis.fetch === fetchWrapper) {
6546
6637
  globalThis.fetch = originalFetch;
6547
6638
  }
6639
+ if (OriginalXHR && originalXhrOpen && originalXhrSend) {
6640
+ if (xhrOpenWrapper && XMLHttpRequest.prototype.open === xhrOpenWrapper) {
6641
+ XMLHttpRequest.prototype.open = originalXhrOpen;
6642
+ }
6643
+ if (xhrSendWrapper && XMLHttpRequest.prototype.send === xhrSendWrapper) {
6644
+ XMLHttpRequest.prototype.send = originalXhrSend;
6645
+ }
6646
+ }
6548
6647
  }
6549
6648
  };
6550
6649
  }
6551
6650
  function truncateUrl(url) {
6651
+ const scrubbed = scrubUrl(url);
6552
6652
  try {
6553
- const parsed = new URL(url);
6653
+ const parsed = new URL(scrubbed);
6554
6654
  const path = parsed.pathname + parsed.search;
6555
6655
  if (path.length > 200) {
6556
6656
  return parsed.origin + path.slice(0, 200) + "...";
6557
6657
  }
6558
6658
  return parsed.origin + path;
6559
6659
  } catch {
6560
- return url.slice(0, 200);
6660
+ return scrubbed.slice(0, 200);
6561
6661
  }
6562
6662
  }
6563
6663
 
6664
+ // src/capture/console.ts
6665
+ var MAX_ENTRIES2 = 50;
6666
+ var MAX_MESSAGE_LENGTH = 500;
6667
+ function createConsoleCapture() {
6668
+ const entries = [];
6669
+ const originals = {};
6670
+ const wrappers = {};
6671
+ const levels = ["log", "warn", "error", "info", "debug"];
6672
+ for (const level of levels) {
6673
+ const original = console[level];
6674
+ originals[level] = original;
6675
+ const wrapper = (...args) => {
6676
+ const message = args.map((arg) => {
6677
+ try {
6678
+ return typeof arg === "string" ? arg : JSON.stringify(arg);
6679
+ } catch {
6680
+ return String(arg);
6681
+ }
6682
+ }).join(" ").slice(0, MAX_MESSAGE_LENGTH);
6683
+ const correlationId = getActiveCorrelationId();
6684
+ const entry = {
6685
+ level,
6686
+ message,
6687
+ timestamp: Date.now(),
6688
+ ...correlationId ? { correlationId } : {}
6689
+ };
6690
+ if (level === "error" && args[0] instanceof Error) {
6691
+ entry.stack = args[0].stack?.slice(0, 1e3);
6692
+ }
6693
+ entries.push(entry);
6694
+ if (entries.length > MAX_ENTRIES2) {
6695
+ entries.shift();
6696
+ }
6697
+ original.call(console, ...args);
6698
+ };
6699
+ wrappers[level] = wrapper;
6700
+ console[level] = wrapper;
6701
+ }
6702
+ return {
6703
+ getEntries() {
6704
+ return [...entries];
6705
+ },
6706
+ clear() {
6707
+ entries.length = 0;
6708
+ },
6709
+ destroy() {
6710
+ for (const level of levels) {
6711
+ if (originals[level] && console[level] === wrappers[level]) {
6712
+ console[level] = originals[level];
6713
+ }
6714
+ }
6715
+ }
6716
+ };
6717
+ }
6718
+
6564
6719
  // src/capture/screenshot.ts
6565
6720
  function createScreenshotCapture(options = {}) {
6566
6721
  let activeOptions = options;
@@ -7094,8 +7249,6 @@ function createElementSelector() {
7094
7249
  }
7095
7250
  return { activate, deactivate, isActive: () => active };
7096
7251
  }
7097
-
7098
- // src/capture/timeline.ts
7099
7252
  var MAX_TIMELINE_ENTRIES = 120;
7100
7253
  function createTimelineCapture() {
7101
7254
  const entries = [];
@@ -7112,8 +7265,11 @@ function createTimelineCapture() {
7112
7265
  kind: "route",
7113
7266
  payload: {
7114
7267
  source,
7115
- route: `${location.pathname}${location.search}${location.hash}`,
7116
- href: location.href
7268
+ // Query VALUES are a PII channel (`?token=…`, `?email=…`) — scrub
7269
+ // them at capture, both in the search string and inside hash-router
7270
+ // fragments (`#/path?query`). Keys and paths are preserved.
7271
+ route: scrubUrl(`${location.pathname}${location.search}${location.hash}`),
7272
+ href: scrubUrl(location.href)
7117
7273
  }
7118
7274
  });
7119
7275
  }
@@ -7200,6 +7356,18 @@ function normalizeSegment(seg) {
7200
7356
  if (SLUG_HASHY_RE.test(seg) && /\d/.test(seg)) return "[id]";
7201
7357
  return seg;
7202
7358
  }
7359
+ function deriveRoute(pathname, hash, templates) {
7360
+ if (hash.startsWith("#/")) {
7361
+ const raw = hash.slice(1);
7362
+ const qIdx = raw.indexOf("?");
7363
+ const hashPath = qIdx === -1 ? raw : raw.slice(0, qIdx);
7364
+ const hashTemplates = templates?.map(
7365
+ (t) => t.startsWith("/#/") ? t.slice(2) : t
7366
+ );
7367
+ return "/#" + normalizeRoute(hashPath, hashTemplates);
7368
+ }
7369
+ return normalizeRoute(pathname, templates);
7370
+ }
7203
7371
  function normalizeRoute(pathname, templates) {
7204
7372
  const clean = pathname.length > 1 && pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
7205
7373
  if (templates?.length) {
@@ -7243,9 +7411,14 @@ function readTestids() {
7243
7411
  function readQueryParamKeys() {
7244
7412
  if (typeof window === "undefined") return [];
7245
7413
  try {
7246
- const params = new URLSearchParams(window.location.search);
7247
7414
  const out = /* @__PURE__ */ new Set();
7248
- params.forEach((_, key) => out.add(key));
7415
+ const collect = (qs) => {
7416
+ new URLSearchParams(qs).forEach((_, key) => out.add(key));
7417
+ };
7418
+ collect(window.location.search);
7419
+ const hash = window.location.hash;
7420
+ const qIdx = hash.indexOf("?");
7421
+ if (hash.startsWith("#/") && qIdx !== -1) collect(hash.slice(qIdx + 1));
7249
7422
  return Array.from(out).sort();
7250
7423
  } catch {
7251
7424
  return [];
@@ -7292,7 +7465,11 @@ function createDiscoveryCapture(opts) {
7292
7465
  let pendingTimer = null;
7293
7466
  async function emitForCurrent() {
7294
7467
  if (typeof window === "undefined") return;
7295
- const route = normalizeRoute(window.location.pathname, config.routeTemplates);
7468
+ const route = deriveRoute(
7469
+ window.location.pathname,
7470
+ window.location.hash,
7471
+ config.routeTemplates
7472
+ );
7296
7473
  const now = Date.now();
7297
7474
  const last = lastEmittedAt.get(route) ?? 0;
7298
7475
  if (now - last < throttleMs) return;
@@ -7324,7 +7501,8 @@ function createDiscoveryCapture(opts) {
7324
7501
  }
7325
7502
  function onMaybeNavigation() {
7326
7503
  if (typeof window === "undefined") return;
7327
- const path = window.location.pathname + window.location.search;
7504
+ const hashPart = window.location.hash.startsWith("#/") ? window.location.hash : "";
7505
+ const path = window.location.pathname + window.location.search + hashPart;
7328
7506
  if (path === lastPath) return;
7329
7507
  lastPath = path;
7330
7508
  scheduleEmit();
@@ -7341,10 +7519,12 @@ function createDiscoveryCapture(opts) {
7341
7519
  onReplace: onNav,
7342
7520
  onPop: onNav
7343
7521
  });
7522
+ window.addEventListener("hashchange", onNav);
7344
7523
  scheduleEmit();
7345
7524
  return {
7346
7525
  destroy() {
7347
7526
  unsubHistory();
7527
+ window.removeEventListener("hashchange", onNav);
7348
7528
  if (pendingTimer) {
7349
7529
  clearTimeout(pendingTimer);
7350
7530
  pendingTimer = null;
@@ -7817,8 +7997,6 @@ function tagSentryScope(reportId, options = {}) {
7817
7997
  } catch {
7818
7998
  }
7819
7999
  }
7820
-
7821
- // src/proactive-triggers.ts
7822
8000
  var DEFAULT_EXCLUDE_ROUTES = [
7823
8001
  "/login",
7824
8002
  "/logout",
@@ -7961,6 +8139,15 @@ function setupProactiveTriggers(callbacks, config = {}) {
7961
8139
  }
7962
8140
  if (config.errorBoundary) {
7963
8141
  let handleError2 = function(event) {
8142
+ if (shouldDropCapturedError({
8143
+ message: event.message,
8144
+ filename: event.filename,
8145
+ ignoreErrors: config.ignoreErrors,
8146
+ denyUrls: config.denyUrls,
8147
+ allowUrls: config.allowUrls
8148
+ })) {
8149
+ return;
8150
+ }
7964
8151
  callbacks.onTrigger("error_boundary", {
7965
8152
  message: event.message,
7966
8153
  filename: event.filename,
@@ -7968,8 +8155,17 @@ function setupProactiveTriggers(callbacks, config = {}) {
7968
8155
  colno: event.colno
7969
8156
  });
7970
8157
  }, handleUnhandledRejection2 = function(event) {
8158
+ const message = event.reason instanceof Error ? event.reason.message : String(event.reason);
8159
+ if (shouldDropCapturedError({
8160
+ message,
8161
+ ignoreErrors: config.ignoreErrors,
8162
+ denyUrls: config.denyUrls,
8163
+ allowUrls: config.allowUrls
8164
+ })) {
8165
+ return;
8166
+ }
7971
8167
  callbacks.onTrigger("error_boundary", {
7972
- message: event.reason instanceof Error ? event.reason.message : String(event.reason),
8168
+ message,
7973
8169
  type: "unhandled_rejection"
7974
8170
  });
7975
8171
  };
@@ -8132,6 +8328,7 @@ function createInstance(config) {
8132
8328
  ...typeof bootstrapConfig.timeout === "number" ? { timeout: bootstrapConfig.timeout } : {},
8133
8329
  ...typeof bootstrapConfig.maxRetries === "number" ? { maxRetries: bootstrapConfig.maxRetries } : {},
8134
8330
  ...bootstrapConfig.circuitBreaker ? { circuitBreaker: bootstrapConfig.circuitBreaker } : {},
8331
+ ...bootstrapConfig.tunnel ? { tunnel: bootstrapConfig.tunnel } : {},
8135
8332
  getUserToken: () => userToken,
8136
8333
  sdkPackage: MUSHI_SDK_PACKAGE,
8137
8334
  sdkVersion: MUSHI_SDK_VERSION
@@ -8163,6 +8360,14 @@ function createInstance(config) {
8163
8360
  return next;
8164
8361
  });
8165
8362
  }
8363
+ function scrubConsoleForWire(logs) {
8364
+ if (!logs) return logs;
8365
+ return logs.map((entry) => ({
8366
+ ...entry,
8367
+ message: piiScrubber.scrub(entry.message),
8368
+ ...entry.stack ? { stack: piiScrubber.scrub(entry.stack) } : {}
8369
+ }));
8370
+ }
8166
8371
  function scrubTagsForWire(tags) {
8167
8372
  if (!tags) return void 0;
8168
8373
  const out = {};
@@ -8311,7 +8516,11 @@ function createInstance(config) {
8311
8516
  discoveryCap = null;
8312
8517
  }
8313
8518
  const replayMode = activeConfig.capture?.replay ?? "off";
8314
- if (replayMode === "rrweb" || replayMode === "lite") {
8519
+ const replaySampleRate = activeConfig.replaySampleRate ?? 1;
8520
+ const replaySampled = replaySampleRate >= 1 || Math.random() < replaySampleRate;
8521
+ const onErrorReplayRate = activeConfig.replaysOnErrorSampleRate ?? 0;
8522
+ const replayOnErrorSampled = !replaySampled && onErrorReplayRate > 0 && Math.random() < onErrorReplayRate;
8523
+ if ((replayMode === "rrweb" || replayMode === "lite") && (replaySampled || replayOnErrorSampled)) {
8315
8524
  const generation = ++replayGeneration;
8316
8525
  void createReplayCapture({
8317
8526
  redactSelectors: activeConfig.privacy?.redactSelectors
@@ -8730,6 +8939,9 @@ function createInstance(config) {
8730
8939
  apiCascade: proactiveCfg?.apiCascade,
8731
8940
  apiEndpoint: resolveApiEndpoint(activeConfig),
8732
8941
  errorBoundary: proactiveCfg?.errorBoundary,
8942
+ ignoreErrors: activeConfig.ignoreErrors,
8943
+ denyUrls: activeConfig.denyUrls,
8944
+ allowUrls: activeConfig.allowUrls,
8733
8945
  pageDwell: proactiveCfg?.pageDwell,
8734
8946
  firstSession: proactiveCfg?.firstSession,
8735
8947
  projectId: bootstrapConfig.projectId
@@ -8850,6 +9062,13 @@ function createInstance(config) {
8850
9062
  });
8851
9063
  }
8852
9064
  }
9065
+ const isAutomatic = pendingProactiveTrigger !== null;
9066
+ if (isAutomatic && config.sampleRate !== void 0 && config.sampleRate < 1) {
9067
+ if (config.sampleRate <= 0 || Math.random() > config.sampleRate) {
9068
+ log.debug("Report dropped by sampleRate", { sampleRate: config.sampleRate, trigger: pendingProactiveTrigger });
9069
+ return void 0;
9070
+ }
9071
+ }
8853
9072
  if (!rateLimiter.tryConsume()) {
8854
9073
  log.warn("Report throttled \u2014 rate limit exceeded");
8855
9074
  return void 0;
@@ -8857,7 +9076,7 @@ function createInstance(config) {
8857
9076
  const scrubbedDescription = piiScrubber.scrub(preFilter.truncate(description));
8858
9077
  const sentryCtx = config.sentry ? captureSentryContext(config.sentry) : void 0;
8859
9078
  const fingerprintHash = await getDeviceFingerprintHash().catch(() => null);
8860
- const consoleLogs = activeConfig.capture?.console === false ? void 0 : consoleCap?.getEntries();
9079
+ const consoleLogs = activeConfig.capture?.console === false ? void 0 : scrubConsoleForWire(consoleCap?.getEntries());
8861
9080
  const networkLogs = activeConfig.capture?.network === false ? void 0 : networkCap?.getEntries();
8862
9081
  const reportBreadcrumbs = scrubBreadcrumbsForWire(breadcrumbs.getAll());
8863
9082
  const stickyTagSnapshot = scrubTagsForWire(
@@ -8935,10 +9154,11 @@ function createInstance(config) {
8935
9154
  config.integrations.custom(builder);
8936
9155
  }
8937
9156
  let finalReport = report;
8938
- if (config.beforeSendFeedback) {
9157
+ const sendHook = config.beforeSend ?? config.beforeSendFeedback;
9158
+ if (sendHook) {
8939
9159
  try {
8940
9160
  const hookResult = await Promise.race([
8941
- Promise.resolve(config.beforeSendFeedback(report)),
9161
+ Promise.resolve(sendHook(report)),
8942
9162
  // 2s timeout — async hooks must not block the user's "submit"
8943
9163
  // for longer than the network would. Falls back to original.
8944
9164
  new Promise(
@@ -8946,12 +9166,12 @@ function createInstance(config) {
8946
9166
  )
8947
9167
  ]);
8948
9168
  if (hookResult === null) {
8949
- log.info("Report dropped by beforeSendFeedback hook", { reportId: report.id });
9169
+ log.info("Report dropped by beforeSend hook", { reportId: report.id });
8950
9170
  return;
8951
9171
  }
8952
9172
  finalReport = hookResult;
8953
9173
  } catch (err) {
8954
- log.warn("beforeSendFeedback hook threw \u2014 sending unmodified report", {
9174
+ log.warn("beforeSend hook threw \u2014 sending unmodified report", {
8955
9175
  error: err instanceof Error ? err.message : String(err)
8956
9176
  });
8957
9177
  }
@@ -9229,6 +9449,16 @@ function createInstance(config) {
9229
9449
  },
9230
9450
  async captureException(error, options) {
9231
9451
  const normalised = normaliseThrown(error);
9452
+ const filename = typeof options?.metadata?.filename === "string" ? options.metadata.filename : void 0;
9453
+ if (shouldDropCapturedError({
9454
+ message: normalised.message,
9455
+ filename,
9456
+ ignoreErrors: activeConfig.ignoreErrors,
9457
+ denyUrls: activeConfig.denyUrls,
9458
+ allowUrls: activeConfig.allowUrls
9459
+ })) {
9460
+ return null;
9461
+ }
9232
9462
  breadcrumbs.add({
9233
9463
  category: "lifecycle",
9234
9464
  level: "error",
@@ -9422,6 +9652,8 @@ function createInstance(config) {
9422
9652
  localStorage.setItem(SENTINEL_KEY, "clean");
9423
9653
  } catch {
9424
9654
  }
9655
+ markPageUnloading();
9656
+ flushLastOutboundOnUnload();
9425
9657
  });
9426
9658
  } catch {
9427
9659
  }