/** * @id5io/id5-api.js * @version v1.0.81 * @link https://id5.io/ * @license Apache-2.0 */ !function(){"use strict";function r(t,e){var i,r=Object.keys(t);return Object.getOwnPropertySymbols&&(i=Object.getOwnPropertySymbols(t),e&&(i=i.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,i)),r}function h(t){for(var e=1;ee.length)&&(t=e.length);for(var i=0,r=new Array(t);i=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:t}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,n=!0,o=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return n=e.done,e},e:function(e){o=!0,s=e},f:function(){try{n||null==i.return||i.return()}finally{if(o)throw s}}}}function i(e,t,i){return function(e,t){if(e!==t)throw new TypeError("Private static access of wrong provenance")}(e,t),i}class e{debug(){}info(){}warn(){}error(){}}const p=new e;class l extends e{constructor(e,t){super(),this._prefix=e,this._delegate=t}debug(){for(var e=arguments.length,t=new Array(e),i=0;iparseInt(e)||0,e=(e,t)=>{t=e-t;return 0==t?0:t<0?-1:1},t=e(i(r[0]),i(s[0]));if(0!==t)return t;t=e(i(r[1]),i(s[1]));return 0===t?e(i(r[2]),i(s[2])):t}}const _="Array",v="String",m="Function",I=Object.prototype.toString;function w(e,t){return I.call(e)==="[object "+t+"]"}function S(e){return w(e,m)}function C(e){return w(e,v)}function y(e){return w(e,_)}function b(e){return w(e,"Number")}function D(e){return w(e,"Object")}function E(e){return void 0!==e}function A(t,i){if(!function(e){if(!e)return 1;if(y(e)||C(e))return!(0{let i=t.split("="),r=g(i,2),s=r[0],n=r[1];return/\[\]$/.test(s)?(s=s.replace("[]",""),e[s]=e[s]||[],e[s].push(n)):e[s]=n||"",e},{}):{},hash:(i.hash||"").replace(/^#/,""),host:i.host||window.location.host}}function P(e){return(e.protocol||"http")+"://"+(e.host||e.hostname+(e.port?":".concat(e.port):""))+(e.pathname||"")+(e.search?"?".concat((i=e.search||"",Object.keys(i).map(t=>Array.isArray(i[t])?i[t].map(e=>"".concat(t,"[]=").concat(e)).join("&"):"".concat(t,"=").concat(i[t])).join("&"))):"")+(e.hash?"#".concat(e.hash):"");var i}function O(i,e){function r(e,t){if(S(Math.imul))return Math.imul(e,t);var i=(4194303&e)*(t|=0);return 4290772992&e&&(i+=(4290772992&e)*t|0),0|i}e=1>>16,2246822507)^r(n^n>>>13,3266489909),n=r(n^n>>>16,2246822507)^r(s^s>>>13,3266489909),(4294967296*(2097151&n)+(s>>>0)).toString()}const R="TRUE"===V("id5_debug").toUpperCase(),x="TRACE"===V("id5_debug").toUpperCase(),L=Boolean(window.console);let F=!1;function N(e,t,i,r,s){U()&&L&&e&&e.apply(console,["%cID5 - ".concat(t,"#").concat(i),"color: #fff; background: #1c307e; padding: 1px 4px; border-radius: 3px;",r].concat(s))}function U(){return R||x||F}class k extends e{constructor(e,t){super(),d(this,"_invocationId",void 0),d(this,"_origin",void 0),this._invocationId=t,this._origin=e}debug(){for(var e=arguments.length,t=new Array(e),i=0;inull!=e&&"object"==typeof e;function K(e,t){if(!(Y(e)&&Y(t)))return e===t;if(W(e)&&W(t))return function(t,i){var e=t.length===i.length;if(!e)return!1;for(let e=0;et[e]).reduce((e,t)=>e&&t,!0);return new ae(r,oe.CONSENT_API,t,i)}_addToDebugInfo(e,t,i){return void 0!==t.localStoragePurposeConsent&&(i[e+"-localStoragePurposeConsent"]=t.localStoragePurposeConsent),void 0!==t.vendorsConsentForId5Granted&&(i[e+"-vendorsConsentForId5Granted"]=t.vendorsConsentForId5Granted),i}_isGranted(){return!1===this.gdprApplies||!0===this.localStoragePurposeConsent&&!1!==this.vendorsConsentForId5Granted}hashCode(){this.localStoragePurposeConsent,this.ccpaString;var e=t(this,$);return O(JSON.stringify(e))}static createFrom(e){const t=u(new ne,e);return E(t.api)&&(t.apiTypes=function(e){var t=e.api;if(t===ee.NONE)return[];if(t!==ee.PREBID)return[t];{const i=[];return(E(e.gdprApplies)||E(e.consentString))&&i.push(ee.TCF_V2),E(e.ccpaString)&&i.push(ee.USP_V1),E(e.gppData)&&E(e.gppData.version)&&i.push(e.gppData.version),i}}(e),t.api=void 0),D(t.gppData)&&(t.gppData=se.createFrom(t.gppData)),t}getApiTypeData(e){if(this.apiTypes.includes(e)){if(e===ee.USP_V1)return{ccpaString:this.ccpaString};if(e===ee.TCF_V2)return{consentString:this.consentString,gdprApplies:this.gdprApplies,localStoragePurposeConsent:this.localStoragePurposeConsent};if(e===ee.GPP_V1_1||e===ee.GPP_V1_0)return this.gppData;if(e===ee.ID5_ALLOWED_VENDORS)return{allowedVendors:this.allowedVendors}}}toConsents(){let e={};return E(this.gdprApplies)&&(e.gdpr=this.gdprApplies),E(this.consentString)&&(e.gdpr_consent=this.consentString),E(this.ccpaString)&&(e.us_privacy=this.ccpaString),E(this.gppData)&&(e.gpp=this.gppData.gppString,e.gpp_sid=this.gppData.applicableSections.join(",")),e}}const oe=Object.freeze({FORCE_ALLOWED_BY_CONFIG:"force_allowed_by_config",ID5_CONSENT:"id5_consent",PROVISIONAL:"provisional",JURISDICTION:"jurisdiction",CONSENT_API:"consent_api"});class ae{constructor(e,t){var i=2function(i){Object.keys(i).forEach(function(e){var t=i[e];t&&(t instanceof Object?i[e]=JSON.stringify(t):i[e]="".concat(t))})}(e.tags)),fetch(this.url,{method:"POST",headers:{"Content-Type":"text/plain"},mode:"no-cors",body:JSON.stringify({metadata:h(h({},this._metadata),t),measurements:e})})):Promise.resolve()}}class de{constructor(e,t){d(this,"_publisher",void 0),d(this,"_scheduled",void 0),this.meterRegistry=e,this._publisher=t;const i=this;this.meterRegistry.onUnregister(function(){const e=i._onUnloadPublishAbortController;if(e)return e.abort(),i.publish({trigger:"unregister"})})}publish(){let t=0this._publisher(e,t)).then(()=>this.meterRegistry.reset())}schedulePublishAfterMsec(e){const t=this;return t._scheduled||(setTimeout(()=>(t._scheduled=!1,t.publish({trigger:"fixed-time",fixed_time_msec:e})),e),t._scheduled=!0),this}schedulePublishBeforeUnload(){const e=this;var t="undefined"!=typeof AbortController?new AbortController:void 0;return t&&(addEventListener("beforeunload",()=>e.publish({trigger:"beforeunload"}),{capture:!1,signal:t.signal}),this._onUnloadPublishAbortController=t),this}}const he=Object.freeze({});var ue,ge={EMPTY:he,from:function(e){return e?e instanceof Map?Object.fromEntries(e):e:he},toString:function(e){return Array.from(Object.entries(e),e=>{var t=g(e,2),e=t[0],t=t[1];return"".concat(e,"=").concat(t)}).sort().toString()}};const pe=Object.freeze({TIMER:"TIMER",SUMMARY:"SUMMARY",COUNTER:"COUNTER"});class _e{constructor(e,t,i){d(this,"name",void 0),d(this,"tags",void 0),d(this,"values",void 0),this.name=e,this.tags=ge.from(t),this.type=i,this.values=[]}reset(){this.values=[]}}class ve extends _e{constructor(e){super(e,1{return g(e,2)[1]})}}function Ce(){return new fe}function ye(e){return{partner:e}}class be extends class{constructor(){var e=0({name:e.name,type:e.type,tags:e.tags,values:e.values})).filter(function(e){return e.values&&0e.reset())}addCommonTags(e){this.commonTags=h(h({},this.commonTags),ge.from(e))}timer(e){return this.getOrCreate(e,1new ve(e,t))}counter(e){return this.getOrCreate(e,1new me(e,t))}summary(e){return this.getOrCreate(e,1new Ie(e,t))}unregister(){void 0!==this._onUnregisterCallback&&this._onUnregisterCallback(this)}onUnregister(e){this._onUnregisterCallback=e}}{constructor(e,t){var i=2{var e=i("ping",function(e){t(e)});q(e)&&t(e)});switch(s.gppVersion){case Re.version:return new Re(s,i,r);case Le.version:return new Le(s,i,r,c);default:var n="Unsupported version of gpp: ".concat(s.gppVersion);return a.warn(n),Promise.reject(n)}})()}static caTcfDataHasExpressConsent(e){e=e.PurposesExpressConsent;if(W(e)&&0e==Z)}static tcfDataHasLocalStorageGrant(e){e=i(Pe,Pe,Oe).call(Pe,e,"PurposeConsent","PurposeConsents");if(W(e)&&0e==Z))}static getTcfData(e){let t=void 0;return W(e)&&q(e[0])?t=e[0]:q(e)&&(t=e),t}}function Oe(e,t,i){return t in e?e[t]:e[i]}class Re extends Pe{constructor(e,t,i){super(i,Re.version),d(this,"gppFn",void 0),d(this,"ready",void 0),this.gppFn=t,this.ready=this.isReady(e)}isReady(e){return"loaded"===e.cmpStatus&&"visible"!==e.cmpDisplayStatus}getClientConsentData(){var r=this;return s(function*(){r.ready||(r.ready=yield new Promise(t=>{r.gppFn("addEventListener",e=>!!r.isReady(e.pingData)&&void t(!0))}));var e=new Promise(t=>{r.gppFn("getGPPData",e=>{t(e)})}),t=new Promise(t=>{r.gppFn("getSection",e=>{t(e)},"tcfeuv2")}),e=g(yield Promise.all([e,t]),2),t=e[0],e=e[1];const i=new se(ee.GPP_V1_0,t.applicableSections,t.gppString);return e&&(i.euTcfSection=new re(Pe.tcfDataHasLocalStorageGrant(e),Pe.tcfDataHasID5VendorConsented(e))),i})()}}function xe(e,t,i){i&&(e.apiTypes.push(t),u(e,i))}d(Re,"version","1.0");class Le extends Pe{constructor(e,t,i,r){super(i,Le.version),d(this,"gppFn",void 0),d(this,"readyPingData",void 0),d(this,"metrics",void 0),this.gppFn=t,"ready"===e.signalStatus&&(this.readyPingData=e),this.metrics=r}getClientConsentData(){var o=this;return s(function*(){const n=o.metrics;return new Promise(i=>{let r=!1;if(o.readyPingData)i(o.parsePingData(o.readyPingData));else{const s=Date.now();let t=setTimeout(()=>{t=void 0,o.gppFn("ping",e=>{"stub"===e.cmpStatus&&(n.counter("gpp.stubUsed",{cmpId:e.cmpId}).inc(),i(o.parsePingData(e)))})},1e3);o.gppFn("addEventListener",e=>"ready"===e.pingData.signalStatus&&void(r?o.measureAdditionalEvent(e,n,s):(t?(clearTimeout(t),t=void 0):r||n.timer("gpp.lateCmp",{cmpId:e.pingData.cmpId}).record(Date.now()-s),i(o.parsePingData(e.pingData)),r=!0)))}})})()}static measureAdditionalEvent(e,t,i){["cmpStatus","cmpDisplayStatus","signalStatus","sectionChange"].includes(e.eventName)&&t.timer("gpp.additionalEvents",{cmpId:e.pingData.cmpId,name:e.eventName}).record(Date.now()-i)}parsePingData(e){const t=new se(ee.GPP_V1_1,e.applicableSections,e.gppString);var i;return!t.applicableSections.includes(ie.TCFEUV2)||(i=Pe.getTcfData(null===(i=e.parsedSections)||void 0===i?void 0:i.tcfeuv2))&&(t.euTcfSection=new re(Pe.tcfDataHasLocalStorageGrant(i),Pe.tcfDataHasID5VendorConsented(i))),!t.applicableSections.includes(ie.TCFCAV1)||(e=Pe.getTcfData(null===(e=e.parsedSections)||void 0===e?void 0:e.tcfcav1))&&(t.canadaTcfSection=new re(Pe.caTcfDataHasExpressConsent(e),Pe.caTcfDataHasVendorExpressConsent(e))),t}}d(Le,"version","1.1");class Fe{constructor(e){var t=1{r._lookupInProgress=!1})),this._consentDataPromise}_lookupConsentData(e,t,i){if(e){this._log.warn("cmpApi: ID5 is operating in forced consent mode and will not retrieve any consent signals from the CMP");let e=new ne;return e.forcedGrantByConfig=!0,e.source=te.partner,Promise.resolve(e)}switch(t){case"static":return new Promise(e=>{this._parseStaticConsentData(i,e)});case"iab":return new Promise(e=>{this._lookupIabConsent(e)});default:return this._log.error("cmpApi: Unknown consent API: ".concat(t)),Promise.reject(new Error("Unknown consent API: ".concat(t)))}}_parseStaticConsentData(e,t){e=e||{};let i=new ne;if(i.source=te.partner,q(e.getTCData)){const r=this._parseTcfData(e.getTCData);xe(i,ee.TCF_V2,r);try{const s=this._metrics;this._lookupTcf(e=>{De(s,{apiType:ee.TCF_V2,sameString:(null==e?void 0:e.consentString)===(null===r||void 0===r?void 0:r.consentString),sameLSPC:(null==e?void 0:e.localStoragePurposeConsent)===(null===r||void 0===r?void 0:r.localStoragePurposeConsent),sameVendorsConsentForId5Granted:(null==e?void 0:e.vendorsConsentForId5Granted)===(null===r||void 0===r?void 0:r.vendorsConsentForId5Granted),sameGdpr:(null==e?void 0:e.gdprApplies)===(null===r||void 0===r?void 0:r.gdprApplies)}).inc()})}catch(e){}}if(W(e.allowedVendors)&&xe(i,ee.ID5_ALLOWED_VENDORS,{allowedVendors:e.allowedVendors.map(e=>e.toString()),gdprApplies:!0}),q(e.getUSPData)){const n=this._parseUspData(e.getUSPData);xe(i,ee.USP_V1,n);try{const o=this._metrics;this._lookupUsp(e=>{De(o,{apiType:ee.USP_V1,sameString:(null==e?void 0:e.ccpaString)===(null===n||void 0===n?void 0:n.ccpaString)}).inc()})}catch(e){}}0===i.apiTypes.length&&this._log.warn("cmpApi: No static consent data detected! Using defaults."),this._log.info("cmpApi: Detected APIs '".concat(i.apiTypes,"' from static consent data"),e),t(i)}_lookupIabConsent(r){const s=[];let n=new ne;n.source=te.cmp;var e=i=>(s[i]=0,(e,t)=>{s[i]||(s[i]=Date.now(),e&&xe(n,t,e),s.every(e=>0{t?i(this._parseUspData(e),ee.USP_V1):(this._log.error("cmpApi: USP callback not successful. Using defaults for CCPA."),i())})}_lookupGpp(n){var o=this;return s(function*(){var t=Date.now();try{let e=yield Pe.create(o._log,o._metrics);if(e){var i={gppVersion:e.version,directCmp:e.direct};try{var r=yield e.getConsentData();n({gppData:r},r.version);var s=Date.now();o._metrics.timer("gpp.delay",i).record(s-t)}catch(e){o._metrics.counter("gpp.failure",u({type:"CONSENT"},i)).inc(),o._log.error("cmpApi: getting GPP consent not successful. Using defaults for Gpp."),n()}}else n()}catch(e){o._metrics.counter("gpp.failure",{type:"CLIENT"}).inc(),o._log.error("cmpApi: creating GPP client not successful. Using defaults for Gpp."),n()}})()}static _buildCmpSurrogate(a,c){return(e,t,i)=>{const r=Math.random()+"",s={},n={};n[a.objKeys[0]]=e,n[a.objKeys[1]]=t,n.callId=r,s[a.objName]=n;const o=e=>{e=X(e,"data.".concat(a.returnObjName));e&&e.callId===r&&(void 0!==(e=i(e.returnValue,e.success))&&!0!==e||window.removeEventListener("message",o))};window.addEventListener("message",o,!1),c.postMessage(s,"*")}}_lookupTcf(e){var t=Fe._findTCF(),i=t.cmpFrame,t=t.cmpFunction;if(!i)return this._log.warn("cmpApi: TCF not found! Using defaults for GDPR."),void e();M(t)?this._lookupDirectTcf(t,e):(this._log.info("cmpApi: Detected TCF is outside the current iframe. Using message passing."),this._lookupMessageTcf(i,e))}_lookupMessageTcf(e,t){e=Fe._buildCmpSurrogate(Ae.tcfv2,e);this._lookupDirectTcf(e,t)}_lookupDirectTcf(e,s){const n=this._log;e("addEventListener",2,(e,t)=>{var i,r;return i="event",r=e,n.info("cmpApi: TCFv2 - Received a call back: ".concat(i),r),t?!(!e||!1!==e.gdprApplies&&"tcloaded"!==e.eventStatus&&"useractioncomplete"!==e.eventStatus)&&void s(this._parseTcfData(e),ee.TCF_V2):(n.error("cmpApi: TCFv2 - Received insuccess: ".concat("addEventListener",". Please check your CMP setup. Using defaults for GDPR.")),void s())})}_parseUspData(e){if(q(e)&&j(e.uspString))return{ccpaString:e.uspString};this._log.error("cmpApi: No or malformed USP data. Using defaults for CCPA.")}_parseTcfData(e){let t=this._log,i,r;if(i=Fe._isValidV2ConsentObject,r=Fe._normalizeV2Data,i(e))return r(e);t.error("cmpApi: Invalid CMP data. Using defaults for GDPR.",e)}static _isValidV2ConsentObject(e){var t=e&&e.gdprApplies,e=e&&e.tcString;return!1===t||j(e)}static _tcfDataHasID5VendorConsented(e){var t,i;return!0===(null==e||null===(t=e.vendor)||void 0===t||null===(i=t.consents)||void 0===i?void 0:i[Z])}static _normalizeV2Data(e){let t=X(e,"purpose.consents.1");B(t)||(t=function(e,t){var i=152+t-1,t=~~(i/6);if(e&&"C"===e.charAt(0)&&!(e.length<=t)){t=e.charAt(t),t=Q[t];if(void 0!==t)return 0!=(t&1<<6-i%6-1)}}(e.tcString,1));var i=Fe._tcfDataHasID5VendorConsented(e);return{consentString:e.tcString,localStoragePurposeConsent:t,gdprApplies:e.gdprApplies,vendorsConsentForId5Granted:i}}static _findTCF(){let e=window,t,i;for(;!t;){try{if("function"==typeof e.__tcfapi){i=e.__tcfapi,t=e;break}}catch(e){}try{if(e.frames.__tcfapiLocator){t=e;break}}catch(e){}if(e===window.top)break;e=e.parent}return{cmpFrame:t,cmpFunction:i}}static _findCmpApi(e){let t=window,i,r;for(;!i;){try{if("function"==typeof t[e]){r=t[e],i=t;break}}catch(e){}try{if(t.frames["".concat(e,"Locator")]){i=t;break}}catch(e){}if(t===window.top)break;t=t.parent}return{cmpApiFrame:i,cmpApiFunction:r}}}const Ne=Object.freeze({CONSENT_UPDATED:"consent_updated",USER_ID_READY:"user_id_ready",CASCADE_NEEDED:"fire_sync_pixel",USER_ID_FETCH_CANCELED:"user_id_fetch_canceled",USER_ID_FETCH_FAILED:"user_id_fetch_failed"}),Ue=Object.freeze({ID5_MESSAGE_RECEIVED:"message",ID5_INSTANCE_JOINED:"instance-joined",ID5_LEADER_ELECTED:"leader-elected"}),ke=Object.freeze([...Object.values(Ue),...Object.values(Ne)]);class Ve{constructor(){var e=0this._trigger("immediate"),0):0this._trigger("timeout"),s))}_trigger(){let e=0{this._log.debug("Firing ".concat(this._callbackName," callback after ").concat(t,"ms. Triggered by ").concat(e,", configured timeoutMs=").concat(this._timeout)),this._beforeTrigger(),this._callbackFn.call(globalThis,...this._callbackArgs)},0))}triggerNow(){var e=0{this.options[e]=t,this.providedOptions[e]=t};Object.keys(a).forEach(e=>{if("segments"===e){const r=a[e],s=[];E(r)&&(W(r)?(r.forEach((e,t)=>{t="segments[".concat(t,"]");return W(e.ids)&&function(e,t){let i=!0;return A(e,e=>i=i&&t(e)),i}(e.ids,j)?e.ids.length<1?(l.error("Config option ".concat(t,".ids should contain at least one segment ID")),void(c.invalidSegments+=1)):j(e.destination)?void s.push(e):(qe(l,"".concat(t,".destination"),"String",e.destination),void(c.invalidSegments+=1)):(qe(l,"".concat(t,".ids"),"Array of String",e.ids),void(c.invalidSegments+=1))}),d(e,s)):qe(l,e,"Array",r))}else if("diagnostics"===e){const n=this.options.diagnostics,o=a.diagnostics;if(G(o,He.configTypes.diagnostics)){let t=h({},n);Object.keys(o).forEach(e=>{void 0!==n[e]&&typeof n[e]==typeof o[e]&&(t[e]=o[e])}),this.options[e]=t}this.providedOptions[e]=a[e]}else{var t,i;void 0!==We[e]?(i=a[e])&&We[e].includes(i)&&d(e,i):"partnerId"!==e&&(t=He.configTypes[e],E(i=a[e])&&(G(i,t)?d(e,i):qe(l,e,t,i)))}})}else l.error("Config options must be an object")}setPartnerId(e){let t;if(j(e)){if(t=parseInt(e),isNaN(t)||t<0)throw new Error("partnerId is required and must parse to a positive integer")}else H(e)&&(t=e);if(H(t)){if(H(this.options.partnerId)&&t!==this.options.partnerId)throw new Error("Cannot update config with a different partnerId");this.options.partnerId=t,this.providedOptions.partnerId=e}}}function qe(e,t,i,r){e.error("Config option ".concat(t," must be of type ").concat(i," but was ").concat(toString.call(r),". Ignoring..."))}d(He,"configTypes",{debugBypassConsent:"Boolean",allowLocalStorageWithoutConsentApi:"Boolean",cmpApi:"String",consentData:"Object",refreshInSeconds:"Number",partnerUserId:"String",callbackOnAvailable:"Function",callbackOnUpdates:"Function",callbackTimeoutInMs:"Number",pd:"String",abTesting:"Object",provider:"String",maxCascades:"Number",applyCreativeRestrictions:"Boolean",acr:"Boolean",disableUaHints:"Boolean",storageExpirationDays:"Number",att:"Number",diagnostics:"Object",multiplexing:"Object",dynamicConfig:"Object",allowGCReclaim:"String"});class Be{constructor(e,t,i){d(this,"refererInfo",void 0),d(this,"apiVersion",void 0),d(this,"isUsingCdn",void 0),this.refererInfo=e,this.apiVersion=t,this.isUsingCdn=i}}class Je{constructor(e,t){d(this,"_targets",void 0),d(this,"_metrics",void 0),d(this,"_survivalTimer",void 0),this._targets=[e,t],this._metrics=t,this._survivalTimer=Ce()}unregister(e){var t;this._survivalTimer&&this._metrics&&this._survivalTimer.record((t=this._metrics,e={unregisterTrigger:e},t.timer("instance.survival.time",e))),this._targets.forEach(e=>{try{J(e)&&M(e.unregister)&&e.unregister()}catch(e){}})}}globalThis.__id5_finalization_registry||(globalThis.__id5_finalization_registry=new class{constructor(){d(this,"_finalizationRegistry",void 0),d(this,"_instancesHolder",void 0),this._instancesHolder=new Set;try{this._finalizationRegistry=new FinalizationRegistry(e=>{try{J(e)&&M(e.unregister)&&e.unregister("gc-reclaim")}catch(e){}})}catch(e){}}register(e){try{e.getOptions().allowGCReclaim!==je.ASAP&&this._instancesHolder.add(e),this._finalizationRegistry.register(e,e._unregisterTargets,e)}catch(e){}}unregister(e){try{this.releaseInstance(e,!0),this._finalizationRegistry.unregister(e)}catch(e){}}releaseInstance(e){var t=1{},this),this}onUpdate(e){if(!M(e))throw new Error("onUpdate expects a function");return this._updateCallback=e,this._userIdAvailable&&this._fireOnUpdate(),this}unregister(){try{this._unregisterTargets.unregister("api-call"),ze.unregister(this)}catch(e){}}constructor(e,t,i,r,s,n){var o=6{this._userIdAvailablePromiseResolver=e}),this._pageLevelInfo=s,this._unregisterTargets=new Je(this._multiplexingInstance,this._metrics),this._origin=n,ze.register(this),this._registrationProperties=o}bootstrap(){const n=Ce();var e=this.config.getOptions();const o=this._ref();this._multiplexingInstance.on(Ne.USER_ID_READY,(e,t)=>{const i=o.deref();if(i){try{var r=null!=t&&t.tags?h({},t.tags):{},s=i._metrics;null!=t&&t.timestamp&&s.timer("userid.provisioning.delivery.delay",r).record(Date.now()-t.timestamp),n.record(function(e,t,i){return e.timer("userid.provisioning.delay",h({cachedResponseUsed:t},2{const t=o.deref();t&&t._log.info("ID5 User ID fetch canceled:",e.reason)}),this._log.info("bootstrapped for partner ".concat(e.partnerId," with referer ").concat(null===(e=this._pageLevelInfo)||void 0===e?void 0:e.refererInfo," and options"),this.getProvidedOptions())}init(){const i=this.config.getOptions();return this._gatherFetchIdData().then(e=>{var t;this._multiplexingInstance.register(h({source:this._origin,sourceVersion:Me,sourceConfiguration:{options:i},fetchIdData:e,singletonMode:!0===(null===i||void 0===i||null===(t=i.multiplexing)||void 0===t?void 0:t._disabled),forceAllowLocalStorageGrant:this.config.isForceAllowLocalStorageGrant(),storageExpirationDays:i.storageExpirationDays},this._registrationProperties))})}_gatherFetchIdData(){var t=this;return s(function*(){var e=t.config.getOptions();return Promise.resolve({partnerId:e.partnerId,refererInfo:t._pageLevelInfo.refererInfo,origin:t._origin,originVersion:t._pageLevelInfo.apiVersion,isUsingCdn:t._pageLevelInfo.isUsingCdn,abTesting:e.abTesting,provider:e.provider,refreshInSeconds:e.refreshInSeconds,providedRefreshInSeconds:t.getProvidedOptions().refreshInSeconds,trace:x,consentSource:te.none,segments:e.segments,invalidSegmentsCount:t.getInvalidSegments()})})()}_ref(){return new("undefined"!=typeof WeakRef?WeakRef:Xe)(this)}_setUserId(e,t){var i=2= 0 and <= 1");break;case"control":this._isExposed=!1,this._log.info("User is in control group!")}var s=this._userId!==r||!1===K(this._ext,e.ext)||!1===K(this._ids,e.ids);this._userIdAvailable=!0,this._userId=r,this._gpId=e.gp,this._ids=e.ids,this._userIdAvailablePromiseResolver(r),this._ext=e.ext,this._publisherTrueLinkId=e.publisherTrueLinkId,this._fromCache=t,this._log.info("User id updated",{hasChanged:s,fromCache:t}),this._availableCallback&&this._availableCallback.triggerNow(),this._isRefreshing&&this._refreshCallback&&(!1===t||!1===this._isRefreshingWithFetch)&&this._refreshCallback.triggerNow(),s&&this._fireOnUpdate(),this.getOptions().allowGCReclaim!==je.AFTER_UID_SET||t&&i||ze.releaseInstance(this)}_fireOnUpdate(){setTimeout(()=>{M(this._updateCallback)&&(this._log.debug("Firing onUpdate"),this._updateCallback(this))},0)}}class Ke{static gatherUaHints(e,t){return s(function*(){if(E(window.navigator.userAgentData)&&!e){let e;try{e=yield window.navigator.userAgentData.getHighEntropyValues(["architecture","fullVersionList","model","platformVersion"])}catch(e){return void t.error("Error while calling navigator.userAgentData.getHighEntropyValues()",e)}return Ke.filterUaHints(e)}})()}static filterUaHints(e){if(E(e)){const t=/[()-.:;=?_/]/g;return y(e.brands)&&(e.brands=e.brands.filter(e=>C(e.brand)&&e.brand.search(t)<0)),y(e.fullVersionList)&&(e.fullVersionList=e.fullVersionList.filter(e=>C(e.brand)&&e.brand.search(t)<0)),e}}}function Qe(e,t,i){return e.timer("fetch.call.time",h({status:t},2{let r=i.data;if(void 0!==i.data&&i.data._isId5Message&&i.data.src!==s._id&&(void 0===i.data.dst||i.data.dst===s._id))try{[et,r.type].forEach(e=>{let t=s._handlers[e];t&&t.forEach(e=>e(r,i.source))})}catch(e){s._log.error("Error while handling message",r,e)}},{capture:!1,signal:e})}unregister(){this._abortController&&this._abortController.abort()}onAnyMessage(e){return this.onMessage(et,e)}onMessage(e,t){const i=this._handlers[e];return i?i.push(t):this._handlers[e]=[t],this}broadcastMessage(e,t){this._log.debug("Broadcasting message",t,e),this._postMessage(this._messageFactory.createBroadcastMessage(e,t))}sendResponseMessage(e,t){var i=2void 0===e.dst?(this._countInvalidMessage(e,"no-destination-proxy"),void this._log.error("Received invalid RemoteMethodCallMessage message",JSON.stringify(e),"Ignoring it....")):void t._handle(u(new nt,e.payload)))}_countInvalidMessage(e,t){var i=e=>null!=e;void 0!==this._metrics&&!function(e,t){return e.counter("instance.message.invalid.count",1{var t=e.cacheId;s.has(t)||(e=i.getResponseFor(e.integrationId))&&(this._clientStore.storeResponseV2(t,e,i.timestamp,r),s.add(t))}),this._trueLinkAdapter.setPrivacy(null===(e=i.getGenericResponse())||void 0===e?void 0:e.privacy)}clearAll(e){this._clientStore.clearResponse(),this._clientStore.clearDateTime(),e.forEach(e=>{e=e.cacheId;this._clientStore.clearResponseV2(e)}),this._clientStore.clearHashedConsentData(),this._trueLinkAdapter.clearPrivacy(),this._clientStore.clearExtensions()}getCachedResponse(e){e=this._clientStore.getStoredResponseV2(e);if(e)return new ut(e.response,e.responseTimestamp,e.nb,e.consents)}getCachedExtensions(){return this._clientStore.getExtensions()}storeExtensions(e){var t=b(e.ttl)?e.ttl/86400:dt.DEFAULT.EXTENSIONS.expiresDays,t=new lt(dt.DEFAULT.EXTENSIONS.name,t);return this._clientStore.storeExtensions(e,t)}}class ut{constructor(e,t){var i=2e}isStale(){return!this.timestamp||this._isOlderThanSec(1209600)}isResponseComplete(){return D(this.response)&&C(this.response.universal_uid)&&C(this.response.signature)}isValid(){return this.isResponseComplete()&&!this.isStale()}getMaxAge(){var e,t;return null===(e=this.response)||void 0===e||null===(t=e.cache_control)||void 0===t?void 0:t.max_age_sec}getAgeSec(){return(Date.now()-this.timestamp)/1e3|0}}const gt="_exp";class pt{constructor(e){var t=1{e.removeItem(t)};this._replicas.forEach(e),this._lastKeyOperation[t]=e}setItem(t,i){this._primaryStorage.setItem(t,i);var e=e=>{e.setItem(t,i)};this._replicas.forEach(e),this._lastKeyOperation[t]=e}addReplica(t){Object.values(this._lastKeyOperation).forEach(e=>e(t)),this._replicas.push(t)}getKeysWithPrefix(e){return this._primaryStorage.getKeysWithPrefix(e)}}class It{constructor(e){var t=1{const s=e.map(e=>{const t=e.cacheData;var i=null===t||void 0===t||null===(s=t.response)||void 0===s?void 0:s.signature,r=null===t||void 0===t?void 0:t.nb,s=null===t||void 0===t?void 0:t.getMaxAge();return this._createRequest(l,e,i,r,s,n,d)}),o=this._log,a=this._metrics,c=this;return new Promise((t,i)=>{const r=Ce();var e="".concat("https://id5-sync.com").concat("/gm/v3");o.info("Fetching ID5 ID from:",e,s),function(r,s,n,o,e){o=3{i.setRequestHeader(t,e)}),o.preflight&&i.setRequestHeader("X-Requested-With","XMLHttpRequest"),i.setRequestHeader("Content-Type",o.contentType||"text/plain"),"POST"===l&&n?i.send(n):i.send()}catch(e){a.error("ajax","xhr construction",e)}}(e,{success:function(e){o.info("Success at fetch call:",e),r.record(function(e,t){return Qe(e,"success",1{var t=g(e,2),e=t[0],t=t[1];E(i[e])&&(d[t]=i[e])});e=i.abTesting;e&&!0===e.enabled&&(d.ab_testing={enabled:!0,control_group_pct:e.controlGroupPct});e=i.invalidSegmentsCount;return e&&0void 0!==e.find(e=>t.getId()===e)&&t.canDoCascade()).sort((e,t)=>{function i(e){var t;return(null===(e=e.getFetchIdData().refererInfo)||void 0===e||null===(t=e.stack)||void 0===t?void 0:t.length)||Number.MAX_SAFE_INTEGER}return i(e)-i(t)});if(0{const e=this._consentManager.localStorageGrant("fetch-before-request");if(o.info("Local storage grant",e),e.allowed){var i=this._store.hasConsentChanged(t);e.isDefinitivelyAllowed()&&this._store.storeConsent(t);var r=ft.checkIfAccessible();const c=new Map;let a=n;const s=this._followers.map(e=>{var t=e.getId(),i=(this._followersRequests[t]||0)+1,r=this._properties.id,s=!0===this._refreshRequired[e.getId()];a=a||s;var n,o=e.getCacheId();return c.has(o)||(n=this._store.getCachedResponse(o))&&c.set(o,n),h(h({},e.getFetchIdData()),{},{integrationId:t,requestCount:i,refresh:s,role:r===e.getId()?"leader":e.type||"follower",cacheId:o,cacheData:c.get(o),sourceVersion:e.getSourceVersion(),source:e.getSource()})});i||a?(o.info("Decided to fetch a fresh ID5 ID",{consentHasChanged:i,shouldRefresh:a}),o.info("Fetching ID5 ID (forceFetch:".concat(n,")")),this._inProgressFetch=!0,this._firstFetchTriggered=!0,this._fetcher.fetchId(s,t,r).then(e=>{this._handleRefreshResult(s,c,t,e),this._handleFetchCompleted()}).catch(e=>{this._handleFailed(e),this._handleFetchCompleted()})):(o.info("Not decided to refresh ID5 ID",{consentHasChanged:i,shouldRefresh:a}),this._handleFetchCompleted())}else o.info("No legal basis to use ID5",t),this._store.clearAll(this._followers.map(e=>({cacheId:e.getCacheId()}))),this._handleCancel("No legal basis to use ID5")})}_waitForConsent(){const t=this._log,e=this._consentManager,i=this._metrics;t.info("Waiting for consent");const r=i.timer("fetch.consent.wait.time");return e.getConsentData().then(e=>(t.info("Consent received",e),r&&r.recordNow(),e))}start(){!0!==this._started&&(this._getId(!1),this._started=!0)}refreshUid(){var e=0e.getId()===t))&&this._provisionFromCache(i)),function(e,t,i){return e.counter("refresh.call.count",h({target:t},2e.getDeclaredConsentSource()).filter(e=>e!==te.none));var i=e.source||te.cmp,r=1===s.size&&s.has(te.partner);this._awaitedConsentFrom?this._awaitedConsentFrom===t?(this._consentManager.setConsentData(e),this._awaitedConsentFrom=void 0):this._handleIgnoredConsent(e,"awaited"):i!==te.partner||r?this._consentManager.setConsentData(e):this._handleIgnoredConsent(e,"partner")}}_handleIgnoredConsentUpdate(e){try{const r=this._consentManager._consentDataHolder.getValue();if(r){const s={},n=ne.createFrom(e);Object.values(ee).forEach(e=>{var t,i;n.apiTypes.includes(e)&&r.apiTypes.includes(e)?(t=JSON.stringify(r.getApiTypeData(e)),i=JSON.stringify(n.getApiTypeData(e)),s[e]=t===i?"same":"different"):n.apiTypes.includes(e)?s[e]="added":r.apiTypes.includes(e)&&(s[e]="missed")}),function(e,t){return e.counter("leader.consent.change.count",1i[e]=!0),function(e,t){return e.counter("leader.consent.ignore.count",1e.getId()===t);var r=i.getCacheId();i.updateFetchIdData(e);e=i.getCacheId();e!==r&&(this._log.info("Follower",i.getId(),"cacheId changed from",r," to",e,"required refresh"),this._refreshRequired[i.getId()]=!0)}addFollower(t){const e=this._log;var i=void 0===this._followers.find(e=>e.getCacheId()===t.getCacheId());this._followers.push(t),e.debug("Added follower",t.getId(),"cacheId",t.getCacheId()),this._window!==t.getWindow()&&(r=t.getStorage(),e.debug("Adding follower's",t.getId(),"storage as replica"),this._leaderStorage.addReplica(r));var r=this._provisionFromCache(t);let s=new Et;return!0===this._firstFetchTriggered&&(s.lateJoiner=!0,s.uniqueLateJoiner=i,r&&this._callRefresh({forceFetch:!0})),s}_provisionFromCache(e){var t=this._cachedIdProvider.provisionFromCache(e);return this._refreshRequired[e.getId()]=t.refreshRequired,t.provisioned&&this._store.incNb(t.cacheId),t.refreshRequired}getProperties(){return this._properties}_handleFetchCompleted(){this._inProgressFetch=void 0,this._queuedRefreshArgs&&(this._callRefresh(...this._queuedRefreshArgs),this._queuedRefreshArgs=void 0)}_handleFailed(e){this._log.error("Fetch id failed",e);var t,i=f(this._followers);try{for(i.s();!(t=i.n()).done;){const r=t.value;r.notifyFetchUidCanceled({reason:"error"})}}catch(e){i.e(e)}finally{i.f()}}}class Pt extends At{constructor(e,t){super(),d(this,"_messenger",void 0),d(this,"_leaderInstanceProperties",void 0),this._messenger=e,this._leaderInstanceProperties=t}_sendToLeader(e,t){this._messenger.callProxyMethod(this._leaderInstanceProperties.id,st.LEADER,e,t)}updateConsent(e,t){this._sendToLeader("updateConsent",[e,t])}refreshUid(e,t){this._sendToLeader("refreshUid",[e,t])}updateFetchIdData(e,t){this._sendToLeader("updateFetchIdData",[e,t])}getProperties(){return this._leaderInstanceProperties}}class Ot extends At{constructor(){super(...arguments),d(this,"_callsQueue",[]),d(this,"_assignedLeader",void 0)}updateConsent(e,t){this._callOrBuffer("updateConsent",[e,t])}updateFetchIdData(e,t){this._callOrBuffer("updateFetchIdData",[e,t])}refreshUid(e,t){this._callOrBuffer("refreshUid",[e,t])}addFollower(e){return this._callOrBuffer("addFollower",[e])}getProperties(){if(this._assignedLeader)return this._assignedLeader.getProperties()}assignLeader(e){this._assignedLeader=e;var t,i=f(this._callsQueue);try{for(i.s();!(t=i.n()).done;){var r=t.value;this._callAssignedLeader(r.name,r.args)}}catch(e){i.e(e)}finally{i.f()}this._callsQueue=[]}_callOrBuffer(e,t){if(this._assignedLeader)return this._callAssignedLeader(e,t);this._callsQueue.push({name:e,args:t})}_callAssignedLeader(e,t){return this._assignedLeader[e](...t)}}class Rt extends _t{constructor(e,t){super(),d(this,"_messenger",void 0),d(this,"_destinationId",void 0),this._messanger=e,this._destinationId=t}getItem(){}removeItem(e){this._remoteCall("removeItem",[e])}setItem(e,t){this._remoteCall("setItem",[e,t])}_remoteCall(e,t){this._messanger.callProxyMethod(this._destinationId,st.STORAGE,e,t)}}class xt extends yt{constructor(e,t){var i=2{this._resolve=e})}set(e){this._hasValue?this._valuePromise=Promise.resolve(e):(this._hasValue=!0,this._resolve(e)),this._value=e}getValuePromise(){return this._valuePromise}hasValue(){return this._hasValue}getValue(){return this._value}}class Ft extends class{getConsentData(){}localStorageGrant(){}setStoredPrivacy(){}}{constructor(e,t,i,r,s){super(),d(this,"_consentDataHolder",void 0),d(this,"storedPrivacyData",void 0),d(this,"localStorage",void 0),d(this,"_forceAllowLocalStorageGrant",void 0),this._log=r,this.localStorage=e,this.storageConfig=t,this._consentDataHolder=new Lt,this._forceAllowLocalStorageGrant=i,this._metrics=s}isForceAllowLocalStorageGrant(){return this._forceAllowLocalStorageGrant}resetConsentData(e){this._consentDataHolder.reset(),this.storedPrivacyData=void 0,this._forceAllowLocalStorageGrant=e}localStorageGrant(){var e=0h(h({},e),{},{response:t,responseTimestamp:i,consents:r}))}getStoredResponseV2(e){return this._getObject(this.storageConfig.ID5_V2.withNameSuffixed(e))}incNbV2(e){let i=1{var t=Math.max(0,b(null==e?void 0:e.nb)?Math.round(e.nb)+i:i);return h(h({},e),{},{nb:t})})}static storedDataMatchesCurrentData(e,t){return null==e||e===t}storedConsentDataMatchesConsentData(e){return Nt.storedDataMatchesCurrentData(this.getHashedConsentData(),e.hashCode())}getExtensions(){return this._getObject(this.storageConfig.EXTENSIONS)}storeExtensions(e,t){return this._updateObject(t,()=>e)}clearExtensions(){return this.clear(this.storageConfig.EXTENSIONS)}}class Ut{constructor(e,t,i){d(this,"_metrics",void 0),d(this,"_log",void 0),d(this,"_store",void 0),this._metrics=e,this._log=t,this._store=i}static getChunkUrl(e,t){return"https://d".concat(e,".eu-").concat(t,"-id5-sync.com")}submitExtensionCall(t,i){var e=2{if(e.ok)return r.record($e(this._metrics,i,!0)),e.json();r.record($e(this._metrics,i,!1));e="The call to get extensions at ".concat(t," was not ok, status: ").concat(e.status,", statusText: ").concat(e.statusText);return this._log.warn(e),Promise.reject(new Error(e))}).catch(e=>(r.record($e(this._metrics,i,!1)),this._log.warn("Got error from ".concat(t," endpoint"),e),{}))}gatherChunks(e,i){if(e){let t=Ce();return Promise.all(Array.from({length:i.length},(e,t)=>{t=Ut.getChunkUrl(t,i.urlVersion);return fetch(t).then(e=>{if(e.ok)return e.text();throw new Error("The call to get ".concat(i.name," was not ok, status: ").concat(e.status,", statusText: ").concat(e.statusText))})})).then(e=>(t.record($e(this._metrics,i.name,!0)),{[i.name]:e,[i.name+"Version"]:"".concat(i.version)})).catch(e=>(t.record($e(this._metrics,i.name,!1)),this._log.warn("Got error when getting ".concat(i.name),e),{}))}return Promise.resolve({})}gather(e){var t=this._store.getCachedExtensions();if(void 0!==t)return Promise.resolve(t);let i=Ce(),r=this._submitBounce(e);return this.submitExtensionCall("https://lb.eu-1-id5-sync.com/lb/v1","lb").then(e=>{var t=this.getChunksEnabled(e);return Promise.allSettled([Promise.resolve(e),this.gatherChunks(t,Ut.CHUNKS_CONFIGS.devChunks),this.gatherChunks(t,Ut.CHUNKS_CONFIGS.groupChunks),r])}).then(e=>{i.record($e(this._metrics,"all",!0));let t=Ut.DEFAULT_RESPONSE;return e.forEach(e=>{e.value&&(t=h(h({},t),e.value))}),this._store.storeExtensions(t),t}).catch(e=>(i.record($e(this._metrics,"all",!1)),this._log.error("Got error ".concat(e," when gathering extensions data")),Ut.DEFAULT_RESPONSE))}_submitBounce(e){return e.some(e=>{return E(null===(e=e.cacheData)||void 0===e?void 0:e.signature)})?Promise.resolve({}):this.submitExtensionCall("https://id5-sync.com/bounce","bounce",{credentials:"include"})}getChunksEnabled(e){e=null==e?void 0:e.chunks;return 0!==e&&e}}d(Ut,"CHUNKS_CONFIGS",Object.freeze({devChunks:{name:"devChunks",urlVersion:3,length:8,version:4},groupChunks:{name:"groupChunks",urlVersion:4,length:8,version:4}})),d(Ut,"DEFAULT_RESPONSE",{lbCDN:"%%LB_CDN%%"});const kt={createExtensions:function(e,t,i){return new Ut(e,t,i)}},Vt=Object.freeze({UNKNOWN:"unknown",LEADER:"leader",FOLLOWER:"follower"}),Gt=Object.freeze({MULTIPLEXING:"multiplexing",SINGLETON:"singleton",MULTIPLEXING_PASSIVE:"multiplexing-passive"}),Mt=Object.freeze({AWAITING_SCHEDULE:"awaiting_schedule",SKIPPED:"skipped",SCHEDULED:"scheduled",COMPLETED:"completed",CANCELED:"canceled"});class jt{constructor(e,t,i){d(this,"properties",void 0),d(this,"knownState",void 0),d(this,"_joinTime",void 0),d(this,"_window",void 0),this.properties=e,this.knownState=t,this._window=i,this._joinTime=performance.now()}getId(){return this.properties.id}isMultiplexingPartyAllowed(){var e=null===(e=this.knownState)||void 0===e?void 0:e.operatingMode;return e===Gt.MULTIPLEXING||e===Gt.MULTIPLEXING_PASSIVE}isLeaderCapable(){var e;return(null===(e=this.knownState)||void 0===e?void 0:e.operatingMode)===Gt.MULTIPLEXING}isPassive(){var e;return(null===(e=this.knownState)||void 0===e?void 0:e.operatingMode)===Gt.MULTIPLEXING_PASSIVE}getInstanceMultiplexingLeader(){var e,t;if((null===(e=this.knownState)||void 0===e?void 0:e.operatingMode)===Gt.MULTIPLEXING)return null===(e=this.knownState)||void 0===e||null===(t=e.multiplexing)||void 0===t?void 0:t.leader}getWindow(){return this._window}}class Wt{constructor(e,t,i,r){d(this,"properties",void 0),d(this,"_messenger",void 0),d(this,"_knownInstances",new Map),d(this,"role",void 0),d(this,"_mode",void 0),d(this,"_metrics",void 0),d(this,"_logger",void 0),d(this,"_window",void 0);var s=E(globalThis)&&E(globalThis.crypto)&&S(globalThis.crypto.randomUUID)?globalThis.crypto.randomUUID():"".concat(1e6*Math.random()|0);this.properties=u({id:s,version:"1.0.37",href:null===(s=e.location)||void 0===s?void 0:s.href,domain:null===(s=e.location)||void 0===s?void 0:s.hostname},t),this.role=Vt.UNKNOWN,this._metrics=i,this._loadTime=performance.now(),this._logger=new Ht(r,this),this._window=e,this._dispatcher=new Ve(this._logger),this._followerRole=new bt(this._window,this.properties,this._dispatcher,this._logger,this._metrics)}updateConfig(e){u(this.properties,e)}register(e){try{this.updateConfig(e),this.init(),this._messenger.broadcastMessage(this._createHelloMessage(!1),rt.TYPE)}catch(e){this._logger.error("Failed to register integration instance",e)}return this}init(){let r=this,s=r._window;r._mode=Gt.MULTIPLEXING_PASSIVE,r._messenger=new at(r.properties.id,s,r._logger,r._metrics),r._messenger.onAnyMessage((e,t)=>{var i=Date.now()-e.timestamp|0;!function(e,t){return e.timer("instance.message.delivery.time",1{let i=u(new rt,e.payload);void 0===i.isResponse&&(i.isResponse=void 0!==e.dst),r._handleHelloMessage(i,e,t)})}_handleHelloMessage(e,t,i){var r=e.isResponse;const s=new jt(e.instance,e.instanceState,i);this._knownInstances.get(s.getId())?this._logger.debug("Instance already known",s.getId()):(this._knownInstances.set(s.getId(),s),r||this._messenger.sendResponseMessage(t,this._createHelloMessage(!0),rt.TYPE),this._logger.debug("Instance joined",s.getId()),this._doFireEvent(Ue.ID5_INSTANCE_JOINED,s.properties),this._onInstanceDiscovered(e,s))}unregister(){this._logger.info("Unregistering"),this._messenger&&this._messenger.unregister()}on(e,t){return this._dispatcher.on(e,t),this}_onInstanceDiscovered(){}_createHelloMessage(){var e=0e.properties)};return new rt(this.properties,e,t)}_doFireEvent(e){for(var t=arguments.length,i=new Array(1{t._timeoutId&&(t._timeoutId=void 0,t._instance._doElection(),t._closeWithState(Mt.COMPLETED))},t._delayMs),t._state=Mt.SCHEDULED,t._scheduleTime=performance.now()}skip(){this._closeWithState(Mt.SKIPPED)}cancel(){this._timeoutId&&(clearTimeout(this._timeoutId),this._timeoutId=void 0),this._closeWithState(Mt.CANCELED)}_closeWithState(e){this._state=e,this._closeTime=performance.now()}}class zt extends Wt{constructor(e,t,i,r,s,n,o){super(e,t,r,s),d(this,"_lastJoinedInstance",void 0),d(this,"_leader",void 0),d(this,"_remoteCallsToLeaderHandler",void 0),d(this,"_instanceCounters",void 0),d(this,"_election",void 0),d(this,"_storage",void 0),d(this,"_trueLinkAdapter",void 0),d(this,"_cachedIdProvider",void 0),this._leader=new Ot,this._remoteCallsToLeaderHandler=new Ot,this._instanceCounters=new Bt(r,this.properties),this._storage=i,this._trueLinkAdapter=n,this._cachedIdProvider=new Dt("self",new ht(o,n),this._logger,this._metrics),this._election=new Jt(this)}init(){super.init();var e,t=this;t._mode=!0===t.properties.singletonMode?Gt.SINGLETON:Gt.MULTIPLEXING,t._instanceCounters.addInstance(t.properties),function(i){const r=i._metrics;[100,200,500,1e3,2e3,3e3,5e3].forEach(t=>{setTimeout(()=>{var e=((null===(e=i._knownInstances)||void 0===e?void 0:e.size)||0)+1;r.summary("instance.partySize",{after:t,electionState:i._election._state}).record(e)},t)})}(t),t._messenger.onProxyMethodCall(new ot(t._logger).registerTarget(st.LEADER,t._remoteCallsToLeaderHandler).registerTarget(st.FOLLOWER,t._followerRole).registerTarget(st.STORAGE,t._storage)),t._mode===Gt.SINGLETON?(t._election.skip(),t._onLeaderElected(t.properties)):t._mode===Gt.MULTIPLEXING&&(e=t.properties.electionDelayMSec||500,t._election.schedule(e))}_onInstanceDiscovered(e,t){e=e.isResponse;this._lastJoinedInstance=t,this._instanceCounters.addInstance(t.properties),function(e,t){return e.timer("instance.join.delay.time",1o.localStorageGrant("client-store"),s,n,t),this._trueLinkAdapter),n=new wt(i,t,kt.createExtensions(i,t,s));const a=new Tt(this._window,e,r,s,o,i,t,n);a.addFollower(this._followerRole),this._leader.assignLeader(a),this._remoteCallsToLeaderHandler.assignLeader(a),this._mode===Gt.MULTIPLEXING&&Array.from(this._knownInstances.values()).filter(e=>e.isMultiplexingPartyAllowed()).map(e=>a.addFollower(new xt(e,this._messenger,t,e.isPassive()?Ct.PASSIVE:Ct.STANDARD))),a.start()}_followRemoteLeader(e){this._leader.assignLeader(new Pt(this._messenger,e)),this._remoteCallsToLeaderHandler.assignLeader(new Xt(e.id,this._logger,this._metrics)),this._logger.info("Following remote leader ",e)}updateConsent(e){this._leader.updateConsent(e,this.properties.id)}updateFetchIdData(e){this._leader.updateFetchIdData(this.properties.id,e),u(this.properties.fetchIdData,e)}refreshUid(e){this._leader.refreshUid(e,this.properties.id)}_doElection(){var e=this._election;const t=this._knownInstances;let i=Array.from(t.values()).filter(e=>e.isMultiplexingPartyAllowed()&&e.isLeaderCapable()).map(e=>e.properties);i.push(this.properties),this._onLeaderElected(function(e){if(!e||0===e.length)return;e=e.sort((e,t)=>{let i=-(0|o(e.version,t.version));var r,s,n;return 0===i&&(i=e.source.localeCompare(t.source),0===i&&(i=-(0|o(e.sourceVersion,t.sourceVersion))),0===i&&(s=(null===(s=e.fetchIdData)||void 0===s||null===(r=s.refererInfo)||void 0===r?void 0:r.numIframes)||Number.MAX_SAFE_INTEGER,n=(null===(r=t.fetchIdData)||void 0===r||null===(n=r.refererInfo)||void 0===n?void 0:n.numIframes)||Number.MAX_SAFE_INTEGER,i=s-n),0===i&&(i=e.id.localeCompare(t.id))),i});return e[0]}(i));var r=this._lastJoinedInstance;r&&!function(e,t){return e.timer("instance.lastJoin.delay",h({},1e.eid)}onRefresh(e,t){if(!M(e))throw new Error("onRefresh expects a function");this._refreshCallback&&this._refreshCallback.disableWatchdog();var i=!0===this._isRefreshing&&!1===this._isRefreshingWithFetch&&this._userIdAvailable;return this._refreshCallback=new Ge("onRefresh",this._log,this._metrics,e,t,i,()=>{this._isRefreshing=!1,this._isRefreshingWithFetch=!1},this),this}collectEvent(t,i){const r=e=>{e=new Request("https://id5-sync.com/event",{method:"POST",mode:"no-cors",body:JSON.stringify({partnerId:this.config.getOptions().partnerId,id5id:e,eventType:t,metadata:i})});return this._log.info("Sending event",e),fetch(e).catch(e=>this._log.error("Error while sending event to ID5 of type "+t,e))};return this._userIdAvailable?r(this._userId):this._userIdAvailablePromise.then(e=>r(e))}constructor(e,t,i,r,s,n,o,a,c){super(e,r,n,o,a,"api",{canDoCascade:!e.hasCreativeRestrictions()}),d(this,"clientStore",void 0),d(this,"consentManagement",void 0),d(this,"_consentDataProvider",void 0),d(this,"_trueLinkAdapter",void 0),this.clientStore=t,this.consentManagement=i,this._consentDataProvider=s,this._trueLinkAdapter=c}bootstrap(){super.bootstrap();const i=this._ref();this._multiplexingInstance.on(Ne.CASCADE_NEEDED,e=>{const t=i.deref();t&&t._doCascade(e)})}init(){const e=super.init(),t=this._submitRefreshConsent().then(e=>{e&&this.consentManagement.setConsentData(e)});return e.then(()=>{this._multiplexingInstance.lookupForCachedId().provisioned||(this._log.info("Couldn't find cached userId. Will try again when consent is resolved"),t.then(()=>{this._log.info("Consent resolved. Looking for cached id again"),this._multiplexingInstance.lookupForCachedId()}))}),Promise.allSettled([e,t])}refreshId(t,e){let i,r;this._log.info("ID refresh requested (force=".concat(t,") with additional options "),e);try{this._isRefreshing=!0,this._isRefreshingWithFetch=t,this.config.updOptions(e);var s=this.config.getOptions();const n=s.allowLocalStorageWithoutConsentApi||s.debugBypassConsent;i=this._gatherFetchIdData().then(e=>{this._multiplexingInstance.updateFetchIdData(e),this._multiplexingInstance.refreshUid({resetConsent:!0,forceAllowLocalStorageGrant:n,forceFetch:t}),r=this._submitRefreshConsent()}),function(e,t,i){return e.counter("refresh.call.count",h({target:t},2super._gatherFetchIdData,r=this;return s(function*(){var e=r.config.getOptions(),t=yield Ke.gatherUaHints(e.disableUaHints,r._log);return h(h({},yield i().call(r)),{},{uaHints:t,pd:e.pd,partnerUserId:e.partnerUserId,allowedVendors:null===(t=e.consentData)||void 0===t?void 0:t.allowedVendors,consentSource:"iab"===e.cmpApi&&!0!==e.debugBypassConsent?te.cmp:te.partner,trueLink:r._trueLinkAdapter.getTrueLink(),att:e.att})})()}_submitRefreshConsent(){var n=this;return s(function*(){var e=n.config.getOptions();let t=Ce();var i=e.debugBypassConsent?"bypass":e.cmpApi;let r;try{r=yield n._consentDataProvider.refreshConsentData(e.debugBypassConsent,e.cmpApi,e.consentData);const s={};r.apiTypes.forEach(e=>s[e]=!0),t.record(Ee(n._metrics,i,h({success:!0},s))),n._multiplexingInstance.updateConsent(r)}catch(e){n._log.error("Couldn't get consent data",e),t.record(Ee(n._metrics,i,{success:!1,error:e.message}))}return r})()}localStorageGrant(){return this.clientStore.localStorageGrant()}}class Qt{isBooted(){return D(window.id5Bootstrap)}getTrueLink(){return this.isBooted()?window.id5Bootstrap.getTrueLinkInfo():{booted:!1}}setPrivacy(e){this.isBooted()&&window.id5Bootstrap.setPrivacy&&window.id5Bootstrap.setPrivacy(e)}clearPrivacy(){this.setPrivacy(void 0)}}const $t=(ue=window,function(){try{var i=Zt(),r=i.length-1,s=null!==i[r].location||0p.localStorageGrant("instance-client-store"),o,c,i);var l=new Qt,d=Yt.createInstance(window,i,s,n,l,_),h=new Fe(s,i),u=new Be(t._referer,t._version,t._isUsingCdn);const v=new Kt(g,_,p,s,h,i,d,u,l);return v.bootstrap(),v.init(),_.scheduleGC(s),v}catch(e){i.error("Exception caught during init()",e)}}refreshId(e){var t=1new le(o,{sampling:n}).publish(e,t):e=>e));null!=s&&s.publishAfterLoadInMsec&&0