@bidspark/analytics 0.43.1 → 0.44.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.
@@ -1 +1 @@
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 Gt=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};function Yt(){if(typeof window<"u"){let n=window;return n.__bidsparkLogListeners||(n.__bidsparkLogListeners=new Set),n.__bidsparkLogListeners}return Ht}function zt(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 V(n){if(typeof n=="string"){let e=n.toUpperCase();if(e==="DEBUG"||e==="INFO"||e==="WARN"||e==="ERROR")return e}return C.INFO}function Ie(n){return new me(n)}var C,je,q,Kt,Ht,me,Ge=B(()=>{"use strict";C={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},je={[C.DEBUG]:10,[C.INFO]:20,[C.WARN]:30,[C.ERROR]:40},q={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"},Kt=0,Ht=new Set;me=class{_prefix;_level;_loadedAt;_now;_console;_listeners=new Set;constructor(e={}){this._prefix=e.prefix??"[ads]",this._level=V(e.logLevel??C.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=V(e)}getLevel(){return this._level}setLevel(e){this._level=V(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=V(e);return(je[t]??20)>=(je[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=Yt();for(let i of t)if(!this._listeners.has(i))try{i(e)}catch{}}log(e,t,...i){let r=V(e);if(!this.isEnabled(r))return;let o=this._getElapsed(),s=zt(o),d=Date.now(),u={id:`bk_log_${d}_${++Kt}`,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=q.badge,h=q.event;r===C.WARN?(m=q.badgeWarn,h=q.eventWarn):r===C.ERROR&&(m=q.badgeError,h=q.eventError);let f=["%c%s%c %s %c%s%c",m,this._prefix,q.dim,s,h,t,q.reset];switch(i.length>0&&f.push(...i),r){case C.DEBUG:typeof c.log=="function"?c.log(...f):typeof c.debug=="function"&&c.debug(...f);break;case C.INFO:typeof c.info=="function"?c.info(...f):typeof c.log=="function"&&c.log(...f);break;case C.WARN:typeof c.warn=="function"?c.warn(...f):typeof c.log=="function"&&c.log(...f);break;case C.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(C.DEBUG,e,...t)}info(e,...t){this.log(C.INFO,e,...t)}warn(e,...t){this.log(C.WARN,e,...t)}error(e,...t){this.log(C.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 He(){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 de(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 ve(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>=se&&(r=r+(i/se|0),i=i%se)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),e?ze(i,r):Te(i,r)}function Ye(n,e){let t=Te(n,e),i=t.hi&2147483648;i&&(t=ze(t.lo,t.hi));let r=Ee(t.lo,t.hi);return i?"-"+r:r}function Ee(n,e){if({lo:n,hi:e}=Xt(n,e),e<=2097151)return String(se*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()+Ke(s)+Ke(o)}function Xt(n,e){return{lo:n>>>0,hi:e>>>0}}function Te(n,e){return{lo:n|0,hi:e|0}}function ze(n,e){return e=~e,n?n=~n+1:e+=1,Te(n,e)}function we(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 Xe(){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 se,Ke,Ae=B(()=>{"use strict";se=4294967296;Ke=n=>{let e=String(n);return"0000000".slice(e.length)+e}});function Qt(){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()),Qe(t),t},uParse(t){return typeof t!="string"&&(t=t.toString()),Ze(t),t},enc(t){return typeof t!="string"&&(t=t.toString()),Qe(t),ve(t)},uEnc(t){return typeof t!="string"&&(t=t.toString()),Ze(t),ve(t)},dec(t,i){return Ye(t,i)},uDec(t,i){return Ee(t,i)}}}function Qe(n){if(!/^-?[0-9]+$/.test(n))throw new Error("invalid int64: "+n)}function Ze(n){if(!/^[0-9]+$/.test(n))throw new Error("invalid uint64: "+n)}var M,Je=B(()=>{"use strict";Ae();M=Qt()});function Ce(){if(globalThis[Se]==null){let n=new globalThis.TextEncoder,e=new globalThis.TextDecoder;globalThis[Se]={encodeUtf8(t){return n.encode(t)},decodeUtf8(t){return e.decode(t)},checkUtf8(t){try{return encodeURIComponent(t),!0}catch{return!1}}}}return globalThis[Se]}var Se,Re=B(()=>{"use strict";Se=Symbol.for("@bufbuild/protobuf/text-encoding")});function _e(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>tn||n<nn)throw new Error("invalid int32: "+n)}function et(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>en||n<0)throw new Error("invalid uint32: "+n)}function rn(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>Zt||n<Jt))throw new Error("invalid float32: "+n)}var j,Zt,Jt,en,tn,nn,N,S,tt=B(()=>{"use strict";Ae();Je();Re();(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"})(j||(j={}));Zt=34028234663852886e22,Jt=-34028234663852886e22,en=4294967295,tn=2147483647,nn=-2147483648,N=class{constructor(e=Ce().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(et(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return _e(e),we(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){rn(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){et(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){_e(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return _e(e),e=(e<<1^e>>31)>>>0,we(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=M.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=M.uEnc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=M.enc(e);return de(t.lo,t.hi,this.buf),this}sint64(e){let t=M.enc(e),i=t.hi>>31,r=t.lo<<1^i,o=(t.hi<<1|t.lo>>>31)^i;return de(r,o,this.buf),this}uint64(e){let t=M.uEnc(e);return de(t.lo,t.hi,this.buf),this}},S=class{constructor(e,t=Ce().decodeUtf8){this.decodeUtf8=t,this.varint64=He,this.uint32=Xe,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 j.Varint:for(;this.buf[this.pos++]&128;);break;case j.Bit64:this.pos+=4;case j.Bit32:this.pos+=4;break;case j.LengthDelimited:let r=this.uint32();this.pos+=r;break;case j.StartGroup:for(;;){let[o,s]=this.tag();if(s===j.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 M.dec(...this.varint64())}uint64(){return M.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,M.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 M.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return M.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 nt=B(()=>{"use strict"});var it=B(()=>{"use strict"});var rt=B(()=>{"use strict"});var Be=B(()=>{"use strict";tt();nt();Re();it();rt()});function on(){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}}function sn(){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 dn(){return{key:"",value:""}}function an(){return{adUnitCode:"",outcome:0,bid:void 0,refreshIndex:0,floorCents:void 0,floorSource:0,floorTreatmentBp:void 0,slot:""}}function cn(){return{bidder:"",cpm:0,currency:"",width:0,height:0,dealId:"",mediaType:"",latencyMs:0,advertiserDomain:"",creativeId:""}}var y,$,ue,te,ae,ot,st,ce,le=B(()=>{"use strict";Be();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,UNRECOGNIZED:-1},$={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},ue={FLOOR_SOURCE_UNSPECIFIED:0,FLOOR_SOURCE_STATIC:1,FLOOR_SOURCE_POOL:2,FLOOR_SOURCE_NONE:3,UNRECOGNIZED:-1};te={encode(n,e=new N){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)ae.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),e},decode(n,e){let t=n instanceof S?n:new S(n),i=e===void 0?t.len:t.pos+e,r=on();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=ae.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}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};ae={encode(n,e=new N){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&&ce.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])=>{ot.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)st.encode(t,e.uint32(98).fork()).join();return e},decode(n,e){let t=n instanceof S?n:new S(n),i=e===void 0?t.len:t.pos+e,r=sn();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=ce.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=ot.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=st.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}};ot={encode(n,e=new N){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 S?n:new S(n),i=e===void 0?t.len:t.pos+e,r=dn();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}};st={encode(n,e=new N){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&&ce.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 S?n:new S(n),i=e===void 0?t.len:t.pos+e,r=an();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=ce.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}};ce={encode(n,e=new N){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 S?n:new S(n),i=e===void 0?t.len:t.pos+e,r=cn();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 O(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(un.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(dt)return dt.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 Z(n){return typeof n!="number"||!Number.isFinite(n)||n<=0||n>1?1:n}function xe(n,e){let t=Z(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}var un,dt,Ti,fe=B(()=>{"use strict";un=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,dt=typeof TextEncoder<"u"?new TextEncoder:null,Ti=typeof TextDecoder<"u"?new TextDecoder:null});function ln(){return{unit:0,usageId:new Uint8Array(0),timestampMs:"0",slots:0}}function fn(){return{pageviewId:new Uint8Array(0),events:[]}}var ct,at,ut,lt=B(()=>{"use strict";Be();ct={USAGE_UNIT_UNSPECIFIED:0,AUCTION:1,SERVER_AUCTION:2,UNRECOGNIZED:-1};at={encode(n,e=new N){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 S?n:new S(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!==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}};ut={encode(n,e=new N){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)at.encode(t,e.uint32(18).fork()).join();return e},decode(n,e){let t=n instanceof S?n:new S(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!==10)break;r.pageviewId=t.bytes();continue}case 2:{if(o!==18)break;let s=at.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 ne(){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 Oe,ft=B(()=>{"use strict";le();fe();Oe="text/plain"});var pn,ht,he,pt=B(()=>{"use strict";lt();ft();fe();pn=1e4,ht=200,he=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||ne();let t=O(this.pageviewIdStr);this.pageviewIdBytes=t.length===16?t:O(ne()),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||ne(),this.pageviewIdBytes=O(this.pageviewIdStr)}getQueueLength(){return this.queue.length}record(e,t,i=ct.AUCTION){if(this.isDestroyed||!e)return;let r=O(e);if(r.length!==16&&(r=O(ne())),this.queue.push({unit:i,usageId:r,timestampMs:String(Date.now()),slots:typeof t=="number"&&t>0?t:0}),this.queue.length>=ht){this.flush();return}!this.flushTimer&&typeof setTimeout<"u"&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},pn))}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,ht),i={pageviewId:this.pageviewIdBytes,events:t},r=ut.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:Oe});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":Oe},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 X(){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 Dn(n){let e="";for(let i=0;i<n.length;i+=8192)e+=String.fromCharCode(...n.subarray(i,i+8192));return btoa(e)}function kn(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 Mn(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 Nn(n){let e={},t=0;for(let i of Object.keys(n)){if(t>=In)break;let r=n[i];if(r==null)continue;let o=String(r);e[i]=o.length>mt?`${o.slice(0,mt)}...[truncated]`:o,t++}return e}function Pn(n,e){if(!n||!e)return!1;try{return new URL(n).origin===new URL(e).origin}catch{return!1}}function St(n){try{typeof localStorage<"u"&&(localStorage.setItem(Ne,n.toString()),Y=n)}catch{}}function Ct(n=Date.now()){return W>0&&n-W<=At}function pe(){let n=Date.now(),e=!!L&&!Ct(n);if(W=n,e){L=null;for(let t of $n)t();return}!K||!L||Y===0||n-Y<Fn||St(n)}function Wn(){return!L||K&&Y===0}function qn(){if(Et||typeof window>"u")return;Et=!0;let n=()=>pe();for(let e of Vn)window.addEventListener(e,n,{passive:!0,capture:!0});typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&pe()})}function De(){let n=Date.now(),e=!!L&&Ct(n);try{if(K&&typeof localStorage<"u"){let t=localStorage.getItem(ke),i=localStorage.getItem(Ne),r=i&&parseInt(i,10)||0;if(t&&r&&n-r<=At)return L!==t&&(Le=!1),(L!==t||W<r)&&(L=t,W=Math.max(W,r)),Y===0&&(Y=r),t;let o=e?L:X();return e||(Le=!0,W=n),localStorage.setItem(ke,o),St(W),L=o,o}}catch{}return e||(Le=!0,L=X(),W=n),L}function jn(){Y=0;try{typeof localStorage<"u"&&(localStorage.removeItem(ke),localStorage.removeItem(Ne))}catch{}}function Tt(){try{if(K&&typeof localStorage<"u"){let n=localStorage.getItem(re);if(n)return n;let e=X();return localStorage.setItem(re,e),e}}catch{}return""}function ge(n){return n.regime!=="tcf"||!!n.purposesConsented?.includes(1)}function Rt(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 Gn(){if(typeof window>"u")return;let n=window;if(typeof n.__tcfapi!="function")return;let e;try{n.__tcfapi("getTCData",2,(t,i)=>{i&&t&&(e=ge(Rt(t)))})}catch{}return e!==void 0?e:!1}function Kn(){if(wt||typeof window>"u")return;let n=window;if(typeof n.__tcfapi=="function"){wt=!0;try{n.__tcfapi("addEventListener",2,(e,t)=>{!t||!e||R.setStorageAllowed(ge(Rt(e)))})}catch{}}}function Hn(n){if(typeof window>"u")return;let e=window,t=e[n]?.consent?.getRecord?.()||null;return t?ge(t):e[`__${n}_cmp`]?.gdpr?!1:void 0}function l(n){return String(n??"").replace(/%/g,"%25").replace(/:/g,"%3A")}function Yn(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 G(n){if(Number.isFinite(n?.width)&&Number.isFinite(n?.height))return{width:n.width,height:n.height};if(typeof n?.size=="string"){let e=n.size.match(/^(\d+)x(\d+)$/);if(e)return{width:Number(e[1]),height:Number(e[2])}}return{width:Number.isFinite(n?.width)?n.width:0,height:Number.isFinite(n?.height)?n.height:0}}function J(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?J(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 zn(n){if(!n)return null;if(n._bidsparkAnalyticsConfig){let t=J(n._bidsparkAnalyticsConfig);if(t)return t}let e=n.bidsparkPrebidAnalytics;if(e){if(e.options){let t=J(e.options);if(t)return t}if(e.config){let t=J(e.config);if(t)return t}if(e.propertyId)return J(e)}return null}function Pe(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&&!Pn(c.endpoint||"",a)&&(Q.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(h){Q.warn("Failed to disable previous analytics instance:",h)}let m=new R(c);return m.enable(),t._bidsparkPrebidAnalytics=m,m},o=()=>{try{if(i.adapterManager&&typeof i.adapterManager.registerAnalyticsAdapter=="function"){let d={enableAnalytics:a=>{let u=J(a,!Array.isArray(a));u&&r(u)},disableAnalytics:()=>{t._bidsparkPrebidAnalytics&&t._bidsparkPrebidAnalytics.disable()}};i.adapterManager.registerAnalyticsAdapter({adapter:{...d},code:"bidspark"})}let s=zn(t);s&&(s.propertyId||e?.propertyId)&&r(s)}catch(s){Q.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 gt,yt,gn,yn,ie,bn,mn,bt,mt,In,It,vt,vn,En,Tn,wn,An,Sn,Cn,Rn,H,_n,Bn,Un,xn,On,Ln,ke,Ne,At,L,W,Le,K,Fn,Y,Vn,Et,$n,re,wt,Me,Q,R,Fe=B(()=>{"use strict";Ge();le();fe();pt();gt="ads",yt=1e4,gn=50,yn=20,ie=200,bn=300*1e3,mn=10,bt=32*1024,mt=1024,In=16,It="text/plain",vt="ads_pending_",vn=20,En=7200*1e3,Tn=1e4,wn={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},An={WARN:y.WARN,ERROR:y.ERROR},Sn=new Set([y.ERROR,y.WARN]),Cn=3e3,Rn=new Set([y.IMPRESSION,y.BID_WIN,y.CLICK]),H=1800*1e3,_n=200,Bn=1e3,Un=50,xn=200,On={static:ue.FLOOR_SOURCE_STATIC,pool:ue.FLOOR_SOURCE_POOL,none:ue.FLOOR_SOURCE_NONE},Ln=1e3,ke="ads_session",Ne="ads_session_ts",At=1800*1e3,L=null,W=0,Le=!1,K=!0;Fn=60*1e3,Y=0,Vn=["pointerdown","pointermove","keydown","scroll","wheel","touchstart"],Et=!1,$n=new Set;re="ads_uid";wt=!1;Me=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=Yn(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}};Q=Ie({prefix:"[analytics]",logLevel:"INFO"}),R=class n{static activeInstances=new Set;static allInstances=new Set;static getActiveInstances(){return n.activeInstances}static setLogLevel(e){let t=V(e);Q.setLevel(t);for(let i of n.allInstances)i.setLogLevel(t)}static getLogLevel(){return Q.getLevel()}static setStorageAllowed(e){K=e,Y=0;for(let t of n.allInstances)t.config.storageAllowed=e,e?t.config.userId||(t.config.userId=Tt(),t.config.visitorId=t.config.userId||t.config.pageviewId):(t.config.userId="",t.config.visitorId=t.config.visitorId||t.config.pageviewId)}static isStorageAllowed(){return K}config;usageRecorder=null;queue=[];errorCount=0;flushTimer=null;boundFlushBeacon;boundVisibilityChange;isEnabled=!1;boundPbjsHandlers=[];pageUrl="";deduper=new Me;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;logger;managesSessionId;constructor(e){let t=Gn();typeof window<"u"&&typeof window.__tcfapi=="function"&&Kn();let i=e.storageAllowed??t??Hn(e.alias||gt);i!==void 0&&n.setStorageAllowed(i);let r=i!==void 0?i:K,o=e.endpoint||"",s=!o||Mn(o)?o:"",d=e.pageviewId||X(),a="",u="";if(r){if(a=e.userId||Tt(),e.userId)try{typeof localStorage<"u"&&localStorage.setItem(re,e.userId)}catch{}u=e.visitorId||a||d}else a="",u=e.visitorId||d;let c=e.usageEndpoint||"";this.config={endpoint:s,usageEndpoint:c,propertyId:e.propertyId||"",pageviewId:d,sessionId:e.sessionId||"",userId:a,visitorId:u,deviceType:e.deviceType||"desktop",country:e.country||"",region:e.region||"",auctionEnabled:e.auctionEnabled??!0,warningsEnabled:e.warningsEnabled??!0,sampleRate:Z(e.sampleRate),viewabilityEnabled:e.viewabilityEnabled??!0,storageAllowed:r,logLevel:e.logLevel?V(e.logLevel):Q.getLevel(),pbjsGlobalName:e.pbjsGlobalName||"pbjs",attachPbjsListeners:e.attachPbjsListeners??!0,revenueFlushDelayMs:Number.isFinite(e.revenueFlushDelayMs)&&e.revenueFlushDelayMs>=0?e.revenueFlushDelayMs:Cn,alias:e.alias||gt},n.allInstances.add(this),this.logger=Ie({prefix:"[analytics]",logLevel:this.config.logLevel}),pe(),this.managesSessionId=!e.sessionId,this.managesSessionId&&(this.config.sessionId=De()),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()}setLogLevel(e){let t=V(e);this.config.logLevel=t,this.logger.setLevel(t),Q.setLevel(t)}getLogLevel(){return this.logger.getLevel()}enable(){if(!this.isEnabled){if(this.isEnabled=!0,n.activeInstances.add(this),this.logger.setLevel(this.config.logLevel),this.config.attachPbjsListeners&&this.config.usageEndpoint&&!this.usageRecorder&&(this.usageRecorder=new he({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)}if(this.config.attachPbjsListeners&&this.attachPbjs(),this.cmpDetach=this.attachCmp(),typeof window<"u"){if(!this.pageUrl)try{let e=new URL(window.location.href);this.pageUrl=e.origin+e.pathname}catch{this.pageUrl=window.location.href}window.addEventListener("pagehide",this.boundFlushBeacon),typeof document<"u"&&document.addEventListener("visibilitychange",this.boundVisibilityChange),qn(),this.flushTimer=setInterval(()=>this.flush(),yt),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)}})}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)<Ln)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:"")||X(),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>H){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>H&&this.cachedWinningBids.delete(t);for(;this.cachedWinningBids.size>_n;){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>=Bn;){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>Un;){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(o){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 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)}`):this.slotEmittedImpressionKeys.has(d)}markImpressionEmitted(e,t,i,r,o){let s=`${l(e)}:${t}`;!!(o||r)?(o&&(this.addImpressionKey(`${s}:ad:${l(o)}`),i&&this.addImpressionKey(`${s}:auc:${l(i)}:ad:${l(o)}`)),r&&r!==o&&(this.addImpressionKey(`${s}:${l(r)}`),i&&this.addImpressionKey(`${s}:auc:${l(i)}:${l(r)}`)),i&&this.addImpressionKey(`${s}:auc:${l(i)}`)):(this.addImpressionKey(s),i&&this.addImpressionKey(`${s}:auc:${l(i)}`))}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",h=i||r,f=(i?this.slotViewabilityRecords.get(i):void 0)||(r?this.slotViewabilityRecords.get(r):void 0),U=h?this.slotLastAuctionIds.get(h)||(f?f.auctionId:void 0):void 0,I=!!(h&&d&&U&&U!==d&&t?.refreshIndex===void 0),_={bidder:s.bidderCode||s.bidder||o?.bidTrace?.bidder||"",cpm:Number.isFinite(s.originalCpm)?s.originalCpm:Number.isFinite(s.cpm)?s.cpm:o?.bidTrace?.cpm??0,currency:s.originalCurrency??s.currency??o?.bidTrace?.currency??"USD",...G(s).width?G(s):o?.bidTrace?{width:o.bidTrace.width,height:o.bidTrace.height}:G(s),dealId:s.dealId||o?.bidTrace?.dealId||"",mediaType:m,latencyMs:Number.isFinite(s.timeToRespond)?s.timeToRespond:o?.bidTrace?.latencyMs??0,advertiserDomain:s.meta?.advertiserDomains?.[0]||o?.bidTrace?.advertiserDomain||"",creativeId:s.creativeId||o?.bidTrace?.creativeId||""};if(I&&h){this.flushSlotTimeInView(h);let v=(this.slotRefreshIndices.get(h)??(f?f.refreshIndex:0))+1;this.slotRefreshIndices.set(h,v),this.slotLastAuctionIds.set(h,d),f&&(f.refreshIndex=v,f.auctionId=d,f.transactionId=a,f.bidPayload=_,f.viewableFired=!1,f.accumulatedTimeInViewMs=0)}else h&&(d&&this.slotLastAuctionIds.set(h,d),this.slotRefreshIndices.has(h)||this.slotRefreshIndices.set(h,0));let x=t?.refreshIndex??(i?this.slotRefreshIndices.get(i)??(r?this.slotRefreshIndices.get(r):void 0)??(f?f.refreshIndex:0):0);return i&&this.hasImpressionEmitted(i,x,d,u,c)||r&&r!==i&&this.hasImpressionEmitted(r,x,d,u,c)?(this.log("DEBUG",`Impression already emitted for slot ${i||r} in cycle ${x}`),!1):(i&&this.markImpressionEmitted(i,x,d,u,c),r&&r!==i&&this.markImpressionEmitted(r,x,d,u,c),this.enqueue(y.IMPRESSION,"impression",{auctionId:d,transactionId:a,adUnitCode:r,bid:_,metadata:{...t?.metadata,refresh_index:String(x)}}),f&&(!f.bidPayload&&_&&(f.bidPayload=_),!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=An[e]??wn[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>xn;){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.recordConsent(s),this.followConsent(s))};document.addEventListener("ads:consent",e);let i=(typeof window<"u"?window:{})[this.config.alias]?.consent?.getRecord?.()||null;i&&(this.recordConsent(i),this.followConsent(i));let r=!1;return()=>{r||(r=!0,document.removeEventListener("ads:consent",e))}}followConsent(e){let t=ge(e);t||jn(),n.setStorageAllowed(t)}setUserId(e){if(this.config.userId=e,e&&(this.config.visitorId=e),this.config.storageAllowed&&typeof localStorage<"u")try{e?localStorage.setItem(re,e):localStorage.removeItem(re)}catch{}}setVisitorId(e){this.config.visitorId=e}setSampleRate(e){this.config.sampleRate=Z(e)}setSessionId(e){this.config.sessionId=e,this.managesSessionId=!e,this.managesSessionId&&(this.config.sessionId=De())}navigate(e,t){if(this.disable(),this.slotRefreshIndices.clear(),this.slotNames.clear(),this.slotAdSessionCounters.clear(),this.floorDecisions.clear(),this.recordedConsentKeys.clear(),this.consentCount=0,this.config.pageviewId=e||X(),t)try{let i=new URL(t);this.pageUrl=i.origin+i.pathname}catch{this.pageUrl=t}else this.pageUrl="";this.logger.resetTiming(),pe(),this.enable()}recordAuctionStart(e,t="",i){!this.isEnabled||!this.config.auctionEnabled||this.enqueue(y.AUCTION_START,"auctionStart",{auctionId:e,adUnitCode:t,...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=d.length>0?d[0]:o.mediaType||"banner",u=`${i}:${s}`;r.has(u)||r.set(u,{adUnitCode:s,outcome:$.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=Number.isFinite(e.originalCpm)?e.originalCpm:Number.isFinite(e.cpm)?e.cpm:0,s=Number.isFinite(e.timeToRespond)?e.timeToRespond:0,d=Object.keys(e.mediaTypes||{}),a=e.mediaType||(e.mediaTypes?.video?"video":d.length>0?d[0]:"banner");if(!t||!i)return;let u=o>0?{bidder:i,cpm:o,currency:e.originalCurrency??e.currency??"USD",...G(e),dealId:e.dealId||"",mediaType:a,latencyMs:s,advertiserDomain:e.meta?.advertiserDomains?.[0]||"",creativeId:e.creativeId||""}:{bidder:i,mediaType:a,latencyMs:s};this.getOrCreateAuctionOutcomes(t).set(`${i}:${r}`,{adUnitCode:r,outcome:o>0?$.BIDDER_OUTCOME_BID:$.BIDDER_OUTCOME_NO_BID,bid:u})}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=$.BIDDER_OUTCOME_TIMEOUT,d>0&&c.bid&&(c.bid.latencyMs=d)):a.set(u,{adUnitCode:s,outcome:$.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||"",cpm:Number.isFinite(e.originalCpm)?e.originalCpm:Number.isFinite(e.cpm)?e.cpm:0,currency:e.originalCurrency??e.currency??"USD",...G(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===$.BIDDER_OUTCOME_NO_RESPONSE&&(d.outcome=$.BIDDER_OUTCOME_NO_BID):o.set(s,{adUnitCode:r,outcome:$.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),c=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",m=c?"video":s||u?.bidTrace?.mediaType||"banner",h={bidder:t.bidderCode||t.bidder||u?.bidTrace?.bidder||"",cpm:Number.isFinite(t.originalCpm)?t.originalCpm:Number.isFinite(t.cpm)?t.cpm:u?.bidTrace?.cpm??0,currency:t.originalCurrency??t.currency??u?.bidTrace?.currency??"USD",...G(t).width?G(t):u?.bidTrace?{width:u.bidTrace.width,height:u.bidTrace.height}:G(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||"",U=o||u?.transactionId||"",I=i?this.slotViewabilityRecords.get(i):void 0,_=I&&f&&I.auctionId&&I.auctionId!==f,x=!!(i&&I&&_);if(x){this.flushSlotTimeInView(i);let v=(this.slotRefreshIndices.get(i)??(I?I.refreshIndex:0))+1;this.slotRefreshIndices.set(i,v),this.slotLastAuctionIds.set(i,f),I&&(I.auctionId=f,I.transactionId=U,I.bidPayload=h)}else i&&(f&&this.slotLastAuctionIds.set(i,f),this.slotRefreshIndices.has(i)||this.slotRefreshIndices.set(i,0));let D=i?this.slotRefreshIndices.get(i)??(I?I.refreshIndex:0):0;if(c?this.log("DEBUG",`adRenderSucceeded received for video ad unit ${i||"unknown"}: suppressing IMPRESSION until verified video lifecycle event`):i&&this.hasImpressionEmitted(i,D,f,h.creativeId)||(i&&this.markImpressionEmitted(i,D,f,h.creativeId),this.enqueue(y.IMPRESSION,"impression",{auctionId:f,transactionId:U,adUnitCode:i,bid:h,metadata:{refresh_index:String(D)}})),this.config.viewabilityEnabled&&typeof document<"u"){let v=i&&this.slotElements.get(i)||null,T=i||e.adId||t.adId;if(!v&&T&&(v=document.getElementById(T)),!v&&typeof window<"u"&&window.googletag?.pubads)try{let P=window.googletag.pubads().getSlots();for(let b of P)if((b.getAdUnitPath?.()===i||b.getSlotElementId?.()===i)&&(v=document.getElementById(b.getSlotElementId()),v))break}catch{}if(!v&&T)try{for(let P of Array.from(document.querySelectorAll("[data-ad-slot]")))if(P.getAttribute("data-ad-slot")===T){v=P;break}}catch{}v?this.observeSlot(v,i||T,{adUnitCode:i,auctionId:f,transactionId:U,mediaType:m,bid:h,refreshIndex:D,isRefresh:x}):I&&x&&(I.refreshIndex=D,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.managesSessionId&&Wn()&&(this.config.sessionId=De());let r={eventId:O(X()),timestampMs:Date.now(),type:e,eventName:Sn.has(e)?t:"",auctionId:O(String(i.auctionId||"")),transactionId:O(String(i.transactionId||"")),adUnitCode:i.adUnitCode||i.elementId||"",namespace:i.ns||i.namespace||""};i.bid&&(r.bid={bidder:i.bid.bidder||"",cpm:Number.isFinite(i.bid.cpm)?i.bid.cpm:0,currency:i.bid.currency||"",width:Number.isFinite(i.bid.width)?i.bid.width:0,height:Number.isFinite(i.bid.height)?i.bid.height:0,dealId:i.bid.dealId||"",mediaType:i.bid.mediaType||"",latencyMs:Number.isFinite(i.bid.latencyMs)?i.bid.latencyMs:0,advertiserDomain:i.bid.advertiserDomain||"",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:On[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=Nn(o);Object.keys(d).length>0&&(r.metadata=d),this.queue.push(r),this.queue.length>=ie?(this.flush(),this.queue.length>ie&&this.queue.splice(0,this.queue.length-ie)):Rn.has(e)&&this.revenueFlushTimer===null&&(this.revenueFlushTimer=setTimeout(()=>{this.revenueFlushTimer=null,this.flush()},this.config.revenueFlushDelayMs))}isSampledVisitor(){let e=this.config.userId||this.config.visitorId||this.config.pageviewId;return xe(e,this.config.sampleRate)}shouldSample(e){return this.isSampledVisitor()?e===y.ERROR?(this.errorCount++,this.errorCount<=gn):e===y.CONSENT?(this.consentCount++,this.consentCount<=yn):e===y.WARN?this.config.warningsEnabled:this.config.auctionEnabled:!1}requeue(e){e.length&&(this.queue=e.concat(this.queue),this.queue.length>ie&&this.queue.splice(0,this.queue.length-ie))}drainBatch(){if(this.queue.length===0||!this.config.endpoint)return null;let e=typeof window<"u"?window.location.hostname:"",t=Z(this.config.sampleRate),i=o=>({propertyId:O(this.config.propertyId),pageviewId:O(this.config.pageviewId),sessionId:O(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:o,...t<1?{sampleRate:t}:{}}),r=te.encode(i([])).finish().byteLength;for(;;){if(this.queue.length===0)return null;let o=0,s=r;for(let u=0;u<this.queue.length;u++){let c=this.queue[u],h=ae.encode(c).finish().byteLength+6;if(s+h>bt){if(o===0){let[f]=this.queue.splice(0,1),U=te.encode(i([f])).finish().byteLength;this.log("WARN",`Dropping oversized event (type ${f?.type}, ${U} bytes exceeds the ${bt}-byte cap on its own)`);break}break}s+=h,o++}if(o===0)continue;let d=this.queue.slice(0,o),a=te.encode(i(d)).finish();return this.queue=this.queue.slice(d.length),{url:this.batchUrl(),encoded:a,events:d}}}sendFetch(e,t=!1,i,r=!1){let o={method:"POST",headers:{"Content-Type":It},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(yt*2**(this.consecutiveSendFailures-1),bn);this.nextSendAllowedAt=Date.now()+t,this.consecutiveSendFailures<=mn?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();for(;e&&(this.sendFetch(e,!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:It});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`${vt}${encodeURIComponent(this.config.propertyId)}_`}persistBatch(e){if(!K)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(vt)&&t++}if(t>=vn)return null;let i=`${this.pendingKeyPrefix()}${Date.now()}_${Math.floor(Math.random()*1e6)}`;return localStorage.setItem(i,Dn(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)},Tn))}resendPersistedBatches(){try{if(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>En)continue;let s;try{s=kn(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 Xn(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 Ot(n,e,t){let i=ye(n),{err:r,message:o,metadata:s}=Xn(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 Qn(n,e){if(!n||typeof n!="object"||_t.has(n))return;_t.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 R.getActiveInstances())try{let o=Dt(r,{mediaType:"video"});Ot(r,i,{adStarted:!1,adUnitCode:o?.adUnitCode||"video",auctionId:o?.auctionId,transactionId:o?.transactionId,bid:o?.bidTrace})}catch{}})}catch{}}function Bt(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 R.getActiveInstances())try{s.attachImaAdsManager(o)}catch{}return o};i.__bidsparkHooked=!0,e.getAdsManager=i}}catch{}}function Ut(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 R.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 R.getActiveInstances())try{o.attachImaAdsManager(this)}catch{}return t.apply(this,r)};i.__bidsparkHooked=!0,e.start=i}}catch{}}function xt(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(Qn(this,t),(r==="adsManagerLoaded"||r===(this?.AdsManagerLoadedEvent?.Type?.ADS_MANAGER_LOADED||"adsManagerLoaded"))&&typeof o=="function"){let d=Ve.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 h of R.getActiveInstances())try{h.attachImaAdsManager(m)}catch{}return m},a.getAdsManager.__bidsparkHooked=!0}return o.apply(this,arguments)},Ve.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"?Ve.get(o):void 0;return t.call(this,r,d||o,...s)};i.__bidsparkHooked=!0,e.removeEventListener=i}}catch{}}function oe(n){if(!(!n||typeof n!="object"))try{n.AdsManagerLoadedEvent&&Bt(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,Bt(o)}})}catch{}}n.AdsLoader&&xt(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,xt(o)}})}catch{}}n.AdsManager&&Ut(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,Ut(o)}})}catch{}}}catch{}}function Lt(){if(typeof window>"u")return;let n=window;if(n.google?.ima&&oe(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,oe(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&&oe(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,oe(s)}})}catch{}}}}})}catch{}}}function Dt(n,e){let t=ye(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>H)&&(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>H)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>H)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>H||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>H||(!s||d.timestamp>s.timestamp)&&(s=d);return s}function kt(n,e,t){let i=ye(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||"",u=t?.transactionId||"",c=g=>{let p=(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 p||(p=Dt(n,{creativeId:g?.creativeId,adId:g?.adId,mediaType:"video"})),p},m=!1,h=null,f=g=>{let p=typeof i.nextSlotAdSession=="function"?i.nextSlotAdSession(s):`ad-session-${(i.slotAdSessionCounters?.get(s)??0)+1}`;if(i.slotAdSessionCounters&&typeof i.nextSlotAdSession!="function"){let F=(i.slotAdSessionCounters.get(s)??0)+1;i.slotAdSessionCounters.set(s,F)}let E=(typeof g?.getAdId=="function"?g.getAdId():g?.adId??g?.id)||"",z=(typeof g?.getCreativeId=="function"?g.getCreativeId():g?.creativeId)||"";return h={sessionId:p,adId:E||void 0,creativeId:z||void 0},h},U=g=>{let p=typeof g?.getAd=="function"?g.getAd():g?.ad;f(p),i.log("DEBUG","IMA AdEvent.LOADED received",{slotId:s,activeAdSession:h})},I=g=>{m=!0;let p=typeof g?.getAd=="function"?g.getAd():g?.ad,E={};p&&(E.creativeId=(typeof p.getCreativeId=="function"?p.getCreativeId():p.creativeId)||"",E.adId=(typeof p.getAdId=="function"?p.getAdId():p.id)||"",E.title=(typeof p.getTitle=="function"?p.getTitle():p.title)||"",E.duration=typeof p.getDuration=="function"?p.getDuration():p.duration,E.advertiserName=typeof p.getAdvertiserName=="function"?p.getAdvertiserName():""),!h||E.adId&&h.adId&&h.adId!==E.adId?f(p):(!h.adId&&E.adId&&(h.adId=E.adId),!h.creativeId&&E.creativeId&&(h.creativeId=E.creativeId));let z=h||f(p),F=c(E),be=t?.slotId&&t.slotId!=="video"?t.slotId:t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:F?.adUnitCode||t?.slotId||t?.adUnitCode||"video",Ft=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:F?.adUnitCode||be,Vt=a||F?.auctionId||"",$t=u||F?.transactionId||"",$e=z.creativeId||E.creativeId||F?.bidTrace?.creativeId||t?.bid?.creativeId||"",Wt=z.adId||E.adId||$e||z.sessionId,We={...F?.rawBid||t?.bid,mediaType:"video",creativeId:$e},qe=i.recordImpression(be,{adUnitCode:Ft,auctionId:Vt,transactionId:$t,mediaType:"video",bid:We,adId:Wt,metadata:{...t?.metadata,media_type:"video",...E.title?{ad_title:E.title}:{},...Number.isFinite(E.duration)?{ad_duration_s:String(E.duration)}:{}}}),ee=typeof g?.type=="string"?g.type:typeof g?.getType=="function"?g.getType():typeof g=="string"?g:"";ee.toLowerCase().startsWith("adevent.")&&(ee=ee.slice(8));let qt=ee?ee.toUpperCase():"STARTED/IMPRESSION";if(i.log("DEBUG",`IMA AdEvent.${qt} received${qe?"":" (second event for this ad, already counted)"}`,g),qe&&t?.onImpression)try{t.onImpression(be,{ad:p,bid:We})}catch(jt){i.log("ERROR","Error in onImpression callback",jt)}},_=g=>{if(i.log("DEBUG",`IMA AdEvent milestone: ${g}`),t?.onMilestone)try{t.onMilestone(g,s)}catch(p){i.log("ERROR","Error in onMilestone callback",p)}},x=g=>{i.log("DEBUG","IMA AdEvent.CLICK received",g);let p=c(),E=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:p?.adUnitCode||s;i.enqueue(y.CLICK,"click",{auctionId:a||p?.auctionId,transactionId:u||p?.transactionId,adUnitCode:E,bid:p?.bidTrace||t?.bid,metadata:{...t?.metadata,media_type:"video"}})},D=g=>{h=null;let p=c(),E=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:p?.adUnitCode||s,z=Ot(n,g,{adStarted:m,adUnitCode:E,auctionId:a||p?.auctionId,transactionId:u||p?.transactionId,bid:p?.bidTrace||t?.bid,metadata:t?.metadata});if(t?.onError)try{t.onError(z)}catch(F){i.log("ERROR","Error in onError callback",F)}},v=typeof window<"u"?window.google?.ima:void 0,T=v?.AdEvent?.Type||{},P=v?.AdErrorEvent?.Type||{},b=[{type:T.LOADED||"loaded",handler:U},{type:T.STARTED||"started",handler:I},{type:T.IMPRESSION||"impression",handler:I},{type:T.FIRST_QUARTILE||"firstQuartile",handler:()=>_("firstQuartile")},{type:T.MIDPOINT||"midpoint",handler:()=>_("midpoint")},{type:T.THIRD_QUARTILE||"thirdQuartile",handler:()=>_("thirdQuartile")},{type:T.COMPLETE||"complete",handler:()=>{h=null,_("complete")}},{type:T.ALL_ADS_COMPLETED||"allAdsCompleted",handler:()=>{h=null}},{type:T.CLICK||"click",handler:x},{type:P.AD_ERROR||"adError",handler:D}],A=new Set,w=[];for(let g of b)A.has(g.type)||(A.add(g.type),w.push(g));for(let{type:g,handler:p}of w)try{e.addEventListener(g,p)}catch{}let k=()=>{h=null,r.delete(n);for(let{type:g,handler:p}of w)try{e.removeEventListener(g,p)}catch{}i.videoDetachCleanups.delete(k)};return r.set(n,k),i.videoDetachCleanups.add(k),k}function Zn(n,e,t){let i=ye(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 kt(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},h=b=>{let A=b||c||(r?.querySelector?r.querySelector("video"):null),w=u(),k={...w?.rawBid||t?.bid,mediaType:"video"};if(i.recordImpression(o,{adUnitCode:s,auctionId:d||w?.auctionId,transactionId:a||w?.transactionId,mediaType:"video",bid:k,metadata:{...t?.metadata,media_type:"video",...A&&Number.isFinite(A.duration)?{video_duration_s:String(Math.round(A.duration))}:{}}})&&t?.onImpression)try{t.onImpression(o,{element:A||r,bid:k})}catch(p){i.log("ERROR","Error in onImpression callback",p)}},f=b=>{i.log("DEBUG","HTML5 video playing event received");let A=b?.target instanceof HTMLVideoElement?b.target:c;h(A)},U=b=>{let A=b?.target instanceof HTMLVideoElement?b.target:c;if(A&&A.currentTime>0&&(h(A),Number.isFinite(A.duration)&&A.duration>0)){let w=A.currentTime/A.duration;w>=.25&&!m.q1&&(m.q1=!0,t?.onMilestone?.("firstQuartile",o)),w>=.5&&!m.q2&&(m.q2=!0,t?.onMilestone?.("midpoint",o)),w>=.75&&!m.q3&&(m.q3=!0,t?.onMilestone?.("thirdQuartile",o))}},I=()=>{m.q4||(m.q4=!0,t?.onMilestone?.("complete",o))},_=b=>{let w=(b?.target instanceof HTMLVideoElement?b.target:c)?.error||c?.error,k=u(),g=w?`HTML5 video error code ${w.code}: ${w.message}`:"Video playback error";if(i.log("WARN",g),i.enqueue(y.AD_RENDER_FAILED,"adRenderFailed",{auctionId:d||k?.auctionId,transactionId:a||k?.transactionId,adUnitCode:s,bid:k?.bidTrace||t?.bid,metadata:{...t?.metadata,reason:"html5_video_error",message:g,...w?.code?{error_code:String(w.code)}:{}},error:w?new Error(g):void 0}),t?.onError)try{t.onError(w)}catch(p){i.log("ERROR","Error in onError callback",p)}},x=b=>{b.addEventListener("playing",f),b.addEventListener("play",f),b.addEventListener("timeupdate",U),b.addEventListener("ended",I),b.addEventListener("error",_)},D=b=>{b.removeEventListener("playing",f),b.removeEventListener("play",f),b.removeEventListener("timeupdate",U),b.removeEventListener("ended",I),b.removeEventListener("error",_)},v=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",_,!0)),c&&x(c),r&&r.tagName?.toLowerCase()!=="video"&&typeof MutationObserver<"u"&&(v=new MutationObserver(()=>{let b=r.querySelector("video");b&&b!==c&&(c&&D(c),c=b,c&&x(c))}),v.observe(r,{childList:!0,subtree:!0}));let T=u();t?.trackViewability!==!1&&r&&i.observeSlot(r,o,{adUnitCode:s,auctionId:d||T?.auctionId,transactionId:a||T?.transactionId,mediaType:"video",bid:T?.bidTrace||t?.bid,metadata:t?.metadata});let P=()=>{v&&(v.disconnect(),v=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",_,!0)),c&&D(c),i.videoDetachCleanups.delete(P)};return i.videoDetachCleanups.add(P),P}var ye,Ve,_t,Jn,Mt=B(()=>{"use strict";Fe();le();ye=n=>n,Ve=new WeakMap,_t=new WeakSet;typeof window<"u"&&Lt();R.prototype.attachImaAdsManager=function(n,e){return kt(this,n,e)};R.prototype.attachVideoPlayer=function(n,e){return Zn(this,n,e)};Jn=R.prototype.enable;R.prototype.enable=function(){Jn.call(this),typeof window<"u"&&(Lt(),window.google?.ima&&oe(window.google.ima))}});var ti=Gt(()=>{Fe();Mt();var Nt="https://by.bidspark.io/t",Pt="https://by.bidspark.io/u",ei=window._bidsparkPbjsGlobal||"pbjs";Pe(ei,{endpoint:Nt,usageEndpoint:Pt});window.bidsparkPrebidAnalytics={...window.bidsparkPrebidAnalytics,register:(n,e)=>Pe(n,{endpoint:Nt,usageEndpoint:Pt,...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},setLogLevel:n=>{R.setLogLevel(n)},getLogLevel:()=>R.getLogLevel()}});return ti();})();
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 Kt=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};function zt(){if(typeof window<"u"){let n=window;return n.__bidsparkLogListeners||(n.__bidsparkLogListeners=new Set),n.__bidsparkLogListeners}return Yt}function Xt(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 F(n){if(typeof n=="string"){let e=n.toUpperCase();if(e==="DEBUG"||e==="INFO"||e==="WARN"||e==="ERROR")return e}return C.INFO}function ve(n){return new Ie(n)}var C,Ge,q,Ht,Yt,Ie,Ke=U(()=>{"use strict";C={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},Ge={[C.DEBUG]:10,[C.INFO]:20,[C.WARN]:30,[C.ERROR]:40},q={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"},Ht=0,Yt=new Set;Ie=class{_prefix;_level;_loadedAt;_now;_console;_listeners=new Set;constructor(e={}){this._prefix=e.prefix??"[ads]",this._level=F(e.logLevel??C.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=F(e)}getLevel(){return this._level}setLevel(e){this._level=F(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=F(e);return(Ge[t]??20)>=(Ge[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=zt();for(let i of t)if(!this._listeners.has(i))try{i(e)}catch{}}log(e,t,...i){let r=F(e);if(!this.isEnabled(r))return;let o=this._getElapsed(),s=Xt(o),d=Date.now(),u={id:`bk_log_${d}_${++Ht}`,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=q.badge,h=q.event;r===C.WARN?(m=q.badgeWarn,h=q.eventWarn):r===C.ERROR&&(m=q.badgeError,h=q.eventError);let f=["%c%s%c %s %c%s%c",m,this._prefix,q.dim,s,h,t,q.reset];switch(i.length>0&&f.push(...i),r){case C.DEBUG:typeof c.log=="function"?c.log(...f):typeof c.debug=="function"&&c.debug(...f);break;case C.INFO:typeof c.info=="function"?c.info(...f):typeof c.log=="function"&&c.log(...f);break;case C.WARN:typeof c.warn=="function"?c.warn(...f):typeof c.log=="function"&&c.log(...f);break;case C.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(C.DEBUG,e,...t)}info(e,...t){this.log(C.INFO,e,...t)}warn(e,...t){this.log(C.WARN,e,...t)}error(e,...t){this.log(C.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 Ye(){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 de(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 Ee(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>=se&&(r=r+(i/se|0),i=i%se)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),e?Xe(i,r):we(i,r)}function ze(n,e){let t=we(n,e),i=t.hi&2147483648;i&&(t=Xe(t.lo,t.hi));let r=Te(t.lo,t.hi);return i?"-"+r:r}function Te(n,e){if({lo:n,hi:e}=Qt(n,e),e<=2097151)return String(se*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()+He(s)+He(o)}function Qt(n,e){return{lo:n>>>0,hi:e>>>0}}function we(n,e){return{lo:n|0,hi:e|0}}function Xe(n,e){return e=~e,n?n=~n+1:e+=1,we(n,e)}function Ae(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 Qe(){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 se,He,Se=U(()=>{"use strict";se=4294967296;He=n=>{let e=String(n);return"0000000".slice(e.length)+e}});function Zt(){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()),Ze(t),t},uParse(t){return typeof t!="string"&&(t=t.toString()),Je(t),t},enc(t){return typeof t!="string"&&(t=t.toString()),Ze(t),Ee(t)},uEnc(t){return typeof t!="string"&&(t=t.toString()),Je(t),Ee(t)},dec(t,i){return ze(t,i)},uDec(t,i){return Te(t,i)}}}function Ze(n){if(!/^-?[0-9]+$/.test(n))throw new Error("invalid int64: "+n)}function Je(n){if(!/^[0-9]+$/.test(n))throw new Error("invalid uint64: "+n)}var M,et=U(()=>{"use strict";Se();M=Zt()});function Re(){if(globalThis[Ce]==null){let n=new globalThis.TextEncoder,e=new globalThis.TextDecoder;globalThis[Ce]={encodeUtf8(t){return n.encode(t)},decodeUtf8(t){return e.decode(t)},checkUtf8(t){try{return encodeURIComponent(t),!0}catch{return!1}}}}return globalThis[Ce]}var Ce,_e=U(()=>{"use strict";Ce=Symbol.for("@bufbuild/protobuf/text-encoding")});function Be(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>nn||n<rn)throw new Error("invalid int32: "+n)}function tt(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>tn||n<0)throw new Error("invalid uint32: "+n)}function on(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>Jt||n<en))throw new Error("invalid float32: "+n)}var j,Jt,en,tn,nn,rn,N,S,nt=U(()=>{"use strict";Se();et();_e();(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"})(j||(j={}));Jt=34028234663852886e22,en=-34028234663852886e22,tn=4294967295,nn=2147483647,rn=-2147483648,N=class{constructor(e=Re().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(tt(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Be(e),Ae(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){on(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){tt(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Be(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Be(e),e=(e<<1^e>>31)>>>0,Ae(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=M.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=M.uEnc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=M.enc(e);return de(t.lo,t.hi,this.buf),this}sint64(e){let t=M.enc(e),i=t.hi>>31,r=t.lo<<1^i,o=(t.hi<<1|t.lo>>>31)^i;return de(r,o,this.buf),this}uint64(e){let t=M.uEnc(e);return de(t.lo,t.hi,this.buf),this}},S=class{constructor(e,t=Re().decodeUtf8){this.decodeUtf8=t,this.varint64=Ye,this.uint32=Qe,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 j.Varint:for(;this.buf[this.pos++]&128;);break;case j.Bit64:this.pos+=4;case j.Bit32:this.pos+=4;break;case j.LengthDelimited:let r=this.uint32();this.pos+=r;break;case j.StartGroup:for(;;){let[o,s]=this.tag();if(s===j.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 M.dec(...this.varint64())}uint64(){return M.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,M.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 M.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return M.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 it=U(()=>{"use strict"});var rt=U(()=>{"use strict"});var ot=U(()=>{"use strict"});var Ue=U(()=>{"use strict";nt();it();_e();rt();ot()});function sn(){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 dn(){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 an(){return{key:"",value:""}}function cn(){return{adUnitCode:"",outcome:0,bid:void 0,refreshIndex:0,floorCents:void 0,floorSource:0,floorTreatmentBp:void 0,slot:""}}function un(){return{bidder:"",cpm:0,currency:"",width:0,height:0,dealId:"",mediaType:"",latencyMs:0,advertiserDomain:"",creativeId:""}}var y,$,ue,te,ae,st,dt,ce,le=U(()=>{"use strict";Ue();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},$={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},ue={FLOOR_SOURCE_UNSPECIFIED:0,FLOOR_SOURCE_STATIC:1,FLOOR_SOURCE_POOL:2,FLOOR_SOURCE_NONE:3,UNRECOGNIZED:-1};te={encode(n,e=new N){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)ae.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 S?n:new S(n),i=e===void 0?t.len:t.pos+e,r=sn();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=ae.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}};ae={encode(n,e=new N){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&&ce.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])=>{st.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)dt.encode(t,e.uint32(98).fork()).join();return e},decode(n,e){let t=n instanceof S?n:new S(n),i=e===void 0?t.len:t.pos+e,r=dn();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=ce.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=st.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=dt.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}};st={encode(n,e=new N){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 S?n:new S(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.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}};dt={encode(n,e=new N){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&&ce.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 S?n:new S(n),i=e===void 0?t.len:t.pos+e,r=cn();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=ce.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}};ce={encode(n,e=new N){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 S?n:new S(n),i=e===void 0?t.len:t.pos+e,r=un();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 O(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(ln.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(at)return at.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 Z(n){return typeof n!="number"||!Number.isFinite(n)||n<=0||n>1?1:n}function Oe(n,e){let t=Z(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}var ln,at,wi,fe=U(()=>{"use strict";ln=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,at=typeof TextEncoder<"u"?new TextEncoder:null,wi=typeof TextDecoder<"u"?new TextDecoder:null});function fn(){return{unit:0,usageId:new Uint8Array(0),timestampMs:"0",slots:0}}function hn(){return{pageviewId:new Uint8Array(0),events:[]}}var ut,ct,lt,ft=U(()=>{"use strict";Ue();ut={USAGE_UNIT_UNSPECIFIED:0,AUCTION:1,SERVER_AUCTION:2,UNRECOGNIZED:-1};ct={encode(n,e=new N){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 S?n:new S(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!==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}};lt={encode(n,e=new N){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)ct.encode(t,e.uint32(18).fork()).join();return e},decode(n,e){let t=n instanceof S?n:new S(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.pageviewId=t.bytes();continue}case 2:{if(o!==18)break;let s=ct.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 ne(){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 Le,ht=U(()=>{"use strict";le();fe();Le="text/plain"});var gn,pt,he,gt=U(()=>{"use strict";ft();ht();fe();gn=1e4,pt=200,he=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||ne();let t=O(this.pageviewIdStr);this.pageviewIdBytes=t.length===16?t:O(ne()),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||ne(),this.pageviewIdBytes=O(this.pageviewIdStr)}getQueueLength(){return this.queue.length}record(e,t,i=ut.AUCTION){if(this.isDestroyed||!e)return;let r=O(e);if(r.length!==16&&(r=O(ne())),this.queue.push({unit:i,usageId:r,timestampMs:String(Date.now()),slots:typeof t=="number"&&t>0?t:0}),this.queue.length>=pt){this.flush();return}!this.flushTimer&&typeof setTimeout<"u"&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},gn))}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,pt),i={pageviewId:this.pageviewIdBytes,events:t},r=lt.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:Le});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":Le},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 X(){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 Mn(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 Nn(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 Pn(n){let e={},t=0;for(let i of Object.keys(n)){if(t>=vn)break;let r=n[i];if(r==null)continue;let o=String(r);e[i]=o.length>It?`${o.slice(0,It)}...[truncated]`:o,t++}return e}function Vn(n,e){if(!n||!e)return!1;try{return new URL(n).origin===new URL(e).origin}catch{return!1}}function Ct(n){try{typeof localStorage<"u"&&(localStorage.setItem(Pe,n.toString()),Y=n)}catch{}}function Rt(n=Date.now()){return W>0&&n-W<=St}function ge(){let n=Date.now(),e=!!L&&!Rt(n);if(W=n,e){L=null;for(let t of Wn)t();return}!K||!L||Y===0||n-Y<Fn||Ct(n)}function qn(){return!L||K&&Y===0}function jn(){if(Tt||typeof window>"u")return;Tt=!0;let n=()=>ge();for(let e of $n)window.addEventListener(e,n,{passive:!0,capture:!0});typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&ge()})}function ke(){let n=Date.now(),e=!!L&&Rt(n);try{if(K&&typeof localStorage<"u"){let t=localStorage.getItem(Me),i=localStorage.getItem(Pe),r=i&&parseInt(i,10)||0;if(t&&r&&n-r<=St)return L!==t&&(De=!1),(L!==t||W<r)&&(L=t,W=Math.max(W,r)),Y===0&&(Y=r),t;let o=e?L:X();return e||(De=!0,W=n),localStorage.setItem(Me,o),Ct(W),L=o,o}}catch{}return e||(De=!0,L=X(),W=n),L}function Gn(){Y=0;try{typeof localStorage<"u"&&(localStorage.removeItem(Me),localStorage.removeItem(Pe))}catch{}}function wt(){try{if(K&&typeof localStorage<"u"){let n=localStorage.getItem(re);if(n)return n;let e=X();return localStorage.setItem(re,e),e}}catch{}return""}function ye(n){return n.regime!=="tcf"||!!n.purposesConsented?.includes(1)}function _t(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 Kn(){if(typeof window>"u")return;let n=window;if(typeof n.__tcfapi!="function")return;let e;try{n.__tcfapi("getTCData",2,(t,i)=>{i&&t&&(e=ye(_t(t)))})}catch{}return e!==void 0?e:!1}function Hn(){if(At||typeof window>"u")return;let n=window;if(typeof n.__tcfapi=="function"){At=!0;try{n.__tcfapi("addEventListener",2,(e,t)=>{!t||!e||R.setStorageAllowed(ye(_t(e)))})}catch{}}}function Yn(n){if(typeof window>"u")return;let e=window,t=e[n]?.consent?.getRecord?.()||null;return t?ye(t):e[`__${n}_cmp`]?.gdpr?!1:void 0}function l(n){return String(n??"").replace(/%/g,"%25").replace(/:/g,"%3A")}function zn(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 G(n){if(Number.isFinite(n?.width)&&Number.isFinite(n?.height))return{width:n.width,height:n.height};if(typeof n?.size=="string"){let e=n.size.match(/^(\d+)x(\d+)$/);if(e)return{width:Number(e[1]),height:Number(e[2])}}return{width:Number.isFinite(n?.width)?n.width:0,height:Number.isFinite(n?.height)?n.height:0}}function pe(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 J(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?J(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 Xn(n){if(!n)return null;if(n._bidsparkAnalyticsConfig){let t=J(n._bidsparkAnalyticsConfig);if(t)return t}let e=n.bidsparkPrebidAnalytics;if(e){if(e.options){let t=J(e.options);if(t)return t}if(e.config){let t=J(e.config);if(t)return t}if(e.propertyId)return J(e)}return null}function Ve(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&&!Vn(c.endpoint||"",a)&&(Q.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(h){Q.warn("Failed to disable previous analytics instance:",h)}let m=new R(c);return m.enable(),t._bidsparkPrebidAnalytics=m,m},o=()=>{try{if(i.adapterManager&&typeof i.adapterManager.registerAnalyticsAdapter=="function"){let d={enableAnalytics:a=>{let u=J(a,!Array.isArray(a));u&&r(u)},disableAnalytics:()=>{t._bidsparkPrebidAnalytics&&t._bidsparkPrebidAnalytics.disable()}};i.adapterManager.registerAnalyticsAdapter({adapter:{...d},code:"bidspark"})}let s=Xn(t);s&&(s.propertyId||e?.propertyId)&&r(s)}catch(s){Q.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 yt,bt,yn,bn,ie,mn,In,mt,It,vn,vt,Et,En,Tn,wn,An,Sn,Cn,Rn,_n,H,Bn,Un,xn,On,Ln,Dn,Me,Pe,St,L,W,De,K,Fn,Y,$n,Tt,Wn,re,At,Ne,Q,R,Fe=U(()=>{"use strict";Ke();le();fe();gt();yt="ads",bt=1e4,yn=50,bn=20,ie=200,mn=300*1e3,In=10,mt=32*1024,It=1024,vn=16,vt="text/plain",Et="ads_pending_",En=20,Tn=7200*1e3,wn=1e4,An={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},Sn={WARN:y.WARN,ERROR:y.ERROR},Cn=new Set([y.ERROR,y.WARN]),Rn=3e3,_n=new Set([y.IMPRESSION,y.BID_WIN,y.CLICK]),H=1800*1e3,Bn=200,Un=1e3,xn=50,On=200,Ln={static:ue.FLOOR_SOURCE_STATIC,pool:ue.FLOOR_SOURCE_POOL,none:ue.FLOOR_SOURCE_NONE},Dn=1e3,Me="ads_session",Pe="ads_session_ts",St=1800*1e3,L=null,W=0,De=!1,K=!0;Fn=60*1e3,Y=0,$n=["pointerdown","pointermove","keydown","scroll","wheel","touchstart"],Tt=!1,Wn=new Set;re="ads_uid";At=!1;Ne=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=zn(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}};Q=ve({prefix:"[analytics]",logLevel:"INFO"}),R=class n{static activeInstances=new Set;static allInstances=new Set;static getActiveInstances(){return n.activeInstances}static setLogLevel(e){let t=F(e);Q.setLevel(t);for(let i of n.allInstances)i.setLogLevel(t)}static getLogLevel(){return Q.getLevel()}static setStorageAllowed(e){K=e,Y=0;for(let t of n.allInstances)t.config.storageAllowed=e,e?t.config.userId||(t.config.userId=wt(),t.config.visitorId=t.config.visitorId||t.config.userId||t.config.pageviewId):(t.config.userId="",t.config.visitorId=t.config.visitorId||t.config.pageviewId)}static isStorageAllowed(){return K}config;usageRecorder=null;queue=[];errorCount=0;flushTimer=null;boundFlushBeacon;boundVisibilityChange;isEnabled=!1;boundPbjsHandlers=[];pageUrl="";deduper=new Ne;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;constructor(e){let t=Kn();typeof window<"u"&&typeof window.__tcfapi=="function"&&Hn();let i=e.storageAllowed??t??Yn(e.alias||yt);i!==void 0&&n.setStorageAllowed(i);let r=i!==void 0?i:K,o=e.endpoint||"",s=!o||Nn(o)?o:"",d=e.pageviewId||X(),a="",u="";if(r){if(a=e.userId||wt(),e.userId)try{typeof localStorage<"u"&&localStorage.setItem(re,e.userId)}catch{}u=e.visitorId||a||d}else a="",u=e.visitorId||d;let c=e.usageEndpoint||"";this.config={endpoint:s,usageEndpoint:c,propertyId:e.propertyId||"",pageviewId:d,sessionId:e.sessionId||"",userId:a,visitorId:u,deviceType:e.deviceType||"desktop",country:e.country||"",region:e.region||"",auctionEnabled:e.auctionEnabled??!0,warningsEnabled:e.warningsEnabled??!0,sampleRate:Z(e.sampleRate),viewabilityEnabled:e.viewabilityEnabled??!0,storageAllowed:r,logLevel:e.logLevel?F(e.logLevel):Q.getLevel(),pbjsGlobalName:e.pbjsGlobalName||"pbjs",attachPbjsListeners:e.attachPbjsListeners??!0,revenueFlushDelayMs:Number.isFinite(e.revenueFlushDelayMs)&&e.revenueFlushDelayMs>=0?e.revenueFlushDelayMs:Rn,alias:e.alias||yt},n.allInstances.add(this),this.logger=ve({prefix:"[analytics]",logLevel:this.config.logLevel}),ge(),this.managesSessionId=!e.sessionId,this.managesSessionId&&(this.config.sessionId=ke()),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()}setLogLevel(e){let t=F(e);this.config.logLevel=t,this.logger.setLevel(t),Q.setLevel(t)}getLogLevel(){return this.logger.getLevel()}enable(){if(!this.isEnabled){if(this.isEnabled=!0,n.activeInstances.add(this),this.logger.setLevel(this.config.logLevel),this.config.attachPbjsListeners&&this.config.usageEndpoint&&!this.usageRecorder&&(this.usageRecorder=new he({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)}if(this.config.attachPbjsListeners&&this.attachPbjs(),this.cmpDetach=this.attachCmp(),typeof window<"u"){if(!this.pageUrl)try{let e=new URL(window.location.href);this.pageUrl=e.origin+e.pathname}catch{this.pageUrl=window.location.href}window.addEventListener("pagehide",this.boundFlushBeacon),typeof document<"u"&&document.addEventListener("visibilitychange",this.boundVisibilityChange),jn(),this.pageviewEmitted||(this.pageviewEmitted=!0,this.enqueue(y.PAGEVIEW,"pageview",{})),this.flushTimer=setInterval(()=>this.flush(),bt),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)<Dn)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:"")||X(),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>H){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>H&&this.cachedWinningBids.delete(t);for(;this.cachedWinningBids.size>Bn;){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>=Un;){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>xn;){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(o){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 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)}`):this.slotEmittedImpressionKeys.has(d)}markImpressionEmitted(e,t,i,r,o){let s=`${l(e)}:${t}`;!!(o||r)?(o&&(this.addImpressionKey(`${s}:ad:${l(o)}`),i&&this.addImpressionKey(`${s}:auc:${l(i)}:ad:${l(o)}`)),r&&r!==o&&(this.addImpressionKey(`${s}:${l(r)}`),i&&this.addImpressionKey(`${s}:auc:${l(i)}:${l(r)}`)),i&&this.addImpressionKey(`${s}:auc:${l(i)}`)):(this.addImpressionKey(s),i&&this.addImpressionKey(`${s}:auc:${l(i)}`))}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",h=i||r,f=(i?this.slotViewabilityRecords.get(i):void 0)||(r?this.slotViewabilityRecords.get(r):void 0),_=h?this.slotLastAuctionIds.get(h)||(f?f.auctionId:void 0):void 0,I=!!(h&&d&&_&&_!==d&&t?.refreshIndex===void 0),B={bidder:s.bidderCode||s.bidder||o?.bidTrace?.bidder||"",...pe(s,o?.bidTrace),...G(s).width?G(s):o?.bidTrace?{width:o.bidTrace.width,height:o.bidTrace.height}:G(s),dealId:s.dealId||o?.bidTrace?.dealId||"",mediaType:m,latencyMs:Number.isFinite(s.timeToRespond)?s.timeToRespond:o?.bidTrace?.latencyMs??0,advertiserDomain:s.meta?.advertiserDomains?.[0]||o?.bidTrace?.advertiserDomain||"",creativeId:s.creativeId||o?.bidTrace?.creativeId||""};if(I&&h){this.flushSlotTimeInView(h);let v=(this.slotRefreshIndices.get(h)??(f?f.refreshIndex:0))+1;this.slotRefreshIndices.set(h,v),this.slotLastAuctionIds.set(h,d),f&&(f.refreshIndex=v,f.auctionId=d,f.transactionId=a,f.bidPayload=B,f.viewableFired=!1,f.accumulatedTimeInViewMs=0)}else h&&(d&&this.slotLastAuctionIds.set(h,d),this.slotRefreshIndices.has(h)||this.slotRefreshIndices.set(h,0));let x=t?.refreshIndex??(i?this.slotRefreshIndices.get(i)??(r?this.slotRefreshIndices.get(r):void 0)??(f?f.refreshIndex:0):0);return i&&this.hasImpressionEmitted(i,x,d,u,c)||r&&r!==i&&this.hasImpressionEmitted(r,x,d,u,c)?(this.log("DEBUG",`Impression already emitted for slot ${i||r} in cycle ${x}`),!1):(i&&this.markImpressionEmitted(i,x,d,u,c),r&&r!==i&&this.markImpressionEmitted(r,x,d,u,c),this.enqueue(y.IMPRESSION,"impression",{auctionId:d,transactionId:a,adUnitCode:r,bid:B,metadata:{...t?.metadata,refresh_index:String(x)}}),f&&(!f.bidPayload&&B&&(f.bidPayload=B),!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=Sn[e]??An[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>On;){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.recordConsent(s),this.followConsent(s))};document.addEventListener("ads:consent",e);let i=(typeof window<"u"?window:{})[this.config.alias]?.consent?.getRecord?.()||null;i&&(this.recordConsent(i),this.followConsent(i));let r=!1;return()=>{r||(r=!0,document.removeEventListener("ads:consent",e))}}followConsent(e){let t=ye(e);t||Gn(),n.setStorageAllowed(t)}setUserId(e){if(this.config.userId=e,e&&(this.config.visitorId=e),this.config.storageAllowed&&typeof localStorage<"u")try{e?localStorage.setItem(re,e):localStorage.removeItem(re)}catch{}}setVisitorId(e){this.config.visitorId=e}setSampleRate(e){this.config.sampleRate=Z(e)}setSessionId(e){this.config.sessionId=e,this.managesSessionId=!e,this.managesSessionId&&(this.config.sessionId=ke())}navigate(e,t){if(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||X(),this.config.visitorId=this.config.userId||this.config.pageviewId,t)try{let i=new URL(t);this.pageUrl=i.origin+i.pathname}catch{this.pageUrl=t}else this.pageUrl="";this.logger.resetTiming(),ge(),this.enable()}recordAuctionStart(e,t="",i){!this.isEnabled||!this.config.auctionEnabled||this.enqueue(y.AUCTION_START,"auctionStart",{auctionId:e,adUnitCode:t,...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=d.length>0?d[0]:o.mediaType||"banner",u=`${i}:${s}`;r.has(u)||r.set(u,{adUnitCode:s,outcome:$.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=pe(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,...G(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?$.BIDDER_OUTCOME_BID:$.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=$.BIDDER_OUTCOME_TIMEOUT,d>0&&c.bid&&(c.bid.latencyMs=d)):a.set(u,{adUnitCode:s,outcome:$.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||"",...pe(e),...G(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===$.BIDDER_OUTCOME_NO_RESPONSE&&(d.outcome=$.BIDDER_OUTCOME_NO_BID):o.set(s,{adUnitCode:r,outcome:$.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),c=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",m=c?"video":s||u?.bidTrace?.mediaType||"banner",h={bidder:t.bidderCode||t.bidder||u?.bidTrace?.bidder||"",...pe(t,u?.bidTrace),...G(t).width?G(t):u?.bidTrace?{width:u.bidTrace.width,height:u.bidTrace.height}:G(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||"",_=o||u?.transactionId||"",I=i?this.slotViewabilityRecords.get(i):void 0,B=I&&f&&I.auctionId&&I.auctionId!==f,x=!!(i&&I&&B);if(x){this.flushSlotTimeInView(i);let v=(this.slotRefreshIndices.get(i)??(I?I.refreshIndex:0))+1;this.slotRefreshIndices.set(i,v),this.slotLastAuctionIds.set(i,f),I&&(I.auctionId=f,I.transactionId=_,I.bidPayload=h)}else i&&(f&&this.slotLastAuctionIds.set(i,f),this.slotRefreshIndices.has(i)||this.slotRefreshIndices.set(i,0));let D=i?this.slotRefreshIndices.get(i)??(I?I.refreshIndex:0):0;if(c?this.log("DEBUG",`adRenderSucceeded received for video ad unit ${i||"unknown"}: suppressing IMPRESSION until verified video lifecycle event`):i&&this.hasImpressionEmitted(i,D,f,h.creativeId)||(i&&this.markImpressionEmitted(i,D,f,h.creativeId),this.enqueue(y.IMPRESSION,"impression",{auctionId:f,transactionId:_,adUnitCode:i,bid:h,metadata:{refresh_index:String(D)}})),this.config.viewabilityEnabled&&typeof document<"u"){let v=i&&this.slotElements.get(i)||null,T=i||e.adId||t.adId;if(!v&&T&&(v=document.getElementById(T)),!v&&typeof window<"u"&&window.googletag?.pubads)try{let P=window.googletag.pubads().getSlots();for(let b of P)if((b.getAdUnitPath?.()===i||b.getSlotElementId?.()===i)&&(v=document.getElementById(b.getSlotElementId()),v))break}catch{}if(!v&&T)try{for(let P of Array.from(document.querySelectorAll("[data-ad-slot]")))if(P.getAttribute("data-ad-slot")===T){v=P;break}}catch{}v?this.observeSlot(v,i||T,{adUnitCode:i,auctionId:f,transactionId:_,mediaType:m,bid:h,refreshIndex:D,isRefresh:x}):I&&x&&(I.refreshIndex=D,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.managesSessionId&&qn()&&(this.config.sessionId=ke());let r={eventId:O(X()),timestampMs:Date.now(),type:e,eventName:Cn.has(e)?t:"",auctionId:O(String(i.auctionId||"")),transactionId:O(String(i.transactionId||"")),adUnitCode:i.adUnitCode||i.elementId||"",namespace:i.ns||i.namespace||""};i.bid&&(r.bid={bidder:i.bid.bidder||"",cpm:Number.isFinite(i.bid.cpm)?i.bid.cpm:0,currency:i.bid.currency||"",width:Number.isFinite(i.bid.width)?i.bid.width:0,height:Number.isFinite(i.bid.height)?i.bid.height:0,dealId:i.bid.dealId||"",mediaType:i.bid.mediaType||"",latencyMs:Number.isFinite(i.bid.latencyMs)?i.bid.latencyMs:0,advertiserDomain:i.bid.advertiserDomain||"",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:Ln[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=Pn(o);Object.keys(d).length>0&&(r.metadata=d),this.queue.push(r),this.queue.length>=ie?(this.flush(),this.queue.length>ie&&this.queue.splice(0,this.queue.length-ie)):_n.has(e)&&this.revenueFlushTimer===null&&(this.revenueFlushTimer=setTimeout(()=>{this.revenueFlushTimer=null,this.flush()},this.config.revenueFlushDelayMs))}isSampledVisitor(){let e=this.config.visitorId||this.config.userId||this.config.pageviewId;return Oe(e,this.config.sampleRate)}shouldSample(e){return this.isSampledVisitor()?e===y.ERROR?(this.errorCount++,this.errorCount<=yn):e===y.CONSENT?(this.consentCount++,this.consentCount<=bn):e===y.WARN?this.config.warningsEnabled:this.config.auctionEnabled:!1}requeue(e){e.length&&(this.queue=e.concat(this.queue),this.queue.length>ie&&this.queue.splice(0,this.queue.length-ie))}drainBatch(){if(this.queue.length===0||!this.config.endpoint)return null;let e=typeof window<"u"?window.location.hostname:"",t=Z(this.config.sampleRate),i=typeof navigator<"u"&&navigator.webdriver===!0,r=s=>({propertyId:O(this.config.propertyId),pageviewId:O(this.config.pageviewId),sessionId:O(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=te.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=ae.encode(m).finish().byteLength+6;if(d+f>mt){if(s===0){let[_]=this.queue.splice(0,1),I=te.encode(r([_])).finish().byteLength;this.log("WARN",`Dropping oversized event (type ${_?.type}, ${I} bytes exceeds the ${mt}-byte cap on its own)`);break}break}d+=f,s++}if(s===0)continue;let a=this.queue.slice(0,s),u=te.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":vt},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(bt*2**(this.consecutiveSendFailures-1),mn);this.nextSendAllowedAt=Date.now()+t,this.consecutiveSendFailures<=In?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:vt});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`${Et}${encodeURIComponent(this.config.propertyId)}_`}persistBatch(e){if(!K)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(Et)&&t++}if(t>=En)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)},wn))}resendPersistedBatches(){try{if(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>Tn)continue;let s;try{s=Mn(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 Qn(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 Lt(n,e,t){let i=be(n),{err:r,message:o,metadata:s}=Qn(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 Zn(n,e){if(!n||typeof n!="object"||Bt.has(n))return;Bt.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 R.getActiveInstances())try{let o=kt(r,{mediaType:"video"});Lt(r,i,{adStarted:!1,adUnitCode:o?.adUnitCode||"video",auctionId:o?.auctionId,transactionId:o?.transactionId,bid:o?.bidTrace})}catch{}})}catch{}}function Ut(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 R.getActiveInstances())try{s.attachImaAdsManager(o)}catch{}return o};i.__bidsparkHooked=!0,e.getAdsManager=i}}catch{}}function xt(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 R.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 R.getActiveInstances())try{o.attachImaAdsManager(this)}catch{}return t.apply(this,r)};i.__bidsparkHooked=!0,e.start=i}}catch{}}function Ot(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(Zn(this,t),(r==="adsManagerLoaded"||r===(this?.AdsManagerLoadedEvent?.Type?.ADS_MANAGER_LOADED||"adsManagerLoaded"))&&typeof o=="function"){let d=$e.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 h of R.getActiveInstances())try{h.attachImaAdsManager(m)}catch{}return m},a.getAdsManager.__bidsparkHooked=!0}return o.apply(this,arguments)},$e.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"?$e.get(o):void 0;return t.call(this,r,d||o,...s)};i.__bidsparkHooked=!0,e.removeEventListener=i}}catch{}}function oe(n){if(!(!n||typeof n!="object"))try{n.AdsManagerLoadedEvent&&Ut(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,Ut(o)}})}catch{}}n.AdsLoader&&Ot(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,Ot(o)}})}catch{}}n.AdsManager&&xt(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,xt(o)}})}catch{}}}catch{}}function Dt(){if(typeof window>"u")return;let n=window;if(n.google?.ima&&oe(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,oe(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&&oe(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,oe(s)}})}catch{}}}}})}catch{}}}function kt(n,e){let t=be(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>H)&&(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>H)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>H)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>H||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>H||(!s||d.timestamp>s.timestamp)&&(s=d);return s}function Mt(n,e,t){let i=be(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||"",u=t?.transactionId||"",c=g=>{let p=(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 p||(p=kt(n,{creativeId:g?.creativeId,adId:g?.adId,mediaType:"video"})),p},m=!1,h=null,f=g=>{let p=typeof i.nextSlotAdSession=="function"?i.nextSlotAdSession(s):`ad-session-${(i.slotAdSessionCounters?.get(s)??0)+1}`;if(i.slotAdSessionCounters&&typeof i.nextSlotAdSession!="function"){let V=(i.slotAdSessionCounters.get(s)??0)+1;i.slotAdSessionCounters.set(s,V)}let E=(typeof g?.getAdId=="function"?g.getAdId():g?.adId??g?.id)||"",z=(typeof g?.getCreativeId=="function"?g.getCreativeId():g?.creativeId)||"";return h={sessionId:p,adId:E||void 0,creativeId:z||void 0},h},_=g=>{let p=typeof g?.getAd=="function"?g.getAd():g?.ad;f(p),i.log("DEBUG","IMA AdEvent.LOADED received",{slotId:s,activeAdSession:h})},I=g=>{m=!0;let p=typeof g?.getAd=="function"?g.getAd():g?.ad,E={};p&&(E.creativeId=(typeof p.getCreativeId=="function"?p.getCreativeId():p.creativeId)||"",E.adId=(typeof p.getAdId=="function"?p.getAdId():p.id)||"",E.title=(typeof p.getTitle=="function"?p.getTitle():p.title)||"",E.duration=typeof p.getDuration=="function"?p.getDuration():p.duration,E.advertiserName=typeof p.getAdvertiserName=="function"?p.getAdvertiserName():""),!h||E.adId&&h.adId&&h.adId!==E.adId?f(p):(!h.adId&&E.adId&&(h.adId=E.adId),!h.creativeId&&E.creativeId&&(h.creativeId=E.creativeId));let z=h||f(p),V=c(E),me=t?.slotId&&t.slotId!=="video"?t.slotId:t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:V?.adUnitCode||t?.slotId||t?.adUnitCode||"video",Ft=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:V?.adUnitCode||me,$t=a||V?.auctionId||"",Wt=u||V?.transactionId||"",We=z.creativeId||E.creativeId||V?.bidTrace?.creativeId||t?.bid?.creativeId||"",qt=z.adId||E.adId||We||z.sessionId,qe={...V?.rawBid||t?.bid,mediaType:"video",creativeId:We},je=i.recordImpression(me,{adUnitCode:Ft,auctionId:$t,transactionId:Wt,mediaType:"video",bid:qe,adId:qt,metadata:{...t?.metadata,media_type:"video",...E.title?{ad_title:E.title}:{},...Number.isFinite(E.duration)?{ad_duration_s:String(E.duration)}:{}}}),ee=typeof g?.type=="string"?g.type:typeof g?.getType=="function"?g.getType():typeof g=="string"?g:"";ee.toLowerCase().startsWith("adevent.")&&(ee=ee.slice(8));let jt=ee?ee.toUpperCase():"STARTED/IMPRESSION";if(i.log("DEBUG",`IMA AdEvent.${jt} received${je?"":" (second event for this ad, already counted)"}`,g),je&&t?.onImpression)try{t.onImpression(me,{ad:p,bid:qe})}catch(Gt){i.log("ERROR","Error in onImpression callback",Gt)}},B=g=>{if(i.log("DEBUG",`IMA AdEvent milestone: ${g}`),t?.onMilestone)try{t.onMilestone(g,s)}catch(p){i.log("ERROR","Error in onMilestone callback",p)}},x=g=>{i.log("DEBUG","IMA AdEvent.CLICK received",g);let p=c(),E=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:p?.adUnitCode||s;i.enqueue(y.CLICK,"click",{auctionId:a||p?.auctionId,transactionId:u||p?.transactionId,adUnitCode:E,bid:p?.bidTrace||t?.bid,metadata:{...t?.metadata,media_type:"video"}})},D=g=>{h=null;let p=c(),E=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:p?.adUnitCode||s,z=Lt(n,g,{adStarted:m,adUnitCode:E,auctionId:a||p?.auctionId,transactionId:u||p?.transactionId,bid:p?.bidTrace||t?.bid,metadata:t?.metadata});if(t?.onError)try{t.onError(z)}catch(V){i.log("ERROR","Error in onError callback",V)}},v=typeof window<"u"?window.google?.ima:void 0,T=v?.AdEvent?.Type||{},P=v?.AdErrorEvent?.Type||{},b=[{type:T.LOADED||"loaded",handler:_},{type:T.STARTED||"started",handler:I},{type:T.IMPRESSION||"impression",handler:I},{type:T.FIRST_QUARTILE||"firstQuartile",handler:()=>B("firstQuartile")},{type:T.MIDPOINT||"midpoint",handler:()=>B("midpoint")},{type:T.THIRD_QUARTILE||"thirdQuartile",handler:()=>B("thirdQuartile")},{type:T.COMPLETE||"complete",handler:()=>{h=null,B("complete")}},{type:T.ALL_ADS_COMPLETED||"allAdsCompleted",handler:()=>{h=null}},{type:T.CLICK||"click",handler:x},{type:P.AD_ERROR||"adError",handler:D}],A=new Set,w=[];for(let g of b)A.has(g.type)||(A.add(g.type),w.push(g));for(let{type:g,handler:p}of w)try{e.addEventListener(g,p)}catch{}let k=()=>{h=null,r.delete(n);for(let{type:g,handler:p}of w)try{e.removeEventListener(g,p)}catch{}i.videoDetachCleanups.delete(k)};return r.set(n,k),i.videoDetachCleanups.add(k),k}function Jn(n,e,t){let i=be(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 Mt(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},h=b=>{let A=b||c||(r?.querySelector?r.querySelector("video"):null),w=u(),k={...w?.rawBid||t?.bid,mediaType:"video"};if(i.recordImpression(o,{adUnitCode:s,auctionId:d||w?.auctionId,transactionId:a||w?.transactionId,mediaType:"video",bid:k,metadata:{...t?.metadata,media_type:"video",...A&&Number.isFinite(A.duration)?{video_duration_s:String(Math.round(A.duration))}:{}}})&&t?.onImpression)try{t.onImpression(o,{element:A||r,bid:k})}catch(p){i.log("ERROR","Error in onImpression callback",p)}},f=b=>{i.log("DEBUG","HTML5 video playing event received");let A=b?.target instanceof HTMLVideoElement?b.target:c;h(A)},_=b=>{let A=b?.target instanceof HTMLVideoElement?b.target:c;if(A&&A.currentTime>0&&(h(A),Number.isFinite(A.duration)&&A.duration>0)){let w=A.currentTime/A.duration;w>=.25&&!m.q1&&(m.q1=!0,t?.onMilestone?.("firstQuartile",o)),w>=.5&&!m.q2&&(m.q2=!0,t?.onMilestone?.("midpoint",o)),w>=.75&&!m.q3&&(m.q3=!0,t?.onMilestone?.("thirdQuartile",o))}},I=()=>{m.q4||(m.q4=!0,t?.onMilestone?.("complete",o))},B=b=>{let w=(b?.target instanceof HTMLVideoElement?b.target:c)?.error||c?.error,k=u(),g=w?`HTML5 video error code ${w.code}: ${w.message}`:"Video playback error";if(i.log("WARN",g),i.enqueue(y.AD_RENDER_FAILED,"adRenderFailed",{auctionId:d||k?.auctionId,transactionId:a||k?.transactionId,adUnitCode:s,bid:k?.bidTrace||t?.bid,metadata:{...t?.metadata,reason:"html5_video_error",message:g,...w?.code?{error_code:String(w.code)}:{}},error:w?new Error(g):void 0}),t?.onError)try{t.onError(w)}catch(p){i.log("ERROR","Error in onError callback",p)}},x=b=>{b.addEventListener("playing",f),b.addEventListener("play",f),b.addEventListener("timeupdate",_),b.addEventListener("ended",I),b.addEventListener("error",B)},D=b=>{b.removeEventListener("playing",f),b.removeEventListener("play",f),b.removeEventListener("timeupdate",_),b.removeEventListener("ended",I),b.removeEventListener("error",B)},v=null;r&&r!==c&&(r.addEventListener("playing",f,!0),r.addEventListener("play",f,!0),r.addEventListener("timeupdate",_,!0),r.addEventListener("ended",I,!0),r.addEventListener("error",B,!0)),c&&x(c),r&&r.tagName?.toLowerCase()!=="video"&&typeof MutationObserver<"u"&&(v=new MutationObserver(()=>{let b=r.querySelector("video");b&&b!==c&&(c&&D(c),c=b,c&&x(c))}),v.observe(r,{childList:!0,subtree:!0}));let T=u();t?.trackViewability!==!1&&r&&i.observeSlot(r,o,{adUnitCode:s,auctionId:d||T?.auctionId,transactionId:a||T?.transactionId,mediaType:"video",bid:T?.bidTrace||t?.bid,metadata:t?.metadata});let P=()=>{v&&(v.disconnect(),v=null),r&&r!==c&&(r.removeEventListener("playing",f,!0),r.removeEventListener("play",f,!0),r.removeEventListener("timeupdate",_,!0),r.removeEventListener("ended",I,!0),r.removeEventListener("error",B,!0)),c&&D(c),i.videoDetachCleanups.delete(P)};return i.videoDetachCleanups.add(P),P}var be,$e,Bt,ei,Nt=U(()=>{"use strict";Fe();le();be=n=>n,$e=new WeakMap,Bt=new WeakSet;typeof window<"u"&&Dt();R.prototype.attachImaAdsManager=function(n,e){return Mt(this,n,e)};R.prototype.attachVideoPlayer=function(n,e){return Jn(this,n,e)};ei=R.prototype.enable;R.prototype.enable=function(){ei.call(this),typeof window<"u"&&(Dt(),window.google?.ima&&oe(window.google.ima))}});var ni=Kt(()=>{Fe();Nt();var Pt="https://by.bidspark.io/t",Vt="https://by.bidspark.io/u",ti=window._bidsparkPbjsGlobal||"pbjs";Ve(ti,{endpoint:Pt,usageEndpoint:Vt});window.bidsparkPrebidAnalytics={...window.bidsparkPrebidAnalytics,register:(n,e)=>Ve(n,{endpoint:Pt,usageEndpoint:Vt,...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},setLogLevel:n=>{R.setLogLevel(n)},getLogLevel:()=>R.getLogLevel()}});return ni();})();
package/dist/index.d.mts CHANGED
@@ -44,6 +44,8 @@ declare const TraceEventType: {
44
44
  * signals (bitmask), sdk_loaded, device (mobile|desktop), browser, forced ("1" on forced show).
45
45
  */
46
46
  readonly RECOVERY: 20;
47
+ /** PAGEVIEW - Pageview start (once per initial load or SPA navigate()). */
48
+ readonly PAGEVIEW: 21;
47
49
  readonly UNRECOGNIZED: -1;
48
50
  };
49
51
  type TraceEventType = typeof TraceEventType[keyof typeof TraceEventType];
@@ -63,14 +65,15 @@ declare namespace TraceEventType {
63
65
  type WARN = typeof TraceEventType.WARN;
64
66
  type CONSENT = typeof TraceEventType.CONSENT;
65
67
  type RECOVERY = typeof TraceEventType.RECOVERY;
68
+ type PAGEVIEW = typeof TraceEventType.PAGEVIEW;
66
69
  type UNRECOGNIZED = typeof TraceEventType.UNRECOGNIZED;
67
70
  }
68
71
  /** Per-bid metrics for reporting warehouse. CPM is gross value reported by bidder. */
69
72
  interface BidTrace {
70
73
  bidder?: string | undefined;
71
- /** Raw CPM; falls back to converted CPM if absent */
74
+ /** Prebid-converted CPM; falls back to originalCpm if absent */
72
75
  cpm?: number | undefined;
73
- /** Raw currency; falls back to converted currency (default "USD") */
76
+ /** Prebid-converted currency; falls back to originalCurrency (default "USD") */
74
77
  currency?: string | undefined;
75
78
  width?: number | undefined;
76
79
  height?: number | undefined;
@@ -231,9 +234,7 @@ declare function getOrCreateUserId(): string;
231
234
  declare function clearStoredUserId(): void;
232
235
  declare function resetTcfListener(): void;
233
236
  /**
234
- * Canonical duplicate-detection key for a Prebid event. Shared by the adapter
235
- * and the diagnostic extension so the two can never drift apart. Covers the
236
- * events the adapter forwards plus display-only events the extension shows.
237
+ * Canonical duplicate-detection key for a Prebid event.
237
238
  */
238
239
  declare function getPrebidEventKey(eventName: string, data: any): string;
239
240
  /**
@@ -290,6 +291,7 @@ declare class BidsparkPrebidAnalytics {
290
291
  private recordedConsentKeys;
291
292
  private consentCount;
292
293
  private cmpDetach;
294
+ private pageviewEmitted;
293
295
  private logger;
294
296
  private managesSessionId;
295
297
  constructor(config: AnalyticsConfig);
package/dist/index.d.ts CHANGED
@@ -44,6 +44,8 @@ declare const TraceEventType: {
44
44
  * signals (bitmask), sdk_loaded, device (mobile|desktop), browser, forced ("1" on forced show).
45
45
  */
46
46
  readonly RECOVERY: 20;
47
+ /** PAGEVIEW - Pageview start (once per initial load or SPA navigate()). */
48
+ readonly PAGEVIEW: 21;
47
49
  readonly UNRECOGNIZED: -1;
48
50
  };
49
51
  type TraceEventType = typeof TraceEventType[keyof typeof TraceEventType];
@@ -63,14 +65,15 @@ declare namespace TraceEventType {
63
65
  type WARN = typeof TraceEventType.WARN;
64
66
  type CONSENT = typeof TraceEventType.CONSENT;
65
67
  type RECOVERY = typeof TraceEventType.RECOVERY;
68
+ type PAGEVIEW = typeof TraceEventType.PAGEVIEW;
66
69
  type UNRECOGNIZED = typeof TraceEventType.UNRECOGNIZED;
67
70
  }
68
71
  /** Per-bid metrics for reporting warehouse. CPM is gross value reported by bidder. */
69
72
  interface BidTrace {
70
73
  bidder?: string | undefined;
71
- /** Raw CPM; falls back to converted CPM if absent */
74
+ /** Prebid-converted CPM; falls back to originalCpm if absent */
72
75
  cpm?: number | undefined;
73
- /** Raw currency; falls back to converted currency (default "USD") */
76
+ /** Prebid-converted currency; falls back to originalCurrency (default "USD") */
74
77
  currency?: string | undefined;
75
78
  width?: number | undefined;
76
79
  height?: number | undefined;
@@ -231,9 +234,7 @@ declare function getOrCreateUserId(): string;
231
234
  declare function clearStoredUserId(): void;
232
235
  declare function resetTcfListener(): void;
233
236
  /**
234
- * Canonical duplicate-detection key for a Prebid event. Shared by the adapter
235
- * and the diagnostic extension so the two can never drift apart. Covers the
236
- * events the adapter forwards plus display-only events the extension shows.
237
+ * Canonical duplicate-detection key for a Prebid event.
237
238
  */
238
239
  declare function getPrebidEventKey(eventName: string, data: any): string;
239
240
  /**
@@ -290,6 +291,7 @@ declare class BidsparkPrebidAnalytics {
290
291
  private recordedConsentKeys;
291
292
  private consentCount;
292
293
  private cmpDetach;
294
+ private pageviewEmitted;
293
295
  private logger;
294
296
  private managesSessionId;
295
297
  constructor(config: AnalyticsConfig);
package/dist/index.js CHANGED
@@ -336,6 +336,8 @@ var TraceEventType = {
336
336
  * signals (bitmask), sdk_loaded, device (mobile|desktop), browser, forced ("1" on forced show).
337
337
  */
338
338
  RECOVERY: 20,
339
+ /** PAGEVIEW - Pageview start (once per initial load or SPA navigate()). */
340
+ PAGEVIEW: 21,
339
341
  UNRECOGNIZED: -1
340
342
  };
341
343
  var BidderOutcome = {
@@ -377,7 +379,8 @@ function createBaseTraceEventBatch() {
377
379
  deviceModel: "",
378
380
  city: "",
379
381
  postalCode: "",
380
- sampleRate: void 0
382
+ sampleRate: void 0,
383
+ automated: false
381
384
  };
382
385
  }
383
386
  var TraceEventBatch = {
@@ -432,6 +435,9 @@ var TraceEventBatch = {
432
435
  if (message.sampleRate !== void 0) {
433
436
  writer.uint32(129).double(message.sampleRate);
434
437
  }
438
+ if (message.automated !== void 0 && message.automated !== false) {
439
+ writer.uint32(136).bool(message.automated);
440
+ }
435
441
  return writer;
436
442
  },
437
443
  decode(input, length) {
@@ -556,6 +562,13 @@ var TraceEventBatch = {
556
562
  message.sampleRate = reader.double();
557
563
  continue;
558
564
  }
565
+ case 17: {
566
+ if (tag !== 136) {
567
+ break;
568
+ }
569
+ message.automated = reader.bool();
570
+ continue;
571
+ }
559
572
  }
560
573
  if ((tag & 7) === 4 || tag === 0) {
561
574
  break;
@@ -1238,6 +1251,8 @@ function sendEvents(opts) {
1238
1251
  viewableDurationMs: void 0,
1239
1252
  bidderOutcomes: []
1240
1253
  }));
1254
+ const nav = g && "navigator" in g ? g.navigator : void 0;
1255
+ const automated = Boolean(nav && nav.webdriver === true);
1241
1256
  const batch = {
1242
1257
  propertyId: idToBytes(opts.propertyId),
1243
1258
  pageviewId: idToBytes(pageviewId),
@@ -1249,10 +1264,10 @@ function sendEvents(opts) {
1249
1264
  deviceType: void 0,
1250
1265
  domain,
1251
1266
  events: traceEvents,
1252
- ...sampleRate < 1 ? { sampleRate } : {}
1267
+ ...sampleRate < 1 ? { sampleRate } : {},
1268
+ ...automated ? { automated: true } : {}
1253
1269
  };
1254
1270
  const encoded = TraceEventBatch.encode(batch).finish();
1255
- const nav = g && "navigator" in g ? g.navigator : void 0;
1256
1271
  if (nav && typeof nav.sendBeacon === "function") {
1257
1272
  try {
1258
1273
  const blob = new Blob([encoded], { type: SAFE_CONTENT_TYPE });
@@ -1816,6 +1831,24 @@ function parseBidDimensions(bid) {
1816
1831
  height: Number.isFinite(bid?.height) ? bid.height : 0
1817
1832
  };
1818
1833
  }
1834
+ function resolveBidPricing(bid, fallback) {
1835
+ if (Number.isFinite(bid?.cpm)) {
1836
+ return {
1837
+ cpm: bid.cpm,
1838
+ currency: bid?.currency || bid?.originalCurrency || fallback?.currency || "USD"
1839
+ };
1840
+ }
1841
+ if (Number.isFinite(bid?.originalCpm)) {
1842
+ return {
1843
+ cpm: bid.originalCpm,
1844
+ currency: bid?.originalCurrency || bid?.currency || fallback?.currency || "USD"
1845
+ };
1846
+ }
1847
+ return {
1848
+ cpm: fallback?.cpm ?? 0,
1849
+ currency: fallback?.currency || bid?.currency || bid?.originalCurrency || "USD"
1850
+ };
1851
+ }
1819
1852
  var defaultLogger = createLogger({
1820
1853
  prefix: "[analytics]",
1821
1854
  logLevel: "INFO"
@@ -1847,7 +1880,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1847
1880
  inst.config.visitorId = inst.config.visitorId || inst.config.pageviewId;
1848
1881
  } else if (!inst.config.userId) {
1849
1882
  inst.config.userId = getOrCreateUserId();
1850
- inst.config.visitorId = inst.config.userId || inst.config.pageviewId;
1883
+ inst.config.visitorId = inst.config.visitorId || inst.config.userId || inst.config.pageviewId;
1851
1884
  }
1852
1885
  }
1853
1886
  }
@@ -1895,6 +1928,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1895
1928
  recordedConsentKeys = /* @__PURE__ */ new Set();
1896
1929
  consentCount = 0;
1897
1930
  cmpDetach = null;
1931
+ pageviewEmitted = false;
1898
1932
  logger;
1899
1933
  // True when managing session lifecycle internally; false if caller supplied fixed sessionId.
1900
1934
  managesSessionId;
@@ -2025,6 +2059,10 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2025
2059
  document.addEventListener("visibilitychange", this.boundVisibilityChange);
2026
2060
  }
2027
2061
  bindActivityListeners();
2062
+ if (!this.pageviewEmitted) {
2063
+ this.pageviewEmitted = true;
2064
+ this.enqueue(TraceEventType.PAGEVIEW, "pageview", {});
2065
+ }
2028
2066
  this.flushTimer = setInterval(() => this.flush(), FLUSH_INTERVAL_MS);
2029
2067
  this.resendPersistedBatches();
2030
2068
  }
@@ -2194,6 +2232,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2194
2232
  }
2195
2233
  });
2196
2234
  }
2235
+ record.accumulatedTimeInViewMs = 0;
2197
2236
  }
2198
2237
  this.flushBeacon();
2199
2238
  } else if (document.visibilityState === "visible") {
@@ -2716,8 +2755,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2716
2755
  );
2717
2756
  const bidTrace = {
2718
2757
  bidder: rawBid.bidderCode || rawBid.bidder || cached?.bidTrace?.bidder || "",
2719
- cpm: Number.isFinite(rawBid.originalCpm) ? rawBid.originalCpm : Number.isFinite(rawBid.cpm) ? rawBid.cpm : cached?.bidTrace?.cpm ?? 0,
2720
- currency: rawBid.originalCurrency ?? rawBid.currency ?? cached?.bidTrace?.currency ?? "USD",
2758
+ ...resolveBidPricing(rawBid, cached?.bidTrace),
2721
2759
  ...parseBidDimensions(rawBid).width ? parseBidDimensions(rawBid) : cached?.bidTrace ? { width: cached.bidTrace.width, height: cached.bidTrace.height } : parseBidDimensions(rawBid),
2722
2760
  dealId: rawBid.dealId || cached?.bidTrace?.dealId || "",
2723
2761
  mediaType,
@@ -2950,7 +2988,9 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2950
2988
  this.floorDecisions.clear();
2951
2989
  this.recordedConsentKeys.clear();
2952
2990
  this.consentCount = 0;
2991
+ this.pageviewEmitted = false;
2953
2992
  this.config.pageviewId = pageviewId || generateUUID2();
2993
+ this.config.visitorId = this.config.userId || this.config.pageviewId;
2954
2994
  if (pageUrl) {
2955
2995
  try {
2956
2996
  const u = new URL(pageUrl);
@@ -3047,15 +3087,15 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3047
3087
  const auctionId = data.auctionId || "";
3048
3088
  const bidder = data.bidderCode || data.bidder || "";
3049
3089
  const adUnitCode = data.adUnitCode || "";
3050
- const cpm = Number.isFinite(data.originalCpm) ? data.originalCpm : Number.isFinite(data.cpm) ? data.cpm : 0;
3090
+ const pricing = resolveBidPricing(data);
3091
+ const cpm = pricing.cpm;
3051
3092
  const latencyMs = Number.isFinite(data.timeToRespond) ? data.timeToRespond : 0;
3052
3093
  const resMediaTypes = Object.keys(data.mediaTypes || {});
3053
3094
  const mediaType = data.mediaType || (data.mediaTypes?.video ? "video" : resMediaTypes.length > 0 ? resMediaTypes[0] : "banner");
3054
3095
  if (!auctionId || !bidder) return;
3055
3096
  const bid = cpm > 0 ? {
3056
3097
  bidder,
3057
- cpm,
3058
- currency: data.originalCurrency ?? data.currency ?? "USD",
3098
+ ...pricing,
3059
3099
  ...parseBidDimensions(data),
3060
3100
  dealId: data.dealId || "",
3061
3101
  mediaType,
@@ -3105,8 +3145,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3105
3145
  const resolvedMediaType = data.mediaType || (data.mediaTypes?.video ? "video" : wonMediaTypes.length > 0 ? wonMediaTypes[0] : "banner");
3106
3146
  const bidTrace = {
3107
3147
  bidder: data.bidderCode || data.bidder || "",
3108
- cpm: Number.isFinite(data.originalCpm) ? data.originalCpm : Number.isFinite(data.cpm) ? data.cpm : 0,
3109
- currency: data.originalCurrency ?? data.currency ?? "USD",
3148
+ ...resolveBidPricing(data),
3110
3149
  ...parseBidDimensions(data),
3111
3150
  dealId: data.dealId || "",
3112
3151
  mediaType: resolvedMediaType,
@@ -3200,8 +3239,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3200
3239
  const resolvedMediaType = isVideo ? "video" : mediaType || cached?.bidTrace?.mediaType || "banner";
3201
3240
  const bidTrace = {
3202
3241
  bidder: bid.bidderCode || bid.bidder || cached?.bidTrace?.bidder || "",
3203
- cpm: Number.isFinite(bid.originalCpm) ? bid.originalCpm : Number.isFinite(bid.cpm) ? bid.cpm : cached?.bidTrace?.cpm ?? 0,
3204
- currency: bid.originalCurrency ?? bid.currency ?? cached?.bidTrace?.currency ?? "USD",
3242
+ ...resolveBidPricing(bid, cached?.bidTrace),
3205
3243
  ...parseBidDimensions(bid).width ? parseBidDimensions(bid) : cached?.bidTrace ? { width: cached.bidTrace.width, height: cached.bidTrace.height } : parseBidDimensions(bid),
3206
3244
  dealId: bid.dealId || cached?.bidTrace?.dealId || "",
3207
3245
  mediaType: resolvedMediaType,
@@ -3409,7 +3447,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3409
3447
  }
3410
3448
  }
3411
3449
  isSampledVisitor() {
3412
- const key = this.config.userId || this.config.visitorId || this.config.pageviewId;
3450
+ const key = this.config.visitorId || this.config.userId || this.config.pageviewId;
3413
3451
  return isVisitorSampled(key, this.config.sampleRate);
3414
3452
  }
3415
3453
  shouldSample(type) {
@@ -3442,6 +3480,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3442
3480
  if (this.queue.length === 0 || !this.config.endpoint) return null;
3443
3481
  const domain = typeof window !== "undefined" ? window.location.hostname : "";
3444
3482
  const sampleRate = normalizeSampleRate(this.config.sampleRate);
3483
+ const automated = typeof navigator !== "undefined" && navigator.webdriver === true;
3445
3484
  const buildBatch = (evts) => ({
3446
3485
  propertyId: idToBytes(this.config.propertyId),
3447
3486
  pageviewId: idToBytes(this.config.pageviewId),
@@ -3453,7 +3492,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3453
3492
  userId: this.config.userId || "",
3454
3493
  domain,
3455
3494
  events: evts,
3456
- ...sampleRate < 1 ? { sampleRate } : {}
3495
+ ...sampleRate < 1 ? { sampleRate } : {},
3496
+ ...automated ? { automated: true } : {}
3457
3497
  });
3458
3498
  const headerBytes = TraceEventBatch.encode(buildBatch([])).finish().byteLength;
3459
3499
  for (; ; ) {
@@ -3554,8 +3594,10 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3554
3594
  flush() {
3555
3595
  if (Date.now() < this.nextSendAllowedAt) return;
3556
3596
  let payload = this.drainBatch();
3597
+ let useKeepalive = true;
3557
3598
  while (payload) {
3558
- this.sendFetch(payload, false);
3599
+ this.sendFetch(payload, useKeepalive);
3600
+ useKeepalive = false;
3559
3601
  if (Date.now() < this.nextSendAllowedAt) break;
3560
3602
  payload = this.drainBatch();
3561
3603
  }
package/dist/index.mjs CHANGED
@@ -285,6 +285,8 @@ var TraceEventType = {
285
285
  * signals (bitmask), sdk_loaded, device (mobile|desktop), browser, forced ("1" on forced show).
286
286
  */
287
287
  RECOVERY: 20,
288
+ /** PAGEVIEW - Pageview start (once per initial load or SPA navigate()). */
289
+ PAGEVIEW: 21,
288
290
  UNRECOGNIZED: -1
289
291
  };
290
292
  var BidderOutcome = {
@@ -326,7 +328,8 @@ function createBaseTraceEventBatch() {
326
328
  deviceModel: "",
327
329
  city: "",
328
330
  postalCode: "",
329
- sampleRate: void 0
331
+ sampleRate: void 0,
332
+ automated: false
330
333
  };
331
334
  }
332
335
  var TraceEventBatch = {
@@ -381,6 +384,9 @@ var TraceEventBatch = {
381
384
  if (message.sampleRate !== void 0) {
382
385
  writer.uint32(129).double(message.sampleRate);
383
386
  }
387
+ if (message.automated !== void 0 && message.automated !== false) {
388
+ writer.uint32(136).bool(message.automated);
389
+ }
384
390
  return writer;
385
391
  },
386
392
  decode(input, length) {
@@ -505,6 +511,13 @@ var TraceEventBatch = {
505
511
  message.sampleRate = reader.double();
506
512
  continue;
507
513
  }
514
+ case 17: {
515
+ if (tag !== 136) {
516
+ break;
517
+ }
518
+ message.automated = reader.bool();
519
+ continue;
520
+ }
508
521
  }
509
522
  if ((tag & 7) === 4 || tag === 0) {
510
523
  break;
@@ -1187,6 +1200,8 @@ function sendEvents(opts) {
1187
1200
  viewableDurationMs: void 0,
1188
1201
  bidderOutcomes: []
1189
1202
  }));
1203
+ const nav = g && "navigator" in g ? g.navigator : void 0;
1204
+ const automated = Boolean(nav && nav.webdriver === true);
1190
1205
  const batch = {
1191
1206
  propertyId: idToBytes(opts.propertyId),
1192
1207
  pageviewId: idToBytes(pageviewId),
@@ -1198,10 +1213,10 @@ function sendEvents(opts) {
1198
1213
  deviceType: void 0,
1199
1214
  domain,
1200
1215
  events: traceEvents,
1201
- ...sampleRate < 1 ? { sampleRate } : {}
1216
+ ...sampleRate < 1 ? { sampleRate } : {},
1217
+ ...automated ? { automated: true } : {}
1202
1218
  };
1203
1219
  const encoded = TraceEventBatch.encode(batch).finish();
1204
- const nav = g && "navigator" in g ? g.navigator : void 0;
1205
1220
  if (nav && typeof nav.sendBeacon === "function") {
1206
1221
  try {
1207
1222
  const blob = new Blob([encoded], { type: SAFE_CONTENT_TYPE });
@@ -1765,6 +1780,24 @@ function parseBidDimensions(bid) {
1765
1780
  height: Number.isFinite(bid?.height) ? bid.height : 0
1766
1781
  };
1767
1782
  }
1783
+ function resolveBidPricing(bid, fallback) {
1784
+ if (Number.isFinite(bid?.cpm)) {
1785
+ return {
1786
+ cpm: bid.cpm,
1787
+ currency: bid?.currency || bid?.originalCurrency || fallback?.currency || "USD"
1788
+ };
1789
+ }
1790
+ if (Number.isFinite(bid?.originalCpm)) {
1791
+ return {
1792
+ cpm: bid.originalCpm,
1793
+ currency: bid?.originalCurrency || bid?.currency || fallback?.currency || "USD"
1794
+ };
1795
+ }
1796
+ return {
1797
+ cpm: fallback?.cpm ?? 0,
1798
+ currency: fallback?.currency || bid?.currency || bid?.originalCurrency || "USD"
1799
+ };
1800
+ }
1768
1801
  var defaultLogger = createLogger({
1769
1802
  prefix: "[analytics]",
1770
1803
  logLevel: "INFO"
@@ -1796,7 +1829,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1796
1829
  inst.config.visitorId = inst.config.visitorId || inst.config.pageviewId;
1797
1830
  } else if (!inst.config.userId) {
1798
1831
  inst.config.userId = getOrCreateUserId();
1799
- inst.config.visitorId = inst.config.userId || inst.config.pageviewId;
1832
+ inst.config.visitorId = inst.config.visitorId || inst.config.userId || inst.config.pageviewId;
1800
1833
  }
1801
1834
  }
1802
1835
  }
@@ -1844,6 +1877,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1844
1877
  recordedConsentKeys = /* @__PURE__ */ new Set();
1845
1878
  consentCount = 0;
1846
1879
  cmpDetach = null;
1880
+ pageviewEmitted = false;
1847
1881
  logger;
1848
1882
  // True when managing session lifecycle internally; false if caller supplied fixed sessionId.
1849
1883
  managesSessionId;
@@ -1974,6 +2008,10 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1974
2008
  document.addEventListener("visibilitychange", this.boundVisibilityChange);
1975
2009
  }
1976
2010
  bindActivityListeners();
2011
+ if (!this.pageviewEmitted) {
2012
+ this.pageviewEmitted = true;
2013
+ this.enqueue(TraceEventType.PAGEVIEW, "pageview", {});
2014
+ }
1977
2015
  this.flushTimer = setInterval(() => this.flush(), FLUSH_INTERVAL_MS);
1978
2016
  this.resendPersistedBatches();
1979
2017
  }
@@ -2143,6 +2181,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2143
2181
  }
2144
2182
  });
2145
2183
  }
2184
+ record.accumulatedTimeInViewMs = 0;
2146
2185
  }
2147
2186
  this.flushBeacon();
2148
2187
  } else if (document.visibilityState === "visible") {
@@ -2665,8 +2704,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2665
2704
  );
2666
2705
  const bidTrace = {
2667
2706
  bidder: rawBid.bidderCode || rawBid.bidder || cached?.bidTrace?.bidder || "",
2668
- cpm: Number.isFinite(rawBid.originalCpm) ? rawBid.originalCpm : Number.isFinite(rawBid.cpm) ? rawBid.cpm : cached?.bidTrace?.cpm ?? 0,
2669
- currency: rawBid.originalCurrency ?? rawBid.currency ?? cached?.bidTrace?.currency ?? "USD",
2707
+ ...resolveBidPricing(rawBid, cached?.bidTrace),
2670
2708
  ...parseBidDimensions(rawBid).width ? parseBidDimensions(rawBid) : cached?.bidTrace ? { width: cached.bidTrace.width, height: cached.bidTrace.height } : parseBidDimensions(rawBid),
2671
2709
  dealId: rawBid.dealId || cached?.bidTrace?.dealId || "",
2672
2710
  mediaType,
@@ -2899,7 +2937,9 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2899
2937
  this.floorDecisions.clear();
2900
2938
  this.recordedConsentKeys.clear();
2901
2939
  this.consentCount = 0;
2940
+ this.pageviewEmitted = false;
2902
2941
  this.config.pageviewId = pageviewId || generateUUID2();
2942
+ this.config.visitorId = this.config.userId || this.config.pageviewId;
2903
2943
  if (pageUrl) {
2904
2944
  try {
2905
2945
  const u = new URL(pageUrl);
@@ -2996,15 +3036,15 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2996
3036
  const auctionId = data.auctionId || "";
2997
3037
  const bidder = data.bidderCode || data.bidder || "";
2998
3038
  const adUnitCode = data.adUnitCode || "";
2999
- const cpm = Number.isFinite(data.originalCpm) ? data.originalCpm : Number.isFinite(data.cpm) ? data.cpm : 0;
3039
+ const pricing = resolveBidPricing(data);
3040
+ const cpm = pricing.cpm;
3000
3041
  const latencyMs = Number.isFinite(data.timeToRespond) ? data.timeToRespond : 0;
3001
3042
  const resMediaTypes = Object.keys(data.mediaTypes || {});
3002
3043
  const mediaType = data.mediaType || (data.mediaTypes?.video ? "video" : resMediaTypes.length > 0 ? resMediaTypes[0] : "banner");
3003
3044
  if (!auctionId || !bidder) return;
3004
3045
  const bid = cpm > 0 ? {
3005
3046
  bidder,
3006
- cpm,
3007
- currency: data.originalCurrency ?? data.currency ?? "USD",
3047
+ ...pricing,
3008
3048
  ...parseBidDimensions(data),
3009
3049
  dealId: data.dealId || "",
3010
3050
  mediaType,
@@ -3054,8 +3094,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3054
3094
  const resolvedMediaType = data.mediaType || (data.mediaTypes?.video ? "video" : wonMediaTypes.length > 0 ? wonMediaTypes[0] : "banner");
3055
3095
  const bidTrace = {
3056
3096
  bidder: data.bidderCode || data.bidder || "",
3057
- cpm: Number.isFinite(data.originalCpm) ? data.originalCpm : Number.isFinite(data.cpm) ? data.cpm : 0,
3058
- currency: data.originalCurrency ?? data.currency ?? "USD",
3097
+ ...resolveBidPricing(data),
3059
3098
  ...parseBidDimensions(data),
3060
3099
  dealId: data.dealId || "",
3061
3100
  mediaType: resolvedMediaType,
@@ -3149,8 +3188,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3149
3188
  const resolvedMediaType = isVideo ? "video" : mediaType || cached?.bidTrace?.mediaType || "banner";
3150
3189
  const bidTrace = {
3151
3190
  bidder: bid.bidderCode || bid.bidder || cached?.bidTrace?.bidder || "",
3152
- cpm: Number.isFinite(bid.originalCpm) ? bid.originalCpm : Number.isFinite(bid.cpm) ? bid.cpm : cached?.bidTrace?.cpm ?? 0,
3153
- currency: bid.originalCurrency ?? bid.currency ?? cached?.bidTrace?.currency ?? "USD",
3191
+ ...resolveBidPricing(bid, cached?.bidTrace),
3154
3192
  ...parseBidDimensions(bid).width ? parseBidDimensions(bid) : cached?.bidTrace ? { width: cached.bidTrace.width, height: cached.bidTrace.height } : parseBidDimensions(bid),
3155
3193
  dealId: bid.dealId || cached?.bidTrace?.dealId || "",
3156
3194
  mediaType: resolvedMediaType,
@@ -3358,7 +3396,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3358
3396
  }
3359
3397
  }
3360
3398
  isSampledVisitor() {
3361
- const key = this.config.userId || this.config.visitorId || this.config.pageviewId;
3399
+ const key = this.config.visitorId || this.config.userId || this.config.pageviewId;
3362
3400
  return isVisitorSampled(key, this.config.sampleRate);
3363
3401
  }
3364
3402
  shouldSample(type) {
@@ -3391,6 +3429,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3391
3429
  if (this.queue.length === 0 || !this.config.endpoint) return null;
3392
3430
  const domain = typeof window !== "undefined" ? window.location.hostname : "";
3393
3431
  const sampleRate = normalizeSampleRate(this.config.sampleRate);
3432
+ const automated = typeof navigator !== "undefined" && navigator.webdriver === true;
3394
3433
  const buildBatch = (evts) => ({
3395
3434
  propertyId: idToBytes(this.config.propertyId),
3396
3435
  pageviewId: idToBytes(this.config.pageviewId),
@@ -3402,7 +3441,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3402
3441
  userId: this.config.userId || "",
3403
3442
  domain,
3404
3443
  events: evts,
3405
- ...sampleRate < 1 ? { sampleRate } : {}
3444
+ ...sampleRate < 1 ? { sampleRate } : {},
3445
+ ...automated ? { automated: true } : {}
3406
3446
  });
3407
3447
  const headerBytes = TraceEventBatch.encode(buildBatch([])).finish().byteLength;
3408
3448
  for (; ; ) {
@@ -3503,8 +3543,10 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3503
3543
  flush() {
3504
3544
  if (Date.now() < this.nextSendAllowedAt) return;
3505
3545
  let payload = this.drainBatch();
3546
+ let useKeepalive = true;
3506
3547
  while (payload) {
3507
- this.sendFetch(payload, false);
3548
+ this.sendFetch(payload, useKeepalive);
3549
+ useKeepalive = false;
3508
3550
  if (Date.now() < this.nextSendAllowedAt) break;
3509
3551
  payload = this.drainBatch();
3510
3552
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bidspark/analytics",
3
- "version": "0.43.1",
3
+ "version": "0.44.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",