posthog-js 1.419.0 → 1.419.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- !function(){"use strict";function e(e,t,i,s,r,n,o){try{var a=e[n](o),l=a.value}catch(e){return void i(e)}a.done?t(l):Promise.resolve(l).then(s,r)}function t(t){return function(){var i=this,s=arguments;return new Promise((function(r,n){var o=t.apply(i,s);function a(t){e(o,r,n,a,l,"next",t)}function l(t){e(o,r,n,a,l,"throw",t)}a(void 0)}))}}function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;arguments.length>t;t++){var i=arguments[t];for(var s in i)({}).hasOwnProperty.call(i,s)&&(e[s]=i[s])}return e},i.apply(null,arguments)}function s(e,t){if(null==e)return{};var i={};for(var s in e)if({}.hasOwnProperty.call(e,s)){if(-1!==t.indexOf(s))continue;i[s]=e[s]}return i}var r={DEBUG:!1,LIB_VERSION:"0.5.2",LIB_NAME:"browser-common"};r.DEBUG=!1,r.LIB_VERSION="1.419.0",r.LIB_NAME="web";var n="$people_distinct_id",o="distinct_id",a="$device_id",l="$device_model",u="__alias",c="__timers",d="$autocapture_disabled_server_side",h="$heatmaps_enabled_server_side",_="$exception_capture_enabled_server_side",p="$error_tracking_suppression_rules",g="$error_tracking_capture_extension_exceptions",v="$web_vitals_enabled_server_side",f="$dead_clicks_enabled_server_side",m="$product_tours_enabled_server_side",y="$web_vitals_allowed_metrics",b="$session_recording_remote_config",w="$replay_sample_rate",S="$replay_override_sampling",x="$replay_override_linked_flag",E="$replay_override_url_trigger",k="$replay_override_event_trigger",P="$sesid",C="$session_is_sampled",I="$enabled_feature_flags",F="$active_feature_flags",T="$early_access_features",R="$feature_flag_details",A="$feature_flag_payloads",L="$feature_flag_request_id",M="$minimal_flag_called_events",O="$override_feature_flags",D="$override_feature_flag_payloads",B="$stored_person_properties",q="$stored_group_properties",H="$groups",N="$surveys",z="$surveys_loaded_at",j="$surveys_activated",U="$surveys_activated_session",V="$surveys_activated_timestamps",W="ph_product_tours",G="$flag_call_reported",K="$flag_call_reported_session_id",Q="$feature_flag_errors",J="$feature_flag_evaluated_at",Y="$user_state",Z="$client_session_props",X="$capture_rate_limit",ee="$initial_campaign_params",te="$initial_referrer_info",ie="$initial_person_info",se="$epp",re="$posthog_cookieless",ne="$cookieless_mode",oe="$sdk_debug_extensions_init_method",ae="$sdk_debug_extensions_init_time_ms",le="$sdk_debug_recording_script_not_loaded",ue="PostHog loadExternalDependency extension not found.",ce="on_reject",de="always",he="anonymous",_e="identified",pe="identified_only",ge="visibilitychange",ve="beforeunload",fe="$pageview",me="$pageleave",ye="$identify",be="$groupidentify",we="undefined"!=typeof window?window:void 0,Se="undefined"!=typeof globalThis?globalThis:we,xe=null==Se?void 0:Se.navigator,Ee=null==Se?void 0:Se.document,ke=null==Se?void 0:Se.location,Pe=null==Se?void 0:Se.fetch,Ce=null!=Se&&Se.XMLHttpRequest&&"withCredentials"in new Se.XMLHttpRequest?Se.XMLHttpRequest:void 0,Ie=null==Se?void 0:Se.AbortController,Fe=null==Se?void 0:Se.CompressionStream,Te=null==xe?void 0:xe.userAgent;function Re(){return!(!we||!1===we.navigator.onLine)}var Ae="undefined"!=typeof globalThis?globalThis:we;Ae&&"undefined"==typeof self&&(Ae.self=Ae),Ae&&"undefined"==typeof File&&(Ae.File=function(){});var Le=null!=we?we:{},Me=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}};function $e(e){return"string"==typeof e||e}function Oe(e){return"string"==typeof e?e:void 0}var De,Be=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],qe=function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.AiQueue="ai_queue",e.AiCaptureQueue="ai_capture_queue",e.LogsQueue="logs_queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.PushRegistered="push_registered",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e}({}),He=function(e){return e.GZipJS="gzip-js",e.Base64="base64",e}({}),Ne=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"],ze=["token"],je="NativeGzipValidationError",Ue=e=>e.length>=2&&31===e[0]&&139===e[1],Ve=(e,t)=>e===He.GZipJS||t===He.GZipJS||"gzip"===t,We=e=>!(!e||"object"!=typeof e)&&"NotReadableError"===("name"in e?String(e.name):""),Ge=e=>{var t=new Error("Native gzip produced invalid output: "+e);throw t.name=je,t},Ke=function(){var e=t((function*(e,t){18>e.size&&Ge("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());Ue(i)&&8===i[2]||Ge("invalid-header");var s=new DataView(yield e.slice(e.size-8).arrayBuffer());s.getUint32(0,!0)!==(e=>{for(var t=(()=>{if(De)return De;De=[];for(var e=0;256>e;e++){for(var t=e,i=0;8>i;i++)t=1&t?3988292384^t>>>1:t>>>1;De[e]=t>>>0}return De})(),i=4294967295,s=0;e.length>s;s++)i=t[255&(i^e[s])]^i>>>8;return(4294967295^i)>>>0})(t)&&Ge("invalid-crc");var r=t.length>>>0;s.getUint32(4,!0)!==r&&Ge("invalid-size")}));return function(t,i){return e.apply(this,arguments)}}();function Qe(){return Qe=t((function*(e,i,s){void 0===i&&(i=!0);try{var r=(new TextEncoder).encode(e),n=new globalThis.CompressionStream("gzip"),o=n.writable.getWriter(),a=o.write(r).then((()=>o.close())).catch(function(){var e=t((function*(e){try{yield o.abort(e)}catch(e){}throw e}));return function(t){return e.apply(this,arguments)}}()),l=new Response(n.readable).blob(),u=(yield Promise.all([l,a]))[0];return yield Ke(u,r),u}catch(e){if(null!=s&&s.rethrow)throw e;return i&&console.error("Failed to gzip compress data",e),null}})),Qe.apply(this,arguments)}var Je=20,Ye=1e3,Ze=1e4,Xe="[Circular]",et="[Truncated]",tt="[Unserializable]",it="[Function]";function st(e){for(var t="",i=0;e.length>i;i++){var s=e.charCodeAt(i);if(55296>s||s>56319)t+=56320>s||s>57343?e[i]:"�";else{var r=e.charCodeAt(i+1);56320>r||r>57343?t+="�":(t+=e[i]+e[i+1],i++)}}return t}var rt=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],nt=function(e,t){if(void 0===t&&(t=[]),!e)return!1;var i=e.toLowerCase();return rt.concat(t).some((e=>{var t=e.toLowerCase();return-1!==i.indexOf(t)}))};function ot(e,t){return-1!==e.indexOf(t)}var at=function(e){return e.trim()},lt=function(e){return e.replace(/^\$/,"")};function ut(e){var t,i=[];return null!==(t=JSON.stringify(e,(function(e,t){if("bigint"==typeof t)return t.toString();if("function"!=typeof t&&"symbol"!=typeof t){if(t instanceof Error)return{name:t.name,message:t.message,stack:t.stack};if(t&&"object"==typeof t){for(;i.length>0&&i[i.length-1]!==this;)i.pop();if(i.includes(t))return"[Circular]";i.push(t)}return t}})))&&void 0!==t?t:"null"}var ct=Object.prototype,dt=ct.hasOwnProperty,ht=ct.toString,_t=Array.isArray||function(e){return"[object Array]"===ht.call(e)},pt=e=>"function"==typeof e,gt=e=>e===Object(e)&&!_t(e),vt=e=>{if(gt(e)){for(var t in e)if(dt.call(e,t))return!1;return!0}return!1},ft=e=>void 0===e,mt=e=>"[object String]"==ht.call(e),yt=e=>mt(e)&&0===e.trim().length,bt=e=>null===e,wt=e=>ft(e)||bt(e),St=e=>"[object Number]"==ht.call(e)&&e==e,xt=e=>St(e)&&e>0,Et=e=>"[object Boolean]"===ht.call(e),kt=e=>e instanceof FormData,Pt=e=>ot(Ne,e),Ct=e=>ot(ze,e);function It(e){return null===e||"object"!=typeof e}function Ft(e,t){return{}.toString.call(e)==="[object "+t+"]"}function Tt(e){switch({}.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return At(e,Error)}}function Rt(e){return"undefined"!=typeof Event&&At(e,Event)}function At(e,t){try{return e instanceof t}catch(e){return!1}}var Lt=[!0,"true",1,"1","yes"],Mt=e=>ot(Lt,e),$t=[!1,"false",0,"0","no"];function Ot(e,t,i,s,r){return t>i&&(s.warn("min cannot be greater than max."),t=i),St(e)?e>i?(s.warn(" cannot be greater than max: "+i+". Using max value instead."),i):t>e?(s.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(s.warn(" must be a number. using max or fallback. max: "+i+", fallback: "+r),Ot(r||i,t,i,s))}class Dt{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Ot(e.bucketSize,0,100,e._logger),this._refillRate=Ot(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Ot(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){var i=Math.floor((t-e.lastAccess)/this._refillInterval);i>0&&(e.tokens=Math.min(e.tokens+i*this._refillRate,this._bucketSize),e.lastAccess=e.lastAccess+i*this._refillInterval)}consumeRateLimit(e){var t,i=Date.now(),s=String(e),r=this._buckets[s];return r?this._applyRefill(r,i):this._buckets[s]=r={tokens:this._bucketSize,lastAccess:i},0===r.tokens||(r.tokens--,0===r.tokens&&(null==(t=this._onBucketRateLimited)||t.call(this,e)),0===r.tokens)}stop(){this._buckets={}}}var Bt="Mobile",qt="iOS",Ht="Android",Nt="Tablet",zt=Ht+" "+Nt,jt="iPad",Ut="Apple",Vt=Ut+" Watch",Wt="Safari",Gt="BlackBerry",Kt="Samsung",Qt=Kt+"Browser",Jt=Kt+" Internet",Yt="Chrome",Zt=Yt+" OS",Xt=Yt+" "+qt,ei="Internet Explorer",ti=ei+" "+Bt,ii="Opera",si=ii+" Mini",ri="Edge",ni="Microsoft "+ri,oi="Firefox",ai=oi+" "+qt,li="Nintendo",ui="PlayStation",ci="Xbox",di=Ht+" "+Bt,hi=Bt+" "+Wt,_i="Windows",pi=_i+" Phone",gi="Nokia",vi="Ouya",fi="Generic",mi=fi+" "+Bt.toLowerCase(),yi=fi+" "+Nt.toLowerCase(),bi="Konqueror",wi="Oculus Browser",Si="Vivaldi",xi="Yandex",Ei="Whale",ki="DuckDuckGo",Pi="Pale Moon",Ci="Waterfox",Ii="Brave",Fi="Google Search App",Ti="(\\d+(\\.\\d+)?)",Ri=new RegExp("Version/"+Ti),Ai=new RegExp(ci,"i"),Li=new RegExp(ui+" \\w+","i"),Mi=new RegExp(li+" \\w+","i"),$i=new RegExp(Gt+"|PlayBook|BB10","i"),Oi={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},Di=function(e,t,i,s){t=t||"";var r=function(e){return null!=e&&e.brave?Ii:null}(i);return r||(null!=s&&s.detectGoogleSearchApp&&ot(e,"GSA/")?Fi:ot(e," OPR/")&&ot(e,"Mini")?si:ot(e," OPR/")?ii:$i.test(e)?Gt:ot(e,"IE"+Bt)||ot(e,"WPDesktop")?ti:ot(e,"OculusBrowser")?wi:ot(e,Qt)?Jt:ot(e,ri)||ot(e,"Edg/")?ni:ot(e,Si+"/")?Si:ot(e,"YaBrowser/")?xi:ot(e,Ei+"/")?Ei:ot(e,ki+"/")||ot(e,"Ddg/")?ki:ot(e,"FBIOS")?"Facebook "+Bt:ot(e,"UCWEB")||ot(e,"UCBrowser")?"UC Browser":ot(e,"CriOS")?Xt:ot(e,"CrMo")||ot(e,Yt)?Yt:ot(e,Ht)&&ot(e,Wt)?di:ot(e,"FxiOS")?ai:ot(e.toLowerCase(),bi.toLowerCase())?bi:ot(e,Ii+"/")?Ii:((e,t)=>t&&ot(t,Ut)||function(e){return ot(e,Wt)&&!ot(e,Yt)&&!ot(e,Ht)}(e))(e,t)?ot(e,Bt)?hi:Wt:ot(e,"PaleMoon/")?Pi:ot(e,Ci+"/")?Ci:ot(e,oi)?oi:ot(e,"MSIE")||ot(e,"Trident/")?ei:ot(e,"Gecko")?oi:"")},Bi={[ti]:[new RegExp("rv:"+Ti)],[ni]:[new RegExp(ri+"?\\/"+Ti)],[Yt]:[new RegExp("("+Yt+"|CrMo)\\/"+Ti)],[Xt]:[new RegExp("CriOS\\/"+Ti)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Ti)],[Wt]:[Ri],[hi]:[Ri],[ii]:[new RegExp("(Opera|OPR)\\/"+Ti)],[oi]:[new RegExp(oi+"\\/"+Ti)],[ai]:[new RegExp("FxiOS\\/"+Ti)],[bi]:[new RegExp("Konqueror[:/]?"+Ti,"i")],[Gt]:[new RegExp(Gt+" "+Ti),Ri],[di]:[new RegExp("android\\s"+Ti,"i")],[Jt]:[new RegExp(Qt+"\\/"+Ti)],[wi]:[new RegExp("OculusBrowser\\/"+Ti)],[Si]:[new RegExp(Si+"\\/"+Ti)],[xi]:[new RegExp("YaBrowser\\/"+Ti)],[Ei]:[new RegExp(Ei+"\\/"+Ti)],[Ii]:[new RegExp(Ii+"\\/"+Ti)],[ki]:[new RegExp("(DuckDuckGo|Ddg)\\/"+Ti)],[Pi]:[new RegExp("PaleMoon\\/"+Ti)],[Ci]:[new RegExp(Ci+"\\/"+Ti)],[Fi]:[new RegExp("GSA\\/"+Ti)],[ei]:[new RegExp("(rv:|MSIE )"+Ti)],Mozilla:[new RegExp("rv:"+Ti)]},qi=function(e,t,i,s){var r=Di(e,t,i,s),n=Bi[r];if(ft(n))return null;for(var o=0;n.length>o;o++){var a=e.match(n[o]);if(a)return parseFloat(a[a.length-2])}return null},Hi=[[new RegExp(ci+"; "+ci+" (.*?)[);]","i"),e=>[ci,e&&e[1]||""]],[new RegExp(li,"i"),[li,""]],[new RegExp(ui,"i"),[ui,""]],[$i,[Gt,""]],[new RegExp(_i,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[pi,""];if(new RegExp(Bt).test(t)&&!/IEMobile\b/.test(t))return[_i+" "+Bt,""];var i=/Windows NT ([0-9.]+)/i.exec(t);if(i&&i[1]){var s=Oi[i[1]]||"";return/arm/i.test(t)&&(s="RT"),[_i,s]}return[_i,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>e&&e[3]?[qt,[e[3],e[4],e[5]||"0"].join(".")]:[qt,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{var t="";return e&&e.length>=3&&(t=ft(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Ht+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Ht+")","i"),e=>e&&e[2]?[Ht,[e[2],e[3],e[4]||"0"].join(".")]:[Ht,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{var t=["Mac OS X",""];return e&&e[1]&&(t[1]=[e[1],e[2],e[3]||"0"].join(".")),t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Zt,""]],[/Linux|debian/i,["Linux",""]]],Ni=function(e){return Mi.test(e)?li:Li.test(e)?ui:Ai.test(e)?ci:new RegExp(vi,"i").test(e)?vi:new RegExp("("+pi+"|WPDesktop)","i").test(e)?pi:/iPad/.test(e)?jt:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?Vt:$i.test(e)?Gt:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(gi,"i").test(e)?gi:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(e)||/(kf[a-z]+)( bui|\)).+silk\//i.test(e)?"Kindle Fire":/(Android|ZTE)/i.test(e)?new RegExp(Bt).test(e)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(e)||/pixel[\daxl ]{1,6}/i.test(e)&&!/pixel c/i.test(e)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(e)||/lmy47v/i.test(e)&&!/QTAQZ3/i.test(e)?Ht:zt:new RegExp("(pda|"+Bt+")","i").test(e)?mi:new RegExp(Nt,"i").test(e)&&!new RegExp(Nt+" pc","i").test(e)?yi:""},zi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ji(e,t){return"string"==typeof(i=e)&&zi.test(i)?e:t();var i}function Ui(e){return e?e.split("#")[0]:e}function Vi(e,t){var i=setTimeout(e,t);return(null==i?void 0:i.unref)&&(null==i||i.unref()),i}function Wi(e,t,i){return Gi.apply(this,arguments)}function Gi(){return(Gi=t((function*(e,t,i){var s;try{return yield Promise.race([e,new Promise(((e,r)=>{s=Vi((()=>{try{null==i||i(),e()}catch(e){r(e)}}),t)}))])}finally{clearTimeout(s)}}))).apply(this,arguments)}var Ki={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},Qi=Ki.info,Ji=0x8000000000000000,Yi={}.propertyIsEnumerable;function Zi(e,t){try{return ts(e,t,{ancestors:new WeakSet,remainingNodes:Ze},0)}catch(e){return[]}}function Xi(e,t,i,s){if(0>=i.remainingNodes)return{stringValue:et};if(i.remainingNodes--,Et(e))return{boolValue:e};if("number"==typeof e){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if("undefined"==typeof BigInt)return{stringValue:String(e)};var r=BigInt(e).toString();return e>=Ji||-Ji>e?(null==t||t.debug("Attribute "+r+" is outside the int64 range; encoding it as a string"),{stringValue:r}):{intValue:r}}return{doubleValue:e}}if("string"==typeof e)return{stringValue:st(e)};if("function"==typeof e)return{stringValue:it};if("symbol"==typeof e)return{stringValue:String(e)};if("object"==typeof e&&null!==e){if(i.ancestors.has(e))return{stringValue:Xe};if(s>=Je)return{stringValue:et};if(e instanceof Date){var n=e.getTime(),o=Number.isFinite(n)?e.toISOString():String(e);return{stringValue:"string"==typeof o?st(o):String(o)}}i.ancestors.add(e);try{try{var a=e.toJSON;if("function"==typeof a)return Xi(a.call(e),t,i,s+1)}catch(e){}return _t(e)?{arrayValue:{values:es(e,t,i,s+1)}}:{kvlistValue:{values:ts(e,t,i,s+1)}}}finally{i.ancestors.delete(e)}}return{stringValue:st(String(e))}}function es(e,t,i,s){for(var r=[],n=Math.min(e.length,Ye),o=0;n>o&&i.remainingNodes>0;o++)try{var a=o in e?e[o]:void 0;if(wt(a))continue;r.push(Xi(a,t,i,s))}catch(e){r.push({stringValue:tt})}return e.length>o&&r.push({stringValue:et}),r}function ts(e,t,i,s){var r=[];for(var n in e)if(Yi.call(e,n)){if(r.length>=Ye||0>=i.remainingNodes){null==t||t.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{var o=e[n];if(bt(o)||ft(o))continue;r.push({key:st(n),value:Xi(o,t,i,s)})}catch(e){r.push({key:st(n),value:{stringValue:tt}})}}return r}function is(e){try{return st(String(e))}catch(e){return tt}}function ss(e,t,s){var r=Ki[e.level||"info"]||Qi,n=r.text,o=r.number,a=String(Date.now())+"000000",l={};t.distinctId&&(l.posthogDistinctId=t.distinctId),t.sessionId&&(l.sessionId=t.sessionId),t.windowId&&(l["window.id"]=t.windowId),wt(t.sessionStartTimestamp)||(l.sessionStartTimestamp=String(t.sessionStartTimestamp)),wt(t.lastActivityTimestamp)||(l.lastActivityTimestamp=String(t.lastActivityTimestamp)),t.currentUrl&&(l["url.full"]=t.currentUrl),t.screenName&&(l["screen.name"]=t.screenName),t.appState&&(l["app.state"]=t.appState),t.activeFeatureFlags&&t.activeFeatureFlags.length>0&&(l.feature_flags=t.activeFeatureFlags);var u=i({},l),c=e.attributes;if(c){var d=[];try{d=Object.keys(c)}catch(e){d=[]}for(var h of d){var _=void 0;try{_=c[h]}catch(e){_=tt}Object.defineProperty(u,h,{value:_,enumerable:!0,writable:!0,configurable:!0})}}var p={timeUnixNano:a,observedTimeUnixNano:a,severityNumber:o,severityText:n,body:{stringValue:is(e.body)},attributes:Zi(u,s)};return e.trace_id&&(p.traceId=e.trace_id),e.span_id&&(p.spanId=e.span_id),ft(e.trace_flags)||(p.flags=e.trace_flags),p}function rs(e,t,s){return i({},e.resourceAttributes,{"service.name":e.serviceName||"unknown_service"},e.environment&&{"deployment.environment":e.environment},e.serviceVersion&&{"service.version":e.serviceVersion},{"telemetry.sdk.name":t,"telemetry.sdk.version":s})}function ns(e,t,i,s){return{resourceLogs:[{resource:{attributes:Zi(t)},scopeLogs:[{scope:{name:i,version:s},logRecords:e}]}]}}let os=class{constructor(e,t,i,s,r,n,o){var a;void 0===n&&(n=()=>Promise.resolve()),this._instance=e,this._config=t,this._logger=i,this._getContext=s,this._onReady=r,this._waitForStoragePersist=n,this._scopeName=o,this._flushPromise=null,this._evictedSinceAdvance=0,this._consecutiveFlushFailures=0,this._intervalWindowStart=0,this._intervalLogCount=0,this._droppedWarned=!1,this._maxBufferSize=t.maxBufferSize,this._maxQueueSize=Math.max(null!==(a=t.maxQueueSize)&&void 0!==a?a:t.maxBufferSize,t.maxBufferSize),this._flushIntervalMs=t.flushIntervalMs,this._maxBatchRecordsPerPost=t.maxBatchRecordsPerPost,this._rateCapWindowMs=t.rateCapWindowMs,this._maxLogsPerInterval=t.maxLogsPerInterval}reset(){this._clearFlushTimer(),this._flushPromise=null,this._intervalWindowStart=0,this._intervalLogCount=0,this._droppedWarned=!1,this._evictedSinceAdvance=0,this._consecutiveFlushFailures=0,this._maxBatchRecordsPerPost=this._config.maxBatchRecordsPerPost}onReconnect(){this._consecutiveFlushFailures=0,this._flushInBackground()}captureLog(e){if(!this._instance.isDisabled&&!this._instance.optedOut&&null!=e&&e.body){var t=this._runBeforeSend(e);if(null!==t)if(t.body){if(this._checkRateLimit()){var i={record:ss(t,this._getContext(),this._logger)};this._onReady((()=>this._enqueue(i)))}}else this._logger.info("Log was rejected in beforeSend function")}}_runBeforeSend(e){var t=this._config.beforeSend;if(!t)return e;var i=_t(t)?t:[t],s=e;for(var r of i)try{var n=r(s);if(!n)return this._logger.info("Log was rejected in beforeSend function"),null;s=n}catch(e){return this._logger.error("Error in beforeSend function for log:",e),null}return s}_checkRateLimit(){if(void 0===this._maxLogsPerInterval)return!0;var e=Date.now(),t=e-this._intervalWindowStart;return this._rateCapWindowMs>t&&t>=0||(this._intervalWindowStart=e,this._intervalLogCount=0,this._droppedWarned=!1),this._maxLogsPerInterval>this._intervalLogCount?(this._intervalLogCount++,!0):(this._droppedWarned||(this._logger.warn("captureLog dropping logs: exceeded "+this._maxLogsPerInterval+" logs per "+this._rateCapWindowMs+"ms"),this._droppedWarned=!0),!1)}flush(){var e=this;return t((function*(){if(!e._instance.isDisabled)return e._flushPromise||(e._flushPromise=e._flushInner().finally((()=>{e._flushPromise=null}))),e._flushPromise}))()}_flushInner(){var e=this;return t((function*(){var t;e._clearFlushTimer();var i=null!==(t=e._instance.getPersistedProperty(qe.LogsQueue))&&void 0!==t?t:[];if(0!==i.length)for(var s=i.length,r=0;i.length>0&&s>r;){var n,o;e._evictedSinceAdvance=0;var a=Math.min(i.length,e._maxBatchRecordsPerPost),l=i.slice(0,a),u=ns(l.map((e=>e.record)),e._buildResourceAttributes(),null!==(n=e._scopeName)&&void 0!==n?n:e._instance.getLibraryId(),e._instance.getLibraryVersion()),c=yield e._instance._sendLogsBatch(u);if("too-large"===c.kind&&l.length>1)e._maxBatchRecordsPerPost=Math.max(1,Math.floor(l.length/2)),e._logger.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+e._maxBatchRecordsPerPost);else{if("retry-later"===c.kind)throw c.error;if("too-large"===c.kind?e._logger.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):"ok"===c.kind&&e._config.maxBatchRecordsPerPost>e._maxBatchRecordsPerPost&&(e._maxBatchRecordsPerPost=Math.min(e._config.maxBatchRecordsPerPost,e._maxBatchRecordsPerPost+1)),yield e._persistQueueAdvance(l.length),i=null!==(o=e._instance.getPersistedProperty(qe.LogsQueue))&&void 0!==o?o:[],r+=l.length,"fatal"===c.kind)throw c.error}}}))()}_persistQueueAdvance(e){var i=this;return t((function*(){var t,s=Math.max(0,e-i._evictedSinceAdvance),r=null!==(t=i._instance.getPersistedProperty(qe.LogsQueue))&&void 0!==t?t:[];i._instance.setPersistedProperty(qe.LogsQueue,r.slice(s)),yield i._waitForStoragePersist()}))()}_buildResourceAttributes(){return rs(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion())}_enqueue(e){var t;if(!this._instance.optedOut){var i=null!==(t=this._instance.getPersistedProperty(qe.LogsQueue))&&void 0!==t?t:[];this._maxQueueSize>i.length||(i.shift(),this._evictedSinceAdvance++,this._logger.info("Logs queue is full, dropping oldest record.")),i.push(e),this._instance.setPersistedProperty(qe.LogsQueue,i),this._maxBufferSize>i.length?this._armFlushTimer():this._flushInBackground()}}_armFlushTimer(e){void 0===e&&(e=this._flushIntervalMs),this._flushTimer||(this._flushTimer=Vi((()=>{this._flushTimer=void 0,this._flushInBackground()}),e))}_nextFlushDelay(){var e=Math.min(Math.max(0,this._consecutiveFlushFailures-1),6);return this._flushIntervalMs*Math.pow(2,e)}_hasQueuedRecords(){var e=this._instance.getPersistedProperty(qe.LogsQueue);return!!e&&e.length>0}shutdown(e){var i=this;return t((function*(){i._clearFlushTimer();var t=i.flush().catch((()=>{}));void 0!==e?yield Wi(t,e):yield t}))()}flushWithTimeout(e){var i=this;return t((function*(){var t=i.flush();yield Wi(t,e,(()=>{t.catch((()=>{}))}))}))()}_flushInBackground(){this.flush().then((()=>{this._consecutiveFlushFailures=0}),(e=>{this._consecutiveFlushFailures++,this._logger.error("PostHog logs flush failed:",e)})).finally((()=>{!this._instance.isDisabled&&this._hasQueuedRecords()&&this._armFlushTimer(this._nextFlushDelay())}))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}};var as=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function ls(e){return String(e)+"000000"}function us(e,t,i,s){var r="";return s&&(r=Object.keys(s).sort().map((e=>JSON.stringify(e)+":"+JSON.stringify(s[e]))).join(",")),e+"\0"+t+"\0"+(null!=i?i:"")+"\0"+r}let cs=class{constructor(e,t,i){this._instance=e,this._config=t,this._logger=i,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._generation=0}count(e,t,i){void 0===t&&(t=1),this._capture({name:e,type:"count",value:t,unit:null==i?void 0:i.unit,attributes:null==i?void 0:i.attributes})}gauge(e,t,i){this._capture({name:e,type:"gauge",value:t,unit:null==i?void 0:i.unit,attributes:null==i?void 0:i.attributes})}histogram(e,t,i){this._capture({name:e,type:"histogram",value:t,unit:null==i?void 0:i.unit,attributes:null==i?void 0:i.attributes})}flush(){var e=this,i=this._flushPromise,s=function(){var s=t((function*(){i&&(yield i.catch((()=>{}))),yield e._doFlush()}));return function(){return s.apply(this,arguments)}}(),r=s().finally((()=>{this._flushPromise===r&&(this._flushPromise=null)}));return this._flushPromise=r,r}drainWindow(){if(0===this._series.size)return null;var e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._clearFlushTimer(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(!this._instance.isDisabled&&!this._instance.optedOut){var t=this._runBeforeSend(e);if(null!==t)if(t.name&&"string"==typeof t.name)if("number"==typeof t.value&&Number.isFinite(t.value))if("count"===t.type&&0>t.value)this._logger.warn("Dropping count '"+t.name+"': counters are monotonic, value must be >= 0");else{var s,r;try{s=t.attributes?i({},t.attributes):void 0,r=us(t.type,t.name,t.unit,s)}catch(e){return void this._logger.warn("Dropping metric '"+t.name+"': attributes could not be serialized",e)}var n=this._series.get(r);if(!n){if(!this._admitNewSeries())return;n={name:t.name,type:t.type,unit:t.unit,attributes:s,windowStartMs:Date.now()},this._series.set(r,n)}var o=this._typeByName.get(t.name);void 0===o?this._typeByName.set(t.name,t.type):o===t.type||this._typeCollisionWarned.has(t.name)||(this._typeCollisionWarned.add(t.name),this._logger.warn("Metric name '"+t.name+"' is already used as a "+o+"; recording it as a "+t.type+" too will blend both series in charts. Use a distinct name.")),this._fold(n,t.value),this._armFlushTimer()}else this._logger.warn("Dropping metric '"+t.name+"': value must be a finite number");else this._logger.warn("Dropping metric with empty name")}}_admitNewSeries(){return this._config.maxSeriesPerFlush>this._series.size||(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn("Metric series cap reached ("+this._config.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}_fold(e,t){var i;switch(e.type){case"count":e.total=(null!==(i=e.total)&&void 0!==i?i:0)+t;break;case"gauge":e.last=t;break;case"histogram":e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:new Array(as.length+1).fill(0)});var s=e.hist;s.count+=1,s.sum+=t,s.min=Math.min(s.min,t),s.max=Math.max(s.max,t),s.bucketCounts[function(e,t){for(var i=0;t.length>i;i++)if(t[i]>=e)return i;return t.length}(t,as)]+=1}}_runBeforeSend(e){var t=this._config.beforeSend;if(!t)return e;var i=_t(t)?t:[t],s=e;for(var r of i)try{var n=r(s);if(!n)return this._logger.info("Metric was rejected in beforeSend function"),null;s=n}catch(e){return this._logger.error("Error in beforeSend function for metric:",e),null}return s}_armFlushTimer(){this._flushTimer||(this._flushTimer=Vi((()=>{this._flushTimer=void 0,this.flush().catch((e=>{this._logger.error("Metrics flush failed:",e)}))}),this._config.flushIntervalMs))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}_doFlush(){var e=this;return t((function*(){if(0!==e._series.size){var t=e._series;e._series=new Map,e._seriesCapWarned=!1,e._typeByName=new Map,e._typeCollisionWarned=new Set;var i=e._generation,s=yield e._instance._sendMetricsBatch(e._buildPayload(t));if(i===e._generation)switch(s.kind){case"ok":return;case"retry-later":return e._mergeWindowBack(t),void e._armFlushTimer();case"too-large":return void e._logger.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void e._logger.error("Failed to send metrics batch:",s.error)}}}))()}_buildPayload(e){return t=this._buildMetrics(e),s=function(e,t,s){return i({},e.resourceAttributes,{"service.name":e.serviceName||"unknown_service"},e.environment&&{"deployment.environment":e.environment},e.serviceVersion&&{"service.version":e.serviceVersion},{"telemetry.sdk.name":t,"telemetry.sdk.version":s})}(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),r=this._instance.getLibraryId(),n=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Zi(s)},scopeMetrics:[{scope:{name:r,version:n},metrics:t}]}]};var t,s,r,n}_buildMetrics(e){var t=ls(Date.now()),s=new Map;for(var r of e.values()){var n,o=us(r.type,r.name,r.unit,void 0),a=s.get(o);a||(a=i({name:r.name},r.unit&&{unit:r.unit}),"count"===r.type?a.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===r.type?a.gauge={dataPoints:[]}:a.histogram={aggregationTemporality:1,dataPoints:[]},s.set(o,a));var l=Zi(null!==(n=r.attributes)&&void 0!==n?n:{},this._logger),u=ls(r.windowStartMs);if("count"===r.type){var c,d={attributes:l,startTimeUnixNano:u,timeUnixNano:t,asDouble:null!==(c=r.total)&&void 0!==c?c:0};a.sum.dataPoints.push(d)}else if("gauge"===r.type){var h,_={attributes:l,timeUnixNano:t,asDouble:null!==(h=r.last)&&void 0!==h?h:0};a.gauge.dataPoints.push(_)}else r.hist&&a.histogram.dataPoints.push({attributes:l,startTimeUnixNano:u,timeUnixNano:t,count:r.hist.count,sum:r.hist.sum,min:r.hist.min,max:r.hist.max,bucketCounts:r.hist.bucketCounts,explicitBounds:as})}return Array.from(s.values())}_mergeWindowBack(e){var t,i;for(var s of e){var r=s[0],n=s[1],o=this._series.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,n.windowStartMs),o.type){case"count":o.total=(null!==(t=o.total)&&void 0!==t?t:0)+(null!==(i=n.total)&&void 0!==i?i:0);break;case"gauge":break;case"histogram":if(n.hist)if(o.hist){o.hist.count+=n.hist.count,o.hist.sum+=n.hist.sum,o.hist.min=Math.min(o.hist.min,n.hist.min),o.hist.max=Math.max(o.hist.max,n.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=n.hist.bucketCounts[a]}else o.hist=n.hist}else this._admitNewSeries()&&this._series.set(r,n)}}};var ds,hs,_s;function ps(e){var t=globalThis._posthogChunkIds;if(t){var i=Object.keys(t);return _s&&i.length===hs||(hs=i.length,_s=i.reduce(((i,s)=>{ds||(ds={});var r=ds[s];if(r)i[r[0]]=r[1];else for(var n=e(s),o=n.length-1;o>=0;o--){var a=n[o],l=null==a?void 0:a.filename,u=t[s];if(l&&u){i[l]=u,ds[s]=[l,u];break}}return i}),{})),_s}}class gs{constructor(e,t,i){void 0===i&&(i=[]),this.coercers=e,this.stackParser=t,this.modifiers=i}buildFromUnknown(e,t){void 0===t&&(t={});var i=t&&t.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,t,0).apply(e),r=this.buildParsingContext(t),n=this.parseStacktrace(s,r);return{$exception_list:this.convertToExceptionList(n,i),$exception_level:"error"}}modifyFrames(e){var i=this;return t((function*(){for(var t of e)t.stacktrace&&t.stacktrace.frames&&_t(t.stacktrace.frames)&&(t.stacktrace.frames=yield i.applyModifiers(t.stacktrace.frames));return e}))()}coerceFallback(e){var t;return{type:"Error",value:"Unknown error",stack:null==(t=e.syntheticException)?void 0:t.stack,synthetic:!0}}parseStacktrace(e,t){var s,r;return null!=e.cause&&(s=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),i({},e,{cause:s,stack:r})}applyChunkIds(e,t){return e.map((e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e)))}applyCoercers(e,t){for(var i of this.coercers)if(i.match(e))return i.coerce(e,t);return this.coerceFallback(t)}applyModifiers(e){var i=this;return t((function*(){var t=e;for(var s of i.modifiers)t=yield s(t);return t}))()}convertToExceptionList(e,t){var s,r,n,o={type:e.type,value:e.value,mechanism:{type:null!==(s=t.type)&&void 0!==s?s:"generic",handled:null===(r=t.handled)||void 0===r||r,synthetic:null!==(n=e.synthetic)&&void 0!==n&&n}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return null!=e.cause&&a.push(...this.convertToExceptionList(e.cause,i({},t,{handled:!0}))),a}buildParsingContext(e){var t;return{chunkIdMap:ps(this.stackParser),skipFirstLines:null!==(t=e.skipFirstLines)&&void 0!==t?t:1}}buildCoercingContext(e,t,s){void 0===s&&(s=0);var r=(i,s)=>{if(4>=s){var r=this.buildCoercingContext(e,t,s);return this.applyCoercers(i,r)}};return i({},t,{syntheticException:0==s?t.syntheticException:void 0,mechanism:e,apply:e=>r(e,s),next:e=>r(e,s+1)})}}var vs="?";function fs(e,t,i,s,r){var n={platform:e,filename:t,function:"<anonymous>"===i?vs:i,in_app:!(null!=t&&t.startsWith("webkit-masked-url://"))&&"<anonymous>"!==t};return ft(s)||(n.lineno=s),ft(r)||(n.colno=r),n}var ms=(e,t)=>{var i=-1!==e.indexOf("safari-extension"),s=-1!==e.indexOf("safari-web-extension");return i||s?[-1!==e.indexOf("@")?e.split("@")[0]:vs,i?"safari-extension:"+t:"safari-web-extension:"+t]:[e,t]},ys=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,bs=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ws=/\((\S*)(?::(\d+))(?::(\d+))\)/,Ss=(e,t)=>{var i=ys.exec(e);if(i)return fs(t,i[1],vs,+i[2],+i[3]);var s=bs.exec(e);if(s){if(s[2]&&0===s[2].indexOf("eval")){var r=ws.exec(s[2]);r&&(s[2]=r[1],s[3]=r[2],s[4]=r[3])}var n=ms(s[1]||vs,s[2]);return fs(t,n[1],n[0],s[3]?+s[3]:void 0,s[4]?+s[4]:void 0)}},xs=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Es=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ks=(e,t)=>{var i=xs.exec(e);if(i){if(i[3]&&i[3].indexOf(" > eval")>-1){var s=Es.exec(i[3]);s&&(i[1]=i[1]||"eval",i[3]=s[1],i[4]=s[2],i[5]="")}var r=i[3],n=i[1]||vs,o=ms(n,r);return fs(t,r=o[1],n=o[0],i[4]?+i[4]:void 0,i[5]?+i[5]:void 0)}},Ps=/\(error: (.*)\)/;class Cs{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){var i=mt(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?t+": "+e.message:t}isDOMException(e){return Ft(e,"DOMException")}isDOMError(e){return Ft(e,"DOMError")}}class Is{match(e){return Tt(e)}coerce(e,t){var i,s=this.getStack(e),r=void 0===s;return{type:this.getType(e),value:this.getMessage(e,t),stack:null!=s?s:null==(i=t.syntheticException)?void 0:i.stack,cause:e.cause?t.next(e.cause):void 0,synthetic:r}}getType(e){return e.name||e.constructor.name}getMessage(e,t){var i=e.message;return String(i.error&&"string"==typeof i.error.message?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class Fs{constructor(){}match(e){return!!Ft(e,"ErrorEvent")&&(null!=e.error||this._hasUsableMessage(e))}coerce(e,t){var s;if(null!=e.error)return t.apply(e.error);var r=t.apply(e.message);return i({},r,{stack:null!==(s=this._buildLocationStack(e))&&void 0!==s?s:r.stack,synthetic:!0})}_hasUsableMessage(e){return mt(e.message)&&e.message.length>0}_buildLocationStack(e){var t,i,s=e,r=null!==(t=s.lineno)&&void 0!==t?t:0,n=null!==(i=s.colno)&&void 0!==i?i:0;if(mt(s.filename)&&0!==s.filename.length&&0!==r)return"Error\n at "+s.filename+":"+r+":"+n}}var Ts=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Rs{match(e){return"string"==typeof e}coerce(e,t){var i,s=this.getInfos(e),r=s[0],n=s[1];return{type:null!=r?r:"Error",value:null!=n?n:e,stack:null==(i=t.syntheticException)?void 0:i.stack,synthetic:!0}}getInfos(e){var t="Error",i=e,s=e.match(Ts);return s&&(t=s[1],i=s[2]),[t,i]}}var As=["fatal","error","warning","log","info","debug"];function Ls(e,t){void 0===t&&(t=40);var i=Object.keys(e);if(i.sort(),!i.length)return"[object has no keys]";for(var s=i.length;s>0;s--){var r=i.slice(0,s).join(", ");if(t>=r.length)return s===i.length?r:r.length>t?r.slice(0,t)+"...":r}return""}class Ms{match(e){return"object"==typeof e&&null!==e}coerce(e,t){var i,s,r=this.getErrorPropertyFromObject(e);return r?t.apply(r):{type:this.getType(e),value:this.getValue(e),stack:null!==(i=this.getStack(e))&&void 0!==i?i:null==(s=t.syntheticException)?void 0:s.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(Rt(e))return e.constructor.name;var t="name"in e?e.name:void 0;return mt(t)&&!yt(t)?t:"Error"}getValue(e){if("name"in e&&"string"==typeof e.name){var t="'"+e.name+"' captured as exception";return"message"in e&&"string"==typeof e.message&&(t+=" with message: '"+e.message+"'"),t}if("message"in e&&"string"==typeof e.message)return e.message;var i=this.getObjectClassName(e);return(i&&"Object"!==i?"'"+i+"'":"Object")+" captured as exception with keys: "+Ls(e)}isSeverityLevel(e){return mt(e)&&!yt(e)&&As.indexOf(e)>=0}getStack(e){try{return mt(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:mt(e.stack)&&e.stack.length>0?e.stack:void 0}catch(e){return}}getErrorPropertyFromObject(e){for(var t in e)if({}.hasOwnProperty.call(e,t)){var i=e[t];if(Tt(i))return i}}getObjectClassName(e){try{var t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){return}}}class $s{match(e){return Rt(e)}coerce(e,t){var i,s=e.constructor.name;return{type:s,value:s+" captured as exception with keys: "+Ls(e),stack:null==(i=t.syntheticException)?void 0:i.stack,synthetic:!0}}}class Os{match(e){return It(e)}coerce(e,t){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:null==(i=t.syntheticException)?void 0:i.stack,synthetic:!0}}}class Ds{match(e){return Ft(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Rt(e))return!1;try{var t=e.detail;return null!=t&&"object"==typeof t&&"reason"in t}catch(e){return!1}}coerce(e,t){var i,s=this.getUnhandledRejectionReason(e);return It(s)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(s),stack:null==(i=t.syntheticException)?void 0:i.stack,synthetic:!0}:t.apply(s)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&null!=e.detail&&"object"==typeof e.detail&&"reason"in e.detail)return e.detail.reason}catch(e){}return e}}var Bs="$message",qs="$timestamp",Hs=new Set([Bs,qs]),Ns={enabled:!0,max_bytes:32768};function zs(e){var t;return e?{enabled:null!==(t=e.enabled)&&void 0!==t?t:Ns.enabled,max_bytes:Us(e.max_bytes,Ns.max_bytes)}:i({},Ns)}class js{constructor(e){this._entries=[],this._totalBytes=0,this._config=zs(e)}setConfig(e){this._config=zs(e),this._trimToMaxBytes()}add(e){var t=function(e){var t;try{t=ut(e)}catch(e){return}try{var i=JSON.parse(t);if(!gt(i))return;var s=i,r=s[Bs],n=s[qs];if(!mt(r)||0===r.trim().length)return;if(!mt(n)&&!St(n))return;return{step:s,json:t}}catch(e){return}}(e);if(t){var i=function(e){if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e).length;for(var t=encodeURIComponent(e),i=0,s=0;t.length>s;s++)"%"===t[s]?(i+=1,s+=2):i+=1;return i}(t.json);i>this._config.max_bytes||(this._entries.push({step:t.step,bytes:i}),this._totalBytes+=i,this._trimToMaxBytes())}}getAttachable(){return this._entries.map((e=>e.step))}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){var e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}}function Us(e,t){if(!St(e)||e===1/0||e===-1/0)return t;var i=Math.floor(e);return 0>i?t:i}var Vs=function(e,t){var i=(void 0===t?{}:t).debugEnabled,s={_log(t){if(we&&(r.DEBUG||we.POSTHOG_DEBUG||i)&&!ft(we.console)&&we.console){for(var s=("__rrweb_original__"in we.console[t]?we.console[t].__rrweb_original__:we.console[t]),n=arguments.length,o=new Array(n>1?n-1:0),a=1;n>a;a++)o[a-1]=arguments[a];s(e,...o)}},debug(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];s._log("debug",...t)},info(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];s._log("log",...t)},warn(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];s._log("warn",...t)},error(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];s._log("error",...t)},critical(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];console.error(e,...i)},uninitializedWarning(e){s.error("You must initialize PostHog before calling "+e)},createLogger:(t,i)=>Vs(e+" "+t,i)};return s},Ws=Vs("[PostHog.js]"),Gs=Ws.createLogger;function Ks(e,t){_t(e)&&e.forEach(t)}function Qs(e,t){if(!wt(e))if(_t(e))e.forEach(t);else if(kt(e))e.forEach(((e,i)=>t(e,i)));else for(var i in e)dt.call(e,i)&&t(e[i],i)}var Js=function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;t>s;s++)i[s-1]=arguments[s];for(var r of i)for(var n in r)void 0!==r[n]&&(e[n]=r[n]);return e};function Ys(e){for(var t=Object.keys(e),i=t.length,s=new Array(i);i--;)s[i]=[t[i],e[t[i]]];return s}var Zs=function(e){try{return e()}catch(e){return}},Xs=function(e){return function(){try{for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];return e.apply(this,i)}catch(e){Ws.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),Ws.critical(e)}}},er=function(e){var t={};return Qs(e,(function(e,i){(mt(e)&&e.length>0||St(e))&&(t[i]=e)})),t};var tr=["herokuapp.com","vercel.app","netlify.app"];function ir(e){var t=null==e?void 0:e.hostname;if(!mt(t))return!1;var i=t.split(".").slice(-2).join(".");for(var s of tr)if(i===s)return!1;return!0}function sr(e,t,i,s){var r=null!=s?s:{},n=r.capture,o=r.passive;null==e||e.addEventListener(t,i,{capture:void 0!==n&&n,passive:void 0===o||o})}function rr(e){return"ph_toolbar_internal"===e.name}var nr=e=>{if(Ee){try{for(var t=e+"=",i=Ee.cookie.split(";").filter((e=>e.length)),s=0;i.length>s;s++){for(var r=i[s];" "==r.charAt(0);)r=r.substring(1,r.length);if(0===r.indexOf(t))return decodeURIComponent(r.substring(t.length,r.length))}}catch(e){}return null}};Math.trunc||(Math.trunc=function(e){return 0>e?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return St(e)&&isFinite(e)&&Math.floor(e)===e});class or{constructor(e){if(this.bytes=e,16!==e.length)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,i,s){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(i)||!Number.isInteger(s)||0>e||0>t||0>i||0>s||e>0xffffffffffff||t>4095||i>1073741823||s>4294967295)throw new RangeError("invalid field value");var r=new Uint8Array(16);return r[0]=e/Math.pow(2,40),r[1]=e/Math.pow(2,32),r[2]=e/Math.pow(2,24),r[3]=e/Math.pow(2,16),r[4]=e/256,r[5]=e,r[6]=112|t>>>8,r[7]=t,r[8]=128|i>>>24,r[9]=i>>>16,r[10]=i>>>8,r[11]=i,r[12]=s>>>24,r[13]=s>>>16,r[14]=s>>>8,r[15]=s,new or(r)}toString(){for(var e="",t=0;this.bytes.length>t;t++)e=e+(this.bytes[t]>>>4).toString(16)+(15&this.bytes[t]).toString(16),3!==t&&5!==t&&7!==t&&9!==t||(e+="-");if(36!==e.length)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new or(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(var t=0;16>t;t++){var i=this.bytes[t]-e.bytes[t];if(0!==i)return Math.sign(i)}return 0}}class ar{generate(){var e=this.generateOrAbort();if(!ft(e))return e;this._timestamp=0;var t=this.generateOrAbort();if(ft(t))throw new Error("Could not generate UUID after timestamp reset");return t}generateOrAbort(){var e=Date.now();if(e>this._timestamp)this._timestamp=e,this._resetCounter();else{if(this._timestamp>=e+1e4)return;this._counter++,this._counter>4398046511103&&(this._timestamp++,this._resetCounter())}return or.fromFieldsV7(this._timestamp,Math.trunc(this._counter/Math.pow(2,30)),this._counter&Math.pow(2,30)-1,this._random.nextUint32())}_resetCounter(){this._counter=1024*this._random.nextUint32()+(1023&this._random.nextUint32())}constructor(){this._timestamp=0,this._counter=0,this._random=new cr}}var lr,ur=e=>{if("undefined"!=typeof UUIDV7_DENY_WEAK_RNG&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var t=0;e.length>t;t++)e[t]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e};we&&!ft(we.crypto)&&crypto.getRandomValues&&(ur=e=>crypto.getRandomValues(e));class cr{nextUint32(){return this._buffer.length>this._cursor||(ur(this._buffer),this._cursor=0),this._buffer[this._cursor++]}constructor(){this._buffer=new Uint32Array(8),this._cursor=1/0}}var dr=()=>hr().toString(),hr=()=>(lr||(lr=new ar)).generate(),_r="",pr=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;var gr={_is_supported:()=>!!Ee,_error(e){Ws.error("cookieStore error: "+e)},_get:nr,_parse(e){var t;try{t=JSON.parse(gr._get(e))||{}}catch(e){}return t},_set(e,t,i,s,r){if(!Ee)return!1;try{var n="",o="",a=function(e,t){if(t){var i=function(e,t){if(void 0===t&&(t=Ee),_r)return _r;if(!t)return"";if(["localhost","127.0.0.1"].includes(e))return"";for(var i=e.split("."),s=Math.min(i.length,8),r="dmn_chk_"+dr();!_r&&s--;){var n=i.slice(s).join("."),o=r+"=1;domain=."+n+";path=/";t.cookie=o+";max-age=3",t.cookie.includes(r)&&(t.cookie=o+";max-age=0",_r=n)}return _r}(e);if(!i){var s=(e=>{var t=e.match(pr);return t?t[0]:""})(e);s!==i&&Ws.info("Warning: cookie subdomain discovery mismatch",s,i),i=s}return i?"; domain=."+i:""}return""}(Ee.location.hostname,s);if(i){var l=new Date;l.setTime(l.getTime()+864e5*i),n="; expires="+l.toUTCString()}r&&(o="; secure");var u=e+"="+encodeURIComponent(JSON.stringify(t))+n+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&Ws.warn("cookieStore warning: large cookie, len="+u.length),Ee.cookie=u,!0}catch(e){return!1}},_remove(e,t){if(null!=Ee&&Ee.cookie)try{gr._set(e,"",-1,t)}catch(e){return}}},vr=null,fr={_is_supported(){if(!bt(vr))return vr;var e=!0;if(ft(we))e=!1;else try{var t="__mplssupport__";fr._set(t,"xyz"),'"xyz"'!==fr._get(t)&&(e=!1),fr._remove(t)}catch(t){e=!1}return e||Ws.error("localStorage unsupported; falling back to cookie store"),vr=e,e},_error(e){Ws.error("localStorage error: "+e)},_get(e){try{return null==we?void 0:we.localStorage.getItem(e)}catch(e){fr._error(e)}return null},_parse(e){try{return JSON.parse(fr._get(e))||{}}catch(e){}return null},_set(e,t){try{return null==we||we.localStorage.setItem(e,JSON.stringify(t)),!0}catch(e){fr._error(e)}return!1},_remove(e){try{null==we||we.localStorage.removeItem(e)}catch(e){fr._error(e)}}},mr=[B,F,I,R,A,L,J,Q,G],yr=[a,o,P,C,se,ie,Y],br=e=>e+"_cpm",wr=["__proto__","constructor","prototype"],Sr=e=>{if(!gt(e))return{};var t={};return Object.keys(e).forEach((i=>{-1===wr.indexOf(i)&&(t[i]=e[i])})),t},xr=function(e,t){void 0===t&&(t=[]);var i={};return[...yr,...t].forEach((t=>{var s=e[t];ft(s)||bt(s)||""===s||(i[t]=s)})),i},Er=e=>{for(var t=5381,i=2166136261,s=0;e.length>s;s++){var r=e.charCodeAt(s);t=33*t^r,i=Math.imul(i^r,16777619)}return e.length.toString(36)+"."+(t>>>0).toString(36)+"."+(i>>>0).toString(36)},kr=(e,t)=>({p:t,f:Er(JSON.stringify(e))}),Pr=(e,t)=>{if(!t)return{properties:[],isValid:!1};try{var i=gr._parse(br(e)),s=(null==i?void 0:i.f)===Er(t)&&_t(i.p);return{properties:s?i.p:[],isValid:s}}catch(e){return{properties:[],isValid:!1}}},Cr=(e,t)=>t+"|"+(gr._get(br(e))||""),Ir={},Fr={_is_supported:()=>!0,_error(e){Ws.error("memoryStorage error: "+e)},_get:e=>Ir[e]||null,_parse:e=>Ir[e]||null,_set:(e,t)=>(Ir[e]=t,!0),_remove(e){delete Ir[e]}},Tr=null,Rr={_is_supported(){if(!bt(Tr))return Tr;if(Tr=!0,ft(we))Tr=!1;else try{var e="__support__";Rr._set(e,"xyz"),'"xyz"'!==Rr._get(e)&&(Tr=!1),Rr._remove(e)}catch(e){Tr=!1}return Tr},_error(e){Ws.error("sessionStorage error: ",e)},_get(e){try{return null==we?void 0:we.sessionStorage.getItem(e)}catch(e){Rr._error(e)}return null},_parse(e){try{return JSON.parse(Rr._get(e))||null}catch(e){}return null},_set(e,t){try{return null==we||we.sessionStorage.setItem(e,JSON.stringify(t)),!0}catch(e){Rr._error(e)}return!1},_remove(e){try{null==we||we.sessionStorage.removeItem(e)}catch(e){Rr._error(e)}}};class Ar{constructor(e){this._instance=e}get _config(){return this._instance.config}get consent(){return this._getDnt()?0:this._storedConsent}isOptedOut(){return this._config.cookieless_mode===de||this.isRejected()||-1===this.consent&&this._config.cookieless_mode===ce}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return 0===this.consent}isRejected(){return 0===this.consent||-1===this.consent&&this._config.opt_out_capturing_by_default}optInOut(e){this._storage._set(this._storageKey,e?1:0,this._config.cookie_expiration,this._config.cross_subdomain_cookie,this._config.secure_cookie)}reset(){this._storage._remove(this._storageKey,this._config.cross_subdomain_cookie)}get _storageKey(){var e=this._instance.config,t=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+t:"__ph_opt_in_out_"+t)}get _storedConsent(){var e=this._storage._get(this._storageKey);return Mt(e)?1:ot($t,e)?0:-1}get _storage(){var e=this._config.opt_out_capturing_persistence_type,t="localStorage"===e?fr:gr;if(!this._persistentStore||this._persistentStore!==t){this._persistentStore=t;var i="localStorage"===e?gr:fr;i._get(this._storageKey)&&(this._persistentStore._get(this._storageKey)||this.optInOut(Mt(i._get(this._storageKey))),i._remove(this._storageKey,this._config.cross_subdomain_cookie))}return this._persistentStore}_getDnt(){return!!this._config.respect_dnt&&[null==xe?void 0:xe.doNotTrack,null==xe?void 0:xe.msDoNotTrack,Le.doNotTrack].some((e=>Mt(e)))}}function Lr(e,t){var i,s=null==e||null==(i=e.config)?void 0:i.get_current_url;if(!pt(s))return t;try{var r=s(t);return mt(r)&&r?r:t}catch(e){return Ws.error("Error in get_current_url, falling back to window.location.href",e),t}}var Mr="__POSTHOG_TOOLBAR__",$r=1,Or=3,Dr=11;function Br(e){return e instanceof Element&&(e.id===Mr||!(null==e.closest||!e.closest(".toolbar-global-fade-container")))}function qr(e){return!!e&&e.nodeType===$r}function Hr(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function Nr(e){return!!e&&e.nodeType===Or}function zr(e){return!!e&&e.nodeType===Dr&&qr(e.host)}var jr=1e3;function Ur(e){return e?at(e).split(/\s+/):[]}function Vr(e,t){var i=function(e){var t,i=null==we||null==(t=we.location)?void 0:t.href;return ft(i)?void 0:Lr(e,i)}(t);return!!(i&&e&&e.some((e=>i.match(e))))}function Wr(e){var t="";switch(typeof e.className){case"string":t=e.className;break;case"object":t=(e.className&&"baseVal"in e.className?e.className.baseVal:null)||e.getAttribute("class")||"";break;default:t=""}return Ur(t)}function Gr(e){return wt(e)?null:at(e).split(/(\s+)/).filter((e=>mn(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Kr(e){var t="";return un(e)&&!cn(e)&&e.childNodes&&e.childNodes.length&&Qs(e.childNodes,(function(e){var i;Nr(e)&&e.textContent&&(t+=null!==(i=Gr(e.textContent))&&void 0!==i?i:"")})),at(t)}function Qr(e){var t;return ft(e.target)?e.srcElement||null:null!=(t=e.target)&&t.shadowRoot?e.composedPath()[0]||null:e.target||null}var Jr=["a","button","form","input","select","textarea","label"];function Yr(e,t){if(ft(t))return!0;var i,s=function(e){if(t.some((t=>function(e,t){var i=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector;try{return!!i&&i.call(e,t)}catch(e){return!1}}(e,t))))return{v:!0}};for(var r of e)if(i=s(r))return i.v;return!1}function Zr(e){var t=e.parentNode;return!(!t||!qr(t))&&t}var Xr=[".ph-no-autocapture","[data-ph-no-autocapture]"],en=["next","previous","prev",">","<"],tn=[...en,"+","-","−","–"],sn=(e,t)=>/[a-z0-9]/i.test(t)?e.includes(t):e===t,rn=[".ph-no-rageclick",".ph-no-capture"],nn=["","text","search","email","password","url","tel","number"];function on(e,t){if(!we||an(e))return!1;var i,s,r,n,o;if(Et(t)?(i=!!t&&rn,s=void 0,r=!1):(i=null!==(n=null==t?void 0:t.css_selector_ignorelist)&&void 0!==n?n:rn,s=null==t?void 0:t.content_ignorelist,r=null!==(o=null==t?void 0:t.ignore_text_selection)&&void 0!==o&&o),!1===i)return!1;if(r&&function(e){return!(!e||!qr(e))&&(!!Hr(e,"textarea")||(Hr(e,"input")?ot(nn,(e.getAttribute("type")||"").toLowerCase()):function(e){if(e.isContentEditable)return!0;var t=null==e.getAttribute?void 0:e.getAttribute("contenteditable");return"true"===t||""===t}(e)))}(e))return!1;var a=ln(e,!1).targetElementList;return!function(e,t){if(!1===e||ft(e))return!1;var i;if(!0===e)i=en;else{if(!_t(e))return!1;if(e.length>10)return Ws.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;i=e.map((e=>e.toLowerCase()))}return t.some((e=>{var t=e.safeText,s=e.ariaLabel;return i.some((e=>sn(t,e)||sn(s,e)))}))}(s,a.map((e=>{var t;return{safeText:Kr(e).toLowerCase(),ariaLabel:(null==(t=e.getAttribute("aria-label"))?void 0:t.toLowerCase().trim())||""}})))&&!Yr(a,i)}var an=e=>!e||Hr(e,"html")||!qr(e),ln=(e,t)=>{if(!we||an(e))return{parentIsUsefulElement:!1,targetElementList:[]};for(var i=!1,s=[e],r=e;r.parentNode&&!Hr(r,"body");)if(zr(r.parentNode))s.push(r.parentNode.host),r=r.parentNode.host;else{var n=Zr(r);if(!n)break;if(t||Jr.indexOf(n.tagName.toLowerCase())>-1)i=!0;else try{var o=we.getComputedStyle(n);o&&"pointer"===o.getPropertyValue("cursor")&&(i=!0)}catch(e){}s.push(n),r=n}return{parentIsUsefulElement:i,targetElementList:s}};function un(e){for(var t=new Set,i=0,s=e;s.parentNode&&!Hr(s,"body");s=s.parentNode){if(i++>=jr||t.has(s))return!1;t.add(s);var r=Wr(s);if(ot(r,"ph-sensitive")||ot(r,"ph-no-capture"))return!1}if(ot(Wr(e),"ph-include"))return!0;var n=e.type||"";if(mt(n))switch(n.toLowerCase()){case"hidden":case"password":return!1}var o=e.name||e.id||"";return!mt(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function cn(e){return!!(Hr(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||Hr(e,"select")||Hr(e,"textarea")||"true"===e.getAttribute("contenteditable"))}var dn=new RegExp("^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$"),hn=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,_n=[16,15,14,13],pn=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),gn=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),vn=/[0-9A-Za-z_]/;function fn(e){for(var t=0,i=!1,s=e.length-1;s>=0;s--){var r=e.charCodeAt(s)-48;i&&(r*=2)>9&&(r-=9),t+=r,i=!i}return t%10==0}function mn(e,t){if(void 0===t&&(t=!0),wt(e))return!1;if(mt(e)){e=at(e);var i=t?dn.test((e||"").replace(/[- ]/g,"")):function(e){var t;for(hn.lastIndex=0;t=hn.exec(e);){var i=t[2];if(i)for(var s=i.replace(/[- ]/g,""),r=0;s.length>r;r++)for(var n of _n){var o=r+n;if(s.length>=o){var a=s.slice(r,o);if(dn.test(a)&&fn(a))return!0}}}return!1}(e);if(i)return!1;var s=t?pn.test(e):function(e){var t;for(gn.lastIndex=0;t=gn.exec(e);){var i=t[1],s=t[3];if(!(i&&s&&vn.test(i)&&vn.test(s)))return!0}return!1}(e);if(s)return!1}return!0}function yn(e){var t=Kr(e);return mn(t=(t+" "+bn(e)).trim())?t:""}function bn(e){var t="";return e&&e.childNodes&&e.childNodes.length&&Qs(e.childNodes,(function(e){var i;if(e&&"span"===(null==(i=e.tagName)?void 0:i.toLowerCase()))try{var s=Kr(e);t=(t+" "+s).trim(),e.childNodes&&e.childNodes.length&&(t=(t+" "+bn(e)).trim())}catch(e){Ws.error("[AutoCapture]",e)}})),t}function wn(e){return e.replace(/"|\\"/g,'\\"')}function Sn(e){var t=e.attr__class;if(t)return _t(t)?t:Ur(t)}var xn=Gs("[Dead Clicks]"),En=()=>!0,kn=e=>{var t,i=!(null==(t=e.instance.persistence)||!t.get_property(f)),s=e.instance.config.capture_dead_clicks;return Et(s)?s:!!gt(s)||i};class Pn{get lazyLoadedDeadClicksAutocapture(){return this._lazyLoadedDeadClicksAutocapture}constructor(e,t,i){this.instance=e,this.isEnabled=t,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var t=e.config;"captureDeadClicks"in t&&(this.instance.persistence&&this.instance.persistence.register({[f]:t.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this._loadScript((()=>{this._start()})):this.stop()}_loadScript(e){var t,i;null!=(t=Le.__PosthogExtensions__)&&t.initDeadClicksAutocapture?e():null==(i=Le.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(t=>{t?xn.error("failed to load script",t):e()}))}_start(){var e;if(Ee){if(!this._lazyLoadedDeadClicksAutocapture&&null!=(e=Le.__PosthogExtensions__)&&e.initDeadClicksAutocapture){var t=gt(this.instance.config.capture_dead_clicks)?i({},this.instance.config.capture_dead_clicks):{};t.__onCapture=this.onCapture,this.onCapture&&(t.capture_dead_swipes=!1),this._lazyLoadedDeadClicksAutocapture=Le.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,t),this._lazyLoadedDeadClicksAutocapture.start(Ee),xn.info("starting...")}}else xn.error("`document` not found. Cannot start.")}stop(){this._lazyLoadedDeadClicksAutocapture&&(this._lazyLoadedDeadClicksAutocapture.stop(),this._lazyLoadedDeadClicksAutocapture=void 0,xn.info("stopping..."))}}var Cn=Gs("[SegmentIntegration]");var In="posthog-js";function Fn(e,t){var s=void 0===t?{}:t,r=s.organization,n=s.projectId,o=s.prefix,a=s.severityAllowList,l=void 0===a?["error"]:a,u=s.sendExceptionsToPostHog,c=void 0===u||u;return t=>{var s,a,u,d,h;if("*"!==l&&!l.includes(t.level)||!e.__loaded)return t;t.tags||(t.tags={});var _=e.requestRouter.endpointFor("ui","/project/"+e.config.token+"/person/"+e.get_distinct_id());t.tags["PostHog Person URL"]=_,e.sessionRecordingStarted()&&(t.tags["PostHog Recording URL"]=e.get_session_replay_url({withTimestamp:!0}));var p,g=(null==(s=t.exception)?void 0:s.values)||[],v=g.map((e=>i({},e,{stacktrace:e.stacktrace?i({},e.stacktrace,{type:"raw",frames:(e.stacktrace.frames||[]).map((e=>i({},e,{platform:"web:javascript"})))}):void 0}))),f={$exception_message:(null==(a=g[0])?void 0:a.value)||t.message,$exception_type:null==(u=g[0])?void 0:u.type,$exception_level:t.level,$exception_list:v,$sentry_event_id:t.event_id,$sentry_exception:t.exception,$sentry_exception_message:(null==(d=g[0])?void 0:d.value)||t.message,$sentry_exception_type:null==(h=g[0])?void 0:h.type,$sentry_tags:t.tags};return r&&n&&(f.$sentry_url=(o||"https://sentry.io/organizations/")+r+"/issues/?project="+n+"&query="+t.event_id),c&&(null==(p=e.exceptions)||p.sendExceptionEvent(f)),t}}class Tn{constructor(e,t,i,s,r,n){this.name=In,this.setupOnce=function(o){o(Fn(e,{organization:t,projectId:i,prefix:s,severityAllowList:r,sendExceptionsToPostHog:null==n||n}))}}}class Rn{constructor(e){this._onSessionIdChange=(e,t,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength||i.crossTabAdoption)&&(Ws.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:e,changeReason:i}),this._currentPageview=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this._setupSessionRotationHandler()}_setupSessionRotationHandler(){var e;this._unsubscribeSessionId=null==(e=this._instance.sessionManager)?void 0:e.onSessionId(this._onSessionIdChange)}destroy(){var e;null==(e=this._unsubscribeSessionId)||e.call(this),this._unsubscribeSessionId=void 0}doPageView(e,t){var i,s=this._previousPageViewProperties(e,t);return this._currentPageview={pathname:null!==(i=null==we?void 0:we.location.pathname)&&void 0!==i?i:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),s}doPageLeave(e){var t;return this._previousPageViewProperties(e,null==(t=this._currentPageview)?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:null==(e=this._currentPageview)?void 0:e.pageViewId}}_previousPageViewProperties(e,t){var i=this._currentPageview;if(!i)return{$pageview_id:t};var s={$pageview_id:t,$prev_pageview_id:i.pageViewId},r=this._instance.scrollManager.getContext();if(r&&!this._instance.config.disable_scroll_properties){var n=r.maxScrollHeight,o=r.lastScrollY,a=r.maxScrollY,l=r.maxContentHeight,u=r.lastContentY,c=r.maxContentY;if(!(ft(n)||ft(o)||ft(a)||ft(l)||ft(u)||ft(c))){n=Math.ceil(n),o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c);var d=n>1?Ot(o/n,0,1,Ws):1,h=n>1?Ot(a/n,0,1,Ws):1,_=l>1?Ot(u/l,0,1,Ws):1,p=l>1?Ot(c/l,0,1,Ws):1;s=Js(s,{$prev_pageview_last_scroll:o,$prev_pageview_last_scroll_percentage:d,$prev_pageview_max_scroll:a,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:u,$prev_pageview_last_content_percentage:_,$prev_pageview_max_content:c,$prev_pageview_max_content_percentage:p})}}return i.pathname&&(s.$prev_pageview_pathname=i.pathname),i.timestamp&&(s.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),s}}var An=["flags","surveys"],Ln={[n]:{exposure:"hidden"},[u]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[c]:{exposure:"hidden"},[d]:{exposure:"event"},[h]:{exposure:"hidden"},[_]:{exposure:"event"},[p]:{exposure:"hidden"},[g]:{exposure:"event"},[v]:{exposure:"event"},[f]:{exposure:"event"},[m]:{exposure:"hidden"},[y]:{exposure:"event"},[b]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[P]:{exposure:"hidden"},[C]:{exposure:"event"},[w]:{exposure:"event",shouldSkipFromEventProperties:e=>bt(e)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[I]:{exposure:"hidden",storageGroup:"flags"},[F]:{exposure:"hidden",storageGroup:"flags"},[T]:{exposure:"hidden"},[R]:{exposure:"hidden",storageGroup:"flags"},[A]:{exposure:"hidden",storageGroup:"flags"},[L]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[M]:{exposure:"hidden",storageGroup:"flags"},[O]:{exposure:"hidden"},[D]:{exposure:"hidden"},[B]:{exposure:"hidden"},[q]:{exposure:"hidden"},[N]:{exposure:"hidden",storageGroup:"surveys"},[z]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[j]:{exposure:"event"},[U]:{exposure:"hidden"},[V]:{exposure:"hidden"},[W]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[G]:{exposure:"hidden"},[K]:{exposure:"hidden"},[H]:{exposure:"event"},[Q]:{exposure:"hidden"},[J]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Y]:{exposure:"hidden"},[Z]:{exposure:"hidden"},[X]:{exposure:"hidden"},[ee]:{exposure:"hidden"},[te]:{exposure:"hidden"},[ie]:{exposure:"hidden"},[se]:{exposure:"hidden"},[S]:{exposure:"event"},[x]:{exposure:"event"},[E]:{exposure:"event"},[k]:{exposure:"event"},[oe]:{exposure:"event"},[ae]:{exposure:"event"},[le]:{exposure:"event"},$sdk_debug_replay_event_trigger_status:{exposure:"event"},$sdk_debug_replay_linked_flag_trigger_status:{exposure:"event"},$sdk_debug_replay_matched_recording_trigger_groups:{exposure:"event"},$sdk_debug_replay_pending_trigger_conditions:{exposure:"event"},$sdk_debug_replay_remote_trigger_matching_config:{exposure:"event"},$sdk_debug_replay_trigger_groups_count:{exposure:"event"},$sdk_debug_replay_url_trigger_status:{exposure:"event"},$session_recording_start_reason:{exposure:"event"}},Mn=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],$n=e=>{var t=Ln[e];if(t)return t;for(var i of Mn){var s=i[1];if(0===e.indexOf(i[0]))return s}},On=(e,t)=>{try{return JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString():t),t)}catch(t){return ut(e)}},Dn=e=>{var t=null==Ee?void 0:Ee.createElement("a");return ft(t)?null:(t.href=e,t)},Bn=function(e,t){for(var i,s=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;s.length>r;r++){var n=s[r].split("=");if(n[0]===t){i=n;break}}if(!_t(i)||2>i.length)return"";var o=i[1];try{o=decodeURIComponent(o)}catch(e){Ws.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},qn=function(e,t,i){if(!e||!t||!t.length)return e;for(var s=e.split("#"),r=s[1],n=(s[0]||"").split("?"),o=n[1],a=n[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");_t(d)&&(t.includes(d[0])?u.push(d[0]+"="+i):u.push(l[c]))}var h=a;return null!=o&&(h+="?"+u.join("&")),null!=r&&(h+="#"+r),h},Hn=function(e,t){var i=e.match(new RegExp(t+"=([^&]*)"));return i?i[1]:null},Nn=(e,t)=>e>=t&&Re(),zn=(e,t,i,s)=>{if(0===e){if(Re()){var r=t+1;return r===i&&s(),r}return t}return 0},jn="https?://(.*)",Un=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Vn=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...Un],Wn="<masked>",Gn=["li_fat_id"];function Kn(e,t,i){if(!Ee)return{};var s,r=t?[...Un,...i||[]]:[],n=Qn(qn(Ee.URL,r,Wn),e),o=(s={},Qs(Gn,(function(e){var t=nr(e);s[e]=t||null})),s);return Js(o,n)}function Qn(e,t){var i=Vn.concat(t||[]),s={};return Qs(i,(function(t){var i=Bn(e,t);s[t]=i||null})),s}function Jn(e){var t=function(e){return e?0===e.search(jn+"google.([^/?]*)")?"google":0===e.search(jn+"bing.com")?"bing":0===e.search(jn+"yahoo.com")?"yahoo":0===e.search(jn+"duckduckgo.com")?"duckduckgo":null:null}(e),i="yahoo"!=t?"q":"p",s={};if(!bt(t)){s.$search_engine=t;var r=Ee?Bn(Ee.referrer,i):"";r.length&&(s.ph_keyword=r)}return s}function Yn(){return navigator.language||navigator.userLanguage}var Zn="$direct";function Xn(){return(null==Ee?void 0:Ee.referrer)||Zn}function eo(e,t,i){void 0===i&&(i=!1);var s=e?[...Un,...t||[]]:[],r=i?Ui(null==ke?void 0:ke.href):null==ke?void 0:ke.href,n=null==r?void 0:r.substring(0,1e3);return{r:Xn().substring(0,1e3),u:n?qn(n,s,Wn):void 0}}function to(e,t){var i;void 0===t&&(t=!1);var s=e.r,r=e.u,n=t?Ui(r):r,o={$referrer:s,$referring_domain:null==s?void 0:s==Zn?Zn:null==(i=Dn(s))?void 0:i.host};if(n){o.$current_url=n;var a=Dn(n);o.$host=null==a?void 0:a.host,o.$pathname=null==a?void 0:a.pathname;var l=Qn(n);Js(o,l)}if(s){var u=Jn(s);Js(o,u)}return o}function io(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(e){return}}function so(){try{return(new Date).getTimezoneOffset()}catch(e){return}}var ro={flags:J,surveys:z},no=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],oo=e=>e+"_cookie_identity_change_pending",ao="main",lo=(e,t)=>{Qs(e,((i,s)=>{var r=$n(s);r&&"event"!==r.exposure||{}.hasOwnProperty.call(t,s)||delete e[s]}))};class uo{constructor(e,t,s){if(void 0===s&&(s=!0),this._slotState={},this._splitStorageEligible=!1,this._splitStorage=!1,this._cookieIdentityChangePending=!1,this._cookieSyncSuppressed=!1,this._config=e,this._ownsSplitStorage=s,this.props={},this._campaign_params_url=void 0,this._name=(e=>{var t="";return e.token&&(t=e.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),e.persistence_name?"ph_"+e.persistence_name:"ph_"+t+"_posthog"})(e),this._storage=this._buildStorage(e),this._splitStorage=this._resolveSplitStorage(e),this.load(),e.debug&&Ws.info("Persistence loaded",e.persistence,i({},this.props)),this.update_config(e,e,t),this.save(),we){var r=()=>this.flush();sr(we,"beforeunload",r,{capture:!1}),sr(we,"pagehide",r,{capture:!1})}}_saveDebounceMs(){var e,t=null==(e=this._config)?void 0:e.persistence_save_debounce_ms;return St(t)&&t>0?t:0}_rememberCurrentCookieProperties(e){if(this._config.cookieWinsOnConflict&&"localstorage+cookie"===this._config.persistence.toLowerCase())if(e)try{var t=xr(e,this._config.cookie_persisted_properties||[]),i=kr(t,this._config.cookie_persisted_properties||[]),s=JSON.stringify(t)+"|"+JSON.stringify(i),r=gr._get(this._name)||void 0;r&&Cr(this._name,r)===s&&(this._lastSeenCookiePropertiesFingerprint=s,this._lastSeenMainCookieValue=r)}catch(e){}else try{var n=gr._get(this._name)||void 0;this._lastSeenCookiePropertiesFingerprint=n?Cr(this._name,n):void 0,this._lastSeenMainCookieValue=n}catch(e){}}syncCookieProperties(){return this._syncCookieProperties(this._config)}_syncCookieProperties(e,t){if(void 0===t&&(t=!1),this._disabled&&!t||this._cookieSyncSuppressed||!e.cookieWinsOnConflict||"localstorage+cookie"!==e.persistence.toLowerCase())return!1;var i;try{i=gr._get(this._name)||void 0}catch(e){}if(!i||i===this._lastSeenMainCookieValue)return!1;var s,r=Cr(this._name,i);try{s=Sr(JSON.parse(i))}catch(e){return!1}if((gr._get(this._name)||void 0)!==i)return!1;this._lastSeenCookiePropertiesFingerprint=r,this._lastSeenMainCookieValue=i;var n=Pr(this._name,i),a=[...yr,...n.properties],l={};if(Object.keys(s).forEach((e=>{var t=s[e];(ft(t)||bt(t)||""===t||e===Y&&t!==he&&t!==_e)&&(l[e]=!0,delete s[e])})),vt(s))return!1;var c=o in s||s[Y]===he||s[Y]===_e,d=this.props[o],h=this.props[Y],_=Js({},this.props);[...yr,...e.cookie_persisted_properties||[]].forEach((e=>{if(-1!==a.indexOf(e)&&!(e in s)&&!l[e]&&(c||e!==o&&e!==Y)){var t=_[e];!n.isValid&&-1!==yr.indexOf(e)&&(!1===t||0===t)||delete _[e]}})),this.props=Js(_,s),!c||Y in s||Y in this.props||this._setProp(Y,he);var p=this.props[o],g=this.props[Y];return!c||p===d&&g===h||(this._cookieIdentityChangePending=!0,Rr._set(oo(this._name),!0),this._deleteProp(B),this._deleteProp(F),this._deleteProp(I),this._deleteProp(R),this._deleteProp(A),this._deleteProp(L),this._deleteProp(J),this._deleteProp(Q),this._deleteProp(G),g===he&&(h===_e||s[Y]===he||!ft(d)&&p!==d)&&(lo(this.props,s),this._deleteProp(q)),g===_e?this.props.$user_id=p:delete this.props.$user_id,this._deleteProp(u)),!0}consumeCookieIdentityChange(){var e=oo(this._name),t=this._cookieIdentityChangePending||!!Rr._get(e);return this._cookieIdentityChangePending=!1,t&&Rr._remove(e),t}_beginCookieSyncSuppression(e){return void 0===e&&(e=!1),!(this._cookieSyncSuppressed||this._disabled&&!e||!this._config.cookieWinsOnConflict||"localstorage+cookie"!==this._config.persistence.toLowerCase()||(this._cookieSyncSuppressed=!0,0))}_publishSuppressedCookieSnapshot(){this._cookieSyncSuppressed&&(ft(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0),delete this._slotState[ao],this._writeNow(!0))}_endCookieSyncSuppression(e){if(void 0===e&&(e=!0),this._cookieSyncSuppressed)try{e?this._publishSuppressedCookieSnapshot():ft(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0)}finally{this._cookieSyncSuppressed=!1}}isDisabled(){return!!this._disabled}_buildStorage(e){-1===no.indexOf(e.persistence.toLowerCase())&&(Ws.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var t,s=function(e,t){void 0===e&&(e=[]),void 0===t&&(t=!1);var s=[...yr,...e];return i({},fr,{_parse(e){try{var i,r={};try{i=gr._get(e)||void 0,r=i?Sr(JSON.parse(i)):{}}catch(e){}var n,a=JSON.parse(fr._get(e)||"{}");if(t){var l=Pr(e,i),u=[...yr,...l.properties],c={};Object.keys(r).forEach((e=>{var t=r[e];bt(t)||""===t||e===Y&&t!==he&&t!==_e||(c[e]=t)}));var d=o in c||c[Y]===he||c[Y]===_e;if(Object.keys(c).length>0){var h,_=a[o],p=null!==(h=a[Y])&&void 0!==h?h:he;s.forEach((e=>{if(-1!==u.indexOf(e)&&!(e in r)&&(d||e!==o&&e!==Y)){var t=a[e];!l.isValid&&-1!==yr.indexOf(e)&&(!1===t||0===t)||delete a[e]}})),!d||Y in r||Y in a||(a[Y]=he),!d||(o in c?c[o]:a[o])===_&&(Y in c?c[Y]:a[Y])===p||(mr.forEach((e=>delete a[e])),c[Y]===_e&&o in c?a.$user_id=c[o]:delete a.$user_id,c[Y]!==_e&&(delete a[H],delete a[q]),delete a.__alias)}n=Js(a,c)}else n=Js(r,a);return fr._set(e,n),n}catch(e){}return null},_set(i,s,r,n,o,a){var l=fr._set(i,s,void 0,void 0,a);try{var u=xr(s,e);if(Object.keys(u).length){if(t){var c=br(i),d=kr(u,e);if(gr._set(c,d,r,n,o,a),gr._get(c)!==JSON.stringify(d)){gr._remove(c,n);var h=xr(s);return gr._set(i,h,r,n,o,a),l}}gr._set(i,u,r,n,o,a)}}catch(e){fr._error(e)}return l},_remove(e,t){try{null==we||we.localStorage.removeItem(e),gr._remove(e,t),gr._remove(br(e),t)}catch(e){fr._error(e)}}})}(e.cookie_persisted_properties||[],e.cookieWinsOnConflict),r=!1,n=e.persistence.toLowerCase();return"localstorage"===n&&fr._is_supported()?(t=fr,r=!0):"localstorage+cookie"===n&&s._is_supported()?(t=s,r=!0):"sessionstorage"===n&&Rr._is_supported()?t=Rr:"memory"===n?t=Fr:"cookie"===n?t=gr:s._is_supported()?(t=s,r=!0):t=gr,this._splitStorageEligible=r,t}_groupEntryName(e){return this._name+"__"+e}_resolveSplitStorage(e){return this._splitStorageEligible&&!!e.split_storage}properties(){var e={};return Qs(this.props,((t,i)=>{var s=$n(i);if(!s||"event"===s.exposure){if(null!=s&&null!=s.shouldSkipFromEventProperties&&s.shouldSkipFromEventProperties(t))return;e[i]=t}})),e}load(e){if(void 0===e&&(e=!1),!this._disabled||e){var t=this._config.cookieWinsOnConflict&&"localstorage+cookie"===this._config.persistence.toLowerCase(),i=t?fr._parse(this._name):null,s={};if(t)try{Qs(s=Sr(gr._parse(this._name)),((e,t)=>{(ft(e)||bt(e)||""===e)&&delete s[t]}))}catch(e){}var r=this._storage._parse(this._name);if(r&&(this.props=Js({},r)),this._splitStorage&&this._loadGroupEntries(),t&&r){var n,a,l=null==i?void 0:i[o],u=null!==(n=null==i?void 0:i[Y])&&void 0!==n?n:he,c=r[o],d=null!==(a=r[Y])&&void 0!==a?a:he;if(c!==l||d!==u){this._cookieIdentityChangePending=!0,Rr._set(oo(this._name),!0);var h=Js({},this.props);mr.forEach((e=>delete h[e])),d===he&&(u===_e||s[Y]===he||!ft(l)&&c!==l)&&(lo(h,s),delete h[q]),this.props=h;var _=new Set;mr.forEach((e=>{var t,i=null==(t=$n(e))?void 0:t.storageGroup;i&&_.add(i)})),_.forEach((e=>{var t={};Qs(this.props,((i,s)=>{var r;(null==(r=$n(s))?void 0:r.storageGroup)===e&&(t[s]=i)})),vt(t)?(fr._remove(this._groupEntryName(e)),this._slotState[e]={}):fr._set(this._groupEntryName(e),t)&&(this._slotState[e]={persisted:!0,fingerprint:this._entryFingerprint(t,e)})}))}}Rr._get(oo(this._name))&&(this._cookieIdentityChangePending=!0)}}_loadGroupEntries(){for(var e of An){var t=fr._parse(this._groupEntryName(e));if(t&&!vt(t)){var i=this._slotWriteState(e);i.persisted=!0,this._mainCarriesGroupKey(e)||(i.fingerprint=this._entryFingerprint(t,e)),this._groupEntryIsStale(e,t)||Js(this.props,t)}}}_mainCarriesGroupKey(e){return Object.keys(this.props).some((t=>{var i;return(null==(i=$n(t))?void 0:i.storageGroup)===e}))}_groupEntryIsStale(e,t){var i=ro[e];if(!i)return!1;var s=t[i],r=this.props[i];return St(s)&&St(r)&&r>s}refreshKey(e){var t;if(!this._disabled){var i=this._splitStorage?null==(t=$n(e))?void 0:t.storageGroup:void 0,s=i?fr._parse(this._groupEntryName(i)):this._storage._parse(this._name);if(s&&e in s)this._setProp(e,s[e]);else{if(i){var r=this._storage._parse(this._name);if(r&&e in r)return void this._setProp(e,r[e])}this._deleteProp(e)}}}save(){if(!this._disabled){var e=this._saveDebounceMs();e>0?ft(this._pendingSaveTimer)&&(this._pendingSaveTimer=setTimeout((()=>{this._pendingSaveTimer=void 0,this._writeNow()}),e)):this._writeNow()}}flush(){ft(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0,this._writeNow())}_writeNow(e){void 0===e&&(e=!1),this._disabled||this._cookieSyncSuppressed&&!e||(e||this.syncCookieProperties(),this._splitStorage?this._writeNowSplit():this._writeEntry(this._storage,this._name,this.props,ao)&&this._rememberCurrentCookieProperties(this.props))}_writeNowSplit(){var e=this._partitionProps(),t=e.main,i=e.groups;for(var s of(this._writeEntry(this._storage,this._name,t,ao)&&this._rememberCurrentCookieProperties(t),An)){var r,n=i[s];(!vt(n)||null!=(r=this._slotState[s])&&r.persisted)&&this._writeEntry(fr,this._groupEntryName(s),n,s)}}_partitionProps(){var e={},t={flags:{},surveys:{}};return Qs(this.props,((i,s)=>{var r,n=null==(r=$n(s))?void 0:r.storageGroup;n?t[n][s]=i:e[s]=i})),{main:e,groups:t}}_entryFingerprint(e,t){if(t===ao)return JSON.stringify(e)+"|"+this._expire_days+"|"+this._cross_subdomain+"|"+this._secure;var i={};return Qs(e,((e,t)=>{var s;i[t]=null!=(s=$n(t))&&s.volatile?"__volatile__":e})),JSON.stringify(i)}_writeEntry(e,t,i,s){var r,n=this._slotWriteState(s);if(s!==ao&&!n.dirty&&!ft(n.fingerprint))return!1;try{if((r=this._entryFingerprint(i,s))===n.fingerprint)return n.dirty=!1,!1}catch(e){r=void 0}return e._set(t,i,this._expire_days,this._cross_subdomain,this._secure,this._config.debug)?(n.dirty=!1,s!==ao&&(n.persisted=!0),ft(r)||(n.fingerprint=r),!0):(this._config.debug&&Ws.warn('failed to persist storage entry "'+t+'"; will retry on next save'),!1)}remove(e){var t=(void 0===e?{}:e).keepGroupEntries,i=void 0!==t&&t;if(ft(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0),this._storage._remove(this._name,!1),this._storage._remove(this._name,!0),!i&&this._ownsSplitStorage)for(var s of An)fr._remove(this._groupEntryName(s));i?delete this._slotState[ao]:this._slotState={},this._lastSeenCookiePropertiesFingerprint=void 0,this._lastSeenMainCookieValue=void 0}clear(){this.remove(),this.props={}}register_once(e,t,i){if(gt(e)){this.syncCookieProperties(),ft(t)&&(t="None"),this._expire_days=ft(i)?this._default_expiry:i;var s=!1;if(Qs(e,((e,i)=>{this.props.hasOwnProperty(i)&&this.props[i]!==t||(this._setProp(i,e),s=!0)})),s)return this.save(),!0}return!1}register(e,t){if(gt(e)){this.syncCookieProperties(),this._expire_days=ft(t)?this._default_expiry:t;var i=!1;if(Qs(e,((t,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==t||gt(t)||_t(t))&&(this._setProp(s,t),i=!0)})),i)return this.save(),!0}return!1}unregister(e){this.syncCookieProperties();var t="string"==typeof e?[e]:e,i=!1;for(var s of t)s in this.props&&(this._deleteProp(s),i=!0);i&&this.save()}update_campaign_params(){var e=null==Ee?void 0:Ee.URL;if(e!==this._campaign_params_url){var t=Kn(this._config.custom_campaign_params,this._config.mask_personal_data_properties,this._config.custom_personal_data_properties);vt(er(t))||this.register(t),this._campaign_params_url=e}}update_search_keyword(){var e;this.register((e=null==Ee?void 0:Ee.referrer)?Jn(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Xn(),$referring_domain:null!=Ee&&Ee.referrer&&(null==(e=Dn(Ee.referrer))?void 0:e.host)||Zn},void 0)}set_initial_person_info(){this.props[ee]||this.props[te]||this.register_once({[ie]:eo(this._config.mask_personal_data_properties,this._config.custom_personal_data_properties,this._config.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};Qs([te,ee],(t=>{var i=this.props[t];i&&Qs(i,(function(t,i){e["$initial_"+lt(i)]=t}))}));var t=this.props[ie];if(t){var i=function(e,t){void 0===t&&(t=!1);var i=to(e,t),s={};return Qs(i,(function(e,t){s["$initial_"+lt(t)]=e})),s}(t,this._config.disable_capture_url_hashes);Js(e,i)}return e}safe_merge(e){return Qs(this.props,(function(t,i){i in e||(e[i]=t)})),e}update_config(e,t,s){var r=e.persistence!==t.persistence,n=!((e,t)=>{if(e.length!==t.length)return!1;var i=[...e].sort(),s=[...t].sort();return i.every(((e,t)=>e===s[t]))})(e.cookie_persisted_properties||[],t.cookie_persisted_properties||[]),o=r||n,a=e.cookieWinsOnConflict!==t.cookieWinsOnConflict,l=e.disable_persistence||!!s,u=!!this._disabled&&!l;l||this._syncCookieProperties(t,u),this._config=e,!l&&(r||n||a)&&(this._lastSeenCookiePropertiesFingerprint=void 0,this._lastSeenMainCookieValue=void 0,this._syncCookieProperties(i({},e,{cookie_persisted_properties:t.cookie_persisted_properties}),u));var c=o||a?this._buildStorage(e):this._storage,d=this._resolveSplitStorage(e),h=o||d!==this._splitStorage,_=!l&&(h||e.cross_subdomain_cookie!==this._cross_subdomain||e.secure_cookie!==this._secure)&&this._beginCookieSyncSuppression(u);try{if(this._default_expiry=this._expire_days=e.cookie_expiration,this.set_disabled(l),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),h){var p=this.props;this.clear(),this._storage=c,this._splitStorage=d,this.props=p,this.save()}else a&&(this._storage=c,l||(delete this._slotState[ao],this._writeNow()))}finally{_&&this._endCookieSyncSuppression()}}set_disabled(e){this._disabled=e,this._disabled?this.remove():this.save()}set_cross_subdomain(e){e!==this._cross_subdomain&&(this._cross_subdomain=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this._secure&&(this._secure=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,t){var i=this.props[c]||{};i[e]=t,this._setProp(c,i),this.save()}remove_event_timer(e){var t=this.props[c]||{},i=t[e];return ft(i)||(delete t[e],this._setProp(c,t),this.save()),i}get_property(e){return this.props[e]}set_property(e,t){this._setProp(e,t),this.save()}_setProp(e,t){var i;this.props[e]=t,null!=(i=$n(e))&&i.volatile||this._markGroupDirty(e)}_deleteProp(e){delete this.props[e],this._markGroupDirty(e)}_markGroupDirty(e){var t,i=null==(t=$n(e))?void 0:t.storageGroup;i&&(this._slotWriteState(i).dirty=!0)}_slotWriteState(e){return this._slotState[e]||(this._slotState[e]={})}}function co(e){var t=!0;return{dispose(){if(t){t=!1;var i=e();i&&pt(i.then)&&i.then(void 0,(()=>{}))}}}}var ho="gzip-js",_o="base64",po="events",go="cancelEvents",vo="survey shown",fo="survey dismissed",mo="survey sent",yo="popover",bo=Gs("[RateLimiter]");class wo{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=e=>{var t=e.text;if(t&&t.length)try{(JSON.parse(t).quota_limited||[]).forEach((e=>{bo.info((e||"events")+" is quota limited."),this.serverLimits[e]=(new Date).getTime()+6e4}))}catch(e){return void bo.warn('could not rate limit - continuing. Error: "'+(null==e?void 0:e.message)+'"',{text:t})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return(null==(e=this.instance.config.rate_limiting)?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max((null==(e=this.instance.config.rate_limiting)?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var t,i,s;void 0===e&&(e=!1);var r=this.captureEventsBurstLimit,n=this.captureEventsPerSecond,o=(new Date).getTime(),a=null!==(t=null==(i=this.instance.persistence)?void 0:i.get_property(X))&&void 0!==t?t:{tokens:r,last:o};a.tokens+=(o-a.last)/1e3*n,a.last=o,a.tokens>r&&(a.tokens=r);var l=1>a.tokens;if(l||e||(a.tokens=Math.max(0,a.tokens-1)),l&&!e){var u=(St(a.dropped)?a.dropped:0)+1;a.dropped=u,!this.lastEventRateLimited&&this._captureWarning(u)&&(a.dropped=0)}return this.lastEventRateLimited=l,null==(s=this.instance.persistence)||s.set_property(X,a),{isRateLimited:l,remainingTokens:a.tokens}}_isPropertyAllowed(e){var t=this.instance.config.property_denylist;return!_t(t)||!t.includes(e)}_triggeringPage(){var e;if(this._isPropertyAllowed("$current_url")&&this._isPropertyAllowed("$pathname")&&null!=ke&&ke.pathname)return""+(null!==(e=ke.origin)&&void 0!==e?e:"")+ke.pathname}_captureWarning(e){var t,i,s=this.captureEventsBurstLimit,r=this.captureEventsPerSecond,n=this._triggeringPage(),o=this._isPropertyAllowed("$session_id")?null==(t=(i=this.instance).get_session_id)?void 0:t.call(i):void 0,a=[e+" event(s) dropped since the last warning",n?"triggered on "+n:void 0,o?"session "+o:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+a+". Config is set to "+r+" events per second and "+s+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var t=this.serverLimits[e||"events"]||!1;return!1!==t&&(new Date).getTime()<t}}var So=Gs("[RemoteConfig]");class xo{constructor(e){this._instance=e}get remoteConfig(){var e;return null==(e=Le._POSTHOG_REMOTE_CONFIG)||null==(e=e[this._instance.config.token])?void 0:e.config}_loadRemoteConfigJs(e){var t,i;null!=(t=Le.__PosthogExtensions__)&&t.loadExternalDependency?null==(i=Le.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,"remote-config",(()=>e(this.remoteConfig))):e()}_loadRemoteConfigJSON(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return So.info("Using preloaded remote config",this.remoteConfig),this._onRemoteConfig(this.remoteConfig),void this._startRefreshInterval();if(this._instance._shouldDisableFlags())return void So.warn("Remote config is disabled. Falling back to local config.");this._loadRemoteConfigJs((e=>{if(!e)return So.info("No config found after loading remote JS config. Falling back to JSON."),void this._loadRemoteConfigJSON((e=>{this._onRemoteConfig(e.json,e),this._startRefreshInterval()}));this._onRemoteConfig(e),this._startRefreshInterval()}))}catch(e){So.error("Error loading remote config",e),this._onRemoteConfig()}}stop(){this._refreshInterval&&(clearInterval(this._refreshInterval),this._refreshInterval=void 0)}refresh(){!this._instance._shouldDisableFlags()&&Ee&&"hidden"!==Ee.visibilityState&&this._instance.reloadFeatureFlags()}_startRefreshInterval(){var e;if(!this._refreshInterval){var t=null!==(e=this._instance.config.remote_config_refresh_interval_ms)&&void 0!==e?e:3e5;0!==t&&(this._refreshInterval=setInterval((()=>{this.refresh()}),t))}}_onRemoteConfig(e,t){!e&&t&&(0===t.statusCode?t.error||So.warn("Failed to fetch remote config from PostHog."):So.error("Failed to fetch remote config from PostHog."));try{this._instance._onRemoteConfig(e?{ok:!0,config:e}:{ok:!1})}catch(e){So.error("Error applying remote config",e)}if(!1!==(null==e?void 0:e.hasFeatureFlags)&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;null==(i=this._instance.featureFlags)||i.ensureFlagsLoaded()}catch(e){So.error("Error loading feature flags",e)}}}var Eo=Uint8Array,ko=Uint16Array,Po=Uint32Array,Co=new Eo([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Io=new Eo([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Fo=new Eo([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),To=function(e,t){for(var i=new ko(31),s=0;31>s;++s)i[s]=t+=1<<e[s-1];var r=new Po(i[30]);for(s=1;30>s;++s)for(var n=i[s];i[s+1]>n;++n)r[n]=n-i[s]<<5|s;return[i,r]},Ro=To(Co,2),Ao=Ro[1];Ro[0][28]=258,Ao[258]=28;for(var Lo=To(Io,0)[1],Mo=new ko(32768),$o=0;32768>$o;++$o){var Oo=(43690&$o)>>>1|(21845&$o)<<1;Mo[$o]=((65280&(Oo=(61680&(Oo=(52428&Oo)>>>2|(13107&Oo)<<2))>>>4|(3855&Oo)<<4))>>>8|(255&Oo)<<8)>>>1}var Do=function(e,t,i){for(var s=e.length,r=0,n=new ko(t);s>r;++r)++n[e[r]-1];var o,a=new ko(t);for(r=0;t>r;++r)a[r]=a[r-1]+n[r-1]<<1;if(i){o=new ko(1<<t);var l=15-t;for(r=0;s>r;++r)if(e[r])for(var u=r<<4|e[r],c=t-e[r],d=a[e[r]-1]++<<c,h=d|(1<<c)-1;h>=d;++d)o[Mo[d]>>>l]=u}else for(o=new ko(s),r=0;s>r;++r)o[r]=Mo[a[e[r]-1]++]>>>15-e[r];return o},Bo=new Eo(288);for($o=0;144>$o;++$o)Bo[$o]=8;for($o=144;256>$o;++$o)Bo[$o]=9;for($o=256;280>$o;++$o)Bo[$o]=7;for($o=280;288>$o;++$o)Bo[$o]=8;var qo=new Eo(32);for($o=0;32>$o;++$o)qo[$o]=5;var Ho=Do(Bo,9,0),No=Do(qo,5,0),zo=function(e){return(e/8>>0)+(7&e&&1)},jo=function(e,t,i){(null==i||i>e.length)&&(i=e.length);var s=new(e instanceof ko?ko:e instanceof Po?Po:Eo)(i-t);return s.set(e.subarray(t,i)),s},Uo=function(e,t,i){var s=t/8>>0;e[s]|=i<<=7&t,e[s+1]|=i>>>8},Vo=function(e,t,i){var s=t/8>>0;e[s]|=i<<=7&t,e[s+1]|=i>>>8,e[s+2]|=i>>>16},Wo=function(e,t){for(var i=[],s=0;e.length>s;++s)e[s]&&i.push({s:s,f:e[s]});var r=i.length,n=i.slice();if(!r)return[new Eo(0),0];if(1==r){var o=new Eo(i[0].s+1);return o[i[0].s]=1,[o,1]}i.sort((function(e,t){return e.f-t.f})),i.push({s:-1,f:25001});var a=i[0],l=i[1],u=0,c=1,d=2;for(i[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=i[i[d].f>i[u].f?u++:d++],l=i[u!=c&&i[d].f>i[u].f?u++:d++],i[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=n[0].s;for(s=1;r>s;++s)n[s].s>h&&(h=n[s].s);var _=new ko(h+1),p=Go(i[c-1],_,0);if(p>t){s=0;var g=0,v=p-t,f=1<<v;for(n.sort((function(e,t){return _[t.s]-_[e.s]||e.f-t.f}));r>s;++s){var m=n[s].s;if(t>=_[m])break;g+=f-(1<<p-_[m]),_[m]=t}for(g>>>=v;g>0;){var y=n[s].s;t>_[y]?g-=1<<t-_[y]++-1:++s}for(;s>=0&&g;--s){var b=n[s].s;_[b]==t&&(--_[b],++g)}p=t}return[new Eo(_),p]},Go=function(e,t,i){return-1==e.s?Math.max(Go(e.l,t,i+1),Go(e.r,t,i+1)):t[e.s]=i},Ko=function(e){for(var t=e.length;t&&!e[--t];);for(var i=new ko(++t),s=0,r=e[0],n=1,o=function(e){i[s++]=e},a=1;t>=a;++a)if(e[a]==r&&a!=t)++n;else{if(!r&&n>2){for(;n>138;n-=138)o(32754);n>2&&(o(n>10?n-11<<5|28690:n-3<<5|12305),n=0)}else if(n>3){for(o(r),--n;n>6;n-=6)o(8304);n>2&&(o(n-3<<5|8208),n=0)}for(;n--;)o(r);n=1,r=e[a]}return[i.subarray(0,s),t]},Qo=function(e,t){for(var i=0,s=0;t.length>s;++s)i+=e[s]*t[s];return i},Jo=function(e,t,i){var s=i.length,r=zo(t+2);e[r]=255&s,e[r+1]=s>>>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var n=0;s>n;++n)e[r+n+4]=i[n];return 8*(r+4+s)},Yo=function(e,t,i,s,r,n,o,a,l,u,c){Uo(t,c++,i),++r[256];for(var d=Wo(r,15),h=d[0],_=d[1],p=Wo(n,15),g=p[0],v=p[1],f=Ko(h),m=f[0],y=f[1],b=Ko(g),w=b[0],S=b[1],x=new ko(19),E=0;m.length>E;++E)x[31&m[E]]++;for(E=0;w.length>E;++E)x[31&w[E]]++;for(var k=Wo(x,7),P=k[0],C=k[1],I=19;I>4&&!P[Fo[I-1]];--I);var F,T,R,A,L=u+5<<3,M=Qo(r,Bo)+Qo(n,qo)+o,O=Qo(r,h)+Qo(n,g)+o+14+3*I+Qo(x,P)+(2*x[16]+3*x[17]+7*x[18]);if(M>=L&&O>=L)return Jo(t,c,e.subarray(l,l+u));if(Uo(t,c,1+(M>O)),c+=2,M>O){F=Do(h,_,0),T=h,R=Do(g,v,0),A=g;var D=Do(P,C,0);for(Uo(t,c,y-257),Uo(t,c+5,S-1),Uo(t,c+10,I-4),c+=14,E=0;I>E;++E)Uo(t,c+3*E,P[Fo[E]]);c+=3*I;for(var B=[m,w],q=0;2>q;++q){var H=B[q];for(E=0;H.length>E;++E)Uo(t,c,D[N=31&H[E]]),c+=P[N],N>15&&(Uo(t,c,H[E]>>>5&127),c+=H[E]>>>12)}}else F=Ho,T=Bo,R=No,A=qo;for(E=0;a>E;++E)if(s[E]>255){var N;Vo(t,c,F[257+(N=s[E]>>>18&31)]),c+=T[N+257],N>7&&(Uo(t,c,s[E]>>>23&31),c+=Co[N]);var z=31&s[E];Vo(t,c,R[z]),c+=A[z],z>3&&(Vo(t,c,s[E]>>>5&8191),c+=Io[z])}else Vo(t,c,F[s[E]]),c+=T[s[E]];return Vo(t,c,F[256]),c+T[256]},Zo=new Po([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Xo=function(){for(var e=new Po(256),t=0;256>t;++t){for(var i=t,s=9;--s;)i=(1&i&&3988292384)^i>>>1;e[t]=i}return e}(),ea=function(e,t,i){for(;i;++t)e[t]=i,i>>>=8};function ta(e,t){void 0===t&&(t={});var i=function(){var e=4294967295;return{p(t){for(var i=e,s=0;t.length>s;++s)i=Xo[255&i^t[s]]^i>>>8;e=i},d(){return 4294967295^e}}}(),s=e.length;i.p(e);var r,n,o,a,l,u=(a=10+((r=t).filename&&r.filename.length+1||0),l=8,function(e,t,i,s,r,n){var o=e.length,a=new Eo(s+o+5*(1+Math.floor(o/7e3))+r),l=a.subarray(s,a.length-r),u=0;if(!t||8>o)for(var c=0;o>=c;c+=65535){var d=c+65535;o>d?u=Jo(l,u,e.subarray(c,d)):(l[c]=!0,u=Jo(l,u,e.subarray(c,o)))}else{for(var h=Zo[t-1],_=h>>>13,p=8191&h,g=(1<<i)-1,v=new ko(32768),f=new ko(g+1),m=Math.ceil(i/3),y=2*m,b=function(t){return(e[t]^e[t+1]<<m^e[t+2]<<y)&g},w=new Po(25e3),S=new ko(288),x=new ko(32),E=0,k=0,P=(c=0,0),C=0,I=0;o>c;++c){var F=b(c),T=32767&c,R=f[F];if(v[T]=R,f[F]=T,c>=C){var A=o-c;if((E>7e3||P>24576)&&A>423){u=Yo(e,l,0,w,S,x,k,P,I,c-I,u),P=E=k=0,I=c;for(var L=0;286>L;++L)S[L]=0;for(L=0;30>L;++L)x[L]=0}var M=2,O=0,D=p,B=T-R&32767;if(A>2&&F==b(c-B))for(var q=Math.min(_,A)-1,H=Math.min(32767,c),N=Math.min(258,A);H>=B&&--D&&T!=R;){if(e[c+M]==e[c+M-B]){for(var z=0;N>z&&e[c+z]==e[c+z-B];++z);if(z>M){if(M=z,O=B,z>q)break;var j=Math.min(B,z-2),U=0;for(L=0;j>L;++L){var V=c-B+L+32768&32767,W=V-v[V]+32768&32767;W>U&&(U=W,R=V)}}}B+=(T=R)-(R=v[T])+32768&32767}if(O){w[P++]=268435456|Ao[M]<<18|Lo[O];var G=31&Ao[M],K=31&Lo[O];k+=Co[G]+Io[K],++S[257+G],++x[K],C=c+M,++E}else w[P++]=e[c],++S[e[c]]}}u=Yo(e,l,!0,w,S,x,k,P,I,c-I,u)}return jo(a,0,s+zo(u)+r)}(n=e,null==(o=t).level?6:o.level,null==o.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(n.length)))):12+o.mem,a,l)),c=u.length;return function(e,t){var i=t.filename;if(e[0]=31,e[1]=139,e[2]=8,e[8]=2>t.level?4:9==t.level?2:0,e[9]=3,0!=t.mtime&&ea(e,4,Math.floor(new Date(t.mtime||Date.now())/1e3)),i){e[3]=8;for(var s=0;i.length>=s;++s)e[s+10]=i.charCodeAt(s)}}(u,t),ea(u,c-8,i.d()),ea(u,c-4,s),u}var ia=!!Ce||!!Pe,sa="text/plain",ra=!1,na=(e,t)=>{var i=e.split("#"),s=i[1],r=i[0].split("?"),n=r[0],o=r[1];if(!o)return e;var a=o.split("&").filter((e=>e.split("=")[0]!==t)).join("&");return n+(a?"?"+a:"")+(s?"#"+s:"")},oa=function(e,t,s){var r;void 0===s&&(s=!0);var n=e.split("?"),o=n[0],a=n[1],l=i({},t),u=null!==(r=null==a?void 0:a.split("&").map((e=>{var t,i=e.split("="),r=i[0],n=s&&null!==(t=l[r])&&void 0!==t?t:i[1];return delete l[r],r+"="+n})))&&void 0!==r?r:[],c=function(e,t){var i,s;void 0===t&&(t="&");var r=[];return Qs(e,(function(e,t){ft(e)||ft(t)||"undefined"===t||(i=encodeURIComponent((e=>e instanceof File)(e)?e.name:e.toString()),s=encodeURIComponent(t),r[r.length]=s+"="+i)})),r.join(t)}(l);return c&&u.push(c),u.length>0?o+"?"+u.join("&"):o},aa=e=>{if(e._encodedBody)return e._encodedBody;var t=e.data,i=e.compression;if(t){if(i===ho){var s=ta(function(e,t){var i=e.length;if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);for(var s=new Eo(e.length+(e.length>>>1)),r=0,n=function(e){s[r++]=e},o=0;i>o;++o){if(r+5>s.length){var a=new Eo(r+8+(i-o<<1));a.set(s),s=a}var l=e.charCodeAt(o);128>l?n(l):2048>l?(n(192|l>>>6),n(128|63&l)):l>55295&&57344>l?(n(240|(l=65536+(1047552&l)|1023&e.charCodeAt(++o))>>>18),n(128|l>>>12&63),n(128|l>>>6&63),n(128|63&l)):(n(224|l>>>12),n(128|l>>>6&63),n(128|63&l))}return jo(s,0,r)}(On(t)),{mtime:0});return{contentType:sa,body:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength),estimatedSize:s.byteLength}}if(i===_o){var r=function(e){return e?btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,((e,t)=>String.fromCharCode(parseInt(t,16))))):e}(On(t)),n=(e=>"data="+encodeURIComponent("string"==typeof e?e:On(e)))(r);return{contentType:"application/x-www-form-urlencoded",body:n,estimatedSize:new Blob([n]).size}}var o=On(t);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},la=e=>{var t,s,r=()=>"sendBeacon"===e.transport?{url:oa(e.url,{compression:_o}),encodedBody:aa(i({},e,{compression:_o,_encodedBody:void 0}))}:{url:na(e.url,"compression"),encodedBody:aa(i({},e,{compression:void 0,_encodedBody:void 0}))};try{t=aa(e)}catch(t){if(Ve(e.compression,Bn(e.url,"compression")))return Ws.error("Failed to gzip request body, sending uncompressed payload",t),r();throw t}return t&&Ve(e.compression,Bn(e.url,"compression"))&&!((s=t.body)instanceof ArrayBuffer?Ue(new Uint8Array(s)):ArrayBuffer.isView(s)&&Ue(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(ra=!0,r()):{url:e.url,encodedBody:t}},ua=e=>{try{return la(e)}catch(t){return Ws.error(t),void(null==e.callback||e.callback({statusCode:0,error:t}))}},ca=function(){var e=t((function*(e){var t=On(e.data),s=yield function(e,t,i){return Qe.apply(this,arguments)}(t,r.DEBUG,{rethrow:!0});if(!s)return e;var n=yield s.arrayBuffer();return i({},e,{_encodedBody:{contentType:sa,body:n,estimatedSize:n.byteLength}})}));return function(t){return e.apply(this,arguments)}}(),da=/Failed to fetch|NetworkError|Load failed/i,ha=e=>"TypeError"===(null==e?void 0:e.name)&&da.test((null==e?void 0:e.message)||""),_a=e=>{var t=ua(e);if(t){var s=t.url,r=t.encodedBody,n=null!=r?r:{},o=n.contentType,a=n.body,l=n.estimatedSize,u=new Headers;Qs(e.headers,(function(e,t){u.append(t,e)})),o&&u.append("Content-Type",o);var c=null,d=!1;if(Ie){var h=new Ie;c={signal:h.signal,timeout:setTimeout((()=>{var t,i;d=!0,h.abort((t=e.timeout,(i=new Error("PostHog request timed out"+(t?" after "+t+"ms":""))).name="AbortError",i))}),e.timeout)}}var _=t=>{d&&"AbortError"===(null==t?void 0:t.name)||ha(t)?Ws.warn(t):Ws.error(t),null==e.callback||e.callback({statusCode:0,error:t})};try{var p;Pe(s,i({method:(null==e?void 0:e.method)||"GET",headers:u,keepalive:"POST"===e.method&&!e._keepaliveDisabled&&52428.8>(l||0),body:a,signal:null==(p=c)?void 0:p.signal},e.fetchOptions)).then((t=>t.text().then((i=>{var s={statusCode:t.status,text:i};if(200===t.status)try{s.json=JSON.parse(i)}catch(e){Ws.error(e)}null==e.callback||e.callback(s)})))).catch(_).finally((()=>c?clearTimeout(c.timeout):null))}catch(e){c&&clearTimeout(c.timeout),_(e)}}},pa=e=>{try{var t,s=la(e),r=s.url,n=s.encodedBody,o=null!=n?n:{},a=o.body,l=o.estimatedSize;if(!a)return;var u=a instanceof Blob?a:new Blob([a],{type:o.contentType});if(xe.sendBeacon(r,u))return;var c=_t(e.data)?e.data:null==(t=e.data)?void 0:t.batch;if(_t(c)&&c.length>1&&(null!=l?l:0)>16384){var d=Math.ceil(c.length/2),h=t=>_t(e.data)?t:i({},e.data,{batch:t});return pa(i({},e,{data:h(c.slice(0,d))})),void pa(i({},e,{data:h(c.slice(d))}))}Ws.warn("Beacon of ~"+(null!=l?l:0)+" bytes was rejected by the browser, falling back to fetch"),_a(i({},e,{_keepaliveDisabled:!0}))}catch(e){Ws.warn("Beacon send failed",e)}},ga=(e,t,s,r)=>{var n="query"===r?"POST"===t?"sent_at":"_":void 0;return oa(s===ho?na(e,"compression"):e,i({},n?{[n]:Date.now().toString()}:{},s===ho?{}:{compression:s}))},va=[];Pe&&va.push({transport:"fetch",method:_a}),Ce&&va.push({transport:"XHR",method(e){var t=ua(e);if(t){var i=new Ce,s=t.encodedBody;i.open(e.method||"GET",t.url,!0);var r=null!=s?s:{},n=r.contentType,o=r.body;Qs(e.headers,(function(e,t){i.setRequestHeader(t,e)})),n&&i.setRequestHeader("Content-Type",n),e.timeout&&(i.timeout=e.timeout),i.onreadystatechange=()=>{if(4===i.readyState){var t={statusCode:i.status,text:i.responseText};if(200===i.status)try{t.json=JSON.parse(i.responseText)}catch(e){}null==e.callback||e.callback(t)}},i.send(o)}}}),null!=xe&&xe.sendBeacon&&va.push({transport:"sendBeacon",method:pa});var fa=3e3;class ma{constructor(e,t){this._isPaused=!0,this._queue=[],this._flushTimeoutMs=Ot((null==t?void 0:t.flush_interval_ms)||fa,250,5e3,Ws.createLogger("flush interval"),fa),this._sendRequest=e}enqueue(e){this._queue.push(e),this._flushTimeout||this._setFlushTimeout()}unload(){this._clearFlushTimeout();var e=this._queue.length>0?this._formatQueue():{},t=Object.values(e);[...t.filter((e=>0===e.url.indexOf("/e"))),...t.filter((e=>0!==e.url.indexOf("/e")))].map((e=>{this._sendRequestSafely(i({},e,{transport:"sendBeacon"}))}))}enable(){this._isPaused=!1,this._setFlushTimeout()}_setFlushTimeout(){var e=this;this._isPaused||(this._flushTimeout=setTimeout((()=>{if(this._clearFlushTimeout(),this._queue.length>0){var t=this._formatQueue(),i=function(){var i=t[s],r=(new Date).getTime();i.data&&_t(i.data)&&Qs(i.data,(e=>{e.offset=Math.abs(e.timestamp-r),delete e.timestamp})),e._sendRequestSafely(i)};for(var s in t)i()}}),this._flushTimeoutMs))}_sendRequestSafely(e){try{this._sendRequest(e)}catch(e){Ws.error(e)}}_clearFlushTimeout(){clearTimeout(this._flushTimeout),this._flushTimeout=void 0}_formatQueue(){var e={};return Qs(this._queue,(t=>{var s,r=t,n=(r?r.batchKey:null)||r.url;ft(e[n])&&(e[n]=i({},r,{data:[]})),null==(s=e[n].data)||s.push(r.data)})),this._queue=[],e}}var ya=["retriesPerformedSoFar"];class ba{constructor(e){this._isPolling=!1,this._pollIntervalMs=3e3,this._queue=[],this._instance=e,this._queue=[],this._areWeOnline=!0,!ft(we)&&"onLine"in we.navigator&&(this._areWeOnline=we.navigator.onLine,this._onlineListener=()=>{this._areWeOnline=!0,this._flush()},this._offlineListener=()=>{this._areWeOnline=!1},sr(we,"online",this._onlineListener),sr(we,"offline",this._offlineListener))}get length(){return this._queue.length}retriableRequest(e){var t=e.retriesPerformedSoFar,r=s(e,ya);xt(t)&&(r.url=oa(r.url,{retry_count:t})),this._instance._send_request(i({},r,{callback:e=>{if(200!==e.statusCode&&(400>e.statusCode||e.statusCode>=500)){if((0===e.statusCode?3:10)>(null!=t?t:0))return void this._enqueue(i({retriesPerformedSoFar:t},r));0===e.statusCode&&Ws.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(null!=t?t:0)+" retries.")}null==r.callback||r.callback(e)}}))}_enqueue(e){var t=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=t+1;var i=function(e){var t=3e3*Math.pow(2,e),i=t/2,s=Math.min(18e5,t),r=Math.random()-.5;return Math.ceil(s+r*(s-i))}(t),s=Date.now()+i;this._queue.push({retryAt:s,requestOptions:e});var r="Enqueued failed request for retry in "+i;navigator.onLine||(r+=" (Browser is offline)"),Ws.warn(r),this._isPolling||(this._isPolling=!0,this._poll())}_poll(){if(this._poller&&clearTimeout(this._poller),0===this._queue.length)return this._isPolling=!1,void(this._poller=void 0);this._poller=setTimeout((()=>{this._areWeOnline&&this._queue.length>0&&this._flush(),this._poll()}),this._pollIntervalMs)}_flush(){var e=Date.now(),t=[],i=this._queue.filter((i=>e>i.retryAt||(t.push(i),!1)));if(this._queue=t,i.length>0)for(var s of i)this.retriableRequest(s.requestOptions)}unload(){for(var e of(this._poller&&(clearTimeout(this._poller),this._poller=void 0),this._isPolling=!1,ft(we)||(this._onlineListener&&(we.removeEventListener("online",this._onlineListener),this._onlineListener=void 0),this._offlineListener&&(we.removeEventListener("offline",this._offlineListener),this._offlineListener=void 0)),this._queue)){var t=e.requestOptions;try{this._instance._send_request(i({},t,{transport:"sendBeacon"}))}catch(e){Ws.error(e)}}this._queue=[]}}class wa{constructor(e){this._updateScrollData=()=>{var e,t,i,s;this._context||(this._context={});var r=this.scrollElement(),n=this.scrollY(),o=r?Math.max(0,r.scrollHeight-r.clientHeight):0,a=n+((null==r?void 0:r.clientHeight)||0),l=(null==r?void 0:r.scrollHeight)||0;this._context.lastScrollY=Math.ceil(n),this._context.maxScrollY=Math.max(n,null!==(e=this._context.maxScrollY)&&void 0!==e?e:0),this._context.maxScrollHeight=Math.max(o,null!==(t=this._context.maxScrollHeight)&&void 0!==t?t:0),this._context.lastContentY=a,this._context.maxContentY=Math.max(a,null!==(i=this._context.maxContentY)&&void 0!==i?i:0),this._context.maxContentHeight=Math.max(l,null!==(s=this._context.maxContentHeight)&&void 0!==s?s:0)},this._instance=e}get _scrollRoot(){return this._instance.config.scroll_root_selector}getContext(){return this._context}resetContext(){var e=this._context;return setTimeout(this._updateScrollData,0),e}startMeasuringScrollPosition(){sr(we,"scroll",this._updateScrollData,{capture:!0}),sr(we,"scrollend",this._updateScrollData,{capture:!0}),sr(we,"resize",this._updateScrollData)}scrollElement(){if(!this._scrollRoot)return null==we?void 0:we.document.documentElement;var e=_t(this._scrollRoot)?this._scrollRoot:[this._scrollRoot];for(var t of e){var i=null==we?void 0:we.document.querySelector(t);if(i)return i}}_scrollPosition(e){var t="y"===e?"scrollTop":"scrollLeft";if(this._scrollRoot){var i=this.scrollElement();return i&&i[t]||0}return we?"y"===e?we.scrollY||we.pageYOffset||we.document.documentElement.scrollTop||0:we.scrollX||we.pageXOffset||we.document.documentElement.scrollLeft||0:0}scrollY(){return this._scrollPosition("y")}scrollX(){return this._scrollPosition("x")}}var Sa=e=>eo(null==e?void 0:e.config.mask_personal_data_properties,null==e?void 0:e.config.custom_personal_data_properties,null==e?void 0:e.config.disable_capture_url_hashes);class xa{constructor(e,t,i,s){this._onSessionIdCallback=e=>{var t=this._getStored();if(!t||t.sessionId!==e){var i={sessionId:e,props:this._sessionSourceParamGenerator(this._instance)};this._persistence.register({[Z]:i})}},this._instance=e,this._sessionIdManager=t,this._persistence=i,this._sessionSourceParamGenerator=s||Sa,this._sessionIdManager.onSessionId(this._onSessionIdCallback)}_getStored(){return this._persistence.props[Z]}getSetOnceProps(){var e,t=null==(e=this._getStored())?void 0:e.props;return t?"r"in t?to(t,this._instance.config.disable_capture_url_hashes):{$referring_domain:t.referringDomain,$pathname:t.initialPathName,utm_source:t.utm_source,utm_campaign:t.utm_campaign,utm_medium:t.utm_medium,utm_content:t.utm_content,utm_term:t.utm_term}:{}}getSessionProps(){var e={};return Qs(er(this.getSetOnceProps()),((t,i)=>{"$current_url"===i&&(i="url"),e["$session_entry_"+lt(i)]=t})),e}}class Ea{on(e,t){return this._events[e]||(this._events[e]=[]),this._events[e].push(t),()=>{this._events[e]=this._events[e].filter((e=>e!==t))}}emit(e,t){for(var i of this._events[e]||[])i(t);for(var s of this._events["*"]||[])s(e,t)}constructor(){this._events={}}}var ka=Gs("[SessionId]"),Pa=864e5;class Ca{on(e,t){return this._eventEmitter.on(e,t)}constructor(e,t,i){var s;if(this._lastPersistedActivityTimestamp=null,this._lastCookieSyncTimestamp=null,this._sessionIdChangedHandlers=[],this._beforeUnloadListener=void 0,this._destroyed=!1,this._eventEmitter=new Ea,this._sessionHasBeenIdleTooLong=(e,t)=>!(!xt(e)||!xt(t))&&Math.abs(e-t)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===de)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this._config=e.config,this._persistence=e.persistence,this._windowId=void 0,this._sessionId=void 0,this._sessionStartTimestamp=null,this._pendingBootstrapSession=void 0,this._sessionActivityTimestamp=null,this._sessionIdGenerator=t||dr,this._windowIdGenerator=i||dr;var r=this._config.persistence_name||this._config.token;if(this._sessionTimeoutMs=1e3*Ot(this._config.session_idle_timeout_seconds||1800,60,36e3,ka.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this._resetIdleTimer(),this._window_id_storage_key="ph_"+r+"_window_id",this._primary_window_exists_storage_key="ph_"+r+"_primary_window_exists",this._canUseSessionStorage()){var n=Rr._parse(this._window_id_storage_key),o=Rr._parse(this._primary_window_exists_storage_key);n&&!o?this._windowId=n:Rr._remove(this._window_id_storage_key),Rr._set(this._primary_window_exists_storage_key,!0)}null!=(s=this._config.bootstrap)&&s.sessionID&&this.setBootstrapSessionId(this._config.bootstrap.sessionID),this._listenToReloadWindow()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return ft(this._sessionIdChangedHandlers)&&(this._sessionIdChangedHandlers=[]),this._sessionIdChangedHandlers.push(e),this._sessionId&&e(this._sessionId,this._windowId),()=>{this._sessionIdChangedHandlers=this._sessionIdChangedHandlers.filter((t=>t!==e))}}_canUseSessionStorage(){return"memory"!==this._config.persistence&&!this._persistence._disabled&&Rr._is_supported()}_setWindowId(e){e!==this._windowId&&(this._windowId=e,this._canUseSessionStorage()&&Rr._set(this._window_id_storage_key,e))}_getWindowId(){return this._windowId?this._windowId:this._canUseSessionStorage()?Rr._parse(this._window_id_storage_key):null}_isActivityChangeBelowGranularity(e){var t=this._lastPersistedActivityTimestamp;return!bt(t)&&!bt(e)&&5e3>Math.abs(e-t)}_setSessionId(e,t,i){var s=t!==this._sessionActivityTimestamp,r=!(e!==this._sessionId||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=t,this._sessionId=e,r&&!s||r&&this._isActivityChangeBelowGranularity(t)||(this._lastPersistedActivityTimestamp=t,this._persistence.register({[P]:[t,e,i]}))}_useCrossTabRefreshHardening(){var e,t=null==(e=this._config)?void 0:e.persistence_save_debounce_ms;return xt(t)&&t>0}_refreshSessionIdFromStorage(){this._useCrossTabRefreshHardening()?this._persistence.refreshKey(P):(this._persistence.flush(),this._persistence.load())}_flushPendingActivityTimestamp(){var e;if(!bt(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this._lastPersistedActivityTimestamp){this._refreshSessionIdFromStorage();var t=this._getSessionId();t[1]===this._sessionId&&t[2]===this._sessionStartTimestamp&&(this._lastPersistedActivityTimestamp=this._sessionActivityTimestamp,this._persistence.register({[P]:[this._sessionActivityTimestamp,null!==(e=this._sessionId)&&void 0!==e?e:null,this._sessionStartTimestamp]}),this._persistence.flush())}}_freshestActivityTimestamp(){var e=this._getSessionId()[0],t=xt(e)?e:0,i=xt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(t,i)}_isSessionIdleAfterCrossTabRefresh(e){return this._refreshSessionIdFromStorage(),this._sessionHasBeenIdleTooLong(e,this._freshestActivityTimestamp())}_getSessionId(){var e=this._persistence.props[P];return _t(e)&&2===e.length&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this._lastPersistedActivityTimestamp=null,this._pendingBootstrapSession=void 0,clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=void 0,this._setSessionId(null,null,null)}setBootstrapSessionId(e,t){void 0===t&&(t=!1);var i=function(e,t){void 0===t&&(t=(new Date).getTime());try{var i=(e=>{var t=e.replace(/-/g,"");if(32!==t.length)throw new Error("Not a valid UUID");if("7"!==t[12])throw new Error("Not a UUIDv7");return parseInt(t.substring(0,12),16)})(e);return i>t+6e4?void ka.error("Bootstrap sessionID cannot be in the future"):i}catch(e){return void ka.error("Invalid sessionID in bootstrap",e)}}(e);return!ft(i)&&(t?this._pendingBootstrapSession={sessionId:e,sessionStartTimestamp:i}:this._setSessionId(e,(new Date).getTime(),i),!0)}destroy(){this._destroyed=!0,this._flushPendingActivityTimestamp(),clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=void 0,this._beforeUnloadListener&&we&&(we.removeEventListener(ve,this._beforeUnloadListener,{capture:!1}),this._beforeUnloadListener=void 0),this._sessionIdChangedHandlers=[]}_listenToReloadWindow(){this._beforeUnloadListener=()=>{this._flushPendingActivityTimestamp(),this._canUseSessionStorage()&&Rr._remove(this._primary_window_exists_storage_key)},sr(we,ve,this._beforeUnloadListener,{capture:!1})}checkAndGetSessionAndWindowId(e,t,i){if(void 0===e&&(e=!1),void 0===t&&(t=null),void 0===i&&(i=!1),this._config.cookieless_mode===de)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var s=t||(new Date).getTime(),r=this._sessionId;if(i)this._lastCookieSyncTimestamp=s;else if(bt(this._lastCookieSyncTimestamp)||this._lastCookieSyncTimestamp>s||s-this._lastCookieSyncTimestamp>=1e3){var n,o;null==(n=(o=this._persistence).syncCookieProperties)||n.call(o),this._lastCookieSyncTimestamp=s}var a=this._getSessionId(),l=a[1],u=a[2],c=!ft(r)&&l!==r,d=this._freshestActivityTimestamp(),h=this._getWindowId(),_=this._pendingBootstrapSession,p=!!_&&(_.sessionStartTimestamp>s+6e4||s-_.sessionStartTimestamp>Pa),g=_?p:xt(u)&&Math.abs(s-u)>Pa,v=!1,f=c,m=!l||!!_,y=l,b=!m&&!e&&this._sessionHasBeenIdleTooLong(s,d);if(b){(b=this._isSessionIdleAfterCrossTabRefresh(s))||ka.info("cross-tab refresh kept the session alive",{sessionId:l});var w=this._getSessionId();l=w[1],u=w[2]}if(m||b||g){f=!1;var S=_&&!p;l=S?_.sessionId:this._sessionIdGenerator(),h=this._windowIdGenerator(),ka.info("new session ID assigned",{sessionId:l,windowId:h,bootstrapped:!!S,changeReason:{noSessionId:m,activityTimeout:b,sessionPastMaximumLength:g}}),u=S?_.sessionStartTimestamp:s,this._pendingBootstrapSession=void 0,v=!0}else h||(h=this._windowIdGenerator(),v=!0),(f=f||l!==y)&&(ka.info("adopted cross-tab session id",{sessionId:l,windowId:h}),v=!0);var x=xt(d)&&e&&!g?d:s,E=xt(u)?u:(new Date).getTime();this._setWindowId(h),this._setSessionId(l,x,E),e||this._resetIdleTimer();var k={noSessionId:m,activityTimeout:b,sessionPastMaximumLength:g,crossTabAdoption:f};return v&&this._sessionIdChangedHandlers.forEach((e=>e(l,h,k))),{sessionId:l,windowId:h,sessionStartTimestamp:E,changeReason:v?k:void 0,lastActivityTimestamp:d}}_resetIdleTimer(){this._destroyed||(clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=setTimeout((()=>{if(!this._destroyed)if(this._isSessionIdleAfterCrossTabRefresh((new Date).getTime())){var e=this._sessionId;this.resetSessionId(),this._eventEmitter.emit("forcedIdleReset",{idleSessionId:e})}else this._resetIdleTimer()}),1.1*this.sessionTimeoutMs))}}var Ia=function(e,t){if(!e)return!1;var i=e.userAgent;if(i&&nt(i,t))return!0;try{var s=null==e?void 0:e.userAgentData;if(null!=s&&s.brands&&s.brands.some((e=>nt(null==e?void 0:e.brand,t))))return!0}catch(e){}return!!e.webdriver};function Fa(){return(Fa=t((function*(){var e=null==xe?void 0:xe.userAgentData;if(null!=e&&e.getHighEntropyValues)try{var t=yield e.getHighEntropyValues(["model"]),i=null==t?void 0:t.model;return mt(i)&&i.length>0?i:void 0}catch(e){return void Ws.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",e)}}))).apply(this,arguments)}function Ta(e){var t;return!(null==(t=e.conditions)||null==(t=t.events)||null==(t=t.values)||!t.length)}var Ra=(e,t)=>{if(!(e=>{try{new RegExp(e)}catch(e){return!1}return!0})(t))return!1;try{return new RegExp(t).test(e)}catch(e){return!1}},Aa=e=>e.toLowerCase(),La={exact:(e,t)=>t.some((t=>e.some((e=>t===e)))),is_not:(e,t)=>t.every((t=>e.every((e=>t!==e)))),regex:(e,t)=>t.some((t=>e.some((e=>Ra(t,e))))),not_regex:(e,t)=>t.every((t=>e.every((e=>!Ra(t,e))))),icontains:(e,t)=>t.map(Aa).some((t=>e.map(Aa).some((e=>t.includes(e))))),not_icontains:(e,t)=>t.map(Aa).every((t=>e.map(Aa).every((e=>!t.includes(e))))),gt:(e,t)=>t.some((t=>{var i=parseFloat(t);return!isNaN(i)&&e.some((e=>i>parseFloat(e)))})),lt:(e,t)=>t.some((t=>{var i=parseFloat(t);return!isNaN(i)&&e.some((e=>i<parseFloat(e)))}))};function Ma(e,t){return!e||Object.entries(e).every((e=>{var i=e[1],s=null==t?void 0:t[e[0]];if(null==s)return!1;var r=La[i.operator];return!!r&&r(i.values,[String(s)])}))}function $a(e,t,i){return On({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:i})}var Oa="custom",Da="i.posthog.com",Ba=/^\/static\//,qa=["/s/","/e/","/i/"];class Ha{constructor(e){this._regionCache={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return"https://app.posthog.com"===e?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,t=null==(e=this.instance.config.ui_host)?void 0:e.replace(/\/$/,"");return t||(t=this.apiHost.replace("."+Da,".posthog.com")),"https://app.posthog.com"===t?"https://us.posthog.com":t}get region(){return this._regionCache[this.apiHost]||(this._regionCache[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":Oa),this._regionCache[this.apiHost]}_staticAssetHostOverride(e){if(Ba.test(e)){var t=this.instance.config.asset_host;if("string"==typeof t)return t.trim().replace(/\/$/,"")||void 0}}_urlKey(e){var t=Dn(e);return t?t.protocol+"//"+t.host+t.pathname:void 0}_prepareEndpoint(e,t,i){if("ui"===e)return i;var s=i,r=this.instance.config.rewriteRequestPath;if(r){var n,o=(null==(n=Dn(i))?void 0:n.href)||i;s=r(new URL(o)).toString()}if(r&&"api"===e&&qa.some((e=>0===t.indexOf(e)))){var a=this._urlKey(s);if(a){var l,u=this.apiHost,c=this._ingestionEndpoints;(null==(l=c)?void 0:l.apiHost)===u&&c.rewriteRequestPath===r||(c={apiHost:u,rewriteRequestPath:r,urls:new Set},this._ingestionEndpoints=c),c.urls.add(a)}}return s}isIngestionEndpoint(e){var t=this._ingestionEndpoints,i=this._urlKey(e);return(null==t?void 0:t.apiHost)===this.apiHost&&t.rewriteRequestPath===this.instance.config.rewriteRequestPath&&!!i&&t.urls.has(i)}endpointFor(e,t){if(void 0===t&&(t=""),t&&(t="/"===t[0]?t:"/"+t),"ui"===e)return this._prepareEndpoint(e,t,this.uiHost+t);if("flags"===e)return this._prepareEndpoint(e,t,this.flagsApiHost+t);if("assets"===e){var i=this._staticAssetHostOverride(t);if(i)return this._prepareEndpoint(e,t,""+i+t)}if(this.region===Oa)return this._prepareEndpoint(e,t,this.apiHost+t);var s=Da+t;switch(e){case"assets":return this._prepareEndpoint(e,t,"https://"+this.region+"-assets."+s);case"api":return this._prepareEndpoint(e,t,"https://"+this.region+"."+s)}}}var Na=Gs("[Surveys]"),za="seenSurvey_",ja=e=>{try{var t=(e=>((e,t)=>""+e+function(e){return e.current_iteration&&e.current_iteration>0?e.id+"_"+e.current_iteration:e.id}(t))(za,e))(e);if(localStorage.getItem(t))return;localStorage.setItem(t,"true")}catch(e){Na.error("Failed to persist survey seen state",e)}},Ua=["popover","widget","api"],Va={ignoreConditions:!1,ignoreDelay:!1,displayType:yo},Wa=Gs("[PostHog ExternalIntegrations]"),Ga={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Ka{constructor(e){this._instance=e}_loadScript(e,t){var i;null==(i=Le.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,e,(e=>{if(e)return Wa.error("failed to load script",e);t()}))}startIfEnabledOrStop(){var e=this,t=function(){var t,s,r,n=i[0],o=i[1];!o||null!=(t=Le.__PosthogExtensions__)&&null!=(t=t.integrations)&&t[n]||e._loadScript(Ga[n],(()=>{var t;null==(t=Le.__PosthogExtensions__)||null==(t=t.integrations)||null==(t=t[n])||t.start(e._instance)})),!o&&null!=(s=Le.__PosthogExtensions__)&&null!=(s=s.integrations)&&s[n]&&(null==(r=Le.__PosthogExtensions__)||null==(r=r.integrations)||null==(r=r[n])||r.stop())};for(var i of Object.entries(null!==(s=this._instance.config.integrations)&&void 0!==s?s:{})){var s;t()}}}class Qa{constructor(e,t){this._logger=e,this._client=t,this._extensions=new Map,this._disposed=!1}add(e){var i=this;return t((function*(){if(i._disposed)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(i._extensions.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');i._extensions.set(e.name,e);try{var t=e.setup(i._client);t&&(yield t)}catch(t){var s=i._extensions.get(e.name)===e;s&&i._extensions.delete(e.name),i._logger.error('Failed to set up browser extension "'+e.name+'"',t),s&&i._disposeExtension(e)}}))()}dispose(){if(!this._disposed){this._disposed=!0;var e=Array.from(this._extensions.values()).reverse();for(var t of(this._extensions.clear(),e))this._disposeExtension(t)}}_disposeExtension(e){try{var t=null==e.dispose?void 0:e.dispose();t&&pt(t.then)&&t.then(void 0,(t=>{this._logger.error('Failed to dispose browser extension "'+e.name+'"',t)}))}catch(t){this._logger.error('Failed to dispose browser extension "'+e.name+'"',t)}}}class Ja{constructor(e){this._instance=e}initialize(){}get(e){var t=this._instance.persistence;if("string"==typeof e)return null==t?void 0:t.get_property(e);var i={};for(var s of e){var r=null==t?void 0:t.get_property(s);ft(r)||(i[s]=r)}return i}set(e,t){var i;null==(i=this._instance.persistence)||i.register("string"==typeof e?{[e]:t}:e)}remove(e){var t;null==(t=this._instance.persistence)||t.unregister(e)}}var Ya="extensionsRemoteConfig";class Za{constructor(e){this._disposed=!1,this.instance=e,this._logger=Ws,this._latestRemoteConfigResult=e._lastRemoteConfig,this.kv=new Ja(e),this.onEvent=e=>co(this.instance.on("eventCaptured",(t=>{try{e({event:t.event,properties:t.properties})}catch(e){this._logger.error("Browser extension event listener failed",e)}}))),this.onRemoteConfig=e=>{if(this._disposed)return co((()=>{}));var t=t=>{try{e(t)}catch(e){this._logger.error("Browser extension remote config listener failed",e)}},i=this.instance._internalEventEmitter.on(Ya,t);return this._latestRemoteConfigResult&&t(this._latestRemoteConfigResult),co(i)},this._runtime=new Qa(Ws.createLogger("[BrowserExtensions]"),this)}get logger(){return this._logger}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return null!==(e=this.instance.get_property(a))&&void 0!==e?e:this.distinctId}get deviceId(){var e=this.instance.get_property(a);return"string"==typeof e?e:void 0}get library(){return{name:r.LIB_NAME,version:r.LIB_VERSION}}get initialPersonProperties(){var e,t;return null!==(e=null==(t=this.instance.persistence)?void 0:t.get_initial_props())&&void 0!==e?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,t,i,s,r=null==(e=this.instance.sessionManager)?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:null!==(t=null==r?void 0:r.sessionId)&&void 0!==t?t:"",windowId:null!==(i=null==r?void 0:r.windowId)&&void 0!==i?i:"",sessionStartTimestamp:null!==(s=null==r?void 0:r.sessionStartTimestamp)&&void 0!==s?s:0}}catch(e){return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this._runtime.add(e)}capture(e,i,s){var r=this;return t((function*(){s?r.instance.capture(e,i,{timestamp:s.timestamp,uuid:s.uuid,$set:s.set,$set_once:s.setOnce}):r.instance.capture(e,i)}))()}registerDynamicEventProperties(e){return co(this.instance._registerExtensionEventProperties(e))}handleRemoteConfig(e){this._disposed||(this._latestRemoteConfigResult=e,this.instance._internalEventEmitter.emit(Ya,e))}sendRequest(e,i){var s=this;return t((function*(){var t;void 0===i&&(i={});var r=s.instance.requestRouter.endpointFor(null!==(t=i.target)&&void 0!==t?t:"api",e),n={method:i.method,url:i.query?oa(r,i.query):r,data:i.body,headers:i.headers,timeout:i.timeoutMs,fireCallbackOnDrop:!0,transport:i.transport,compression:i.compression,timestampMode:i.sentAt};return"sendBeacon"===i.transport?(s.instance._send_request(n),{statusCode:202}):new Promise((e=>{n.callback=e,s.instance._send_request(n)}))}))()}dispose(){this._disposed||(this._disposed=!0,this._runtime.dispose())}}var Xa={},el=0,tl=()=>{},il='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',sl="Surveys module not available",rl="sanitize_properties is deprecated. Use before_send instead",nl="Invalid value for property_denylist config: ",ol=["token","distinct_id",ne],al="posthog",ll=!ia&&-1===(null==Te?void 0:Te.indexOf("MSIE"))&&-1===(null==Te?void 0:Te.indexOf("Mozilla")),ul=e=>{var t;return i({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:ir(null==Ee?void 0:Ee.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:tl,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:null!=e?e:"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:ke&&mt(null==ke?void 0:ke.search)&&-1!==ke.search.indexOf("__posthog_debug=true")||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:"fallback",enable_recording_console_log:void 0,secure_cookie:"https:"===(null==we||null==(t=we.location)?void 0:t.protocol),ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(e){Ws.error("Bad HTTP status: "+e.statusCode+" "+e.text)},get_device_id:e=>e,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:pe,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:fa},error_tracking:{},_onCapture:tl},(e=>({rageclick:e&&e>="2026-05-30"?{content_ignorelist:tn,ignore_text_selection:!0}:!e||"2025-11-30">e||{content_ignorelist:!0},capture_pageview:!e||"2025-05-24">e||"history_change",session_recording:e&&e>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:e&&e>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:e&&e>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:e&&e>="2026-01-30"?"head":"body",internal_or_test_user_hostname:e&&e>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:e&&e>="2026-05-30"?250:0,split_storage:!(!e||"2026-05-30">e),detect_google_search_app:!(!e||"2026-05-30">e),disable_capture_url_hashes:!(!e||"2026-06-25">e),cookieWinsOnConflict:!(!e||"unset"===e||"2026-08-29">e)}))(e))},cl=[["process_person","person_profiles"],["xhr_headers","request_headers"],["cookie_name","persistence_name"],["disable_cookie","disable_persistence"],["__preview_disable_beacon","disable_beacon"],["store_google","save_campaign_params"],["verbose","debug"],["__preview_cookie_wins_on_conflict","cookieWinsOnConflict"]],dl=e=>{var t={};for(var i of cl){var s=i[0],r=i[1];ft(e[s])||(t[r]=e[s])}var n=Js({},t,e),o=e.__preview_external_dependency_versioned_paths;return ft(o)||(ft(e.strict_script_versioning)&&(n.strict_script_versioning=!!o),mt(o)&&ft(e.asset_host)&&(n.asset_host=o)),_t(e.property_blacklist)&&(ft(e.property_denylist)?n.property_denylist=e.property_blacklist:_t(e.property_denylist)?n.property_denylist=[...e.property_blacklist,...e.property_denylist]:Ws.error(nl+e.property_denylist)),n};class hl{constructor(){this.__forceAllowLocalhost=!1}get _forceAllowLocalhost(){return this.__forceAllowLocalhost}set _forceAllowLocalhost(e){Ws.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class _l{_replaceExtension(e,t){if(e){var i=this._extensions.indexOf(e);-1!==i&&this._extensions.splice(i,1)}return this._extensions.push(t),null==t.initialize||t.initialize(),t}_inCookielessMode(){return this.config.cookieless_mode===de||this.config.cookieless_mode===ce&&this.consent.isRejected()}_healCookielessSentinelDistinctId(){if(!this._inCookielessMode()&&this.get_distinct_id()===re){var e=this.persistence;if(e){this._is_persistence_disabled()||e.load(!0);var t=this.get_distinct_id();if(!t||t===re){var i=this.config.get_device_id(dr());this.register({distinct_id:i,$device_id:i}),e.set_property(Y,he)}this._sync_opt_out_with_persistence()}}}get decideEndpointWasHit(){var e,t;return null!==(e=null==(t=this.featureFlags)?void 0:t.hasLoadedFlags)&&void 0!==e&&e}get flagsEndpointWasHit(){var e,t;return null!==(e=null==(t=this.featureFlags)?void 0:t.hasLoadedFlags)&&void 0!==e&&e}constructor(){var e;this.webPerformance=new hl,this._personProcessingSetOncePropertiesSent=!1,this.version=r.LIB_VERSION,this._sessionRegisteredPropKeys=new Set,this._sessionRegisteredPropertiesStorageKey="",this._internalEventEmitter=new Ea,this._extensions=[],this._extensionEventPropertyProducers=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=ul(),this.SentryIntegration=Tn,this.sentryIntegration=e=>function(e,t){var i=Fn(e,t);return{name:In,processEvent:e=>i(e)}}(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this._initialPageviewCaptured=!1,this._visibilityStateListener=null,this._initialPersonProfilesConfig=null,this._cachedPersonProperties=null,this.scrollManager=new wa(this),this.pageViewManager=new Rn(this),this.rateLimiter=new wo(this),this.requestRouter=new Ha(this),this.consent=new Ar(this),this.externalIntegrations=new Ka(this);var t=null!==(e=_l.__defaultExtensionClasses)&&void 0!==e?e:{};this.featureFlags=t.featureFlags&&new t.featureFlags(this),this.toolbar=t.toolbar&&new t.toolbar(this),this.surveys=t.surveys&&new t.surveys(this),this.conversations=t.conversations&&new t.conversations(this),this.logs=t.logs&&new t.logs(this),this.metrics=t.metrics&&new t.metrics(this),this.experiments=t.experiments&&new t.experiments(this),this.exceptions=t.exceptions&&new t.exceptions(this),this.people={set:(e,t,i)=>{var s=mt(e)?{[e]:t}:e;this.setPersonProperties(s),null==i||i({})},set_once:(e,t,i)=>{var s=mt(e)?{[e]:t}:e;this.setPersonProperties(void 0,s),null==i||i({})}},this.on("eventCaptured",(e=>Ws.info('send "'+(null==e?void 0:e.event)+'"',e)))}init(e,t,i){if(i&&i!==al){var s,r=null!==(s=Xa[i])&&void 0!==s?s:new _l;return r._init(e,t,i),Xa[i]=r,Xa[al][i]=r,r}return this._init(e,t,i)}_init(e,t,s){var n,o;void 0===t&&(t={});var a,u=mt(e)?e.trim():"";if(!u)return Ws.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return u!==(null==(a=this.config)?void 0:a.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+u+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=ul(t.defaults),t.debug=this._checkLocalStorageForDebug(t.debug),this._originalUserConfig=t,this._triggered_notifs=[],t.person_profiles?this._initialPersonProfilesConfig=t.person_profiles:t.process_person&&(this._initialPersonProfilesConfig=t.process_person);var c=ul(t.defaults),d=dl(t),h=Js({},c,d,{name:s,token:u});gt(c.rageclick)&&gt(d.rageclick)&&(h.rageclick=Js({},c.rageclick,d.rageclick)),gt(c.session_recording)&&gt(d.session_recording)&&(h.session_recording=Js({},c.session_recording,d.session_recording)),this.set_config(h),this.config.on_xhr_error&&Ws.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=t.disable_compression?void 0:ho;var _=this._is_persistence_disabled();if(this.persistence=new uo(this.config,_),this.sessionPersistence="sessionStorage"===this.config.persistence||"memory"===this.config.persistence?this.persistence:new uo(i({},this.config,{persistence:"sessionStorage"}),_,!1),this._sessionRegisteredPropertiesStorageKey="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties","memory"!==this.config.persistence&&!_&&Rr._is_supported()){var p=Rr._parse(this._sessionRegisteredPropertiesStorageKey);_t(p)&&p.forEach((e=>{mt(e)&&this._sessionRegisteredPropKeys.add(e)}))}else Rr._remove(this._sessionRegisteredPropertiesStorageKey);var g=i({},this.persistence.props),v=i({},this.sessionPersistence.props);this.register({$initialization_time:(new Date).toISOString()}),this._requestQueue=new ma((e=>this._send_retriable_request(e)),this.config.request_queue_config),this._retryQueue=new ba(this),this.__request_queue=[];var f=this._inCookielessMode();if(f||(this.sessionManager=new Ca(this),this.sessionPropsManager=new xa(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((e,t,i)=>{(null!=i&&i.activityTimeout||null!=i&&i.sessionPastMaximumLength||null!=i&&i.crossTabAdoption)&&this._clearSessionRegisteredProps()}))),this._enrollFeatureFlags(),this.config.__preview_deferred_init_extensions?(Ws.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this._initExtensions(f)}),0)):(Ws.info("Initializing extensions synchronously"),this._initExtensions(f)),r.DEBUG=r.DEBUG||this.config.debug,r.DEBUG&&Ws.info("Starting in debug mode",{this:this,config:t,thisC:i({},this.config),p:g,s:v}),!this.config.identity_distinct_id||null!=(n=t.bootstrap)&&n.distinctID||(t.bootstrap=i({},t.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),void 0!==(null==(o=t.bootstrap)?void 0:o.distinctID)){var m=t.bootstrap.distinctID,y=this.get_distinct_id(),b=this.persistence.get_property(Y);if(t.bootstrap.isIdentifiedID&&null!=y&&y!==m&&b===he)this.identify(m);else if(t.bootstrap.isIdentifiedID&&null!=y&&y!==m&&b===_e)Ws.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var w=this.config.get_device_id(dr()),S=t.bootstrap.isIdentifiedID?w:m;this.persistence.set_property(Y,t.bootstrap.isIdentifiedID?_e:he),this.register({distinct_id:m,$device_id:S})}}if(f)this.register_once({distinct_id:re,$device_id:null},"");else if(!this.get_distinct_id()){var x=this.config.get_device_id(dr());this.register_once({distinct_id:x,$device_id:x},""),this.persistence.set_property(Y,he)}return sr(we,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),t.segment?function(e,t){var i=e.config.segment;if(!i)return t();!function(e,t){var i=e.config.segment;if(!i)return t();var s=i=>{var s=()=>i.anonymousId()||dr();e.config.get_device_id=s,i.id()&&(e.register({distinct_id:i.id(),$device_id:s()}),e.persistence.set_property(Y,_e)),t()},r=i.user();"then"in r&&pt(r.then)?r.then(s):s(r)}(e,(()=>{i.register((e=>{"undefined"!=typeof Promise&&Promise.resolve||Cn.warn("This browser does not have Promise support, and can not use the segment integration");var t=(t,i)=>{if(!i)return t;t.event.userId||t.event.anonymousId===e.get_distinct_id()||(Cn.info("No userId set, resetting PostHog"),e.reset()),t.event.userId&&t.event.userId!==e.get_distinct_id()&&(Cn.info("UserId set, identifying with PostHog"),e.identify(t.event.userId));var s=e.calculateEventProperties(i,t.event.properties);return t.event.properties=Object.assign({},s,t.event.properties),t};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:e=>t(e,e.event.event),page:e=>t(e,fe),identify:e=>t(e,ye),screen:e=>t(e,"$screen")}})(e)).then((()=>{t()}))}))}(this,(()=>this._loaded())):this._loaded(),pt(this.config._onCapture)&&this.config._onCapture!==tl&&(Ws.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(e=>this.config._onCapture(e.event,e)))),this.config.ip&&Ws.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||function(){return Fa.apply(this,arguments)}().then((e=>{e&&this.register({[l]:e})})).catch(tl),this}_isSharedExtension(e){var t=e;return mt(t.name)&&pt(t.setup)}_enrollExtension(e,t){this._isSharedExtension(e)?t.push((()=>{this._getBrowserClientAdapter().add(e).catch(tl)})):this._extensions.push(e)}_enrollFeatureFlags(){var e,t,i,s,r,n,o=null!==(e=null==(t=this.config.__extensionClasses)?void 0:t.featureFlags)&&void 0!==e?e:null==(i=_l.__defaultExtensionClasses)?void 0:i.featureFlags;o&&(this.featureFlags&&this.featureFlags instanceof o||(null==(s=this._featureFlagsReloadingUnsubscribe)||s.call(this),this._featureFlagsReloadingUnsubscribe=void 0,this.featureFlags=new o(this)),pt(this.featureFlags.onReloading)&&pt(this.featureFlags.setup)?this._featureFlagsReloadingUnsubscribe||(this._featureFlagsReloadingUnsubscribe=this.featureFlags.onReloading((()=>{this._internalEventEmitter.emit("featureFlagsReloading",!0)})),this._getBrowserClientAdapter().add(this.featureFlags)):null==(r=(n=this.featureFlags).initialize)||r.call(n))}_initExtensions(e){var t,s,r,n,o,a,l,u=performance.now(),c=i({},_l.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this._extensions.push(this.exceptions=null!==(t=this.exceptions)&&void 0!==t?t:new c.exceptions(this)),c.historyAutocapture&&this._extensions.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this._extensions.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this._extensions.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this._extensions.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this._enrollExtension(this.autocapture=new c.autocapture(this),d),c.surveys&&this._enrollExtension(this.surveys=null!==(s=this.surveys)&&void 0!==s?s:new c.surveys(this),d),c.logs&&this._extensions.push(this.logs=null!==(r=this.logs)&&void 0!==r?r:new c.logs(this)),c.metrics&&this._extensions.push(this.metrics=null!==(n=this.metrics)&&void 0!==n?n:new c.metrics(this)),c.conversations&&this._extensions.push(this.conversations=null!==(o=this.conversations)&&void 0!==o?o:new c.conversations(this)),c.productTours&&this._extensions.push(this.productTours=new c.productTours(this)),c.heatmaps&&this._extensions.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this._extensions.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this._extensions.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this._extensions.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,kn)),c.toolbar&&this._extensions.push(this.toolbar=null!==(a=this.toolbar)&&void 0!==a?a:new c.toolbar(this)),c.experiments&&this._extensions.push(this.experiments=null!==(l=this.experiments)&&void 0!==l?l:new c.experiments(this)),this._extensions.forEach((e=>{e.initialize&&d.push((()=>{null==e.initialize||e.initialize()}))})),d.push((()=>{if(this._pendingRemoteConfig){var e=this._pendingRemoteConfig;this._pendingRemoteConfig=void 0,this._extensions.forEach((t=>null==t.onRemoteConfig?void 0:t.onRemoteConfig(e)))}})),this._processInitTaskQueue(d,u)}_processInitTaskQueue(e,t){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-t>=30&&e.length>0)return void setTimeout((()=>{this._processInitTaskQueue(e,t)}),0);var i=e.shift();if(i)try{i()}catch(e){Ws.error("Error initializing extension:",e)}}var s=Math.round(performance.now()-t);this.register_for_session({[oe]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[ae]:s}),this.config.__preview_deferred_init_extensions&&Ws.info("PostHog extensions initialized ("+s+"ms)")}_onRemoteConfig(e){var t;if(!Ee||!Ee.body)return Ws.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this._onRemoteConfig(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this._pendingRemoteConfig=e),this._lastRemoteConfig=e,this.compression=void 0,e.ok){var i,s=e.config;s.supportedCompression&&!this.config.disable_compression&&(this.compression=ot(s.supportedCompression,ho)?ho:ot(s.supportedCompression,_o)?_o:void 0),null!=(i=s.analytics)&&i.endpoint&&(this.analyticsDefaultEndpoint=s.analytics.endpoint)}this.set_config({person_profiles:this._initialPersonProfilesConfig?this._initialPersonProfilesConfig:pe}),null==(t=this._browserClientAdapter)||t.handleRemoteConfig(e),this._extensions.forEach((t=>null==t.onRemoteConfig?void 0:t.onRemoteConfig(e)))}_loaded(){try{this.config.loaded(this)}catch(e){Ws.critical("`loaded` function failed",e)}if(this._start_queue_if_opted_in(),this.config.internal_or_test_user_hostname&&null!=ke&&ke.hostname){var e=ke.hostname,t=this.config.internal_or_test_user_hostname;("string"==typeof t?e===t:t.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this._inCookielessMode())&&this._captureInitialPageview()}),1),this._remoteConfigLoader=new xo(this),this._remoteConfigLoader.load()}_start_queue_if_opted_in(){var e;this.is_capturing()&&this.config.request_batching&&(null==(e=this._requestQueue)||e.enable())}_dom_loaded(){this.is_capturing()&&Ks(this.__request_queue,(e=>this._send_retriable_request(e))),this.__request_queue=[],this._start_queue_if_opted_in()}_handle_unload(){var e,t,i,s,r;null==(e=this.surveys)||null==e.handlePageUnload||e.handlePageUnload(),null==(t=this.metrics)||t.flush("sendBeacon"),this.config.request_batching?(this._shouldCapturePageleave()&&this.capture(me),null==(i=this.logs)||i.flushLogs("sendBeacon"),null==(s=this._requestQueue)||s.unload(),null==(r=this._retryQueue)||r.unload()):this._shouldCapturePageleave()&&this.capture(me,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?ll?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(null==e.callback||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=i({},this.config.request_headers,e.headers),e.compression="best-available"===e.compression?this.compression:e.compression,(ft(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(e=>{var t,s,r,n=i({},e);n.timeout=n.timeout||6e4;var o,a,l,u,c,d=null!==(t=n.transport)&&void 0!==t?t:"fetch";"sendBeacon"===d&&ft(n.compression)&&n.data&&(n.compression=_o),"POST"===n.method&&n.data&&("capture-body"===n.timestampMode?n.data={api_key:null!==(a=null==(c=(u=(_t(o=n.data)?o:[o]).map((e=>i({},e,e.timestamp instanceof Date&&!isNaN(e.timestamp.getTime())?{timestamp:e.timestamp.toISOString()}:{}))))[0])||null==(l=c.properties)?void 0:l.token)&&void 0!==a?a:null==c?void 0:c.token,batch:u,sent_at:(new Date).toISOString()}:"body"===n.timestampMode&&(n.data=function(e,t){return void 0===t&&(t=(new Date).toISOString()),_t(e)?e.map((e=>i({},e,{sent_at:t}))):i({},e,{sent_at:t})}(n.data))),n.url=ga(n.url,n.method,n.compression,n.timestampMode);var h=va.filter((e=>!n.disableTransport||!e.transport||!n.disableTransport.includes(e.transport))),_=null!==(s=null==(r=function(e,t){for(var i=0;e.length>i;i++)if(e[i].transport===d)return e[i]}(h))?void 0:r.method)&&void 0!==s?s:h[0].method;if(!_)throw new Error("No available transport method");var p=e=>{try{_(e)}catch(e){ha(e)?Ws.warn(e):Ws.error(e),null==n.callback||n.callback({statusCode:0,error:e})}};"sendBeacon"!==d&&n.data&&n.compression===ho&&Fe&&"undefined"!=typeof Promise&&!ra?ca(n).then((e=>{p(e)})).catch((t=>{if(We(t))return ra=!0,void p(i({},n,{compression:void 0,url:ga(e.url,e.method,void 0,e.timestampMode)}));(e=>{if(!e||"object"!=typeof e)return!1;var t="name"in e?String(e.name):"";return We(e)||t===je})(t)&&(ra=!0),p(n)})):_(n)})(i({},e,{callback:t=>{var i,s;this.rateLimiter.checkForLimiting(t),400>t.statusCode||null==(i=(s=this.config).on_request_error)||i.call(s,t),null==e.callback||e.callback(t)}}))):e.fireCallbackOnDrop&&(null==e.callback||e.callback({statusCode:0}))}_send_retriable_request(e){this._retryQueue?this._retryQueue.retriableRequest(e):this._send_request(e)}_execute_array(e){el++;try{var t,i=[],s=[],r=[];Ks(e,(e=>{if(e)if(_t(t=e[0]))r.push(e);else if(pt(e))try{e.call(this)}catch(t){Ws.error("Error executing queued PostHog call",e,t)}else _t(e)&&"alias"===t?i.push(e):_t(e)&&-1!==t.indexOf("capture")&&pt(this[t])?r.push(e):s.push(e)}));var n=function(e,t){Ks(e,(function(e){try{if(_t(e[0])){var i=t;Qs(e,(function(e){i=i[e[0]].apply(i,e.slice(1))}))}else t[e[0]].apply(t,e.slice(1))}catch(t){Ws.error("Error executing queued PostHog call",e,t)}}))};n(i,this),n(s,this),n(r,this)}finally{el--}}push(e){if(el>0&&_t(e)&&mt(e[0])){var t=_l.prototype[e[0]];pt(t)&&t.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,t,s){var r,n,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this._requestQueue){if(this.is_capturing())if(!ft(e)&&mt(e)){this._healCookielessSentinelDistinctId();var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=null!=s&&s.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(null==c||!c.isRateLimited){null!=t&&t.$current_url&&!mt(null==t?void 0:t.$current_url)&&(Ws.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),null==t||delete t.$current_url),"$exception"!==e||null!=s&&s._originatedFromCaptureException||Ws.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=(null==s?void 0:s.timestamp)||d,_=ji(null==s?void 0:s.uuid,dr),p={uuid:_,event:e,properties:this.calculateEventProperties(e,t||{},h,_)};e===fe&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g="$feature_flag_called"===e&&!1===p.properties.$feature_flag_has_experiment&&!0===this.get_property(M);(null==s?void 0:s.$set)&&!g&&(p.$set=null==s?void 0:s.$set);var v=null==s?void 0:s.$unset;v&&(p.$unset=v);var f,m,y,b=g?void 0:this._calculate_set_once_properties(null==s?void 0:s.$set_once,e!==be,e===ye);if(b&&(p.$set_once=b),null!=s&&s._noTruncate||(n=this.config.properties_string_max_length,o=p,a=e=>mt(e)?e.slice(0,n):e,l=new Set,p=function e(t,i){if(t!==Object(t))return a?a(t):t;if(!l.has(t)){var s;if(l.add(t),_t(t))s=[],Ks(t,(t=>{s.push(e(t))}));else{var r={};Qs(t,((t,i)=>{l.has(t)||(r[i]=e(t,i))})),s=r}return s}}(o)),p.timestamp=h,ft(null==s?void 0:s.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=function(e,t){void 0===t&&(t=[]);var i={},s=t=>{void 0!==e[t]&&(i[t]=e[t])};return Be.forEach(s),t.forEach(s),i}(p.properties,ol)),e===fo||e===mo){var w=null==t?void 0:t.$survey_id,S=null==t?void 0:t.$survey_iteration;ja({id:w,current_iteration:S}),p.$set=i({},p.$set,{[(f={id:w,current_iteration:S},m=e===mo?"responded":"dismissed",y="$survey_"+m+"/"+f.id,f.current_iteration&&f.current_iteration>0&&(y="$survey_"+m+"/"+f.id+"/"+f.current_iteration),y)]:!0})}else e===vo&&(p.$set=i({},p.$set,{$survey_last_seen_date:(new Date).toISOString()}));if("product tour shown"===e){var x=null==t?void 0:t.$product_tour_type;x&&(p.$set=i({},p.$set,{["$product_tour_last_seen_date/"+x]:(new Date).toISOString()}))}var E=i({},p.properties.$set,p.$set);if(vt(E)||this.setPersonPropertiesForFlags(E),!wt(this.config.before_send)){var k=this._runBeforeSend(p);if(!k)return;(p=k).uuid=ji(p.uuid,dr)}this._internalEventEmitter.emit("eventCaptured",p);var P=null!==(r=null==s?void 0:s._url)&&void 0!==r?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),C={method:"POST",url:P,data:p,compression:"best-available",timestampMode:"recordings"===(null==s?void 0:s._batchKey)||/\/s\/(?:\?|$)/.test(P)?"body":"capture-body",batchKey:null==s?void 0:s._batchKey,transport:null==s?void 0:s.transport};return!this.config.request_batching||s&&(null==s||!s._batchKey)||null!=s&&s.send_instantly?this._send_retriable_request(C):this._requestQueue.enqueue(C),p}Ws.critical("This capture call is ignored due to client rate limiting.")}}else Ws.error("No event name provided to posthog.capture")}else Ws.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(t=>e(t.event,t)))}_getBrowserClientAdapter(){var e;return null!==(e=this._browserClientAdapter)&&void 0!==e?e:this._browserClientAdapter=new Za(this)}_registerExtensionEventProperties(e){this._extensionEventPropertyProducers.push(e);var t=!0;return()=>{if(t){t=!1;var i=this._extensionEventPropertyProducers.indexOf(e);-1!==i&&this._extensionEventPropertyProducers.splice(i,1)}}}_processCookieIdentityChange(e){var t,i,s;return void 0===e&&(e=!0),!(null==(t=this.persistence)||!t.consumeCookieIdentityChange())&&(this._cachedPersonProperties=null,this.persistence.get_property(Y)===he&&(null==(s=this.sessionPersistence)||s.clear(),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys()),null==(i=this.featureFlags)||i.reset(),e&&this.reloadFeatureFlags(),!0)}calculateEventProperties(e,t,s,n,o){if(s=s||new Date,!this.persistence||!this.sessionPersistence)return t;this.persistence.syncCookieProperties(),this._processCookieIdentityChange();var a=o?void 0:this.persistence.remove_event_timer(e),l=i({},t);if(l.token=this.config.token,l.$config_defaults=this.config.defaults,this._inCookielessMode()&&(l[ne]=!0),"$snapshot"===e){var u=i({},this.persistence.properties(),this.sessionPersistence.properties());return l.distinct_id=u.distinct_id,(!mt(l.distinct_id)&&!St(l.distinct_id)||yt(l.distinct_id))&&Ws.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),l}var c,d=function(e,t,i,s){var n,o,a,l;if(void 0===s&&(s=!1),!Te)return{};var u,c=e?[...Un,...t||[]]:[],d=function(e){for(var t=0;Hi.length>t;t++){var i=Hi[t],s=i[1],r=i[0].exec(e),n=r&&(pt(s)?s(r,e):s);if(n)return n}return["",""]}(Te),h=d[0],_=d[1],p=null!=(u="undefined"!=typeof navigator?navigator:void 0)&&u.brave?{brave:!0}:{},g={};ft(i)||(g.detectGoogleSearchApp=i);var v={},f=null==(n=navigator)||null==(n=n.userAgentData)?void 0:n.platform,m=null==(o=navigator)?void 0:o.maxTouchPoints,y=null==we||null==(a=we.screen)?void 0:a.width,b=null==we||null==(l=we.screen)?void 0:l.height,w=null==we?void 0:we.devicePixelRatio;ft(f)||(v.userAgentDataPlatform=f),ft(m)||(v.maxTouchPoints=m),ft(y)||(v.screenWidth=y),ft(b)||(v.screenHeight=b),ft(w)||(v.devicePixelRatio=w);var S,x,E,k,P,C,I,F,T=Js(er({$os:h,$os_version:_,$browser:Di(Te,navigator.vendor,p,g),$device:Ni(Te),$device_type:(x=Te,E=v,F=Ni(x),F===jt||F===zt||"Kobo"===F||"Kindle Fire"===F||F===yi?Nt:F===li||F===ci||F===ui||F===vi?"Console":F===Vt?"Wearable":F?Bt:"Android"===(null==E?void 0:E.userAgentDataPlatform)&&(null!==(k=null==E?void 0:E.maxTouchPoints)&&void 0!==k?k:0)>0?600>Math.min(null!==(P=null==E?void 0:E.screenWidth)&&void 0!==P?P:0,null!==(C=null==E?void 0:E.screenHeight)&&void 0!==C?C:0)/(null!==(I=null==E?void 0:E.devicePixelRatio)&&void 0!==I?I:1)?Bt:Nt:"Desktop"),$timezone:io(),$timezone_offset:so()}),{$current_url:qn(s?Ui(null==ke?void 0:ke.href):null==ke?void 0:ke.href,c,Wn),$host:null==ke?void 0:ke.host,$pathname:null==ke?void 0:ke.pathname,$raw_user_agent:Te.length>1e3?Te.substring(0,997)+"...":Te,$browser_version:qi(Te,navigator.vendor,p,g),$browser_language:Yn(),$browser_language_prefix:(S=Yn(),"string"==typeof S?S.split("-")[0]:void 0),$screen_height:null==we?void 0:we.screen.height,$screen_width:null==we?void 0:we.screen.width,$viewport_height:null==we?void 0:we.innerHeight,$viewport_width:null==we?void 0:we.innerWidth,$lib:r.LIB_NAME,$lib_version:r.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return r.SDK_DIST_CHANNEL&&(T.$sdk_dist_channel=r.SDK_DIST_CHANNEL),T}(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var h=this.sessionManager.checkAndGetSessionAndWindowId(o,s.getTime(),!0),_=h.windowId;l.$session_id=h.sessionId,l.$window_id=_}this.sessionPropsManager&&Js(l,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&Js(l,this.sessionRecording.sdkDebugProperties),l.$sdk_debug_retry_queue_size=null==(p=this._retryQueue)?void 0:p.length}catch(e){l.$sdk_debug_error_capturing_properties=String(e)}if(this.requestRouter.region===Oa&&(l.$lib_custom_api_host=this.config.api_host),c=e!==fe||o?e!==me||o?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(s):this.pageViewManager.doPageView(s,n),l=Js(l,c),e===fe&&Ee&&(l.title=Ee.title),!ft(a)){var g=s.getTime()-a;l.$duration=parseFloat((g/1e3).toFixed(3))}Te&&this.config.opt_out_useragent_filter&&(l.$browser_type=this._is_bot()?"bot":"browser");var v=this.persistence.properties(),f=this.sessionPersistence.properties();Qs(["$referrer","$referring_domain"],(e=>{e in v&&delete f[e]}));var m={};if(this._extensionEventPropertyProducers.length>0)for(var y of this._extensionEventPropertyProducers.slice())try{Js(m,y())}catch(e){Ws.error("Failed to produce browser extension event properties",e)}(l=Js({},d,v,f,i({},m,l))).$is_identified=this._isIdentified(),_t(this.config.property_denylist)?Qs(this.config.property_denylist,(function(e){delete l[e]})):Ws.error(nl+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var b=this.config.sanitize_properties;b&&(Ws.error(rl),l=b(l,e));var w=this._hasPersonProcessing();return l.$process_person_profile=w,w&&!o&&this._requirePersonProcessing("_calculate_event_properties"),l}_calculate_set_once_properties(e,t,i){var s;if(void 0===t&&(t=!0),void 0===i&&(i=!1),!this.persistence||!this._hasPersonProcessing())return e;if(this._personProcessingSetOncePropertiesSent&&!i)return e;var r=this.persistence.get_initial_props(),n=null==(s=this.sessionPropsManager)?void 0:s.getSetOnceProps(),o=Js({},r,n||{},e||{}),a=this.config.sanitize_properties;return a&&(Ws.error(rl),o=a(o,"$set_once")),t&&(this._personProcessingSetOncePropertiesSent=!0),vt(o)?void 0:o}register(e,t){var i;null==(i=this.persistence)||i.register(e,t)}register_once(e,t,i){var s;null==(s=this.persistence)||s.register_once(e,t,i)}register_for_session(e){var t,i;null==(t=this.persistence)||t.syncCookieProperties(),this._processCookieIdentityChange(),null==(i=this.sessionPersistence)||i.register(e),Object.keys(e).forEach((e=>this._sessionRegisteredPropKeys.add(e))),this._persistSessionRegisteredPropKeys()}unregister(e){var t;null==(t=this.persistence)||t.unregister(e)}unregister_for_session(e){var t;null==(t=this.sessionPersistence)||t.unregister(e),this._sessionRegisteredPropKeys.delete(e),this._persistSessionRegisteredPropKeys()}_register_single(e,t){this.register({[e]:t})}_clearSessionRegisteredProps(){this._sessionRegisteredPropKeys.forEach((e=>{var t;null==(t=this.sessionPersistence)||t.unregister(e)})),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys()}_persistSessionRegisteredPropKeys(){var e;if(this._sessionRegisteredPropertiesStorageKey)if("memory"===this.config.persistence||null!=(e=this.sessionPersistence)&&e._disabled||!Rr._is_supported())Rr._remove(this._sessionRegisteredPropertiesStorageKey);else{var t=[];this._sessionRegisteredPropKeys.forEach((e=>t.push(e))),t.length>0?Rr._set(this._sessionRegisteredPropertiesStorageKey,t):Rr._remove(this._sessionRegisteredPropertiesStorageKey)}}getFeatureFlag(e,t){var i;return null==(i=this.featureFlags)?void 0:i.getFeatureFlag(e,t)}getFeatureFlagPayload(e){var t;return null==(t=this.featureFlags)?void 0:t.getFeatureFlagPayload(e)}getFeatureFlagResult(e,t){var i;return null==(i=this.featureFlags)?void 0:i.getFeatureFlagResult(e,t)}getAllFeatureFlags(){var e,t;return null!==(e=null==(t=this.featureFlags)?void 0:t.getAllFeatureFlags())&&void 0!==e?e:[]}isFeatureEnabled(e,t){var i,s;return null!==(i=null==(s=this.featureFlags)?void 0:s.isFeatureEnabled(e,t))&&void 0!==i?i:null==t?void 0:t.defaultValue}reloadFeatureFlags(){var e;null==(e=this.featureFlags)||e.reloadFeatureFlags()}updateFlags(e,t,i){var s;null==(s=this.featureFlags)||s.updateFlags(e,t,i)}updateEarlyAccessFeatureEnrollment(e,t,i){var s;null==(s=this.featureFlags)||s.updateEarlyAccessFeatureEnrollment(e,t,i)}getEarlyAccessFeatures(e,t,i){var s;return void 0===t&&(t=!1),null==(s=this.featureFlags)?void 0:s.getEarlyAccessFeatures(e,t,i)}on(e,t){return this._internalEventEmitter.on(e,t)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:sl}),()=>{})}onSessionId(e){var t,i;return null!==(t=null==(i=this.sessionManager)?void 0:i.onSessionId(e))&&void 0!==t?t:()=>{}}getSurveys(e,t){void 0===t&&(t=!1),this.surveys?this.surveys.getSurveys(e,t):e([],{isLoaded:!1,error:sl})}getActiveMatchingSurveys(e,t){void 0===t&&(t=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,t):e([],{isLoaded:!1,error:sl})}renderSurvey(e,t){var i;null==(i=this.surveys)||i.renderSurvey(e,t)}displaySurvey(e,t){var i;void 0===t&&(t=Va),null==(i=this.surveys)||i.displaySurvey(e,t)}cancelPendingSurvey(e){var t;null==(t=this.surveys)||t.cancelPendingSurvey(e)}canRenderSurvey(e){var t,i;return null!==(t=null==(i=this.surveys)?void 0:i.canRenderSurvey(e))&&void 0!==t?t:{visible:!1,disabledReason:sl}}canRenderSurveyAsync(e,t){var i,s;return void 0===t&&(t=!1),null!==(i=null==(s=this.surveys)?void 0:s.canRenderSurveyAsync(e,t))&&void 0!==i?i:Promise.resolve({visible:!1,disabledReason:sl})}_validateIdentifyId(e){return!e||yt(e)?(Ws.critical("Unique user id has not been set in posthog.identify"),!1):e===re?(Ws.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(Ws.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,t,i){if(!this.__loaded||!this.persistence)return Ws.uninitializedWarning("posthog.identify");if(St(e)&&(e=e.toString(),Ws.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this._validateIdentifyId(e)&&this._requirePersonProcessing("posthog.identify")){this._healCookielessSentinelDistinctId();var s=this.get_distinct_id(),r=this.persistence.syncCookieProperties()&&this.get_distinct_id()!==s,n=this._processCookieIdentityChange(!1),o=this.persistence._beginCookieSyncSuppression(),l=!1;try{var c=this.get_distinct_id();this.register({$user_id:e}),this.get_property(a)||this.register_once({$had_persisted_distinct_id:!0,$device_id:c},""),e!==c&&e!==this.get_property(u)&&(this.unregister(u),this.register({distinct_id:e}));var d,h=(this.persistence.get_property(Y)||he)===he,_=e!==c,p=!_&&h;if(_&&h)this.persistence.set_property(Y,_e),this.setPersonPropertiesForFlags({$set:t||{},$set_once:i||{}},!1),this.config.cookieWinsOnConflict&&this.persistence._publishSuppressedCookieSnapshot(),this.capture(ye,{distinct_id:e,$anon_distinct_id:c},{$set:t||{},$set_once:i||{}}),this._cachedPersonProperties=$a(e,t,i),null==(d=this.featureFlags)||d.setAnonymousDistinctId(c);else if(p){this.persistence.set_property(Y,_e);var g=t||{},v=i||{};this.setPersonPropertiesForFlags({$set:g,$set_once:v},!1),this.config.cookieWinsOnConflict&&this.persistence._publishSuppressedCookieSnapshot(),this.capture("$set",{$set:g,$set_once:v}),this._cachedPersonProperties=$a(e,t,i)}else(t||i)&&this.setPersonProperties(t,i);_||r||n?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(G)):p&&(t||i)&&this.reloadFeatureFlags(),l=!0}finally{o&&this.persistence._endCookieSyncSuppression(l)}}}setPersonProperties(e,t){if((e||t)&&this._requirePersonProcessing("posthog.setPersonProperties")){var i=$a(this.get_distinct_id(),e,t);this._cachedPersonProperties!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:t||{}},!0),this.capture("$set",{$set:e||{},$set_once:t||{}}),this._cachedPersonProperties=i):Ws.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var t,i=(_t(e)?e:[e]).filter((e=>mt(e)&&e.length>0));0!==i.length&&this._requirePersonProcessing("posthog.unsetPersonProperties")&&(null==(t=this.featureFlags)||t.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this._cachedPersonProperties=null)}group(e,t,s){var r;if(e&&t){null==(r=this.persistence)||r.syncCookieProperties(),this._processCookieIdentityChange();var n=this.getGroups(),o=n[e]!==t;if(o&&this.resetGroupPropertiesForFlags(e),this.register({$groups:i({},n,{[e]:t})}),o||s){var a={$group_type:e,$group_key:t};s&&(a.$group_set=s),this.capture(be,a)}s&&this.setGroupPropertiesForFlags({[e]:s}),o&&!s&&this.reloadFeatureFlags()}else Ws.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,t){var i;void 0===t&&(t=!0),null==(i=this.featureFlags)||i.setPersonPropertiesForFlags(e,t)}resetPersonPropertiesForFlags(e){var t;void 0===e&&(e=!0),null==(t=this.featureFlags)||t.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,t){var i;void 0===t&&(t=!0),this._requirePersonProcessing("posthog.setGroupPropertiesForFlags")&&(null==(i=this.featureFlags)||i.setGroupPropertiesForFlags(e,t))}resetGroupPropertiesForFlags(e){var t;null==(t=this.featureFlags)||t.resetGroupPropertiesForFlags(e)}reset(e){var t=Et(e)?e:null==e?void 0:e.resetDeviceID,i=Et(e)||null==e?void 0:e.bootstrap;this._reset(t,!1,i)}_reset(e,t,s){var r,n,o;if(void 0===t&&(t=!1),Ws.info("reset"),!this.__loaded)return Ws.uninitializedWarning("posthog.reset");var u=null==s?void 0:s.sessionID;this.config.bootstrap=s||(null==(r=this._originalUserConfig)?void 0:r.bootstrap)||{},null==(n=this.featureFlags)||null==n.updateConfig||n.updateConfig(this.config,this._shouldDisableFlags());var c=this.get_property(a),d=this.get_property(l),h=this.get_property(b),_=this.is_capturing();this.consent.reset(),t||!_||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after.");var p=null==(o=this.persistence)||null==o._beginCookieSyncSuppression?void 0:o._beginCookieSyncSuppression(),g=!1;try{var v,f,m,y,w,S,x,E,k,P,C,I,F,T;if(null==(v=this.persistence)||v.clear(),null==(f=this.sessionPersistence)||f.clear(),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys(),ft(h)||null==(C=this.persistence)||C.register({[b]:h}),null==(m=this.surveys)||m.reset(),null==(y=this._remoteConfigLoader)||y.stop(),null==(w=this.featureFlags)||w.reset(),null==(S=this.conversations)||S.reset(),null==(x=this.logs)||x.reset(),null==(E=this.metrics)||E.reset(),null==(k=this.persistence)||k.set_property(Y,he),null==(P=this.sessionManager)||P.resetSessionId(),this._cachedPersonProperties=null,this.config.cookieless_mode===de)this.register_once({distinct_id:re,$device_id:null},"");else{var R=this.config.get_device_id(dr());this.register_once({distinct_id:R,$device_id:e?R:c},""),e||ft(d)||this.register({[l]:d})}if(this.register({$last_posthog_reset:(new Date).toISOString()},1),s)if(void 0===s.distinctID||this._inCookielessMode()||(null==(T=this.persistence)||T.set_property(Y,s.isIdentifiedID?_e:he),this.register({distinct_id:s.distinctID})),null==(I=this.featureFlags)||I.initialize(),!(ft(u)||null!=(F=this.sessionManager)&&F.setBootstrapSessionId(u,!0))){var A=i({},s);delete A.sessionID,this.config.bootstrap=A}delete this.config.identity_distinct_id,delete this.config.identity_hash,g=!0}finally{var L;p&&(null==(L=this.persistence)||null==L._endCookieSyncSuppression||L._endCookieSyncSuppression(g))}this.reloadFeatureFlags()}shutdown(e){var i=this;return t((function*(){var e,t,s,r,n,o;if(i.__loaded){null==(e=i._remoteConfigLoader)||e.stop(),i._getBrowserClientAdapter().dispose(),null==(t=i.sessionRecording)||t.dispose(),null==(s=i.logs)||s.flushLogs("sendBeacon"),null==(r=i.metrics)||r.flush("sendBeacon"),null==(n=i._requestQueue)||n.unload(),null==(o=i._retryQueue)||o.unload();try{var a;null==(a=i.featureFlags)||a.destroy()}catch(e){Ws.error("Error while destroying feature flags",e)}}else Ws.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,t){var i;this.config.identity_distinct_id=e,this.config.identity_hash=t,this.alias(e),null==(i=this.conversations)||i._onIdentityChanged()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,null==(e=this.conversations)||e._onIdentityCleared()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,t;return null!==(e=null==(t=this.sessionManager)?void 0:t.checkAndGetSessionAndWindowId(!0).sessionId)&&void 0!==e?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var t=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=t.sessionStartTimestamp,s=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+t.sessionId);if(null!=e&&e.withTimestamp&&i){var r,n=null!==(r=e.timestampLookBack)&&void 0!==r?r:10;if(!i)return s;s+="?t="+Math.max(Math.floor(((new Date).getTime()-i)/1e3)-n,0)}return s}alias(e,t){return e===this.get_property(n)?(Ws.critical("Attempting to create alias for existing People user - aborting."),-2):this._requirePersonProcessing("posthog.alias")?(ft(t)&&(t=this.get_distinct_id()),e!==t?(this._register_single(u,e),this.capture("$create_alias",{alias:e,distinct_id:t})):(Ws.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var t=i({},this.config);if(gt(e)){var s,n,o,a,l,u,c,d,h,_,p,g;Js(this.config,dl(e));var v=this._is_persistence_disabled();null==(s=this.persistence)||s.update_config(this.config,t,v),this.sessionPersistence="sessionStorage"===this.config.persistence||"memory"===this.config.persistence?this.persistence:new uo(i({},this.config,{persistence:"sessionStorage"}),v,!1);var f,m=this._checkLocalStorageForDebug(this.config.debug);Et(m)&&(this.config.debug=m),Et(this.config.debug)&&(this.config.debug?(r.DEBUG=!0,fr._is_supported()&&fr._set("ph_debug",!0),Ws.info("set_config",{config:e,oldConfig:t,newConfig:i({},this.config)})):(r.DEBUG=!1,fr._is_supported()&&fr._remove("ph_debug"))),null==(n=this.featureFlags)||null==n.updateConfig||n.updateConfig(this.config,this._shouldDisableFlags()),null==(o=this.exceptionObserver)||o.onConfigChange(),null==(a=this.exceptions)||a.onConfigChange(),null==(l=this.sessionRecording)||l.startIfEnabledOrStop(),null==(u=this.tracingHeaders)||u.startIfEnabledOrStop(),null==(c=this.autocapture)||c.startIfEnabled(),null==(d=this.heatmaps)||d.startIfEnabled(),("capture_pageview"in e||"disable_capture_url_hashes"in e)&&(null==(f=this.historyAutocapture)||f.startIfEnabledOrStop()),null==(h=this.exceptionObserver)||h.startIfEnabledOrStop(),null==(_=this.deadClicksAutocapture)||_.startIfEnabledOrStop(),null==(p=this.surveys)||p.loadIfEnabled(),this._sync_opt_out_with_persistence(),null==(g=this.externalIntegrations)||g.startIfEnabledOrStop()}}_overrideSDKInfo(e,t){r.LIB_NAME=e,r.LIB_VERSION=t}startSessionRecording(e){var t,i,s,r,n,o=!0===e,a={sampling:o||!(null==e||!e.sampling),linked_flag:o||!(null==e||!e.linked_flag),url_trigger:o||!(null==e||!e.url_trigger),event_trigger:o||!(null==e||!e.event_trigger)};Object.values(a).some(Boolean)&&(null==(t=this.sessionManager)||t.checkAndGetSessionAndWindowId(),a.sampling&&(null==(i=this.sessionRecording)||i.overrideSampling()),a.linked_flag&&(null==(s=this.sessionRecording)||s.overrideLinkedFlag()),a.url_trigger&&(null==(r=this.sessionRecording)||r.overrideTrigger("url")),a.event_trigger&&(null==(n=this.sessionRecording)||n.overrideTrigger("event")));this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!(null==(e=this.sessionRecording)||!e.started)}captureException(e,t){if(this.exceptions){var s=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:s});return this.exceptions.sendExceptionEvent(i({},r,t))}}addExceptionStep(e,t){var i;null==(i=this.exceptions)||i.addExceptionStep(e,t)}captureLog(e){var t;null==(t=this.logs)||t.captureLog(e)}get logger(){var e,t;return null!==(e=null==(t=this.logs)?void 0:t.logger)&&void 0!==e?e:_l._noopLogger}startExceptionAutocapture(e){this.set_config({capture_exceptions:null==e||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var t,i;return null!==(t=null==(i=this.toolbar)?void 0:i.loadToolbar(e))&&void 0!==t&&t}get_property(e){var t;return null==(t=this.persistence)?void 0:t.props[e]}getSessionProperty(e){var t;return null==(t=this.sessionPersistence)?void 0:t.props[e]}toString(){var e,t=null!==(e=this.config.name)&&void 0!==e?e:al;return t!==al&&(t=al+"."+t),t}_isIdentified(){var e,t;return(null==(e=this.persistence)?void 0:e.get_property(Y))===_e||(null==(t=this.sessionPersistence)?void 0:t.get_property(Y))===_e}_hasPersonProcessing(){var e,t;return!("never"===this.config.person_profiles||this.config.person_profiles===pe&&!this._isIdentified()&&vt(this.getGroups())&&(null==(e=this.persistence)||null==(e=e.props)||!e[u])&&(null==(t=this.persistence)||null==(t=t.props)||!t[se]))}_shouldCapturePageleave(){return!0===this.config.capture_pageleave||"if_capture_pageview"===this.config.capture_pageleave&&!!this.config.capture_pageview}createPersonProfile(){this._hasPersonProcessing()||this._requirePersonProcessing("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this._requirePersonProcessing("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}_requirePersonProcessing(e){return"never"===this.config.person_profiles?(Ws.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this._register_single(se,!0),!0)}_is_persistence_disabled(){if("always"===this.config.cookieless_mode)return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==ce)}_sync_opt_out_with_persistence(){var e,t,i,s,r=this._is_persistence_disabled();return(null==(e=this.persistence)?void 0:e._disabled)!==r&&(null==(i=this.persistence)||i.set_disabled(r)),(null==(t=this.sessionPersistence)?void 0:t._disabled)!==r&&(null==(s=this.sessionPersistence)||s.set_disabled(r)),r&&(this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys()),r}opt_in_capturing(e){var t;if(this.config.cookieless_mode!==de){if(this._inCookielessMode()){var i,s,r,n,o;this._reset(!0,!0),null==(i=this.sessionManager)||i.destroy(),null==(s=this.pageViewManager)||s.destroy(),this.sessionManager=new Ca(this),this.pageViewManager=new Rn(this),this.persistence&&(this.sessionPropsManager=new xa(this,this.sessionManager,this.persistence));var a,l=null!==(r=null==(n=this.config.__extensionClasses)?void 0:n.sessionRecording)&&void 0!==r?r:null==(o=_l.__defaultExtensionClasses)?void 0:o.sessionRecording;l&&(this.sessionRecording=this._replaceExtension(this.sessionRecording,new l(this)),this._lastRemoteConfig&&(null==(a=this.sessionRecording)||null==a.onRemoteConfig||a.onRemoteConfig(this._lastRemoteConfig)))}var u,c;this.consent.optInOut(!0),this._sync_opt_out_with_persistence(),this._start_queue_if_opted_in(),null==(t=this.sessionRecording)||t.startIfEnabledOrStop(),this.config.cookieless_mode==ce&&(null==(u=this.surveys)||u.loadIfEnabled()),(ft(null==e?void 0:e.captureEventName)||null!=e&&e.captureEventName)&&this.capture(null!==(c=null==e?void 0:e.captureEventName)&&void 0!==c?c:"$opt_in",null==e?void 0:e.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this._captureInitialPageview()}else Ws.warn(il)}opt_out_capturing(){var e,t,i;this.config.cookieless_mode!==de?(this.config.cookieless_mode===ce&&this.consent.isOptedIn()&&this._reset(!0,!0),this.consent.optInOut(!1),this._sync_opt_out_with_persistence(),this.config.cookieless_mode===ce&&(this.register({distinct_id:re,$device_id:null}),null==(e=this.sessionRecording)||e.stopRecording(),this.sessionRecording=void 0,null==(t=this.sessionManager)||t.destroy(),null==(i=this.pageViewManager)||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this._captureInitialPageview(),this._start_queue_if_opted_in())):Ws.warn(il)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return 1===e?"granted":0===e?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===de||(this.config.cookieless_mode===ce?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this._sync_opt_out_with_persistence()}_is_bot(){return xe?Ia(xe,this.config.custom_blocked_useragents):void 0}_captureInitialPageview(){Ee&&("visible"===Ee.visibilityState?this._initialPageviewCaptured||(this._initialPageviewCaptured=!0,this.capture(fe,{title:Ee.title},{send_instantly:!0}),this._visibilityStateListener&&(Ee.removeEventListener(ge,this._visibilityStateListener),this._visibilityStateListener=null)):this._visibilityStateListener||(this._visibilityStateListener=this._captureInitialPageview.bind(this),sr(Ee,ge,this._visibilityStateListener)))}debug(e){!1===e?(null==we||we.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(null==we||we.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}_shouldDisableFlags(){var e=this._originalUserConfig||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:!1!==this.config.advanced_disable_flags?!!this.config.advanced_disable_flags:!0===this.config.advanced_disable_decide?(Ws.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):function(e,t,i,s,r){var n=t in e&&!wt(e[t]),o=i in e&&!wt(e[i]);return n?e[t]:!!o&&(r&&r.warn("Config field '"+i+"' is deprecated. Please use '"+t+"' instead. The old field will be removed in a future major version."),e[i])}(e,"advanced_disable_flags","advanced_disable_decide",0,Ws)}_runBeforeSend(e){var t;if(wt(this.config.before_send))return e;var i=Object.keys(null!==(t=e.properties)&&void 0!==t?t:{}).filter(Ct),s=_t(this.config.before_send)?this.config.before_send:[this.config.before_send],r=e;for(var n of s)try{if(r=n(r),wt(r)){var o="Event '"+e.event+"' was rejected in beforeSend function";return Pt(e.event)?Ws.warn(o+". This can cause unexpected behavior."):Ws.info(o),null}r.properties&&!vt(r.properties)||Ws.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}catch(t){return Ws.error("Error in beforeSend function for event '"+e.event+"':",t),null}for(var a of i)if(r.properties&&wt(r.properties[a]))return Ws.warn("Event '"+e.event+"' had its '"+a+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return r}getPageViewId(){var e;return null==(e=this.pageViewManager._currentPageview)?void 0:e.pageViewId}captureTraceFeedback(e,t){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:t})}captureTraceMetric(e,t,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:t,$ai_metric_value:String(i)})}_checkLocalStorageForDebug(e){var t=Et(e)&&!e,i=fr._is_supported()&&"true"===fr._get("ph_debug");return!t&&(!!i||e)}}_l.__defaultExtensionClasses={},_l._noopLogger=(()=>{var e=()=>{};return{trace:e,debug:e,info:e,warn:e,error:e,fatal:e}})(),function(e,t){for(var i=0;t.length>i;i++)e.prototype[t[i]]=Xs(e.prototype[t[i]])}(_l,["identify"]);class pl{constructor(e){this.disabled=!1===e;var t=gt(e)?e:{};this.thresholdPx=t.threshold_px||30,this.timeoutMs=t.timeout_ms||1e3,this.clickCount=t.click_count||3,this.clicks=[]}isRageClick(e,t,i){if(this.disabled)return!1;var s=this.clicks[this.clicks.length-1];if(s&&Math.abs(e-s.x)+Math.abs(t-s.y)<this.thresholdPx&&this.timeoutMs>i-s.timestamp){if(this.clicks.push({x:e,y:t,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:t,timestamp:i}];return!1}}var gl="$copy_autocapture",vl=Gs("[AutoCapture]");function fl(e,t){return t.length>e?t.slice(0,e)+"...":t}function ml(e){if(e.previousElementSibling)return e.previousElementSibling;var t=e;do{t=t.previousSibling}while(t&&!qr(t));return t}function yl(e,t){var s,r,n=t.e,o=t.maskAllElementAttributes,a=t.maskAllText,l=t.elementAttributeIgnoreList,u=t.elementsChainAsString,c=t.disableCaptureUrlHashes;if(!qr(e))return{props:{}};for(var d=[e],h=new Set([e]),_=e;_.parentNode&&!Hr(_,"body")&&jr>d.length;)if(zr(_.parentNode)){var p=_.parentNode.host;if(h.has(p))break;h.add(p),d.push(p),_=p}else{if(!qr(_.parentNode))break;if(h.has(_.parentNode))break;h.add(_.parentNode),d.push(_.parentNode),_=_.parentNode}var g,v,f=[],m={},y=!1,b=!1;if(Qs(d,(e=>{var t=un(e);if(Hr(e,"a")){var i=e.getAttribute("href");y=!!(t&&i&&mn(i))&&(c?Ui(i):i)}ot(Wr(e),"ph-no-capture")&&(b=!0),f.push(function(e,t,i,s,r){void 0===r&&(r=!1);var n=e.tagName.toLowerCase(),o={tag_name:n};Jr.indexOf(n)>-1&&!i&&(o.$el_text="a"===n.toLowerCase()||"button"===n.toLowerCase()?fl(1024,yn(e)):fl(1024,Kr(e)));var a=Wr(e);a.length>0&&(o.classes=a.filter((function(e){return""!==e}))),Qs(e.attributes,(function(i){var n;if((!cn(e)||-1!==["name","id","class","aria-label"].indexOf(i.name))&&(null==s||!s.includes(i.name))&&!t&&mn(i.value)&&(!mt(n=i.name)||"_ngcontent"!==n.substring(0,10)&&"_nghost"!==n.substring(0,7))){var a=i.value;"class"===i.name&&(a=Ur(a).join(" ")),o["attr__"+i.name]=fl(1024,"href"===i.name&&r?Ui(a):a)}}));for(var l=1,u=1,c=e;c=ml(c);)l++,c.tagName===e.tagName&&u++;return o.nth_child=l,o.nth_of_type=u,o}(e,o,a,l,c));var s=function(e){if(!un(e))return{};var t={};return Qs(e.attributes,(function(e){if(e.name&&0===e.name.indexOf("data-ph-capture-attribute")){var i=e.name.replace("data-ph-capture-attribute-",""),s=e.value;i&&s&&mn(s)&&(t[i]=s)}})),t}(e);Js(m,s)})),b)return{props:{},explicitNoCapture:b};if(a||(f[0].$el_text=Hr(e,"a")||Hr(e,"button")?yn(e):Kr(e)),y){var w,S;f[0].attr__href=y;var x=null==(w=Dn(y))?void 0:w.host,E=null==we||null==(S=we.location)?void 0:S.host;x&&E&&x!==E&&(g=y)}return{props:Js({$event_type:n.type,$ce_version:1},u?{}:{$elements:f},{$elements_chain:(v=f,function(e){return e.map((e=>{var t,s,r="";if(e.tag_name&&(r+=e.tag_name),e.attr_class)for(var n of(e.attr_class.sort(),e.attr_class))r+="."+n.replace(/"/g,"");var o=i({},e.text?{text:e.text}:{},{"nth-child":null!==(t=e.nth_child)&&void 0!==t?t:0,"nth-of-type":null!==(s=e.nth_of_type)&&void 0!==s?s:0},e.href?{href:e.href}:{},e.attr_id?{attr_id:e.attr_id}:{},e.attributes),a={};return Ys(o).sort(((e,t)=>e[0].localeCompare(t[0]))).forEach((e=>{var t=e[1];return a[wn(e[0].toString())]=wn(t.toString())})),(r+=":")+Ys(a).map((e=>e[0]+'="'+e[1]+'"')).join("")})).join(";")}(function(e){return e.map((e=>{var t,i,s={text:null==(t=e.$el_text)?void 0:t.slice(0,400),tag_name:e.tag_name,href:null==(i=e.attr__href)?void 0:i.slice(0,2048),attr_class:Sn(e),attr_id:e.attr__id,nth_child:e.nth_child,nth_of_type:e.nth_of_type,attributes:{}};return Ys(e).filter((e=>0===e[0].indexOf("attr__"))).forEach((e=>s.attributes[e[0]]=e[1])),s}))}(v)))},null!=(s=f[0])&&s.$el_text?{$el_text:null==(r=f[0])?void 0:r.$el_text}:{},g&&"click"===n.type?{$external_click_url:g}:{},m)}}class bl{constructor(e){this.name="autocapture",this._initialized=!1,this._isDisabledServerSide=null,this._hasReceivedConfigResponse=!1,this._elementsChainAsString=!1,this._config={enabled:!1,rageclick:!1,maskAllElementAttributes:!1,maskAllText:!1,disableCaptureUrlHashes:!1,remoteRequestsDisabled:!1},this._disposed=!1,this._configSource=e,this._configSource.refresh(this._config),this.rageclicks=new pl(this._config.rageclick),this._elementSelectors=null}setup(e){this._compileUrlPatterns(),this._client=e;var t=e.onRemoteConfig(this.onRemoteConfig.bind(this));this._disposed?t.dispose():(this._remoteConfigSubscription=t,this.startIfEnabled())}dispose(){var e;this._disposed||(this._disposed=!0,this._client=void 0,null==(e=this._remoteConfigSubscription)||e.dispose(),this._remoteConfigSubscription=void 0,this._removeDomEventHandlers())}_refreshConfig(){return this._configSource.refresh(this._config),this._config}_compileUrlPatterns(){var e,t;return this._refreshConfig(),this._config.url_allowlist=null==(e=this._config.url_allowlist)?void 0:e.map((e=>new RegExp(e))),this._config.url_ignorelist=null==(t=this._config.url_ignorelist)?void 0:t.map((e=>new RegExp(e))),this._config}_addDomEventHandlers(){if(this.isBrowserSupported()){if(we&&Ee){var e=this._domEventHandler=e=>{e=e||(null==we?void 0:we.event);try{this._captureEvent(e)}catch(e){vl.error("Failed to capture event",e)}};if(sr(Ee,"submit",e,{capture:!0}),sr(Ee,"change",e,{capture:!0}),sr(Ee,"click",e,{capture:!0}),this._refreshConfig().capture_copied_text){var t=this._copiedTextHandler=e=>{e=e||(null==we?void 0:we.event);try{this._captureEvent(e,gl)}catch(e){vl.error("Failed to capture copy/cut event",e)}};sr(Ee,"copy",t,{capture:!0}),sr(Ee,"cut",t,{capture:!0})}}}else vl.info("Disabling Automatic Event Collection because this browser is not supported")}_removeDomEventHandlers(){this._domEventHandler&&(null==Ee||Ee.removeEventListener("submit",this._domEventHandler,!0),null==Ee||Ee.removeEventListener("change",this._domEventHandler,!0),null==Ee||Ee.removeEventListener("click",this._domEventHandler,!0),this._domEventHandler=void 0),this._copiedTextHandler&&(null==Ee||Ee.removeEventListener("copy",this._copiedTextHandler,!0),null==Ee||Ee.removeEventListener("cut",this._copiedTextHandler,!0),this._copiedTextHandler=void 0),this._initialized=!1}startIfEnabled(){!this._disposed&&this._client&&this.isEnabled&&!this._initialized&&(this._addDomEventHandlers(),this._initialized=!0)}onRemoteConfig(e){if(!this._disposed)if(this._hasReceivedConfigResponse=!0,e.ok){var t=e.config;t.elementsChainAsString&&(this._elementsChainAsString=t.elementsChainAsString);var i,s=t.autocapture_opt_out;Et(s)&&(null==(i=this._client)||i.kv.set(d,s),this._isDisabledServerSide=s),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(e){this._elementSelectors=e}getElementSelectors(e){var t,i=[];return null==(t=this._elementSelectors)||t.forEach((t=>{var s=null==Ee?void 0:Ee.querySelectorAll(t);null==s||s.forEach((s=>{e===s&&i.push(t)}))})),i}get isEnabled(){var e,t;if(this._disposed)return!1;var i=null==(e=this._client)?void 0:e.kv.get(d),s=this._isDisabledServerSide,r=this._refreshConfig(),n=r.remoteRequestsDisabled&&!this._hasReceivedConfigResponse;if(bt(s)&&!Et(i)&&!n)return!1;var o=null!==(t=this._isDisabledServerSide)&&void 0!==t?t:!!i;return!!r.enabled&&!o}_captureEvent(e,t){if(void 0===t&&(t="$autocapture"),this.isEnabled){var i=Qr(e);Nr(i)&&(i=i.parentNode||null);var s,r=this._compileUrlPatterns();"$autocapture"===t&&"click"===e.type&&e instanceof MouseEvent&&r.rageclick&&null!=(s=this.rageclicks)&&s.isRageClick(e.clientX,e.clientY,e.timeStamp||(new Date).getTime())&&on(i,r.rageclick)&&this._captureEvent(e,"$rageclick");var n=t===gl;if(i&&function(e,t,i,s,r,n){var o;if(!we||an(e))return!1;if(null!=i&&i.url_allowlist&&!Vr(i.url_allowlist,n))return!1;if(null!=i&&i.url_ignorelist&&Vr(i.url_ignorelist,n))return!1;if(null!=i&&i.dom_event_allowlist){var a=i.dom_event_allowlist;if(a&&!a.some((e=>t.type===e)))return!1}var l=ln(e,s),u=l.parentIsUsefulElement,c=l.targetElementList;if(!function(e,t){var i=null==t?void 0:t.element_allowlist;if(ft(i))return!0;var s,r=function(e){if(i.some((t=>e.tagName.toLowerCase()===t)))return{v:!0}};for(var n of e)if(s=r(n))return s.v;return!1}(c,i))return!1;if(!Yr(c,null==i?void 0:i.css_selector_allowlist))return!1;if(Yr(c,null!==(o=null==i?void 0:i.css_selector_ignorelist)&&void 0!==o?o:Xr))return!1;try{var d=we.getComputedStyle(e);if(d&&"pointer"===d.getPropertyValue("cursor")&&"click"===t.type)return!0}catch(e){}var h=e.tagName.toLowerCase();switch(h){case"html":return!1;case"form":return(r||["submit"]).indexOf(t.type)>=0;case"input":case"select":case"textarea":return(r||["change","click"]).indexOf(t.type)>=0;default:return u?(r||["click"]).indexOf(t.type)>=0:(r||["click"]).indexOf(t.type)>=0&&(Jr.indexOf(h)>-1||"true"===e.getAttribute("contenteditable"))}}(i,e,r,n,n?["copy","cut"]:void 0,{config:{get_current_url:r.getCurrentUrl}})){var o,a=yl(i,{e:e,maskAllElementAttributes:r.maskAllElementAttributes,maskAllText:r.maskAllText,elementAttributeIgnoreList:r.element_attribute_ignorelist,elementsChainAsString:this._elementsChainAsString,disableCaptureUrlHashes:r.disableCaptureUrlHashes}),l=a.props;if(a.explicitNoCapture)return!1;var u=this.getElementSelectors(i);if(u&&u.length>0&&(l.$element_selectors=u),t===gl){var c,d=Gr(null==we||null==(c=we.getSelection())?void 0:c.toString()),h=e.type||"clipboard";if(!d)return!1;l.$selected_content=d,l.$copy_type=h}return null==(o=this._client)||o.capture(t,l).catch((e=>vl.error("Failed to capture event",e))),!0}}}isBrowserSupported(){return pt(null==Ee?void 0:Ee.querySelectorAll)}}class wl{constructor(e){this._instance=e}refresh(e){var t=this._instance.config,i=gt(t.autocapture)?t.autocapture:void 0;e.enabled=!!t.autocapture,e.rageclick=t.rageclick,e.maskAllElementAttributes=t.mask_all_element_attributes,e.maskAllText=t.mask_all_text,e.disableCaptureUrlHashes=t.disable_capture_url_hashes,e.getCurrentUrl=t.get_current_url,e.remoteRequestsDisabled=this._instance._shouldDisableFlags(),e.url_allowlist=null==i?void 0:i.url_allowlist,e.url_ignorelist=null==i?void 0:i.url_ignorelist,e.dom_event_allowlist=null==i?void 0:i.dom_event_allowlist,e.element_allowlist=null==i?void 0:i.element_allowlist,e.css_selector_allowlist=null==i?void 0:i.css_selector_allowlist,e.css_selector_ignorelist=null==i?void 0:i.css_selector_ignorelist,e.element_attribute_ignorelist=null==i?void 0:i.element_attribute_ignorelist,e.capture_copied_text=null==i?void 0:i.capture_copied_text}}var Sl=Gs("[ExceptionAutocapture]"),xl=()=>{},El=Gs("[TracingHeaders]"),kl=Gs("[Web Vitals]"),Pl=9e5,Cl=["CLS","FCP","INP","LCP"],Il=["INP","LCP"],Fl=["interactionTarget","interactionType","inputDelay","processingDuration","presentationDelay","loadState","target","url","timeToFirstByte","resourceLoadDelay","resourceLoadDuration","elementRenderDelay","largestShiftTarget","largestShiftTime","largestShiftValue","firstByteToFCP"],Tl="disabled",Rl="lazy_loading",Al="awaiting_config",Ll="missing_config";Gs("[SessionRecording]"),Gs("[SessionRecording]");var Ml="[SessionRecording]",$l=Gs(Ml),Ol=Gs("[Heatmaps]");function Dl(e){return gt(e)&&"clientX"in e&&"clientY"in e&&St(e.clientX)&&St(e.clientY)}var Bl=Gs("[Product Tours]"),ql=e=>{var t;return!e.config.disable_product_tours&&!(null==(t=e.persistence)||!t.get_property(m))},Hl=["$set_once","$set"],Nl=Gs("[SiteApps]"),zl="Error while initializing PostHog app with config id ",jl=(e,t)=>null!=e&&e.then?e.then(t):t(e),Ul="SDK is not enabled or survey functionality is not yet loaded",Vl="Disabled. Not loading surveys.";class Wl{constructor(e,t){this.name="surveys",this._surveyEventReceiver=null,this._surveyManager=null,this._isInitializingSurveys=!1,this._surveyCallbacks=[],this._getSurveysInFlightPromise=null,this._lastSurveyRefreshFailedAt=null,this._disposed=!1,this._renderTimeouts=new Set,this.onRemoteConfig=e=>{if(!this._disposed&&!this._config.disableSurveys){if(!e.ok)return Na.warn("Remote config unavailable. Not loading surveys.");var t=e.config.surveys;if(wt(t))return Na.warn("Flags not loaded yet. Not loading surveys.");this._isSurveysEnabled=Et(t)?t:t.length>0,Na.info("flags response received, isSurveysEnabled: "+this._isSurveysEnabled),this.loadIfEnabled()}},this._configSource=e,this._initialClientState=t}setup(e){if(!this._disposed)return this._initializingClient=e,jl(e.kv.initialize(),(()=>{if(this._initializingClient===e&&!this._disposed){this._initializingClient=void 0,this._client=e;var t=e.onRemoteConfig(this.onRemoteConfig);this._disposed?t.dispose():(this._remoteConfigSubscription=t,this.loadIfEnabled())}}))}dispose(){var e,t,i;this._disposed||(this._disposed=!0,this._initializingClient=void 0,this._client=void 0,null==(e=this._remoteConfigSubscription)||e.dispose(),this._remoteConfigSubscription=void 0,null==(t=this._surveyEventReceiver)||t.dispose(),this._surveyEventReceiver=null,null==(i=this._surveyManager)||null==i.dispose||i.dispose(),this._surveyManager=null,this._surveyCallbacks=[],this._getSurveysInFlightPromise=null,this._renderTimeouts.forEach((e=>clearTimeout(e))),this._renderTimeouts.clear())}get _config(){return this._configSource.get()}initialize(){this.loadIfEnabled()}reset(){try{var e;null==(e=this._surveyEventReceiver)||e.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var t=[],i=0;i<localStorage.length;i++){var s=localStorage.key(i);(null!=s&&s.startsWith(za)||null!=s&&s.startsWith("inProgressSurvey_"))&&t.push(s)}t.forEach((e=>localStorage.removeItem(e)))}catch(e){}}loadIfEnabled(){if(!this._disposed&&this._client){var e=this._config;if(!this._surveyManager)if(this._isInitializingSurveys)Na.info("Already initializing surveys, skipping...");else if(e.disableSurveys)Na.info(Vl);else if(e.cookielessMode&&this._configSource.isOptedOut())Na.info("Not loading surveys in cookieless mode without consent.");else{var t=this._configSource.getExtensions();if(t){if(!ft(this._isSurveysEnabled)||e.advancedEnableSurveys){var i=this._isSurveysEnabled||e.advancedEnableSurveys;this._isInitializingSurveys=!0;try{var s=t.generateSurveys;if(s)return this._completeSurveyInitialization(s,i),void(this._isInitializingSurveys=!1);var r=t.loadExternalDependency;if(!r)return this._handleSurveyLoadError(ue),void(this._isInitializingSurveys=!1);r((e=>{try{if(this._disposed)return;var t=this._configSource.getExtensions();e||null==t||!t.generateSurveys?this._handleSurveyLoadError("Could not load surveys script",e):this._completeSurveyInitialization(t.generateSurveys,i)}finally{this._isInitializingSurveys=!1}}))}catch(e){throw this._isInitializingSurveys=!1,this._handleSurveyLoadError("Error initializing surveys",e),e}}}else Na.error("PostHog Extensions not found.")}}}_completeSurveyInitialization(e,t){this._disposed||(this._surveyManager=e(t),this._surveyEventReceiver=this._configSource.createEventReceiver(),Na.info("Surveys loaded successfully"),this._notifySurveyCallbacks({isLoaded:!0}))}_handleSurveyLoadError(e,t){Na.error(e,t),this._notifySurveyCallbacks({isLoaded:!1,error:e})}onSurveysLoaded(e){return this._surveyCallbacks.push(e),this._surveyManager&&this._notifySurveyCallbacks({isLoaded:!0}),()=>{this._surveyCallbacks=this._surveyCallbacks.filter((t=>t!==e))}}getSurveys(e,t){var i;void 0===t&&(t=!1);var s=null!==(i=this._client)&&void 0!==i?i:this._initialClientState;if(s&&!this._disposed){if(this._config.disableSurveys)return Na.info(Vl),e([]);var r=s.kv.get(N);if(r&&!t)return e(r,{isLoaded:!0}),void(this._shouldBackgroundRefreshSurveys()&&this.getSurveys((()=>{}),!0));if(this._getSurveysInFlightPromise)this._getSurveysInFlightPromise.then((t=>{this._disposed||e(t.surveys,t.context)})).catch((e=>Na.error("Error in survey callback",e)));else{var n=this._sendSurveysRequest("/api/surveys/",{method:"GET",query:{token:s.projectToken},sentAt:"query",timeoutMs:this._config.requestTimeoutMs}).then((e=>{try{return this._handleSurveyResponse(s,e)}catch(e){return Na.error("Error processing surveys response",e),this._handleSurveyResponse(s,{statusCode:0,error:e})}}),(e=>this._handleSurveyResponse(s,{statusCode:0,error:e})));this._getSurveysInFlightPromise=n;var o=()=>{this._getSurveysInFlightPromise===n&&(this._getSurveysInFlightPromise=null)};n.then((t=>{o(),this._disposed||e(t.surveys,t.context)}),o).catch((e=>Na.error("Error in survey callback",e)))}}}_sendSurveysRequest(e,t){var i=this._client;return i?i.sendRequest(e,t):new Promise((e=>e({statusCode:0,error:new Error(Ul)})))}_handleSurveyResponse(e,t){if(this._disposed)return{surveys:[],context:{isLoaded:!1,error:Ul}};var i=t.statusCode;if(200!==i||!t.json){var s="Surveys API could not be loaded, status: "+i;return 0!==i?Na.error(s):t.error||Na.warn(s),this._lastSurveyRefreshFailedAt=Date.now(),{surveys:[],context:{isLoaded:!1,error:s}}}this._lastSurveyRefreshFailedAt=null;var r,n=t.json.surveys||[],o=n.filter((e=>function(e){return!(!e.start_date||e.end_date)}(e)&&(Ta(e)||function(e){var t;return!(null==(t=e.conditions)||null==(t=t.actions)||null==(t=t.values)||!t.length)}(e))));return o.length>0&&(null==(r=this._surveyEventReceiver)||r.register(o)),e.kv.set({[N]:n,[z]:Date.now()}),{surveys:n,context:{isLoaded:!0}}}_shouldBackgroundRefreshSurveys(){return this._isSurveyCacheStale()&&!this._getSurveysInFlightPromise&&!this._isSurveyRefreshBackingOff()}_isSurveyCacheStale(){var e,t,i=null==(e=null!==(t=this._client)&&void 0!==t?t:this._initialClientState)?void 0:e.kv.get(z);return St(i)&&Date.now()-i>3e5}_isSurveyRefreshBackingOff(){return St(this._lastSurveyRefreshFailedAt)&&3e5>Date.now()-this._lastSurveyRefreshFailedAt}markSurveyAsSeen(e,t){var i,s={id:e,current_iteration:null!==(i=null==t?void 0:t.iteration)&&void 0!==i?i:null};ja(s);try{localStorage.setItem("lastSeenSurveyDate",(new Date).toISOString())}catch(e){}}_notifySurveyCallbacks(e){for(var t of this._surveyCallbacks)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(e){Na.error("Error in survey callback",e)}}getActiveMatchingSurveys(e,t){if(void 0===t&&(t=!1),!wt(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);Na.warn("init was not called")}_getSurveyById(e){var t=null;return this.getSurveys((i=>{var s;t=null!==(s=i.find((t=>t.id===e)))&&void 0!==s?s:null})),t}_checkSurveyEligibility(e){if(wt(this._surveyManager))return{eligible:!1,reason:Ul};var t="string"==typeof e?this._getSurveyById(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}_checkSurveyRenderability(e){if(wt(this._surveyManager))return{eligible:!1,reason:Ul};var t="string"==typeof e?this._getSurveyById(e):e;return t?this._surveyManager.checkSurveyRenderability(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(wt(this._surveyManager))return Na.warn("init was not called"),{visible:!1,disabledReason:Ul};var t=this._checkSurveyRenderability(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return wt(this._surveyManager)?(Na.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ul})):new Promise((i=>{this.getSurveys((t=>{var s,r=null!==(s=t.find((t=>t.id===e)))&&void 0!==s?s:null;if(r){var n=this._checkSurveyRenderability(r);i({visible:n.eligible,disabledReason:n.reason})}else i({visible:!1,disabledReason:"Survey not found"})}),t)}))}renderSurvey(e,t,i){var s;if(wt(this._surveyManager))Na.warn("init was not called");else{var r="string"==typeof e?this._getSurveyById(e):e;if(null!=r&&r.id)if(Ua.includes(r.type)){var n=null==Ee?void 0:Ee.querySelector(t);if(n)if(null!=(s=r.appearance)&&s.surveyPopupDelaySeconds){Na.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds");var o=setTimeout((()=>{var e,t;this._renderTimeouts.delete(o),this._disposed||(Na.info("Rendering survey "+r.id+" with delay of "+(null==(e=r.appearance)?void 0:e.surveyPopupDelaySeconds)+" seconds"),null==(t=this._surveyManager)||t.renderSurvey(r,n,i),Na.info("Survey "+r.id+" rendered"))}),1e3*r.appearance.surveyPopupDelaySeconds);this._renderTimeouts.add(o)}else this._surveyManager.renderSurvey(r,n,i);else Na.warn("Survey element not found")}else Na.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Na.warn("Survey not found")}}displaySurvey(e,t){var s;if(wt(this._surveyManager))Na.warn("init was not called");else{var r=this._getSurveyById(e);if(r){var n=r;if(null!=(s=r.appearance)&&s.surveyPopupDelaySeconds&&t.ignoreDelay&&(n=i({},r,{appearance:i({},r.appearance,{surveyPopupDelaySeconds:0})})),t.displayType!==yo&&t.initialResponses&&Na.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),!1===t.ignoreConditions){var o=this._checkSurveyEligibility(r);if(!o.eligible)return void Na.warn("Survey is not eligible to be displayed: ",o.reason)}"inline"!==t.displayType?this._surveyManager.handlePopoverSurvey(n,t):this.renderSurvey(n,t.selector,t.properties)}else Na.warn("Survey not found")}}cancelPendingSurvey(e){wt(this._surveyManager)?Na.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e;null==(e=this._surveyManager)||null==e.handlePageUnload||e.handlePageUnload()}}function Gl(e,t,i){if(wt(e))return!1;switch(i){case"exact":return e===t;case"contains":var s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(s,"i").test(e);case"regex":try{return new RegExp(t).test(e)}catch(e){return!1}default:return!1}}class Kl{constructor(e){this._actionRegistry=new Set,this._actionEvents=new Set,this._debugEventEmitter=new Ea,this._checkStep=(e,t)=>this._checkStepEvent(e,t)&&this._checkStepUrl(e,t)&&this._checkStepElement(e,t)&&this._checkStepProperties(e,t),this._checkStepEvent=(e,t)=>null==t||!t.event||(null==e?void 0:e.event)===(null==t?void 0:t.event),this._instance=e}init(){var e,t;ft(null==(e=this._instance)?void 0:e._addCaptureHook)||(this._captureHookUnsubscribe=null==(t=this._instance)?void 0:t._addCaptureHook(((e,t)=>{this.on(e,t)})))}dispose(){var e;null==(e=this._captureHookUnsubscribe)||e.call(this),this._captureHookUnsubscribe=void 0,this._debugEventEmitter=new Ea}register(e){var t,i;if(!ft(null==(t=this._instance)?void 0:t._addCaptureHook)&&(e.forEach((e=>{var t;this._actionRegistry.add(e),null==(t=e.steps)||t.forEach((e=>{this._actionEvents.add((null==e?void 0:e.event)||"")}))})),null!=(i=this._instance)&&i.autocapture)){var s=new Set;this._actionRegistry.forEach((e=>{var t;null==(t=e.steps)||t.forEach((e=>{null!=e&&e.selector&&s.add(e.selector)}))})),this._instance.autocapture.setElementSelectors(s)}}replace(e){this._actionRegistry.clear(),this._actionEvents.clear(),this.register(e)}on(e,t){null!=t&&0!=e.length&&(this._actionEvents.has(e)||this._actionEvents.has(t.event))&&this._actionRegistry.forEach((e=>{this._checkAction(t,e)&&this._debugEventEmitter.emit("actionCaptured",e.name)}))}_addActionHook(e){this.onAction("actionCaptured",(t=>e(t)))}_checkAction(e,t){if(null==(null==t?void 0:t.steps))return!1;for(var i of t.steps)if(this._checkStep(e,i))return!0;return!1}onAction(e,t){return this._debugEventEmitter.on(e,t)}_checkStepUrl(e,t){if(null!=t&&t.url){var i,s=null==e||null==(i=e.properties)?void 0:i.$current_url;if(!s||"string"!=typeof s)return!1;if(!Gl(s,t.url,t.url_matching||"contains"))return!1}return!0}_checkStepElement(e,t){return!!this._checkStepHref(e,t)&&!!this._checkStepText(e,t)&&!!this._checkStepSelector(e,t)}_checkStepHref(e,t){var i;if(null==t||!t.href)return!0;var s=this._getElementsList(e);if(s.length>0)return s.some((e=>Gl(e.href,t.href,t.href_matching||"exact")));var r,n=(null==e||null==(i=e.properties)?void 0:i.$elements_chain)||"";return!!n&&Gl((r=n.match(/(?::|")href="(.*?)"/))?r[1]:"",t.href,t.href_matching||"exact")}_checkStepText(e,t){var i;if(null==t||!t.text)return!0;var s=this._getElementsList(e);if(s.length>0)return s.some((e=>Gl(e.text,t.text,t.text_matching||"exact")||Gl(e.$el_text,t.text,t.text_matching||"exact")));var r,n,o,a=(null==e||null==(i=e.properties)?void 0:i.$elements_chain)||"";return!!a&&(r=function(e){for(var t,i=[],s=/(?::|")text="(.*?)"/g;!wt(t=s.exec(e));)i.includes(t[1])||i.push(t[1]);return i}(a),n=t.text,o=t.text_matching||"exact",r.some((e=>Gl(e,n,o))))}_checkStepSelector(e,t){var i,s;if(null==t||!t.selector)return!0;var r=null==e||null==(i=e.properties)?void 0:i.$element_selectors;if(null!=r&&r.includes(t.selector))return!0;var n=(null==e||null==(s=e.properties)?void 0:s.$elements_chain)||"";if(t.selector_regex&&n)try{return new RegExp(t.selector_regex).test(n)}catch(e){return!1}return!1}_getElementsList(e){var t;return null==(null==e||null==(t=e.properties)?void 0:t.$elements)?[]:null==e?void 0:e.properties.$elements}_checkStepProperties(e,t){return null==t||!t.properties||0===t.properties.length||Ma(t.properties.reduce(((e,t)=>{var i=_t(t.value)?t.value.map(String):null!=t.value?[String(t.value)]:[];return e[t.key]={values:i,operator:t.operator||"exact"},e}),{}),null==e?void 0:e.properties)}}class Ql{constructor(e){var t;this._pendingActivatedItems=[],this._instance=e,this._eventToItems=new Map,this._cancelEventToItems=new Map,this._actionToItems=new Map,this._sessionIdUnsubscribe=null==(t=this._instance)||null==t.onSessionId?void 0:t.onSessionId((e=>this._onSessionIdChanged(e)))}_shouldPersistArmedActivation(e){return!1}_getActivationTimestampsKey(){return null}_writeActivationTimestamps(e){}_clearActivationTimestampsStore(){}_doesEventMatchFilter(e,t){return!!e&&Ma(e.propertyFilters,null==t?void 0:t.properties)}_buildEventToItemMap(e,t){var i=new Map;return e.forEach((e=>{var s;null==(s=e.conditions)||null==(s=s[t])||null==(s=s.values)||s.forEach((t=>{if(null!=t&&t.name){var s=i.get(t.name)||[];s.push(e.id),i.set(t.name,s)}}))})),i}_getMatchingItems(e,t,i){var s=(i===po?this._eventToItems:this._cancelEventToItems).get(e),r=[];return this._getItems((e=>{r=e.filter((e=>null==s?void 0:s.includes(e.id)))})),r.filter((s=>{var r,n=null==(r=s.conditions)||null==(r=r[i])||null==(r=r.values)?void 0:r.find((t=>t.name===e));return this._doesEventMatchFilter(n,t)}))}register(e){this._register(e,!1)}replace(e){this._register(e,!0)}_register(e,t){var i;ft(null==(i=this._instance)?void 0:i._addCaptureHook)||(this._setupEventBasedItems(e,t),this._setupActionBasedItems(e,t))}_setupActionBasedItems(e,t){var i=e.filter((e=>{var t;return null==(t=e.conditions)||null==(t=t.actions)||null==(t=t.values)?void 0:t.length}));if(t&&this._actionToItems.clear(),0!==i.length){this._actionMatcher||(this._actionMatcher=new Kl(this._instance),this._actionMatcher.init(),this._actionMatcher._addActionHook((e=>this.onAction(e))));var s=[];i.forEach((e=>{var t;null==(t=e.conditions)||null==(t=t.actions)||t.values.forEach((t=>{if(s.push(t),t.name){var i,r=null!==(i=this._actionToItems.get(t.name))&&void 0!==i?i:[];r.includes(e.id)||r.push(e.id),this._actionToItems.set(t.name,r)}}))})),t?this._actionMatcher.replace(s):this._actionMatcher.register(s)}else{var r;t&&(null==(r=this._actionMatcher)||r.replace([]))}}_mergeItemMaps(e,t){t.forEach(((t,i)=>{var s,r=null!==(s=e.get(i))&&void 0!==s?s:[];t.forEach((e=>{r.includes(e)||r.push(e)})),e.set(i,r)}))}_setupEventBasedItems(e,t){var i,s,r=e.filter((e=>{var t,i;return(null==(t=e.conditions)?void 0:t.events)&&(null==(i=e.conditions)||null==(i=i.events)||null==(i=i.values)?void 0:i.length)>0})),n=e.filter((e=>{var t,i;return(null==(t=e.conditions)?void 0:t.cancelEvents)&&(null==(i=e.conditions)||null==(i=i.cancelEvents)||null==(i=i.values)?void 0:i.length)>0})),o=this._buildEventToItemMap(e,po),a=this._buildEventToItemMap(e,go);t?(this._eventToItems=o,this._cancelEventToItems=a):(this._mergeItemMaps(this._eventToItems,o),this._mergeItemMaps(this._cancelEventToItems,a)),(0!==r.length||0!==n.length)&&(null!==(i=this._captureHookUnsubscribe)&&void 0!==i||(this._captureHookUnsubscribe=null==(s=this._instance)?void 0:s._addCaptureHook(((e,t)=>{this.onEvent(e,t)}))))}onEvent(e,t){var i,s,r=this._getLogger(),n=(null==t||null==(i=t.properties)?void 0:i.$survey_id)||(null==t||null==(s=t.properties)?void 0:s.$product_tour_id);if(n&&this.getActivatedIds().includes(n)){var o=this._activationOutcome(e,n);if("consume"===o)return r.info("event consumed activated item, removing it",{event:e,itemId:n}),void this._deactivateItems([n]);if("persist"===o)return r.info("shown item promoted to persisted activation",{event:e,itemId:n}),this._persistActivation(n),void this._clearActivationTimestamps([n])}if(this._cancelEventToItems.has(e)){var a=this._getMatchingItems(e,t,go);a.length>0&&(r.info("cancel event matched, cancelling items",{event:e,itemsToCancel:a.map((e=>e.id))}),this._deactivateItems(a.map((e=>e.id))),a.forEach((e=>this._cancelPendingItem(e.id))))}if(this._eventToItems.has(e)){r.info("event name matched",{event:e,eventPayload:t,items:this._eventToItems.get(e)});var l=this._getMatchingItems(e,t,po);this._activateItems(l.map((e=>e.id)))}}onAction(e){this._actionToItems.has(e)&&this._activateItems(this._actionToItems.get(e)||[])}_activateItems(e){var t;if(0!==e.length){var i=!(null==(t=this._instance)||null==t.get_session_id||!t.get_session_id()),s=[];for(var r of e)i&&this._shouldPersistArmedActivation(r)?this._persistActivation(r)&&this._recordActivationTimestamp(r):s.push(r);s.length>0&&(this._pendingActivatedItems=[...new Set([...this._pendingActivatedItems,...s])]),this._getLogger().info("updating activated items",{activatedItems:this.getActivatedIds()})}}_persistActivation(e){this._pendingActivatedItems=this._pendingActivatedItems.filter((t=>t!==e));var t=this._getPersistedActivatedIds();return!t.includes(e)&&(this._setActivatedItems([...t,e]),this._stampActivationSession(),!0)}_deactivateItems(e){var t=new Set(e);this._pendingActivatedItems=this._pendingActivatedItems.filter((e=>!t.has(e)));var i=this._getRawPersistedActivatedIds(),s=i.filter((e=>!t.has(e)));s.length!==i.length&&(this._setActivatedItems(s),0===s.length&&this._clearActivationSession()),this._clearActivationTimestamps(e)}_getRawActivationTimestamps(){var e,t=this._getActivationTimestampsKey();if(!t)return{};var i=null==(e=this._instance)||null==(e=e.persistence)?void 0:e.props[t];return i&&"object"==typeof i?i:{}}_recordActivationTimestamp(e){if(this._getActivationTimestampsKey()){var t=this._getRawActivationTimestamps();this._writeActivationTimestamps(i({},t,{[e]:Date.now()}))}}_clearActivationTimestamps(e){if(this._getActivationTimestampsKey()){var t=this._getRawActivationTimestamps(),i={},s=!1;for(var r of Object.entries(t)){var n=r[0],o=r[1];e.includes(n)?s=!0:i[n]=o}s&&(vt(i)?this._clearActivationTimestampsStore():this._writeActivationTimestamps(i))}}_clearAllActivationTimestamps(){this._getActivationTimestampsKey()&&this._clearActivationTimestampsStore()}getActivationTimestamp(e){if(this._getPersistedActivatedIds().includes(e)){var t=this._getRawActivationTimestamps()[e];return St(t)?t:void 0}}_getRawPersistedActivatedIds(){var e,t=this._getActivatedKey();return(null==(e=this._instance)||null==(e=e.persistence)?void 0:e.props[t])||[]}_getPersistedActivatedIds(){var e,t,i=this._getRawPersistedActivatedIds();if(0===i.length)return[];var s=null==(e=this._instance)||null==(e=e.persistence)?void 0:e.props[this._getActivatedSessionKey()],r=null==(t=this._instance)||null==t.get_session_id?void 0:t.get_session_id();return r&&s===r?i:[]}_stampActivationSession(){var e,t=null==(e=this._instance)||null==e.get_session_id?void 0:e.get_session_id();t&&this._setActivatedSession(t)}_clearActivationSession(){this._clearActivatedSession()}_onSessionIdChanged(e){var t,i=null==(t=this._instance)||null==(t=t.persistence)?void 0:t.props[this._getActivatedSessionKey()];if(i&&i!==e){var s=this._getRawPersistedActivatedIds(),r=this._getRawActivationTimestamps();s.length>0&&(this._setActivatedItems([]),s.filter((e=>St(r[e]))).forEach((e=>this._cancelPendingItem(e)))),this._clearActivationSession(),this._clearAllActivationTimestamps()}}getActivatedIds(){return[...new Set([...this._getPersistedActivatedIds(),...this._pendingActivatedItems])].filter((e=>!this._isItemPermanentlyIneligible(e)))}dispose(){var e,t,i;null==(e=this._sessionIdUnsubscribe)||e.call(this),this._sessionIdUnsubscribe=void 0,null==(t=this._captureHookUnsubscribe)||t.call(this),this._captureHookUnsubscribe=void 0,null==(i=this._actionMatcher)||i.dispose(),this._actionMatcher=void 0}reset(){this._pendingActivatedItems=[],this._getRawPersistedActivatedIds().length>0&&this._setActivatedItems([]),this._clearActivationSession(),this._clearAllActivationTimestamps()}getEventToItemsMap(){return this._eventToItems}_getActionMatcher(){return this._actionMatcher}}class Jl extends Ql{constructor(e){super(e)}_getActivatedKey(){return j}_getActivatedSessionKey(){return U}_getActivationTimestampsKey(){return V}_writeActivationTimestamps(e){var t;null==(t=this._instance)||null==(t=t.persistence)||t.register({[V]:e})}_clearActivationTimestampsStore(){var e;null==(e=this._instance)||null==(e=e.persistence)||e.unregister(V)}_shouldPersistArmedActivation(e){var t,i;this._getItems((t=>{i=t.find((t=>t.id===e))}));var s=null==(t=i)||null==(t=t.appearance)?void 0:t.surveyPopupDelaySeconds;return St(s)&&s>0}_getShownEventName(){return vo}_getItems(e){var t;null==(t=this._instance)||t.getSurveys(e)}_cancelPendingItem(e){var t;null==(t=this._instance)||t.cancelPendingSurvey(e)}_getLogger(){return Na}_setActivatedItems(e){var t;null==(t=this._instance)||null==(t=t.persistence)||t.register({[j]:e})}_setActivatedSession(e){var t;null==(t=this._instance)||null==(t=t.persistence)||t.register({[U]:e})}_clearActivatedSession(){var e;null==(e=this._instance)||null==(e=e.persistence)||e.unregister(U)}_isItemPermanentlyIneligible(){return!1}_activationOutcome(e,t){var i;this._getItems((e=>{i=e.find((e=>e.id===t))}));var s=!i||function(e){var t;return Ta(e)&&!(null==(t=e.conditions)||null==(t=t.events)||!t.repeatedActivation)||"always"===e.schedule}(i);return s?e===vo?"consume":"ignore":e===vo?"persist":e===fo||e===mo?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}class Yl{constructor(e){this._instance=e}initialize(){}get(e){if("string"==typeof e)return this._instance.get_property(e);var t={};for(var i of e){var s=this._instance.get_property(i);ft(s)||(t[i]=s)}return t}set(e,t){this._instance.register("string"==typeof e?{[e]:t}:e)}remove(e){"string"!=typeof e?e.forEach((e=>this._instance.unregister(e))):this._instance.unregister(e)}}class Zl{constructor(e){this._instance=e}get(){var e=this._instance.config;return{disableSurveys:e.disable_surveys,cookielessMode:!!e.cookieless_mode,advancedEnableSurveys:e.advanced_enable_surveys,requestTimeoutMs:e.surveys_request_timeout_ms}}isOptedOut(){return this._instance.consent.isOptedOut()}getExtensions(){var e=null==Le?void 0:Le.__PosthogExtensions__;if(e){var t=e.generateSurveys,i=e.loadExternalDependency;return{generateSurveys:t?e=>t(this._instance,e):void 0,loadExternalDependency:i?e=>i(this._instance,"surveys",e):void 0}}}createEventReceiver(){return new Jl(this._instance)}}var Xl=null!=we&&we.location?Hn(we.location.hash,"__posthog")||Hn(location.hash,"state"):null,eu="_postHogToolbarParams",tu=Gs("[Toolbar]"),iu=Gs("[FeatureFlags]");class su{constructor(e,t){void 0===t&&(t=!1),this._loggedEvaluationEnvironmentsDeprecation=!1,this.update(e,t)}update(e,t){this._snapshot=((e,t)=>{var i,s,r,n;return{bootstrap:{featureFlags:null==(i=e.bootstrap)?void 0:i.featureFlags,featureFlagPayloads:null==(s=e.bootstrap)?void 0:s.featureFlagPayloads},remoteRequestsDisabled:t,featureFlagsDisabled:!!e.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!e.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!e.advanced_feature_flags_dedup_per_session,cacheTtlMs:e.feature_flag_cache_ttl_ms,requestTimeoutMs:e.feature_flag_request_timeout_ms,compression:e.disable_compression?"none":"base64",evaluationContexts:null!==(r=null!==(n=e.evaluation_contexts)&&void 0!==n?n:e.evaluation_environments)&&void 0!==r?r:[],flagKeys:_t(e.flag_keys)?e.flag_keys:void 0}})(e,t),!e.evaluation_environments||e.evaluation_contexts||this._loggedEvaluationEnvironmentsDeprecation||(iu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this._loggedEvaluationEnvironmentsDeprecation=!0),ft(e.flag_keys)||_t(e.flag_keys)||iu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this._snapshot}}var ru=Gs("[FeatureFlags]"),nu=Gs("[FeatureFlags]",{debugEnabled:!0}),ou="\" failed. Feature flags didn't load in time.",au="connection_error",lu=e=>{for(var t={},i=0;e.length>i;i++)t[e[i]]=!0;return t},uu=e=>{var t={};for(var i of Ys(e||{})){var s=i[1];s&&(t[i[0]]=s)}return t},cu=Gs("[Error tracking]"),du=["chrome-extension://","moz-extension://","safari-extension:","safari-web-extension:"],hu=["__firefox__","__gCrWeb"],_u="Refusing to render web experiment since the viewer is a likely bot",pu={icontains:(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())>-1,not_icontains:(e,t)=>-1===t.toLowerCase().indexOf(e.toLowerCase()),regex:(e,t)=>Ra(t,e),not_regex:(e,t)=>!Ra(t,e),exact:(e,t)=>t===e,is_not:(e,t)=>t!==e};class gu{get _config(){return this._instance.config}constructor(e){var t=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(e){void 0===e&&(e=!1),t.getWebExperiments((e=>{gu._logInfo("retrieved web experiments from the server"),t._flagToExperiments=new Map,e.forEach((e=>{if(e.feature_flag_key){var i;t._flagToExperiments&&(gu._logInfo("setting flag key ",e.feature_flag_key," to web experiment ",e),null==(i=t._flagToExperiments)||i.set(e.feature_flag_key,e));var s=t._instance.getFeatureFlag(e.feature_flag_key);mt(s)&&e.variants[s]&&t._applyTransforms(e.name,s,e.variants[s].transforms)}else if(e.variants)for(var r in e.variants){var n=e.variants[r];gu._matchesTestVariant(n,t._instance)&&t._applyTransforms(e.name,r,n.transforms)}}))}),e)},this._instance=e,this._instance.onFeatureFlags((e=>{this.onFeatureFlags(e)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())gu._logInfo(_u);else if(!this._config.disable_web_experiments){if(wt(this._flagToExperiments))return this._flagToExperiments=new Map,this.loadIfEnabled(),void this.previewWebExperiment();gu._logInfo("applying feature flags",e),e.forEach((e=>{var t;if(this._flagToExperiments&&null!=(t=this._flagToExperiments)&&t.has(e)){var i,s=this._instance.getFeatureFlag(e),r=null==(i=this._flagToExperiments)?void 0:i.get(e);s&&null!=r&&r.variants[s]&&this._applyTransforms(r.name,s,r.variants[s].transforms)}}))}}previewWebExperiment(){var e=gu.getWindowLocation();if(null!=e&&e.search){var t=Bn(null==e?void 0:e.search,"__experiment_id"),i=Bn(null==e?void 0:e.search,"__experiment_variant");t&&i&&(gu._logInfo("previewing web experiments "+t+" && "+i),this.getWebExperiments((e=>{this._showPreviewWebExperiment(parseInt(t),i,e)}),!1,!0))}}loadIfEnabled(){this._config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,t,i){if(this._config.disable_web_experiments&&!i)return e([]);var s=this._instance.get_property("$web_experiments");if(s&&!t)return e(s);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._config.token),method:"GET",timestampMode:"query",callback:t=>e(200===t.statusCode&&t.json&&t.json.experiments||[])})}_showPreviewWebExperiment(e,t,i){var s=i.filter((t=>t.id===e));s&&s.length>0&&(gu._logInfo("Previewing web experiment ["+s[0].name+"] with variant ["+t+"]"),this._applyTransforms(s[0].name,t,s[0].variants[t].transforms))}static _matchesTestVariant(e,t){return!wt(e.conditions)&&gu._matchUrlConditions(e,t)&&gu._matchUTMConditions(e)}static _matchUrlConditions(e,t){var i;if(wt(e.conditions)||wt(null==(i=e.conditions)?void 0:i.url))return!0;var s=gu.getWindowLocation();if(s){var r,n,o,a=Lr(t,s.href);return null==(r=e.conditions)||!r.url||pu[null!==(n=null==(o=e.conditions)?void 0:o.urlMatchType)&&void 0!==n?n:"icontains"](e.conditions.url,a)}return!1}static getWindowLocation(){return null==we?void 0:we.location}static _matchUTMConditions(e){var t;if(wt(e.conditions)||wt(null==(t=e.conditions)?void 0:t.utm))return!0;var i=Kn();if(i.utm_source){var s,r,n,o,a,l,u,c,d=null==(s=e.conditions)||null==(s=s.utm)||!s.utm_campaign||(null==(r=e.conditions)||null==(r=r.utm)?void 0:r.utm_campaign)==i.utm_campaign,h=null==(n=e.conditions)||null==(n=n.utm)||!n.utm_source||(null==(o=e.conditions)||null==(o=o.utm)?void 0:o.utm_source)==i.utm_source,_=null==(a=e.conditions)||null==(a=a.utm)||!a.utm_medium||(null==(l=e.conditions)||null==(l=l.utm)?void 0:l.utm_medium)==i.utm_medium,p=null==(u=e.conditions)||null==(u=u.utm)||!u.utm_term||(null==(c=e.conditions)||null==(c=c.utm)?void 0:c.utm_term)==i.utm_term;return d&&_&&p&&h}return!1}static _logInfo(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;t>s;s++)i[s-1]=arguments[s];Ws.info("[WebExperiments] "+e,i)}_applyTransforms(e,t,i){this._is_bot()?gu._logInfo(_u):"control"!==t?i.forEach((i=>{if(i.selector){var s;gu._logInfo("applying transform of variant "+t+" for experiment "+e+" ",i);var r=null==(s=document)?void 0:s.querySelectorAll(i.selector);null==r||r.forEach((e=>{var t=e;i.html&&(t.innerHTML=i.html),i.css&&t.setAttribute("style",i.css)}))}})):gu._logInfo("Control variants leave the page unmodified.")}_is_bot(){return xe&&this._instance?Ia(xe,this._config.custom_blocked_useragents):void 0}}var vu=Gs("[Conversations]"),fu="Conversations not available yet.",mu="console",yu="__posthogHandledLogsRequestError",bu=(e,t)=>{var i=e instanceof Error?e:new Error(t);return i[yu]=!0,i},wu=e=>!!e&&"object"==typeof e&&!0===e[yu],Su={featureFlags:class{constructor(e){this.name="featureFlags",this._override_warning=!1,this.featureFlagEventHandlers=[],this._logger=ru,this._baseEventProperties={},this._eventPropertiesWithFlagValues={},this._reloadingHandlers=[],this._hasLoadedFlags=!1,this._requestInFlight=!1,this._requestGeneration=0,this._reloadingDisabled=!1,this._additionalReloadRequested=!1,this._flagsLoadedFromRemote=!1,this._staleCacheRefreshTriggered=!1,this._consecutiveStatusZeroFailures=0,this._onOnline=()=>{var e=this._hasStatusZeroCircuitBreakerTripped();this._consecutiveStatusZeroFailures=0,e&&this.reloadFeatureFlags()},"get"in e?this._configSource=e:(this._mutableConfigSource=new su(e.config,e._shouldDisableFlags()),this._configSource=this._mutableConfigSource)}updateConfig(e,t){var i;null==(i=this._mutableConfigSource)||i.update(e,t)}setup(e){return this._initializingClient=e,this._logger=e.logger.createLogger("[FeatureFlags]"),jl(e.kv.initialize(),(()=>{this._initializingClient===e&&(this._initializingClient=void 0,this._client=e,this._finishSetup(e))}))}_finishSetup(e){if(this._client===e)return we&&sr(we,"online",this._onOnline),this._dynamicProperties=e.registerDynamicEventProperties((()=>this._isCacheStale()?this._baseEventProperties:this._eventPropertiesWithFlagValues)),this._rebuildEventProperties(),this.initialize()}destroy(){null==we||we.removeEventListener("online",this._onOnline)}dispose(){var e;this._requestGeneration++,this._additionalReloadRequested=!1,this._initializingClient=void 0,this._client&&(this._clearDebouncer(),null==(e=this._dynamicProperties)||e.dispose(),this._dynamicProperties=void 0,this._reloadingHandlers=[],null==we||we.removeEventListener("online",this._onOnline),this._client=void 0)}get _config(){return this._configSource.get()}_prop(e){var t;return null==(t=this._client)?void 0:t.kv.get(e)}_set(e){this._persist((()=>{var t;return null==(t=this._client)?void 0:t.kv.set(e)}))}_remove(e){this._persist((()=>{var t;return null==(t=this._client)?void 0:t.kv.remove(e)}))}_persist(e){try{e()}catch(e){this._logger.error("Failed to update feature flag persistence",e)}}_rebuildEventProperties(){var e={};for(var t of[F,A,L,O]){var s=this._prop(t);ft(s)||(e[t]=s)}this._baseEventProperties=e;var r=i({},e),n=this._prop(I);if(n)for(var o of Object.entries(n))r["$feature/"+o[0]]=o[1];this._eventPropertiesWithFlagValues=r}_isCacheStale(){var e=this._config.cacheTtlMs;if(!e||0>=e)return!1;var t=this._prop(J);return"number"!=typeof t||Date.now()-t>e}_checkAndTriggerStaleRefresh(){return!!this._isCacheStale()&&(this._staleCacheRefreshTriggered||this._requestInFlight||(this._staleCacheRefreshTriggered=!0,this._logger.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}_getValidEvaluationEnvironments(){var e=this._config.evaluationContexts;return null!=e&&e.length?e.filter((e=>{var t=e&&"string"==typeof e&&e.trim().length>0;return t||this._logger.error("Invalid evaluation context found:",e,"Expected non-empty string"),t})):[]}_getValidFlagKeys(){var e=this._config.flagKeys;if(!ft(e))return e.filter((e=>{var t=e&&"string"==typeof e&&e.trim().length>0;return t||this._logger.error("Invalid flag key found:",e,"Expected non-empty string"),t}))}initialize(){var e,t,i=this._config,s=null!==(e=null==(t=i.bootstrap)?void 0:t.featureFlags)&&void 0!==e?e:{};if(Object.keys(s).length){var r,n,o=null!==(r=null==(n=i.bootstrap)?void 0:n.featureFlagPayloads)&&void 0!==r?r:{},a=Object.keys(s).filter((e=>!!s[e])).reduce(((e,t)=>(e[t]=s[t]||!1,e)),{}),l=Object.keys(o).filter((e=>a[e])).reduce(((e,t)=>(e[t]=o[t],e)),{});return this._receivedFeatureFlags({featureFlags:a,featureFlagPayloads:l})}}updateFlags(e,t,s){var r,n,o=null!=s&&s.merge&&null!==(r=this._prop(I))&&void 0!==r?r:{},a=null!=s&&s.merge&&null!==(n=this._prop(A))&&void 0!==n?n:{},l=i({},o,e),u=i({},a,t),c={};for(var d of Object.entries(l)){var h=d[0],_=d[1];c[h]={key:h,enabled:$e(_),variant:Oe(_),reason:void 0,metadata:ft(null==u?void 0:u[h])?void 0:{id:0,version:void 0,description:void 0,payload:u[h]}}}this._receivedFeatureFlags({flags:c})}get hasLoadedFlags(){return this._hasLoadedFlags}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._prop(R),t=this._prop(O),s=this._prop(D);if(!s&&!t)return e||{};var r=Js({},e||{}),n=[...new Set([...Object.keys(s||{}),...Object.keys(t||{})])];for(var o of n){var a,l,u=r[o],c=null==t?void 0:t[o],d=ft(c)?null!==(a=null==u?void 0:u.enabled)&&void 0!==a&&a:!!c,h=ft(c)?null==u?void 0:u.variant:"string"==typeof c?c:void 0,_=null==s?void 0:s[o],p=i({},u,{enabled:d,variant:d?null!=h?h:null==u?void 0:u.variant:void 0});d!==(null==u?void 0:u.enabled)&&(p.original_enabled=null==u?void 0:u.enabled),h!==(null==u?void 0:u.variant)&&(p.original_variant=null==u?void 0:u.variant),_&&(p.metadata=i({},null==u?void 0:u.metadata,{payload:_,original_payload:null==u||null==(l=u.metadata)?void 0:l.payload})),r[o]=p}return this._override_warning||(this._logger.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:s,finalDetails:r}),this._override_warning=!0),r}getAllFeatureFlags(){var e=this.getFlagVariants(),t=this.getFlagPayloads();return Object.keys(e).map((i=>{var s=e[i];return{key:i,enabled:$e(s),variant:Oe(s),payload:Me(t[i])}}))}getFlagVariants(){var e=this._prop(I),t=this._prop(O);if(!t)return e||{};for(var i=Js({},e||{}),s=Object.keys(t),r=0;s.length>r;r++)i[s[r]]=t[s[r]];return this._override_warning||(this._logger.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:t,finalFlags:i}),this._override_warning=!0),i}getFlagPayloads(){var e=this._prop(A),t=this._prop(D);if(!t)return e||{};for(var i=Js({},e||{}),s=Object.keys(t),r=0;s.length>r;r++)i[s[r]]=t[s[r]];return this._override_warning||(this._logger.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:t,finalPayloads:i}),this._override_warning=!0),i}reloadFeatureFlags(){this._reloadingDisabled||this._config.featureFlagsDisabled||this._hasStatusZeroCircuitBreakerTripped()||this._reloadDebouncer||(this._reloadingHandlers.slice().forEach((e=>{try{e()}catch(e){this._logger.error("Error while running feature flags reloading callback",e)}})),this._reloadDebouncer=setTimeout((()=>{this._callFlagsEndpoint()}),5))}_clearDebouncer(){clearTimeout(this._reloadDebouncer),this._reloadDebouncer=void 0}onReloading(e){return this._reloadingHandlers.push(e),()=>{this._reloadingHandlers=this._reloadingHandlers.filter((t=>t!==e))}}ensureFlagsLoaded(){this._hasLoadedFlags||this._requestInFlight||this._reloadDebouncer||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this._reloadingDisabled=e}resetFlagCallReported(){this._remove(G)}_callFlagsEndpoint(e){this._clearDebouncer();var t=this._client;if(t&&!this._config.remoteRequestsDisabled&&!this._hasStatusZeroCircuitBreakerTripped())if(this._requestInFlight)this._additionalReloadRequested=!0;else{var s={token:t.projectToken,distinct_id:t.distinctId,groups:t.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:i({},t.initialPersonProperties,this._prop(B)||{},{$lib:t.library.name,$lib_version:t.library.version}),group_properties:this._prop(q),timezone:io()};ft(t.deviceId)||(s.$device_id=t.deviceId),(null!=e&&e.disableFlags||this._config.featureFlagsDisabled)&&(s.disable_flags=!0);var r=this._getValidEvaluationEnvironments();r.length&&(s.evaluation_contexts=r);var n=this._getValidFlagKeys();ft(n)||(s.flag_keys=n);var o=this._config.onlyEvaluateSurveyFeatureFlags,a="/flags/?v=2"+(o?"&only_evaluate_survey_feature_flags=true":""),l=this._requestGeneration;this._requestInFlight=!0;var u=()=>{this._additionalReloadRequested&&(this._additionalReloadRequested=!1,this._callFlagsEndpoint())},c=e=>{this._requestInFlight=!1,l===this._requestGeneration?(this._set({[Q]:[au]}),this._logger.error("Feature flag request failed",e),u()):u()};try{t.sendRequest(a,{target:"flags",method:"POST",body:s,compression:"base64"===this._config.compression?_o:void 0,sentAt:"body",timeoutMs:this._config.requestTimeoutMs}).then((e=>{var t,i,r=null!==(t=e.json)&&void 0!==t?t:{},n=200!==e.statusCode;if(this._requestInFlight=!1,l===this._requestGeneration){if(this._trackStatusZeroReachability(e.statusCode),n||this._additionalReloadRequested||(this.$anon_distinct_id=void 0),!s.disable_flags||this._additionalReloadRequested){this._flagsLoadedFromRemote=!n;var a=[];e.error?a.push(e.error instanceof Error&&"AbortError"===e.error.name?"timeout":e.error instanceof Error?au:"unknown_error"):200!==e.statusCode&&a.push("api_error_"+e.statusCode),r.errorsWhileComputingFlags&&a.push("errors_while_computing_flags");var c=!(null==(i=r.quotaLimited)||!i.includes("feature_flags"));c&&a.push("quota_limited"),this._set({[Q]:a}),c?this._logger.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):s.disable_flags||this._receivedFeatureFlags(r,n,{partialResponse:o}),u()}}else u()})).catch(c)}catch(e){c(e)}}}_hasStatusZeroCircuitBreakerTripped(){return Nn(this._consecutiveStatusZeroFailures,3)}_trackStatusZeroReachability(e){this._consecutiveStatusZeroFailures=zn(e,this._consecutiveStatusZeroFailures,3,(()=>this._logger.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(e,t){var i;if(void 0===t&&(t={}),!t.fresh||this._flagsLoadedFromRemote)if(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0){if(!this._checkAndTriggerStaleRefresh()){var s=this.getFeatureFlagResult(e,t);return null!==(i=null==s?void 0:s.variant)&&void 0!==i?i:null==s?void 0:s.enabled}}else this._logger.warn('getFeatureFlag for key "'+e+ou)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){var t=this.getFeatureFlagResult(e,{send_event:!1});return null==t?void 0:t.payload}getFeatureFlagResult(e,t){if(void 0===t&&(t={}),!t.fresh||this._flagsLoadedFromRemote)if(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0){if(!this._checkAndTriggerStaleRefresh()){var s,r=this.getFlagVariants(),n=e in r,o=r[e],a=this.getFlagPayloads()[e],l=String(o),u=this._prop(L)||void 0,c=this._prop(J)||void 0,d=this._prop(G)||{};if(this._config.deduplicateCallsPerSession){var h,_=null==(h=this._client)?void 0:h.session.sessionId,p=this._prop(K);_&&_!==p&&(d={},s=_)}if(t.send_event||!("send_event"in t))if(e in d&&d[e].includes(l))s&&this._set({[G]:d,[K]:s});else{var g,v,f,m,y,b,w,S,x,E,k,P;_t(d[e])?d[e].push(l):d[e]=[l],this._set(i({[G]:d},s?{[K]:s}:{}));var C=this.getFeatureFlagDetails(e),I=[...null!==(g=this._prop(Q))&&void 0!==g?g:[]];ft(o)&&I.push("flag_missing");var F={$feature_flag:e,$feature_flag_response:o,$feature_flag_payload:null!=a?a:null,$feature_flag_request_id:u,$feature_flag_evaluated_at:c,$feature_flag_bootstrapped_response:null!==(v=null==(f=this._config.bootstrap)||null==(f=f.featureFlags)?void 0:f[e])&&void 0!==v?v:null,$feature_flag_bootstrapped_payload:null!==(m=null==(y=this._config.bootstrap)||null==(y=y.featureFlagPayloads)?void 0:y[e])&&void 0!==m?m:null,$used_bootstrap_value:!this._flagsLoadedFromRemote};ft(null==C||null==(b=C.metadata)?void 0:b.has_experiment)||(F.$feature_flag_has_experiment=C.metadata.has_experiment),ft(null==C||null==(w=C.metadata)?void 0:w.version)||(F.$feature_flag_version=C.metadata.version);var T,R=null!==(S=null==C||null==(x=C.reason)?void 0:x.description)&&void 0!==S?S:null==C||null==(E=C.reason)?void 0:E.code;R&&(F.$feature_flag_reason=R),null!=C&&null!=(k=C.metadata)&&k.id&&(F.$feature_flag_id=C.metadata.id),ft(null==C?void 0:C.original_variant)&&ft(null==C?void 0:C.original_enabled)||(F.$feature_flag_original_response=ft(C.original_variant)?C.original_enabled:C.original_variant),null!=C&&null!=(P=C.metadata)&&P.original_payload&&(F.$feature_flag_original_payload=null==C||null==(T=C.metadata)?void 0:T.original_payload),I.length&&(F.$feature_flag_error=I.join(",")),this._captureFeatureFlagCalled(F)}else s&&this._set({[G]:d,[K]:s});if(n)return{key:e,enabled:!!o,variant:"string"==typeof o?o:void 0,payload:Me(a)}}}else this._logger.warn('getFeatureFlagResult for key "'+e+ou)}_captureFeatureFlagCalled(e){try{var t;null==(t=this._client)||t.capture("$feature_flag_called",e).catch((e=>{this._logger.error("Failed to capture feature flag call",e)}))}catch(e){this._logger.error("Failed to capture feature flag call",e)}}getRemoteConfigPayload(e,t){this._getRemoteConfigPayload(e,t)}_getRemoteConfigPayload(e,i){var s=this;return t((function*(){var t=s._client;if(t){var r={distinct_id:t.distinctId,token:t.projectToken,person_properties:{$lib:t.library.name,$lib_version:t.library.version}},n=s._getValidEvaluationEnvironments();n.length&&(r.evaluation_contexts=n);var o,a=s._getValidFlagKeys();ft(a)||(r.flag_keys=a);try{var l,u=null==(l=(yield t.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:"base64"===s._config.compression?_o:void 0,sentAt:"body",timeoutMs:s._config.requestTimeoutMs})).json)?void 0:l.featureFlagPayloads;o=(null==u?void 0:u[e])||void 0}catch(e){return void s._logger.error("Remote config feature flag request failed",e)}try{i(o)}catch(e){s._logger.error("Remote config feature flag callback failed",e)}}}))()}isFeatureEnabled(e,t){if(void 0===t&&(t={}),t.fresh&&!this._flagsLoadedFromRemote)return t.defaultValue;if(!(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0))return this._logger.warn('isFeatureEnabled for key "'+e+ou),t.defaultValue;var i=this.getFeatureFlag(e,t);return ft(i)?t.defaultValue:!!i}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((t=>t!==e))}receivedFeatureFlags(e,t,i){this._receivedFeatureFlags(e,t,i)}_receivedFeatureFlags(e,t,s){if(this._client){this._hasLoadedFlags=!0;var r=function(e,t,s,r,n,o){void 0===t&&(t={}),void 0===s&&(s={}),void 0===r&&(r={}),void 0===o&&(o=ru);var a=((e,t)=>{var s=e.flags;return s?i({},e,{featureFlags:Object.fromEntries(Object.keys(s).map((e=>{var t;return[e,null!==(t=s[e].variant)&&void 0!==t?t:s[e].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(s).filter((e=>s[e].enabled)).filter((e=>{var t;return null==(t=s[e].metadata)?void 0:t.payload})).map((e=>{var t;return[e,null==(t=s[e].metadata)?void 0:t.payload]})))}):(e.featureFlags&&t.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),e)})(e,o),l=a.flags,u=a.featureFlags,c=a.featureFlagPayloads;if(u){var d=e.requestId,h=e.evaluatedAt;if(_t(u)){o.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var _={};if(u)for(var p=0;u.length>p;p++)_[u[p]]=!0;return{[F]:u,[I]:_,[M]:!1}}var g=u,v=c,f=l;if(null!=n&&n.partialResponse)g=i({},t,g),v=i({},s,v),f=i({},r,f);else if(e.errorsWhileComputingFlags)if(l){var m=new Set(Object.keys(l).filter((e=>{var t;return!(null!=(t=l[e])&&t.failed)})));g=i({},t,Object.fromEntries(Object.entries(g).filter((e=>m.has(e[0]))))),v=i({},s,Object.fromEntries(Object.entries(v||{}).filter((e=>m.has(e[0]))))),f=i({},r,Object.fromEntries(Object.entries(f||{}).filter((e=>m.has(e[0])))))}else g=i({},t,g),v=i({},s,v),f=i({},r,f);return i({[F]:Object.keys(uu(g)),[I]:g||{},[A]:v||{},[R]:f||{},[M]:!0===e.minimalFlagCalledEvents},d?{[L]:d}:{},h?{[J]:h}:{})}}(e,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),s,this._logger);r&&this._set(r),t||(this._staleCacheRefreshTriggered=!1),this._fireFeatureFlagsCallbacks(t)}}override(e,t){void 0===t&&(t=!1),this._logger.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:t})}overrideFeatureFlags(e){this._overrideFeatureFlags(e)}_overrideFeatureFlags(e){if(this._client){if(!1===e)return this._remove([O,D]),this._fireFeatureFlagsCallbacks(),void nu.info("All overrides cleared");if(_t(e))return this._set({[O]:lu(e)}),this._fireFeatureFlagsCallbacks(),void nu.info("Flag overrides set",{flags:e});if(e&&"object"==typeof e&&("flags"in e||"payloads"in e)){var t,i=e;this._override_warning=Boolean(null!==(t=i.suppressWarning)&&void 0!==t&&t);var s={},r=i.flags,n=i.payloads;return r&&(s[O]=_t(r)?lu(r):r),n&&(s[D]=n),Object.keys(s).length&&this._set(s),!1===r&&!1===n?this._remove([O,D]):!1===r?this._remove(O):!1===n&&this._remove(D),this._fireFeatureFlagsCallbacks(),!1===r?nu.info("Flag overrides cleared"):r&&nu.info("Flag overrides set",{flags:r}),void(!1===n?nu.info("Payload overrides cleared"):n&&nu.info("Payload overrides set",{payloads:n}))}if(e&&"object"==typeof e)return this._set({[O]:e}),this._fireFeatureFlagsCallbacks(),void nu.info("Flag overrides set",{flags:e});this._logger.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:e})}else this._logger.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this._hasLoadedFlags){var t=this._prepareFeatureFlagsForCallbacks(),i=t.flags,s=t.flagVariants;try{e(i,s)}catch(e){this._logger.error("Error while running feature flags callback",e)}}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,s){var r=(this._prop(T)||[]).find((t=>t.flagKey===e)),n={["$feature_enrollment/"+e]:t},o={$feature_flag:e,$feature_enrollment:t,$set:n};r&&(o.$early_access_feature_name=r.name),s&&(o.$feature_enrollment_stage=s);var a=i({},this.getFlagVariants(),{[e]:t});this._set({[F]:Object.keys(uu(a)),[I]:a,[B]:i({},this._prop(B)||{},n)}),this._fireFeatureFlagsCallbacks();try{var l;null==(l=this._client)||l.capture("$feature_enrollment_update",o).catch((e=>{this._logger.error("Failed to capture early access feature enrollment",e)}))}catch(e){this._logger.error("Failed to capture early access feature enrollment",e)}}getEarlyAccessFeatures(e,t,i){void 0===t&&(t=!1);var s=this._prop(T);!s||t?this._getEarlyAccessFeatures(e,i):e(s)}_getEarlyAccessFeatures(e,i){var s=this;return t((function*(){var t=s._client;if(t){var r,n=i?"&"+i.map((e=>"stage="+e)).join("&"):"";try{var o=yield t.sendRequest("/api/early_access_features/?token="+t.projectToken+n,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;s._set({[T]:r=o.json.earlyAccessFeatures})}catch(e){return void s._logger.error("Early access feature request failed",e)}try{e(r)}catch(e){s._logger.error("Early access feature callback failed",e)}}}))()}_prepareFeatureFlagsForCallbacks(){var e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter((e=>t[e])),flagVariants:Object.keys(t).filter((e=>t[e])).reduce(((e,i)=>(e[i]=t[i],e)),{})}}_fireFeatureFlagsCallbacks(e){this._rebuildEventProperties();var t=this._prepareFeatureFlagsForCallbacks(),i=t.flags,s=t.flagVariants;this.featureFlagEventHandlers.forEach((t=>{try{t(i,s,{errorsLoading:e})}catch(e){this._logger.error("Error while running feature flags callback",e)}}))}setPersonPropertiesForFlags(e,t){void 0===t&&(t=!0),this._setPersonPropertiesForFlags(e,t)}_setPersonPropertiesForFlags(e,t){void 0===t&&(t=!0);var s=this._prop(B)||{},r=(null==e?void 0:e.$set)||(null!=e&&e.$set_once?{}:e),n=null==e?void 0:e.$set_once,o={};if(n)for(var a in n)({}).hasOwnProperty.call(n,a)&&(a in s||(o[a]=n[a]));this._set({[B]:i({},s,o,r)}),t&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(e,t){void 0===t&&(t=!0);var s=i({},this._prop(B)||{});e.forEach((e=>{delete s[e]})),this._set({[B]:s}),t&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(e){void 0===e&&(e=!0),this._remove(B),e&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(e,t){void 0===t&&(t=!0);var s=this._prop(q)||{},r=i({},s);for(var n of Object.keys(e))r[n]=i({},s[n],e[n]);this._set({[q]:r}),t&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var t=this._prop(q)||{};this._set({[q]:i({},t,{[e]:{}})})}else this._remove(q)}reset(){this._requestGeneration++,this._additionalReloadRequested=!1,this._baseEventProperties={},this._eventPropertiesWithFlagValues={},this._hasLoadedFlags=!1,this._reloadingDisabled=!1,this._flagsLoadedFromRemote=!1,this.$anon_distinct_id=void 0,this._clearDebouncer(),this._override_warning=!1,this._consecutiveStatusZeroFailures=0}}},xu={sessionRecording:class{get _config(){return this._instance.config}get _persistence(){return this._instance.persistence}get started(){var e;return!(null==(e=this._lazyLoadedSessionRecording)||!e.isStarted)}get status(){var e,t;return this._recordingStatus===Al||this._recordingStatus===Ll?this._recordingStatus:null!==(e=null==(t=this._lazyLoadedSessionRecording)?void 0:t.status)&&void 0!==e?e:this._recordingStatus}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this._recordingStatus=Tl,this._persistFlagsOnSessionListener=void 0,this._sessionRecordingDisposed=!1,this._documentWasEverVisible=(()=>{var e;if(null==Ee||!Ee.visibilityState||"visible"===Ee.visibilityState)return!0;var t=null==we||null==(e=we.performance)||null==e.getEntriesByType?void 0:e.getEntriesByType("visibility-state");return!(null!=t&&t.length)||t.some((e=>"visible"===e.name))})(),this._onVisibilityChange=()=>{var e;"visible"===(null==Ee?void 0:Ee.visibilityState)&&(this._documentWasEverVisible=!0,null==(e=this._lazyLoadedSessionRecording)||null==e.setDocumentWasEverVisible||e.setDocumentWasEverVisible(!0))},this._instance=e,!this._instance.sessionManager)throw $l.error("started without valid sessionManager"),new Error(Ml+" started without valid sessionManager. This is a bug.");if(this._config.cookieless_mode===de)throw new Error(Ml+' cannot be used with cookieless_mode="always"');null!=Ee&&Ee.addEventListener&&sr(Ee,"visibilitychange",this._onVisibilityChange)}initialize(){this.startIfEnabledOrStop()}dispose(){this._sessionRecordingDisposed=!0,null==Ee||null==Ee.removeEventListener||Ee.removeEventListener("visibilitychange",this._onVisibilityChange),this.stopRecording()}get _isRecordingEnabled(){var e,t=!(null==(e=this._instance.get_property(b))||!e.enabled),i=!this._config.disable_session_recording,s=this._config.disable_session_recording||this._instance.consent.isOptedOut();return we&&t&&i&&!s}startIfEnabledOrStop(e){var t;if(!(this._sessionRecordingDisposed||this._isRecordingEnabled&&null!=(t=this._lazyLoadedSessionRecording)&&t.isStarted)){var i=!ft(Object.assign)&&!ft(Array.from);this._isRecordingEnabled&&i?(this._lazyLoadAndStart(e),$l.info("starting")):(this._recordingStatus=Tl,this.stopRecording())}}_lazyLoadAndStart(e){var t,i,s;this._isRecordingEnabled&&(this._recordingStatus!==Al&&this._recordingStatus!==Ll&&(this._recordingStatus=Rl),null!=Le&&null!=(t=Le.__PosthogExtensions__)&&null!=(t=t.rrweb)&&t.record&&null!=(i=Le.__PosthogExtensions__)&&i.initSessionRecording?this._onScriptLoaded(e):null==(s=Le.__PosthogExtensions__)||null==s.loadExternalDependency||s.loadExternalDependency(this._instance,this._scriptName,(t=>{if(t)return this._instance.register_for_session({[le]:!0}),$l.error("could not load recorder",t);this._onScriptLoaded(e)})))}stopRecording(){var e,t;null==(e=this._persistFlagsOnSessionListener)||e.call(this),this._persistFlagsOnSessionListener=void 0,null==(t=this._lazyLoadedSessionRecording)||t.stop()}_discardRecording(){var e,t;null==(e=this._persistFlagsOnSessionListener)||e.call(this),this._persistFlagsOnSessionListener=void 0,null==(t=this._lazyLoadedSessionRecording)||t.discard()}_resetSampling(){var e,t;null==(e=this._persistence)||e.unregister(C),null==(t=this._persistence)||t.unregister(w)}_validateSampleRate(e,t){if(wt(e))return null;var i,s=St(e)?e:parseFloat(e);return"number"!=typeof(i=s)||!Number.isFinite(i)||0>i||i>1?($l.warn(t+" must be between 0 and 1. Ignoring invalid value:",e),null):s}_persistRemoteConfig(e){if(this._persistence){var t,s,r=this._persistence,n=()=>{var t,s=!1===e.sessionRecording?void 0:e.sessionRecording,n=this._validateSampleRate(null==(t=this._config.session_recording)?void 0:t.sampleRate,"session_recording.sampleRate"),o=this._validateSampleRate(null==s?void 0:s.sampleRate,"remote config sampleRate"),a=null!=n?n:o;wt(a)&&this._resetSampling();var l=null==s?void 0:s.minimumDurationMilliseconds;r.register({[b]:i({cache_timestamp:Date.now(),enabled:!!s},s,{networkPayloadCapture:i({capturePerformance:e.capturePerformance},null==s?void 0:s.networkPayloadCapture),canvasRecording:{enabled:null==s?void 0:s.recordCanvas,fps:null==s?void 0:s.canvasFps,quality:null==s?void 0:s.canvasQuality},sampleRate:a,minimumDurationMilliseconds:ft(l)?null:l,endpoint:null==s?void 0:s.endpoint,triggerMatchType:null==s?void 0:s.triggerMatchType,masking:null==s?void 0:s.masking,urlTriggers:null==s?void 0:s.urlTriggers,version:null==s?void 0:s.version,triggerGroups:null==s?void 0:s.triggerGroups})})};n(),null==(t=this._persistFlagsOnSessionListener)||t.call(this),this._persistFlagsOnSessionListener=null==(s=this._instance.sessionManager)?void 0:s.onSessionId(n)}}onRemoteConfig(e){var t=e.ok?e.config:void 0;return t&&"sessionRecording"in t?!1===t.sessionRecording?(this._persistRemoteConfig(t),void this._discardRecording()):(this._persistRemoteConfig(t),void this.startIfEnabledOrStop()):(this._recordingStatus===Al&&(this._recordingStatus=Ll,$l.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(e,t){var i;void 0===t&&(t="log"),null!=(i=this._lazyLoadedSessionRecording)&&i.log?this._lazyLoadedSessionRecording.log(e,t):$l.warn("log called before recorder was ready")}get _scriptName(){var e,t,i=null==(e=this._instance)||null==(e=e.persistence)?void 0:e.get_property(b);return(null==i||null==(t=i.scriptConfig)?void 0:t.script)||"lazy-recorder"}_isRemoteConfigFresh(){var e,t=this._instance.get_property(b);if(!t)return!1;try{e="object"==typeof t?t:JSON.parse(t)}catch(e){return $l.warn("persisted remote config for session recording is invalid and will be ignored",e),!1}return!wt(e.cache_timestamp)&&36e5>=Date.now()-e.cache_timestamp}_onScriptLoaded(e){var t,i,s;if(!this._sessionRecordingDisposed){if(null==(t=Le.__PosthogExtensions__)||!t.initSessionRecording)return $l.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[le]:!0});var r;if(this._lazyLoadedSessionRecording||(this._lazyLoadedSessionRecording=null==(r=Le.__PosthogExtensions__)?void 0:r.initSessionRecording(this._instance,this._documentWasEverVisible),this._lazyLoadedSessionRecording._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this._isRemoteConfigFresh()){if(this._recordingStatus===Ll||this._recordingStatus===Al)return;return this._recordingStatus=Al,$l.info("persisted remote config is stale, requesting fresh config before starting"),void new xo(this._instance).load()}this._recordingStatus=Rl,null==(i=(s=this._lazyLoadedSessionRecording).setDocumentWasEverVisible)||i.call(s,this._documentWasEverVisible),this._lazyLoadedSessionRecording.start(e)}}onRRwebEmit(e){var t;null==(t=this._lazyLoadedSessionRecording)||null==t.onRRwebEmit||t.onRRwebEmit(e)}overrideLinkedFlag(){var e,t;this._lazyLoadedSessionRecording||null==(t=this._persistence)||t.register({[x]:!0}),null==(e=this._lazyLoadedSessionRecording)||e.overrideLinkedFlag()}overrideSampling(){var e,t;this._lazyLoadedSessionRecording||null==(t=this._persistence)||t.register({[S]:!0}),null==(e=this._lazyLoadedSessionRecording)||e.overrideSampling()}overrideTrigger(e){var t,i;this._lazyLoadedSessionRecording||null==(i=this._persistence)||i.register({["url"===e?E:k]:!0}),null==(t=this._lazyLoadedSessionRecording)||t.overrideTrigger(e)}get sdkDebugProperties(){var e;return(null==(e=this._lazyLoadedSessionRecording)?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,t){var i;return!(null==(i=this._lazyLoadedSessionRecording)||!i.tryAddCustomEvent(e,t))}}},Eu={autocapture:class extends bl{constructor(e){super(new wl(e)),this.instance=e}},historyAutocapture:class{constructor(e){this._instance=e,this._lastLocation=this._getCurrentLocation()}initialize(){this.startIfEnabled()}get isEnabled(){var e=this._getCaptureOptions();return!!(e.path||e.search||this._shouldCaptureHashChanges(e))}startIfEnabled(){this.isEnabled&&(Ws.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}startIfEnabledOrStop(){this.stop(),this._lastLocation=this._getCurrentLocation(),this.startIfEnabled()}stop(){this._popstateListener&&this._popstateListener(),this._popstateListener=void 0,this._hashchangeListener&&this._hashchangeListener(),this._hashchangeListener=void 0,Ws.info("History API monitoring stopped")}monitorHistoryChanges(){we&&we.history&&(this._patchHistoryMethod("pushState"),this._patchHistoryMethod("replaceState"),this._setupPopstateListener(),this._shouldCaptureHashChanges()&&this._setupHashchangeListener())}_patchHistoryMethod(e){var t;if(we&&(null==(t=we.history[e])||!t.__posthog_wrapped__)){var i=this;!function(e,t,i){try{if(!(t in e))return xl;var s={next:e[t]},r=i((function(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];return s.next.apply(this,t)}));return pt(r)&&(r.prototype=r.prototype||{},Object.defineProperties(r,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:s}})),e[t]=r,()=>{if(e[t]!==r)for(var i=e[t];pt(i)&&i.__posthog_layer__;){var n=i.__posthog_layer__;if(n.next===r)return void(n.next=s.next);i=n.next}else e[t]=s.next}}catch(e){return xl}}(we.history,e,(t=>function(s,r,n){t.call(this,s,r,n),i._capturePageview(e)}))}}_getCurrentLocation(){var e=null==we?void 0:we.location;if(null!=e&&e.pathname)return{pathname:e.pathname,search:e.search,hash:e.hash}}_getCaptureOptions(){var e=this._instance.config.capture_pageview;return"history_change"===e?{path:!0}:gt(e)?e:{}}_shouldCaptureHashChanges(e){return void 0===e&&(e=this._getCaptureOptions()),!!e.hash&&!this._instance.config.disable_capture_url_hashes}_hasLocationChanged(e){var t=this._getCaptureOptions(),i=this._lastLocation;return!(!i||!(t.path&&e.pathname!==i.pathname||t.search&&e.search!==i.search||this._shouldCaptureHashChanges(t)&&e.hash!==i.hash))}_capturePageview(e){try{var t=this._getCurrentLocation();if(!t)return;this._hasLocationChanged(t)&&this._instance.capture(fe,{navigation_type:e}),this._lastLocation=t}catch(t){Ws.error("Error capturing "+e+" pageview",t)}}_setupPopstateListener(){if(!this._popstateListener){var e=()=>{this._capturePageview("popstate")};sr(we,"popstate",e),this._popstateListener=()=>{we&&we.removeEventListener("popstate",e)}}}_setupHashchangeListener(){if(!this._hashchangeListener){var e=()=>{this._capturePageview("hashchange")};sr(we,"hashchange",e),this._hashchangeListener=()=>{we&&we.removeEventListener("hashchange",e)}}}},heatmaps:class{get _config(){return this.instance.config}constructor(e){var t;this._enabledServerSide=!1,this._initialized=!1,this._flushInterval=null,this.instance=e,this._enabledServerSide=!(null==(t=this.instance.persistence)||!t.props[h]),this.rageclicks=new pl(e.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var e=5e3;return gt(this._config.capture_heatmaps)&&this._config.capture_heatmaps.flush_interval_milliseconds&&(e=this._config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return wt(this._config.capture_heatmaps)?wt(this._config.enable_heatmaps)?this._enabledServerSide:this._config.enable_heatmaps:!1!==this._config.capture_heatmaps}startIfEnabled(){if(this.isEnabled){if(this._initialized)return;Ol.info("starting..."),this._setupListeners(),this._onVisibilityChange()}else{var e;clearInterval(null!==(e=this._flushInterval)&&void 0!==e?e:void 0),this._removeListeners(),this.getAndClearBuffer()}}onRemoteConfig(e){if(e.ok){var t=e.config;if("heatmaps"in t){var i=!!t.heatmaps;this.instance.persistence&&this.instance.persistence.register({[h]:i}),this._enabledServerSide=i,this.startIfEnabled()}}}getAndClearBuffer(){var e=this._buffer;return this._buffer=void 0,e}_onDeadClick(e){Dl(e.originalEvent)&&this._onClick(e.originalEvent,"deadclick")}_onVisibilityChange(){this._flushInterval&&clearInterval(this._flushInterval),this._flushInterval=function(e){return"visible"===(null==e?void 0:e.visibilityState)}(Ee)?setInterval(this._flush.bind(this),this.flushIntervalMilliseconds):null}_setupListeners(){we&&Ee&&(this._flushHandler=this._flush.bind(this),sr(we,ve,this._flushHandler),this._onClickHandler=e=>this._onClick(e||(null==we?void 0:we.event)),sr(Ee,"click",this._onClickHandler,{capture:!0}),this._onMouseMoveHandler=e=>this._onMouseMove(e||(null==we?void 0:we.event)),sr(Ee,"mousemove",this._onMouseMoveHandler,{capture:!0}),this._deadClicksCapture=new Pn(this.instance,En,this._onDeadClick.bind(this)),this._deadClicksCapture.startIfEnabledOrStop(),this._onVisibilityChange_handler=this._onVisibilityChange.bind(this),sr(Ee,ge,this._onVisibilityChange_handler),this._initialized=!0)}_removeListeners(){var e;we&&Ee&&(this._flushHandler&&we.removeEventListener(ve,this._flushHandler),this._onClickHandler&&Ee.removeEventListener("click",this._onClickHandler,{capture:!0}),this._onMouseMoveHandler&&Ee.removeEventListener("mousemove",this._onMouseMoveHandler,{capture:!0}),this._onVisibilityChange_handler&&Ee.removeEventListener(ge,this._onVisibilityChange_handler),clearTimeout(this._mouseMoveTimeout),null==(e=this._deadClicksCapture)||e.stop(),this._initialized=!1)}_getProperties(e,t){var i=this.instance.scrollManager.scrollY(),s=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),n=function(e,t,i){for(var s=e;s&&qr(s)&&!Hr(s,"body");){if(s===i)return!1;var r=void 0;try{var n,o,a;r=null==(n=null!==(o=null==(a=s.ownerDocument)?void 0:a.defaultView)&&void 0!==o?o:we)?void 0:n.getComputedStyle(s).position}catch(e){return!1}if(ot(t,r))return!0;s=Zr(s)}return!1}(Qr(e),["fixed","sticky"],r);return{x:e.clientX+(n?0:s),y:e.clientY+(n?0:i),target_fixed:n,type:t}}_onClick(e,t){var s;if(void 0===t&&(t="click"),!Br(e.target)&&Dl(e)){var r=this._getProperties(e,t);null!=(s=this.rageclicks)&&s.isRageClick(e.clientX,e.clientY,(new Date).getTime())&&on(Qr(e),this.instance.config.rageclick)&&this._capture(i({},r,{type:"rageclick"})),this._capture(r)}}_onMouseMove(e){!Br(e.target)&&Dl(e)&&(clearTimeout(this._mouseMoveTimeout),this._mouseMoveTimeout=setTimeout((()=>{this._capture(this._getProperties(e,"mousemove"))}),500))}_capture(e){if(we){var t=this._config.disable_capture_url_hashes?Ui(we.location.href):we.location.href,i=this._config.custom_personal_data_properties,s=this._config.mask_personal_data_properties?[...Un,...i||[]]:[],r=qn(t,s,Wn);this._buffer=this._buffer||{},this._buffer[r]||(this._buffer[r]=[]),this._buffer[r].push(e)}}_flush(){this._buffer&&!vt(this._buffer)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Pn,webVitalsAutocapture:class{constructor(e){var t;this._enabledServerSide=!1,this._initialized=!1,this._buffer={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this._flushToCapture=()=>{clearTimeout(this._delayedFlushTimer),this._delayedFlushTimer=void 0,0!==this._buffer.metrics.length&&(this._instance.capture("$web_vitals",i({$current_url:this._buffer.url},this._buffer.metrics.reduce(((e,t)=>i({},e,{["$web_vitals_"+t.name+"_event"]:i({},t),["$web_vitals_"+t.name+"_value"]:t.value})),{}))),this._buffer={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this._addToBuffer=e=>{var t;if(this._buffer=this._buffer||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},wt(null==e?void 0:e.name)||wt(null==e?void 0:e.value))kl.error("Invalid metric received",e);else{var s="string"==typeof e.navigationURL?e.navigationURL:void 0,r=this._maskedURL(s);if(!ft(r)){var n=St(e.navigationId)||"string"==typeof e.navigationId?"navigation:"+e.navigationId:"url:"+r;if(!this._maxAllowedValue||this._maxAllowedValue>e.value){this._buffer.navigationKey!==n&&(this._flushToCapture(),this._delayedFlushTimer=setTimeout(this._flushToCapture,this.flushToCaptureTimeoutMs)),ft(this._buffer.navigationKey)&&(this._buffer.navigationKey=n,this._buffer.url=r),this._buffer.firstMetricTimestamp=ft(this._buffer.firstMetricTimestamp)?Date.now():this._buffer.firstMetricTimestamp;var o=null==(t=this._instance.sessionManager)?void 0:t.checkAndGetSessionAndWindowId(!0),a=i({},e,s?{navigationURL:r}:{},{$current_url:r,timestamp:Date.now()});if(delete a.entries,gt(e.attribution)&&this.attributionMetrics.indexOf(e.name)>-1){var l={};for(var u of Fl){var c="url"===u&&"string"==typeof e.attribution[u]?this._maskedURL(e.attribution[u]):e.attribution[u];ft(c)||(l[u]=c)}a.attribution=l}else delete a.attribution;ft(o)||(a.$session_id=o.sessionId,a.$window_id=o.windowId),this._buffer.metrics.push(a),this._buffer.metrics.length===this.allowedMetrics.length&&this._flushToCapture()}else kl.error("Ignoring metric with value >= "+this._maxAllowedValue,e)}}},this._startCapturing=()=>{if(!this._initialized){var e,t,s,r,n=!1,o=Le.__PosthogExtensions__,a=null==o?void 0:o.postHogWebVitalsCallbacksByFlavor,l=(null==a?void 0:a[this._callbackFlavor])||("web-vitals"===this._callbackFlavor&&ft(a)?null==o?void 0:o.postHogWebVitalsCallbacks:void 0);if(!ft(l)){var u=l.withoutAttribution,c=this.attributionMetrics;n=!ft(u),e=c.indexOf("LCP")>-1?l.onLCP:(null==u?void 0:u.onLCP)||l.onLCP,t=c.indexOf("CLS")>-1?l.onCLS:(null==u?void 0:u.onCLS)||l.onCLS,s=c.indexOf("FCP")>-1?l.onFCP:(null==u?void 0:u.onFCP)||l.onFCP,r=c.indexOf("INP")>-1?l.onINP:(null==u?void 0:u.onINP)||l.onINP}if(e&&t&&s&&r){var d={reportSoftNavs:this.useSoftNavs},h=n&&this.attributionMetrics.indexOf("INP")>-1?i({},d,{includeProcessedEventEntries:!1}):d;this.allowedMetrics.indexOf("LCP")>-1&&e(this._addToBuffer.bind(this),d),this.allowedMetrics.indexOf("CLS")>-1&&t(this._addToBuffer.bind(this),d),this.allowedMetrics.indexOf("FCP")>-1&&s(this._addToBuffer.bind(this),d),this.allowedMetrics.indexOf("INP")>-1&&r(this._addToBuffer.bind(this),h),this._initialized=!0}else kl.error("web vitals callbacks not loaded - not starting")}},this._instance=e,this._enabledServerSide=!(null==(t=this._instance.persistence)||!t.props[v]),this.startIfEnabled()}get _perfConfig(){return this._instance.config.capture_performance}get allowedMetrics(){var e,t,i=gt(this._perfConfig)?null==(e=this._perfConfig)?void 0:e.web_vitals_allowed_metrics:void 0;return wt(i)?(null==(t=this._instance.persistence)?void 0:t.props[y])||Cl:i}get flushToCaptureTimeoutMs(){return(gt(this._perfConfig)?this._perfConfig.web_vitals_delayed_flush_ms:void 0)||5e3}get attributionMetrics(){var e=gt(this._perfConfig)?this._perfConfig.web_vitals_attribution:void 0;return Et(e)?e?Cl:[]:_t(e)?e:Il}get useAttribution(){return this.attributionMetrics.length>0}get useSoftNavs(){var e=gt(this._perfConfig)?this._perfConfig.__preview_web_vitals_soft_navs:void 0;return null!=e&&e}get _maxAllowedValue(){var e=gt(this._perfConfig)&&St(this._perfConfig.__web_vitals_max_value)?this._perfConfig.__web_vitals_max_value:Pl;return e>0&&6e4>=e?Pl:e}get isEnabled(){var e=null==ke?void 0:ke.protocol;if("http:"!==e&&"https:"!==e)return kl.info("Web Vitals are disabled on non-http/https protocols"),!1;var t=gt(this._perfConfig)?this._perfConfig.web_vitals:Et(this._perfConfig)?this._perfConfig:void 0;return Et(t)?t:this._enabledServerSide}startIfEnabled(){this.isEnabled&&!this._initialized&&(kl.info("enabled, starting..."),this._loadScript(this._startCapturing))}onRemoteConfig(e){if(e.ok){var t=e.config;if("capturePerformance"in t){var i=gt(t.capturePerformance)&&!!t.capturePerformance.web_vitals,s=gt(t.capturePerformance)?t.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[v]:i}),this._instance.persistence.register({[y]:s})),this._enabledServerSide=i,this.startIfEnabled()}}}get _callbackFlavor(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}_loadScript(e){var t=Le.__PosthogExtensions__,i=this._callbackFlavor,s=null==t?void 0:t.postHogWebVitalsCallbacksByFlavor;null!=s&&s[i]||"web-vitals"===i&&ft(s)&&null!=t&&t.postHogWebVitalsCallbacks?e():null==t||null==t.loadExternalDependency||t.loadExternalDependency(this._instance,i,(t=>{t?kl.error("failed to load script",t):e()}))}_maskedURL(e){var t=e||(null==we?void 0:we.location.href);if(t){var i=this._instance.config.disable_capture_url_hashes?Ui(t):t,s=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...Un,...s||[]]:[];return qn(i,r,Wn)}kl.error("Could not determine current URL")}}},ku={exceptionObserver:class{constructor(e){var t;this._startCapturing=()=>{var e;if(we&&this.isEnabled&&null!=(e=Le.__PosthogExtensions__)&&e.errorWrappingFunctions){var t=Le.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=Le.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=Le.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this._unwrapOnError&&this._config.capture_unhandled_errors&&(this._unwrapOnError=t(this.captureException.bind(this))),!this._unwrapUnhandledRejection&&this._config.capture_unhandled_rejections&&(this._unwrapUnhandledRejection=i(this.captureException.bind(this))),!this._unwrapConsoleError&&this._config.capture_console_errors&&(this._unwrapConsoleError=s(this.captureException.bind(this)))}catch(e){Sl.error("failed to start",e),this._stopCapturing()}}},this._instance=e,this._remoteEnabled=!(null==(t=this._instance.persistence)||!t.props[_]),this._rateLimiter=new Dt(i({},function(e){var t,i,s,r;return void 0===e&&(e={}),{refillRate:null!==(t=null!==(i=e.exceptionRateLimiterRefillRate)&&void 0!==i?i:e.__exceptionRateLimiterRefillRate)&&void 0!==t?t:1,bucketSize:null!==(s=null!==(r=e.exceptionRateLimiterBucketSize)&&void 0!==r?r:e.__exceptionRateLimiterBucketSize)&&void 0!==s?s:10}}(this._instance.config.error_tracking),{refillInterval:1e4,_logger:Sl})),this._config=this._requiredConfig(),this.startIfEnabledOrStop()}_requiredConfig(){var e=this._instance.config.capture_exceptions,t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return gt(e)?t=i({},t,e):(ft(e)?this._remoteEnabled:e)&&(t=i({},t,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),t}get isEnabled(){return this._config.capture_console_errors||this._config.capture_unhandled_errors||this._config.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Sl.info("enabled"),this._stopCapturing(),this._loadScript(this._startCapturing)):this._stopCapturing()}_loadScript(e){var t,i;null!=(t=Le.__PosthogExtensions__)&&t.errorWrappingFunctions?e():null==(i=Le.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,"exception-autocapture",(t=>{if(t)return Sl.error("failed to load script",t);e()}))}_stopCapturing(){var e,t,i;null==(e=this._unwrapOnError)||e.call(this),this._unwrapOnError=void 0,null==(t=this._unwrapUnhandledRejection)||t.call(this),this._unwrapUnhandledRejection=void 0,null==(i=this._unwrapConsoleError)||i.call(this),this._unwrapConsoleError=void 0}onRemoteConfig(e){if(e.ok){var t=e.config;"autocaptureExceptions"in t&&(this._remoteEnabled=!!t.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[_]:this._remoteEnabled}),this._config=this._requiredConfig(),this.startIfEnabledOrStop())}}onConfigChange(){this._config=this._requiredConfig()}captureException(e){var t,i,s,r=null!==(t=null==e||null==(i=e.$exception_list)||null==(i=i[0])?void 0:i.type)&&void 0!==t?t:"Exception";this._rateLimiter.consumeRateLimit(r)?Sl.info("Skipping exception capture because of client rate limiting.",{exception:r}):null==(s=this._instance.exceptions)||s.sendExceptionEvent(e)}},exceptions:class{constructor(e){var t,s;this._suppressionRules=[],this._errorPropertiesBuilder=new gs([new Cs,new Ds,new Fs,new Is,new $s,new Ms,new Rs,new Os],function(e){for(var t=arguments.length,s=new Array(t>1?t-1:0),r=1;t>r;r++)s[r-1]=arguments[r];return function(t,r){void 0===r&&(r=0);for(var n=[],o=t.split("\n"),a=r;o.length>a;a++){var l=o[a];if(1024>=l.length){var u=Ps.test(l)?l.replace(Ps,"$1"):l;if(!u.match(/\S*Error: /)){for(var c of s){var d=c(u,e);if(d){n.push(d);break}}if(n.length>=50)break}}}return function(e){if(!e.length)return[];var t=Array.from(e);return t.reverse(),t.slice(0,50).map((e=>{return i({},e,{filename:e.filename||(s=t,s[s.length-1]||{}).filename,function:e.function||vs});var s}))}(n)}}("web:javascript",Ss,ks)),this._instance=e,this._suppressionRules=null!==(t=null==(s=this._instance.persistence)?void 0:s.get_property(p))&&void 0!==t?t:[],this._exceptionStepsConfig=zs(this._getExceptionStepsConfig()),this._exceptionStepsBuffer=new js(this._exceptionStepsConfig)}onConfigChange(){this._exceptionStepsConfig=zs(this._getExceptionStepsConfig()),this._exceptionStepsBuffer.setConfig(this._exceptionStepsConfig)}onRemoteConfig(e){var t,i,s;if(e.ok){var r=e.config;if("errorTracking"in r){var n=null!==(t=null==(i=r.errorTracking)?void 0:i.suppressionRules)&&void 0!==t?t:[],o=null==(s=r.errorTracking)?void 0:s.captureExtensionExceptions;this._suppressionRules=n,this._instance.persistence&&this._instance.persistence.register({[p]:this._suppressionRules,[g]:o})}}}get _captureExtensionExceptions(){var e,t=!!this._instance.get_property(g),i=this._instance.config.error_tracking.captureExtensionExceptions;return null!==(e=null!=i?i:t)&&void 0!==e&&e}buildProperties(e,t){return this._errorPropertiesBuilder.buildFromUnknown(e,{syntheticException:null==t?void 0:t.syntheticException,mechanism:{handled:null==t?void 0:t.handled}})}addExceptionStep(e,t){if(this._exceptionStepsConfig.enabled)try{if(!mt(e)||0===e.trim().length)return void cu.warn("Ignoring exception step because message must be a non-empty string");var s=function(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};var t=[];return{sanitizedProperties:Object.keys(e).reduce(((i,s)=>Hs.has(s)?(t.push(s),i):(i[s]=e[s],i)),{}),droppedKeys:t}}(this._coerceExceptionStepProperties(t)),r=s.sanitizedProperties,n=s.droppedKeys;n.length>0&&cu.warn("Ignoring reserved exception step fields",{droppedKeys:n}),this._exceptionStepsBuffer.add(i({[Bs]:e,[qs]:(new Date).toISOString()},r))}catch(e){cu.error("Failed to add exception step. Ignoring breadcrumb.",e)}}sendExceptionEvent(e){try{var t=e.$exception_list;if(this._isExceptionList(t)){if(this._matchesSuppressionRule(t))return this._addDroppedExceptionStep("Exception dropped: matched a suppression rule"),void cu.info("Skipping exception capture because a suppression rule matched");if(!this._captureExtensionExceptions&&this._isExtensionException(t))return this._addDroppedExceptionStep("Exception dropped: thrown by a browser extension"),void cu.info("Skipping exception capture because it was thrown by an extension");if(!this._captureExtensionExceptions&&this._isInjectedBrowserScriptException(t))return this._addDroppedExceptionStep("Exception dropped: thrown by an injected browser script"),void cu.info("Skipping exception capture because it was thrown by an injected browser script");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this._isPostHogException(t))return this._addDroppedExceptionStep("Exception dropped: thrown by the PostHog SDK"),void cu.info("Skipping exception capture because it was thrown by the PostHog SDK")}var i=this._exceptionStepsConfig.enabled&&wt(e.$exception_steps)?this._addBufferedExceptionSteps(e):e,s="string"==typeof(n=globalThis._posthogReleaseId)&&n.length>0?n:void 0;s&&(i.$release_id=s);try{var r=this._instance.capture("$exception",i,{_noTruncate:!0,_batchKey:"exceptionEvent",_originatedFromCaptureException:!0});return r&&this._exceptionStepsBuffer.clear(),r}catch(e){return cu.error("Failed to capture exception event. Dropping this exception.",e),void this._exceptionStepsBuffer.clear()}}catch(e){return void cu.error("Failed to process exception event. Ignoring this exception.",e)}var n}_addBufferedExceptionSteps(e){try{var t=this._exceptionStepsBuffer.getAttachable();return 0===t.length?e:i({},e,{$exception_steps:t})}catch(t){return cu.error("Failed to read buffered exception steps. Capturing exception without steps.",t),e}}_addDroppedExceptionStep(e){this._exceptionStepsConfig.enabled&&this._exceptionStepsBuffer.add({[Bs]:e,[qs]:(new Date).toISOString()})}_coerceExceptionStepProperties(e){return gt(e)?i({},e):{}}_getExceptionStepsConfig(){var e,t;return null!==(e=null==(t=this._instance.config.error_tracking)?void 0:t.exception_steps)&&void 0!==e?e:{}}_matchesSuppressionRule(e){if(0===e.length)return!1;try{var t=e.reduce(((e,t)=>{var i=t.type,s=t.value;return mt(i)&&i.length>0&&e.$exception_types.push(i),mt(s)&&s.length>0&&e.$exception_values.push(s),e}),{$exception_types:[],$exception_values:[]});return this._suppressionRules.some((e=>{var i=e.values.map((e=>{var i=La[e.operator],s=t[e.key];if(!i||!s)return!1;var r=_t(e.value)?e.value:[e.value];return r.length>0&&i(r,s)}));return"OR"===e.type?i.some(Boolean):i.every(Boolean)}))}catch(e){return cu.warn("Failed to evaluate suppression rules. Capturing the exception.",e),!1}}_isExtensionException(e){return e.flatMap((e=>{var t,i;return null!==(t=null==(i=e.stacktrace)?void 0:i.frames)&&void 0!==t?t:[]})).some((e=>{var t=e.filename;return!!t&&du.some((e=>t.startsWith(e)))}))}_isInjectedBrowserScriptException(e){return e.some((e=>{var t=e.value;return mt(t)&&hu.some((e=>t.includes(e)))}))}_isPostHogException(e){if(e.length>0){var t,i,s,r,n=null!==(t=null==(i=e[0].stacktrace)?void 0:i.frames)&&void 0!==t?t:[],o=n[n.length-1];return null!==(s=null==o||null==(r=o.filename)?void 0:r.includes("posthog.com/static"))&&void 0!==s&&s}return!1}_isExceptionList(e){return!wt(e)&&_t(e)}}},Pu=i({productTours:class{get _persistence(){return this._instance.persistence}constructor(e){this._productTourManager=null,this._cachedTours=null,this._instance=e}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(e.ok){var t=e.config;if("productTours"in t){var i,s;if(this._persistence&&this._persistence.register({[m]:!!t.productTours}),!ql(this._instance))return!this._productTourManager&&wt(null==(i=this._persistence)?void 0:i.props[W])||Bl.info("product tours disabled; stopping and clearing cached tours"),null==(s=this._productTourManager)||s.stop(),this._productTourManager=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this._productTourManager&&ql(this._instance)&&this._loadScript((()=>this._startProductTours()))}_loadScript(e){var t,i;null!=(t=Le.__PosthogExtensions__)&&t.generateProductTours?e():null==(i=Le.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,"product-tours",(t=>{t?Bl.error("Could not load product tours script",t):e()}))}_startProductTours(){var e;!this._productTourManager&&null!=(e=Le.__PosthogExtensions__)&&e.generateProductTours&&(this._productTourManager=Le.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t){if(void 0===t&&(t=!1),!_t(this._cachedTours)||t){var i=this._persistence;if(i){var s=i.props[W];if(_t(s)&&!t)return this._cachedTours=s,void e(s,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:t=>{if(ql(this._instance)){var s=t.statusCode;if(200!==s||!t.json){var r="Product Tours API could not be loaded, status: "+s;return 0===s?t.error||Bl.warn(r):Bl.error(r),void e([],{isLoaded:!1,error:r})}var n=_t(t.json.product_tours)?t.json.product_tours:[];this._cachedTours=n,i&&i.register({[W]:n}),e(n,{isLoaded:!0})}else e([],{isLoaded:!0})}})}else e(this._cachedTours,{isLoaded:!0})}getActiveProductTours(e){wt(this._productTourManager)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this._productTourManager.getActiveProductTours(e)}showProductTour(e){var t;null==(t=this._productTourManager)||t.showTourById(e)}previewTour(e){this._productTourManager?this._productTourManager.previewTour(e):this._loadScript((()=>{var t;this._startProductTours(),null==(t=this._productTourManager)||t.previewTour(e)}))}dismissProductTour(){var e;null==(e=this._productTourManager)||e.dismissTour("user_clicked_skip")}nextStep(){var e;null==(e=this._productTourManager)||e.nextStep()}previousStep(){var e;null==(e=this._productTourManager)||e.previousStep()}clearCache(){var e;this._cachedTours=null,null==(e=this._persistence)||e.unregister(W)}resetTour(e){var t;null==(t=this._productTourManager)||t.resetTour(e)}resetAllTours(){var e;null==(e=this._productTourManager)||e.resetAllTours()}cancelPendingTour(e){var t;null==(t=this._productTourManager)||t.cancelPendingTour(e)}}},Su),Cu={siteApps:class{constructor(e){this._siteAppElementPatchCount=0,this._instance=e,this._bufferedInvocations=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}_eventCollector(e,t){if(t){var i=this.globalsForEvent(t);this._bufferedInvocations.push(i),this._bufferedInvocations.length>1e3&&(this._bufferedInvocations=this._bufferedInvocations.slice(10))}}get siteAppLoaders(){var e;return null==(e=Le._POSTHOG_REMOTE_CONFIG)||null==(e=e[this._instance.config.token])?void 0:e.siteApps}initialize(){if(this.isEnabled){var e=this._instance._addCaptureHook(this._eventCollector.bind(this));this._stopBuffering=()=>{e(),this._bufferedInvocations=[],this._stopBuffering=void 0}}}globalsForEvent(e){var t,r,n,o,a,l,u;if(!e)throw new Error("Event payload is required");var c={},d=this._instance.get_property("$groups")||[],h=this._instance.get_property("$stored_group_properties")||{};for(var _ of Object.entries(h)){var p=_[0];c[p]={id:d[p],type:p,properties:_[1]}}var g=e.$set_once,v=e.$set;return{event:i({},s(e,Hl),{properties:i({},e.properties,v?{$set:i({},null!==(t=null==(r=e.properties)?void 0:r.$set)&&void 0!==t?t:{},v)}:{},g?{$set_once:i({},null!==(n=null==(o=e.properties)?void 0:o.$set_once)&&void 0!==n?n:{},g)}:{}),elements_chain:null!==(a=null==(l=e.properties)?void 0:l.$elements_chain)&&void 0!==a?a:"",distinct_id:null==(u=e.properties)?void 0:u.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:c}}_prepareElementForSiteApp(e){var t,i=null==(t=e.tagName)?void 0:t.toLowerCase();return"style"===i&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(e)||(Nl.error("prepare_external_dependency_stylesheet returned null"),null):"script"===i&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(e)||(Nl.error("prepare_external_dependency_script returned null"),null):e}_patchSiteAppElementInsertionMethods(){var e,t,i,s,r,n,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=null==Ee?void 0:Ee.defaultView,u=null==l||null==(e=l.Node)?void 0:e.prototype;if(!l||!u)return()=>{};if(this._siteAppElementPatchCount++,this._restoreSiteAppElementPatches)return this._releaseSiteAppElementPatches();var c=[],d=this,h=new WeakSet,_=(e,t,i)=>{if(null!=e&&e[t]){var s=e[t];e[t]=i(s),c.push((()=>{e[t]=s}))}},p=e=>{if(h.has(e))return e;var t=d._prepareElementForSiteApp(e);return t&&h.add(t),t},g=e=>e.map((e=>"string"==typeof e?e:p(e))).filter((e=>!bt(e)));return _(u,"appendChild",(e=>function(t){var i=p(t);return i?e.call(this,i):t})),_(u,"insertBefore",(e=>function(t,i){var s=p(t);return s?e.call(this,s,i):t})),_(u,"replaceChild",(e=>function(t,i){var s=p(t);return s?e.call(this,s,i):i})),[null==(t=l.Element)?void 0:t.prototype,null==(i=l.Document)?void 0:i.prototype,null==(s=l.DocumentFragment)?void 0:s.prototype].forEach((e=>{_(e,"append",(e=>function(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];return e.apply(this,g(i))})),_(e,"prepend",(e=>function(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];return e.apply(this,g(i))}))})),[null==(r=l.Element)?void 0:r.prototype,null==(n=l.CharacterData)?void 0:n.prototype,null==(o=l.DocumentType)?void 0:o.prototype].forEach((e=>{_(e,"before",(e=>function(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];return e.apply(this,g(i))})),_(e,"after",(e=>function(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];return e.apply(this,g(i))})),_(e,"replaceWith",(e=>function(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];var r=g(i);return i.length&&!r.length?void 0:e.apply(this,r)}))})),_(null==(a=l.Element)?void 0:a.prototype,"insertAdjacentElement",(e=>function(t,i){var s=p(i);return s?e.call(this,t,s):null})),this._restoreSiteAppElementPatches=()=>{c.forEach((e=>e())),this._restoreSiteAppElementPatches=void 0},this._releaseSiteAppElementPatches()}_releaseSiteAppElementPatches(){var e=!1;return()=>{var t;e||(e=!0,this._siteAppElementPatchCount--,0===this._siteAppElementPatchCount&&(null==(t=this._restoreSiteAppElementPatches)||t.call(this)))}}_runWithPreparedSiteAppElements(e,t){void 0===t&&(t=!0);var i=this._patchSiteAppElementInsertionMethods();try{var s=e(i);return t&&i(),s}catch(e){throw i(),e}}setupSiteApp(e){var t=this.apps[e.id],i=()=>{var i;!t.errored&&this._bufferedInvocations.length&&(Nl.info("Processing "+this._bufferedInvocations.length+" events for site app with id "+e.id),this._bufferedInvocations.forEach((e=>this._runWithPreparedSiteAppElements((()=>null==t.processEvent?void 0:t.processEvent(e))))),t.processedBuffer=!0),Object.values(this.apps).every((e=>e.processedBuffer||e.errored))&&(null==(i=this._stopBuffering)||i.call(this))},s=!1,r=r=>{t.errored=!r,t.loaded=!0,Nl.info("Site app with id "+e.id+" "+(r?"loaded":"errored")),s&&i()};try{var n=this._runWithPreparedSiteAppElements((t=>e.init({posthog:this._instance,callback(e){t(),r(e)}})),!1).processEvent;n&&(t.processEvent=n),s=!0}catch(t){Nl.error(zl+e.id,t),r(!1)}if(s&&t.loaded)try{i()}catch(i){Nl.error("Error while processing buffered events PostHog app with config id "+e.id,i),t.errored=!0}}_setupSiteApps(){var e=this.siteAppLoaders||[];for(var t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(var i of e)this.setupSiteApp(i)}_onCapturedEvent(e){var t=this;if(0!==Object.keys(this.apps).length){var i=this.globalsForEvent(e),s=function(s){try{t._runWithPreparedSiteAppElements((()=>null==s.processEvent?void 0:s.processEvent(i)))}catch(t){Nl.error("Error while processing event "+e.event+" for site app "+s.id,t)}};for(var r of Object.values(this.apps))s(r)}}onRemoteConfig(e){var t,i,s,r=this;if(null!=(t=this.siteAppLoaders)&&t.length)return this.isEnabled?(this._setupSiteApps(),void this._instance.on("eventCaptured",(e=>this._onCapturedEvent(e)))):void Nl.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if(null==(i=this._stopBuffering)||i.call(this),e.ok){var n=e.config;if(null!=(s=n.siteApps)&&s.length)if(this.isEnabled){var o=function(){var e,t=a.id,i=a.url;Le["__$$ph_site_app_"+t]=r._instance,null==(e=Le.__PosthogExtensions__)||null==e.loadSiteApp||e.loadSiteApp(r._instance,i,(e=>{if(e)return Nl.error(zl+t,e)}))};for(var a of n.siteApps)o()}else Nl.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Iu={tracingHeaders:class{constructor(e){this._restoreXHRPatch=void 0,this._restoreFetchPatch=void 0,this._hostnamesForPatch=void 0,this._startCapturing=()=>{var e,t,i=this._syncHostnamesForPatch();i?(ft(this._restoreXHRPatch)&&(this._restoreXHRPatch=null==(e=Le.__PosthogExtensions__)||null==(e=e.tracingHeadersPatchFns)?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),ft(this._restoreFetchPatch)&&(this._restoreFetchPatch=null==(t=Le.__PosthogExtensions__)||null==(t=t.tracingHeadersPatchFns)?void 0:t._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this._stopCapturing()},this._instance=e}initialize(){this.startIfEnabledOrStop()}_loadScript(e){var t,i;null!=(t=Le.__PosthogExtensions__)&&t.tracingHeadersPatchFns?e():null==(i=Le.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,"tracing-headers",(t=>{if(t)return El.error("failed to load script",t);e()}))}_getConfiguredHostnames(){var e,t;return null!==(e=null!==(t=this._instance.config.tracing_headers)&&void 0!==t?t:this._instance.config.addTracingHeaders)&&void 0!==e?e:this._instance.config.__add_tracing_headers}_syncHostnamesForPatch(){var e=this._getConfiguredHostnames();return _t(e)?(_t(this._hostnamesForPatch)?this._hostnamesForPatch.splice(0,this._hostnamesForPatch.length,...e):this._hostnamesForPatch=[...e],e.length>0?this._hostnamesForPatch:void 0):(_t(this._hostnamesForPatch)&&this._hostnamesForPatch.splice(0),this._hostnamesForPatch=e||void 0,this._hostnamesForPatch)}_stopCapturing(){var e,t;null==(e=this._restoreXHRPatch)||e.call(this),null==(t=this._restoreFetchPatch)||t.call(this),this._restoreXHRPatch=void 0,this._restoreFetchPatch=void 0}startIfEnabledOrStop(){this._syncHostnamesForPatch()?this._loadScript(this._startCapturing):this._stopCapturing()}}},Fu=i({surveys:class extends Wl{constructor(e){var t;super(new Zl(e),{get projectToken(){return t.config.token},kv:new Yl(t=e)}),this._instance=e}_sendSurveysRequest(e,t){var i=t.query?oa(e,t.query):e;return new Promise((e=>{var s;this._instance._send_request({method:t.method,url:this._instance.requestRouter.endpointFor(null!==(s=t.target)&&void 0!==s?s:"api",i),data:t.body,headers:t.headers,timeout:t.timeoutMs,fireCallbackOnDrop:!0,transport:t.transport,compression:t.compression,timestampMode:t.sentAt,callback:e})}))}}},Su),Tu={toolbar:class{constructor(e){this.instance=e}_setToolbarState(e){Le.ph_toolbar_state=e}_getToolbarState(){var e;return null!==(e=Le.ph_toolbar_state)&&void 0!==e?e:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(e,t,i){if(void 0===e&&(e=void 0),void 0===t&&(t=void 0),void 0===i&&(i=void 0),rr(this.instance.config))return!1;if(!we||!Ee)return!1;e=null!=e?e:we.location,i=null!=i?i:we.history;try{if(!t){try{we.localStorage.setItem("test","test"),we.localStorage.removeItem("test")}catch(e){return!1}t=null==we?void 0:we.localStorage}var s,r=Xl||Hn(e.hash,"__posthog")||Hn(e.hash,"state"),n=r?Zs((()=>JSON.parse(atob(decodeURIComponent(r)))))||Zs((()=>JSON.parse(decodeURIComponent(r)))):null;return n&&"ph_authorize"===n.action?((s=n).source="url",s&&Object.keys(s).length>0&&(n.desiredHash?e.hash=n.desiredHash:i?i.replaceState(i.state,"",e.pathname+e.search):e.hash="")):((s=JSON.parse(t.getItem(eu)||"{}")).source="localstorage",delete s.userIntent),!(!s.token||this.instance.config.token!==s.token||(this.loadToolbar(s),0))}catch(e){return!1}}_callLoadToolbar(e){var t=Le.ph_load_toolbar||Le.ph_load_editor;!wt(t)&&pt(t)?t(e,this.instance):tu.warn("No toolbar load function found")}loadToolbar(e){var t=!(null==Ee||!Ee.getElementById(Mr));if(!we||t)return!1;var s="custom"===this.instance.requestRouter.region&&this.instance.config.advanced_disable_toolbar_metrics,r=i({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},s?{instrument:!1}:{});if(we.localStorage.setItem(eu,JSON.stringify(i({},r,{source:void 0}))),2===this._getToolbarState())this._callLoadToolbar(r);else if(0===this._getToolbarState()){var n;this._setToolbarState(1),null==(n=Le.__PosthogExtensions__)||null==n.loadExternalDependency||n.loadExternalDependency(this.instance,"toolbar",(e=>{if(e)return tu.error("[Toolbar] Failed to load",e),void this._setToolbarState(0);this._setToolbarState(2),this._callLoadToolbar(r)})),sr(we,"turbolinks:load",(()=>{this._setToolbarState(0),this.loadToolbar(r)}))}return!0}_loadEditor(e){return this.loadToolbar(e)}maybeLoadEditor(e,t,i){return void 0===e&&(e=void 0),void 0===t&&(t=void 0),void 0===i&&(i=void 0),this.maybeLoadToolbar(e,t,i)}}},Ru=i({experiments:gu},Su),Au={conversations:class{constructor(e){this._isConversationsEnabled=void 0,this._conversationsManager=null,this._isInitializing=!1,this._remoteConfig=null,this._loadFailed=!1,this._instance=e}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(!this._instance.config.disable_conversations&&(this._remoteConfigSuccessful=e.ok,e.ok)){var t=e.config.conversations;wt(t)||(Et(t)?this._isConversationsEnabled=t:(this._isConversationsEnabled=t.enabled,this._remoteConfig=t),this.loadIfEnabled())}}reset(){var e;null==(e=this._conversationsManager)||e.reset(),this._conversationsManager=null,this._isConversationsEnabled=void 0,this._remoteConfig=null,this._remoteConfigSuccessful=void 0,this._loadFailed=!1}loadIfEnabled(){if(!(this._conversationsManager||this._isInitializing||this._instance.config.disable_conversations||rr(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var e=null==Le?void 0:Le.__PosthogExtensions__;if(e&&!ft(this._isConversationsEnabled)&&this._isConversationsEnabled)if(this._remoteConfig&&this._remoteConfig.token){this._isInitializing=!0;try{var t=e.initConversations;if(t)return this._completeInitialization(t),void(this._isInitializing=!1);var i=e.loadExternalDependency;if(!i)return void this._handleLoadError(ue);i(this._instance,"conversations",(t=>{t||!e.initConversations?this._handleLoadError("Could not load conversations script",t):this._completeInitialization(e.initConversations),this._isInitializing=!1}))}catch(e){this._handleLoadError("Error initializing conversations",e),this._isInitializing=!1}}else vu.error("Conversations enabled but missing token in remote config.")}}_completeInitialization(e){if(this._remoteConfig)try{this._conversationsManager=e(this._remoteConfig,this._instance),this._loadFailed=!1,vu.info("Conversations loaded successfully")}catch(e){this._handleLoadError("Error completing conversations initialization",e)}else vu.error("Cannot complete initialization: remote config is null")}_handleLoadError(e,t){vu.error(e,t),this._conversationsManager=null,this._isInitializing=!1,this._loadFailed=!0}show(){this._conversationsManager?this._conversationsManager.show():vu.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return!0===this._isConversationsEnabled&&!bt(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":rr(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":!1===this._remoteConfigSuccessful?"remote_config_failed":ft(this._isConversationsEnabled)?this._remoteConfigSuccessful?"disabled_in_project":"remote_config_pending":this._isConversationsEnabled?wt(this._remoteConfig)||!this._remoteConfig.token?"missing_token":null!=Le&&Le.__PosthogExtensions__?this._isInitializing?"initializing":this._loadFailed?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var e,t;return null!==(e=null==(t=this._conversationsManager)?void 0:t.isVisible())&&void 0!==e&&e}sendMessage(e,i,s){var r=this;return t((function*(){return r._conversationsManager?r._conversationsManager.sendMessage(e,i,s):(vu.warn(fu),null)}))()}getMessages(e,i){var s=this;return t((function*(){return s._conversationsManager?s._conversationsManager.getMessages(e,i):(vu.warn(fu),null)}))()}markAsRead(e){var i=this;return t((function*(){return i._conversationsManager?i._conversationsManager.markAsRead(e):(vu.warn(fu),null)}))()}getTickets(e){var i=this;return t((function*(){return i._conversationsManager?i._conversationsManager.getTickets(e):(vu.warn(fu),null)}))()}requestRestoreLink(e){var i=this;return t((function*(){return i._conversationsManager?i._conversationsManager.requestRestoreLink(e):(vu.warn(fu),null)}))()}restoreFromToken(e){var i=this;return t((function*(){return i._conversationsManager?i._conversationsManager.restoreFromToken(e):(vu.warn(fu),null)}))()}restoreFromUrlToken(){var e=this;return t((function*(){return e._conversationsManager?e._conversationsManager.restoreFromUrlToken():(vu.warn(fu),null)}))()}getCurrentTicketId(){var e,t;return null!==(e=null==(t=this._conversationsManager)?void 0:t.getCurrentTicketId())&&void 0!==e?e:null}getWidgetSessionId(){var e,t;return null!==(e=null==(t=this._conversationsManager)?void 0:t.getWidgetSessionId())&&void 0!==e?e:null}_onIdentityChanged(){var e;null==(e=this._conversationsManager)||e.setIdentity()}_onIdentityCleared(){var e;null==(e=this._conversationsManager)||e.clearIdentity()}}},Lu={logs:class{constructor(e){var t,s=this;this._isLogsEnabled=!1,this._isLoaded=!1,this._logger=Gs("[logs]"),this._coreLogger=i({},this._logger,{error(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];t.some(wu)||s._logger.error(...t)}}),this._queue=[],this._consoleQueue=[],this._consecutiveStatusZeroFailures=0,this._onReconnect=()=>{var e,t;this._consecutiveStatusZeroFailures=0,null==(e=this._core)||e.onReconnect(),null==(t=this._consoleCore)||t.onReconnect()},this._instance=e,this._instance&&null!=(t=this._instance.config.logs)&&t.captureConsoleLogs&&(this._isLogsEnabled=!0),we&&sr(we,"online",this._onReconnect)}_buildCore(e,t,i,s){var r,n=function(e,t){var i,s,r,n,o,a,l,u=null!==(i=null==e?void 0:e.flushIntervalMs)&&void 0!==i?i:3e3,c=null!==(s=null==e?void 0:e.maxBufferSize)&&void 0!==s?s:100,d=null!=t&&t.consoleCapture?void 0:null!==(r=null==e?void 0:e.maxLogsPerInterval)&&void 0!==r?r:1e3,h=ft(d)?Math.max(c,2048):Math.max(c,d),_=null==e?void 0:e.resourceAttributes;return{serviceName:null!==(n=null!==(o=null==_?void 0:_["service.name"])&&void 0!==o?o:null==e?void 0:e.serviceName)&&void 0!==n?n:null==t?void 0:t.serviceNameDefault,serviceVersion:null!==(a=null==_?void 0:_["service.version"])&&void 0!==a?a:null==e?void 0:e.serviceVersion,environment:null!==(l=null==_?void 0:_["deployment.environment"])&&void 0!==l?l:null==e?void 0:e.environment,resourceAttributes:_,beforeSend:null==e?void 0:e.beforeSend,flushIntervalMs:u,maxBufferSize:c,maxQueueSize:h,maxBatchRecordsPerPost:100,rateCapWindowMs:u,maxLogsPerInterval:d,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}}(null==(r=this._instance)||null==(r=r.config)?void 0:r.logs,i);return[new os(this._createHost(e,t),n,this._coreLogger,(()=>this._getSdkContext()),(e=>e()),void 0,s),n]}_getCore(){var e,t=null==(e=this._instance)||null==(e=e.config)?void 0:e.logs;if(!this._core||this._resolvedFrom!==t){var i;null==(i=this._core)||i.reset(),this._resolvedFrom=t;var s=this._buildCore((()=>this._queue),(e=>{this._queue=e}));this._core=s[0],this._resolvedConfig=s[1]}return this._core}_getConsoleCore(){var e,t=null==(e=this._instance)||null==(e=e.config)?void 0:e.logs;if(!this._consoleCore||this._consoleResolvedFrom!==t){var i;null==(i=this._consoleCore)||i.reset(),this._consoleResolvedFrom=t;var s=this._buildCore((()=>this._consoleQueue),(e=>{this._consoleQueue=e}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},mu);this._consoleCore=s[0],this._consoleResolvedConfig=s[1]}return this._consoleCore}initialize(){this.loadIfEnabled()}onRemoteConfig(e){var t;if(e.ok){var i=null==(t=e.config.logs)?void 0:t.captureConsoleLogs;!wt(i)&&i&&(this._isLogsEnabled=!0,this.loadIfEnabled())}}reset(){var e,t;this._queue=[],null==(e=this._core)||e.reset(),this._consoleQueue=[],null==(t=this._consoleCore)||t.reset(),this._consecutiveStatusZeroFailures=0}captureLog(e){this._getCore().captureLog(e)}_captureConsoleLog(e){this._getConsoleCore().captureLog(e)}get logger(){return this._capture_logger||(this._capture_logger={trace:(e,t)=>this.captureLog({body:e,level:"trace",attributes:t}),debug:(e,t)=>this.captureLog({body:e,level:"debug",attributes:t}),info:(e,t)=>this.captureLog({body:e,level:"info",attributes:t}),warn:(e,t)=>this.captureLog({body:e,level:"warn",attributes:t}),error:(e,t)=>this.captureLog({body:e,level:"error",attributes:t}),fatal:(e,t)=>this.captureLog({body:e,level:"fatal",attributes:t})}),this._capture_logger}flushLogs(e){e?this._flushViaTransport(e):(this._core&&this._core.flush().catch((e=>this._logFlushError(e))),this._consoleCore&&this._consoleCore.flush().catch((e=>this._logFlushError(e))))}_logFlushError(e){wu(e)||this._logger.error("PostHog logs flush failed:",e)}loadIfEnabled(){if(this._isLogsEnabled&&!this._isLoaded){var e=null==Le?void 0:Le.__PosthogExtensions__;if(e){var t=e.loadExternalDependency;t?t(this._instance,"logs",(t=>{var i;t||null==(i=e.logs)||!i.initializeLogs?this._logger.error("Could not load logs script",t):(e.logs.initializeLogs(this._instance),this._isLoaded=!0)})):this._logger.error(ue)}else this._logger.error("PostHog Extensions not found.")}}_createHost(e,t){var i=this._instance;return{get isDisabled(){return!1},get optedOut(){return!i.is_capturing()},getPersistedProperty:t=>t===qe.LogsQueue?e():void 0,setPersistedProperty(e,i){var s;e===qe.LogsQueue&&t(null!==(s=i)&&void 0!==s?s:[])},_sendLogsBatch:e=>this._sendLogsBatch(e),getLibraryId:()=>r.LIB_NAME,getLibraryVersion:()=>r.LIB_VERSION}}_sendLogsBatch(e){return new Promise((t=>{if(Nn(this._consecutiveStatusZeroFailures,3))t({kind:"fatal",error:bu(void 0,"logs endpoint is unreachable, dropping batch")});else{var i=!1,s=e=>{i||(i=!0,clearTimeout(r),t(e))},r=setTimeout((()=>{this._logger.warn("Logs request timed out before receiving a response"),s({kind:"retry-later",error:bu(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this._logsUrl(),data:e,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:e=>{var t=e.statusCode;if(this._trackEndpointReachability(t),t>=200&&300>t)s({kind:"ok"});else if(413===t)s({kind:"too-large"});else if(0!==t&&408!==t&&429!==t&&500>t)s({kind:"fatal",error:new Error("logs request failed with status "+t)});else{var i;0===t?(e.error||this._logger.warn("Logs request failed before receiving an HTTP response"),s({kind:"retry-later",error:bu(e.error,"logs request failed before receiving an HTTP response")})):s({kind:"retry-later",error:null!==(i=e.error)&&void 0!==i?i:new Error("logs request failed with status "+t)})}}})}}))}_trackEndpointReachability(e){(0!==e||this._instance.__loaded)&&(this._consecutiveStatusZeroFailures=zn(e,this._consecutiveStatusZeroFailures,3,(()=>this._logger.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}_flushViaTransport(e){this._queue.length>0&&this._drainQueueViaTransport(e,this._queue,this._resolvedConfig,r.LIB_NAME,(e=>{this._queue=e})),this._consoleQueue.length>0&&this._drainQueueViaTransport(e,this._consoleQueue,this._consoleResolvedConfig,mu,(e=>{this._consoleQueue=e}))}_drainQueueViaTransport(e,t,i,s,n){if(0!==t.length){var o=t.map((e=>e.record));n([]);var a=ns(o,rs(i,r.LIB_NAME,r.LIB_VERSION),s,r.LIB_VERSION);this._instance._send_request({method:"POST",url:this._logsUrl(),data:a,compression:"best-available",batchKey:"logs",transport:e})}}_logsUrl(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}_getSdkContext(){var e,t={};if(t.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var i=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),s=i.windowId,r=i.sessionStartTimestamp,n=i.lastActivityTimestamp;t.sessionId=i.sessionId,t.windowId=s,wt(r)||(t.sessionStartTimestamp=r),wt(n)||(t.lastActivityTimestamp=n)}if(null!=Le&&null!=(e=Le.location)&&e.href&&(t.currentUrl=this._instance.config.disable_capture_url_hashes?Ui(Le.location.href):Le.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(t.activeFeatureFlags=o)}return t}}},Mu={metrics:class{constructor(e){this._logger=Gs("[metrics]"),this._instance=e}initialize(){}_getCore(){var e,t,i=null==(e=this._instance)||null==(e=e.config)?void 0:e.metrics;return this._core&&this._resolvedFrom===i||(null==(t=this._core)||t.reset(),this._resolvedFrom=i,this._core=new cs(this._createHost(),function(e){var t,i,s,r,n,o=null==e?void 0:e.resourceAttributes;return{serviceName:null!==(t=null==o?void 0:o["service.name"])&&void 0!==t?t:null==e?void 0:e.serviceName,serviceVersion:null!==(i=null==o?void 0:o["service.version"])&&void 0!==i?i:null==e?void 0:e.serviceVersion,environment:null!==(s=null==o?void 0:o["deployment.environment"])&&void 0!==s?s:null==e?void 0:e.environment,resourceAttributes:o,beforeSend:null==e?void 0:e.beforeSend,flushIntervalMs:null!==(r=null==e?void 0:e.flushIntervalMs)&&void 0!==r?r:1e4,maxSeriesPerFlush:null!==(n=null==e?void 0:e.maxSeriesPerFlush)&&void 0!==n?n:1e3}}(i),this._logger)),this._core}count(e,t,i){void 0===t&&(t=1),this._getCore().count(e,t,i)}gauge(e,t,i){this._getCore().gauge(e,t,i)}histogram(e,t,i){this._getCore().histogram(e,t,i)}flush(e){if(!this._core)return Promise.resolve();if(e){var t=this._core.drainWindow();return t&&this._sendMetricsBatch(t,e),Promise.resolve()}return this._core.flush().catch((e=>this._logger.error("PostHog metrics flush failed:",e)))}reset(){var e;null==(e=this._core)||e.reset()}_createHost(){var e=this._instance,t=this;return{get isDisabled(){return!1},get optedOut(){return!e.is_capturing()},_sendMetricsBatch:e=>t._sendMetricsBatch(e),getLibraryId:()=>r.LIB_NAME,getLibraryVersion:()=>r.LIB_VERSION}}_sendMetricsBatch(e,t){return new Promise((s=>{var r=!1,n=e=>{r||(r=!0,clearTimeout(o),s(e))},o=setTimeout((()=>n({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(i({method:"POST",url:this._metricsUrl(),data:e,compression:"best-available",batchKey:"metrics"},t&&{transport:t},{fireCallbackOnDrop:!0,callback(e){var t=e.statusCode;if(t>=200&&300>t)n({kind:"ok"});else if(413===t)n({kind:"too-large"});else if(0!==t&&408!==t&&429!==t&&500>t)n({kind:"fatal",error:new Error("metrics request failed with status "+t)});else{var i;n({kind:"retry-later",error:null!==(i=e.error)&&void 0!==i?i:new Error("metrics request failed with status "+t)})}}}))}))}_metricsUrl(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},$u=i({},Su,xu,Eu,ku,Pu,Cu,Fu,Iu,Tu,Ru,Au,Lu,Mu);_l.__defaultExtensionClasses=i({},$u),function(){r.SDK_DIST_CHANNEL="cdn";var e=Le.posthog;if(!e||_t(e._i)){var t=Xa[al]=new _l;if(e){var i=[];Qs(e._i,(function(s){if(s&&_t(s)){var r=t.init(s[0],s[1],s[2]),n=e[s[2]]||e;r.__loaded&&-1===i.indexOf(n)&&(i.push(n),r._execute_array.call(r.people,n.people),r._execute_array(n))}}))}t.__SV=1,Le.posthog=t,function(){function e(){e.done||(e.done=!0,ll=!1,Qs(Xa,(function(e){e._dom_loaded()})))}null!=Ee&&Ee.addEventListener?"complete"===Ee.readyState?e():sr(Ee,"DOMContentLoaded",e,{capture:!1}):we&&Ws.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}()}}()}();
1
+ !function(){"use strict";function e(e,t,i,s,r,n,o){try{var a=e[n](o),l=a.value}catch(e){return void i(e)}a.done?t(l):Promise.resolve(l).then(s,r)}function t(t){return function(){var i=this,s=arguments;return new Promise((function(r,n){var o=t.apply(i,s);function a(t){e(o,r,n,a,l,"next",t)}function l(t){e(o,r,n,a,l,"throw",t)}a(void 0)}))}}function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;arguments.length>t;t++){var i=arguments[t];for(var s in i)({}).hasOwnProperty.call(i,s)&&(e[s]=i[s])}return e},i.apply(null,arguments)}function s(e,t){if(null==e)return{};var i={};for(var s in e)if({}.hasOwnProperty.call(e,s)){if(-1!==t.indexOf(s))continue;i[s]=e[s]}return i}var r={DEBUG:!1,LIB_VERSION:"0.5.2",LIB_NAME:"browser-common"};r.DEBUG=!1,r.LIB_VERSION="1.419.2",r.LIB_NAME="web";var n="$people_distinct_id",o="distinct_id",a="$device_id",l="$device_model",u="__alias",c="__timers",d="$autocapture_disabled_server_side",h="$heatmaps_enabled_server_side",_="$exception_capture_enabled_server_side",p="$error_tracking_suppression_rules",g="$error_tracking_capture_extension_exceptions",v="$web_vitals_enabled_server_side",f="$dead_clicks_enabled_server_side",m="$product_tours_enabled_server_side",y="$web_vitals_allowed_metrics",b="$session_recording_remote_config",w="$replay_sample_rate",S="$replay_override_sampling",x="$replay_override_linked_flag",E="$replay_override_url_trigger",k="$replay_override_event_trigger",P="$sesid",C="$session_is_sampled",I="$enabled_feature_flags",F="$active_feature_flags",T="$early_access_features",R="$feature_flag_details",A="$feature_flag_payloads",L="$feature_flag_request_id",M="$minimal_flag_called_events",O="$override_feature_flags",D="$override_feature_flag_payloads",B="$stored_person_properties",q="$stored_group_properties",H="$groups",N="$surveys",z="$surveys_loaded_at",j="$surveys_activated",U="$surveys_activated_session",V="$surveys_activated_timestamps",W="ph_product_tours",G="$flag_call_reported",K="$flag_call_reported_session_id",Q="$feature_flag_errors",J="$feature_flag_evaluated_at",Y="$user_state",Z="$client_session_props",X="$capture_rate_limit",ee="$initial_campaign_params",te="$initial_referrer_info",ie="$initial_person_info",se="$epp",re="$posthog_cookieless",ne="$cookieless_mode",oe="$sdk_debug_extensions_init_method",ae="$sdk_debug_extensions_init_time_ms",le="$sdk_debug_recording_script_not_loaded",ue="PostHog loadExternalDependency extension not found.",ce="on_reject",de="always",he="anonymous",_e="identified",pe="identified_only",ge="visibilitychange",ve="beforeunload",fe="$pageview",me="$pageleave",ye="$identify",be="$groupidentify",we="undefined"!=typeof window?window:void 0,Se="undefined"!=typeof globalThis?globalThis:we,xe=null==Se?void 0:Se.navigator,Ee=null==Se?void 0:Se.document,ke=null==Se?void 0:Se.location,Pe=null==Se?void 0:Se.fetch,Ce=null!=Se&&Se.XMLHttpRequest&&"withCredentials"in new Se.XMLHttpRequest?Se.XMLHttpRequest:void 0,Ie=null==Se?void 0:Se.AbortController,Fe=null==Se?void 0:Se.CompressionStream,Te=null==xe?void 0:xe.userAgent;function Re(){return!(!we||!1===we.navigator.onLine)}var Ae="undefined"!=typeof globalThis?globalThis:we;Ae&&"undefined"==typeof self&&(Ae.self=Ae),Ae&&"undefined"==typeof File&&(Ae.File=function(){});var Le=null!=we?we:{},Me=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}};function $e(e){return"string"==typeof e||e}function Oe(e){return"string"==typeof e?e:void 0}var De,Be=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],qe=function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.AiQueue="ai_queue",e.AiCaptureQueue="ai_capture_queue",e.LogsQueue="logs_queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.PushRegistered="push_registered",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e}({}),He=function(e){return e.GZipJS="gzip-js",e.Base64="base64",e}({}),Ne=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"],ze=["token"],je="NativeGzipValidationError",Ue=e=>e.length>=2&&31===e[0]&&139===e[1],Ve=(e,t)=>e===He.GZipJS||t===He.GZipJS||"gzip"===t,We=e=>!(!e||"object"!=typeof e)&&"NotReadableError"===("name"in e?String(e.name):""),Ge=e=>{var t=new Error("Native gzip produced invalid output: "+e);throw t.name=je,t},Ke=function(){var e=t((function*(e,t){18>e.size&&Ge("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());Ue(i)&&8===i[2]||Ge("invalid-header");var s=new DataView(yield e.slice(e.size-8).arrayBuffer());s.getUint32(0,!0)!==(e=>{for(var t=(()=>{if(De)return De;De=[];for(var e=0;256>e;e++){for(var t=e,i=0;8>i;i++)t=1&t?3988292384^t>>>1:t>>>1;De[e]=t>>>0}return De})(),i=4294967295,s=0;e.length>s;s++)i=t[255&(i^e[s])]^i>>>8;return(4294967295^i)>>>0})(t)&&Ge("invalid-crc");var r=t.length>>>0;s.getUint32(4,!0)!==r&&Ge("invalid-size")}));return function(t,i){return e.apply(this,arguments)}}();function Qe(){return Qe=t((function*(e,i,s){void 0===i&&(i=!0);try{var r=(new TextEncoder).encode(e),n=new globalThis.CompressionStream("gzip"),o=n.writable.getWriter(),a=o.write(r).then((()=>o.close())).catch(function(){var e=t((function*(e){try{yield o.abort(e)}catch(e){}throw e}));return function(t){return e.apply(this,arguments)}}()),l=new Response(n.readable).blob(),u=(yield Promise.all([l,a]))[0];return yield Ke(u,r),u}catch(e){if(null!=s&&s.rethrow)throw e;return i&&console.error("Failed to gzip compress data",e),null}})),Qe.apply(this,arguments)}var Je=20,Ye=1e3,Ze=1e4,Xe="[Circular]",et="[Truncated]",tt="[Unserializable]",it="[Function]";function st(e){for(var t="",i=0;e.length>i;i++){var s=e.charCodeAt(i);if(55296>s||s>56319)t+=56320>s||s>57343?e[i]:"�";else{var r=e.charCodeAt(i+1);56320>r||r>57343?t+="�":(t+=e[i]+e[i+1],i++)}}return t}var rt=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],nt=function(e,t){if(void 0===t&&(t=[]),!e)return!1;var i=e.toLowerCase();return rt.concat(t).some((e=>{var t=e.toLowerCase();return-1!==i.indexOf(t)}))};function ot(e,t){return-1!==e.indexOf(t)}var at=function(e){return e.trim()},lt=function(e){return e.replace(/^\$/,"")};function ut(e){var t,i=[];return null!==(t=JSON.stringify(e,(function(e,t){if("bigint"==typeof t)return t.toString();if("function"!=typeof t&&"symbol"!=typeof t){if(t instanceof Error)return{name:t.name,message:t.message,stack:t.stack};if(t&&"object"==typeof t){for(;i.length>0&&i[i.length-1]!==this;)i.pop();if(i.includes(t))return"[Circular]";i.push(t)}return t}})))&&void 0!==t?t:"null"}var ct=Object.prototype,dt=ct.hasOwnProperty,ht=ct.toString,_t=Array.isArray||function(e){return"[object Array]"===ht.call(e)},pt=e=>"function"==typeof e,gt=e=>e===Object(e)&&!_t(e),vt=e=>{if(gt(e)){for(var t in e)if(dt.call(e,t))return!1;return!0}return!1},ft=e=>void 0===e,mt=e=>"[object String]"==ht.call(e),yt=e=>mt(e)&&0===e.trim().length,bt=e=>null===e,wt=e=>ft(e)||bt(e),St=e=>"[object Number]"==ht.call(e)&&e==e,xt=e=>St(e)&&e>0,Et=e=>"[object Boolean]"===ht.call(e),kt=e=>e instanceof FormData,Pt=e=>ot(Ne,e),Ct=e=>ot(ze,e);function It(e){return null===e||"object"!=typeof e}function Ft(e,t){return{}.toString.call(e)==="[object "+t+"]"}function Tt(e){switch({}.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return At(e,Error)}}function Rt(e){return"undefined"!=typeof Event&&At(e,Event)}function At(e,t){try{return e instanceof t}catch(e){return!1}}var Lt=[!0,"true",1,"1","yes"],Mt=e=>ot(Lt,e),$t=[!1,"false",0,"0","no"];function Ot(e,t,i,s,r){return t>i&&(s.warn("min cannot be greater than max."),t=i),St(e)?e>i?(s.warn(" cannot be greater than max: "+i+". Using max value instead."),i):t>e?(s.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(s.warn(" must be a number. using max or fallback. max: "+i+", fallback: "+r),Ot(r||i,t,i,s))}class Dt{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Ot(e.bucketSize,0,100,e._logger),this._refillRate=Ot(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Ot(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){var i=Math.floor((t-e.lastAccess)/this._refillInterval);i>0&&(e.tokens=Math.min(e.tokens+i*this._refillRate,this._bucketSize),e.lastAccess=e.lastAccess+i*this._refillInterval)}consumeRateLimit(e){var t,i=Date.now(),s=String(e),r=this._buckets[s];return r?this._applyRefill(r,i):this._buckets[s]=r={tokens:this._bucketSize,lastAccess:i},0===r.tokens||(r.tokens--,0===r.tokens&&(null==(t=this._onBucketRateLimited)||t.call(this,e)),0===r.tokens)}stop(){this._buckets={}}}var Bt="Mobile",qt="iOS",Ht="Android",Nt="Tablet",zt=Ht+" "+Nt,jt="iPad",Ut="Apple",Vt=Ut+" Watch",Wt="Safari",Gt="BlackBerry",Kt="Samsung",Qt=Kt+"Browser",Jt=Kt+" Internet",Yt="Chrome",Zt=Yt+" OS",Xt=Yt+" "+qt,ei="Internet Explorer",ti=ei+" "+Bt,ii="Opera",si=ii+" Mini",ri="Edge",ni="Microsoft "+ri,oi="Firefox",ai=oi+" "+qt,li="Nintendo",ui="PlayStation",ci="Xbox",di=Ht+" "+Bt,hi=Bt+" "+Wt,_i="Windows",pi=_i+" Phone",gi="Nokia",vi="Ouya",fi="Generic",mi=fi+" "+Bt.toLowerCase(),yi=fi+" "+Nt.toLowerCase(),bi="Konqueror",wi="Oculus Browser",Si="Vivaldi",xi="Yandex",Ei="Whale",ki="DuckDuckGo",Pi="Pale Moon",Ci="Waterfox",Ii="Brave",Fi="Google Search App",Ti="(\\d+(\\.\\d+)?)",Ri=new RegExp("Version/"+Ti),Ai=new RegExp(ci,"i"),Li=new RegExp(ui+" \\w+","i"),Mi=new RegExp(li+" \\w+","i"),$i=new RegExp(Gt+"|PlayBook|BB10","i"),Oi={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},Di=function(e,t,i,s){t=t||"";var r=function(e){return null!=e&&e.brave?Ii:null}(i);return r||(null!=s&&s.detectGoogleSearchApp&&ot(e,"GSA/")?Fi:ot(e," OPR/")&&ot(e,"Mini")?si:ot(e," OPR/")?ii:$i.test(e)?Gt:ot(e,"IE"+Bt)||ot(e,"WPDesktop")?ti:ot(e,"OculusBrowser")?wi:ot(e,Qt)?Jt:ot(e,ri)||ot(e,"Edg/")?ni:ot(e,Si+"/")?Si:ot(e,"YaBrowser/")?xi:ot(e,Ei+"/")?Ei:ot(e,ki+"/")||ot(e,"Ddg/")?ki:ot(e,"FBIOS")?"Facebook "+Bt:ot(e,"UCWEB")||ot(e,"UCBrowser")?"UC Browser":ot(e,"CriOS")?Xt:ot(e,"CrMo")||ot(e,Yt)?Yt:ot(e,Ht)&&ot(e,Wt)?di:ot(e,"FxiOS")?ai:ot(e.toLowerCase(),bi.toLowerCase())?bi:ot(e,Ii+"/")?Ii:((e,t)=>t&&ot(t,Ut)||function(e){return ot(e,Wt)&&!ot(e,Yt)&&!ot(e,Ht)}(e))(e,t)?ot(e,Bt)?hi:Wt:ot(e,"PaleMoon/")?Pi:ot(e,Ci+"/")?Ci:ot(e,oi)?oi:ot(e,"MSIE")||ot(e,"Trident/")?ei:ot(e,"Gecko")?oi:"")},Bi={[ti]:[new RegExp("rv:"+Ti)],[ni]:[new RegExp(ri+"?\\/"+Ti)],[Yt]:[new RegExp("("+Yt+"|CrMo)\\/"+Ti)],[Xt]:[new RegExp("CriOS\\/"+Ti)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Ti)],[Wt]:[Ri],[hi]:[Ri],[ii]:[new RegExp("(Opera|OPR)\\/"+Ti)],[oi]:[new RegExp(oi+"\\/"+Ti)],[ai]:[new RegExp("FxiOS\\/"+Ti)],[bi]:[new RegExp("Konqueror[:/]?"+Ti,"i")],[Gt]:[new RegExp(Gt+" "+Ti),Ri],[di]:[new RegExp("android\\s"+Ti,"i")],[Jt]:[new RegExp(Qt+"\\/"+Ti)],[wi]:[new RegExp("OculusBrowser\\/"+Ti)],[Si]:[new RegExp(Si+"\\/"+Ti)],[xi]:[new RegExp("YaBrowser\\/"+Ti)],[Ei]:[new RegExp(Ei+"\\/"+Ti)],[Ii]:[new RegExp(Ii+"\\/"+Ti)],[ki]:[new RegExp("(DuckDuckGo|Ddg)\\/"+Ti)],[Pi]:[new RegExp("PaleMoon\\/"+Ti)],[Ci]:[new RegExp(Ci+"\\/"+Ti)],[Fi]:[new RegExp("GSA\\/"+Ti)],[ei]:[new RegExp("(rv:|MSIE )"+Ti)],Mozilla:[new RegExp("rv:"+Ti)]},qi=function(e,t,i,s){var r=Di(e,t,i,s),n=Bi[r];if(ft(n))return null;for(var o=0;n.length>o;o++){var a=e.match(n[o]);if(a)return parseFloat(a[a.length-2])}return null},Hi=[[new RegExp(ci+"; "+ci+" (.*?)[);]","i"),e=>[ci,e&&e[1]||""]],[new RegExp(li,"i"),[li,""]],[new RegExp(ui,"i"),[ui,""]],[$i,[Gt,""]],[new RegExp(_i,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[pi,""];if(new RegExp(Bt).test(t)&&!/IEMobile\b/.test(t))return[_i+" "+Bt,""];var i=/Windows NT ([0-9.]+)/i.exec(t);if(i&&i[1]){var s=Oi[i[1]]||"";return/arm/i.test(t)&&(s="RT"),[_i,s]}return[_i,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>e&&e[3]?[qt,[e[3],e[4],e[5]||"0"].join(".")]:[qt,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{var t="";return e&&e.length>=3&&(t=ft(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Ht+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Ht+")","i"),e=>e&&e[2]?[Ht,[e[2],e[3],e[4]||"0"].join(".")]:[Ht,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{var t=["Mac OS X",""];return e&&e[1]&&(t[1]=[e[1],e[2],e[3]||"0"].join(".")),t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Zt,""]],[/Linux|debian/i,["Linux",""]]],Ni=function(e){return Mi.test(e)?li:Li.test(e)?ui:Ai.test(e)?ci:new RegExp(vi,"i").test(e)?vi:new RegExp("("+pi+"|WPDesktop)","i").test(e)?pi:/iPad/.test(e)?jt:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?Vt:$i.test(e)?Gt:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(gi,"i").test(e)?gi:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(e)||/(kf[a-z]+)( bui|\)).+silk\//i.test(e)?"Kindle Fire":/(Android|ZTE)/i.test(e)?new RegExp(Bt).test(e)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(e)||/pixel[\daxl ]{1,6}/i.test(e)&&!/pixel c/i.test(e)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(e)||/lmy47v/i.test(e)&&!/QTAQZ3/i.test(e)?Ht:zt:new RegExp("(pda|"+Bt+")","i").test(e)?mi:new RegExp(Nt,"i").test(e)&&!new RegExp(Nt+" pc","i").test(e)?yi:""},zi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ji(e,t){return"string"==typeof(i=e)&&zi.test(i)?e:t();var i}function Ui(e){return e?e.split("#")[0]:e}function Vi(e,t){var i=setTimeout(e,t);return(null==i?void 0:i.unref)&&(null==i||i.unref()),i}function Wi(e,t,i){return Gi.apply(this,arguments)}function Gi(){return(Gi=t((function*(e,t,i){var s;try{return yield Promise.race([e,new Promise(((e,r)=>{s=Vi((()=>{try{null==i||i(),e()}catch(e){r(e)}}),t)}))])}finally{clearTimeout(s)}}))).apply(this,arguments)}var Ki={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},Qi=Ki.info,Ji=0x8000000000000000,Yi={}.propertyIsEnumerable;function Zi(e,t){try{return ts(e,t,{ancestors:new WeakSet,remainingNodes:Ze},0)}catch(e){return[]}}function Xi(e,t,i,s){if(0>=i.remainingNodes)return{stringValue:et};if(i.remainingNodes--,Et(e))return{boolValue:e};if("number"==typeof e){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if("undefined"==typeof BigInt)return{stringValue:String(e)};var r=BigInt(e).toString();return e>=Ji||-Ji>e?(null==t||t.debug("Attribute "+r+" is outside the int64 range; encoding it as a string"),{stringValue:r}):{intValue:r}}return{doubleValue:e}}if("string"==typeof e)return{stringValue:st(e)};if("function"==typeof e)return{stringValue:it};if("symbol"==typeof e)return{stringValue:String(e)};if("object"==typeof e&&null!==e){if(i.ancestors.has(e))return{stringValue:Xe};if(s>=Je)return{stringValue:et};if(e instanceof Date){var n=e.getTime(),o=Number.isFinite(n)?e.toISOString():String(e);return{stringValue:"string"==typeof o?st(o):String(o)}}i.ancestors.add(e);try{try{var a=e.toJSON;if("function"==typeof a)return Xi(a.call(e),t,i,s+1)}catch(e){}return _t(e)?{arrayValue:{values:es(e,t,i,s+1)}}:{kvlistValue:{values:ts(e,t,i,s+1)}}}finally{i.ancestors.delete(e)}}return{stringValue:st(String(e))}}function es(e,t,i,s){for(var r=[],n=Math.min(e.length,Ye),o=0;n>o&&i.remainingNodes>0;o++)try{var a=o in e?e[o]:void 0;if(wt(a))continue;r.push(Xi(a,t,i,s))}catch(e){r.push({stringValue:tt})}return e.length>o&&r.push({stringValue:et}),r}function ts(e,t,i,s){var r=[];for(var n in e)if(Yi.call(e,n)){if(r.length>=Ye||0>=i.remainingNodes){null==t||t.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{var o=e[n];if(bt(o)||ft(o))continue;r.push({key:st(n),value:Xi(o,t,i,s)})}catch(e){r.push({key:st(n),value:{stringValue:tt}})}}return r}function is(e){try{return st(String(e))}catch(e){return tt}}function ss(e,t,s){var r=Ki[e.level||"info"]||Qi,n=r.text,o=r.number,a=String(Date.now())+"000000",l={};t.distinctId&&(l.posthogDistinctId=t.distinctId),t.sessionId&&(l.sessionId=t.sessionId),t.windowId&&(l["window.id"]=t.windowId),wt(t.sessionStartTimestamp)||(l.sessionStartTimestamp=String(t.sessionStartTimestamp)),wt(t.lastActivityTimestamp)||(l.lastActivityTimestamp=String(t.lastActivityTimestamp)),t.currentUrl&&(l["url.full"]=t.currentUrl),t.screenName&&(l["screen.name"]=t.screenName),t.appState&&(l["app.state"]=t.appState),t.activeFeatureFlags&&t.activeFeatureFlags.length>0&&(l.feature_flags=t.activeFeatureFlags);var u=i({},l),c=e.attributes;if(c){var d=[];try{d=Object.keys(c)}catch(e){d=[]}for(var h of d){var _=void 0;try{_=c[h]}catch(e){_=tt}Object.defineProperty(u,h,{value:_,enumerable:!0,writable:!0,configurable:!0})}}var p={timeUnixNano:a,observedTimeUnixNano:a,severityNumber:o,severityText:n,body:{stringValue:is(e.body)},attributes:Zi(u,s)};return e.trace_id&&(p.traceId=e.trace_id),e.span_id&&(p.spanId=e.span_id),ft(e.trace_flags)||(p.flags=e.trace_flags),p}function rs(e,t,s){return i({},e.resourceAttributes,{"service.name":e.serviceName||"unknown_service"},e.environment&&{"deployment.environment":e.environment},e.serviceVersion&&{"service.version":e.serviceVersion},{"telemetry.sdk.name":t,"telemetry.sdk.version":s})}function ns(e,t,i,s){return{resourceLogs:[{resource:{attributes:Zi(t)},scopeLogs:[{scope:{name:i,version:s},logRecords:e}]}]}}let os=class{constructor(e,t,i,s,r,n,o){var a;void 0===n&&(n=()=>Promise.resolve()),this._instance=e,this._config=t,this._logger=i,this._getContext=s,this._onReady=r,this._waitForStoragePersist=n,this._scopeName=o,this._flushPromise=null,this._evictedSinceAdvance=0,this._consecutiveFlushFailures=0,this._intervalWindowStart=0,this._intervalLogCount=0,this._droppedWarned=!1,this._maxBufferSize=t.maxBufferSize,this._maxQueueSize=Math.max(null!==(a=t.maxQueueSize)&&void 0!==a?a:t.maxBufferSize,t.maxBufferSize),this._flushIntervalMs=t.flushIntervalMs,this._maxBatchRecordsPerPost=t.maxBatchRecordsPerPost,this._rateCapWindowMs=t.rateCapWindowMs,this._maxLogsPerInterval=t.maxLogsPerInterval}reset(){this._clearFlushTimer(),this._flushPromise=null,this._intervalWindowStart=0,this._intervalLogCount=0,this._droppedWarned=!1,this._evictedSinceAdvance=0,this._consecutiveFlushFailures=0,this._maxBatchRecordsPerPost=this._config.maxBatchRecordsPerPost}onReconnect(){this._consecutiveFlushFailures=0,this._flushInBackground()}captureLog(e){if(!this._instance.isDisabled&&!this._instance.optedOut&&null!=e&&e.body){var t=this._runBeforeSend(e);if(null!==t)if(t.body){if(this._checkRateLimit()){var i={record:ss(t,this._getContext(),this._logger)};this._onReady((()=>this._enqueue(i)))}}else this._logger.info("Log was rejected in beforeSend function")}}_runBeforeSend(e){var t=this._config.beforeSend;if(!t)return e;var i=_t(t)?t:[t],s=e;for(var r of i)try{var n=r(s);if(!n)return this._logger.info("Log was rejected in beforeSend function"),null;s=n}catch(e){return this._logger.error("Error in beforeSend function for log:",e),null}return s}_checkRateLimit(){if(void 0===this._maxLogsPerInterval)return!0;var e=Date.now(),t=e-this._intervalWindowStart;return this._rateCapWindowMs>t&&t>=0||(this._intervalWindowStart=e,this._intervalLogCount=0,this._droppedWarned=!1),this._maxLogsPerInterval>this._intervalLogCount?(this._intervalLogCount++,!0):(this._droppedWarned||(this._logger.warn("captureLog dropping logs: exceeded "+this._maxLogsPerInterval+" logs per "+this._rateCapWindowMs+"ms"),this._droppedWarned=!0),!1)}flush(){var e=this;return t((function*(){if(!e._instance.isDisabled)return e._flushPromise||(e._flushPromise=e._flushInner().finally((()=>{e._flushPromise=null}))),e._flushPromise}))()}_flushInner(){var e=this;return t((function*(){var t;e._clearFlushTimer();var i=null!==(t=e._instance.getPersistedProperty(qe.LogsQueue))&&void 0!==t?t:[];if(0!==i.length)for(var s=i.length,r=0;i.length>0&&s>r;){var n,o;e._evictedSinceAdvance=0;var a=Math.min(i.length,e._maxBatchRecordsPerPost),l=i.slice(0,a),u=ns(l.map((e=>e.record)),e._buildResourceAttributes(),null!==(n=e._scopeName)&&void 0!==n?n:e._instance.getLibraryId(),e._instance.getLibraryVersion()),c=yield e._instance._sendLogsBatch(u);if("too-large"===c.kind&&l.length>1)e._maxBatchRecordsPerPost=Math.max(1,Math.floor(l.length/2)),e._logger.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+e._maxBatchRecordsPerPost);else{if("retry-later"===c.kind)throw c.error;if("too-large"===c.kind?e._logger.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):"ok"===c.kind&&e._config.maxBatchRecordsPerPost>e._maxBatchRecordsPerPost&&(e._maxBatchRecordsPerPost=Math.min(e._config.maxBatchRecordsPerPost,e._maxBatchRecordsPerPost+1)),yield e._persistQueueAdvance(l.length),i=null!==(o=e._instance.getPersistedProperty(qe.LogsQueue))&&void 0!==o?o:[],r+=l.length,"fatal"===c.kind)throw c.error}}}))()}_persistQueueAdvance(e){var i=this;return t((function*(){var t,s=Math.max(0,e-i._evictedSinceAdvance),r=null!==(t=i._instance.getPersistedProperty(qe.LogsQueue))&&void 0!==t?t:[];i._instance.setPersistedProperty(qe.LogsQueue,r.slice(s)),yield i._waitForStoragePersist()}))()}_buildResourceAttributes(){return rs(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion())}_enqueue(e){var t;if(!this._instance.optedOut){var i=null!==(t=this._instance.getPersistedProperty(qe.LogsQueue))&&void 0!==t?t:[];this._maxQueueSize>i.length||(i.shift(),this._evictedSinceAdvance++,this._logger.info("Logs queue is full, dropping oldest record.")),i.push(e),this._instance.setPersistedProperty(qe.LogsQueue,i),this._maxBufferSize>i.length?this._armFlushTimer():this._flushInBackground()}}_armFlushTimer(e){void 0===e&&(e=this._flushIntervalMs),this._flushTimer||(this._flushTimer=Vi((()=>{this._flushTimer=void 0,this._flushInBackground()}),e))}_nextFlushDelay(){var e=Math.min(Math.max(0,this._consecutiveFlushFailures-1),6);return this._flushIntervalMs*Math.pow(2,e)}_hasQueuedRecords(){var e=this._instance.getPersistedProperty(qe.LogsQueue);return!!e&&e.length>0}shutdown(e){var i=this;return t((function*(){i._clearFlushTimer();var t=i.flush().catch((()=>{}));void 0!==e?yield Wi(t,e):yield t}))()}flushWithTimeout(e){var i=this;return t((function*(){var t=i.flush();yield Wi(t,e,(()=>{t.catch((()=>{}))}))}))()}_flushInBackground(){this.flush().then((()=>{this._consecutiveFlushFailures=0}),(e=>{this._consecutiveFlushFailures++,this._logger.error("PostHog logs flush failed:",e)})).finally((()=>{!this._instance.isDisabled&&this._hasQueuedRecords()&&this._armFlushTimer(this._nextFlushDelay())}))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}};var as=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function ls(e){return String(e)+"000000"}function us(e,t,i,s){var r="";return s&&(r=Object.keys(s).sort().map((e=>JSON.stringify(e)+":"+JSON.stringify(s[e]))).join(",")),e+"\0"+t+"\0"+(null!=i?i:"")+"\0"+r}let cs=class{constructor(e,t,i){this._instance=e,this._config=t,this._logger=i,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._generation=0}count(e,t,i){void 0===t&&(t=1),this._capture({name:e,type:"count",value:t,unit:null==i?void 0:i.unit,attributes:null==i?void 0:i.attributes})}gauge(e,t,i){this._capture({name:e,type:"gauge",value:t,unit:null==i?void 0:i.unit,attributes:null==i?void 0:i.attributes})}histogram(e,t,i){this._capture({name:e,type:"histogram",value:t,unit:null==i?void 0:i.unit,attributes:null==i?void 0:i.attributes})}flush(){var e=this,i=this._flushPromise,s=function(){var s=t((function*(){i&&(yield i.catch((()=>{}))),yield e._doFlush()}));return function(){return s.apply(this,arguments)}}(),r=s().finally((()=>{this._flushPromise===r&&(this._flushPromise=null)}));return this._flushPromise=r,r}drainWindow(){if(0===this._series.size)return null;var e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._clearFlushTimer(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(!this._instance.isDisabled&&!this._instance.optedOut){var t=this._runBeforeSend(e);if(null!==t)if(t.name&&"string"==typeof t.name)if("number"==typeof t.value&&Number.isFinite(t.value))if("count"===t.type&&0>t.value)this._logger.warn("Dropping count '"+t.name+"': counters are monotonic, value must be >= 0");else{var s,r;try{s=t.attributes?i({},t.attributes):void 0,r=us(t.type,t.name,t.unit,s)}catch(e){return void this._logger.warn("Dropping metric '"+t.name+"': attributes could not be serialized",e)}var n=this._series.get(r);if(!n){if(!this._admitNewSeries())return;n={name:t.name,type:t.type,unit:t.unit,attributes:s,windowStartMs:Date.now()},this._series.set(r,n)}var o=this._typeByName.get(t.name);void 0===o?this._typeByName.set(t.name,t.type):o===t.type||this._typeCollisionWarned.has(t.name)||(this._typeCollisionWarned.add(t.name),this._logger.warn("Metric name '"+t.name+"' is already used as a "+o+"; recording it as a "+t.type+" too will blend both series in charts. Use a distinct name.")),this._fold(n,t.value),this._armFlushTimer()}else this._logger.warn("Dropping metric '"+t.name+"': value must be a finite number");else this._logger.warn("Dropping metric with empty name")}}_admitNewSeries(){return this._config.maxSeriesPerFlush>this._series.size||(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn("Metric series cap reached ("+this._config.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}_fold(e,t){var i;switch(e.type){case"count":e.total=(null!==(i=e.total)&&void 0!==i?i:0)+t;break;case"gauge":e.last=t;break;case"histogram":e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:new Array(as.length+1).fill(0)});var s=e.hist;s.count+=1,s.sum+=t,s.min=Math.min(s.min,t),s.max=Math.max(s.max,t),s.bucketCounts[function(e,t){for(var i=0;t.length>i;i++)if(t[i]>=e)return i;return t.length}(t,as)]+=1}}_runBeforeSend(e){var t=this._config.beforeSend;if(!t)return e;var i=_t(t)?t:[t],s=e;for(var r of i)try{var n=r(s);if(!n)return this._logger.info("Metric was rejected in beforeSend function"),null;s=n}catch(e){return this._logger.error("Error in beforeSend function for metric:",e),null}return s}_armFlushTimer(){this._flushTimer||(this._flushTimer=Vi((()=>{this._flushTimer=void 0,this.flush().catch((e=>{this._logger.error("Metrics flush failed:",e)}))}),this._config.flushIntervalMs))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}_doFlush(){var e=this;return t((function*(){if(0!==e._series.size){var t=e._series;e._series=new Map,e._seriesCapWarned=!1,e._typeByName=new Map,e._typeCollisionWarned=new Set;var i=e._generation,s=yield e._instance._sendMetricsBatch(e._buildPayload(t));if(i===e._generation)switch(s.kind){case"ok":return;case"retry-later":return e._mergeWindowBack(t),void e._armFlushTimer();case"too-large":return void e._logger.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void e._logger.error("Failed to send metrics batch:",s.error)}}}))()}_buildPayload(e){return t=this._buildMetrics(e),s=function(e,t,s){return i({},e.resourceAttributes,{"service.name":e.serviceName||"unknown_service"},e.environment&&{"deployment.environment":e.environment},e.serviceVersion&&{"service.version":e.serviceVersion},{"telemetry.sdk.name":t,"telemetry.sdk.version":s})}(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),r=this._instance.getLibraryId(),n=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Zi(s)},scopeMetrics:[{scope:{name:r,version:n},metrics:t}]}]};var t,s,r,n}_buildMetrics(e){var t=ls(Date.now()),s=new Map;for(var r of e.values()){var n,o=us(r.type,r.name,r.unit,void 0),a=s.get(o);a||(a=i({name:r.name},r.unit&&{unit:r.unit}),"count"===r.type?a.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===r.type?a.gauge={dataPoints:[]}:a.histogram={aggregationTemporality:1,dataPoints:[]},s.set(o,a));var l=Zi(null!==(n=r.attributes)&&void 0!==n?n:{},this._logger),u=ls(r.windowStartMs);if("count"===r.type){var c,d={attributes:l,startTimeUnixNano:u,timeUnixNano:t,asDouble:null!==(c=r.total)&&void 0!==c?c:0};a.sum.dataPoints.push(d)}else if("gauge"===r.type){var h,_={attributes:l,timeUnixNano:t,asDouble:null!==(h=r.last)&&void 0!==h?h:0};a.gauge.dataPoints.push(_)}else r.hist&&a.histogram.dataPoints.push({attributes:l,startTimeUnixNano:u,timeUnixNano:t,count:r.hist.count,sum:r.hist.sum,min:r.hist.min,max:r.hist.max,bucketCounts:r.hist.bucketCounts,explicitBounds:as})}return Array.from(s.values())}_mergeWindowBack(e){var t,i;for(var s of e){var r=s[0],n=s[1],o=this._series.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,n.windowStartMs),o.type){case"count":o.total=(null!==(t=o.total)&&void 0!==t?t:0)+(null!==(i=n.total)&&void 0!==i?i:0);break;case"gauge":break;case"histogram":if(n.hist)if(o.hist){o.hist.count+=n.hist.count,o.hist.sum+=n.hist.sum,o.hist.min=Math.min(o.hist.min,n.hist.min),o.hist.max=Math.max(o.hist.max,n.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=n.hist.bucketCounts[a]}else o.hist=n.hist}else this._admitNewSeries()&&this._series.set(r,n)}}};var ds,hs,_s;function ps(e){var t=globalThis._posthogChunkIds;if(t){var i=Object.keys(t);return _s&&i.length===hs||(hs=i.length,_s=i.reduce(((i,s)=>{ds||(ds={});var r=ds[s];if(r)i[r[0]]=r[1];else for(var n=e(s),o=n.length-1;o>=0;o--){var a=n[o],l=null==a?void 0:a.filename,u=t[s];if(l&&u){i[l]=u,ds[s]=[l,u];break}}return i}),{})),_s}}class gs{constructor(e,t,i){void 0===i&&(i=[]),this.coercers=e,this.stackParser=t,this.modifiers=i}buildFromUnknown(e,t){void 0===t&&(t={});var i=t&&t.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,t,0).apply(e),r=this.buildParsingContext(t),n=this.parseStacktrace(s,r);return{$exception_list:this.convertToExceptionList(n,i),$exception_level:"error"}}modifyFrames(e){var i=this;return t((function*(){for(var t of e)t.stacktrace&&t.stacktrace.frames&&_t(t.stacktrace.frames)&&(t.stacktrace.frames=yield i.applyModifiers(t.stacktrace.frames));return e}))()}coerceFallback(e){var t;return{type:"Error",value:"Unknown error",stack:null==(t=e.syntheticException)?void 0:t.stack,synthetic:!0}}parseStacktrace(e,t){var s,r;return null!=e.cause&&(s=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),i({},e,{cause:s,stack:r})}applyChunkIds(e,t){return e.map((e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e)))}applyCoercers(e,t){for(var i of this.coercers)if(i.match(e))return i.coerce(e,t);return this.coerceFallback(t)}applyModifiers(e){var i=this;return t((function*(){var t=e;for(var s of i.modifiers)t=yield s(t);return t}))()}convertToExceptionList(e,t){var s,r,n,o={type:e.type,value:e.value,mechanism:{type:null!==(s=t.type)&&void 0!==s?s:"generic",handled:null===(r=t.handled)||void 0===r||r,synthetic:null!==(n=e.synthetic)&&void 0!==n&&n}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return null!=e.cause&&a.push(...this.convertToExceptionList(e.cause,i({},t,{handled:!0}))),a}buildParsingContext(e){var t;return{chunkIdMap:ps(this.stackParser),skipFirstLines:null!==(t=e.skipFirstLines)&&void 0!==t?t:1}}buildCoercingContext(e,t,s){void 0===s&&(s=0);var r=(i,s)=>{if(4>=s){var r=this.buildCoercingContext(e,t,s);return this.applyCoercers(i,r)}};return i({},t,{syntheticException:0==s?t.syntheticException:void 0,mechanism:e,apply:e=>r(e,s),next:e=>r(e,s+1)})}}var vs="?";function fs(e,t,i,s,r){var n={platform:e,filename:t,function:"<anonymous>"===i?vs:i,in_app:!(null!=t&&t.startsWith("webkit-masked-url://"))&&"<anonymous>"!==t};return ft(s)||(n.lineno=s),ft(r)||(n.colno=r),n}var ms=(e,t)=>{var i=-1!==e.indexOf("safari-extension"),s=-1!==e.indexOf("safari-web-extension");return i||s?[-1!==e.indexOf("@")?e.split("@")[0]:vs,i?"safari-extension:"+t:"safari-web-extension:"+t]:[e,t]},ys=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,bs=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ws=/\((\S*)(?::(\d+))(?::(\d+))\)/,Ss=(e,t)=>{var i=ys.exec(e);if(i)return fs(t,i[1],vs,+i[2],+i[3]);var s=bs.exec(e);if(s){if(s[2]&&0===s[2].indexOf("eval")){var r=ws.exec(s[2]);r&&(s[2]=r[1],s[3]=r[2],s[4]=r[3])}var n=ms(s[1]||vs,s[2]);return fs(t,n[1],n[0],s[3]?+s[3]:void 0,s[4]?+s[4]:void 0)}},xs=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Es=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ks=(e,t)=>{var i=xs.exec(e);if(i){if(i[3]&&i[3].indexOf(" > eval")>-1){var s=Es.exec(i[3]);s&&(i[1]=i[1]||"eval",i[3]=s[1],i[4]=s[2],i[5]="")}var r=i[3],n=i[1]||vs,o=ms(n,r);return fs(t,r=o[1],n=o[0],i[4]?+i[4]:void 0,i[5]?+i[5]:void 0)}},Ps=/\(error: (.*)\)/;class Cs{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){var i=mt(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?t+": "+e.message:t}isDOMException(e){return Ft(e,"DOMException")}isDOMError(e){return Ft(e,"DOMError")}}class Is{match(e){return Tt(e)}coerce(e,t){var i,s=this.getStack(e),r=void 0===s;return{type:this.getType(e),value:this.getMessage(e,t),stack:null!=s?s:null==(i=t.syntheticException)?void 0:i.stack,cause:e.cause?t.next(e.cause):void 0,synthetic:r}}getType(e){return e.name||e.constructor.name}getMessage(e,t){var i=e.message;return String(i.error&&"string"==typeof i.error.message?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class Fs{constructor(){}match(e){return!!Ft(e,"ErrorEvent")&&(null!=e.error||this._hasUsableMessage(e))}coerce(e,t){var s;if(null!=e.error)return t.apply(e.error);var r=t.apply(e.message);return i({},r,{stack:null!==(s=this._buildLocationStack(e))&&void 0!==s?s:r.stack,synthetic:!0})}_hasUsableMessage(e){return mt(e.message)&&e.message.length>0}_buildLocationStack(e){var t,i,s=e,r=null!==(t=s.lineno)&&void 0!==t?t:0,n=null!==(i=s.colno)&&void 0!==i?i:0;if(mt(s.filename)&&0!==s.filename.length&&0!==r)return"Error\n at "+s.filename+":"+r+":"+n}}var Ts=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Rs{match(e){return"string"==typeof e}coerce(e,t){var i,s=this.getInfos(e),r=s[0],n=s[1];return{type:null!=r?r:"Error",value:null!=n?n:e,stack:null==(i=t.syntheticException)?void 0:i.stack,synthetic:!0}}getInfos(e){var t="Error",i=e,s=e.match(Ts);return s&&(t=s[1],i=s[2]),[t,i]}}var As=["fatal","error","warning","log","info","debug"];function Ls(e,t){void 0===t&&(t=40);var i=Object.keys(e);if(i.sort(),!i.length)return"[object has no keys]";for(var s=i.length;s>0;s--){var r=i.slice(0,s).join(", ");if(t>=r.length)return s===i.length?r:r.length>t?r.slice(0,t)+"...":r}return""}class Ms{match(e){return"object"==typeof e&&null!==e}coerce(e,t){var i,s,r=this.getErrorPropertyFromObject(e);return r?t.apply(r):{type:this.getType(e),value:this.getValue(e),stack:null!==(i=this.getStack(e))&&void 0!==i?i:null==(s=t.syntheticException)?void 0:s.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(Rt(e))return e.constructor.name;var t="name"in e?e.name:void 0;return mt(t)&&!yt(t)?t:"Error"}getValue(e){if("name"in e&&"string"==typeof e.name){var t="'"+e.name+"' captured as exception";return"message"in e&&"string"==typeof e.message&&(t+=" with message: '"+e.message+"'"),t}if("message"in e&&"string"==typeof e.message)return e.message;var i=this.getObjectClassName(e);return(i&&"Object"!==i?"'"+i+"'":"Object")+" captured as exception with keys: "+Ls(e)}isSeverityLevel(e){return mt(e)&&!yt(e)&&As.indexOf(e)>=0}getStack(e){try{return mt(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:mt(e.stack)&&e.stack.length>0?e.stack:void 0}catch(e){return}}getErrorPropertyFromObject(e){for(var t in e)if({}.hasOwnProperty.call(e,t)){var i=e[t];if(Tt(i))return i}}getObjectClassName(e){try{var t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){return}}}class $s{match(e){return Rt(e)}coerce(e,t){var i,s=e.constructor.name;return{type:s,value:s+" captured as exception with keys: "+Ls(e),stack:null==(i=t.syntheticException)?void 0:i.stack,synthetic:!0}}}class Os{match(e){return It(e)}coerce(e,t){var i;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:null==(i=t.syntheticException)?void 0:i.stack,synthetic:!0}}}class Ds{match(e){return Ft(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Rt(e))return!1;try{var t=e.detail;return null!=t&&"object"==typeof t&&"reason"in t}catch(e){return!1}}coerce(e,t){var i,s=this.getUnhandledRejectionReason(e);return It(s)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(s),stack:null==(i=t.syntheticException)?void 0:i.stack,synthetic:!0}:t.apply(s)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&null!=e.detail&&"object"==typeof e.detail&&"reason"in e.detail)return e.detail.reason}catch(e){}return e}}var Bs="$message",qs="$timestamp",Hs=new Set([Bs,qs]),Ns={enabled:!0,max_bytes:32768};function zs(e){var t;return e?{enabled:null!==(t=e.enabled)&&void 0!==t?t:Ns.enabled,max_bytes:Us(e.max_bytes,Ns.max_bytes)}:i({},Ns)}class js{constructor(e){this._entries=[],this._totalBytes=0,this._config=zs(e)}setConfig(e){this._config=zs(e),this._trimToMaxBytes()}add(e){var t=function(e){var t;try{t=ut(e)}catch(e){return}try{var i=JSON.parse(t);if(!gt(i))return;var s=i,r=s[Bs],n=s[qs];if(!mt(r)||0===r.trim().length)return;if(!mt(n)&&!St(n))return;return{step:s,json:t}}catch(e){return}}(e);if(t){var i=function(e){if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e).length;for(var t=encodeURIComponent(e),i=0,s=0;t.length>s;s++)"%"===t[s]?(i+=1,s+=2):i+=1;return i}(t.json);i>this._config.max_bytes||(this._entries.push({step:t.step,bytes:i}),this._totalBytes+=i,this._trimToMaxBytes())}}getAttachable(){return this._entries.map((e=>e.step))}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){var e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}}function Us(e,t){if(!St(e)||e===1/0||e===-1/0)return t;var i=Math.floor(e);return 0>i?t:i}var Vs=function(e,t){var i=(void 0===t?{}:t).debugEnabled,s={_log(t){if(we&&(r.DEBUG||we.POSTHOG_DEBUG||i)&&!ft(we.console)&&we.console){for(var s=("__rrweb_original__"in we.console[t]?we.console[t].__rrweb_original__:we.console[t]),n=arguments.length,o=new Array(n>1?n-1:0),a=1;n>a;a++)o[a-1]=arguments[a];s(e,...o)}},debug(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];s._log("debug",...t)},info(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];s._log("log",...t)},warn(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];s._log("warn",...t)},error(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];s._log("error",...t)},critical(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];console.error(e,...i)},uninitializedWarning(e){s.error("You must initialize PostHog before calling "+e)},createLogger:(t,i)=>Vs(e+" "+t,i)};return s},Ws=Vs("[PostHog.js]"),Gs=Ws.createLogger;function Ks(e,t){_t(e)&&e.forEach(t)}function Qs(e,t){if(!wt(e))if(_t(e))e.forEach(t);else if(kt(e))e.forEach(((e,i)=>t(e,i)));else for(var i in e)dt.call(e,i)&&t(e[i],i)}var Js=function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;t>s;s++)i[s-1]=arguments[s];for(var r of i)for(var n in r)void 0!==r[n]&&(e[n]=r[n]);return e};function Ys(e){for(var t=Object.keys(e),i=t.length,s=new Array(i);i--;)s[i]=[t[i],e[t[i]]];return s}var Zs=function(e){try{return e()}catch(e){return}},Xs=function(e){return function(){try{for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];return e.apply(this,i)}catch(e){Ws.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),Ws.critical(e)}}},er=function(e){var t={};return Qs(e,(function(e,i){(mt(e)&&e.length>0||St(e))&&(t[i]=e)})),t};var tr=["herokuapp.com","vercel.app","netlify.app"];function ir(e){var t=null==e?void 0:e.hostname;if(!mt(t))return!1;var i=t.split(".").slice(-2).join(".");for(var s of tr)if(i===s)return!1;return!0}function sr(e,t,i,s){var r=null!=s?s:{},n=r.capture,o=r.passive;null==e||e.addEventListener(t,i,{capture:void 0!==n&&n,passive:void 0===o||o})}function rr(e){return"ph_toolbar_internal"===e.name}var nr=e=>{if(Ee){try{for(var t=e+"=",i=Ee.cookie.split(";").filter((e=>e.length)),s=0;i.length>s;s++){for(var r=i[s];" "==r.charAt(0);)r=r.substring(1,r.length);if(0===r.indexOf(t))return decodeURIComponent(r.substring(t.length,r.length))}}catch(e){}return null}};Math.trunc||(Math.trunc=function(e){return 0>e?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return St(e)&&isFinite(e)&&Math.floor(e)===e});class or{constructor(e){if(this.bytes=e,16!==e.length)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,i,s){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(i)||!Number.isInteger(s)||0>e||0>t||0>i||0>s||e>0xffffffffffff||t>4095||i>1073741823||s>4294967295)throw new RangeError("invalid field value");var r=new Uint8Array(16);return r[0]=e/Math.pow(2,40),r[1]=e/Math.pow(2,32),r[2]=e/Math.pow(2,24),r[3]=e/Math.pow(2,16),r[4]=e/256,r[5]=e,r[6]=112|t>>>8,r[7]=t,r[8]=128|i>>>24,r[9]=i>>>16,r[10]=i>>>8,r[11]=i,r[12]=s>>>24,r[13]=s>>>16,r[14]=s>>>8,r[15]=s,new or(r)}toString(){for(var e="",t=0;this.bytes.length>t;t++)e=e+(this.bytes[t]>>>4).toString(16)+(15&this.bytes[t]).toString(16),3!==t&&5!==t&&7!==t&&9!==t||(e+="-");if(36!==e.length)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new or(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(var t=0;16>t;t++){var i=this.bytes[t]-e.bytes[t];if(0!==i)return Math.sign(i)}return 0}}class ar{generate(){var e=this.generateOrAbort();if(!ft(e))return e;this._timestamp=0;var t=this.generateOrAbort();if(ft(t))throw new Error("Could not generate UUID after timestamp reset");return t}generateOrAbort(){var e=Date.now();if(e>this._timestamp)this._timestamp=e,this._resetCounter();else{if(this._timestamp>=e+1e4)return;this._counter++,this._counter>4398046511103&&(this._timestamp++,this._resetCounter())}return or.fromFieldsV7(this._timestamp,Math.trunc(this._counter/Math.pow(2,30)),this._counter&Math.pow(2,30)-1,this._random.nextUint32())}_resetCounter(){this._counter=1024*this._random.nextUint32()+(1023&this._random.nextUint32())}constructor(){this._timestamp=0,this._counter=0,this._random=new cr}}var lr,ur=e=>{if("undefined"!=typeof UUIDV7_DENY_WEAK_RNG&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var t=0;e.length>t;t++)e[t]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e};we&&!ft(we.crypto)&&crypto.getRandomValues&&(ur=e=>crypto.getRandomValues(e));class cr{nextUint32(){return this._buffer.length>this._cursor||(ur(this._buffer),this._cursor=0),this._buffer[this._cursor++]}constructor(){this._buffer=new Uint32Array(8),this._cursor=1/0}}var dr=()=>hr().toString(),hr=()=>(lr||(lr=new ar)).generate(),_r="",pr=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;var gr={_is_supported:()=>!!Ee,_error(e){Ws.error("cookieStore error: "+e)},_get:nr,_parse(e){var t;try{t=JSON.parse(gr._get(e))||{}}catch(e){}return t},_set(e,t,i,s,r){if(!Ee)return!1;try{var n="",o="",a=function(e,t){if(t){var i=function(e,t){if(void 0===t&&(t=Ee),_r)return _r;if(!t)return"";if(["localhost","127.0.0.1"].includes(e))return"";for(var i=e.split("."),s=Math.min(i.length,8),r="dmn_chk_"+dr();!_r&&s--;){var n=i.slice(s).join("."),o=r+"=1;domain=."+n+";path=/";t.cookie=o+";max-age=3",t.cookie.includes(r)&&(t.cookie=o+";max-age=0",_r=n)}return _r}(e);if(!i){var s=(e=>{var t=e.match(pr);return t?t[0]:""})(e);s!==i&&Ws.info("Warning: cookie subdomain discovery mismatch",s,i),i=s}return i?"; domain=."+i:""}return""}(Ee.location.hostname,s);if(i){var l=new Date;l.setTime(l.getTime()+864e5*i),n="; expires="+l.toUTCString()}r&&(o="; secure");var u=e+"="+encodeURIComponent(JSON.stringify(t))+n+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&Ws.warn("cookieStore warning: large cookie, len="+u.length),Ee.cookie=u,!0}catch(e){return!1}},_remove(e,t){if(null!=Ee&&Ee.cookie)try{gr._set(e,"",-1,t)}catch(e){return}}},vr=null,fr={_is_supported(){if(!bt(vr))return vr;var e=!0;if(ft(we))e=!1;else try{var t="__mplssupport__";fr._set(t,"xyz"),'"xyz"'!==fr._get(t)&&(e=!1),fr._remove(t)}catch(t){e=!1}return e||Ws.error("localStorage unsupported; falling back to cookie store"),vr=e,e},_error(e){Ws.error("localStorage error: "+e)},_get(e){try{return null==we?void 0:we.localStorage.getItem(e)}catch(e){fr._error(e)}return null},_parse(e){try{return JSON.parse(fr._get(e))||{}}catch(e){}return null},_set(e,t){try{return null==we||we.localStorage.setItem(e,JSON.stringify(t)),!0}catch(e){fr._error(e)}return!1},_remove(e){try{null==we||we.localStorage.removeItem(e)}catch(e){fr._error(e)}}},mr=[B,F,I,R,A,L,J,Q,G],yr=[a,o,P,C,se,ie,Y],br=e=>e+"_cpm",wr=["__proto__","constructor","prototype"],Sr=e=>{if(!gt(e))return{};var t={};return Object.keys(e).forEach((i=>{-1===wr.indexOf(i)&&(t[i]=e[i])})),t},xr=function(e,t){void 0===t&&(t=[]);var i={};return[...yr,...t].forEach((t=>{var s=e[t];ft(s)||bt(s)||""===s||(i[t]=s)})),i},Er=e=>{for(var t=5381,i=2166136261,s=0;e.length>s;s++){var r=e.charCodeAt(s);t=33*t^r,i=Math.imul(i^r,16777619)}return e.length.toString(36)+"."+(t>>>0).toString(36)+"."+(i>>>0).toString(36)},kr=(e,t)=>({p:t,f:Er(JSON.stringify(e))}),Pr=(e,t)=>{if(!t)return{properties:[],isValid:!1};try{var i=gr._parse(br(e)),s=(null==i?void 0:i.f)===Er(t)&&_t(i.p);return{properties:s?i.p:[],isValid:s}}catch(e){return{properties:[],isValid:!1}}},Cr=(e,t)=>t+"|"+(gr._get(br(e))||""),Ir={},Fr={_is_supported:()=>!0,_error(e){Ws.error("memoryStorage error: "+e)},_get:e=>Ir[e]||null,_parse:e=>Ir[e]||null,_set:(e,t)=>(Ir[e]=t,!0),_remove(e){delete Ir[e]}},Tr=null,Rr={_is_supported(){if(!bt(Tr))return Tr;if(Tr=!0,ft(we))Tr=!1;else try{var e="__support__";Rr._set(e,"xyz"),'"xyz"'!==Rr._get(e)&&(Tr=!1),Rr._remove(e)}catch(e){Tr=!1}return Tr},_error(e){Ws.error("sessionStorage error: ",e)},_get(e){try{return null==we?void 0:we.sessionStorage.getItem(e)}catch(e){Rr._error(e)}return null},_parse(e){try{return JSON.parse(Rr._get(e))||null}catch(e){}return null},_set(e,t){try{return null==we||we.sessionStorage.setItem(e,JSON.stringify(t)),!0}catch(e){Rr._error(e)}return!1},_remove(e){try{null==we||we.sessionStorage.removeItem(e)}catch(e){Rr._error(e)}}};class Ar{constructor(e){this._instance=e}get _config(){return this._instance.config}get consent(){return this._getDnt()?0:this._storedConsent}isOptedOut(){return this._config.cookieless_mode===de||this.isRejected()||-1===this.consent&&this._config.cookieless_mode===ce}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return 0===this.consent}isRejected(){return 0===this.consent||-1===this.consent&&this._config.opt_out_capturing_by_default}optInOut(e){this._storage._set(this._storageKey,e?1:0,this._config.cookie_expiration,this._config.cross_subdomain_cookie,this._config.secure_cookie)}reset(){this._storage._remove(this._storageKey,this._config.cross_subdomain_cookie)}get _storageKey(){var e=this._instance.config,t=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+t:"__ph_opt_in_out_"+t)}get _storedConsent(){var e=this._storage._get(this._storageKey);return Mt(e)?1:ot($t,e)?0:-1}get _storage(){var e=this._config.opt_out_capturing_persistence_type,t="localStorage"===e?fr:gr;if(!this._persistentStore||this._persistentStore!==t){this._persistentStore=t;var i="localStorage"===e?gr:fr;i._get(this._storageKey)&&(this._persistentStore._get(this._storageKey)||this.optInOut(Mt(i._get(this._storageKey))),i._remove(this._storageKey,this._config.cross_subdomain_cookie))}return this._persistentStore}_getDnt(){return!!this._config.respect_dnt&&[null==xe?void 0:xe.doNotTrack,null==xe?void 0:xe.msDoNotTrack,Le.doNotTrack].some((e=>Mt(e)))}}function Lr(e,t){var i,s=null==e||null==(i=e.config)?void 0:i.get_current_url;if(!pt(s))return t;try{var r=s(t);return mt(r)&&r?r:t}catch(e){return Ws.error("Error in get_current_url, falling back to window.location.href",e),t}}var Mr="__POSTHOG_TOOLBAR__",$r=1,Or=3,Dr=11;function Br(e){return e instanceof Element&&(e.id===Mr||!(null==e.closest||!e.closest(".toolbar-global-fade-container")))}function qr(e){return!!e&&e.nodeType===$r}function Hr(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function Nr(e){return!!e&&e.nodeType===Or}function zr(e){return!!e&&e.nodeType===Dr&&qr(e.host)}var jr=1e3;function Ur(e){return e?at(e).split(/\s+/):[]}function Vr(e,t){var i=function(e){var t,i=null==we||null==(t=we.location)?void 0:t.href;return ft(i)?void 0:Lr(e,i)}(t);return!!(i&&e&&e.some((e=>i.match(e))))}function Wr(e){var t="";switch(typeof e.className){case"string":t=e.className;break;case"object":t=(e.className&&"baseVal"in e.className?e.className.baseVal:null)||e.getAttribute("class")||"";break;default:t=""}return Ur(t)}function Gr(e){return wt(e)?null:at(e).split(/(\s+)/).filter((e=>mn(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Kr(e){var t="";return un(e)&&!cn(e)&&e.childNodes&&e.childNodes.length&&Qs(e.childNodes,(function(e){var i;Nr(e)&&e.textContent&&(t+=null!==(i=Gr(e.textContent))&&void 0!==i?i:"")})),at(t)}function Qr(e){var t;return ft(e.target)?e.srcElement||null:null!=(t=e.target)&&t.shadowRoot?e.composedPath()[0]||null:e.target||null}var Jr=["a","button","form","input","select","textarea","label"];function Yr(e,t){if(ft(t))return!0;var i,s=function(e){if(t.some((t=>function(e,t){var i=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector;try{return!!i&&i.call(e,t)}catch(e){return!1}}(e,t))))return{v:!0}};for(var r of e)if(i=s(r))return i.v;return!1}function Zr(e){var t=e.parentNode;return!(!t||!qr(t))&&t}var Xr=[".ph-no-autocapture","[data-ph-no-autocapture]"],en=["next","previous","prev",">","<"],tn=[...en,"+","-","−","–"],sn=(e,t)=>/[a-z0-9]/i.test(t)?e.includes(t):e===t,rn=[".ph-no-rageclick",".ph-no-capture"],nn=["","text","search","email","password","url","tel","number"];function on(e,t){if(!we||an(e))return!1;var i,s,r,n,o;if(Et(t)?(i=!!t&&rn,s=void 0,r=!1):(i=null!==(n=null==t?void 0:t.css_selector_ignorelist)&&void 0!==n?n:rn,s=null==t?void 0:t.content_ignorelist,r=null!==(o=null==t?void 0:t.ignore_text_selection)&&void 0!==o&&o),!1===i)return!1;if(r&&function(e){return!(!e||!qr(e))&&(!!Hr(e,"textarea")||(Hr(e,"input")?ot(nn,(e.getAttribute("type")||"").toLowerCase()):function(e){if(e.isContentEditable)return!0;var t=null==e.getAttribute?void 0:e.getAttribute("contenteditable");return"true"===t||""===t}(e)))}(e))return!1;var a=ln(e,!1).targetElementList;return!function(e,t){if(!1===e||ft(e))return!1;var i;if(!0===e)i=en;else{if(!_t(e))return!1;if(e.length>10)return Ws.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;i=e.map((e=>e.toLowerCase()))}return t.some((e=>{var t=e.safeText,s=e.ariaLabel;return i.some((e=>sn(t,e)||sn(s,e)))}))}(s,a.map((e=>{var t;return{safeText:Kr(e).toLowerCase(),ariaLabel:(null==(t=e.getAttribute("aria-label"))?void 0:t.toLowerCase().trim())||""}})))&&!Yr(a,i)}var an=e=>!e||Hr(e,"html")||!qr(e),ln=(e,t)=>{if(!we||an(e))return{parentIsUsefulElement:!1,targetElementList:[]};for(var i=!1,s=[e],r=e;r.parentNode&&!Hr(r,"body");)if(zr(r.parentNode))s.push(r.parentNode.host),r=r.parentNode.host;else{var n=Zr(r);if(!n)break;if(t||Jr.indexOf(n.tagName.toLowerCase())>-1)i=!0;else try{var o=we.getComputedStyle(n);o&&"pointer"===o.getPropertyValue("cursor")&&(i=!0)}catch(e){}s.push(n),r=n}return{parentIsUsefulElement:i,targetElementList:s}};function un(e){for(var t=new Set,i=0,s=e;s.parentNode&&!Hr(s,"body");s=s.parentNode){if(i++>=jr||t.has(s))return!1;t.add(s);var r=Wr(s);if(ot(r,"ph-sensitive")||ot(r,"ph-no-capture"))return!1}if(ot(Wr(e),"ph-include"))return!0;var n=e.type||"";if(mt(n))switch(n.toLowerCase()){case"hidden":case"password":return!1}var o=e.name||e.id||"";return!mt(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function cn(e){return!!(Hr(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||Hr(e,"select")||Hr(e,"textarea")||"true"===e.getAttribute("contenteditable"))}var dn=new RegExp("^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$"),hn=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,_n=[16,15,14,13],pn=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),gn=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),vn=/[0-9A-Za-z_]/;function fn(e){for(var t=0,i=!1,s=e.length-1;s>=0;s--){var r=e.charCodeAt(s)-48;i&&(r*=2)>9&&(r-=9),t+=r,i=!i}return t%10==0}function mn(e,t){if(void 0===t&&(t=!0),wt(e))return!1;if(mt(e)){e=at(e);var i=t?dn.test((e||"").replace(/[- ]/g,"")):function(e){var t;for(hn.lastIndex=0;t=hn.exec(e);){var i=t[2];if(i)for(var s=i.replace(/[- ]/g,""),r=0;s.length>r;r++)for(var n of _n){var o=r+n;if(s.length>=o){var a=s.slice(r,o);if(dn.test(a)&&fn(a))return!0}}}return!1}(e);if(i)return!1;var s=t?pn.test(e):function(e){var t;for(gn.lastIndex=0;t=gn.exec(e);){var i=t[1],s=t[3];if(!(i&&s&&vn.test(i)&&vn.test(s)))return!0}return!1}(e);if(s)return!1}return!0}function yn(e){var t=Kr(e);return mn(t=(t+" "+bn(e)).trim())?t:""}function bn(e){var t="";return e&&e.childNodes&&e.childNodes.length&&Qs(e.childNodes,(function(e){var i;if(e&&"span"===(null==(i=e.tagName)?void 0:i.toLowerCase()))try{var s=Kr(e);t=(t+" "+s).trim(),e.childNodes&&e.childNodes.length&&(t=(t+" "+bn(e)).trim())}catch(e){Ws.error("[AutoCapture]",e)}})),t}function wn(e){return e.replace(/"|\\"/g,'\\"')}function Sn(e){var t=e.attr__class;if(t)return _t(t)?t:Ur(t)}var xn=Gs("[Dead Clicks]"),En=()=>!0,kn=e=>{var t,i=!(null==(t=e.instance.persistence)||!t.get_property(f)),s=e.instance.config.capture_dead_clicks;return Et(s)?s:!!gt(s)||i};class Pn{get lazyLoadedDeadClicksAutocapture(){return this._lazyLoadedDeadClicksAutocapture}constructor(e,t,i){this.instance=e,this.isEnabled=t,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var t=e.config;"captureDeadClicks"in t&&(this.instance.persistence&&this.instance.persistence.register({[f]:t.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this._loadScript((()=>{this._start()})):this.stop()}_loadScript(e){var t,i;null!=(t=Le.__PosthogExtensions__)&&t.initDeadClicksAutocapture?e():null==(i=Le.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(t=>{t?xn.error("failed to load script",t):e()}))}_start(){var e;if(Ee){if(!this._lazyLoadedDeadClicksAutocapture&&null!=(e=Le.__PosthogExtensions__)&&e.initDeadClicksAutocapture){var t=gt(this.instance.config.capture_dead_clicks)?i({},this.instance.config.capture_dead_clicks):{};t.__onCapture=this.onCapture,this.onCapture&&(t.capture_dead_swipes=!1),this._lazyLoadedDeadClicksAutocapture=Le.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,t),this._lazyLoadedDeadClicksAutocapture.start(Ee),xn.info("starting...")}}else xn.error("`document` not found. Cannot start.")}stop(){this._lazyLoadedDeadClicksAutocapture&&(this._lazyLoadedDeadClicksAutocapture.stop(),this._lazyLoadedDeadClicksAutocapture=void 0,xn.info("stopping..."))}}var Cn=Gs("[SegmentIntegration]");var In="posthog-js";function Fn(e,t){var s=void 0===t?{}:t,r=s.organization,n=s.projectId,o=s.prefix,a=s.severityAllowList,l=void 0===a?["error"]:a,u=s.sendExceptionsToPostHog,c=void 0===u||u;return t=>{var s,a,u,d,h;if("*"!==l&&!l.includes(t.level)||!e.__loaded)return t;t.tags||(t.tags={});var _=e.requestRouter.endpointFor("ui","/project/"+e.config.token+"/person/"+e.get_distinct_id());t.tags["PostHog Person URL"]=_,e.sessionRecordingStarted()&&(t.tags["PostHog Recording URL"]=e.get_session_replay_url({withTimestamp:!0}));var p,g=(null==(s=t.exception)?void 0:s.values)||[],v=g.map((e=>i({},e,{stacktrace:e.stacktrace?i({},e.stacktrace,{type:"raw",frames:(e.stacktrace.frames||[]).map((e=>i({},e,{platform:"web:javascript"})))}):void 0}))),f={$exception_message:(null==(a=g[0])?void 0:a.value)||t.message,$exception_type:null==(u=g[0])?void 0:u.type,$exception_level:t.level,$exception_list:v,$sentry_event_id:t.event_id,$sentry_exception:t.exception,$sentry_exception_message:(null==(d=g[0])?void 0:d.value)||t.message,$sentry_exception_type:null==(h=g[0])?void 0:h.type,$sentry_tags:t.tags};return r&&n&&(f.$sentry_url=(o||"https://sentry.io/organizations/")+r+"/issues/?project="+n+"&query="+t.event_id),c&&(null==(p=e.exceptions)||p.sendExceptionEvent(f)),t}}class Tn{constructor(e,t,i,s,r,n){this.name=In,this.setupOnce=function(o){o(Fn(e,{organization:t,projectId:i,prefix:s,severityAllowList:r,sendExceptionsToPostHog:null==n||n}))}}}class Rn{constructor(e){this._onSessionIdChange=(e,t,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength||i.crossTabAdoption)&&(Ws.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:e,changeReason:i}),this._currentPageview=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this._setupSessionRotationHandler()}_setupSessionRotationHandler(){var e;this._unsubscribeSessionId=null==(e=this._instance.sessionManager)?void 0:e.onSessionId(this._onSessionIdChange)}destroy(){var e;null==(e=this._unsubscribeSessionId)||e.call(this),this._unsubscribeSessionId=void 0}doPageView(e,t){var i,s=this._previousPageViewProperties(e,t);return this._currentPageview={pathname:null!==(i=null==we?void 0:we.location.pathname)&&void 0!==i?i:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),s}doPageLeave(e){var t;return this._previousPageViewProperties(e,null==(t=this._currentPageview)?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:null==(e=this._currentPageview)?void 0:e.pageViewId}}_previousPageViewProperties(e,t){var i=this._currentPageview;if(!i)return{$pageview_id:t};var s={$pageview_id:t,$prev_pageview_id:i.pageViewId},r=this._instance.scrollManager.getContext();if(r&&!this._instance.config.disable_scroll_properties){var n=r.maxScrollHeight,o=r.lastScrollY,a=r.maxScrollY,l=r.maxContentHeight,u=r.lastContentY,c=r.maxContentY;if(!(ft(n)||ft(o)||ft(a)||ft(l)||ft(u)||ft(c))){n=Math.ceil(n),o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c);var d=n>1?Ot(o/n,0,1,Ws):1,h=n>1?Ot(a/n,0,1,Ws):1,_=l>1?Ot(u/l,0,1,Ws):1,p=l>1?Ot(c/l,0,1,Ws):1;s=Js(s,{$prev_pageview_last_scroll:o,$prev_pageview_last_scroll_percentage:d,$prev_pageview_max_scroll:a,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:u,$prev_pageview_last_content_percentage:_,$prev_pageview_max_content:c,$prev_pageview_max_content_percentage:p})}}return i.pathname&&(s.$prev_pageview_pathname=i.pathname),i.timestamp&&(s.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),s}}var An=["flags","surveys"],Ln={[n]:{exposure:"hidden"},[u]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[c]:{exposure:"hidden"},[d]:{exposure:"event"},[h]:{exposure:"hidden"},[_]:{exposure:"event"},[p]:{exposure:"hidden"},[g]:{exposure:"event"},[v]:{exposure:"event"},[f]:{exposure:"event"},[m]:{exposure:"hidden"},[y]:{exposure:"event"},[b]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[P]:{exposure:"hidden"},[C]:{exposure:"event"},[w]:{exposure:"event",shouldSkipFromEventProperties:e=>bt(e)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[I]:{exposure:"hidden",storageGroup:"flags"},[F]:{exposure:"hidden",storageGroup:"flags"},[T]:{exposure:"hidden"},[R]:{exposure:"hidden",storageGroup:"flags"},[A]:{exposure:"hidden",storageGroup:"flags"},[L]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[M]:{exposure:"hidden",storageGroup:"flags"},[O]:{exposure:"hidden"},[D]:{exposure:"hidden"},[B]:{exposure:"hidden"},[q]:{exposure:"hidden"},[N]:{exposure:"hidden",storageGroup:"surveys"},[z]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[j]:{exposure:"event"},[U]:{exposure:"hidden"},[V]:{exposure:"hidden"},[W]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[G]:{exposure:"hidden"},[K]:{exposure:"hidden"},[H]:{exposure:"event"},[Q]:{exposure:"hidden"},[J]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Y]:{exposure:"hidden"},[Z]:{exposure:"hidden"},[X]:{exposure:"hidden"},[ee]:{exposure:"hidden"},[te]:{exposure:"hidden"},[ie]:{exposure:"hidden"},[se]:{exposure:"hidden"},[S]:{exposure:"event"},[x]:{exposure:"event"},[E]:{exposure:"event"},[k]:{exposure:"event"},[oe]:{exposure:"event"},[ae]:{exposure:"event"},[le]:{exposure:"event"},$sdk_debug_replay_event_trigger_status:{exposure:"event"},$sdk_debug_replay_linked_flag_trigger_status:{exposure:"event"},$sdk_debug_replay_matched_recording_trigger_groups:{exposure:"event"},$sdk_debug_replay_pending_trigger_conditions:{exposure:"event"},$sdk_debug_replay_remote_trigger_matching_config:{exposure:"event"},$sdk_debug_replay_trigger_groups_count:{exposure:"event"},$sdk_debug_replay_url_trigger_status:{exposure:"event"},$session_recording_start_reason:{exposure:"event"}},Mn=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],$n=e=>{var t=Ln[e];if(t)return t;for(var i of Mn){var s=i[1];if(0===e.indexOf(i[0]))return s}},On=(e,t)=>{try{return JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString():t),t)}catch(t){return ut(e)}},Dn=e=>{var t=null==Ee?void 0:Ee.createElement("a");return ft(t)?null:(t.href=e,t)},Bn=function(e,t){for(var i,s=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;s.length>r;r++){var n=s[r].split("=");if(n[0]===t){i=n;break}}if(!_t(i)||2>i.length)return"";var o=i[1];try{o=decodeURIComponent(o)}catch(e){Ws.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},qn=function(e,t,i){if(!e||!t||!t.length)return e;for(var s=e.split("#"),r=s[1],n=(s[0]||"").split("?"),o=n[1],a=n[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");_t(d)&&(t.includes(d[0])?u.push(d[0]+"="+i):u.push(l[c]))}var h=a;return null!=o&&(h+="?"+u.join("&")),null!=r&&(h+="#"+r),h},Hn=function(e,t){var i=e.match(new RegExp(t+"=([^&]*)"));return i?i[1]:null},Nn=(e,t)=>e>=t&&Re(),zn=(e,t,i,s)=>{if(0===e){if(Re()){var r=t+1;return r===i&&s(),r}return t}return 0},jn="https?://(.*)",Un=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Vn=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...Un],Wn="<masked>",Gn=["li_fat_id"];function Kn(e,t,i){if(!Ee)return{};var s,r=t?[...Un,...i||[]]:[],n=Qn(qn(Ee.URL,r,Wn),e),o=(s={},Qs(Gn,(function(e){var t=nr(e);s[e]=t||null})),s);return Js(o,n)}function Qn(e,t){var i=Vn.concat(t||[]),s={};return Qs(i,(function(t){var i=Bn(e,t);s[t]=i||null})),s}function Jn(e){var t=function(e){return e?0===e.search(jn+"google.([^/?]*)")?"google":0===e.search(jn+"bing.com")?"bing":0===e.search(jn+"yahoo.com")?"yahoo":0===e.search(jn+"duckduckgo.com")?"duckduckgo":null:null}(e),i="yahoo"!=t?"q":"p",s={};if(!bt(t)){s.$search_engine=t;var r=Ee?Bn(Ee.referrer,i):"";r.length&&(s.ph_keyword=r)}return s}function Yn(){return navigator.language||navigator.userLanguage}var Zn="$direct";function Xn(){return(null==Ee?void 0:Ee.referrer)||Zn}function eo(e,t,i){void 0===i&&(i=!1);var s=e?[...Un,...t||[]]:[],r=i?Ui(null==ke?void 0:ke.href):null==ke?void 0:ke.href,n=null==r?void 0:r.substring(0,1e3);return{r:Xn().substring(0,1e3),u:n?qn(n,s,Wn):void 0}}function to(e,t){var i;void 0===t&&(t=!1);var s=e.r,r=e.u,n=t?Ui(r):r,o={$referrer:s,$referring_domain:null==s?void 0:s==Zn?Zn:null==(i=Dn(s))?void 0:i.host};if(n){o.$current_url=n;var a=Dn(n);o.$host=null==a?void 0:a.host,o.$pathname=null==a?void 0:a.pathname;var l=Qn(n);Js(o,l)}if(s){var u=Jn(s);Js(o,u)}return o}function io(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(e){return}}function so(){try{return(new Date).getTimezoneOffset()}catch(e){return}}var ro={flags:J,surveys:z},no=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],oo=e=>e+"_cookie_identity_change_pending",ao="main",lo=(e,t)=>{Qs(e,((i,s)=>{var r=$n(s);r&&"event"!==r.exposure||{}.hasOwnProperty.call(t,s)||delete e[s]}))};class uo{constructor(e,t,s){if(void 0===s&&(s=!0),this._slotState={},this._splitStorageEligible=!1,this._splitStorage=!1,this._cookieIdentityChangePending=!1,this._cookieSyncSuppressed=!1,this._config=e,this._ownsSplitStorage=s,this.props={},this._campaign_params_url=void 0,this._name=(e=>{var t="";return e.token&&(t=e.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),e.persistence_name?"ph_"+e.persistence_name:"ph_"+t+"_posthog"})(e),this._storage=this._buildStorage(e),this._splitStorage=this._resolveSplitStorage(e),this.load(),e.debug&&Ws.info("Persistence loaded",e.persistence,i({},this.props)),this.update_config(e,e,t),this.save(),we){var r=()=>this.flush();sr(we,"beforeunload",r,{capture:!1}),sr(we,"pagehide",r,{capture:!1})}}_saveDebounceMs(){var e,t=null==(e=this._config)?void 0:e.persistence_save_debounce_ms;return St(t)&&t>0?t:0}_rememberCurrentCookieProperties(e){if(this._config.cookieWinsOnConflict&&"localstorage+cookie"===this._config.persistence.toLowerCase())if(e)try{var t=xr(e,this._config.cookie_persisted_properties||[]),i=kr(t,this._config.cookie_persisted_properties||[]),s=JSON.stringify(t)+"|"+JSON.stringify(i),r=gr._get(this._name)||void 0;r&&Cr(this._name,r)===s&&(this._lastSeenCookiePropertiesFingerprint=s,this._lastSeenMainCookieValue=r)}catch(e){}else try{var n=gr._get(this._name)||void 0;this._lastSeenCookiePropertiesFingerprint=n?Cr(this._name,n):void 0,this._lastSeenMainCookieValue=n}catch(e){}}syncCookieProperties(){return this._syncCookieProperties(this._config)}_syncCookieProperties(e,t){if(void 0===t&&(t=!1),this._disabled&&!t||this._cookieSyncSuppressed||!e.cookieWinsOnConflict||"localstorage+cookie"!==e.persistence.toLowerCase())return!1;var i;try{i=gr._get(this._name)||void 0}catch(e){}if(!i||i===this._lastSeenMainCookieValue)return!1;var s,r=Cr(this._name,i);try{s=Sr(JSON.parse(i))}catch(e){return!1}if((gr._get(this._name)||void 0)!==i)return!1;this._lastSeenCookiePropertiesFingerprint=r,this._lastSeenMainCookieValue=i;var n=Pr(this._name,i),a=[...yr,...n.properties],l={};if(Object.keys(s).forEach((e=>{var t=s[e];(ft(t)||bt(t)||""===t||e===Y&&t!==he&&t!==_e)&&(l[e]=!0,delete s[e])})),vt(s))return!1;var c=o in s||s[Y]===he||s[Y]===_e,d=this.props[o],h=this.props[Y],_=Js({},this.props);[...yr,...e.cookie_persisted_properties||[]].forEach((e=>{if(-1!==a.indexOf(e)&&!(e in s)&&!l[e]&&(c||e!==o&&e!==Y)){var t=_[e];!n.isValid&&-1!==yr.indexOf(e)&&(!1===t||0===t)||delete _[e]}})),this.props=Js(_,s),!c||Y in s||Y in this.props||this._setProp(Y,he);var p=this.props[o],g=this.props[Y];return!c||p===d&&g===h||(this._cookieIdentityChangePending=!0,Rr._set(oo(this._name),!0),this._deleteProp(B),this._deleteProp(F),this._deleteProp(I),this._deleteProp(R),this._deleteProp(A),this._deleteProp(L),this._deleteProp(J),this._deleteProp(Q),this._deleteProp(G),g===he&&(h===_e||s[Y]===he||!ft(d)&&p!==d)&&(lo(this.props,s),this._deleteProp(q)),g===_e?this.props.$user_id=p:delete this.props.$user_id,this._deleteProp(u)),!0}consumeCookieIdentityChange(){var e=oo(this._name),t=this._cookieIdentityChangePending||!!Rr._get(e);return this._cookieIdentityChangePending=!1,t&&Rr._remove(e),t}_beginCookieSyncSuppression(e){return void 0===e&&(e=!1),!(this._cookieSyncSuppressed||this._disabled&&!e||!this._config.cookieWinsOnConflict||"localstorage+cookie"!==this._config.persistence.toLowerCase()||(this._cookieSyncSuppressed=!0,0))}_publishSuppressedCookieSnapshot(){this._cookieSyncSuppressed&&(ft(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0),delete this._slotState[ao],this._writeNow(!0))}_endCookieSyncSuppression(e){if(void 0===e&&(e=!0),this._cookieSyncSuppressed)try{e?this._publishSuppressedCookieSnapshot():ft(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0)}finally{this._cookieSyncSuppressed=!1}}isDisabled(){return!!this._disabled}_buildStorage(e){-1===no.indexOf(e.persistence.toLowerCase())&&(Ws.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var t,s=function(e,t){void 0===e&&(e=[]),void 0===t&&(t=!1);var s=[...yr,...e];return i({},fr,{_parse(e){try{var i,r={};try{i=gr._get(e)||void 0,r=i?Sr(JSON.parse(i)):{}}catch(e){}var n,a=JSON.parse(fr._get(e)||"{}");if(t){var l=Pr(e,i),u=[...yr,...l.properties],c={};Object.keys(r).forEach((e=>{var t=r[e];bt(t)||""===t||e===Y&&t!==he&&t!==_e||(c[e]=t)}));var d=o in c||c[Y]===he||c[Y]===_e;if(Object.keys(c).length>0){var h,_=a[o],p=null!==(h=a[Y])&&void 0!==h?h:he;s.forEach((e=>{if(-1!==u.indexOf(e)&&!(e in r)&&(d||e!==o&&e!==Y)){var t=a[e];!l.isValid&&-1!==yr.indexOf(e)&&(!1===t||0===t)||delete a[e]}})),!d||Y in r||Y in a||(a[Y]=he),!d||(o in c?c[o]:a[o])===_&&(Y in c?c[Y]:a[Y])===p||(mr.forEach((e=>delete a[e])),c[Y]===_e&&o in c?a.$user_id=c[o]:delete a.$user_id,c[Y]!==_e&&(delete a[H],delete a[q]),delete a.__alias)}n=Js(a,c)}else n=Js(r,a);return fr._set(e,n),n}catch(e){}return null},_set(i,s,r,n,o,a){var l=fr._set(i,s,void 0,void 0,a);try{var u=xr(s,e);if(Object.keys(u).length){if(t){var c=br(i),d=kr(u,e);if(gr._set(c,d,r,n,o,a),gr._get(c)!==JSON.stringify(d)){gr._remove(c,n);var h=xr(s);return gr._set(i,h,r,n,o,a),l}}gr._set(i,u,r,n,o,a)}}catch(e){fr._error(e)}return l},_remove(e,t){try{null==we||we.localStorage.removeItem(e),gr._remove(e,t),gr._remove(br(e),t)}catch(e){fr._error(e)}}})}(e.cookie_persisted_properties||[],e.cookieWinsOnConflict),r=!1,n=e.persistence.toLowerCase();return"localstorage"===n&&fr._is_supported()?(t=fr,r=!0):"localstorage+cookie"===n&&s._is_supported()?(t=s,r=!0):"sessionstorage"===n&&Rr._is_supported()?t=Rr:"memory"===n?t=Fr:"cookie"===n?t=gr:s._is_supported()?(t=s,r=!0):t=gr,this._splitStorageEligible=r,t}_groupEntryName(e){return this._name+"__"+e}_resolveSplitStorage(e){return this._splitStorageEligible&&!!e.split_storage}properties(){var e={};return Qs(this.props,((t,i)=>{var s=$n(i);if(!s||"event"===s.exposure){if(null!=s&&null!=s.shouldSkipFromEventProperties&&s.shouldSkipFromEventProperties(t))return;e[i]=t}})),e}load(e){if(void 0===e&&(e=!1),!this._disabled||e){var t=this._config.cookieWinsOnConflict&&"localstorage+cookie"===this._config.persistence.toLowerCase(),i=t?fr._parse(this._name):null,s={};if(t)try{Qs(s=Sr(gr._parse(this._name)),((e,t)=>{(ft(e)||bt(e)||""===e)&&delete s[t]}))}catch(e){}var r=this._storage._parse(this._name);if(r&&(this.props=Js({},r)),this._splitStorage&&this._loadGroupEntries(),t&&r){var n,a,l=null==i?void 0:i[o],u=null!==(n=null==i?void 0:i[Y])&&void 0!==n?n:he,c=r[o],d=null!==(a=r[Y])&&void 0!==a?a:he;if(c!==l||d!==u){this._cookieIdentityChangePending=!0,Rr._set(oo(this._name),!0);var h=Js({},this.props);mr.forEach((e=>delete h[e])),d===he&&(u===_e||s[Y]===he||!ft(l)&&c!==l)&&(lo(h,s),delete h[q]),this.props=h;var _=new Set;mr.forEach((e=>{var t,i=null==(t=$n(e))?void 0:t.storageGroup;i&&_.add(i)})),_.forEach((e=>{var t={};Qs(this.props,((i,s)=>{var r;(null==(r=$n(s))?void 0:r.storageGroup)===e&&(t[s]=i)})),vt(t)?(fr._remove(this._groupEntryName(e)),this._slotState[e]={}):fr._set(this._groupEntryName(e),t)&&(this._slotState[e]={persisted:!0,fingerprint:this._entryFingerprint(t,e)})}))}}Rr._get(oo(this._name))&&(this._cookieIdentityChangePending=!0)}}_loadGroupEntries(){for(var e of An){var t=fr._parse(this._groupEntryName(e));if(t&&!vt(t)){var i=this._slotWriteState(e);i.persisted=!0,this._mainCarriesGroupKey(e)||(i.fingerprint=this._entryFingerprint(t,e)),this._groupEntryIsStale(e,t)||Js(this.props,t)}}}_mainCarriesGroupKey(e){return Object.keys(this.props).some((t=>{var i;return(null==(i=$n(t))?void 0:i.storageGroup)===e}))}_groupEntryIsStale(e,t){var i=ro[e];if(!i)return!1;var s=t[i],r=this.props[i];return St(s)&&St(r)&&r>s}refreshKey(e){var t;if(!this._disabled){var i=this._splitStorage?null==(t=$n(e))?void 0:t.storageGroup:void 0,s=i?fr._parse(this._groupEntryName(i)):this._storage._parse(this._name);if(s&&e in s)this._setProp(e,s[e]);else{if(i){var r=this._storage._parse(this._name);if(r&&e in r)return void this._setProp(e,r[e])}this._deleteProp(e)}}}save(){if(!this._disabled){var e=this._saveDebounceMs();e>0?ft(this._pendingSaveTimer)&&(this._pendingSaveTimer=setTimeout((()=>{this._pendingSaveTimer=void 0,this._writeNow()}),e)):this._writeNow()}}flush(){ft(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0,this._writeNow())}_writeNow(e){void 0===e&&(e=!1),this._disabled||this._cookieSyncSuppressed&&!e||(e||this.syncCookieProperties(),this._splitStorage?this._writeNowSplit():this._writeEntry(this._storage,this._name,this.props,ao)&&this._rememberCurrentCookieProperties(this.props))}_writeNowSplit(){var e=this._partitionProps(),t=e.main,i=e.groups;for(var s of(this._writeEntry(this._storage,this._name,t,ao)&&this._rememberCurrentCookieProperties(t),An)){var r,n=i[s];(!vt(n)||null!=(r=this._slotState[s])&&r.persisted)&&this._writeEntry(fr,this._groupEntryName(s),n,s)}}_partitionProps(){var e={},t={flags:{},surveys:{}};return Qs(this.props,((i,s)=>{var r,n=null==(r=$n(s))?void 0:r.storageGroup;n?t[n][s]=i:e[s]=i})),{main:e,groups:t}}_entryFingerprint(e,t){if(t===ao)return JSON.stringify(e)+"|"+this._expire_days+"|"+this._cross_subdomain+"|"+this._secure;var i={};return Qs(e,((e,t)=>{var s;i[t]=null!=(s=$n(t))&&s.volatile?"__volatile__":e})),JSON.stringify(i)}_writeEntry(e,t,i,s){var r,n=this._slotWriteState(s);if(s!==ao&&!n.dirty&&!ft(n.fingerprint))return!1;try{if((r=this._entryFingerprint(i,s))===n.fingerprint)return n.dirty=!1,!1}catch(e){r=void 0}return e._set(t,i,this._expire_days,this._cross_subdomain,this._secure,this._config.debug)?(n.dirty=!1,s!==ao&&(n.persisted=!0),ft(r)||(n.fingerprint=r),!0):(this._config.debug&&Ws.warn('failed to persist storage entry "'+t+'"; will retry on next save'),!1)}remove(e){var t=(void 0===e?{}:e).keepGroupEntries,i=void 0!==t&&t;if(ft(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0),this._storage._remove(this._name,!1),this._storage._remove(this._name,!0),!i&&this._ownsSplitStorage)for(var s of An)fr._remove(this._groupEntryName(s));i?delete this._slotState[ao]:this._slotState={},this._lastSeenCookiePropertiesFingerprint=void 0,this._lastSeenMainCookieValue=void 0}clear(){this.remove(),this.props={}}register_once(e,t,i){if(gt(e)){this.syncCookieProperties(),ft(t)&&(t="None"),this._expire_days=ft(i)?this._default_expiry:i;var s=!1;if(Qs(e,((e,i)=>{this.props.hasOwnProperty(i)&&this.props[i]!==t||(this._setProp(i,e),s=!0)})),s)return this.save(),!0}return!1}register(e,t){if(gt(e)){this.syncCookieProperties(),this._expire_days=ft(t)?this._default_expiry:t;var i=!1;if(Qs(e,((t,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==t||gt(t)||_t(t))&&(this._setProp(s,t),i=!0)})),i)return this.save(),!0}return!1}unregister(e){this.syncCookieProperties();var t="string"==typeof e?[e]:e,i=!1;for(var s of t)s in this.props&&(this._deleteProp(s),i=!0);i&&this.save()}update_campaign_params(){var e=null==Ee?void 0:Ee.URL;if(e!==this._campaign_params_url){var t=Kn(this._config.custom_campaign_params,this._config.mask_personal_data_properties,this._config.custom_personal_data_properties);vt(er(t))||this.register(t),this._campaign_params_url=e}}update_search_keyword(){var e;this.register((e=null==Ee?void 0:Ee.referrer)?Jn(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Xn(),$referring_domain:null!=Ee&&Ee.referrer&&(null==(e=Dn(Ee.referrer))?void 0:e.host)||Zn},void 0)}set_initial_person_info(){this.props[ee]||this.props[te]||this.register_once({[ie]:eo(this._config.mask_personal_data_properties,this._config.custom_personal_data_properties,this._config.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};Qs([te,ee],(t=>{var i=this.props[t];i&&Qs(i,(function(t,i){e["$initial_"+lt(i)]=t}))}));var t=this.props[ie];if(t){var i=function(e,t){void 0===t&&(t=!1);var i=to(e,t),s={};return Qs(i,(function(e,t){s["$initial_"+lt(t)]=e})),s}(t,this._config.disable_capture_url_hashes);Js(e,i)}return e}safe_merge(e){return Qs(this.props,(function(t,i){i in e||(e[i]=t)})),e}update_config(e,t,s){var r=e.persistence!==t.persistence,n=!((e,t)=>{if(e.length!==t.length)return!1;var i=[...e].sort(),s=[...t].sort();return i.every(((e,t)=>e===s[t]))})(e.cookie_persisted_properties||[],t.cookie_persisted_properties||[]),o=r||n,a=e.cookieWinsOnConflict!==t.cookieWinsOnConflict,l=e.disable_persistence||!!s,u=!!this._disabled&&!l;l||this._syncCookieProperties(t,u),this._config=e,!l&&(r||n||a)&&(this._lastSeenCookiePropertiesFingerprint=void 0,this._lastSeenMainCookieValue=void 0,this._syncCookieProperties(i({},e,{cookie_persisted_properties:t.cookie_persisted_properties}),u));var c=o||a?this._buildStorage(e):this._storage,d=this._resolveSplitStorage(e),h=o||d!==this._splitStorage,_=!l&&(h||e.cross_subdomain_cookie!==this._cross_subdomain||e.secure_cookie!==this._secure)&&this._beginCookieSyncSuppression(u);try{if(this._default_expiry=this._expire_days=e.cookie_expiration,this.set_disabled(l),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),h){var p=this.props;this.clear(),this._storage=c,this._splitStorage=d,this.props=p,this.save()}else a&&(this._storage=c,l||(delete this._slotState[ao],this._writeNow()))}finally{_&&this._endCookieSyncSuppression()}}set_disabled(e){this._disabled=e,this._disabled?this.remove():this.save()}set_cross_subdomain(e){e!==this._cross_subdomain&&(this._cross_subdomain=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this._secure&&(this._secure=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,t){var i=this.props[c]||{};i[e]=t,this._setProp(c,i),this.save()}remove_event_timer(e){var t=this.props[c]||{},i=t[e];return ft(i)||(delete t[e],this._setProp(c,t),this.save()),i}get_property(e){return this.props[e]}set_property(e,t){this._setProp(e,t),this.save()}_setProp(e,t){var i;this.props[e]=t,null!=(i=$n(e))&&i.volatile||this._markGroupDirty(e)}_deleteProp(e){delete this.props[e],this._markGroupDirty(e)}_markGroupDirty(e){var t,i=null==(t=$n(e))?void 0:t.storageGroup;i&&(this._slotWriteState(i).dirty=!0)}_slotWriteState(e){return this._slotState[e]||(this._slotState[e]={})}}function co(e){var t=!0;return{dispose(){if(t){t=!1;var i=e();i&&pt(i.then)&&i.then(void 0,(()=>{}))}}}}var ho="gzip-js",_o="base64",po="events",go="cancelEvents",vo="survey shown",fo="survey dismissed",mo="survey sent",yo="popover",bo=Gs("[RateLimiter]");class wo{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=e=>{var t=e.text;if(t&&t.length)try{(JSON.parse(t).quota_limited||[]).forEach((e=>{bo.info((e||"events")+" is quota limited."),this.serverLimits[e]=(new Date).getTime()+6e4}))}catch(e){return void bo.warn('could not rate limit - continuing. Error: "'+(null==e?void 0:e.message)+'"',{text:t})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return(null==(e=this.instance.config.rate_limiting)?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max((null==(e=this.instance.config.rate_limiting)?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var t,i,s;void 0===e&&(e=!1);var r=this.captureEventsBurstLimit,n=this.captureEventsPerSecond,o=(new Date).getTime(),a=null!==(t=null==(i=this.instance.persistence)?void 0:i.get_property(X))&&void 0!==t?t:{tokens:r,last:o};a.tokens+=(o-a.last)/1e3*n,a.last=o,a.tokens>r&&(a.tokens=r);var l=1>a.tokens;if(l||e||(a.tokens=Math.max(0,a.tokens-1)),l&&!e){var u=(St(a.dropped)?a.dropped:0)+1;a.dropped=u,!this.lastEventRateLimited&&this._captureWarning(u)&&(a.dropped=0)}return this.lastEventRateLimited=l,null==(s=this.instance.persistence)||s.set_property(X,a),{isRateLimited:l,remainingTokens:a.tokens}}_isPropertyAllowed(e){var t=this.instance.config.property_denylist;return!_t(t)||!t.includes(e)}_triggeringPage(){var e;if(this._isPropertyAllowed("$current_url")&&this._isPropertyAllowed("$pathname")&&null!=ke&&ke.pathname)return""+(null!==(e=ke.origin)&&void 0!==e?e:"")+ke.pathname}_captureWarning(e){var t,i,s=this.captureEventsBurstLimit,r=this.captureEventsPerSecond,n=this._triggeringPage(),o=this._isPropertyAllowed("$session_id")?null==(t=(i=this.instance).get_session_id)?void 0:t.call(i):void 0,a=[e+" event(s) dropped since the last warning",n?"triggered on "+n:void 0,o?"session "+o:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+a+". Config is set to "+r+" events per second and "+s+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var t=this.serverLimits[e||"events"]||!1;return!1!==t&&(new Date).getTime()<t}}var So=Gs("[RemoteConfig]");class xo{constructor(e){this._instance=e}get remoteConfig(){var e;return null==(e=Le._POSTHOG_REMOTE_CONFIG)||null==(e=e[this._instance.config.token])?void 0:e.config}_loadRemoteConfigJs(e){var t,i;null!=(t=Le.__PosthogExtensions__)&&t.loadExternalDependency?null==(i=Le.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,"remote-config",(()=>e(this.remoteConfig))):e()}_loadRemoteConfigJSON(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return So.info("Using preloaded remote config",this.remoteConfig),this._onRemoteConfig(this.remoteConfig),void this._startRefreshInterval();if(this._instance._shouldDisableFlags())return void So.warn("Remote config is disabled. Falling back to local config.");this._loadRemoteConfigJs((e=>{if(!e)return So.info("No config found after loading remote JS config. Falling back to JSON."),void this._loadRemoteConfigJSON((e=>{this._onRemoteConfig(e.json,e),this._startRefreshInterval()}));this._onRemoteConfig(e),this._startRefreshInterval()}))}catch(e){So.error("Error loading remote config",e),this._onRemoteConfig()}}stop(){this._refreshInterval&&(clearInterval(this._refreshInterval),this._refreshInterval=void 0)}refresh(){!this._instance._shouldDisableFlags()&&Ee&&"hidden"!==Ee.visibilityState&&this._instance.reloadFeatureFlags()}_startRefreshInterval(){var e;if(!this._refreshInterval){var t=null!==(e=this._instance.config.remote_config_refresh_interval_ms)&&void 0!==e?e:3e5;0!==t&&(this._refreshInterval=setInterval((()=>{this.refresh()}),t))}}_onRemoteConfig(e,t){!e&&t&&(0===t.statusCode?t.error||So.warn("Failed to fetch remote config from PostHog."):So.error("Failed to fetch remote config from PostHog."));try{this._instance._onRemoteConfig(e?{ok:!0,config:e}:{ok:!1})}catch(e){So.error("Error applying remote config",e)}if(!1!==(null==e?void 0:e.hasFeatureFlags)&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;null==(i=this._instance.featureFlags)||i.ensureFlagsLoaded()}catch(e){So.error("Error loading feature flags",e)}}}var Eo=Uint8Array,ko=Uint16Array,Po=Uint32Array,Co=new Eo([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Io=new Eo([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Fo=new Eo([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),To=function(e,t){for(var i=new ko(31),s=0;31>s;++s)i[s]=t+=1<<e[s-1];var r=new Po(i[30]);for(s=1;30>s;++s)for(var n=i[s];i[s+1]>n;++n)r[n]=n-i[s]<<5|s;return[i,r]},Ro=To(Co,2),Ao=Ro[1];Ro[0][28]=258,Ao[258]=28;for(var Lo=To(Io,0)[1],Mo=new ko(32768),$o=0;32768>$o;++$o){var Oo=(43690&$o)>>>1|(21845&$o)<<1;Mo[$o]=((65280&(Oo=(61680&(Oo=(52428&Oo)>>>2|(13107&Oo)<<2))>>>4|(3855&Oo)<<4))>>>8|(255&Oo)<<8)>>>1}var Do=function(e,t,i){for(var s=e.length,r=0,n=new ko(t);s>r;++r)++n[e[r]-1];var o,a=new ko(t);for(r=0;t>r;++r)a[r]=a[r-1]+n[r-1]<<1;if(i){o=new ko(1<<t);var l=15-t;for(r=0;s>r;++r)if(e[r])for(var u=r<<4|e[r],c=t-e[r],d=a[e[r]-1]++<<c,h=d|(1<<c)-1;h>=d;++d)o[Mo[d]>>>l]=u}else for(o=new ko(s),r=0;s>r;++r)o[r]=Mo[a[e[r]-1]++]>>>15-e[r];return o},Bo=new Eo(288);for($o=0;144>$o;++$o)Bo[$o]=8;for($o=144;256>$o;++$o)Bo[$o]=9;for($o=256;280>$o;++$o)Bo[$o]=7;for($o=280;288>$o;++$o)Bo[$o]=8;var qo=new Eo(32);for($o=0;32>$o;++$o)qo[$o]=5;var Ho=Do(Bo,9,0),No=Do(qo,5,0),zo=function(e){return(e/8>>0)+(7&e&&1)},jo=function(e,t,i){(null==i||i>e.length)&&(i=e.length);var s=new(e instanceof ko?ko:e instanceof Po?Po:Eo)(i-t);return s.set(e.subarray(t,i)),s},Uo=function(e,t,i){var s=t/8>>0;e[s]|=i<<=7&t,e[s+1]|=i>>>8},Vo=function(e,t,i){var s=t/8>>0;e[s]|=i<<=7&t,e[s+1]|=i>>>8,e[s+2]|=i>>>16},Wo=function(e,t){for(var i=[],s=0;e.length>s;++s)e[s]&&i.push({s:s,f:e[s]});var r=i.length,n=i.slice();if(!r)return[new Eo(0),0];if(1==r){var o=new Eo(i[0].s+1);return o[i[0].s]=1,[o,1]}i.sort((function(e,t){return e.f-t.f})),i.push({s:-1,f:25001});var a=i[0],l=i[1],u=0,c=1,d=2;for(i[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=i[i[d].f>i[u].f?u++:d++],l=i[u!=c&&i[d].f>i[u].f?u++:d++],i[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=n[0].s;for(s=1;r>s;++s)n[s].s>h&&(h=n[s].s);var _=new ko(h+1),p=Go(i[c-1],_,0);if(p>t){s=0;var g=0,v=p-t,f=1<<v;for(n.sort((function(e,t){return _[t.s]-_[e.s]||e.f-t.f}));r>s;++s){var m=n[s].s;if(t>=_[m])break;g+=f-(1<<p-_[m]),_[m]=t}for(g>>>=v;g>0;){var y=n[s].s;t>_[y]?g-=1<<t-_[y]++-1:++s}for(;s>=0&&g;--s){var b=n[s].s;_[b]==t&&(--_[b],++g)}p=t}return[new Eo(_),p]},Go=function(e,t,i){return-1==e.s?Math.max(Go(e.l,t,i+1),Go(e.r,t,i+1)):t[e.s]=i},Ko=function(e){for(var t=e.length;t&&!e[--t];);for(var i=new ko(++t),s=0,r=e[0],n=1,o=function(e){i[s++]=e},a=1;t>=a;++a)if(e[a]==r&&a!=t)++n;else{if(!r&&n>2){for(;n>138;n-=138)o(32754);n>2&&(o(n>10?n-11<<5|28690:n-3<<5|12305),n=0)}else if(n>3){for(o(r),--n;n>6;n-=6)o(8304);n>2&&(o(n-3<<5|8208),n=0)}for(;n--;)o(r);n=1,r=e[a]}return[i.subarray(0,s),t]},Qo=function(e,t){for(var i=0,s=0;t.length>s;++s)i+=e[s]*t[s];return i},Jo=function(e,t,i){var s=i.length,r=zo(t+2);e[r]=255&s,e[r+1]=s>>>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var n=0;s>n;++n)e[r+n+4]=i[n];return 8*(r+4+s)},Yo=function(e,t,i,s,r,n,o,a,l,u,c){Uo(t,c++,i),++r[256];for(var d=Wo(r,15),h=d[0],_=d[1],p=Wo(n,15),g=p[0],v=p[1],f=Ko(h),m=f[0],y=f[1],b=Ko(g),w=b[0],S=b[1],x=new ko(19),E=0;m.length>E;++E)x[31&m[E]]++;for(E=0;w.length>E;++E)x[31&w[E]]++;for(var k=Wo(x,7),P=k[0],C=k[1],I=19;I>4&&!P[Fo[I-1]];--I);var F,T,R,A,L=u+5<<3,M=Qo(r,Bo)+Qo(n,qo)+o,O=Qo(r,h)+Qo(n,g)+o+14+3*I+Qo(x,P)+(2*x[16]+3*x[17]+7*x[18]);if(M>=L&&O>=L)return Jo(t,c,e.subarray(l,l+u));if(Uo(t,c,1+(M>O)),c+=2,M>O){F=Do(h,_,0),T=h,R=Do(g,v,0),A=g;var D=Do(P,C,0);for(Uo(t,c,y-257),Uo(t,c+5,S-1),Uo(t,c+10,I-4),c+=14,E=0;I>E;++E)Uo(t,c+3*E,P[Fo[E]]);c+=3*I;for(var B=[m,w],q=0;2>q;++q){var H=B[q];for(E=0;H.length>E;++E)Uo(t,c,D[N=31&H[E]]),c+=P[N],N>15&&(Uo(t,c,H[E]>>>5&127),c+=H[E]>>>12)}}else F=Ho,T=Bo,R=No,A=qo;for(E=0;a>E;++E)if(s[E]>255){var N;Vo(t,c,F[257+(N=s[E]>>>18&31)]),c+=T[N+257],N>7&&(Uo(t,c,s[E]>>>23&31),c+=Co[N]);var z=31&s[E];Vo(t,c,R[z]),c+=A[z],z>3&&(Vo(t,c,s[E]>>>5&8191),c+=Io[z])}else Vo(t,c,F[s[E]]),c+=T[s[E]];return Vo(t,c,F[256]),c+T[256]},Zo=new Po([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Xo=function(){for(var e=new Po(256),t=0;256>t;++t){for(var i=t,s=9;--s;)i=(1&i&&3988292384)^i>>>1;e[t]=i}return e}(),ea=function(e,t,i){for(;i;++t)e[t]=i,i>>>=8};function ta(e,t){void 0===t&&(t={});var i=function(){var e=4294967295;return{p(t){for(var i=e,s=0;t.length>s;++s)i=Xo[255&i^t[s]]^i>>>8;e=i},d(){return 4294967295^e}}}(),s=e.length;i.p(e);var r,n,o,a,l,u=(a=10+((r=t).filename&&r.filename.length+1||0),l=8,function(e,t,i,s,r,n){var o=e.length,a=new Eo(s+o+5*(1+Math.floor(o/7e3))+r),l=a.subarray(s,a.length-r),u=0;if(!t||8>o)for(var c=0;o>=c;c+=65535){var d=c+65535;o>d?u=Jo(l,u,e.subarray(c,d)):(l[c]=!0,u=Jo(l,u,e.subarray(c,o)))}else{for(var h=Zo[t-1],_=h>>>13,p=8191&h,g=(1<<i)-1,v=new ko(32768),f=new ko(g+1),m=Math.ceil(i/3),y=2*m,b=function(t){return(e[t]^e[t+1]<<m^e[t+2]<<y)&g},w=new Po(25e3),S=new ko(288),x=new ko(32),E=0,k=0,P=(c=0,0),C=0,I=0;o>c;++c){var F=b(c),T=32767&c,R=f[F];if(v[T]=R,f[F]=T,c>=C){var A=o-c;if((E>7e3||P>24576)&&A>423){u=Yo(e,l,0,w,S,x,k,P,I,c-I,u),P=E=k=0,I=c;for(var L=0;286>L;++L)S[L]=0;for(L=0;30>L;++L)x[L]=0}var M=2,O=0,D=p,B=T-R&32767;if(A>2&&F==b(c-B))for(var q=Math.min(_,A)-1,H=Math.min(32767,c),N=Math.min(258,A);H>=B&&--D&&T!=R;){if(e[c+M]==e[c+M-B]){for(var z=0;N>z&&e[c+z]==e[c+z-B];++z);if(z>M){if(M=z,O=B,z>q)break;var j=Math.min(B,z-2),U=0;for(L=0;j>L;++L){var V=c-B+L+32768&32767,W=V-v[V]+32768&32767;W>U&&(U=W,R=V)}}}B+=(T=R)-(R=v[T])+32768&32767}if(O){w[P++]=268435456|Ao[M]<<18|Lo[O];var G=31&Ao[M],K=31&Lo[O];k+=Co[G]+Io[K],++S[257+G],++x[K],C=c+M,++E}else w[P++]=e[c],++S[e[c]]}}u=Yo(e,l,!0,w,S,x,k,P,I,c-I,u)}return jo(a,0,s+zo(u)+r)}(n=e,null==(o=t).level?6:o.level,null==o.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(n.length)))):12+o.mem,a,l)),c=u.length;return function(e,t){var i=t.filename;if(e[0]=31,e[1]=139,e[2]=8,e[8]=2>t.level?4:9==t.level?2:0,e[9]=3,0!=t.mtime&&ea(e,4,Math.floor(new Date(t.mtime||Date.now())/1e3)),i){e[3]=8;for(var s=0;i.length>=s;++s)e[s+10]=i.charCodeAt(s)}}(u,t),ea(u,c-8,i.d()),ea(u,c-4,s),u}var ia=!!Ce||!!Pe,sa="text/plain",ra=!1,na=(e,t)=>{var i=e.split("#"),s=i[1],r=i[0].split("?"),n=r[0],o=r[1];if(!o)return e;var a=o.split("&").filter((e=>e.split("=")[0]!==t)).join("&");return n+(a?"?"+a:"")+(s?"#"+s:"")},oa=function(e,t,s){var r;void 0===s&&(s=!0);var n=e.split("?"),o=n[0],a=n[1],l=i({},t),u=null!==(r=null==a?void 0:a.split("&").map((e=>{var t,i=e.split("="),r=i[0],n=s&&null!==(t=l[r])&&void 0!==t?t:i[1];return delete l[r],r+"="+n})))&&void 0!==r?r:[],c=function(e,t){var i,s;void 0===t&&(t="&");var r=[];return Qs(e,(function(e,t){ft(e)||ft(t)||"undefined"===t||(i=encodeURIComponent((e=>e instanceof File)(e)?e.name:e.toString()),s=encodeURIComponent(t),r[r.length]=s+"="+i)})),r.join(t)}(l);return c&&u.push(c),u.length>0?o+"?"+u.join("&"):o},aa=e=>{if(e._encodedBody)return e._encodedBody;var t=e.data,i=e.compression;if(t){if(i===ho){var s=ta(function(e,t){var i=e.length;if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);for(var s=new Eo(e.length+(e.length>>>1)),r=0,n=function(e){s[r++]=e},o=0;i>o;++o){if(r+5>s.length){var a=new Eo(r+8+(i-o<<1));a.set(s),s=a}var l=e.charCodeAt(o);128>l?n(l):2048>l?(n(192|l>>>6),n(128|63&l)):l>55295&&57344>l?(n(240|(l=65536+(1047552&l)|1023&e.charCodeAt(++o))>>>18),n(128|l>>>12&63),n(128|l>>>6&63),n(128|63&l)):(n(224|l>>>12),n(128|l>>>6&63),n(128|63&l))}return jo(s,0,r)}(On(t)),{mtime:0});return{contentType:sa,body:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength),estimatedSize:s.byteLength}}if(i===_o){var r=function(e){return e?btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,((e,t)=>String.fromCharCode(parseInt(t,16))))):e}(On(t)),n=(e=>"data="+encodeURIComponent("string"==typeof e?e:On(e)))(r);return{contentType:"application/x-www-form-urlencoded",body:n,estimatedSize:new Blob([n]).size}}var o=On(t);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},la=e=>{var t,s,r=()=>"sendBeacon"===e.transport?{url:oa(e.url,{compression:_o}),encodedBody:aa(i({},e,{compression:_o,_encodedBody:void 0}))}:{url:na(e.url,"compression"),encodedBody:aa(i({},e,{compression:void 0,_encodedBody:void 0}))};try{t=aa(e)}catch(t){if(Ve(e.compression,Bn(e.url,"compression")))return Ws.error("Failed to gzip request body, sending uncompressed payload",t),r();throw t}return t&&Ve(e.compression,Bn(e.url,"compression"))&&!((s=t.body)instanceof ArrayBuffer?Ue(new Uint8Array(s)):ArrayBuffer.isView(s)&&Ue(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(ra=!0,r()):{url:e.url,encodedBody:t}},ua=e=>{try{return la(e)}catch(t){return Ws.error(t),void(null==e.callback||e.callback({statusCode:0,error:t}))}},ca=function(){var e=t((function*(e){var t=On(e.data),s=yield function(e,t,i){return Qe.apply(this,arguments)}(t,r.DEBUG,{rethrow:!0});if(!s)return e;var n=yield s.arrayBuffer();return i({},e,{_encodedBody:{contentType:sa,body:n,estimatedSize:n.byteLength}})}));return function(t){return e.apply(this,arguments)}}(),da=/Failed to fetch|NetworkError|Load failed/i,ha=e=>"TypeError"===(null==e?void 0:e.name)&&da.test((null==e?void 0:e.message)||""),_a=e=>{var t=ua(e);if(t){var s=t.url,r=t.encodedBody,n=null!=r?r:{},o=n.contentType,a=n.body,l=n.estimatedSize,u=new Headers;Qs(e.headers,(function(e,t){u.append(t,e)})),o&&u.append("Content-Type",o);var c=null,d=!1;if(Ie){var h=new Ie;c={signal:h.signal,timeout:setTimeout((()=>{var t,i;d=!0,h.abort((t=e.timeout,(i=new Error("PostHog request timed out"+(t?" after "+t+"ms":""))).name="AbortError",i))}),e.timeout)}}var _=t=>{d&&"AbortError"===(null==t?void 0:t.name)||ha(t)?Ws.warn(t):Ws.error(t),null==e.callback||e.callback({statusCode:0,error:t})};try{var p;Pe(s,i({method:(null==e?void 0:e.method)||"GET",headers:u,keepalive:"POST"===e.method&&!e._keepaliveDisabled&&52428.8>(l||0),body:a,signal:null==(p=c)?void 0:p.signal},e.fetchOptions)).then((t=>t.text().then((i=>{var s={statusCode:t.status,text:i};if(200===t.status)try{s.json=JSON.parse(i)}catch(e){Ws.error(e)}null==e.callback||e.callback(s)})))).catch(_).finally((()=>c?clearTimeout(c.timeout):null))}catch(e){c&&clearTimeout(c.timeout),_(e)}}},pa=e=>{try{var t,s=la(e),r=s.url,n=s.encodedBody,o=null!=n?n:{},a=o.body,l=o.estimatedSize;if(!a)return;var u=a instanceof Blob?a:new Blob([a],{type:o.contentType});if(xe.sendBeacon(r,u))return;var c=_t(e.data)?e.data:null==(t=e.data)?void 0:t.batch;if(_t(c)&&c.length>1&&(null!=l?l:0)>16384){var d=Math.ceil(c.length/2),h=t=>_t(e.data)?t:i({},e.data,{batch:t});return pa(i({},e,{data:h(c.slice(0,d))})),void pa(i({},e,{data:h(c.slice(d))}))}Ws.warn("Beacon of ~"+(null!=l?l:0)+" bytes was rejected by the browser, falling back to fetch"),_a(i({},e,{_keepaliveDisabled:!0}))}catch(e){Ws.warn("Beacon send failed",e)}},ga=(e,t,s,r)=>{var n="query"===r?"POST"===t?"sent_at":"_":void 0;return oa(s===ho?na(e,"compression"):e,i({},n?{[n]:Date.now().toString()}:{},s===ho?{}:{compression:s}))},va=[];Pe&&va.push({transport:"fetch",method:_a}),Ce&&va.push({transport:"XHR",method(e){var t=ua(e);if(t){var i=new Ce,s=t.encodedBody;i.open(e.method||"GET",t.url,!0);var r=null!=s?s:{},n=r.contentType,o=r.body;Qs(e.headers,(function(e,t){i.setRequestHeader(t,e)})),n&&i.setRequestHeader("Content-Type",n),e.timeout&&(i.timeout=e.timeout),i.onreadystatechange=()=>{if(4===i.readyState){var t={statusCode:i.status,text:i.responseText};if(200===i.status)try{t.json=JSON.parse(i.responseText)}catch(e){}null==e.callback||e.callback(t)}},i.send(o)}}}),null!=xe&&xe.sendBeacon&&va.push({transport:"sendBeacon",method:pa});var fa=3e3;class ma{constructor(e,t){this._isPaused=!0,this._queue=[],this._flushTimeoutMs=Ot((null==t?void 0:t.flush_interval_ms)||fa,250,5e3,Ws.createLogger("flush interval"),fa),this._sendRequest=e}enqueue(e){this._queue.push(e),this._flushTimeout||this._setFlushTimeout()}unload(){this._clearFlushTimeout();var e=this._queue.length>0?this._formatQueue():{},t=Object.values(e);[...t.filter((e=>0===e.url.indexOf("/e"))),...t.filter((e=>0!==e.url.indexOf("/e")))].map((e=>{this._sendRequestSafely(i({},e,{transport:"sendBeacon"}))}))}enable(){this._isPaused=!1,this._setFlushTimeout()}_setFlushTimeout(){var e=this;this._isPaused||(this._flushTimeout=setTimeout((()=>{if(this._clearFlushTimeout(),this._queue.length>0){var t=this._formatQueue(),i=function(){var i=t[s],r=(new Date).getTime();i.data&&_t(i.data)&&Qs(i.data,(e=>{e.offset=Math.abs(e.timestamp-r),delete e.timestamp})),e._sendRequestSafely(i)};for(var s in t)i()}}),this._flushTimeoutMs))}_sendRequestSafely(e){try{this._sendRequest(e)}catch(e){Ws.error(e)}}_clearFlushTimeout(){clearTimeout(this._flushTimeout),this._flushTimeout=void 0}_formatQueue(){var e={};return Qs(this._queue,(t=>{var s,r=t,n=(r?r.batchKey:null)||r.url;ft(e[n])&&(e[n]=i({},r,{data:[]})),null==(s=e[n].data)||s.push(r.data)})),this._queue=[],e}}var ya=["retriesPerformedSoFar"];class ba{constructor(e){this._isPolling=!1,this._pollIntervalMs=3e3,this._queue=[],this._instance=e,this._queue=[],this._areWeOnline=!0,!ft(we)&&"onLine"in we.navigator&&(this._areWeOnline=we.navigator.onLine,this._onlineListener=()=>{this._areWeOnline=!0,this._flush()},this._offlineListener=()=>{this._areWeOnline=!1},sr(we,"online",this._onlineListener),sr(we,"offline",this._offlineListener))}get length(){return this._queue.length}retriableRequest(e){var t=e.retriesPerformedSoFar,r=s(e,ya);xt(t)&&(r.url=oa(r.url,{retry_count:t})),this._instance._send_request(i({},r,{callback:e=>{if(200!==e.statusCode&&(400>e.statusCode||e.statusCode>=500)){if((0===e.statusCode?3:10)>(null!=t?t:0))return void this._enqueue(i({retriesPerformedSoFar:t},r));0===e.statusCode&&Ws.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(null!=t?t:0)+" retries.")}null==r.callback||r.callback(e)}}))}_enqueue(e){var t=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=t+1;var i=function(e){var t=3e3*Math.pow(2,e),i=t/2,s=Math.min(18e5,t),r=Math.random()-.5;return Math.ceil(s+r*(s-i))}(t),s=Date.now()+i;this._queue.push({retryAt:s,requestOptions:e});var r="Enqueued failed request for retry in "+i;navigator.onLine||(r+=" (Browser is offline)"),Ws.warn(r),this._isPolling||(this._isPolling=!0,this._poll())}_poll(){if(this._poller&&clearTimeout(this._poller),0===this._queue.length)return this._isPolling=!1,void(this._poller=void 0);this._poller=setTimeout((()=>{this._areWeOnline&&this._queue.length>0&&this._flush(),this._poll()}),this._pollIntervalMs)}_flush(){var e=Date.now(),t=[],i=this._queue.filter((i=>e>i.retryAt||(t.push(i),!1)));if(this._queue=t,i.length>0)for(var s of i)this.retriableRequest(s.requestOptions)}unload(){for(var e of(this._poller&&(clearTimeout(this._poller),this._poller=void 0),this._isPolling=!1,ft(we)||(this._onlineListener&&(we.removeEventListener("online",this._onlineListener),this._onlineListener=void 0),this._offlineListener&&(we.removeEventListener("offline",this._offlineListener),this._offlineListener=void 0)),this._queue)){var t=e.requestOptions;try{this._instance._send_request(i({},t,{transport:"sendBeacon"}))}catch(e){Ws.error(e)}}this._queue=[]}}class wa{constructor(e){this._updateScrollData=()=>{var e,t,i,s;this._context||(this._context={});var r=this.scrollElement(),n=this.scrollY(),o=r?Math.max(0,r.scrollHeight-r.clientHeight):0,a=n+((null==r?void 0:r.clientHeight)||0),l=(null==r?void 0:r.scrollHeight)||0;this._context.lastScrollY=Math.ceil(n),this._context.maxScrollY=Math.max(n,null!==(e=this._context.maxScrollY)&&void 0!==e?e:0),this._context.maxScrollHeight=Math.max(o,null!==(t=this._context.maxScrollHeight)&&void 0!==t?t:0),this._context.lastContentY=a,this._context.maxContentY=Math.max(a,null!==(i=this._context.maxContentY)&&void 0!==i?i:0),this._context.maxContentHeight=Math.max(l,null!==(s=this._context.maxContentHeight)&&void 0!==s?s:0)},this._instance=e}get _scrollRoot(){return this._instance.config.scroll_root_selector}getContext(){return this._context}resetContext(){var e=this._context;return setTimeout(this._updateScrollData,0),e}startMeasuringScrollPosition(){sr(we,"scroll",this._updateScrollData,{capture:!0}),sr(we,"scrollend",this._updateScrollData,{capture:!0}),sr(we,"resize",this._updateScrollData)}scrollElement(){if(!this._scrollRoot)return null==we?void 0:we.document.documentElement;var e=_t(this._scrollRoot)?this._scrollRoot:[this._scrollRoot];for(var t of e){var i=null==we?void 0:we.document.querySelector(t);if(i)return i}}_scrollPosition(e){var t="y"===e?"scrollTop":"scrollLeft";if(this._scrollRoot){var i=this.scrollElement();return i&&i[t]||0}return we?"y"===e?we.scrollY||we.pageYOffset||we.document.documentElement.scrollTop||0:we.scrollX||we.pageXOffset||we.document.documentElement.scrollLeft||0:0}scrollY(){return this._scrollPosition("y")}scrollX(){return this._scrollPosition("x")}}var Sa=e=>eo(null==e?void 0:e.config.mask_personal_data_properties,null==e?void 0:e.config.custom_personal_data_properties,null==e?void 0:e.config.disable_capture_url_hashes);class xa{constructor(e,t,i,s){this._onSessionIdCallback=e=>{var t=this._getStored();if(!t||t.sessionId!==e){var i={sessionId:e,props:this._sessionSourceParamGenerator(this._instance)};this._persistence.register({[Z]:i})}},this._instance=e,this._sessionIdManager=t,this._persistence=i,this._sessionSourceParamGenerator=s||Sa,this._sessionIdManager.onSessionId(this._onSessionIdCallback)}_getStored(){return this._persistence.props[Z]}getSetOnceProps(){var e,t=null==(e=this._getStored())?void 0:e.props;return t?"r"in t?to(t,this._instance.config.disable_capture_url_hashes):{$referring_domain:t.referringDomain,$pathname:t.initialPathName,utm_source:t.utm_source,utm_campaign:t.utm_campaign,utm_medium:t.utm_medium,utm_content:t.utm_content,utm_term:t.utm_term}:{}}getSessionProps(){var e={};return Qs(er(this.getSetOnceProps()),((t,i)=>{"$current_url"===i&&(i="url"),e["$session_entry_"+lt(i)]=t})),e}}class Ea{on(e,t){return this._events[e]||(this._events[e]=[]),this._events[e].push(t),()=>{this._events[e]=this._events[e].filter((e=>e!==t))}}emit(e,t){for(var i of this._events[e]||[])i(t);for(var s of this._events["*"]||[])s(e,t)}constructor(){this._events={}}}var ka=Gs("[SessionId]"),Pa=864e5;class Ca{on(e,t){return this._eventEmitter.on(e,t)}constructor(e,t,i){var s;if(this._lastPersistedActivityTimestamp=null,this._lastCookieSyncTimestamp=null,this._sessionIdChangedHandlers=[],this._beforeUnloadListener=void 0,this._destroyed=!1,this._eventEmitter=new Ea,this._sessionHasBeenIdleTooLong=(e,t)=>!(!xt(e)||!xt(t))&&Math.abs(e-t)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===de)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this._config=e.config,this._persistence=e.persistence,this._windowId=void 0,this._sessionId=void 0,this._sessionStartTimestamp=null,this._pendingBootstrapSession=void 0,this._sessionActivityTimestamp=null,this._sessionIdGenerator=t||dr,this._windowIdGenerator=i||dr;var r=this._config.persistence_name||this._config.token;if(this._sessionTimeoutMs=1e3*Ot(this._config.session_idle_timeout_seconds||1800,60,36e3,ka.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this._resetIdleTimer(),this._window_id_storage_key="ph_"+r+"_window_id",this._primary_window_exists_storage_key="ph_"+r+"_primary_window_exists",this._canUseSessionStorage()){var n=Rr._parse(this._window_id_storage_key),o=Rr._parse(this._primary_window_exists_storage_key);n&&!o?this._windowId=n:Rr._remove(this._window_id_storage_key),Rr._set(this._primary_window_exists_storage_key,!0)}null!=(s=this._config.bootstrap)&&s.sessionID&&this.setBootstrapSessionId(this._config.bootstrap.sessionID),this._listenToReloadWindow()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return ft(this._sessionIdChangedHandlers)&&(this._sessionIdChangedHandlers=[]),this._sessionIdChangedHandlers.push(e),this._sessionId&&e(this._sessionId,this._windowId),()=>{this._sessionIdChangedHandlers=this._sessionIdChangedHandlers.filter((t=>t!==e))}}_canUseSessionStorage(){return"memory"!==this._config.persistence&&!this._persistence._disabled&&Rr._is_supported()}_setWindowId(e){e!==this._windowId&&(this._windowId=e,this._canUseSessionStorage()&&Rr._set(this._window_id_storage_key,e))}_getWindowId(){return this._windowId?this._windowId:this._canUseSessionStorage()?Rr._parse(this._window_id_storage_key):null}_isActivityChangeBelowGranularity(e){var t=this._lastPersistedActivityTimestamp;return!bt(t)&&!bt(e)&&5e3>Math.abs(e-t)}_setSessionId(e,t,i){var s=t!==this._sessionActivityTimestamp,r=!(e!==this._sessionId||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=t,this._sessionId=e,r&&!s||r&&this._isActivityChangeBelowGranularity(t)||(this._lastPersistedActivityTimestamp=t,this._persistence.register({[P]:[t,e,i]}))}_useCrossTabRefreshHardening(){var e,t=null==(e=this._config)?void 0:e.persistence_save_debounce_ms;return xt(t)&&t>0}_refreshSessionIdFromStorage(){this._useCrossTabRefreshHardening()?this._persistence.refreshKey(P):(this._persistence.flush(),this._persistence.load())}_flushPendingActivityTimestamp(){var e;if(!bt(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this._lastPersistedActivityTimestamp){this._refreshSessionIdFromStorage();var t=this._getSessionId();t[1]===this._sessionId&&t[2]===this._sessionStartTimestamp&&(this._lastPersistedActivityTimestamp=this._sessionActivityTimestamp,this._persistence.register({[P]:[this._sessionActivityTimestamp,null!==(e=this._sessionId)&&void 0!==e?e:null,this._sessionStartTimestamp]}),this._persistence.flush())}}_freshestActivityTimestamp(){var e=this._getSessionId()[0],t=xt(e)?e:0,i=xt(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(t,i)}_isSessionIdleAfterCrossTabRefresh(e){return this._refreshSessionIdFromStorage(),this._sessionHasBeenIdleTooLong(e,this._freshestActivityTimestamp())}_getSessionId(){var e=this._persistence.props[P];return _t(e)&&2===e.length&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this._lastPersistedActivityTimestamp=null,this._pendingBootstrapSession=void 0,clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=void 0,this._setSessionId(null,null,null)}setBootstrapSessionId(e,t){void 0===t&&(t=!1);var i=function(e,t){void 0===t&&(t=(new Date).getTime());try{var i=(e=>{var t=e.replace(/-/g,"");if(32!==t.length)throw new Error("Not a valid UUID");if("7"!==t[12])throw new Error("Not a UUIDv7");return parseInt(t.substring(0,12),16)})(e);return i>t+6e4?void ka.error("Bootstrap sessionID cannot be in the future"):i}catch(e){return void ka.error("Invalid sessionID in bootstrap",e)}}(e);return!ft(i)&&(t?this._pendingBootstrapSession={sessionId:e,sessionStartTimestamp:i}:this._setSessionId(e,(new Date).getTime(),i),!0)}destroy(){this._destroyed=!0,this._flushPendingActivityTimestamp(),clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=void 0,this._beforeUnloadListener&&we&&(we.removeEventListener(ve,this._beforeUnloadListener,{capture:!1}),this._beforeUnloadListener=void 0),this._sessionIdChangedHandlers=[]}_listenToReloadWindow(){this._beforeUnloadListener=()=>{this._flushPendingActivityTimestamp(),this._canUseSessionStorage()&&Rr._remove(this._primary_window_exists_storage_key)},sr(we,ve,this._beforeUnloadListener,{capture:!1})}checkAndGetSessionAndWindowId(e,t,i){if(void 0===e&&(e=!1),void 0===t&&(t=null),void 0===i&&(i=!1),this._config.cookieless_mode===de)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var s=t||(new Date).getTime(),r=this._sessionId;if(i)this._lastCookieSyncTimestamp=s;else if(bt(this._lastCookieSyncTimestamp)||this._lastCookieSyncTimestamp>s||s-this._lastCookieSyncTimestamp>=1e3){var n,o;null==(n=(o=this._persistence).syncCookieProperties)||n.call(o),this._lastCookieSyncTimestamp=s}var a=this._getSessionId(),l=a[1],u=a[2],c=!ft(r)&&l!==r,d=this._freshestActivityTimestamp(),h=this._getWindowId(),_=this._pendingBootstrapSession,p=!!_&&(_.sessionStartTimestamp>s+6e4||s-_.sessionStartTimestamp>Pa),g=_?p:xt(u)&&Math.abs(s-u)>Pa,v=!1,f=c,m=!l||!!_,y=l,b=!m&&!e&&this._sessionHasBeenIdleTooLong(s,d);if(b){(b=this._isSessionIdleAfterCrossTabRefresh(s))||ka.info("cross-tab refresh kept the session alive",{sessionId:l});var w=this._getSessionId();l=w[1],u=w[2]}if(m||b||g){f=!1;var S=_&&!p;l=S?_.sessionId:this._sessionIdGenerator(),h=this._windowIdGenerator(),ka.info("new session ID assigned",{sessionId:l,windowId:h,bootstrapped:!!S,changeReason:{noSessionId:m,activityTimeout:b,sessionPastMaximumLength:g}}),u=S?_.sessionStartTimestamp:s,this._pendingBootstrapSession=void 0,v=!0}else h||(h=this._windowIdGenerator(),v=!0),(f=f||l!==y)&&(ka.info("adopted cross-tab session id",{sessionId:l,windowId:h}),v=!0);var x=xt(d)&&e&&!g?d:s,E=xt(u)?u:(new Date).getTime();this._setWindowId(h),this._setSessionId(l,x,E),e||this._resetIdleTimer();var k={noSessionId:m,activityTimeout:b,sessionPastMaximumLength:g,crossTabAdoption:f};return v&&this._sessionIdChangedHandlers.forEach((e=>e(l,h,k))),{sessionId:l,windowId:h,sessionStartTimestamp:E,changeReason:v?k:void 0,lastActivityTimestamp:d}}_resetIdleTimer(){this._destroyed||(clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=setTimeout((()=>{if(!this._destroyed)if(this._isSessionIdleAfterCrossTabRefresh((new Date).getTime())){var e=this._sessionId;this.resetSessionId(),this._eventEmitter.emit("forcedIdleReset",{idleSessionId:e})}else this._resetIdleTimer()}),1.1*this.sessionTimeoutMs))}}var Ia=function(e,t){if(!e)return!1;var i=e.userAgent;if(i&&nt(i,t))return!0;try{var s=null==e?void 0:e.userAgentData;if(null!=s&&s.brands&&s.brands.some((e=>nt(null==e?void 0:e.brand,t))))return!0}catch(e){}return!!e.webdriver};function Fa(){return(Fa=t((function*(){var e=null==xe?void 0:xe.userAgentData;if(null!=e&&e.getHighEntropyValues)try{var t=yield e.getHighEntropyValues(["model"]),i=null==t?void 0:t.model;return mt(i)&&i.length>0?i:void 0}catch(e){return void Ws.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",e)}}))).apply(this,arguments)}function Ta(e){var t;return!(null==(t=e.conditions)||null==(t=t.events)||null==(t=t.values)||!t.length)}var Ra=(e,t)=>{if(!(e=>{try{new RegExp(e)}catch(e){return!1}return!0})(t))return!1;try{return new RegExp(t).test(e)}catch(e){return!1}},Aa=e=>e.toLowerCase(),La={exact:(e,t)=>t.some((t=>e.some((e=>t===e)))),is_not:(e,t)=>t.every((t=>e.every((e=>t!==e)))),regex:(e,t)=>t.some((t=>e.some((e=>Ra(t,e))))),not_regex:(e,t)=>t.every((t=>e.every((e=>!Ra(t,e))))),icontains:(e,t)=>t.map(Aa).some((t=>e.map(Aa).some((e=>t.includes(e))))),not_icontains:(e,t)=>t.map(Aa).every((t=>e.map(Aa).every((e=>!t.includes(e))))),gt:(e,t)=>t.some((t=>{var i=parseFloat(t);return!isNaN(i)&&e.some((e=>i>parseFloat(e)))})),lt:(e,t)=>t.some((t=>{var i=parseFloat(t);return!isNaN(i)&&e.some((e=>i<parseFloat(e)))}))};function Ma(e,t){return!e||Object.entries(e).every((e=>{var i=e[1],s=null==t?void 0:t[e[0]];if(null==s)return!1;var r=La[i.operator];return!!r&&r(i.values,[String(s)])}))}function $a(e,t,i){return On({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:i})}var Oa="custom",Da="i.posthog.com",Ba=/^\/static\//,qa=["/s/","/e/","/i/"];class Ha{constructor(e){this._regionCache={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return"https://app.posthog.com"===e?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,t=null==(e=this.instance.config.ui_host)?void 0:e.replace(/\/$/,"");return t||(t=this.apiHost.replace("."+Da,".posthog.com")),"https://app.posthog.com"===t?"https://us.posthog.com":t}get region(){return this._regionCache[this.apiHost]||(this._regionCache[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":Oa),this._regionCache[this.apiHost]}_staticAssetHostOverride(e){if(Ba.test(e)){var t=this.instance.config.asset_host;if("string"==typeof t)return t.trim().replace(/\/$/,"")||void 0}}_urlKey(e){var t=Dn(e);return t?t.protocol+"//"+t.host+t.pathname:void 0}_prepareEndpoint(e,t,i){if("ui"===e)return i;var s=i,r=this.instance.config.rewriteRequestPath;if(r){var n,o=(null==(n=Dn(i))?void 0:n.href)||i;s=r(new URL(o)).toString()}if(r&&"api"===e&&qa.some((e=>0===t.indexOf(e)))){var a=this._urlKey(s);if(a){var l,u=this.apiHost,c=this._ingestionEndpoints;(null==(l=c)?void 0:l.apiHost)===u&&c.rewriteRequestPath===r||(c={apiHost:u,rewriteRequestPath:r,urls:new Set},this._ingestionEndpoints=c),c.urls.add(a)}}return s}isIngestionEndpoint(e){var t=this._ingestionEndpoints,i=this._urlKey(e);return(null==t?void 0:t.apiHost)===this.apiHost&&t.rewriteRequestPath===this.instance.config.rewriteRequestPath&&!!i&&t.urls.has(i)}endpointFor(e,t){if(void 0===t&&(t=""),t&&(t="/"===t[0]?t:"/"+t),"ui"===e)return this._prepareEndpoint(e,t,this.uiHost+t);if("flags"===e)return this._prepareEndpoint(e,t,this.flagsApiHost+t);if("assets"===e){var i=this._staticAssetHostOverride(t);if(i)return this._prepareEndpoint(e,t,""+i+t)}if(this.region===Oa)return this._prepareEndpoint(e,t,this.apiHost+t);var s=Da+t;switch(e){case"assets":return this._prepareEndpoint(e,t,"https://"+this.region+"-assets."+s);case"api":return this._prepareEndpoint(e,t,"https://"+this.region+"."+s)}}}var Na=Gs("[Surveys]"),za="seenSurvey_",ja=e=>{try{var t=(e=>((e,t)=>""+e+function(e){return e.current_iteration&&e.current_iteration>0?e.id+"_"+e.current_iteration:e.id}(t))(za,e))(e);if(localStorage.getItem(t))return;localStorage.setItem(t,"true")}catch(e){Na.error("Failed to persist survey seen state",e)}},Ua=["popover","widget","api"],Va={ignoreConditions:!1,ignoreDelay:!1,displayType:yo},Wa=Gs("[PostHog ExternalIntegrations]"),Ga={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Ka{constructor(e){this._instance=e}_loadScript(e,t){var i;null==(i=Le.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,e,(e=>{if(e)return Wa.error("failed to load script",e);t()}))}startIfEnabledOrStop(){var e=this,t=function(){var t,s,r,n=i[0],o=i[1];!o||null!=(t=Le.__PosthogExtensions__)&&null!=(t=t.integrations)&&t[n]||e._loadScript(Ga[n],(()=>{var t;null==(t=Le.__PosthogExtensions__)||null==(t=t.integrations)||null==(t=t[n])||t.start(e._instance)})),!o&&null!=(s=Le.__PosthogExtensions__)&&null!=(s=s.integrations)&&s[n]&&(null==(r=Le.__PosthogExtensions__)||null==(r=r.integrations)||null==(r=r[n])||r.stop())};for(var i of Object.entries(null!==(s=this._instance.config.integrations)&&void 0!==s?s:{})){var s;t()}}}class Qa{constructor(e,t){this._logger=e,this._client=t,this._extensions=new Map,this._disposed=!1}add(e){var i=this;return t((function*(){if(i._disposed)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(i._extensions.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');i._extensions.set(e.name,e);try{var t=e.setup(i._client);t&&(yield t)}catch(t){var s=i._extensions.get(e.name)===e;s&&i._extensions.delete(e.name),i._logger.error('Failed to set up browser extension "'+e.name+'"',t),s&&i._disposeExtension(e)}}))()}dispose(){if(!this._disposed){this._disposed=!0;var e=Array.from(this._extensions.values()).reverse();for(var t of(this._extensions.clear(),e))this._disposeExtension(t)}}_disposeExtension(e){try{var t=null==e.dispose?void 0:e.dispose();t&&pt(t.then)&&t.then(void 0,(t=>{this._logger.error('Failed to dispose browser extension "'+e.name+'"',t)}))}catch(t){this._logger.error('Failed to dispose browser extension "'+e.name+'"',t)}}}class Ja{constructor(e){this._instance=e}initialize(){}get(e){var t=this._instance.persistence;if("string"==typeof e)return null==t?void 0:t.get_property(e);var i={};for(var s of e){var r=null==t?void 0:t.get_property(s);ft(r)||(i[s]=r)}return i}set(e,t){var i;null==(i=this._instance.persistence)||i.register("string"==typeof e?{[e]:t}:e)}remove(e){var t;null==(t=this._instance.persistence)||t.unregister(e)}}var Ya="extensionsRemoteConfig";class Za{constructor(e){this._disposed=!1,this.instance=e,this._logger=Ws,this._latestRemoteConfigResult=e._lastRemoteConfig,this.kv=new Ja(e),this.onEvent=e=>co(this.instance.on("eventCaptured",(t=>{try{e({event:t.event,properties:t.properties})}catch(e){this._logger.error("Browser extension event listener failed",e)}}))),this.onRemoteConfig=e=>{if(this._disposed)return co((()=>{}));var t=t=>{try{e(t)}catch(e){this._logger.error("Browser extension remote config listener failed",e)}},i=this.instance._internalEventEmitter.on(Ya,t);return this._latestRemoteConfigResult&&t(this._latestRemoteConfigResult),co(i)},this._runtime=new Qa(Ws.createLogger("[BrowserExtensions]"),this)}get logger(){return this._logger}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return null!==(e=this.instance.get_property(a))&&void 0!==e?e:this.distinctId}get deviceId(){var e=this.instance.get_property(a);return"string"==typeof e?e:void 0}get library(){return{name:r.LIB_NAME,version:r.LIB_VERSION}}get initialPersonProperties(){var e,t;return null!==(e=null==(t=this.instance.persistence)?void 0:t.get_initial_props())&&void 0!==e?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,t,i,s,r=null==(e=this.instance.sessionManager)?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:null!==(t=null==r?void 0:r.sessionId)&&void 0!==t?t:"",windowId:null!==(i=null==r?void 0:r.windowId)&&void 0!==i?i:"",sessionStartTimestamp:null!==(s=null==r?void 0:r.sessionStartTimestamp)&&void 0!==s?s:0}}catch(e){return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this._runtime.add(e)}capture(e,i,s){var r=this;return t((function*(){s?r.instance.capture(e,i,{timestamp:s.timestamp,uuid:s.uuid,$set:s.set,$set_once:s.setOnce}):r.instance.capture(e,i)}))()}registerDynamicEventProperties(e){return co(this.instance._registerExtensionEventProperties(e))}handleRemoteConfig(e){this._disposed||(this._latestRemoteConfigResult=e,this.instance._internalEventEmitter.emit(Ya,e))}sendRequest(e,i){var s=this;return t((function*(){var t;void 0===i&&(i={});var r=s.instance.requestRouter.endpointFor(null!==(t=i.target)&&void 0!==t?t:"api",e),n={method:i.method,url:i.query?oa(r,i.query):r,data:i.body,headers:i.headers,timeout:i.timeoutMs,fireCallbackOnDrop:!0,transport:i.transport,compression:i.compression,timestampMode:i.sentAt};return"sendBeacon"===i.transport?(s.instance._send_request(n),{statusCode:202}):new Promise((e=>{n.callback=e,s.instance._send_request(n)}))}))()}dispose(){this._disposed||(this._disposed=!0,this._runtime.dispose())}}var Xa={},el=0,tl=()=>{},il='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',sl="Surveys module not available",rl="sanitize_properties is deprecated. Use before_send instead",nl="Invalid value for property_denylist config: ",ol=["token","distinct_id",ne],al="posthog",ll=!ia&&-1===(null==Te?void 0:Te.indexOf("MSIE"))&&-1===(null==Te?void 0:Te.indexOf("Mozilla")),ul=e=>{var t;return i({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:ir(null==Ee?void 0:Ee.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:tl,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:null!=e?e:"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:ke&&mt(null==ke?void 0:ke.search)&&-1!==ke.search.indexOf("__posthog_debug=true")||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:"fallback",enable_recording_console_log:void 0,secure_cookie:"https:"===(null==we||null==(t=we.location)?void 0:t.protocol),ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(e){Ws.error("Bad HTTP status: "+e.statusCode+" "+e.text)},get_device_id:e=>e,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:pe,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:fa},error_tracking:{},_onCapture:tl},(e=>({rageclick:e&&e>="2026-05-30"?{content_ignorelist:tn,ignore_text_selection:!0}:!e||"2025-11-30">e||{content_ignorelist:!0},capture_pageview:!e||"2025-05-24">e||"history_change",session_recording:e&&e>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:e&&e>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:e&&e>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:e&&e>="2026-01-30"?"head":"body",internal_or_test_user_hostname:e&&e>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:e&&e>="2026-05-30"?250:0,split_storage:!(!e||"2026-05-30">e),detect_google_search_app:!(!e||"2026-05-30">e),disable_capture_url_hashes:!(!e||"2026-06-25">e),cookieWinsOnConflict:!(!e||"unset"===e||"2026-08-29">e)}))(e))},cl=[["process_person","person_profiles"],["xhr_headers","request_headers"],["cookie_name","persistence_name"],["disable_cookie","disable_persistence"],["__preview_disable_beacon","disable_beacon"],["store_google","save_campaign_params"],["verbose","debug"],["__preview_cookie_wins_on_conflict","cookieWinsOnConflict"]],dl=e=>{var t={};for(var i of cl){var s=i[0],r=i[1];ft(e[s])||(t[r]=e[s])}var n=Js({},t,e),o=e.__preview_external_dependency_versioned_paths;return ft(o)||(ft(e.strict_script_versioning)&&(n.strict_script_versioning=!!o),mt(o)&&ft(e.asset_host)&&(n.asset_host=o)),_t(e.property_blacklist)&&(ft(e.property_denylist)?n.property_denylist=e.property_blacklist:_t(e.property_denylist)?n.property_denylist=[...e.property_blacklist,...e.property_denylist]:Ws.error(nl+e.property_denylist)),n};class hl{constructor(){this.__forceAllowLocalhost=!1}get _forceAllowLocalhost(){return this.__forceAllowLocalhost}set _forceAllowLocalhost(e){Ws.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class _l{_replaceExtension(e,t){if(e){var i=this._extensions.indexOf(e);-1!==i&&this._extensions.splice(i,1)}return this._extensions.push(t),null==t.initialize||t.initialize(),t}_inCookielessMode(){return this.config.cookieless_mode===de||this.config.cookieless_mode===ce&&this.consent.isRejected()}_healCookielessSentinelDistinctId(){if(!this._inCookielessMode()&&this.get_distinct_id()===re){var e=this.persistence;if(e){this._is_persistence_disabled()||e.load(!0);var t=this.get_distinct_id();if(!t||t===re){var i=this.config.get_device_id(dr());this.register({distinct_id:i,$device_id:i}),e.set_property(Y,he)}this._sync_opt_out_with_persistence()}}}get decideEndpointWasHit(){var e,t;return null!==(e=null==(t=this.featureFlags)?void 0:t.hasLoadedFlags)&&void 0!==e&&e}get flagsEndpointWasHit(){var e,t;return null!==(e=null==(t=this.featureFlags)?void 0:t.hasLoadedFlags)&&void 0!==e&&e}constructor(){var e;this.webPerformance=new hl,this._personProcessingSetOncePropertiesSent=!1,this.version=r.LIB_VERSION,this._sessionRegisteredPropKeys=new Set,this._sessionRegisteredPropertiesStorageKey="",this._internalEventEmitter=new Ea,this._extensions=[],this._extensionEventPropertyProducers=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=ul(),this.SentryIntegration=Tn,this.sentryIntegration=e=>function(e,t){var i=Fn(e,t);return{name:In,processEvent:e=>i(e)}}(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this._initialPageviewCaptured=!1,this._visibilityStateListener=null,this._initialPersonProfilesConfig=null,this._cachedPersonProperties=null,this.scrollManager=new wa(this),this.pageViewManager=new Rn(this),this.rateLimiter=new wo(this),this.requestRouter=new Ha(this),this.consent=new Ar(this),this.externalIntegrations=new Ka(this);var t=null!==(e=_l.__defaultExtensionClasses)&&void 0!==e?e:{};this.featureFlags=t.featureFlags&&new t.featureFlags(this),this.toolbar=t.toolbar&&new t.toolbar(this),this.surveys=t.surveys&&new t.surveys(this),this.conversations=t.conversations&&new t.conversations(this),this.logs=t.logs&&new t.logs(this),this.metrics=t.metrics&&new t.metrics(this),this.experiments=t.experiments&&new t.experiments(this),this.exceptions=t.exceptions&&new t.exceptions(this),this.people={set:(e,t,i)=>{var s=mt(e)?{[e]:t}:e;this.setPersonProperties(s),null==i||i({})},set_once:(e,t,i)=>{var s=mt(e)?{[e]:t}:e;this.setPersonProperties(void 0,s),null==i||i({})}},this.on("eventCaptured",(e=>Ws.info('send "'+(null==e?void 0:e.event)+'"',e)))}init(e,t,i){if(i&&i!==al){var s,r=null!==(s=Xa[i])&&void 0!==s?s:new _l;return r._init(e,t,i),Xa[i]=r,Xa[al][i]=r,r}return this._init(e,t,i)}_init(e,t,s){var n,o;void 0===t&&(t={});var a,u=mt(e)?e.trim():"";if(!u)return Ws.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return u!==(null==(a=this.config)?void 0:a.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+u+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=ul(t.defaults),t.debug=this._checkLocalStorageForDebug(t.debug),this._originalUserConfig=t,this._triggered_notifs=[],t.person_profiles?this._initialPersonProfilesConfig=t.person_profiles:t.process_person&&(this._initialPersonProfilesConfig=t.process_person);var c=ul(t.defaults),d=dl(t),h=Js({},c,d,{name:s,token:u});gt(c.rageclick)&&gt(d.rageclick)&&(h.rageclick=Js({},c.rageclick,d.rageclick)),gt(c.session_recording)&&gt(d.session_recording)&&(h.session_recording=Js({},c.session_recording,d.session_recording)),this.set_config(h),this.config.on_xhr_error&&Ws.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=t.disable_compression?void 0:ho;var _=this._is_persistence_disabled();if(this.persistence=new uo(this.config,_),this.sessionPersistence="sessionStorage"===this.config.persistence||"memory"===this.config.persistence?this.persistence:new uo(i({},this.config,{persistence:"sessionStorage"}),_,!1),this._sessionRegisteredPropertiesStorageKey="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties","memory"!==this.config.persistence&&!_&&Rr._is_supported()){var p=Rr._parse(this._sessionRegisteredPropertiesStorageKey);_t(p)&&p.forEach((e=>{mt(e)&&this._sessionRegisteredPropKeys.add(e)}))}else Rr._remove(this._sessionRegisteredPropertiesStorageKey);var g=i({},this.persistence.props),v=i({},this.sessionPersistence.props);this.register({$initialization_time:(new Date).toISOString()}),this._requestQueue=new ma((e=>this._send_retriable_request(e)),this.config.request_queue_config),this._retryQueue=new ba(this),this.__request_queue=[];var f=this._inCookielessMode();if(f||(this.sessionManager=new Ca(this),this.sessionPropsManager=new xa(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((e,t,i)=>{(null!=i&&i.activityTimeout||null!=i&&i.sessionPastMaximumLength||null!=i&&i.crossTabAdoption)&&this._clearSessionRegisteredProps()}))),this._enrollFeatureFlags(),this.config.__preview_deferred_init_extensions?(Ws.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this._initExtensions(f)}),0)):(Ws.info("Initializing extensions synchronously"),this._initExtensions(f)),r.DEBUG=r.DEBUG||this.config.debug,r.DEBUG&&Ws.info("Starting in debug mode",{this:this,config:t,thisC:i({},this.config),p:g,s:v}),!this.config.identity_distinct_id||null!=(n=t.bootstrap)&&n.distinctID||(t.bootstrap=i({},t.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),void 0!==(null==(o=t.bootstrap)?void 0:o.distinctID)){var m=t.bootstrap.distinctID,y=this.get_distinct_id(),b=this.persistence.get_property(Y);if(t.bootstrap.isIdentifiedID&&null!=y&&y!==m&&b===he)this.identify(m);else if(t.bootstrap.isIdentifiedID&&null!=y&&y!==m&&b===_e)Ws.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var w=this.config.get_device_id(dr()),S=t.bootstrap.isIdentifiedID?w:m;this.persistence.set_property(Y,t.bootstrap.isIdentifiedID?_e:he),this.register({distinct_id:m,$device_id:S})}}if(f)this.register_once({distinct_id:re,$device_id:null},"");else if(!this.get_distinct_id()){var x=this.config.get_device_id(dr());this.register_once({distinct_id:x,$device_id:x},""),this.persistence.set_property(Y,he)}return sr(we,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),t.segment?function(e,t){var i=e.config.segment;if(!i)return t();!function(e,t){var i=e.config.segment;if(!i)return t();var s=i=>{var s=()=>i.anonymousId()||dr();e.config.get_device_id=s,i.id()&&(e.register({distinct_id:i.id(),$device_id:s()}),e.persistence.set_property(Y,_e)),t()},r=i.user();"then"in r&&pt(r.then)?r.then(s):s(r)}(e,(()=>{i.register((e=>{"undefined"!=typeof Promise&&Promise.resolve||Cn.warn("This browser does not have Promise support, and can not use the segment integration");var t=(t,i)=>{if(!i)return t;t.event.userId||t.event.anonymousId===e.get_distinct_id()||(Cn.info("No userId set, resetting PostHog"),e.reset()),t.event.userId&&t.event.userId!==e.get_distinct_id()&&(Cn.info("UserId set, identifying with PostHog"),e.identify(t.event.userId));var s=e.calculateEventProperties(i,t.event.properties);return t.event.properties=Object.assign({},s,t.event.properties),t};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:e=>t(e,e.event.event),page:e=>t(e,fe),identify:e=>t(e,ye),screen:e=>t(e,"$screen")}})(e)).then((()=>{t()}))}))}(this,(()=>this._loaded())):this._loaded(),pt(this.config._onCapture)&&this.config._onCapture!==tl&&(Ws.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(e=>this.config._onCapture(e.event,e)))),this.config.ip&&Ws.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||function(){return Fa.apply(this,arguments)}().then((e=>{e&&this.register({[l]:e})})).catch(tl),this}_isSharedExtension(e){var t=e;return mt(t.name)&&pt(t.setup)}_enrollExtension(e,t){this._isSharedExtension(e)?t.push((()=>{this._getBrowserClientAdapter().add(e).catch(tl)})):this._extensions.push(e)}_enrollFeatureFlags(){var e,t,i,s,r,n,o=null!==(e=null==(t=this.config.__extensionClasses)?void 0:t.featureFlags)&&void 0!==e?e:null==(i=_l.__defaultExtensionClasses)?void 0:i.featureFlags;o&&(this.featureFlags&&this.featureFlags instanceof o||(null==(s=this._featureFlagsReloadingUnsubscribe)||s.call(this),this._featureFlagsReloadingUnsubscribe=void 0,this.featureFlags=new o(this)),pt(this.featureFlags.onReloading)&&pt(this.featureFlags.setup)?this._featureFlagsReloadingUnsubscribe||(this._featureFlagsReloadingUnsubscribe=this.featureFlags.onReloading((()=>{this._internalEventEmitter.emit("featureFlagsReloading",!0)})),this._getBrowserClientAdapter().add(this.featureFlags)):null==(r=(n=this.featureFlags).initialize)||r.call(n))}_initExtensions(e){var t,s,r,n,o,a,l,u=performance.now(),c=i({},_l.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this._extensions.push(this.exceptions=null!==(t=this.exceptions)&&void 0!==t?t:new c.exceptions(this)),c.historyAutocapture&&this._extensions.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this._extensions.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this._extensions.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this._extensions.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this._enrollExtension(this.autocapture=new c.autocapture(this),d),c.surveys&&this._enrollExtension(this.surveys=null!==(s=this.surveys)&&void 0!==s?s:new c.surveys(this),d),c.logs&&this._extensions.push(this.logs=null!==(r=this.logs)&&void 0!==r?r:new c.logs(this)),c.metrics&&this._extensions.push(this.metrics=null!==(n=this.metrics)&&void 0!==n?n:new c.metrics(this)),c.conversations&&this._extensions.push(this.conversations=null!==(o=this.conversations)&&void 0!==o?o:new c.conversations(this)),c.productTours&&this._extensions.push(this.productTours=new c.productTours(this)),c.heatmaps&&this._extensions.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this._extensions.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this._extensions.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this._extensions.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,kn)),c.toolbar&&this._extensions.push(this.toolbar=null!==(a=this.toolbar)&&void 0!==a?a:new c.toolbar(this)),c.experiments&&this._extensions.push(this.experiments=null!==(l=this.experiments)&&void 0!==l?l:new c.experiments(this)),this._extensions.forEach((e=>{e.initialize&&d.push((()=>{null==e.initialize||e.initialize()}))})),d.push((()=>{if(this._pendingRemoteConfig){var e=this._pendingRemoteConfig;this._pendingRemoteConfig=void 0,this._extensions.forEach((t=>null==t.onRemoteConfig?void 0:t.onRemoteConfig(e)))}})),this._processInitTaskQueue(d,u)}_processInitTaskQueue(e,t){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-t>=30&&e.length>0)return void setTimeout((()=>{this._processInitTaskQueue(e,t)}),0);var i=e.shift();if(i)try{i()}catch(e){Ws.error("Error initializing extension:",e)}}var s=Math.round(performance.now()-t);this.register_for_session({[oe]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[ae]:s}),this.config.__preview_deferred_init_extensions&&Ws.info("PostHog extensions initialized ("+s+"ms)")}_onRemoteConfig(e){var t;if(!Ee||!Ee.body)return Ws.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this._onRemoteConfig(e)}),500);if(this.config.__preview_deferred_init_extensions&&(this._pendingRemoteConfig=e),this._lastRemoteConfig=e,this.compression=void 0,e.ok){var i,s=e.config;s.supportedCompression&&!this.config.disable_compression&&(this.compression=ot(s.supportedCompression,ho)?ho:ot(s.supportedCompression,_o)?_o:void 0),null!=(i=s.analytics)&&i.endpoint&&(this.analyticsDefaultEndpoint=s.analytics.endpoint)}this.set_config({person_profiles:this._initialPersonProfilesConfig?this._initialPersonProfilesConfig:pe}),null==(t=this._browserClientAdapter)||t.handleRemoteConfig(e),this._extensions.forEach((t=>null==t.onRemoteConfig?void 0:t.onRemoteConfig(e)))}_loaded(){try{this.config.loaded(this)}catch(e){Ws.critical("`loaded` function failed",e)}if(this._start_queue_if_opted_in(),this.config.internal_or_test_user_hostname&&null!=ke&&ke.hostname){var e=ke.hostname,t=this.config.internal_or_test_user_hostname;("string"==typeof t?e===t:t.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this._inCookielessMode())&&this._captureInitialPageview()}),1),this._remoteConfigLoader=new xo(this),this._remoteConfigLoader.load()}_start_queue_if_opted_in(){var e;this.is_capturing()&&this.config.request_batching&&(null==(e=this._requestQueue)||e.enable())}_dom_loaded(){this.is_capturing()&&Ks(this.__request_queue,(e=>this._send_retriable_request(e))),this.__request_queue=[],this._start_queue_if_opted_in()}_handle_unload(){var e,t,i,s,r;null==(e=this.surveys)||null==e.handlePageUnload||e.handlePageUnload(),null==(t=this.metrics)||t.flush("sendBeacon"),this.config.request_batching?(this._shouldCapturePageleave()&&this.capture(me),null==(i=this.logs)||i.flushLogs("sendBeacon"),null==(s=this._requestQueue)||s.unload(),null==(r=this._retryQueue)||r.unload()):this._shouldCapturePageleave()&&this.capture(me,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?ll?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(null==e.callback||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=i({},this.config.request_headers,e.headers),e.compression="best-available"===e.compression?this.compression:e.compression,(ft(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(e=>{var t,s,r,n=i({},e);n.timeout=n.timeout||6e4;var o,a,l,u,c,d=null!==(t=n.transport)&&void 0!==t?t:"fetch";"sendBeacon"===d&&ft(n.compression)&&n.data&&(n.compression=_o),"POST"===n.method&&n.data&&("capture-body"===n.timestampMode?n.data={api_key:null!==(a=null==(c=(u=(_t(o=n.data)?o:[o]).map((e=>i({},e,e.timestamp instanceof Date&&!isNaN(e.timestamp.getTime())?{timestamp:e.timestamp.toISOString()}:{}))))[0])||null==(l=c.properties)?void 0:l.token)&&void 0!==a?a:null==c?void 0:c.token,batch:u,sent_at:(new Date).toISOString()}:"body"===n.timestampMode&&(n.data=function(e,t){return void 0===t&&(t=(new Date).toISOString()),_t(e)?e.map((e=>i({},e,{sent_at:t}))):i({},e,{sent_at:t})}(n.data))),n.url=ga(n.url,n.method,n.compression,n.timestampMode);var h=va.filter((e=>!n.disableTransport||!e.transport||!n.disableTransport.includes(e.transport))),_=null!==(s=null==(r=function(e,t){for(var i=0;e.length>i;i++)if(e[i].transport===d)return e[i]}(h))?void 0:r.method)&&void 0!==s?s:h[0].method;if(!_)throw new Error("No available transport method");var p=e=>{try{_(e)}catch(e){ha(e)?Ws.warn(e):Ws.error(e),null==n.callback||n.callback({statusCode:0,error:e})}};"sendBeacon"!==d&&n.data&&n.compression===ho&&Fe&&"undefined"!=typeof Promise&&!ra?ca(n).then((e=>{p(e)})).catch((t=>{if(We(t))return ra=!0,void p(i({},n,{compression:void 0,url:ga(e.url,e.method,void 0,e.timestampMode)}));(e=>{if(!e||"object"!=typeof e)return!1;var t="name"in e?String(e.name):"";return We(e)||t===je})(t)&&(ra=!0),p(n)})):_(n)})(i({},e,{callback:t=>{var i,s;this.rateLimiter.checkForLimiting(t),400>t.statusCode||null==(i=(s=this.config).on_request_error)||i.call(s,t),null==e.callback||e.callback(t)}}))):e.fireCallbackOnDrop&&(null==e.callback||e.callback({statusCode:0}))}_send_retriable_request(e){this._retryQueue?this._retryQueue.retriableRequest(e):this._send_request(e)}_execute_array(e){el++;try{var t,i=[],s=[],r=[];Ks(e,(e=>{if(e)if(_t(t=e[0]))r.push(e);else if(pt(e))try{e.call(this)}catch(t){Ws.error("Error executing queued PostHog call",e,t)}else _t(e)&&"alias"===t?i.push(e):_t(e)&&-1!==t.indexOf("capture")&&pt(this[t])?r.push(e):s.push(e)}));var n=function(e,t){Ks(e,(function(e){try{if(_t(e[0])){var i=t;Qs(e,(function(e){i=i[e[0]].apply(i,e.slice(1))}))}else t[e[0]].apply(t,e.slice(1))}catch(t){Ws.error("Error executing queued PostHog call",e,t)}}))};n(i,this),n(s,this),n(r,this)}finally{el--}}push(e){if(el>0&&_t(e)&&mt(e[0])){var t=_l.prototype[e[0]];pt(t)&&t.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,t,s){var r,n,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this._requestQueue){if(this.is_capturing())if(!ft(e)&&mt(e)){this._healCookielessSentinelDistinctId();var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=null!=s&&s.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(null==c||!c.isRateLimited){null!=t&&t.$current_url&&!mt(null==t?void 0:t.$current_url)&&(Ws.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),null==t||delete t.$current_url),"$exception"!==e||null!=s&&s._originatedFromCaptureException||Ws.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=(null==s?void 0:s.timestamp)||d,_=ji(null==s?void 0:s.uuid,dr),p={uuid:_,event:e,properties:this.calculateEventProperties(e,t||{},h,_)};e===fe&&this.config.__preview_capture_bot_pageviews&&u&&(p.event="$bot_pageview",p.properties.$browser_type="bot"),c&&(p.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g="$feature_flag_called"===e&&!1===p.properties.$feature_flag_has_experiment&&!0===this.get_property(M);(null==s?void 0:s.$set)&&!g&&(p.$set=null==s?void 0:s.$set);var v=null==s?void 0:s.$unset;v&&(p.$unset=v);var f,m,y,b=g?void 0:this._calculate_set_once_properties(null==s?void 0:s.$set_once,e!==be,e===ye);if(b&&(p.$set_once=b),null!=s&&s._noTruncate||(n=this.config.properties_string_max_length,o=p,a=e=>mt(e)?e.slice(0,n):e,l=new Set,p=function e(t,i){if(t!==Object(t))return a?a(t):t;if(!l.has(t)){var s;if(l.add(t),_t(t))s=[],Ks(t,(t=>{s.push(e(t))}));else{var r={};Qs(t,((t,i)=>{l.has(t)||(r[i]=e(t,i))})),s=r}return s}}(o)),p.timestamp=h,ft(null==s?void 0:s.timestamp)||(p.properties.$event_time_override_provided=!0,p.properties.$event_time_override_system_time=d),g&&(p.properties=function(e,t){void 0===t&&(t=[]);var i={},s=t=>{void 0!==e[t]&&(i[t]=e[t])};return Be.forEach(s),t.forEach(s),i}(p.properties,ol)),e===fo||e===mo){var w=null==t?void 0:t.$survey_id,S=null==t?void 0:t.$survey_iteration;ja({id:w,current_iteration:S}),p.$set=i({},p.$set,{[(f={id:w,current_iteration:S},m=e===mo?"responded":"dismissed",y="$survey_"+m+"/"+f.id,f.current_iteration&&f.current_iteration>0&&(y="$survey_"+m+"/"+f.id+"/"+f.current_iteration),y)]:!0})}else e===vo&&(p.$set=i({},p.$set,{$survey_last_seen_date:(new Date).toISOString()}));if("product tour shown"===e){var x=null==t?void 0:t.$product_tour_type;x&&(p.$set=i({},p.$set,{["$product_tour_last_seen_date/"+x]:(new Date).toISOString()}))}var E=i({},p.properties.$set,p.$set);if(vt(E)||this.setPersonPropertiesForFlags(E),!wt(this.config.before_send)){var k=this._runBeforeSend(p);if(!k)return;(p=k).uuid=ji(p.uuid,dr)}this._internalEventEmitter.emit("eventCaptured",p);var P=null!==(r=null==s?void 0:s._url)&&void 0!==r?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),C={method:"POST",url:P,data:p,compression:"best-available",timestampMode:"recordings"===(null==s?void 0:s._batchKey)||/\/s\/(?:\?|$)/.test(P)?"body":"capture-body",batchKey:null==s?void 0:s._batchKey,transport:null==s?void 0:s.transport};return!this.config.request_batching||s&&(null==s||!s._batchKey)||null!=s&&s.send_instantly?this._send_retriable_request(C):this._requestQueue.enqueue(C),p}Ws.critical("This capture call is ignored due to client rate limiting.")}}else Ws.error("No event name provided to posthog.capture")}else Ws.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(t=>e(t.event,t)))}_getBrowserClientAdapter(){var e;return null!==(e=this._browserClientAdapter)&&void 0!==e?e:this._browserClientAdapter=new Za(this)}_registerExtensionEventProperties(e){this._extensionEventPropertyProducers.push(e);var t=!0;return()=>{if(t){t=!1;var i=this._extensionEventPropertyProducers.indexOf(e);-1!==i&&this._extensionEventPropertyProducers.splice(i,1)}}}_processCookieIdentityChange(e){var t,i,s;return void 0===e&&(e=!0),!(null==(t=this.persistence)||!t.consumeCookieIdentityChange())&&(this._cachedPersonProperties=null,this.persistence.get_property(Y)===he&&(null==(s=this.sessionPersistence)||s.clear(),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys()),null==(i=this.featureFlags)||i.reset(),e&&this.reloadFeatureFlags(),!0)}calculateEventProperties(e,t,s,n,o){if(s=s||new Date,!this.persistence||!this.sessionPersistence)return t;this.persistence.syncCookieProperties(),this._processCookieIdentityChange();var a=o?void 0:this.persistence.remove_event_timer(e),l=i({},t);if(l.token=this.config.token,l.$config_defaults=this.config.defaults,this._inCookielessMode()&&(l[ne]=!0),"$snapshot"===e){var u=i({},this.persistence.properties(),this.sessionPersistence.properties());return l.distinct_id=u.distinct_id,(!mt(l.distinct_id)&&!St(l.distinct_id)||yt(l.distinct_id))&&Ws.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),l}var c,d=function(e,t,i,s){var n,o,a,l;if(void 0===s&&(s=!1),!Te)return{};var u,c=e?[...Un,...t||[]]:[],d=function(e){for(var t=0;Hi.length>t;t++){var i=Hi[t],s=i[1],r=i[0].exec(e),n=r&&(pt(s)?s(r,e):s);if(n)return n}return["",""]}(Te),h=d[0],_=d[1],p=null!=(u="undefined"!=typeof navigator?navigator:void 0)&&u.brave?{brave:!0}:{},g={};ft(i)||(g.detectGoogleSearchApp=i);var v={},f=null==(n=navigator)||null==(n=n.userAgentData)?void 0:n.platform,m=null==(o=navigator)?void 0:o.maxTouchPoints,y=null==we||null==(a=we.screen)?void 0:a.width,b=null==we||null==(l=we.screen)?void 0:l.height,w=null==we?void 0:we.devicePixelRatio;ft(f)||(v.userAgentDataPlatform=f),ft(m)||(v.maxTouchPoints=m),ft(y)||(v.screenWidth=y),ft(b)||(v.screenHeight=b),ft(w)||(v.devicePixelRatio=w);var S,x,E,k,P,C,I,F,T=Js(er({$os:h,$os_version:_,$browser:Di(Te,navigator.vendor,p,g),$device:Ni(Te),$device_type:(x=Te,E=v,F=Ni(x),F===jt||F===zt||"Kobo"===F||"Kindle Fire"===F||F===yi?Nt:F===li||F===ci||F===ui||F===vi?"Console":F===Vt?"Wearable":F?Bt:"Android"===(null==E?void 0:E.userAgentDataPlatform)&&(null!==(k=null==E?void 0:E.maxTouchPoints)&&void 0!==k?k:0)>0?600>Math.min(null!==(P=null==E?void 0:E.screenWidth)&&void 0!==P?P:0,null!==(C=null==E?void 0:E.screenHeight)&&void 0!==C?C:0)/(null!==(I=null==E?void 0:E.devicePixelRatio)&&void 0!==I?I:1)?Bt:Nt:"Desktop"),$timezone:io(),$timezone_offset:so()}),{$current_url:qn(s?Ui(null==ke?void 0:ke.href):null==ke?void 0:ke.href,c,Wn),$host:null==ke?void 0:ke.host,$pathname:null==ke?void 0:ke.pathname,$raw_user_agent:Te.length>1e3?Te.substring(0,997)+"...":Te,$browser_version:qi(Te,navigator.vendor,p,g),$browser_language:Yn(),$browser_language_prefix:(S=Yn(),"string"==typeof S?S.split("-")[0]:void 0),$screen_height:null==we?void 0:we.screen.height,$screen_width:null==we?void 0:we.screen.width,$viewport_height:null==we?void 0:we.innerHeight,$viewport_width:null==we?void 0:we.innerWidth,$lib:r.LIB_NAME,$lib_version:r.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return r.SDK_DIST_CHANNEL&&(T.$sdk_dist_channel=r.SDK_DIST_CHANNEL),T}(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var h=this.sessionManager.checkAndGetSessionAndWindowId(o,s.getTime(),!0),_=h.windowId;l.$session_id=h.sessionId,l.$window_id=_}this.sessionPropsManager&&Js(l,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&Js(l,this.sessionRecording.sdkDebugProperties),l.$sdk_debug_retry_queue_size=null==(p=this._retryQueue)?void 0:p.length}catch(e){l.$sdk_debug_error_capturing_properties=String(e)}if(this.requestRouter.region===Oa&&(l.$lib_custom_api_host=this.config.api_host),c=e!==fe||o?e!==me||o?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(s):this.pageViewManager.doPageView(s,n),l=Js(l,c),e===fe&&Ee&&(l.title=Ee.title),!ft(a)){var g=s.getTime()-a;l.$duration=parseFloat((g/1e3).toFixed(3))}Te&&this.config.opt_out_useragent_filter&&(l.$browser_type=this._is_bot()?"bot":"browser");var v=this.persistence.properties(),f=this.sessionPersistence.properties();Qs(["$referrer","$referring_domain"],(e=>{e in v&&delete f[e]}));var m={};if(this._extensionEventPropertyProducers.length>0)for(var y of this._extensionEventPropertyProducers.slice())try{Js(m,y())}catch(e){Ws.error("Failed to produce browser extension event properties",e)}(l=Js({},d,v,f,i({},m,l))).$is_identified=this._isIdentified(),_t(this.config.property_denylist)?Qs(this.config.property_denylist,(function(e){delete l[e]})):Ws.error(nl+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var b=this.config.sanitize_properties;b&&(Ws.error(rl),l=b(l,e));var w=this._hasPersonProcessing();return l.$process_person_profile=w,w&&!o&&this._requirePersonProcessing("_calculate_event_properties"),l}_calculate_set_once_properties(e,t,i){var s;if(void 0===t&&(t=!0),void 0===i&&(i=!1),!this.persistence||!this._hasPersonProcessing())return e;if(this._personProcessingSetOncePropertiesSent&&!i)return e;var r=this.persistence.get_initial_props(),n=null==(s=this.sessionPropsManager)?void 0:s.getSetOnceProps(),o=Js({},r,n||{},e||{}),a=this.config.sanitize_properties;return a&&(Ws.error(rl),o=a(o,"$set_once")),t&&(this._personProcessingSetOncePropertiesSent=!0),vt(o)?void 0:o}register(e,t){var i;null==(i=this.persistence)||i.register(e,t)}register_once(e,t,i){var s;null==(s=this.persistence)||s.register_once(e,t,i)}register_for_session(e){var t,i;null==(t=this.persistence)||t.syncCookieProperties(),this._processCookieIdentityChange(),null==(i=this.sessionPersistence)||i.register(e),Object.keys(e).forEach((e=>this._sessionRegisteredPropKeys.add(e))),this._persistSessionRegisteredPropKeys()}unregister(e){var t;null==(t=this.persistence)||t.unregister(e)}unregister_for_session(e){var t;null==(t=this.sessionPersistence)||t.unregister(e),this._sessionRegisteredPropKeys.delete(e),this._persistSessionRegisteredPropKeys()}_register_single(e,t){this.register({[e]:t})}_clearSessionRegisteredProps(){this._sessionRegisteredPropKeys.forEach((e=>{var t;null==(t=this.sessionPersistence)||t.unregister(e)})),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys()}_persistSessionRegisteredPropKeys(){var e;if(this._sessionRegisteredPropertiesStorageKey)if("memory"===this.config.persistence||null!=(e=this.sessionPersistence)&&e._disabled||!Rr._is_supported())Rr._remove(this._sessionRegisteredPropertiesStorageKey);else{var t=[];this._sessionRegisteredPropKeys.forEach((e=>t.push(e))),t.length>0?Rr._set(this._sessionRegisteredPropertiesStorageKey,t):Rr._remove(this._sessionRegisteredPropertiesStorageKey)}}getFeatureFlag(e,t){var i;return null==(i=this.featureFlags)?void 0:i.getFeatureFlag(e,t)}getFeatureFlagPayload(e){var t;return null==(t=this.featureFlags)?void 0:t.getFeatureFlagPayload(e)}getFeatureFlagResult(e,t){var i;return null==(i=this.featureFlags)?void 0:i.getFeatureFlagResult(e,t)}getAllFeatureFlags(){var e,t;return null!==(e=null==(t=this.featureFlags)?void 0:t.getAllFeatureFlags())&&void 0!==e?e:[]}isFeatureEnabled(e,t){var i,s;return null!==(i=null==(s=this.featureFlags)?void 0:s.isFeatureEnabled(e,t))&&void 0!==i?i:null==t?void 0:t.defaultValue}reloadFeatureFlags(){var e;null==(e=this.featureFlags)||e.reloadFeatureFlags()}updateFlags(e,t,i){var s;null==(s=this.featureFlags)||s.updateFlags(e,t,i)}updateEarlyAccessFeatureEnrollment(e,t,i){var s;null==(s=this.featureFlags)||s.updateEarlyAccessFeatureEnrollment(e,t,i)}getEarlyAccessFeatures(e,t,i){var s;return void 0===t&&(t=!1),null==(s=this.featureFlags)?void 0:s.getEarlyAccessFeatures(e,t,i)}on(e,t){return this._internalEventEmitter.on(e,t)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:sl}),()=>{})}onSessionId(e){var t,i;return null!==(t=null==(i=this.sessionManager)?void 0:i.onSessionId(e))&&void 0!==t?t:()=>{}}getSurveys(e,t){void 0===t&&(t=!1),this.surveys?this.surveys.getSurveys(e,t):e([],{isLoaded:!1,error:sl})}getActiveMatchingSurveys(e,t){void 0===t&&(t=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,t):e([],{isLoaded:!1,error:sl})}renderSurvey(e,t){var i;null==(i=this.surveys)||i.renderSurvey(e,t)}displaySurvey(e,t){var i;void 0===t&&(t=Va),null==(i=this.surveys)||i.displaySurvey(e,t)}cancelPendingSurvey(e){var t;null==(t=this.surveys)||t.cancelPendingSurvey(e)}canRenderSurvey(e){var t,i;return null!==(t=null==(i=this.surveys)?void 0:i.canRenderSurvey(e))&&void 0!==t?t:{visible:!1,disabledReason:sl}}canRenderSurveyAsync(e,t){var i,s;return void 0===t&&(t=!1),null!==(i=null==(s=this.surveys)?void 0:s.canRenderSurveyAsync(e,t))&&void 0!==i?i:Promise.resolve({visible:!1,disabledReason:sl})}_validateIdentifyId(e){return!e||yt(e)?(Ws.critical("Unique user id has not been set in posthog.identify"),!1):e===re?(Ws.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(Ws.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,t,i){if(!this.__loaded||!this.persistence)return Ws.uninitializedWarning("posthog.identify");if(St(e)&&(e=e.toString(),Ws.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this._validateIdentifyId(e)&&this._requirePersonProcessing("posthog.identify")){this._healCookielessSentinelDistinctId();var s=this.get_distinct_id(),r=this.persistence.syncCookieProperties()&&this.get_distinct_id()!==s,n=this._processCookieIdentityChange(!1),o=this.persistence._beginCookieSyncSuppression(),l=!1;try{var c=this.get_distinct_id();this.register({$user_id:e}),this.get_property(a)||this.register_once({$had_persisted_distinct_id:!0,$device_id:c},""),e!==c&&e!==this.get_property(u)&&(this.unregister(u),this.register({distinct_id:e}));var d,h=(this.persistence.get_property(Y)||he)===he,_=e!==c,p=!_&&h;if(_&&h)this.persistence.set_property(Y,_e),this.setPersonPropertiesForFlags({$set:t||{},$set_once:i||{}},!1),this.config.cookieWinsOnConflict&&this.persistence._publishSuppressedCookieSnapshot(),this.capture(ye,{distinct_id:e,$anon_distinct_id:c},{$set:t||{},$set_once:i||{}}),this._cachedPersonProperties=$a(e,t,i),null==(d=this.featureFlags)||d.setAnonymousDistinctId(c);else if(p){this.persistence.set_property(Y,_e);var g=t||{},v=i||{};this.setPersonPropertiesForFlags({$set:g,$set_once:v},!1),this.config.cookieWinsOnConflict&&this.persistence._publishSuppressedCookieSnapshot(),this.capture("$set",{$set:g,$set_once:v}),this._cachedPersonProperties=$a(e,t,i)}else(t||i)&&this.setPersonProperties(t,i);_||r||n?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(G)):p&&(t||i)&&this.reloadFeatureFlags(),l=!0}finally{o&&this.persistence._endCookieSyncSuppression(l)}}}setPersonProperties(e,t){if((e||t)&&this._requirePersonProcessing("posthog.setPersonProperties")){var i=$a(this.get_distinct_id(),e,t);this._cachedPersonProperties!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:t||{}},!0),this.capture("$set",{$set:e||{},$set_once:t||{}}),this._cachedPersonProperties=i):Ws.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var t,i=(_t(e)?e:[e]).filter((e=>mt(e)&&e.length>0));0!==i.length&&this._requirePersonProcessing("posthog.unsetPersonProperties")&&(null==(t=this.featureFlags)||t.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this._cachedPersonProperties=null)}group(e,t,s){var r;if(e&&t){null==(r=this.persistence)||r.syncCookieProperties(),this._processCookieIdentityChange();var n=this.getGroups(),o=n[e]!==t;if(o&&this.resetGroupPropertiesForFlags(e),this.register({$groups:i({},n,{[e]:t})}),o||s){var a={$group_type:e,$group_key:t};s&&(a.$group_set=s),this.capture(be,a)}s&&this.setGroupPropertiesForFlags({[e]:s}),o&&!s&&this.reloadFeatureFlags()}else Ws.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,t){var i;void 0===t&&(t=!0),null==(i=this.featureFlags)||i.setPersonPropertiesForFlags(e,t)}resetPersonPropertiesForFlags(e){var t;void 0===e&&(e=!0),null==(t=this.featureFlags)||t.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,t){var i;void 0===t&&(t=!0),this._requirePersonProcessing("posthog.setGroupPropertiesForFlags")&&(null==(i=this.featureFlags)||i.setGroupPropertiesForFlags(e,t))}resetGroupPropertiesForFlags(e){var t;null==(t=this.featureFlags)||t.resetGroupPropertiesForFlags(e)}reset(e){var t=Et(e)?e:null==e?void 0:e.resetDeviceID,i=Et(e)||null==e?void 0:e.bootstrap;this._reset(t,!1,i)}_reset(e,t,s){var r,n,o;if(void 0===t&&(t=!1),Ws.info("reset"),!this.__loaded)return Ws.uninitializedWarning("posthog.reset");var u=null==s?void 0:s.sessionID;this.config.bootstrap=s||(null==(r=this._originalUserConfig)?void 0:r.bootstrap)||{},null==(n=this.featureFlags)||null==n.updateConfig||n.updateConfig(this.config,this._shouldDisableFlags());var c=this.get_property(a),d=this.get_property(l),h=this.get_property(b),_=this.is_capturing();this.consent.reset(),t||!_||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after.");var p=null==(o=this.persistence)||null==o._beginCookieSyncSuppression?void 0:o._beginCookieSyncSuppression(),g=!1;try{var v,f,m,y,w,S,x,E,k,P,C,I,F,T;if(null==(v=this.persistence)||v.clear(),null==(f=this.sessionPersistence)||f.clear(),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys(),ft(h)||null==(C=this.persistence)||C.register({[b]:h}),null==(m=this.surveys)||m.reset(),null==(y=this._remoteConfigLoader)||y.stop(),null==(w=this.featureFlags)||w.reset(),null==(S=this.conversations)||S.reset(),null==(x=this.logs)||x.reset(),null==(E=this.metrics)||E.reset(),null==(k=this.persistence)||k.set_property(Y,he),null==(P=this.sessionManager)||P.resetSessionId(),this._cachedPersonProperties=null,this.config.cookieless_mode===de)this.register_once({distinct_id:re,$device_id:null},"");else{var R=this.config.get_device_id(dr());this.register_once({distinct_id:R,$device_id:e?R:c},""),e||ft(d)||this.register({[l]:d})}if(this.register({$last_posthog_reset:(new Date).toISOString()},1),s)if(void 0===s.distinctID||this._inCookielessMode()||(null==(T=this.persistence)||T.set_property(Y,s.isIdentifiedID?_e:he),this.register({distinct_id:s.distinctID})),null==(I=this.featureFlags)||I.initialize(),!(ft(u)||null!=(F=this.sessionManager)&&F.setBootstrapSessionId(u,!0))){var A=i({},s);delete A.sessionID,this.config.bootstrap=A}delete this.config.identity_distinct_id,delete this.config.identity_hash,g=!0}finally{var L;p&&(null==(L=this.persistence)||null==L._endCookieSyncSuppression||L._endCookieSyncSuppression(g))}this.reloadFeatureFlags()}shutdown(e){var i=this;return t((function*(){var e,t,s,r,n,o;if(i.__loaded){null==(e=i._remoteConfigLoader)||e.stop(),i._getBrowserClientAdapter().dispose(),null==(t=i.sessionRecording)||t.dispose(),null==(s=i.logs)||s.flushLogs("sendBeacon"),null==(r=i.metrics)||r.flush("sendBeacon"),null==(n=i._requestQueue)||n.unload(),null==(o=i._retryQueue)||o.unload();try{var a;null==(a=i.featureFlags)||a.destroy()}catch(e){Ws.error("Error while destroying feature flags",e)}}else Ws.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,t){var i;this.config.identity_distinct_id=e,this.config.identity_hash=t,this.alias(e),null==(i=this.conversations)||i._onIdentityChanged()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,null==(e=this.conversations)||e._onIdentityCleared()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,t;return null!==(e=null==(t=this.sessionManager)?void 0:t.checkAndGetSessionAndWindowId(!0).sessionId)&&void 0!==e?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var t=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=t.sessionStartTimestamp,s=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+t.sessionId);if(null!=e&&e.withTimestamp&&i){var r,n=null!==(r=e.timestampLookBack)&&void 0!==r?r:10;if(!i)return s;s+="?t="+Math.max(Math.floor(((new Date).getTime()-i)/1e3)-n,0)}return s}alias(e,t){return e===this.get_property(n)?(Ws.critical("Attempting to create alias for existing People user - aborting."),-2):this._requirePersonProcessing("posthog.alias")?(ft(t)&&(t=this.get_distinct_id()),e!==t?(this._register_single(u,e),this.capture("$create_alias",{alias:e,distinct_id:t})):(Ws.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var t=i({},this.config);if(gt(e)){var s,n,o,a,l,u,c,d,h,_,p,g;Js(this.config,dl(e));var v=this._is_persistence_disabled();null==(s=this.persistence)||s.update_config(this.config,t,v),this.sessionPersistence="sessionStorage"===this.config.persistence||"memory"===this.config.persistence?this.persistence:new uo(i({},this.config,{persistence:"sessionStorage"}),v,!1);var f,m=this._checkLocalStorageForDebug(this.config.debug);Et(m)&&(this.config.debug=m),Et(this.config.debug)&&(this.config.debug?(r.DEBUG=!0,fr._is_supported()&&fr._set("ph_debug",!0),Ws.info("set_config",{config:e,oldConfig:t,newConfig:i({},this.config)})):(r.DEBUG=!1,fr._is_supported()&&fr._remove("ph_debug"))),null==(n=this.featureFlags)||null==n.updateConfig||n.updateConfig(this.config,this._shouldDisableFlags()),null==(o=this.exceptionObserver)||o.onConfigChange(),null==(a=this.exceptions)||a.onConfigChange(),null==(l=this.sessionRecording)||l.startIfEnabledOrStop(),null==(u=this.tracingHeaders)||u.startIfEnabledOrStop(),null==(c=this.autocapture)||c.startIfEnabled(),null==(d=this.heatmaps)||d.startIfEnabled(),("capture_pageview"in e||"disable_capture_url_hashes"in e)&&(null==(f=this.historyAutocapture)||f.startIfEnabledOrStop()),null==(h=this.exceptionObserver)||h.startIfEnabledOrStop(),null==(_=this.deadClicksAutocapture)||_.startIfEnabledOrStop(),null==(p=this.surveys)||p.loadIfEnabled(),this._sync_opt_out_with_persistence(),null==(g=this.externalIntegrations)||g.startIfEnabledOrStop()}}_overrideSDKInfo(e,t){r.LIB_NAME=e,r.LIB_VERSION=t}startSessionRecording(e){var t,i,s,r,n,o=!0===e,a={sampling:o||!(null==e||!e.sampling),linked_flag:o||!(null==e||!e.linked_flag),url_trigger:o||!(null==e||!e.url_trigger),event_trigger:o||!(null==e||!e.event_trigger)};Object.values(a).some(Boolean)&&(null==(t=this.sessionManager)||t.checkAndGetSessionAndWindowId(),a.sampling&&(null==(i=this.sessionRecording)||i.overrideSampling()),a.linked_flag&&(null==(s=this.sessionRecording)||s.overrideLinkedFlag()),a.url_trigger&&(null==(r=this.sessionRecording)||r.overrideTrigger("url")),a.event_trigger&&(null==(n=this.sessionRecording)||n.overrideTrigger("event")));this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!(null==(e=this.sessionRecording)||!e.started)}captureException(e,t){if(this.exceptions){var s=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:s});return this.exceptions.sendExceptionEvent(i({},r,t))}}addExceptionStep(e,t){var i;null==(i=this.exceptions)||i.addExceptionStep(e,t)}captureLog(e){var t;null==(t=this.logs)||t.captureLog(e)}get logger(){var e,t;return null!==(e=null==(t=this.logs)?void 0:t.logger)&&void 0!==e?e:_l._noopLogger}startExceptionAutocapture(e){this.set_config({capture_exceptions:null==e||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var t,i;return null!==(t=null==(i=this.toolbar)?void 0:i.loadToolbar(e))&&void 0!==t&&t}get_property(e){var t;return null==(t=this.persistence)?void 0:t.props[e]}getSessionProperty(e){var t;return null==(t=this.sessionPersistence)?void 0:t.props[e]}toString(){var e,t=null!==(e=this.config.name)&&void 0!==e?e:al;return t!==al&&(t=al+"."+t),t}_isIdentified(){var e,t;return(null==(e=this.persistence)?void 0:e.get_property(Y))===_e||(null==(t=this.sessionPersistence)?void 0:t.get_property(Y))===_e}_hasPersonProcessing(){var e,t;return!("never"===this.config.person_profiles||this.config.person_profiles===pe&&!this._isIdentified()&&vt(this.getGroups())&&(null==(e=this.persistence)||null==(e=e.props)||!e[u])&&(null==(t=this.persistence)||null==(t=t.props)||!t[se]))}_shouldCapturePageleave(){return!0===this.config.capture_pageleave||"if_capture_pageview"===this.config.capture_pageleave&&!!this.config.capture_pageview}createPersonProfile(){this._hasPersonProcessing()||this._requirePersonProcessing("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this._requirePersonProcessing("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}_requirePersonProcessing(e){return"never"===this.config.person_profiles?(Ws.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this._register_single(se,!0),!0)}_is_persistence_disabled(){if("always"===this.config.cookieless_mode)return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==ce)}_sync_opt_out_with_persistence(){var e,t,i,s,r=this._is_persistence_disabled();return(null==(e=this.persistence)?void 0:e._disabled)!==r&&(null==(i=this.persistence)||i.set_disabled(r)),(null==(t=this.sessionPersistence)?void 0:t._disabled)!==r&&(null==(s=this.sessionPersistence)||s.set_disabled(r)),r&&(this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys()),r}opt_in_capturing(e){var t;if(this.config.cookieless_mode!==de){if(this._inCookielessMode()){var i,s,r,n,o;this._reset(!0,!0),null==(i=this.sessionManager)||i.destroy(),null==(s=this.pageViewManager)||s.destroy(),this.sessionManager=new Ca(this),this.pageViewManager=new Rn(this),this.persistence&&(this.sessionPropsManager=new xa(this,this.sessionManager,this.persistence));var a,l=null!==(r=null==(n=this.config.__extensionClasses)?void 0:n.sessionRecording)&&void 0!==r?r:null==(o=_l.__defaultExtensionClasses)?void 0:o.sessionRecording;l&&(this.sessionRecording=this._replaceExtension(this.sessionRecording,new l(this)),this._lastRemoteConfig&&(null==(a=this.sessionRecording)||null==a.onRemoteConfig||a.onRemoteConfig(this._lastRemoteConfig)))}var u,c;this.consent.optInOut(!0),this._sync_opt_out_with_persistence(),this._start_queue_if_opted_in(),null==(t=this.sessionRecording)||t.startIfEnabledOrStop(),this.config.cookieless_mode==ce&&(null==(u=this.surveys)||u.loadIfEnabled()),(ft(null==e?void 0:e.captureEventName)||null!=e&&e.captureEventName)&&this.capture(null!==(c=null==e?void 0:e.captureEventName)&&void 0!==c?c:"$opt_in",null==e?void 0:e.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this._captureInitialPageview()}else Ws.warn(il)}opt_out_capturing(){var e,t,i;this.config.cookieless_mode!==de?(this.config.cookieless_mode===ce&&this.consent.isOptedIn()&&this._reset(!0,!0),this.consent.optInOut(!1),this._sync_opt_out_with_persistence(),this.config.cookieless_mode===ce&&(this.register({distinct_id:re,$device_id:null}),null==(e=this.sessionRecording)||e.stopRecording(),this.sessionRecording=void 0,null==(t=this.sessionManager)||t.destroy(),null==(i=this.pageViewManager)||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this._captureInitialPageview(),this._start_queue_if_opted_in())):Ws.warn(il)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return 1===e?"granted":0===e?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===de||(this.config.cookieless_mode===ce?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this._sync_opt_out_with_persistence()}_is_bot(){return xe?Ia(xe,this.config.custom_blocked_useragents):void 0}_captureInitialPageview(){Ee&&("visible"===Ee.visibilityState?this._initialPageviewCaptured||(this._initialPageviewCaptured=!0,this.capture(fe,{title:Ee.title},{send_instantly:!0}),this._visibilityStateListener&&(Ee.removeEventListener(ge,this._visibilityStateListener),this._visibilityStateListener=null)):this._visibilityStateListener||(this._visibilityStateListener=this._captureInitialPageview.bind(this),sr(Ee,ge,this._visibilityStateListener)))}debug(e){!1===e?(null==we||we.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(null==we||we.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}_shouldDisableFlags(){var e=this._originalUserConfig||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:!1!==this.config.advanced_disable_flags?!!this.config.advanced_disable_flags:!0===this.config.advanced_disable_decide?(Ws.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):function(e,t,i,s,r){var n=t in e&&!wt(e[t]),o=i in e&&!wt(e[i]);return n?e[t]:!!o&&(r&&r.warn("Config field '"+i+"' is deprecated. Please use '"+t+"' instead. The old field will be removed in a future major version."),e[i])}(e,"advanced_disable_flags","advanced_disable_decide",0,Ws)}_runBeforeSend(e){var t;if(wt(this.config.before_send))return e;var i=Object.keys(null!==(t=e.properties)&&void 0!==t?t:{}).filter(Ct),s=_t(this.config.before_send)?this.config.before_send:[this.config.before_send],r=e;for(var n of s)try{if(r=n(r),wt(r)){var o="Event '"+e.event+"' was rejected in beforeSend function";return Pt(e.event)?Ws.warn(o+". This can cause unexpected behavior."):Ws.info(o),null}r.properties&&!vt(r.properties)||Ws.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}catch(t){return Ws.error("Error in beforeSend function for event '"+e.event+"':",t),null}for(var a of i)if(r.properties&&wt(r.properties[a]))return Ws.warn("Event '"+e.event+"' had its '"+a+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return r}getPageViewId(){var e;return null==(e=this.pageViewManager._currentPageview)?void 0:e.pageViewId}captureTraceFeedback(e,t){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:t})}captureTraceMetric(e,t,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:t,$ai_metric_value:String(i)})}_checkLocalStorageForDebug(e){var t=Et(e)&&!e,i=fr._is_supported()&&"true"===fr._get("ph_debug");return!t&&(!!i||e)}}_l.__defaultExtensionClasses={},_l._noopLogger=(()=>{var e=()=>{};return{trace:e,debug:e,info:e,warn:e,error:e,fatal:e}})(),function(e,t){for(var i=0;t.length>i;i++)e.prototype[t[i]]=Xs(e.prototype[t[i]])}(_l,["identify"]);class pl{constructor(e){this.disabled=!1===e;var t=gt(e)?e:{};this.thresholdPx=t.threshold_px||30,this.timeoutMs=t.timeout_ms||1e3,this.clickCount=t.click_count||3,this.clicks=[]}isRageClick(e,t,i){if(this.disabled)return!1;var s=this.clicks[this.clicks.length-1];if(s&&Math.abs(e-s.x)+Math.abs(t-s.y)<this.thresholdPx&&this.timeoutMs>i-s.timestamp){if(this.clicks.push({x:e,y:t,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:t,timestamp:i}];return!1}}var gl="$copy_autocapture",vl=Gs("[AutoCapture]");function fl(e,t){return t.length>e?t.slice(0,e)+"...":t}function ml(e){if(e.previousElementSibling)return e.previousElementSibling;var t=e;do{t=t.previousSibling}while(t&&!qr(t));return t}function yl(e,t){var s,r,n=t.e,o=t.maskAllElementAttributes,a=t.maskAllText,l=t.elementAttributeIgnoreList,u=t.elementsChainAsString,c=t.disableCaptureUrlHashes;if(!qr(e))return{props:{}};for(var d=[e],h=new Set([e]),_=e;_.parentNode&&!Hr(_,"body")&&jr>d.length;)if(zr(_.parentNode)){var p=_.parentNode.host;if(h.has(p))break;h.add(p),d.push(p),_=p}else{if(!qr(_.parentNode))break;if(h.has(_.parentNode))break;h.add(_.parentNode),d.push(_.parentNode),_=_.parentNode}var g,v,f=[],m={},y=!1,b=!1;if(Qs(d,(e=>{var t=un(e);if(Hr(e,"a")){var i=e.getAttribute("href");y=!!(t&&i&&mn(i))&&(c?Ui(i):i)}ot(Wr(e),"ph-no-capture")&&(b=!0),f.push(function(e,t,i,s,r){void 0===r&&(r=!1);var n=e.tagName.toLowerCase(),o={tag_name:n};Jr.indexOf(n)>-1&&!i&&(o.$el_text="a"===n.toLowerCase()||"button"===n.toLowerCase()?fl(1024,yn(e)):fl(1024,Kr(e)));var a=Wr(e);a.length>0&&(o.classes=a.filter((function(e){return""!==e}))),Qs(e.attributes,(function(i){var n;if((!cn(e)||-1!==["name","id","class","aria-label"].indexOf(i.name))&&(null==s||!s.includes(i.name))&&!t&&mn(i.value)&&(!mt(n=i.name)||"_ngcontent"!==n.substring(0,10)&&"_nghost"!==n.substring(0,7))){var a=i.value;"class"===i.name&&(a=Ur(a).join(" ")),o["attr__"+i.name]=fl(1024,"href"===i.name&&r?Ui(a):a)}}));for(var l=1,u=1,c=e;c=ml(c);)l++,c.tagName===e.tagName&&u++;return o.nth_child=l,o.nth_of_type=u,o}(e,o,a,l,c));var s=function(e){if(!un(e))return{};var t={};return Qs(e.attributes,(function(e){if(e.name&&0===e.name.indexOf("data-ph-capture-attribute")){var i=e.name.replace("data-ph-capture-attribute-",""),s=e.value;i&&s&&mn(s)&&(t[i]=s)}})),t}(e);Js(m,s)})),b)return{props:{},explicitNoCapture:b};if(a||(f[0].$el_text=Hr(e,"a")||Hr(e,"button")?yn(e):Kr(e)),y){var w,S;f[0].attr__href=y;var x=null==(w=Dn(y))?void 0:w.host,E=null==we||null==(S=we.location)?void 0:S.host;x&&E&&x!==E&&(g=y)}return{props:Js({$event_type:n.type,$ce_version:1},u?{}:{$elements:f},{$elements_chain:(v=f,function(e){return e.map((e=>{var t,s,r="";if(e.tag_name&&(r+=e.tag_name),e.attr_class)for(var n of(e.attr_class.sort(),e.attr_class))r+="."+n.replace(/"/g,"");var o=i({},e.text?{text:e.text}:{},{"nth-child":null!==(t=e.nth_child)&&void 0!==t?t:0,"nth-of-type":null!==(s=e.nth_of_type)&&void 0!==s?s:0},e.href?{href:e.href}:{},e.attr_id?{attr_id:e.attr_id}:{},e.attributes),a={};return Ys(o).sort(((e,t)=>e[0].localeCompare(t[0]))).forEach((e=>{var t=e[1];return a[wn(e[0].toString())]=wn(t.toString())})),(r+=":")+Ys(a).map((e=>e[0]+'="'+e[1]+'"')).join("")})).join(";")}(function(e){return e.map((e=>{var t,i,s={text:null==(t=e.$el_text)?void 0:t.slice(0,400),tag_name:e.tag_name,href:null==(i=e.attr__href)?void 0:i.slice(0,2048),attr_class:Sn(e),attr_id:e.attr__id,nth_child:e.nth_child,nth_of_type:e.nth_of_type,attributes:{}};return Ys(e).filter((e=>0===e[0].indexOf("attr__"))).forEach((e=>s.attributes[e[0]]=e[1])),s}))}(v)))},null!=(s=f[0])&&s.$el_text?{$el_text:null==(r=f[0])?void 0:r.$el_text}:{},g&&"click"===n.type?{$external_click_url:g}:{},m)}}class bl{constructor(e){this.name="autocapture",this._initialized=!1,this._isDisabledServerSide=null,this._hasReceivedConfigResponse=!1,this._elementsChainAsString=!1,this._config={enabled:!1,rageclick:!1,maskAllElementAttributes:!1,maskAllText:!1,disableCaptureUrlHashes:!1,remoteRequestsDisabled:!1},this._disposed=!1,this._configSource=e,this._configSource.refresh(this._config),this.rageclicks=new pl(this._config.rageclick),this._elementSelectors=null}setup(e){this._compileUrlPatterns(),this._client=e;var t=e.onRemoteConfig(this.onRemoteConfig.bind(this));this._disposed?t.dispose():(this._remoteConfigSubscription=t,this.startIfEnabled())}dispose(){var e;this._disposed||(this._disposed=!0,this._client=void 0,null==(e=this._remoteConfigSubscription)||e.dispose(),this._remoteConfigSubscription=void 0,this._removeDomEventHandlers())}_refreshConfig(){return this._configSource.refresh(this._config),this._config}_compileUrlPatterns(){var e,t;return this._refreshConfig(),this._config.url_allowlist=null==(e=this._config.url_allowlist)?void 0:e.map((e=>new RegExp(e))),this._config.url_ignorelist=null==(t=this._config.url_ignorelist)?void 0:t.map((e=>new RegExp(e))),this._config}_addDomEventHandlers(){if(this.isBrowserSupported()){if(we&&Ee){var e=this._domEventHandler=e=>{e=e||(null==we?void 0:we.event);try{this._captureEvent(e)}catch(e){vl.error("Failed to capture event",e)}};if(sr(Ee,"submit",e,{capture:!0}),sr(Ee,"change",e,{capture:!0}),sr(Ee,"click",e,{capture:!0}),this._refreshConfig().capture_copied_text){var t=this._copiedTextHandler=e=>{e=e||(null==we?void 0:we.event);try{this._captureEvent(e,gl)}catch(e){vl.error("Failed to capture copy/cut event",e)}};sr(Ee,"copy",t,{capture:!0}),sr(Ee,"cut",t,{capture:!0})}}}else vl.info("Disabling Automatic Event Collection because this browser is not supported")}_removeDomEventHandlers(){this._domEventHandler&&(null==Ee||Ee.removeEventListener("submit",this._domEventHandler,!0),null==Ee||Ee.removeEventListener("change",this._domEventHandler,!0),null==Ee||Ee.removeEventListener("click",this._domEventHandler,!0),this._domEventHandler=void 0),this._copiedTextHandler&&(null==Ee||Ee.removeEventListener("copy",this._copiedTextHandler,!0),null==Ee||Ee.removeEventListener("cut",this._copiedTextHandler,!0),this._copiedTextHandler=void 0),this._initialized=!1}startIfEnabled(){!this._disposed&&this._client&&this.isEnabled&&!this._initialized&&(this._addDomEventHandlers(),this._initialized=!0)}onRemoteConfig(e){if(!this._disposed)if(this._hasReceivedConfigResponse=!0,e.ok){var t=e.config;t.elementsChainAsString&&(this._elementsChainAsString=t.elementsChainAsString);var i,s=t.autocapture_opt_out;Et(s)&&(null==(i=this._client)||i.kv.set(d,s),this._isDisabledServerSide=s),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(e){this._elementSelectors=e}getElementSelectors(e){var t,i=[];return null==(t=this._elementSelectors)||t.forEach((t=>{var s=null==Ee?void 0:Ee.querySelectorAll(t);null==s||s.forEach((s=>{e===s&&i.push(t)}))})),i}get isEnabled(){var e,t;if(this._disposed)return!1;var i=null==(e=this._client)?void 0:e.kv.get(d),s=this._isDisabledServerSide,r=this._refreshConfig(),n=r.remoteRequestsDisabled&&!this._hasReceivedConfigResponse;if(bt(s)&&!Et(i)&&!n)return!1;var o=null!==(t=this._isDisabledServerSide)&&void 0!==t?t:!!i;return!!r.enabled&&!o}_captureEvent(e,t){if(void 0===t&&(t="$autocapture"),this.isEnabled){var i=Qr(e);Nr(i)&&(i=i.parentNode||null);var s,r=this._compileUrlPatterns();"$autocapture"===t&&"click"===e.type&&e instanceof MouseEvent&&r.rageclick&&null!=(s=this.rageclicks)&&s.isRageClick(e.clientX,e.clientY,e.timeStamp||(new Date).getTime())&&on(i,r.rageclick)&&this._captureEvent(e,"$rageclick");var n=t===gl;if(i&&function(e,t,i,s,r,n){var o;if(!we||an(e))return!1;if(null!=i&&i.url_allowlist&&!Vr(i.url_allowlist,n))return!1;if(null!=i&&i.url_ignorelist&&Vr(i.url_ignorelist,n))return!1;if(null!=i&&i.dom_event_allowlist){var a=i.dom_event_allowlist;if(a&&!a.some((e=>t.type===e)))return!1}var l=ln(e,s),u=l.parentIsUsefulElement,c=l.targetElementList;if(!function(e,t){var i=null==t?void 0:t.element_allowlist;if(ft(i))return!0;var s,r=function(e){if(i.some((t=>e.tagName.toLowerCase()===t)))return{v:!0}};for(var n of e)if(s=r(n))return s.v;return!1}(c,i))return!1;if(!Yr(c,null==i?void 0:i.css_selector_allowlist))return!1;if(Yr(c,null!==(o=null==i?void 0:i.css_selector_ignorelist)&&void 0!==o?o:Xr))return!1;try{var d=we.getComputedStyle(e);if(d&&"pointer"===d.getPropertyValue("cursor")&&"click"===t.type)return!0}catch(e){}var h=e.tagName.toLowerCase();switch(h){case"html":return!1;case"form":return(r||["submit"]).indexOf(t.type)>=0;case"input":case"select":case"textarea":return(r||["change","click"]).indexOf(t.type)>=0;default:return u?(r||["click"]).indexOf(t.type)>=0:(r||["click"]).indexOf(t.type)>=0&&(Jr.indexOf(h)>-1||"true"===e.getAttribute("contenteditable"))}}(i,e,r,n,n?["copy","cut"]:void 0,{config:{get_current_url:r.getCurrentUrl}})){var o,a=yl(i,{e:e,maskAllElementAttributes:r.maskAllElementAttributes,maskAllText:r.maskAllText,elementAttributeIgnoreList:r.element_attribute_ignorelist,elementsChainAsString:this._elementsChainAsString,disableCaptureUrlHashes:r.disableCaptureUrlHashes}),l=a.props;if(a.explicitNoCapture)return!1;var u=this.getElementSelectors(i);if(u&&u.length>0&&(l.$element_selectors=u),t===gl){var c,d=Gr(null==we||null==(c=we.getSelection())?void 0:c.toString()),h=e.type||"clipboard";if(!d)return!1;l.$selected_content=d,l.$copy_type=h}return null==(o=this._client)||o.capture(t,l).catch((e=>vl.error("Failed to capture event",e))),!0}}}isBrowserSupported(){return pt(null==Ee?void 0:Ee.querySelectorAll)}}class wl{constructor(e){this._instance=e}refresh(e){var t=this._instance.config,i=gt(t.autocapture)?t.autocapture:void 0;e.enabled=!!t.autocapture,e.rageclick=t.rageclick,e.maskAllElementAttributes=t.mask_all_element_attributes,e.maskAllText=t.mask_all_text,e.disableCaptureUrlHashes=t.disable_capture_url_hashes,e.getCurrentUrl=t.get_current_url,e.remoteRequestsDisabled=this._instance._shouldDisableFlags(),e.url_allowlist=null==i?void 0:i.url_allowlist,e.url_ignorelist=null==i?void 0:i.url_ignorelist,e.dom_event_allowlist=null==i?void 0:i.dom_event_allowlist,e.element_allowlist=null==i?void 0:i.element_allowlist,e.css_selector_allowlist=null==i?void 0:i.css_selector_allowlist,e.css_selector_ignorelist=null==i?void 0:i.css_selector_ignorelist,e.element_attribute_ignorelist=null==i?void 0:i.element_attribute_ignorelist,e.capture_copied_text=null==i?void 0:i.capture_copied_text}}var Sl=Gs("[ExceptionAutocapture]"),xl=()=>{},El=Gs("[TracingHeaders]"),kl=Gs("[Web Vitals]"),Pl=9e5,Cl=["CLS","FCP","INP","LCP"],Il=["INP","LCP"],Fl=["interactionTarget","interactionType","inputDelay","processingDuration","presentationDelay","loadState","target","url","timeToFirstByte","resourceLoadDelay","resourceLoadDuration","elementRenderDelay","largestShiftTarget","largestShiftTime","largestShiftValue","firstByteToFCP"],Tl="disabled",Rl="lazy_loading",Al="awaiting_config",Ll="missing_config";Gs("[SessionRecording]"),Gs("[SessionRecording]");var Ml="[SessionRecording]",$l=Gs(Ml),Ol=Gs("[Heatmaps]");function Dl(e){return gt(e)&&"clientX"in e&&"clientY"in e&&St(e.clientX)&&St(e.clientY)}var Bl=Gs("[Product Tours]"),ql=e=>{var t;return!e.config.disable_product_tours&&!(null==(t=e.persistence)||!t.get_property(m))},Hl=["$set_once","$set"],Nl=Gs("[SiteApps]"),zl="Error while initializing PostHog app with config id ",jl=(e,t)=>null!=e&&e.then?e.then(t):t(e),Ul="SDK is not enabled or survey functionality is not yet loaded",Vl="Disabled. Not loading surveys.";class Wl{constructor(e,t){this.name="surveys",this._surveyEventReceiver=null,this._surveyManager=null,this._isInitializingSurveys=!1,this._surveyCallbacks=[],this._getSurveysInFlightPromise=null,this._lastSurveyRefreshFailedAt=null,this._disposed=!1,this._renderTimeouts=new Set,this.onRemoteConfig=e=>{if(!this._disposed&&!this._config.disableSurveys){if(!e.ok)return Na.warn("Remote config unavailable. Not loading surveys.");var t=e.config.surveys;if(wt(t))return Na.warn("Flags not loaded yet. Not loading surveys.");this._isSurveysEnabled=Et(t)?t:t.length>0,Na.info("flags response received, isSurveysEnabled: "+this._isSurveysEnabled),this.loadIfEnabled()}},this._configSource=e,this._initialClientState=t}setup(e){if(!this._disposed)return this._initializingClient=e,jl(e.kv.initialize(),(()=>{if(this._initializingClient===e&&!this._disposed){this._initializingClient=void 0,this._client=e;var t=e.onRemoteConfig(this.onRemoteConfig);this._disposed?t.dispose():(this._remoteConfigSubscription=t,this.loadIfEnabled())}}))}dispose(){var e,t,i;this._disposed||(this._disposed=!0,this._initializingClient=void 0,this._client=void 0,null==(e=this._remoteConfigSubscription)||e.dispose(),this._remoteConfigSubscription=void 0,null==(t=this._surveyEventReceiver)||t.dispose(),this._surveyEventReceiver=null,null==(i=this._surveyManager)||null==i.dispose||i.dispose(),this._surveyManager=null,this._surveyCallbacks=[],this._getSurveysInFlightPromise=null,this._renderTimeouts.forEach((e=>clearTimeout(e))),this._renderTimeouts.clear())}get _config(){return this._configSource.get()}initialize(){this.loadIfEnabled()}reset(){try{var e;null==(e=this._surveyEventReceiver)||e.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var t=[],i=0;i<localStorage.length;i++){var s=localStorage.key(i);(null!=s&&s.startsWith(za)||null!=s&&s.startsWith("inProgressSurvey_"))&&t.push(s)}t.forEach((e=>localStorage.removeItem(e)))}catch(e){}}loadIfEnabled(){if(!this._disposed&&this._client){var e=this._config;if(!this._surveyManager)if(this._isInitializingSurveys)Na.info("Already initializing surveys, skipping...");else if(e.disableSurveys)Na.info(Vl);else if(e.cookielessMode&&this._configSource.isOptedOut())Na.info("Not loading surveys in cookieless mode without consent.");else{var t=this._configSource.getExtensions();if(t){if(!ft(this._isSurveysEnabled)||e.advancedEnableSurveys){var i=this._isSurveysEnabled||e.advancedEnableSurveys;this._isInitializingSurveys=!0;try{var s=t.generateSurveys;if(s)return this._completeSurveyInitialization(s,i),void(this._isInitializingSurveys=!1);var r=t.loadExternalDependency;if(!r)return this._handleSurveyLoadError(ue),void(this._isInitializingSurveys=!1);r((e=>{try{if(this._disposed)return;var t=this._configSource.getExtensions();e||null==t||!t.generateSurveys?this._handleSurveyLoadError("Could not load surveys script",e):this._completeSurveyInitialization(t.generateSurveys,i)}finally{this._isInitializingSurveys=!1}}))}catch(e){throw this._isInitializingSurveys=!1,this._handleSurveyLoadError("Error initializing surveys",e),e}}}else Na.error("PostHog Extensions not found.")}}}_completeSurveyInitialization(e,t){this._disposed||(this._surveyManager=e(t),this._surveyEventReceiver=this._configSource.createEventReceiver(),Na.info("Surveys loaded successfully"),this._notifySurveyCallbacks({isLoaded:!0}))}_handleSurveyLoadError(e,t){Na.error(e,t),this._notifySurveyCallbacks({isLoaded:!1,error:e})}onSurveysLoaded(e){return this._surveyCallbacks.push(e),this._surveyManager&&this._notifySurveyCallbacks({isLoaded:!0}),()=>{this._surveyCallbacks=this._surveyCallbacks.filter((t=>t!==e))}}getSurveys(e,t){var i;void 0===t&&(t=!1);var s=null!==(i=this._client)&&void 0!==i?i:this._initialClientState;if(s&&!this._disposed){if(this._config.disableSurveys)return Na.info(Vl),e([]);var r=s.kv.get(N);if(r&&!t)return e(r,{isLoaded:!0}),void(this._shouldBackgroundRefreshSurveys()&&this.getSurveys((()=>{}),!0));if(this._getSurveysInFlightPromise)this._getSurveysInFlightPromise.then((t=>{this._disposed||e(t.surveys,t.context)})).catch((e=>Na.error("Error in survey callback",e)));else{var n=this._sendSurveysRequest("/api/surveys/",{method:"GET",query:{token:s.projectToken},sentAt:"query",timeoutMs:this._config.requestTimeoutMs}).then((e=>{try{return this._handleSurveyResponse(s,e)}catch(e){return Na.error("Error processing surveys response",e),this._handleSurveyResponse(s,{statusCode:0,error:e})}}),(e=>this._handleSurveyResponse(s,{statusCode:0,error:e})));this._getSurveysInFlightPromise=n;var o=()=>{this._getSurveysInFlightPromise===n&&(this._getSurveysInFlightPromise=null)};n.then((t=>{o(),this._disposed||e(t.surveys,t.context)}),o).catch((e=>Na.error("Error in survey callback",e)))}}}_sendSurveysRequest(e,t){var i=this._client;return i?i.sendRequest(e,t):new Promise((e=>e({statusCode:0,error:new Error(Ul)})))}_handleSurveyResponse(e,t){if(this._disposed)return{surveys:[],context:{isLoaded:!1,error:Ul}};var i=t.statusCode;if(200!==i||!t.json){var s="Surveys API could not be loaded, status: "+i;return 0!==i?Na.error(s):t.error||Na.warn(s),this._lastSurveyRefreshFailedAt=Date.now(),{surveys:[],context:{isLoaded:!1,error:s}}}this._lastSurveyRefreshFailedAt=null;var r,n=t.json.surveys||[],o=n.filter((e=>function(e){return!(!e.start_date||e.end_date)}(e)&&(Ta(e)||function(e){var t;return!(null==(t=e.conditions)||null==(t=t.actions)||null==(t=t.values)||!t.length)}(e))));return o.length>0&&(null==(r=this._surveyEventReceiver)||r.register(o)),e.kv.set({[N]:n,[z]:Date.now()}),{surveys:n,context:{isLoaded:!0}}}_shouldBackgroundRefreshSurveys(){return this._isSurveyCacheStale()&&!this._getSurveysInFlightPromise&&!this._isSurveyRefreshBackingOff()}_isSurveyCacheStale(){var e,t,i=null==(e=null!==(t=this._client)&&void 0!==t?t:this._initialClientState)?void 0:e.kv.get(z);return St(i)&&Date.now()-i>3e5}_isSurveyRefreshBackingOff(){return St(this._lastSurveyRefreshFailedAt)&&3e5>Date.now()-this._lastSurveyRefreshFailedAt}markSurveyAsSeen(e,t){var i,s={id:e,current_iteration:null!==(i=null==t?void 0:t.iteration)&&void 0!==i?i:null};ja(s);try{localStorage.setItem("lastSeenSurveyDate",(new Date).toISOString())}catch(e){}}_notifySurveyCallbacks(e){for(var t of this._surveyCallbacks)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(e){Na.error("Error in survey callback",e)}}getActiveMatchingSurveys(e,t){if(void 0===t&&(t=!1),!wt(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);Na.warn("init was not called")}_getSurveyById(e){var t=null;return this.getSurveys((i=>{var s;t=null!==(s=i.find((t=>t.id===e)))&&void 0!==s?s:null})),t}_checkSurveyEligibility(e){if(wt(this._surveyManager))return{eligible:!1,reason:Ul};var t="string"==typeof e?this._getSurveyById(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}_checkSurveyRenderability(e){if(wt(this._surveyManager))return{eligible:!1,reason:Ul};var t="string"==typeof e?this._getSurveyById(e):e;return t?this._surveyManager.checkSurveyRenderability(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(wt(this._surveyManager))return Na.warn("init was not called"),{visible:!1,disabledReason:Ul};var t=this._checkSurveyRenderability(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return wt(this._surveyManager)?(Na.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ul})):new Promise((i=>{this.getSurveys((t=>{var s,r=null!==(s=t.find((t=>t.id===e)))&&void 0!==s?s:null;if(r){var n=this._checkSurveyRenderability(r);i({visible:n.eligible,disabledReason:n.reason})}else i({visible:!1,disabledReason:"Survey not found"})}),t)}))}renderSurvey(e,t,i){var s;if(wt(this._surveyManager))Na.warn("init was not called");else{var r="string"==typeof e?this._getSurveyById(e):e;if(null!=r&&r.id)if(Ua.includes(r.type)){var n=null==Ee?void 0:Ee.querySelector(t);if(n)if(null!=(s=r.appearance)&&s.surveyPopupDelaySeconds){Na.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds");var o=setTimeout((()=>{var e,t;this._renderTimeouts.delete(o),this._disposed||(Na.info("Rendering survey "+r.id+" with delay of "+(null==(e=r.appearance)?void 0:e.surveyPopupDelaySeconds)+" seconds"),null==(t=this._surveyManager)||t.renderSurvey(r,n,i),Na.info("Survey "+r.id+" rendered"))}),1e3*r.appearance.surveyPopupDelaySeconds);this._renderTimeouts.add(o)}else this._surveyManager.renderSurvey(r,n,i);else Na.warn("Survey element not found")}else Na.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Na.warn("Survey not found")}}displaySurvey(e,t){var s;if(wt(this._surveyManager))Na.warn("init was not called");else{var r=this._getSurveyById(e);if(r){var n=r;if(null!=(s=r.appearance)&&s.surveyPopupDelaySeconds&&t.ignoreDelay&&(n=i({},r,{appearance:i({},r.appearance,{surveyPopupDelaySeconds:0})})),t.displayType!==yo&&t.initialResponses&&Na.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),!1===t.ignoreConditions){var o=this._checkSurveyEligibility(r);if(!o.eligible)return void Na.warn("Survey is not eligible to be displayed: ",o.reason)}"inline"!==t.displayType?this._surveyManager.handlePopoverSurvey(n,t):this.renderSurvey(n,t.selector,t.properties)}else Na.warn("Survey not found")}}cancelPendingSurvey(e){wt(this._surveyManager)?Na.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e;null==(e=this._surveyManager)||null==e.handlePageUnload||e.handlePageUnload()}}function Gl(e,t,i){if(wt(e))return!1;switch(i){case"exact":return e===t;case"contains":var s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(s,"i").test(e);case"regex":try{return new RegExp(t).test(e)}catch(e){return!1}default:return!1}}class Kl{constructor(e){this._actionRegistry=new Set,this._actionEvents=new Set,this._debugEventEmitter=new Ea,this._checkStep=(e,t)=>this._checkStepEvent(e,t)&&this._checkStepUrl(e,t)&&this._checkStepElement(e,t)&&this._checkStepProperties(e,t),this._checkStepEvent=(e,t)=>null==t||!t.event||(null==e?void 0:e.event)===(null==t?void 0:t.event),this._instance=e}init(){var e,t;ft(null==(e=this._instance)?void 0:e._addCaptureHook)||(this._captureHookUnsubscribe=null==(t=this._instance)?void 0:t._addCaptureHook(((e,t)=>{this.on(e,t)})))}dispose(){var e;null==(e=this._captureHookUnsubscribe)||e.call(this),this._captureHookUnsubscribe=void 0,this._debugEventEmitter=new Ea}register(e){var t,i;if(!ft(null==(t=this._instance)?void 0:t._addCaptureHook)&&(e.forEach((e=>{var t;this._actionRegistry.add(e),null==(t=e.steps)||t.forEach((e=>{this._actionEvents.add((null==e?void 0:e.event)||"")}))})),null!=(i=this._instance)&&i.autocapture)){var s=new Set;this._actionRegistry.forEach((e=>{var t;null==(t=e.steps)||t.forEach((e=>{null!=e&&e.selector&&s.add(e.selector)}))})),this._instance.autocapture.setElementSelectors(s)}}replace(e){this._actionRegistry.clear(),this._actionEvents.clear(),this.register(e)}on(e,t){null!=t&&0!=e.length&&(this._actionEvents.has(e)||this._actionEvents.has(t.event))&&this._actionRegistry.forEach((e=>{this._checkAction(t,e)&&this._debugEventEmitter.emit("actionCaptured",e.name)}))}_addActionHook(e){this.onAction("actionCaptured",(t=>e(t)))}_checkAction(e,t){if(null==(null==t?void 0:t.steps))return!1;for(var i of t.steps)if(this._checkStep(e,i))return!0;return!1}onAction(e,t){return this._debugEventEmitter.on(e,t)}_checkStepUrl(e,t){if(null!=t&&t.url){var i,s=null==e||null==(i=e.properties)?void 0:i.$current_url;if(!s||"string"!=typeof s)return!1;if(!Gl(s,t.url,t.url_matching||"contains"))return!1}return!0}_checkStepElement(e,t){return!!this._checkStepHref(e,t)&&!!this._checkStepText(e,t)&&!!this._checkStepSelector(e,t)}_checkStepHref(e,t){var i;if(null==t||!t.href)return!0;var s=this._getElementsList(e);if(s.length>0)return s.some((e=>Gl(e.href,t.href,t.href_matching||"exact")));var r,n=(null==e||null==(i=e.properties)?void 0:i.$elements_chain)||"";return!!n&&Gl((r=n.match(/(?::|")href="(.*?)"/))?r[1]:"",t.href,t.href_matching||"exact")}_checkStepText(e,t){var i;if(null==t||!t.text)return!0;var s=this._getElementsList(e);if(s.length>0)return s.some((e=>Gl(e.text,t.text,t.text_matching||"exact")||Gl(e.$el_text,t.text,t.text_matching||"exact")));var r,n,o,a=(null==e||null==(i=e.properties)?void 0:i.$elements_chain)||"";return!!a&&(r=function(e){for(var t,i=[],s=/(?::|")text="(.*?)"/g;!wt(t=s.exec(e));)i.includes(t[1])||i.push(t[1]);return i}(a),n=t.text,o=t.text_matching||"exact",r.some((e=>Gl(e,n,o))))}_checkStepSelector(e,t){var i,s;if(null==t||!t.selector)return!0;var r=null==e||null==(i=e.properties)?void 0:i.$element_selectors;if(null!=r&&r.includes(t.selector))return!0;var n=(null==e||null==(s=e.properties)?void 0:s.$elements_chain)||"";if(t.selector_regex&&n)try{return new RegExp(t.selector_regex).test(n)}catch(e){return!1}return!1}_getElementsList(e){var t;return null==(null==e||null==(t=e.properties)?void 0:t.$elements)?[]:null==e?void 0:e.properties.$elements}_checkStepProperties(e,t){return null==t||!t.properties||0===t.properties.length||Ma(t.properties.reduce(((e,t)=>{var i=_t(t.value)?t.value.map(String):null!=t.value?[String(t.value)]:[];return e[t.key]={values:i,operator:t.operator||"exact"},e}),{}),null==e?void 0:e.properties)}}class Ql{constructor(e){var t;this._pendingActivatedItems=[],this._instance=e,this._eventToItems=new Map,this._cancelEventToItems=new Map,this._actionToItems=new Map,this._sessionIdUnsubscribe=null==(t=this._instance)||null==t.onSessionId?void 0:t.onSessionId((e=>this._onSessionIdChanged(e)))}_shouldPersistArmedActivation(e){return!1}_getActivationTimestampsKey(){return null}_writeActivationTimestamps(e){}_clearActivationTimestampsStore(){}_doesEventMatchFilter(e,t){return!!e&&Ma(e.propertyFilters,null==t?void 0:t.properties)}_buildEventToItemMap(e,t){var i=new Map;return e.forEach((e=>{var s;null==(s=e.conditions)||null==(s=s[t])||null==(s=s.values)||s.forEach((t=>{if(null!=t&&t.name){var s=i.get(t.name)||[];s.push(e.id),i.set(t.name,s)}}))})),i}_getMatchingItems(e,t,i){var s=(i===po?this._eventToItems:this._cancelEventToItems).get(e),r=[];return this._getItems((e=>{r=e.filter((e=>null==s?void 0:s.includes(e.id)))})),r.filter((s=>{var r,n=null==(r=s.conditions)||null==(r=r[i])||null==(r=r.values)?void 0:r.find((t=>t.name===e));return this._doesEventMatchFilter(n,t)}))}register(e){this._register(e,!1)}replace(e){this._register(e,!0)}_register(e,t){var i;ft(null==(i=this._instance)?void 0:i._addCaptureHook)||(this._setupEventBasedItems(e,t),this._setupActionBasedItems(e,t))}_setupActionBasedItems(e,t){var i=e.filter((e=>{var t;return null==(t=e.conditions)||null==(t=t.actions)||null==(t=t.values)?void 0:t.length}));if(t&&this._actionToItems.clear(),0!==i.length){this._actionMatcher||(this._actionMatcher=new Kl(this._instance),this._actionMatcher.init(),this._actionMatcher._addActionHook((e=>this.onAction(e))));var s=[];i.forEach((e=>{var t;null==(t=e.conditions)||null==(t=t.actions)||t.values.forEach((t=>{if(s.push(t),t.name){var i,r=null!==(i=this._actionToItems.get(t.name))&&void 0!==i?i:[];r.includes(e.id)||r.push(e.id),this._actionToItems.set(t.name,r)}}))})),t?this._actionMatcher.replace(s):this._actionMatcher.register(s)}else{var r;t&&(null==(r=this._actionMatcher)||r.replace([]))}}_mergeItemMaps(e,t){t.forEach(((t,i)=>{var s,r=null!==(s=e.get(i))&&void 0!==s?s:[];t.forEach((e=>{r.includes(e)||r.push(e)})),e.set(i,r)}))}_setupEventBasedItems(e,t){var i,s,r=e.filter((e=>{var t,i;return(null==(t=e.conditions)?void 0:t.events)&&(null==(i=e.conditions)||null==(i=i.events)||null==(i=i.values)?void 0:i.length)>0})),n=e.filter((e=>{var t,i;return(null==(t=e.conditions)?void 0:t.cancelEvents)&&(null==(i=e.conditions)||null==(i=i.cancelEvents)||null==(i=i.values)?void 0:i.length)>0})),o=this._buildEventToItemMap(e,po),a=this._buildEventToItemMap(e,go);t?(this._eventToItems=o,this._cancelEventToItems=a):(this._mergeItemMaps(this._eventToItems,o),this._mergeItemMaps(this._cancelEventToItems,a)),(0!==r.length||0!==n.length)&&(null!==(i=this._captureHookUnsubscribe)&&void 0!==i||(this._captureHookUnsubscribe=null==(s=this._instance)?void 0:s._addCaptureHook(((e,t)=>{this.onEvent(e,t)}))))}onEvent(e,t){var i,s,r=this._getLogger(),n=(null==t||null==(i=t.properties)?void 0:i.$survey_id)||(null==t||null==(s=t.properties)?void 0:s.$product_tour_id);if(n&&this.getActivatedIds().includes(n)){var o=this._activationOutcome(e,n);if("consume"===o)return r.info("event consumed activated item, removing it",{event:e,itemId:n}),void this._deactivateItems([n]);if("persist"===o)return r.info("shown item promoted to persisted activation",{event:e,itemId:n}),this._persistActivation(n),void this._clearActivationTimestamps([n])}if(this._cancelEventToItems.has(e)){var a=this._getMatchingItems(e,t,go);a.length>0&&(r.info("cancel event matched, cancelling items",{event:e,itemsToCancel:a.map((e=>e.id))}),this._deactivateItems(a.map((e=>e.id))),a.forEach((e=>this._cancelPendingItem(e.id))))}if(this._eventToItems.has(e)){r.info("event name matched",{event:e,eventPayload:t,items:this._eventToItems.get(e)});var l=this._getMatchingItems(e,t,po);this._activateItems(l.map((e=>e.id)))}}onAction(e){this._actionToItems.has(e)&&this._activateItems(this._actionToItems.get(e)||[])}_activateItems(e){var t;if(0!==e.length){var i=!(null==(t=this._instance)||null==t.get_session_id||!t.get_session_id()),s=[];for(var r of e)i&&this._shouldPersistArmedActivation(r)?this._persistActivation(r)&&this._recordActivationTimestamp(r):s.push(r);s.length>0&&(this._pendingActivatedItems=[...new Set([...this._pendingActivatedItems,...s])]),this._getLogger().info("updating activated items",{activatedItems:this.getActivatedIds()})}}_persistActivation(e){this._pendingActivatedItems=this._pendingActivatedItems.filter((t=>t!==e));var t=this._getPersistedActivatedIds();return!t.includes(e)&&(this._setActivatedItems([...t,e]),this._stampActivationSession(),!0)}_deactivateItems(e){var t=new Set(e);this._pendingActivatedItems=this._pendingActivatedItems.filter((e=>!t.has(e)));var i=this._getRawPersistedActivatedIds(),s=i.filter((e=>!t.has(e)));s.length!==i.length&&(this._setActivatedItems(s),0===s.length&&this._clearActivationSession()),this._clearActivationTimestamps(e)}_getRawActivationTimestamps(){var e,t=this._getActivationTimestampsKey();if(!t)return{};var i=null==(e=this._instance)||null==(e=e.persistence)?void 0:e.props[t];return i&&"object"==typeof i?i:{}}_recordActivationTimestamp(e){if(this._getActivationTimestampsKey()){var t=this._getRawActivationTimestamps();this._writeActivationTimestamps(i({},t,{[e]:Date.now()}))}}_clearActivationTimestamps(e){if(this._getActivationTimestampsKey()){var t=this._getRawActivationTimestamps(),i={},s=!1;for(var r of Object.entries(t)){var n=r[0],o=r[1];e.includes(n)?s=!0:i[n]=o}s&&(vt(i)?this._clearActivationTimestampsStore():this._writeActivationTimestamps(i))}}_clearAllActivationTimestamps(){this._getActivationTimestampsKey()&&this._clearActivationTimestampsStore()}getActivationTimestamp(e){if(this._getPersistedActivatedIds().includes(e)){var t=this._getRawActivationTimestamps()[e];return St(t)?t:void 0}}_getRawPersistedActivatedIds(){var e,t=this._getActivatedKey();return(null==(e=this._instance)||null==(e=e.persistence)?void 0:e.props[t])||[]}_getPersistedActivatedIds(){var e,t,i=this._getRawPersistedActivatedIds();if(0===i.length)return[];var s=null==(e=this._instance)||null==(e=e.persistence)?void 0:e.props[this._getActivatedSessionKey()],r=null==(t=this._instance)||null==t.get_session_id?void 0:t.get_session_id();return r&&s===r?i:[]}_stampActivationSession(){var e,t=null==(e=this._instance)||null==e.get_session_id?void 0:e.get_session_id();t&&this._setActivatedSession(t)}_clearActivationSession(){this._clearActivatedSession()}_onSessionIdChanged(e){var t,i=null==(t=this._instance)||null==(t=t.persistence)?void 0:t.props[this._getActivatedSessionKey()];if(i&&i!==e){var s=this._getRawPersistedActivatedIds(),r=this._getRawActivationTimestamps();s.length>0&&(this._setActivatedItems([]),s.filter((e=>St(r[e]))).forEach((e=>this._cancelPendingItem(e)))),this._clearActivationSession(),this._clearAllActivationTimestamps()}}getActivatedIds(){return[...new Set([...this._getPersistedActivatedIds(),...this._pendingActivatedItems])].filter((e=>!this._isItemPermanentlyIneligible(e)))}dispose(){var e,t,i;null==(e=this._sessionIdUnsubscribe)||e.call(this),this._sessionIdUnsubscribe=void 0,null==(t=this._captureHookUnsubscribe)||t.call(this),this._captureHookUnsubscribe=void 0,null==(i=this._actionMatcher)||i.dispose(),this._actionMatcher=void 0}reset(){this._pendingActivatedItems=[],this._getRawPersistedActivatedIds().length>0&&this._setActivatedItems([]),this._clearActivationSession(),this._clearAllActivationTimestamps()}getEventToItemsMap(){return this._eventToItems}_getActionMatcher(){return this._actionMatcher}}class Jl extends Ql{constructor(e){super(e)}_getActivatedKey(){return j}_getActivatedSessionKey(){return U}_getActivationTimestampsKey(){return V}_writeActivationTimestamps(e){var t;null==(t=this._instance)||null==(t=t.persistence)||t.register({[V]:e})}_clearActivationTimestampsStore(){var e;null==(e=this._instance)||null==(e=e.persistence)||e.unregister(V)}_shouldPersistArmedActivation(e){var t,i;this._getItems((t=>{i=t.find((t=>t.id===e))}));var s=null==(t=i)||null==(t=t.appearance)?void 0:t.surveyPopupDelaySeconds;return St(s)&&s>0}_getShownEventName(){return vo}_getItems(e){var t;null==(t=this._instance)||t.getSurveys(e)}_cancelPendingItem(e){var t;null==(t=this._instance)||t.cancelPendingSurvey(e)}_getLogger(){return Na}_setActivatedItems(e){var t;null==(t=this._instance)||null==(t=t.persistence)||t.register({[j]:e})}_setActivatedSession(e){var t;null==(t=this._instance)||null==(t=t.persistence)||t.register({[U]:e})}_clearActivatedSession(){var e;null==(e=this._instance)||null==(e=e.persistence)||e.unregister(U)}_isItemPermanentlyIneligible(){return!1}_activationOutcome(e,t){var i;this._getItems((e=>{i=e.find((e=>e.id===t))}));var s=!i||function(e){var t;return Ta(e)&&!(null==(t=e.conditions)||null==(t=t.events)||!t.repeatedActivation)||"always"===e.schedule}(i);return s?e===vo?"consume":"ignore":e===vo?"persist":e===fo||e===mo?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}class Yl{constructor(e){this._instance=e}initialize(){}get(e){if("string"==typeof e)return this._instance.get_property(e);var t={};for(var i of e){var s=this._instance.get_property(i);ft(s)||(t[i]=s)}return t}set(e,t){this._instance.register("string"==typeof e?{[e]:t}:e)}remove(e){"string"!=typeof e?e.forEach((e=>this._instance.unregister(e))):this._instance.unregister(e)}}class Zl{constructor(e){this._instance=e}get(){var e=this._instance.config;return{disableSurveys:e.disable_surveys,cookielessMode:!!e.cookieless_mode,advancedEnableSurveys:e.advanced_enable_surveys,requestTimeoutMs:e.surveys_request_timeout_ms}}isOptedOut(){return this._instance.consent.isOptedOut()}getExtensions(){var e=null==Le?void 0:Le.__PosthogExtensions__;if(e){var t=e.generateSurveys,i=e.loadExternalDependency;return{generateSurveys:t?e=>t(this._instance,e):void 0,loadExternalDependency:i?e=>i(this._instance,"surveys",e):void 0}}}createEventReceiver(){return new Jl(this._instance)}}var Xl=null!=we&&we.location?Hn(we.location.hash,"__posthog")||Hn(location.hash,"state"):null,eu="_postHogToolbarParams",tu=Gs("[Toolbar]"),iu=Gs("[FeatureFlags]");class su{constructor(e,t){void 0===t&&(t=!1),this._loggedEvaluationEnvironmentsDeprecation=!1,this.update(e,t)}update(e,t){this._snapshot=((e,t)=>{var i,s,r,n;return{bootstrap:{featureFlags:null==(i=e.bootstrap)?void 0:i.featureFlags,featureFlagPayloads:null==(s=e.bootstrap)?void 0:s.featureFlagPayloads},remoteRequestsDisabled:t,featureFlagsDisabled:!!e.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!e.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!e.advanced_feature_flags_dedup_per_session,cacheTtlMs:e.feature_flag_cache_ttl_ms,requestTimeoutMs:e.feature_flag_request_timeout_ms,compression:e.disable_compression?"none":"base64",evaluationContexts:null!==(r=null!==(n=e.evaluation_contexts)&&void 0!==n?n:e.evaluation_environments)&&void 0!==r?r:[],flagKeys:_t(e.flag_keys)?e.flag_keys:void 0}})(e,t),!e.evaluation_environments||e.evaluation_contexts||this._loggedEvaluationEnvironmentsDeprecation||(iu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this._loggedEvaluationEnvironmentsDeprecation=!0),ft(e.flag_keys)||_t(e.flag_keys)||iu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this._snapshot}}var ru=Gs("[FeatureFlags]"),nu=Gs("[FeatureFlags]",{debugEnabled:!0}),ou="\" failed. Feature flags didn't load in time.",au="connection_error",lu=e=>{for(var t={},i=0;e.length>i;i++)t[e[i]]=!0;return t},uu=e=>{var t={};for(var i of Ys(e||{})){var s=i[1];s&&(t[i[0]]=s)}return t},cu=Gs("[Error tracking]"),du=["chrome-extension://","moz-extension://","safari-extension:","safari-web-extension:"],hu=["__firefox__","__gCrWeb"],_u="Refusing to render web experiment since the viewer is a likely bot",pu={icontains:(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())>-1,not_icontains:(e,t)=>-1===t.toLowerCase().indexOf(e.toLowerCase()),regex:(e,t)=>Ra(t,e),not_regex:(e,t)=>!Ra(t,e),exact:(e,t)=>t===e,is_not:(e,t)=>t!==e};class gu{get _config(){return this._instance.config}constructor(e){var t=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(e){void 0===e&&(e=!1),t.getWebExperiments((e=>{gu._logInfo("retrieved web experiments from the server"),t._flagToExperiments=new Map,e.forEach((e=>{if(e.feature_flag_key){var i;t._flagToExperiments&&(gu._logInfo("setting flag key ",e.feature_flag_key," to web experiment ",e),null==(i=t._flagToExperiments)||i.set(e.feature_flag_key,e));var s=t._instance.getFeatureFlag(e.feature_flag_key);mt(s)&&e.variants[s]&&t._applyTransforms(e.name,s,e.variants[s].transforms)}else if(e.variants)for(var r in e.variants){var n=e.variants[r];gu._matchesTestVariant(n,t._instance)&&t._applyTransforms(e.name,r,n.transforms)}}))}),e)},this._instance=e,this._instance.onFeatureFlags((e=>{this.onFeatureFlags(e)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())gu._logInfo(_u);else if(!this._config.disable_web_experiments){if(wt(this._flagToExperiments))return this._flagToExperiments=new Map,this.loadIfEnabled(),void this.previewWebExperiment();gu._logInfo("applying feature flags",e),e.forEach((e=>{var t;if(this._flagToExperiments&&null!=(t=this._flagToExperiments)&&t.has(e)){var i,s=this._instance.getFeatureFlag(e),r=null==(i=this._flagToExperiments)?void 0:i.get(e);s&&null!=r&&r.variants[s]&&this._applyTransforms(r.name,s,r.variants[s].transforms)}}))}}previewWebExperiment(){var e=gu.getWindowLocation();if(null!=e&&e.search){var t=Bn(null==e?void 0:e.search,"__experiment_id"),i=Bn(null==e?void 0:e.search,"__experiment_variant");t&&i&&(gu._logInfo("previewing web experiments "+t+" && "+i),this.getWebExperiments((e=>{this._showPreviewWebExperiment(parseInt(t),i,e)}),!1,!0))}}loadIfEnabled(){this._config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,t,i){if(this._config.disable_web_experiments&&!i)return e([]);var s=this._instance.get_property("$web_experiments");if(s&&!t)return e(s);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._config.token),method:"GET",timestampMode:"query",callback:t=>e(200===t.statusCode&&t.json&&t.json.experiments||[])})}_showPreviewWebExperiment(e,t,i){var s=i.filter((t=>t.id===e));s&&s.length>0&&(gu._logInfo("Previewing web experiment ["+s[0].name+"] with variant ["+t+"]"),this._applyTransforms(s[0].name,t,s[0].variants[t].transforms))}static _matchesTestVariant(e,t){return!wt(e.conditions)&&gu._matchUrlConditions(e,t)&&gu._matchUTMConditions(e)}static _matchUrlConditions(e,t){var i;if(wt(e.conditions)||wt(null==(i=e.conditions)?void 0:i.url))return!0;var s=gu.getWindowLocation();if(s){var r,n,o,a=Lr(t,s.href);return null==(r=e.conditions)||!r.url||pu[null!==(n=null==(o=e.conditions)?void 0:o.urlMatchType)&&void 0!==n?n:"icontains"](e.conditions.url,a)}return!1}static getWindowLocation(){return null==we?void 0:we.location}static _matchUTMConditions(e){var t;if(wt(e.conditions)||wt(null==(t=e.conditions)?void 0:t.utm))return!0;var i=Kn();if(i.utm_source){var s,r,n,o,a,l,u,c,d=null==(s=e.conditions)||null==(s=s.utm)||!s.utm_campaign||(null==(r=e.conditions)||null==(r=r.utm)?void 0:r.utm_campaign)==i.utm_campaign,h=null==(n=e.conditions)||null==(n=n.utm)||!n.utm_source||(null==(o=e.conditions)||null==(o=o.utm)?void 0:o.utm_source)==i.utm_source,_=null==(a=e.conditions)||null==(a=a.utm)||!a.utm_medium||(null==(l=e.conditions)||null==(l=l.utm)?void 0:l.utm_medium)==i.utm_medium,p=null==(u=e.conditions)||null==(u=u.utm)||!u.utm_term||(null==(c=e.conditions)||null==(c=c.utm)?void 0:c.utm_term)==i.utm_term;return d&&_&&p&&h}return!1}static _logInfo(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;t>s;s++)i[s-1]=arguments[s];Ws.info("[WebExperiments] "+e,i)}_applyTransforms(e,t,i){this._is_bot()?gu._logInfo(_u):"control"!==t?i.forEach((i=>{if(i.selector){var s;gu._logInfo("applying transform of variant "+t+" for experiment "+e+" ",i);var r=null==(s=document)?void 0:s.querySelectorAll(i.selector);null==r||r.forEach((e=>{var t=e;i.html&&(t.innerHTML=i.html),i.css&&t.setAttribute("style",i.css)}))}})):gu._logInfo("Control variants leave the page unmodified.")}_is_bot(){return xe&&this._instance?Ia(xe,this._config.custom_blocked_useragents):void 0}}var vu=Gs("[Conversations]"),fu="Conversations not available yet.",mu="console",yu="__posthogHandledLogsRequestError",bu=(e,t)=>{var i=e instanceof Error?e:new Error(t);return i[yu]=!0,i},wu=e=>!!e&&"object"==typeof e&&!0===e[yu],Su={featureFlags:class{constructor(e){this.name="featureFlags",this._override_warning=!1,this.featureFlagEventHandlers=[],this._logger=ru,this._baseEventProperties={},this._eventPropertiesWithFlagValues={},this._reloadingHandlers=[],this._hasLoadedFlags=!1,this._requestInFlight=!1,this._requestGeneration=0,this._reloadingDisabled=!1,this._additionalReloadRequested=!1,this._flagsLoadedFromRemote=!1,this._staleCacheRefreshTriggered=!1,this._consecutiveStatusZeroFailures=0,this._onOnline=()=>{var e=this._hasStatusZeroCircuitBreakerTripped();this._consecutiveStatusZeroFailures=0,e&&this.reloadFeatureFlags()},"get"in e?this._configSource=e:(this._mutableConfigSource=new su(e.config,e._shouldDisableFlags()),this._configSource=this._mutableConfigSource)}updateConfig(e,t){var i;null==(i=this._mutableConfigSource)||i.update(e,t)}setup(e){return this._initializingClient=e,this._logger=e.logger.createLogger("[FeatureFlags]"),jl(e.kv.initialize(),(()=>{this._initializingClient===e&&(this._initializingClient=void 0,this._client=e,this._finishSetup(e))}))}_finishSetup(e){if(this._client===e)return we&&sr(we,"online",this._onOnline),this._dynamicProperties=e.registerDynamicEventProperties((()=>this._isCacheStale()?this._baseEventProperties:this._eventPropertiesWithFlagValues)),this._rebuildEventProperties(),this.initialize()}destroy(){null==we||we.removeEventListener("online",this._onOnline)}dispose(){var e;this._requestGeneration++,this._additionalReloadRequested=!1,this._initializingClient=void 0,this._client&&(this._clearDebouncer(),null==(e=this._dynamicProperties)||e.dispose(),this._dynamicProperties=void 0,this._reloadingHandlers=[],null==we||we.removeEventListener("online",this._onOnline),this._client=void 0)}get _config(){return this._configSource.get()}_prop(e){var t;return null==(t=this._client)?void 0:t.kv.get(e)}_set(e){this._persist((()=>{var t;return null==(t=this._client)?void 0:t.kv.set(e)}))}_remove(e){this._persist((()=>{var t;return null==(t=this._client)?void 0:t.kv.remove(e)}))}_persist(e){try{e()}catch(e){this._logger.error("Failed to update feature flag persistence",e)}}_rebuildEventProperties(){var e={};for(var t of[F,A,L,O]){var s=this._prop(t);ft(s)||(e[t]=s)}this._baseEventProperties=e;var r=i({},e),n=this._prop(I);if(n)for(var o of Object.entries(n))r["$feature/"+o[0]]=o[1];this._eventPropertiesWithFlagValues=r}_isCacheStale(){var e=this._config.cacheTtlMs;if(!e||0>=e)return!1;var t=this._prop(J);return"number"!=typeof t||Date.now()-t>e}_checkAndTriggerStaleRefresh(){return!!this._isCacheStale()&&(this._staleCacheRefreshTriggered||this._requestInFlight||(this._staleCacheRefreshTriggered=!0,this._logger.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}_getValidEvaluationEnvironments(){var e=this._config.evaluationContexts;return null!=e&&e.length?e.filter((e=>{var t=e&&"string"==typeof e&&e.trim().length>0;return t||this._logger.error("Invalid evaluation context found:",e,"Expected non-empty string"),t})):[]}_getValidFlagKeys(){var e=this._config.flagKeys;if(!ft(e))return e.filter((e=>{var t=e&&"string"==typeof e&&e.trim().length>0;return t||this._logger.error("Invalid flag key found:",e,"Expected non-empty string"),t}))}initialize(){var e,t,i=this._config,s=null!==(e=null==(t=i.bootstrap)?void 0:t.featureFlags)&&void 0!==e?e:{};if(Object.keys(s).length){var r,n,o=null!==(r=null==(n=i.bootstrap)?void 0:n.featureFlagPayloads)&&void 0!==r?r:{},a=Object.keys(s).filter((e=>!!s[e])).reduce(((e,t)=>(e[t]=s[t]||!1,e)),{}),l=Object.keys(o).filter((e=>a[e])).reduce(((e,t)=>(e[t]=o[t],e)),{});return this._receivedFeatureFlags({featureFlags:a,featureFlagPayloads:l})}}updateFlags(e,t,s){var r,n,o=null!=s&&s.merge&&null!==(r=this._prop(I))&&void 0!==r?r:{},a=null!=s&&s.merge&&null!==(n=this._prop(A))&&void 0!==n?n:{},l=i({},o,e),u=i({},a,t),c={};for(var d of Object.entries(l)){var h=d[0],_=d[1];c[h]={key:h,enabled:$e(_),variant:Oe(_),reason:void 0,metadata:ft(null==u?void 0:u[h])?void 0:{id:0,version:void 0,description:void 0,payload:u[h]}}}this._receivedFeatureFlags({flags:c})}get hasLoadedFlags(){return this._hasLoadedFlags}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._prop(R),t=this._prop(O),s=this._prop(D);if(!s&&!t)return e||{};var r=Js({},e||{}),n=[...new Set([...Object.keys(s||{}),...Object.keys(t||{})])];for(var o of n){var a,l,u=r[o],c=null==t?void 0:t[o],d=ft(c)?null!==(a=null==u?void 0:u.enabled)&&void 0!==a&&a:!!c,h=ft(c)?null==u?void 0:u.variant:"string"==typeof c?c:void 0,_=null==s?void 0:s[o],p=i({},u,{enabled:d,variant:d?null!=h?h:null==u?void 0:u.variant:void 0});d!==(null==u?void 0:u.enabled)&&(p.original_enabled=null==u?void 0:u.enabled),h!==(null==u?void 0:u.variant)&&(p.original_variant=null==u?void 0:u.variant),_&&(p.metadata=i({},null==u?void 0:u.metadata,{payload:_,original_payload:null==u||null==(l=u.metadata)?void 0:l.payload})),r[o]=p}return this._override_warning||(this._logger.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:s,finalDetails:r}),this._override_warning=!0),r}getAllFeatureFlags(){var e=this.getFlagVariants(),t=this.getFlagPayloads();return Object.keys(e).map((i=>{var s=e[i];return{key:i,enabled:$e(s),variant:Oe(s),payload:Me(t[i])}}))}getFlagVariants(){var e=this._prop(I),t=this._prop(O);if(!t)return e||{};for(var i=Js({},e||{}),s=Object.keys(t),r=0;s.length>r;r++)i[s[r]]=t[s[r]];return this._override_warning||(this._logger.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:t,finalFlags:i}),this._override_warning=!0),i}getFlagPayloads(){var e=this._prop(A),t=this._prop(D);if(!t)return e||{};for(var i=Js({},e||{}),s=Object.keys(t),r=0;s.length>r;r++)i[s[r]]=t[s[r]];return this._override_warning||(this._logger.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:t,finalPayloads:i}),this._override_warning=!0),i}reloadFeatureFlags(){this._reloadingDisabled||this._config.featureFlagsDisabled||this._hasStatusZeroCircuitBreakerTripped()||this._reloadDebouncer||(this._reloadingHandlers.slice().forEach((e=>{try{e()}catch(e){this._logger.error("Error while running feature flags reloading callback",e)}})),this._reloadDebouncer=setTimeout((()=>{this._callFlagsEndpoint()}),5))}_clearDebouncer(){clearTimeout(this._reloadDebouncer),this._reloadDebouncer=void 0}onReloading(e){return this._reloadingHandlers.push(e),()=>{this._reloadingHandlers=this._reloadingHandlers.filter((t=>t!==e))}}ensureFlagsLoaded(){this._hasLoadedFlags||this._requestInFlight||this._reloadDebouncer||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this._reloadingDisabled=e}resetFlagCallReported(){this._remove(G)}_callFlagsEndpoint(e){this._clearDebouncer();var t=this._client;if(t&&!this._config.remoteRequestsDisabled&&!this._hasStatusZeroCircuitBreakerTripped())if(this._requestInFlight)this._additionalReloadRequested=!0;else{var s={token:t.projectToken,distinct_id:t.distinctId,groups:t.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:i({},t.initialPersonProperties,this._prop(B)||{},{$lib:t.library.name,$lib_version:t.library.version}),group_properties:this._prop(q),timezone:io()};ft(t.deviceId)||(s.$device_id=t.deviceId),(null!=e&&e.disableFlags||this._config.featureFlagsDisabled)&&(s.disable_flags=!0);var r=this._getValidEvaluationEnvironments();r.length&&(s.evaluation_contexts=r);var n=this._getValidFlagKeys();ft(n)||(s.flag_keys=n);var o=this._config.onlyEvaluateSurveyFeatureFlags,a="/flags/?v=2"+(o?"&only_evaluate_survey_feature_flags=true":""),l=this._requestGeneration;this._requestInFlight=!0;var u=()=>{this._additionalReloadRequested&&(this._additionalReloadRequested=!1,this._callFlagsEndpoint())},c=e=>{this._requestInFlight=!1,l===this._requestGeneration?(this._set({[Q]:[au]}),this._logger.error("Feature flag request failed",e),u()):u()};try{t.sendRequest(a,{target:"flags",method:"POST",body:s,compression:"base64"===this._config.compression?_o:void 0,sentAt:"body",timeoutMs:this._config.requestTimeoutMs}).then((e=>{var t,i,r=null!==(t=e.json)&&void 0!==t?t:{},n=200!==e.statusCode;if(this._requestInFlight=!1,l===this._requestGeneration){if(this._trackStatusZeroReachability(e.statusCode),n||this._additionalReloadRequested||(this.$anon_distinct_id=void 0),!s.disable_flags||this._additionalReloadRequested){this._flagsLoadedFromRemote=!n;var a=[];e.error?a.push(e.error instanceof Error&&"AbortError"===e.error.name?"timeout":e.error instanceof Error?au:"unknown_error"):200!==e.statusCode&&a.push("api_error_"+e.statusCode),r.errorsWhileComputingFlags&&a.push("errors_while_computing_flags");var c=!(null==(i=r.quotaLimited)||!i.includes("feature_flags"));c&&a.push("quota_limited"),this._set({[Q]:a}),c?this._logger.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):s.disable_flags||this._receivedFeatureFlags(r,n,{partialResponse:o}),u()}}else u()})).catch(c)}catch(e){c(e)}}}_hasStatusZeroCircuitBreakerTripped(){return Nn(this._consecutiveStatusZeroFailures,3)}_trackStatusZeroReachability(e){this._consecutiveStatusZeroFailures=zn(e,this._consecutiveStatusZeroFailures,3,(()=>this._logger.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(e,t){var i;if(void 0===t&&(t={}),!t.fresh||this._flagsLoadedFromRemote)if(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0){if(!this._checkAndTriggerStaleRefresh()){var s=this.getFeatureFlagResult(e,t);return null!==(i=null==s?void 0:s.variant)&&void 0!==i?i:null==s?void 0:s.enabled}}else this._logger.warn('getFeatureFlag for key "'+e+ou)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){var t=this.getFeatureFlagResult(e,{send_event:!1});return null==t?void 0:t.payload}getFeatureFlagResult(e,t){if(void 0===t&&(t={}),!t.fresh||this._flagsLoadedFromRemote)if(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0){if(!this._checkAndTriggerStaleRefresh()){var s,r=this.getFlagVariants(),n=e in r,o=r[e],a=this.getFlagPayloads()[e],l=String(o),u=this._prop(L)||void 0,c=this._prop(J)||void 0,d=this._prop(G)||{};if(this._config.deduplicateCallsPerSession){var h,_=null==(h=this._client)?void 0:h.session.sessionId,p=this._prop(K);_&&_!==p&&(d={},s=_)}if(t.send_event||!("send_event"in t))if(e in d&&d[e].includes(l))s&&this._set({[G]:d,[K]:s});else{var g,v,f,m,y,b,w,S,x,E,k,P;_t(d[e])?d[e].push(l):d[e]=[l],this._set(i({[G]:d},s?{[K]:s}:{}));var C=this.getFeatureFlagDetails(e),I=[...null!==(g=this._prop(Q))&&void 0!==g?g:[]];ft(o)&&I.push("flag_missing");var F={$feature_flag:e,$feature_flag_response:o,$feature_flag_payload:null!=a?a:null,$feature_flag_request_id:u,$feature_flag_evaluated_at:c,$feature_flag_bootstrapped_response:null!==(v=null==(f=this._config.bootstrap)||null==(f=f.featureFlags)?void 0:f[e])&&void 0!==v?v:null,$feature_flag_bootstrapped_payload:null!==(m=null==(y=this._config.bootstrap)||null==(y=y.featureFlagPayloads)?void 0:y[e])&&void 0!==m?m:null,$used_bootstrap_value:!this._flagsLoadedFromRemote};ft(null==C||null==(b=C.metadata)?void 0:b.has_experiment)||(F.$feature_flag_has_experiment=C.metadata.has_experiment),ft(null==C||null==(w=C.metadata)?void 0:w.version)||(F.$feature_flag_version=C.metadata.version);var T,R=null!==(S=null==C||null==(x=C.reason)?void 0:x.description)&&void 0!==S?S:null==C||null==(E=C.reason)?void 0:E.code;R&&(F.$feature_flag_reason=R),null!=C&&null!=(k=C.metadata)&&k.id&&(F.$feature_flag_id=C.metadata.id),ft(null==C?void 0:C.original_variant)&&ft(null==C?void 0:C.original_enabled)||(F.$feature_flag_original_response=ft(C.original_variant)?C.original_enabled:C.original_variant),null!=C&&null!=(P=C.metadata)&&P.original_payload&&(F.$feature_flag_original_payload=null==C||null==(T=C.metadata)?void 0:T.original_payload),I.length&&(F.$feature_flag_error=I.join(",")),this._captureFeatureFlagCalled(F)}else s&&this._set({[G]:d,[K]:s});if(n)return{key:e,enabled:!!o,variant:"string"==typeof o?o:void 0,payload:Me(a)}}}else this._logger.warn('getFeatureFlagResult for key "'+e+ou)}_captureFeatureFlagCalled(e){try{var t;null==(t=this._client)||t.capture("$feature_flag_called",e).catch((e=>{this._logger.error("Failed to capture feature flag call",e)}))}catch(e){this._logger.error("Failed to capture feature flag call",e)}}getRemoteConfigPayload(e,t){this._getRemoteConfigPayload(e,t)}_getRemoteConfigPayload(e,i){var s=this;return t((function*(){var t=s._client;if(t){var r={distinct_id:t.distinctId,token:t.projectToken,person_properties:{$lib:t.library.name,$lib_version:t.library.version}},n=s._getValidEvaluationEnvironments();n.length&&(r.evaluation_contexts=n);var o,a=s._getValidFlagKeys();ft(a)||(r.flag_keys=a);try{var l,u=null==(l=(yield t.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:"base64"===s._config.compression?_o:void 0,sentAt:"body",timeoutMs:s._config.requestTimeoutMs})).json)?void 0:l.featureFlagPayloads;o=(null==u?void 0:u[e])||void 0}catch(e){return void s._logger.error("Remote config feature flag request failed",e)}try{i(o)}catch(e){s._logger.error("Remote config feature flag callback failed",e)}}}))()}isFeatureEnabled(e,t){if(void 0===t&&(t={}),t.fresh&&!this._flagsLoadedFromRemote)return t.defaultValue;if(!(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0))return this._logger.warn('isFeatureEnabled for key "'+e+ou),t.defaultValue;var i=this.getFeatureFlag(e,t);return ft(i)?t.defaultValue:!!i}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((t=>t!==e))}receivedFeatureFlags(e,t,i){this._receivedFeatureFlags(e,t,i)}_receivedFeatureFlags(e,t,s){if(this._client){this._hasLoadedFlags=!0;var r=function(e,t,s,r,n,o){void 0===t&&(t={}),void 0===s&&(s={}),void 0===r&&(r={}),void 0===o&&(o=ru);var a=((e,t)=>{var s=e.flags;return s?i({},e,{featureFlags:Object.fromEntries(Object.keys(s).map((e=>{var t;return[e,null!==(t=s[e].variant)&&void 0!==t?t:s[e].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(s).filter((e=>s[e].enabled)).filter((e=>{var t;return null==(t=s[e].metadata)?void 0:t.payload})).map((e=>{var t;return[e,null==(t=s[e].metadata)?void 0:t.payload]})))}):(e.featureFlags&&t.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),e)})(e,o),l=a.flags,u=a.featureFlags,c=a.featureFlagPayloads;if(u){var d=e.requestId,h=e.evaluatedAt;if(_t(u)){o.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var _={};if(u)for(var p=0;u.length>p;p++)_[u[p]]=!0;return{[F]:u,[I]:_,[M]:!1}}var g=u,v=c,f=l;if(null!=n&&n.partialResponse)g=i({},t,g),v=i({},s,v),f=i({},r,f);else if(e.errorsWhileComputingFlags)if(l){var m=new Set(Object.keys(l).filter((e=>{var t;return!(null!=(t=l[e])&&t.failed)})));g=i({},t,Object.fromEntries(Object.entries(g).filter((e=>m.has(e[0]))))),v=i({},s,Object.fromEntries(Object.entries(v||{}).filter((e=>m.has(e[0]))))),f=i({},r,Object.fromEntries(Object.entries(f||{}).filter((e=>m.has(e[0])))))}else g=i({},t,g),v=i({},s,v),f=i({},r,f);return i({[F]:Object.keys(uu(g)),[I]:g||{},[A]:v||{},[R]:f||{},[M]:!0===e.minimalFlagCalledEvents},d?{[L]:d}:{},h?{[J]:h}:{})}}(e,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),s,this._logger);r&&this._set(r),t||(this._staleCacheRefreshTriggered=!1),this._fireFeatureFlagsCallbacks(t)}}override(e,t){void 0===t&&(t=!1),this._logger.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:t})}overrideFeatureFlags(e){this._overrideFeatureFlags(e)}_overrideFeatureFlags(e){if(this._client){if(!1===e)return this._remove([O,D]),this._fireFeatureFlagsCallbacks(),void nu.info("All overrides cleared");if(_t(e))return this._set({[O]:lu(e)}),this._fireFeatureFlagsCallbacks(),void nu.info("Flag overrides set",{flags:e});if(e&&"object"==typeof e&&("flags"in e||"payloads"in e)){var t,i=e;this._override_warning=Boolean(null!==(t=i.suppressWarning)&&void 0!==t&&t);var s={},r=i.flags,n=i.payloads;return r&&(s[O]=_t(r)?lu(r):r),n&&(s[D]=n),Object.keys(s).length&&this._set(s),!1===r&&!1===n?this._remove([O,D]):!1===r?this._remove(O):!1===n&&this._remove(D),this._fireFeatureFlagsCallbacks(),!1===r?nu.info("Flag overrides cleared"):r&&nu.info("Flag overrides set",{flags:r}),void(!1===n?nu.info("Payload overrides cleared"):n&&nu.info("Payload overrides set",{payloads:n}))}if(e&&"object"==typeof e)return this._set({[O]:e}),this._fireFeatureFlagsCallbacks(),void nu.info("Flag overrides set",{flags:e});this._logger.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:e})}else this._logger.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this._hasLoadedFlags){var t=this._prepareFeatureFlagsForCallbacks(),i=t.flags,s=t.flagVariants;try{e(i,s)}catch(e){this._logger.error("Error while running feature flags callback",e)}}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,s){var r=(this._prop(T)||[]).find((t=>t.flagKey===e)),n={["$feature_enrollment/"+e]:t},o={$feature_flag:e,$feature_enrollment:t,$set:n};r&&(o.$early_access_feature_name=r.name),s&&(o.$feature_enrollment_stage=s);var a=i({},this.getFlagVariants(),{[e]:t});this._set({[F]:Object.keys(uu(a)),[I]:a,[B]:i({},this._prop(B)||{},n)}),this._fireFeatureFlagsCallbacks();try{var l;null==(l=this._client)||l.capture("$feature_enrollment_update",o).catch((e=>{this._logger.error("Failed to capture early access feature enrollment",e)}))}catch(e){this._logger.error("Failed to capture early access feature enrollment",e)}}getEarlyAccessFeatures(e,t,i){void 0===t&&(t=!1);var s=this._prop(T);!s||t?this._getEarlyAccessFeatures(e,i):e(s)}_getEarlyAccessFeatures(e,i){var s=this;return t((function*(){var t=s._client;if(t){var r,n=i?"&"+i.map((e=>"stage="+e)).join("&"):"";try{var o=yield t.sendRequest("/api/early_access_features/?token="+t.projectToken+n,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;s._set({[T]:r=o.json.earlyAccessFeatures})}catch(e){return void s._logger.error("Early access feature request failed",e)}try{e(r)}catch(e){s._logger.error("Early access feature callback failed",e)}}}))()}_prepareFeatureFlagsForCallbacks(){var e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter((e=>t[e])),flagVariants:Object.keys(t).filter((e=>t[e])).reduce(((e,i)=>(e[i]=t[i],e)),{})}}_fireFeatureFlagsCallbacks(e){this._rebuildEventProperties();var t=this._prepareFeatureFlagsForCallbacks(),i=t.flags,s=t.flagVariants;this.featureFlagEventHandlers.forEach((t=>{try{t(i,s,{errorsLoading:e})}catch(e){this._logger.error("Error while running feature flags callback",e)}}))}setPersonPropertiesForFlags(e,t){void 0===t&&(t=!0),this._setPersonPropertiesForFlags(e,t)}_setPersonPropertiesForFlags(e,t){void 0===t&&(t=!0);var s=this._prop(B)||{},r=(null==e?void 0:e.$set)||(null!=e&&e.$set_once?{}:e),n=null==e?void 0:e.$set_once,o={};if(n)for(var a in n)({}).hasOwnProperty.call(n,a)&&(a in s||(o[a]=n[a]));this._set({[B]:i({},s,o,r)}),t&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(e,t){void 0===t&&(t=!0);var s=i({},this._prop(B)||{});e.forEach((e=>{delete s[e]})),this._set({[B]:s}),t&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(e){void 0===e&&(e=!0),this._remove(B),e&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(e,t){void 0===t&&(t=!0);var s=this._prop(q)||{},r=i({},s);for(var n of Object.keys(e))r[n]=i({},s[n],e[n]);this._set({[q]:r}),t&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var t=this._prop(q)||{};this._set({[q]:i({},t,{[e]:{}})})}else this._remove(q)}reset(){this._requestGeneration++,this._additionalReloadRequested=!1,this._baseEventProperties={},this._eventPropertiesWithFlagValues={},this._hasLoadedFlags=!1,this._reloadingDisabled=!1,this._flagsLoadedFromRemote=!1,this.$anon_distinct_id=void 0,this._clearDebouncer(),this._override_warning=!1,this._consecutiveStatusZeroFailures=0}}},xu={sessionRecording:class{get _config(){return this._instance.config}get _persistence(){return this._instance.persistence}get started(){var e;return!(null==(e=this._lazyLoadedSessionRecording)||!e.isStarted)}get status(){var e,t;return this._recordingStatus===Al||this._recordingStatus===Ll?this._recordingStatus:null!==(e=null==(t=this._lazyLoadedSessionRecording)?void 0:t.status)&&void 0!==e?e:this._recordingStatus}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this._recordingStatus=Tl,this._persistFlagsOnSessionListener=void 0,this._sessionRecordingDisposed=!1,this._documentWasEverVisible=(()=>{var e;if(null==Ee||!Ee.visibilityState||"visible"===Ee.visibilityState)return!0;var t=null==we||null==(e=we.performance)||null==e.getEntriesByType?void 0:e.getEntriesByType("visibility-state");return!(null!=t&&t.length)||t.some((e=>"visible"===e.name))})(),this._onVisibilityChange=()=>{var e;"visible"===(null==Ee?void 0:Ee.visibilityState)&&(this._documentWasEverVisible=!0,null==(e=this._lazyLoadedSessionRecording)||null==e.setDocumentWasEverVisible||e.setDocumentWasEverVisible(!0))},this._instance=e,!this._instance.sessionManager)throw $l.error("started without valid sessionManager"),new Error(Ml+" started without valid sessionManager. This is a bug.");if(this._config.cookieless_mode===de)throw new Error(Ml+' cannot be used with cookieless_mode="always"');null!=Ee&&Ee.addEventListener&&sr(Ee,"visibilitychange",this._onVisibilityChange)}initialize(){this.startIfEnabledOrStop()}dispose(){this._sessionRecordingDisposed=!0,null==Ee||null==Ee.removeEventListener||Ee.removeEventListener("visibilitychange",this._onVisibilityChange),this.stopRecording()}get _isRecordingEnabled(){var e,t=!(null==(e=this._instance.get_property(b))||!e.enabled),i=!this._config.disable_session_recording,s=this._config.disable_session_recording||this._instance.consent.isOptedOut();return we&&t&&i&&!s}startIfEnabledOrStop(e){var t;if(!(this._sessionRecordingDisposed||this._isRecordingEnabled&&null!=(t=this._lazyLoadedSessionRecording)&&t.isStarted)){var i=!ft(Object.assign)&&!ft(Array.from);this._isRecordingEnabled&&i?(this._lazyLoadAndStart(e),$l.info("starting")):(this._recordingStatus=Tl,this.stopRecording())}}_lazyLoadAndStart(e){var t,i,s;this._isRecordingEnabled&&(this._recordingStatus!==Al&&this._recordingStatus!==Ll&&(this._recordingStatus=Rl),null!=Le&&null!=(t=Le.__PosthogExtensions__)&&null!=(t=t.rrweb)&&t.record&&null!=(i=Le.__PosthogExtensions__)&&i.initSessionRecording?this._onScriptLoaded(e):null==(s=Le.__PosthogExtensions__)||null==s.loadExternalDependency||s.loadExternalDependency(this._instance,this._scriptName,(t=>{if(t)return this._instance.register_for_session({[le]:!0}),$l.error("could not load recorder",t);this._onScriptLoaded(e)})))}stopRecording(){var e,t;null==(e=this._persistFlagsOnSessionListener)||e.call(this),this._persistFlagsOnSessionListener=void 0,null==(t=this._lazyLoadedSessionRecording)||t.stop()}_discardRecording(){var e,t;null==(e=this._persistFlagsOnSessionListener)||e.call(this),this._persistFlagsOnSessionListener=void 0,null==(t=this._lazyLoadedSessionRecording)||t.discard()}_resetSampling(){var e,t;null==(e=this._persistence)||e.unregister(C),null==(t=this._persistence)||t.unregister(w)}_validateSampleRate(e,t){if(wt(e))return null;var i,s=St(e)?e:parseFloat(e);return"number"!=typeof(i=s)||!Number.isFinite(i)||0>i||i>1?($l.warn(t+" must be between 0 and 1. Ignoring invalid value:",e),null):s}_persistRemoteConfig(e){if(this._persistence){var t,s,r=this._persistence,n=()=>{var t,s=!1===e.sessionRecording?void 0:e.sessionRecording,n=this._validateSampleRate(null==(t=this._config.session_recording)?void 0:t.sampleRate,"session_recording.sampleRate"),o=this._validateSampleRate(null==s?void 0:s.sampleRate,"remote config sampleRate"),a=null!=n?n:o;wt(a)&&this._resetSampling();var l=null==s?void 0:s.minimumDurationMilliseconds;r.register({[b]:i({cache_timestamp:Date.now(),enabled:!!s},s,{networkPayloadCapture:i({capturePerformance:e.capturePerformance},null==s?void 0:s.networkPayloadCapture),canvasRecording:{enabled:null==s?void 0:s.recordCanvas,fps:null==s?void 0:s.canvasFps,quality:null==s?void 0:s.canvasQuality},sampleRate:a,minimumDurationMilliseconds:ft(l)?null:l,endpoint:null==s?void 0:s.endpoint,triggerMatchType:null==s?void 0:s.triggerMatchType,masking:null==s?void 0:s.masking,urlTriggers:null==s?void 0:s.urlTriggers,version:null==s?void 0:s.version,triggerGroups:null==s?void 0:s.triggerGroups})})};n(),null==(t=this._persistFlagsOnSessionListener)||t.call(this),this._persistFlagsOnSessionListener=null==(s=this._instance.sessionManager)?void 0:s.onSessionId(n)}}onRemoteConfig(e){var t=e.ok?e.config:void 0;return t&&"sessionRecording"in t?!1===t.sessionRecording?(this._persistRemoteConfig(t),void this._discardRecording()):(this._persistRemoteConfig(t),void this.startIfEnabledOrStop()):(this._recordingStatus===Al&&(this._recordingStatus=Ll,$l.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(e,t){var i;void 0===t&&(t="log"),null!=(i=this._lazyLoadedSessionRecording)&&i.log?this._lazyLoadedSessionRecording.log(e,t):$l.warn("log called before recorder was ready")}get _scriptName(){var e,t,i=null==(e=this._instance)||null==(e=e.persistence)?void 0:e.get_property(b);return(null==i||null==(t=i.scriptConfig)?void 0:t.script)||"lazy-recorder"}_isRemoteConfigFresh(){var e,t=this._instance.get_property(b);if(!t)return!1;try{e="object"==typeof t?t:JSON.parse(t)}catch(e){return $l.warn("persisted remote config for session recording is invalid and will be ignored",e),!1}return!wt(e.cache_timestamp)&&36e5>=Date.now()-e.cache_timestamp}_onScriptLoaded(e){var t,i,s;if(!this._sessionRecordingDisposed){if(null==(t=Le.__PosthogExtensions__)||!t.initSessionRecording)return $l.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[le]:!0});var r;if(this._lazyLoadedSessionRecording||(this._lazyLoadedSessionRecording=null==(r=Le.__PosthogExtensions__)?void 0:r.initSessionRecording(this._instance,this._documentWasEverVisible),this._lazyLoadedSessionRecording._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this._isRemoteConfigFresh()){if(this._recordingStatus===Ll||this._recordingStatus===Al)return;return this._recordingStatus=Al,$l.info("persisted remote config is stale, requesting fresh config before starting"),void new xo(this._instance).load()}this._recordingStatus=Rl,null==(i=(s=this._lazyLoadedSessionRecording).setDocumentWasEverVisible)||i.call(s,this._documentWasEverVisible),this._lazyLoadedSessionRecording.start(e)}}onRRwebEmit(e){var t;null==(t=this._lazyLoadedSessionRecording)||null==t.onRRwebEmit||t.onRRwebEmit(e)}overrideLinkedFlag(){var e,t;this._lazyLoadedSessionRecording||null==(t=this._persistence)||t.register({[x]:!0}),null==(e=this._lazyLoadedSessionRecording)||e.overrideLinkedFlag()}overrideSampling(){var e,t;this._lazyLoadedSessionRecording||null==(t=this._persistence)||t.register({[S]:!0}),null==(e=this._lazyLoadedSessionRecording)||e.overrideSampling()}overrideTrigger(e){var t,i;this._lazyLoadedSessionRecording||null==(i=this._persistence)||i.register({["url"===e?E:k]:!0}),null==(t=this._lazyLoadedSessionRecording)||t.overrideTrigger(e)}get sdkDebugProperties(){var e;return(null==(e=this._lazyLoadedSessionRecording)?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,t){var i;return!(null==(i=this._lazyLoadedSessionRecording)||!i.tryAddCustomEvent(e,t))}}},Eu={autocapture:class extends bl{constructor(e){super(new wl(e)),this.instance=e}},historyAutocapture:class{constructor(e){this._instance=e,this._lastLocation=this._getCurrentLocation()}initialize(){this.startIfEnabled()}get isEnabled(){var e=this._getCaptureOptions();return!!(e.path||e.search||this._shouldCaptureHashChanges(e))}startIfEnabled(){this.isEnabled&&(Ws.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}startIfEnabledOrStop(){this.stop(),this._lastLocation=this._getCurrentLocation(),this.startIfEnabled()}stop(){this._popstateListener&&this._popstateListener(),this._popstateListener=void 0,this._hashchangeListener&&this._hashchangeListener(),this._hashchangeListener=void 0,Ws.info("History API monitoring stopped")}monitorHistoryChanges(){we&&we.history&&(this._patchHistoryMethod("pushState"),this._patchHistoryMethod("replaceState"),this._setupPopstateListener(),this._shouldCaptureHashChanges()&&this._setupHashchangeListener())}_patchHistoryMethod(e){var t;if(we&&(null==(t=we.history[e])||!t.__posthog_wrapped__)){var i=this;!function(e,t,i){try{if(!(t in e))return xl;var s={next:e[t]},r=i((function(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];return s.next.apply(this,t)}));return pt(r)&&(r.prototype=r.prototype||{},Object.defineProperties(r,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:s}})),e[t]=r,()=>{if(e[t]!==r)for(var i=e[t];pt(i)&&i.__posthog_layer__;){var n=i.__posthog_layer__;if(n.next===r)return void(n.next=s.next);i=n.next}else e[t]=s.next}}catch(e){return xl}}(we.history,e,(t=>function(s,r,n){t.call(this,s,r,n),i._capturePageview(e)}))}}_getCurrentLocation(){var e=null==we?void 0:we.location;if(null!=e&&e.pathname)return{pathname:e.pathname,search:e.search,hash:e.hash}}_getCaptureOptions(){var e=this._instance.config.capture_pageview;return"history_change"===e?{path:!0}:gt(e)?e:{}}_shouldCaptureHashChanges(e){return void 0===e&&(e=this._getCaptureOptions()),!!e.hash&&!this._instance.config.disable_capture_url_hashes}_hasLocationChanged(e){var t=this._getCaptureOptions(),i=this._lastLocation;return!(!i||!(t.path&&e.pathname!==i.pathname||t.search&&e.search!==i.search||this._shouldCaptureHashChanges(t)&&e.hash!==i.hash))}_capturePageview(e){try{var t=this._getCurrentLocation();if(!t)return;this._hasLocationChanged(t)&&this._instance.capture(fe,{navigation_type:e}),this._lastLocation=t}catch(t){Ws.error("Error capturing "+e+" pageview",t)}}_setupPopstateListener(){if(!this._popstateListener){var e=()=>{this._capturePageview("popstate")};sr(we,"popstate",e),this._popstateListener=()=>{we&&we.removeEventListener("popstate",e)}}}_setupHashchangeListener(){if(!this._hashchangeListener){var e=()=>{this._capturePageview("hashchange")};sr(we,"hashchange",e),this._hashchangeListener=()=>{we&&we.removeEventListener("hashchange",e)}}}},heatmaps:class{get _config(){return this.instance.config}constructor(e){var t;this._enabledServerSide=!1,this._initialized=!1,this._flushInterval=null,this.instance=e,this._enabledServerSide=!(null==(t=this.instance.persistence)||!t.props[h]),this.rageclicks=new pl(e.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var e=5e3;return gt(this._config.capture_heatmaps)&&this._config.capture_heatmaps.flush_interval_milliseconds&&(e=this._config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return wt(this._config.capture_heatmaps)?wt(this._config.enable_heatmaps)?this._enabledServerSide:this._config.enable_heatmaps:!1!==this._config.capture_heatmaps}startIfEnabled(){if(this.isEnabled){if(this._initialized)return;Ol.info("starting..."),this._setupListeners(),this._onVisibilityChange()}else{var e;clearInterval(null!==(e=this._flushInterval)&&void 0!==e?e:void 0),this._removeListeners(),this.getAndClearBuffer()}}onRemoteConfig(e){if(e.ok){var t=e.config;if("heatmaps"in t){var i=!!t.heatmaps;this.instance.persistence&&this.instance.persistence.register({[h]:i}),this._enabledServerSide=i,this.startIfEnabled()}}}getAndClearBuffer(){var e=this._buffer;return this._buffer=void 0,e}_onDeadClick(e){Dl(e.originalEvent)&&this._onClick(e.originalEvent,"deadclick")}_onVisibilityChange(){this._flushInterval&&clearInterval(this._flushInterval),this._flushInterval=function(e){return"visible"===(null==e?void 0:e.visibilityState)}(Ee)?setInterval(this._flush.bind(this),this.flushIntervalMilliseconds):null}_setupListeners(){we&&Ee&&(this._flushHandler=this._flush.bind(this),sr(we,ve,this._flushHandler),this._onClickHandler=e=>this._onClick(e||(null==we?void 0:we.event)),sr(Ee,"click",this._onClickHandler,{capture:!0}),this._onMouseMoveHandler=e=>this._onMouseMove(e||(null==we?void 0:we.event)),sr(Ee,"mousemove",this._onMouseMoveHandler,{capture:!0}),this._deadClicksCapture=new Pn(this.instance,En,this._onDeadClick.bind(this)),this._deadClicksCapture.startIfEnabledOrStop(),this._onVisibilityChange_handler=this._onVisibilityChange.bind(this),sr(Ee,ge,this._onVisibilityChange_handler),this._initialized=!0)}_removeListeners(){var e;we&&Ee&&(this._flushHandler&&we.removeEventListener(ve,this._flushHandler),this._onClickHandler&&Ee.removeEventListener("click",this._onClickHandler,{capture:!0}),this._onMouseMoveHandler&&Ee.removeEventListener("mousemove",this._onMouseMoveHandler,{capture:!0}),this._onVisibilityChange_handler&&Ee.removeEventListener(ge,this._onVisibilityChange_handler),clearTimeout(this._mouseMoveTimeout),null==(e=this._deadClicksCapture)||e.stop(),this._initialized=!1)}_getProperties(e,t){var i=this.instance.scrollManager.scrollY(),s=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),n=function(e,t,i){for(var s=e;s&&qr(s)&&!Hr(s,"body");){if(s===i)return!1;var r=void 0;try{var n,o,a;r=null==(n=null!==(o=null==(a=s.ownerDocument)?void 0:a.defaultView)&&void 0!==o?o:we)?void 0:n.getComputedStyle(s).position}catch(e){return!1}if(ot(t,r))return!0;s=Zr(s)}return!1}(Qr(e),["fixed","sticky"],r);return{x:e.clientX+(n?0:s),y:e.clientY+(n?0:i),target_fixed:n,type:t}}_onClick(e,t){var s;if(void 0===t&&(t="click"),!Br(e.target)&&Dl(e)){var r=this._getProperties(e,t);null!=(s=this.rageclicks)&&s.isRageClick(e.clientX,e.clientY,(new Date).getTime())&&on(Qr(e),this.instance.config.rageclick)&&this._capture(i({},r,{type:"rageclick"})),this._capture(r)}}_onMouseMove(e){!Br(e.target)&&Dl(e)&&(clearTimeout(this._mouseMoveTimeout),this._mouseMoveTimeout=setTimeout((()=>{this._capture(this._getProperties(e,"mousemove"))}),500))}_capture(e){if(we){var t=this._config.disable_capture_url_hashes?Ui(we.location.href):we.location.href,i=this._config.custom_personal_data_properties,s=this._config.mask_personal_data_properties?[...Un,...i||[]]:[],r=qn(t,s,Wn);this._buffer=this._buffer||{},this._buffer[r]||(this._buffer[r]=[]),this._buffer[r].push(e)}}_flush(){this._buffer&&!vt(this._buffer)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Pn,webVitalsAutocapture:class{constructor(e){var t;this._enabledServerSide=!1,this._initialized=!1,this._buffer={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this._flushToCapture=()=>{clearTimeout(this._delayedFlushTimer),this._delayedFlushTimer=void 0,0!==this._buffer.metrics.length&&(this._instance.capture("$web_vitals",i({$current_url:this._buffer.url},this._buffer.metrics.reduce(((e,t)=>i({},e,{["$web_vitals_"+t.name+"_event"]:i({},t),["$web_vitals_"+t.name+"_value"]:t.value})),{}))),this._buffer={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this._addToBuffer=e=>{var t;if(this._buffer=this._buffer||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},wt(null==e?void 0:e.name)||wt(null==e?void 0:e.value))kl.error("Invalid metric received",e);else{var s="string"==typeof e.navigationURL?e.navigationURL:void 0,r=this._maskedURL(s);if(!ft(r)){var n=St(e.navigationId)||"string"==typeof e.navigationId?"navigation:"+e.navigationId:"url:"+r;if(!this._maxAllowedValue||this._maxAllowedValue>e.value){this._buffer.navigationKey!==n&&(this._flushToCapture(),this._delayedFlushTimer=setTimeout(this._flushToCapture,this.flushToCaptureTimeoutMs)),ft(this._buffer.navigationKey)&&(this._buffer.navigationKey=n,this._buffer.url=r),this._buffer.firstMetricTimestamp=ft(this._buffer.firstMetricTimestamp)?Date.now():this._buffer.firstMetricTimestamp;var o=null==(t=this._instance.sessionManager)?void 0:t.checkAndGetSessionAndWindowId(!0),a=i({},e,s?{navigationURL:r}:{},{$current_url:r,timestamp:Date.now()});if(delete a.entries,gt(e.attribution)&&this.attributionMetrics.indexOf(e.name)>-1){var l={};for(var u of Fl){var c="url"===u&&"string"==typeof e.attribution[u]?this._maskedURL(e.attribution[u]):e.attribution[u];ft(c)||(l[u]=c)}a.attribution=l}else delete a.attribution;ft(o)||(a.$session_id=o.sessionId,a.$window_id=o.windowId),this._buffer.metrics.push(a),this._buffer.metrics.length===this.allowedMetrics.length&&this._flushToCapture()}else kl.error("Ignoring metric with value >= "+this._maxAllowedValue,e)}}},this._startCapturing=()=>{if(!this._initialized){var e,t,s,r,n=!1,o=Le.__PosthogExtensions__,a=null==o?void 0:o.postHogWebVitalsCallbacksByFlavor,l=(null==a?void 0:a[this._callbackFlavor])||("web-vitals"===this._callbackFlavor&&ft(a)?null==o?void 0:o.postHogWebVitalsCallbacks:void 0);if(!ft(l)){var u=l.withoutAttribution,c=this.attributionMetrics;n=!ft(u),e=c.indexOf("LCP")>-1?l.onLCP:(null==u?void 0:u.onLCP)||l.onLCP,t=c.indexOf("CLS")>-1?l.onCLS:(null==u?void 0:u.onCLS)||l.onCLS,s=c.indexOf("FCP")>-1?l.onFCP:(null==u?void 0:u.onFCP)||l.onFCP,r=c.indexOf("INP")>-1?l.onINP:(null==u?void 0:u.onINP)||l.onINP}if(e&&t&&s&&r){var d={reportSoftNavs:this.useSoftNavs},h=n&&this.attributionMetrics.indexOf("INP")>-1?i({},d,{includeProcessedEventEntries:!1}):d;this.allowedMetrics.indexOf("LCP")>-1&&e(this._addToBuffer.bind(this),d),this.allowedMetrics.indexOf("CLS")>-1&&t(this._addToBuffer.bind(this),d),this.allowedMetrics.indexOf("FCP")>-1&&s(this._addToBuffer.bind(this),d),this.allowedMetrics.indexOf("INP")>-1&&r(this._addToBuffer.bind(this),h),this._initialized=!0}else kl.error("web vitals callbacks not loaded - not starting")}},this._instance=e,this._enabledServerSide=!(null==(t=this._instance.persistence)||!t.props[v]),this.startIfEnabled()}get _perfConfig(){return this._instance.config.capture_performance}get allowedMetrics(){var e,t,i=gt(this._perfConfig)?null==(e=this._perfConfig)?void 0:e.web_vitals_allowed_metrics:void 0;return wt(i)?(null==(t=this._instance.persistence)?void 0:t.props[y])||Cl:i}get flushToCaptureTimeoutMs(){return(gt(this._perfConfig)?this._perfConfig.web_vitals_delayed_flush_ms:void 0)||5e3}get attributionMetrics(){var e=gt(this._perfConfig)?this._perfConfig.web_vitals_attribution:void 0;return Et(e)?e?Cl:[]:_t(e)?e:Il}get useAttribution(){return this.attributionMetrics.length>0}get useSoftNavs(){var e=gt(this._perfConfig)?this._perfConfig.__preview_web_vitals_soft_navs:void 0;return null!=e&&e}get _maxAllowedValue(){var e=gt(this._perfConfig)&&St(this._perfConfig.__web_vitals_max_value)?this._perfConfig.__web_vitals_max_value:Pl;return e>0&&6e4>=e?Pl:e}get isEnabled(){var e=null==ke?void 0:ke.protocol;if("http:"!==e&&"https:"!==e)return kl.info("Web Vitals are disabled on non-http/https protocols"),!1;var t=gt(this._perfConfig)?this._perfConfig.web_vitals:Et(this._perfConfig)?this._perfConfig:void 0;return Et(t)?t:this._enabledServerSide}startIfEnabled(){this.isEnabled&&!this._initialized&&(kl.info("enabled, starting..."),this._loadScript(this._startCapturing))}onRemoteConfig(e){if(e.ok){var t=e.config;if("capturePerformance"in t){var i=gt(t.capturePerformance)&&!!t.capturePerformance.web_vitals,s=gt(t.capturePerformance)?t.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[v]:i}),this._instance.persistence.register({[y]:s})),this._enabledServerSide=i,this.startIfEnabled()}}}get _callbackFlavor(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}_loadScript(e){var t=Le.__PosthogExtensions__,i=this._callbackFlavor,s=null==t?void 0:t.postHogWebVitalsCallbacksByFlavor;null!=s&&s[i]||"web-vitals"===i&&ft(s)&&null!=t&&t.postHogWebVitalsCallbacks?e():null==t||null==t.loadExternalDependency||t.loadExternalDependency(this._instance,i,(t=>{t?kl.error("failed to load script",t):e()}))}_maskedURL(e){var t=e||(null==we?void 0:we.location.href);if(t){var i=this._instance.config.disable_capture_url_hashes?Ui(t):t,s=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...Un,...s||[]]:[];return qn(i,r,Wn)}kl.error("Could not determine current URL")}}},ku={exceptionObserver:class{constructor(e){var t;this._startCapturing=()=>{var e;if(we&&this.isEnabled&&null!=(e=Le.__PosthogExtensions__)&&e.errorWrappingFunctions){var t=Le.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=Le.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=Le.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this._unwrapOnError&&this._config.capture_unhandled_errors&&(this._unwrapOnError=t(this.captureException.bind(this))),!this._unwrapUnhandledRejection&&this._config.capture_unhandled_rejections&&(this._unwrapUnhandledRejection=i(this.captureException.bind(this))),!this._unwrapConsoleError&&this._config.capture_console_errors&&(this._unwrapConsoleError=s(this.captureException.bind(this)))}catch(e){Sl.error("failed to start",e),this._stopCapturing()}}},this._instance=e,this._remoteEnabled=!(null==(t=this._instance.persistence)||!t.props[_]),this._rateLimiter=new Dt(i({},function(e){var t,i,s,r;return void 0===e&&(e={}),{refillRate:null!==(t=null!==(i=e.exceptionRateLimiterRefillRate)&&void 0!==i?i:e.__exceptionRateLimiterRefillRate)&&void 0!==t?t:1,bucketSize:null!==(s=null!==(r=e.exceptionRateLimiterBucketSize)&&void 0!==r?r:e.__exceptionRateLimiterBucketSize)&&void 0!==s?s:10}}(this._instance.config.error_tracking),{refillInterval:1e4,_logger:Sl})),this._config=this._requiredConfig(),this.startIfEnabledOrStop()}_requiredConfig(){var e=this._instance.config.capture_exceptions,t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return gt(e)?t=i({},t,e):(ft(e)?this._remoteEnabled:e)&&(t=i({},t,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),t}get isEnabled(){return this._config.capture_console_errors||this._config.capture_unhandled_errors||this._config.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Sl.info("enabled"),this._stopCapturing(),this._loadScript(this._startCapturing)):this._stopCapturing()}_loadScript(e){var t,i;null!=(t=Le.__PosthogExtensions__)&&t.errorWrappingFunctions?e():null==(i=Le.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,"exception-autocapture",(t=>{if(t)return Sl.error("failed to load script",t);e()}))}_stopCapturing(){var e,t,i;null==(e=this._unwrapOnError)||e.call(this),this._unwrapOnError=void 0,null==(t=this._unwrapUnhandledRejection)||t.call(this),this._unwrapUnhandledRejection=void 0,null==(i=this._unwrapConsoleError)||i.call(this),this._unwrapConsoleError=void 0}onRemoteConfig(e){if(e.ok){var t=e.config;"autocaptureExceptions"in t&&(this._remoteEnabled=!!t.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[_]:this._remoteEnabled}),this._config=this._requiredConfig(),this.startIfEnabledOrStop())}}onConfigChange(){this._config=this._requiredConfig()}captureException(e){var t,i,s,r=null!==(t=null==e||null==(i=e.$exception_list)||null==(i=i[0])?void 0:i.type)&&void 0!==t?t:"Exception";this._rateLimiter.consumeRateLimit(r)?Sl.info("Skipping exception capture because of client rate limiting.",{exception:r}):null==(s=this._instance.exceptions)||s.sendExceptionEvent(e)}},exceptions:class{constructor(e){var t,s;this._suppressionRules=[],this._errorPropertiesBuilder=new gs([new Cs,new Ds,new Fs,new Is,new $s,new Ms,new Rs,new Os],function(e){for(var t=arguments.length,s=new Array(t>1?t-1:0),r=1;t>r;r++)s[r-1]=arguments[r];return function(t,r){void 0===r&&(r=0);for(var n=[],o=t.split("\n"),a=r;o.length>a;a++){var l=o[a];if(1024>=l.length){var u=Ps.test(l)?l.replace(Ps,"$1"):l;if(!u.match(/\S*Error: /)){for(var c of s){var d=c(u,e);if(d){n.push(d);break}}if(n.length>=50)break}}}return function(e){if(!e.length)return[];var t=Array.from(e);return t.reverse(),t.slice(0,50).map((e=>{return i({},e,{filename:e.filename||(s=t,s[s.length-1]||{}).filename,function:e.function||vs});var s}))}(n)}}("web:javascript",Ss,ks)),this._instance=e,this._suppressionRules=null!==(t=null==(s=this._instance.persistence)?void 0:s.get_property(p))&&void 0!==t?t:[],this._exceptionStepsConfig=zs(this._getExceptionStepsConfig()),this._exceptionStepsBuffer=new js(this._exceptionStepsConfig)}onConfigChange(){this._exceptionStepsConfig=zs(this._getExceptionStepsConfig()),this._exceptionStepsBuffer.setConfig(this._exceptionStepsConfig)}onRemoteConfig(e){var t,i,s;if(e.ok){var r=e.config;if("errorTracking"in r){var n=null!==(t=null==(i=r.errorTracking)?void 0:i.suppressionRules)&&void 0!==t?t:[],o=null==(s=r.errorTracking)?void 0:s.captureExtensionExceptions;this._suppressionRules=n,this._instance.persistence&&this._instance.persistence.register({[p]:this._suppressionRules,[g]:o})}}}get _captureExtensionExceptions(){var e,t=!!this._instance.get_property(g),i=this._instance.config.error_tracking.captureExtensionExceptions;return null!==(e=null!=i?i:t)&&void 0!==e&&e}buildProperties(e,t){return this._errorPropertiesBuilder.buildFromUnknown(e,{syntheticException:null==t?void 0:t.syntheticException,mechanism:{handled:null==t?void 0:t.handled}})}addExceptionStep(e,t){if(this._exceptionStepsConfig.enabled)try{if(!mt(e)||0===e.trim().length)return void cu.warn("Ignoring exception step because message must be a non-empty string");var s=function(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};var t=[];return{sanitizedProperties:Object.keys(e).reduce(((i,s)=>Hs.has(s)?(t.push(s),i):(i[s]=e[s],i)),{}),droppedKeys:t}}(this._coerceExceptionStepProperties(t)),r=s.sanitizedProperties,n=s.droppedKeys;n.length>0&&cu.warn("Ignoring reserved exception step fields",{droppedKeys:n}),this._exceptionStepsBuffer.add(i({[Bs]:e,[qs]:(new Date).toISOString()},r))}catch(e){cu.error("Failed to add exception step. Ignoring breadcrumb.",e)}}sendExceptionEvent(e){try{var t=e.$exception_list;if(this._isExceptionList(t)){if(this._matchesSuppressionRule(t))return this._addDroppedExceptionStep("Exception dropped: matched a suppression rule"),void cu.info("Skipping exception capture because a suppression rule matched");if(!this._captureExtensionExceptions&&this._isExtensionException(t))return this._addDroppedExceptionStep("Exception dropped: thrown by a browser extension"),void cu.info("Skipping exception capture because it was thrown by an extension");if(!this._captureExtensionExceptions&&this._isInjectedBrowserScriptException(t))return this._addDroppedExceptionStep("Exception dropped: thrown by an injected browser script"),void cu.info("Skipping exception capture because it was thrown by an injected browser script");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this._isPostHogException(t))return this._addDroppedExceptionStep("Exception dropped: thrown by the PostHog SDK"),void cu.info("Skipping exception capture because it was thrown by the PostHog SDK")}var i=this._exceptionStepsConfig.enabled&&wt(e.$exception_steps)?this._addBufferedExceptionSteps(e):e,s="string"==typeof(n=globalThis._posthogReleaseId)&&n.length>0?n:void 0;s&&(i.$release_id=s);try{var r=this._instance.capture("$exception",i,{_noTruncate:!0,_batchKey:"exceptionEvent",_originatedFromCaptureException:!0});return r&&this._exceptionStepsBuffer.clear(),r}catch(e){return cu.error("Failed to capture exception event. Dropping this exception.",e),void this._exceptionStepsBuffer.clear()}}catch(e){return void cu.error("Failed to process exception event. Ignoring this exception.",e)}var n}_addBufferedExceptionSteps(e){try{var t=this._exceptionStepsBuffer.getAttachable();return 0===t.length?e:i({},e,{$exception_steps:t})}catch(t){return cu.error("Failed to read buffered exception steps. Capturing exception without steps.",t),e}}_addDroppedExceptionStep(e){this._exceptionStepsConfig.enabled&&this._exceptionStepsBuffer.add({[Bs]:e,[qs]:(new Date).toISOString()})}_coerceExceptionStepProperties(e){return gt(e)?i({},e):{}}_getExceptionStepsConfig(){var e,t;return null!==(e=null==(t=this._instance.config.error_tracking)?void 0:t.exception_steps)&&void 0!==e?e:{}}_matchesSuppressionRule(e){if(0===e.length)return!1;try{var t=e.reduce(((e,t)=>{var i=t.type,s=t.value;return mt(i)&&i.length>0&&e.$exception_types.push(i),mt(s)&&s.length>0&&e.$exception_values.push(s),e}),{$exception_types:[],$exception_values:[]});return this._suppressionRules.some((e=>{var i=e.values.map((e=>{var i=La[e.operator],s=t[e.key];if(!i||!s)return!1;var r=_t(e.value)?e.value:[e.value];return r.length>0&&i(r,s)}));return"OR"===e.type?i.some(Boolean):i.every(Boolean)}))}catch(e){return cu.warn("Failed to evaluate suppression rules. Capturing the exception.",e),!1}}_isExtensionException(e){return e.flatMap((e=>{var t,i;return null!==(t=null==(i=e.stacktrace)?void 0:i.frames)&&void 0!==t?t:[]})).some((e=>{var t=e.filename;return!!t&&du.some((e=>t.startsWith(e)))}))}_isInjectedBrowserScriptException(e){return e.some((e=>{var t=e.value;return mt(t)&&hu.some((e=>t.includes(e)))}))}_isPostHogException(e){if(e.length>0){var t,i,s,r,n=null!==(t=null==(i=e[0].stacktrace)?void 0:i.frames)&&void 0!==t?t:[],o=n[n.length-1];return null!==(s=null==o||null==(r=o.filename)?void 0:r.includes("posthog.com/static"))&&void 0!==s&&s}return!1}_isExceptionList(e){return!wt(e)&&_t(e)}}},Pu=i({productTours:class{get _persistence(){return this._instance.persistence}constructor(e){this._productTourManager=null,this._cachedTours=null,this._instance=e}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(e.ok){var t=e.config;if("productTours"in t){var i,s;if(this._persistence&&this._persistence.register({[m]:!!t.productTours}),!ql(this._instance))return!this._productTourManager&&wt(null==(i=this._persistence)?void 0:i.props[W])||Bl.info("product tours disabled; stopping and clearing cached tours"),null==(s=this._productTourManager)||s.stop(),this._productTourManager=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this._productTourManager&&ql(this._instance)&&this._loadScript((()=>this._startProductTours()))}_loadScript(e){var t,i;null!=(t=Le.__PosthogExtensions__)&&t.generateProductTours?e():null==(i=Le.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,"product-tours",(t=>{t?Bl.error("Could not load product tours script",t):e()}))}_startProductTours(){var e;!this._productTourManager&&null!=(e=Le.__PosthogExtensions__)&&e.generateProductTours&&(this._productTourManager=Le.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t){if(void 0===t&&(t=!1),!_t(this._cachedTours)||t){var i=this._persistence;if(i){var s=i.props[W];if(_t(s)&&!t)return this._cachedTours=s,void e(s,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:t=>{if(ql(this._instance)){var s=t.statusCode;if(200!==s||!t.json){var r="Product Tours API could not be loaded, status: "+s;return 0===s?t.error||Bl.warn(r):Bl.error(r),void e([],{isLoaded:!1,error:r})}var n=_t(t.json.product_tours)?t.json.product_tours:[];this._cachedTours=n,i&&i.register({[W]:n}),e(n,{isLoaded:!0})}else e([],{isLoaded:!0})}})}else e(this._cachedTours,{isLoaded:!0})}getActiveProductTours(e){wt(this._productTourManager)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this._productTourManager.getActiveProductTours(e)}showProductTour(e){var t;null==(t=this._productTourManager)||t.showTourById(e)}previewTour(e){this._productTourManager?this._productTourManager.previewTour(e):this._loadScript((()=>{var t;this._startProductTours(),null==(t=this._productTourManager)||t.previewTour(e)}))}dismissProductTour(){var e;null==(e=this._productTourManager)||e.dismissTour("user_clicked_skip")}nextStep(){var e;null==(e=this._productTourManager)||e.nextStep()}previousStep(){var e;null==(e=this._productTourManager)||e.previousStep()}clearCache(){var e;this._cachedTours=null,null==(e=this._persistence)||e.unregister(W)}resetTour(e){var t;null==(t=this._productTourManager)||t.resetTour(e)}resetAllTours(){var e;null==(e=this._productTourManager)||e.resetAllTours()}cancelPendingTour(e){var t;null==(t=this._productTourManager)||t.cancelPendingTour(e)}}},Su),Cu={siteApps:class{constructor(e){this._siteAppElementPatchCount=0,this._instance=e,this._bufferedInvocations=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}_eventCollector(e,t){if(t){var i=this.globalsForEvent(t);this._bufferedInvocations.push(i),this._bufferedInvocations.length>1e3&&(this._bufferedInvocations=this._bufferedInvocations.slice(10))}}get siteAppLoaders(){var e;return null==(e=Le._POSTHOG_REMOTE_CONFIG)||null==(e=e[this._instance.config.token])?void 0:e.siteApps}initialize(){if(this.isEnabled){var e=this._instance._addCaptureHook(this._eventCollector.bind(this));this._stopBuffering=()=>{e(),this._bufferedInvocations=[],this._stopBuffering=void 0}}}globalsForEvent(e){var t,r,n,o,a,l,u;if(!e)throw new Error("Event payload is required");var c={},d=this._instance.get_property("$groups")||[],h=this._instance.get_property("$stored_group_properties")||{};for(var _ of Object.entries(h)){var p=_[0];c[p]={id:d[p],type:p,properties:_[1]}}var g=e.$set_once,v=e.$set;return{event:i({},s(e,Hl),{properties:i({},e.properties,v?{$set:i({},null!==(t=null==(r=e.properties)?void 0:r.$set)&&void 0!==t?t:{},v)}:{},g?{$set_once:i({},null!==(n=null==(o=e.properties)?void 0:o.$set_once)&&void 0!==n?n:{},g)}:{}),elements_chain:null!==(a=null==(l=e.properties)?void 0:l.$elements_chain)&&void 0!==a?a:"",distinct_id:null==(u=e.properties)?void 0:u.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:c}}_prepareElementForSiteApp(e){var t,i=null==(t=e.tagName)?void 0:t.toLowerCase();return"style"===i&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(e)||(Nl.error("prepare_external_dependency_stylesheet returned null"),null):"script"===i&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(e)||(Nl.error("prepare_external_dependency_script returned null"),null):e}_patchSiteAppElementInsertionMethods(){var e,t,i,s,r,n,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=null==Ee?void 0:Ee.defaultView,u=null==l||null==(e=l.Node)?void 0:e.prototype;if(!l||!u)return()=>{};if(this._siteAppElementPatchCount++,this._restoreSiteAppElementPatches)return this._releaseSiteAppElementPatches();var c=[],d=this,h=new WeakSet,_=(e,t,i)=>{if(null!=e&&e[t]){var s=e[t];e[t]=i(s),c.push((()=>{e[t]=s}))}},p=e=>{if(h.has(e))return e;var t=d._prepareElementForSiteApp(e);return t&&h.add(t),t},g=e=>e.map((e=>"string"==typeof e?e:p(e))).filter((e=>!bt(e)));return _(u,"appendChild",(e=>function(t){var i=p(t);return i?e.call(this,i):t})),_(u,"insertBefore",(e=>function(t,i){var s=p(t);return s?e.call(this,s,i):t})),_(u,"replaceChild",(e=>function(t,i){var s=p(t);return s?e.call(this,s,i):i})),[null==(t=l.Element)?void 0:t.prototype,null==(i=l.Document)?void 0:i.prototype,null==(s=l.DocumentFragment)?void 0:s.prototype].forEach((e=>{_(e,"append",(e=>function(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];return e.apply(this,g(i))})),_(e,"prepend",(e=>function(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];return e.apply(this,g(i))}))})),[null==(r=l.Element)?void 0:r.prototype,null==(n=l.CharacterData)?void 0:n.prototype,null==(o=l.DocumentType)?void 0:o.prototype].forEach((e=>{_(e,"before",(e=>function(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];return e.apply(this,g(i))})),_(e,"after",(e=>function(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];return e.apply(this,g(i))})),_(e,"replaceWith",(e=>function(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];var r=g(i);return i.length&&!r.length?void 0:e.apply(this,r)}))})),_(null==(a=l.Element)?void 0:a.prototype,"insertAdjacentElement",(e=>function(t,i){var s=p(i);return s?e.call(this,t,s):null})),this._restoreSiteAppElementPatches=()=>{c.forEach((e=>e())),this._restoreSiteAppElementPatches=void 0},this._releaseSiteAppElementPatches()}_releaseSiteAppElementPatches(){var e=!1;return()=>{var t;e||(e=!0,this._siteAppElementPatchCount--,0===this._siteAppElementPatchCount&&(null==(t=this._restoreSiteAppElementPatches)||t.call(this)))}}_runWithPreparedSiteAppElements(e,t){void 0===t&&(t=!0);var i=this._patchSiteAppElementInsertionMethods();try{var s=e(i);return t&&i(),s}catch(e){throw i(),e}}setupSiteApp(e){var t=this.apps[e.id],i=()=>{var i;!t.errored&&this._bufferedInvocations.length&&(Nl.info("Processing "+this._bufferedInvocations.length+" events for site app with id "+e.id),this._bufferedInvocations.forEach((e=>this._runWithPreparedSiteAppElements((()=>null==t.processEvent?void 0:t.processEvent(e))))),t.processedBuffer=!0),Object.values(this.apps).every((e=>e.processedBuffer||e.errored))&&(null==(i=this._stopBuffering)||i.call(this))},s=!1,r=r=>{t.errored=!r,t.loaded=!0,Nl.info("Site app with id "+e.id+" "+(r?"loaded":"errored")),s&&i()};try{var n=this._runWithPreparedSiteAppElements((t=>e.init({posthog:this._instance,callback(e){t(),r(e)}})),!1).processEvent;n&&(t.processEvent=n),s=!0}catch(t){Nl.error(zl+e.id,t),r(!1)}if(s&&t.loaded)try{i()}catch(i){Nl.error("Error while processing buffered events PostHog app with config id "+e.id,i),t.errored=!0}}_setupSiteApps(){var e=this.siteAppLoaders||[];for(var t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(var i of e)this.setupSiteApp(i)}_onCapturedEvent(e){var t=this;if(0!==Object.keys(this.apps).length){var i=this.globalsForEvent(e),s=function(s){try{t._runWithPreparedSiteAppElements((()=>null==s.processEvent?void 0:s.processEvent(i)))}catch(t){Nl.error("Error while processing event "+e.event+" for site app "+s.id,t)}};for(var r of Object.values(this.apps))s(r)}}onRemoteConfig(e){var t,i,s,r=this;if(null!=(t=this.siteAppLoaders)&&t.length)return this.isEnabled?(this._setupSiteApps(),void this._instance.on("eventCaptured",(e=>this._onCapturedEvent(e)))):void Nl.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if(null==(i=this._stopBuffering)||i.call(this),e.ok){var n=e.config;if(null!=(s=n.siteApps)&&s.length)if(this.isEnabled){var o=function(){var e,t=a.id,i=a.url;Le["__$$ph_site_app_"+t]=r._instance,null==(e=Le.__PosthogExtensions__)||null==e.loadSiteApp||e.loadSiteApp(r._instance,i,(e=>{if(e)return Nl.error(zl+t,e)}))};for(var a of n.siteApps)o()}else Nl.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Iu={tracingHeaders:class{constructor(e){this._restoreXHRPatch=void 0,this._restoreFetchPatch=void 0,this._hostnamesForPatch=void 0,this._startCapturing=()=>{var e,t,i=this._syncHostnamesForPatch();i?(ft(this._restoreXHRPatch)&&(this._restoreXHRPatch=null==(e=Le.__PosthogExtensions__)||null==(e=e.tracingHeadersPatchFns)?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),ft(this._restoreFetchPatch)&&(this._restoreFetchPatch=null==(t=Le.__PosthogExtensions__)||null==(t=t.tracingHeadersPatchFns)?void 0:t._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this._stopCapturing()},this._instance=e}initialize(){this.startIfEnabledOrStop()}_loadScript(e){var t,i;null!=(t=Le.__PosthogExtensions__)&&t.tracingHeadersPatchFns?e():null==(i=Le.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,"tracing-headers",(t=>{if(t)return El.error("failed to load script",t);e()}))}_getConfiguredHostnames(){var e,t;return null!==(e=null!==(t=this._instance.config.tracing_headers)&&void 0!==t?t:this._instance.config.addTracingHeaders)&&void 0!==e?e:this._instance.config.__add_tracing_headers}_syncHostnamesForPatch(){var e=this._getConfiguredHostnames();return _t(e)?(_t(this._hostnamesForPatch)?this._hostnamesForPatch.splice(0,this._hostnamesForPatch.length,...e):this._hostnamesForPatch=[...e],e.length>0?this._hostnamesForPatch:void 0):(_t(this._hostnamesForPatch)&&this._hostnamesForPatch.splice(0),this._hostnamesForPatch=e||void 0,this._hostnamesForPatch)}_stopCapturing(){var e,t;null==(e=this._restoreXHRPatch)||e.call(this),null==(t=this._restoreFetchPatch)||t.call(this),this._restoreXHRPatch=void 0,this._restoreFetchPatch=void 0}startIfEnabledOrStop(){this._syncHostnamesForPatch()?this._loadScript(this._startCapturing):this._stopCapturing()}}},Fu=i({surveys:class extends Wl{constructor(e){var t;super(new Zl(e),{get projectToken(){return t.config.token},kv:new Yl(t=e)}),this._instance=e}_sendSurveysRequest(e,t){var i=t.query?oa(e,t.query):e;return new Promise((e=>{var s;this._instance._send_request({method:t.method,url:this._instance.requestRouter.endpointFor(null!==(s=t.target)&&void 0!==s?s:"api",i),data:t.body,headers:t.headers,timeout:t.timeoutMs,fireCallbackOnDrop:!0,transport:t.transport,compression:t.compression,timestampMode:t.sentAt,callback:e})}))}}},Su),Tu={toolbar:class{constructor(e){this.instance=e}_setToolbarState(e){Le.ph_toolbar_state=e}_getToolbarState(){var e;return null!==(e=Le.ph_toolbar_state)&&void 0!==e?e:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(e,t,i){if(void 0===e&&(e=void 0),void 0===t&&(t=void 0),void 0===i&&(i=void 0),rr(this.instance.config))return!1;if(!we||!Ee)return!1;e=null!=e?e:we.location,i=null!=i?i:we.history;try{if(!t){try{we.localStorage.setItem("test","test"),we.localStorage.removeItem("test")}catch(e){return!1}t=null==we?void 0:we.localStorage}var s,r=Xl||Hn(e.hash,"__posthog")||Hn(e.hash,"state"),n=r?Zs((()=>JSON.parse(atob(decodeURIComponent(r)))))||Zs((()=>JSON.parse(decodeURIComponent(r)))):null;return n&&"ph_authorize"===n.action?((s=n).source="url",s&&Object.keys(s).length>0&&(n.desiredHash?e.hash=n.desiredHash:i?i.replaceState(i.state,"",e.pathname+e.search):e.hash="")):((s=JSON.parse(t.getItem(eu)||"{}")).source="localstorage",delete s.userIntent),!(!s.token||this.instance.config.token!==s.token||(this.loadToolbar(s),0))}catch(e){return!1}}_callLoadToolbar(e){var t=Le.ph_load_toolbar||Le.ph_load_editor;!wt(t)&&pt(t)?t(e,this.instance):tu.warn("No toolbar load function found")}loadToolbar(e){var t=!(null==Ee||!Ee.getElementById(Mr));if(!we||t)return!1;var s="custom"===this.instance.requestRouter.region&&this.instance.config.advanced_disable_toolbar_metrics,r=i({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},s?{instrument:!1}:{});if(we.localStorage.setItem(eu,JSON.stringify(i({},r,{source:void 0}))),2===this._getToolbarState())this._callLoadToolbar(r);else if(0===this._getToolbarState()){var n;this._setToolbarState(1),null==(n=Le.__PosthogExtensions__)||null==n.loadExternalDependency||n.loadExternalDependency(this.instance,"toolbar",(e=>{if(e)return tu.error("[Toolbar] Failed to load",e),void this._setToolbarState(0);this._setToolbarState(2),this._callLoadToolbar(r)})),sr(we,"turbolinks:load",(()=>{this._setToolbarState(0),this.loadToolbar(r)}))}return!0}_loadEditor(e){return this.loadToolbar(e)}maybeLoadEditor(e,t,i){return void 0===e&&(e=void 0),void 0===t&&(t=void 0),void 0===i&&(i=void 0),this.maybeLoadToolbar(e,t,i)}}},Ru=i({experiments:gu},Su),Au={conversations:class{constructor(e){this._isConversationsEnabled=void 0,this._conversationsManager=null,this._isInitializing=!1,this._remoteConfig=null,this._loadFailed=!1,this._instance=e}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(!this._instance.config.disable_conversations&&(this._remoteConfigSuccessful=e.ok,e.ok)){var t=e.config.conversations;wt(t)||(Et(t)?this._isConversationsEnabled=t:(this._isConversationsEnabled=t.enabled,this._remoteConfig=t),this.loadIfEnabled())}}reset(){var e;null==(e=this._conversationsManager)||e.reset(),this._conversationsManager=null,this._isConversationsEnabled=void 0,this._remoteConfig=null,this._remoteConfigSuccessful=void 0,this._loadFailed=!1}loadIfEnabled(){if(!(this._conversationsManager||this._isInitializing||this._instance.config.disable_conversations||rr(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var e=null==Le?void 0:Le.__PosthogExtensions__;if(e&&!ft(this._isConversationsEnabled)&&this._isConversationsEnabled)if(this._remoteConfig&&this._remoteConfig.token){this._isInitializing=!0;try{var t=e.initConversations;if(t)return this._completeInitialization(t),void(this._isInitializing=!1);var i=e.loadExternalDependency;if(!i)return void this._handleLoadError(ue);i(this._instance,"conversations",(t=>{t||!e.initConversations?this._handleLoadError("Could not load conversations script",t):this._completeInitialization(e.initConversations),this._isInitializing=!1}))}catch(e){this._handleLoadError("Error initializing conversations",e),this._isInitializing=!1}}else vu.error("Conversations enabled but missing token in remote config.")}}_completeInitialization(e){if(this._remoteConfig)try{this._conversationsManager=e(this._remoteConfig,this._instance),this._loadFailed=!1,vu.info("Conversations loaded successfully")}catch(e){this._handleLoadError("Error completing conversations initialization",e)}else vu.error("Cannot complete initialization: remote config is null")}_handleLoadError(e,t){vu.error(e,t),this._conversationsManager=null,this._isInitializing=!1,this._loadFailed=!0}show(){this._conversationsManager?this._conversationsManager.show():vu.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return!0===this._isConversationsEnabled&&!bt(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":rr(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":!1===this._remoteConfigSuccessful?"remote_config_failed":ft(this._isConversationsEnabled)?this._remoteConfigSuccessful?"disabled_in_project":"remote_config_pending":this._isConversationsEnabled?wt(this._remoteConfig)||!this._remoteConfig.token?"missing_token":null!=Le&&Le.__PosthogExtensions__?this._isInitializing?"initializing":this._loadFailed?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var e,t;return null!==(e=null==(t=this._conversationsManager)?void 0:t.isVisible())&&void 0!==e&&e}sendMessage(e,i,s){var r=this;return t((function*(){return r._conversationsManager?r._conversationsManager.sendMessage(e,i,s):(vu.warn(fu),null)}))()}getMessages(e,i){var s=this;return t((function*(){return s._conversationsManager?s._conversationsManager.getMessages(e,i):(vu.warn(fu),null)}))()}markAsRead(e){var i=this;return t((function*(){return i._conversationsManager?i._conversationsManager.markAsRead(e):(vu.warn(fu),null)}))()}getTickets(e){var i=this;return t((function*(){return i._conversationsManager?i._conversationsManager.getTickets(e):(vu.warn(fu),null)}))()}requestRestoreLink(e){var i=this;return t((function*(){return i._conversationsManager?i._conversationsManager.requestRestoreLink(e):(vu.warn(fu),null)}))()}restoreFromToken(e){var i=this;return t((function*(){return i._conversationsManager?i._conversationsManager.restoreFromToken(e):(vu.warn(fu),null)}))()}restoreFromUrlToken(){var e=this;return t((function*(){return e._conversationsManager?e._conversationsManager.restoreFromUrlToken():(vu.warn(fu),null)}))()}getCurrentTicketId(){var e,t;return null!==(e=null==(t=this._conversationsManager)?void 0:t.getCurrentTicketId())&&void 0!==e?e:null}getWidgetSessionId(){var e,t;return null!==(e=null==(t=this._conversationsManager)?void 0:t.getWidgetSessionId())&&void 0!==e?e:null}_onIdentityChanged(){var e;null==(e=this._conversationsManager)||e.setIdentity()}_onIdentityCleared(){var e;null==(e=this._conversationsManager)||e.clearIdentity()}}},Lu={logs:class{constructor(e){var t,s=this;this._isLogsEnabled=!1,this._isLoaded=!1,this._logger=Gs("[logs]"),this._coreLogger=i({},this._logger,{error(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];t.some(wu)||s._logger.error(...t)}}),this._queue=[],this._consoleQueue=[],this._consecutiveStatusZeroFailures=0,this._onReconnect=()=>{var e,t;this._consecutiveStatusZeroFailures=0,null==(e=this._core)||e.onReconnect(),null==(t=this._consoleCore)||t.onReconnect()},this._instance=e,this._instance&&null!=(t=this._instance.config.logs)&&t.captureConsoleLogs&&(this._isLogsEnabled=!0),we&&sr(we,"online",this._onReconnect)}_buildCore(e,t,i,s){var r,n=function(e,t){var i,s,r,n,o,a,l,u=null!==(i=null==e?void 0:e.flushIntervalMs)&&void 0!==i?i:3e3,c=null!==(s=null==e?void 0:e.maxBufferSize)&&void 0!==s?s:100,d=null!=t&&t.consoleCapture?void 0:null!==(r=null==e?void 0:e.maxLogsPerInterval)&&void 0!==r?r:1e3,h=ft(d)?Math.max(c,2048):Math.max(c,d),_=null==e?void 0:e.resourceAttributes;return{serviceName:null!==(n=null!==(o=null==_?void 0:_["service.name"])&&void 0!==o?o:null==e?void 0:e.serviceName)&&void 0!==n?n:null==t?void 0:t.serviceNameDefault,serviceVersion:null!==(a=null==_?void 0:_["service.version"])&&void 0!==a?a:null==e?void 0:e.serviceVersion,environment:null!==(l=null==_?void 0:_["deployment.environment"])&&void 0!==l?l:null==e?void 0:e.environment,resourceAttributes:_,beforeSend:null==e?void 0:e.beforeSend,flushIntervalMs:u,maxBufferSize:c,maxQueueSize:h,maxBatchRecordsPerPost:100,rateCapWindowMs:u,maxLogsPerInterval:d,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}}(null==(r=this._instance)||null==(r=r.config)?void 0:r.logs,i);return[new os(this._createHost(e,t),n,this._coreLogger,(()=>this._getSdkContext()),(e=>e()),void 0,s),n]}_getCore(){var e,t=null==(e=this._instance)||null==(e=e.config)?void 0:e.logs;if(!this._core||this._resolvedFrom!==t){var i;null==(i=this._core)||i.reset(),this._resolvedFrom=t;var s=this._buildCore((()=>this._queue),(e=>{this._queue=e}));this._core=s[0],this._resolvedConfig=s[1]}return this._core}_getConsoleCore(){var e,t=null==(e=this._instance)||null==(e=e.config)?void 0:e.logs;if(!this._consoleCore||this._consoleResolvedFrom!==t){var i;null==(i=this._consoleCore)||i.reset(),this._consoleResolvedFrom=t;var s=this._buildCore((()=>this._consoleQueue),(e=>{this._consoleQueue=e}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},mu);this._consoleCore=s[0],this._consoleResolvedConfig=s[1]}return this._consoleCore}initialize(){this.loadIfEnabled()}onRemoteConfig(e){var t;if(e.ok){var i=null==(t=e.config.logs)?void 0:t.captureConsoleLogs;!wt(i)&&i&&(this._isLogsEnabled=!0,this.loadIfEnabled())}}reset(){var e,t;this._queue=[],null==(e=this._core)||e.reset(),this._consoleQueue=[],null==(t=this._consoleCore)||t.reset(),this._consecutiveStatusZeroFailures=0}captureLog(e){this._getCore().captureLog(e)}_captureConsoleLog(e){this._getConsoleCore().captureLog(e)}get logger(){return this._capture_logger||(this._capture_logger={trace:(e,t)=>this.captureLog({body:e,level:"trace",attributes:t}),debug:(e,t)=>this.captureLog({body:e,level:"debug",attributes:t}),info:(e,t)=>this.captureLog({body:e,level:"info",attributes:t}),warn:(e,t)=>this.captureLog({body:e,level:"warn",attributes:t}),error:(e,t)=>this.captureLog({body:e,level:"error",attributes:t}),fatal:(e,t)=>this.captureLog({body:e,level:"fatal",attributes:t})}),this._capture_logger}flushLogs(e){e?this._flushViaTransport(e):(this._core&&this._core.flush().catch((e=>this._logFlushError(e))),this._consoleCore&&this._consoleCore.flush().catch((e=>this._logFlushError(e))))}_logFlushError(e){wu(e)||this._logger.error("PostHog logs flush failed:",e)}loadIfEnabled(){if(this._isLogsEnabled&&!this._isLoaded){var e=null==Le?void 0:Le.__PosthogExtensions__;if(e){var t=e.loadExternalDependency;t?t(this._instance,"logs",(t=>{var i;t||null==(i=e.logs)||!i.initializeLogs?this._logger.error("Could not load logs script",t):(e.logs.initializeLogs(this._instance),this._isLoaded=!0)})):this._logger.error(ue)}else this._logger.error("PostHog Extensions not found.")}}_createHost(e,t){var i=this._instance;return{get isDisabled(){return!1},get optedOut(){return!i.is_capturing()},getPersistedProperty:t=>t===qe.LogsQueue?e():void 0,setPersistedProperty(e,i){var s;e===qe.LogsQueue&&t(null!==(s=i)&&void 0!==s?s:[])},_sendLogsBatch:e=>this._sendLogsBatch(e),getLibraryId:()=>r.LIB_NAME,getLibraryVersion:()=>r.LIB_VERSION}}_sendLogsBatch(e){return new Promise((t=>{if(Nn(this._consecutiveStatusZeroFailures,3))t({kind:"fatal",error:bu(void 0,"logs endpoint is unreachable, dropping batch")});else{var i=!1,s=e=>{i||(i=!0,clearTimeout(r),t(e))},r=setTimeout((()=>{this._logger.warn("Logs request timed out before receiving a response"),s({kind:"retry-later",error:bu(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this._logsUrl(),data:e,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:e=>{var t=e.statusCode;if(this._trackEndpointReachability(t),t>=200&&300>t)s({kind:"ok"});else if(413===t)s({kind:"too-large"});else if(0!==t&&408!==t&&429!==t&&500>t)s({kind:"fatal",error:new Error("logs request failed with status "+t)});else{var i;0===t?(e.error||this._logger.warn("Logs request failed before receiving an HTTP response"),s({kind:"retry-later",error:bu(e.error,"logs request failed before receiving an HTTP response")})):s({kind:"retry-later",error:null!==(i=e.error)&&void 0!==i?i:new Error("logs request failed with status "+t)})}}})}}))}_trackEndpointReachability(e){(0!==e||this._instance.__loaded)&&(this._consecutiveStatusZeroFailures=zn(e,this._consecutiveStatusZeroFailures,3,(()=>this._logger.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes."))))}_flushViaTransport(e){this._queue.length>0&&this._drainQueueViaTransport(e,this._queue,this._resolvedConfig,r.LIB_NAME,(e=>{this._queue=e})),this._consoleQueue.length>0&&this._drainQueueViaTransport(e,this._consoleQueue,this._consoleResolvedConfig,mu,(e=>{this._consoleQueue=e}))}_drainQueueViaTransport(e,t,i,s,n){if(0!==t.length){var o=t.map((e=>e.record));n([]);var a=ns(o,rs(i,r.LIB_NAME,r.LIB_VERSION),s,r.LIB_VERSION);this._instance._send_request({method:"POST",url:this._logsUrl(),data:a,compression:"best-available",batchKey:"logs",transport:e})}}_logsUrl(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}_getSdkContext(){var e,t={};if(t.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var i=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),s=i.windowId,r=i.sessionStartTimestamp,n=i.lastActivityTimestamp;t.sessionId=i.sessionId,t.windowId=s,wt(r)||(t.sessionStartTimestamp=r),wt(n)||(t.lastActivityTimestamp=n)}if(null!=Le&&null!=(e=Le.location)&&e.href&&(t.currentUrl=this._instance.config.disable_capture_url_hashes?Ui(Le.location.href):Le.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(t.activeFeatureFlags=o)}return t}}},Mu={metrics:class{constructor(e){this._logger=Gs("[metrics]"),this._instance=e}initialize(){}_getCore(){var e,t,i=null==(e=this._instance)||null==(e=e.config)?void 0:e.metrics;return this._core&&this._resolvedFrom===i||(null==(t=this._core)||t.reset(),this._resolvedFrom=i,this._core=new cs(this._createHost(),function(e){var t,i,s,r,n,o=null==e?void 0:e.resourceAttributes;return{serviceName:null!==(t=null==o?void 0:o["service.name"])&&void 0!==t?t:null==e?void 0:e.serviceName,serviceVersion:null!==(i=null==o?void 0:o["service.version"])&&void 0!==i?i:null==e?void 0:e.serviceVersion,environment:null!==(s=null==o?void 0:o["deployment.environment"])&&void 0!==s?s:null==e?void 0:e.environment,resourceAttributes:o,beforeSend:null==e?void 0:e.beforeSend,flushIntervalMs:null!==(r=null==e?void 0:e.flushIntervalMs)&&void 0!==r?r:1e4,maxSeriesPerFlush:null!==(n=null==e?void 0:e.maxSeriesPerFlush)&&void 0!==n?n:1e3}}(i),this._logger)),this._core}count(e,t,i){void 0===t&&(t=1),this._getCore().count(e,t,i)}gauge(e,t,i){this._getCore().gauge(e,t,i)}histogram(e,t,i){this._getCore().histogram(e,t,i)}flush(e){if(!this._core)return Promise.resolve();if(e){var t=this._core.drainWindow();return t&&this._sendMetricsBatch(t,e),Promise.resolve()}return this._core.flush().catch((e=>this._logger.error("PostHog metrics flush failed:",e)))}reset(){var e;null==(e=this._core)||e.reset()}_createHost(){var e=this._instance,t=this;return{get isDisabled(){return!1},get optedOut(){return!e.is_capturing()},_sendMetricsBatch:e=>t._sendMetricsBatch(e),getLibraryId:()=>r.LIB_NAME,getLibraryVersion:()=>r.LIB_VERSION}}_sendMetricsBatch(e,t){return new Promise((s=>{var r=!1,n=e=>{r||(r=!0,clearTimeout(o),s(e))},o=setTimeout((()=>n({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(i({method:"POST",url:this._metricsUrl(),data:e,compression:"best-available",batchKey:"metrics"},t&&{transport:t},{fireCallbackOnDrop:!0,callback(e){var t=e.statusCode;if(t>=200&&300>t)n({kind:"ok"});else if(413===t)n({kind:"too-large"});else if(0!==t&&408!==t&&429!==t&&500>t)n({kind:"fatal",error:new Error("metrics request failed with status "+t)});else{var i;n({kind:"retry-later",error:null!==(i=e.error)&&void 0!==i?i:new Error("metrics request failed with status "+t)})}}}))}))}_metricsUrl(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},$u=i({},Su,xu,Eu,ku,Pu,Cu,Fu,Iu,Tu,Ru,Au,Lu,Mu);_l.__defaultExtensionClasses=i({},$u),function(){r.SDK_DIST_CHANNEL="cdn";var e=Le.posthog;if(!e||_t(e._i)){var t=Xa[al]=new _l;if(e){var i=[];Qs(e._i,(function(s){if(s&&_t(s)){var r=t.init(s[0],s[1],s[2]),n=e[s[2]]||e;r.__loaded&&-1===i.indexOf(n)&&(i.push(n),r._execute_array.call(r.people,n.people),r._execute_array(n))}}))}t.__SV=1,Le.posthog=t,function(){function e(){e.done||(e.done=!0,ll=!1,Qs(Xa,(function(e){e._dom_loaded()})))}null!=Ee&&Ee.addEventListener?"complete"===Ee.readyState?e():sr(Ee,"DOMContentLoaded",e,{capture:!1}):we&&Ws.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}()}}()}();
2
2
  //# sourceMappingURL=array.no-external.js.map