@bidspark/analytics 0.45.2 → 0.46.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/README.md CHANGED
@@ -63,10 +63,39 @@ analytics.enable();
63
63
  | `userId` | `""` | User identifier. Not auto-generated; see [User identity](#user-identity). |
64
64
  | `sessionId` / `pageviewId` | generated | Override identity; defaults to managed 30-minute visitor sessions. See [Sessions](#sessions). |
65
65
  | `deviceType` / `country` / `region` | server-derived | Optional client hints; resolved server-side. |
66
+ | `alias` | `"ads"` | Window global alias for CMP/SDK instance and default DOM event prefix (`<alias>:session`, `<alias>:pageview`). |
67
+ | `events` | `{}` | Optional `{ pageview, session }` overrides: custom DOM event names or `(detail: { pageviewId, sessionId }) => void` callbacks. See [Pageview and session events](#pageview-and-session-events). |
66
68
  | `logLevel` | `"INFO"` | Console log verbosity (`DEBUG`, `INFO`, `WARN`, `ERROR`). |
67
69
 
68
70
  SPA route transitions: call `analytics.navigate(newPageviewId, newUrl)` to flush the previous pageview and reset session timing.
69
71
 
72
+ ## Pageview and session events
73
+
74
+ The adapter announces each pageview and each newly minted 30-minute session on `window` via `CustomEvent<{ pageviewId: string; sessionId: string }>`:
75
+
76
+ - `<alias>:session` (default `ads:session`) fires when a new session starts (initial visit, or user activity / `navigate()` after `>30m` idle). Returning visits within 30 minutes, cross-tab session adoption, and caller-supplied fixed `sessionId` values do not emit `session`.
77
+ - `<alias>:pageview` (default `ads:pageview`) fires once per pageview at `enable()` and on SPA `navigate()`. When a pageview also starts a session, `session` fires before `pageview`.
78
+
79
+ Register `window.addEventListener` listeners before calling `enable()` or `pbjs.enableAnalytics()` so the initial synchronous dispatch is not missed, or pass callback functions in `events: { pageview, session }`:
80
+
81
+ ```js
82
+ const analytics = new BidsparkPrebidAnalytics({
83
+ endpoint: "https://by.bidspark.io/t",
84
+ propertyId: "YOUR_PROPERTY_ID",
85
+ alias: "archidekt",
86
+ events: {
87
+ session: ({ pageviewId, sessionId }) => {
88
+ // Called instead of dispatching a DOM CustomEvent on window
89
+ },
90
+ pageview: "archidekt:custom-pageview",
91
+ },
92
+ });
93
+ ```
94
+
95
+ - **Handler precedence:** A function in `events.pageview` or `events.session` is invoked directly with `{ pageviewId, sessionId }` and skips dispatching the corresponding DOM `CustomEvent` on `window`.
96
+ - **Event name validation:** Custom string event names must match `/^[a-zA-Z0-9:_.-]{1,64}$/` and may not use reserved `ads:*` names other than the default. Invalid names log a warning and fall back to `<alias>:<key>`.
97
+ - **Storage consent:** When storage is disabled at page load (`storageAllowed: false` or pending CMP consent), each page load mints a fresh in-memory session ID and therefore fires the `session` event on every page load. If consent is later granted mid-page and a prior stored session is adopted from `localStorage`, no second `session` event is emitted.
98
+
70
99
  ## Sessions
71
100
 
72
101
  A session is a 30-minute window of visitor activity. It starts with a pageview and extends on user interaction (`pointerdown`, `keydown`, `scroll`, `touch`, tab visibility). Ad events do not extend sessions; idle tabs stop refreshing 30 minutes after last user interaction. Subsequent interaction mints a new `sessionId`.
@@ -1 +1 @@
1
- "use strict";var bidsparkPrebidAnalyticsBundle=(()=>{var U=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(i){throw t=[i],i}};var Qt=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};function en(){if(typeof window<"u"){let n=window;return n.__bidsparkLogListeners||(n.__bidsparkLogListeners=new Set),n.__bidsparkLogListeners}return Jt}function tn(n){if((n<0||!Number.isFinite(n))&&(n=0),n<1e3)return`${n.toFixed(2)}ms`;let e=n/1e3;if(e<60)return`${e.toFixed(2)}s`;let t=Math.floor(e/60);return t<60?`${t}m ${(e%60).toFixed(2)}s`:`${Math.floor(t/60)}h ${t%60}m ${(e%60).toFixed(2)}s`}function K(n){if(typeof n=="string"){let e=n.toUpperCase();if(e==="DEBUG"||e==="INFO"||e==="WARN"||e==="ERROR")return e}return R.INFO}function Ee(n){return new ve(n)}var R,He,H,Zt,Jt,ve,Ye=U(()=>{"use strict";R={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},He={[R.DEBUG]:10,[R.INFO]:20,[R.WARN]:30,[R.ERROR]:40},H={badge:"color: #2dd4bf; font-weight: bold",badgeWarn:"background: #f59e0b; color: #fff; padding: 2px 4px; border-radius: 3px; font-weight: bold",badgeError:"background: #ef4444; color: #fff; padding: 2px 4px; border-radius: 3px; font-weight: bold",dim:"color: #6b7280",event:"color: #38bdf8; font-weight: bold",eventWarn:"color: #f59e0b; font-weight: bold",eventError:"color: #ef4444; font-weight: bold",reset:"color: inherit"},Zt=0,Jt=new Set;ve=class{_prefix;_level;_loadedAt;_now;_console;_listeners=new Set;constructor(e={}){this._prefix=e.prefix??"[ads]",this._level=K(e.logLevel??R.INFO),this._now=e.now,this._console=e.console,e.onLog&&this._listeners.add(e.onLog),this._loadedAt=e.loadedAt??(this._now?this._now():typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now())}get prefix(){return this._prefix}set prefix(e){this._prefix=e}get logLevel(){return this._level}set logLevel(e){this._level=K(e)}getLevel(){return this._level}setLevel(e){this._level=K(e)}getPrefix(){return this._prefix}setPrefix(e){this._prefix=e}resetTiming(e){this._loadedAt=e??(this._now?this._now():typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now())}getLoadedAt(){return this._loadedAt}addListener(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}removeListener(e){this._listeners.delete(e)}isEnabled(e){let t=K(e);return(He[t]??20)>=(He[this._level]??20)}_getConsole(){if(this._console)return this._console;if(typeof console<"u")return console}_getElapsed(){let e=this._now?this._now():typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();return Math.max(0,e-this._loadedAt)}_dispatchRecord(e){for(let i of this._listeners)try{i(e)}catch{}let t=en();for(let i of t)if(!this._listeners.has(i))try{i(e)}catch{}}log(e,t,...i){let r=K(e);if(!this.isEnabled(r))return;let o=this._getElapsed(),s=tn(o),d=Date.now(),u={id:`bk_log_${d}_${++Zt}`,timestamp:d,elapsedMs:o,level:r,prefix:this._prefix,message:t,args:i,data:i.length===1?i[0]:i.length>1?i:void 0};this._dispatchRecord(u);let c=this._getConsole();if(!c)return;let m=H.badge,p=H.event;r===R.WARN?(m=H.badgeWarn,p=H.eventWarn):r===R.ERROR&&(m=H.badgeError,p=H.eventError);let f=["%c%s%c %s %c%s%c",m,this._prefix,H.dim,s,p,t,H.reset];switch(i.length>0&&f.push(...i),r){case R.DEBUG:typeof c.log=="function"?c.log(...f):typeof c.debug=="function"&&c.debug(...f);break;case R.INFO:typeof c.info=="function"?c.info(...f):typeof c.log=="function"&&c.log(...f);break;case R.WARN:typeof c.warn=="function"?c.warn(...f):typeof c.log=="function"&&c.log(...f);break;case R.ERROR:typeof c.error=="function"?c.error(...f):typeof c.log=="function"&&c.log(...f);break;default:typeof c.log=="function"&&c.log(...f);break}}debug(e,...t){this.log(R.DEBUG,e,...t)}info(e,...t){this.log(R.INFO,e,...t)}warn(e,...t){this.log(R.WARN,e,...t)}error(e,...t){this.log(R.ERROR,e,...t)}logEvent(e){e&&(e.data!==void 0?this.log(e.level,e.eventName,e.data):this.log(e.level,e.eventName))}}});function Xe(){let n=0,e=0;for(let i=0;i<28;i+=7){let r=this.buf[this.pos++];if(n|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function ue(n,e,t){for(let o=0;o<28;o=o+7){let s=n>>>o,d=!(!(s>>>7)&&e==0),a=(d?s|128:s)&255;if(t.push(a),!d)return}let i=n>>>28&15|(e&7)<<4,r=e>>3!=0;if(t.push((r?i|128:i)&255),!!r){for(let o=3;o<31;o=o+7){let s=e>>>o,d=!!(s>>>7),a=(d?s|128:s)&255;if(t.push(a),!d)return}t.push(e>>>31&1)}}function Te(n){let e=n[0]==="-";e&&(n=n.slice(1));let t=1e6,i=0,r=0;function o(s,d){let a=Number(n.slice(s,d));r*=t,i=i*t+a,i>=ce&&(r=r+(i/ce|0),i=i%ce)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),e?Ze(i,r):Ae(i,r)}function Qe(n,e){let t=Ae(n,e),i=t.hi&2147483648;i&&(t=Ze(t.lo,t.hi));let r=we(t.lo,t.hi);return i?"-"+r:r}function we(n,e){if({lo:n,hi:e}=nn(n,e),e<=2097151)return String(ce*e+n);let t=n&16777215,i=(n>>>24|e<<8)&16777215,r=e>>16&65535,o=t+i*6777216+r*6710656,s=i+r*8147497,d=r*2,a=1e7;return o>=a&&(s+=Math.floor(o/a),o%=a),s>=a&&(d+=Math.floor(s/a),s%=a),d.toString()+ze(s)+ze(o)}function nn(n,e){return{lo:n>>>0,hi:e>>>0}}function Ae(n,e){return{lo:n|0,hi:e|0}}function Ze(n,e){return e=~e,n?n=~n+1:e+=1,Ae(n,e)}function Se(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function Je(){let n=this.buf[this.pos++],e=n&127;if((n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,(n&128)==0)return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;(n&128)!==0&&t<10;t++)n=this.buf[this.pos++];if((n&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}var ce,ze,Ce=U(()=>{"use strict";ce=4294967296;ze=n=>{let e=String(n);return"0000000".slice(e.length)+e}});function rn(){let n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(!!globalThis.Deno||typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){let t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),r=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(s){let d=typeof s=="bigint"?s:BigInt(s);if(d>i||d<t)throw new Error(`invalid int64: ${s}`);return d},uParse(s){let d=typeof s=="bigint"?s:BigInt(s);if(d>o||d<r)throw new Error(`invalid uint64: ${s}`);return d},enc(s){return n.setBigInt64(0,this.parse(s),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(s){return n.setBigInt64(0,this.uParse(s),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(s,d){return n.setInt32(0,s,!0),n.setInt32(4,d,!0),n.getBigInt64(0,!0)},uDec(s,d){return n.setInt32(0,s,!0),n.setInt32(4,d,!0),n.getBigUint64(0,!0)}}}return{zero:"0",supported:!1,parse(t){return typeof t!="string"&&(t=t.toString()),et(t),t},uParse(t){return typeof t!="string"&&(t=t.toString()),tt(t),t},enc(t){return typeof t!="string"&&(t=t.toString()),et(t),Te(t)},uEnc(t){return typeof t!="string"&&(t=t.toString()),tt(t),Te(t)},dec(t,i){return Qe(t,i)},uDec(t,i){return we(t,i)}}}function et(n){if(!/^-?[0-9]+$/.test(n))throw new Error("invalid int64: "+n)}function tt(n){if(!/^[0-9]+$/.test(n))throw new Error("invalid uint64: "+n)}var V,nt=U(()=>{"use strict";Ce();V=rn()});function _e(){if(globalThis[Re]==null){let n=new globalThis.TextEncoder,e=new globalThis.TextDecoder;globalThis[Re]={encodeUtf8(t){return n.encode(t)},decodeUtf8(t){return e.decode(t)},checkUtf8(t){try{return encodeURIComponent(t),!0}catch{return!1}}}}return globalThis[Re]}var Re,Be=U(()=>{"use strict";Re=Symbol.for("@bufbuild/protobuf/text-encoding")});function Ue(n){if(typeof n=="string")n=Number(n);else if(typeof n!="number")throw new Error("invalid int32: "+typeof n);if(!Number.isInteger(n)||n>an||n<cn)throw new Error("invalid int32: "+n)}function it(n){if(typeof n=="string")n=Number(n);else if(typeof n!="number")throw new Error("invalid uint32: "+typeof n);if(!Number.isInteger(n)||n>dn||n<0)throw new Error("invalid uint32: "+n)}function un(n){if(typeof n=="string"){let e=n;if(n=Number(n),Number.isNaN(n)&&e!=="NaN")throw new Error("invalid float32: "+e)}else if(typeof n!="number")throw new Error("invalid float32: "+typeof n);if(Number.isFinite(n)&&(n>on||n<sn))throw new Error("invalid float32: "+n)}var Y,on,sn,dn,an,cn,F,C,rt=U(()=>{"use strict";Ce();nt();Be();(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(Y||(Y={}));on=34028234663852886e22,sn=-34028234663852886e22,dn=4294967295,an=2147483647,cn=-2147483648,F=class{constructor(e=_e().encodeUtf8){this.encodeUtf8=e,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let e=0;for(let r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let t=new Uint8Array(e),i=0;for(let r=0;r<this.chunks.length;r++)t.set(this.chunks[r],i),i+=this.chunks[r].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(it(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Ue(e),Se(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.encodeUtf8(e);return this.uint32(t.byteLength),this.raw(t)}float(e){un(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){it(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Ue(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Ue(e),e=(e<<1^e>>31)>>>0,Se(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=V.enc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=V.uEnc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=V.enc(e);return ue(t.lo,t.hi,this.buf),this}sint64(e){let t=V.enc(e),i=t.hi>>31,r=t.lo<<1^i,o=(t.hi<<1|t.lo>>>31)^i;return ue(r,o,this.buf),this}uint64(e){let t=V.uEnc(e);return ue(t.lo,t.hi,this.buf),this}},C=class{constructor(e,t=_e().decodeUtf8){this.decodeUtf8=t,this.varint64=Xe,this.uint32=Je,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case Y.Varint:for(;this.buf[this.pos++]&128;);break;case Y.Bit64:this.pos+=4;case Y.Bit32:this.pos+=4;break;case Y.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Y.StartGroup:for(;;){let[o,s]=this.tag();if(s===Y.EndGroup){if(t!==void 0&&o!==t)throw new Error("invalid end group tag");break}this.skip(s,o)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return V.dec(...this.varint64())}uint64(){return V.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,V.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return V.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return V.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.decodeUtf8(this.bytes())}}});var ot=U(()=>{"use strict"});var st=U(()=>{"use strict"});var dt=U(()=>{"use strict"});var xe=U(()=>{"use strict";rt();ot();Be();st();dt()});function ln(){return{propertyId:new Uint8Array(0),pageviewId:new Uint8Array(0),sessionId:new Uint8Array(0),pageUrl:"",country:"",region:"",deviceType:"",userId:"",domain:"",events:[],browser:"",deviceManufacturer:"",deviceModel:"",city:"",postalCode:"",sampleRate:void 0,automated:!1}}function fn(){return{timestampMs:0,type:0,eventName:"",auctionId:new Uint8Array(0),transactionId:new Uint8Array(0),adUnitCode:"",bid:void 0,namespace:"",eventId:new Uint8Array(0),metadata:{},viewableDurationMs:void 0,bidderOutcomes:[]}}function hn(){return{key:"",value:""}}function pn(){return{adUnitCode:"",outcome:0,bid:void 0,refreshIndex:0,floorCents:void 0,floorSource:0,floorTreatmentBp:void 0,slot:""}}function gn(){return{bidder:"",cpm:0,currency:"",width:0,height:0,dealId:"",mediaType:"",latencyMs:0,advertiserDomain:"",creativeId:""}}var y,q,he,re,le,at,ct,fe,pe=U(()=>{"use strict";xe();y={TRACE_EVENT_TYPE_UNSPECIFIED:0,AUCTION_START:1,AUCTION_END:2,BID_WIN:4,IMPRESSION:5,VIEWABLE:6,TIME_IN_VIEW:7,ERROR:9,SLOT_DEFINED:10,SLOT_DESTROYED:11,CLICK:12,AD_RENDER_FAILED:13,WARN:17,CONSENT:19,RECOVERY:20,PAGEVIEW:21,UNRECOGNIZED:-1},q={BIDDER_OUTCOME_UNSPECIFIED:0,BIDDER_OUTCOME_BID:1,BIDDER_OUTCOME_NO_BID:2,BIDDER_OUTCOME_TIMEOUT:3,BIDDER_OUTCOME_ERROR:4,BIDDER_OUTCOME_NO_RESPONSE:5,UNRECOGNIZED:-1},he={FLOOR_SOURCE_UNSPECIFIED:0,FLOOR_SOURCE_STATIC:1,FLOOR_SOURCE_POOL:2,FLOOR_SOURCE_NONE:3,UNRECOGNIZED:-1};re={encode(n,e=new F){if(n.propertyId!==void 0&&n.propertyId.length!==0&&e.uint32(10).bytes(n.propertyId),n.pageviewId!==void 0&&n.pageviewId.length!==0&&e.uint32(18).bytes(n.pageviewId),n.sessionId!==void 0&&n.sessionId.length!==0&&e.uint32(26).bytes(n.sessionId),n.pageUrl!==void 0&&n.pageUrl!==""&&e.uint32(34).string(n.pageUrl),n.country!==void 0&&n.country!==""&&e.uint32(42).string(n.country),n.region!==void 0&&n.region!==""&&e.uint32(50).string(n.region),n.deviceType!==void 0&&n.deviceType!==""&&e.uint32(58).string(n.deviceType),n.userId!==void 0&&n.userId!==""&&e.uint32(66).string(n.userId),n.domain!==void 0&&n.domain!==""&&e.uint32(74).string(n.domain),n.events!==void 0&&n.events.length!==0)for(let t of n.events)le.encode(t,e.uint32(82).fork()).join();return n.browser!==void 0&&n.browser!==""&&e.uint32(90).string(n.browser),n.deviceManufacturer!==void 0&&n.deviceManufacturer!==""&&e.uint32(98).string(n.deviceManufacturer),n.deviceModel!==void 0&&n.deviceModel!==""&&e.uint32(106).string(n.deviceModel),n.city!==void 0&&n.city!==""&&e.uint32(114).string(n.city),n.postalCode!==void 0&&n.postalCode!==""&&e.uint32(122).string(n.postalCode),n.sampleRate!==void 0&&e.uint32(129).double(n.sampleRate),n.automated!==void 0&&n.automated!==!1&&e.uint32(136).bool(n.automated),e},decode(n,e){let t=n instanceof C?n:new C(n),i=e===void 0?t.len:t.pos+e,r=ln();for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==10)break;r.propertyId=t.bytes();continue}case 2:{if(o!==18)break;r.pageviewId=t.bytes();continue}case 3:{if(o!==26)break;r.sessionId=t.bytes();continue}case 4:{if(o!==34)break;r.pageUrl=t.string();continue}case 5:{if(o!==42)break;r.country=t.string();continue}case 6:{if(o!==50)break;r.region=t.string();continue}case 7:{if(o!==58)break;r.deviceType=t.string();continue}case 8:{if(o!==66)break;r.userId=t.string();continue}case 9:{if(o!==74)break;r.domain=t.string();continue}case 10:{if(o!==82)break;let s=le.decode(t,t.uint32());s!==void 0&&r.events.push(s);continue}case 11:{if(o!==90)break;r.browser=t.string();continue}case 12:{if(o!==98)break;r.deviceManufacturer=t.string();continue}case 13:{if(o!==106)break;r.deviceModel=t.string();continue}case 14:{if(o!==114)break;r.city=t.string();continue}case 15:{if(o!==122)break;r.postalCode=t.string();continue}case 16:{if(o!==129)break;r.sampleRate=t.double();continue}case 17:{if(o!==136)break;r.automated=t.bool();continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};le={encode(n,e=new F){if(n.timestampMs!==void 0&&n.timestampMs!==0&&e.uint32(9).double(n.timestampMs),n.type!==void 0&&n.type!==0&&e.uint32(16).int32(n.type),n.eventName!==void 0&&n.eventName!==""&&e.uint32(26).string(n.eventName),n.auctionId!==void 0&&n.auctionId.length!==0&&e.uint32(34).bytes(n.auctionId),n.transactionId!==void 0&&n.transactionId.length!==0&&e.uint32(42).bytes(n.transactionId),n.adUnitCode!==void 0&&n.adUnitCode!==""&&e.uint32(50).string(n.adUnitCode),n.bid!==void 0&&fe.encode(n.bid,e.uint32(58).fork()).join(),n.namespace!==void 0&&n.namespace!==""&&e.uint32(66).string(n.namespace),n.eventId!==void 0&&n.eventId.length!==0&&e.uint32(74).bytes(n.eventId),globalThis.Object.entries(n.metadata||{}).forEach(([t,i])=>{at.encode({key:t,value:i},e.uint32(82).fork()).join()}),n.viewableDurationMs!==void 0&&e.uint32(89).double(n.viewableDurationMs),n.bidderOutcomes!==void 0&&n.bidderOutcomes.length!==0)for(let t of n.bidderOutcomes)ct.encode(t,e.uint32(98).fork()).join();return e},decode(n,e){let t=n instanceof C?n:new C(n),i=e===void 0?t.len:t.pos+e,r=fn();for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==9)break;r.timestampMs=t.double();continue}case 2:{if(o!==16)break;r.type=t.int32();continue}case 3:{if(o!==26)break;r.eventName=t.string();continue}case 4:{if(o!==34)break;r.auctionId=t.bytes();continue}case 5:{if(o!==42)break;r.transactionId=t.bytes();continue}case 6:{if(o!==50)break;r.adUnitCode=t.string();continue}case 7:{if(o!==58)break;r.bid=fe.decode(t,t.uint32());continue}case 8:{if(o!==66)break;r.namespace=t.string();continue}case 9:{if(o!==74)break;r.eventId=t.bytes();continue}case 10:{if(o!==82)break;let s=at.decode(t,t.uint32());s.value!==void 0&&(r.metadata[s.key]=s.value);continue}case 11:{if(o!==89)break;r.viewableDurationMs=t.double();continue}case 12:{if(o!==98)break;let s=ct.decode(t,t.uint32());s!==void 0&&r.bidderOutcomes.push(s);continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};at={encode(n,e=new F){return n.key!==""&&e.uint32(10).string(n.key),n.value!==""&&e.uint32(18).string(n.value),e},decode(n,e){let t=n instanceof C?n:new C(n),i=e===void 0?t.len:t.pos+e,r=hn();for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==10)break;r.key=t.string();continue}case 2:{if(o!==18)break;r.value=t.string();continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};ct={encode(n,e=new F){return n.adUnitCode!==void 0&&n.adUnitCode!==""&&e.uint32(18).string(n.adUnitCode),n.outcome!==void 0&&n.outcome!==0&&e.uint32(32).int32(n.outcome),n.bid!==void 0&&fe.encode(n.bid,e.uint32(50).fork()).join(),n.refreshIndex!==void 0&&n.refreshIndex!==0&&e.uint32(56).int32(n.refreshIndex),n.floorCents!==void 0&&e.uint32(64).int32(n.floorCents),n.floorSource!==void 0&&n.floorSource!==0&&e.uint32(72).int32(n.floorSource),n.floorTreatmentBp!==void 0&&e.uint32(80).int32(n.floorTreatmentBp),n.slot!==void 0&&n.slot!==""&&e.uint32(90).string(n.slot),e},decode(n,e){let t=n instanceof C?n:new C(n),i=e===void 0?t.len:t.pos+e,r=pn();for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 2:{if(o!==18)break;r.adUnitCode=t.string();continue}case 4:{if(o!==32)break;r.outcome=t.int32();continue}case 6:{if(o!==50)break;r.bid=fe.decode(t,t.uint32());continue}case 7:{if(o!==56)break;r.refreshIndex=t.int32();continue}case 8:{if(o!==64)break;r.floorCents=t.int32();continue}case 9:{if(o!==72)break;r.floorSource=t.int32();continue}case 10:{if(o!==80)break;r.floorTreatmentBp=t.int32();continue}case 11:{if(o!==90)break;r.slot=t.string();continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};fe={encode(n,e=new F){return n.bidder!==void 0&&n.bidder!==""&&e.uint32(10).string(n.bidder),n.cpm!==void 0&&n.cpm!==0&&e.uint32(17).double(n.cpm),n.currency!==void 0&&n.currency!==""&&e.uint32(26).string(n.currency),n.width!==void 0&&n.width!==0&&e.uint32(32).int32(n.width),n.height!==void 0&&n.height!==0&&e.uint32(40).int32(n.height),n.dealId!==void 0&&n.dealId!==""&&e.uint32(50).string(n.dealId),n.mediaType!==void 0&&n.mediaType!==""&&e.uint32(58).string(n.mediaType),n.latencyMs!==void 0&&n.latencyMs!==0&&e.uint32(65).double(n.latencyMs),n.advertiserDomain!==void 0&&n.advertiserDomain!==""&&e.uint32(74).string(n.advertiserDomain),n.creativeId!==void 0&&n.creativeId!==""&&e.uint32(82).string(n.creativeId),e},decode(n,e){let t=n instanceof C?n:new C(n),i=e===void 0?t.len:t.pos+e,r=gn();for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==10)break;r.bidder=t.string();continue}case 2:{if(o!==17)break;r.cpm=t.double();continue}case 3:{if(o!==26)break;r.currency=t.string();continue}case 4:{if(o!==32)break;r.width=t.int32();continue}case 5:{if(o!==40)break;r.height=t.int32();continue}case 6:{if(o!==50)break;r.dealId=t.string();continue}case 7:{if(o!==58)break;r.mediaType=t.string();continue}case 8:{if(o!==65)break;r.latencyMs=t.double();continue}case 9:{if(o!==74)break;r.advertiserDomain=t.string();continue}case 10:{if(o!==82)break;r.creativeId=t.string();continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}}});function L(n){if(!n)return new Uint8Array(0);let e=n.trim();e.startsWith("{")&&e.endsWith("}")&&(e=e.slice(1,-1).trim());let t=e.toLowerCase();if(yn.test(t)){let r=t.replace(/-/g,""),o=new Uint8Array(16);for(let s=0;s<16;s++)o[s]=parseInt(r.slice(s*2,s*2+2),16);return o}if(ut)return ut.encode(n);let i=new Uint8Array(n.length);for(let r=0;r<n.length;r++)i[r]=n.charCodeAt(r)&255;return i}function J(n){return typeof n!="number"||!Number.isFinite(n)||n<=0||n>1?1:n}function Le(n,e){let t=J(e);if(t>=1||!n)return!0;let i=2166136261;for(let r=0;r<n.length;r++)i^=n.charCodeAt(r),i=Math.imul(i,16777619);return(i>>>0)/4294967296<t}function De(){let n=typeof globalThis<"u"?globalThis:void 0,e=n&&"navigator"in n?n.navigator:void 0;if(!e)return!1;if(e.webdriver===!0)return!0;let t=typeof e.userAgent=="string"?e.userAgent:"";if(bn.test(t))return!0;let i=n&&"window"in n?n.window:n,r=0;if(i&&typeof i.outerWidth=="number"&&typeof i.outerHeight=="number"&&i.outerWidth===0&&i.outerHeight===0&&r++,Array.isArray(e.languages)&&e.languages.length===0&&r++,mn.test(t)&&!In.test(t)){i&&!i.chrome&&r++;let o=e.plugins;o!=null&&o.length===0&&r++}return r>=2}var yn,ut,xi,bn,mn,In,ge=U(()=>{"use strict";yn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ut=typeof TextEncoder<"u"?new TextEncoder:null,xi=typeof TextDecoder<"u"?new TextDecoder:null;bn=/headless|phantomjs|slimerjs|puppeteer|playwright/i,mn=/Chrome\/\d+/i,In=/Mobile|Android|iPhone|iPad|iPod|CriOS|FxiOS|Edg\/|OPR\/|SamsungBrowser/i});function vn(){return{unit:0,usageId:new Uint8Array(0),timestampMs:"0",slots:0}}function En(){return{pageviewId:new Uint8Array(0),events:[]}}var ft,lt,ht,pt=U(()=>{"use strict";xe();ft={USAGE_UNIT_UNSPECIFIED:0,AUCTION:1,SERVER_AUCTION:2,UNRECOGNIZED:-1};lt={encode(n,e=new F){return n.unit!==void 0&&n.unit!==0&&e.uint32(8).int32(n.unit),n.usageId!==void 0&&n.usageId.length!==0&&e.uint32(18).bytes(n.usageId),n.timestampMs!==void 0&&n.timestampMs!=="0"&&e.uint32(24).int64(n.timestampMs),n.slots!==void 0&&n.slots!==0&&e.uint32(32).uint32(n.slots),e},decode(n,e){let t=n instanceof C?n:new C(n),i=e===void 0?t.len:t.pos+e,r=vn();for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==8)break;r.unit=t.int32();continue}case 2:{if(o!==18)break;r.usageId=t.bytes();continue}case 3:{if(o!==24)break;r.timestampMs=t.int64().toString();continue}case 4:{if(o!==32)break;r.slots=t.uint32();continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};ht={encode(n,e=new F){if(n.pageviewId!==void 0&&n.pageviewId.length!==0&&e.uint32(10).bytes(n.pageviewId),n.events!==void 0&&n.events.length!==0)for(let t of n.events)lt.encode(t,e.uint32(18).fork()).join();return e},decode(n,e){let t=n instanceof C?n:new C(n),i=e===void 0?t.len:t.pos+e,r=En();for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==10)break;r.pageviewId=t.bytes();continue}case 2:{if(o!==18)break;let s=lt.decode(t,t.uint32());s!==void 0&&r.events.push(s);continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}}});function oe(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}var ke,gt=U(()=>{"use strict";pe();ge();ke="text/plain"});var wn,yt,ye,bt=U(()=>{"use strict";pt();gt();ge();wn=1e4,yt=200,ye=class{endpoint;propertyId;pageviewIdStr;pageviewIdBytes;queue=[];flushTimer=null;boundPageHide;boundVisibilityChange;isDestroyed=!1;constructor(e){this.endpoint=(e.endpoint||"").replace(/\/+$/,""),this.propertyId=e.propertyId||"",this.pageviewIdStr=e.pageviewId||oe();let t=L(this.pageviewIdStr);this.pageviewIdBytes=t.length===16?t:L(oe()),this.boundPageHide=()=>this.flush(),this.boundVisibilityChange=()=>{typeof document<"u"&&document.visibilityState==="hidden"&&this.flush()},typeof window<"u"&&(window.addEventListener("pagehide",this.boundPageHide),typeof document<"u"&&document.addEventListener("visibilitychange",this.boundVisibilityChange))}getEndpoint(){return this.endpoint}setEndpoint(e){this.endpoint=(e||"").replace(/\/+$/,"")}getPropertyId(){return this.propertyId}setPropertyId(e){this.propertyId=e||""}getPageviewId(){return this.pageviewIdStr}setPageviewId(e){this.pageviewIdStr=e||oe(),this.pageviewIdBytes=L(this.pageviewIdStr)}getQueueLength(){return this.queue.length}record(e,t,i=ft.AUCTION){if(this.isDestroyed||!e)return;let r=L(e);if(r.length!==16&&(r=L(oe())),this.queue.push({unit:i,usageId:r,timestampMs:String(Date.now()),slots:typeof t=="number"&&t>0?t:0}),this.queue.length>=yt){this.flush();return}!this.flushTimer&&typeof setTimeout<"u"&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},wn))}flush(){if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.queue.length===0||!this.endpoint||!this.propertyId)return!1;let e=!1;for(;this.queue.length>0;){let t=this.queue.splice(0,yt),i={pageviewId:this.pageviewIdBytes,events:t},r=ht.encode(i).finish(),s=`${this.endpoint.replace(new RegExp(`/${this.propertyId}$`),"")}/${this.propertyId}`,d=!1;if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function")try{let u=new Blob([r],{type:ke});d=navigator.sendBeacon(s,u)}catch{d=!1}let a=typeof globalThis<"u"&&typeof globalThis.fetch=="function"?globalThis.fetch:typeof fetch=="function"?fetch:null;if(!d&&a)try{a(s,{method:"POST",headers:{"Content-Type":ke},body:r,keepalive:!0}).catch(()=>{}),d=!0}catch{d=!1}d&&(e=!0)}return e}destroy(){this.queue.length>0&&this.flush(),this.isDestroyed=!0,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),typeof window<"u"&&(window.removeEventListener("pagehide",this.boundPageHide),typeof document<"u"&&document.removeEventListener("visibilitychange",this.boundVisibilityChange))}}});function Q(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}function Kn(n){let e="";for(let i=0;i<n.length;i+=8192)e+=String.fromCharCode(...n.subarray(i,i+8192));return btoa(e)}function qn(n){let e=atob(n),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}function jn(n){if(!n)return!1;let e;try{e=new URL(n)}catch{return!1}return e.username||e.password?!1:e.protocol==="https:"?!0:e.protocol==="http:"?e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]":!1}function Gn(n){let e={},t=0;for(let i of Object.keys(n)){if(t>=_n)break;let r=n[i];if(r==null)continue;let o=String(r);e[i]=o.length>Et?`${o.slice(0,Et)}...[truncated]`:o,t++}return e}function Hn(n,e){if(!n||!e)return!1;try{return new URL(n).origin===new URL(e).origin}catch{return!1}}function At(n){if(!n)return"";try{let e=new URL(n);return e.origin+e.pathname}catch{return n}}function Bt(n){try{typeof localStorage<"u"&&(localStorage.setItem(Ve,n.toString()),X=n)}catch{}}function Ut(n=Date.now()){return j>0&&n-j<=_t}function de(){let n=Date.now(),e=!!O&&!Ut(n);if(j=n,e){O=null;for(let t of Xn)t();return}!G||!O||X===0||n-X<Yn||Bt(n)}function Qn(){return!O||G&&X===0}function Zn(){if(St||typeof window>"u")return;St=!0;let n=()=>de();for(let e of zn)window.addEventListener(e,n,{passive:!0,capture:!0});typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&de()})}function te(){let n=Date.now(),e=!!O&&Ut(n);try{if(G&&typeof localStorage<"u"){let t=localStorage.getItem(Ne),i=localStorage.getItem(Ve),r=i&&parseInt(i,10)||0;if(t&&r&&n-r<=_t)return O!==t&&(Me=!1),(O!==t||j<r)&&(O=t,j=Math.max(j,r)),X===0&&(X=r),t;let o=e?O:Q();return e||(Me=!0,j=n),localStorage.setItem(Ne,o),Bt(j),O=o,o}}catch{}return e||(Me=!0,O=Q(),j=n),O}function xt(){X=0;try{typeof localStorage<"u"&&(localStorage.removeItem(Ne),localStorage.removeItem(Ve))}catch{}}function Ct(){try{if(G&&typeof localStorage<"u"){let n=localStorage.getItem(ne);if(n)return n;let e=O||Q();return localStorage.setItem(ne,e),e}}catch{}return""}function Ot(){try{typeof localStorage<"u"&&localStorage.removeItem(ne)}catch{}}function Fe(n){return n.regime!=="tcf"||!!n.purposesConsented?.includes(1)}function Jn(n){let e=[];if(n?.purpose?.consents)for(let[t,i]of Object.entries(n.purpose.consents))i&&e.push(Number(t));return{regime:n?.gdprApplies===!1?"us":"tcf",action:"replay",cmpId:n?.cmpId??0,cmpVersion:n?.cmpVersion??0,purposesConsented:e}}function Lt(n,e){if(!e||!n)return;if(n.eventStatus==="cmpuishown"&&!n.tcString)return!1;let t=Fe(Jn(n));return t||(xt(),Ot()),t}function ei(){if(typeof window>"u")return;let n=window;if(typeof n.__tcfapi!="function")return;let e;try{n.__tcfapi("getTCData",2,(t,i)=>{e=Lt(t,i)})}catch{}return e!==void 0?e:!1}function ti(){if(typeof window>"u")return;let n=window;if(!(typeof n.__tcfapi!="function"||Rt===n.__tcfapi)){Rt=n.__tcfapi;try{n.__tcfapi("addEventListener",2,(e,t)=>{let i=Lt(e,t);i!==void 0&&_.setStorageAllowed(i)})}catch{}}}function ni(n){if(typeof window>"u")return;let e=window,t=e[n]?.consent?.getRecord?.()||null;return t?Fe(t):e[`__${n}_cmp`]?.gdpr?!1:void 0}function l(n){return String(n??"").replace(/%/g,"%25").replace(/:/g,"%3A")}function ii(n,e){switch(n){case"auctionInit":return`auctionInit:${l(e?.auctionId)}`;case"auctionEnd":return`auctionEnd:${l(e?.auctionId)}`;case"bidRequested":{let t=Array.isArray(e?.bids)?e.bids.map(i=>l(i?.bidId||i?.transactionId||i?.adUnitCode)).join(","):"";return`bidRequested:${l(e?.auctionId)}:${l(e?.bidderCode||e?.bidder)}:${t}`}case"bidResponse":{let t=e||{},i=t.creativeId||t.adId||t.requestId||t.bidId||"",r=t.originalCpm??t.cpm??"";return`bidResponse:${l(t.auctionId)}:${l(t.adUnitCode)}:${l(t.bidderCode||t.bidder)}:${l(i)}:${l(r)}`}case"bidTimeout":return"bidTimeout:"+(Array.isArray(e)?e:e?[e]:[]).map(i=>`${l(i?.auctionId)}:${l(i?.bidderCode||i?.bidder)}:${l(i?.bidId||i?.transactionId||i?.adUnitCode)}`).join(",");case"bidWon":{let t=e||{},i=t.creativeId||t.adId||t.requestId||t.bidId||"",r=t.originalCpm??t.cpm??"";return`bidWon:${l(t.auctionId)}:${l(t.adUnitCode)}:${l(t.bidderCode||t.bidder)}:${l(i)}:${l(r)}`}case"noBid":return`noBid:${l(e?.auctionId)}:${l(e?.adUnitCode)}:${l(e?.bidderCode||e?.bidder)}:${l(e?.bidId||e?.transactionId)}`;case"adRenderFailed":{let t=e?.bid||{};return`adRenderFailed:${l(t.auctionId||e?.auctionId)}:${l(t.adUnitCode||e?.adUnitCode)}:${l(t.bidderCode||t.bidder||e?.bidderCode||e?.bidder)}:${l(e?.reason)}:${l(e?.message)}`}case"adRenderSucceeded":{let t=e?.bid||e||{},i=t.creativeId||t.adId||e?.adId||"",r=t.originalCpm??t.cpm??"";return`adRenderSucceeded:${l(t.auctionId||e?.auctionId)}:${l(t.adUnitCode||e?.adUnitCode)}:${l(t.bidderCode||t.bidder)}:${l(i)}:${l(r)}`}case"setTargeting":return`setTargeting:${Object.keys(e||{}).sort().map(l).join(",")}`;case"auctionDebug":return`auctionDebug:${l(e?.type)}:${l(String(e?.arguments?.[0]??"").slice(0,50))}`;default:return""}}function k(n){if(Number.isFinite(n?.width)&&n.width>0&&Number.isFinite(n?.height)&&n.height>0)return{width:n.width,height:n.height};if(Number.isFinite(n?.w)&&n.w>0&&Number.isFinite(n?.h)&&n.h>0)return{width:n.w,height:n.h};if(Number.isFinite(n?.playerWidth)&&n.playerWidth>0&&Number.isFinite(n?.playerHeight)&&n.playerHeight>0)return{width:n.playerWidth,height:n.playerHeight};let e=n?.mediaTypes?.video?.playerSize;if(Array.isArray(e)&&e.length>0){let r=Array.isArray(e[0])?e[0]:e;if(Number.isFinite(r[0])&&r[0]>0&&Number.isFinite(r[1])&&r[1]>0)return{width:r[0],height:r[1]}}if(typeof n?.size=="string"){let r=n.size.match(/^(\d+)x(\d+)$/);if(r)return{width:Number(r[1]),height:Number(r[2])}}let t=Number.isFinite(n?.width)?n.width:Number.isFinite(n?.w)?n.w:Number.isFinite(n?.playerWidth)?n.playerWidth:0,i=Number.isFinite(n?.height)?n.height:Number.isFinite(n?.h)?n.h:Number.isFinite(n?.playerHeight)?n.playerHeight:0;return{width:t,height:i}}function be(n,e){return Number.isFinite(n?.cpm)?{cpm:n.cpm,currency:n?.currency||n?.originalCurrency||e?.currency||"USD"}:Number.isFinite(n?.originalCpm)?{cpm:n.originalCpm,currency:n?.originalCurrency||n?.currency||e?.currency||"USD"}:{cpm:e?.cpm??0,currency:e?.currency||n?.currency||n?.originalCurrency||"USD"}}function ee(n,e=!0){if(!n)return null;if(Array.isArray(n)){let t=n.find(i=>i?.provider==="bidspark")??(e?n.find(i=>i&&typeof i=="object"&&i.provider===void 0):void 0);return t?ee(t,e):null}if(typeof n=="object"){if(n.options&&typeof n.options=="object")return n.options;if(n.config&&typeof n.config=="object")return n.config;if(n.propertyId||n.endpoint)return n}return null}function ri(n){if(!n)return null;if(n._bidsparkAnalyticsConfig){let t=ee(n._bidsparkAnalyticsConfig);if(t)return t}let e=n.bidsparkPrebidAnalytics;if(e){if(e.options){let t=ee(e.options);if(t)return t}if(e.config){let t=ee(e.config);if(t)return t}if(e.propertyId)return ee(e)}return null}function $e(n="pbjs",e){let t=typeof window<"u"?window:{};t[n]=t[n]||{};let i=t[n],r=s=>{let d=t._bidsparkPrebidAnalytics,a=d?.getEndpoint?.()||"",u=e?.usageEndpoint||"https://by.bidspark.io/u",c={pbjsGlobalName:n,...e,...s};if(c.usageEndpoint=u,a&&!Hn(c.endpoint||"",a)&&(Z.warn(`Ignoring analytics endpoint change to ${c.endpoint||"(empty)"}: this page is pinned to ${a}. Reload to change the ingest endpoint.`),c.endpoint=a),d)try{d.disable()}catch(p){Z.warn("Failed to disable previous analytics instance:",p)}let m=new _(c);return d&&!c.pageviewId&&m.continuePageview(d),m.enable(),t._bidsparkPrebidAnalytics=m,m},o=()=>{try{if(i.adapterManager&&typeof i.adapterManager.registerAnalyticsAdapter=="function"){let d={enableAnalytics:a=>{let u=ee(a,!Array.isArray(a));u&&r(u)},disableAnalytics:()=>{t._bidsparkPrebidAnalytics&&t._bidsparkPrebidAnalytics.disable()}};i.adapterManager.registerAnalyticsAdapter({adapter:{...d},code:"bidspark"})}let s=ri(t);s&&(s.propertyId||e?.propertyId)&&r(s)}catch(s){Z.warn("Failed to register standard Prebid analytics adapter:",s)}};i.adapterManager&&typeof i.adapterManager.registerAnalyticsAdapter=="function"?o():(i.que=i.que||[],i.que.push(o))}var mt,It,An,Sn,se,Cn,Rn,vt,Et,_n,Tt,wt,Bn,Un,xn,On,Ln,Dn,kn,Mn,z,Nn,Pn,Vn,Fn,$n,Wn,Ne,Ve,_t,O,j,Me,G,Yn,X,zn,St,Xn,ne,Rt,Pe,Z,_,We=U(()=>{"use strict";Ye();pe();ge();bt();mt="ads",It=1e4,An=50,Sn=20,se=200,Cn=300*1e3,Rn=10,vt=32*1024,Et=1024,_n=16,Tt="text/plain",wt="ads_pending_",Bn=20,Un=7200*1e3,xn=1e4,On={auctionStart:y.AUCTION_START,auctionEnd:y.AUCTION_END,bidWin:y.BID_WIN,adRenderFailed:y.AD_RENDER_FAILED,click:y.CLICK,impression:y.IMPRESSION,timeInView:y.TIME_IN_VIEW,viewable:y.VIEWABLE},Ln={WARN:y.WARN,ERROR:y.ERROR},Dn=new Set([y.ERROR,y.WARN]),kn=3e3,Mn=new Set([y.IMPRESSION,y.BID_WIN,y.CLICK]),z=1800*1e3,Nn=200,Pn=1e3,Vn=50,Fn=200,$n={static:he.FLOOR_SOURCE_STATIC,pool:he.FLOOR_SOURCE_POOL,none:he.FLOOR_SOURCE_NONE},Wn=1e3,Ne="ads_session",Ve="ads_session_ts",_t=1800*1e3,O=null,j=0,Me=!1,G=!0;Yn=60*1e3,X=0,zn=["pointerdown","pointermove","keydown","scroll","wheel","touchstart"],St=!1,Xn=new Set;ne="ads_uid";Rt=null;Pe=class{seenObjects=new WeakMap;seenKeys=new Set;isDuplicate(e,t){if(!t)return!1;if(typeof t=="object"){let r=this.seenObjects.get(t);if(r){if(r.has(e))return!0;r.add(e)}else this.seenObjects.set(t,new Set([e]))}let i=ii(e,t);if(i){if(this.seenKeys.has(i))return!0;if(this.seenKeys.size>=1e3){let r=this.seenKeys.values().next().value;r!==void 0&&this.seenKeys.delete(r)}this.seenKeys.add(i)}return!1}};Z=Ee({prefix:"[analytics]",logLevel:"INFO"}),_=class n{static activeInstances=new Set;static allInstances=new Set;static getActiveInstances(){return n.activeInstances}static setLogLevel(e){let t=K(e);Z.setLevel(t);for(let i of n.allInstances)i.setLogLevel(t)}static getLogLevel(){return Z.getLevel()}static setStorageAllowed(e){G=e,X=0;for(let t of n.allInstances)t.applyStorageAllowed(e)}static isStorageAllowed(){return G}config;usageRecorder=null;queue=[];errorCount=0;flushTimer=null;boundFlushBeacon;boundVisibilityChange;isEnabled=!1;boundPbjsHandlers=[];pageUrl="";deduper=new Pe;consecutiveSendFailures=0;nextSendAllowedAt=0;replayedEventCount=0;revenueFlushTimer=null;persistedBatchKeys=[];persistedCleanupTimer=null;intersectionObserver=null;slotViewabilityRecords=new Map;elementToSlotId=new Map;slotRefreshIndices=new Map;slotNames=new Map;slotAdSessionCounters=new Map;slotLastAuctionIds=new Map;pendingViewableListeners=new Map;slotElements=new Map;clickDetachCleanups=new Set;lastClickAt=new Map;slotEmittedImpressionKeys=new Set;cachedWinningBids=new Map;videoDetachCleanups=new Set;auctionBidderOutcomes=new Map;floorDecisions=new Map;recordedConsentKeys=new Set;consentCount=0;cmpDetach=null;pageviewEmitted=!1;logger;managesSessionId;configuredUserId;managesVisitorId;visitorKeyLocked;constructor(e){let t=ei();typeof window<"u"&&typeof window.__tcfapi=="function"&&ti();let i=e.storageAllowed??t??ni(e.alias||mt);i!==void 0&&n.setStorageAllowed(i);let r=i!==void 0?i:G,o=e.endpoint||"",s=!o||jn(o)?o:"",d=e.pageviewId||Q();de(),this.managesSessionId=!e.sessionId;let a=e.sessionId||te();this.configuredUserId=e.userId||"";let u="";if(r&&(u=this.configuredUserId||Ct(),this.configuredUserId))try{typeof localStorage<"u"&&localStorage.setItem(ne,this.configuredUserId)}catch{}this.managesVisitorId=!e.visitorId&&!e.userId&&!e.sessionId,this.visitorKeyLocked=r||!this.managesVisitorId;let c=e.usageEndpoint||"";this.config={endpoint:s,usageEndpoint:c,propertyId:e.propertyId||"",pageviewId:d,sessionId:a,userId:u,visitorId:e.visitorId||this.configuredUserId||u||a,deviceType:e.deviceType||"desktop",country:e.country||"",region:e.region||"",auctionEnabled:e.auctionEnabled??!0,warningsEnabled:e.warningsEnabled??!0,sampleRate:J(e.sampleRate),viewabilityEnabled:e.viewabilityEnabled??!0,storageAllowed:r,logLevel:e.logLevel?K(e.logLevel):Z.getLevel(),pbjsGlobalName:e.pbjsGlobalName||"pbjs",attachPbjsListeners:e.attachPbjsListeners??!0,revenueFlushDelayMs:Number.isFinite(e.revenueFlushDelayMs)&&e.revenueFlushDelayMs>=0?e.revenueFlushDelayMs:kn,alias:e.alias||mt},n.allInstances.add(this),this.logger=Ee({prefix:"[analytics]",logLevel:this.config.logLevel}),o&&!s&&this.log("ERROR",`Rejected untrusted analytics endpoint ${o}: must be an absolute https:// URL without embedded credentials. Events will not be transmitted.`),this.boundFlushBeacon=()=>{this.flushAllSlotsTimeInView(),this.flushBeacon()},this.boundVisibilityChange=()=>this.handleVisibilityChange()}applyStorageAllowed(e){if(this.config.storageAllowed=e,!e){this.config.userId="";return}this.syncSessionId(),this.config.userId||(this.config.userId=this.configuredUserId||Ct()),this.managesVisitorId&&!this.visitorKeyLocked&&(this.config.visitorId=this.config.userId||this.config.sessionId,this.visitorKeyLocked=!0,this.isSampledVisitor()||(this.queue=[],this.revenueFlushTimer&&(clearTimeout(this.revenueFlushTimer),this.revenueFlushTimer=null))),this.isEnabled&&this.resendPersistedBatches()}setLogLevel(e){let t=K(e);this.config.logLevel=t,this.logger.setLevel(t),Z.setLevel(t)}getLogLevel(){return this.logger.getLevel()}enable(){if(!this.isEnabled){if(this.isEnabled=!0,n.activeInstances.add(this),n.allInstances.add(this),this.logger.setLevel(this.config.logLevel),this.config.attachPbjsListeners&&this.config.usageEndpoint&&!this.usageRecorder&&(this.usageRecorder=new ye({endpoint:this.config.usageEndpoint,propertyId:this.config.propertyId,pageviewId:this.config.pageviewId})),this.config.endpoint||this.log("WARN","Endpoint is empty. Analytics events will not be transmitted."),this.config.viewabilityEnabled&&typeof IntersectionObserver<"u"){this.intersectionObserver=new IntersectionObserver(this.handleIntersection.bind(this),{threshold:[.5]});for(let e of this.slotViewabilityRecords.values())e.element&&this.intersectionObserver.observe(e.element)}this.config.attachPbjsListeners&&this.attachPbjs(),this.cmpDetach=this.attachCmp(),typeof window<"u"&&(this.pageUrl||(this.pageUrl=At(window.location.href)),window.addEventListener("pagehide",this.boundFlushBeacon),typeof document<"u"&&document.addEventListener("visibilitychange",this.boundVisibilityChange),Zn(),this.pageviewEmitted||(this.pageviewEmitted=!0,this.enqueue(y.PAGEVIEW,"pageview",{})),this.flushTimer=setInterval(()=>this.flush(),It),this.resendPersistedBatches())}}attachPbjs(){if(!this.isEnabled)return!1;if(this.boundPbjsHandlers.length>0)return!0;let t=(typeof window<"u"?window:{})[this.config.pbjsGlobalName]||{};if(typeof t.onEvent!="function")return this.log("WARN","pbjs.onEvent is not defined. Prebid analytics will not function."),!1;this.log("DEBUG","Attaching event listeners to pbjs");let i={auctionInit:this.handleAuctionInit.bind(this),auctionEnd:this.handleAuctionEnd.bind(this),bidRequested:this.handleBidRequested.bind(this),bidResponse:this.handleBidResponse.bind(this),bidTimeout:this.handleBidTimeout.bind(this),bidWon:this.handleBidWon.bind(this),noBid:this.handleNoBid.bind(this),adRenderFailed:this.handleAdRenderFailed.bind(this),adRenderSucceeded:this.handleAdRenderSucceeded.bind(this)};for(let[r,o]of Object.entries(i))t.onEvent(r,o),this.boundPbjsHandlers.push({event:r,handler:o});if(typeof t.getEvents=="function")try{let r=t.getEvents();if(Array.isArray(r)){let o=r.slice(this.replayedEventCount);if(this.replayedEventCount=r.length,o.length>0){this.log("DEBUG",`Replaying ${o.length} historical events from pbjs.getEvents()`);for(let s of o){if(!s)continue;let d=s.eventType||s.event||s.name,a=s.args!==void 0?s.args:s.data!==void 0?s.data:s,u=i[d];u&&u(a)}}}}catch(r){this.log("WARN","Failed to replay historical events from pbjs.getEvents()",r)}return!0}disable(){if(this.isEnabled){this.flushAllSlotsTimeInView(),this.isEnabled=!1,n.activeInstances.delete(this),n.allInstances.delete(this),this.usageRecorder&&(this.usageRecorder.destroy(),this.usageRecorder=null);for(let e of this.slotViewabilityRecords.values())e.dwellTimer&&(clearTimeout(e.dwellTimer),e.dwellTimer=null,e.dwellStartedAt=null);this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.slotViewabilityRecords.clear(),this.elementToSlotId.clear();for(let e of this.videoDetachCleanups)try{e()}catch{}this.videoDetachCleanups.clear();for(let e of Array.from(this.clickDetachCleanups))try{e()}catch{}if(this.clickDetachCleanups.clear(),this.slotElements.clear(),this.cachedWinningBids.clear(),this.slotEmittedImpressionKeys.clear(),this.slotLastAuctionIds.clear(),this.auctionBidderOutcomes.clear(),this.floorDecisions.clear(),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.revenueFlushTimer&&(clearTimeout(this.revenueFlushTimer),this.revenueFlushTimer=null),this.persistedCleanupTimer&&(clearTimeout(this.persistedCleanupTimer),this.persistedCleanupTimer=null),typeof window<"u"&&(window.removeEventListener("pagehide",this.boundFlushBeacon),typeof document<"u"&&document.removeEventListener("visibilitychange",this.boundVisibilityChange)),this.boundPbjsHandlers.length>0){let t=(typeof window<"u"?window:{})[this.config.pbjsGlobalName]||{};if(typeof t.offEvent=="function")for(let{event:i,handler:r}of this.boundPbjsHandlers)t.offEvent(i,r);this.boundPbjsHandlers=[]}if(this.cmpDetach){try{this.cmpDetach()}catch{}this.cmpDetach=null}this.flush()}}handleVisibilityChange(){if(!(typeof document>"u")){if(document.visibilityState==="hidden"){let e=typeof performance<"u"&&performance.now?performance.now():Date.now();for(let t of this.slotViewabilityRecords.values()){t.inView&&t.lastEnteredViewAt!==null&&(t.accumulatedTimeInViewMs+=Math.max(0,e-t.lastEnteredViewAt),t.lastEnteredViewAt=null),t.dwellTimer&&(clearTimeout(t.dwellTimer),t.dwellTimer=null,t.dwellStartedAt=null);let i=Math.round(t.accumulatedTimeInViewMs);i>0&&this.enqueue(y.TIME_IN_VIEW,"timeInView",{auctionId:t.auctionId,transactionId:t.transactionId,adUnitCode:t.adUnitCode,viewableDurationMs:i,bid:t.bidPayload,metadata:{...t.metadata,refresh_index:String(t.refreshIndex)}}),t.accumulatedTimeInViewMs=0}this.flushBeacon()}else if(document.visibilityState==="visible"){let e=typeof performance<"u"&&performance.now?performance.now():Date.now();for(let t of this.slotViewabilityRecords.values())if(t.inView&&(t.lastEnteredViewAt=e,!t.viewableFired&&t.dwellTimer===null)){let i=t.mediaType==="video"?2e3:1e3;t.dwellStartedAt=e,t.dwellTimer=setTimeout(()=>{this.handleDwellComplete(t)},i)}}}}handleIntersection(e){for(let t of e){let i=this.elementToSlotId.get(t.target);if(!i){for(let a of n.activeInstances)if(a!==this&&a.elementToSlotId.has(t.target)){a.handleIntersection([t]);break}continue}let r=this.slotViewabilityRecords.get(i);if(!r)continue;let o=t.isIntersecting&&(t.intersectionRatio===void 0||t.intersectionRatio>=.5),s=typeof document>"u"||document.visibilityState==="visible",d=typeof performance<"u"&&performance.now?performance.now():Date.now();if(o){if(!r.inView&&(r.inView=!0,s&&(r.lastEnteredViewAt=d,!r.viewableFired&&r.dwellTimer===null))){let a=r.mediaType==="video"?2e3:1e3;r.dwellStartedAt=d,r.dwellTimer=setTimeout(()=>{this.handleDwellComplete(r)},a)}}else r.inView&&(r.lastEnteredViewAt!==null&&(r.accumulatedTimeInViewMs+=Math.max(0,d-r.lastEnteredViewAt),r.lastEnteredViewAt=null),r.inView=!1),r.dwellTimer!==null&&(clearTimeout(r.dwellTimer),r.dwellTimer=null,r.dwellStartedAt=null)}}handleDwellComplete(e){e.dwellTimer=null,e.dwellStartedAt=null,e.inView&&(typeof document<"u"&&document.visibilityState==="hidden"||(e.viewableFired||(e.viewableFired=!0,this.enqueue(y.VIEWABLE,"viewable",{auctionId:e.auctionId,transactionId:e.transactionId,adUnitCode:e.adUnitCode,bid:e.bidPayload,metadata:{...e.metadata,refresh_index:String(e.refreshIndex)}})),this.notifyViewable(e)))}notifyViewable(e){if(e.viewableFired){for(let t of e.viewableListeners)if(t.firedForIndex!==e.refreshIndex){t.firedForIndex=e.refreshIndex;try{t.callback(e.slotId)}catch(i){this.log("ERROR","Error in viewable listener callback",i)}}}}setSlotElement(e,t){this.slotElements.set(e,t);let i=this.slotViewabilityRecords.get(e);i&&i.element!==t&&this.observeSlot(t,e,{refreshIndex:i.refreshIndex})}recordClick(e,t){if(!this.isEnabled||!e)return!1;let i=Date.now();if(i-(this.lastClickAt.get(e)||0)<Wn)return!1;this.lastClickAt.set(e,i);let r=this.getCachedBid(e);return this.enqueue(y.CLICK,"click",{auctionId:r?.auctionId||"",transactionId:r?.transactionId||"",adUnitCode:e,bid:r?.bidTrace,metadata:{...t?.metadata,refresh_index:String(this.getRefreshIndex(e))}}),!0}attachClickTracker(e,t){if(typeof window>"u")return()=>{};let i=()=>{setTimeout(()=>{let o=document.activeElement;o&&(o===e||e.contains(o))&&(this.recordClick(t,{metadata:{source:"blur"}}),window.focus())},0)};window.addEventListener("blur",i);let r=()=>{window.removeEventListener("blur",i),this.clickDetachCleanups.delete(r)};return this.clickDetachCleanups.add(r),r}onViewable(e,t){let i={callback:t,firedForIndex:-1},r=this.slotViewabilityRecords.get(e);return r?(r.viewableListeners.add(i),this.notifyViewable(r)):(this.pendingViewableListeners.has(e)||this.pendingViewableListeners.set(e,new Set),this.pendingViewableListeners.get(e).add(i)),()=>{this.slotViewabilityRecords.get(e)?.viewableListeners.delete(i),this.pendingViewableListeners.get(e)?.delete(i)}}getCurrentTimeInView(e){let t=e.accumulatedTimeInViewMs;if(e.inView&&e.lastEnteredViewAt!==null){let i=typeof performance<"u"&&performance.now?performance.now():Date.now();t+=Math.max(0,i-e.lastEnteredViewAt)}return t}flushSlotTimeInView(e){let t=this.slotViewabilityRecords.get(e);if(!t)return;if(t.inView&&t.lastEnteredViewAt!==null){let r=typeof performance<"u"&&performance.now?performance.now():Date.now();t.accumulatedTimeInViewMs+=Math.max(0,r-t.lastEnteredViewAt),t.lastEnteredViewAt=null}let i=Math.round(t.accumulatedTimeInViewMs);i>0&&this.enqueue(y.TIME_IN_VIEW,"timeInView",{auctionId:t.auctionId,transactionId:t.transactionId,adUnitCode:t.adUnitCode,viewableDurationMs:i,bid:t.bidPayload,metadata:{...t.metadata,refresh_index:String(t.refreshIndex)}}),t.accumulatedTimeInViewMs=0}flushAllSlotsTimeInView(){for(let e of Array.from(this.slotViewabilityRecords.keys()))this.flushSlotTimeInView(e)}observeSlot(e,t,i){if(!this.config.viewabilityEnabled)return;let r=null;if(typeof e=="string"){if(typeof document<"u"){try{r=document.querySelector(e)||document.getElementById(e)}catch{r=document.getElementById(e)}r||(r=document.getElementById(e))}}else r=e;let o=t||i?.adUnitCode||(r?r.id:"")||Q(),s=this.slotViewabilityRecords.get(o);if(s){if(!!i?.isRefresh||i?.refreshIndex===void 0||i.refreshIndex>s.refreshIndex||!!(i?.auctionId&&s.auctionId&&i.auctionId!==s.auctionId)){this.flushSlotTimeInView(o);let a=i?.refreshIndex!==void 0?i.refreshIndex:(this.slotRefreshIndices.get(o)??s.refreshIndex)+1;this.slotRefreshIndices.set(o,a),s.dwellTimer&&(clearTimeout(s.dwellTimer),s.dwellTimer=null,s.dwellStartedAt=null),s.viewableFired=!1,s.accumulatedTimeInViewMs=0;let u=typeof performance<"u"&&performance.now?performance.now():Date.now();if(s.lastEnteredViewAt=s.inView?u:null,s.refreshIndex=a,s.auctionId=i?.auctionId||s.auctionId,s.transactionId=i?.transactionId||s.transactionId,s.mediaType=i?.mediaType||s.mediaType||"banner",s.bidPayload=i?.bid!==void 0?i.bid:s.bidPayload,s.metadata=i?.metadata??s.metadata,s.inView&&(typeof document>"u"||document.visibilityState==="visible")){let c=s.mediaType==="video"?2e3:1e3;s.dwellStartedAt=u,s.dwellTimer=setTimeout(()=>{this.handleDwellComplete(s)},c)}}else s.auctionId=i?.auctionId||s.auctionId,s.transactionId=i?.transactionId||s.transactionId,s.mediaType=i?.mediaType||s.mediaType,i?.bid!==void 0&&(s.bidPayload=i.bid),i?.metadata!==void 0&&(s.metadata=i.metadata);i?.auctionId&&this.slotLastAuctionIds.set(o,i.auctionId),r&&(s.element&&s.element!==r&&this.intersectionObserver&&(this.intersectionObserver.unobserve(s.element),this.elementToSlotId.delete(s.element)),s.element=r,this.elementToSlotId.set(r,o),this.intersectionObserver?.observe(r))}else{let d=i?.refreshIndex??this.slotRefreshIndices.get(o)??0;this.slotRefreshIndices.set(o,d),i?.auctionId&&this.slotLastAuctionIds.set(o,i.auctionId);let a=this.pendingViewableListeners.get(o)||new Set;this.pendingViewableListeners.delete(o);let u={slotId:o,element:r,adUnitCode:i?.adUnitCode||o,auctionId:i?.auctionId||"",transactionId:i?.transactionId||"",mediaType:i?.mediaType||"banner",bidPayload:i?.bid,metadata:i?.metadata,refreshIndex:d,inView:!1,lastEnteredViewAt:null,accumulatedTimeInViewMs:0,viewableFired:!1,dwellTimer:null,dwellStartedAt:null,viewableListeners:a};this.slotViewabilityRecords.set(o,u),r&&(this.elementToSlotId.set(r,o),this.intersectionObserver?.observe(r))}}unobserveSlot(e){let t=this.slotViewabilityRecords.get(e);t&&(this.flushSlotTimeInView(e),t.dwellTimer&&(clearTimeout(t.dwellTimer),t.dwellTimer=null,t.dwellStartedAt=null),t.viewableListeners=new Set,t.element&&this.intersectionObserver&&(this.intersectionObserver.unobserve(t.element),this.elementToSlotId.delete(t.element),t.element=null),t.inView=!1,t.lastEnteredViewAt=null)}registerSlot(e,t){e&&(t?this.slotNames.set(e,t):this.slotNames.delete(e))}destroySlot(e){this.unobserveSlot(e),this.slotNames.delete(e),this.slotViewabilityRecords.delete(e),this.slotRefreshIndices.delete(e),this.slotAdSessionCounters.delete(e),this.slotLastAuctionIds.delete(e),this.pendingViewableListeners.delete(e);let t=`${l(e)}:`;for(let r of Array.from(this.slotEmittedImpressionKeys))(r===e||r.startsWith(t))&&this.slotEmittedImpressionKeys.delete(r);let i=this.cachedWinningBids.get(e);i&&this.deleteCachedBidEntry(i)}getCachedBid(e){let t=this.cachedWinningBids.get(e);if(t){if(Date.now()-t.timestamp>z){this.deleteCachedBidEntry(t);return}return t}}deleteCachedBidEntry(e){for(let[t,i]of Array.from(this.cachedWinningBids))i===e&&this.cachedWinningBids.delete(t)}pruneCachedWinningBids(){let e=Date.now();for(let[t,i]of Array.from(this.cachedWinningBids))e-i.timestamp>z&&this.cachedWinningBids.delete(t);for(;this.cachedWinningBids.size>Nn;){let t=this.cachedWinningBids.keys().next();if(t.done)break;this.cachedWinningBids.delete(t.value)}}addImpressionKey(e){if(!this.slotEmittedImpressionKeys.has(e)){for(;this.slotEmittedImpressionKeys.size>=Pn;){let t=this.slotEmittedImpressionKeys.values().next();if(t.done)break;this.slotEmittedImpressionKeys.delete(t.value)}this.slotEmittedImpressionKeys.add(e)}}getOrCreateAuctionOutcomes(e){let t=this.auctionBidderOutcomes.get(e);for(t||(t=new Map,this.auctionBidderOutcomes.set(e,t));this.auctionBidderOutcomes.size>Vn;){let i=this.auctionBidderOutcomes.keys().next();if(i.done||i.value===e)break;this.auctionBidderOutcomes.delete(i.value)}return t}nextSlotAdSession(e){let t=(this.slotAdSessionCounters.get(e)??0)+1;return this.slotAdSessionCounters.set(e,t),`ad-session-${t}`}hasImpressionEmitted(e,t,i,r,o){let s=t??this.slotRefreshIndices.get(e)??0,d=`${l(e)}:${s}`;if(i?this.slotEmittedImpressionKeys.has(`${d}:auc:${l(i)}`):this.slotEmittedImpressionKeys.has(d))return!0;if(o){if(i&&this.slotEmittedImpressionKeys.has(`${d}:auc:${l(i)}:render`)||this.slotEmittedImpressionKeys.has(`${d}:render`))return!0;if(i){if(this.slotEmittedImpressionKeys.has(`${d}:auc:${l(i)}:ad:${l(o)}`)||this.slotEmittedImpressionKeys.has(`${d}:ad:${l(o)}`))return!0}else if(this.slotEmittedImpressionKeys.has(`${d}:ad:${l(o)}`))return!0;if(r&&r!==o){if(i){if(this.slotEmittedImpressionKeys.has(`${d}:auc:${l(i)}:${l(r)}`)||this.slotEmittedImpressionKeys.has(`${d}:${l(r)}`))return!0}else if(this.slotEmittedImpressionKeys.has(`${d}:${l(r)}`))return!0}return!1}return i&&this.slotEmittedImpressionKeys.has(`${d}:auc:${l(i)}:ad-emitted`)||this.slotEmittedImpressionKeys.has(`${d}:ad-emitted`)?!0:r?i?this.slotEmittedImpressionKeys.has(`${d}:auc:${l(i)}:${l(r)}`)||this.slotEmittedImpressionKeys.has(`${d}:${l(r)}`):this.slotEmittedImpressionKeys.has(`${d}:${l(r)}`):!!(i&&this.slotEmittedImpressionKeys.has(`${d}:auc:${l(i)}:any`))}markImpressionEmitted(e,t,i,r,o){let s=`${l(e)}:${t}`;!!(o||r)?(o&&(this.addImpressionKey(`${s}:ad:${l(o)}`),this.addImpressionKey(`${s}:ad-emitted`),i&&(this.addImpressionKey(`${s}:auc:${l(i)}:ad:${l(o)}`),this.addImpressionKey(`${s}:auc:${l(i)}:any`),this.addImpressionKey(`${s}:auc:${l(i)}:ad-emitted`))),r&&r!==o&&(this.addImpressionKey(`${s}:${l(r)}`),i&&(this.addImpressionKey(`${s}:auc:${l(i)}:${l(r)}`),this.addImpressionKey(`${s}:auc:${l(i)}:any`))),o||(this.addImpressionKey(`${s}:render`),i&&this.addImpressionKey(`${s}:auc:${l(i)}:render`))):(this.addImpressionKey(s),this.addImpressionKey(`${s}:render`),i&&(this.addImpressionKey(`${s}:auc:${l(i)}`),this.addImpressionKey(`${s}:auc:${l(i)}:render`)))}recordImpression(e,t){if(!this.isEnabled)return!1;let i=e||t?.adUnitCode||"",r=t?.adUnitCode||i,o=(t?.auctionId&&i?this.getCachedBid(`${t.auctionId}:${i}`):void 0)||(t?.auctionId&&r?this.getCachedBid(`${t.auctionId}:${r}`):void 0)||(i?this.getCachedBid(i):void 0)||(r?this.getCachedBid(r):void 0),s=t?.bid||o?.rawBid||{},d=t?.auctionId||s.auctionId||o?.auctionId||"",a=t?.transactionId||s.transactionId||o?.transactionId||"",u=s.creativeId||o?.bidTrace?.creativeId||t?.bid?.creativeId||"",c=t?.adId||s.adId||t?.bid?.adId||"",m=t?.mediaType||s.mediaType||o?.bidTrace?.mediaType||"banner",p=i||r,f=(i?this.slotViewabilityRecords.get(i):void 0)||(r?this.slotViewabilityRecords.get(r):void 0),B=p?this.slotLastAuctionIds.get(p)||(f?f.auctionId:void 0):void 0,I=!!(p&&d&&B&&B!==d&&t?.refreshIndex===void 0),x={bidder:s.bidderCode||s.bidder||o?.bidTrace?.bidder||"",...be(s,o?.bidTrace),...k(s).width?k(s):o?.bidTrace?{width:o.bidTrace.width,height:o.bidTrace.height}:k(s),dealId:s.dealId||o?.bidTrace?.dealId||"",mediaType:m,latencyMs:Number.isFinite(s.timeToRespond)?s.timeToRespond:Number.isFinite(s.latencyMs)?s.latencyMs:o?.bidTrace?.latencyMs??0,advertiserDomain:s.advertiserDomain||s.meta?.advertiserDomains?.[0]||(Array.isArray(s.adomain)?s.adomain[0]:"")||o?.bidTrace?.advertiserDomain||"",creativeId:s.creativeId||o?.bidTrace?.creativeId||""};if(I&&p){this.flushSlotTimeInView(p);let N=(this.slotRefreshIndices.get(p)??(f?f.refreshIndex:0))+1;this.slotRefreshIndices.set(p,N),this.slotLastAuctionIds.set(p,d),f&&(f.refreshIndex=N,f.auctionId=d,f.transactionId=a,f.bidPayload=x,f.viewableFired=!1,f.accumulatedTimeInViewMs=0)}else p&&(d&&this.slotLastAuctionIds.set(p,d),this.slotRefreshIndices.has(p)||this.slotRefreshIndices.set(p,0));let w=t?.refreshIndex??(i?this.slotRefreshIndices.get(i)??(r?this.slotRefreshIndices.get(r):void 0)??(f?f.refreshIndex:0):0);return i&&this.hasImpressionEmitted(i,w,d,u,c)||r&&r!==i&&this.hasImpressionEmitted(r,w,d,u,c)?(this.log("DEBUG",`Impression already emitted for slot ${i||r} in cycle ${w}`),!1):(i&&this.markImpressionEmitted(i,w,d,u,c),r&&r!==i&&this.markImpressionEmitted(r,w,d,u,c),this.enqueue(y.IMPRESSION,"impression",{auctionId:d,transactionId:a,adUnitCode:r,bid:x,metadata:{...t?.metadata,refresh_index:String(w)}}),f&&(!f.bidPayload&&x&&(f.bidPayload=x),!f.auctionId&&d&&(f.auctionId=d),!f.transactionId&&a&&(f.transactionId=a)),!0)}getViewabilityState(e){let t=this.slotViewabilityRecords.get(e);if(!t)return;let i=Math.round(this.getCurrentTimeInView(t));return{inView:t.inView,viewable:t.viewableFired,timeInViewMs:i,refreshIndex:t.refreshIndex}}getEndpoint(){return this.config.endpoint}getRefreshIndex(e){return this.slotRefreshIndices.get(e)??0}triggerSlotRefresh(e,t){let i=this.slotViewabilityRecords.get(e);i&&i.element&&this.observeSlot(i.element,e,t)}trackRawEvent(e,t,i){let r=Ln[e]??On[t];r!==void 0&&this.enqueue(r,t,i)}recordFloorDecision(e,t,i){if(!e||!t)return;let r=`${e}:${t}`;for(this.floorDecisions.delete(r),this.floorDecisions.set(r,{floorCents:i.floorCents!==void 0&&Number.isFinite(i.floorCents)?Math.round(i.floorCents):void 0,source:i.source,treatment:Number.isFinite(i.treatment)?i.treatment:1});this.floorDecisions.size>Fn;){let o=this.floorDecisions.keys().next();if(o.done)break;this.floorDecisions.delete(o.value)}}floorDecisionFor(e,t){return e&&t?this.floorDecisions.get(`${e}:${t}`):void 0}recordConsent(e){if(!this.isEnabled||!e)return!1;let t=`${e.regime}|${e.action}|${e.tcString??""}|${e.gppString??""}|${e.uspString??""}`;if(this.recordedConsentKeys.has(t))return!1;this.recordedConsentKeys.add(t);let i={},r=(o,s)=>{if(!(s==null||s===""))if(typeof s=="number"){if(!Number.isFinite(s))return;i[o]=String(s)}else if(typeof s=="boolean")i[o]=s?"true":"false";else if(Array.isArray(s)){if(s.length===0)return;i[o]=[...s].sort((d,a)=>d-a).join(",")}else typeof s=="string"&&(i[o]=s)};return r("regime",e.regime),r("action",e.action),r("cmp_id",e.cmpId),r("cmp_version",e.cmpVersion),r("gvl_version",e.gvlVersion),r("tc_string",e.tcString),r("ac_string",e.acString),r("gpp_string",e.gppString),r("usp_string",e.uspString),r("purposes_consented",e.purposesConsented),r("vendors_consented",e.vendorsConsented),r("vendors_total",e.vendorsTotal),r("language",e.language),r("opt_out",e.optOut),r("gpc",e.gpc),this.enqueue(y.CONSENT,"consent",{metadata:i}),!0}attachCmp(){if(typeof document>"u")return()=>{};let e=o=>{let s=o.detail;s&&(this.followConsent(s),this.recordConsent(s))};document.addEventListener("ads:consent",e);let i=(typeof window<"u"?window:{})[this.config.alias]?.consent?.getRecord?.()||null;i&&(this.followConsent(i),this.recordConsent(i));let r=!1;return()=>{r||(r=!0,document.removeEventListener("ads:consent",e))}}followConsent(e){let t=Fe(e);t||(xt(),Ot()),n.setStorageAllowed(t)}setUserId(e){if(this.configuredUserId=e,this.config.userId=e,e&&(this.config.visitorId=e,this.managesVisitorId=!1,this.visitorKeyLocked=!0),this.config.storageAllowed&&typeof localStorage<"u")try{e?localStorage.setItem(ne,e):localStorage.removeItem(ne)}catch{}}setVisitorId(e){this.config.visitorId=e,this.managesVisitorId=!e,e&&(this.visitorKeyLocked=!0)}setSampleRate(e){this.config.sampleRate=J(e)}setSessionId(e){this.config.sessionId=e,this.managesSessionId=!e,this.managesSessionId&&(this.config.sessionId=te())}getSessionId(){return this.syncSessionId(),this.config.sessionId}getPageviewId(){return this.config.pageviewId}getContext(){return{pageviewId:this.getPageviewId(),sessionId:this.getSessionId()}}continuePageview(e){this.config.pageviewId=e.config.pageviewId,this.pageviewEmitted=e.pageviewEmitted,this.deduper=e.deduper,this.replayedEventCount=e.replayedEventCount}navigate(e,t=""){let i=At(t);if(this.isEnabled&&this.pageviewEmitted&&e!==""&&e===this.config.pageviewId&&(!i||i===this.pageUrl)){de();return}this.disable(),this.slotRefreshIndices.clear(),this.slotNames.clear(),this.slotAdSessionCounters.clear(),this.floorDecisions.clear(),this.recordedConsentKeys.clear(),this.consentCount=0,this.pageviewEmitted=!1,this.config.pageviewId=e||Q(),this.pageUrl=i,this.logger.resetTiming();let r=this.config.sessionId;de(),this.syncSessionId(),(!this.config.visitorId||this.config.sessionId!==r&&this.config.visitorId===r)&&(this.config.visitorId=this.config.userId||this.config.sessionId),this.enable()}recordAuctionStart(e,t="",i,r){!this.isEnabled||!this.config.auctionEnabled||this.enqueue(y.AUCTION_START,"auctionStart",{auctionId:e,adUnitCode:t,...r?{bid:{mediaType:r}}:{},...typeof i=="number"?{metadata:{bidderCount:String(i)}}:{}})}handleAuctionInit(e){if(this.isDuplicate("auctionInit",e))return;this.log("DEBUG","auctionInit",e);let t=e.auctionId||"";t&&(this.auctionBidderOutcomes.delete(t),this.getOrCreateAuctionOutcomes(t));let i=Array.isArray(e.adUnitCodes)?e.adUnitCodes.length:Array.isArray(e.adUnits)?e.adUnits.length:1;this.config.attachPbjsListeners&&this.usageRecorder&&this.usageRecorder.record(t,i),this.enqueue(y.AUCTION_START,"auctionStart",{auctionId:t,transactionId:e.transactionId||""})}handleAuctionEnd(e){if(this.isDuplicate("auctionEnd",e))return;this.log("DEBUG","auctionEnd",e);let t=e.auctionId||"",i=t?this.auctionBidderOutcomes.get(t):void 0,r=i?Array.from(i.values()):[];t&&this.auctionBidderOutcomes.delete(t),this.enqueue(y.AUCTION_END,"auctionEnd",{auctionId:t,transactionId:e.transactionId||"",bidderOutcomes:r})}auctionCycleIndex(e){if(!e)return 0;let t=this.slotRefreshIndices.get(e)??this.slotViewabilityRecords.get(e)?.refreshIndex;return t===void 0?0:t+1}handleBidRequested(e){if(this.isDuplicate("bidRequested",e))return;this.log("DEBUG","bidRequested",e);let t=e.auctionId||"",i=e.bidderCode||e.bidder||"";if(!t||!i)return;let r=this.getOrCreateAuctionOutcomes(t);Array.isArray(e.bids)&&e.bids.forEach(o=>{let s=o.adUnitCode||"",d=Object.keys(o.mediaTypes||{}),a=o.mediaType||(o.mediaTypes?.video?"video":d.length>0?d[0]:"banner"),u=`${i}:${s}`;r.has(u)||r.set(u,{adUnitCode:s,outcome:q.BIDDER_OUTCOME_NO_RESPONSE,bid:{bidder:i,mediaType:a,latencyMs:0}})})}handleBidResponse(e){if(this.isDuplicate("bidResponse",e))return;this.log("DEBUG","bidResponse",e);let t=e.auctionId||"",i=e.bidderCode||e.bidder||"",r=e.adUnitCode||"",o=be(e),s=o.cpm,d=Number.isFinite(e.timeToRespond)?e.timeToRespond:0,a=Object.keys(e.mediaTypes||{}),u=e.mediaType||(e.mediaTypes?.video?"video":a.length>0?a[0]:"banner");if(!t||!i)return;let c=s>0?{bidder:i,...o,...k(e),dealId:e.dealId||"",mediaType:u,latencyMs:d,advertiserDomain:e.meta?.advertiserDomains?.[0]||"",creativeId:e.creativeId||""}:{bidder:i,mediaType:u,latencyMs:d};this.getOrCreateAuctionOutcomes(t).set(`${i}:${r}`,{adUnitCode:r,outcome:s>0?q.BIDDER_OUTCOME_BID:q.BIDDER_OUTCOME_NO_BID,bid:c})}handleBidTimeout(e){if(this.isDuplicate("bidTimeout",e))return;this.log("DEBUG","bidTimeout",e);let t=Array.isArray(e)?e:e?[e]:[];for(let i of t){let r=i.auctionId||"",o=i.bidderCode||i.bidder||"",s=i.adUnitCode||"",d=Number.isFinite(i.timeout)?i.timeout:0;if(r&&o){let a=this.getOrCreateAuctionOutcomes(r),u=`${o}:${s}`,c=a.get(u);c?(c.outcome=q.BIDDER_OUTCOME_TIMEOUT,d>0&&c.bid&&(c.bid.latencyMs=d)):a.set(u,{adUnitCode:s,outcome:q.BIDDER_OUTCOME_TIMEOUT,bid:{bidder:o,mediaType:"banner",latencyMs:d}})}}}handleBidWon(e){if(this.isDuplicate("bidWon",e))return;this.log("DEBUG","bidWon",e);let t=e.auctionId||"",i=e.transactionId||"",r=e.adUnitCode||e.adId||"",o=Object.keys(e.mediaTypes||{}),s=e.mediaType||(e.mediaTypes?.video?"video":o.length>0?o[0]:"banner"),d={bidder:e.bidderCode||e.bidder||"",...be(e),...k(e),dealId:e.dealId||"",mediaType:s,latencyMs:Number.isFinite(e.timeToRespond)?e.timeToRespond:0,advertiserDomain:e.meta?.advertiserDomains?.[0]||"",creativeId:e.creativeId||""};if(r){let a={bidTrace:d,auctionId:t,transactionId:i,adUnitCode:r,rawBid:e,timestamp:Date.now()};this.cachedWinningBids.set(r,a),e.adId&&e.adId!==r&&this.cachedWinningBids.set(e.adId,a),t&&(this.cachedWinningBids.set(`${t}:${r}`,a),e.adId&&e.adId!==r&&this.cachedWinningBids.set(`${t}:${e.adId}`,a)),this.pruneCachedWinningBids()}this.enqueue(y.BID_WIN,"bidWon",{auctionId:t,transactionId:i,adUnitCode:r,bid:d})}handleNoBid(e){if(this.isDuplicate("noBid",e))return;this.log("DEBUG","noBid",e);let t=e.auctionId||"",i=e.bidderCode||e.bidder||"",r=e.adUnitCode||"";if(t&&i){let o=this.getOrCreateAuctionOutcomes(t),s=`${i}:${r}`,d=o.get(s);d?d.outcome===q.BIDDER_OUTCOME_NO_RESPONSE&&(d.outcome=q.BIDDER_OUTCOME_NO_BID):o.set(s,{adUnitCode:r,outcome:q.BIDDER_OUTCOME_NO_BID,bid:{bidder:i,mediaType:"banner",latencyMs:0}})}}handleAdRenderFailed(e){if(this.isDuplicate("adRenderFailed",e))return;this.log("DEBUG","adRenderFailed",e);let t=e.bid||{};this.enqueue(y.AD_RENDER_FAILED,"adRenderFailed",{auctionId:t.auctionId||e.auctionId||"",transactionId:t.transactionId||e.transactionId||"",adUnitCode:t.adUnitCode||e.adUnitCode||"",bid:{bidder:t.bidderCode||t.bidder||e.bidderCode||e.bidder||""},metadata:{reason:String(e.reason||""),message:String(e.message||e.error?.message||"")},error:e.error||(e.message?new Error(String(e.message)):void 0)})}handleAdRenderSucceeded(e){if(this.isDuplicate("adRenderSucceeded",e))return;this.log("DEBUG","adRenderSucceeded",e);let t=e.bid||e||{},i=e.adUnitCode||t.adUnitCode||e.adId||t.adId||"",r=t.auctionId||e.auctionId||"",o=t.transactionId||e.transactionId||"",s=t.mediaType||"banner",d=e.adUnitCode||t.adUnitCode||"",a=e.adId||t.adId||"",u=(r&&d?this.getCachedBid(`${r}:${d}`):void 0)||(r&&a?this.getCachedBid(`${r}:${a}`):void 0)||(d?this.getCachedBid(d):void 0)||(a?this.getCachedBid(a):void 0),m=s==="video"||t.mediaType==="video"||t.mediaTypes?.video!==void 0||u?.bidTrace?.mediaType==="video"||u?.rawBid?.mediaType==="video"||i&&this.slotViewabilityRecords.get(i)?.mediaType==="video"?"video":s||u?.bidTrace?.mediaType||"banner",p={bidder:t.bidderCode||t.bidder||u?.bidTrace?.bidder||"",...be(t,u?.bidTrace),...k(t).width?k(t):u?.bidTrace?{width:u.bidTrace.width,height:u.bidTrace.height}:k(t),dealId:t.dealId||u?.bidTrace?.dealId||"",mediaType:m,latencyMs:Number.isFinite(t.timeToRespond)?t.timeToRespond:u?.bidTrace?.latencyMs??0,advertiserDomain:t.meta?.advertiserDomains?.[0]||u?.bidTrace?.advertiserDomain||"",creativeId:t.creativeId||u?.bidTrace?.creativeId||""},f=r||u?.auctionId||"",B=o||u?.transactionId||"",I=i?this.slotViewabilityRecords.get(i):void 0,x=I&&f&&I.auctionId&&I.auctionId!==f,w=!!(i&&I&&x);if(w){this.flushSlotTimeInView(i);let A=(this.slotRefreshIndices.get(i)??(I?I.refreshIndex:0))+1;this.slotRefreshIndices.set(i,A),this.slotLastAuctionIds.set(i,f),I&&(I.auctionId=f,I.transactionId=B,I.bidPayload=p)}else i&&(f&&this.slotLastAuctionIds.set(i,f),this.slotRefreshIndices.has(i)||this.slotRefreshIndices.set(i,0));let M=i?this.slotRefreshIndices.get(i)??(I?I.refreshIndex:0):0;if(i&&this.hasImpressionEmitted(i,M,f,p.creativeId)||(i&&this.markImpressionEmitted(i,M,f,p.creativeId),this.enqueue(y.IMPRESSION,"impression",{auctionId:f,transactionId:B,adUnitCode:i,bid:p,metadata:{refresh_index:String(M)}})),this.config.viewabilityEnabled&&typeof document<"u"){let A=i&&this.slotElements.get(i)||null,T=i||e.adId||t.adId;if(!A&&T&&(A=document.getElementById(T)),!A&&typeof window<"u"&&window.googletag?.pubads)try{let b=window.googletag.pubads().getSlots();for(let E of b)if((E.getAdUnitPath?.()===i||E.getSlotElementId?.()===i)&&(A=document.getElementById(E.getSlotElementId()),A))break}catch{}if(!A&&T)try{for(let b of Array.from(document.querySelectorAll("[data-ad-slot]")))if(b.getAttribute("data-ad-slot")===T){A=b;break}}catch{}A?this.observeSlot(A,i||T,{adUnitCode:i,auctionId:f,transactionId:B,mediaType:m,bid:p,refreshIndex:M,isRefresh:w}):I&&w&&(I.refreshIndex=M,I.viewableFired=!1,I.accumulatedTimeInViewMs=0)}}isDuplicate(e,t){return this.deduper.isDuplicate(e,t)}enqueue(e,t,i){if(!this.isEnabled||!this.shouldSample(e))return;this.syncSessionId();let r={eventId:L(Q()),timestampMs:Date.now(),type:e,eventName:Dn.has(e)?t:"",auctionId:L(String(i.auctionId||"")),transactionId:L(String(i.transactionId||"")),adUnitCode:i.adUnitCode||i.elementId||"",namespace:i.ns||i.namespace||""};if(i.bid){let a=k(i.bid);r.bid={bidder:i.bid.bidder||i.bid.bidderCode||"",cpm:Number.isFinite(i.bid.cpm)?i.bid.cpm:0,currency:i.bid.currency||"",width:a.width,height:a.height,dealId:i.bid.dealId||"",mediaType:i.bid.mediaType||"",latencyMs:Number.isFinite(i.bid.latencyMs)?i.bid.latencyMs:Number.isFinite(i.bid.timeToRespond)?i.bid.timeToRespond:0,advertiserDomain:i.bid.advertiserDomain||i.bid.meta?.advertiserDomains?.[0]||(Array.isArray(i.bid.adomain)?i.bid.adomain[0]:"")||"",creativeId:i.bid.creativeId||""}}i.viewableDurationMs!==void 0&&(r.viewableDurationMs=Number.isFinite(i.viewableDurationMs)?i.viewableDurationMs:0),i.bidderOutcomes&&Array.isArray(i.bidderOutcomes)&&(r.bidderOutcomes=i.bidderOutcomes.map(a=>{let u=this.floorDecisionFor(String(i.auctionId||""),a.adUnitCode||""),c=a.slot||this.slotNames.get(a.adUnitCode||"");return{...a,...c?{slot:c}:{},refreshIndex:a.refreshIndex??this.auctionCycleIndex(a.adUnitCode||""),...u?{floorCents:u.floorCents,floorSource:$n[u.source],floorTreatmentBp:Math.round(u.treatment*1e4)}:{}}}));let o={...i.metadata},s=r.adUnitCode?this.slotNames.get(r.adUnitCode):void 0;if(s&&o.slot===void 0&&(o.slot=s),e===y.BID_WIN||e===y.IMPRESSION){let a=this.floorDecisionFor(String(i.auctionId||""),r.adUnitCode||"");a&&(a.floorCents!==void 0&&(o.floor_cents=String(a.floorCents)),o.floor_source=a.source,o.floor_treatment=a.treatment.toFixed(2))}i.error!==void 0&&i.error!==null&&(o.error=typeof i.error=="object"&&i.error.message?String(i.error.message):String(i.error)),i.gpid&&(o.gpid=String(i.gpid)),i.refreshIndex!==void 0&&o.refresh_index===void 0&&(o.refresh_index=String(i.refreshIndex));let d=Gn(o);Object.keys(d).length>0&&(r.metadata=d),this.queue.push(r),this.queue.length>=se?(this.flush(),this.queue.length>se&&this.queue.splice(0,this.queue.length-se)):Mn.has(e)&&this.revenueFlushTimer===null&&(this.revenueFlushTimer=setTimeout(()=>{this.revenueFlushTimer=null,this.flush()},this.config.revenueFlushDelayMs))}syncSessionId(){this.managesSessionId&&(this.config.sessionId=Qn()?te():O)}isSampledVisitor(){let e=this.config.visitorId||this.config.sessionId;return Le(e,this.config.sampleRate)}shouldSample(e){return this.visitorKeyLocked&&!this.isSampledVisitor()?!1:e===y.ERROR?(this.errorCount++,this.errorCount<=An):e===y.CONSENT?(this.consentCount++,this.consentCount<=Sn):e===y.WARN?this.config.warningsEnabled:this.config.auctionEnabled}requeue(e){e.length&&(this.queue=e.concat(this.queue),this.queue.length>se&&this.queue.splice(0,this.queue.length-se))}drainBatch(){if(this.queue.length===0||!this.config.endpoint)return null;if(this.syncSessionId(),this.visitorKeyLocked=!0,!this.isSampledVisitor())return this.queue=[],null;let e=typeof window<"u"?window.location.hostname:"",t=J(this.config.sampleRate),i=De(),r=s=>({propertyId:L(this.config.propertyId),pageviewId:L(this.config.pageviewId),sessionId:L(this.config.sessionId),pageUrl:this.pageUrl,country:this.config.country,region:this.config.region,deviceType:this.config.deviceType,userId:this.config.userId||"",domain:e,events:s,...t<1?{sampleRate:t}:{},...i?{automated:!0}:{}}),o=re.encode(r([])).finish().byteLength;for(;;){if(this.queue.length===0)return null;let s=0,d=o;for(let c=0;c<this.queue.length;c++){let m=this.queue[c],f=le.encode(m).finish().byteLength+6;if(d+f>vt){if(s===0){let[B]=this.queue.splice(0,1),I=re.encode(r([B])).finish().byteLength;this.log("WARN",`Dropping oversized event (type ${B?.type}, ${I} bytes exceeds the ${vt}-byte cap on its own)`);break}break}d+=f,s++}if(s===0)continue;let a=this.queue.slice(0,s),u=re.encode(r(a)).finish();return this.queue=this.queue.slice(a.length),{url:this.batchUrl(),encoded:u,events:a}}}sendFetch(e,t=!1,i,r=!1){let o={method:"POST",headers:{"Content-Type":Tt},body:e.encoded};t&&(o.keepalive=!0),fetch(e.url,o).then(d=>{if(d.ok)r||(this.consecutiveSendFailures=0,this.nextSendAllowedAt=0),i&&i();else{if(this.log("WARN",`Failed to send batch: HTTP ${d.status}`),d.status>=400&&d.status<500&&d.status!==429&&d.status!==408){this.log("WARN",`Dropping batch due to non-retryable client error HTTP ${d.status}`);return}r||this.handleSendFailure(e.events)}}).catch(d=>{this.log("ERROR","Failed to send batch",d),r||this.handleSendFailure(e.events)});let s=typeof globalThis<"u"?globalThis.process:void 0;if(s&&typeof s._tickCallback=="function")try{s._tickCallback()}catch{}}handleSendFailure(e){this.consecutiveSendFailures++;let t=Math.min(It*2**(this.consecutiveSendFailures-1),Cn);this.nextSendAllowedAt=Date.now()+t,this.consecutiveSendFailures<=Rn?this.requeue(e):this.log("WARN",`Dropping ${e.length} events after ${this.consecutiveSendFailures} consecutive send failures`)}flush(){if(Date.now()<this.nextSendAllowedAt)return;let e=this.drainBatch(),t=!0;for(;e&&(this.sendFetch(e,t),t=!1,!(Date.now()<this.nextSendAllowedAt));)e=this.drainBatch()}batchUrl(){return`${this.config.endpoint}/${this.config.propertyId}`}flushBeacon(){let e=this.drainBatch();for(;e;){let t=!1;if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function")try{let i=new Blob([e.encoded],{type:Tt});t=navigator.sendBeacon(e.url,i)}catch{t=!1}if(!t){let i=this.persistBatch(e.encoded);this.sendFetch(e,!0,()=>this.removePersistedBatch(i))}e=this.drainBatch()}this.schedulePersistedCleanup()}pendingKeyPrefix(){return`${wt}${encodeURIComponent(this.config.propertyId)}_`}persistBatch(e){if(!G)return null;try{if(typeof localStorage>"u"||!this.config.propertyId)return null;let t=0;for(let r=0;r<localStorage.length;r++){let o=localStorage.key(r);o&&o.startsWith(wt)&&t++}if(t>=Bn)return null;let i=`${this.pendingKeyPrefix()}${Date.now()}_${Math.floor(Math.random()*1e6)}`;return localStorage.setItem(i,Kn(e)),this.persistedBatchKeys.push(i),i}catch{return null}}removePersistedBatch(e){if(!e)return;try{typeof localStorage<"u"&&localStorage.removeItem(e)}catch{}let t=this.persistedBatchKeys.indexOf(e);t!==-1&&this.persistedBatchKeys.splice(t,1)}schedulePersistedCleanup(){this.persistedBatchKeys.length!==0&&(this.persistedCleanupTimer&&clearTimeout(this.persistedCleanupTimer),this.persistedCleanupTimer=setTimeout(()=>{this.persistedCleanupTimer=null;for(let e of Array.from(this.persistedBatchKeys))this.removePersistedBatch(e)},xn))}resendPersistedBatches(){try{if(!G||typeof localStorage>"u"||!this.config.endpoint||!this.config.propertyId)return;let e=this.pendingKeyPrefix(),t=[];for(let i=0;i<localStorage.length;i++){let r=localStorage.key(i);r&&r.startsWith(e)&&t.push(r)}for(let i of t){let r=null;try{r=localStorage.getItem(i),localStorage.removeItem(i)}catch{continue}if(!r)continue;let o=parseInt(i.slice(e.length),10);if(!Number.isFinite(o)||Date.now()-o>Un)continue;let s;try{s=qn(r)}catch{continue}s.byteLength!==0&&(this.log("DEBUG",`Resending persisted exit batch (${s.byteLength} bytes)`),this.sendFetch({url:`${this.config.endpoint}/${this.config.propertyId}`,encoded:s,events:[]},!1,void 0,!0))}}catch{}}log(e,t,...i){this.logger.log(e,t,...i)}}});function oi(n){let e=typeof n?.getError=="function"?n.getError():n?.error||n,t=a=>e&&typeof e[a]=="function"?e[a]():void 0,i=t("getMessage")||e?.message||String(e||"IMA ad error"),r=t("getErrorCode")??e?.code,o=t("getVastErrorCode"),s=t("getType")??e?.type,d={message:i};return r&&(d.error_code=String(r)),o&&(d.vast_error_code=String(o)),s&&(d.error_type=String(s)),{err:e,message:i,metadata:d}}function Pt(n,e,t){let i=me(n),{err:r,message:o,metadata:s}=oi(e);return i.log("WARN","IMA AdErrorEvent received",e),i.enqueue(y.AD_RENDER_FAILED,"adRenderFailed",{auctionId:t.auctionId,transactionId:t.transactionId,adUnitCode:t.adUnitCode,bid:t.bid,metadata:{...t.metadata,reason:t.adStarted?"ima_playback_error":"ima_ad_error",playback_phase:t.adStarted?"post_start":"pre_start",...s},error:typeof r=="object"?r:new Error(o)}),r}function si(n,e){if(!n||typeof n!="object"||Dt.has(n))return;Dt.add(n);let t=typeof window<"u"&&window.google?.ima?.AdErrorEvent?.Type?.AD_ERROR||"adError";try{e.call(n,t,i=>{for(let r of _.getActiveInstances())try{let o=Ft(r,{mediaType:"video"});Pt(r,i,{adStarted:!1,adUnitCode:o?.adUnitCode||"video",auctionId:o?.auctionId,transactionId:o?.transactionId,bid:o?.bidTrace})}catch{}})}catch{}}function kt(n){if(n)try{let e=n.prototype;if(e&&typeof e.getAdsManager=="function"&&!e.getAdsManager.__bidsparkHooked){let t=e.getAdsManager,i=function(...r){let o=t.apply(this,r);if(o)for(let s of _.getActiveInstances())try{s.attachImaAdsManager(o)}catch{}return o};i.__bidsparkHooked=!0,e.getAdsManager=i}}catch{}}function Mt(n){if(n)try{let e=n.prototype||n;if(e&&typeof e.init=="function"&&!e.init.__bidsparkHooked){let t=e.init,i=function(...r){for(let o of _.getActiveInstances())try{o.attachImaAdsManager(this)}catch{}return t.apply(this,r)};i.__bidsparkHooked=!0,e.init=i}if(e&&typeof e.start=="function"&&!e.start.__bidsparkHooked){let t=e.start,i=function(...r){for(let o of _.getActiveInstances())try{o.attachImaAdsManager(this)}catch{}return t.apply(this,r)};i.__bidsparkHooked=!0,e.start=i}}catch{}}function Nt(n){if(n)try{let e=n.prototype;if(!e)return;if(typeof e.addEventListener=="function"&&!e.addEventListener.__bidsparkHooked){let t=e.addEventListener,i=function(r,o,...s){if(si(this,t),(r==="adsManagerLoaded"||r===(this?.AdsManagerLoadedEvent?.Type?.ADS_MANAGER_LOADED||"adsManagerLoaded"))&&typeof o=="function"){let d=Ke.get(o);return d||(d=function(a){if(a&&typeof a.getAdsManager=="function"&&!a.getAdsManager.__bidsparkHooked){let u=a.getAdsManager;a.getAdsManager=function(...c){let m=u.apply(this,c);if(m)for(let p of _.getActiveInstances())try{p.attachImaAdsManager(m)}catch{}return m},a.getAdsManager.__bidsparkHooked=!0}return o.apply(this,arguments)},Ke.set(o,d)),t.call(this,r,d,...s)}return t.call(this,r,o,...s)};i.__bidsparkHooked=!0,e.addEventListener=i}if(typeof e.removeEventListener=="function"&&!e.removeEventListener.__bidsparkHooked){let t=e.removeEventListener,i=function(r,o,...s){let d=typeof o=="function"?Ke.get(o):void 0;return t.call(this,r,d||o,...s)};i.__bidsparkHooked=!0,e.removeEventListener=i}}catch{}}function ae(n){if(!(!n||typeof n!="object"))try{n.AdsManagerLoadedEvent&&kt(n.AdsManagerLoadedEvent);let e=Object.getOwnPropertyDescriptor(n,"AdsManagerLoadedEvent");if(!e||e.configurable){let r=n.AdsManagerLoadedEvent;try{Object.defineProperty(n,"AdsManagerLoadedEvent",{configurable:!0,enumerable:!0,get(){return r},set(o){r=o,kt(o)}})}catch{}}n.AdsLoader&&Nt(n.AdsLoader);let t=Object.getOwnPropertyDescriptor(n,"AdsLoader");if(!t||t.configurable){let r=n.AdsLoader;try{Object.defineProperty(n,"AdsLoader",{configurable:!0,enumerable:!0,get(){return r},set(o){r=o,Nt(o)}})}catch{}}n.AdsManager&&Mt(n.AdsManager);let i=Object.getOwnPropertyDescriptor(n,"AdsManager");if(!i||i.configurable){let r=n.AdsManager;try{Object.defineProperty(n,"AdsManager",{configurable:!0,enumerable:!0,get(){return r},set(o){r=o,Mt(o)}})}catch{}}}catch{}}function Vt(){if(typeof window>"u")return;let n=window;if(n.google?.ima&&ae(n.google.ima),n.google&&typeof n.google=="object"){let t=Object.getOwnPropertyDescriptor(n.google,"ima");if(!t||t.configurable){let i=n.google.ima;try{Object.defineProperty(n.google,"ima",{configurable:!0,enumerable:!0,get(){return i},set(r){i=r,ae(r)}})}catch{}}}let e=Object.getOwnPropertyDescriptor(n,"google");if(!e||e.configurable){let t=n.google;try{Object.defineProperty(n,"google",{configurable:!0,enumerable:!0,get(){return t},set(i){if(t=i,t&&typeof t=="object"){t.ima&&ae(t.ima);let r=Object.getOwnPropertyDescriptor(t,"ima");if(!r||r.configurable){let o=t.ima;try{Object.defineProperty(t,"ima",{configurable:!0,enumerable:!0,get(){return o},set(s){o=s,ae(s)}})}catch{}}}}})}catch{}}}function Ft(n,e){let t=me(n),i=Date.now(),r=d=>t.hasImpressionEmitted(d.adUnitCode,void 0,d.auctionId,d.bidTrace.creativeId);if(e?.creativeId||e?.adId){for(let d of Array.from(t.cachedWinningBids.values()))if(!(i-d.timestamp>z)&&(e.creativeId&&(d.bidTrace.creativeId===e.creativeId||d.rawBid?.creativeId===e.creativeId)||e.adId&&(d.rawBid?.adId===e.adId||d.adUnitCode===e.adId)))return d}let o;if(e?.mediaType){for(let a of Array.from(t.cachedWinningBids.values())){if(i-a.timestamp>z)continue;(a.bidTrace.mediaType===e.mediaType||a.rawBid?.mediaType===e.mediaType||e.mediaType==="video"&&a.rawBid?.mediaTypes?.video!==void 0)&&(r(a)||(!o||a.timestamp<o.timestamp)&&(o=a))}if(o)return o;let d;for(let a of Array.from(t.cachedWinningBids.values())){if(i-a.timestamp>z)continue;(a.bidTrace.mediaType===e.mediaType||a.rawBid?.mediaType===e.mediaType||e.mediaType==="video"&&a.rawBid?.mediaTypes?.video!==void 0)&&(!d||a.timestamp>d.timestamp)&&(d=a)}if(d)return d}for(let d of Array.from(t.cachedWinningBids.values()))i-d.timestamp>z||r(d)||(!o||d.timestamp>o.timestamp)&&(o=d);if(o)return o;let s;for(let d of Array.from(t.cachedWinningBids.values()))i-d.timestamp>z||(!s||d.timestamp>s.timestamp)&&(s=d);return s}function $t(n,e,t){let i=me(n);if(!e||typeof e.addEventListener!="function")return i.log("WARN","Invalid AdsManager passed to attachImaAdsManager"),()=>{};if(!e.__bidsparkAttachedInstances)try{Object.defineProperty(e,"__bidsparkAttachedInstances",{value:new Map,configurable:!0,writable:!0})}catch{e.__bidsparkAttachedInstances=new Map}let r=e.__bidsparkAttachedInstances,o=r.get(n);if(o){if(!t)return()=>{};o()}let s=t?.slotId||t?.adUnitCode||"video",d=t?.adUnitCode||s,a=t?.auctionId||t?.bid?.auctionId||"",u=t?.transactionId||t?.bid?.transactionId||"",c=h=>{let g=(a?i.getCachedBid(`${a}:${d}`):void 0)||(a&&s!==d?i.getCachedBid(`${a}:${s}`):void 0)||(d!=="video"?i.getCachedBid(d):void 0)||(s!==d&&s!=="video"?i.getCachedBid(s):void 0);return g||(g=Ft(n,{creativeId:h?.creativeId,adId:h?.adId,mediaType:"video"})),g},m=!1,p=null,f=h=>{let g=typeof i.nextSlotAdSession=="function"?i.nextSlotAdSession(s):`ad-session-${(i.slotAdSessionCounters?.get(s)??0)+1}`;if(i.slotAdSessionCounters&&typeof i.nextSlotAdSession!="function"){let D=(i.slotAdSessionCounters.get(s)??0)+1;i.slotAdSessionCounters.set(s,D)}let v=(typeof h?.getAdId=="function"?h.getAdId():h?.adId??h?.id)||"",P=(typeof h?.getCreativeId=="function"?h.getCreativeId():h?.creativeId)||"";return p={sessionId:g,adId:v||void 0,creativeId:P||void 0},p},B=h=>{let g=typeof h?.getAd=="function"?h.getAd():h?.ad;f(g),i.log("DEBUG","IMA AdEvent.LOADED received",{slotId:s,activeAdSession:p})},I=h=>{m=!0;let g=typeof h?.getAd=="function"?h.getAd():h?.ad,v={};g&&(v.creativeId=(typeof g.getCreativeId=="function"?g.getCreativeId():g.creativeId)||"",v.adId=(typeof g.getAdId=="function"?g.getAdId():g.id)||"",v.title=(typeof g.getTitle=="function"?g.getTitle():g.title)||"",v.duration=typeof g.getDuration=="function"?g.getDuration():g.duration,v.advertiserName=typeof g.getAdvertiserName=="function"?g.getAdvertiserName():""),!p||v.adId&&p.adId&&p.adId!==v.adId?f(g):(!p.adId&&v.adId&&(p.adId=v.adId),!p.creativeId&&v.creativeId&&(p.creativeId=v.creativeId));let P=p||f(g),D=c(v),Ie=t?.slotId&&t.slotId!=="video"?t.slotId:t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:D?.adUnitCode||t?.slotId||t?.adUnitCode||"video",jt=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:D?.adUnitCode||Ie,Gt=a||D?.auctionId||"",Ht=u||D?.transactionId||"",qe=P.creativeId||v.creativeId||D?.bidTrace?.creativeId||t?.bid?.creativeId||"",Yt=P.adId||v.adId||qe||P.sessionId,je=x(D,qe),Ge=i.recordImpression(Ie,{adUnitCode:jt,auctionId:Gt,transactionId:Ht,mediaType:"video",bid:je,adId:Yt,metadata:{...t?.metadata,media_type:"video",...v.title?{ad_title:v.title}:{},...Number.isFinite(v.duration)?{ad_duration_s:String(v.duration)}:{}}}),ie=typeof h?.type=="string"?h.type:typeof h?.getType=="function"?h.getType():typeof h=="string"?h:"";ie.toLowerCase().startsWith("adevent.")&&(ie=ie.slice(8));let zt=ie?ie.toUpperCase():"STARTED/IMPRESSION";if(i.log("DEBUG",`IMA AdEvent.${zt} received${Ge?"":" (second event for this ad, already counted)"}`,h),Ge&&t?.onImpression)try{t.onImpression(Ie,{ad:g,bid:je})}catch(Xt){i.log("ERROR","Error in onImpression callback",Xt)}},x=(h,g)=>{let v=k(h?.rawBid),P=k(t?.bid),D=g||t?.bid?.creativeId||h?.bidTrace?.creativeId||"";return{...h?.rawBid,...t?.bid,...t?.bid?.bidder||t?.bid?.bidderCode?{bidderCode:t.bid.bidderCode||t.bid.bidder}:{},...P.width>0&&P.height>0?P:v,mediaType:"video",...D?{creativeId:D}:{}}},w=h=>{if(i.log("DEBUG",`IMA AdEvent milestone: ${h}`),t?.onMilestone)try{t.onMilestone(h,s)}catch(g){i.log("ERROR","Error in onMilestone callback",g)}},M=h=>{i.log("DEBUG","IMA AdEvent.CLICK received",h);let g=c(),v=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:g?.adUnitCode||s;i.enqueue(y.CLICK,"click",{auctionId:a||g?.auctionId,transactionId:u||g?.transactionId,adUnitCode:v,bid:g||t?.bid?x(g):void 0,metadata:{...t?.metadata,media_type:"video"}})},N=h=>{p=null;let g=c(),v=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:g?.adUnitCode||s,P=Pt(n,h,{adStarted:m,adUnitCode:v,auctionId:a||g?.auctionId,transactionId:u||g?.transactionId,bid:g||t?.bid?x(g):void 0,metadata:t?.metadata});if(t?.onError)try{t.onError(P)}catch(D){i.log("ERROR","Error in onError callback",D)}},A=typeof window<"u"?window.google?.ima:void 0,T=A?.AdEvent?.Type||{},b=A?.AdErrorEvent?.Type||{},E=[{type:T.LOADED||"loaded",handler:B},{type:T.STARTED||"started",handler:I},{type:T.IMPRESSION||"impression",handler:I},{type:T.FIRST_QUARTILE||"firstQuartile",handler:()=>w("firstQuartile")},{type:T.MIDPOINT||"midpoint",handler:()=>w("midpoint")},{type:T.THIRD_QUARTILE||"thirdQuartile",handler:()=>w("thirdQuartile")},{type:T.COMPLETE||"complete",handler:()=>{p=null,w("complete")}},{type:T.ALL_ADS_COMPLETED||"allAdsCompleted",handler:()=>{p=null}},{type:T.CLICK||"click",handler:M},{type:b.AD_ERROR||"adError",handler:N}],S=new Set,$=[];for(let h of E)S.has(h.type)||(S.add(h.type),$.push(h));for(let{type:h,handler:g}of $)try{e.addEventListener(h,g)}catch{}let W=()=>{p=null,r.delete(n);for(let{type:h,handler:g}of $)try{e.removeEventListener(h,g)}catch{}i.videoDetachCleanups.delete(W)};return r.set(n,W),i.videoDetachCleanups.add(W),W}function di(n,e,t){let i=me(n);if(!e)return i.log("WARN","attachVideoPlayer called with null/undefined target"),()=>{};let r=null;if(typeof e=="string"){if(typeof document<"u")try{r=document.querySelector(e)||document.getElementById(e)}catch{r=document.getElementById(e)}}else if(typeof HTMLElement<"u"&&e instanceof HTMLElement)r=e;else if(e&&typeof e=="object"&&e.nodeType===1)r=e;else{if(typeof e.addEventListener=="function"&&(typeof e.init=="function"||typeof e.start=="function"||typeof e.getCuePoints=="function"||typeof e.getVolume=="function"||e.__imaAdsManager))return $t(n,e,t);e&&typeof e.addEventListener=="function"&&(r=e)}let o=t?.slotId||t?.adUnitCode||(r?r.id:"")||"video",s=t?.adUnitCode||o,d=t?.auctionId||"",a=t?.transactionId||"",u=()=>(d?i.getCachedBid(`${d}:${s}`):void 0)||(d&&o!==s?i.getCachedBid(`${d}:${o}`):void 0)||i.getCachedBid(s)||(o!==s?i.getCachedBid(o):void 0),c=null;r&&(r.tagName&&r.tagName.toLowerCase()==="video"?c=r:c=r.querySelector("video"));let m={q1:!1,q2:!1,q3:!1,q4:!1},p=b=>{let E=b||c||(r?.querySelector?r.querySelector("video"):null),S=u(),$={...S?.rawBid||t?.bid,mediaType:"video"};if(i.recordImpression(o,{adUnitCode:s,auctionId:d||S?.auctionId,transactionId:a||S?.transactionId,mediaType:"video",bid:$,metadata:{...t?.metadata,media_type:"video",...E&&Number.isFinite(E.duration)?{video_duration_s:String(Math.round(E.duration))}:{}}})&&t?.onImpression)try{t.onImpression(o,{element:E||r,bid:$})}catch(h){i.log("ERROR","Error in onImpression callback",h)}},f=b=>{i.log("DEBUG","HTML5 video playing event received");let E=b?.target instanceof HTMLVideoElement?b.target:c;p(E)},B=b=>{let E=b?.target instanceof HTMLVideoElement?b.target:c;if(E&&E.currentTime>0&&(p(E),Number.isFinite(E.duration)&&E.duration>0)){let S=E.currentTime/E.duration;S>=.25&&!m.q1&&(m.q1=!0,t?.onMilestone?.("firstQuartile",o)),S>=.5&&!m.q2&&(m.q2=!0,t?.onMilestone?.("midpoint",o)),S>=.75&&!m.q3&&(m.q3=!0,t?.onMilestone?.("thirdQuartile",o))}},I=()=>{m.q4||(m.q4=!0,t?.onMilestone?.("complete",o))},x=b=>{let S=(b?.target instanceof HTMLVideoElement?b.target:c)?.error||c?.error,$=u(),W=S?`HTML5 video error code ${S.code}: ${S.message}`:"Video playback error";if(i.log("WARN",W),i.enqueue(y.AD_RENDER_FAILED,"adRenderFailed",{auctionId:d||$?.auctionId,transactionId:a||$?.transactionId,adUnitCode:s,bid:$?.bidTrace||t?.bid,metadata:{...t?.metadata,reason:"html5_video_error",message:W,...S?.code?{error_code:String(S.code)}:{}},error:S?new Error(W):void 0}),t?.onError)try{t.onError(S)}catch(h){i.log("ERROR","Error in onError callback",h)}},w=b=>{b.addEventListener("playing",f),b.addEventListener("play",f),b.addEventListener("timeupdate",B),b.addEventListener("ended",I),b.addEventListener("error",x)},M=b=>{b.removeEventListener("playing",f),b.removeEventListener("play",f),b.removeEventListener("timeupdate",B),b.removeEventListener("ended",I),b.removeEventListener("error",x)},N=null;r&&r!==c&&(r.addEventListener("playing",f,!0),r.addEventListener("play",f,!0),r.addEventListener("timeupdate",B,!0),r.addEventListener("ended",I,!0),r.addEventListener("error",x,!0)),c&&w(c),r&&r.tagName?.toLowerCase()!=="video"&&typeof MutationObserver<"u"&&(N=new MutationObserver(()=>{let b=r.querySelector("video");b&&b!==c&&(c&&M(c),c=b,c&&w(c))}),N.observe(r,{childList:!0,subtree:!0}));let A=u();t?.trackViewability!==!1&&r&&i.observeSlot(r,o,{adUnitCode:s,auctionId:d||A?.auctionId,transactionId:a||A?.transactionId,mediaType:"video",bid:A?.bidTrace||t?.bid,metadata:t?.metadata});let T=()=>{N&&(N.disconnect(),N=null),r&&r!==c&&(r.removeEventListener("playing",f,!0),r.removeEventListener("play",f,!0),r.removeEventListener("timeupdate",B,!0),r.removeEventListener("ended",I,!0),r.removeEventListener("error",x,!0)),c&&M(c),i.videoDetachCleanups.delete(T)};return i.videoDetachCleanups.add(T),T}var me,Ke,Dt,ai,Wt=U(()=>{"use strict";We();pe();me=n=>n,Ke=new WeakMap,Dt=new WeakSet;typeof window<"u"&&Vt();_.prototype.attachImaAdsManager=function(n,e){return $t(this,n,e)};_.prototype.attachVideoPlayer=function(n,e){return di(this,n,e)};ai=_.prototype.enable;_.prototype.enable=function(){ai.call(this),typeof window<"u"&&(Vt(),window.google?.ima&&ae(window.google.ima))}});var ui=Qt(()=>{We();Wt();var Kt="https://by.bidspark.io/t",qt="https://by.bidspark.io/u",ci=window._bidsparkPbjsGlobal||"pbjs";$e(ci,{endpoint:Kt,usageEndpoint:qt});window.bidsparkPrebidAnalytics={...window.bidsparkPrebidAnalytics,register:(n,e)=>$e(n,{endpoint:Kt,usageEndpoint:qt,...e}),attachVideoPlayer:(n,e)=>{let t=window._bidsparkPrebidAnalytics;return t?.attachVideoPlayer?t.attachVideoPlayer(n,e):()=>{}},attachImaAdsManager:(n,e)=>{let t=window._bidsparkPrebidAnalytics;return t?.attachImaAdsManager?t.attachImaAdsManager(n,e):()=>{}},recordImpression:(n,e)=>{let t=window._bidsparkPrebidAnalytics;return t?.recordImpression?t.recordImpression(n,e):!1},getSessionId:()=>{let n=window._bidsparkPrebidAnalytics;return n?.getSessionId?n.getSessionId():te()},getPageviewId:()=>{let n=window._bidsparkPrebidAnalytics;return n?.getPageviewId?n.getPageviewId():""},getContext:()=>{let n=window._bidsparkPrebidAnalytics;return n?.getContext?n.getContext():{pageviewId:"",sessionId:te()}},setLogLevel:n=>{_.setLogLevel(n)},getLogLevel:()=>_.getLogLevel()}});return ui();})();
1
+ "use strict";var bidsparkPrebidAnalyticsBundle=(()=>{var B=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(i){throw t=[i],i}};var en=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};function rn(){if(typeof window<"u"){let n=window;return n.__bidsparkLogListeners||(n.__bidsparkLogListeners=new Set),n.__bidsparkLogListeners}return nn}function on(n){if((n<0||!Number.isFinite(n))&&(n=0),n<1e3)return`${n.toFixed(2)}ms`;let e=n/1e3;if(e<60)return`${e.toFixed(2)}s`;let t=Math.floor(e/60);return t<60?`${t}m ${(e%60).toFixed(2)}s`:`${Math.floor(t/60)}h ${t%60}m ${(e%60).toFixed(2)}s`}function K(n){if(typeof n=="string"){let e=n.toUpperCase();if(e==="DEBUG"||e==="INFO"||e==="WARN"||e==="ERROR")return e}return R.INFO}function Te(n){return new Ee(n)}var R,Ye,G,tn,nn,Ee,ze=B(()=>{"use strict";R={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},Ye={[R.DEBUG]:10,[R.INFO]:20,[R.WARN]:30,[R.ERROR]:40},G={badge:"color: #2dd4bf; font-weight: bold",badgeWarn:"background: #f59e0b; color: #fff; padding: 2px 4px; border-radius: 3px; font-weight: bold",badgeError:"background: #ef4444; color: #fff; padding: 2px 4px; border-radius: 3px; font-weight: bold",dim:"color: #6b7280",event:"color: #38bdf8; font-weight: bold",eventWarn:"color: #f59e0b; font-weight: bold",eventError:"color: #ef4444; font-weight: bold",reset:"color: inherit"},tn=0,nn=new Set;Ee=class{_prefix;_level;_loadedAt;_now;_console;_listeners=new Set;constructor(e={}){this._prefix=e.prefix??"[ads]",this._level=K(e.logLevel??R.INFO),this._now=e.now,this._console=e.console,e.onLog&&this._listeners.add(e.onLog),this._loadedAt=e.loadedAt??(this._now?this._now():typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now())}get prefix(){return this._prefix}set prefix(e){this._prefix=e}get logLevel(){return this._level}set logLevel(e){this._level=K(e)}getLevel(){return this._level}setLevel(e){this._level=K(e)}getPrefix(){return this._prefix}setPrefix(e){this._prefix=e}resetTiming(e){this._loadedAt=e??(this._now?this._now():typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now())}getLoadedAt(){return this._loadedAt}addListener(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}removeListener(e){this._listeners.delete(e)}isEnabled(e){let t=K(e);return(Ye[t]??20)>=(Ye[this._level]??20)}_getConsole(){if(this._console)return this._console;if(typeof console<"u")return console}_getElapsed(){let e=this._now?this._now():typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();return Math.max(0,e-this._loadedAt)}_dispatchRecord(e){for(let i of this._listeners)try{i(e)}catch{}let t=rn();for(let i of t)if(!this._listeners.has(i))try{i(e)}catch{}}log(e,t,...i){let r=K(e);if(!this.isEnabled(r))return;let o=this._getElapsed(),s=on(o),d=Date.now(),u={id:`bk_log_${d}_${++tn}`,timestamp:d,elapsedMs:o,level:r,prefix:this._prefix,message:t,args:i,data:i.length===1?i[0]:i.length>1?i:void 0};this._dispatchRecord(u);let c=this._getConsole();if(!c)return;let b=G.badge,p=G.event;r===R.WARN?(b=G.badgeWarn,p=G.eventWarn):r===R.ERROR&&(b=G.badgeError,p=G.eventError);let f=["%c%s%c %s %c%s%c",b,this._prefix,G.dim,s,p,t,G.reset];switch(i.length>0&&f.push(...i),r){case R.DEBUG:typeof c.log=="function"?c.log(...f):typeof c.debug=="function"&&c.debug(...f);break;case R.INFO:typeof c.info=="function"?c.info(...f):typeof c.log=="function"&&c.log(...f);break;case R.WARN:typeof c.warn=="function"?c.warn(...f):typeof c.log=="function"&&c.log(...f);break;case R.ERROR:typeof c.error=="function"?c.error(...f):typeof c.log=="function"&&c.log(...f);break;default:typeof c.log=="function"&&c.log(...f);break}}debug(e,...t){this.log(R.DEBUG,e,...t)}info(e,...t){this.log(R.INFO,e,...t)}warn(e,...t){this.log(R.WARN,e,...t)}error(e,...t){this.log(R.ERROR,e,...t)}logEvent(e){e&&(e.data!==void 0?this.log(e.level,e.eventName,e.data):this.log(e.level,e.eventName))}}});function Qe(){let n=0,e=0;for(let i=0;i<28;i+=7){let r=this.buf[this.pos++];if(n|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function ue(n,e,t){for(let o=0;o<28;o=o+7){let s=n>>>o,d=!(!(s>>>7)&&e==0),a=(d?s|128:s)&255;if(t.push(a),!d)return}let i=n>>>28&15|(e&7)<<4,r=e>>3!=0;if(t.push((r?i|128:i)&255),!!r){for(let o=3;o<31;o=o+7){let s=e>>>o,d=!!(s>>>7),a=(d?s|128:s)&255;if(t.push(a),!d)return}t.push(e>>>31&1)}}function we(n){let e=n[0]==="-";e&&(n=n.slice(1));let t=1e6,i=0,r=0;function o(s,d){let a=Number(n.slice(s,d));r*=t,i=i*t+a,i>=ce&&(r=r+(i/ce|0),i=i%ce)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),e?Je(i,r):Se(i,r)}function Ze(n,e){let t=Se(n,e),i=t.hi&2147483648;i&&(t=Je(t.lo,t.hi));let r=Ae(t.lo,t.hi);return i?"-"+r:r}function Ae(n,e){if({lo:n,hi:e}=sn(n,e),e<=2097151)return String(ce*e+n);let t=n&16777215,i=(n>>>24|e<<8)&16777215,r=e>>16&65535,o=t+i*6777216+r*6710656,s=i+r*8147497,d=r*2,a=1e7;return o>=a&&(s+=Math.floor(o/a),o%=a),s>=a&&(d+=Math.floor(s/a),s%=a),d.toString()+Xe(s)+Xe(o)}function sn(n,e){return{lo:n>>>0,hi:e>>>0}}function Se(n,e){return{lo:n|0,hi:e|0}}function Je(n,e){return e=~e,n?n=~n+1:e+=1,Se(n,e)}function Ce(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function et(){let n=this.buf[this.pos++],e=n&127;if((n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,(n&128)==0)return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;(n&128)!==0&&t<10;t++)n=this.buf[this.pos++];if((n&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}var ce,Xe,Re=B(()=>{"use strict";ce=4294967296;Xe=n=>{let e=String(n);return"0000000".slice(e.length)+e}});function dn(){let n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(!!globalThis.Deno||typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){let t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),r=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(s){let d=typeof s=="bigint"?s:BigInt(s);if(d>i||d<t)throw new Error(`invalid int64: ${s}`);return d},uParse(s){let d=typeof s=="bigint"?s:BigInt(s);if(d>o||d<r)throw new Error(`invalid uint64: ${s}`);return d},enc(s){return n.setBigInt64(0,this.parse(s),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(s){return n.setBigInt64(0,this.uParse(s),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(s,d){return n.setInt32(0,s,!0),n.setInt32(4,d,!0),n.getBigInt64(0,!0)},uDec(s,d){return n.setInt32(0,s,!0),n.setInt32(4,d,!0),n.getBigUint64(0,!0)}}}return{zero:"0",supported:!1,parse(t){return typeof t!="string"&&(t=t.toString()),tt(t),t},uParse(t){return typeof t!="string"&&(t=t.toString()),nt(t),t},enc(t){return typeof t!="string"&&(t=t.toString()),tt(t),we(t)},uEnc(t){return typeof t!="string"&&(t=t.toString()),nt(t),we(t)},dec(t,i){return Ze(t,i)},uDec(t,i){return Ae(t,i)}}}function tt(n){if(!/^-?[0-9]+$/.test(n))throw new Error("invalid int64: "+n)}function nt(n){if(!/^[0-9]+$/.test(n))throw new Error("invalid uint64: "+n)}var V,it=B(()=>{"use strict";Re();V=dn()});function Ue(){if(globalThis[_e]==null){let n=new globalThis.TextEncoder,e=new globalThis.TextDecoder;globalThis[_e]={encodeUtf8(t){return n.encode(t)},decodeUtf8(t){return e.decode(t)},checkUtf8(t){try{return encodeURIComponent(t),!0}catch{return!1}}}}return globalThis[_e]}var _e,Be=B(()=>{"use strict";_e=Symbol.for("@bufbuild/protobuf/text-encoding")});function xe(n){if(typeof n=="string")n=Number(n);else if(typeof n!="number")throw new Error("invalid int32: "+typeof n);if(!Number.isInteger(n)||n>ln||n<fn)throw new Error("invalid int32: "+n)}function rt(n){if(typeof n=="string")n=Number(n);else if(typeof n!="number")throw new Error("invalid uint32: "+typeof n);if(!Number.isInteger(n)||n>un||n<0)throw new Error("invalid uint32: "+n)}function hn(n){if(typeof n=="string"){let e=n;if(n=Number(n),Number.isNaN(n)&&e!=="NaN")throw new Error("invalid float32: "+e)}else if(typeof n!="number")throw new Error("invalid float32: "+typeof n);if(Number.isFinite(n)&&(n>an||n<cn))throw new Error("invalid float32: "+n)}var Y,an,cn,un,ln,fn,F,C,ot=B(()=>{"use strict";Re();it();Be();(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(Y||(Y={}));an=34028234663852886e22,cn=-34028234663852886e22,un=4294967295,ln=2147483647,fn=-2147483648,F=class{constructor(e=Ue().encodeUtf8){this.encodeUtf8=e,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let e=0;for(let r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let t=new Uint8Array(e),i=0;for(let r=0;r<this.chunks.length;r++)t.set(this.chunks[r],i),i+=this.chunks[r].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(rt(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return xe(e),Ce(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.encodeUtf8(e);return this.uint32(t.byteLength),this.raw(t)}float(e){hn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){rt(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){xe(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return xe(e),e=(e<<1^e>>31)>>>0,Ce(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=V.enc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=V.uEnc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=V.enc(e);return ue(t.lo,t.hi,this.buf),this}sint64(e){let t=V.enc(e),i=t.hi>>31,r=t.lo<<1^i,o=(t.hi<<1|t.lo>>>31)^i;return ue(r,o,this.buf),this}uint64(e){let t=V.uEnc(e);return ue(t.lo,t.hi,this.buf),this}},C=class{constructor(e,t=Ue().decodeUtf8){this.decodeUtf8=t,this.varint64=Qe,this.uint32=et,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case Y.Varint:for(;this.buf[this.pos++]&128;);break;case Y.Bit64:this.pos+=4;case Y.Bit32:this.pos+=4;break;case Y.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Y.StartGroup:for(;;){let[o,s]=this.tag();if(s===Y.EndGroup){if(t!==void 0&&o!==t)throw new Error("invalid end group tag");break}this.skip(s,o)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return V.dec(...this.varint64())}uint64(){return V.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,V.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return V.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return V.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.decodeUtf8(this.bytes())}}});var st=B(()=>{"use strict"});var dt=B(()=>{"use strict"});var at=B(()=>{"use strict"});var Oe=B(()=>{"use strict";ot();st();Be();dt();at()});function pn(){return{propertyId:new Uint8Array(0),pageviewId:new Uint8Array(0),sessionId:new Uint8Array(0),pageUrl:"",country:"",region:"",deviceType:"",userId:"",domain:"",events:[],browser:"",deviceManufacturer:"",deviceModel:"",city:"",postalCode:"",sampleRate:void 0,automated:!1}}function gn(){return{timestampMs:0,type:0,eventName:"",auctionId:new Uint8Array(0),transactionId:new Uint8Array(0),adUnitCode:"",bid:void 0,namespace:"",eventId:new Uint8Array(0),metadata:{},viewableDurationMs:void 0,bidderOutcomes:[]}}function yn(){return{key:"",value:""}}function mn(){return{adUnitCode:"",outcome:0,bid:void 0,refreshIndex:0,floorCents:void 0,floorSource:0,floorTreatmentBp:void 0,slot:""}}function bn(){return{bidder:"",cpm:0,currency:"",width:0,height:0,dealId:"",mediaType:"",latencyMs:0,advertiserDomain:"",creativeId:""}}var y,q,he,re,le,ct,ut,fe,pe=B(()=>{"use strict";Oe();y={TRACE_EVENT_TYPE_UNSPECIFIED:0,AUCTION_START:1,AUCTION_END:2,BID_WIN:4,IMPRESSION:5,VIEWABLE:6,TIME_IN_VIEW:7,ERROR:9,SLOT_DEFINED:10,SLOT_DESTROYED:11,CLICK:12,AD_RENDER_FAILED:13,WARN:17,CONSENT:19,RECOVERY:20,PAGEVIEW:21,UNRECOGNIZED:-1},q={BIDDER_OUTCOME_UNSPECIFIED:0,BIDDER_OUTCOME_BID:1,BIDDER_OUTCOME_NO_BID:2,BIDDER_OUTCOME_TIMEOUT:3,BIDDER_OUTCOME_ERROR:4,BIDDER_OUTCOME_NO_RESPONSE:5,UNRECOGNIZED:-1},he={FLOOR_SOURCE_UNSPECIFIED:0,FLOOR_SOURCE_STATIC:1,FLOOR_SOURCE_POOL:2,FLOOR_SOURCE_NONE:3,UNRECOGNIZED:-1};re={encode(n,e=new F){if(n.propertyId!==void 0&&n.propertyId.length!==0&&e.uint32(10).bytes(n.propertyId),n.pageviewId!==void 0&&n.pageviewId.length!==0&&e.uint32(18).bytes(n.pageviewId),n.sessionId!==void 0&&n.sessionId.length!==0&&e.uint32(26).bytes(n.sessionId),n.pageUrl!==void 0&&n.pageUrl!==""&&e.uint32(34).string(n.pageUrl),n.country!==void 0&&n.country!==""&&e.uint32(42).string(n.country),n.region!==void 0&&n.region!==""&&e.uint32(50).string(n.region),n.deviceType!==void 0&&n.deviceType!==""&&e.uint32(58).string(n.deviceType),n.userId!==void 0&&n.userId!==""&&e.uint32(66).string(n.userId),n.domain!==void 0&&n.domain!==""&&e.uint32(74).string(n.domain),n.events!==void 0&&n.events.length!==0)for(let t of n.events)le.encode(t,e.uint32(82).fork()).join();return n.browser!==void 0&&n.browser!==""&&e.uint32(90).string(n.browser),n.deviceManufacturer!==void 0&&n.deviceManufacturer!==""&&e.uint32(98).string(n.deviceManufacturer),n.deviceModel!==void 0&&n.deviceModel!==""&&e.uint32(106).string(n.deviceModel),n.city!==void 0&&n.city!==""&&e.uint32(114).string(n.city),n.postalCode!==void 0&&n.postalCode!==""&&e.uint32(122).string(n.postalCode),n.sampleRate!==void 0&&e.uint32(129).double(n.sampleRate),n.automated!==void 0&&n.automated!==!1&&e.uint32(136).bool(n.automated),e},decode(n,e){let t=n instanceof C?n:new C(n),i=e===void 0?t.len:t.pos+e,r=pn();for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==10)break;r.propertyId=t.bytes();continue}case 2:{if(o!==18)break;r.pageviewId=t.bytes();continue}case 3:{if(o!==26)break;r.sessionId=t.bytes();continue}case 4:{if(o!==34)break;r.pageUrl=t.string();continue}case 5:{if(o!==42)break;r.country=t.string();continue}case 6:{if(o!==50)break;r.region=t.string();continue}case 7:{if(o!==58)break;r.deviceType=t.string();continue}case 8:{if(o!==66)break;r.userId=t.string();continue}case 9:{if(o!==74)break;r.domain=t.string();continue}case 10:{if(o!==82)break;let s=le.decode(t,t.uint32());s!==void 0&&r.events.push(s);continue}case 11:{if(o!==90)break;r.browser=t.string();continue}case 12:{if(o!==98)break;r.deviceManufacturer=t.string();continue}case 13:{if(o!==106)break;r.deviceModel=t.string();continue}case 14:{if(o!==114)break;r.city=t.string();continue}case 15:{if(o!==122)break;r.postalCode=t.string();continue}case 16:{if(o!==129)break;r.sampleRate=t.double();continue}case 17:{if(o!==136)break;r.automated=t.bool();continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};le={encode(n,e=new F){if(n.timestampMs!==void 0&&n.timestampMs!==0&&e.uint32(9).double(n.timestampMs),n.type!==void 0&&n.type!==0&&e.uint32(16).int32(n.type),n.eventName!==void 0&&n.eventName!==""&&e.uint32(26).string(n.eventName),n.auctionId!==void 0&&n.auctionId.length!==0&&e.uint32(34).bytes(n.auctionId),n.transactionId!==void 0&&n.transactionId.length!==0&&e.uint32(42).bytes(n.transactionId),n.adUnitCode!==void 0&&n.adUnitCode!==""&&e.uint32(50).string(n.adUnitCode),n.bid!==void 0&&fe.encode(n.bid,e.uint32(58).fork()).join(),n.namespace!==void 0&&n.namespace!==""&&e.uint32(66).string(n.namespace),n.eventId!==void 0&&n.eventId.length!==0&&e.uint32(74).bytes(n.eventId),globalThis.Object.entries(n.metadata||{}).forEach(([t,i])=>{ct.encode({key:t,value:i},e.uint32(82).fork()).join()}),n.viewableDurationMs!==void 0&&e.uint32(89).double(n.viewableDurationMs),n.bidderOutcomes!==void 0&&n.bidderOutcomes.length!==0)for(let t of n.bidderOutcomes)ut.encode(t,e.uint32(98).fork()).join();return e},decode(n,e){let t=n instanceof C?n:new C(n),i=e===void 0?t.len:t.pos+e,r=gn();for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==9)break;r.timestampMs=t.double();continue}case 2:{if(o!==16)break;r.type=t.int32();continue}case 3:{if(o!==26)break;r.eventName=t.string();continue}case 4:{if(o!==34)break;r.auctionId=t.bytes();continue}case 5:{if(o!==42)break;r.transactionId=t.bytes();continue}case 6:{if(o!==50)break;r.adUnitCode=t.string();continue}case 7:{if(o!==58)break;r.bid=fe.decode(t,t.uint32());continue}case 8:{if(o!==66)break;r.namespace=t.string();continue}case 9:{if(o!==74)break;r.eventId=t.bytes();continue}case 10:{if(o!==82)break;let s=ct.decode(t,t.uint32());s.value!==void 0&&(r.metadata[s.key]=s.value);continue}case 11:{if(o!==89)break;r.viewableDurationMs=t.double();continue}case 12:{if(o!==98)break;let s=ut.decode(t,t.uint32());s!==void 0&&r.bidderOutcomes.push(s);continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};ct={encode(n,e=new F){return n.key!==""&&e.uint32(10).string(n.key),n.value!==""&&e.uint32(18).string(n.value),e},decode(n,e){let t=n instanceof C?n:new C(n),i=e===void 0?t.len:t.pos+e,r=yn();for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==10)break;r.key=t.string();continue}case 2:{if(o!==18)break;r.value=t.string();continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};ut={encode(n,e=new F){return n.adUnitCode!==void 0&&n.adUnitCode!==""&&e.uint32(18).string(n.adUnitCode),n.outcome!==void 0&&n.outcome!==0&&e.uint32(32).int32(n.outcome),n.bid!==void 0&&fe.encode(n.bid,e.uint32(50).fork()).join(),n.refreshIndex!==void 0&&n.refreshIndex!==0&&e.uint32(56).int32(n.refreshIndex),n.floorCents!==void 0&&e.uint32(64).int32(n.floorCents),n.floorSource!==void 0&&n.floorSource!==0&&e.uint32(72).int32(n.floorSource),n.floorTreatmentBp!==void 0&&e.uint32(80).int32(n.floorTreatmentBp),n.slot!==void 0&&n.slot!==""&&e.uint32(90).string(n.slot),e},decode(n,e){let t=n instanceof C?n:new C(n),i=e===void 0?t.len:t.pos+e,r=mn();for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 2:{if(o!==18)break;r.adUnitCode=t.string();continue}case 4:{if(o!==32)break;r.outcome=t.int32();continue}case 6:{if(o!==50)break;r.bid=fe.decode(t,t.uint32());continue}case 7:{if(o!==56)break;r.refreshIndex=t.int32();continue}case 8:{if(o!==64)break;r.floorCents=t.int32();continue}case 9:{if(o!==72)break;r.floorSource=t.int32();continue}case 10:{if(o!==80)break;r.floorTreatmentBp=t.int32();continue}case 11:{if(o!==90)break;r.slot=t.string();continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};fe={encode(n,e=new F){return n.bidder!==void 0&&n.bidder!==""&&e.uint32(10).string(n.bidder),n.cpm!==void 0&&n.cpm!==0&&e.uint32(17).double(n.cpm),n.currency!==void 0&&n.currency!==""&&e.uint32(26).string(n.currency),n.width!==void 0&&n.width!==0&&e.uint32(32).int32(n.width),n.height!==void 0&&n.height!==0&&e.uint32(40).int32(n.height),n.dealId!==void 0&&n.dealId!==""&&e.uint32(50).string(n.dealId),n.mediaType!==void 0&&n.mediaType!==""&&e.uint32(58).string(n.mediaType),n.latencyMs!==void 0&&n.latencyMs!==0&&e.uint32(65).double(n.latencyMs),n.advertiserDomain!==void 0&&n.advertiserDomain!==""&&e.uint32(74).string(n.advertiserDomain),n.creativeId!==void 0&&n.creativeId!==""&&e.uint32(82).string(n.creativeId),e},decode(n,e){let t=n instanceof C?n:new C(n),i=e===void 0?t.len:t.pos+e,r=bn();for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==10)break;r.bidder=t.string();continue}case 2:{if(o!==17)break;r.cpm=t.double();continue}case 3:{if(o!==26)break;r.currency=t.string();continue}case 4:{if(o!==32)break;r.width=t.int32();continue}case 5:{if(o!==40)break;r.height=t.int32();continue}case 6:{if(o!==50)break;r.dealId=t.string();continue}case 7:{if(o!==58)break;r.mediaType=t.string();continue}case 8:{if(o!==65)break;r.latencyMs=t.double();continue}case 9:{if(o!==74)break;r.advertiserDomain=t.string();continue}case 10:{if(o!==82)break;r.creativeId=t.string();continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}}});function L(n){if(!n)return new Uint8Array(0);let e=n.trim();e.startsWith("{")&&e.endsWith("}")&&(e=e.slice(1,-1).trim());let t=e.toLowerCase();if(In.test(t)){let r=t.replace(/-/g,""),o=new Uint8Array(16);for(let s=0;s<16;s++)o[s]=parseInt(r.slice(s*2,s*2+2),16);return o}if(lt)return lt.encode(n);let i=new Uint8Array(n.length);for(let r=0;r<n.length;r++)i[r]=n.charCodeAt(r)&255;return i}function J(n){return typeof n!="number"||!Number.isFinite(n)||n<=0||n>1?1:n}function De(n,e){let t=J(e);if(t>=1||!n)return!0;let i=2166136261;for(let r=0;r<n.length;r++)i^=n.charCodeAt(r),i=Math.imul(i,16777619);return(i>>>0)/4294967296<t}function ke(){let n=typeof globalThis<"u"?globalThis:void 0,e=n&&"navigator"in n?n.navigator:void 0;if(!e)return!1;if(e.webdriver===!0)return!0;let t=typeof e.userAgent=="string"?e.userAgent:"";if(vn.test(t))return!0;let i=n&&"window"in n?n.window:n,r=0;if(i&&typeof i.outerWidth=="number"&&typeof i.outerHeight=="number"&&i.outerWidth===0&&i.outerHeight===0&&r++,Array.isArray(e.languages)&&e.languages.length===0&&r++,En.test(t)&&!Tn.test(t)){i&&!i.chrome&&r++;let o=e.plugins;o!=null&&o.length===0&&r++}return r>=2}var In,lt,Di,vn,En,Tn,ge=B(()=>{"use strict";In=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,lt=typeof TextEncoder<"u"?new TextEncoder:null,Di=typeof TextDecoder<"u"?new TextDecoder:null;vn=/headless|phantomjs|slimerjs|puppeteer|playwright/i,En=/Chrome\/\d+/i,Tn=/Mobile|Android|iPhone|iPad|iPod|CriOS|FxiOS|Edg\/|OPR\/|SamsungBrowser/i});function wn(){return{unit:0,usageId:new Uint8Array(0),timestampMs:"0",slots:0}}function An(){return{pageviewId:new Uint8Array(0),events:[]}}var ht,ft,pt,gt=B(()=>{"use strict";Oe();ht={USAGE_UNIT_UNSPECIFIED:0,AUCTION:1,SERVER_AUCTION:2,UNRECOGNIZED:-1};ft={encode(n,e=new F){return n.unit!==void 0&&n.unit!==0&&e.uint32(8).int32(n.unit),n.usageId!==void 0&&n.usageId.length!==0&&e.uint32(18).bytes(n.usageId),n.timestampMs!==void 0&&n.timestampMs!=="0"&&e.uint32(24).int64(n.timestampMs),n.slots!==void 0&&n.slots!==0&&e.uint32(32).uint32(n.slots),e},decode(n,e){let t=n instanceof C?n:new C(n),i=e===void 0?t.len:t.pos+e,r=wn();for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==8)break;r.unit=t.int32();continue}case 2:{if(o!==18)break;r.usageId=t.bytes();continue}case 3:{if(o!==24)break;r.timestampMs=t.int64().toString();continue}case 4:{if(o!==32)break;r.slots=t.uint32();continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};pt={encode(n,e=new F){if(n.pageviewId!==void 0&&n.pageviewId.length!==0&&e.uint32(10).bytes(n.pageviewId),n.events!==void 0&&n.events.length!==0)for(let t of n.events)ft.encode(t,e.uint32(18).fork()).join();return e},decode(n,e){let t=n instanceof C?n:new C(n),i=e===void 0?t.len:t.pos+e,r=An();for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==10)break;r.pageviewId=t.bytes();continue}case 2:{if(o!==18)break;let s=ft.decode(t,t.uint32());s!==void 0&&r.events.push(s);continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}}});function oe(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}var Ne,yt=B(()=>{"use strict";pe();ge();Ne="text/plain"});var Cn,mt,ye,bt=B(()=>{"use strict";gt();yt();ge();Cn=1e4,mt=200,ye=class{endpoint;propertyId;pageviewIdStr;pageviewIdBytes;queue=[];flushTimer=null;boundPageHide;boundVisibilityChange;isDestroyed=!1;constructor(e){this.endpoint=(e.endpoint||"").replace(/\/+$/,""),this.propertyId=e.propertyId||"",this.pageviewIdStr=e.pageviewId||oe();let t=L(this.pageviewIdStr);this.pageviewIdBytes=t.length===16?t:L(oe()),this.boundPageHide=()=>this.flush(),this.boundVisibilityChange=()=>{typeof document<"u"&&document.visibilityState==="hidden"&&this.flush()},typeof window<"u"&&(window.addEventListener("pagehide",this.boundPageHide),typeof document<"u"&&document.addEventListener("visibilitychange",this.boundVisibilityChange))}getEndpoint(){return this.endpoint}setEndpoint(e){this.endpoint=(e||"").replace(/\/+$/,"")}getPropertyId(){return this.propertyId}setPropertyId(e){this.propertyId=e||""}getPageviewId(){return this.pageviewIdStr}setPageviewId(e){this.pageviewIdStr=e||oe(),this.pageviewIdBytes=L(this.pageviewIdStr)}getQueueLength(){return this.queue.length}record(e,t,i=ht.AUCTION){if(this.isDestroyed||!e)return;let r=L(e);if(r.length!==16&&(r=L(oe())),this.queue.push({unit:i,usageId:r,timestampMs:String(Date.now()),slots:typeof t=="number"&&t>0?t:0}),this.queue.length>=mt){this.flush();return}!this.flushTimer&&typeof setTimeout<"u"&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},Cn))}flush(){if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.queue.length===0||!this.endpoint||!this.propertyId)return!1;let e=!1;for(;this.queue.length>0;){let t=this.queue.splice(0,mt),i={pageviewId:this.pageviewIdBytes,events:t},r=pt.encode(i).finish(),s=`${this.endpoint.replace(new RegExp(`/${this.propertyId}$`),"")}/${this.propertyId}`,d=!1;if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function")try{let u=new Blob([r],{type:Ne});d=navigator.sendBeacon(s,u)}catch{d=!1}let a=typeof globalThis<"u"&&typeof globalThis.fetch=="function"?globalThis.fetch:typeof fetch=="function"?fetch:null;if(!d&&a)try{a(s,{method:"POST",headers:{"Content-Type":Ne},body:r,keepalive:!0}).catch(()=>{}),d=!0}catch{d=!1}d&&(e=!0)}return e}destroy(){this.queue.length>0&&this.flush(),this.isDestroyed=!0,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),typeof window<"u"&&(window.removeEventListener("pagehide",this.boundPageHide),typeof document<"u"&&document.removeEventListener("visibilitychange",this.boundVisibilityChange))}}});function Q(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}function Gn(n){let e="";for(let i=0;i<n.length;i+=8192)e+=String.fromCharCode(...n.subarray(i,i+8192));return btoa(e)}function Yn(n){let e=atob(n),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}function zn(n){if(!n)return!1;let e;try{e=new URL(n)}catch{return!1}return e.username||e.password?!1:e.protocol==="https:"?!0:e.protocol==="http:"?e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]":!1}function Xn(n){let e={},t=0;for(let i of Object.keys(n)){if(t>=xn)break;let r=n[i];if(r==null)continue;let o=String(r);e[i]=o.length>Tt?`${o.slice(0,Tt)}...[truncated]`:o,t++}return e}function Qn(n,e){if(!n||!e)return!1;try{return new URL(n).origin===new URL(e).origin}catch{return!1}}function Ct(n){if(!n)return"";try{let e=new URL(n);return e.origin+e.pathname}catch{return n}}function xt(n){try{typeof localStorage<"u"&&(localStorage.setItem(Fe,n.toString()),X=n)}catch{}}function Ot(n=Date.now()){return j>0&&n-j<=Bt}function ei(n){return Lt(),Pe.add(n),()=>{Pe.delete(n)}}function de(){let n=Date.now(),e=!!O&&!Ot(n);if(j=n,e){O=null;for(let t of Pe)t();return}!H||!O||X===0||n-X<Zn||xt(n)}function ti(){return!O||H&&X===0}function Lt(){if(Rt||typeof window>"u")return;Rt=!0;let n=()=>de();for(let e of Jn)window.addEventListener(e,n,{passive:!0,capture:!0});typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&de()})}function te(){let n=Date.now(),e=!!O&&Ot(n);try{if(H&&typeof localStorage<"u"){let t=localStorage.getItem(Me),i=localStorage.getItem(Fe),r=i&&parseInt(i,10)||0;if(t&&r&&n-r<=Bt)return O!==t&&(be=!1),(O!==t||j<r)&&(O=t,j=Math.max(j,r)),X===0&&(X=r),t;let o=e?O:Q();return e||(be=!0,j=n),localStorage.setItem(Me,o),xt(j),O=o,o}}catch{}return e||(be=!0,O=Q(),j=n),O}function Dt(){X=0;try{typeof localStorage<"u"&&(localStorage.removeItem(Me),localStorage.removeItem(Fe))}catch{}}function _t(){try{if(H&&typeof localStorage<"u"){let n=localStorage.getItem(ne);if(n)return n;let e=O||Q();return localStorage.setItem(ne,e),e}}catch{}return""}function kt(){try{typeof localStorage<"u"&&localStorage.removeItem(ne)}catch{}}function $e(n){return n.regime!=="tcf"||!!n.purposesConsented?.includes(1)}function ni(n){let e=[];if(n?.purpose?.consents)for(let[t,i]of Object.entries(n.purpose.consents))i&&e.push(Number(t));return{regime:n?.gdprApplies===!1?"us":"tcf",action:"replay",cmpId:n?.cmpId??0,cmpVersion:n?.cmpVersion??0,purposesConsented:e}}function Nt(n,e){if(!e||!n)return;if(n.eventStatus==="cmpuishown"&&!n.tcString)return!1;let t=$e(ni(n));return t||(Dt(),kt()),t}function ii(){if(typeof window>"u")return;let n=window;if(typeof n.__tcfapi!="function")return;let e;try{n.__tcfapi("getTCData",2,(t,i)=>{e=Nt(t,i)})}catch{}return e!==void 0?e:!1}function ri(){if(typeof window>"u")return;let n=window;if(!(typeof n.__tcfapi!="function"||Ut===n.__tcfapi)){Ut=n.__tcfapi;try{n.__tcfapi("addEventListener",2,(e,t)=>{let i=Nt(e,t);i!==void 0&&_.setStorageAllowed(i)})}catch{}}}function oi(n){if(typeof window>"u")return;let e=window,t=e[n]?.consent?.getRecord?.()||null;return t?$e(t):e[`__${n}_cmp`]?.gdpr?!1:void 0}function l(n){return String(n??"").replace(/%/g,"%25").replace(/:/g,"%3A")}function si(n,e){switch(n){case"auctionInit":return`auctionInit:${l(e?.auctionId)}`;case"auctionEnd":return`auctionEnd:${l(e?.auctionId)}`;case"bidRequested":{let t=Array.isArray(e?.bids)?e.bids.map(i=>l(i?.bidId||i?.transactionId||i?.adUnitCode)).join(","):"";return`bidRequested:${l(e?.auctionId)}:${l(e?.bidderCode||e?.bidder)}:${t}`}case"bidResponse":{let t=e||{},i=t.creativeId||t.adId||t.requestId||t.bidId||"",r=t.originalCpm??t.cpm??"";return`bidResponse:${l(t.auctionId)}:${l(t.adUnitCode)}:${l(t.bidderCode||t.bidder)}:${l(i)}:${l(r)}`}case"bidTimeout":return"bidTimeout:"+(Array.isArray(e)?e:e?[e]:[]).map(i=>`${l(i?.auctionId)}:${l(i?.bidderCode||i?.bidder)}:${l(i?.bidId||i?.transactionId||i?.adUnitCode)}`).join(",");case"bidWon":{let t=e||{},i=t.creativeId||t.adId||t.requestId||t.bidId||"",r=t.originalCpm??t.cpm??"";return`bidWon:${l(t.auctionId)}:${l(t.adUnitCode)}:${l(t.bidderCode||t.bidder)}:${l(i)}:${l(r)}`}case"noBid":return`noBid:${l(e?.auctionId)}:${l(e?.adUnitCode)}:${l(e?.bidderCode||e?.bidder)}:${l(e?.bidId||e?.transactionId)}`;case"adRenderFailed":{let t=e?.bid||{};return`adRenderFailed:${l(t.auctionId||e?.auctionId)}:${l(t.adUnitCode||e?.adUnitCode)}:${l(t.bidderCode||t.bidder||e?.bidderCode||e?.bidder)}:${l(e?.reason)}:${l(e?.message)}`}case"adRenderSucceeded":{let t=e?.bid||e||{},i=t.creativeId||t.adId||e?.adId||"",r=t.originalCpm??t.cpm??"";return`adRenderSucceeded:${l(t.auctionId||e?.auctionId)}:${l(t.adUnitCode||e?.adUnitCode)}:${l(t.bidderCode||t.bidder)}:${l(i)}:${l(r)}`}case"setTargeting":return`setTargeting:${Object.keys(e||{}).sort().map(l).join(",")}`;case"auctionDebug":return`auctionDebug:${l(e?.type)}:${l(String(e?.arguments?.[0]??"").slice(0,50))}`;default:return""}}function k(n){if(Number.isFinite(n?.width)&&n.width>0&&Number.isFinite(n?.height)&&n.height>0)return{width:n.width,height:n.height};if(Number.isFinite(n?.w)&&n.w>0&&Number.isFinite(n?.h)&&n.h>0)return{width:n.w,height:n.h};if(Number.isFinite(n?.playerWidth)&&n.playerWidth>0&&Number.isFinite(n?.playerHeight)&&n.playerHeight>0)return{width:n.playerWidth,height:n.playerHeight};let e=n?.mediaTypes?.video?.playerSize;if(Array.isArray(e)&&e.length>0){let r=Array.isArray(e[0])?e[0]:e;if(Number.isFinite(r[0])&&r[0]>0&&Number.isFinite(r[1])&&r[1]>0)return{width:r[0],height:r[1]}}if(typeof n?.size=="string"){let r=n.size.match(/^(\d+)x(\d+)$/);if(r)return{width:Number(r[1]),height:Number(r[2])}}let t=Number.isFinite(n?.width)?n.width:Number.isFinite(n?.w)?n.w:Number.isFinite(n?.playerWidth)?n.playerWidth:0,i=Number.isFinite(n?.height)?n.height:Number.isFinite(n?.h)?n.h:Number.isFinite(n?.playerHeight)?n.playerHeight:0;return{width:t,height:i}}function me(n,e){return Number.isFinite(n?.cpm)?{cpm:n.cpm,currency:n?.currency||n?.originalCurrency||e?.currency||"USD"}:Number.isFinite(n?.originalCpm)?{cpm:n.originalCpm,currency:n?.originalCurrency||n?.currency||e?.currency||"USD"}:{cpm:e?.cpm??0,currency:e?.currency||n?.currency||n?.originalCurrency||"USD"}}function ee(n,e=!0){if(!n)return null;if(Array.isArray(n)){let t=n.find(i=>i?.provider==="bidspark")??(e?n.find(i=>i&&typeof i=="object"&&i.provider===void 0):void 0);return t?ee(t,e):null}if(typeof n=="object"){if(n.options&&typeof n.options=="object")return n.options;if(n.config&&typeof n.config=="object")return n.config;if(n.propertyId||n.endpoint)return n}return null}function di(n){if(!n)return null;if(n._bidsparkAnalyticsConfig){let t=ee(n._bidsparkAnalyticsConfig);if(t)return t}let e=n.bidsparkPrebidAnalytics;if(e){if(e.options){let t=ee(e.options);if(t)return t}if(e.config){let t=ee(e.config);if(t)return t}if(e.propertyId)return ee(e)}return null}function We(n="pbjs",e){let t=typeof window<"u"?window:{};t[n]=t[n]||{};let i=t[n],r=s=>{let d=t._bidsparkPrebidAnalytics,a=d?.getEndpoint?.()||"",u=e?.usageEndpoint||"https://by.bidspark.io/u",c={pbjsGlobalName:n,...e,...s};if(c.usageEndpoint=u,a&&!Qn(c.endpoint||"",a)&&(Z.warn(`Ignoring analytics endpoint change to ${c.endpoint||"(empty)"}: this page is pinned to ${a}. Reload to change the ingest endpoint.`),c.endpoint=a),d)try{d.disable()}catch(p){Z.warn("Failed to disable previous analytics instance:",p)}let b=new _(c);return d&&!c.pageviewId&&b.continuePageview(d),b.enable(),t._bidsparkPrebidAnalytics=b,b},o=()=>{try{if(i.adapterManager&&typeof i.adapterManager.registerAnalyticsAdapter=="function"){let d={enableAnalytics:a=>{let u=ee(a,!Array.isArray(a));u&&r(u)},disableAnalytics:()=>{t._bidsparkPrebidAnalytics&&t._bidsparkPrebidAnalytics.disable()}};i.adapterManager.registerAnalyticsAdapter({adapter:{...d},code:"bidspark"})}let s=di(t);s&&(s.propertyId||e?.propertyId)&&r(s)}catch(s){Z.warn("Failed to register standard Prebid analytics adapter:",s)}};i.adapterManager&&typeof i.adapterManager.registerAnalyticsAdapter=="function"?o():(i.que=i.que||[],i.que.push(o))}var It,vt,Rn,_n,se,Un,Bn,Et,Tt,xn,wt,At,On,Ln,Dn,kn,Nn,Mn,Pn,Vn,z,Fn,$n,Wn,Kn,qn,jn,Me,Fe,Bt,Hn,O,j,be,St,H,Zn,X,Jn,Rt,Pe,ne,Ut,Ve,Z,_,Ke=B(()=>{"use strict";ze();pe();ge();bt();It="ads",vt=1e4,Rn=50,_n=20,se=200,Un=300*1e3,Bn=10,Et=32*1024,Tt=1024,xn=16,wt="text/plain",At="ads_pending_",On=20,Ln=7200*1e3,Dn=1e4,kn={auctionStart:y.AUCTION_START,auctionEnd:y.AUCTION_END,bidWin:y.BID_WIN,adRenderFailed:y.AD_RENDER_FAILED,click:y.CLICK,impression:y.IMPRESSION,timeInView:y.TIME_IN_VIEW,viewable:y.VIEWABLE},Nn={WARN:y.WARN,ERROR:y.ERROR},Mn=new Set([y.ERROR,y.WARN]),Pn=3e3,Vn=new Set([y.IMPRESSION,y.BID_WIN,y.CLICK]),z=1800*1e3,Fn=200,$n=1e3,Wn=50,Kn=200,qn={static:he.FLOOR_SOURCE_STATIC,pool:he.FLOOR_SOURCE_POOL,none:he.FLOOR_SOURCE_NONE},jn=1e3,Me="ads_session",Fe="ads_session_ts",Bt=1800*1e3,Hn=/^[a-zA-Z0-9:_.-]{1,64}$/,O=null,j=0,be=!1,St="",H=!0;Zn=60*1e3,X=0,Jn=["pointerdown","pointermove","keydown","scroll","wheel","touchstart"],Rt=!1,Pe=new Set;ne="ads_uid";Ut=null;Ve=class{seenObjects=new WeakMap;seenKeys=new Set;isDuplicate(e,t){if(!t)return!1;if(typeof t=="object"){let r=this.seenObjects.get(t);if(r){if(r.has(e))return!0;r.add(e)}else this.seenObjects.set(t,new Set([e]))}let i=si(e,t);if(i){if(this.seenKeys.has(i))return!0;if(this.seenKeys.size>=1e3){let r=this.seenKeys.values().next().value;r!==void 0&&this.seenKeys.delete(r)}this.seenKeys.add(i)}return!1}};Z=Te({prefix:"[analytics]",logLevel:"INFO"}),_=class n{static activeInstances=new Set;static allInstances=new Set;static getActiveInstances(){return n.activeInstances}static setLogLevel(e){let t=K(e);Z.setLevel(t);for(let i of n.allInstances)i.setLogLevel(t)}static getLogLevel(){return Z.getLevel()}static setStorageAllowed(e){H=e,X=0;for(let t of n.allInstances)t.applyStorageAllowed(e)}static isStorageAllowed(){return H}config;usageRecorder=null;queue=[];errorCount=0;flushTimer=null;boundFlushBeacon;boundVisibilityChange;isEnabled=!1;boundPbjsHandlers=[];pageUrl="";deduper=new Ve;consecutiveSendFailures=0;nextSendAllowedAt=0;replayedEventCount=0;revenueFlushTimer=null;persistedBatchKeys=[];persistedCleanupTimer=null;intersectionObserver=null;slotViewabilityRecords=new Map;elementToSlotId=new Map;slotRefreshIndices=new Map;slotNames=new Map;slotAdSessionCounters=new Map;slotLastAuctionIds=new Map;pendingViewableListeners=new Map;slotElements=new Map;clickDetachCleanups=new Set;lastClickAt=new Map;slotEmittedImpressionKeys=new Set;cachedWinningBids=new Map;videoDetachCleanups=new Set;auctionBidderOutcomes=new Map;floorDecisions=new Map;recordedConsentKeys=new Set;consentCount=0;cmpDetach=null;sessionResumeUnsub=null;pageviewEmitted=!1;logger;managesSessionId;configuredUserId;managesVisitorId;visitorKeyLocked;constructor(e){let t=ii();typeof window<"u"&&typeof window.__tcfapi=="function"&&ri();let i=e.storageAllowed??t??oi(e.alias||It);i!==void 0&&n.setStorageAllowed(i);let r=i!==void 0?i:H,o=e.endpoint||"",s=!o||zn(o)?o:"",d=e.pageviewId||Q();de(),this.managesSessionId=!e.sessionId;let a=e.sessionId||te();this.configuredUserId=e.userId||"";let u="";if(r&&(u=this.configuredUserId||_t(),this.configuredUserId))try{typeof localStorage<"u"&&localStorage.setItem(ne,this.configuredUserId)}catch{}this.managesVisitorId=!e.visitorId&&!e.userId&&!e.sessionId,this.visitorKeyLocked=r||!this.managesVisitorId;let c=e.usageEndpoint||"";this.config={endpoint:s,usageEndpoint:c,propertyId:e.propertyId||"",pageviewId:d,sessionId:a,userId:u,visitorId:e.visitorId||this.configuredUserId||u||a,deviceType:e.deviceType||"desktop",country:e.country||"",region:e.region||"",auctionEnabled:e.auctionEnabled??!0,warningsEnabled:e.warningsEnabled??!0,sampleRate:J(e.sampleRate),viewabilityEnabled:e.viewabilityEnabled??!0,storageAllowed:r,logLevel:e.logLevel?K(e.logLevel):Z.getLevel(),pbjsGlobalName:e.pbjsGlobalName||"pbjs",attachPbjsListeners:e.attachPbjsListeners??!0,revenueFlushDelayMs:Number.isFinite(e.revenueFlushDelayMs)&&e.revenueFlushDelayMs>=0?e.revenueFlushDelayMs:Pn,alias:e.alias||It,events:e.events||{}},n.allInstances.add(this),this.logger=Te({prefix:"[analytics]",logLevel:this.config.logLevel}),o&&!s&&this.log("ERROR",`Rejected untrusted analytics endpoint ${o}: must be an absolute https:// URL without embedded credentials. Events will not be transmitted.`),this.boundFlushBeacon=()=>{this.flushAllSlotsTimeInView(),this.flushBeacon()},this.boundVisibilityChange=()=>this.handleVisibilityChange()}applyStorageAllowed(e){if(this.config.storageAllowed=e,!e){this.config.userId="";return}this.syncSessionId(),this.config.userId||(this.config.userId=this.configuredUserId||_t()),this.managesVisitorId&&!this.visitorKeyLocked&&(this.config.visitorId=this.config.userId||this.config.sessionId,this.visitorKeyLocked=!0,this.isSampledVisitor()||(this.queue=[],this.revenueFlushTimer&&(clearTimeout(this.revenueFlushTimer),this.revenueFlushTimer=null))),this.isEnabled&&this.resendPersistedBatches()}setLogLevel(e){let t=K(e);this.config.logLevel=t,this.logger.setLevel(t),Z.setLevel(t)}getLogLevel(){return this.logger.getLevel()}enable(){if(!this.isEnabled){if(this.isEnabled=!0,n.activeInstances.add(this),n.allInstances.add(this),this.logger.setLevel(this.config.logLevel),this.config.attachPbjsListeners&&this.config.usageEndpoint&&!this.usageRecorder&&(this.usageRecorder=new ye({endpoint:this.config.usageEndpoint,propertyId:this.config.propertyId,pageviewId:this.config.pageviewId})),this.config.endpoint||this.log("WARN","Endpoint is empty. Analytics events will not be transmitted."),this.config.viewabilityEnabled&&typeof IntersectionObserver<"u"){this.intersectionObserver=new IntersectionObserver(this.handleIntersection.bind(this),{threshold:[.5]});for(let e of this.slotViewabilityRecords.values())e.element&&this.intersectionObserver.observe(e.element)}this.config.attachPbjsListeners&&this.attachPbjs(),this.cmpDetach=this.attachCmp(),typeof window<"u"&&(this.pageUrl||(this.pageUrl=Ct(window.location.href)),window.addEventListener("pagehide",this.boundFlushBeacon),typeof document<"u"&&document.addEventListener("visibilitychange",this.boundVisibilityChange),Lt(),this.sessionResumeUnsub=ei(()=>this.syncSessionAndRotateVisitor()),this.syncSessionId(),this.pageviewEmitted||(this.pageviewEmitted=!0,this.emitPageEvent("pageview"),this.enqueue(y.PAGEVIEW,"pageview",{})),this.flushTimer=setInterval(()=>this.flush(),vt),this.resendPersistedBatches())}}attachPbjs(){if(!this.isEnabled)return!1;if(this.boundPbjsHandlers.length>0)return!0;let t=(typeof window<"u"?window:{})[this.config.pbjsGlobalName]||{};if(typeof t.onEvent!="function")return this.log("WARN","pbjs.onEvent is not defined. Prebid analytics will not function."),!1;this.log("DEBUG","Attaching event listeners to pbjs");let i={auctionInit:this.handleAuctionInit.bind(this),auctionEnd:this.handleAuctionEnd.bind(this),bidRequested:this.handleBidRequested.bind(this),bidResponse:this.handleBidResponse.bind(this),bidTimeout:this.handleBidTimeout.bind(this),bidWon:this.handleBidWon.bind(this),noBid:this.handleNoBid.bind(this),adRenderFailed:this.handleAdRenderFailed.bind(this),adRenderSucceeded:this.handleAdRenderSucceeded.bind(this)};for(let[r,o]of Object.entries(i))t.onEvent(r,o),this.boundPbjsHandlers.push({event:r,handler:o});if(typeof t.getEvents=="function")try{let r=t.getEvents();if(Array.isArray(r)){let o=r.slice(this.replayedEventCount);if(this.replayedEventCount=r.length,o.length>0){this.log("DEBUG",`Replaying ${o.length} historical events from pbjs.getEvents()`);for(let s of o){if(!s)continue;let d=s.eventType||s.event||s.name,a=s.args!==void 0?s.args:s.data!==void 0?s.data:s,u=i[d];u&&u(a)}}}}catch(r){this.log("WARN","Failed to replay historical events from pbjs.getEvents()",r)}return!0}disable(){if(this.isEnabled){this.flushAllSlotsTimeInView(),this.isEnabled=!1,n.activeInstances.delete(this),n.allInstances.delete(this),this.usageRecorder&&(this.usageRecorder.destroy(),this.usageRecorder=null);for(let e of this.slotViewabilityRecords.values())e.dwellTimer&&(clearTimeout(e.dwellTimer),e.dwellTimer=null,e.dwellStartedAt=null);this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.slotViewabilityRecords.clear(),this.elementToSlotId.clear();for(let e of this.videoDetachCleanups)try{e()}catch{}this.videoDetachCleanups.clear();for(let e of Array.from(this.clickDetachCleanups))try{e()}catch{}if(this.clickDetachCleanups.clear(),this.slotElements.clear(),this.cachedWinningBids.clear(),this.slotEmittedImpressionKeys.clear(),this.slotLastAuctionIds.clear(),this.auctionBidderOutcomes.clear(),this.floorDecisions.clear(),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.revenueFlushTimer&&(clearTimeout(this.revenueFlushTimer),this.revenueFlushTimer=null),this.persistedCleanupTimer&&(clearTimeout(this.persistedCleanupTimer),this.persistedCleanupTimer=null),typeof window<"u"&&(window.removeEventListener("pagehide",this.boundFlushBeacon),typeof document<"u"&&document.removeEventListener("visibilitychange",this.boundVisibilityChange)),this.boundPbjsHandlers.length>0){let t=(typeof window<"u"?window:{})[this.config.pbjsGlobalName]||{};if(typeof t.offEvent=="function")for(let{event:i,handler:r}of this.boundPbjsHandlers)t.offEvent(i,r);this.boundPbjsHandlers=[]}if(this.cmpDetach){try{this.cmpDetach()}catch{}this.cmpDetach=null}this.sessionResumeUnsub?.(),this.sessionResumeUnsub=null,this.flush()}}handleVisibilityChange(){if(!(typeof document>"u")){if(document.visibilityState==="hidden"){let e=typeof performance<"u"&&performance.now?performance.now():Date.now();for(let t of this.slotViewabilityRecords.values()){t.inView&&t.lastEnteredViewAt!==null&&(t.accumulatedTimeInViewMs+=Math.max(0,e-t.lastEnteredViewAt),t.lastEnteredViewAt=null),t.dwellTimer&&(clearTimeout(t.dwellTimer),t.dwellTimer=null,t.dwellStartedAt=null);let i=Math.round(t.accumulatedTimeInViewMs);i>0&&this.enqueue(y.TIME_IN_VIEW,"timeInView",{auctionId:t.auctionId,transactionId:t.transactionId,adUnitCode:t.adUnitCode,viewableDurationMs:i,bid:t.bidPayload,metadata:{...t.metadata,refresh_index:String(t.refreshIndex)}}),t.accumulatedTimeInViewMs=0}this.flushBeacon()}else if(document.visibilityState==="visible"){let e=typeof performance<"u"&&performance.now?performance.now():Date.now();for(let t of this.slotViewabilityRecords.values())if(t.inView&&(t.lastEnteredViewAt=e,!t.viewableFired&&t.dwellTimer===null)){let i=t.mediaType==="video"?2e3:1e3;t.dwellStartedAt=e,t.dwellTimer=setTimeout(()=>{this.handleDwellComplete(t)},i)}}}}handleIntersection(e){for(let t of e){let i=this.elementToSlotId.get(t.target);if(!i){for(let a of n.activeInstances)if(a!==this&&a.elementToSlotId.has(t.target)){a.handleIntersection([t]);break}continue}let r=this.slotViewabilityRecords.get(i);if(!r)continue;let o=t.isIntersecting&&(t.intersectionRatio===void 0||t.intersectionRatio>=.5),s=typeof document>"u"||document.visibilityState==="visible",d=typeof performance<"u"&&performance.now?performance.now():Date.now();if(o){if(!r.inView&&(r.inView=!0,s&&(r.lastEnteredViewAt=d,!r.viewableFired&&r.dwellTimer===null))){let a=r.mediaType==="video"?2e3:1e3;r.dwellStartedAt=d,r.dwellTimer=setTimeout(()=>{this.handleDwellComplete(r)},a)}}else r.inView&&(r.lastEnteredViewAt!==null&&(r.accumulatedTimeInViewMs+=Math.max(0,d-r.lastEnteredViewAt),r.lastEnteredViewAt=null),r.inView=!1),r.dwellTimer!==null&&(clearTimeout(r.dwellTimer),r.dwellTimer=null,r.dwellStartedAt=null)}}handleDwellComplete(e){e.dwellTimer=null,e.dwellStartedAt=null,e.inView&&(typeof document<"u"&&document.visibilityState==="hidden"||(e.viewableFired||(e.viewableFired=!0,this.enqueue(y.VIEWABLE,"viewable",{auctionId:e.auctionId,transactionId:e.transactionId,adUnitCode:e.adUnitCode,bid:e.bidPayload,metadata:{...e.metadata,refresh_index:String(e.refreshIndex)}})),this.notifyViewable(e)))}notifyViewable(e){if(e.viewableFired){for(let t of e.viewableListeners)if(t.firedForIndex!==e.refreshIndex){t.firedForIndex=e.refreshIndex;try{t.callback(e.slotId)}catch(i){this.log("ERROR","Error in viewable listener callback",i)}}}}setSlotElement(e,t){this.slotElements.set(e,t);let i=this.slotViewabilityRecords.get(e);i&&i.element!==t&&this.observeSlot(t,e,{refreshIndex:i.refreshIndex})}recordClick(e,t){if(!this.isEnabled||!e)return!1;let i=Date.now();if(i-(this.lastClickAt.get(e)||0)<jn)return!1;this.lastClickAt.set(e,i);let r=this.getCachedBid(e);return this.enqueue(y.CLICK,"click",{auctionId:r?.auctionId||"",transactionId:r?.transactionId||"",adUnitCode:e,bid:r?.bidTrace,metadata:{...t?.metadata,refresh_index:String(this.getRefreshIndex(e))}}),!0}attachClickTracker(e,t){if(typeof window>"u")return()=>{};let i=()=>{setTimeout(()=>{let o=document.activeElement;o&&(o===e||e.contains(o))&&(this.recordClick(t,{metadata:{source:"blur"}}),window.focus())},0)};window.addEventListener("blur",i);let r=()=>{window.removeEventListener("blur",i),this.clickDetachCleanups.delete(r)};return this.clickDetachCleanups.add(r),r}onViewable(e,t){let i={callback:t,firedForIndex:-1},r=this.slotViewabilityRecords.get(e);return r?(r.viewableListeners.add(i),this.notifyViewable(r)):(this.pendingViewableListeners.has(e)||this.pendingViewableListeners.set(e,new Set),this.pendingViewableListeners.get(e).add(i)),()=>{this.slotViewabilityRecords.get(e)?.viewableListeners.delete(i),this.pendingViewableListeners.get(e)?.delete(i)}}getCurrentTimeInView(e){let t=e.accumulatedTimeInViewMs;if(e.inView&&e.lastEnteredViewAt!==null){let i=typeof performance<"u"&&performance.now?performance.now():Date.now();t+=Math.max(0,i-e.lastEnteredViewAt)}return t}flushSlotTimeInView(e){let t=this.slotViewabilityRecords.get(e);if(!t)return;if(t.inView&&t.lastEnteredViewAt!==null){let r=typeof performance<"u"&&performance.now?performance.now():Date.now();t.accumulatedTimeInViewMs+=Math.max(0,r-t.lastEnteredViewAt),t.lastEnteredViewAt=null}let i=Math.round(t.accumulatedTimeInViewMs);i>0&&this.enqueue(y.TIME_IN_VIEW,"timeInView",{auctionId:t.auctionId,transactionId:t.transactionId,adUnitCode:t.adUnitCode,viewableDurationMs:i,bid:t.bidPayload,metadata:{...t.metadata,refresh_index:String(t.refreshIndex)}}),t.accumulatedTimeInViewMs=0}flushAllSlotsTimeInView(){for(let e of Array.from(this.slotViewabilityRecords.keys()))this.flushSlotTimeInView(e)}observeSlot(e,t,i){if(!this.config.viewabilityEnabled)return;let r=null;if(typeof e=="string"){if(typeof document<"u"){try{r=document.querySelector(e)||document.getElementById(e)}catch{r=document.getElementById(e)}r||(r=document.getElementById(e))}}else r=e;let o=t||i?.adUnitCode||(r?r.id:"")||Q(),s=this.slotViewabilityRecords.get(o);if(s){if(!!i?.isRefresh||i?.refreshIndex===void 0||i.refreshIndex>s.refreshIndex||!!(i?.auctionId&&s.auctionId&&i.auctionId!==s.auctionId)){this.flushSlotTimeInView(o);let a=i?.refreshIndex!==void 0?i.refreshIndex:(this.slotRefreshIndices.get(o)??s.refreshIndex)+1;this.slotRefreshIndices.set(o,a),s.dwellTimer&&(clearTimeout(s.dwellTimer),s.dwellTimer=null,s.dwellStartedAt=null),s.viewableFired=!1,s.accumulatedTimeInViewMs=0;let u=typeof performance<"u"&&performance.now?performance.now():Date.now();if(s.lastEnteredViewAt=s.inView?u:null,s.refreshIndex=a,s.auctionId=i?.auctionId||s.auctionId,s.transactionId=i?.transactionId||s.transactionId,s.mediaType=i?.mediaType||s.mediaType||"banner",s.bidPayload=i?.bid!==void 0?i.bid:s.bidPayload,s.metadata=i?.metadata??s.metadata,s.inView&&(typeof document>"u"||document.visibilityState==="visible")){let c=s.mediaType==="video"?2e3:1e3;s.dwellStartedAt=u,s.dwellTimer=setTimeout(()=>{this.handleDwellComplete(s)},c)}}else s.auctionId=i?.auctionId||s.auctionId,s.transactionId=i?.transactionId||s.transactionId,s.mediaType=i?.mediaType||s.mediaType,i?.bid!==void 0&&(s.bidPayload=i.bid),i?.metadata!==void 0&&(s.metadata=i.metadata);i?.auctionId&&this.slotLastAuctionIds.set(o,i.auctionId),r&&(s.element&&s.element!==r&&this.intersectionObserver&&(this.intersectionObserver.unobserve(s.element),this.elementToSlotId.delete(s.element)),s.element=r,this.elementToSlotId.set(r,o),this.intersectionObserver?.observe(r))}else{let d=i?.refreshIndex??this.slotRefreshIndices.get(o)??0;this.slotRefreshIndices.set(o,d),i?.auctionId&&this.slotLastAuctionIds.set(o,i.auctionId);let a=this.pendingViewableListeners.get(o)||new Set;this.pendingViewableListeners.delete(o);let u={slotId:o,element:r,adUnitCode:i?.adUnitCode||o,auctionId:i?.auctionId||"",transactionId:i?.transactionId||"",mediaType:i?.mediaType||"banner",bidPayload:i?.bid,metadata:i?.metadata,refreshIndex:d,inView:!1,lastEnteredViewAt:null,accumulatedTimeInViewMs:0,viewableFired:!1,dwellTimer:null,dwellStartedAt:null,viewableListeners:a};this.slotViewabilityRecords.set(o,u),r&&(this.elementToSlotId.set(r,o),this.intersectionObserver?.observe(r))}}unobserveSlot(e){let t=this.slotViewabilityRecords.get(e);t&&(this.flushSlotTimeInView(e),t.dwellTimer&&(clearTimeout(t.dwellTimer),t.dwellTimer=null,t.dwellStartedAt=null),t.viewableListeners=new Set,t.element&&this.intersectionObserver&&(this.intersectionObserver.unobserve(t.element),this.elementToSlotId.delete(t.element),t.element=null),t.inView=!1,t.lastEnteredViewAt=null)}registerSlot(e,t){e&&(t?this.slotNames.set(e,t):this.slotNames.delete(e))}destroySlot(e){this.unobserveSlot(e),this.slotNames.delete(e),this.slotViewabilityRecords.delete(e),this.slotRefreshIndices.delete(e),this.slotAdSessionCounters.delete(e),this.slotLastAuctionIds.delete(e),this.pendingViewableListeners.delete(e);let t=`${l(e)}:`;for(let r of Array.from(this.slotEmittedImpressionKeys))(r===e||r.startsWith(t))&&this.slotEmittedImpressionKeys.delete(r);let i=this.cachedWinningBids.get(e);i&&this.deleteCachedBidEntry(i)}getCachedBid(e){let t=this.cachedWinningBids.get(e);if(t){if(Date.now()-t.timestamp>z){this.deleteCachedBidEntry(t);return}return t}}deleteCachedBidEntry(e){for(let[t,i]of Array.from(this.cachedWinningBids))i===e&&this.cachedWinningBids.delete(t)}pruneCachedWinningBids(){let e=Date.now();for(let[t,i]of Array.from(this.cachedWinningBids))e-i.timestamp>z&&this.cachedWinningBids.delete(t);for(;this.cachedWinningBids.size>Fn;){let t=this.cachedWinningBids.keys().next();if(t.done)break;this.cachedWinningBids.delete(t.value)}}addImpressionKey(e){if(!this.slotEmittedImpressionKeys.has(e)){for(;this.slotEmittedImpressionKeys.size>=$n;){let t=this.slotEmittedImpressionKeys.values().next();if(t.done)break;this.slotEmittedImpressionKeys.delete(t.value)}this.slotEmittedImpressionKeys.add(e)}}getOrCreateAuctionOutcomes(e){let t=this.auctionBidderOutcomes.get(e);for(t||(t=new Map,this.auctionBidderOutcomes.set(e,t));this.auctionBidderOutcomes.size>Wn;){let i=this.auctionBidderOutcomes.keys().next();if(i.done||i.value===e)break;this.auctionBidderOutcomes.delete(i.value)}return t}nextSlotAdSession(e){let t=(this.slotAdSessionCounters.get(e)??0)+1;return this.slotAdSessionCounters.set(e,t),`ad-session-${t}`}hasImpressionEmitted(e,t,i,r,o){let s=t??this.slotRefreshIndices.get(e)??0,d=`${l(e)}:${s}`;if(i?this.slotEmittedImpressionKeys.has(`${d}:auc:${l(i)}`):this.slotEmittedImpressionKeys.has(d))return!0;if(o){if(i&&this.slotEmittedImpressionKeys.has(`${d}:auc:${l(i)}:render`)||this.slotEmittedImpressionKeys.has(`${d}:render`))return!0;if(i){if(this.slotEmittedImpressionKeys.has(`${d}:auc:${l(i)}:ad:${l(o)}`)||this.slotEmittedImpressionKeys.has(`${d}:ad:${l(o)}`))return!0}else if(this.slotEmittedImpressionKeys.has(`${d}:ad:${l(o)}`))return!0;if(r&&r!==o){if(i){if(this.slotEmittedImpressionKeys.has(`${d}:auc:${l(i)}:${l(r)}`)||this.slotEmittedImpressionKeys.has(`${d}:${l(r)}`))return!0}else if(this.slotEmittedImpressionKeys.has(`${d}:${l(r)}`))return!0}return!1}return i&&this.slotEmittedImpressionKeys.has(`${d}:auc:${l(i)}:ad-emitted`)||this.slotEmittedImpressionKeys.has(`${d}:ad-emitted`)?!0:r?i?this.slotEmittedImpressionKeys.has(`${d}:auc:${l(i)}:${l(r)}`)||this.slotEmittedImpressionKeys.has(`${d}:${l(r)}`):this.slotEmittedImpressionKeys.has(`${d}:${l(r)}`):!!(i&&this.slotEmittedImpressionKeys.has(`${d}:auc:${l(i)}:any`))}markImpressionEmitted(e,t,i,r,o){let s=`${l(e)}:${t}`;!!(o||r)?(o&&(this.addImpressionKey(`${s}:ad:${l(o)}`),this.addImpressionKey(`${s}:ad-emitted`),i&&(this.addImpressionKey(`${s}:auc:${l(i)}:ad:${l(o)}`),this.addImpressionKey(`${s}:auc:${l(i)}:any`),this.addImpressionKey(`${s}:auc:${l(i)}:ad-emitted`))),r&&r!==o&&(this.addImpressionKey(`${s}:${l(r)}`),i&&(this.addImpressionKey(`${s}:auc:${l(i)}:${l(r)}`),this.addImpressionKey(`${s}:auc:${l(i)}:any`))),o||(this.addImpressionKey(`${s}:render`),i&&this.addImpressionKey(`${s}:auc:${l(i)}:render`))):(this.addImpressionKey(s),this.addImpressionKey(`${s}:render`),i&&(this.addImpressionKey(`${s}:auc:${l(i)}`),this.addImpressionKey(`${s}:auc:${l(i)}:render`)))}recordImpression(e,t){if(!this.isEnabled)return!1;let i=e||t?.adUnitCode||"",r=t?.adUnitCode||i,o=(t?.auctionId&&i?this.getCachedBid(`${t.auctionId}:${i}`):void 0)||(t?.auctionId&&r?this.getCachedBid(`${t.auctionId}:${r}`):void 0)||(i?this.getCachedBid(i):void 0)||(r?this.getCachedBid(r):void 0),s=t?.bid||o?.rawBid||{},d=t?.auctionId||s.auctionId||o?.auctionId||"",a=t?.transactionId||s.transactionId||o?.transactionId||"",u=s.creativeId||o?.bidTrace?.creativeId||t?.bid?.creativeId||"",c=t?.adId||s.adId||t?.bid?.adId||"",b=t?.mediaType||s.mediaType||o?.bidTrace?.mediaType||"banner",p=i||r,f=(i?this.slotViewabilityRecords.get(i):void 0)||(r?this.slotViewabilityRecords.get(r):void 0),U=p?this.slotLastAuctionIds.get(p)||(f?f.auctionId:void 0):void 0,I=!!(p&&d&&U&&U!==d&&t?.refreshIndex===void 0),x={bidder:s.bidderCode||s.bidder||o?.bidTrace?.bidder||"",...me(s,o?.bidTrace),...k(s).width?k(s):o?.bidTrace?{width:o.bidTrace.width,height:o.bidTrace.height}:k(s),dealId:s.dealId||o?.bidTrace?.dealId||"",mediaType:b,latencyMs:Number.isFinite(s.timeToRespond)?s.timeToRespond:Number.isFinite(s.latencyMs)?s.latencyMs:o?.bidTrace?.latencyMs??0,advertiserDomain:s.advertiserDomain||s.meta?.advertiserDomains?.[0]||(Array.isArray(s.adomain)?s.adomain[0]:"")||o?.bidTrace?.advertiserDomain||"",creativeId:s.creativeId||o?.bidTrace?.creativeId||""};if(I&&p){this.flushSlotTimeInView(p);let M=(this.slotRefreshIndices.get(p)??(f?f.refreshIndex:0))+1;this.slotRefreshIndices.set(p,M),this.slotLastAuctionIds.set(p,d),f&&(f.refreshIndex=M,f.auctionId=d,f.transactionId=a,f.bidPayload=x,f.viewableFired=!1,f.accumulatedTimeInViewMs=0)}else p&&(d&&this.slotLastAuctionIds.set(p,d),this.slotRefreshIndices.has(p)||this.slotRefreshIndices.set(p,0));let w=t?.refreshIndex??(i?this.slotRefreshIndices.get(i)??(r?this.slotRefreshIndices.get(r):void 0)??(f?f.refreshIndex:0):0);return i&&this.hasImpressionEmitted(i,w,d,u,c)||r&&r!==i&&this.hasImpressionEmitted(r,w,d,u,c)?(this.log("DEBUG",`Impression already emitted for slot ${i||r} in cycle ${w}`),!1):(i&&this.markImpressionEmitted(i,w,d,u,c),r&&r!==i&&this.markImpressionEmitted(r,w,d,u,c),this.enqueue(y.IMPRESSION,"impression",{auctionId:d,transactionId:a,adUnitCode:r,bid:x,metadata:{...t?.metadata,refresh_index:String(w)}}),f&&(!f.bidPayload&&x&&(f.bidPayload=x),!f.auctionId&&d&&(f.auctionId=d),!f.transactionId&&a&&(f.transactionId=a)),!0)}getViewabilityState(e){let t=this.slotViewabilityRecords.get(e);if(!t)return;let i=Math.round(this.getCurrentTimeInView(t));return{inView:t.inView,viewable:t.viewableFired,timeInViewMs:i,refreshIndex:t.refreshIndex}}getEndpoint(){return this.config.endpoint}getRefreshIndex(e){return this.slotRefreshIndices.get(e)??0}triggerSlotRefresh(e,t){let i=this.slotViewabilityRecords.get(e);i&&i.element&&this.observeSlot(i.element,e,t)}trackRawEvent(e,t,i){let r=Nn[e]??kn[t];r!==void 0&&this.enqueue(r,t,i)}recordFloorDecision(e,t,i){if(!e||!t)return;let r=`${e}:${t}`;for(this.floorDecisions.delete(r),this.floorDecisions.set(r,{floorCents:i.floorCents!==void 0&&Number.isFinite(i.floorCents)?Math.round(i.floorCents):void 0,source:i.source,treatment:Number.isFinite(i.treatment)?i.treatment:1});this.floorDecisions.size>Kn;){let o=this.floorDecisions.keys().next();if(o.done)break;this.floorDecisions.delete(o.value)}}floorDecisionFor(e,t){return e&&t?this.floorDecisions.get(`${e}:${t}`):void 0}recordConsent(e){if(!this.isEnabled||!e)return!1;let t=`${e.regime}|${e.action}|${e.tcString??""}|${e.gppString??""}|${e.uspString??""}`;if(this.recordedConsentKeys.has(t))return!1;this.recordedConsentKeys.add(t);let i={},r=(o,s)=>{if(!(s==null||s===""))if(typeof s=="number"){if(!Number.isFinite(s))return;i[o]=String(s)}else if(typeof s=="boolean")i[o]=s?"true":"false";else if(Array.isArray(s)){if(s.length===0)return;i[o]=[...s].sort((d,a)=>d-a).join(",")}else typeof s=="string"&&(i[o]=s)};return r("regime",e.regime),r("action",e.action),r("cmp_id",e.cmpId),r("cmp_version",e.cmpVersion),r("gvl_version",e.gvlVersion),r("tc_string",e.tcString),r("ac_string",e.acString),r("gpp_string",e.gppString),r("usp_string",e.uspString),r("purposes_consented",e.purposesConsented),r("vendors_consented",e.vendorsConsented),r("vendors_total",e.vendorsTotal),r("language",e.language),r("opt_out",e.optOut),r("gpc",e.gpc),this.enqueue(y.CONSENT,"consent",{metadata:i}),!0}attachCmp(){if(typeof document>"u")return()=>{};let e=o=>{let s=o.detail;s&&(this.followConsent(s),this.recordConsent(s))};document.addEventListener("ads:consent",e);let i=(typeof window<"u"?window:{})[this.config.alias]?.consent?.getRecord?.()||null;i&&(this.followConsent(i),this.recordConsent(i));let r=!1;return()=>{r||(r=!0,document.removeEventListener("ads:consent",e))}}followConsent(e){let t=$e(e);t||(Dt(),kt()),n.setStorageAllowed(t)}setUserId(e){if(this.configuredUserId=e,this.config.userId=e,e&&(this.config.visitorId=e,this.managesVisitorId=!1,this.visitorKeyLocked=!0),this.config.storageAllowed&&typeof localStorage<"u")try{e?localStorage.setItem(ne,e):localStorage.removeItem(ne)}catch{}}setVisitorId(e){this.config.visitorId=e,this.managesVisitorId=!e,e&&(this.visitorKeyLocked=!0)}setSampleRate(e){this.config.sampleRate=J(e)}setEvents(e){this.config.events=e||{}}setSessionId(e){this.config.sessionId=e,this.managesSessionId=!e,this.managesSessionId&&(this.config.sessionId=te())}getSessionId(){return this.syncSessionId(),this.config.sessionId}getPageviewId(){return this.config.pageviewId}getContext(){return{pageviewId:this.getPageviewId(),sessionId:this.getSessionId()}}continuePageview(e){this.config.pageviewId=e.config.pageviewId,this.pageviewEmitted=e.pageviewEmitted,this.deduper=e.deduper,this.replayedEventCount=e.replayedEventCount}navigate(e,t=""){let i=Ct(t);if(this.isEnabled&&this.pageviewEmitted&&e!==""&&e===this.config.pageviewId&&(!i||i===this.pageUrl)){de();return}this.disable(),this.slotRefreshIndices.clear(),this.slotNames.clear(),this.slotAdSessionCounters.clear(),this.floorDecisions.clear(),this.recordedConsentKeys.clear(),this.consentCount=0,this.pageviewEmitted=!1,this.config.pageviewId=e||Q(),this.pageUrl=i,this.logger.resetTiming(),de(),this.syncSessionAndRotateVisitor(),this.enable()}recordAuctionStart(e,t="",i,r){!this.isEnabled||!this.config.auctionEnabled||this.enqueue(y.AUCTION_START,"auctionStart",{auctionId:e,adUnitCode:t,...r?{bid:{mediaType:r}}:{},...typeof i=="number"?{metadata:{bidderCount:String(i)}}:{}})}handleAuctionInit(e){if(this.isDuplicate("auctionInit",e))return;this.log("DEBUG","auctionInit",e);let t=e.auctionId||"";t&&(this.auctionBidderOutcomes.delete(t),this.getOrCreateAuctionOutcomes(t));let i=Array.isArray(e.adUnitCodes)?e.adUnitCodes.length:Array.isArray(e.adUnits)?e.adUnits.length:1;this.config.attachPbjsListeners&&this.usageRecorder&&this.usageRecorder.record(t,i),this.enqueue(y.AUCTION_START,"auctionStart",{auctionId:t,transactionId:e.transactionId||""})}handleAuctionEnd(e){if(this.isDuplicate("auctionEnd",e))return;this.log("DEBUG","auctionEnd",e);let t=e.auctionId||"",i=t?this.auctionBidderOutcomes.get(t):void 0,r=i?Array.from(i.values()):[];t&&this.auctionBidderOutcomes.delete(t),this.enqueue(y.AUCTION_END,"auctionEnd",{auctionId:t,transactionId:e.transactionId||"",bidderOutcomes:r})}auctionCycleIndex(e){if(!e)return 0;let t=this.slotRefreshIndices.get(e)??this.slotViewabilityRecords.get(e)?.refreshIndex;return t===void 0?0:t+1}handleBidRequested(e){if(this.isDuplicate("bidRequested",e))return;this.log("DEBUG","bidRequested",e);let t=e.auctionId||"",i=e.bidderCode||e.bidder||"";if(!t||!i)return;let r=this.getOrCreateAuctionOutcomes(t);Array.isArray(e.bids)&&e.bids.forEach(o=>{let s=o.adUnitCode||"",d=Object.keys(o.mediaTypes||{}),a=o.mediaType||(o.mediaTypes?.video?"video":d.length>0?d[0]:"banner"),u=`${i}:${s}`;r.has(u)||r.set(u,{adUnitCode:s,outcome:q.BIDDER_OUTCOME_NO_RESPONSE,bid:{bidder:i,mediaType:a,latencyMs:0}})})}handleBidResponse(e){if(this.isDuplicate("bidResponse",e))return;this.log("DEBUG","bidResponse",e);let t=e.auctionId||"",i=e.bidderCode||e.bidder||"",r=e.adUnitCode||"",o=me(e),s=o.cpm,d=Number.isFinite(e.timeToRespond)?e.timeToRespond:0,a=Object.keys(e.mediaTypes||{}),u=e.mediaType||(e.mediaTypes?.video?"video":a.length>0?a[0]:"banner");if(!t||!i)return;let c=s>0?{bidder:i,...o,...k(e),dealId:e.dealId||"",mediaType:u,latencyMs:d,advertiserDomain:e.meta?.advertiserDomains?.[0]||"",creativeId:e.creativeId||""}:{bidder:i,mediaType:u,latencyMs:d};this.getOrCreateAuctionOutcomes(t).set(`${i}:${r}`,{adUnitCode:r,outcome:s>0?q.BIDDER_OUTCOME_BID:q.BIDDER_OUTCOME_NO_BID,bid:c})}handleBidTimeout(e){if(this.isDuplicate("bidTimeout",e))return;this.log("DEBUG","bidTimeout",e);let t=Array.isArray(e)?e:e?[e]:[];for(let i of t){let r=i.auctionId||"",o=i.bidderCode||i.bidder||"",s=i.adUnitCode||"",d=Number.isFinite(i.timeout)?i.timeout:0;if(r&&o){let a=this.getOrCreateAuctionOutcomes(r),u=`${o}:${s}`,c=a.get(u);c?(c.outcome=q.BIDDER_OUTCOME_TIMEOUT,d>0&&c.bid&&(c.bid.latencyMs=d)):a.set(u,{adUnitCode:s,outcome:q.BIDDER_OUTCOME_TIMEOUT,bid:{bidder:o,mediaType:"banner",latencyMs:d}})}}}handleBidWon(e){if(this.isDuplicate("bidWon",e))return;this.log("DEBUG","bidWon",e);let t=e.auctionId||"",i=e.transactionId||"",r=e.adUnitCode||e.adId||"",o=Object.keys(e.mediaTypes||{}),s=e.mediaType||(e.mediaTypes?.video?"video":o.length>0?o[0]:"banner"),d={bidder:e.bidderCode||e.bidder||"",...me(e),...k(e),dealId:e.dealId||"",mediaType:s,latencyMs:Number.isFinite(e.timeToRespond)?e.timeToRespond:0,advertiserDomain:e.meta?.advertiserDomains?.[0]||"",creativeId:e.creativeId||""};if(r){let a={bidTrace:d,auctionId:t,transactionId:i,adUnitCode:r,rawBid:e,timestamp:Date.now()};this.cachedWinningBids.set(r,a),e.adId&&e.adId!==r&&this.cachedWinningBids.set(e.adId,a),t&&(this.cachedWinningBids.set(`${t}:${r}`,a),e.adId&&e.adId!==r&&this.cachedWinningBids.set(`${t}:${e.adId}`,a)),this.pruneCachedWinningBids()}this.enqueue(y.BID_WIN,"bidWon",{auctionId:t,transactionId:i,adUnitCode:r,bid:d})}handleNoBid(e){if(this.isDuplicate("noBid",e))return;this.log("DEBUG","noBid",e);let t=e.auctionId||"",i=e.bidderCode||e.bidder||"",r=e.adUnitCode||"";if(t&&i){let o=this.getOrCreateAuctionOutcomes(t),s=`${i}:${r}`,d=o.get(s);d?d.outcome===q.BIDDER_OUTCOME_NO_RESPONSE&&(d.outcome=q.BIDDER_OUTCOME_NO_BID):o.set(s,{adUnitCode:r,outcome:q.BIDDER_OUTCOME_NO_BID,bid:{bidder:i,mediaType:"banner",latencyMs:0}})}}handleAdRenderFailed(e){if(this.isDuplicate("adRenderFailed",e))return;this.log("DEBUG","adRenderFailed",e);let t=e.bid||{};this.enqueue(y.AD_RENDER_FAILED,"adRenderFailed",{auctionId:t.auctionId||e.auctionId||"",transactionId:t.transactionId||e.transactionId||"",adUnitCode:t.adUnitCode||e.adUnitCode||"",bid:{bidder:t.bidderCode||t.bidder||e.bidderCode||e.bidder||""},metadata:{reason:String(e.reason||""),message:String(e.message||e.error?.message||"")},error:e.error||(e.message?new Error(String(e.message)):void 0)})}handleAdRenderSucceeded(e){if(this.isDuplicate("adRenderSucceeded",e))return;this.log("DEBUG","adRenderSucceeded",e);let t=e.bid||e||{},i=e.adUnitCode||t.adUnitCode||e.adId||t.adId||"",r=t.auctionId||e.auctionId||"",o=t.transactionId||e.transactionId||"",s=t.mediaType||"banner",d=e.adUnitCode||t.adUnitCode||"",a=e.adId||t.adId||"",u=(r&&d?this.getCachedBid(`${r}:${d}`):void 0)||(r&&a?this.getCachedBid(`${r}:${a}`):void 0)||(d?this.getCachedBid(d):void 0)||(a?this.getCachedBid(a):void 0),b=s==="video"||t.mediaType==="video"||t.mediaTypes?.video!==void 0||u?.bidTrace?.mediaType==="video"||u?.rawBid?.mediaType==="video"||i&&this.slotViewabilityRecords.get(i)?.mediaType==="video"?"video":s||u?.bidTrace?.mediaType||"banner",p={bidder:t.bidderCode||t.bidder||u?.bidTrace?.bidder||"",...me(t,u?.bidTrace),...k(t).width?k(t):u?.bidTrace?{width:u.bidTrace.width,height:u.bidTrace.height}:k(t),dealId:t.dealId||u?.bidTrace?.dealId||"",mediaType:b,latencyMs:Number.isFinite(t.timeToRespond)?t.timeToRespond:u?.bidTrace?.latencyMs??0,advertiserDomain:t.meta?.advertiserDomains?.[0]||u?.bidTrace?.advertiserDomain||"",creativeId:t.creativeId||u?.bidTrace?.creativeId||""},f=r||u?.auctionId||"",U=o||u?.transactionId||"",I=i?this.slotViewabilityRecords.get(i):void 0,x=I&&f&&I.auctionId&&I.auctionId!==f,w=!!(i&&I&&x);if(w){this.flushSlotTimeInView(i);let A=(this.slotRefreshIndices.get(i)??(I?I.refreshIndex:0))+1;this.slotRefreshIndices.set(i,A),this.slotLastAuctionIds.set(i,f),I&&(I.auctionId=f,I.transactionId=U,I.bidPayload=p)}else i&&(f&&this.slotLastAuctionIds.set(i,f),this.slotRefreshIndices.has(i)||this.slotRefreshIndices.set(i,0));let N=i?this.slotRefreshIndices.get(i)??(I?I.refreshIndex:0):0;if(i&&this.hasImpressionEmitted(i,N,f,p.creativeId)||(i&&this.markImpressionEmitted(i,N,f,p.creativeId),this.enqueue(y.IMPRESSION,"impression",{auctionId:f,transactionId:U,adUnitCode:i,bid:p,metadata:{refresh_index:String(N)}})),this.config.viewabilityEnabled&&typeof document<"u"){let A=i&&this.slotElements.get(i)||null,T=i||e.adId||t.adId;if(!A&&T&&(A=document.getElementById(T)),!A&&typeof window<"u"&&window.googletag?.pubads)try{let m=window.googletag.pubads().getSlots();for(let E of m)if((E.getAdUnitPath?.()===i||E.getSlotElementId?.()===i)&&(A=document.getElementById(E.getSlotElementId()),A))break}catch{}if(!A&&T)try{for(let m of Array.from(document.querySelectorAll("[data-ad-slot]")))if(m.getAttribute("data-ad-slot")===T){A=m;break}}catch{}A?this.observeSlot(A,i||T,{adUnitCode:i,auctionId:f,transactionId:U,mediaType:b,bid:p,refreshIndex:N,isRefresh:w}):I&&w&&(I.refreshIndex=N,I.viewableFired=!1,I.accumulatedTimeInViewMs=0)}}isDuplicate(e,t){return this.deduper.isDuplicate(e,t)}enqueue(e,t,i){if(!this.isEnabled||!this.shouldSample(e))return;this.syncSessionId();let r={eventId:L(Q()),timestampMs:Date.now(),type:e,eventName:Mn.has(e)?t:"",auctionId:L(String(i.auctionId||"")),transactionId:L(String(i.transactionId||"")),adUnitCode:i.adUnitCode||i.elementId||"",namespace:i.ns||i.namespace||""};if(i.bid){let a=k(i.bid);r.bid={bidder:i.bid.bidder||i.bid.bidderCode||"",cpm:Number.isFinite(i.bid.cpm)?i.bid.cpm:0,currency:i.bid.currency||"",width:a.width,height:a.height,dealId:i.bid.dealId||"",mediaType:i.bid.mediaType||"",latencyMs:Number.isFinite(i.bid.latencyMs)?i.bid.latencyMs:Number.isFinite(i.bid.timeToRespond)?i.bid.timeToRespond:0,advertiserDomain:i.bid.advertiserDomain||i.bid.meta?.advertiserDomains?.[0]||(Array.isArray(i.bid.adomain)?i.bid.adomain[0]:"")||"",creativeId:i.bid.creativeId||""}}i.viewableDurationMs!==void 0&&(r.viewableDurationMs=Number.isFinite(i.viewableDurationMs)?i.viewableDurationMs:0),i.bidderOutcomes&&Array.isArray(i.bidderOutcomes)&&(r.bidderOutcomes=i.bidderOutcomes.map(a=>{let u=this.floorDecisionFor(String(i.auctionId||""),a.adUnitCode||""),c=a.slot||this.slotNames.get(a.adUnitCode||"");return{...a,...c?{slot:c}:{},refreshIndex:a.refreshIndex??this.auctionCycleIndex(a.adUnitCode||""),...u?{floorCents:u.floorCents,floorSource:qn[u.source],floorTreatmentBp:Math.round(u.treatment*1e4)}:{}}}));let o={...i.metadata},s=r.adUnitCode?this.slotNames.get(r.adUnitCode):void 0;if(s&&o.slot===void 0&&(o.slot=s),e===y.BID_WIN||e===y.IMPRESSION){let a=this.floorDecisionFor(String(i.auctionId||""),r.adUnitCode||"");a&&(a.floorCents!==void 0&&(o.floor_cents=String(a.floorCents)),o.floor_source=a.source,o.floor_treatment=a.treatment.toFixed(2))}i.error!==void 0&&i.error!==null&&(o.error=typeof i.error=="object"&&i.error.message?String(i.error.message):String(i.error)),i.gpid&&(o.gpid=String(i.gpid)),i.refreshIndex!==void 0&&o.refresh_index===void 0&&(o.refresh_index=String(i.refreshIndex));let d=Xn(o);Object.keys(d).length>0&&(r.metadata=d),this.queue.push(r),this.queue.length>=se?(this.flush(),this.queue.length>se&&this.queue.splice(0,this.queue.length-se)):Vn.has(e)&&this.revenueFlushTimer===null&&(this.revenueFlushTimer=setTimeout(()=>{this.revenueFlushTimer=null,this.flush()},this.config.revenueFlushDelayMs))}syncSessionId(){this.managesSessionId&&(this.config.sessionId=ti()?te():O,this.announceSession())}syncSessionAndRotateVisitor(){let e=this.config.sessionId;this.syncSessionId(),(!this.config.visitorId||this.config.sessionId!==e&&this.config.visitorId===e)&&(this.config.visitorId=this.config.userId||this.config.sessionId)}announceSession(){!this.isEnabled||!this.managesSessionId||!be||this.config.sessionId===St||(St=this.config.sessionId,this.emitPageEvent("session"))}emitPageEvent(e){let t={pageviewId:this.config.pageviewId,sessionId:this.config.sessionId},i=this.config.events?.[e];if(typeof i=="function"){try{i(t)}catch(d){this.log("ERROR",`Error in ${e} event handler`,d)}return}let r=`${this.config.alias}:${e}`,o=r,s=typeof i=="string"?i.trim():"";if(s&&(Hn.test(s)&&(!s.startsWith("ads:")||s===r)?o=s:this.log("WARN",`Invalid ${e} event name "${i}"; falling back to "${r}".`)),!(typeof window>"u"||typeof window.dispatchEvent!="function"))try{window.dispatchEvent(new CustomEvent(o,{detail:t}))}catch(d){this.log("ERROR",`Failed to dispatch ${o} event`,d)}}isSampledVisitor(){let e=this.config.visitorId||this.config.sessionId;return De(e,this.config.sampleRate)}shouldSample(e){return this.visitorKeyLocked&&!this.isSampledVisitor()?!1:e===y.ERROR?(this.errorCount++,this.errorCount<=Rn):e===y.CONSENT?(this.consentCount++,this.consentCount<=_n):e===y.WARN?this.config.warningsEnabled:this.config.auctionEnabled}requeue(e){e.length&&(this.queue=e.concat(this.queue),this.queue.length>se&&this.queue.splice(0,this.queue.length-se))}drainBatch(){if(this.queue.length===0||!this.config.endpoint)return null;if(this.syncSessionId(),this.visitorKeyLocked=!0,!this.isSampledVisitor())return this.queue=[],null;let e=typeof window<"u"?window.location.hostname:"",t=J(this.config.sampleRate),i=ke(),r=s=>({propertyId:L(this.config.propertyId),pageviewId:L(this.config.pageviewId),sessionId:L(this.config.sessionId),pageUrl:this.pageUrl,country:this.config.country,region:this.config.region,deviceType:this.config.deviceType,userId:this.config.userId||"",domain:e,events:s,...t<1?{sampleRate:t}:{},...i?{automated:!0}:{}}),o=re.encode(r([])).finish().byteLength;for(;;){if(this.queue.length===0)return null;let s=0,d=o;for(let c=0;c<this.queue.length;c++){let b=this.queue[c],f=le.encode(b).finish().byteLength+6;if(d+f>Et){if(s===0){let[U]=this.queue.splice(0,1),I=re.encode(r([U])).finish().byteLength;this.log("WARN",`Dropping oversized event (type ${U?.type}, ${I} bytes exceeds the ${Et}-byte cap on its own)`);break}break}d+=f,s++}if(s===0)continue;let a=this.queue.slice(0,s),u=re.encode(r(a)).finish();return this.queue=this.queue.slice(a.length),{url:this.batchUrl(),encoded:u,events:a}}}sendFetch(e,t=!1,i,r=!1){let o={method:"POST",headers:{"Content-Type":wt},body:e.encoded};t&&(o.keepalive=!0),fetch(e.url,o).then(d=>{if(d.ok)r||(this.consecutiveSendFailures=0,this.nextSendAllowedAt=0),i&&i();else{if(this.log("WARN",`Failed to send batch: HTTP ${d.status}`),d.status>=400&&d.status<500&&d.status!==429&&d.status!==408){this.log("WARN",`Dropping batch due to non-retryable client error HTTP ${d.status}`);return}r||this.handleSendFailure(e.events)}}).catch(d=>{this.log("ERROR","Failed to send batch",d),r||this.handleSendFailure(e.events)});let s=typeof globalThis<"u"?globalThis.process:void 0;if(s&&typeof s._tickCallback=="function")try{s._tickCallback()}catch{}}handleSendFailure(e){this.consecutiveSendFailures++;let t=Math.min(vt*2**(this.consecutiveSendFailures-1),Un);this.nextSendAllowedAt=Date.now()+t,this.consecutiveSendFailures<=Bn?this.requeue(e):this.log("WARN",`Dropping ${e.length} events after ${this.consecutiveSendFailures} consecutive send failures`)}flush(){if(Date.now()<this.nextSendAllowedAt)return;let e=this.drainBatch(),t=!0;for(;e&&(this.sendFetch(e,t),t=!1,!(Date.now()<this.nextSendAllowedAt));)e=this.drainBatch()}batchUrl(){return`${this.config.endpoint}/${this.config.propertyId}`}flushBeacon(){let e=this.drainBatch();for(;e;){let t=!1;if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function")try{let i=new Blob([e.encoded],{type:wt});t=navigator.sendBeacon(e.url,i)}catch{t=!1}if(!t){let i=this.persistBatch(e.encoded);this.sendFetch(e,!0,()=>this.removePersistedBatch(i))}e=this.drainBatch()}this.schedulePersistedCleanup()}pendingKeyPrefix(){return`${At}${encodeURIComponent(this.config.propertyId)}_`}persistBatch(e){if(!H)return null;try{if(typeof localStorage>"u"||!this.config.propertyId)return null;let t=0;for(let r=0;r<localStorage.length;r++){let o=localStorage.key(r);o&&o.startsWith(At)&&t++}if(t>=On)return null;let i=`${this.pendingKeyPrefix()}${Date.now()}_${Math.floor(Math.random()*1e6)}`;return localStorage.setItem(i,Gn(e)),this.persistedBatchKeys.push(i),i}catch{return null}}removePersistedBatch(e){if(!e)return;try{typeof localStorage<"u"&&localStorage.removeItem(e)}catch{}let t=this.persistedBatchKeys.indexOf(e);t!==-1&&this.persistedBatchKeys.splice(t,1)}schedulePersistedCleanup(){this.persistedBatchKeys.length!==0&&(this.persistedCleanupTimer&&clearTimeout(this.persistedCleanupTimer),this.persistedCleanupTimer=setTimeout(()=>{this.persistedCleanupTimer=null;for(let e of Array.from(this.persistedBatchKeys))this.removePersistedBatch(e)},Dn))}resendPersistedBatches(){try{if(!H||typeof localStorage>"u"||!this.config.endpoint||!this.config.propertyId)return;let e=this.pendingKeyPrefix(),t=[];for(let i=0;i<localStorage.length;i++){let r=localStorage.key(i);r&&r.startsWith(e)&&t.push(r)}for(let i of t){let r=null;try{r=localStorage.getItem(i),localStorage.removeItem(i)}catch{continue}if(!r)continue;let o=parseInt(i.slice(e.length),10);if(!Number.isFinite(o)||Date.now()-o>Ln)continue;let s;try{s=Yn(r)}catch{continue}s.byteLength!==0&&(this.log("DEBUG",`Resending persisted exit batch (${s.byteLength} bytes)`),this.sendFetch({url:`${this.config.endpoint}/${this.config.propertyId}`,encoded:s,events:[]},!1,void 0,!0))}}catch{}}log(e,t,...i){this.logger.log(e,t,...i)}}});function ai(n){let e=typeof n?.getError=="function"?n.getError():n?.error||n,t=a=>e&&typeof e[a]=="function"?e[a]():void 0,i=t("getMessage")||e?.message||String(e||"IMA ad error"),r=t("getErrorCode")??e?.code,o=t("getVastErrorCode"),s=t("getType")??e?.type,d={message:i};return r&&(d.error_code=String(r)),o&&(d.vast_error_code=String(o)),s&&(d.error_type=String(s)),{err:e,message:i,metadata:d}}function $t(n,e,t){let i=Ie(n),{err:r,message:o,metadata:s}=ai(e);return i.log("WARN","IMA AdErrorEvent received",e),i.enqueue(y.AD_RENDER_FAILED,"adRenderFailed",{auctionId:t.auctionId,transactionId:t.transactionId,adUnitCode:t.adUnitCode,bid:t.bid,metadata:{...t.metadata,reason:t.adStarted?"ima_playback_error":"ima_ad_error",playback_phase:t.adStarted?"post_start":"pre_start",...s},error:typeof r=="object"?r:new Error(o)}),r}function ci(n,e){if(!n||typeof n!="object"||Mt.has(n))return;Mt.add(n);let t=typeof window<"u"&&window.google?.ima?.AdErrorEvent?.Type?.AD_ERROR||"adError";try{e.call(n,t,i=>{for(let r of _.getActiveInstances())try{let o=Kt(r,{mediaType:"video"});$t(r,i,{adStarted:!1,adUnitCode:o?.adUnitCode||"video",auctionId:o?.auctionId,transactionId:o?.transactionId,bid:o?.bidTrace})}catch{}})}catch{}}function Pt(n){if(n)try{let e=n.prototype;if(e&&typeof e.getAdsManager=="function"&&!e.getAdsManager.__bidsparkHooked){let t=e.getAdsManager,i=function(...r){let o=t.apply(this,r);if(o)for(let s of _.getActiveInstances())try{s.attachImaAdsManager(o)}catch{}return o};i.__bidsparkHooked=!0,e.getAdsManager=i}}catch{}}function Vt(n){if(n)try{let e=n.prototype||n;if(e&&typeof e.init=="function"&&!e.init.__bidsparkHooked){let t=e.init,i=function(...r){for(let o of _.getActiveInstances())try{o.attachImaAdsManager(this)}catch{}return t.apply(this,r)};i.__bidsparkHooked=!0,e.init=i}if(e&&typeof e.start=="function"&&!e.start.__bidsparkHooked){let t=e.start,i=function(...r){for(let o of _.getActiveInstances())try{o.attachImaAdsManager(this)}catch{}return t.apply(this,r)};i.__bidsparkHooked=!0,e.start=i}}catch{}}function Ft(n){if(n)try{let e=n.prototype;if(!e)return;if(typeof e.addEventListener=="function"&&!e.addEventListener.__bidsparkHooked){let t=e.addEventListener,i=function(r,o,...s){if(ci(this,t),(r==="adsManagerLoaded"||r===(this?.AdsManagerLoadedEvent?.Type?.ADS_MANAGER_LOADED||"adsManagerLoaded"))&&typeof o=="function"){let d=qe.get(o);return d||(d=function(a){if(a&&typeof a.getAdsManager=="function"&&!a.getAdsManager.__bidsparkHooked){let u=a.getAdsManager;a.getAdsManager=function(...c){let b=u.apply(this,c);if(b)for(let p of _.getActiveInstances())try{p.attachImaAdsManager(b)}catch{}return b},a.getAdsManager.__bidsparkHooked=!0}return o.apply(this,arguments)},qe.set(o,d)),t.call(this,r,d,...s)}return t.call(this,r,o,...s)};i.__bidsparkHooked=!0,e.addEventListener=i}if(typeof e.removeEventListener=="function"&&!e.removeEventListener.__bidsparkHooked){let t=e.removeEventListener,i=function(r,o,...s){let d=typeof o=="function"?qe.get(o):void 0;return t.call(this,r,d||o,...s)};i.__bidsparkHooked=!0,e.removeEventListener=i}}catch{}}function ae(n){if(!(!n||typeof n!="object"))try{n.AdsManagerLoadedEvent&&Pt(n.AdsManagerLoadedEvent);let e=Object.getOwnPropertyDescriptor(n,"AdsManagerLoadedEvent");if(!e||e.configurable){let r=n.AdsManagerLoadedEvent;try{Object.defineProperty(n,"AdsManagerLoadedEvent",{configurable:!0,enumerable:!0,get(){return r},set(o){r=o,Pt(o)}})}catch{}}n.AdsLoader&&Ft(n.AdsLoader);let t=Object.getOwnPropertyDescriptor(n,"AdsLoader");if(!t||t.configurable){let r=n.AdsLoader;try{Object.defineProperty(n,"AdsLoader",{configurable:!0,enumerable:!0,get(){return r},set(o){r=o,Ft(o)}})}catch{}}n.AdsManager&&Vt(n.AdsManager);let i=Object.getOwnPropertyDescriptor(n,"AdsManager");if(!i||i.configurable){let r=n.AdsManager;try{Object.defineProperty(n,"AdsManager",{configurable:!0,enumerable:!0,get(){return r},set(o){r=o,Vt(o)}})}catch{}}}catch{}}function Wt(){if(typeof window>"u")return;let n=window;if(n.google?.ima&&ae(n.google.ima),n.google&&typeof n.google=="object"){let t=Object.getOwnPropertyDescriptor(n.google,"ima");if(!t||t.configurable){let i=n.google.ima;try{Object.defineProperty(n.google,"ima",{configurable:!0,enumerable:!0,get(){return i},set(r){i=r,ae(r)}})}catch{}}}let e=Object.getOwnPropertyDescriptor(n,"google");if(!e||e.configurable){let t=n.google;try{Object.defineProperty(n,"google",{configurable:!0,enumerable:!0,get(){return t},set(i){if(t=i,t&&typeof t=="object"){t.ima&&ae(t.ima);let r=Object.getOwnPropertyDescriptor(t,"ima");if(!r||r.configurable){let o=t.ima;try{Object.defineProperty(t,"ima",{configurable:!0,enumerable:!0,get(){return o},set(s){o=s,ae(s)}})}catch{}}}}})}catch{}}}function Kt(n,e){let t=Ie(n),i=Date.now(),r=d=>t.hasImpressionEmitted(d.adUnitCode,void 0,d.auctionId,d.bidTrace.creativeId);if(e?.creativeId||e?.adId){for(let d of Array.from(t.cachedWinningBids.values()))if(!(i-d.timestamp>z)&&(e.creativeId&&(d.bidTrace.creativeId===e.creativeId||d.rawBid?.creativeId===e.creativeId)||e.adId&&(d.rawBid?.adId===e.adId||d.adUnitCode===e.adId)))return d}let o;if(e?.mediaType){for(let a of Array.from(t.cachedWinningBids.values())){if(i-a.timestamp>z)continue;(a.bidTrace.mediaType===e.mediaType||a.rawBid?.mediaType===e.mediaType||e.mediaType==="video"&&a.rawBid?.mediaTypes?.video!==void 0)&&(r(a)||(!o||a.timestamp<o.timestamp)&&(o=a))}if(o)return o;let d;for(let a of Array.from(t.cachedWinningBids.values())){if(i-a.timestamp>z)continue;(a.bidTrace.mediaType===e.mediaType||a.rawBid?.mediaType===e.mediaType||e.mediaType==="video"&&a.rawBid?.mediaTypes?.video!==void 0)&&(!d||a.timestamp>d.timestamp)&&(d=a)}if(d)return d}for(let d of Array.from(t.cachedWinningBids.values()))i-d.timestamp>z||r(d)||(!o||d.timestamp>o.timestamp)&&(o=d);if(o)return o;let s;for(let d of Array.from(t.cachedWinningBids.values()))i-d.timestamp>z||(!s||d.timestamp>s.timestamp)&&(s=d);return s}function qt(n,e,t){let i=Ie(n);if(!e||typeof e.addEventListener!="function")return i.log("WARN","Invalid AdsManager passed to attachImaAdsManager"),()=>{};if(!e.__bidsparkAttachedInstances)try{Object.defineProperty(e,"__bidsparkAttachedInstances",{value:new Map,configurable:!0,writable:!0})}catch{e.__bidsparkAttachedInstances=new Map}let r=e.__bidsparkAttachedInstances,o=r.get(n);if(o){if(!t)return()=>{};o()}let s=t?.slotId||t?.adUnitCode||"video",d=t?.adUnitCode||s,a=t?.auctionId||t?.bid?.auctionId||"",u=t?.transactionId||t?.bid?.transactionId||"",c=h=>{let g=(a?i.getCachedBid(`${a}:${d}`):void 0)||(a&&s!==d?i.getCachedBid(`${a}:${s}`):void 0)||(d!=="video"?i.getCachedBid(d):void 0)||(s!==d&&s!=="video"?i.getCachedBid(s):void 0);return g||(g=Kt(n,{creativeId:h?.creativeId,adId:h?.adId,mediaType:"video"})),g},b=!1,p=null,f=h=>{let g=typeof i.nextSlotAdSession=="function"?i.nextSlotAdSession(s):`ad-session-${(i.slotAdSessionCounters?.get(s)??0)+1}`;if(i.slotAdSessionCounters&&typeof i.nextSlotAdSession!="function"){let D=(i.slotAdSessionCounters.get(s)??0)+1;i.slotAdSessionCounters.set(s,D)}let v=(typeof h?.getAdId=="function"?h.getAdId():h?.adId??h?.id)||"",P=(typeof h?.getCreativeId=="function"?h.getCreativeId():h?.creativeId)||"";return p={sessionId:g,adId:v||void 0,creativeId:P||void 0},p},U=h=>{let g=typeof h?.getAd=="function"?h.getAd():h?.ad;f(g),i.log("DEBUG","IMA AdEvent.LOADED received",{slotId:s,activeAdSession:p})},I=h=>{b=!0;let g=typeof h?.getAd=="function"?h.getAd():h?.ad,v={};g&&(v.creativeId=(typeof g.getCreativeId=="function"?g.getCreativeId():g.creativeId)||"",v.adId=(typeof g.getAdId=="function"?g.getAdId():g.id)||"",v.title=(typeof g.getTitle=="function"?g.getTitle():g.title)||"",v.duration=typeof g.getDuration=="function"?g.getDuration():g.duration,v.advertiserName=typeof g.getAdvertiserName=="function"?g.getAdvertiserName():""),!p||v.adId&&p.adId&&p.adId!==v.adId?f(g):(!p.adId&&v.adId&&(p.adId=v.adId),!p.creativeId&&v.creativeId&&(p.creativeId=v.creativeId));let P=p||f(g),D=c(v),ve=t?.slotId&&t.slotId!=="video"?t.slotId:t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:D?.adUnitCode||t?.slotId||t?.adUnitCode||"video",Yt=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:D?.adUnitCode||ve,zt=a||D?.auctionId||"",Xt=u||D?.transactionId||"",je=P.creativeId||v.creativeId||D?.bidTrace?.creativeId||t?.bid?.creativeId||"",Qt=P.adId||v.adId||je||P.sessionId,He=x(D,je),Ge=i.recordImpression(ve,{adUnitCode:Yt,auctionId:zt,transactionId:Xt,mediaType:"video",bid:He,adId:Qt,metadata:{...t?.metadata,media_type:"video",...v.title?{ad_title:v.title}:{},...Number.isFinite(v.duration)?{ad_duration_s:String(v.duration)}:{}}}),ie=typeof h?.type=="string"?h.type:typeof h?.getType=="function"?h.getType():typeof h=="string"?h:"";ie.toLowerCase().startsWith("adevent.")&&(ie=ie.slice(8));let Zt=ie?ie.toUpperCase():"STARTED/IMPRESSION";if(i.log("DEBUG",`IMA AdEvent.${Zt} received${Ge?"":" (second event for this ad, already counted)"}`,h),Ge&&t?.onImpression)try{t.onImpression(ve,{ad:g,bid:He})}catch(Jt){i.log("ERROR","Error in onImpression callback",Jt)}},x=(h,g)=>{let v=k(h?.rawBid),P=k(t?.bid),D=g||t?.bid?.creativeId||h?.bidTrace?.creativeId||"";return{...h?.rawBid,...t?.bid,...t?.bid?.bidder||t?.bid?.bidderCode?{bidderCode:t.bid.bidderCode||t.bid.bidder}:{},...P.width>0&&P.height>0?P:v,mediaType:"video",...D?{creativeId:D}:{}}},w=h=>{if(i.log("DEBUG",`IMA AdEvent milestone: ${h}`),t?.onMilestone)try{t.onMilestone(h,s)}catch(g){i.log("ERROR","Error in onMilestone callback",g)}},N=h=>{i.log("DEBUG","IMA AdEvent.CLICK received",h);let g=c(),v=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:g?.adUnitCode||s;i.enqueue(y.CLICK,"click",{auctionId:a||g?.auctionId,transactionId:u||g?.transactionId,adUnitCode:v,bid:g||t?.bid?x(g):void 0,metadata:{...t?.metadata,media_type:"video"}})},M=h=>{p=null;let g=c(),v=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:g?.adUnitCode||s,P=$t(n,h,{adStarted:b,adUnitCode:v,auctionId:a||g?.auctionId,transactionId:u||g?.transactionId,bid:g||t?.bid?x(g):void 0,metadata:t?.metadata});if(t?.onError)try{t.onError(P)}catch(D){i.log("ERROR","Error in onError callback",D)}},A=typeof window<"u"?window.google?.ima:void 0,T=A?.AdEvent?.Type||{},m=A?.AdErrorEvent?.Type||{},E=[{type:T.LOADED||"loaded",handler:U},{type:T.STARTED||"started",handler:I},{type:T.IMPRESSION||"impression",handler:I},{type:T.FIRST_QUARTILE||"firstQuartile",handler:()=>w("firstQuartile")},{type:T.MIDPOINT||"midpoint",handler:()=>w("midpoint")},{type:T.THIRD_QUARTILE||"thirdQuartile",handler:()=>w("thirdQuartile")},{type:T.COMPLETE||"complete",handler:()=>{p=null,w("complete")}},{type:T.ALL_ADS_COMPLETED||"allAdsCompleted",handler:()=>{p=null}},{type:T.CLICK||"click",handler:N},{type:m.AD_ERROR||"adError",handler:M}],S=new Set,$=[];for(let h of E)S.has(h.type)||(S.add(h.type),$.push(h));for(let{type:h,handler:g}of $)try{e.addEventListener(h,g)}catch{}let W=()=>{p=null,r.delete(n);for(let{type:h,handler:g}of $)try{e.removeEventListener(h,g)}catch{}i.videoDetachCleanups.delete(W)};return r.set(n,W),i.videoDetachCleanups.add(W),W}function ui(n,e,t){let i=Ie(n);if(!e)return i.log("WARN","attachVideoPlayer called with null/undefined target"),()=>{};let r=null;if(typeof e=="string"){if(typeof document<"u")try{r=document.querySelector(e)||document.getElementById(e)}catch{r=document.getElementById(e)}}else if(typeof HTMLElement<"u"&&e instanceof HTMLElement)r=e;else if(e&&typeof e=="object"&&e.nodeType===1)r=e;else{if(typeof e.addEventListener=="function"&&(typeof e.init=="function"||typeof e.start=="function"||typeof e.getCuePoints=="function"||typeof e.getVolume=="function"||e.__imaAdsManager))return qt(n,e,t);e&&typeof e.addEventListener=="function"&&(r=e)}let o=t?.slotId||t?.adUnitCode||(r?r.id:"")||"video",s=t?.adUnitCode||o,d=t?.auctionId||"",a=t?.transactionId||"",u=()=>(d?i.getCachedBid(`${d}:${s}`):void 0)||(d&&o!==s?i.getCachedBid(`${d}:${o}`):void 0)||i.getCachedBid(s)||(o!==s?i.getCachedBid(o):void 0),c=null;r&&(r.tagName&&r.tagName.toLowerCase()==="video"?c=r:c=r.querySelector("video"));let b={q1:!1,q2:!1,q3:!1,q4:!1},p=m=>{let E=m||c||(r?.querySelector?r.querySelector("video"):null),S=u(),$={...S?.rawBid||t?.bid,mediaType:"video"};if(i.recordImpression(o,{adUnitCode:s,auctionId:d||S?.auctionId,transactionId:a||S?.transactionId,mediaType:"video",bid:$,metadata:{...t?.metadata,media_type:"video",...E&&Number.isFinite(E.duration)?{video_duration_s:String(Math.round(E.duration))}:{}}})&&t?.onImpression)try{t.onImpression(o,{element:E||r,bid:$})}catch(h){i.log("ERROR","Error in onImpression callback",h)}},f=m=>{i.log("DEBUG","HTML5 video playing event received");let E=m?.target instanceof HTMLVideoElement?m.target:c;p(E)},U=m=>{let E=m?.target instanceof HTMLVideoElement?m.target:c;if(E&&E.currentTime>0&&(p(E),Number.isFinite(E.duration)&&E.duration>0)){let S=E.currentTime/E.duration;S>=.25&&!b.q1&&(b.q1=!0,t?.onMilestone?.("firstQuartile",o)),S>=.5&&!b.q2&&(b.q2=!0,t?.onMilestone?.("midpoint",o)),S>=.75&&!b.q3&&(b.q3=!0,t?.onMilestone?.("thirdQuartile",o))}},I=()=>{b.q4||(b.q4=!0,t?.onMilestone?.("complete",o))},x=m=>{let S=(m?.target instanceof HTMLVideoElement?m.target:c)?.error||c?.error,$=u(),W=S?`HTML5 video error code ${S.code}: ${S.message}`:"Video playback error";if(i.log("WARN",W),i.enqueue(y.AD_RENDER_FAILED,"adRenderFailed",{auctionId:d||$?.auctionId,transactionId:a||$?.transactionId,adUnitCode:s,bid:$?.bidTrace||t?.bid,metadata:{...t?.metadata,reason:"html5_video_error",message:W,...S?.code?{error_code:String(S.code)}:{}},error:S?new Error(W):void 0}),t?.onError)try{t.onError(S)}catch(h){i.log("ERROR","Error in onError callback",h)}},w=m=>{m.addEventListener("playing",f),m.addEventListener("play",f),m.addEventListener("timeupdate",U),m.addEventListener("ended",I),m.addEventListener("error",x)},N=m=>{m.removeEventListener("playing",f),m.removeEventListener("play",f),m.removeEventListener("timeupdate",U),m.removeEventListener("ended",I),m.removeEventListener("error",x)},M=null;r&&r!==c&&(r.addEventListener("playing",f,!0),r.addEventListener("play",f,!0),r.addEventListener("timeupdate",U,!0),r.addEventListener("ended",I,!0),r.addEventListener("error",x,!0)),c&&w(c),r&&r.tagName?.toLowerCase()!=="video"&&typeof MutationObserver<"u"&&(M=new MutationObserver(()=>{let m=r.querySelector("video");m&&m!==c&&(c&&N(c),c=m,c&&w(c))}),M.observe(r,{childList:!0,subtree:!0}));let A=u();t?.trackViewability!==!1&&r&&i.observeSlot(r,o,{adUnitCode:s,auctionId:d||A?.auctionId,transactionId:a||A?.transactionId,mediaType:"video",bid:A?.bidTrace||t?.bid,metadata:t?.metadata});let T=()=>{M&&(M.disconnect(),M=null),r&&r!==c&&(r.removeEventListener("playing",f,!0),r.removeEventListener("play",f,!0),r.removeEventListener("timeupdate",U,!0),r.removeEventListener("ended",I,!0),r.removeEventListener("error",x,!0)),c&&N(c),i.videoDetachCleanups.delete(T)};return i.videoDetachCleanups.add(T),T}var Ie,qe,Mt,li,jt=B(()=>{"use strict";Ke();pe();Ie=n=>n,qe=new WeakMap,Mt=new WeakSet;typeof window<"u"&&Wt();_.prototype.attachImaAdsManager=function(n,e){return qt(this,n,e)};_.prototype.attachVideoPlayer=function(n,e){return ui(this,n,e)};li=_.prototype.enable;_.prototype.enable=function(){li.call(this),typeof window<"u"&&(Wt(),window.google?.ima&&ae(window.google.ima))}});var hi=en(()=>{Ke();jt();var Ht="https://by.bidspark.io/t",Gt="https://by.bidspark.io/u",fi=window._bidsparkPbjsGlobal||"pbjs";We(fi,{endpoint:Ht,usageEndpoint:Gt});window.bidsparkPrebidAnalytics={...window.bidsparkPrebidAnalytics,register:(n,e)=>We(n,{endpoint:Ht,usageEndpoint:Gt,...e}),attachVideoPlayer:(n,e)=>{let t=window._bidsparkPrebidAnalytics;return t?.attachVideoPlayer?t.attachVideoPlayer(n,e):()=>{}},attachImaAdsManager:(n,e)=>{let t=window._bidsparkPrebidAnalytics;return t?.attachImaAdsManager?t.attachImaAdsManager(n,e):()=>{}},recordImpression:(n,e)=>{let t=window._bidsparkPrebidAnalytics;return t?.recordImpression?t.recordImpression(n,e):!1},getSessionId:()=>{let n=window._bidsparkPrebidAnalytics;return n?.getSessionId?n.getSessionId():te()},getPageviewId:()=>{let n=window._bidsparkPrebidAnalytics;return n?.getPageviewId?n.getPageviewId():""},getContext:()=>{let n=window._bidsparkPrebidAnalytics;return n?.getContext?n.getContext():{pageviewId:"",sessionId:te()}},setLogLevel:n=>{_.setLogLevel(n)},getLogLevel:()=>_.getLogLevel()}});return hi();})();
package/dist/index.d.mts CHANGED
@@ -117,6 +117,15 @@ declare function isVisitorSampled(visitorKey: string, sampleRate?: number): bool
117
117
  */
118
118
  declare function isAutomatedClient(): boolean;
119
119
 
120
+ interface PageEventDetail {
121
+ pageviewId: string;
122
+ sessionId: string;
123
+ }
124
+ type PageEventHandler = (detail: PageEventDetail) => void;
125
+ interface PageEventsConfig {
126
+ pageview?: string | PageEventHandler;
127
+ session?: string | PageEventHandler;
128
+ }
120
129
  interface AnalyticsConfig {
121
130
  endpoint: string;
122
131
  /** Usage endpoint origin (e.g. "https://by.bidspark.io/u"). */
@@ -154,6 +163,8 @@ interface AnalyticsConfig {
154
163
  revenueFlushDelayMs?: number;
155
164
  /** Window global alias for CMP instance. Defaults to "ads". */
156
165
  alias?: string;
166
+ /** Custom DOM event names or callback handlers for pageview and session start. */
167
+ events?: PageEventsConfig;
157
168
  }
158
169
  /** Canonical consent record shape from CMP. */
159
170
  interface ConsentRecord {
@@ -299,6 +310,7 @@ declare class BidsparkPrebidAnalytics {
299
310
  private recordedConsentKeys;
300
311
  private consentCount;
301
312
  private cmpDetach;
313
+ private sessionResumeUnsub;
302
314
  private pageviewEmitted;
303
315
  private logger;
304
316
  private managesSessionId;
@@ -414,13 +426,11 @@ declare class BidsparkPrebidAnalytics {
414
426
  setUserId(userId: string): void;
415
427
  setVisitorId(visitorId: string): void;
416
428
  setSampleRate(sampleRate?: number): void;
429
+ setEvents(events?: PageEventsConfig): void;
417
430
  setSessionId(sessionId: string): void;
418
431
  getSessionId(): string;
419
432
  getPageviewId(): string;
420
- getContext(): {
421
- pageviewId: string;
422
- sessionId: string;
423
- };
433
+ getContext(): PageEventDetail;
424
434
  /**
425
435
  * Continues the pageview of the instance this one replaces: re-registering on
426
436
  * the same page must not count a second pageview or replay Prebid's history.
@@ -449,6 +459,9 @@ declare class BidsparkPrebidAnalytics {
449
459
  private isDuplicate;
450
460
  private enqueue;
451
461
  private syncSessionId;
462
+ private syncSessionAndRotateVisitor;
463
+ private announceSession;
464
+ private emitPageEvent;
452
465
  private isSampledVisitor;
453
466
  private shouldSample;
454
467
  private requeue;
@@ -688,4 +701,4 @@ interface AdsGlobal {
688
701
  */
689
702
  declare function getAdsGlobal(alias?: string): AdsGlobal;
690
703
 
691
- export { type AdsGlobal, type AnalyticsConfig, type BeaconEvent, BidsparkPrebidAnalytics, CACHED_BID_TTL_MS, type CachedWinningBid, type ConsentRecord, DEFAULT_ALIAS, type FloorDecision, ImaAdsManagerStub, LogLevel, MAX_USAGE_BATCH_SIZE, PrebidEventDeduper, SAFE_CONTENT_TYPE, type SendEventsOptions, type SizeMapping, type SlotConfig, type SlotObserveOptions, type SlotSize, type SlotSizes, type SlotViewabilityState, USAGE_FLUSH_INTERVAL_MS, usage_event as UsageProto, UsageRecorder, type UsageRecorderOptions, type VideoPlayerOptions, attachImaAdsManager, attachVideoPlayer, clearStoredSession, clearStoredUserId, generateUUID, getAdsGlobal, getOrCreateSessionId, getOrCreateUserId, getPrebidEventKey, idToBytes, idToString, isAutomatedClient, isSessionActive, isTrustedEndpoint, isVisitorSampled, normalizeLogLevel, normalizeSampleRate, onSessionResume, parseBidDimensions, registerPrebidAnalytics, sendEvents, sessionStarted };
704
+ export { type AdsGlobal, type AnalyticsConfig, type BeaconEvent, BidsparkPrebidAnalytics, CACHED_BID_TTL_MS, type CachedWinningBid, type ConsentRecord, DEFAULT_ALIAS, type FloorDecision, ImaAdsManagerStub, LogLevel, MAX_USAGE_BATCH_SIZE, type PageEventDetail, type PageEventHandler, type PageEventsConfig, PrebidEventDeduper, SAFE_CONTENT_TYPE, type SendEventsOptions, type SizeMapping, type SlotConfig, type SlotObserveOptions, type SlotSize, type SlotSizes, type SlotViewabilityState, USAGE_FLUSH_INTERVAL_MS, usage_event as UsageProto, UsageRecorder, type UsageRecorderOptions, type VideoPlayerOptions, attachImaAdsManager, attachVideoPlayer, clearStoredSession, clearStoredUserId, generateUUID, getAdsGlobal, getOrCreateSessionId, getOrCreateUserId, getPrebidEventKey, idToBytes, idToString, isAutomatedClient, isSessionActive, isTrustedEndpoint, isVisitorSampled, normalizeLogLevel, normalizeSampleRate, onSessionResume, parseBidDimensions, registerPrebidAnalytics, sendEvents, sessionStarted };
package/dist/index.d.ts CHANGED
@@ -117,6 +117,15 @@ declare function isVisitorSampled(visitorKey: string, sampleRate?: number): bool
117
117
  */
118
118
  declare function isAutomatedClient(): boolean;
119
119
 
120
+ interface PageEventDetail {
121
+ pageviewId: string;
122
+ sessionId: string;
123
+ }
124
+ type PageEventHandler = (detail: PageEventDetail) => void;
125
+ interface PageEventsConfig {
126
+ pageview?: string | PageEventHandler;
127
+ session?: string | PageEventHandler;
128
+ }
120
129
  interface AnalyticsConfig {
121
130
  endpoint: string;
122
131
  /** Usage endpoint origin (e.g. "https://by.bidspark.io/u"). */
@@ -154,6 +163,8 @@ interface AnalyticsConfig {
154
163
  revenueFlushDelayMs?: number;
155
164
  /** Window global alias for CMP instance. Defaults to "ads". */
156
165
  alias?: string;
166
+ /** Custom DOM event names or callback handlers for pageview and session start. */
167
+ events?: PageEventsConfig;
157
168
  }
158
169
  /** Canonical consent record shape from CMP. */
159
170
  interface ConsentRecord {
@@ -299,6 +310,7 @@ declare class BidsparkPrebidAnalytics {
299
310
  private recordedConsentKeys;
300
311
  private consentCount;
301
312
  private cmpDetach;
313
+ private sessionResumeUnsub;
302
314
  private pageviewEmitted;
303
315
  private logger;
304
316
  private managesSessionId;
@@ -414,13 +426,11 @@ declare class BidsparkPrebidAnalytics {
414
426
  setUserId(userId: string): void;
415
427
  setVisitorId(visitorId: string): void;
416
428
  setSampleRate(sampleRate?: number): void;
429
+ setEvents(events?: PageEventsConfig): void;
417
430
  setSessionId(sessionId: string): void;
418
431
  getSessionId(): string;
419
432
  getPageviewId(): string;
420
- getContext(): {
421
- pageviewId: string;
422
- sessionId: string;
423
- };
433
+ getContext(): PageEventDetail;
424
434
  /**
425
435
  * Continues the pageview of the instance this one replaces: re-registering on
426
436
  * the same page must not count a second pageview or replay Prebid's history.
@@ -449,6 +459,9 @@ declare class BidsparkPrebidAnalytics {
449
459
  private isDuplicate;
450
460
  private enqueue;
451
461
  private syncSessionId;
462
+ private syncSessionAndRotateVisitor;
463
+ private announceSession;
464
+ private emitPageEvent;
452
465
  private isSampledVisitor;
453
466
  private shouldSample;
454
467
  private requeue;
@@ -688,4 +701,4 @@ interface AdsGlobal {
688
701
  */
689
702
  declare function getAdsGlobal(alias?: string): AdsGlobal;
690
703
 
691
- export { type AdsGlobal, type AnalyticsConfig, type BeaconEvent, BidsparkPrebidAnalytics, CACHED_BID_TTL_MS, type CachedWinningBid, type ConsentRecord, DEFAULT_ALIAS, type FloorDecision, ImaAdsManagerStub, LogLevel, MAX_USAGE_BATCH_SIZE, PrebidEventDeduper, SAFE_CONTENT_TYPE, type SendEventsOptions, type SizeMapping, type SlotConfig, type SlotObserveOptions, type SlotSize, type SlotSizes, type SlotViewabilityState, USAGE_FLUSH_INTERVAL_MS, usage_event as UsageProto, UsageRecorder, type UsageRecorderOptions, type VideoPlayerOptions, attachImaAdsManager, attachVideoPlayer, clearStoredSession, clearStoredUserId, generateUUID, getAdsGlobal, getOrCreateSessionId, getOrCreateUserId, getPrebidEventKey, idToBytes, idToString, isAutomatedClient, isSessionActive, isTrustedEndpoint, isVisitorSampled, normalizeLogLevel, normalizeSampleRate, onSessionResume, parseBidDimensions, registerPrebidAnalytics, sendEvents, sessionStarted };
704
+ export { type AdsGlobal, type AnalyticsConfig, type BeaconEvent, BidsparkPrebidAnalytics, CACHED_BID_TTL_MS, type CachedWinningBid, type ConsentRecord, DEFAULT_ALIAS, type FloorDecision, ImaAdsManagerStub, LogLevel, MAX_USAGE_BATCH_SIZE, type PageEventDetail, type PageEventHandler, type PageEventsConfig, PrebidEventDeduper, SAFE_CONTENT_TYPE, type SendEventsOptions, type SizeMapping, type SlotConfig, type SlotObserveOptions, type SlotSize, type SlotSizes, type SlotViewabilityState, USAGE_FLUSH_INTERVAL_MS, usage_event as UsageProto, UsageRecorder, type UsageRecorderOptions, type VideoPlayerOptions, attachImaAdsManager, attachVideoPlayer, clearStoredSession, clearStoredUserId, generateUUID, getAdsGlobal, getOrCreateSessionId, getOrCreateUserId, getPrebidEventKey, idToBytes, idToString, isAutomatedClient, isSessionActive, isTrustedEndpoint, isVisitorSampled, normalizeLogLevel, normalizeSampleRate, onSessionResume, parseBidDimensions, registerPrebidAnalytics, sendEvents, sessionStarted };
package/dist/index.js CHANGED
@@ -1518,9 +1518,11 @@ var CLICK_DEDUP_MS = 1e3;
1518
1518
  var SESSION_KEY = "ads_session";
1519
1519
  var SESSION_TS_KEY = "ads_session_ts";
1520
1520
  var THIRTY_MINUTES_MS = 30 * 60 * 1e3;
1521
+ var PAGE_EVENT_NAME_RE = /^[a-zA-Z0-9:_.-]{1,64}$/;
1521
1522
  var inMemorySessionId = null;
1522
1523
  var inMemorySessionTs = 0;
1523
1524
  var sessionStartedHere = false;
1525
+ var announcedSessionId = "";
1524
1526
  var storageAllowed = true;
1525
1527
  function generateUUID2() {
1526
1528
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
@@ -1975,6 +1977,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1975
1977
  recordedConsentKeys = /* @__PURE__ */ new Set();
1976
1978
  consentCount = 0;
1977
1979
  cmpDetach = null;
1980
+ sessionResumeUnsub = null;
1978
1981
  pageviewEmitted = false;
1979
1982
  logger;
1980
1983
  // True when managing session lifecycle internally; false if caller supplied fixed sessionId.
@@ -2036,7 +2039,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2036
2039
  pbjsGlobalName: config.pbjsGlobalName || "pbjs",
2037
2040
  attachPbjsListeners: config.attachPbjsListeners ?? true,
2038
2041
  revenueFlushDelayMs: Number.isFinite(config.revenueFlushDelayMs) && config.revenueFlushDelayMs >= 0 ? config.revenueFlushDelayMs : REVENUE_FLUSH_DELAY_MS,
2039
- alias: config.alias || DEFAULT_ALIAS
2042
+ alias: config.alias || DEFAULT_ALIAS,
2043
+ events: config.events || {}
2040
2044
  };
2041
2045
  _BidsparkPrebidAnalytics.allInstances.add(this);
2042
2046
  this.logger = createLogger({
@@ -2130,8 +2134,11 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2130
2134
  document.addEventListener("visibilitychange", this.boundVisibilityChange);
2131
2135
  }
2132
2136
  bindActivityListeners();
2137
+ this.sessionResumeUnsub = onSessionResume(() => this.syncSessionAndRotateVisitor());
2138
+ this.syncSessionId();
2133
2139
  if (!this.pageviewEmitted) {
2134
2140
  this.pageviewEmitted = true;
2141
+ this.emitPageEvent("pageview");
2135
2142
  this.enqueue(TraceEventType.PAGEVIEW, "pageview", {});
2136
2143
  }
2137
2144
  this.flushTimer = setInterval(() => this.flush(), FLUSH_INTERVAL_MS);
@@ -2273,6 +2280,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2273
2280
  }
2274
2281
  this.cmpDetach = null;
2275
2282
  }
2283
+ this.sessionResumeUnsub?.();
2284
+ this.sessionResumeUnsub = null;
2276
2285
  this.flush();
2277
2286
  }
2278
2287
  handleVisibilityChange() {
@@ -3078,6 +3087,9 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3078
3087
  setSampleRate(sampleRate) {
3079
3088
  this.config.sampleRate = normalizeSampleRate(sampleRate);
3080
3089
  }
3090
+ setEvents(events) {
3091
+ this.config.events = events || {};
3092
+ }
3081
3093
  setSessionId(sessionId) {
3082
3094
  this.config.sessionId = sessionId;
3083
3095
  this.managesSessionId = !sessionId;
@@ -3120,12 +3132,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3120
3132
  this.config.pageviewId = pageviewId || generateUUID2();
3121
3133
  this.pageUrl = nextPageUrl;
3122
3134
  this.logger.resetTiming();
3123
- const prevSessionId = this.config.sessionId;
3124
3135
  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
- }
3136
+ this.syncSessionAndRotateVisitor();
3129
3137
  this.enable();
3130
3138
  }
3131
3139
  recordAuctionStart(auctionId, adUnitCode = "", bidderCount, mediaType) {
@@ -3568,6 +3576,55 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3568
3576
  syncSessionId() {
3569
3577
  if (!this.managesSessionId) return;
3570
3578
  this.config.sessionId = sessionNeedsSync() ? getOrCreateSessionId() : inMemorySessionId;
3579
+ this.announceSession();
3580
+ }
3581
+ syncSessionAndRotateVisitor() {
3582
+ const prevSessionId = this.config.sessionId;
3583
+ this.syncSessionId();
3584
+ if (!this.config.visitorId || this.config.sessionId !== prevSessionId && this.config.visitorId === prevSessionId) {
3585
+ this.config.visitorId = this.config.userId || this.config.sessionId;
3586
+ }
3587
+ }
3588
+ announceSession() {
3589
+ if (!this.isEnabled || !this.managesSessionId || !sessionStartedHere || this.config.sessionId === announcedSessionId) {
3590
+ return;
3591
+ }
3592
+ announcedSessionId = this.config.sessionId;
3593
+ this.emitPageEvent("session");
3594
+ }
3595
+ emitPageEvent(key) {
3596
+ const detail = {
3597
+ pageviewId: this.config.pageviewId,
3598
+ sessionId: this.config.sessionId
3599
+ };
3600
+ const configured = this.config.events?.[key];
3601
+ if (typeof configured === "function") {
3602
+ try {
3603
+ configured(detail);
3604
+ } catch (e) {
3605
+ this.log("ERROR", `Error in ${key} event handler`, e);
3606
+ }
3607
+ return;
3608
+ }
3609
+ const defaultName = `${this.config.alias}:${key}`;
3610
+ let eventName = defaultName;
3611
+ const trimmed = typeof configured === "string" ? configured.trim() : "";
3612
+ if (trimmed) {
3613
+ if (PAGE_EVENT_NAME_RE.test(trimmed) && (!trimmed.startsWith("ads:") || trimmed === defaultName)) {
3614
+ eventName = trimmed;
3615
+ } else {
3616
+ this.log(
3617
+ "WARN",
3618
+ `Invalid ${key} event name "${configured}"; falling back to "${defaultName}".`
3619
+ );
3620
+ }
3621
+ }
3622
+ if (typeof window === "undefined" || typeof window.dispatchEvent !== "function") return;
3623
+ try {
3624
+ window.dispatchEvent(new CustomEvent(eventName, { detail }));
3625
+ } catch (e) {
3626
+ this.log("ERROR", `Failed to dispatch ${eventName} event`, e);
3627
+ }
3571
3628
  }
3572
3629
  isSampledVisitor() {
3573
3630
  const key = this.config.visitorId || this.config.sessionId;
package/dist/index.mjs CHANGED
@@ -1466,9 +1466,11 @@ var CLICK_DEDUP_MS = 1e3;
1466
1466
  var SESSION_KEY = "ads_session";
1467
1467
  var SESSION_TS_KEY = "ads_session_ts";
1468
1468
  var THIRTY_MINUTES_MS = 30 * 60 * 1e3;
1469
+ var PAGE_EVENT_NAME_RE = /^[a-zA-Z0-9:_.-]{1,64}$/;
1469
1470
  var inMemorySessionId = null;
1470
1471
  var inMemorySessionTs = 0;
1471
1472
  var sessionStartedHere = false;
1473
+ var announcedSessionId = "";
1472
1474
  var storageAllowed = true;
1473
1475
  function generateUUID2() {
1474
1476
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
@@ -1923,6 +1925,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1923
1925
  recordedConsentKeys = /* @__PURE__ */ new Set();
1924
1926
  consentCount = 0;
1925
1927
  cmpDetach = null;
1928
+ sessionResumeUnsub = null;
1926
1929
  pageviewEmitted = false;
1927
1930
  logger;
1928
1931
  // True when managing session lifecycle internally; false if caller supplied fixed sessionId.
@@ -1984,7 +1987,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1984
1987
  pbjsGlobalName: config.pbjsGlobalName || "pbjs",
1985
1988
  attachPbjsListeners: config.attachPbjsListeners ?? true,
1986
1989
  revenueFlushDelayMs: Number.isFinite(config.revenueFlushDelayMs) && config.revenueFlushDelayMs >= 0 ? config.revenueFlushDelayMs : REVENUE_FLUSH_DELAY_MS,
1987
- alias: config.alias || DEFAULT_ALIAS
1990
+ alias: config.alias || DEFAULT_ALIAS,
1991
+ events: config.events || {}
1988
1992
  };
1989
1993
  _BidsparkPrebidAnalytics.allInstances.add(this);
1990
1994
  this.logger = createLogger({
@@ -2078,8 +2082,11 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2078
2082
  document.addEventListener("visibilitychange", this.boundVisibilityChange);
2079
2083
  }
2080
2084
  bindActivityListeners();
2085
+ this.sessionResumeUnsub = onSessionResume(() => this.syncSessionAndRotateVisitor());
2086
+ this.syncSessionId();
2081
2087
  if (!this.pageviewEmitted) {
2082
2088
  this.pageviewEmitted = true;
2089
+ this.emitPageEvent("pageview");
2083
2090
  this.enqueue(TraceEventType.PAGEVIEW, "pageview", {});
2084
2091
  }
2085
2092
  this.flushTimer = setInterval(() => this.flush(), FLUSH_INTERVAL_MS);
@@ -2221,6 +2228,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2221
2228
  }
2222
2229
  this.cmpDetach = null;
2223
2230
  }
2231
+ this.sessionResumeUnsub?.();
2232
+ this.sessionResumeUnsub = null;
2224
2233
  this.flush();
2225
2234
  }
2226
2235
  handleVisibilityChange() {
@@ -3026,6 +3035,9 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3026
3035
  setSampleRate(sampleRate) {
3027
3036
  this.config.sampleRate = normalizeSampleRate(sampleRate);
3028
3037
  }
3038
+ setEvents(events) {
3039
+ this.config.events = events || {};
3040
+ }
3029
3041
  setSessionId(sessionId) {
3030
3042
  this.config.sessionId = sessionId;
3031
3043
  this.managesSessionId = !sessionId;
@@ -3068,12 +3080,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3068
3080
  this.config.pageviewId = pageviewId || generateUUID2();
3069
3081
  this.pageUrl = nextPageUrl;
3070
3082
  this.logger.resetTiming();
3071
- const prevSessionId = this.config.sessionId;
3072
3083
  recordActivity();
3073
- this.syncSessionId();
3074
- if (!this.config.visitorId || this.config.sessionId !== prevSessionId && this.config.visitorId === prevSessionId) {
3075
- this.config.visitorId = this.config.userId || this.config.sessionId;
3076
- }
3084
+ this.syncSessionAndRotateVisitor();
3077
3085
  this.enable();
3078
3086
  }
3079
3087
  recordAuctionStart(auctionId, adUnitCode = "", bidderCount, mediaType) {
@@ -3516,6 +3524,55 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3516
3524
  syncSessionId() {
3517
3525
  if (!this.managesSessionId) return;
3518
3526
  this.config.sessionId = sessionNeedsSync() ? getOrCreateSessionId() : inMemorySessionId;
3527
+ this.announceSession();
3528
+ }
3529
+ syncSessionAndRotateVisitor() {
3530
+ const prevSessionId = this.config.sessionId;
3531
+ this.syncSessionId();
3532
+ if (!this.config.visitorId || this.config.sessionId !== prevSessionId && this.config.visitorId === prevSessionId) {
3533
+ this.config.visitorId = this.config.userId || this.config.sessionId;
3534
+ }
3535
+ }
3536
+ announceSession() {
3537
+ if (!this.isEnabled || !this.managesSessionId || !sessionStartedHere || this.config.sessionId === announcedSessionId) {
3538
+ return;
3539
+ }
3540
+ announcedSessionId = this.config.sessionId;
3541
+ this.emitPageEvent("session");
3542
+ }
3543
+ emitPageEvent(key) {
3544
+ const detail = {
3545
+ pageviewId: this.config.pageviewId,
3546
+ sessionId: this.config.sessionId
3547
+ };
3548
+ const configured = this.config.events?.[key];
3549
+ if (typeof configured === "function") {
3550
+ try {
3551
+ configured(detail);
3552
+ } catch (e) {
3553
+ this.log("ERROR", `Error in ${key} event handler`, e);
3554
+ }
3555
+ return;
3556
+ }
3557
+ const defaultName = `${this.config.alias}:${key}`;
3558
+ let eventName = defaultName;
3559
+ const trimmed = typeof configured === "string" ? configured.trim() : "";
3560
+ if (trimmed) {
3561
+ if (PAGE_EVENT_NAME_RE.test(trimmed) && (!trimmed.startsWith("ads:") || trimmed === defaultName)) {
3562
+ eventName = trimmed;
3563
+ } else {
3564
+ this.log(
3565
+ "WARN",
3566
+ `Invalid ${key} event name "${configured}"; falling back to "${defaultName}".`
3567
+ );
3568
+ }
3569
+ }
3570
+ if (typeof window === "undefined" || typeof window.dispatchEvent !== "function") return;
3571
+ try {
3572
+ window.dispatchEvent(new CustomEvent(eventName, { detail }));
3573
+ } catch (e) {
3574
+ this.log("ERROR", `Failed to dispatch ${eventName} event`, e);
3575
+ }
3519
3576
  }
3520
3577
  isSampledVisitor() {
3521
3578
  const key = this.config.visitorId || this.config.sessionId;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bidspark/analytics",
3
- "version": "0.45.2",
3
+ "version": "0.46.0",
4
4
  "description": "Bidspark auction analytics: a standalone Prebid.js analytics adapter, plus TypeScript bindings for the Bidspark ad SDK.",
5
5
  "keywords": [
6
6
  "advertising",