@bidspark/analytics 0.44.0 → 0.45.2

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
@@ -42,14 +42,15 @@ __export(src_exports, {
42
42
  getPrebidEventKey: () => getPrebidEventKey,
43
43
  idToBytes: () => idToBytes,
44
44
  idToString: () => idToString,
45
+ isAutomatedClient: () => isAutomatedClient,
45
46
  isSessionActive: () => isSessionActive,
46
47
  isTrustedEndpoint: () => isTrustedEndpoint,
47
48
  isVisitorSampled: () => isVisitorSampled,
48
49
  normalizeLogLevel: () => normalizeLogLevel,
49
50
  normalizeSampleRate: () => normalizeSampleRate,
50
51
  onSessionResume: () => onSessionResume,
52
+ parseBidDimensions: () => parseBidDimensions,
51
53
  registerPrebidAnalytics: () => registerPrebidAnalytics,
52
- resetTcfListener: () => resetTcfListener,
53
54
  sendEvents: () => sendEvents,
54
55
  sessionStarted: () => sessionStarted
55
56
  });
@@ -1086,6 +1087,33 @@ function isVisitorSampled(visitorKey, sampleRate) {
1086
1087
  }
1087
1088
  return (hash >>> 0) / 4294967296 < rate;
1088
1089
  }
1090
+ var AUTOMATED_UA_RE = /headless|phantomjs|slimerjs|puppeteer|playwright/i;
1091
+ var DESKTOP_CHROME_UA_RE = /Chrome\/\d+/i;
1092
+ var NON_DESKTOP_CHROME_UA_RE = /Mobile|Android|iPhone|iPad|iPod|CriOS|FxiOS|Edg\/|OPR\/|SamsungBrowser/i;
1093
+ function isAutomatedClient() {
1094
+ const g = typeof globalThis !== "undefined" ? globalThis : void 0;
1095
+ const nav = g && "navigator" in g ? g.navigator : void 0;
1096
+ if (!nav) return false;
1097
+ if (nav.webdriver === true) return true;
1098
+ const ua = typeof nav.userAgent === "string" ? nav.userAgent : "";
1099
+ if (AUTOMATED_UA_RE.test(ua)) return true;
1100
+ const win = g && "window" in g ? g.window : g;
1101
+ let weakSignals = 0;
1102
+ if (win && typeof win.outerWidth === "number" && typeof win.outerHeight === "number" && win.outerWidth === 0 && win.outerHeight === 0) {
1103
+ weakSignals++;
1104
+ }
1105
+ if (Array.isArray(nav.languages) && nav.languages.length === 0) {
1106
+ weakSignals++;
1107
+ }
1108
+ if (DESKTOP_CHROME_UA_RE.test(ua) && !NON_DESKTOP_CHROME_UA_RE.test(ua)) {
1109
+ if (win && !win.chrome) weakSignals++;
1110
+ const plugins = nav.plugins;
1111
+ if (plugins !== void 0 && plugins !== null && plugins.length === 0) {
1112
+ weakSignals++;
1113
+ }
1114
+ }
1115
+ return weakSignals >= 2;
1116
+ }
1089
1117
 
1090
1118
  // ../../protogen/usage_event.ts
1091
1119
  var usage_event_exports = {};
@@ -1252,7 +1280,7 @@ function sendEvents(opts) {
1252
1280
  bidderOutcomes: []
1253
1281
  }));
1254
1282
  const nav = g && "navigator" in g ? g.navigator : void 0;
1255
- const automated = Boolean(nav && nav.webdriver === true);
1283
+ const automated = isAutomatedClient();
1256
1284
  const batch = {
1257
1285
  propertyId: idToBytes(opts.propertyId),
1258
1286
  pageviewId: idToBytes(pageviewId),
@@ -1556,6 +1584,15 @@ function sameEndpointOrigin(a, b) {
1556
1584
  return false;
1557
1585
  }
1558
1586
  }
1587
+ function normalizePageUrl(raw) {
1588
+ if (!raw) return "";
1589
+ try {
1590
+ const u = new URL(raw);
1591
+ return u.origin + u.pathname;
1592
+ } catch {
1593
+ return raw;
1594
+ }
1595
+ }
1559
1596
  var SESSION_PERSIST_INTERVAL_MS = 60 * 1e3;
1560
1597
  var persistedSessionTs = 0;
1561
1598
  var ACTIVITY_EVENTS = ["pointerdown", "pointermove", "keydown", "scroll", "wheel", "touchstart"];
@@ -1665,7 +1702,7 @@ function getOrCreateUserId() {
1665
1702
  if (storageAllowed && typeof localStorage !== "undefined") {
1666
1703
  const stored = localStorage.getItem(USER_ID_KEY);
1667
1704
  if (stored) return stored;
1668
- const newId = generateUUID2();
1705
+ const newId = inMemorySessionId || generateUUID2();
1669
1706
  localStorage.setItem(USER_ID_KEY, newId);
1670
1707
  return newId;
1671
1708
  }
@@ -1699,6 +1736,16 @@ function tcDataToConsentRecord(tcData) {
1699
1736
  purposesConsented: purposes
1700
1737
  };
1701
1738
  }
1739
+ function resolveTcfStorageAllowed(tcData, success) {
1740
+ if (!success || !tcData) return void 0;
1741
+ if (tcData.eventStatus === "cmpuishown" && !tcData.tcString) return false;
1742
+ const allowed = storageAllowedBy(tcDataToConsentRecord(tcData));
1743
+ if (!allowed) {
1744
+ clearStoredSession();
1745
+ clearStoredUserId();
1746
+ }
1747
+ return allowed;
1748
+ }
1702
1749
  function probeTcfStorageAllowed() {
1703
1750
  if (typeof window === "undefined") return void 0;
1704
1751
  const win = window;
@@ -1706,27 +1753,22 @@ function probeTcfStorageAllowed() {
1706
1753
  let allowed = void 0;
1707
1754
  try {
1708
1755
  win.__tcfapi("getTCData", 2, (tcData, success) => {
1709
- if (success && tcData) {
1710
- allowed = storageAllowedBy(tcDataToConsentRecord(tcData));
1711
- }
1756
+ allowed = resolveTcfStorageAllowed(tcData, success);
1712
1757
  });
1713
1758
  } catch {
1714
1759
  }
1715
1760
  return allowed !== void 0 ? allowed : false;
1716
1761
  }
1717
- var tcfListenerAttached = false;
1718
- function resetTcfListener() {
1719
- tcfListenerAttached = false;
1720
- }
1762
+ var attachedTcfApi = null;
1721
1763
  function attachTcfListener() {
1722
- if (tcfListenerAttached || typeof window === "undefined") return;
1764
+ if (typeof window === "undefined") return;
1723
1765
  const win = window;
1724
- if (typeof win.__tcfapi !== "function") return;
1725
- tcfListenerAttached = true;
1766
+ if (typeof win.__tcfapi !== "function" || attachedTcfApi === win.__tcfapi) return;
1767
+ attachedTcfApi = win.__tcfapi;
1726
1768
  try {
1727
1769
  win.__tcfapi("addEventListener", 2, (tcData, success) => {
1728
- if (!success || !tcData) return;
1729
- BidsparkPrebidAnalytics.setStorageAllowed(storageAllowedBy(tcDataToConsentRecord(tcData)));
1770
+ const allowed = resolveTcfStorageAllowed(tcData, success);
1771
+ if (allowed !== void 0) BidsparkPrebidAnalytics.setStorageAllowed(allowed);
1730
1772
  });
1731
1773
  } catch {
1732
1774
  }
@@ -1817,19 +1859,31 @@ var PrebidEventDeduper = class {
1817
1859
  }
1818
1860
  };
1819
1861
  function parseBidDimensions(bid) {
1820
- if (Number.isFinite(bid?.width) && Number.isFinite(bid?.height)) {
1862
+ if (Number.isFinite(bid?.width) && bid.width > 0 && Number.isFinite(bid?.height) && bid.height > 0) {
1821
1863
  return { width: bid.width, height: bid.height };
1822
1864
  }
1865
+ if (Number.isFinite(bid?.w) && bid.w > 0 && Number.isFinite(bid?.h) && bid.h > 0) {
1866
+ return { width: bid.w, height: bid.h };
1867
+ }
1868
+ if (Number.isFinite(bid?.playerWidth) && bid.playerWidth > 0 && Number.isFinite(bid?.playerHeight) && bid.playerHeight > 0) {
1869
+ return { width: bid.playerWidth, height: bid.playerHeight };
1870
+ }
1871
+ const ps = bid?.mediaTypes?.video?.playerSize;
1872
+ if (Array.isArray(ps) && ps.length > 0) {
1873
+ const tuple = Array.isArray(ps[0]) ? ps[0] : ps;
1874
+ if (Number.isFinite(tuple[0]) && tuple[0] > 0 && Number.isFinite(tuple[1]) && tuple[1] > 0) {
1875
+ return { width: tuple[0], height: tuple[1] };
1876
+ }
1877
+ }
1823
1878
  if (typeof bid?.size === "string") {
1824
1879
  const match = bid.size.match(/^(\d+)x(\d+)$/);
1825
1880
  if (match) {
1826
1881
  return { width: Number(match[1]), height: Number(match[2]) };
1827
1882
  }
1828
1883
  }
1829
- return {
1830
- width: Number.isFinite(bid?.width) ? bid.width : 0,
1831
- height: Number.isFinite(bid?.height) ? bid.height : 0
1832
- };
1884
+ const w = Number.isFinite(bid?.width) ? bid.width : Number.isFinite(bid?.w) ? bid.w : Number.isFinite(bid?.playerWidth) ? bid.playerWidth : 0;
1885
+ const h = Number.isFinite(bid?.height) ? bid.height : Number.isFinite(bid?.h) ? bid.h : Number.isFinite(bid?.playerHeight) ? bid.playerHeight : 0;
1886
+ return { width: w, height: h };
1833
1887
  }
1834
1888
  function resolveBidPricing(bid, fallback) {
1835
1889
  if (Number.isFinite(bid?.cpm)) {
@@ -1874,14 +1928,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1874
1928
  storageAllowed = allowed;
1875
1929
  persistedSessionTs = 0;
1876
1930
  for (const inst of _BidsparkPrebidAnalytics.allInstances) {
1877
- inst.config.storageAllowed = allowed;
1878
- if (!allowed) {
1879
- inst.config.userId = "";
1880
- inst.config.visitorId = inst.config.visitorId || inst.config.pageviewId;
1881
- } else if (!inst.config.userId) {
1882
- inst.config.userId = getOrCreateUserId();
1883
- inst.config.visitorId = inst.config.visitorId || inst.config.userId || inst.config.pageviewId;
1884
- }
1931
+ inst.applyStorageAllowed(allowed);
1885
1932
  }
1886
1933
  }
1887
1934
  static isStorageAllowed() {
@@ -1932,6 +1979,11 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1932
1979
  logger;
1933
1980
  // True when managing session lifecycle internally; false if caller supplied fixed sessionId.
1934
1981
  managesSessionId;
1982
+ configuredUserId;
1983
+ // True when visitor sampling key is derived internally from storage/session rather than caller config.
1984
+ managesVisitorId;
1985
+ // True once visitorId is settled (storage read, caller-supplied, or first batch drained).
1986
+ visitorKeyLocked;
1935
1987
  constructor(config) {
1936
1988
  const tcfStorage = probeTcfStorageAllowed();
1937
1989
  if (typeof window !== "undefined" && typeof window.__tcfapi === "function") {
@@ -1945,32 +1997,33 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1945
1997
  const requestedEndpoint = config.endpoint || "";
1946
1998
  const endpoint = !requestedEndpoint || isTrustedEndpoint(requestedEndpoint) ? requestedEndpoint : "";
1947
1999
  const pageviewId = config.pageviewId || generateUUID2();
2000
+ recordActivity();
2001
+ this.managesSessionId = !config.sessionId;
2002
+ const sessionId = config.sessionId || getOrCreateSessionId();
2003
+ this.configuredUserId = config.userId || "";
1948
2004
  let initialUserId = "";
1949
- let initialVisitorId = "";
1950
2005
  if (isStorageOn) {
1951
- initialUserId = config.userId || getOrCreateUserId();
1952
- if (config.userId) {
2006
+ initialUserId = this.configuredUserId || getOrCreateUserId();
2007
+ if (this.configuredUserId) {
1953
2008
  try {
1954
2009
  if (typeof localStorage !== "undefined") {
1955
- localStorage.setItem(USER_ID_KEY, config.userId);
2010
+ localStorage.setItem(USER_ID_KEY, this.configuredUserId);
1956
2011
  }
1957
2012
  } catch {
1958
2013
  }
1959
2014
  }
1960
- initialVisitorId = config.visitorId || initialUserId || pageviewId;
1961
- } else {
1962
- initialUserId = "";
1963
- initialVisitorId = config.visitorId || pageviewId;
1964
2015
  }
2016
+ this.managesVisitorId = !config.visitorId && !config.userId && !config.sessionId;
2017
+ this.visitorKeyLocked = isStorageOn || !this.managesVisitorId;
1965
2018
  const usageEndpoint = config.usageEndpoint || "";
1966
2019
  this.config = {
1967
2020
  endpoint,
1968
2021
  usageEndpoint,
1969
2022
  propertyId: config.propertyId || "",
1970
2023
  pageviewId,
1971
- sessionId: config.sessionId || "",
2024
+ sessionId,
1972
2025
  userId: initialUserId,
1973
- visitorId: initialVisitorId,
2026
+ visitorId: config.visitorId || this.configuredUserId || initialUserId || sessionId,
1974
2027
  deviceType: config.deviceType || "desktop",
1975
2028
  country: config.country || "",
1976
2029
  region: config.region || "",
@@ -1990,9 +2043,6 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1990
2043
  prefix: "[analytics]",
1991
2044
  logLevel: this.config.logLevel
1992
2045
  });
1993
- recordActivity();
1994
- this.managesSessionId = !config.sessionId;
1995
- if (this.managesSessionId) this.config.sessionId = getOrCreateSessionId();
1996
2046
  if (requestedEndpoint && !endpoint) {
1997
2047
  this.log(
1998
2048
  "ERROR",
@@ -2005,6 +2055,31 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2005
2055
  };
2006
2056
  this.boundVisibilityChange = () => this.handleVisibilityChange();
2007
2057
  }
2058
+ applyStorageAllowed(allowed) {
2059
+ this.config.storageAllowed = allowed;
2060
+ if (!allowed) {
2061
+ this.config.userId = "";
2062
+ return;
2063
+ }
2064
+ this.syncSessionId();
2065
+ if (!this.config.userId) {
2066
+ this.config.userId = this.configuredUserId || getOrCreateUserId();
2067
+ }
2068
+ if (this.managesVisitorId && !this.visitorKeyLocked) {
2069
+ this.config.visitorId = this.config.userId || this.config.sessionId;
2070
+ this.visitorKeyLocked = true;
2071
+ if (!this.isSampledVisitor()) {
2072
+ this.queue = [];
2073
+ if (this.revenueFlushTimer) {
2074
+ clearTimeout(this.revenueFlushTimer);
2075
+ this.revenueFlushTimer = null;
2076
+ }
2077
+ }
2078
+ }
2079
+ if (this.isEnabled) {
2080
+ this.resendPersistedBatches();
2081
+ }
2082
+ }
2008
2083
  setLogLevel(level) {
2009
2084
  const norm = normalizeLogLevel(level);
2010
2085
  this.config.logLevel = norm;
@@ -2018,6 +2093,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2018
2093
  if (this.isEnabled) return;
2019
2094
  this.isEnabled = true;
2020
2095
  _BidsparkPrebidAnalytics.activeInstances.add(this);
2096
+ _BidsparkPrebidAnalytics.allInstances.add(this);
2021
2097
  this.logger.setLevel(this.config.logLevel);
2022
2098
  if (this.config.attachPbjsListeners && this.config.usageEndpoint && !this.usageRecorder) {
2023
2099
  this.usageRecorder = new UsageRecorder({
@@ -2047,12 +2123,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2047
2123
  this.cmpDetach = this.attachCmp();
2048
2124
  if (typeof window !== "undefined") {
2049
2125
  if (!this.pageUrl) {
2050
- try {
2051
- const u = new URL(window.location.href);
2052
- this.pageUrl = u.origin + u.pathname;
2053
- } catch {
2054
- this.pageUrl = window.location.href;
2055
- }
2126
+ this.pageUrl = normalizePageUrl(window.location.href);
2056
2127
  }
2057
2128
  window.addEventListener("pagehide", this.boundFlushBeacon);
2058
2129
  if (typeof document !== "undefined") {
@@ -2670,7 +2741,15 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2670
2741
  hasImpressionEmitted(slotId, refreshIndex, auctionId, creativeId, adId) {
2671
2742
  const rIndex = refreshIndex ?? this.slotRefreshIndices.get(slotId) ?? 0;
2672
2743
  const baseSlotKey = `${escapeKeyPart(slotId)}:${rIndex}`;
2744
+ if (auctionId ? this.slotEmittedImpressionKeys.has(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}`) : this.slotEmittedImpressionKeys.has(baseSlotKey)) {
2745
+ return true;
2746
+ }
2673
2747
  if (adId) {
2748
+ if (auctionId && this.slotEmittedImpressionKeys.has(
2749
+ `${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:render`
2750
+ ) || this.slotEmittedImpressionKeys.has(`${baseSlotKey}:render`)) {
2751
+ return true;
2752
+ }
2674
2753
  if (auctionId) {
2675
2754
  if (this.slotEmittedImpressionKeys.has(
2676
2755
  `${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:ad:${escapeKeyPart(adId)}`
@@ -2693,6 +2772,11 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2693
2772
  }
2694
2773
  return false;
2695
2774
  }
2775
+ if (auctionId && this.slotEmittedImpressionKeys.has(
2776
+ `${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:ad-emitted`
2777
+ ) || this.slotEmittedImpressionKeys.has(`${baseSlotKey}:ad-emitted`)) {
2778
+ return true;
2779
+ }
2696
2780
  if (creativeId) {
2697
2781
  if (auctionId) {
2698
2782
  return this.slotEmittedImpressionKeys.has(
@@ -2701,10 +2785,10 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2701
2785
  }
2702
2786
  return this.slotEmittedImpressionKeys.has(`${baseSlotKey}:${escapeKeyPart(creativeId)}`);
2703
2787
  }
2704
- if (auctionId) {
2705
- return this.slotEmittedImpressionKeys.has(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}`);
2788
+ if (auctionId && this.slotEmittedImpressionKeys.has(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:any`)) {
2789
+ return true;
2706
2790
  }
2707
- return this.slotEmittedImpressionKeys.has(baseSlotKey);
2791
+ return false;
2708
2792
  }
2709
2793
  markImpressionEmitted(slotId, refreshIndex, auctionId, creativeId, adId) {
2710
2794
  const baseSlotKey = `${escapeKeyPart(slotId)}:${refreshIndex}`;
@@ -2712,10 +2796,13 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2712
2796
  if (hasIdentity) {
2713
2797
  if (adId) {
2714
2798
  this.addImpressionKey(`${baseSlotKey}:ad:${escapeKeyPart(adId)}`);
2799
+ this.addImpressionKey(`${baseSlotKey}:ad-emitted`);
2715
2800
  if (auctionId) {
2716
2801
  this.addImpressionKey(
2717
2802
  `${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:ad:${escapeKeyPart(adId)}`
2718
2803
  );
2804
+ this.addImpressionKey(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:any`);
2805
+ this.addImpressionKey(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:ad-emitted`);
2719
2806
  }
2720
2807
  }
2721
2808
  if (creativeId && creativeId !== adId) {
@@ -2724,15 +2811,21 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2724
2811
  this.addImpressionKey(
2725
2812
  `${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:${escapeKeyPart(creativeId)}`
2726
2813
  );
2814
+ this.addImpressionKey(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:any`);
2727
2815
  }
2728
2816
  }
2729
- if (auctionId) {
2730
- this.addImpressionKey(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}`);
2817
+ if (!adId) {
2818
+ this.addImpressionKey(`${baseSlotKey}:render`);
2819
+ if (auctionId) {
2820
+ this.addImpressionKey(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:render`);
2821
+ }
2731
2822
  }
2732
2823
  } else {
2733
2824
  this.addImpressionKey(baseSlotKey);
2825
+ this.addImpressionKey(`${baseSlotKey}:render`);
2734
2826
  if (auctionId) {
2735
2827
  this.addImpressionKey(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}`);
2828
+ this.addImpressionKey(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:render`);
2736
2829
  }
2737
2830
  }
2738
2831
  }
@@ -2759,8 +2852,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2759
2852
  ...parseBidDimensions(rawBid).width ? parseBidDimensions(rawBid) : cached?.bidTrace ? { width: cached.bidTrace.width, height: cached.bidTrace.height } : parseBidDimensions(rawBid),
2760
2853
  dealId: rawBid.dealId || cached?.bidTrace?.dealId || "",
2761
2854
  mediaType,
2762
- latencyMs: Number.isFinite(rawBid.timeToRespond) ? rawBid.timeToRespond : cached?.bidTrace?.latencyMs ?? 0,
2763
- advertiserDomain: rawBid.meta?.advertiserDomains?.[0] || cached?.bidTrace?.advertiserDomain || "",
2855
+ latencyMs: Number.isFinite(rawBid.timeToRespond) ? rawBid.timeToRespond : Number.isFinite(rawBid.latencyMs) ? rawBid.latencyMs : cached?.bidTrace?.latencyMs ?? 0,
2856
+ advertiserDomain: rawBid.advertiserDomain || rawBid.meta?.advertiserDomains?.[0] || (Array.isArray(rawBid.adomain) ? rawBid.adomain[0] : "") || cached?.bidTrace?.advertiserDomain || "",
2764
2857
  creativeId: rawBid.creativeId || cached?.bidTrace?.creativeId || ""
2765
2858
  };
2766
2859
  if (isDifferentAuction && targetSlot) {
@@ -2931,16 +3024,16 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2931
3024
  const handler = (evt) => {
2932
3025
  const detail = evt.detail;
2933
3026
  if (detail) {
2934
- this.recordConsent(detail);
2935
3027
  this.followConsent(detail);
3028
+ this.recordConsent(detail);
2936
3029
  }
2937
3030
  };
2938
3031
  document.addEventListener("ads:consent", handler);
2939
3032
  const win = typeof window !== "undefined" ? window : {};
2940
3033
  const existingRecord = win[this.config.alias]?.consent?.getRecord?.() || null;
2941
3034
  if (existingRecord) {
2942
- this.recordConsent(existingRecord);
2943
3035
  this.followConsent(existingRecord);
3036
+ this.recordConsent(existingRecord);
2944
3037
  }
2945
3038
  let detached = false;
2946
3039
  return () => {
@@ -2949,15 +3042,23 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2949
3042
  document.removeEventListener("ads:consent", handler);
2950
3043
  };
2951
3044
  }
2952
- /** Device storage follows the decision; a refusal also drops the stored session. */
3045
+ /** Device storage follows the decision; a refusal also drops stored session and user IDs. */
2953
3046
  followConsent(record) {
2954
3047
  const allowed = storageAllowedBy(record);
2955
- if (!allowed) clearStoredSession();
3048
+ if (!allowed) {
3049
+ clearStoredSession();
3050
+ clearStoredUserId();
3051
+ }
2956
3052
  _BidsparkPrebidAnalytics.setStorageAllowed(allowed);
2957
3053
  }
2958
3054
  setUserId(userId) {
3055
+ this.configuredUserId = userId;
2959
3056
  this.config.userId = userId;
2960
- if (userId) this.config.visitorId = userId;
3057
+ if (userId) {
3058
+ this.config.visitorId = userId;
3059
+ this.managesVisitorId = false;
3060
+ this.visitorKeyLocked = true;
3061
+ }
2961
3062
  if (this.config.storageAllowed && typeof localStorage !== "undefined") {
2962
3063
  try {
2963
3064
  if (userId) {
@@ -2971,6 +3072,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2971
3072
  }
2972
3073
  setVisitorId(visitorId) {
2973
3074
  this.config.visitorId = visitorId;
3075
+ this.managesVisitorId = !visitorId;
3076
+ if (visitorId) this.visitorKeyLocked = true;
2974
3077
  }
2975
3078
  setSampleRate(sampleRate) {
2976
3079
  this.config.sampleRate = normalizeSampleRate(sampleRate);
@@ -2980,7 +3083,32 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2980
3083
  this.managesSessionId = !sessionId;
2981
3084
  if (this.managesSessionId) this.config.sessionId = getOrCreateSessionId();
2982
3085
  }
2983
- navigate(pageviewId, pageUrl) {
3086
+ getSessionId() {
3087
+ this.syncSessionId();
3088
+ return this.config.sessionId;
3089
+ }
3090
+ getPageviewId() {
3091
+ return this.config.pageviewId;
3092
+ }
3093
+ getContext() {
3094
+ return { pageviewId: this.getPageviewId(), sessionId: this.getSessionId() };
3095
+ }
3096
+ /**
3097
+ * Continues the pageview of the instance this one replaces: re-registering on
3098
+ * the same page must not count a second pageview or replay Prebid's history.
3099
+ */
3100
+ continuePageview(previous) {
3101
+ this.config.pageviewId = previous.config.pageviewId;
3102
+ this.pageviewEmitted = previous.pageviewEmitted;
3103
+ this.deduper = previous.deduper;
3104
+ this.replayedEventCount = previous.replayedEventCount;
3105
+ }
3106
+ navigate(pageviewId, pageUrl = "") {
3107
+ const nextPageUrl = normalizePageUrl(pageUrl);
3108
+ if (this.isEnabled && this.pageviewEmitted && pageviewId !== "" && pageviewId === this.config.pageviewId && (!nextPageUrl || nextPageUrl === this.pageUrl)) {
3109
+ recordActivity();
3110
+ return;
3111
+ }
2984
3112
  this.disable();
2985
3113
  this.slotRefreshIndices.clear();
2986
3114
  this.slotNames.clear();
@@ -2990,26 +3118,22 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2990
3118
  this.consentCount = 0;
2991
3119
  this.pageviewEmitted = false;
2992
3120
  this.config.pageviewId = pageviewId || generateUUID2();
2993
- this.config.visitorId = this.config.userId || this.config.pageviewId;
2994
- if (pageUrl) {
2995
- try {
2996
- const u = new URL(pageUrl);
2997
- this.pageUrl = u.origin + u.pathname;
2998
- } catch {
2999
- this.pageUrl = pageUrl;
3000
- }
3001
- } else {
3002
- this.pageUrl = "";
3003
- }
3121
+ this.pageUrl = nextPageUrl;
3004
3122
  this.logger.resetTiming();
3123
+ const prevSessionId = this.config.sessionId;
3005
3124
  recordActivity();
3125
+ this.syncSessionId();
3126
+ if (!this.config.visitorId || this.config.sessionId !== prevSessionId && this.config.visitorId === prevSessionId) {
3127
+ this.config.visitorId = this.config.userId || this.config.sessionId;
3128
+ }
3006
3129
  this.enable();
3007
3130
  }
3008
- recordAuctionStart(auctionId, adUnitCode = "", bidderCount) {
3131
+ recordAuctionStart(auctionId, adUnitCode = "", bidderCount, mediaType) {
3009
3132
  if (!this.isEnabled || !this.config.auctionEnabled) return;
3010
3133
  this.enqueue(TraceEventType.AUCTION_START, "auctionStart", {
3011
3134
  auctionId,
3012
3135
  adUnitCode,
3136
+ ...mediaType ? { bid: { mediaType } } : {},
3013
3137
  ...typeof bidderCount === "number" ? { metadata: { bidderCount: String(bidderCount) } } : {}
3014
3138
  });
3015
3139
  }
@@ -3069,7 +3193,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3069
3193
  data.bids.forEach((bid) => {
3070
3194
  const adUnitCode = bid.adUnitCode || "";
3071
3195
  const mediaTypes = Object.keys(bid.mediaTypes || {});
3072
- const mediaType = mediaTypes.length > 0 ? mediaTypes[0] : bid.mediaType || "banner";
3196
+ const mediaType = bid.mediaType || (bid.mediaTypes?.video ? "video" : mediaTypes.length > 0 ? mediaTypes[0] : "banner");
3073
3197
  const key = `${bidder}:${adUnitCode}`;
3074
3198
  if (!auctionMap.has(key)) {
3075
3199
  auctionMap.set(key, {
@@ -3271,35 +3395,28 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3271
3395
  }
3272
3396
  }
3273
3397
  const currentRefreshIndex = adUnitCode ? this.slotRefreshIndices.get(adUnitCode) ?? (record ? record.refreshIndex : 0) : 0;
3274
- if (!isVideo) {
3275
- const alreadyEmitted = adUnitCode ? this.hasImpressionEmitted(
3276
- adUnitCode,
3277
- currentRefreshIndex,
3278
- resolvedAuctionId,
3279
- bidTrace.creativeId
3280
- ) : false;
3281
- if (!alreadyEmitted) {
3282
- if (adUnitCode) {
3283
- this.markImpressionEmitted(
3284
- adUnitCode,
3285
- currentRefreshIndex,
3286
- resolvedAuctionId,
3287
- bidTrace.creativeId
3288
- );
3289
- }
3290
- this.enqueue(TraceEventType.IMPRESSION, "impression", {
3291
- auctionId: resolvedAuctionId,
3292
- transactionId: resolvedTransactionId,
3398
+ const alreadyEmitted = adUnitCode ? this.hasImpressionEmitted(
3399
+ adUnitCode,
3400
+ currentRefreshIndex,
3401
+ resolvedAuctionId,
3402
+ bidTrace.creativeId
3403
+ ) : false;
3404
+ if (!alreadyEmitted) {
3405
+ if (adUnitCode) {
3406
+ this.markImpressionEmitted(
3293
3407
  adUnitCode,
3294
- bid: bidTrace,
3295
- metadata: { refresh_index: String(currentRefreshIndex) }
3296
- });
3408
+ currentRefreshIndex,
3409
+ resolvedAuctionId,
3410
+ bidTrace.creativeId
3411
+ );
3297
3412
  }
3298
- } else {
3299
- this.log(
3300
- "DEBUG",
3301
- `adRenderSucceeded received for video ad unit ${adUnitCode || "unknown"}: suppressing IMPRESSION until verified video lifecycle event`
3302
- );
3413
+ this.enqueue(TraceEventType.IMPRESSION, "impression", {
3414
+ auctionId: resolvedAuctionId,
3415
+ transactionId: resolvedTransactionId,
3416
+ adUnitCode,
3417
+ bid: bidTrace,
3418
+ metadata: { refresh_index: String(currentRefreshIndex) }
3419
+ });
3303
3420
  }
3304
3421
  if (this.config.viewabilityEnabled && typeof document !== "undefined") {
3305
3422
  let el = adUnitCode && this.slotElements.get(adUnitCode) || null;
@@ -3353,9 +3470,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3353
3470
  enqueue(type, eventName, data) {
3354
3471
  if (!this.isEnabled) return;
3355
3472
  if (!this.shouldSample(type)) return;
3356
- if (this.managesSessionId && sessionNeedsSync()) {
3357
- this.config.sessionId = getOrCreateSessionId();
3358
- }
3473
+ this.syncSessionId();
3359
3474
  const protoEvent = {
3360
3475
  eventId: idToBytes(generateUUID2()),
3361
3476
  timestampMs: Date.now(),
@@ -3369,19 +3484,20 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3369
3484
  namespace: data.ns || data.namespace || ""
3370
3485
  };
3371
3486
  if (data.bid) {
3487
+ const dims = parseBidDimensions(data.bid);
3372
3488
  protoEvent.bid = {
3373
- bidder: data.bid.bidder || "",
3489
+ bidder: data.bid.bidder || data.bid.bidderCode || "",
3374
3490
  cpm: Number.isFinite(data.bid.cpm) ? data.bid.cpm : 0,
3375
3491
  // No defaults here: handlers with a priced bid (bidWon, impression)
3376
3492
  // set currency/mediaType themselves. Defaulting for the rest would
3377
3493
  // stamp fake "USD"/"banner" on rows that carried no bid.
3378
3494
  currency: data.bid.currency || "",
3379
- width: Number.isFinite(data.bid.width) ? data.bid.width : 0,
3380
- height: Number.isFinite(data.bid.height) ? data.bid.height : 0,
3495
+ width: dims.width,
3496
+ height: dims.height,
3381
3497
  dealId: data.bid.dealId || "",
3382
3498
  mediaType: data.bid.mediaType || "",
3383
- latencyMs: Number.isFinite(data.bid.latencyMs) ? data.bid.latencyMs : 0,
3384
- advertiserDomain: data.bid.advertiserDomain || "",
3499
+ latencyMs: Number.isFinite(data.bid.latencyMs) ? data.bid.latencyMs : Number.isFinite(data.bid.timeToRespond) ? data.bid.timeToRespond : 0,
3500
+ advertiserDomain: data.bid.advertiserDomain || data.bid.meta?.advertiserDomains?.[0] || (Array.isArray(data.bid.adomain) ? data.bid.adomain[0] : "") || "",
3385
3501
  creativeId: data.bid.creativeId || ""
3386
3502
  };
3387
3503
  }
@@ -3446,12 +3562,19 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3446
3562
  }, this.config.revenueFlushDelayMs);
3447
3563
  }
3448
3564
  }
3565
+ // Follows the page's session, which consent or a lapse can move after this
3566
+ // instance took its ID. A settled session is read as is: only a pageview or
3567
+ // visitor input may start a new one, never a flush.
3568
+ syncSessionId() {
3569
+ if (!this.managesSessionId) return;
3570
+ this.config.sessionId = sessionNeedsSync() ? getOrCreateSessionId() : inMemorySessionId;
3571
+ }
3449
3572
  isSampledVisitor() {
3450
- const key = this.config.visitorId || this.config.userId || this.config.pageviewId;
3573
+ const key = this.config.visitorId || this.config.sessionId;
3451
3574
  return isVisitorSampled(key, this.config.sampleRate);
3452
3575
  }
3453
3576
  shouldSample(type) {
3454
- if (!this.isSampledVisitor()) {
3577
+ if (this.visitorKeyLocked && !this.isSampledVisitor()) {
3455
3578
  return false;
3456
3579
  }
3457
3580
  if (type === TraceEventType.ERROR) {
@@ -3478,9 +3601,15 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3478
3601
  // Shared by flush() and flushBeacon().
3479
3602
  drainBatch() {
3480
3603
  if (this.queue.length === 0 || !this.config.endpoint) return null;
3604
+ this.syncSessionId();
3605
+ this.visitorKeyLocked = true;
3606
+ if (!this.isSampledVisitor()) {
3607
+ this.queue = [];
3608
+ return null;
3609
+ }
3481
3610
  const domain = typeof window !== "undefined" ? window.location.hostname : "";
3482
3611
  const sampleRate = normalizeSampleRate(this.config.sampleRate);
3483
- const automated = typeof navigator !== "undefined" && navigator.webdriver === true;
3612
+ const automated = isAutomatedClient();
3484
3613
  const buildBatch = (evts) => ({
3485
3614
  propertyId: idToBytes(this.config.propertyId),
3486
3615
  pageviewId: idToBytes(this.config.pageviewId),
@@ -3683,7 +3812,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3683
3812
  // event timestamps, so late rows attribute correctly.
3684
3813
  resendPersistedBatches() {
3685
3814
  try {
3686
- if (typeof localStorage === "undefined" || !this.config.endpoint) return;
3815
+ if (!storageAllowed || typeof localStorage === "undefined" || !this.config.endpoint) return;
3687
3816
  if (!this.config.propertyId) return;
3688
3817
  const ownPrefix = this.pendingKeyPrefix();
3689
3818
  const keys = [];
@@ -3801,6 +3930,7 @@ function registerPrebidAnalytics(pbjsGlobalName = "pbjs", defaults) {
3801
3930
  }
3802
3931
  }
3803
3932
  const analytics = new BidsparkPrebidAnalytics(merged);
3933
+ if (previous && !merged.pageviewId) analytics.continuePageview(previous);
3804
3934
  analytics.enable();
3805
3935
  win._bidsparkPrebidAnalytics = analytics;
3806
3936
  return analytics;
@@ -4241,8 +4371,8 @@ function attachImaAdsManager(analytics, adsManager, options) {
4241
4371
  }
4242
4372
  const slotId = options?.slotId || options?.adUnitCode || "video";
4243
4373
  const adUnitCode = options?.adUnitCode || slotId;
4244
- const auctionId = options?.auctionId || "";
4245
- const transactionId = options?.transactionId || "";
4374
+ const auctionId = options?.auctionId || options?.bid?.auctionId || "";
4375
+ const transactionId = options?.transactionId || options?.bid?.transactionId || "";
4246
4376
  const getWinningBid = (adData) => {
4247
4377
  let cached = (auctionId ? self.getCachedBid(`${auctionId}:${adUnitCode}`) : void 0) || (auctionId && slotId !== adUnitCode ? self.getCachedBid(`${auctionId}:${slotId}`) : void 0) || (adUnitCode !== "video" ? self.getCachedBid(adUnitCode) : void 0) || (slotId !== adUnitCode && slotId !== "video" ? self.getCachedBid(slotId) : void 0);
4248
4378
  if (!cached) {
@@ -4305,11 +4435,7 @@ function attachImaAdsManager(analytics, adsManager, options) {
4305
4435
  const resolvedTransactionId = transactionId || cached?.transactionId || "";
4306
4436
  const creativeId = session.creativeId || adData.creativeId || cached?.bidTrace?.creativeId || options?.bid?.creativeId || "";
4307
4437
  const stableAdIdentity = session.adId || adData.adId || creativeId || session.sessionId;
4308
- const mergedBid = {
4309
- ...cached?.rawBid || options?.bid,
4310
- mediaType: "video",
4311
- creativeId
4312
- };
4438
+ const mergedBid = resolveMergedBid(cached, creativeId);
4313
4439
  const emitted = self.recordImpression(resolvedSlotId, {
4314
4440
  adUnitCode: resolvedAdUnitCode,
4315
4441
  auctionId: resolvedAuctionId,
@@ -4342,6 +4468,19 @@ function attachImaAdsManager(analytics, adsManager, options) {
4342
4468
  }
4343
4469
  }
4344
4470
  };
4471
+ const resolveMergedBid = (cached, extraCreativeId) => {
4472
+ const rawDims = parseBidDimensions(cached?.rawBid);
4473
+ const optDims = parseBidDimensions(options?.bid);
4474
+ const creativeId = extraCreativeId || options?.bid?.creativeId || cached?.bidTrace?.creativeId || "";
4475
+ return {
4476
+ ...cached?.rawBid,
4477
+ ...options?.bid,
4478
+ ...options?.bid?.bidder || options?.bid?.bidderCode ? { bidderCode: options.bid.bidderCode || options.bid.bidder } : {},
4479
+ ...optDims.width > 0 && optDims.height > 0 ? optDims : rawDims,
4480
+ mediaType: "video",
4481
+ ...creativeId ? { creativeId } : {}
4482
+ };
4483
+ };
4345
4484
  const onMilestone = (milestone) => {
4346
4485
  self.log("DEBUG", `IMA AdEvent milestone: ${milestone}`);
4347
4486
  if (options?.onMilestone) {
@@ -4360,7 +4499,7 @@ function attachImaAdsManager(analytics, adsManager, options) {
4360
4499
  auctionId: auctionId || cached?.auctionId,
4361
4500
  transactionId: transactionId || cached?.transactionId,
4362
4501
  adUnitCode: resolvedAdUnitCode,
4363
- bid: cached?.bidTrace || options?.bid,
4502
+ bid: cached || options?.bid ? resolveMergedBid(cached) : void 0,
4364
4503
  metadata: {
4365
4504
  ...options?.metadata,
4366
4505
  media_type: "video"
@@ -4376,7 +4515,7 @@ function attachImaAdsManager(analytics, adsManager, options) {
4376
4515
  adUnitCode: resolvedAdUnitCode,
4377
4516
  auctionId: auctionId || cached?.auctionId,
4378
4517
  transactionId: transactionId || cached?.transactionId,
4379
- bid: cached?.bidTrace || options?.bid,
4518
+ bid: cached || options?.bid ? resolveMergedBid(cached) : void 0,
4380
4519
  metadata: options?.metadata
4381
4520
  });
4382
4521
  if (options?.onError) {
@@ -4788,6 +4927,24 @@ function getAdsGlobal(alias = DEFAULT_ALIAS) {
4788
4927
  const win = window;
4789
4928
  win[alias] = win[alias] || { q: [] };
4790
4929
  const sdk = win[alias];
4930
+ if (!sdk.getContext) {
4931
+ sdk.getContext = () => {
4932
+ const inst = win._bidsparkPrebidAnalytics;
4933
+ return inst?.getContext ? inst.getContext() : { pageviewId: inst?.getPageviewId?.() || "", sessionId: getOrCreateSessionId() };
4934
+ };
4935
+ }
4936
+ if (!sdk.getSessionId) {
4937
+ sdk.getSessionId = () => {
4938
+ const inst = win._bidsparkPrebidAnalytics;
4939
+ return inst?.getSessionId ? inst.getSessionId() : getOrCreateSessionId();
4940
+ };
4941
+ }
4942
+ if (!sdk.getPageviewId) {
4943
+ sdk.getPageviewId = () => {
4944
+ const inst = win._bidsparkPrebidAnalytics;
4945
+ return inst?.getPageviewId ? inst.getPageviewId() : "";
4946
+ };
4947
+ }
4791
4948
  if (!sdk.attachVideoPlayer) {
4792
4949
  sdk.attachVideoPlayer = (target, options) => {
4793
4950
  const inst = win._bidsparkPrebidAnalytics;
@@ -4834,14 +4991,15 @@ function getAdsGlobal(alias = DEFAULT_ALIAS) {
4834
4991
  getPrebidEventKey,
4835
4992
  idToBytes,
4836
4993
  idToString,
4994
+ isAutomatedClient,
4837
4995
  isSessionActive,
4838
4996
  isTrustedEndpoint,
4839
4997
  isVisitorSampled,
4840
4998
  normalizeLogLevel,
4841
4999
  normalizeSampleRate,
4842
5000
  onSessionResume,
5001
+ parseBidDimensions,
4843
5002
  registerPrebidAnalytics,
4844
- resetTcfListener,
4845
5003
  sendEvents,
4846
5004
  sessionStarted
4847
5005
  });