@mushi-mushi/web 1.26.0 → 1.27.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.cjs CHANGED
@@ -2675,7 +2675,7 @@ function getWidgetStyles(theme, accent = "", accentText = "") {
2675
2675
 
2676
2676
  // src/version.ts
2677
2677
  var MUSHI_SDK_PACKAGE = "@mushi-mushi/web";
2678
- var MUSHI_SDK_VERSION = "1.26.0" ;
2678
+ var MUSHI_SDK_VERSION = "1.27.0" ;
2679
2679
  var ASSISTANT_SESSION_STORAGE_KEY = "mushi-assistant-session-v1";
2680
2680
  function loadAssistantSession() {
2681
2681
  try {
@@ -6335,59 +6335,6 @@ function renderConsentBanner(projectId, config) {
6335
6335
  });
6336
6336
  document.body.appendChild(consentHost);
6337
6337
  }
6338
-
6339
- // src/capture/console.ts
6340
- var MAX_ENTRIES = 50;
6341
- var MAX_MESSAGE_LENGTH = 500;
6342
- function createConsoleCapture() {
6343
- const entries = [];
6344
- const originals = {};
6345
- const wrappers = {};
6346
- const levels = ["log", "warn", "error", "info", "debug"];
6347
- for (const level of levels) {
6348
- const original = console[level];
6349
- originals[level] = original;
6350
- const wrapper = (...args) => {
6351
- const message = args.map((arg) => {
6352
- try {
6353
- return typeof arg === "string" ? arg : JSON.stringify(arg);
6354
- } catch {
6355
- return String(arg);
6356
- }
6357
- }).join(" ").slice(0, MAX_MESSAGE_LENGTH);
6358
- const entry = {
6359
- level,
6360
- message,
6361
- timestamp: Date.now()
6362
- };
6363
- if (level === "error" && args[0] instanceof Error) {
6364
- entry.stack = args[0].stack?.slice(0, 1e3);
6365
- }
6366
- entries.push(entry);
6367
- if (entries.length > MAX_ENTRIES) {
6368
- entries.shift();
6369
- }
6370
- original.call(console, ...args);
6371
- };
6372
- wrappers[level] = wrapper;
6373
- console[level] = wrapper;
6374
- }
6375
- return {
6376
- getEntries() {
6377
- return [...entries];
6378
- },
6379
- clear() {
6380
- entries.length = 0;
6381
- },
6382
- destroy() {
6383
- for (const level of levels) {
6384
- if (originals[level] && console[level] === wrappers[level]) {
6385
- console[level] = originals[level];
6386
- }
6387
- }
6388
- }
6389
- };
6390
- }
6391
6338
  var DEFAULT_INTERNAL_URL_MATCHERS = [
6392
6339
  /\/v1\/sdk(?:\/|$)/,
6393
6340
  /\/v1\/reports(?:\/|$)/,
@@ -6451,7 +6398,7 @@ function readHeader(headers, name) {
6451
6398
  }
6452
6399
 
6453
6400
  // src/capture/network.ts
6454
- var MAX_ENTRIES2 = 30;
6401
+ var MAX_ENTRIES = 30;
6455
6402
  var TRACEPARENT_VERSION = "00";
6456
6403
  function generateTraceparent() {
6457
6404
  const traceBytes = crypto.getRandomValues(new Uint8Array(16));
@@ -6475,9 +6422,21 @@ function matchesCorsUrls(url, corsUrls) {
6475
6422
  }
6476
6423
  return false;
6477
6424
  }
6425
+ var _activeCorrelationStack = [];
6426
+ function getActiveCorrelationId() {
6427
+ return _activeCorrelationStack[_activeCorrelationStack.length - 1];
6428
+ }
6429
+ function generateCorrelationId() {
6430
+ const bytes = crypto.getRandomValues(new Uint8Array(4));
6431
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
6432
+ }
6478
6433
  function createNetworkCapture(options = {}) {
6479
6434
  const entries = [];
6480
6435
  const originalFetch = globalThis.fetch;
6436
+ const OriginalXHR = typeof XMLHttpRequest !== "undefined" ? XMLHttpRequest : null;
6437
+ const originalXhrOpen = OriginalXHR ? XMLHttpRequest.prototype.open : null;
6438
+ const originalXhrSend = OriginalXHR ? XMLHttpRequest.prototype.send : null;
6439
+ const originalXhrSetRequestHeader = OriginalXHR ? XMLHttpRequest.prototype.setRequestHeader : null;
6481
6440
  let activeOptions = options;
6482
6441
  let fetchWrapper;
6483
6442
  globalThis.fetch = fetchWrapper = async function mushiFetchInterceptor(input, init) {
@@ -6486,6 +6445,7 @@ function createNetworkCapture(options = {}) {
6486
6445
  const url = getRequestUrl(input);
6487
6446
  const internalKind = getInternalRequestKind(input, init);
6488
6447
  const shouldRecord = !internalKind && !shouldIgnoreMushiUrl(url, activeOptions);
6448
+ const correlationId = shouldRecord ? generateCorrelationId() : void 0;
6489
6449
  let traceId;
6490
6450
  let patchedInit = init;
6491
6451
  const tp = activeOptions.tracePropagation;
@@ -6499,6 +6459,7 @@ function createNetworkCapture(options = {}) {
6499
6459
  }
6500
6460
  patchedInit = { ...init, headers: existingHeaders };
6501
6461
  }
6462
+ if (correlationId) _activeCorrelationStack.push(correlationId);
6502
6463
  try {
6503
6464
  const response = await originalFetch.call(globalThis, input, patchedInit);
6504
6465
  if (shouldRecord) {
@@ -6508,7 +6469,9 @@ function createNetworkCapture(options = {}) {
6508
6469
  status: response.status,
6509
6470
  duration: Date.now() - startTime,
6510
6471
  timestamp: startTime,
6511
- ...traceId ? { traceId } : {}
6472
+ captureMethod: "fetch",
6473
+ ...traceId ? { traceId } : {},
6474
+ ...correlationId ? { correlationId } : {}
6512
6475
  });
6513
6476
  }
6514
6477
  return response;
@@ -6521,15 +6484,99 @@ function createNetworkCapture(options = {}) {
6521
6484
  duration: Date.now() - startTime,
6522
6485
  timestamp: startTime,
6523
6486
  error: error instanceof Error ? error.message : "Network error",
6524
- ...traceId ? { traceId } : {}
6487
+ captureMethod: "fetch",
6488
+ ...traceId ? { traceId } : {},
6489
+ ...correlationId ? { correlationId } : {}
6525
6490
  });
6526
6491
  }
6527
6492
  throw error;
6493
+ } finally {
6494
+ if (correlationId) {
6495
+ const idx = _activeCorrelationStack.lastIndexOf(correlationId);
6496
+ if (idx !== -1) _activeCorrelationStack.splice(idx, 1);
6497
+ }
6528
6498
  }
6529
6499
  };
6500
+ const xhrStateMap = typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : null;
6501
+ if (OriginalXHR && originalXhrOpen && originalXhrSend && originalXhrSetRequestHeader && xhrStateMap) {
6502
+ const _originalOpen = originalXhrOpen;
6503
+ XMLHttpRequest.prototype.open = function mushiXhrOpen(...args) {
6504
+ const [method, url] = args;
6505
+ const urlStr = typeof url === "string" ? url : String(url);
6506
+ const shouldRecord = !shouldIgnoreMushiUrl(urlStr, activeOptions);
6507
+ const correlationId = shouldRecord ? generateCorrelationId() : void 0;
6508
+ let traceId;
6509
+ let storedTraceparent;
6510
+ const tp = activeOptions.tracePropagation;
6511
+ if (shouldRecord && tp?.enabled && tp.corsUrls?.length && matchesCorsUrls(urlStr, tp.corsUrls)) {
6512
+ const generated = generateTraceparent();
6513
+ traceId = generated.traceId;
6514
+ storedTraceparent = generated.traceparent;
6515
+ }
6516
+ const _prevXhrState = xhrStateMap.get(this);
6517
+ if (_prevXhrState?._listener) {
6518
+ this.removeEventListener("readystatechange", _prevXhrState._listener);
6519
+ }
6520
+ xhrStateMap.set(this, {
6521
+ method: String(method).toUpperCase(),
6522
+ url: truncateUrl(urlStr),
6523
+ startTime: 0,
6524
+ // set in .send()
6525
+ shouldRecord,
6526
+ ...traceId ? { traceId } : {},
6527
+ ...correlationId ? { correlationId } : {},
6528
+ // Attach the traceparent string as an extra prop for injection in .send().
6529
+ ...storedTraceparent ? { _traceparent: storedTraceparent } : {}
6530
+ });
6531
+ _originalOpen.apply(this, args);
6532
+ };
6533
+ XMLHttpRequest.prototype.send = function mushiXhrSend(body) {
6534
+ const state = xhrStateMap.get(this);
6535
+ if (state) {
6536
+ state.startTime = Date.now();
6537
+ const xhrTraceparent = state._traceparent;
6538
+ if (xhrTraceparent) {
6539
+ originalXhrSetRequestHeader.call(this, "traceparent", xhrTraceparent);
6540
+ if (activeOptions.sessionId) {
6541
+ originalXhrSetRequestHeader.call(this, "x-mushi-session", activeOptions.sessionId);
6542
+ }
6543
+ }
6544
+ if (state.correlationId) _activeCorrelationStack.push(state.correlationId);
6545
+ const _readystateHandler = () => {
6546
+ if (this.readyState !== 4) return;
6547
+ if (state.shouldRecord) {
6548
+ const duration = Date.now() - state.startTime;
6549
+ const entry = {
6550
+ method: state.method,
6551
+ url: state.url,
6552
+ status: this.status,
6553
+ duration,
6554
+ timestamp: state.startTime,
6555
+ captureMethod: "xhr",
6556
+ ...state.traceId ? { traceId: state.traceId } : {},
6557
+ ...state.correlationId ? { correlationId: state.correlationId } : {}
6558
+ };
6559
+ if (this.status === 0) {
6560
+ entry.error = "XHR network error or aborted";
6561
+ }
6562
+ addEntry(entry);
6563
+ }
6564
+ if (state.correlationId) {
6565
+ const idx = _activeCorrelationStack.lastIndexOf(state.correlationId);
6566
+ if (idx !== -1) _activeCorrelationStack.splice(idx, 1);
6567
+ }
6568
+ };
6569
+ state._listener = _readystateHandler;
6570
+ this.addEventListener("readystatechange", _readystateHandler);
6571
+ }
6572
+ originalXhrSend.call(this, body);
6573
+ };
6574
+ }
6575
+ const xhrOpenWrapper = OriginalXHR ? XMLHttpRequest.prototype.open : null;
6576
+ const xhrSendWrapper = OriginalXHR ? XMLHttpRequest.prototype.send : null;
6530
6577
  function addEntry(entry) {
6531
6578
  entries.push(entry);
6532
- if (entries.length > MAX_ENTRIES2) {
6579
+ if (entries.length > MAX_ENTRIES) {
6533
6580
  entries.shift();
6534
6581
  }
6535
6582
  }
@@ -6547,22 +6594,86 @@ function createNetworkCapture(options = {}) {
6547
6594
  if (globalThis.fetch === fetchWrapper) {
6548
6595
  globalThis.fetch = originalFetch;
6549
6596
  }
6597
+ if (OriginalXHR && originalXhrOpen && originalXhrSend) {
6598
+ if (xhrOpenWrapper && XMLHttpRequest.prototype.open === xhrOpenWrapper) {
6599
+ XMLHttpRequest.prototype.open = originalXhrOpen;
6600
+ }
6601
+ if (xhrSendWrapper && XMLHttpRequest.prototype.send === xhrSendWrapper) {
6602
+ XMLHttpRequest.prototype.send = originalXhrSend;
6603
+ }
6604
+ }
6550
6605
  }
6551
6606
  };
6552
6607
  }
6553
6608
  function truncateUrl(url) {
6609
+ const scrubbed = core.scrubUrl(url);
6554
6610
  try {
6555
- const parsed = new URL(url);
6611
+ const parsed = new URL(scrubbed);
6556
6612
  const path = parsed.pathname + parsed.search;
6557
6613
  if (path.length > 200) {
6558
6614
  return parsed.origin + path.slice(0, 200) + "...";
6559
6615
  }
6560
6616
  return parsed.origin + path;
6561
6617
  } catch {
6562
- return url.slice(0, 200);
6618
+ return scrubbed.slice(0, 200);
6563
6619
  }
6564
6620
  }
6565
6621
 
6622
+ // src/capture/console.ts
6623
+ var MAX_ENTRIES2 = 50;
6624
+ var MAX_MESSAGE_LENGTH = 500;
6625
+ function createConsoleCapture() {
6626
+ const entries = [];
6627
+ const originals = {};
6628
+ const wrappers = {};
6629
+ const levels = ["log", "warn", "error", "info", "debug"];
6630
+ for (const level of levels) {
6631
+ const original = console[level];
6632
+ originals[level] = original;
6633
+ const wrapper = (...args) => {
6634
+ const message = args.map((arg) => {
6635
+ try {
6636
+ return typeof arg === "string" ? arg : JSON.stringify(arg);
6637
+ } catch {
6638
+ return String(arg);
6639
+ }
6640
+ }).join(" ").slice(0, MAX_MESSAGE_LENGTH);
6641
+ const correlationId = getActiveCorrelationId();
6642
+ const entry = {
6643
+ level,
6644
+ message,
6645
+ timestamp: Date.now(),
6646
+ ...correlationId ? { correlationId } : {}
6647
+ };
6648
+ if (level === "error" && args[0] instanceof Error) {
6649
+ entry.stack = args[0].stack?.slice(0, 1e3);
6650
+ }
6651
+ entries.push(entry);
6652
+ if (entries.length > MAX_ENTRIES2) {
6653
+ entries.shift();
6654
+ }
6655
+ original.call(console, ...args);
6656
+ };
6657
+ wrappers[level] = wrapper;
6658
+ console[level] = wrapper;
6659
+ }
6660
+ return {
6661
+ getEntries() {
6662
+ return [...entries];
6663
+ },
6664
+ clear() {
6665
+ entries.length = 0;
6666
+ },
6667
+ destroy() {
6668
+ for (const level of levels) {
6669
+ if (originals[level] && console[level] === wrappers[level]) {
6670
+ console[level] = originals[level];
6671
+ }
6672
+ }
6673
+ }
6674
+ };
6675
+ }
6676
+
6566
6677
  // src/capture/screenshot.ts
6567
6678
  function createScreenshotCapture(options = {}) {
6568
6679
  let activeOptions = options;
@@ -7096,8 +7207,6 @@ function createElementSelector() {
7096
7207
  }
7097
7208
  return { activate, deactivate, isActive: () => active };
7098
7209
  }
7099
-
7100
- // src/capture/timeline.ts
7101
7210
  var MAX_TIMELINE_ENTRIES = 120;
7102
7211
  function createTimelineCapture() {
7103
7212
  const entries = [];
@@ -7114,8 +7223,11 @@ function createTimelineCapture() {
7114
7223
  kind: "route",
7115
7224
  payload: {
7116
7225
  source,
7117
- route: `${location.pathname}${location.search}${location.hash}`,
7118
- href: location.href
7226
+ // Query VALUES are a PII channel (`?token=…`, `?email=…`) — scrub
7227
+ // them at capture, both in the search string and inside hash-router
7228
+ // fragments (`#/path?query`). Keys and paths are preserved.
7229
+ route: core.scrubUrl(`${location.pathname}${location.search}${location.hash}`),
7230
+ href: core.scrubUrl(location.href)
7119
7231
  }
7120
7232
  });
7121
7233
  }
@@ -7202,6 +7314,18 @@ function normalizeSegment(seg) {
7202
7314
  if (SLUG_HASHY_RE.test(seg) && /\d/.test(seg)) return "[id]";
7203
7315
  return seg;
7204
7316
  }
7317
+ function deriveRoute(pathname, hash, templates) {
7318
+ if (hash.startsWith("#/")) {
7319
+ const raw = hash.slice(1);
7320
+ const qIdx = raw.indexOf("?");
7321
+ const hashPath = qIdx === -1 ? raw : raw.slice(0, qIdx);
7322
+ const hashTemplates = templates?.map(
7323
+ (t) => t.startsWith("/#/") ? t.slice(2) : t
7324
+ );
7325
+ return "/#" + normalizeRoute(hashPath, hashTemplates);
7326
+ }
7327
+ return normalizeRoute(pathname, templates);
7328
+ }
7205
7329
  function normalizeRoute(pathname, templates) {
7206
7330
  const clean = pathname.length > 1 && pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
7207
7331
  if (templates?.length) {
@@ -7245,9 +7369,14 @@ function readTestids() {
7245
7369
  function readQueryParamKeys() {
7246
7370
  if (typeof window === "undefined") return [];
7247
7371
  try {
7248
- const params = new URLSearchParams(window.location.search);
7249
7372
  const out = /* @__PURE__ */ new Set();
7250
- params.forEach((_, key) => out.add(key));
7373
+ const collect = (qs) => {
7374
+ new URLSearchParams(qs).forEach((_, key) => out.add(key));
7375
+ };
7376
+ collect(window.location.search);
7377
+ const hash = window.location.hash;
7378
+ const qIdx = hash.indexOf("?");
7379
+ if (hash.startsWith("#/") && qIdx !== -1) collect(hash.slice(qIdx + 1));
7251
7380
  return Array.from(out).sort();
7252
7381
  } catch {
7253
7382
  return [];
@@ -7294,7 +7423,11 @@ function createDiscoveryCapture(opts) {
7294
7423
  let pendingTimer = null;
7295
7424
  async function emitForCurrent() {
7296
7425
  if (typeof window === "undefined") return;
7297
- const route = normalizeRoute(window.location.pathname, config.routeTemplates);
7426
+ const route = deriveRoute(
7427
+ window.location.pathname,
7428
+ window.location.hash,
7429
+ config.routeTemplates
7430
+ );
7298
7431
  const now = Date.now();
7299
7432
  const last = lastEmittedAt.get(route) ?? 0;
7300
7433
  if (now - last < throttleMs) return;
@@ -7326,7 +7459,8 @@ function createDiscoveryCapture(opts) {
7326
7459
  }
7327
7460
  function onMaybeNavigation() {
7328
7461
  if (typeof window === "undefined") return;
7329
- const path = window.location.pathname + window.location.search;
7462
+ const hashPart = window.location.hash.startsWith("#/") ? window.location.hash : "";
7463
+ const path = window.location.pathname + window.location.search + hashPart;
7330
7464
  if (path === lastPath) return;
7331
7465
  lastPath = path;
7332
7466
  scheduleEmit();
@@ -7343,10 +7477,12 @@ function createDiscoveryCapture(opts) {
7343
7477
  onReplace: onNav,
7344
7478
  onPop: onNav
7345
7479
  });
7480
+ window.addEventListener("hashchange", onNav);
7346
7481
  scheduleEmit();
7347
7482
  return {
7348
7483
  destroy() {
7349
7484
  unsubHistory();
7485
+ window.removeEventListener("hashchange", onNav);
7350
7486
  if (pendingTimer) {
7351
7487
  clearTimeout(pendingTimer);
7352
7488
  pendingTimer = null;
@@ -8165,6 +8301,14 @@ function createInstance(config) {
8165
8301
  return next;
8166
8302
  });
8167
8303
  }
8304
+ function scrubConsoleForWire(logs) {
8305
+ if (!logs) return logs;
8306
+ return logs.map((entry) => ({
8307
+ ...entry,
8308
+ message: piiScrubber.scrub(entry.message),
8309
+ ...entry.stack ? { stack: piiScrubber.scrub(entry.stack) } : {}
8310
+ }));
8311
+ }
8168
8312
  function scrubTagsForWire(tags) {
8169
8313
  if (!tags) return void 0;
8170
8314
  const out = {};
@@ -8313,7 +8457,9 @@ function createInstance(config) {
8313
8457
  discoveryCap = null;
8314
8458
  }
8315
8459
  const replayMode = activeConfig.capture?.replay ?? "off";
8316
- if (replayMode === "rrweb" || replayMode === "lite") {
8460
+ const replaySampleRate = activeConfig.replaySampleRate ?? 1;
8461
+ const replaySampled = replaySampleRate >= 1 || Math.random() < replaySampleRate;
8462
+ if ((replayMode === "rrweb" || replayMode === "lite") && replaySampled) {
8317
8463
  const generation = ++replayGeneration;
8318
8464
  void createReplayCapture({
8319
8465
  redactSelectors: activeConfig.privacy?.redactSelectors
@@ -8852,6 +8998,13 @@ function createInstance(config) {
8852
8998
  });
8853
8999
  }
8854
9000
  }
9001
+ const isAutomatic = pendingProactiveTrigger !== null;
9002
+ if (isAutomatic && config.sampleRate !== void 0 && config.sampleRate < 1) {
9003
+ if (config.sampleRate <= 0 || Math.random() > config.sampleRate) {
9004
+ log.debug("Report dropped by sampleRate", { sampleRate: config.sampleRate, trigger: pendingProactiveTrigger });
9005
+ return void 0;
9006
+ }
9007
+ }
8855
9008
  if (!rateLimiter.tryConsume()) {
8856
9009
  log.warn("Report throttled \u2014 rate limit exceeded");
8857
9010
  return void 0;
@@ -8859,7 +9012,7 @@ function createInstance(config) {
8859
9012
  const scrubbedDescription = piiScrubber.scrub(preFilter.truncate(description));
8860
9013
  const sentryCtx = config.sentry ? captureSentryContext(config.sentry) : void 0;
8861
9014
  const fingerprintHash = await core.getDeviceFingerprintHash().catch(() => null);
8862
- const consoleLogs = activeConfig.capture?.console === false ? void 0 : consoleCap?.getEntries();
9015
+ const consoleLogs = activeConfig.capture?.console === false ? void 0 : scrubConsoleForWire(consoleCap?.getEntries());
8863
9016
  const networkLogs = activeConfig.capture?.network === false ? void 0 : networkCap?.getEntries();
8864
9017
  const reportBreadcrumbs = scrubBreadcrumbsForWire(breadcrumbs.getAll());
8865
9018
  const stickyTagSnapshot = scrubTagsForWire(
@@ -8937,10 +9090,11 @@ function createInstance(config) {
8937
9090
  config.integrations.custom(builder);
8938
9091
  }
8939
9092
  let finalReport = report;
8940
- if (config.beforeSendFeedback) {
9093
+ const sendHook = config.beforeSend ?? config.beforeSendFeedback;
9094
+ if (sendHook) {
8941
9095
  try {
8942
9096
  const hookResult = await Promise.race([
8943
- Promise.resolve(config.beforeSendFeedback(report)),
9097
+ Promise.resolve(sendHook(report)),
8944
9098
  // 2s timeout — async hooks must not block the user's "submit"
8945
9099
  // for longer than the network would. Falls back to original.
8946
9100
  new Promise(
@@ -8948,12 +9102,12 @@ function createInstance(config) {
8948
9102
  )
8949
9103
  ]);
8950
9104
  if (hookResult === null) {
8951
- log.info("Report dropped by beforeSendFeedback hook", { reportId: report.id });
9105
+ log.info("Report dropped by beforeSend hook", { reportId: report.id });
8952
9106
  return;
8953
9107
  }
8954
9108
  finalReport = hookResult;
8955
9109
  } catch (err) {
8956
- log.warn("beforeSendFeedback hook threw \u2014 sending unmodified report", {
9110
+ log.warn("beforeSend hook threw \u2014 sending unmodified report", {
8957
9111
  error: err instanceof Error ? err.message : String(err)
8958
9112
  });
8959
9113
  }