PageSourceSearch

https://www.mumsnet.com/build/assets/meta-pixel-events-lcDa2LQI.js

js mumsnet.com collected 2026-10-01 10:35:35 UTC 148,006 bytes, 3 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/esm-Dlxfe34J.js","assets/json-query-BNy9RHg4.js","assets/observers-DVg-uRJo.js"])))=>i.map(i=>d[i]);
2(function(){try{var e=typeof window<`u`?window:typeof global<`u`?global:typeof globalThis<`u`?globalThis:typeof self<`u`?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]=`9b880aa6-b138-4d05-a6c7-a4ecc9d7eb21`,e._sentryDebugIdIdentifier=`sentry-dbid-9b880aa6-b138-4d05-a6c7-a4ecc9d7eb21`)}catch{}})();import{J as e,L as t,i as n,wn as r}from"./dist-DViRp4pB.js";import{A as i,B as a,G as o,H as s,P as c,T as l,U as u,W as d,_ as f,b as p,j as m,n as h,x as g,y as _}from"./helpers-BbGwLwYt.js";import{t as v}from"./useFeature-BghRU3ys.js";import{a as y,r as b,s as x}from"./consent-CB6N6ypq.js";import{n as S,r as C,t as w}from"./classPrivateFieldSet2-BpGEd64M.js";import{n as T}from"./tailwind-BdxN9Y1q.js";import{n as E,r as D,t as O}from"./tag-data-Rq-cAmkU.js";import{a as k,c as ee,i as te,l as ne,n as re,o as A,r as j,s as M,u as ie}from"./click-id-BskgSvSs.js";import{t as ae}from"./talk-page-QauGri7G.js";import{a as oe,c as se,i as N,l as P,n as F,o as I,r as L,s as R,u as z}from"./json-query-BNy9RHg4.js";import{C as ce,S as le,T as ue,_ as de,a as fe,b as pe,c as me,d as he,f as ge,g as _e,h as ve,l as ye,m as be,n as xe,o as Se,p as Ce,s as we,t as Te,u as Ee,v as De,w as Oe,x as ke,y as Ae}from"./esm-BiFo4-4P.js";import{t as je}from"./preload-helper-Bc_9wxK1.js";import{t as Me}from"./once-per-session-CUTUIF3h.js";var Ne=a(),B=null,Pe=null,Fe=(e=void 0)=>({identity:Math.random().toString(36).substring(2,15),duplicated_from:e}),Ie=()=>(B||(B=t(`tab-identity`,Fe()),Pe=new Promise(e=>{if(!n?.BroadcastChannel)return e(r(B));let t=new n.BroadcastChannel(`tab-identity`),i=setTimeout(()=>{e(r(B)),i=null},100);t.onmessage=n=>{switch(n.data.type){case`ping`:t.postMessage({type:`pong`,identity:B.value.identity});break;case`pong`:n.data.identity===B.value.identity&&(B.value=Fe(n.data.identity),i&&(clearTimeout(i),i=null,e(r(B))))}},t.postMessage({type:`ping`})})),c(r(B),Pe)),V,H=new WeakMap,Le=new WeakMap,Re=new WeakMap,ze=new WeakMap,Be=new WeakMap,Ve=new WeakMap,U=new WeakSet,W=class e{constructor(){if(o(this,U),C(this,H,null),C(this,Le,null),C(this,Re,new s(`cfd`)),C(this,ze,Ie()),C(this,Be,n?.performance?.timeOrigin??Date.now()),C(this,Ve,t(`tabStartTime:${Ie().value.identity}`,n?.performance?.timeOrigin??Date.now())),it._)return it._;it._=this,u(U,this,Ze).call(this)}static getInstance(){return it._||new e,it._}static peekCurrentSessionId(){var e;return((e=it._)==null?void 0:S(H,e))?.id??null}static replayLastEvent(e){let t=at._.get(e);return t?(n?.dispatchEvent(new CustomEvent(e,{detail:t})),!0):!1}get currentSessionId(){return S(H,this)?.id??null}initialize(){u(U,this,Qe).call(this),u(U,this,tt).call(this),u(U,this,nt).call(this),w(H,this,u(U,this,Ge).call(this)),u(U,this,$e).call(this),u(U,this,rt).call(this)}};V=W;function He(e,t={}){n?.mnAmpEvent({event_type:e,event_properties:{cfd:{session:S(H,this),...t}}}),u(U,this,Ue).call(this,e,t)}function Ue(e,t){let r=ot._.get(e);if(!r)return;let a={session:S(H,this),...t};at._.set(r,a),i(()=>n?.dispatchEvent(new CustomEvent(r,{detail:a})))}function We(e=void 0){return e??=S(H,this)?.id,`${V.SESSION_KEY_PREFIX}${e}`}function Ge(){let e=crypto.randomUUID?.()??Date.now().toString(36),n=Date.now(),r={id:e,startedAt:n,lastHeartbeatAt:n,isVisible:document.visibilityState===`visible`,tab:{adRenderCount:t(`adRenderCount:${S(ze,this).value.identity}`,0).value,primisRenderCount:t(`primisRenderCount:${S(ze,this).value.identity}`,0).value,age:u(U,this,qe).call(this)},page:{adRenderCount:0,primisRenderCount:0,age:u(U,this,Ke).call(this)}};return i(()=>localStorage.setItem(u(U,this,We).call(this,e),JSON.stringify(r))),r}function Ke(){return n?.performance?.now?n.performance.now():Date.now()-S(Be,this)}function qe(){return Date.now()-S(Ve,this).value}function Je(){let e=[];return i(()=>{Object.keys(localStorage).forEach(t=>{if(!t.startsWith(V.SESSION_KEY_PREFIX))return;let n=i(()=>JSON.parse(localStorage.getItem(t)));n&&e.push(n)})}),e}function Ye(e){if(!S(H,this))return;S(Re,this).debug(`Patch session`,e);let t=(0,Ne.merge)({},S(H,this),e);w(H,this,t),i(()=>localStorage.setItem(u(U,this,We).call(this,t.id),JSON.stringify(t)))}function Xe(e){S(H,this)&&(u(U,this,He).call(this,`page_clean_exit`,{unload_reason:e,time_on_page_ms:performance.now()}),u(U,this,et).call(this))}function Ze(){n?.addEventListener(`pagehide`,()=>u(U,this,Xe).call(this,`pagehide`)),n?.addEventListener(`beforeunload`,()=>u(U,this,Xe).call(this,`unload`)),n?.googletag?.cmd.push(()=>{let e=0,r=t(`adRenderCount:${S(ze,this).value.identity}`,0);n?.googletag?.pubads().addEventListener(`slotRenderEnded`,()=>{e++,r.value++,u(U,this,Ye).call(this,{page:{adRenderCount:e},tab:{adRenderCount:r.value}})})}),(()=>{let e=0,r=t(`primisRenderCount:${S(ze,this).value.identity}`,0);n?.addEventListener(`mn:external-ad-render`,t=>{t.detail?.metadata?.advertiserId===`primis`&&(e++,r.value++,u(U,this,Ye).call(this,{page:{primisRenderCount:e},tab:{primisRenderCount:r.value}}))})})()}function Qe(){i(()=>localStorage.removeItem(V.LEGACY_SESSION_KEY))}function $e(){let e=V.EVENTS.SESSION_STARTED,t={session:S(H,this)};at._.set(e,t),i(()=>n?.dispatchEvent(new CustomEvent(e,{detail:t})))}function et(e){e??=S(H,this)?.id;let t=u(U,this,We).call(this,e);i(()=>localStorage.removeItem(t)),e===S(H,this)?.id&&w(H,this,null)}function tt(){let e=u(U,this,Je).call(this),t=Date.now();
2e.forEach(e=>{let n=t-e.lastHeartbeatAt;n<V.STALE_THRESHOLD_MS||(u(U,this,He).call(this,`page_stale_exit`,{session:e,age_ms:n}),u(U,this,et).call(this,e.id))})}function nt(){let e=u(U,this,Je).call(this),t=Date.now();e.length&&e.forEach(e=>{let n=t-e.lastHeartbeatAt;if(n>=V.STALE_THRESHOLD_MS){u(U,this,et).call(this,e.id);return}let r=V.HEARTBEAT_INTERVAL_MS*2;e.isVisible&&(n<r||(u(U,this,He).call(this,`page_unclean_exit`,{session:e,age_ms:n}),u(U,this,et).call(this,e.id)))})}function rt(){let e=document.visibilityState===`visible`,t=performance.now(),r=()=>{t=performance.now(),w(Le,this,setInterval(()=>{if(!e)return;let n=performance.now(),r=n-t-V.HEARTBEAT_INTERVAL_MS;t=n,u(U,this,Ye).call(this,{lastHeartbeatAt:Date.now(),page:{age:u(U,this,Ke).call(this)},tab:{age:u(U,this,qe).call(this)}}),r>=V.FREEZE_THRESHOLD_MS&&u(U,this,He).call(this,`page_freeze`,{lag_ms:r,heartbeat_interval_ms:V.HEARTBEAT_INTERVAL_MS})},V.HEARTBEAT_INTERVAL_MS))},i=()=>{clearInterval(S(Le,this)),u(U,this,Ye).call(this,{lastHeartbeatAt:Date.now(),page:{age:u(U,this,Ke).call(this)},tab:{age:u(U,this,qe).call(this)}})};n?.addEventListener(`visibilitychange`,()=>{let t=e,n=document.visibilityState===`visible`;if(e=n,u(U,this,Ye).call(this,{isVisible:n}),!t&&n)return r();t&&!n&&i()}),e&&r()}var it={_:null},at={_:new Map};d(W,`EVENTS`,Object.freeze({FREEZE:`mn:crashfreeze:freeze`,UNCLEAN_EXIT:`mn:crashfreeze:uncleanexit`,CLEAN_EXIT:`mn:crashfreeze:cleanexit`,STALE_EXIT:`mn:crashfreeze:staleexit`,SESSION_STARTED:`mn:crashfreeze:sessionstarted`}));var ot={_:new Map([[`page_freeze`,`mn:crashfreeze:freeze`],[`page_unclean_exit`,`mn:crashfreeze:uncleanexit`],[`page_clean_exit`,`mn:crashfreeze:cleanexit`],[`page_stale_exit`,`mn:crashfreeze:staleexit`]])};d(W,`LEGACY_SESSION_KEY`,`mumsnet_crash_detect`),d(W,`SESSION_KEY_PREFIX`,`mncfd_`),d(W,`STALE_THRESHOLD_MS`,18e5),d(W,`HEARTBEAT_INTERVAL_MS`,15e3),d(W,`FREEZE_THRESHOLD_MS`,4e3),n&&(n.CrashFreezeDetector=W);var st=`2.0.0`,G={Awesomium:`awesomium`,Cef:`cef`,CefSharp:`cefsharp`,CoachJS:`coachjs`,Electron:`electron`,FMiner:`fminer`,Geb:`geb`,NightmareJS:`nightmarejs`,Phantomas:`phantomas`,PhantomJS:`phantomjs`,Rhino:`rhino`,Selenium:`selenium`,Sequentum:`sequentum`,SlimerJS:`slimerjs`,WebDriverIO:`webdriverio`,WebDriver:`webdriver`,HeadlessChrome:`headless_chrome`,Unknown:`unknown`},K=class e extends Error{constructor(t,n){super(n),this.state=t,this.name=`BotdError`,Object.setPrototypeOf(this,e.prototype)}};function ct(e,t){let n={},r={bot:!1};for(let i in t){let a=t[i],o=a(e),s={bot:!1};typeof o==`string`?s={bot:!0,botKind:o}:o&&(s={bot:!0,botKind:G.Unknown}),n[i]=s,s.bot&&(r=s)}return[n,r]}async function lt(e){let t={},n=Object.keys(e);return await Promise.all(n.map(async n=>{let r=e[n];try{t[n]={value:await r(),state:0}}catch(e){e instanceof K?t[n]={state:e.state,error:`${e.name}: ${e.message}`}:t[n]={state:-3,error:e instanceof Error?`${e.name}: ${e.message}`:String(e)}}})),t}function ut({appVersion:e}){if(e.state!==0)return!1;if(/headless/i.test(e.value))return G.HeadlessChrome;if(/electron/i.test(e.value))return G.Electron;if(/slimerjs/i.test(e.value))return G.SlimerJS}function dt(e,t){return e.indexOf(t)!==-1}function q(e,t){return e.indexOf(t)!==-1}function ft(e,t){if(`find`in e)return e.find(t);for(let n=0;n<e.length;n++)if(t(e[n],n,e))return e[n]}function pt(e){return Object.getOwnPropertyNames(e)}function mt(e,...t){for(let n of t)if(typeof n==`string`){if(dt(e,n))return!0}else if(ft(e,e=>n.test(e))!=null)return!0;return!1}function ht(e){return e.reduce((e,t)=>e+ +!!t,0)}function gt({documentElementKeys:e}){if(e.state!==0)return!1;if(mt(e.value,`selenium`,`webdriver`,`driver`))return G.Selenium}function _t({errorTrace:e}){if(e.state!==0)return!1;if(/PhantomJS/i.test(e.value))return G.PhantomJS}function vt({evalLength:e,browserKind:t,browserEngineKind:n}){if(e.state!==0||t.state!==0||n.state!==0)return;let r=e.value;return n.value===`unknown`?!1:r===37&&!dt([`webkit`,`gecko`],n.value)||r===39&&!dt([`internet_explorer`],t.value)||r===33&&!dt([`chromium`],n.value)}function yt({functionBind:e}){if(e.state===-2)return G.PhantomJS}function bt({languages:e}){if(e.state===0&&e.value.length===0)return G.HeadlessChrome}function xt({mimeTypesConsistent:e}){if(e.state===0&&!e.value)return G.Unknown}function St({notificationPermissions:e,browserKind:t}){if(t.state!==0||t.value!==`chrome`)return!1;if(e.state===0&&e.value)return G.HeadlessChrome}function Ct({pluginsArray:e}){if(e.state===0&&!e.value)return G.HeadlessChrome}function wt({pluginsLength:e,android:t,browserKind:n,browserEngineKind:r}){if(e.state===0&&t.state===0&&n.state===0&&r.state===0&&!(n.value!==`chrome`||t.value||r.value!==`chromium`)&&e.value===0)return G.HeadlessChrome}function Tt({process:e}){if(e.state!==0)return!1;if(e.value.type===`renderer`||e.value.versions?.electron!=null)return G.Electron}function Et({productSub:e,browserKind:t}){if(e.state!==0||t.state!==0)return!1;if((t.value===`chrome`||t.value===`safari`||t.value===`opera`||t.value===`wechat`)&&e.value!==`20030107`)return G.Unknown}function Dt({userAgent:e}){if(e.state!==0)return!1;if(/PhantomJS/i.test(e.value))return G.PhantomJS;if(/Headless/i.test(e.value))return G.HeadlessChrome;if(/Electron/i.test(e.value))return G.Electron;if(/slimerjs/i.test(e.value))return G.SlimerJS}function Ot({webDriver:e}){if(e.state===0&&e.value)return G.HeadlessChrome}function kt({webGL:e}){if(e.state===0){let{vendor:t,renderer:n}=e.value;if(t==`Brian Paul`&&n==`Mesa OffScreen`)return G.HeadlessChrome}}function At({windowExternal:e}){if(e.state!==0)return!1;if(/Sequentum/i.test(e.value))return G.Sequentum}function jt({windowSize:e,documentFocus:t}){if(e.state!==0||t.state!==0)return!1;let{outerWidth:n,outerHeight:r}=e.value;if(t.value&&n===0&&r===0)return G.HeadlessChrome}function Mt({distinctiveProps:e}){if(e.state!==0)return!1;let t=e.value,n;for(n in t)if(t[n])return n}var Nt={detectAppVersion:ut,detectDocumentAttributes:gt,detectErrorTrace:_t,detectEvalLengthInconsistency:vt,detectFunctionBind:yt,detectLanguagesLengthInconsistency:bt,detectNotificationPermissions:St,detectPluginsArray:Ct,detectPluginsLengthInconsistency:wt,detectProcess:Tt,detectUserAgent:Dt,detectWebDriver:Ot,detectWebGL:kt,detectWindowExternal:At,detectWindowSize:jt,detectMimeTypesConsistent:xt,detectProductSub:Et,detectDistinctiveProperties:Mt};function Pt(){let e=navigator.appVersion;if(e==null)throw new K(-1,`navigator.appVersion is undefined`);return e}function Ft(){if(document.documentElement===void 0)throw new K(-1,`document.documentElement is undefined`);let{documentElement:e}=document;if(typeof e.getAttributeNames!=`function`)throw new K(-2,`document.documentElement.getAttributeNames is not a function`);return e.getAttributeNames()}function It(){try{null[0]()}catch(e){if(e instanceof Error&&e.stack!=null)return e.stack.toString()}throw new K(-3,`errorTrace signal unexpected behaviour`)}function Lt(){return eval.toString().length}function Rt(){if(Function.prototype.bind===void 0)throw new K(-2,`Function.prototype.bind is undefined`);return Function.prototype.bind.toString()}function zt(){let e=window,t=navigator;return ht([`webkitPersistentStorage`in t,`webkitTemporaryStorage`in t,t.vendor.indexOf(`Google`)===0,`webkitResolveLocalFileSystemURL`in e,`BatteryManager`in e,`webkitMediaStream`in e,`webkitSpeechGrammar`in e])>
2=5?`chromium`:ht([`ApplePayError`in e,`CSSPrimitiveValue`in e,`Counter`in e,t.vendor.indexOf(`Apple`)===0,`getStorageUpdates`in t,`WebKitMediaKeys`in e])>=4?`webkit`:ht([`buildID`in navigator,`MozAppearance`in(document.documentElement?.style??{}),`onmozfullscreenchange`in e,`mozInnerScreenX`in e,`CSSMozDocumentRule`in e,`CanvasCaptureMediaStream`in e])>=4?`gecko`:`unknown`}function Bt(){let e=navigator.userAgent?.toLowerCase();return q(e,`edg/`)?`edge`:q(e,`trident`)||q(e,`msie`)?`internet_explorer`:q(e,`wechat`)?`wechat`:q(e,`firefox`)?`firefox`:q(e,`opera`)||q(e,`opr`)?`opera`:q(e,`chrome`)?`chrome`:q(e,`safari`)?`safari`:`unknown`}function Vt(){let e=zt(),t=e===`chromium`,n=e===`gecko`,r=window,i=navigator,a=`connection`;return t?ht([!(`SharedWorker`in r),i[a]&&`ontypechange`in i[a],!(`sinkId`in new Audio)])>=2:n?ht([`onorientationchange`in r,`orientation`in r,/android/i.test(i.appVersion)])>=2:!1}function Ht(){return document.hasFocus!==void 0&&document.hasFocus()}function Ut(){let e=window;return ht([!(`MediaSettingsRange`in e),`RTCEncodedAudioFrame`in e,``+e.Intl==`[object Intl]`,``+e.Reflect==`[object Reflect]`])>=3}function Wt(){let e=navigator,t=[],n=e.language||e.userLanguage||e.browserLanguage||e.systemLanguage;if(n!==void 0&&t.push([n]),Array.isArray(e.languages))zt()===`chromium`&&Ut()||t.push(e.languages);else if(typeof e.languages==`string`){let n=e.languages;n&&t.push(n.split(`,`))}return t}function Gt(){if(navigator.mimeTypes===void 0)throw new K(-1,`navigator.mimeTypes is undefined`);let{mimeTypes:e}=navigator,t=Object.getPrototypeOf(e)===MimeTypeArray.prototype;for(let n=0;n<e.length;n++)t&&=Object.getPrototypeOf(e[n])===MimeType.prototype;return t}async function Kt(){if(window.Notification===void 0)throw new K(-1,`window.Notification is undefined`);if(navigator.permissions===void 0)throw new K(-1,`navigator.permissions is undefined`);let{permissions:e}=navigator;if(typeof e.query!=`function`)throw new K(-2,`navigator.permissions.query is not a function`);try{let t=await e.query({name:`notifications`});return window.Notification.permission===`denied`&&t.state===`prompt`}catch{throw new K(-3,`notificationPermissions signal unexpected behaviour`)}}function qt(){if(navigator.plugins===void 0)throw new K(-1,`navigator.plugins is undefined`);if(window.PluginArray===void 0)throw new K(-1,`window.PluginArray is undefined`);return navigator.plugins instanceof PluginArray}function Jt(){if(navigator.plugins===void 0)throw new K(-1,`navigator.plugins is undefined`);if(navigator.plugins.length===void 0)throw new K(-3,`navigator.plugins.length is undefined`);return navigator.plugins.length}function Yt(){let{process:e}=window,t=`window.process is`;if(e===void 0)throw new K(-1,`${t} undefined`);if(e&&typeof e!=`object`)throw new K(-3,`${t} not an object`);return e}function Xt(){let{productSub:e}=navigator;if(e===void 0)throw new K(-1,`navigator.productSub is undefined`);return e}function Zt(){if(navigator.connection===void 0)throw new K(-1,`navigator.connection is undefined`);if(navigator.connection.rtt===void 0)throw new K(-1,`navigator.connection.rtt is undefined`);return navigator.connection.rtt}function Qt(){return navigator.userAgent}function $t(){if(navigator.webdriver==null)throw new K(-1,`navigator.webdriver is undefined`);return navigator.webdriver}function en(){let e=document.createElement(`canvas`);if(typeof e.getContext!=`function`)throw new K(-2,`HTMLCanvasElement.getContext is not a function`);let t=e.getContext(`webgl`);if(t===null)throw new K(-4,`WebGLRenderingContext is null`);if(typeof t.getParameter!=`function`)throw new K(-2,`WebGLRenderingContext.getParameter is not a function`);return{vendor:t.getParameter(t.VENDOR),renderer:t.getParameter(t.RENDERER)}}function tn(){if(window.external===void 0)throw new K(-1,`window.external is undefined`);let{external:e}=window;if(typeof e.toString!=`function`)throw new K(-2,`window.external.toString is not a function`);return e.toString()}function nn(){return{outerWidth:window.outerWidth,outerHeight:window.outerHeight,innerWidth:window.innerWidth,innerHeight:window.innerHeight}}function rn(){let e={[G.Awesomium]:{window:[`awesomium`]},[G.Cef]:{window:[`RunPerfTest`]},[G.CefSharp]:{window:[`CefSharp`]}
2,[G.CoachJS]:{window:[`emit`]},[G.FMiner]:{window:[`fmget_targets`]},[G.Geb]:{window:[`geb`]},[G.NightmareJS]:{window:[`__nightmare`,`nightmare`]},[G.Phantomas]:{window:[`__phantomas`]},[G.PhantomJS]:{window:[`callPhantom`,`_phantom`]},[G.Rhino]:{window:[`spawn`]},[G.Selenium]:{window:[`_Selenium_IDE_Recorder`,`_selenium`,`calledSelenium`,/^([a-z]){3}_.*_(Array|Promise|Symbol)$/],document:[`__selenium_evaluate`,`selenium-evaluate`,`__selenium_unwrapped`]},[G.WebDriverIO]:{window:[`wdioElectron`]},[G.WebDriver]:{window:[`webdriver`,`__webdriverFunc`,`__lastWatirAlert`,`__lastWatirConfirm`,`__lastWatirPrompt`,`_WEBDRIVER_ELEM_CACHE`,`ChromeDriverw`],document:[`__webdriver_script_fn`,`__driver_evaluate`,`__webdriver_evaluate`,`__fxdriver_evaluate`,`__driver_unwrapped`,`__webdriver_unwrapped`,`__fxdriver_unwrapped`,`__webdriver_script_fn`,`__webdriver_script_func`,`__webdriver_script_function`,`$cdc_asdjflasutopfhvcZLmcf`,`$cdc_asdjflasutopfhvcZLmcfl_`,`$chrome_asyncScriptInfo`,`__$webdriverAsyncExecutor`]},[G.HeadlessChrome]:{window:[`domAutomation`,`domAutomationController`]}},t,n={},r=pt(window),i=[];for(t in window.document!==void 0&&(i=pt(window.document)),e){let a=e[t];if(a!==void 0){let e=a.window!==void 0&&mt(r,...a.window),o=a.document===void 0||!i.length?!1:mt(i,...a.document);n[t]=e||o}}return n}var an={android:Vt,browserKind:Bt,browserEngineKind:zt,documentFocus:Ht,userAgent:Qt,appVersion:Pt,rtt:Zt,windowSize:nn,pluginsLength:Jt,pluginsArray:qt,errorTrace:It,productSub:Xt,windowExternal:tn,mimeTypesConsistent:Gt,evalLength:Lt,webGL:en,webDriver:$t,languages:Wt,notificationPermissions:Kt,documentElementKeys:Ft,functionBind:Rt,process:Yt,distinctiveProps:rn},on=class{constructor(){this.components=void 0,this.detections=void 0}getComponents(){return this.components}getDetections(){return this.detections}detect(){if(this.components===void 0)throw Error(`BotDetector.detect can't be called before BotDetector.collect`);let[e,t]=ct(this.components,Nt);return this.detections=e,t}async collect(){return this.components=await lt(an),this.components}};function sn(){if(!(window.__fpjs_d_m||Math.random()>=.001))try{let e=new XMLHttpRequest;e.open(`get`,`https://m1.openfpcdn.io/botd/v${st}/npm-monitoring`,!0),e.send()}catch(e){console.error(e)}}async function cn({monitoring:e=!0}={}){e&&sn();let t=new on;return await t.collect(),t}var ln;async function un(){try{let e=(await cn()).detect();return{isBot:e.bot,kind:e.botKind}}catch{return}}function dn(){return ln||=un(),ln}var fn=new s(`gtm data layer`,{withTimeIntervals:!0}),{user:J,page:Y}=n.globalState;window.addEventListener(`user-logged-in`,e=>{window.mnPushToDataLayer({event:`logIn`,user:{method:e.detail.method,..._(`userID`,J.id?.toString()),..._(`isLoggedIn`,J.is_logged_in?`Logged In`:`Not Logged In`),..._(`isPremium`,J.is_premium?`Premium`:`Not Premium`),..._(`talkStatus`,h(J.talk_status)),..._(`userType`,J.is_logged_in?`Member`:`Non-Member`)}})}),window.addEventListener(`user-registered`,e=>{window.mnPushToDataLayer({event:`accountCreated`,user:{method:e.detail.method,..._(`userID`,J.id?.toString()),..._(`isLoggedIn`,J.is_logged_in?`Logged In`:`Not Logged In`),..._(`isPremium`,J.is_premium?`Premium`:`Not Premium`),..._(`talkStatus`,h(J.talk_status)),..._(`userType`,J.is_logged_in?`Member`:`Non-Member`)}})}),window.addEventListener(`user-interests-saved`,e=>{let t=e.detail[0];window.mnPushToDataLayer({event:`onboardingInterestsCompleted`,user:{interests:t.map(e=>e.interest)}})}),window.addEventListener(`user-about-you-saved`,e=>{let t=e.detail[0];window.mnPushToDataLayer({event:`onboardingAboutYouCompleted`,user:{gender:t.gender,expecting:t.expecting,dueDate:t.dueDate,pregnancyNewsletter:t.pregnancyNewsletter,children:t.children,numberOfChildren:t.numberOfChildren,childDetails:t.childDetails.map(e=>({age:e.age,gender:e.gender})),childDevelopmentNewsletter:t.childDevelopmentNewsletter,postcodeRegion:t.postcodeRegion}})}),window.addEventListener(`user-subscribed-premium`,e=>{window.mnPushToDataLayer({event:`premiumSignUp`,user:{..._(`userID`,J.id?.toString()),..._(`isPremium`,J.is_premium?`Premium`:`Not Premium`),premiumType:e.detail}})}),window.addEventListener(`user-cancelled-premium`,e=>{window.mnPushToDataLayer({event:`premiumCancellation`,user:{..._(`userID`,J.id?.toString()),..._(`isPremium`,J.is_premium?`Premium`:`Not Premium`),
2cancellationReason:e.detail}})}),window.addEventListener(`virtual-page-view`,e=>{let t={event:`virtualPageview`,page:{newUrl:e.detail.newUrl,oldUrl:e.detail.oldUrl,pageTitle:e.detail.pageTitle,..._(`pageNumber`,e.detail.pageNumber?.toString()),..._(`pageType`,g(Y.name)),..._(`pageCategory`,l(Y.path)),..._(`pageTotal`,Y.page_total?.toString()),..._(`topic`,Y.topic_name),..._(`topicID`,Y.topic_id?.toString()),..._(`relatedTopics`,f(`meta-related-topic-titles`)),..._(`action`,e.detail.action),..._(`target`,e.detail.target)},thread:{..._(`threadName`,Y.thread_subject),..._(`threadID`,Y.thread_id?.toString()),..._(`threadType`,Y.thread_type),..._(`threadTags`,Y?.tagger_tags?.join(`,`)),..._(`isZombie`,Y.is_zombie?`1`:null)}};window.mnPushToDataLayer(p(t))}),(async()=>{if(!e)return;let[t,n]=await m(()=>b());if(n)return fn.error(n);window.mnPushToDataLayer({event:`sourcepoint_consent`,user:{consent:t,isPremium:window.globalState.user.is_premium}})})();var pn=function(e){oe(t,e);function t(t){t===void 0&&(t={});var n=e.call(this)||this;return n.customHeaders=t,n}return t.prototype.send=function(e,t){return N(this,void 0,void 0,function(){var n,r,i;return I(this,function(a){switch(a.label){case 0:if(typeof fetch>`u`)throw Error(`FetchTransport is not supported`);return n={headers:L({"Content-Type":`application/json`,Accept:`*/*`},this.customHeaders),body:JSON.stringify(t),method:`POST`},[4,fetch(e,n)];case 1:return r=a.sent(),[4,r.text()];case 2:i=a.sent();try{return[2,this.buildResponse(JSON.parse(i))]}catch{return[2,this.buildResponse({code:r.status})]}}})})},t}(ve),mn=`[Amplitude]`,hn=`${mn} Session Replay ID`,gn=Ce.US,_n={enabled:!0},vn=1e3,yn=`${mn} Session Replay Debug`,bn=`amp-block`,xn=`amp-mask`,Sn=`amp-unmask`,Cn=`https://api-sr.amplitude.com/sessions/v2/track`,wn=`https://api-sr.eu.amplitude.com/sessions/v2/track`,Tn=`https://api-sr.stag2.amplitude.com/sessions/v2/track`,En=2e6,Dn=6e6,On=9e6,kn=/payload.*exceed/i,An=3e4,jn=6e4,Mn=1e4,Nn=1e3,Pn=1e4,Fn=1024,In=1e3,Ln=65536,Rn=1e4,zn=6e4;2*En;var Bn=`amplitude-sr-iframe`,Vn;(function(e){e.GET_SR_PROPS=`get-sr-props`,e.DEBUG_INFO=`debug-info`,e.FETCH_REQUEST=`fetch-request`,e.METADATA=`metadata`,e.TARGETING_DECISION=`targeting-decision`,e.REPLAY_GATE_DECISION=`replay-gate-decision`})(Vn||={});var Hn=function(){function e(e){this.logger=e,this.log=this.getSafeMethod(`log`),this.warn=this.getSafeMethod(`warn`),this.error=this.getSafeMethod(`error`),this.debug=this.getSafeMethod(`debug`)}return e.prototype.getSafeMethod=function(e){if(!this.logger)return(function(){});var t=this.logger[e];return typeof t==`function`?(t.__rrweb_original__??t).bind(this.logger):(function(){})},e.prototype.enable=function(e){this.logger.enable(e)},e.prototype.disable=function(){this.logger.disable()},e}(),Un=`medium`;function Wn(e){return e.toLowerCase()}function Gn(e){var t=e.type;return e.hasAttribute(`data-rr-is-password`)?`password`:t?Wn(t):null}function Kn(e,t){return t||(e===`STAGING`?Tn:e===`EU`?wn:Cn)}var qn=function(e,t,n){switch(t){case`light`:if(e!==`input`)return!1;var r=n?Gn(n):``;return r?!!([`password`,`hidden`,`email`,`tel`].includes(r)||n.autocomplete.startsWith(`cc-`)):!1;case`medium`:return e===`input`;case`conservative`:return!0;default:return qn(e,Un,n)}},Jn=function(e,t){var n,r;if(e&&t.urlMaskLevels)try{for(var i=z(t.urlMaskLevels),a=i.next();!a.done;a=i.next()){var o=a.value;if(nr(o.match).test(e))return o.maskLevel}}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return t.defaultMaskLevel??Un},Yn=function(e,t,n,r){if(t===void 0&&(t={defaultMaskLevel:Un}),n){if(n.closest(`.amp-mask`)||(t.maskSelector??[]).some(function(e){return n.closest(e)}))return!0;if(n.closest(`.amp-unmask`)||(t.unmaskSelector??[]).some(function(e){return n.closest(e)}))return!1}return qn(e,Jn(r,t),n)},Xn=function(e,t,n){return function(r,i){return Yn(e,t,i,n?.())?r.replace(/[^\s]/g,`*`):r}},Zn=function(e,t){return function(n,r,i){return n===`style`||!(e?.maskAttributes??[]).includes(n)?r:Yn([`INPUT`,`SELECT`,`TEXTAREA`].includes(i.tagName)?`input`:`text`,e,i,t?.())?r.replace(/[^\s]/g,`*`):r}},Qn=function(){var e=F();return e?.location?e.location.href:``},$n=function(e,t){return`${t}/${e}`},er=function(e){return!(typeof e!=`string`||e.trim()===``||!/^\/|^https?:\/\/[^\s]+$/.test(e))},tr=new Map,nr=function(e){var t=tr.get(e);if(t)return t;var n=`\0TRAIL\0`,r=`\0MID\0`,i=`\0DS\0`,a=`\0ST\0`,o=`\0QU\0`,s=e;s=s.replace(/\/\*\*$/,n),s=s.replace(/\/\*\*\//g,r),s=s.replace(/\*\*/g,i),s=s.replace(/\*/g,a),s=s.replace(/\?/g,o),s=s.replace(/[.+^${}()|[\]\\]/g,`\\$&`),s=s.split(n).join(`(/.*)?`),s=s.split(r).join(`/(.*\\/)?`),s=s.split(i).join(`.*`),s=s.split(a).join(`.*`),s=s.split(o).join(`.`);var c=RegExp(`^${s}\$`);return tr.set(e,c),c},rr=function(e){if(!e.every(function(e){return typeof e.selector==`string`&&typeof e.replacement==`string`}))throw Error(`ugcFilterRules must be an array of objects with selector and replacement properties`);
2if(!e.every(function(e){return er(e.selector)}))throw Error(`ugcFilterRules must be an array of objects with valid globs`)},ir=function(e,t){var n,r;try{for(var i=z(t),a=i.next();!a.done;a=i.next()){var o=a.value,s=nr(o.selector);if(s.test(e))return e.replace(s,o.replacement)}}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return e},ar=function(){return N(void 0,void 0,void 0,function(){var e,t,n,r,i,a,o;return I(this,function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),e=F(),e?[4,e.navigator.storage.estimate()]:[3,2];case 1:return t=s.sent(),n=t.usage,r=t.quota,i=t.usageDetails,a=n?Math.round(n/Fn):0,o=n&&r?Math.round((n/r+2**-52)*1e3)/1e3:0,[2,{totalStorageSize:a,percentOfQuota:o,usageDetails:JSON.stringify(i)}];case 2:return[3,4];case 3:return s.sent(),[3,4];case 4:return[2,{totalStorageSize:0,percentOfQuota:0,usageDetails:``}]}})})},or=function(e){var t=L({},e),n=t.apiKey;return t.apiKey=`****${n.substring(n.length-4)}`,t},sr=function(){return{flushMaxRetries:2,logLevel:ke.Warn,loggerProvider:new pe,transportProvider:new pn}},cr=function(e){oe(t,e);function t(t,n){var r=this,i=sr();r=e.call(this,L(L({transportProvider:i.transportProvider,loggerProvider:new Hn(n.loggerProvider||i.loggerProvider)},n),{apiKey:t}))||this,r.flushMaxRetries=n.flushMaxRetries!==void 0&&n.flushMaxRetries<=i.flushMaxRetries?n.flushMaxRetries:i.flushMaxRetries,r.apiKey=t,r.sampleRate=n.sampleRate||0,r.serverZone=n.serverZone||gn,r.configServerUrl=n.configServerUrl,r.trackServerUrl=n.trackServerUrl,r.shouldInlineStylesheet=n.shouldInlineStylesheet,r.version=n.version,r.performanceConfig=n.performanceConfig||_n,r.storeType=n.storeType??`memory`,r.applyBackgroundColorToBlockedElements=n.applyBackgroundColorToBlockedElements??!1,r.enableUrlChangePolling=n.enableUrlChangePolling??!1,r.urlChangePollingInterval=n.urlChangePollingInterval??vn,r.captureDocumentTitle=n.captureDocumentTitle??!1,n.fullSnapshotIntervalMs!==void 0&&(r.fullSnapshotIntervalMs=n.fullSnapshotIntervalMs),n.eagerFullSnapshotSend!==void 0&&(r.eagerFullSnapshotSend=n.eagerFullSnapshotSend),r.captureFullSnapshotOnFocus=n.captureFullSnapshotOnFocus??!1,n.maxPersistedEventsSizeBytes!==void 0&&(r.maxPersistedEventsSizeBytes=pr(n.maxPersistedEventsSizeBytes,ur,dr,`maxPer
2sistedEventsSizeBytes`,r.loggerProvider)),n.maxSingleEventSizeBytes!==void 0&&(r.maxSingleEventSizeBytes=pr(n.maxSingleEventSizeBytes,ur,fr,`maxSingleEventSizeBytes`,r.loggerProvider)),r.privacyConfig=L(L({},n.privacyConfig??{}),{unmaskSelector:Array.from(new Set(P([`.${Sn}`],R(n.privacyConfig?.unmaskSelector??[]),!1)))}),n.interactionConfig&&(r.interactionConfig=n.interactionConfig,r.interactionConfig.ugcFilterRules&&rr(r.interactionConfig.ugcFilterRules)),n.debugMode&&(r.debugMode=n.debugMode);var a=n;return r.useWebWorker=n.useWebWorker??a.experimental?.useWebWorker??!0,r.enableTransportCompression=n.enableTransportCompression??!0,r.sendTimeoutMs=n.sendTimeoutMs,r.captureAdoptedStyleSheets=n.captureAdoptedStyleSheets??!0,n.crossOriginIframes&&(r.crossOriginIframes=n.crossOriginIframes),n.flushIntervalConfig?r.flushIntervalConfig=mr(n.flushIntervalConfig,r.loggerProvider):r.flushIntervalConfig={minIntervalMs:Nn,maxIntervalMs:Pn},r.handleSendEvents=n.handleSendEvents,r.handleFetchConfig=n.handleFetchConfig,r}return t}(Ae),lr=100,ur=1e3,dr=8e6,fr=1e7;function pr(e,t,n,r,i){if(!Number.isFinite(e)){i.warn(`${r} value is not a finite number (got ${String(e)}); ignoring.`);return}return e<t?(i.warn(`${r} ${e} is below floor ${t}; clamping.`),t):e>n?(i.warn(`${r} ${e} exceeds ceiling ${n}; clamping.`),n):e}function mr(e,t){var n={};if(e.minIntervalMs!==void 0&&(!Number.isFinite(e.minIntervalMs)||e.minIntervalMs<lr?(t.warn(`flushIntervalConfig.minIntervalMs ${e.minIntervalMs} is below floor ${lr}ms; clamping.`),n.minIntervalMs=lr):n.minIntervalMs=e.minIntervalMs),e.maxIntervalMs!==void 0&&(Number.isNaN(e.maxIntervalMs)||e.maxIntervalMs<lr?(t.warn(`flushIntervalConfig.maxIntervalMs ${e.maxIntervalMs} is below floor ${lr}ms; clamping.`),n.maxIntervalMs=lr):n.maxIntervalMs=e.maxIntervalMs),n.minIntervalMs!==void 0||n.maxIntervalMs!==void 0){var r=n.minIntervalMs??500,i=n.maxIntervalMs??Mn;i<r&&(n.maxIntervalMs===void 0?(t.warn(`flushIntervalConfig.minIntervalMs (${r}) exceeds the default maxIntervalMs (${Mn}); raising max to match min.`),n.maxIntervalMs=r):n.minIntervalMs===void 0?(t.warn(`flushIntervalConfig.maxIntervalMs (${i}) is below the default minIntervalMs (500); lowering min to match max.`),n.minIntervalMs=i):(t.warn(`flushIntervalConfig.maxIntervalMs (${n.maxIntervalMs}) is less than minIntervalMs (${n.minIntervalMs}); raising max to match min.`),n.maxIntervalMs=n.minIntervalMs))}return n}var hr=(e=>(e[e.DomContentLoaded=0]=`DomContentLoaded`,e[e.Load=1]=`Load`,e[e.FullSnapshot=2]=`FullSnapshot`,e[e.IncrementalSnapshot=3]=`IncrementalSnapshot`,e[e.Meta=4]=`Meta`,e[e.Custom=5]=`Custom`,e[e.Plugin=6]=`Plugin`,e))(hr||{}),gr=(e=>(e[e.Mutation=0]=`Mutation`,e[e.MouseMove=1]=`MouseMove`,e[e.MouseInteraction=2]=`MouseInteraction`,e[e.Scroll=3]=`Scroll`,e[e.ViewportResize=4]=`ViewportResize`,e[e.Input=5]=`Input`,e[e.TouchMove=6]=`TouchMove`,e[e.MediaInteraction=7]=`MediaInteraction`,e[e.StyleSheetRule=8]=`StyleSheetRule`,e[e.CanvasMutation=9]=`CanvasMutation`,e[e.Font=10]=`Font`,e[e.Log=11]=`Log`,e[e.Drag=12]=`Drag`,e[e.StyleDeclaration=13]=`StyleDeclaration`,e[e.Selection=14]=`Selection`,e[e.AdoptedStyleSheet=15]=`AdoptedStyleSheet`,e[e.CustomElement=16]=`CustomElement`,e))(gr||{}),_r=(e=>(e[e.MouseUp=0]=`MouseUp`,e[e.MouseDown=1]=`MouseDown`,e[e.Click=2]=`Click`,e[e.ContextMenu=3]=`ContextMenu`,e[e.DblClick=4]=`DblClick`,e[e.Focus=5]=`Focus`,e[e.Blur=6]=`Blur`,e[e.TouchStart=7]=`TouchStart`,e[e.TouchMove_Departed=8]=`TouchMove_Departed`,e[e.TouchEnd=9]=`TouchEnd`,e[e.TouchCancel=10]=`TouchCancel`,e))(_r||{}),vr=1500,yr=function(e,t){var n=document.createDocumentFragment(),r=function(e){if(e===void 0&&(e=[]),typeof e==`string`&&(e=[e]),e=e.filter(function(e){try{n.querySelector(e)}catch{return t.warn(`[session-replay-browser] omitting selector "${e}" because it is invalid`),!1}return!0}),e.length!==0)return e};return e.blockSelector=r(e.blockSelector),e.maskSelector=r(e.maskSelector),e.unmaskSelector=r(e.unmaskSelector),e},br=function(){function e(e,t){this.localConfig=t,this.remoteConfigClient=e}return e.prototype.generateJoinedConfig=function(){return N(this,void 0,void 0,function(){var e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_=this;return I(this,function(v){switch(v.label){case 0:e=L({},this.localConfig),e.optOut=this.localConfig.optOut,e.captureEnabled=!0,v.label=1;case 1:return v.trys.push([1,3,,4]),[4,new Promise(function(n,r){_.remoteConfigClient.subscribe(`configs.sessionReplay`,{timeout:vr},function(i,a){if(_.localConfig.loggerProvider.debug(`Session Replay remote configuration received from ${a}:`,JSON.stringify(i,null,2)),!i){r(Error(`No remote config received`));return}var o=i,s=o.sr_sampling_config,c=o.sr_privacy_config,l=o.sr_targeting_config,u=e.interactionConfig?.ugcFilterRules;e.interactionConfig=o.sr_interaction_config,e.interactionConfig&&u&&(e.interactionConfig.ugcFilterRules=u),e.loggingConfig=o.sr_logging_config,(s||c||l)&&(t={},s&&(t.sr_sampling_config=s),c&&(t.sr_privacy_config=c),l&&(t.sr_targeting_config=l)),n()})})];case 2:return v.sent(),[3,4];case 3:return n=v.sent(),this.localConfig.loggerProvider.error(`Failed to generate joined config: `,n),e.captureEnabled=!1,[2,{localConfig:this.localConfig,joinedConfig:e,remoteConfig:void 0}];case 4:if(!t)return[2,{localConfig:this.localConfig,joinedConfig:e,remoteConfig:t}];if(r=t.sr_sampling_config,i=t.sr_privacy_config,a=t.sr_targeting_config,r&&Object.keys(r).length>0?(Object.prototype.hasOwnProperty.call(r,`capture_enabled`)?e.captureEnabled=r.capture_enabled:e.captureEnabled=!1,Object.prototype.hasOwnProperty.call(r,`sample_rate`)&&(e.sampleRate=r.sample_rate),Object.prototype.hasOwnProperty.call(r,`min_session_duration_ms`)&&(e.minSessionDurationMs=this.sanitizeMinSessionDurationMs(r.min_session_duration_ms))):(e.captureEnabled=!0,this.localConfig.loggerProvider.debug(`Remote config successfully fetched, but no values set for project, Session Replay capture enabled.`)),i){o=e.privacyConfig??{},s={defaultMaskLevel:i.defaultMaskLevel??o.defaultMaskLevel??`medium`,blockSelector:[],maskSelector:[],unmaskSelector:[],maskAttributes:P([],R(new Set(P(P([],R(o.maskAttributes??[]),!1),R(i.maskAttributes??[]),!1))),!1),urlMaskLevels:P(P([],R(i.urlMaskLevels??[]),!1),R(o.urlMaskLevels??[]),!1)},c=function(e){var t,n,r,i,a,o,s={};typeof e.blockSelector==`string`&&(e.blockSelector=[e.blockSelector]);try{for(var c=z(e.blockSelector??[]),l=c.next();!l.done;l=c.next()){var u=l.value;s[u]=`block`}}catch(e){t={error:e}}finally{try{l&&!l.done&&(n=c.return)&&n.call(c)}finally{if(t)throw t.error}}try{for(var d=z(e.maskSelector??[]),f=d.next();!f.done;f=d.next()){var u=f.value;s[u]=`mask`}}catch(e){r={error:e}}finally{try{f&&!f.done&&(i=d.return)&&i.call(d)}finally{if(r)throw r.error}}try{for(var p=z(e.unmaskSelector??[]),m=p.next();!m.done;m=p.next()){var u=m.value;s[u]=`unmask`}}catch(e){a={error:e}}finally{try{m&&!m.done&&(o=p.return)&&o.call(p)}finally{if(a)throw a.error}}return s},l=L(L({},c(o)),c(i));try{for(u=z(Object.entries(l)),d=u.next();!d.done;d=u.next())f=R(d.value,2),p=f[0],m=f[1],m===`mask`?s.maskSelector.push(p):m===`block`?s.blockSelector.push(p):m===`unmask`&&s.unmaskSelector.push(p)}catch(e){h={error:e}}finally{try{d&&!d.done&&(g=u.return)&&g.call(u)}finally{if(h)throw h.error}}e.privacyConfig=yr(s,this.localConfig.loggerProvider)}return a&&Object.keys(a).length>0&&(e.targetingConfig=a),this.localConfig.loggerProvider.debug(JSON.stringify({name:`session replay joined config`,config:or(e)},null,2)),[2,{localConfig:this.localConfig,joinedConfig:e,remoteConfig:t}]}})})},e.prototype.sanitizeMinSessionDurationMs=function(e){if(typeof e!=`number`||!Number.isFinite(e)){this.localConfig.loggerProvider.warn(`min_session_duration_ms remote value is not a finite number (got ${String(e)}); ignoring.`);return}if(e<0){this.localConfig.loggerProvider.warn(`min_session_duration_ms remote value is negative (${e}); ignoring.`);return}return e>6e4?(this.localConfig.loggerProvider.warn(`min_session_duration_ms remote value ${e} exceeds ${xr}ms ceiling; clamping.`),xr):e},e}(),xr=6e4,Sr=function(e,t){return N(void 0,void 0,void 0,function(){var n,r;return I(this,function(i){return n=new cr(e,t),r=new be(e,n.loggerProvider,n.serverZone,t.configServerUrl,t.handleFetchConfig),[2,new br(r,n)]})})};function Cr(e){if(e.type!==hr.IncrementalSnapshot)return!1;var t=e.data;return t.source===gr.Mutation&&!t.isAttachIframe}function wr(e){return typeof e==`object`&&!!e}function Tr(e){var t,n,r,i,a={};try{for(var o=z(e),s=o.next();!s.done;s=o.next()){var c=s.value;try{for(var l=(r=void 0,z(Object.keys(c))),u=l.next();!u.done;u=l.next()){var d=u.value;a[d]=c[d]}}catch(e){r={error:e}}finally{try{u&&!u.done&&(i=l.return)&&i.call(l)}finally{if(r)throw r.error}}}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return a}function Er(e){var t,n,r=new Map;if(e.forEach(function(e,t){if(e.attributes&&`style`in e.attributes){var n=r.get(e.id);n?n.push(t):r.set(e.id,[t])}}),r.size===0)return e;var i=function(t){return e[t].attributes.style},a=new Set,o=new Map,s=function(e){if(e.length===1)return`continue`;var t=-1;e.forEach(function(e,n){wr(i(e))||(t=n)});var n=[];
2if(e.forEach(function(e,r){r!==t&&(a.add(e),r>t&&n.push(e))}),n.length>0){var r=n[n.length-1],s=Tr(n.map(function(e){return i(e)}));a.delete(r),o.set(r,s)}};try{for(var c=z(r.values()),l=c.next();!l.done;l=c.next()){var u=l.value;s(u)}}catch(e){t={error:e}}finally{try{l&&!l.done&&(n=c.return)&&n.call(c)}finally{if(t)throw t.error}}if(a.size===0&&o.size===0)return e;var d=[];return e.forEach(function(e,t){var n=o.get(t);if(n!==void 0){d.push(L(L({},e),{attributes:L(L({},e.attributes),{style:n})}));return}if(!a.has(t)){d.push(e);return}var r=L({},e.attributes);delete r.style,Object.keys(r).length>0&&d.push(L(L({},e),{attributes:r}))}),d}function Dr(e){var t,n,r,i,a=e[0],o=new Map,s=new Map,c=new Map,l=new Map,u=new Map;e.forEach(function(e,t){var n,r,i,a,d=e.data;try{for(var f=z(d.adds),p=f.next();!p.done;p=f.next()){var m=p.value;o.has(m.node.id)||o.set(m.node.id,t),s.set(m.node.id,t),u.set(m.node.id,m.parentId)}}catch(e){n={error:e}}finally{try{p&&!p.done&&(r=f.return)&&r.call(f)}finally{if(n)throw n.error}}try{for(var h=z(d.removes),g=h.next();!g.done;g=h.next()){var _=g.value;c.has(_.id)||c.set(_.id,t),l.set(_.id,t)}}catch(e){i={error:e}}finally{try{g&&!g.done&&(a=h.return)&&a.call(h)}finally{if(i)throw i.error}}});var d=new Set,f=new Set;try{for(var p=z(o),m=p.next();!m.done;m=p.next()){var h=R(m.value,2),g=h[0],_=h[1],v=c.get(g);v!==void 0&&(s.get(g)>=l.get(g)||(_<v?d.add(g):v<_&&f.add(g)))}}catch(e){t={error:e}}finally{try{m&&!m.done&&(n=p.return)&&n.call(p)}finally{if(t)throw t.error}}var y=new Set;if(d.size>0||f.size>0)for(var b=!0;b;){b=!1;try{for(var x=(r=void 0,z(u)),S=x.next();!S.done;S=x.next()){var C=R(S.value,2),w=C[0],T=C[1];if(!d.has(w)&&!f.has(w)&&!y.has(w)&&(d.has(T)||f.has(T)||y.has(T))){var E=c.get(w),D=o.get(w);E!==void 0&&D!==void 0&&E<D?f.add(w):E!==void 0&&D!==void 0&&E===D?y.add(w):d.add(w),b=!0}}}catch(e){r={error:e}}finally{try{S&&!S.done&&(i=x.return)&&i.call(x)}finally{if(r)throw r.error}}}var O=d.size>0||f.size>0||y.size>0,k=[];e.forEach(function(e,t){var n,r;try{for(var i=z(e.data.removes),a=i.next();!a.done;a=i.next()){var s=a.value;d.has(s.id)||f.has(s.id)&&t>=o.get(s.id)||y.has(s.id)&&(d.has(s.parentId)||f.has(s.parentId)||y.has(s.parentId))||k.push(s)}}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}});var ee=e.flatMap(function(e){return e.data.adds}),te=e.flatMap(function(e){return e.data.texts}),ne=e.flatMap(function(e){return e.data.attributes}),re=O?ne.filter(function(e){return!d.has(e.id)&&!f.has(e.id)&&!y.has(e.id)}):ne,A={source:gr.Mutation,removes:k,adds:O?ee.filter(function(e){return!d.has(e.node.id)&&!f.has(e.node.id)&&!y.has(e.node.id)}):ee,texts:O?te.filter(function(e){return!d.has(e.id)&&!f.has(e.id)&&!y.has(e.id)}):te,attributes:Er(re)};return L(L({},a),{data:A})}function Or(e){if(e.length<=1)return e;for(var t=[],n=0;n<e.length;){if(!Cr(e[n])){t.push(e[n]),n++;continue}for(var r=n+1;r<e.length&&Cr(e[r]);)r++;t.push(r>n+1?Dr(e.slice(n,r)):e[n]),n=r}return t}var kr=2e3,Ar=function(){function e(e,t,n,r,i){var a=this;this.taskQueue=[],this.pendingQueue=[],this.isProcessing=!1,this.compressEvent=function(e){var t=e,n=t.type,r=t.timestamp,i=t.delay,a=t.data;return JSON.stringify(i==null?{type:n,timestamp:r,data:a}:{type:n,timestamp:r,delay:i,data:a})},this.addCompressedEventToManager=function(e,t){var n=new Blob([e]).size;if(n>(a.config.maxSingleEventSizeBytes??9e6)){a.config.loggerProvider.warn(`Session replay event dropped: serialized size ${Math.round(n/1024)} KB exceeds maximum allowed event size. If this recurs, please open a GitHub issue at https://github.com/amplitude/Amplitude-TypeScript/issues or contact Amplitude support.`);return}a.eventsManager&&a.deviceId&&a.eventsManager.addEvent({event:{type:`replay`,data:e},sessionId:t,deviceId:a.deviceId})},this.addCompressedEvent=function(e,t){if(a.worker)try{a.worker.postMessage({event:e,sessionId:t})}catch(n){n.name===`DataCloneError`?a.worker.postMessage(JSON.stringify({event:e,sessionId:t})):a.config.loggerProvider.warn(`Unexpected error while posting message to worker:`,n)}else{var n=a.compressEvent(e);a.addCompressedEventToManager(n,t)}},this.flushQueue=function(){var e;
2for(a.pendingQueue.length>0&&(e=a.taskQueue).push.apply(e,P([],R(a.mergeMutationTasks(a.pendingQueue.splice(0))),!1));a.taskQueue.length>0;){var t=a.taskQueue.shift();if(t){var n=t.event,r=t.sessionId,i=a.compressEvent(n);a.addCompressedEventToManager(i,r)}}a.isProcessing=!1},this.terminate=function(){var e;(e=a.worker)==null||e.terminate()};var o=F();if(this.canUseIdleCallback=o&&`requestIdleCallback`in o,this.eventsManager=e,this.config=t,this.deviceId=n,this.timeout=t.performanceConfig?.timeout||kr,this.onFullSnapshotProcessed=i,r){t.loggerProvider.log(`Enabling web worker for compression`);try{var s=new Blob([r],{type:`application/javascript`}),c=URL.createObjectURL(s),l=new Worker(c);l.onerror=function(e){e.preventDefault(),t.loggerProvider.error(`Worker failed, falling back to non-worker compression: ${e.message} (${e.filename}:${e.lineno})`),l.terminate(),a.worker=void 0},l.onmessage=function(e){var t=e.data,n=t.compressedEvent,r=t.sessionId;a.addCompressedEventToManager(n,r)},this.worker=l}catch(e){t.loggerProvider.error(`Failed to create worker, falling back to non-worker compression:`,e)}}}return e.prototype.scheduleIdleProcessing=function(){var e=this;this.isProcessing||(this.isProcessing=!0,requestIdleCallback(function(t){e.processQueue(t)},{timeout:this.timeout}))},e.prototype.enqueueEvent=function(e,t){var n,r,i;if(e.type===hr.FullSnapshot){if(this.config.loggerProvider.debug(`Processing full snapshot immediately.`),this.taskQueue.length>0||this.pendingQueue.length>0){var a=P(P([],R(this.taskQueue.splice(0)),!1),R(this.mergeMutationTasks(this.pendingQueue.splice(0))),!1);try{for(var o=z(a),s=o.next();!s.done;s=o.next()){var c=s.value,l=this.compressEvent(c.event);this.addCompressedEventToManager(l,c.sessionId)}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}this.isProcessing=!1}var u=this.compressEvent(e);this.addCompressedEventToManager(u,t),(i=this.onFullSnapshotProcessed)==null||i.call(this);return}this.canUseIdleCallback&&this.config.performanceConfig?.enabled?(this.config.loggerProvider.debug(`Enqueuing event for processing during idle time.`),this.pendingQueue.push({event:e,sessionId:t}),this.scheduleIdleProcessing()):(this.config.loggerProvider.debug(`Processing event without idle callback.`),this.addCompressedEvent(e,t))},e.prototype.processQueue=function(e){var t,n=this;for(this.pendingQueue.length>0&&(t=this.taskQueue).push.apply(t,P([],R(this.mergeMutationTasks(this.pendingQueue.splice(0))),!1));this.taskQueue.length>0&&(e.timeRemaining()>0||e.didTimeout);){var r=this.taskQueue.shift();if(r){var i=r.event,a=r.sessionId;this.addCompressedEvent(i,a)}}this.taskQueue.length>0||this.pendingQueue.length>0?requestIdleCallback(function(e){n.processQueue(e)},{timeout:this.timeout}):this.isProcessing=!1},e.prototype.mergeMutationTasks=function(e){var t,n;if(this.config.performanceConfig?.mergeMutations===!1||e.length<=1)return e;for(var r=[],i=0;i<e.length;){for(var a=e[i].sessionId,o=i+1;o<e.length&&e[o].sessionId===a;)o++;var s=Or(e.slice(i,o).map(function(e){return e.event}));try{for(var c=(t=void 0,z(s)),l=c.next();!l.done;l=c.next()){var u=l.value;r.push({event:u,sessionId:a})}}catch(e){t={error:e}}finally{try{l&&!l.done&&(n=c.return)&&n.call(c)}finally{if(t)throw t.error}}i=o}return r},e}(),jr=`Unexpected error occurred`,Mr=`Network error occurred, event batch rejected`,Nr=`Session replay event batch rejected due to exceeded retry count`,X=`Failed to store session replay events in IndexedDB`,Pr=`Session replay event batch not sent due to missing device ID`,Fr=`Session replay event batch not sent due to missing api key`,Ir=`Session replay event batch dropped: server signalled capture disabled or session out of valid range for this session`,Lr=`1.48.3`;function Rr(e,t){return N(this,void 0,void 0,function(){var n,r,i,a,o,s,c,l,u,d,f,p,m,h,g=this;return I(this,function(_){switch(_.label){case 0:return _.trys.push([0,4,,5]),n=t.CompressionStream,r=new n(`gzip`),i=r.writable.getWriter(),a=r.readable.getReader(),o=[],s=(function(){return N(g,void 0,void 0,function(){var e,t,n;return I(this,function(r){switch(r.label){case 0:return[4,a.read()];case 1:if(e=r.sent(),t=e.done,n=e.value,t)return[3,3];o.push(n),r.label=2;case 2:return[3,0];case 3:return[2]}})})})(),[4,i.write(new TextEncoder().encode(e))];case 1:return _.sent(),[4,i.close()];case 2:return _.sent(),[4,s];case 3:_.sent(),c=o.reduce(function(e,t){return e+t.length},0),l=new Uint8Array(c),u=0;try{for(d=z(o),f=d.next();!f.done;f=d.next())p=f.value,l.set(p,u),u+=p.length}catch(e){m={error:e}}finally{try{f&&!f.done&&(h=d.return)&&h.call(d)}finally{if(m)throw m.error}}return[2,l];case 4:return _.sent(),[2,null];case 5:return[2]}})})}var zr=256,Br=256;function Vr(e,t){return new Promise(function(n,r){var i=function(){var e=Error(`Custom session replay transport aborted by send timeout`);e.name=`AbortError`,r(e)};t.addEventListener(`abort`,i,{once:!0}),e.then(function(e){t.removeEventListener(`abort`,i),n(e)},function(e){t.removeEventListener(`abort`,i),r(e)})})}var Hr=function(){function e(e){var t=e.trackServerUrl,n=e.loggerProvider,r=e.payloadBatcher,i=e.workerScript,a=e.enableTransportCompression,o=e.sendTimeoutMs,s=e.handleSendEvents,c=this;if(this.storageKey=``,this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.sendIdCounter=0,this.pendingWorkerRequests=new Map,this.timedOutWorkerRequests=new Map,this.flushPauseUntilMs=0,this.mergeOnNextFlush=!1,this.coalesceNextFlush=!1,this.mergeLogFiredThisPause=!1,this.killedSessions=new Set,this.loggerProvider=n,this.payloadBatcher=r||function(e){return e},this.trackServerUrl=t,this.enableTransportCompression=a??!0,this.sendTimeoutMs=o??Rn,this.handleSendEvents=s,i)try{var l=new Blob([i],{type:`application/javascript`}),u=URL.createObjectURL(l),d=new Worker(u);d.onerror=function(e){var t,r;e.preventDefault(),n.error(`Track destination worker failed, falling back to main-thread sending: ${e.message} (${e.filename}:${e.lineno})`),d.terminate(),c.worker=void 0;try{for(var i=z(c.pendingWorkerRequests),a=i.next();!a.done;a=i.next()){var o=R(a.value,2)[1];o.timeout&&clearTimeout(o.timeout),n.warn(`Session replay event send failed due to worker crash: ${e.message}`),o.resolve()}}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}c.pendingWorkerRequests.clear(),c.timedOutWorkerRequests.clear()},d.onmessage=function(e){var t=e.data;if(t.type===`log`)n.log(t.message);else if(t.type===`warn`)n.warn(t.message);else if(t.type===`payload_too_large`){var r=c.pendingWorkerRequests.get(t.id);if(r)r.timeout&&clearTimeout(r.timeout),c.handlePayloadTooLargeResponse(r.context,t.isWaf),r.resolve(),c.pendingWorkerRequests.delete(t.id);else{var i=c.timedOutWorkerRequests.get(t.id);i&&(c.timedOutWorkerRequests.delete(t.id),c.handlePayloadTooLargeResponse(i,t.isWaf))}}else if(t.type===`complete`){var a=c.pendingWorkerRequests.get(t.id);if(a)a.timeout&&clearTimeout(a.timeout),t.skipCode!==void 0&&c.applyServerDirective(a.context.sessionId,t.skipCode),c.completeRequest({context:a.context}),a.resolve(),c.pendingWorkerRequests.delete(t.id);else{var i=c.timedOutWorkerRequests.get(t.id);i&&(c.timedOutWorkerRequests.delete(t.id),t.skipCode!==void 0&&c.applyServerDirective(i.sessionId,t.skipCode),c.completeRequest({context:i}))}}else t.type===`fetch-request`&&c.handleDelegatedFetch(d,t).catch(function(e){n.warn(`Failed to handle delegated session replay fetch:`,e)})},this.worker=d}catch(e){n.error(`Failed to create track destination worker, falling back to main-thread sending:`,e)}}return e.prototype.sendEventsList=function(e){this.addToQueue(L(L({},e),{attempts:0,timeout:0}))},e.prototype.markCoalesceNextFlush=function(){this.coalesceNextFlush=!0,this.schedule(0)},e.prototype.sendBeacon=function(e){var t=this,n,r=e.events,i=e.sessionId,a=e.deviceId,o=e.apiKey,s=e.serverZone,c=65536,l=function(e){return new Blob([e]).size},u=r,d=JSON.stringify({version:2,events:u});if(l(d)>c){for(var f=0,p=u.length;f<p;){var m=Math.floor((f+p+1)/2);
2l(JSON.stringify({version:2,events:u.slice(0,m)}))<=c?f=m:p=m-1}u=u.slice(0,f),d=JSON.stringify({version:2,events:u}),this.loggerProvider.warn(`sendBeacon payload exceeded 64 KB limit, trimmed from ${r.length} to ${u.length} events`)}if(u.length!==0){if(this.handleSendEvents){var h=new URLSearchParams({device_id:a,session_id:String(i),type:`replay`}),g=`${Kn(s,this.trackServerUrl)}?${h.toString()}`,_={"Content-Type":`application/json`,Accept:`*/*`,Authorization:`Bearer ${o}`};this.loggerProvider.debug(`Routing session replay exit batch (${u.length} events) through custom transport for session id ${i}.`);try{this.handleSendEvents({url:g,method:`POST`,headers:_,body:d,keepalive:!0}).catch(function(e){t.loggerProvider.warn(`Custom transport failed to send session replay exit batch:`,e)})}catch(e){this.loggerProvider.warn(`Custom transport threw while sending session replay exit batch:`,e)}return}var v=new URLSearchParams({device_id:a,session_id:String(i),type:`replay`,api_key:o}),y=`${Kn(s,this.trackServerUrl)}?${v.toString()}`,b=F();try{var x=new Blob([d],{type:`application/json`});((n=b?.navigator)?.sendBeacon)?.call(n,y,x)===!1&&this.loggerProvider.warn(`sendBeacon failed to queue session replay payload`)}catch{}}},e.prototype.addToQueue=function(){for(var e=this,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];t.filter(function(t){return e.killedSessions.has(t.sessionId)?(e.completeRequest({context:t,err:Ir}),!1):t.attempts<(t.flushMaxRetries||0)?(t.attempts+=1,!0):(e.completeRequest({context:t,err:Nr}),!1)}).forEach(function(t){e.queue=e.queue.concat(t),e.schedule(0)})},e.prototype.schedule=function(e){var t=this;if(!this.scheduled){var n=this.flushPauseUntilMs-Date.now(),r=n>0,i=n>e?n:e;r&&(this.mergeOnNextFlush=!0),this.scheduled=setTimeout(function(){t.flush(!0).then(function(){t.queue.length>0&&t.schedule(e)})},i)}},e.prototype.flush=function(e){return e===void 0&&(e=!1),N(this,void 0,void 0,function(){var t,n,r,i,a,o,s;return I(this,function(c){switch(c.label){case 0:t=this.queue,this.queue=[],this.scheduled&&=(clearTimeout(this.scheduled),null),this.mergeOnNextFlush?(this.mergeOnNextFlush=!1,this.coalesceNextFlush=!1,t=this.mergeQueueAfterThrottle(t)):this.coalesceNextFlush&&(this.coalesceNextFlush=!1,t=this.mergeDrainBacklog(t)),c.label=1;case 1:c.trys.push([1,6,7,8]),n=z(t),r=n.next(),c.label=2;case 2:return r.done?[3,5]:(i=r.value,[4,this.send(i,e)]);case 3:c.sent(),c.label=4;case 4:return r=n.next(),[3,2];case 5:return[3,8];case 6:return a=c.sent(),o={error:a},[3,8];case 7:try{r&&!r.done&&(s=n.return)&&s.call(n)}finally{if(o)throw o.error}return[7];case 8:return[2]}})})},e.prototype.mergeQueueAfterThrottle=function(e){var t=this.coalesceByIdentity(e);return t.length<e.length&&!this.mergeLogFiredThisPause&&(this.mergeLogFiredThisPause=!0,this.loggerProvider.log(`Session replay throttle pause ended; merged ${e.length} queued batches into ${t.length} request(s)`)),t},e.prototype.mergeDrainBacklog=function(e){var t=this.coalesceByIdentity(e);return t.length<e.length&&this.loggerProvider.log(`Session replay coalesced ${e.length} persisted page-load backlog batches into ${t.length} request(s)`),t},e.prototype.coalesceByIdentity=function(e){var t,n,r,i,a=this;if(e.length<=1)return e;var o=new Map;try{for(var s=z(e),c=s.next();!c.done;c=s.next()){var l=c.value,u=[l.sessionId,l.deviceId??``,l.apiKey??``,l.type,l.serverZone??``,l.sampleRate,l.version?.type??``,l.version?.version??``].join(`|`),d=o.get(u);d?d.push(l):o.set(u,[l])}}catch(e){t={error:e}}finally{try{c&&!c.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}var f=[],p=function(e){var t,n;if(e.length===1)return f.push(e[0]),`continue`;var r=null,i=0,o=function(){r&&f.push(r),r=null,i=0},s=function(e){var t=e.events.reduce(function(e,t){return e+new Blob([t]).size},0);if(r===null)return r=L(L({},e),{events:P([],R(e.events),!1),attempts:0}),i=t,`continue`;if(i+t>4e6)return o(),r=L(L({},e),{events:P([],R(e.events),!1),attempts:0}),i=t,`continue`;var n=r.onComplete,s=e.onComplete;r.events=r.events.concat(e.events),i+=t,r.onComplete=function(){return N(a,void 0,void 0,function(){return I(this,function(e){switch(e.label){case 0:return[4,Promise.allSettled([n(),s()])];case 1:return e.sent(),[2]}})})}};try{for(var c=(t=void 0,z(e)),l=c.next();!l.done;l=c.next()){var u=l.value;s(u)}}catch(e){t={error:e}}finally{try{l&&!l.done&&(n=c.return)&&n.call(c)}finally{if(t)throw t.error}}o()};try{for(var m=z(o.values()),h=m.next();!h.done;h=m.next()){var g=h.value;p(g)}}catch(e){r={error:e}}finally{try{h&&!h.done&&(i=m.return)&&i.call(m)}finally{if(r)throw r.error}}return f},e.prototype.send=function(e,t){return t===void 0&&(t=!0),N(this,void 0,void 0,function(){var n,r,i,a;return I(this,function(o){return this.killedSessions.has(e.sessionId)?[2,this.completeRequest({context:e,err:Ir})]:(n=e.apiKey,n?(r=e.deviceId,r?(i=this.payloadBatcher({version:1,events:e.events}),i.events.length===0?(this.completeRequest({context:e}),[2]):(a=this.worker,a?[2,this.sendViaWorker(a,e,i,t)]:[2,this.sendOnMainThread(n,r,e,i,t)])):[2,this.completeRequest({context:e,err:Pr})]):[2,this.completeRequest({context:e,err:Fr})])})})},e.prototype.sendViaWorker=function(e,t,n,r){return N(this,void 0,void 0,function(){var i,a=this;return I(this,function(o){return i=`${++this.sendIdCounter}`,[2,new Promise(function(o){var s=a.sendTimeoutMs>0?setTimeout(function(){var e=a.pendingWorkerRequests.get(i);
2e&&(a.pendingWorkerRequests.delete(i),a.rememberTimedOutRequest(i,e.context),a.loggerProvider.warn(`Session replay worker send timed out after ${a.sendTimeoutMs}ms; leaving events for retry`),e.resolve())},a.sendTimeoutMs):void 0;a.pendingWorkerRequests.set(i,{context:t,resolve:o,timeout:s}),e.postMessage({type:`send`,id:i,payload:n,useRetry:r,useCustomTransport:!!a.handleSendEvents,context:{apiKey:t.apiKey,deviceId:t.deviceId,sessionId:t.sessionId,events:t.events,eventType:t.type,flushMaxRetries:t.flushMaxRetries??0,sampleRate:t.sampleRate,serverZone:t.serverZone,trackServerUrl:a.trackServerUrl,version:t.version,currentUrl:Qn(),sdkVersion:Lr,enableTransportCompression:a.enableTransportCompression,sendTimeoutMs:a.sendTimeoutMs}})})]})})},e.prototype.rememberTimedOutRequest=function(e,t){var n,r;if(this.timedOutWorkerRequests.set(e,t),this.timedOutWorkerRequests.size>Br)try{for(var i=z(this.timedOutWorkerRequests.keys()),a=i.next();!a.done;a=i.next()){var o=a.value;this.timedOutWorkerRequests.delete(o);break}}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}},e.prototype.handleDelegatedFetch=function(e,t){var n;return N(this,void 0,void 0,function(){var r,i,a,o,s,c,l,u,d,f,p;return I(this,function(m){switch(m.label){case 0:r=t.requestId,i=t.url,a=t.method,o=t.headers,s=t.body,c=t.keepalive,m.label=1;case 1:return m.trys.push([1,10,,11]),l=void 0,this.handleSendEvents?[4,this.handleSendEvents({url:i,method:a,headers:o,body:s,keepalive:c})]:[3,3];case 2:return l=m.sent(),[3,5];case 3:return this.loggerProvider.warn(`Delegated session replay fetch received without a custom transport configured; falling back to built-in fetch.`),[4,fetch(i,{method:a,headers:o,body:s,keepalive:c})];case 4:l=m.sent(),m.label=5;case 5:if(u=l.status,d=null,f=``,u>=200&&u<300&&(d=((n=l.headers)?.get)?.call(n,`X-Session-Replay-Event-Skipped`)??null),u!==413)return[3,9];m.label=6;case 6:return m.trys.push([6,8,,9]),[4,l.text()];case 7:return f=m.sent(),[3,9];case 8:return m.sent(),[3,9];case 9:return this.loggerProvider.debug(`Delegated session replay fetch (request ${r}) returned status ${u}.`),e.postMessage({type:`fetch-response`,requestId:r,status:u,skipHeader:d,body:f}),[3,11];case 10:return p=m.sent(),this.loggerProvider.debug(`Delegated session replay fetch (request ${r}) failed:`,p),e.postMessage({type:`fetch-response`,requestId:r,status:0,skipHeader:null,body:String(p),error:!0}),[3,11];case 11:return[2]}})})},e.prototype.sendOnMainThread=function(e,t,n,r,i){var a;return N(this,void 0,void 0,function(){var o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T,E,E,D,O;return I(this,function(k){switch(k.label){case 0:o=Qn(),s=Lr,c=n.sampleRate,l=new URLSearchParams({device_id:t,session_id:`${n.sessionId}`,type:`${n.type}`}),u=`${n.version?.type??`standalone`}/${n.version?.version??s}`,k.label=1;case 1:return k.trys.push([1,19,,23]),d=JSON.stringify(r),f=F(),this.enableTransportCompression&&f&&`CompressionStream`in f?[4,Rr(d,f)]:[3,3];case 2:return m=k.sent(),[3,4];case 3:m=null,k.label=4;case 4:if(p=m,h=p?p.byteLength:new Blob([d]).size,g=new AbortController,_=L({"Content-Type":`application/json`,Accept:`*/*`,Authorization:`Bearer ${e}`,"X-Client-Version":s,"X-Client-Library":u,"X-Client-Url":o.substring(0,In),"X-Client-Sample-Rate":`${c}`,"X-Sampling-Hash-Alg":`xxhash32`},p?{"Content-Encoding":`gzip`}:{}),v=p??d,y=h<=Ln,b={headers:_,body:v,method:`POST`,keepalive:y,signal:g.signal},x=`${Kn(n.serverZone,this.trackServerUrl)}?${l.toString()}`,r.events.length===0)return this.completeRequest({context:n}),[2];S=this.sendTimeoutMs>0?setTimeout(function(){g.abort()},this.sendTimeoutMs):void 0,C=void 0,k.label=5;case 5:return k.trys.push([5,,10,11]),this.handleSendEvents?[4,Vr(this.handleSendEvents({url:x,method:`POST`,headers:_,body:v,keepalive:y}),g.signal)]:[3,7];case 6:return w=k.sent(),[3,9];case 7:return[4,fetch(x,b)];case 8:w=k.sent(),k.label=9;case 9:return C=w,[3,11];case 10:return S&&clearTimeout(S),[7];case 11:if(C===null)return this.completeRequest({context:n,err:jr}),[2];if(C.status>=200&&C.status<300&&(T=((a=C.headers)?.get)?.call(a,`X-Session-Replay-Event-Skipped`)??null,this.applyServerDirective(n.sessionId,T)),i)return[3,12];E=``;try{E=JSON.stringify(C.body,null,2)}catch{}return this.completeRequest({context:n,success:`${C.status}: ${E}`}),[3,18];
2case 12:if(E=``,C.status!==413)return[3,16];k.label=13;case 13:return k.trys.push([13,15,,16]),[4,C.text()];case 14:return E=k.sent(),[3,16];case 15:return k.sent(),[3,16];case 16:return[4,this.handleReponse(C.status,n,E)];case 17:k.sent(),k.label=18;case 18:return[3,23];case 19:return D=k.sent(),O=!!D&&typeof D==`object`&&D.name===`AbortError`,O&&i?[4,this.handleOtherResponse(n)]:[3,21];case 20:return k.sent(),[3,22];case 21:this.completeRequest({context:n,err:D}),k.label=22;case 22:return[3,23];case 23:return[2]}})})},e.prototype.handleReponse=function(e,t,n){return n===void 0&&(n=``),N(this,void 0,void 0,function(){var r,i;return I(this,function(a){switch(a.label){case 0:switch(r=new ve().buildStatus(e),i=r,i){case ce.Success:return[3,1];case ce.Failed:return[3,2];case ce.Timeout:return[3,2];case ce.RateLimit:return[3,2];case ce.PayloadTooLarge:return[3,4]}return[3,5];case 1:return this.handleSuccessResponse(t),[3,8];case 2:return[4,this.handleOtherResponse(t)];case 3:return a.sent(),[3,8];case 4:return this.handlePayloadTooLargeResponse(t,kn.test(n)),[3,8];case 5:return e===499?[4,this.handleOtherResponse(t)]:[3,7];case 6:return a.sent(),[3,8];case 7:this.completeRequest({context:t,err:Mr}),a.label=8;case 8:return[2]}})})},e.prototype.handlePayloadTooLargeResponse=function(e,t){var n=t?`WAF (compressed payload too large)`:`server (event too large)`,r=Math.round(e.events.reduce(function(e,t){return e+t.length},0)/Fn);if(!t){this.completeRequest({context:e,err:`Session replay event batch dropped: ${n} rejected payload (${e.events.length} events, ${r} KB) — not retrying non-WAF 413`});return}if(e.events.length===1){this.completeRequest({context:e,err:`Session replay event dropped: single event (${r} KB, 1 event) rejected by ${n} — cannot split further`});return}this.loggerProvider.warn(`Session replay event batch rejected by ${n} (${e.events.length} events, ${r} KB total) — splitting and retrying`),e.onComplete();var i=function(){return Promise.resolve()},a=Math.floor(e.events.length/2);this.sendEventsList(L(L({},e),{events:e.events.slice(0,a),onComplete:i})),this.sendEventsList(L(L({},e),{events:e.events.slice(a),onComplete:i}))},e.prototype.handleSuccessResponse=function(e){var t=Math.round(new Blob(e.events).size/Fn);this.completeRequest({context:e,success:`Session replay event batch tracked successfully for session id ${e.sessionId}, size of events: ${t} KB`})},e.prototype.handleOtherResponse=function(e){return N(this,void 0,void 0,function(){var t;return I(this,function(n){switch(n.label){case 0:return t=Math.random()*e.attempts*this.retryTimeout,e.attempts++,e.attempts>(e.flushMaxRetries||0)?(this.completeRequest({context:e,err:Nr}),[2]):[4,new Promise(function(e){return setTimeout(e,t)})];case 1:return n.sent(),[4,this.send(e,!0)];case 2:return n.sent(),[2]}})})},e.prototype.completeRequest=function(e){var t=e.context,n=e.err,r=e.success;t.onComplete(),n?this.loggerProvider.warn(n):r&&this.loggerProvider.log(r)},e.prototype.applyServerDirective=function(e,t){if(t===null){this.flushPauseUntilMs=0,this.mergeLogFiredThisPause=!1;return}if(t===`429`){var n=this.flushPauseUntilMs>Date.now();this.flushPauseUntilMs=Date.now()+zn,n||this.loggerProvider.log(`Session replay throttled by server; pausing flush schedule for ${zn/1e3}s`);return}(t===`4005`||t===`4004`)&&this.killSession(e,t)},e.prototype.killSession=function(e,t){var n,r,i,a;if(!this.killedSessions.has(e)){if(this.killedSessions.add(e),this.killedSessions.size>zr)try{for(var o=z(this.killedSessions),s=o.next();!s.done;s=o.next()){var c=s.value;this.killedSessions.delete(c);break}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}this.loggerProvider.log(`Session replay capture stopped for session ${e} by server directive ${t}; remaining events will be dropped`);var l=[];try{for(var u=z(this.queue),d=u.next();!d.done;d=u.next()){var f=d.value;f.sessionId===e?this.completeRequest({context:f,err:Ir}):l.push(f)}}catch(e){i={error:e}}finally{try{d&&!d.done&&(a=u.return)&&a.call(u)}finally{if(i)throw i.error}}this.queue=l}},e}(),Ur=(e,t)=>
2t.some(t=>e instanceof t),Wr,Gr;function Kr(){return Wr||=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]}function qr(){return Gr||=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]}var Jr=new WeakMap,Yr=new WeakMap,Xr=new WeakMap;function Zr(e){let t=new Promise((t,n)=>{let r=()=>{e.removeEventListener(`success`,i),e.removeEventListener(`error`,a)},i=()=>{t(ri(e.result)),r()},a=()=>{n(e.error),r()};e.addEventListener(`success`,i),e.addEventListener(`error`,a)});return Xr.set(t,e),t}function Qr(e){if(Jr.has(e))return;let t=new Promise((t,n)=>{let r=()=>{e.removeEventListener(`complete`,i),e.removeEventListener(`error`,a),e.removeEventListener(`abort`,a)},i=()=>{t(),r()},a=()=>{n(e.error||new DOMException(`AbortError`,`AbortError`)),r()};e.addEventListener(`complete`,i),e.addEventListener(`error`,a),e.addEventListener(`abort`,a)});Jr.set(e,t)}var $r={get(e,t,n){if(e instanceof IDBTransaction){if(t===`done`)return Jr.get(e);if(t===`store`)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return ri(e[t])},set(e,t,n){return e[t]=n,!0},has(e,t){return e instanceof IDBTransaction&&(t===`done`||t===`store`)||t in e}};function ei(e){$r=e($r)}function ti(e){return qr().includes(e)?function(...t){return e.apply(ii(this),t),ri(this.request)}:function(...t){return ri(e.apply(ii(this),t))}}function ni(e){return typeof e==`function`?ti(e):(e instanceof IDBTransaction&&Qr(e),Ur(e,Kr())?new Proxy(e,$r):e)}function ri(e){if(e instanceof IDBRequest)return Zr(e);if(Yr.has(e))return Yr.get(e);let t=ni(e);return t!==e&&(Yr.set(e,t),Xr.set(t,e)),t}var ii=e=>Xr.get(e);function ai(e,t,{blocked:n,upgrade:r,blocking:i,terminated:a}={}){let o=indexedDB.open(e,t),s=ri(o);return r&&o.addEventListener(`upgradeneeded`,e=>{r(ri(o.result),e.oldVersion,e.newVersion,ri(o.transaction),e)}),n&&o.addEventListener(`blocked`,e=>n(e.oldVersion,e.newVersion,e)),s.then(e=>{a&&e.addEventListener(`close`,()=>a()),i&&e.addEventListener(`versionchange`,e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}var oi=[`get`,`getKey`,`getAll`,`getAllKeys`,`count`],si=[`put`,`add`,`delete`,`clear`],ci=new Map;function li(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t==`string`))return;if(ci.get(t))return ci.get(t);let n=t.replace(/FromIndex$/,``),r=t!==n,i=si.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(i||oi.includes(n)))return;let a=async function(e,...t){let a=this.transaction(e,i?`readwrite`:`readonly`),o=a.store;return r&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),i&&a.done]))[0]};return ci.set(t,a),a}ei(e=>({...e,get:(t,n,r)=>li(t,n)||e.get(t,n,r),has:(t,n)=>!!li(t,n)||e.has(t,n)}));var ui=[`continue`,`continuePrimaryKey`,`advance`],di={},fi=new WeakMap,pi=new WeakMap,mi={get(e,t){if(!ui.includes(t))return e[t];let n=di[t];return n||=di[t]=function(...e){fi.set(this,pi.get(this)[t](...e))},n}};async function*hi(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;let n=new Proxy(t,mi);for(pi.set(n,t),Xr.set(n,ii(t));t;)yield n,t=await(fi.get(n)||t.continue()),fi.delete(n)}function gi(e,t){return t===Symbol.asyncIterator&&Ur(e,[IDBIndex,IDBObjectStore,IDBCursor])||t===`iterate`&&Ur(e,[IDBIndex,IDBObjectStore])}ei(e=>({...e,get(t,n,r){return gi(t,n)?hi:e.get(t,n,r)},has(t,n){return gi(t,n)||e.has(t,n)}}));var _i=function(){function e(e){var t=this;this.minInterval=500,this.maxInterval=Mn,this.maxPersistedEventsSize=Dn,this._timeAtLastSplit=Date.now(),this.shouldSplitEventsList=function(e,n){var r=t.getStringSize(n);return t.getEventsArraySize(e)+r>=t.maxPersistedEventsSize?!0:Date.now()-t.timeAtLastSplit>t.interval&&e.length?(t.interval=Math.min(t.maxInterval,t.interval+t.minInterval),t._timeAtLastSplit=Date.now(),!0):!1},this.loggerProvider=e.loggerProvider,this.minInterval=e.minInterval??this.minInterval,this.maxInterval=e.maxInterval??this.maxInterval,this.maxPersistedEventsSize=e.maxPersistedEventsSize??this.maxPersistedEventsSize,this.interval=this.minInterval}return Object.defineProperty(e.prototype,"timeAtLastSplit",{get:function(){return this._timeAtLastSplit}
2,enumerable:!1,configurable:!0}),e.prototype.getStringSize=function(e){for(var t=0,n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<=127)t++;else if(r<=2047)t+=2;else if(r>=55296&&r<=56319){var i=n+1<e.length?e.charCodeAt(n+1):NaN;i>=56320&&i<=57343?(t+=4,n++):t+=3}else t+=3}return t},e.prototype.getEventsArraySize=function(e){var t,n,r=0;try{for(var i=z(e),a=i.next();!a.done;a=i.next()){var o=a.value;r+=this.getStringSize(o)}}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}var s=2+Math.max(0,e.length-1)+e.length*2;return r+s},e}(),vi=function(e){return typeof e==`object`&&!!e&&e.name===`AbortError`},Z=function(e,t,n){vi(n)?e.debug(t):e.warn(t)};function yi(){try{return crypto.randomUUID()}catch{return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,function(e){var t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}}var Q=`sessionCurrentSequence`,bi=`sequencesToSend`,xi=2e3,Si=5e3;function Ci(e,t,n){return n===void 0&&(n=`IDB operation timed out`),new Promise(function(r,i){var a=setTimeout(function(){return i(Error(`${n} after ${t}ms`))},t);e.then(function(e){clearTimeout(a),r(e)},function(e){clearTimeout(a),i(e)})})}function wi(e,t,n){var r=setTimeout(n,t);return e.then(function(){return clearTimeout(r)},function(){return clearTimeout(r)}),function(){return clearTimeout(r)}}var Ti=function(e){var t,n;return e.objectStoreNames.contains(`sessionCurrentSequence`)||(n=e.createObjectStore(Q,{keyPath:`sessionId`})),e.objectStoreNames.contains(`sequencesToSend`)||(t=e.createObjectStore(bi,{keyPath:`sequenceId`,autoIncrement:!0}),t.createIndex(`sessionId`,`sessionId`)),{sequencesStore:t,currentSequenceStore:n}},Ei=function(e){return N(void 0,void 0,void 0,function(){return I(this,function(t){switch(t.label){case 0:return[4,Ci(ai(e,1,{upgrade:Ti}),xi,`IDB openDB timed out`)];case 1:return[2,t.sent()]}})})},Di=function(e){oe(t,e);function t(t){var n=this;return n=e.call(this,t)||this,n.consecutiveFailures=0,n.hasTriggeredFallback=!1,n.emptyFilteredCount=0,n.getSequencesToSend=function(){return N(n,void 0,void 0,function(){var e,t,n,r,i,a,o,s,c,l,u=this;return I(this,function(d){switch(d.label){case 0:e=!1,t=!1,d.label=1;case 1:return d.trys.push([1,9,,10]),n=[],r=this.db.transaction(`sequencesToSend`,`readwrite`),r.done.catch(function(n){!e&&!t&&(Z(u.loggerProvider,`${X}: ${n}`,n),u.recordFailure())}),i=wi(r.done,Si,function(){!e&&!t&&(t=!0,Z(u.loggerProvider,`${X}: transaction timed out`),u.recordFailure())}),[4,r.store.openCursor()];case 2:a=d.sent(),d.label=3;case 3:return a?(o=a.value,s=o.sessionId,c=o.events,c.length===0?(this.maybeLogEmptyFiltered(`getSequencesToSend`),[4,a.delete()]):[3,5]):[3,8];case 4:return d.sent(),[3,6];case 5:n.push({events:c,sequenceId:a.key,sessionId:s}),d.label=6;case 6:return[4,a.continue()];case 7:return a=d.sent(),[3,3];case 8:return this.recordSuccess(),i(),[2,n];case 9:return l=d.sent(),t||(e=!0,Z(this.loggerProvider,`${X}: ${l}`,l),this.recordFailure()),[3,10];case 10:return[2,void 0]}})})},n.storeCurrentSequence=function(e){return N(n,void 0,void 0,function(){var t,n,r,i,a,o,s,c,l=this;return I(this,function(u){switch(u.label){case 0:t=!1,n=!1,u.label=1;case 1:return u.trys.push([1,5,,6]),r=this.db.transaction([Q,bi],`readwrite`),r.done.catch(function(e){!t&&!n&&(Z(l.loggerProvider,`${X}: ${e}`,e),l.recordFailure())}),i=wi(r.done,Si,function(){!t&&!n&&(n=!0,Z(l.loggerProvider,`${X}: transaction timed out`),l.recordFailure())}),[4,r.objectStore(Q).get(e)];case 2:return a=u.sent(),!a||a.tabId&&a.tabId!==this.tabId?(i(),[2,void 0]):a.events.length===0?(this.maybeLogEmptyFiltered(`storeCurrentSequence`),i(),[2,void 0]):[4,r.objectStore(bi).put({sessionId:e,events:a.events,tabId:this.tabId})];case 3:return o=u.sent(),[4,r.objectStore(Q).put({sessionId:e,events:[],tabId:this.tabId})];case 4:return u.sent(),this.recordSuccess(),i(),a.tabId,s=se(a,[`tabId`]),[2,L(L({},s),{sessionId:e,sequenceId:o})];case 5:return c=u.sent(),n||(t=!0,Z(this.loggerProvider,`${X}: ${c}`,c),this.recordFailure()),[3,6];case 6:return[2,void 0]}})})},n.addEventToCurrentSequence=function(e,t){return N(n,void 0,void 0,function(){var n,r,i,a,o,s,c,l,u,d=this;return I(this,function(f){switch(f.label){case 0:n=!1,r=!1,f.label=1;case 1:return f.trys.push([1,15,,16]),i=this.db.transaction([Q,bi],`readwrite`),i.done.catch(function(e){!n&&!r&&(Z(d.loggerProvider,`${X}: ${e}`,e),d.recordFailure())}),a=wi(i.done,Si,function(){!n&&!r&&(r=!0,Z(d.loggerProvider,`${X}: transaction timed out`),d.recordFailure())}),[4,i.objectStore(Q).get(e)];case 2:return o=f.sent(),o?.tabId&&o.tabId!==this.tabId?o.events.length>0?[4,i.objectStore(bi).put({sessionId:e,events:o.events,tabId:o.tabId})]:[3,4]:[3,6];case 3:f.sent(),f.label=4;case 4:return[4,i.objectStore(Q).put({sessionId:e,events:[t],tabId:this.tabId})];case 5:return f.sent(),this.recordSuccess(),a(),[2,void 0];case 6:return s=o,s?[3,8]:[4,i.objectStore(Q).put({sessionId:e,events:[t],tabId:this.tabId})];case 7:return f.sent(),this.recordSuccess(),a(),[2,void 0];case 8:return this.shouldSplitEventsList(s.events,t)?[3,10]:[4,i.objectStore(Q).put({sessionId:e,events:s.events.concat(t),tabId:this.tabId})];case 9:return f.sent(),this.recordSuccess(),a(),[2,void 0];case 10:return c=s.events,c.length===0?(this.maybeLogEmptyFiltered(`addEventToCurrentSequence`),[4,i.objectStore(Q).put({sessionId:e,events:[t],tabId:this.tabId})]):[3,12];case 11:return f.sent(),this.recordSuccess(),a(),[2,void 0];case 12:return[4,i.objectStore(Q).put({sessionId:e,events:[t],tabId:this.tabId})];case 13:return f.sent(),[4,i.objectStore(bi).put({sessionId:e,events:c,tabId:this.tabId})];case 14:return l=f.sent(),this.recordSuccess(),a(),[2,{events:c,sessionId:e,sequenceId:l}];case 15:return u=f.sent(),r||(n=!0,Z(this.loggerProvider,`${X}: ${u}`,u),this.recordFailure()),[3,16];case 16:return[2,void 0]}})})},n.storeSendingEvents=function(e,t){return N(n,void 0,void 0,function(){var n,r;return I(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.db.put(bi,{sessionId:e,events:t,tabId:this.tabId})];case 1:return n=i.sent(),this.recordSuccess(),[2,n];case 2:return r=i.sent(),Z(this.loggerProvider,`${X}: ${r}`,r),this.recordFailure(),[3,3];case 3:return[2,void 0]}})})},n.cleanUpSessionEventsStore=function(e,t){return N(n,void 0,void 0,function(){var e;return I(this,function(n){switch(n.label){case 0:if(!t)return[2];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.db.delete(bi,t)];case 2:return n.sent(),this.recordSuccess(),[3,4];case 3:return e=n.sent(),Z(this.loggerProvider,`${X}: ${e}`,e),this.recordFailure(),[3,4];case 4:return[2]}})})},n.db=t.db,n.tabId=t.tabId,n.onPersistentFailure=t.onPersistentFailure,n.consecutiveFailureThreshold=t.consecutiveFailureThreshold??1,n}return t.prototype.maybeLogEmptyFiltered=function(e){this.emptyFilteredCount++%100==0&&this.loggerProvider.debug(`Filtered empty session replay sequence at ${e} (idb store)`)},t.prototype.recordFailure=function(){var e;this.consecutiveFailures++,!this.hasTriggeredFallback&&this.consecutiveFailures>=this.consecutiveFailureThreshold&&(this.hasTriggeredFallback=!0,(e=this.onPersistentFailure)==null||e.call(this))},t.prototype.recordSuccess=function(){this.consecutiveFailures=0},t.new=function(e,n){return N(this,void 0,void 0,function(){var r,i,a,o,s;return I(this,function(c){switch(c.label){case 0:return c.trys.push([0,2,,3]),r=e===`replay`?``:`_${e}`,i=`${n.apiKey.substring(0,10)}_amp_session_replay_events${r}`,[4,Ei(i)];case 1:return a=c.sent(),o=n.tabId??yi(),[2,new t(L(L({},n),{db:a,tabId:o}))];case 2:return s=c.sent(),Z(n.loggerProvider,`${X}: ${s}`,s),[3,3];case 3:return[2]}})})},t.prototype.getCurrentSequenceEvents=function(e){return N(this,void 0,void 0,function(){var t,n,r,i,a,t,n,o,s,c;return I(this,function(l){switch(l.label){case 0:return e?[4,this.db.get(`sessionCurrentSequence`,e)]:[3,2];case 1:return t=l.sent(),!t||t.tabId&&t.tabId!==this.tabId?[2,void 0]:(t.tabId,n=se(t,[`tabId`]),[2,[n]]);case 2:r=[],l.label=3;case 3:return l.trys.push([3,8,9,10]),[4,this.db.getAll(`sessionCurrentSequence`)];case 4:i=z.apply(void 0,[l.sent()]),a=i.next(),l.label=5;case 5:if(a.done)return[3,7];if(t=a.value,t.tabId&&t.tabId!==this.tabId)return[3,6];t.tabId,n=se(t,[`tabId`]),r.push(n),l.label=6;case 6:return a=i.next(),[3,5];case 7:return[3,10];case 8:return o=l.sent(),s={error:o},[3,10];case 9:try{a&&!a.done&&(c=i.return)&&c.call(i)}finally{if(s)throw s.error}
2return[7];case 10:return[2,r]}})})},t}(_i),Oi=function(e){oe(t,e);function t(){var t=e!==null&&e.apply(this,arguments)||this;return t.finalizedSequences={},t.sequences={},t.sequenceId=0,t.emptyFilteredCount=0,t}return t.prototype.resetCurrentSequence=function(e){this.sequences[e]=[]},t.prototype.addSequence=function(e){var t=this.sequenceId++,n=P([],R(this.sequences[e]),!1);return this.finalizedSequences[t]={sessionId:e,events:n},this.resetCurrentSequence(e),{sequenceId:t,events:n,sessionId:e}},t.prototype.maybeLogEmptyFiltered=function(e){this.emptyFilteredCount++%100==0&&this.loggerProvider.debug(`Filtered empty session replay sequence at ${e} (in-memory store)`)},t.prototype.getSequencesToSend=function(){return N(this,void 0,void 0,function(){var e,t,n,r,i,a,o,s,c,l;return I(this,function(u){e=[];try{for(t=z(Object.entries(this.finalizedSequences)),n=t.next();!n.done;n=t.next()){if(r=R(n.value,2),i=r[0],a=r[1],o=a.sessionId,s=a.events,s.length===0){this.maybeLogEmptyFiltered(`getSequencesToSend`),delete this.finalizedSequences[Number(i)];continue}e.push({sequenceId:Number(i),sessionId:o,events:s})}}catch(e){c={error:e}}finally{try{n&&!n.done&&(l=t.return)&&l.call(t)}finally{if(c)throw c.error}}return[2,e]})})},t.prototype.storeCurrentSequence=function(e){return N(this,void 0,void 0,function(){var t;return I(this,function(n){return t=this.sequences[e],t?t.length===0?(this.maybeLogEmptyFiltered(`storeCurrentSequence`),[2,void 0]):[2,this.addSequence(e)]:[2,void 0]})})},t.prototype.addEventToCurrentSequence=function(e,t){return N(this,void 0,void 0,function(){var n;return I(this,function(r){return this.sequences[e]||this.resetCurrentSequence(e),this.shouldSplitEventsList(this.sequences[e],t)&&(this.sequences[e].length===0?this.maybeLogEmptyFiltered(`addEventToCurrentSequence`):n=this.addSequence(e)),this.sequences[e].push(t),[2,n]})})},t.prototype.storeSendingEvents=function(e,t){return N(this,void 0,void 0,function(){return I(this,function(n){return this.finalizedSequences[this.sequenceId]={sessionId:e,events:t},[2,this.sequenceId++]})})},t.prototype.cleanUpSessionEventsStore=function(e,t){return N(this,void 0,void 0,function(){return I(this,function(e){return t!==void 0&&delete this.finalizedSequences[t],[2]})})},t}(_i),ki=function(e){var t=e.config,n=e.minInterval,r=e.maxInterval,i=e.maxPersistedEventsSize,a=e.type,o=e.payloadBatcher,s=e.storeType,c=e.trackDestinationWorkerScript,l=e.shouldSend;return N(void 0,void 0,void 0,function(){function e(e){return e===void 0&&(e=!1),N(this,void 0,void 0,function(){return I(this,function(t){return[2,d.flush(e)]})})}var u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T,E,D;return I(this,function(O){switch(O.label){case 0:return u=t.maxSingleEventSizeBytes??On,d=new Hr(L(L({},t),{loggerProvider:t.loggerProvider,payloadBatcher:o,workerScript:c})),f=function(){return new Oi({loggerProvider:t.loggerProvider,maxInterval:r,minInterval:n,maxPersistedEventsSize:i})},m=!1,g=function(){return N(void 0,void 0,void 0,function(){var e,n,r;return I(this,function(i){switch(i.label){case 0:return m?(m=!1,t.loggerProvider.warn(`IDB store is experiencing repeated failures; falling back to in-memory event store.`),p?[4,h.getSequencesToSend()]:[3,2]):[2];case 1:return n=i.sent(),[3,3];case 2:n=void 0,i.label=3;case 3:return e=n,h=f(),e&&p&&(r=p,e.forEach(function(e){S({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:r})})),[2]}})})},_=function(){return N(void 0,void 0,void 0,function(){var e;return I(this,function(o){switch(o.label){case 0:return[4,Di.new(a,{loggerProvider:t.loggerProvider,minInterval:n,maxInterval:r,maxPersistedEventsSize:i,apiKey:t.apiKey,onPersistentFailure:function(){g()}})];case 1:return e=o.sent(),e?(m=!0,[2,e]):(t.loggerProvider.log(`Failed to initialize idb store, falling back to memory store.`),[2,f()])}})})},s===`idb`?[4,_()]:[3,2];case 1:return v=O.sent(),[3,3];case 2:v=f(),O.label=3;case 3:return h=v,y=[],b=0,x=function(e){if(!(e<=b)){var t=Math.min(e-b,y.length);t>0&&(y.splice(0,t),b=e)}},S=function(e){var n=e.events,r=e.sessionId,i=e.deviceId,o=e.sequenceId,s=n.map(function(e){return{event:e,bytes:new Blob([e]).size}}
2),c=s.filter(function(e){return e.bytes>u});c.length>0&&t.loggerProvider.warn(`Dropping ${c.length} oversized event(s) from session replay sequence before send. Sizes: ${c.map(function(e){return`${Math.round(e.bytes/1024)} KB`}).join(`, `)}. If this recurs, please open a GitHub issue at https://github.com/amplitude/Amplitude-TypeScript/issues or contact Amplitude support.`);var l=c.length>0?s.filter(function(e){return e.bytes<=u}).map(function(e){return e.event}):n;if(l.length===0){h.cleanUpSessionEventsStore(r,o).catch(function(e){t.loggerProvider.warn(`Failed to clean up session replay events store:`,e)});return}t.debugMode&&ar().then(function(e){var n=e.totalStorageSize,r=e.percentOfQuota,i=e.usageDetails;t.loggerProvider.debug(`Total storage size: ${n} KB, percentage of quota: ${r}%, usage details: ${i}`)}).catch(function(){}),d.sendEventsList({events:l,sessionId:r,flushMaxRetries:t.flushMaxRetries,apiKey:t.apiKey,deviceId:i,sampleRate:t.sampleRate,serverZone:t.serverZone,version:t.version,type:a,onComplete:function(){return N(void 0,void 0,void 0,function(){return I(this,function(e){switch(e.label){case 0:return[4,h.cleanUpSessionEventsStore(r,o)];case 1:return e.sent(),[2]}})})}})},C=function(e){var n=e.sessionId,r=e.deviceId;if(p=r,!(l&&!l())){var i=b+y.length;h.storeCurrentSequence(n).then(function(e){e&&(x(i),S({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:r}))}).catch(function(e){t.loggerProvider.warn(`Failed to get current sequence of session replay events for session:`,e)})}},w=function(e){var n=e.deviceId;return N(void 0,void 0,void 0,function(){var e;return I(this,function(r){switch(r.label){case 0:return p=n,[4,h.getSequencesToSend()];case 1:return e=r.sent(),e?.length?(t.loggerProvider.log(`Draining ${e.length} stored sequence(s) from previous session.`),e.length>1&&d.markCoalesceNextFlush(),e.forEach(function(e){S({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:n})}),[2]):[2]}})})},T=function(e){var n=e.event,r=e.sessionId,i=e.deviceId;p=i;var a=!l||l(),o=b+y.length;y.push(n.data),h.addEventToCurrentSequence(r,n.data).then(function(e){if(e){if(!a){h.cleanUpSessionEventsStore(e.sessionId,e.sequenceId).catch(function(e){t.loggerProvider.warn(`Failed to clean up dropped session replay sequence:`,e)}),x(o);return}x(o),S({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:i})}}).catch(function(e){t.loggerProvider.warn(`Failed to add event to session replay capture:`,e)})},E=function(){return P([],R(y),!1)},D=function(){x(b+y.length)},[2,{sendCurrentSequenceEvents:C,addEvent:T,sendStoredEvents:w,flush:e,getBeaconEvents:E,dropPendingBeaconEvents:D,trackDestination:d}]}})})},Ai=function(){function e(){var e=[...arguments],t=new Map;e.forEach(function(e){t.set(e.name,e.manager)}),this.managers=t}return e.prototype.sendStoredEvents=function(e){return N(this,void 0,void 0,function(){var t;return I(this,function(n){switch(n.label){case 0:return t=[],this.managers.forEach(function(n){t.push(n.sendStoredEvents(e))}),[4,Promise.all(t)];case 1:return n.sent(),[2]}})})},e.prototype.addEvent=function(e){var t,n=e.sessionId,r=e.event,i=e.deviceId;(t=this.managers.get(r.type))==null||t.addEvent({sessionId:n,event:r,deviceId:i})},e.prototype.sendCurrentSequenceEvents=function(e){var t=e.sessionId,n=e.deviceId;this.managers.forEach(function(e){e.sendCurrentSequenceEvents({sessionId:t,deviceId:n})})},e.prototype.flush=function(e){return N(this,void 0,void 0,function(){var t;return I(this,function(n){switch(n.label){case 0:return t=[],this.managers.forEach(function(n){t.push(n.flush(e))}),[4,Promise.all(t)];case 1:return n.sent(),[2]}})})},e}(),$,ji,Mi;function Ni(e,t){if(Mi=new Date,e.nodeType!==Node.ELEMENT_NODE)throw Error(`Can't generate CSS selector for non-element node type.`);if(e.tagName.toLowerCase()===`html`)return`html`;var n={root:document.body,idName:function(e){return!0},className:function(e){return!0},tagName:function(e){return!0},attr:function(e,t){return!1},seedMinLength:1,optimizedMinLength:2,threshold:1e3,maxNumberOfTries:1e4,timeoutMs:void 0};$=L(L({},n),t),ji=Pi($.root,n);var r=Fi(e,`all`,function(){return Fi(e,`two`,function(){return Fi(e,`one`,function(){return Fi(e,`none`)})})});if(r){var i=Zi(Qi(r,e));return i.length>0&&(r=i[0]),Li(r)}throw Error(`Selector was not found.`)}
2function Pi(e,t){return e.nodeType===Node.DOCUMENT_NODE?e:e===t.root?e.ownerDocument:e}function Fi(e,t,n){for(var r=null,i=[],a=e,o=0,s=function(){var e,s,c=new Date().getTime()-Mi.getTime();if($.timeoutMs!==void 0&&c>$.timeoutMs)throw Error(`Timeout: Can't find a unique selector after ${c}ms`);var l=Ji(Bi(a))||Ji.apply(void 0,P([],R(Vi(a)),!1))||Ji.apply(void 0,P([],R(Hi(a)),!1))||Ji(Ui(a))||[Wi()],u=Gi(a);if(t==`all`)u&&(l=l.concat(l.filter(qi).map(function(e){return Ki(e,u)})));else if(t==`two`)l=l.slice(0,1),u&&(l=l.concat(l.filter(qi).map(function(e){return Ki(e,u)})));else if(t==`one`){var d=R(l=l.slice(0,1),1)[0];u&&qi(d)&&(l=[Ki(d,u)])}else t==`none`&&(l=[Wi()],u&&(l=[Ki(l[0],u)]));try{for(var f=(e=void 0,z(l)),p=f.next();!p.done;p=f.next()){var d=p.value;d.level=o}}catch(t){e={error:t}}finally{try{p&&!p.done&&(s=f.return)&&s.call(f)}finally{if(e)throw e.error}}if(i.push(l),i.length>=$.seedMinLength&&(r=Ii(i,n),r))return`break`;a=a.parentElement,o++};a&&s()!==`break`;);return r||=Ii(i,n),!r&&n?n():r}function Ii(e,t){var n,r,i=Zi(Xi(e));if(i.length>$.threshold)return t?t():null;try{for(var a=z(i),o=a.next();!o.done;o=a.next()){var s=o.value;if(zi(s))return s}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}return null}function Li(e){for(var t=e[0],n=t.name,r=1;r<e.length;r++){var i=e[r].level||0;n=t.level===i-1?`${e[r].name} > ${n}`:`${e[r].name} ${n}`,t=e[r]}return n}function Ri(e){return e.map(function(e){return e.penalty}).reduce(function(e,t){return e+t},0)}function zi(e){var t=Li(e);switch(ji.querySelectorAll(t).length){case 0:throw Error(`Can't select any node with this selector: ${t}`);case 1:return!0;default:return!1}}function Bi(e){var t=e.getAttribute(`id`);return t&&$.idName(t)?{name:`#`+CSS.escape(t),penalty:0}:null}function Vi(e){return Array.from(e.attributes).filter(function(e){return $.attr(e.name,e.value)}).map(function(e){return{name:`[${CSS.escape(e.name)}="${CSS.escape(e.value)}"]`,penalty:.5}})}function Hi(e){return Array.from(e.classList).filter($.className).map(function(e){return{name:`.`+CSS.escape(e),penalty:1}})}function Ui(e){var t=e.tagName.toLowerCase();return $.tagName(t)?{name:t,penalty:2}:null}function Wi(){return{name:`*`,penalty:3}}function Gi(e){var t=e.parentNode;if(!t)return null;var n=t.firstChild;if(!n)return null;for(var r=0;n&&(n.nodeType===Node.ELEMENT_NODE&&r++,n!==e);)n=n.nextSibling;return r}function Ki(e,t){return{name:e.name+`:nth-child(${t})`,penalty:e.penalty+1}}function qi(e){return e.name!==`html`&&!e.name.startsWith(`#`)}function Ji(){var e=[...arguments].filter(Yi);return e.length>0?e:null}function Yi(e){return e!=null}function Xi(e,t){var n,r,i,a,o,s;return t===void 0&&(t=[]),I(this,function(c){switch(c.label){case 0:if(!(e.length>0))return[3,9];c.label=1;case 1:c.trys.push([1,6,7,8]),n=z(e[0]),r=n.next(),c.label=2;case 2:return r.done?[3,5]:(i=r.value,[5,z(Xi(e.slice(1,e.length),t.concat(i)))]);case 3:c.sent(),c.label=4;case 4:return r=n.next(),[3,2];case 5:return[3,8];case 6:return a=c.sent(),o={error:a},[3,8];case 7:try{r&&!r.done&&(s=n.return)&&s.call(n)}finally{if(o)throw o.error}return[7];case 8:return[3,11];case 9:return[4,t];case 10:c.sent(),c.label=11;case 11:return[2]}})}function Zi(e){return P([],R(e),!1).sort(function(e,t){return Ri(e)-Ri(t)})}function Qi(e,t,n){var r,i,a;return n===void 0&&(n={counter:0,visited:new Map}),I(this,function(o){switch(o.label){case 0:if(!(e.length>2&&e.length>$.optimizedMinLength))return[3,5];r=1,o.label=1;case 1:return r<e.length-1?n.counter>$.maxNumberOfTries||(n.counter+=1,i=P([],R(e),!1),i.splice(r,1),a=Li(i),n.visited.has(a))?[2]:zi(i)&&$i(i,t)?[4,i]:[3,4]:[3,5];case 2:return o.sent(),n.visited.set(a,!0),[5,z(Qi(i,t,n))];case 3:o.sent(),o.label=4;case 4:return r++,[3,1];case 5:return[2]}})}function $i(e,t){return ji.querySelector(Li(e))===t}var ea=36e5,ta=function(e){var t=e.version,n=e.events,r=[];return n.forEach(function(e){var t=JSON.parse(e);t.count=1,t.type===`click`&&r.push(t)}),{version:t,events:r}},na=function(e){var t=e.version,n=e.events,r=[];n.forEach(function(e){var t=JSON.parse(e);t.type===`click`&&r.push(t)});var i=r.reduce(function(e,t){var n=t.x,r=t.y,i=t.selector,a=t.timestamp,o=a-a%ea,s=`${n}:${r}:${i??``}:${o}`;return e[s]?e[s].count+=1:e[s]=L(L({},t),{timestamp:o,count:1}),e},{});return{version:t,events:Object.values(i)}},ra=function(){function e(e,t){var n=this;this.createHook=function(e){var t=e.eventsManager,r=e.sessionId,i=e.deviceIdFn,a=e.mirror,o=e.ugcFilterRules,s=e.performanceOptions;return function(e){if(e.type===_r.Click){var c=F();if(c){var l=c.location,u=c.innerHeight,d=c.innerWidth;if(l){var f=e.x,p=e.y;if(f!==void 0&&p!==void 0){var m=a.getNode(e.id),h;if(m)try{h=Ni(m,s)}catch{n.logger.debug(`error resolving selector from finder`)}var g=ir(l.href,o),_={x:f+n.scrollWatcher.currentScrollX,y:p+n.scrollWatcher.currentScrollY,selector:h,viewportHe
2ight:u,viewportWidth:d,pageUrl:g,timestamp:Date.now(),type:`click`},v=i();v&&t.addEvent({sessionId:r,event:{type:`interaction`,data:JSON.stringify(_)},deviceId:v})}}}}}},this.logger=e,this.scrollWatcher=t}return e}();function ia(){return F()?.innerHeight||document.documentElement&&document.documentElement.clientHeight||0}function aa(){return F()?.innerWidth||document.documentElement&&document.documentElement.clientWidth||0}var oa=function(){function e(e,t){var n=F();this.sendBeacon=n&&n.navigator&&typeof n.navigator.sendBeacon==`function`?function(e,t){try{if(n.navigator.sendBeacon(e,JSON.stringify(t)))return!0}catch{}return!1}:function(){return!1},this.sendXhr=function(e,t){var n=new XMLHttpRequest;return n.open(`POST`,e,!0),n.setRequestHeader(`Accept`,`*/*`),n.send(JSON.stringify(t)),!0},this.basePageUrl=Kn(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e,this.handleSendEvents=t.handleSendEvents,this.loggerProvider=t.loggerProvider}return e.prototype.send=function(e,t){var n=this,r,i=this.context,a=i.sessionId,o=i.t
2ype;if(this.handleSendEvents){var s=new URLSearchParams({device_id:e,session_id:String(a),type:String(o)}),c=`${this.basePageUrl}?${s.toString()}`,l={"Content-Type":`application/json`,Accept:`*/*`,Authorization:`Bearer ${this.apiKey}`};try{this.handleSendEvents({url:c,method:`POST`,headers:l,body:JSON.stringify(t),keepalive:!0}).catch(function(e){var t;(t=n.loggerProvider)==null||t.warn(`Custom transport failed to send session replay interaction beacon:`,e)})}catch(e){(r=this.loggerProvider)==null||r.warn(`Custom transport threw while sending session replay interaction beacon:`,e)}return}var u=new URLSearchParams({device_id:e,session_id:String(a),type:String(o),api_key:this.apiKey}),d=`${this.basePageUrl}?${u.toString()}`;this.sendBeacon(d,t)||this.sendXhr(d,t)},e}(),sa=function(){function e(e,t){var n=this;this.timestamp=Date.now(),this.hook=function(e){n.update(e)},this.send=function(e){return function(t){var r=e(),i=F();if(i&&r){var a=i.scrollX??0,o=i.scrollY??0;(a>0||o>0)&&n.update({id:1,x:a,y:o}),n.transport.send(r,{version:1,events:[{maxScrollX:n._maxScrollX,maxScrollY:n._maxScrollY,maxScrollWidth:n._maxScrollWidth,maxScrollHeight:n._maxScrollHeight,viewportHeight:ia(),viewportWidth:aa(),pageUrl:ir(i.location.href,n.config.interactionConfig?.ugcFilterRules??[]),timestamp:n.timestamp,type:`scroll`}]})}}},this._maxScrollX=0,this._maxScrollY=0,this._currentScrollX=0,this._currentScrollY=0,this._maxScrollWidth=aa(),this._maxScrollHeight=ia(),this.config=t,this.transport=e}return e.default=function(t,n){return new e(new oa(t,n),n)},Object.defineProperty(e.prototype,"maxScrollX",{get:function(){return this._maxScrollX},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxScrollY",{get:function(){return this._maxScrollY},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxScrollWidth",{get:function(){return this._maxScrollWidth},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxScrollHeight",{get:function(){return this._maxScrollHeight},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentScrollX",{get:function(){return this._currentScrollX},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentScrollY",{get:function(){return this._currentScrollY},enumerable:!1,configurable:!0}),e.prototype.update=function(e){var t=Date.now();if(this._currentScrollX=e.x,this._currentScrollY=e.y,e.x>this._maxScrollX){var n=aa();this._maxScrollX=e.x;var r=e.x+n;r>this._maxScrollWidth&&(this._maxScrollWidth=r),this.timestamp=t}if(e.y>this._maxScrollY){var i=ia();this._maxScrollY=e.y;var a=e.y+i;a>this._maxScrollHeight&&(this._maxScrollHeight=a),this.timestamp=t}},e}(),ca=function(){function e(e){var t=e.sessionId,n=e.deviceId;this.deviceId=n,this.sessionId=t,t&&n&&(this.sessionReplayId=$n(t,n))}return e}(),la=`AMP_SR_START_`,ua=10,da=function(e){return`${la}${e.substring(0,ua)}_`},fa=function(e,t){return`${da(e)}${t}`},pa=function(){try{return F()?.localStorage}catch{return}},ma=function(e,t,n,r){var i=pa();if(i){var a=fa(e,t);try{var o=i.getItem(a);if(o!==null){var s=Number(o);if(Number.isFinite(s)&&s>0&&s<=n&&n-s<864e5)return s}return i.setItem(a,String(n)),n}catch(e){r?.debug(`Failed to read/write replay start time from storage: ${String(e)}`);return}}},ha=function(e,t,n,r){var i=pa();if(i)try{i.setItem(fa(e,t),String(n))}catch(e){r?.debug(`Failed to write replay start time to storage: ${String(e)}`)}},ga=function(e,t,n){var r=pa();if(r)try{r.removeItem(fa(e,t))}catch(e){n?.debug(`Failed to remove replay start time from storage: ${String(e)}`)}},_a=function(e,t,n){var r,i,a=pa();if(a){var o=da(e);try{for(var s=[],c=0;c<a.length;c++){var l=a.key(c);if(!(!l||!l.startsWith(o))){var u=a.getItem(l);if(u!==null){var d=Number(u);(!Number.isFinite(d)||d<=0||t-d>=864e5)&&s.push(l)}}}try{for(var f=z(s),p=f.next();!p.done;p=f.next()){var l=p.value;a.removeItem(l)}}catch(e){r={error:e}}finally{try{p&&!p.done&&(i=f.return)&&i.call(f)}finally{if(r)throw r.error}}}catch(e){n?.debug(`Failed to prune stale replay start times: ${String(e)}`)}}},va=new(function(){function e(){var e=this;this.dbs={},this.createStore=function(t){return N(e,void 0,void 0,function(){return I(this,function(e){switch(e.label){case 0:return[4,ai(t,1,{upgrade:function(e){e.objectStoreNames.contains(`sessionTargetingMatch`)||e.createObjectStore(`sessionTargetingMatch`,{keyPath:`sessionId`})}})];case 1:return[2,e.sent()]}})})},this.openOrCreateDB=function(t){return N(e,void 0,void 0,function(){var e,n;return I(this,function(r){switch(r.label){case 0:return this.dbs&&this.dbs[t]?[2,this.dbs[t]]:(e=`${t.substring(0,10)}_amp_session_replay_targeting`,[4,this.createStore(e)]);case 1:return n=r.sent(),this.dbs[t]=n,[2,n]}})})},this.getTargetingMatchForSession=function(t){var n=t.loggerProvider,r=t.apiKey,i=t.sessionId;return N(e,void 0,void 0,function(){var e,t,a,o;return I(this,function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,this.openOrCreateDB(r)];case 1:return e=s.sent(),t=String(i),[4,e.get(`sessionTargetingMatch`,t)];case 2:return a=s.sent(),[2,a?.targetingMatch];case 3:return o=s.sent(),Z(n,`Failed to get targeting match for session id ${i}: ${o}`,o),[3,4];case 4:return[2,void 0]}})})},this.storeTargetingMatchForSession=function(t){var n=t.loggerProvider,r=t.apiKey,i=t.sessionId,a=t.targetingMatch;return N(e,void 0,void 0,function(){var e,t,o,s;return I(this,function(c){switch(c.label){case 0:return c.trys.push([0,3,,4]),[4,this.openOrCreateDB(r)];case 1:return e=c.sent(),t=String(i),[4,e.put(`sessionTargetingMatch`,{targetingMatch:a,sessionId:t,lastUpdated:Date.now()})];case 2:return o=c.sent(),[2,o];case 3:return s=c.sent(),Z(n,`Failed to store targeting match for session id ${i}: ${s}`,s),[3,4];case 4:return[2,void 0]}})})},this.clearStoreOfOldSessions=function(t){var n=t.loggerProvider,r=t.apiKey,i=t.currentSessionId;return N(e,void 0,void 0,function(){var e,t,a,o,s,c,l,u;return I(this,function(d){switch(d.label){case 0:return d.trys.push([0,8,,9]),[4,this.openOrCreateDB(r)];case 1:return e=d.sent(),t=String(i),a=e.transaction(`sessionTargetingMatch`,`readwrite`),[4,a.store.getAll()];case 2:o=d.sent(),s=0,d.label=3;case 3:return s<o.length?(c=o[s],l=Date.now()-c.lastUpdated,c.sessionId!==t&&l>1728e5?[4,a.store.delete(c.sessionId)]:[3,5]):[3,6];case 4:d.sent(),d.label=5;case 5:return s++,[3,3];case 6:return[4,a.done];case 7:return d.sent(),[3,9];case 8:return u=d.sent(),Z(n,`Failed to clear old targeting matches for sessions: ${u}`,u),[3,9];case 9:return[2]}})})}}return e}()),ya=function(e){var t=e.sessionId,n=e.targetingConfig,r=e.loggerProvider,i=e.apiKey,a=e.targetingParams,o=e.urlChange,s=o!==void 0&&o;return N(void 0,void 0,void 0,function(){var e,o,c,l,u,d,f;return I(this,function(p){switch(p.label){case 0:return[4,va.clearStoreOfOldSessions({loggerProvider:r,apiKey:i,currentSessionId:t})];case 1:return p.sent(),[4,va.getTargetingMatchForSession({loggerProvider:r,apiKey:i,sessionId:t})];case 2:if(e=p.sent(),e===!0&&!s)return[2,!0];o=!0,p.label=3;case 3:return p.trys.push([3,6,,7]),[4,je(()=>import(`./esm-Dlxfe34J.js`),__vite__mapDeps([0,1]))];case 4:return c=p.sent().evaluateTargeting,l=L(L({},a),{flag:n,sessionId:typeof t==`string`?parseInt(t,10):t,apiKey:i,loggerProvider:r}),[4,c(l)];case 5:return u=p.sent(),u&&u.sr_targeting_config&&(o=u.sr_targeting_config.key===`on`),va.storeTargetingMatchForSession({loggerProvider:r,apiKey:i,sessionId:t,targetingMatch:o}),[3,7];case 6:return d=p.sent(),f=d,r.warn(f.message),[3,7];case 7:return[2,o]}})})},ba=2654435761,xa=2246822519,Sa=3266489917,Ca=668265263,wa=374761393;function Ta(e,t){return(e<<t|e>>>32-t)>>>0}function Ea(e,t){return e=e+Math.imul(t,xa)>>>0,e=Ta(e,13),e=Math.imul(e,ba)>>>0,e}function Da(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function Oa(e){for(var t=[],n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r>=55296&&r<=56319&&n+1<e.length){var i=e.charCodeAt(n+1);i>=56320&&i<=57343&&(r=(r-55296<<10)+(i-56320)+65536,n++)}r<128?t.push(r):r<2048?t.push(192|r>>6,128|r&63):r<65536?t.push(224|r>>12,128|r>>6&63,128|r&63):t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}return new Uint8Array(t)}
2function ka(e,t){t===void 0&&(t=0);var n=Oa(e),r=n.length,i,a=0;if(r>=16){for(var o=t+ba+xa>>>0,s=t+xa>>>0,c=t>>>0,l=t-ba>>>0;a<=r-16;)o=Ea(o,Da(n,a)),a+=4,s=Ea(s,Da(n,a)),a+=4,c=Ea(c,Da(n,a)),a+=4,l=Ea(l,Da(n,a)),a+=4;i=Ta(o,1)+Ta(s,7)+Ta(c,12)+Ta(l,18)>>>0}else i=t+wa>>>0;for(i=i+r>>>0;a<=r-4;)i=i+Math.imul(Da(n,a),Sa)>>>0,i=Math.imul(Ta(i,17),Ca)>>>0,a+=4;for(;a<r;)i=i+Math.imul(n[a],wa)>>>0,i=Math.imul(Ta(i,11),ba)>>>0,a++;return i^=i>>>15,i=Math.imul(i,xa)>>>0,i^=i>>>13,i=Math.imul(i,Sa)>>>0,i^=i>>>16,i>>>0}function Aa(e,t){return ka(e.toString())%1e6/1e6<t}var ja=`__amplitude_url_tracking_patched__`,Ma=new WeakMap;function Na(e,t,n){if(n===void 0&&(n={}),!e?.location)return function(){};var r=n.enablePolling,i=r!==void 0&&r,a=n.pollingInterval,o=a===void 0?vn:a;if(i){var s=function(){return e.location.href??``},c=s(),l=e.setInterval(function(){var e=s();e!==c&&(c=e,t(e))},o);return function(){l!=null&&e.clearInterval(l)}}var u=Ma.get(e);if(!u){var d=void 0,f=new Set,p=function(){return e.location.href??``},m=function(){var e=p();(d===void 0||e!==d)&&(d=e,f.forEach(function(t){return t(e)}))},h=function(e){var t=function(){var t=[...arguments],n=e.apply(this,t);return m(),n};return t[ja]=!0,t},g=e.history;if(g?.pushState){var _=Reflect.get(g,`pushState`);_[ja]||(g.pushState=h(_))}if(g?.replaceState){var v=Reflect.get(g,`replaceState`);v[ja]||(g.replaceState=h(v))}u={callbacks:f,notify:m,onPopStateOrHashChange:function(){return m()},listenersAttached:!1},Ma.set(e,u)}var y=u;return y.listenersAttached||=(e.addEventListener(`popstate`,y.onPopStateOrHashChange),e.addEventListener(`hashchange`,y.onPopStateOrHashChange),!0),y.callbacks.add(t),function(){y.callbacks.delete(t),y.callbacks.size===0&&(y.listenersAttached&&=(e.removeEventListener(`popstate`,y.onPopStateOrHashChange),e.removeEventListener(`hashchange`,y.onPopStateOrHashChange),!1))}}function Pa(e){return e===void 0&&(e={}),{name:`amplitude/url-tracking@1`,observer:function(t,n,r){var i=L(L({},e),r),a=i.ugcFilterRules||[],o=i.enablePolling??!1,s=i.pollingInterval??vn,c=i.captureDocumentTitle??!1;if(!n)return function(){};var l=void 0,u=function(){return n.location&&n.location.href||``},d=function(){var e=n.innerHeight,t=n.innerWidth,r=n.document,i=u(),o=``;return c&&(o=r?.title||``),{href:a.length>0?ir(i,a):i,title:o,viewportHeight:e,viewportWidth:t,type:`url-change-event`}},f=function(){var e=u();(l===void 0||e!==l)&&(l=e,t(d()))},p=Na(n,function(){return f()},o?{enablePolling:!0,pollingInterval:s}:{});return f(),function(){return p()}},options:e}}Pa();function Fa(){try{var e=F();return e?e.parent!==e:!1}catch{return!0}}var Ia=function(){function e(){this.pendingLoadListeners=new Map}return e.prototype.start=function(){var e=this,t;(t=this.mutationObserver)==null||t.disconnect(),F()&&(this.sendToAllIframes({type:Bn,action:`start`}),this.mutationObserver=new MutationObserver(function(t){var n,r,i,a,o,s;try{for(var c=z(t),l=c.next();!l.done;l=c.next()){var u=l.value;try{for(var d=(i=void 0,z(Array.from(u.addedNodes))),f=d.next();!f.done;f=d.next()){var p=f.value;p instanceof HTMLIFrameElement?e.sendToIframeAfterLoad(p):p instanceof Element&&p.querySelectorAll(`iframe`).forEach(function(t){e.sendToIframeAfterLoad(t)})}}catch(e){i={error:e}}finally{try{f&&!f.done&&(a=d.return)&&a.call(d)}finally{if(i)throw i.error}}try{for(var m=(o=void 0,z(Array.from(u.removedNodes))),h=m.next();!h.done;h=m.next()){var p=h.value;if(p instanceof HTMLIFrameElement){var g=e.pendingLoadListeners.get(p);g&&(p.removeEventListener(`load`,g),e.pendingLoadListeners.delete(p))}}}catch(e){o={error:e}}finally{try{h&&!h.done&&(s=m.return)&&s.call(m)}finally{if(o)throw o.error}}}}catch(e){n={error:e}}finally{try{l&&!l.done&&(r=c.return)&&r.call(c)}finally{if(n)throw n.error}}}),this.mutationObserver.observe(document.documentElement,{childList:!0,subtree:!0}))},e.prototype.stop=function(){var e;(e=this.mutationObserver)==null||e.disconnect(),this.mutationObserver=void 0,this.pendingLoadListeners.forEach(function(e,t){t.removeEventListener(`load`,e)}),this.pendingLoadListeners.clear(),this.sendToAllIframes({type:Bn,action:`stop`})},e.prototype.sendToIframeAfterLoad=function(e){var t=this,n=function(){t.pendingLoadListeners.delete(e),t.sendToIframe(e,{type:Bn,action:`start`})};this.pendingLoadListeners.set(e,n),e.addEventListener(`load`,n,{once:!0})},e.prototype.sendToAllIframes=function(e){var t=this;document.querySelectorAll(`iframe`).forEach(function(n){return t.sendToIframe(n,e)})},e.prototype.sendToIframe=function(e,t){var n;try{(n=e.contentWindow)==null||n.postMessage(t,`*`)}catch{}},e}();function La(e){var t=F();if(!t)return function(){};var n=t.parent;function r(t){if(t.source===n){var r=t.data;r?.type===`amplitude-sr-iframe`&&(r.action===`start`?e.onStart():r.action===`stop`&&e.onStop())}}return t.addEventListener(`message`,r),function(){return t.removeEventListener(`message`,r)}}var Ra=function(){function e(){var e=this;this.name=`@amplitude/session-replay-browser`,this.recordCancelCallback=null,this.eventCount=0,this.sessionTargetingMatch=!1,this.pageLeaveFns=[],this.suppressedSendCount=0,this.hasEmittedGateDecision=!1,this.recordFunction=null,this.recordEventsInFlight=!1,this.pendingEmitEvents=[],this.currentPageUrl=``,this.recordEventsPendingShouldLogMetadata=null,this.urlChangeCleanup=null,this.crossOriginIframeC
2oordinator=null,this.crossOriginParentSignalCleanup=null,this.latestUrlChangeTargetingEvaluationId=0,this.teardownEventListeners=function(t){var n=F();n&&(n.removeEventListener(`blur`,e.blurListener),n.removeEventListener(`focus`,e.focusListener),!t&&n.addEventListener(`blur`,e.blurListener),!t&&n.addEventListener(`focus`,e.focusListener),n.self&&`onpagehide`in n.self?(n.removeEventListener(`pagehide`,e.pageLeaveListener),!t&&n.addEventListener(`pagehide`,e.pageLeaveListener)):(n.removeEventListener(`beforeunload`,e.pageLeaveListener),!t&&n.addEventListener(`beforeunload`,e.pageLeaveListener)))},this.blurListener=function(){e.sendEvents()},this.focusListener=function(){if(e.recordCancelCallback&&e.recordFunction){if(e.config?.captureFullSnapshotOnFocus===!1)return;try{e.recordFunction.takeFullSnapshot(!0)}catch(t){e.loggerProvider.warn(`Failed to take full snapshot on focus:`,t)}}else e.recordEventsInFlight||e.recordEvents(!1)},this.pageLeaveListener=function(t){var n;(n=e.eventCompressor)==null||n.flushQueue(),e.sendEvents(),e.pageLeaveFns.forEach(function(e){e(t)})},this.evaluateTargetingAndCapture=function(t,n,r,i){return n===void 0&&(n=!1),r===void 0&&(r=!1),i===void 0&&(i=!1),N(e,void 0,void 0,function(){var e,a,o,s,c,l,u;return I(this,function(d){switch(d.label){case 0:if(!this.identifiers||!this.identifiers.sessionId||!this.config)return this.identifiers&&!this.identifiers.sessionId?this.loggerProvider.log(`Session ID has not been set yet, cannot evaluate targeting for Session Replay.`):this.loggerProvider.warn(`Session replay init has not been called, cannot evaluate targeting.`),[2];if(!this.config.targetingConfig){if(n)this.loggerProvider.log(`Targeting config has not been set yet, cannot evaluate targeting.`);else return this.loggerProvider.log(`No targeting config set, skipping initialization/recording for event.`),[2]}return this.lastTargetingParams=t,e=this.config.targetingConfig,a=e&&!this.sessionTargetingMatch,a?(o=i?this.latestUrlChangeTargetingEvaluationId:void 0,s=t.event,s&&Object.values(ue).includes(s.event_type)&&(s=void 0),c=t.page?.url??F()?.location?.href??``,l=t.page??(c===``?void 0:{url:c}),[4,ya({sessionId:this.identifiers.sessionId,targetingConfig:e,loggerProvider:this.loggerProvider,apiKey:this.config.apiKey,targetingParams:{userProperties:t.userProperties,event:s,page:l},urlChange:i})]):[3,2];case 1:if(u=d.sent(),i&&o!==void 0&&o!==this.latestUrlChangeTargetingEvaluationId)return this.loggerProvider.debug(`Ignoring stale URL-change targeting result #${o}; latest is #${this.latestUrlChangeTargetingEvaluationId}.`),[2];this.sessionTargetingMatch=this.sessionTargetingMatch||u,this.loggerProvider.debug(JSON.stringify({name:`targeted replay capture config`,sessionTargetingMatch:this.sessionTargetingMatch,event:s,targetingParams:t},null,2)),d.label=2;case 2:return n?(this.initialize(!0),[3,5]):[3,3];case 3:return r||!this.recordCancelCallback?(this.loggerProvider.log(`Recording events for session due to forceRestart or no ongoing recording.`),[4,this.recordEvents()]):[3,5];case 4:d.sent(),d.label=5;case 5:return[2]}})})},this.addCustomRRWebEvent=function(t,n,r){return n===void 0&&(n={}),r===void 0&&(r=!0),N(e,void 0,void 0,function(){var e,i,a,o;return I(this,function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),e=void 0,i=this.config,!(i&&t!==Vn.METADATA)||(e={config:or(i),version:Lr},!r)?[3,2]:[4,ar()];case 1:a=s.sent(),e=L(L({},a),e),s.label=2;case 2:return this.recordCancelCallback&&this.recordFunction?this.recordFunction.addCustomEvent(t,L(L({},n),e)):this.loggerProvider.debug(`Not able to add custom replay capture event ${t} due to no ongoing recording.`),[3,4];case 3:return o=s.sent(),this.loggerProvider.debug(`Error while adding custom replay capture event: `,o),[3,4];case 4:return[2]}})})},this.stopRecordingEvents=function(){var t,n,r;try{e.loggerProvider.log(`Session Replay capture stopping.`),e.recordCancelCallback&&e.recordCancelCallback(),e.recordCancelCallback=null,(t=e.networkObservers)==null||t.stop(),(n=e.crossOriginIframeCoordinator)==null||n.stop(),e.crossOriginIframeC
2oordinator=null,(r=e.crossOriginParentSignalCleanup)==null||r.call(e),e.crossOriginParentSignalCleanup=null}catch(t){var i=t;e.loggerProvider.warn(`Error occurred while stopping replay capture: ${i.toString()}`)}},this.loggerProvider=new Hn(new pe)}return e.prototype.init=function(e,t){return le(this._init(e,t))},e.prototype.setupUrlChangeListener=function(){var e=this,t;(t=this.urlChangeCleanup)==null||t.call(this);var n=F();if(n?.location){var r=!!this.config?.targetingConfig,i=Na(n,function(t){if(e.currentPageUrl=t,r){var n=++e.latestUrlChangeTargetingEvaluationId;e.evaluateTargetingAndCapture({userProperties:{},event:void 0,page:{url:t}},!1,!1,!0),e.loggerProvider.debug(`Queued URL-change targeting re-evaluation #${n} for ${t}.`)}});this.urlChangeCleanup=function(){i(),e.urlChangeCleanup=null}}},e.prototype.isBelowMinSessionDuration=function(){var e=this.config?.minSessionDurationMs;return e===void 0||this.sessionStartTime===void 0?!1:Date.now()-this.sessionStartTime<e},e.prototype.getCurrentPageForTargeting=function(){var e=F()?.location?.href;return e==null?void 0:{url:e}},e.prototype._init=function(e,t){var n;return N(this,void 0,void 0,function(){var r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,b,w,T,E,D,O,k,ee,te,ne,re,A,j=this;return I(this,function(M){switch(M.label){case 0:return(n=this.urlChangeCleanup)==null||n.call(this),this.loggerProvider=new Hn(t.loggerProvider||new pe),Object.prototype.hasOwnProperty.call(t,`logLevel`)&&this.loggerProvider.enable(t.logLevel),this.currentPageUrl=Qn(),this.identifiers=new ca({sessionId:t.sessionId,deviceId:t.deviceId}
2),r=Date.now(),_a(e,r,this.loggerProvider),this.sessionStartTime=t.sessionId===void 0?r:ma(e,t.sessionId,r,this.loggerProvider)??r,i=this,[4,Sr(e,t)];case 1:return i.joinedConfigGenerator=M.sent(),[4,this.joinedConfigGenerator.generateJoinedConfig()];case 2:return a=M.sent(),o=a.joinedConfig,s=a.localConfig,c=a.remoteConfig,this.config=o,this.setMetadata(t.sessionId,o,s,c,t.version?.version,Lr,t.version?.type),this.pageLeaveFns=[],t.sessionId&&this.config.interactionConfig?.enabled&&(l=sa.default({sessionId:t.sessionId,type:`interaction`},this.config),this.pageLeaveFns=[l.send(this.getDeviceId.bind(this)).bind(l)],this.scrollHook=l.hook.bind(l),this.clickHandler=new ra(this.loggerProvider,l)),u=[],d=this.config.storeType,d===`idb`&&!F()?.indexedDB&&(d=`memory`,this.loggerProvider.warn(`Could not use preferred indexedDB storage, reverting to in memory option.`)),this.loggerProvider.log(`Using ${d} for event storage.`),m=F(),this.config.useWebWorker&&m&&m.Worker?[4,je(()=>import(`./worker-IYNlRkSs.js`),[])]:[3,4];case 3:h=M.sent(),g=h.compressionScript,_=h.trackDestinationScript,f=g,p=_,M.label=4;case 4:return M.trys.push([4,6,,7]),[4,ki({config:this.config,type:`replay`,minInterval:this.config.flushIntervalConfig?.minIntervalMs,maxInterval:this.config.flushIntervalConfig?.maxIntervalMs,maxPersistedEventsSize:this.config.maxPersistedEventsSizeBytes,storeType:d,trackDestinationWorkerScript:p,shouldSend:function(){return!j.isBelowMinSessionDuration()}})];case 5:return v=M.sent(),this.rrwebEventManager=v,u.push({name:`replay`,manager:v}),[3,7];case 6:return y=M.sent(),b=y,this.loggerProvider.warn(`Error occurred while creating replay events manager: ${b.toString()}`),[3,7];case 7:if(!this.config.interactionConfig?.enabled)return[3,11];x=this.config.interactionConfig.batch?na:ta,M.label=8;case 8:return M.trys.push([8,10,,11]),[4,ki({config:this.config,type:`interaction`,minInterval:this.config.interactionConfig.trackEveryNms??An,maxInterval:jn,maxPersistedEventsSize:this.config.maxPersistedEventsSizeBytes,payloadBatcher:x,storeType:d,trackDestinationWorkerScript:p})];case 9:return S=M.sent(),u.push({name:`interaction`,manager:S}),[3,11];case 10:return C=M.sent(),b=C,this.loggerProvider.warn(`Error occurred while creating interaction events manager: ${b.toString()}`),[3,11];case 11:if(this.eventsManager=new(Ai.bind.apply(Ai,P([void 0],R(u),!1))),this.eventCompressor&&this.eventCompressor.terminate(),w=this.config.eagerFullSnapshotSend===!0?function(){return j.sendEvents()}:void 0,this.eventCompressor=new Ar(this.eventsManager,this.config,this.getDeviceId(),f,w),this.pendingEmitEvents.length>0){T=this.pendingEmitEvents.splice(0);try{for(E=z(T),D=E.next();!D.done;D=E.next())O=D.value,k=O.event,ee=O.sessionId,this.eventCompressor.enqueueEvent(k,ee)}catch(e){re={error:e}}finally{try{D&&!D.done&&(A=E.return)&&A.call(E)}finally{if(re)throw re.error}}}return this.pageLeaveFns=P(P([],R(this.pageLeaveFns),!1),[function(){if(!(!j.config||!j.identifiers?.sessionId||!v)){var e=v.getBeaconEvents();if(e.length){var t=j.getDeviceId();t&&(j.isBelowMinSessionDuration()||v.trackDestination.sendBeacon({events:e,sessionId:j.identifiers.sessionId,deviceId:t,apiKey:j.config.apiKey,serverZone:j.config.serverZone}))}}}],!1),[4,this.initializeNetworkObservers()];case 12:return M.sent(),F()?.opener&&(te=he(),Ee(te),te.setup(L({logger:this.loggerProvider},this.config.serverZone&&{endpoint:ge[this.config.serverZone]}))),this.loggerProvider.log(`Installing @amplitude/session-replay-browser.`),this.teardownEventListeners(!1),[4,this.evaluateTargetingAndCapture({userProperties:t.userProperties,page:this.getCurrentPageForTargeting()},!0)];case 13:return M.sent(),ne=this.config.targetingConfig||(this.config.privacyConfig?.urlMaskLevels?.length??0)>0,ne&&this.setupUrlChangeListener(),[2]}})})},e.prototype.setSessionId=function(e,t){return le(this.asyncSetSessionId(e,t))},e.prototype.asyncSetSessionId=function(e,t,n){var r;return N(this,void 0,void 0,function(){var i,a,o,s,c;return I(this,function(l){switch(l.label){case 0:return i=this.identifiers?.sessionId,a=this.getDeviceId(),i!==void 0&&i===e&&(t===void 0||t===a)&&(n?.userProperties===void 0||Object.keys(n.userProperties).length===0)?[2]:(this.latestUrlChangeTargetingEvaluationId++,this.sessionTargetingMatch=!1,this.lastShouldRecordDecision=void 0,i&&this.sendEvents(i),o=i!==e,o&&((r=this.rrwebEventManager)==null||r.dropPendingBeaconEvents()),s=t||this.getDeviceId(),this.identifiers=new ca({sessionId:e,deviceId:s}),o&&(this.sessionStartTime=Date.now(),this.suppressedSendCount=0,this.hasEmittedGateDecision=!1,this.config?.apiKey&&(ha(this.config.apiKey,e,this.sessionStartTime,this.loggerProvider),i!==void 0&&ga(this.config.apiKey,i,this.loggerProvider))),this.joinedConfigGenerator&&i?[4,this.joinedConfigGenerator.generateJoinedConfig()]:[3,2]);case 1:c=l.sent().joinedConfig,this.config=c,l.label=2;case 2:return this.config?.targetingConfig?[4,this.evaluateTargetingAndCapture({userProperties:n?.userProperties,page:this.getCurrentPageForTargeting()},!1,!0)]:[3,4];case 3:return l.sent(),[3,6];case 4:return[4,this.recordEvents()];case 5:l.sent(),l.label=6;case 6:return[2]}})})},e.prototype.getSessionReplayProperties=function(){var e,t=this.config,n=this.identifiers;if(!t||!n)return this.loggerProvider.warn(`Session replay init has not been called, cannot get session replay properties.`),{};var r=this.getShouldRecord(),i={};return r&&(i=(e={},e[hn]=n.sessionReplayId?n.sessionReplayId:null,e),t.debugMode&&(i[yn]=JSON.stringify({appHash:_e(t.apiKey).toString()}))),this.addCustomRRWebEvent(Vn.GET_SR_PROPS,{shouldRecord:r,eventProperties:i},this.eventCount===10),this.eventCount===10&&(this.eventCount=0),this.eventCount++,i},e.prototype.sendEvents=function(e){var t=e||this.identifiers?.sessionId,n=this.getDeviceId();if(this.eventsManager&&t&&n){if(this.isBelowMinSessionDuration()){var r=this.sessionStartTime,i=this.config.minSessionDurationMs;this.loggerProvider.log(`Session ${t} not sent: duration ${Date.now()-r}ms is below minimum ${i}ms.`),this.suppressedSendCount++;return}if(!this.hasEmittedGateDecision&&this.config?.minSessionDurationMs!==void 0&&this.recordCancelCallback&&this.recordFunction){this.hasEmittedGateDecision=!0;var a=this.sessionStartTime===void 0?void 0:Date.now()-this.sessionStartTime;this.addCustomRRWebEvent(Vn.REPLAY_GATE_DECISION,{sessionId:t,suppressedSendCount:this.suppressedSendCount,elapsedMs:a,minSessionDurationMs:this.config.minSessionDurationMs},!1)}this.eventsManager.sendCurrentSequenceEvents({sessionId:t,deviceId:n})}},e.prototype.initialize=function(e){return e===void 0&&(e=!1),N(this,void 0,void 0,function(){var t;return I(this,function(n){return this.identifiers?.sessionId?(t=this.getDeviceId(),t?(this.eventsManager&&e&&this.eventsManager.sendStoredEvents({deviceId:t}),[2,this.recordEvents()]):(this.loggerProvider.log(`Session is not being recorded due to lack of device id.`),[2,Promise.resolve()])):(this.loggerProvider.log(`Session is not being recorded due to lack of session id.`),[2,Promise.resolve()])})})},e.prototype.shouldOptOut=function(){var e;return this.config?.instanceName&&(e=de(this.config.instanceName).identityStore.getIdentity().optOut),e===void 0?this.config?.optOut:e},e.prototype.getShouldRecord=function(){if(!this.identifiers||!this.config||!this.identifiers.sessionId)return this.loggerProvider.warn(`Session is not being recorded due to lack of config, please call sessionReplay.init.`),!1;if(!this.config.captureEnabled)return this.loggerProvider.log(`Session ${this.identifiers.sessionId}
2 not being captured due to capture being disabled for project or because the remote config could not be fetched.`),!1;if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${this.identifiers.sessionId} out of recording due to optOut config.`),!1;var e=!1,t=``,n=!1;return this.config.targetingConfig?this.sessionTargetingMatch?(t=`Capturing replays for session ${this.identifiers.sessionId} due to matching targeting conditions.`,this.loggerProvider.log(t),e=!0,n=!0):(t=`Not capturing replays for session ${this.identifiers.sessionId} due to not matching targeting conditions.`,this.loggerProvider.log(t),e=!1,n=!1):Aa(this.identifiers.sessionId,this.config.sampleRate)?(e=!0,n=!0):(t=`Opting session ${this.identifiers.sessionId} out of recording due to sample rate.`,this.loggerProvider.log(t),e=!1,n=!1),this.lastShouldRecordDecision!==e&&this.config.targetingConfig&&(this.addCustomRRWebEvent(Vn.TARGETING_DECISION,{message:t,sessionId:this.identifiers.sessionId,matched:n,targetingParams:this.lastTargetingParams}),this.lastShouldRecordDecision=e),e},e.prototype.getBlockSelectors=function(){var e=this.config?.privacyConfig?.blockSelector??[];if(e.length!==0)return e},e.prototype.getMaskTextSelectors=function(){var e=this.config?.privacyConfig;if((e?Jn(this.currentPageUrl,e):void 0)===`conservative`||(e?.urlMaskLevels)?.some(function(e){return e.maskLevel===`conservative`}))return`*`;var t=e?.urlMaskLevels;if(e?.defaultMaskLevel===`conservative`&&t&&t.length>0)return`*`;var n=e?.maskSelector;if(n)return n},e.prototype.getRecordingPlugins=function(e){return N(this,void 0,void 0,function(){var t,n,r,i;return I(this,function(a){switch(a.label){case 0:t=[];try{n=Pa({ugcFilterRules:this.config?.interactionConfig?.ugcFilterRules||[],enablePolling:this.config?.enableUrlChangePolling||!1,pollingInterval:this.config?.urlChangePollingInterval,captureDocumentTitle:this.config?.captureDocumentTitle}),t.push(n)}catch(e){this.loggerProvider.warn(`Failed to create URL tracking plugin:`,e)}if(!e?.console?.enabled)return[3,4];a.label=1;case 1:return a.trys.push([1,3,,4]),[4,je(()=>import(`./rrweb-plugin-console-record-CFgto0XN.js`),[])];case 2:return r=a.sent().getRecordConsolePlugin,t.push(r({level:e.console.levels})),[3,4];case 3:return i=a.sent(),this.loggerProvider.warn(`Failed to load console plugin:`,i),[3,4];case 4:return[2,t.length>0?t:void 0]}})})},e.prototype.getRecordFunction=function(){return N(this,void 0,void 0,function(){var e,t;return I(this,function(n){switch(n.label){case 0:if(this.recordFunction)return[2,this.recordFunction];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,je(()=>import(`./rrweb-record-CvV9LUjm.js`),[])];case 2:return e=n.sent().record,this.recordFunction=e,[2,e];case 3:return t=n.sent(),this.loggerProvider.warn(`Failed to load rrweb-record module:`,t),[2,null];case 4:return[2]}})})},e.prototype.recordEvents=function(e){return e===void 0&&(e=!0),N(this,void 0,void 0,function(){var t;return I(this,function(n){switch(n.label){case 0:if(this.recordEventsInFlight)return this.recordEventsPendingShouldLogMetadata=e,[2];this.recordEventsInFlight=!0,n.label=1;case 1:return n.trys.push([1,,6,7]),[4,this._recordEvents(e)];case 2:n.sent(),n.label=3;case 3:return this.recordEventsPendingShouldLogMetadata===null?[3,5]:(t=this.recordEventsPendingShouldLogMetadata,this.recordEventsPendingShouldLogMetadata=null,[4,this._recordEvents(t)]);case 4:return n.sent(),[3,3];case 5:return[3,7];case 6:return this.recordEventsInFlight=!1,this.recordEventsPendingShouldLogMetadata=null,[7];case 7:return[2]}})})},e.prototype._recordEvents=function(e){var t;return e===void 0&&(e=!0),N(this,void 0,void 0,function(){var n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x=this;return I(this,function(S){switch(S.label){case 0:return n=this.config,r=this.getShouldRecord(),i=this.identifiers?.sessionId,!r||!i||!n?[2]:(this.stopRecordingEvents(),[4,this.getRecordFunction()]);case 1:return a=S.sent(),a?[4,this.initializeNetworkObservers()]:[2];case 2:S.sent(),o=n.loggingConfig?.network,s=Kn(n.serverZone,n.trackServerUrl),c=[Cn,wn,Tn,s],(t=this.networkObservers)==null||t.start(function(e){c.some(function(t){return e.url.
2startsWith(t)})||x.addCustomRRWebEvent(Vn.FETCH_REQUEST,e)},o),l=n.interactionConfig,u=n.loggingConfig,d=l?.enabled?{mouseInteraction:this.eventsManager&&this.clickHandler?.createHook({eventsManager:this.eventsManager,sessionId:i,deviceIdFn:this.getDeviceId.bind(this),mirror:a.mirror,ugcFilterRules:l.ugcFilterRules??[],performanceOptions:n.performanceConfig?.interaction}),scroll:this.scrollHook}:{},f=l?.enabled&&l.ugcFilterRules?l.ugcFilterRules:[],this.loggerProvider.log(`Session Replay capture beginning for ${i}.`),S.label=3;case 3:return S.trys.push([3,5,,6]),p=!!n.crossOriginIframes?.enabled,m=n.crossOriginIframes?.coordinateChildren!==!1,h=p&&Fa(),h&&m?(this.crossOriginParentSignalCleanup=La({onStart:function(){return x._recordEventsInChildMode(a,i,n,d)},onStop:function(){try{x.recordCancelCallback&&x.recordCancelCallback(),x.recordCancelCallback=null}catch(t){var e=t;x.loggerProvider.warn(`Error occurred while stopping child iframe replay capture: ${e.toString()}`)}}}),[2]):(g=this,_=a,v=[L({},this.buildRRWebRecordOptions(n,d,function(e){if(x.shouldOptOut()){x.loggerProvider.log(`Opting session ${i} out of recording due to optOut config.`),x.stopRecordingEvents(),x.sendEvents();return}e.type===hr.Meta&&(e.data.href=ir(e.data.href,f)),x.eventCompressor?x.eventCompressor.enqueueEvent(e,i):x.pendingEmitEvents.push({event:e,sessionId:i})},`Error while capturing replay: `))],b={},[4,this.getRecordingPlugins(u)]);case 4:return g.recordCancelCallback=_.apply(void 0,[L.apply(void 0,v.concat([(b.plugins=S.sent(),b.recordCrossOriginIframes=p,b)]))]),p&&!h&&m&&(this.crossOriginIframeCoordinator||=new Ia,this.crossOriginIframeCoordinator.start()),this.addCustomRRWebEvent(Vn.DEBUG_INFO),e&&this.addCustomRRWebEvent(Vn.METADATA,this.metadata),[3,6];case 5:return y=S.sent(),this.loggerProvider.warn(`Failed to initialize session replay:`,y),[3,6];case 6:return[2]}})})},e.prototype.buildRRWebRecordOptions=function(e,t,n,r){var i=this,a=e.privacyConfig;return L(L({emit:n,inlineStylesheet:e.shouldInlineStylesheet,hooks:t,maskAllInputs:!0,maskTextClass:xn,blockClass:bn,blockSelector:this.getBlockSelectors(),applyBackgroundColorToBlockedElements:e.applyBackgroundColorToBlockedElements,maskInputFn:Xn(`input`,a,function(){return i.currentPageUrl}),maskTextFn:Xn(`text`,a,function(){return i.currentPageUrl}),maskAttributeFn:Zn(a,function(){return i.currentPageUrl}),maskTextSelector:this.getMaskTextSelectors()},e.fullSnapshotIntervalMs!==void 0&&{checkoutEveryNms:e.fullSnapshotIntervalMs}),{recordCanvas:!1,captureAdoptedStyleSheets:e.captureAdoptedStyleSheets,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},errorHandler:function(e){var t=e;if(t.message.includes(`insertRule`)&&t.message.includes(`CSSStyleSheet`)||t._external_)throw t;return i.loggerProvider.warn(r,t.toString()),!0}})},e.prototype._recordEventsInChildMode=function(e,t,n,r){try{this.recordCancelCallback&&this.recordCancelCallback(),this.recordCancelCallback=null,this.recordCancelCallback=e(L(L({},this.buildRRWebRecordOptions(n,r,function(){},`Error while capturing replay (child iframe): `)),{recordCrossOriginIframes:!0})),this.loggerProvider.log(`Session Replay child iframe capture beginning for session ${t}.`)}catch(e){this.loggerProvider.warn(`Failed to initialize session replay in child iframe mode:`,e)}},e.prototype.getDeviceId=function(){return this.identifiers?.deviceId},e.prototype.getSessionId=function(){return this.identifiers?.sessionId},e.prototype.flush=function(e){return e===void 0&&(e=!1),N(this,void 0,void 0,function(){return I(this,function(t){return[2,this.eventsManager?.flush(e)]})})},e.prototype.shutdown=function(){var e,t;(e=this.urlChangeCleanup)==null||e.call(this),(t=this.crossOriginParentSignalCleanup)==null||t.call(this),this.crossOriginParentSignalCleanup=null,this.teardownEventListeners(!0),this.stopRecordingEvents(),this.sendEvents()},e.prototype.mapSDKType=function(e){return e===`plugin`?`@amplitude/plugin-session-replay-browser`:e===`segment`?`@amplitude/segment-session-replay-plugin`:null},e.prototype.setMetadata=function(e,t,n,r,i,a,o){var s=e?.toString()?_e(e.toString()):void 0;this.metadata={joinedConfig:t,localConfig:n,remoteConfig:r,sessionId:e,hashValue:s,sampleRate:t.sampleRate,replaySDKType:this.mapSDKType(o),replaySDKVersion:i,standaloneSDKType:`@amplitude/session-replay-browser`,standaloneSDKVersion:a}},e.prototype.initializeNetworkObservers=function(){return N(this,void 0,void 0,function(){var e,t;return I(this,function(n){switch(n.label){case 0:if(!(this.config?.loggingConfig?.network?.enabled&&!this.networkObservers))return[3,4];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,je(()=>
2import(`./observers-DVg-uRJo.js`),__vite__mapDeps([2,1]))];case 2:return e=n.sent().NetworkObservers,this.networkObservers=new e,[3,4];case 3:return t=n.sent(),this.loggerProvider.warn(`Failed to import or instantiate NetworkObservers:`,t),[3,4];case 4:return[2]}})})},e}(),za=function(e){return function(){var t=e.config||sr();return{logger:t.loggerProvider,logLevel:t.logLevel}}},Ba=function(){var e=new Ra;return{init:De(e.init.bind(e),`init`,za(e)),evaluateTargetingAndCapture:De(e.evaluateTargetingAndCapture.bind(e),`evaluateTargetingAndRecord`,za(e)),setSessionId:De(e.setSessionId.bind(e),`setSessionId`,za(e)),getSessionId:De(e.getSessionId.bind(e),`getSessionId`,za(e)),getSessionReplayProperties:De(e.getSessionReplayProperties.bind(e),`getSessionReplayProperties`,za(e)),flush:De(e.flush.bind(e),`flush`,za(e)),shutdown:De(e.shutdown.bind(e),`shutdown`,za(e))}}(),Va=Ba.init,Ha=Ba.setSessionId,Ua=Ba.getSessionId,Wa=Ba.getSessionReplayProperties,Ga=Ba.flush,Ka=Ba.shutdown,qa=Ba.evaluateTargetingAndCapture,Ja;(function(e){e.SET=`$set`,e.SET_ONCE=`$setOnce`,e.ADD=`$add`,e.APPEND=`$append`,e.PREPEND=`$prepend`,e.REMOVE=`$remove`,e.PREINSERT=`$preInsert`,e.POSTINSERT=`$postInsert`,e.UNSET=`$unset`,e.CLEAR_ALL=`$clearAll`})(Ja||={});var Ya;(function(e){e.REVENUE_PRODUCT_ID=`$productId`,e.REVENUE_QUANTITY=`$quantity`,e.REVENUE_PRICE=`$price`,e.REVENUE_TYPE=`$revenueType`,e.REVENUE_CURRENCY=`$currency`,e.REVENUE=`$revenue`})(Ya||={});var Xa;(function(e){e.IDENTIFY=`$identify`,e.GROUP_IDENTIFY=`$groupidentify`,e.REVENUE=`revenue_amount`})(Xa||={});var Za=[Ja.SET,Ja.SET_ONCE,Ja.ADD,Ja.APPEND,Ja.PREPEND,Ja.POSTINSERT],Qa=function(e){if(e.user_properties){var t={};return Object.keys(e.user_properties).forEach(function(n){if(Za.includes(n)){var r=e.user_properties&&e.user_properties[n];t=L(L({},t),r)}}),t}},$a=`1.33.9`,eo=`[Amplitude] Session Replay ID`,to=function(){function e(t){this.name=e.pluginName,this.type=`enrichment`,this.config=null,this.sessionReplay={flush:Ga,getSessionId:Ua,getSessionReplayProperties:Wa,init:Va,setSessionId:Ha,shutdown:Ka,evaluateTargetingAndCapture:qa},this.options=L({forceSessionTracking:!1},t),this.srInitOptions=this.options}return e.prototype.setup=function(e,t){return N(this,void 0,void 0,function(){var t,n,r;return I(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),e?.loggerProvider.log(`Installing @amplitude/plugin-session-replay, version 1.33.9.`),this.config=e,this.options.forceSessionTracking&&(typeof e.defaultTracking==`boolean`?e.defaultTracking===!1&&(e.defaultTracking={pageViews:!1,formInteractions:!1,fileDownloads:!1,sessions:!0}):e.defaultTracking=L(L({},e.defaultTracking),{sessions:!0})),t=de(this.config.instanceName).identityStore,n=t.getIdentity().userProperties,this.srInitOptions={instanceName:this.config.instanceName,deviceId:this.options.deviceId??this.config.deviceId,optOut:this.config.optOut,sessionId:this.options.customSessionId?void 0:this.config.sessionId,loggerProvider:this.config.loggerProvider,logLevel:this.config.logLevel,flushMaxRetries:this.config.flushMaxRetries,serverZone:this.config.serverZone,configServerUrl:this.options.configServerUrl||this.config.remoteConfig?.serverUrl,trackServerUrl:this.options.trackServerUrl,sampleRate:this.options.sampleRate,privacyConfig:{blockSelector:this.options.privacyConfig?.blockSelector,maskSelector:this.options.privacyConfig?.maskSelector,unmaskSelector:this.options.privacyConfig?.unmaskSelector,defaultMaskLevel:this.options.privacyConfig?.defaultMaskLevel},debugMode:this.options.debugMode,shouldInlineStylesheet:this.options.shouldInlineStylesheet,version:{type:`plugin`,version:$a},performanceConfig:this.options.performanceConfig,storeType:this.options.storeType,useWebWorker:this.options.useWebWorker??this.options.experimental?.useWebWorker,userProperties:n,applyBackgroundColorToBlockedElements:this.options.applyBackgroundColorToBlockedElements,interactionConfig:this.options.interactionConfig,captureDocumentTitle:this.options.captureDocumentTitle,enableUrlChangePolling:this.options.enableUrlChangePolling,urlChangePollingInterval:this.options.urlChangePollingInterval,captureAdoptedStyleSheets:this.options.captureAdoptedStyleSheets,crossOriginIframes:this.options.crossOriginIframes,flushIntervalConfig:this.options.flushIntervalConfig,eagerFullSnapshotSend:this.options.eagerFullSnapshotSend,captureFullSnapshotOnFocus:this.options.captureFullSnapshotOnFocus,maxPersistedEventsSizeBytes:this.options.maxPer
2sistedEventsSizeBytes,maxSingleEventSizeBytes:this.options.maxSingleEventSizeBytes,sendTimeoutMs:this.options.sendTimeoutMs,handleSendEvents:this.options.handleSendEvents,handleFetchConfig:this.options.handleFetchConfig},[4,this.sessionReplay.init(e.apiKey,this.srInitOptions).promise];case 1:return i.sent(),[3,3];case 2:return r=i.sent(),e?.loggerProvider.error(`Session Replay: Failed to initialize due to ${r.message}`),[3,3];case 3:return[2]}})})},e.prototype.onSessionIdChanged=function(e){var t;return N(this,void 0,void 0,function(){return I(this,function(n){switch(n.label){case 0:return(t=this.config)==null||t.loggerProvider.debug(`Analytics session id is changed to ${e}, SR session id is ${String(this.sessionReplay.getSessionId())}.`),[4,this.sessionReplay.setSessionId(e).promise];case 1:return n.sent(),[2]}})})},e.prototype.onOptOutChanged=function(e){var t;return N(this,void 0,void 0,function(){var n;return I(this,function(r){switch(r.label){case 0:return(t=this.config)==null||t.loggerProvider.debug(`optOut is changed to ${String(e)}, calling ${e?`sessionReplay.shutdown()`:`sessionReplay.init()`}.`),e?(this.sessionReplay.shutdown(),[3,4]):[3,1];case 1:return n=this.config!=null,n?[4,this.sessionReplay.init(this.config.apiKey,this.srInitOptions).promise]:[3,3];case 2:n=r.sent(),r.label=3;case 3:r.label=4;case 4:return[2]}})})},e.prototype.execute=function(e){var t;return N(this,void 0,void 0,function(){var n,r,n,i,a,r,o;return I(this,function(s){switch(s.label){case 0:return s.trys.push([0,9,,10]),this.options.customSessionId?(n=this.options.customSessionId(e),n?n===this.sessionReplay.getSessionId()?[3,2]:[4,this.sessionReplay.setSessionId(n).promise]:[3,3]):[3,4];case 1:s.sent(),s.label=2;case 2:r=this.sessionReplay.getSessionReplayProperties(),e.event_properties=L(L({},e.event_properties),r),s.label=3;case 3:return[3,8];case 4:return n=this.config?.sessionId,n&&n!==this.sessionReplay.getSessionId()?[4,this.sessionReplay.setSessionId(n).promise]:[3,6];case 5:s.sent(),s.label=6;case 6:return n&&n===e.session_id?(i=void 0,e.event_type===ue.IDENTIFY&&(i=Qa(e)),a=F(),[4,this.sessionReplay.evaluateTargetingAndCapture({event:e,userProperties:i,page:a?.location?.href==null?void 0:{url:a.location.href}})]):[3,8];case 7:s.sent(),r=this.sessionReplay.getSessionReplayProperties(),e.event_properties=L(L({},e.event_properties),r),s.label=8;case 8:return e.event_type===ue.IDENTIFY&&e.event_properties&&delete e.event_properties[eo],[2,Promise.resolve(e)];case 9:return o=s.sent(),(t=this.config)==null||t.loggerProvider.error(`Session Replay: Failed to enrich event due to ${o.message}`),[2,Promise.resolve(e)];case 10:return[2]}})})},e.prototype.teardown=function(){var e;return N(this,void 0,void 0,function(){return I(this,function(t){try{this.sessionReplay.shutdown(),this.config=null}catch(t){(e=this.config)==null||e.loggerProvider.error(`Session Replay: teardown failed due to ${t.message}`)}return[2]})})},e.prototype.getSessionReplayProperties=function(){return this.sessionReplay.getSessionReplayProperties()},e.pluginName=`@amplitude/plugin-session-replay-browser`,e}(),no=function(e){return new to(e)};function ro(){let{adtech:e,user:t,page:r}=n.globalState;return{is_ad_lite_test:e?.is_ad_lite_test,logged_in:t.is_logged_in,topic:r.topic_name,topic_id:r.topic_id,group_name:r.group_name,related_topics:ee(),nlp_tags:E,nlp_tag_ids:O,is_affiliate:r.is_affiliate,is_op:t.is_op,is_zombie:r.is_zombie,thread_id:r.thread_id,thread_name:r.thread_subject,thread_type:r.thread_type,thread_tags:D,replies:r.replies_count,"[Amplitude] Page Location":window.location.href,"[Amplitude] Page URL":window.location.href.split(`?`)[0],"[Amplitude] Page Path":window.location.pathname,"[Amplitude] Page Title":document.title,"[Amplitude] Page Domain":window.location.hostname,page_number:r.page_number,page_total:r.page_total,page_type:g(r.name),page_category:l(r.path),referrer:document.referrer,referring_domain:M(document.referrer),next_best_thread:r.next_best_thread,experiments:n?.globalState.experiment_feature_contextual_cohorts,experiments_cohort_id:n?.globalState?.experiment_feature_contextual_cohort_id}}function io(){let e=new URLSearchParams(n?.location.search);return ie({loggedIn:n?.globalState.user.is_logged_in,repliesPerPage:n?.globalState.preferences.talk_replies_per_page,featureEnabled:v(`infinite-scroll-threads`),urlHasPostsBy:e.has(`postsby`)})}function ao(){let{page:e}=n?.globalState;if(g(e.name)===`topic`&&e.topic_view===`op-view`||g(e.name)===`feed`||g(e.name)===`discover`)return{feed_ad_frequency_experiment:v(`op-view-feed-ads-frequency-experiment`)}}function oo(){return v(`test-hide-talk-fixed-nav-on-scroll`)&&T().smallerOrEqual(`lg`).value&&ae().check()}function so(e){let{user:t}=window.globalState,r={user_type:t.is_logged_in?`Member`:`Non-Member`,talk_status:t.talk_status,is_premium:t.is_premium,feature_toggle_cohorts:window.globalState.feature_toggle_cohorts,ft_cohort_id:window.globalState.ft_cohort_id,experiments:window.globalState.experiment_feature_contextual_cohorts,experiments_cohort_id:window.globalState.experiment_feature_contextual_cohort_id,logged_in:t.is_logged_in,infinite_scroll_threads:io(),talk_replies_per_page:n?.globalState.preferences.talk_replies_per_page,talk_reply_order:n?.globalState.preferences.talk_reply_order,...ao()||{},hidden_bottom_nav:oo(),random_string:Math.random().toString(36).substring(2,15)};return e&&(r.user_id=t.id),r}var co=e=>{if(!e)return null;let t=e.topic||{},n=e.thread||{};return e.page_type?`page-type:${e.page_type}`:e.feature_toggle?`feature-toggle`:t.all?`topic-all`:t.display?`topic-display`:t.native?`topic-native`:n.all?`thread`:n.display?`thread-display`:e.nlp?`nlp`:e.gmt?`gmt`:null},lo=(e={})=>{let{eventType:t=ye}=e;
2return{name:`@mumsnet/enrich-page-view-events`,async execute(e){if(e.event_type!==t)return e;e.event_properties=e.event_properties??{};let r=n?.globalState?.adtech,i=r?.blocked_reason,a=co(i);a&&(r?.blocked||a.includes(`native`)||a.includes(`display`))&&(e.event_properties[`ads-blocked`]=a);let o=ro();return A.debug(`Enrich ${t} properties`,o),Object.entries(o).forEach(([t,n])=>{e.event_properties[t]===void 0&&(e.event_properties[t]=n)}),e}}},uo=Object.freeze([`old_url`,`new_url`,`page_title`,`view_type`]);function fo(){window.addEventListener(`virtual-page-view`,e=>{let t={...ro(),"[Amplitude] Page Location":j(e.detail.newUrl),referrer:j(e.detail.oldUrl),"[Amplitude] Page Path":ne(e.detail.newUrl),"[Amplitude] Page Title":e.detail.pageTitle,"[Amplitude] Page URL":j(e.detail.newUrl?.split(`?`)[0]),view_type:`virtual`};Object.entries(e.detail).forEach(([e,n])=>{e.startsWith(`[Amplitude]`)||(e=(0,Ne.snakeCase)(e),!uo.includes(e)&&(t[e]=n))}),window.mnAmpEvent({event_type:ye,event_properties:t})}),window.addEventListener(`user-logged-in`,e=>{window.mnAmpEvent({event_type:`login`,event_properties:{method:e.detail.method}})}),window.addEventListener(`user-registered`,e=>{window.mnAmpEvent({event_type:`sign_up`,event_properties:{method:e.detail.method}})}),window.addEventListener(`user-cancelled-premium`,e=>{window.mnAmpEvent({event_type:`premium_cancellation`,event_properties:{cancellation_reason:e.detail}})}),window.addEventListener(`user-subscribed-premium`,e=>{window.mnAmpEvent({event_type:`premium_sign_up`,event_properties:{premium_type:e.detail}})}),window.addEventListener(`registration-newsletter-subscribed`,e=>{window.mnAmpEvent({event_type:`newsletter_subscribed`,event_properties:{newsletter_id:e.detail[0].newsletter_id,newsletter_source:e.detail[0].newsletter_source}})}),window.addEventListener(`group-joined`,e=>{window.mnAmpEvent({event_type:`join_group`,event_properties:{group_name:e.detail.groupName}})}),window.addEventListener(`group-left`,e=>{window.mnAmpEvent({event_type:`leave_group`,event_properties:{group_name:e.detail.groupName}})})}var po=async()=>{if(!e||!v(`amplitude-duplicate-cookie`)||!(`cookieStore`in n))return;A.debug(`Run duplicate cookie check`);let t=(await n.cookieStore.getAll()).filter(e=>e.name.includes(`AMP_`)),r=new Map;for(let e of t){let t=e.name,n=r.get(t),i=/^[^.]+\.[^.]+$/.test(e.domain);n?(A.debug(`Duplicate cookie found: ${e.name}, keep the ${i?`2nd`:`1st`}`,[n,e]),i&&r.set(t,{cookie:e,isTopLevel:i})):r.set(t,{cookie:e,isTopLevel:i})}let i=Array.from(r.values()).map(e=>e.cookie),a=new Set(i.map(e=>`${e.name}|${e.domain}`));await Promise.all(t.filter(e=>!a.has(`${e.name}|${e.domain}`)).map(e=>(A.debug(`Deleting cookie: ${e.name} ${e.domain}`,e),n.mnAmpEvent({event_type:`duplicate_cookie_deleted`,event_properties:{cookie_name:e.name,cookie_domain:e.domain}}),n.cookieStore.delete({name:e.name,domain:e.domain,path:e.path}))))};function mo(){let e=`[data-impression-id]`;function t(e,t){window.mnAmpEvent({event_type:`element_impression`,event_properties:{impression_id:e}}),A.debug(`Element with impression ID ${e} is fully visible.`,t)}let n=new Set,r={root:null,rootMargin:`0px`,threshold:1};function i(e,r){e.forEach(e=>{if(e.isIntersecting&&e.intersectionRatio===1){let i=e.target,a=i.getAttribute(`data-impression-id`);n.has(a)||(n.add(a),t(a,i),r.unobserve(i))}})}let a=new IntersectionObserver(i,r);document.querySelectorAll(e).forEach(e=>{a.observe(e)}),new MutationObserver(()=>{document.querySelectorAll(e).forEach(e=>{n.has(e.getAttribute(`data-impression-id`))||a.observe(e)})}).observe(document.body,{childList:!0,subtree:!0})}function ho(e){let t=e.classList.length>0?Array.from(e.classList).join(` `):void 0,n=e.id||void 0,r=e.textContent.trim()||void 0,i=e.hasAttribute(`href`)&&e.getAttribute(`href`).trim()?e.getAttribute(`href`).trim():void 0,a=i&&i.includes(`go.skimresources.com`)?i:void 0;window.mnAmpEvent({event_type:`click`,event_properties:{link_classes:t,link_id:n,link_text:r,link_url:_o(i),skimlink_url:a}})}function go(e){return e?!!(e.startsWith(`https://go.skimresources.com`)||!e.startsWith(`${window.location.protocol}//${window.location.hostname}`)):!1}function _o(e){if(e?.startsWith(`https://go.skimresources.com`)){let t=e.split(`url=`)[1];if(t){let e=t.split(`&`)[0];return decodeURIComponent(e)}}return e}function vo(){document.addEventListener(`click`,function(e){let t=e.target;t.tagName!==`A`&&(t=e.target.closest(`a`)),!(!t||!go(t.href))&&ho(t)})}var yo=`first-scroll-fired`;function bo(){if(!e)return;let t=Me(yo),n=()=>{let e=!1;t(()=>{window.mnAmpEvent({event_type:`first_scroll`}),e=!0}),e&&window.removeEventListener(`scroll`,n)};window.addEventListener(`scroll`,n,{passive:!0})}var xo={id:`mn_house_promo_id`,type:`mn_house_promo_type`,placement:`mn_house_promo_placement`,version:`mn_house_promo_version`,start:`mn_house_promo_start`},So=`House Promo Landing`;function Co(){let e=document.querySelector(`link[rel="canonical"]`)?.href,{origin:t,pathname:n}=window.location;return e||`${t}${n}`}function wo(e){let t=new URLSearchParams(e),n=t.get(xo.type);return n?{event_type:So,event_properties:{promoted_content_id:t.get(xo.id)??void 0,promoted_content_type:n,landing_page_url:Co(),landing_page_title:document.title,placement:t.get(xo.placement)??void 0,creative_version:t.get(xo.version)??void 0,is_fallback:n===`fallback`,promo_start_at:t.get(xo.start)??void 0}}:null}function To(){if(!e)return;let t=wo(window.location.search);if(!t)return;A.debug(`housePromoLanding`,t),window.mnAmpEvent(t);let n=new URL(window.location.href);
2Object.values(xo).forEach(e=>n.searchParams.delete(e)),window.history.replaceState(window.history.state,``,n.href)}function Eo(e){window.addEventListener(`user-interests-saved`,t=>{let n=t.detail[0],r=new e.Identify;r.set(`user_interests`,n.map(e=>e.interest)),e.identify(r),window.mnAmpEvent(`onboarding_interests_completed`)}),window.addEventListener(`user-about-you-saved`,t=>{let n=t.detail[0],r=new e.Identify,{gender:i,yearOfBirth:a,expecting:o,dueDate:s,pregnancyNewsletter:c,children:l,numberOfChildren:u,childDetails:d,childDevelopmentNewsletter:f,postcodeRegion:p}=n,m={user_gender:i,user_year_of_birth:a,user_expecting:o,user_due_date:s,pregnancy_newsletter:c,user_children:l,user_number_of_children:u,user_child_details:d.map(({age:e,gender:t})=>({age:e,gender:t})),child_development_newsletter:f,user_postcode_region:p};for(let[e,t]of Object.entries(m))r.set(e,t);e.identify(r),window.mnAmpEvent(`onboarding_about_you_completed`)})}ue.IDENTIFY;var Do=(e={})=>{let{eventTypes:t=[ue.IDENTIFY]}=e;return{name:`@mumsnet/enrich-identify-events`,async execute(e){A.debug(`Enforcing identity on ${e.event_type} event`);let t=so(await b());return e.user_properties??={},e.user_properties.$set??={},Object.entries(t).forEach(([t,n])=>e.user_properties.$set[t]=n),A.debug(`Enforced properties`,t),e}}},Oo=(e={})=>({name:`@mumsnet/enrich-with-tab-identity`,async execute(e){return A.debug(`Adding tab identity to ${e.event_type} event`),e.event_properties??={},e.event_properties.tab=(await Ie()).value,e}}),ko=new WeakMap,Ao=new WeakMap,jo=new WeakSet,Mo=class e{static getInstance(){return Fo._||new e,Fo._}constructor(){if(o(this,jo),C(this,ko,new s(`SrcDocDetector`)),C(this,Ao,!1),Fo._)return Fo._;Fo._=this}initialize(){u(jo,this,No).call(this)}};function No(){S(Ao,this)||n?.history&&w(Ao,this,i(()=>{let e=history.pushState,t=history.replaceState;return history.pushState=(t,n,r)=>{if(e.apply(history,[t,n,r]),r!==`about:srcdoc`)return;let i={state:t,url:r};S(ko,this).warn(`about:srcdoc detected!`,i),u(jo,this,Po).call(this,`pushstate`,i)},history.replaceState=(e,n,r)=>{if(t.apply(history,[e,n,r]),r!==`about:srcdoc`)return;let i={state:e,url:r};S(ko,this).warn(`about:srcdoc detected!`,i),u(jo,this,Po).call(this,`replacestate`,i)},!0},!1))}function Po(e,t){n?.mnAmpEvent({event_type:`about_srcdoc`,event_properties:{srcdoc:{method:e,state:t.state}}})}var Fo={_:null},Io=async()=>{let e=await dn();if(!e)return;let t=new Oe;t.set(`bot_traffic`,e.isBot),t.set(`bot_source`,e.kind),Se(t)},Lo=`a40f5d73d24f602d7e3b6f1a51ad84e3`,Ro=`Mumsnet: Consented`,zo=`5ff56e8a5974fcad167a723ea54d8aba`,Bo=`Mumsnet: Non-Consented`,Vo=()=>{if(v(`amplitude-suppress-auth-callback`)){let e=performance.getEntriesByType(`navigation`)[0]?.name??window.location.href,{searchParams:t,pathname:n}=new URL(e);return t.get(`callback`)!==`in`||n!==window.location.pathname}let e=new URLSearchParams(window.location.search);return!(e.has(`callback`)&&e.has(`code`)&&e.has(`state`))},Ho=(e={})=>(0,Ne.merge)({autocapture:{attribution:{excludeReferrers:v(`amplitude-exclude-referrers`)?[te(window.location.hostname)]:[]},elementInteractions:!1,fileDownloads:!0,formInteractions:!0,pageViews:{trackHistoryChanges:`pathOnly`,trackOn:Vo},sessions:!0},defaultTracking:!0,serverZone:`EU`},e),Uo=[],Wo=(e,t=!0)=>{if(typeof e==`string`&&(e={event_type:e,event_properties:{}}),!xe){e.time=e.time??Date.now(),Uo.push({event:e,setDefaultEventProperties:t});return}if(e.event_properties||(e.event_properties={}),t){let t=ro();(0,Ne.defaults)(e.event_properties,t)}me(e)};window.mnAmpEvent=Wo;var Go=e=>{let t=new Oe;Object.entries(so(e)).forEach(([e,n])=>t.set(e,n)),Se(t)};(async()=>{if(!e||!v(`amplitude-analytics`)||window.globalState.user.is_premium)return;re(),vo(),fo(),mo();let[t,n]=await Promise.all([m(()=>b()),m(()=>po())]),[,r]=n;r&&A.error(`AMPLITUDE: Cookie Fix Error`,r);let[i,a]=t;if(a)return A.error(`AMPLITUDE: `,a);if(await Promise.all([Te(lo()).promise,Te(Oo()).promise,Te(Do()).promise]),Go(i),Io(),i){await Te(no({storeType:`memory`})).promise;let e=Ho({instanceName:Ro}),t=fe()??k(window.globalState.user.id);t?we(Lo,t,e):we(Lo,e),W.getInstance().initialize(),Mo.getInstance().initialize(),A.debug(`Initial data [consented]`,{defaultEventProperties:ro(),amplitude:xe,instance:xe,userId:t})}else{let e=Ho({identityStorage:`none`,instanceName:Bo,trackingOptions:{ipAddress:!1}});we(zo,e),A.debug(`Initial data [non-consented]`,{defaultEventProperties:ro(),amplitude:xe,instance:xe})}
2Eo(xe),bo(),To(),Uo.forEach(({event:e,setDefaultEventProperties:t})=>Wo(e,t))})();var Ko=(0,Ne.once)(async(e=5e3)=>{if(n)return n.fbq?n.fbq:await new Promise(t=>{let r=Date.now(),i=()=>{if(n.fbq)return t(n.fbq);if(Date.now()-r>=e)return t(void 0);n.requestAnimationFrame(i)};n.requestAnimationFrame(i)})});n?.addEventListener(`user-registered`,async e=>{let{detail:{method:t,eventId:n}}=e;if(!await y()){x.debug(`User did not consent to Meta Pixel events`);return}let r=await Ko();if(!r){x.debug(`fbq not loaded, skipping Meta Pixel event`,e);return}r(`track`,`CompleteRegistration`,t?{method:t}:{},...n?[{eventID:n}]:[])});export{W as n,dn as t};
3//# sourceMappingURL=meta-pixel-events-lcDa2LQI.js.map

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.