posthog-js
Advanced tools
@@ -1,2 +0,2 @@ | ||
| !function(){"use strict";var e={LIB_VERSION:"1.396.5",LIB_NAME:"web"};function r(){return r=Object.assign?Object.assign.bind():function(e){for(var r=1;arguments.length>r;r++){var n=arguments[r];for(var t in n)({}).hasOwnProperty.call(n,t)&&(e[t]=n[t])}return e},r.apply(null,arguments)}function n(e,r){return-1!==e.indexOf(r)}var t=Object.prototype,i=t.hasOwnProperty,o=t.toString,a=Array.isArray||function(e){return"[object Array]"===o.call(e)},l=e=>e===Object(e)&&!a(e),u=e=>{if(l(e)){for(var r in e)if(i.call(e,r))return!1;return!0}return!1},s=e=>void 0===e,c=e=>s(e)||(e=>null===e)(e),d=e=>"[object Number]"==o.call(e)&&e==e,f=e=>e instanceof FormData;function v(e,r,n,t,i){return r>n&&(t.warn("min cannot be greater than max."),r=n),d(e)?e>n?(t.warn(" cannot be greater than max: "+n+". Using max value instead."),n):r>e?(t.warn(" cannot be less than min: "+r+". Using min value instead."),r):e:(t.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+i),v(n,r,n,t))}class h{constructor(e){this.Ee={},this.Pe=e.Pe,this.Fe=v(e.bucketSize,0,100,e.Ae),this.$e=v(e.refillRate,0,this.Fe,e.Ae),this.De=v(e.refillInterval,0,864e5,e.Ae)}Ne(e,r){var n=Math.floor((r-e.lastAccess)/this.De);n>0&&(e.tokens=Math.min(e.tokens+n*this.$e,this.Fe),e.lastAccess=e.lastAccess+n*this.De)}consumeRateLimit(e){var r,n=Date.now(),t=String(e),i=this.Ee[t];return i?this.Ne(i,n):this.Ee[t]=i={tokens:this.Fe,lastAccess:n},0===i.tokens||(i.tokens--,0===i.tokens&&(null==(r=this.Pe)||r.call(this,e)),0===i.tokens)}stop(){this.Ee={}}}var p="Mobile",g="iOS",w="Android",m="Tablet",_=w+" "+m,x="iPad",b="Apple",E=b+" Watch",R="Safari",y="BlackBerry",S="Samsung",M=S+"Browser",k=S+" Internet",P="Chrome",A=P+" OS",O=P+" "+g,B="Internet Explorer",D=B+" "+p,I="Opera",N=I+" Mini",U="Edge",T="Microsoft "+U,C="Firefox",W=C+" "+g,F="Nintendo",L="PlayStation",j="Xbox",z=w+" "+p,G=p+" "+R,K="Windows",V=K+" Phone",H="Nokia",X="Ouya",Y="Generic",q=Y+" "+p.toLowerCase(),J=Y+" "+m.toLowerCase(),Q="Konqueror",Z="Oculus Browser",ee="Vivaldi",re="Yandex",ne="Whale",te="DuckDuckGo",ie="Pale Moon",oe="Waterfox",ae="Brave",le="Google Search App",ue="(\\d+(\\.\\d+)?)",se=new RegExp("Version/"+ue),ce=new RegExp(j,"i"),de=new RegExp(L+" \\w+","i"),fe=new RegExp(F+" \\w+","i"),ve=new RegExp(y+"|PlayBook|BB10","i"),he={"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"},pe=function(e,r,t,i){r=r||"";var o=function(e){return null!=e&&e.brave?ae:null}(t);return o||(null!=i&&i.detectGoogleSearchApp&&n(e,"GSA/")?le:n(e," OPR/")&&n(e,"Mini")?N:n(e," OPR/")?I:ve.test(e)?y:n(e,"IE"+p)||n(e,"WPDesktop")?D:n(e,"OculusBrowser")?Z:n(e,M)?k:n(e,U)||n(e,"Edg/")?T:n(e,ee+"/")?ee:n(e,"YaBrowser/")?re:n(e,ne+"/")?ne:n(e,te+"/")||n(e,"Ddg/")?te:n(e,"FBIOS")?"Facebook "+p:n(e,"UCWEB")||n(e,"UCBrowser")?"UC Browser":n(e,"CriOS")?O:n(e,"CrMo")||n(e,P)?P:n(e,w)&&n(e,R)?z:n(e,"FxiOS")?W:n(e.toLowerCase(),Q.toLowerCase())?Q:n(e,ae+"/")?ae:((e,r)=>r&&n(r,b)||function(e){return n(e,R)&&!n(e,P)&&!n(e,w)}(e))(e,r)?n(e,p)?G:R:n(e,"PaleMoon/")?ie:n(e,oe+"/")?oe:n(e,C)?C:n(e,"MSIE")||n(e,"Trident/")?B:n(e,"Gecko")?C:"")},ge={[D]:[new RegExp("rv:"+ue)],[T]:[new RegExp(U+"?\\/"+ue)],[P]:[new RegExp("("+P+"|CrMo)\\/"+ue)],[O]:[new RegExp("CriOS\\/"+ue)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+ue)],[R]:[se],[G]:[se],[I]:[new RegExp("(Opera|OPR)\\/"+ue)],[C]:[new RegExp(C+"\\/"+ue)],[W]:[new RegExp("FxiOS\\/"+ue)],[Q]:[new RegExp("Konqueror[:/]?"+ue,"i")],[y]:[new RegExp(y+" "+ue),se],[z]:[new RegExp("android\\s"+ue,"i")],[k]:[new RegExp(M+"\\/"+ue)],[Z]:[new RegExp("OculusBrowser\\/"+ue)],[ee]:[new RegExp(ee+"\\/"+ue)],[re]:[new RegExp("YaBrowser\\/"+ue)],[ne]:[new RegExp(ne+"\\/"+ue)],[ae]:[new RegExp(ae+"\\/"+ue)],[te]:[new RegExp("(DuckDuckGo|Ddg)\\/"+ue)],[ie]:[new RegExp("PaleMoon\\/"+ue)],[oe]:[new RegExp(oe+"\\/"+ue)],[le]:[new RegExp("GSA\\/"+ue)],[B]:[new RegExp("(rv:|MSIE )"+ue)],Mozilla:[new RegExp("rv:"+ue)]},we=function(e,r,n,t){var i=pe(e,r,n,t),o=ge[i];if(s(o))return null;for(var a=0;o.length>a;a++){var l=e.match(o[a]);if(l)return parseFloat(l[l.length-2])}return null},me=[[new RegExp(j+"; "+j+" (.*?)[);]","i"),e=>[j,e&&e[1]||""]],[new RegExp(F,"i"),[F,""]],[new RegExp(L,"i"),[L,""]],[ve,[y,""]],[new RegExp(K,"i"),(e,r)=>{if(/Phone/.test(r)||/WPDesktop/.test(r))return[V,""];if(new RegExp(p).test(r)&&!/IEMobile\b/.test(r))return[K+" "+p,""];var n=/Windows NT ([0-9.]+)/i.exec(r);if(n&&n[1]){var t=he[n[1]]||"";return/arm/i.test(r)&&(t="RT"),[K,t]}return[K,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>e&&e[3]?[g,[e[3],e[4],e[5]||"0"].join(".")]:[g,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{var r="";return e&&e.length>=3&&(r=s(e[2])?e[3]:e[2]),["watchOS",r]}],[new RegExp("("+w+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+w+")","i"),e=>e&&e[2]?[w,[e[2],e[3],e[4]||"0"].join(".")]:[w,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{var r=["Mac OS X",""];return e&&e[1]&&(r[1]=[e[1],e[2],e[3]||"0"].join(".")),r}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[A,""]],[/Linux|debian/i,["Linux",""]]],_e=function(e){return fe.test(e)?F:de.test(e)?L:ce.test(e)?j:new RegExp(X,"i").test(e)?X:new RegExp("("+V+"|WPDesktop)","i").test(e)?V:/iPad/.test(e)?x:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?E:ve.test(e)?y:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(H,"i").test(e)?H:/(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(p).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)?w:_:new RegExp("(pda|"+p+")","i").test(e)?q:new RegExp(m,"i").test(e)&&!new RegExp(m+" pc","i").test(e)?J:""},xe="undefined"!=typeof window?window:void 0,be="undefined"!=typeof globalThis?globalThis:xe;"undefined"==typeof self&&(be.self=be),"undefined"==typeof File&&(be.File=function(){});var Ee=null==be?void 0:be.navigator,Re=null==be?void 0:be.document,ye=null==be?void 0:be.location;null!=be&&be.XMLHttpRequest&&new be.XMLHttpRequest;var $e=null==Ee?void 0:Ee.userAgent,Se=null!=xe?xe:{},Me=function(e,r){var{debugEnabled:n}=void 0===r?{}:r,t={k(r){if(xe&&(Se.POSTHOG_DEBUG||n)&&!s(xe.console)&&xe.console){for(var t=("__rrweb_original__"in xe.console[r]?xe.console[r].__rrweb_original__:xe.console[r]),i=arguments.length,o=new Array(i>1?i-1:0),a=1;i>a;a++)o[a-1]=arguments[a];t(e,...o)}},debug(){for(var e=arguments.length,r=new Array(e),n=0;e>n;n++)r[n]=arguments[n];t.k("debug",...r)},info(){for(var e=arguments.length,r=new Array(e),n=0;e>n;n++)r[n]=arguments[n];t.k("log",...r)},warn(){for(var e=arguments.length,r=new Array(e),n=0;e>n;n++)r[n]=arguments[n];t.k("warn",...r)},error(){for(var e=arguments.length,r=new Array(e),n=0;e>n;n++)r[n]=arguments[n];t.k("error",...r)},critical(){for(var r=arguments.length,n=new Array(r),t=0;r>t;t++)n[t]=arguments[t];console.error(e,...n)},uninitializedWarning(e){t.error("You must initialize PostHog before calling "+e)},createLogger:(r,n)=>Me(e+" "+r,n)};return t},ke=Me("[PostHog.js]"),Pe=ke.createLogger;function Ae(e,r){if(!c(e))if(a(e))e.forEach(r);else if(f(e))e.forEach(((e,n)=>r(e,n)));else for(var n in e)i.call(e,n)&&r(e[n],n)}var Oe=function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),t=1;r>t;t++)n[t-1]=arguments[t];for(var i of n)for(var o in i)void 0!==i[o]&&(e[o]=i[o]);return e},Be=e=>{var r=null==Re?void 0:Re.createElement("a");return s(r)?null:(r.href=e,r)},De=function(e,r,n){if(!e||!r||!r.length)return e;for(var t=e.split("#"),i=t[1],o=(t[0]||"").split("?"),l=o[1],u=o[0],s=(l||"").split("&"),c=[],d=0;s.length>d;d++){var f=s[d].split("=");a(f)&&(r.includes(f[0])?c.push(f[0]+"="+n):c.push(s[d]))}var v=u;return null!=l&&(v+="?"+c.join("&")),null!=i&&(v+="#"+i),v};Math.trunc||(Math.trunc=function(e){return 0>e?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return d(e)&&isFinite(e)&&Math.floor(e)===e});class Ie{constructor(e){if(this.bytes=e,16!==e.length)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,r,n,t){if(!Number.isInteger(e)||!Number.isInteger(r)||!Number.isInteger(n)||!Number.isInteger(t)||0>e||0>r||0>n||0>t||e>0xffffffffffff||r>4095||n>1073741823||t>4294967295)throw new RangeError("invalid field value");var i=new Uint8Array(16);return i[0]=e/Math.pow(2,40),i[1]=e/Math.pow(2,32),i[2]=e/Math.pow(2,24),i[3]=e/Math.pow(2,16),i[4]=e/Math.pow(2,8),i[5]=e,i[6]=112|r>>>8,i[7]=r,i[8]=128|n>>>24,i[9]=n>>>16,i[10]=n>>>8,i[11]=n,i[12]=t>>>24,i[13]=t>>>16,i[14]=t>>>8,i[15]=t,new Ie(i)}toString(){for(var e="",r=0;this.bytes.length>r;r++)e=e+(this.bytes[r]>>>4).toString(16)+(15&this.bytes[r]).toString(16),3!==r&&5!==r&&7!==r&&9!==r||(e+="-");if(36!==e.length)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new Ie(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(var r=0;16>r;r++){var n=this.bytes[r]-e.bytes[r];if(0!==n)return Math.sign(n)}return 0}}class Ne{constructor(){this.S=0,this.C=0,this.I=new Ce}generate(){var e=this.generateOrAbort();if(s(e)){this.S=0;var r=this.generateOrAbort();if(s(r))throw new Error("Could not generate UUID after timestamp reset");return r}return e}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.M();else{if(this.S>=e+1e4)return;this.C++,this.C>4398046511103&&(this.S++,this.M())}return Ie.fromFieldsV7(this.S,Math.trunc(this.C/Math.pow(2,30)),this.C&Math.pow(2,30)-1,this.I.nextUint32())}M(){this.C=1024*this.I.nextUint32()+(1023&this.I.nextUint32())}}var Ue,Te=e=>{if("undefined"!=typeof UUIDV7_DENY_WEAK_RNG&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var r=0;e.length>r;r++)e[r]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e};xe&&!s(xe.crypto)&&crypto.getRandomValues&&(Te=e=>crypto.getRandomValues(e));class Ce{constructor(){this.R=new Uint32Array(8),this.O=1/0}nextUint32(){return this.R.length>this.O||(Te(this.R),this.O=0),this.R[this.O++]}}var We=()=>(Ue||(Ue=new Ne)).generate(),Fe="",Le=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function je(e,r){if(r){var n=function(e,r){if(void 0===r&&(r=Re),Fe)return Fe;if(!r)return"";if(["localhost","127.0.0.1"].includes(e))return"";for(var n=e.split("."),t=Math.min(n.length,8),i="dmn_chk_"+We().toString();!Fe&&t--;){var o=n.slice(t).join("."),a=i+"=1;domain=."+o+";path=/";r.cookie=a+";max-age=3",r.cookie.includes(i)&&(r.cookie=a+";max-age=0",Fe=o)}return Fe}(e);if(!n){var t=(e=>{var r=e.match(Le);return r?r[0]:""})(e);t!==n&&ke.info("Warning: cookie subdomain discovery mismatch",t,n),n=t}return n?"; domain=."+n:""}return""}var ze={N:()=>!!Re,D(e){ke.error("cookieStore error: "+e)},A(e){if(Re){try{for(var r=e+"=",n=Re.cookie.split(";").filter((e=>e.length)),t=0;n.length>t;t++){for(var i=n[t];" "==i.charAt(0);)i=i.substring(1,i.length);if(0===i.indexOf(r))return decodeURIComponent(i.substring(r.length,i.length))}}catch(e){}return null}},F(e){var r;try{r=JSON.parse(ze.A(e))||{}}catch(e){}return r},q(e,r,n,t,i){if(!Re)return!1;try{var o="",a="",l=je(Re.location.hostname,t);if(n){var u=new Date;u.setTime(u.getTime()+864e5*n),o="; expires="+u.toUTCString()}i&&(a="; secure");var s=e+"="+encodeURIComponent(JSON.stringify(r))+o+"; SameSite=Lax; path=/"+l+a;return s.length>3686.4&&ke.warn("cookieStore warning: large cookie, len="+s.length),Re.cookie=s,!0}catch(e){return!1}},P(e,r){if(null!=Re&&Re.cookie)try{ze.q(e,"",-1,r)}catch(e){return}}},Ge=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Ke=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...Ge],Ve=["$app_build","$app_name","$app_namespace","$app_version","$browser","$browser_version","$device_type","$current_url","$pathname","$os","$os_name","$os_version","$referring_domain","$referrer","$screen_height","$screen_width","$viewport_height","$viewport_width","$raw_user_agent"],He="<masked>",Xe=["li_fat_id"];function Ye(e,r,n){if(!Re)return{};var t,i,o,l=r?[...Ge,...n||[]]:[],u=(t=De(Re.URL,l,He),i=Ke.concat(e||[]),o={},Ae(i,(function(e){var r=function(e,r){for(var n,t=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),i=0;t.length>i;i++){var o=t[i].split("=");if(o[0]===r){n=o;break}}if(!a(n)||2>n.length)return"";var l=n[1];try{l=decodeURIComponent(l)}catch(e){ke.error("Skipping decoding for malformed query param: "+l)}return l.replace(/\+/g," ")}(t,e);o[e]=r||null})),o),s=function(){var e={};return Ae(Xe,(function(r){var n=ze.A(r);e[r]=n||null})),e}();return Oe(s,u)}function qe(){return navigator.language||navigator.userLanguage}var Je="$direct";function Qe(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(e){return}}function Ze(){try{return(new Date).getTimezoneOffset()}catch(e){return}}function er(r,n,t,i){var a,l,u,s;if(void 0===i&&(i=!1),!$e)return{};var c,f,v,h,g,w,b,R,y,S,M,k,P=r?[...Ge,...n||[]]:[],[A,O]=function(e){for(var r=0;me.length>r;r++){var[n,t]=me[r],i=n.exec(e),o=i&&("function"==typeof t?t(i,e):t);if(o)return o}return["",""]}($e),B=null!=(c="undefined"!=typeof navigator?navigator:void 0)&&c.brave?{brave:!0}:{},D={detectGoogleSearchApp:t},I=Oe((M={$os:A,$os_version:O,$browser:pe($e,navigator.vendor,B,D),$device:_e($e),$device_type:(h=$e,g={userAgentDataPlatform:null==(a=navigator)||null==(a=a.userAgentData)?void 0:a.platform,maxTouchPoints:null==(l=navigator)?void 0:l.maxTouchPoints,screenWidth:null==xe||null==(u=xe.screen)?void 0:u.width,screenHeight:null==xe||null==(s=xe.screen)?void 0:s.height,devicePixelRatio:null==xe?void 0:xe.devicePixelRatio},S=_e(h),S===x||S===_||"Kobo"===S||"Kindle Fire"===S||S===J?m:S===F||S===j||S===L||S===X?"Console":S===E?"Wearable":S?p:"Android"===(null==g?void 0:g.userAgentDataPlatform)&&(null!==(w=null==g?void 0:g.maxTouchPoints)&&void 0!==w?w:0)>0?600>Math.min(null!==(b=null==g?void 0:g.screenWidth)&&void 0!==b?b:0,null!==(R=null==g?void 0:g.screenHeight)&&void 0!==R?R:0)/(null!==(y=null==g?void 0:g.devicePixelRatio)&&void 0!==y?y:1)?p:m:"Desktop"),$timezone:Qe(),$timezone_offset:Ze()},k={},Ae(M,(function(e,r){("[object String]"==o.call(e)&&e.length>0||d(e))&&(k[r]=e)})),k),{$current_url:De(i?(v=null==ye?void 0:ye.href,v?v.split("#")[0]:v):null==ye?void 0:ye.href,P,He),$host:null==ye?void 0:ye.host,$pathname:null==ye?void 0:ye.pathname,$raw_user_agent:$e.length>1e3?$e.substring(0,997)+"...":$e,$browser_version:we($e,navigator.vendor,B,D),$browser_language:qe(),$browser_language_prefix:(f=qe(),"string"==typeof f?f.split("-")[0]:void 0),$screen_height:null==xe?void 0:xe.screen.height,$screen_width:null==xe?void 0:xe.screen.width,$viewport_height:null==xe?void 0:xe.innerHeight,$viewport_width:null==xe?void 0:xe.innerWidth,$lib:e.LIB_NAME,$lib_version:e.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return e.SDK_DIST_CHANNEL&&(I.$sdk_dist_channel=e.SDK_DIST_CHANNEL),I}function rr(e,r){return[...e||[],...a(r)?r:[r]]}function nr(e,r){return(s(e)?1:e)*r}function tr(e,r){return function(e){for(var r=0,n=0;e.length>n;n++)r=(r<<5)-r+e.charCodeAt(n),r|=0;return Math.abs(r)}(e)%100<v(100*r,0,100,ke)}var ir=["type"];function or(e){var{type:r,executionTimeMs:n}=e;return r+(c(n)?"":" ("+n.toFixed(2)+"ms)")}var ar=Pe("[PostHog Action RateLimiting]");function lr(e,r){console.log(e,r)}function ur(e,r,n){if(void 0===n&&(n=5),"object"!=typeof e||"object"!=typeof r)return{};if(e===r)return{};if(!e&&r)return r;if(!r||!e)return{};var t={},i=new Set([...Object.keys(e),...Object.keys(r)]);for(var o of i){var a=e[o],d=r[o];if(s(a))t[o]=d;else if(s(d))t[o]=a;else if(!(a===d||c(a)&&c(d)))if(l(a)&&l(d))if(n>1){var f=ur(a,d,n-1);u(f)||(t[o]=f)}else t[o]="max depth reached, checking for changed value";else t[o]=d}return t}var sr,cr,dr,fr=(sr=null,cr=0,dr=null,{info(e){dr!==e&&(cr=0,dr=e),cr++,sr&&clearTimeout(sr),sr=setTimeout((()=>{ar.info(1===cr?'action "'+e+'" has been rate limited':'action "'+e+'" has been rate limited ('+cr+" times)"),cr=0,sr=null}),1e3)}});function vr(e){void 0===e&&(e={});var{maskAction:r,maskState:n,titleFunction:t=or,logger:i=lr,include:o={prevState:!0,nextState:!1,changedState:!0},rateLimiterRefillRate:a=1,rateLimiterBucketSize:l=10,__stateComparisonDepth:u}=e,s=new h({refillRate:a,bucketSize:l,refillInterval:1e3,Ae:ar});return e=>a=>l=>{var c=l,d=e.getState(),f=performance.now(),v=a(c),h=performance.now()-f,p=e.getState(),g=r?r(c):c;if(!g)return v;if(s.consumeRateLimit(c.type))fr.info(c.type);else try{var w=n?n(d,g):d,m=n?n(p,g):p,_=o.changedState?ur(w,m,null!=u?u:5):void 0,{type:x}=g,b={type:x,payload:function(e,r){if(null==e)return{};var n={};for(var t in e)if({}.hasOwnProperty.call(e,t)){if(-1!==r.indexOf(t))continue;n[t]=e[t]}return n}(g,ir),timestamp:Date.now(),executionTimeMs:h,prevState:o.prevState?w:void 0,nextState:o.nextState?m:void 0,changedState:o.changedState?_:void 0},E=t(b);i(E,b)}catch(e){ar.error("Error logging state:",e)}return v}}Se.posthogCustomizations=Object.freeze({__proto__:null,browserConsoleLogger:lr,posthogKeaLogger(e){void 0===e&&(e={});var r=vr(e);return{name:"posthog-kea-logger",events:{beforeReduxStore(e){e.middleware.push(r)}}}},posthogReduxLogger:vr,printAndDropEverything:e=>(console.log("Would have sent event:",e),null),sampleByDistinctId:e=>n=>n&&tr(n.properties.distinct_id,e)?r({},n,{properties:r({},n.properties,{$sample_type:["sampleByDistinctId"],$sample_threshold:e})}):null,sampleByEvent:(e,t)=>i=>{var o,a,l;return i?n(e,i.event)?100*Math.random()<v(100*t,0,100,ke)?r({},i,{properties:r({},i.properties,{$sample_type:rr(null==(o=i.properties)?void 0:o.$sample_type,"sampleByEvent"),$sample_threshold:nr(null==(a=i.properties)?void 0:a.$sample_threshold,t),$sampled_events:rr(null==(l=i.properties)?void 0:l.$sampled_events,e)})}):null:i:null},sampleBySessionId:e=>n=>n&&tr(n.properties.$session_id,e)?r({},n,{properties:r({},n.properties,{$sample_type:rr(n.properties.$sample_type,"sampleBySessionId"),$sample_threshold:nr(n.properties.$sample_threshold,e)})}):null,sessionRecordingLoggerForPostHogInstance:e=>(r,n)=>{var t;null==e||null==(t=e.sessionRecording)||t.tryAddCustomEvent("app-state",{title:r,stateEvent:n})},setAllPersonProfilePropertiesAsPersonPropertiesForFlags(e){var r,t=Oe({},er(e.config.mask_personal_data_properties,e.config.custom_personal_data_properties,e.config.detect_google_search_app,e.config.disable_capture_url_hashes),Ye(e.config.custom_campaign_params,e.config.mask_personal_data_properties,e.config.custom_personal_data_properties),{$referrer:(null==Re?void 0:Re.referrer)||Je,$referring_domain:null!=Re&&Re.referrer&&(null==(r=Be(Re.referrer))?void 0:r.host)||Je}),i={};Ae(t,(function(e,r){(n(Ke,r)||n(Ve,r))&&(i[r]=e)})),e.setPersonPropertiesForFlags(i)}})}(); | ||
| !function(){"use strict";var e={LIB_VERSION:"1.396.6",LIB_NAME:"web"};function r(){return r=Object.assign?Object.assign.bind():function(e){for(var r=1;arguments.length>r;r++){var n=arguments[r];for(var t in n)({}).hasOwnProperty.call(n,t)&&(e[t]=n[t])}return e},r.apply(null,arguments)}function n(e,r){return-1!==e.indexOf(r)}var t=Object.prototype,i=t.hasOwnProperty,o=t.toString,a=Array.isArray||function(e){return"[object Array]"===o.call(e)},l=e=>e===Object(e)&&!a(e),u=e=>{if(l(e)){for(var r in e)if(i.call(e,r))return!1;return!0}return!1},s=e=>void 0===e,c=e=>s(e)||(e=>null===e)(e),d=e=>"[object Number]"==o.call(e)&&e==e,f=e=>e instanceof FormData;function v(e,r,n,t,i){return r>n&&(t.warn("min cannot be greater than max."),r=n),d(e)?e>n?(t.warn(" cannot be greater than max: "+n+". Using max value instead."),n):r>e?(t.warn(" cannot be less than min: "+r+". Using min value instead."),r):e:(t.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+i),v(n,r,n,t))}class h{constructor(e){this.Ee={},this.Pe=e.Pe,this.Fe=v(e.bucketSize,0,100,e.Ae),this.$e=v(e.refillRate,0,this.Fe,e.Ae),this.De=v(e.refillInterval,0,864e5,e.Ae)}Ne(e,r){var n=Math.floor((r-e.lastAccess)/this.De);n>0&&(e.tokens=Math.min(e.tokens+n*this.$e,this.Fe),e.lastAccess=e.lastAccess+n*this.De)}consumeRateLimit(e){var r,n=Date.now(),t=String(e),i=this.Ee[t];return i?this.Ne(i,n):this.Ee[t]=i={tokens:this.Fe,lastAccess:n},0===i.tokens||(i.tokens--,0===i.tokens&&(null==(r=this.Pe)||r.call(this,e)),0===i.tokens)}stop(){this.Ee={}}}var p="Mobile",g="iOS",w="Android",m="Tablet",_=w+" "+m,x="iPad",b="Apple",E=b+" Watch",R="Safari",y="BlackBerry",S="Samsung",M=S+"Browser",k=S+" Internet",P="Chrome",A=P+" OS",O=P+" "+g,B="Internet Explorer",D=B+" "+p,I="Opera",N=I+" Mini",U="Edge",T="Microsoft "+U,C="Firefox",W=C+" "+g,F="Nintendo",L="PlayStation",j="Xbox",z=w+" "+p,G=p+" "+R,K="Windows",V=K+" Phone",H="Nokia",X="Ouya",Y="Generic",q=Y+" "+p.toLowerCase(),J=Y+" "+m.toLowerCase(),Q="Konqueror",Z="Oculus Browser",ee="Vivaldi",re="Yandex",ne="Whale",te="DuckDuckGo",ie="Pale Moon",oe="Waterfox",ae="Brave",le="Google Search App",ue="(\\d+(\\.\\d+)?)",se=new RegExp("Version/"+ue),ce=new RegExp(j,"i"),de=new RegExp(L+" \\w+","i"),fe=new RegExp(F+" \\w+","i"),ve=new RegExp(y+"|PlayBook|BB10","i"),he={"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"},pe=function(e,r,t,i){r=r||"";var o=function(e){return null!=e&&e.brave?ae:null}(t);return o||(null!=i&&i.detectGoogleSearchApp&&n(e,"GSA/")?le:n(e," OPR/")&&n(e,"Mini")?N:n(e," OPR/")?I:ve.test(e)?y:n(e,"IE"+p)||n(e,"WPDesktop")?D:n(e,"OculusBrowser")?Z:n(e,M)?k:n(e,U)||n(e,"Edg/")?T:n(e,ee+"/")?ee:n(e,"YaBrowser/")?re:n(e,ne+"/")?ne:n(e,te+"/")||n(e,"Ddg/")?te:n(e,"FBIOS")?"Facebook "+p:n(e,"UCWEB")||n(e,"UCBrowser")?"UC Browser":n(e,"CriOS")?O:n(e,"CrMo")||n(e,P)?P:n(e,w)&&n(e,R)?z:n(e,"FxiOS")?W:n(e.toLowerCase(),Q.toLowerCase())?Q:n(e,ae+"/")?ae:((e,r)=>r&&n(r,b)||function(e){return n(e,R)&&!n(e,P)&&!n(e,w)}(e))(e,r)?n(e,p)?G:R:n(e,"PaleMoon/")?ie:n(e,oe+"/")?oe:n(e,C)?C:n(e,"MSIE")||n(e,"Trident/")?B:n(e,"Gecko")?C:"")},ge={[D]:[new RegExp("rv:"+ue)],[T]:[new RegExp(U+"?\\/"+ue)],[P]:[new RegExp("("+P+"|CrMo)\\/"+ue)],[O]:[new RegExp("CriOS\\/"+ue)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+ue)],[R]:[se],[G]:[se],[I]:[new RegExp("(Opera|OPR)\\/"+ue)],[C]:[new RegExp(C+"\\/"+ue)],[W]:[new RegExp("FxiOS\\/"+ue)],[Q]:[new RegExp("Konqueror[:/]?"+ue,"i")],[y]:[new RegExp(y+" "+ue),se],[z]:[new RegExp("android\\s"+ue,"i")],[k]:[new RegExp(M+"\\/"+ue)],[Z]:[new RegExp("OculusBrowser\\/"+ue)],[ee]:[new RegExp(ee+"\\/"+ue)],[re]:[new RegExp("YaBrowser\\/"+ue)],[ne]:[new RegExp(ne+"\\/"+ue)],[ae]:[new RegExp(ae+"\\/"+ue)],[te]:[new RegExp("(DuckDuckGo|Ddg)\\/"+ue)],[ie]:[new RegExp("PaleMoon\\/"+ue)],[oe]:[new RegExp(oe+"\\/"+ue)],[le]:[new RegExp("GSA\\/"+ue)],[B]:[new RegExp("(rv:|MSIE )"+ue)],Mozilla:[new RegExp("rv:"+ue)]},we=function(e,r,n,t){var i=pe(e,r,n,t),o=ge[i];if(s(o))return null;for(var a=0;o.length>a;a++){var l=e.match(o[a]);if(l)return parseFloat(l[l.length-2])}return null},me=[[new RegExp(j+"; "+j+" (.*?)[);]","i"),e=>[j,e&&e[1]||""]],[new RegExp(F,"i"),[F,""]],[new RegExp(L,"i"),[L,""]],[ve,[y,""]],[new RegExp(K,"i"),(e,r)=>{if(/Phone/.test(r)||/WPDesktop/.test(r))return[V,""];if(new RegExp(p).test(r)&&!/IEMobile\b/.test(r))return[K+" "+p,""];var n=/Windows NT ([0-9.]+)/i.exec(r);if(n&&n[1]){var t=he[n[1]]||"";return/arm/i.test(r)&&(t="RT"),[K,t]}return[K,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>e&&e[3]?[g,[e[3],e[4],e[5]||"0"].join(".")]:[g,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{var r="";return e&&e.length>=3&&(r=s(e[2])?e[3]:e[2]),["watchOS",r]}],[new RegExp("("+w+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+w+")","i"),e=>e&&e[2]?[w,[e[2],e[3],e[4]||"0"].join(".")]:[w,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{var r=["Mac OS X",""];return e&&e[1]&&(r[1]=[e[1],e[2],e[3]||"0"].join(".")),r}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[A,""]],[/Linux|debian/i,["Linux",""]]],_e=function(e){return fe.test(e)?F:de.test(e)?L:ce.test(e)?j:new RegExp(X,"i").test(e)?X:new RegExp("("+V+"|WPDesktop)","i").test(e)?V:/iPad/.test(e)?x:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?E:ve.test(e)?y:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(H,"i").test(e)?H:/(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(p).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)?w:_:new RegExp("(pda|"+p+")","i").test(e)?q:new RegExp(m,"i").test(e)&&!new RegExp(m+" pc","i").test(e)?J:""},xe="undefined"!=typeof window?window:void 0,be="undefined"!=typeof globalThis?globalThis:xe;"undefined"==typeof self&&(be.self=be),"undefined"==typeof File&&(be.File=function(){});var Ee=null==be?void 0:be.navigator,Re=null==be?void 0:be.document,ye=null==be?void 0:be.location;null!=be&&be.XMLHttpRequest&&new be.XMLHttpRequest;var $e=null==Ee?void 0:Ee.userAgent,Se=null!=xe?xe:{},Me=function(e,r){var{debugEnabled:n}=void 0===r?{}:r,t={k(r){if(xe&&(Se.POSTHOG_DEBUG||n)&&!s(xe.console)&&xe.console){for(var t=("__rrweb_original__"in xe.console[r]?xe.console[r].__rrweb_original__:xe.console[r]),i=arguments.length,o=new Array(i>1?i-1:0),a=1;i>a;a++)o[a-1]=arguments[a];t(e,...o)}},debug(){for(var e=arguments.length,r=new Array(e),n=0;e>n;n++)r[n]=arguments[n];t.k("debug",...r)},info(){for(var e=arguments.length,r=new Array(e),n=0;e>n;n++)r[n]=arguments[n];t.k("log",...r)},warn(){for(var e=arguments.length,r=new Array(e),n=0;e>n;n++)r[n]=arguments[n];t.k("warn",...r)},error(){for(var e=arguments.length,r=new Array(e),n=0;e>n;n++)r[n]=arguments[n];t.k("error",...r)},critical(){for(var r=arguments.length,n=new Array(r),t=0;r>t;t++)n[t]=arguments[t];console.error(e,...n)},uninitializedWarning(e){t.error("You must initialize PostHog before calling "+e)},createLogger:(r,n)=>Me(e+" "+r,n)};return t},ke=Me("[PostHog.js]"),Pe=ke.createLogger;function Ae(e,r){if(!c(e))if(a(e))e.forEach(r);else if(f(e))e.forEach(((e,n)=>r(e,n)));else for(var n in e)i.call(e,n)&&r(e[n],n)}var Oe=function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),t=1;r>t;t++)n[t-1]=arguments[t];for(var i of n)for(var o in i)void 0!==i[o]&&(e[o]=i[o]);return e},Be=e=>{var r=null==Re?void 0:Re.createElement("a");return s(r)?null:(r.href=e,r)},De=function(e,r,n){if(!e||!r||!r.length)return e;for(var t=e.split("#"),i=t[1],o=(t[0]||"").split("?"),l=o[1],u=o[0],s=(l||"").split("&"),c=[],d=0;s.length>d;d++){var f=s[d].split("=");a(f)&&(r.includes(f[0])?c.push(f[0]+"="+n):c.push(s[d]))}var v=u;return null!=l&&(v+="?"+c.join("&")),null!=i&&(v+="#"+i),v};Math.trunc||(Math.trunc=function(e){return 0>e?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return d(e)&&isFinite(e)&&Math.floor(e)===e});class Ie{constructor(e){if(this.bytes=e,16!==e.length)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,r,n,t){if(!Number.isInteger(e)||!Number.isInteger(r)||!Number.isInteger(n)||!Number.isInteger(t)||0>e||0>r||0>n||0>t||e>0xffffffffffff||r>4095||n>1073741823||t>4294967295)throw new RangeError("invalid field value");var i=new Uint8Array(16);return i[0]=e/Math.pow(2,40),i[1]=e/Math.pow(2,32),i[2]=e/Math.pow(2,24),i[3]=e/Math.pow(2,16),i[4]=e/Math.pow(2,8),i[5]=e,i[6]=112|r>>>8,i[7]=r,i[8]=128|n>>>24,i[9]=n>>>16,i[10]=n>>>8,i[11]=n,i[12]=t>>>24,i[13]=t>>>16,i[14]=t>>>8,i[15]=t,new Ie(i)}toString(){for(var e="",r=0;this.bytes.length>r;r++)e=e+(this.bytes[r]>>>4).toString(16)+(15&this.bytes[r]).toString(16),3!==r&&5!==r&&7!==r&&9!==r||(e+="-");if(36!==e.length)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new Ie(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(var r=0;16>r;r++){var n=this.bytes[r]-e.bytes[r];if(0!==n)return Math.sign(n)}return 0}}class Ne{constructor(){this.S=0,this.C=0,this.I=new Ce}generate(){var e=this.generateOrAbort();if(s(e)){this.S=0;var r=this.generateOrAbort();if(s(r))throw new Error("Could not generate UUID after timestamp reset");return r}return e}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.M();else{if(this.S>=e+1e4)return;this.C++,this.C>4398046511103&&(this.S++,this.M())}return Ie.fromFieldsV7(this.S,Math.trunc(this.C/Math.pow(2,30)),this.C&Math.pow(2,30)-1,this.I.nextUint32())}M(){this.C=1024*this.I.nextUint32()+(1023&this.I.nextUint32())}}var Ue,Te=e=>{if("undefined"!=typeof UUIDV7_DENY_WEAK_RNG&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var r=0;e.length>r;r++)e[r]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e};xe&&!s(xe.crypto)&&crypto.getRandomValues&&(Te=e=>crypto.getRandomValues(e));class Ce{constructor(){this.R=new Uint32Array(8),this.O=1/0}nextUint32(){return this.R.length>this.O||(Te(this.R),this.O=0),this.R[this.O++]}}var We=()=>(Ue||(Ue=new Ne)).generate(),Fe="",Le=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function je(e,r){if(r){var n=function(e,r){if(void 0===r&&(r=Re),Fe)return Fe;if(!r)return"";if(["localhost","127.0.0.1"].includes(e))return"";for(var n=e.split("."),t=Math.min(n.length,8),i="dmn_chk_"+We().toString();!Fe&&t--;){var o=n.slice(t).join("."),a=i+"=1;domain=."+o+";path=/";r.cookie=a+";max-age=3",r.cookie.includes(i)&&(r.cookie=a+";max-age=0",Fe=o)}return Fe}(e);if(!n){var t=(e=>{var r=e.match(Le);return r?r[0]:""})(e);t!==n&&ke.info("Warning: cookie subdomain discovery mismatch",t,n),n=t}return n?"; domain=."+n:""}return""}var ze={N:()=>!!Re,D(e){ke.error("cookieStore error: "+e)},A(e){if(Re){try{for(var r=e+"=",n=Re.cookie.split(";").filter((e=>e.length)),t=0;n.length>t;t++){for(var i=n[t];" "==i.charAt(0);)i=i.substring(1,i.length);if(0===i.indexOf(r))return decodeURIComponent(i.substring(r.length,i.length))}}catch(e){}return null}},F(e){var r;try{r=JSON.parse(ze.A(e))||{}}catch(e){}return r},q(e,r,n,t,i){if(!Re)return!1;try{var o="",a="",l=je(Re.location.hostname,t);if(n){var u=new Date;u.setTime(u.getTime()+864e5*n),o="; expires="+u.toUTCString()}i&&(a="; secure");var s=e+"="+encodeURIComponent(JSON.stringify(r))+o+"; SameSite=Lax; path=/"+l+a;return s.length>3686.4&&ke.warn("cookieStore warning: large cookie, len="+s.length),Re.cookie=s,!0}catch(e){return!1}},P(e,r){if(null!=Re&&Re.cookie)try{ze.q(e,"",-1,r)}catch(e){return}}},Ge=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Ke=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...Ge],Ve=["$app_build","$app_name","$app_namespace","$app_version","$browser","$browser_version","$device_type","$current_url","$pathname","$os","$os_name","$os_version","$referring_domain","$referrer","$screen_height","$screen_width","$viewport_height","$viewport_width","$raw_user_agent"],He="<masked>",Xe=["li_fat_id"];function Ye(e,r,n){if(!Re)return{};var t,i,o,l=r?[...Ge,...n||[]]:[],u=(t=De(Re.URL,l,He),i=Ke.concat(e||[]),o={},Ae(i,(function(e){var r=function(e,r){for(var n,t=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),i=0;t.length>i;i++){var o=t[i].split("=");if(o[0]===r){n=o;break}}if(!a(n)||2>n.length)return"";var l=n[1];try{l=decodeURIComponent(l)}catch(e){ke.error("Skipping decoding for malformed query param: "+l)}return l.replace(/\+/g," ")}(t,e);o[e]=r||null})),o),s=function(){var e={};return Ae(Xe,(function(r){var n=ze.A(r);e[r]=n||null})),e}();return Oe(s,u)}function qe(){return navigator.language||navigator.userLanguage}var Je="$direct";function Qe(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(e){return}}function Ze(){try{return(new Date).getTimezoneOffset()}catch(e){return}}function er(r,n,t,i){var a,l,u,s;if(void 0===i&&(i=!1),!$e)return{};var c,f,v,h,g,w,b,R,y,S,M,k,P=r?[...Ge,...n||[]]:[],[A,O]=function(e){for(var r=0;me.length>r;r++){var[n,t]=me[r],i=n.exec(e),o=i&&("function"==typeof t?t(i,e):t);if(o)return o}return["",""]}($e),B=null!=(c="undefined"!=typeof navigator?navigator:void 0)&&c.brave?{brave:!0}:{},D={detectGoogleSearchApp:t},I=Oe((M={$os:A,$os_version:O,$browser:pe($e,navigator.vendor,B,D),$device:_e($e),$device_type:(h=$e,g={userAgentDataPlatform:null==(a=navigator)||null==(a=a.userAgentData)?void 0:a.platform,maxTouchPoints:null==(l=navigator)?void 0:l.maxTouchPoints,screenWidth:null==xe||null==(u=xe.screen)?void 0:u.width,screenHeight:null==xe||null==(s=xe.screen)?void 0:s.height,devicePixelRatio:null==xe?void 0:xe.devicePixelRatio},S=_e(h),S===x||S===_||"Kobo"===S||"Kindle Fire"===S||S===J?m:S===F||S===j||S===L||S===X?"Console":S===E?"Wearable":S?p:"Android"===(null==g?void 0:g.userAgentDataPlatform)&&(null!==(w=null==g?void 0:g.maxTouchPoints)&&void 0!==w?w:0)>0?600>Math.min(null!==(b=null==g?void 0:g.screenWidth)&&void 0!==b?b:0,null!==(R=null==g?void 0:g.screenHeight)&&void 0!==R?R:0)/(null!==(y=null==g?void 0:g.devicePixelRatio)&&void 0!==y?y:1)?p:m:"Desktop"),$timezone:Qe(),$timezone_offset:Ze()},k={},Ae(M,(function(e,r){("[object String]"==o.call(e)&&e.length>0||d(e))&&(k[r]=e)})),k),{$current_url:De(i?(v=null==ye?void 0:ye.href,v?v.split("#")[0]:v):null==ye?void 0:ye.href,P,He),$host:null==ye?void 0:ye.host,$pathname:null==ye?void 0:ye.pathname,$raw_user_agent:$e.length>1e3?$e.substring(0,997)+"...":$e,$browser_version:we($e,navigator.vendor,B,D),$browser_language:qe(),$browser_language_prefix:(f=qe(),"string"==typeof f?f.split("-")[0]:void 0),$screen_height:null==xe?void 0:xe.screen.height,$screen_width:null==xe?void 0:xe.screen.width,$viewport_height:null==xe?void 0:xe.innerHeight,$viewport_width:null==xe?void 0:xe.innerWidth,$lib:e.LIB_NAME,$lib_version:e.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return e.SDK_DIST_CHANNEL&&(I.$sdk_dist_channel=e.SDK_DIST_CHANNEL),I}function rr(e,r){return[...e||[],...a(r)?r:[r]]}function nr(e,r){return(s(e)?1:e)*r}function tr(e,r){return function(e){for(var r=0,n=0;e.length>n;n++)r=(r<<5)-r+e.charCodeAt(n),r|=0;return Math.abs(r)}(e)%100<v(100*r,0,100,ke)}var ir=["type"];function or(e){var{type:r,executionTimeMs:n}=e;return r+(c(n)?"":" ("+n.toFixed(2)+"ms)")}var ar=Pe("[PostHog Action RateLimiting]");function lr(e,r){console.log(e,r)}function ur(e,r,n){if(void 0===n&&(n=5),"object"!=typeof e||"object"!=typeof r)return{};if(e===r)return{};if(!e&&r)return r;if(!r||!e)return{};var t={},i=new Set([...Object.keys(e),...Object.keys(r)]);for(var o of i){var a=e[o],d=r[o];if(s(a))t[o]=d;else if(s(d))t[o]=a;else if(!(a===d||c(a)&&c(d)))if(l(a)&&l(d))if(n>1){var f=ur(a,d,n-1);u(f)||(t[o]=f)}else t[o]="max depth reached, checking for changed value";else t[o]=d}return t}var sr,cr,dr,fr=(sr=null,cr=0,dr=null,{info(e){dr!==e&&(cr=0,dr=e),cr++,sr&&clearTimeout(sr),sr=setTimeout((()=>{ar.info(1===cr?'action "'+e+'" has been rate limited':'action "'+e+'" has been rate limited ('+cr+" times)"),cr=0,sr=null}),1e3)}});function vr(e){void 0===e&&(e={});var{maskAction:r,maskState:n,titleFunction:t=or,logger:i=lr,include:o={prevState:!0,nextState:!1,changedState:!0},rateLimiterRefillRate:a=1,rateLimiterBucketSize:l=10,__stateComparisonDepth:u}=e,s=new h({refillRate:a,bucketSize:l,refillInterval:1e3,Ae:ar});return e=>a=>l=>{var c=l,d=e.getState(),f=performance.now(),v=a(c),h=performance.now()-f,p=e.getState(),g=r?r(c):c;if(!g)return v;if(s.consumeRateLimit(c.type))fr.info(c.type);else try{var w=n?n(d,g):d,m=n?n(p,g):p,_=o.changedState?ur(w,m,null!=u?u:5):void 0,{type:x}=g,b={type:x,payload:function(e,r){if(null==e)return{};var n={};for(var t in e)if({}.hasOwnProperty.call(e,t)){if(-1!==r.indexOf(t))continue;n[t]=e[t]}return n}(g,ir),timestamp:Date.now(),executionTimeMs:h,prevState:o.prevState?w:void 0,nextState:o.nextState?m:void 0,changedState:o.changedState?_:void 0},E=t(b);i(E,b)}catch(e){ar.error("Error logging state:",e)}return v}}Se.posthogCustomizations=Object.freeze({__proto__:null,browserConsoleLogger:lr,posthogKeaLogger(e){void 0===e&&(e={});var r=vr(e);return{name:"posthog-kea-logger",events:{beforeReduxStore(e){e.middleware.push(r)}}}},posthogReduxLogger:vr,printAndDropEverything:e=>(console.log("Would have sent event:",e),null),sampleByDistinctId:e=>n=>n&&tr(n.properties.distinct_id,e)?r({},n,{properties:r({},n.properties,{$sample_type:["sampleByDistinctId"],$sample_threshold:e})}):null,sampleByEvent:(e,t)=>i=>{var o,a,l;return i?n(e,i.event)?100*Math.random()<v(100*t,0,100,ke)?r({},i,{properties:r({},i.properties,{$sample_type:rr(null==(o=i.properties)?void 0:o.$sample_type,"sampleByEvent"),$sample_threshold:nr(null==(a=i.properties)?void 0:a.$sample_threshold,t),$sampled_events:rr(null==(l=i.properties)?void 0:l.$sampled_events,e)})}):null:i:null},sampleBySessionId:e=>n=>n&&tr(n.properties.$session_id,e)?r({},n,{properties:r({},n.properties,{$sample_type:rr(n.properties.$sample_type,"sampleBySessionId"),$sample_threshold:nr(n.properties.$sample_threshold,e)})}):null,sessionRecordingLoggerForPostHogInstance:e=>(r,n)=>{var t;null==e||null==(t=e.sessionRecording)||t.tryAddCustomEvent("app-state",{title:r,stateEvent:n})},setAllPersonProfilePropertiesAsPersonPropertiesForFlags(e){var r,t=Oe({},er(e.config.mask_personal_data_properties,e.config.custom_personal_data_properties,e.config.detect_google_search_app,e.config.disable_capture_url_hashes),Ye(e.config.custom_campaign_params,e.config.mask_personal_data_properties,e.config.custom_personal_data_properties),{$referrer:(null==Re?void 0:Re.referrer)||Je,$referring_domain:null!=Re&&Re.referrer&&(null==(r=Be(Re.referrer))?void 0:r.host)||Je}),i={};Ae(t,(function(e,r){(n(Ke,r)||n(Ve,r))&&(i[r]=e)})),e.setPersonPropertiesForFlags(i)}})}(); | ||
| //# sourceMappingURL=customizations.full.js.map |
@@ -96,2 +96,4 @@ export declare const PEOPLE_DISTINCT_ID_KEY = "$people_distinct_id"; | ||
| export declare const SURVEYS_REQUEST_TIMEOUT_MS = 10000; | ||
| export declare const SURVEYS_CACHE_TTL_MS: number; | ||
| export declare const SURVEYS_REFRESH_BACKOFF_MS: number; | ||
| export declare const LOAD_EXT_NOT_FOUND = "PostHog loadExternalDependency extension not found."; | ||
@@ -98,0 +100,0 @@ export declare const COOKIELESS_ON_REJECT: "on_reject"; |
@@ -14,2 +14,3 @@ import type { Extension } from './extensions/types'; | ||
| private _getSurveysInFlightPromise; | ||
| private _lastSurveyRefreshFailedAt; | ||
| private get _config(); | ||
@@ -47,2 +48,30 @@ constructor(_instance: PostHog); | ||
| getSurveys(callback: SurveyCallback, forceReload?: boolean): void; | ||
| /** | ||
| * Whether to kick off a background refresh of the cached definitions: the cache is stale, no | ||
| * fetch is already in flight, and we're not backing off after a recent failure. | ||
| */ | ||
| private _shouldBackgroundRefreshSurveys; | ||
| /** | ||
| * Whether the cached `$surveys` definitions have aged past their TTL. Returns false when no | ||
| * timestamp is recorded (e.g. surveys injected directly in tests) so the cache stays valid. | ||
| */ | ||
| private _isSurveyCacheStale; | ||
| private _isSurveyRefreshBackingOff; | ||
| /** | ||
| * Marks a survey as seen for the current device, mirroring the local state the SDK records | ||
| * when it shows or sends a survey itself. | ||
| * | ||
| * Use this when you display surveys through your own backend/integration (so the SDK never | ||
| * captures the `survey shown`/`sent`/`dismissed` events) and still want PostHog's display | ||
| * logic to honour the "already seen" and wait-period checks on subsequent page loads. | ||
| * | ||
| * Note: surveys configured to repeat (`schedule: 'always'` or event `repeatedActivation`) | ||
| * intentionally bypass the seen check, so marking them as seen will not stop them showing. | ||
| * | ||
| * @param surveyId The ID of the survey to mark as seen. | ||
| * @param options Optional settings. `iteration` is the survey's current iteration number, if any. | ||
| */ | ||
| markSurveyAsSeen(surveyId: string, options?: { | ||
| iteration?: number | null; | ||
| }): void; | ||
| /** Helper method to notify all registered callbacks */ | ||
@@ -49,0 +78,0 @@ private _notifySurveyCallbacks; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"tracing-headers.js","sources":["../../core/dist/utils/type-utils.mjs","../src/extensions/replay/rrweb-plugins/patch.ts","../src/utils/globals.ts","../src/entrypoints/tracing-headers.ts","../src/constants.ts"],"sourcesContent":["import { knownUnsafeEditableEvent, knownUnsafeEditableEventProperty } from \"../types.mjs\";\nimport { includes } from \"./string-utils.mjs\";\nconst nativeIsArray = Array.isArray;\nconst ObjProto = Object.prototype;\nconst type_utils_hasOwnProperty = ObjProto.hasOwnProperty;\nconst type_utils_toString = ObjProto.toString;\nconst isArray = nativeIsArray || function(obj) {\n return '[object Array]' === type_utils_toString.call(obj);\n};\nconst isFunction = (x)=>'function' == typeof x;\nconst isNativeFunction = (x)=>isFunction(x) && -1 !== x.toString().indexOf('[native code]');\nconst isObject = (x)=>x === Object(x) && !isArray(x);\nconst isEmptyObject = (x)=>{\n if (isObject(x)) {\n for(const key in x)if (type_utils_hasOwnProperty.call(x, key)) return false;\n return true;\n }\n return false;\n};\nconst isUndefined = (x)=>void 0 === x;\nconst isString = (x)=>'[object String]' == type_utils_toString.call(x);\nconst isEmptyString = (x)=>isString(x) && 0 === x.trim().length;\nconst isNull = (x)=>null === x;\nconst isNullish = (x)=>isUndefined(x) || isNull(x);\nconst isNumber = (x)=>'[object Number]' == type_utils_toString.call(x) && x === x;\nconst isPositiveNumber = (value)=>isNumber(value) && value > 0;\nconst isBoolean = (x)=>'[object Boolean]' === type_utils_toString.call(x);\nconst isFormData = (x)=>x instanceof FormData;\nconst isFile = (x)=>x instanceof File;\nconst isPlainError = (x)=>x instanceof Error;\nconst isKnownUnsafeEditableEvent = (x)=>includes(knownUnsafeEditableEvent, x);\nconst isKnownUnsafeEditableEventProperty = (x)=>includes(knownUnsafeEditableEventProperty, x);\nfunction isPrimitive(value) {\n return null === value || 'object' != typeof value;\n}\nfunction isBuiltin(candidate, className) {\n return Object.prototype.toString.call(candidate) === `[object ${className}]`;\n}\nfunction isError(candidate) {\n switch(Object.prototype.toString.call(candidate)){\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n case '[object DOMError]':\n case '[object WebAssembly.Exception]':\n return true;\n default:\n return isInstanceOf(candidate, Error);\n }\n}\nfunction isErrorEvent(event) {\n return isBuiltin(event, 'ErrorEvent');\n}\nfunction isEvent(candidate) {\n return 'undefined' != typeof Event && isInstanceOf(candidate, Event);\n}\nfunction isPlainObject(candidate) {\n return isBuiltin(candidate, 'Object');\n}\nfunction isInstanceOf(candidate, base) {\n try {\n return candidate instanceof base;\n } catch {\n return false;\n }\n}\nconst yesLikeValues = [\n true,\n 'true',\n 1,\n '1',\n 'yes'\n];\nconst isYesLike = (val)=>includes(yesLikeValues, val);\nconst noLikeValues = [\n false,\n 'false',\n 0,\n '0',\n 'no'\n];\nconst isNoLike = (val)=>includes(noLikeValues, val);\nexport { type_utils_hasOwnProperty as hasOwnProperty, isArray, isBoolean, isBuiltin, isEmptyObject, isEmptyString, isError, isErrorEvent, isEvent, isFile, isFormData, isFunction, isKnownUnsafeEditableEvent, isKnownUnsafeEditableEventProperty, isNativeFunction, isNoLike, isNull, isNullish, isNumber, isObject, isPlainError, isPlainObject, isPositiveNumber, isPrimitive, isString, isUndefined, isYesLike, noLikeValues, yesLikeValues };\n","// Portions of this file are derived from getsentry/sentry-javascript\n// Copyright (c) 2012 Functional Software, Inc. dba Sentry\n// Licensed under the MIT License: https://github.com/getsentry/sentry-javascript/blob/develop/LICENSE\n\n// import { patch } from 'rrweb/typings/utils'\n// copied from https://github.com/rrweb-io/rrweb/blob/8aea5b00a4dfe5a6f59bd2ae72bb624f45e51e81/packages/rrweb/src/utils.ts#L129\nimport { isFunction } from '@posthog/core'\n\nexport function patch(\n source: { [key: string]: any },\n name: string,\n replacement: (...args: unknown[]) => unknown\n): () => void {\n try {\n if (!(name in source)) {\n return () => {\n //\n }\n }\n\n const original = source[name] as () => unknown\n const wrapped = replacement(original)\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (isFunction(wrapped)) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n wrapped.prototype = wrapped.prototype || {}\n Object.defineProperties(wrapped, {\n __posthog_wrapped__: {\n enumerable: false,\n value: true,\n },\n })\n }\n\n source[name] = wrapped\n\n return () => {\n if (source[name] === wrapped) {\n source[name] = original\n }\n }\n } catch {\n return () => {\n //\n }\n // This can throw when multiple instrumentation layers try to wrap the same global object,\n // such as XMLHttpRequest, and redefine the same non-configurable wrapper marker.\n }\n}\n","import type { PostHog } from '../posthog-core'\nimport { SessionIdManager } from '../sessionid'\nimport {\n DeadClicksAutoCaptureConfig,\n ExternalIntegrationKind,\n Properties,\n RemoteConfig,\n SiteAppLoader,\n SessionStartReason,\n} from '../types'\nimport type {\n ConversationsRemoteConfig,\n GetMessagesResponse,\n GetTicketsOptions,\n GetTicketsResponse,\n MarkAsReadResponse,\n RestoreFromTokenResponse,\n RequestRestoreLinkResponse,\n SendMessageResponse,\n UserProvidedTraits,\n} from '../posthog-conversations-types'\n// only importing types here, so won't affect the bundle\n// eslint-disable-next-line posthog-js/no-external-replay-imports\nimport type { SessionRecordingStatus, TriggerType } from '../extensions/replay/external/triggerMatching'\nimport type { TracingHeadersDistinctId, TracingHeadersHostnames } from '../extensions/tracing-headers-types'\nimport { eventWithTime } from '../extensions/replay/types/rrweb-types'\nimport { ErrorTracking } from '@posthog/core'\n\n/*\n * Global helpers to protect access to browser globals in a way that is safer for different targets\n * like DOM, SSR, Web workers etc.\n *\n * NOTE: Typically we want the \"window\" but globalThis works for both the typical browser context as\n * well as other contexts such as the web worker context. Window is still exported for any bits that explicitly require it.\n * If in doubt - export the global you need from this file and use that as an optional value. This way the code path is forced\n * to handle the case where the global is not available.\n */\n\n// eslint-disable-next-line no-restricted-globals\nconst win: (Window & typeof globalThis) | undefined = typeof window !== 'undefined' ? window : undefined\n\nexport type AssignableWindow = Window &\n typeof globalThis & {\n /*\n * Main PostHog instance\n */\n posthog: any\n\n /*\n * This is our contract between (potentially) lazily loaded extensions and the SDK\n */\n __PosthogExtensions__?: PostHogExtensions\n\n /**\n * When loading remote config, we assign it to this global configuration\n * for ease of sharing it with the rest of the SDK\n */\n _POSTHOG_REMOTE_CONFIG?: Record<\n string,\n {\n config: RemoteConfig\n siteApps: SiteAppLoader[]\n }\n >\n\n /**\n * If this is set on the window, our logger will log to the console\n * for ease of debugging. Used for testing purposes only.\n *\n * @see {Config.DEBUG} from config.ts\n */\n POSTHOG_DEBUG: any\n\n // Exposed by the browser\n doNotTrack: any\n\n // See entrypoints/customizations.full.ts\n posthogCustomizations: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/exception-autocapture.ts\n *\n * @deprecated use `__PosthogExtensions__.errorWrappingFunctions` instead\n */\n posthogErrorWrappingFunctions: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/posthog-recorder.ts\n *\n * @deprecated use `__PosthogExtensions__.rrweb` instead\n */\n rrweb: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/posthog-recorder.ts\n *\n * @deprecated use `__PosthogExtensions__.rrwebConsoleRecord` instead\n */\n rrwebConsoleRecord: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/posthog-recorder.ts\n *\n * @deprecated use `__PosthogExtensions__.getRecordNetworkPlugin` instead\n */\n getRecordNetworkPlugin: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/web-vitals.ts\n *\n * @deprecated use `__PosthogExtensions__.postHogWebVitalsCallbacks` instead\n */\n postHogWebVitalsCallbacks: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/tracing-headers.ts\n *\n * @deprecated use `__PosthogExtensions__.postHogTracingHeadersPatchFns` instead\n */\n postHogTracingHeadersPatchFns: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/surveys.ts\n *\n * @deprecated use `__PosthogExtensions__.generateSurveys` instead\n */\n extendPostHogWithSurveys: any\n\n /*\n * These are used to handle our toolbar state.\n * @see {Toolbar} from extensions/toolbar.ts\n */\n ph_load_toolbar: any\n ph_load_editor: any\n ph_toolbar_state: any\n } & Record<`__$$ph_site_app_${string}`, any>\n\n/**\n * This is our contract between (potentially) lazily loaded extensions and the SDK\n * changes to this interface can be breaking changes for users of the SDK\n */\n\nexport type ExternalExtensionKind = 'intercom-integration' | 'crisp-chat-integration'\n\nexport type PostHogExtensionKind =\n | 'toolbar'\n | 'exception-autocapture'\n | 'web-vitals'\n | 'web-vitals-with-attribution'\n | 'recorder'\n | 'lazy-recorder'\n | 'tracing-headers'\n | 'surveys'\n | 'logs'\n | 'conversations'\n | 'product-tours'\n | 'dead-clicks-autocapture'\n | 'remote-config'\n | ExternalExtensionKind\n\nexport interface LazyLoadedSessionRecordingInterface {\n start: (startReason?: SessionStartReason) => void\n stop: () => void\n discard: () => void\n sessionId: string\n status: SessionRecordingStatus\n onRRwebEmit: (rawEvent: eventWithTime) => void\n log: (message: string, level: 'log' | 'warn' | 'error') => void\n sdkDebugProperties: Properties\n overrideLinkedFlag: () => void\n overrideSampling: () => void\n overrideTrigger: (triggerType: TriggerType) => void\n isStarted: boolean\n tryAddCustomEvent(tag: string, payload: any): boolean\n}\n\nexport interface LazyLoadedDeadClicksAutocaptureInterface {\n start: (observerTarget: Node) => void\n stop: () => void\n}\n\nexport interface LazyLoadedConversationsInterface {\n // Widget control\n show: () => void\n hide: () => void\n isVisible: () => boolean\n\n // Lifecycle\n reset: () => void\n\n // Identity verification\n setIdentity: () => void\n clearIdentity: () => void\n\n // API methods\n sendMessage: (message: string, userTraits?: UserProvidedTraits, newTicket?: boolean) => Promise<SendMessageResponse>\n getMessages: (ticketId?: string, after?: string) => Promise<GetMessagesResponse>\n markAsRead: (ticketId?: string) => Promise<MarkAsReadResponse>\n getTickets: (options?: GetTicketsOptions) => Promise<GetTicketsResponse>\n requestRestoreLink: (email: string) => Promise<RequestRestoreLinkResponse>\n restoreFromToken: (restoreToken: string) => Promise<RestoreFromTokenResponse>\n restoreFromUrlToken: () => Promise<RestoreFromTokenResponse | null>\n getCurrentTicketId: () => string | null\n getWidgetSessionId: () => string\n}\n\ninterface PostHogExtensions {\n loadExternalDependency?: (\n posthog: PostHog,\n kind: PostHogExtensionKind,\n callback: (error?: string | Event, event?: Event) => void\n ) => void\n\n loadSiteApp?: (posthog: PostHog, appUrl: string, callback: (error?: string | Event, event?: Event) => void) => void\n\n errorWrappingFunctions?: {\n wrapOnError: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void\n wrapUnhandledRejection: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void\n wrapConsoleError: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void\n }\n rrweb?: { record: any; version: string; wasMaxDepthReached?: () => boolean; resetMaxDepthState?: () => void }\n rrwebPlugins?: { getRecordConsolePlugin: any; getRecordNetworkPlugin?: any }\n generateSurveys?: (posthog: PostHog, isSurveysEnabled: boolean) => any | undefined\n generateProductTours?: (posthog: PostHog, isEnabled: boolean) => any | undefined\n logs?: {\n initializeLogs?: (posthog: PostHog) => any | undefined\n }\n postHogWebVitalsCallbacks?: {\n onLCP: (metric: any) => void\n onCLS: (metric: any) => void\n onFCP: (metric: any) => void\n onINP: (metric: any) => void\n }\n /**\n * @deprecated\n *\n * this was introduced briefly, it is now always a no-op and only kept for backwards compatibility\n */\n loadWebVitalsCallbacks?: (useAttribution?: boolean) => PostHogExtensions['postHogWebVitalsCallbacks']\n tracingHeadersPatchFns?: {\n _patchFetch: (\n hostnames: TracingHeadersHostnames,\n distinctId: TracingHeadersDistinctId,\n sessionManager?: SessionIdManager\n ) => () => void\n _patchXHR: (\n hostnames: TracingHeadersHostnames,\n distinctId: TracingHeadersDistinctId,\n sessionManager?: SessionIdManager\n ) => () => void\n }\n initDeadClicksAutocapture?: (\n ph: PostHog,\n config: DeadClicksAutoCaptureConfig\n ) => LazyLoadedDeadClicksAutocaptureInterface\n integrations?: {\n [K in ExternalIntegrationKind]?: { start: (posthog: PostHog) => void; stop: () => void }\n }\n initSessionRecording?: (ph: PostHog) => LazyLoadedSessionRecordingInterface\n initConversations?: (config: ConversationsRemoteConfig, posthog: PostHog) => LazyLoadedConversationsInterface\n}\n\nconst global: typeof globalThis | undefined = typeof globalThis !== 'undefined' ? globalThis : win\n\n// React Native polyfills for posthog-js compatibility\nif (typeof self === 'undefined') {\n ;(global as any).self = global\n}\nif (typeof File === 'undefined') {\n ;(global as any).File = function () {}\n}\n\nexport const navigator = global?.navigator\nexport const document = global?.document\nexport const location = global?.location\nexport const fetch = global?.fetch\nexport const XMLHttpRequest =\n global?.XMLHttpRequest && 'withCredentials' in new global.XMLHttpRequest() ? global.XMLHttpRequest : undefined\nexport const AbortController = global?.AbortController\nexport const CompressionStream = global?.CompressionStream\nexport const userAgent = navigator?.userAgent\nexport const assignableWindow: AssignableWindow = win ?? ({} as any)\n\nexport { win as window }\n","import { SessionIdManager } from '../sessionid'\nimport { patch } from '../extensions/replay/rrweb-plugins/patch'\nimport { assignableWindow, window } from '../utils/globals'\nimport { COOKIELESS_SENTINEL_VALUE } from '../constants'\nimport { isArray, isFunction, isNull, isUndefined } from '@posthog/core'\nimport type { TracingHeadersDistinctId, TracingHeadersHostnames } from '../extensions/tracing-headers-types'\n\nconst SESSION_ID_HEADER = 'X-POSTHOG-SESSION-ID'\nconst WINDOW_ID_HEADER = 'X-POSTHOG-WINDOW-ID'\nconst DISTINCT_ID_HEADER = 'X-POSTHOG-DISTINCT-ID'\nconst TRACING_HEADERS = [SESSION_ID_HEADER, WINDOW_ID_HEADER, DISTINCT_ID_HEADER]\nconst REQUEST_INIT_KEYS = [\n 'attributionReporting',\n 'body',\n 'browsingTopics',\n 'cache',\n 'credentials',\n 'dispatcher',\n 'duplex',\n 'integrity',\n 'keepalive',\n 'method',\n 'mode',\n 'priority',\n 'redirect',\n 'referrer',\n 'referrerPolicy',\n 'signal',\n 'window',\n]\n\nconst hasOwnProperty = (value: object, property: PropertyKey): boolean =>\n Object.prototype.hasOwnProperty.call(value, property)\n\nconst isObjectLike = (value: unknown): value is object =>\n (typeof value === 'object' && !isNull(value)) || isFunction(value)\n\nconst isRequest = (value: unknown): value is Request =>\n typeof Request !== 'undefined' &&\n (value instanceof Request || Object.prototype.toString.call(value) === '[object Request]')\n\nconst getRequestUrl = (url: URL | RequestInfo): string | undefined => {\n try {\n if (isRequest(url)) {\n return url.url\n }\n\n // eslint-disable-next-line compat/compat\n return new URL(url instanceof URL ? url.toString() : String(url), window?.location?.href).toString()\n } catch {\n return undefined\n }\n}\n\n// RequestInit is a WebIDL dictionary: native fetch reads known keys via property access, including inherited\n// and non-enumerable properties. Avoid `{ ...init, headers }`, which can drop body/signal/duplex/etc. Instead,\n// overlay only `headers` while forwarding every other lookup to the caller's original init object.\nconst createFetchInitWithHeaders = (init: RequestInit | undefined, headers: Headers): RequestInit | undefined => {\n if (isUndefined(init) || isNull(init)) {\n return { headers }\n }\n if (!isObjectLike(init)) {\n return undefined\n }\n\n const originalInit = init as RequestInit & Record<PropertyKey, unknown>\n\n if (typeof Proxy === 'undefined' || typeof Reflect === 'undefined') {\n // Older browsers without Proxy still get an inherited overlay, which preserves native fetch property lookup.\n const initWithHeaders = Object.create(originalInit) as RequestInit\n Object.defineProperty(initWithHeaders, 'headers', {\n configurable: true,\n enumerable: true,\n value: headers,\n writable: true,\n })\n return initWithHeaders\n }\n\n const target = { headers } as RequestInit & Record<PropertyKey, unknown>\n\n return new Proxy(target, {\n get(target, property) {\n if (hasOwnProperty(target, property)) {\n return Reflect.get(target, property)\n }\n return Reflect.get(originalInit, property, originalInit)\n },\n has(target, property) {\n return hasOwnProperty(target, property) || property in originalInit\n },\n ownKeys(target) {\n const keys = new Set<string | symbol>(Reflect.ownKeys(target))\n Reflect.ownKeys(originalInit).forEach((key) => keys.add(key))\n REQUEST_INIT_KEYS.forEach((key) => {\n if (key in originalInit) {\n keys.add(key)\n }\n })\n return Array.from(keys)\n },\n getOwnPropertyDescriptor(target, property) {\n const targetDescriptor = Reflect.getOwnPropertyDescriptor(target, property)\n if (targetDescriptor) {\n return targetDescriptor\n }\n if (typeof property === 'string' && REQUEST_INIT_KEYS.includes(property) && property in originalInit) {\n return {\n configurable: true,\n enumerable: true,\n get: () => Reflect.get(originalInit, property, originalInit),\n }\n }\n\n const descriptor = Reflect.getOwnPropertyDescriptor(originalInit, property)\n return descriptor ? { ...descriptor, configurable: true } : undefined\n },\n getPrototypeOf() {\n return Object.getPrototypeOf(originalInit)\n },\n }) as RequestInit\n}\n\nconst getDistinctId = (distinctId: TracingHeadersDistinctId): string | undefined =>\n isFunction(distinctId) ? distinctId() : distinctId\n\nconst addTracingHeaders = (\n hostnames: TracingHeadersHostnames,\n distinctId: TracingHeadersDistinctId,\n sessionManager: SessionIdManager | undefined,\n url: string,\n headers: Headers\n): boolean => {\n let reqHostname: string\n try {\n // we don't need to support IE11 here\n // eslint-disable-next-line compat/compat\n reqHostname = new URL(url).hostname\n } catch {\n // If the URL is invalid, we skip adding tracing headers\n return false\n }\n if (!hostnames) {\n return false\n }\n if (isArray(hostnames) && !hostnames.includes(reqHostname)) {\n return false\n }\n\n let hasAddedHeaders = false\n if (sessionManager) {\n const { sessionId, windowId } = sessionManager.checkAndGetSessionAndWindowId(true)\n headers.set(SESSION_ID_HEADER, sessionId)\n headers.set(WINDOW_ID_HEADER, windowId)\n hasAddedHeaders = true\n }\n const currentDistinctId = getDistinctId(distinctId)\n if (currentDistinctId && currentDistinctId !== COOKIELESS_SENTINEL_VALUE) {\n headers.set(DISTINCT_ID_HEADER, currentDistinctId)\n hasAddedHeaders = true\n }\n return hasAddedHeaders\n}\n\ntype FetchArgs = [URL | RequestInfo] | [URL | RequestInfo, RequestInit | undefined]\n\nconst patchFetch = (\n hostnames: TracingHeadersHostnames,\n distinctId: TracingHeadersDistinctId,\n sessionManager?: SessionIdManager\n): (() => void) => {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return patch(window, 'fetch', (originalFetch: typeof fetch) => {\n return function (this: unknown, url: URL | RequestInfo, init?: RequestInit | undefined) {\n const originalArgs = (arguments.length > 1 ? [url, init] : [url]) as FetchArgs\n let fetchArgs = originalArgs\n\n try {\n const requestUrl = getRequestUrl(url)\n if (requestUrl) {\n if (isRequest(url)) {\n // For fetch(Request, init), construct a new Request so init overrides are applied and the\n // caller's Request is not mutated. For fetch(url, init), avoid this because it exposes string\n // bodies as ReadableStreams to downstream wrappers in Safari.\n // eslint-disable-next-line compat/compat\n const req = new Request(url, init)\n addTracingHeaders(hostnames, distinctId, sessionManager, req.url, req.headers)\n fetchArgs = [req]\n } else {\n const headers = new Headers(isObjectLike(init) ? init.headers : undefined)\n if (addTracingHeaders(hostnames, distinctId, sessionManager, requestUrl, headers)) {\n const initWithHeaders = createFetchInitWithHeaders(init, headers)\n if (initWithHeaders) {\n fetchArgs = [url, initWithHeaders]\n }\n }\n }\n }\n } catch {\n fetchArgs = originalArgs\n }\n\n return originalFetch.apply(this, fetchArgs)\n }\n })\n}\n\nconst patchXHR = (\n hostnames: TracingHeadersHostnames,\n distinctId: TracingHeadersDistinctId,\n sessionManager?: SessionIdManager\n): (() => void) => {\n return patch(\n // we can assert this is present because we've checked previously\n window!.XMLHttpRequest.prototype,\n 'open',\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n (originalOpen: typeof XMLHttpRequest.prototype.open) => {\n return function (\n method: string,\n url: string | URL,\n async = true,\n username?: string | null,\n password?: string | null\n ) {\n // because this function is returned in its actual context `this` _is_ an XMLHttpRequest\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const xhr = this as XMLHttpRequest\n\n const headers = new Headers()\n const requestUrl = getRequestUrl(url)\n if (requestUrl) {\n addTracingHeaders(hostnames, distinctId, sessionManager, requestUrl, headers)\n }\n\n const result = originalOpen.call(xhr, method, url, async, username, password)\n\n TRACING_HEADERS.forEach((header) => {\n const value = headers.get(header)\n if (value) {\n try {\n xhr.setRequestHeader(header, value)\n } catch {\n // Do not let tracing header injection break the host app's XHR.\n }\n }\n })\n\n return result\n }\n }\n )\n}\n\nassignableWindow.__PosthogExtensions__ = assignableWindow.__PosthogExtensions__ || {}\nconst patchFns = {\n _patchFetch: patchFetch,\n _patchXHR: patchXHR,\n}\nassignableWindow.__PosthogExtensions__.tracingHeadersPatchFns = patchFns\n\n// we used to put tracingHeadersPatchFns on window, and now we put it on __PosthogExtensions__\n// but that means that old clients which lazily load this extension are looking in the wrong place\n// yuck,\n// so we also put it directly on the window\n// when 1.161.1 is the oldest version seen in production we can remove this\nassignableWindow.postHogTracingHeadersPatchFns = patchFns\n\nexport default patchFns\n","/*\n * Constants\n */\n\n/* PROPERTY KEYS */\n\n// This key is deprecated, but we want to check for it to see whether aliasing is allowed.\nexport const PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id'\nexport const DISTINCT_ID = 'distinct_id'\nexport const DEVICE_ID = '$device_id'\nexport const DEVICE_MODEL = '$device_model'\nexport const ALIAS_ID_KEY = '__alias'\nexport const CAMPAIGN_IDS_KEY = '__cmpns'\nexport const EVENT_TIMERS_KEY = '__timers'\nexport const AUTOCAPTURE_DISABLED_SERVER_SIDE = '$autocapture_disabled_server_side'\nexport const HEATMAPS_ENABLED_SERVER_SIDE = '$heatmaps_enabled_server_side'\nexport const EXCEPTION_CAPTURE_ENABLED_SERVER_SIDE = '$exception_capture_enabled_server_side'\nexport const ERROR_TRACKING_SUPPRESSION_RULES = '$error_tracking_suppression_rules'\nexport const ERROR_TRACKING_CAPTURE_EXTENSION_EXCEPTIONS = '$error_tracking_capture_extension_exceptions'\nexport const WEB_VITALS_ENABLED_SERVER_SIDE = '$web_vitals_enabled_server_side'\nexport const DEAD_CLICKS_ENABLED_SERVER_SIDE = '$dead_clicks_enabled_server_side'\nexport const PRODUCT_TOURS_ENABLED_SERVER_SIDE = '$product_tours_enabled_server_side'\nexport const WEB_VITALS_ALLOWED_METRICS = '$web_vitals_allowed_metrics'\nexport const SESSION_RECORDING_REMOTE_CONFIG = '$session_recording_remote_config'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_ENABLED_SERVER_SIDE = '$session_recording_enabled_server_side'\n// @deprecated can be removed along with eager loaded replay\nexport const CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE = '$console_log_recording_enabled_server_side'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE = '$session_recording_network_payload_capture'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_MASKING = '$session_recording_masking'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_CANVAS_RECORDING = '$session_recording_canvas_recording'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_SAMPLE_RATE = '$replay_sample_rate'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_MINIMUM_DURATION = '$replay_minimum_duration'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_SCRIPT_CONFIG = '$replay_script_config'\nexport const SESSION_RECORDING_OVERRIDE_SAMPLING = '$replay_override_sampling'\nexport const SESSION_RECORDING_OVERRIDE_LINKED_FLAG = '$replay_override_linked_flag'\nexport const SESSION_RECORDING_OVERRIDE_URL_TRIGGER = '$replay_override_url_trigger'\nexport const SESSION_RECORDING_OVERRIDE_EVENT_TRIGGER = '$replay_override_event_trigger'\nexport const SESSION_ID = '$sesid'\nexport const SESSION_RECORDING_IS_SAMPLED = '$session_is_sampled'\nexport const SESSION_RECORDING_PAST_MINIMUM_DURATION = '$session_past_minimum_duration'\nexport const SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION = '$session_recording_url_trigger_activated_session'\nexport const SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION = '$session_recording_event_trigger_activated_session'\n// V2 Trigger Groups: Per-group persistence key prefixes (suffix with group ID)\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX = '$posthog_sr_group_event_trigger_'\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX = '$posthog_sr_group_url_trigger_'\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_SAMPLING_PREFIX = '$posthog_sr_group_sampling_'\nexport const SESSION_RECORDING_FIRST_FULL_SNAPSHOT_TIMESTAMP = '$debug_first_full_snapshot_timestamp'\nexport const SESSION_RECORDING_FLUSHED_SIZE = '$sess_rec_flush_size'\nexport const ENABLED_FEATURE_FLAGS = '$enabled_feature_flags'\nexport const PERSISTENCE_ACTIVE_FEATURE_FLAGS = '$active_feature_flags'\nexport const PERSISTENCE_EARLY_ACCESS_FEATURES = '$early_access_features'\nexport const PERSISTENCE_FEATURE_FLAG_DETAILS = '$feature_flag_details'\nexport const PERSISTENCE_FEATURE_FLAG_PAYLOADS = '$feature_flag_payloads'\nexport const PERSISTENCE_FEATURE_FLAG_REQUEST_ID = '$feature_flag_request_id'\nexport const PERSISTENCE_OVERRIDE_FEATURE_FLAGS = '$override_feature_flags'\nexport const PERSISTENCE_OVERRIDE_FEATURE_FLAG_PAYLOADS = '$override_feature_flag_payloads'\nexport const STORED_PERSON_PROPERTIES_KEY = '$stored_person_properties'\nexport const STORED_GROUP_PROPERTIES_KEY = '$stored_group_properties'\nexport const SURVEYS = '$surveys'\nexport const SURVEYS_LOADED_AT = '$surveys_loaded_at'\nexport const SURVEYS_ACTIVATED = '$surveys_activated'\nexport const PRODUCT_TOURS = 'ph_product_tours'\nexport const PRODUCT_TOURS_ACTIVATED = '$product_tours_activated'\nexport const CONVERSATIONS = '$conversations'\nexport const CONVERSATIONS_LEGACY_WIDGET_SESSION_ID = '$conversations_widget_session_id'\nexport const CONVERSATIONS_LEGACY_TICKET_ID = '$conversations_ticket_id'\nexport const CONVERSATIONS_LEGACY_WIDGET_STATE = '$conversations_widget_state'\nexport const CONVERSATIONS_LEGACY_USER_TRAITS = '$conversations_user_traits'\nexport const FLAG_CALL_REPORTED = '$flag_call_reported'\nexport const FLAG_CALL_REPORTED_SESSION_ID = '$flag_call_reported_session_id'\nexport const PERSISTENCE_FEATURE_FLAG_ERRORS = '$feature_flag_errors'\nexport const PERSISTENCE_FEATURE_FLAG_EVALUATED_AT = '$feature_flag_evaluated_at'\nexport const USER_STATE = '$user_state'\nexport const CLIENT_SESSION_PROPS = '$client_session_props'\nexport const CAPTURE_RATE_LIMIT = '$capture_rate_limit'\n\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_CAMPAIGN_PARAMS = '$initial_campaign_params'\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_REFERRER_INFO = '$initial_referrer_info'\nexport const INITIAL_PERSON_INFO = '$initial_person_info'\nexport const ENABLE_PERSON_PROCESSING = '$epp'\nexport const TOOLBAR_ID = '__POSTHOG_TOOLBAR__'\nexport const TOOLBAR_CONTAINER_CLASS = 'toolbar-global-fade-container'\n\n/**\n * PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION\n * Sentinel value for distinct id, device id, session id. Signals that the server should generate the value\n * */\nexport const COOKIELESS_SENTINEL_VALUE = '$posthog_cookieless'\nexport const COOKIELESS_MODE_FLAG_PROPERTY = '$cookieless_mode'\n\nexport const WEB_EXPERIMENTS = '$web_experiments'\n\nexport const SDK_DIST_CHANNEL = '$sdk_dist_channel'\nexport const SDK_DEBUG_EXTENSIONS_INIT_METHOD = '$sdk_debug_extensions_init_method'\nexport const SDK_DEBUG_EXTENSIONS_INIT_TIME_MS = '$sdk_debug_extensions_init_time_ms'\nexport const SDK_DEBUG_RECORDING_SCRIPT_NOT_LOADED = '$sdk_debug_recording_script_not_loaded'\nexport const SDK_DEBUG_REPLAY_EVENT_TRIGGER_STATUS = '$sdk_debug_replay_event_trigger_status'\nexport const SDK_DEBUG_REPLAY_LINKED_FLAG_TRIGGER_STATUS = '$sdk_debug_replay_linked_flag_trigger_status'\nexport const SDK_DEBUG_REPLAY_MATCHED_RECORDING_TRIGGER_GROUPS = '$sdk_debug_replay_matched_recording_trigger_groups'\nexport const SDK_DEBUG_REPLAY_REMOTE_TRIGGER_MATCHING_CONFIG = '$sdk_debug_replay_remote_trigger_matching_config'\nexport const SDK_DEBUG_REPLAY_TRIGGER_GROUPS_COUNT = '$sdk_debug_replay_trigger_groups_count'\nexport const SDK_DEBUG_REPLAY_URL_TRIGGER_STATUS = '$sdk_debug_replay_url_trigger_status'\nexport const SDK_DEBUG_REPLAY_RRWEB_ATTACHED = '$sdk_debug_rrweb_attached'\nexport const SDK_DEBUG_REPLAY_RRWEB_START_ATTEMPTED = '$sdk_debug_rrweb_start_attempted'\nexport const SESSION_RECORDING_START_REASON = '$session_recording_start_reason'\n\nexport const SURVEYS_REQUEST_TIMEOUT_MS = 10000\nexport const LOAD_EXT_NOT_FOUND = 'PostHog loadExternalDependency extension not found.'\n\n/* EVENT NAMES - interned to reduce bundle size */\n/* COOKIELESS MODE VALUES */\nexport const COOKIELESS_ON_REJECT = 'on_reject' as const\nexport const COOKIELESS_ALWAYS = 'always' as const\n\n/* USER STATE VALUES */\nexport const USER_STATE_ANONYMOUS = 'anonymous'\nexport const USER_STATE_IDENTIFIED = 'identified'\n\n/* PERSON PROFILE MODES */\nexport const PERSON_PROFILES_IDENTIFIED_ONLY = 'identified_only' as const\n\n/* DOM EVENT NAMES - interned to reduce bundle size */\nexport const DOM_EVENT_VISIBILITYCHANGE = 'visibilitychange'\nexport const DOM_EVENT_BEFOREUNLOAD = 'beforeunload'\n\nexport const EVENT_PAGEVIEW = '$pageview'\nexport const EVENT_PAGELEAVE = '$pageleave'\nexport const EVENT_IDENTIFY = '$identify'\nexport const EVENT_GROUPIDENTIFY = '$groupidentify'\n\n/* Z-INDEX HIERARCHY: tours > surveys > support */\nexport const Z_INDEX_TOURS = 2147483646\nexport const Z_INDEX_SURVEYS = 2147483645\nexport const Z_INDEX_CONVERSATIONS = 2147483644\n"],"names":["type_utils_toString","Object","prototype","toString","isArray","Array","obj","call","isFunction","x","isNull","patch","source","name","replacement","original","wrapped","defineProperties","__posthog_wrapped__","enumerable","value","_unused","win","window","undefined","global","globalThis","self","File","XMLHttpRequest","assignableWindow","SESSION_ID_HEADER","WINDOW_ID_HEADER","DISTINCT_ID_HEADER","TRACING_HEADERS","REQUEST_INIT_KEYS","hasOwnProperty","property","isObjectLike","isRequest","Request","getRequestUrl","url","_window$location","URL","String","location","href","addTracingHeaders","hostnames","distinctId","sessionManager","headers","reqHostname","hostname","_unused2","includes","hasAddedHeaders","sessionId","windowId","checkAndGetSessionAndWindowId","set","currentDistinctId","getDistinctId","__PosthogExtensions__","patchFns","_patchFetch","patchFetch","originalFetch","init","originalArgs","arguments","length","fetchArgs","requestUrl","req","Headers","initWithHeaders","createFetchInitWithHeaders","originalInit","Proxy","Reflect","create","defineProperty","configurable","writable","get","target","has","ownKeys","keys","Set","forEach","key","add","from","getOwnPropertyDescriptor","targetDescriptor","descriptor","_extends","getPrototypeOf","_unused3","apply","this","_patchXHR","patchXHR","originalOpen","method","async","username","password","xhr","result","header","setRequestHeader","_unused4","tracingHeadersPatchFns","postHogTracingHeadersPatchFns"],"mappings":"iPAEA,IAGMA,EAFWC,CAAOC,EAEaC,SAC/BC,EAJgBC,MAAMD,SAIK,SAASE,GACtC,MAAO,mBAAqBN,EAAoBO,KAAKD,EACzD,EACME,EAAcC,GAAI,mBAAqBA,EAavCC,EAAUD,GAAI,OAASA,ECdtB,SAASE,EACZC,EACAC,EACAC,GAEA,IACI,KAAMD,KAAQD,GACV,MAAO,OAKX,IAAMG,EAAWH,EAAOC,GAClBG,EAAUF,EAAYC,GAiB5B,OAbIP,EAAWQ,KAEXA,EAAQd,UAAYc,EAAQd,WAAa,CAAA,EACzCD,OAAOgB,iBAAiBD,EAAS,CAC7BE,oBAAqB,CACjBC,YAAY,EACZC,OAAO,MAKnBR,EAAOC,GAAQG,EAER,KACCJ,EAAOC,KAAUG,IACjBJ,EAAOC,GAAQE,EACnB,CAER,CAAE,MAAAM,GACE,MAAO,MAKX,CACJ,CCXA,IAAMC,EAAkE,oBAAXC,OAAyBA,YAASC,EAoPzFC,EAA8D,oBAAfC,WAA6BA,WAAaJ,EAG3E,oBAATK,OACLF,EAAeE,KAAOF,GAER,oBAATG,OACLH,EAAeG,KAAO,WAAa,SAQrCH,GAAAA,EAAQI,gBAAuC,IAAIJ,EAAOI,eAIvD,IAAMC,EAAqCR,QAAAA,EAAQ,CAAA,ECvSpDS,EAAoB,uBACpBC,EAAmB,sBACnBC,EAAqB,wBACrBC,EAAkB,CAACH,EAAmBC,EAAkBC,GACxDE,EAAoB,CACtB,uBACA,OACA,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D"} | ||
| {"version":3,"file":"tracing-headers.js","sources":["../../core/dist/utils/type-utils.mjs","../src/extensions/replay/rrweb-plugins/patch.ts","../src/utils/globals.ts","../src/entrypoints/tracing-headers.ts","../src/constants.ts"],"sourcesContent":["import { knownUnsafeEditableEvent, knownUnsafeEditableEventProperty } from \"../types.mjs\";\nimport { includes } from \"./string-utils.mjs\";\nconst nativeIsArray = Array.isArray;\nconst ObjProto = Object.prototype;\nconst type_utils_hasOwnProperty = ObjProto.hasOwnProperty;\nconst type_utils_toString = ObjProto.toString;\nconst isArray = nativeIsArray || function(obj) {\n return '[object Array]' === type_utils_toString.call(obj);\n};\nconst isFunction = (x)=>'function' == typeof x;\nconst isNativeFunction = (x)=>isFunction(x) && -1 !== x.toString().indexOf('[native code]');\nconst isObject = (x)=>x === Object(x) && !isArray(x);\nconst isEmptyObject = (x)=>{\n if (isObject(x)) {\n for(const key in x)if (type_utils_hasOwnProperty.call(x, key)) return false;\n return true;\n }\n return false;\n};\nconst isUndefined = (x)=>void 0 === x;\nconst isString = (x)=>'[object String]' == type_utils_toString.call(x);\nconst isEmptyString = (x)=>isString(x) && 0 === x.trim().length;\nconst isNull = (x)=>null === x;\nconst isNullish = (x)=>isUndefined(x) || isNull(x);\nconst isNumber = (x)=>'[object Number]' == type_utils_toString.call(x) && x === x;\nconst isPositiveNumber = (value)=>isNumber(value) && value > 0;\nconst isBoolean = (x)=>'[object Boolean]' === type_utils_toString.call(x);\nconst isFormData = (x)=>x instanceof FormData;\nconst isFile = (x)=>x instanceof File;\nconst isPlainError = (x)=>x instanceof Error;\nconst isKnownUnsafeEditableEvent = (x)=>includes(knownUnsafeEditableEvent, x);\nconst isKnownUnsafeEditableEventProperty = (x)=>includes(knownUnsafeEditableEventProperty, x);\nfunction isPrimitive(value) {\n return null === value || 'object' != typeof value;\n}\nfunction isBuiltin(candidate, className) {\n return Object.prototype.toString.call(candidate) === `[object ${className}]`;\n}\nfunction isError(candidate) {\n switch(Object.prototype.toString.call(candidate)){\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n case '[object DOMError]':\n case '[object WebAssembly.Exception]':\n return true;\n default:\n return isInstanceOf(candidate, Error);\n }\n}\nfunction isErrorEvent(event) {\n return isBuiltin(event, 'ErrorEvent');\n}\nfunction isEvent(candidate) {\n return 'undefined' != typeof Event && isInstanceOf(candidate, Event);\n}\nfunction isPlainObject(candidate) {\n return isBuiltin(candidate, 'Object');\n}\nfunction isInstanceOf(candidate, base) {\n try {\n return candidate instanceof base;\n } catch {\n return false;\n }\n}\nconst yesLikeValues = [\n true,\n 'true',\n 1,\n '1',\n 'yes'\n];\nconst isYesLike = (val)=>includes(yesLikeValues, val);\nconst noLikeValues = [\n false,\n 'false',\n 0,\n '0',\n 'no'\n];\nconst isNoLike = (val)=>includes(noLikeValues, val);\nexport { type_utils_hasOwnProperty as hasOwnProperty, isArray, isBoolean, isBuiltin, isEmptyObject, isEmptyString, isError, isErrorEvent, isEvent, isFile, isFormData, isFunction, isKnownUnsafeEditableEvent, isKnownUnsafeEditableEventProperty, isNativeFunction, isNoLike, isNull, isNullish, isNumber, isObject, isPlainError, isPlainObject, isPositiveNumber, isPrimitive, isString, isUndefined, isYesLike, noLikeValues, yesLikeValues };\n","// Portions of this file are derived from getsentry/sentry-javascript\n// Copyright (c) 2012 Functional Software, Inc. dba Sentry\n// Licensed under the MIT License: https://github.com/getsentry/sentry-javascript/blob/develop/LICENSE\n\n// import { patch } from 'rrweb/typings/utils'\n// copied from https://github.com/rrweb-io/rrweb/blob/8aea5b00a4dfe5a6f59bd2ae72bb624f45e51e81/packages/rrweb/src/utils.ts#L129\nimport { isFunction } from '@posthog/core'\n\nexport function patch(\n source: { [key: string]: any },\n name: string,\n replacement: (...args: unknown[]) => unknown\n): () => void {\n try {\n if (!(name in source)) {\n return () => {\n //\n }\n }\n\n const original = source[name] as () => unknown\n const wrapped = replacement(original)\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (isFunction(wrapped)) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n wrapped.prototype = wrapped.prototype || {}\n Object.defineProperties(wrapped, {\n __posthog_wrapped__: {\n enumerable: false,\n value: true,\n },\n })\n }\n\n source[name] = wrapped\n\n return () => {\n if (source[name] === wrapped) {\n source[name] = original\n }\n }\n } catch {\n return () => {\n //\n }\n // This can throw when multiple instrumentation layers try to wrap the same global object,\n // such as XMLHttpRequest, and redefine the same non-configurable wrapper marker.\n }\n}\n","import type { PostHog } from '../posthog-core'\nimport { SessionIdManager } from '../sessionid'\nimport {\n DeadClicksAutoCaptureConfig,\n ExternalIntegrationKind,\n Properties,\n RemoteConfig,\n SiteAppLoader,\n SessionStartReason,\n} from '../types'\nimport type {\n ConversationsRemoteConfig,\n GetMessagesResponse,\n GetTicketsOptions,\n GetTicketsResponse,\n MarkAsReadResponse,\n RestoreFromTokenResponse,\n RequestRestoreLinkResponse,\n SendMessageResponse,\n UserProvidedTraits,\n} from '../posthog-conversations-types'\n// only importing types here, so won't affect the bundle\n// eslint-disable-next-line posthog-js/no-external-replay-imports\nimport type { SessionRecordingStatus, TriggerType } from '../extensions/replay/external/triggerMatching'\nimport type { TracingHeadersDistinctId, TracingHeadersHostnames } from '../extensions/tracing-headers-types'\nimport { eventWithTime } from '../extensions/replay/types/rrweb-types'\nimport { ErrorTracking } from '@posthog/core'\n\n/*\n * Global helpers to protect access to browser globals in a way that is safer for different targets\n * like DOM, SSR, Web workers etc.\n *\n * NOTE: Typically we want the \"window\" but globalThis works for both the typical browser context as\n * well as other contexts such as the web worker context. Window is still exported for any bits that explicitly require it.\n * If in doubt - export the global you need from this file and use that as an optional value. This way the code path is forced\n * to handle the case where the global is not available.\n */\n\n// eslint-disable-next-line no-restricted-globals\nconst win: (Window & typeof globalThis) | undefined = typeof window !== 'undefined' ? window : undefined\n\nexport type AssignableWindow = Window &\n typeof globalThis & {\n /*\n * Main PostHog instance\n */\n posthog: any\n\n /*\n * This is our contract between (potentially) lazily loaded extensions and the SDK\n */\n __PosthogExtensions__?: PostHogExtensions\n\n /**\n * When loading remote config, we assign it to this global configuration\n * for ease of sharing it with the rest of the SDK\n */\n _POSTHOG_REMOTE_CONFIG?: Record<\n string,\n {\n config: RemoteConfig\n siteApps: SiteAppLoader[]\n }\n >\n\n /**\n * If this is set on the window, our logger will log to the console\n * for ease of debugging. Used for testing purposes only.\n *\n * @see {Config.DEBUG} from config.ts\n */\n POSTHOG_DEBUG: any\n\n // Exposed by the browser\n doNotTrack: any\n\n // See entrypoints/customizations.full.ts\n posthogCustomizations: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/exception-autocapture.ts\n *\n * @deprecated use `__PosthogExtensions__.errorWrappingFunctions` instead\n */\n posthogErrorWrappingFunctions: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/posthog-recorder.ts\n *\n * @deprecated use `__PosthogExtensions__.rrweb` instead\n */\n rrweb: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/posthog-recorder.ts\n *\n * @deprecated use `__PosthogExtensions__.rrwebConsoleRecord` instead\n */\n rrwebConsoleRecord: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/posthog-recorder.ts\n *\n * @deprecated use `__PosthogExtensions__.getRecordNetworkPlugin` instead\n */\n getRecordNetworkPlugin: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/web-vitals.ts\n *\n * @deprecated use `__PosthogExtensions__.postHogWebVitalsCallbacks` instead\n */\n postHogWebVitalsCallbacks: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/tracing-headers.ts\n *\n * @deprecated use `__PosthogExtensions__.postHogTracingHeadersPatchFns` instead\n */\n postHogTracingHeadersPatchFns: any\n\n /**\n * This is a legacy way to expose these functions, but we still need to support it for backwards compatibility\n * Can be removed once we drop support for 1.161.1\n *\n * See entrypoints/surveys.ts\n *\n * @deprecated use `__PosthogExtensions__.generateSurveys` instead\n */\n extendPostHogWithSurveys: any\n\n /*\n * These are used to handle our toolbar state.\n * @see {Toolbar} from extensions/toolbar.ts\n */\n ph_load_toolbar: any\n ph_load_editor: any\n ph_toolbar_state: any\n } & Record<`__$$ph_site_app_${string}`, any>\n\n/**\n * This is our contract between (potentially) lazily loaded extensions and the SDK\n * changes to this interface can be breaking changes for users of the SDK\n */\n\nexport type ExternalExtensionKind = 'intercom-integration' | 'crisp-chat-integration'\n\nexport type PostHogExtensionKind =\n | 'toolbar'\n | 'exception-autocapture'\n | 'web-vitals'\n | 'web-vitals-with-attribution'\n | 'recorder'\n | 'lazy-recorder'\n | 'tracing-headers'\n | 'surveys'\n | 'logs'\n | 'conversations'\n | 'product-tours'\n | 'dead-clicks-autocapture'\n | 'remote-config'\n | ExternalExtensionKind\n\nexport interface LazyLoadedSessionRecordingInterface {\n start: (startReason?: SessionStartReason) => void\n stop: () => void\n discard: () => void\n sessionId: string\n status: SessionRecordingStatus\n onRRwebEmit: (rawEvent: eventWithTime) => void\n log: (message: string, level: 'log' | 'warn' | 'error') => void\n sdkDebugProperties: Properties\n overrideLinkedFlag: () => void\n overrideSampling: () => void\n overrideTrigger: (triggerType: TriggerType) => void\n isStarted: boolean\n tryAddCustomEvent(tag: string, payload: any): boolean\n}\n\nexport interface LazyLoadedDeadClicksAutocaptureInterface {\n start: (observerTarget: Node) => void\n stop: () => void\n}\n\nexport interface LazyLoadedConversationsInterface {\n // Widget control\n show: () => void\n hide: () => void\n isVisible: () => boolean\n\n // Lifecycle\n reset: () => void\n\n // Identity verification\n setIdentity: () => void\n clearIdentity: () => void\n\n // API methods\n sendMessage: (message: string, userTraits?: UserProvidedTraits, newTicket?: boolean) => Promise<SendMessageResponse>\n getMessages: (ticketId?: string, after?: string) => Promise<GetMessagesResponse>\n markAsRead: (ticketId?: string) => Promise<MarkAsReadResponse>\n getTickets: (options?: GetTicketsOptions) => Promise<GetTicketsResponse>\n requestRestoreLink: (email: string) => Promise<RequestRestoreLinkResponse>\n restoreFromToken: (restoreToken: string) => Promise<RestoreFromTokenResponse>\n restoreFromUrlToken: () => Promise<RestoreFromTokenResponse | null>\n getCurrentTicketId: () => string | null\n getWidgetSessionId: () => string\n}\n\ninterface PostHogExtensions {\n loadExternalDependency?: (\n posthog: PostHog,\n kind: PostHogExtensionKind,\n callback: (error?: string | Event, event?: Event) => void\n ) => void\n\n loadSiteApp?: (posthog: PostHog, appUrl: string, callback: (error?: string | Event, event?: Event) => void) => void\n\n errorWrappingFunctions?: {\n wrapOnError: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void\n wrapUnhandledRejection: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void\n wrapConsoleError: (captureFn: (props: ErrorTracking.ErrorProperties) => void) => () => void\n }\n rrweb?: { record: any; version: string; wasMaxDepthReached?: () => boolean; resetMaxDepthState?: () => void }\n rrwebPlugins?: { getRecordConsolePlugin: any; getRecordNetworkPlugin?: any }\n generateSurveys?: (posthog: PostHog, isSurveysEnabled: boolean) => any | undefined\n generateProductTours?: (posthog: PostHog, isEnabled: boolean) => any | undefined\n logs?: {\n initializeLogs?: (posthog: PostHog) => any | undefined\n }\n postHogWebVitalsCallbacks?: {\n onLCP: (metric: any) => void\n onCLS: (metric: any) => void\n onFCP: (metric: any) => void\n onINP: (metric: any) => void\n }\n /**\n * @deprecated\n *\n * this was introduced briefly, it is now always a no-op and only kept for backwards compatibility\n */\n loadWebVitalsCallbacks?: (useAttribution?: boolean) => PostHogExtensions['postHogWebVitalsCallbacks']\n tracingHeadersPatchFns?: {\n _patchFetch: (\n hostnames: TracingHeadersHostnames,\n distinctId: TracingHeadersDistinctId,\n sessionManager?: SessionIdManager\n ) => () => void\n _patchXHR: (\n hostnames: TracingHeadersHostnames,\n distinctId: TracingHeadersDistinctId,\n sessionManager?: SessionIdManager\n ) => () => void\n }\n initDeadClicksAutocapture?: (\n ph: PostHog,\n config: DeadClicksAutoCaptureConfig\n ) => LazyLoadedDeadClicksAutocaptureInterface\n integrations?: {\n [K in ExternalIntegrationKind]?: { start: (posthog: PostHog) => void; stop: () => void }\n }\n initSessionRecording?: (ph: PostHog) => LazyLoadedSessionRecordingInterface\n initConversations?: (config: ConversationsRemoteConfig, posthog: PostHog) => LazyLoadedConversationsInterface\n}\n\nconst global: typeof globalThis | undefined = typeof globalThis !== 'undefined' ? globalThis : win\n\n// React Native polyfills for posthog-js compatibility\nif (typeof self === 'undefined') {\n ;(global as any).self = global\n}\nif (typeof File === 'undefined') {\n ;(global as any).File = function () {}\n}\n\nexport const navigator = global?.navigator\nexport const document = global?.document\nexport const location = global?.location\nexport const fetch = global?.fetch\nexport const XMLHttpRequest =\n global?.XMLHttpRequest && 'withCredentials' in new global.XMLHttpRequest() ? global.XMLHttpRequest : undefined\nexport const AbortController = global?.AbortController\nexport const CompressionStream = global?.CompressionStream\nexport const userAgent = navigator?.userAgent\nexport const assignableWindow: AssignableWindow = win ?? ({} as any)\n\nexport { win as window }\n","import { SessionIdManager } from '../sessionid'\nimport { patch } from '../extensions/replay/rrweb-plugins/patch'\nimport { assignableWindow, window } from '../utils/globals'\nimport { COOKIELESS_SENTINEL_VALUE } from '../constants'\nimport { isArray, isFunction, isNull, isUndefined } from '@posthog/core'\nimport type { TracingHeadersDistinctId, TracingHeadersHostnames } from '../extensions/tracing-headers-types'\n\nconst SESSION_ID_HEADER = 'X-POSTHOG-SESSION-ID'\nconst WINDOW_ID_HEADER = 'X-POSTHOG-WINDOW-ID'\nconst DISTINCT_ID_HEADER = 'X-POSTHOG-DISTINCT-ID'\nconst TRACING_HEADERS = [SESSION_ID_HEADER, WINDOW_ID_HEADER, DISTINCT_ID_HEADER]\nconst REQUEST_INIT_KEYS = [\n 'attributionReporting',\n 'body',\n 'browsingTopics',\n 'cache',\n 'credentials',\n 'dispatcher',\n 'duplex',\n 'integrity',\n 'keepalive',\n 'method',\n 'mode',\n 'priority',\n 'redirect',\n 'referrer',\n 'referrerPolicy',\n 'signal',\n 'window',\n]\n\nconst hasOwnProperty = (value: object, property: PropertyKey): boolean =>\n Object.prototype.hasOwnProperty.call(value, property)\n\nconst isObjectLike = (value: unknown): value is object =>\n (typeof value === 'object' && !isNull(value)) || isFunction(value)\n\nconst isRequest = (value: unknown): value is Request =>\n typeof Request !== 'undefined' &&\n (value instanceof Request || Object.prototype.toString.call(value) === '[object Request]')\n\nconst getRequestUrl = (url: URL | RequestInfo): string | undefined => {\n try {\n if (isRequest(url)) {\n return url.url\n }\n\n // eslint-disable-next-line compat/compat\n return new URL(url instanceof URL ? url.toString() : String(url), window?.location?.href).toString()\n } catch {\n return undefined\n }\n}\n\n// RequestInit is a WebIDL dictionary: native fetch reads known keys via property access, including inherited\n// and non-enumerable properties. Avoid `{ ...init, headers }`, which can drop body/signal/duplex/etc. Instead,\n// overlay only `headers` while forwarding every other lookup to the caller's original init object.\nconst createFetchInitWithHeaders = (init: RequestInit | undefined, headers: Headers): RequestInit | undefined => {\n if (isUndefined(init) || isNull(init)) {\n return { headers }\n }\n if (!isObjectLike(init)) {\n return undefined\n }\n\n const originalInit = init as RequestInit & Record<PropertyKey, unknown>\n\n if (typeof Proxy === 'undefined' || typeof Reflect === 'undefined') {\n // Older browsers without Proxy still get an inherited overlay, which preserves native fetch property lookup.\n const initWithHeaders = Object.create(originalInit) as RequestInit\n Object.defineProperty(initWithHeaders, 'headers', {\n configurable: true,\n enumerable: true,\n value: headers,\n writable: true,\n })\n return initWithHeaders\n }\n\n const target = { headers } as RequestInit & Record<PropertyKey, unknown>\n\n return new Proxy(target, {\n get(target, property) {\n if (hasOwnProperty(target, property)) {\n return Reflect.get(target, property)\n }\n return Reflect.get(originalInit, property, originalInit)\n },\n has(target, property) {\n return hasOwnProperty(target, property) || property in originalInit\n },\n ownKeys(target) {\n const keys = new Set<string | symbol>(Reflect.ownKeys(target))\n Reflect.ownKeys(originalInit).forEach((key) => keys.add(key))\n REQUEST_INIT_KEYS.forEach((key) => {\n if (key in originalInit) {\n keys.add(key)\n }\n })\n return Array.from(keys)\n },\n getOwnPropertyDescriptor(target, property) {\n const targetDescriptor = Reflect.getOwnPropertyDescriptor(target, property)\n if (targetDescriptor) {\n return targetDescriptor\n }\n if (typeof property === 'string' && REQUEST_INIT_KEYS.includes(property) && property in originalInit) {\n return {\n configurable: true,\n enumerable: true,\n get: () => Reflect.get(originalInit, property, originalInit),\n }\n }\n\n const descriptor = Reflect.getOwnPropertyDescriptor(originalInit, property)\n return descriptor ? { ...descriptor, configurable: true } : undefined\n },\n getPrototypeOf() {\n return Object.getPrototypeOf(originalInit)\n },\n }) as RequestInit\n}\n\nconst getDistinctId = (distinctId: TracingHeadersDistinctId): string | undefined =>\n isFunction(distinctId) ? distinctId() : distinctId\n\nconst addTracingHeaders = (\n hostnames: TracingHeadersHostnames,\n distinctId: TracingHeadersDistinctId,\n sessionManager: SessionIdManager | undefined,\n url: string,\n headers: Headers\n): boolean => {\n let reqHostname: string\n try {\n // we don't need to support IE11 here\n // eslint-disable-next-line compat/compat\n reqHostname = new URL(url).hostname\n } catch {\n // If the URL is invalid, we skip adding tracing headers\n return false\n }\n if (!hostnames) {\n return false\n }\n if (isArray(hostnames) && !hostnames.includes(reqHostname)) {\n return false\n }\n\n let hasAddedHeaders = false\n if (sessionManager) {\n const { sessionId, windowId } = sessionManager.checkAndGetSessionAndWindowId(true)\n headers.set(SESSION_ID_HEADER, sessionId)\n headers.set(WINDOW_ID_HEADER, windowId)\n hasAddedHeaders = true\n }\n const currentDistinctId = getDistinctId(distinctId)\n if (currentDistinctId && currentDistinctId !== COOKIELESS_SENTINEL_VALUE) {\n headers.set(DISTINCT_ID_HEADER, currentDistinctId)\n hasAddedHeaders = true\n }\n return hasAddedHeaders\n}\n\ntype FetchArgs = [URL | RequestInfo] | [URL | RequestInfo, RequestInit | undefined]\n\nconst patchFetch = (\n hostnames: TracingHeadersHostnames,\n distinctId: TracingHeadersDistinctId,\n sessionManager?: SessionIdManager\n): (() => void) => {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return patch(window, 'fetch', (originalFetch: typeof fetch) => {\n return function (this: unknown, url: URL | RequestInfo, init?: RequestInit | undefined) {\n const originalArgs = (arguments.length > 1 ? [url, init] : [url]) as FetchArgs\n let fetchArgs = originalArgs\n\n try {\n const requestUrl = getRequestUrl(url)\n if (requestUrl) {\n if (isRequest(url)) {\n // For fetch(Request, init), construct a new Request so init overrides are applied and the\n // caller's Request is not mutated. For fetch(url, init), avoid this because it exposes string\n // bodies as ReadableStreams to downstream wrappers in Safari.\n // eslint-disable-next-line compat/compat\n const req = new Request(url, init)\n addTracingHeaders(hostnames, distinctId, sessionManager, req.url, req.headers)\n fetchArgs = [req]\n } else {\n const headers = new Headers(isObjectLike(init) ? init.headers : undefined)\n if (addTracingHeaders(hostnames, distinctId, sessionManager, requestUrl, headers)) {\n const initWithHeaders = createFetchInitWithHeaders(init, headers)\n if (initWithHeaders) {\n fetchArgs = [url, initWithHeaders]\n }\n }\n }\n }\n } catch {\n fetchArgs = originalArgs\n }\n\n return originalFetch.apply(this, fetchArgs)\n }\n })\n}\n\nconst patchXHR = (\n hostnames: TracingHeadersHostnames,\n distinctId: TracingHeadersDistinctId,\n sessionManager?: SessionIdManager\n): (() => void) => {\n return patch(\n // we can assert this is present because we've checked previously\n window!.XMLHttpRequest.prototype,\n 'open',\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n (originalOpen: typeof XMLHttpRequest.prototype.open) => {\n return function (\n method: string,\n url: string | URL,\n async = true,\n username?: string | null,\n password?: string | null\n ) {\n // because this function is returned in its actual context `this` _is_ an XMLHttpRequest\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const xhr = this as XMLHttpRequest\n\n const headers = new Headers()\n const requestUrl = getRequestUrl(url)\n if (requestUrl) {\n addTracingHeaders(hostnames, distinctId, sessionManager, requestUrl, headers)\n }\n\n const result = originalOpen.call(xhr, method, url, async, username, password)\n\n TRACING_HEADERS.forEach((header) => {\n const value = headers.get(header)\n if (value) {\n try {\n xhr.setRequestHeader(header, value)\n } catch {\n // Do not let tracing header injection break the host app's XHR.\n }\n }\n })\n\n return result\n }\n }\n )\n}\n\nassignableWindow.__PosthogExtensions__ = assignableWindow.__PosthogExtensions__ || {}\nconst patchFns = {\n _patchFetch: patchFetch,\n _patchXHR: patchXHR,\n}\nassignableWindow.__PosthogExtensions__.tracingHeadersPatchFns = patchFns\n\n// we used to put tracingHeadersPatchFns on window, and now we put it on __PosthogExtensions__\n// but that means that old clients which lazily load this extension are looking in the wrong place\n// yuck,\n// so we also put it directly on the window\n// when 1.161.1 is the oldest version seen in production we can remove this\nassignableWindow.postHogTracingHeadersPatchFns = patchFns\n\nexport default patchFns\n","/*\n * Constants\n */\n\n/* PROPERTY KEYS */\n\n// This key is deprecated, but we want to check for it to see whether aliasing is allowed.\nexport const PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id'\nexport const DISTINCT_ID = 'distinct_id'\nexport const DEVICE_ID = '$device_id'\nexport const DEVICE_MODEL = '$device_model'\nexport const ALIAS_ID_KEY = '__alias'\nexport const CAMPAIGN_IDS_KEY = '__cmpns'\nexport const EVENT_TIMERS_KEY = '__timers'\nexport const AUTOCAPTURE_DISABLED_SERVER_SIDE = '$autocapture_disabled_server_side'\nexport const HEATMAPS_ENABLED_SERVER_SIDE = '$heatmaps_enabled_server_side'\nexport const EXCEPTION_CAPTURE_ENABLED_SERVER_SIDE = '$exception_capture_enabled_server_side'\nexport const ERROR_TRACKING_SUPPRESSION_RULES = '$error_tracking_suppression_rules'\nexport const ERROR_TRACKING_CAPTURE_EXTENSION_EXCEPTIONS = '$error_tracking_capture_extension_exceptions'\nexport const WEB_VITALS_ENABLED_SERVER_SIDE = '$web_vitals_enabled_server_side'\nexport const DEAD_CLICKS_ENABLED_SERVER_SIDE = '$dead_clicks_enabled_server_side'\nexport const PRODUCT_TOURS_ENABLED_SERVER_SIDE = '$product_tours_enabled_server_side'\nexport const WEB_VITALS_ALLOWED_METRICS = '$web_vitals_allowed_metrics'\nexport const SESSION_RECORDING_REMOTE_CONFIG = '$session_recording_remote_config'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_ENABLED_SERVER_SIDE = '$session_recording_enabled_server_side'\n// @deprecated can be removed along with eager loaded replay\nexport const CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE = '$console_log_recording_enabled_server_side'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE = '$session_recording_network_payload_capture'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_MASKING = '$session_recording_masking'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_CANVAS_RECORDING = '$session_recording_canvas_recording'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_SAMPLE_RATE = '$replay_sample_rate'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_MINIMUM_DURATION = '$replay_minimum_duration'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_SCRIPT_CONFIG = '$replay_script_config'\nexport const SESSION_RECORDING_OVERRIDE_SAMPLING = '$replay_override_sampling'\nexport const SESSION_RECORDING_OVERRIDE_LINKED_FLAG = '$replay_override_linked_flag'\nexport const SESSION_RECORDING_OVERRIDE_URL_TRIGGER = '$replay_override_url_trigger'\nexport const SESSION_RECORDING_OVERRIDE_EVENT_TRIGGER = '$replay_override_event_trigger'\nexport const SESSION_ID = '$sesid'\nexport const SESSION_RECORDING_IS_SAMPLED = '$session_is_sampled'\nexport const SESSION_RECORDING_PAST_MINIMUM_DURATION = '$session_past_minimum_duration'\nexport const SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION = '$session_recording_url_trigger_activated_session'\nexport const SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION = '$session_recording_event_trigger_activated_session'\n// V2 Trigger Groups: Per-group persistence key prefixes (suffix with group ID)\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX = '$posthog_sr_group_event_trigger_'\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX = '$posthog_sr_group_url_trigger_'\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_SAMPLING_PREFIX = '$posthog_sr_group_sampling_'\nexport const SESSION_RECORDING_FIRST_FULL_SNAPSHOT_TIMESTAMP = '$debug_first_full_snapshot_timestamp'\nexport const SESSION_RECORDING_FLUSHED_SIZE = '$sess_rec_flush_size'\nexport const ENABLED_FEATURE_FLAGS = '$enabled_feature_flags'\nexport const PERSISTENCE_ACTIVE_FEATURE_FLAGS = '$active_feature_flags'\nexport const PERSISTENCE_EARLY_ACCESS_FEATURES = '$early_access_features'\nexport const PERSISTENCE_FEATURE_FLAG_DETAILS = '$feature_flag_details'\nexport const PERSISTENCE_FEATURE_FLAG_PAYLOADS = '$feature_flag_payloads'\nexport const PERSISTENCE_FEATURE_FLAG_REQUEST_ID = '$feature_flag_request_id'\nexport const PERSISTENCE_OVERRIDE_FEATURE_FLAGS = '$override_feature_flags'\nexport const PERSISTENCE_OVERRIDE_FEATURE_FLAG_PAYLOADS = '$override_feature_flag_payloads'\nexport const STORED_PERSON_PROPERTIES_KEY = '$stored_person_properties'\nexport const STORED_GROUP_PROPERTIES_KEY = '$stored_group_properties'\nexport const SURVEYS = '$surveys'\nexport const SURVEYS_LOADED_AT = '$surveys_loaded_at'\nexport const SURVEYS_ACTIVATED = '$surveys_activated'\nexport const PRODUCT_TOURS = 'ph_product_tours'\nexport const PRODUCT_TOURS_ACTIVATED = '$product_tours_activated'\nexport const CONVERSATIONS = '$conversations'\nexport const CONVERSATIONS_LEGACY_WIDGET_SESSION_ID = '$conversations_widget_session_id'\nexport const CONVERSATIONS_LEGACY_TICKET_ID = '$conversations_ticket_id'\nexport const CONVERSATIONS_LEGACY_WIDGET_STATE = '$conversations_widget_state'\nexport const CONVERSATIONS_LEGACY_USER_TRAITS = '$conversations_user_traits'\nexport const FLAG_CALL_REPORTED = '$flag_call_reported'\nexport const FLAG_CALL_REPORTED_SESSION_ID = '$flag_call_reported_session_id'\nexport const PERSISTENCE_FEATURE_FLAG_ERRORS = '$feature_flag_errors'\nexport const PERSISTENCE_FEATURE_FLAG_EVALUATED_AT = '$feature_flag_evaluated_at'\nexport const USER_STATE = '$user_state'\nexport const CLIENT_SESSION_PROPS = '$client_session_props'\nexport const CAPTURE_RATE_LIMIT = '$capture_rate_limit'\n\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_CAMPAIGN_PARAMS = '$initial_campaign_params'\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_REFERRER_INFO = '$initial_referrer_info'\nexport const INITIAL_PERSON_INFO = '$initial_person_info'\nexport const ENABLE_PERSON_PROCESSING = '$epp'\nexport const TOOLBAR_ID = '__POSTHOG_TOOLBAR__'\nexport const TOOLBAR_CONTAINER_CLASS = 'toolbar-global-fade-container'\n\n/**\n * PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION\n * Sentinel value for distinct id, device id, session id. Signals that the server should generate the value\n * */\nexport const COOKIELESS_SENTINEL_VALUE = '$posthog_cookieless'\nexport const COOKIELESS_MODE_FLAG_PROPERTY = '$cookieless_mode'\n\nexport const WEB_EXPERIMENTS = '$web_experiments'\n\nexport const SDK_DIST_CHANNEL = '$sdk_dist_channel'\nexport const SDK_DEBUG_EXTENSIONS_INIT_METHOD = '$sdk_debug_extensions_init_method'\nexport const SDK_DEBUG_EXTENSIONS_INIT_TIME_MS = '$sdk_debug_extensions_init_time_ms'\nexport const SDK_DEBUG_RECORDING_SCRIPT_NOT_LOADED = '$sdk_debug_recording_script_not_loaded'\nexport const SDK_DEBUG_REPLAY_EVENT_TRIGGER_STATUS = '$sdk_debug_replay_event_trigger_status'\nexport const SDK_DEBUG_REPLAY_LINKED_FLAG_TRIGGER_STATUS = '$sdk_debug_replay_linked_flag_trigger_status'\nexport const SDK_DEBUG_REPLAY_MATCHED_RECORDING_TRIGGER_GROUPS = '$sdk_debug_replay_matched_recording_trigger_groups'\nexport const SDK_DEBUG_REPLAY_REMOTE_TRIGGER_MATCHING_CONFIG = '$sdk_debug_replay_remote_trigger_matching_config'\nexport const SDK_DEBUG_REPLAY_TRIGGER_GROUPS_COUNT = '$sdk_debug_replay_trigger_groups_count'\nexport const SDK_DEBUG_REPLAY_URL_TRIGGER_STATUS = '$sdk_debug_replay_url_trigger_status'\nexport const SDK_DEBUG_REPLAY_RRWEB_ATTACHED = '$sdk_debug_rrweb_attached'\nexport const SDK_DEBUG_REPLAY_RRWEB_START_ATTEMPTED = '$sdk_debug_rrweb_start_attempted'\nexport const SESSION_RECORDING_START_REASON = '$session_recording_start_reason'\n\nexport const SURVEYS_REQUEST_TIMEOUT_MS = 10000\n// How long the cached `$surveys` definitions are considered fresh. After this, the next\n// `getSurveys` call serves the cache immediately but kicks off a background refresh so\n// server-side changes (e.g. a survey switched from popover to API) propagate to a\n// long-lived tab without needing a page reload.\nexport const SURVEYS_CACHE_TTL_MS = 5 * 60 * 1000 // 5 minutes\n// After a failed background refresh we back off for the same window as the cache TTL before\n// trying again. Aliased to make the shared duration intentional rather than coincidental.\nexport const SURVEYS_REFRESH_BACKOFF_MS = SURVEYS_CACHE_TTL_MS\nexport const LOAD_EXT_NOT_FOUND = 'PostHog loadExternalDependency extension not found.'\n\n/* EVENT NAMES - interned to reduce bundle size */\n/* COOKIELESS MODE VALUES */\nexport const COOKIELESS_ON_REJECT = 'on_reject' as const\nexport const COOKIELESS_ALWAYS = 'always' as const\n\n/* USER STATE VALUES */\nexport const USER_STATE_ANONYMOUS = 'anonymous'\nexport const USER_STATE_IDENTIFIED = 'identified'\n\n/* PERSON PROFILE MODES */\nexport const PERSON_PROFILES_IDENTIFIED_ONLY = 'identified_only' as const\n\n/* DOM EVENT NAMES - interned to reduce bundle size */\nexport const DOM_EVENT_VISIBILITYCHANGE = 'visibilitychange'\nexport const DOM_EVENT_BEFOREUNLOAD = 'beforeunload'\n\nexport const EVENT_PAGEVIEW = '$pageview'\nexport const EVENT_PAGELEAVE = '$pageleave'\nexport const EVENT_IDENTIFY = '$identify'\nexport const EVENT_GROUPIDENTIFY = '$groupidentify'\n\n/* Z-INDEX HIERARCHY: tours > surveys > support */\nexport const Z_INDEX_TOURS = 2147483646\nexport const Z_INDEX_SURVEYS = 2147483645\nexport const Z_INDEX_CONVERSATIONS = 2147483644\n"],"names":["type_utils_toString","Object","prototype","toString","isArray","Array","obj","call","isFunction","x","isNull","patch","source","name","replacement","original","wrapped","defineProperties","__posthog_wrapped__","enumerable","value","_unused","win","window","undefined","global","globalThis","self","File","XMLHttpRequest","assignableWindow","SESSION_ID_HEADER","WINDOW_ID_HEADER","DISTINCT_ID_HEADER","TRACING_HEADERS","REQUEST_INIT_KEYS","hasOwnProperty","property","isObjectLike","isRequest","Request","getRequestUrl","url","_window$location","URL","String","location","href","addTracingHeaders","hostnames","distinctId","sessionManager","headers","reqHostname","hostname","_unused2","includes","hasAddedHeaders","sessionId","windowId","checkAndGetSessionAndWindowId","set","currentDistinctId","getDistinctId","__PosthogExtensions__","patchFns","_patchFetch","patchFetch","originalFetch","init","originalArgs","arguments","length","fetchArgs","requestUrl","req","Headers","initWithHeaders","createFetchInitWithHeaders","originalInit","Proxy","Reflect","create","defineProperty","configurable","writable","get","target","has","ownKeys","keys","Set","forEach","key","add","from","getOwnPropertyDescriptor","targetDescriptor","descriptor","_extends","getPrototypeOf","_unused3","apply","this","_patchXHR","patchXHR","originalOpen","method","async","username","password","xhr","result","header","setRequestHeader","_unused4","tracingHeadersPatchFns","postHogTracingHeadersPatchFns"],"mappings":"iPAEA,IAGMA,EAFWC,CAAOC,EAEaC,SAC/BC,EAJgBC,MAAMD,SAIK,SAASE,GACtC,MAAO,mBAAqBN,EAAoBO,KAAKD,EACzD,EACME,EAAcC,GAAI,mBAAqBA,EAavCC,EAAUD,GAAI,OAASA,ECdtB,SAASE,EACZC,EACAC,EACAC,GAEA,IACI,KAAMD,KAAQD,GACV,MAAO,OAKX,IAAMG,EAAWH,EAAOC,GAClBG,EAAUF,EAAYC,GAiB5B,OAbIP,EAAWQ,KAEXA,EAAQd,UAAYc,EAAQd,WAAa,CAAA,EACzCD,OAAOgB,iBAAiBD,EAAS,CAC7BE,oBAAqB,CACjBC,YAAY,EACZC,OAAO,MAKnBR,EAAOC,GAAQG,EAER,KACCJ,EAAOC,KAAUG,IACjBJ,EAAOC,GAAQE,EACnB,CAER,CAAE,MAAAM,GACE,MAAO,MAKX,CACJ,CCXA,IAAMC,EAAkE,oBAAXC,OAAyBA,YAASC,EAoPzFC,EAA8D,oBAAfC,WAA6BA,WAAaJ,EAG3E,oBAATK,OACLF,EAAeE,KAAOF,GAER,oBAATG,OACLH,EAAeG,KAAO,WAAa,SAQrCH,GAAAA,EAAQI,gBAAuC,IAAIJ,EAAOI,eAIvD,IAAMC,EAAqCR,QAAAA,EAAQ,CAAA,ECvSpDS,EAAoB,uBACpBC,EAAmB,sBACnBC,EAAqB,wBACrBC,EAAkB,CAACH,EAAmBC,EAAkBC,GACxDE,EAAoB,CACtB,uBACA,OACA,iBACA,QACA,cACA,aACA,SACA,YACA,YACA,SACA,OACA,WACA,WACA,WACA,iBACA,SACA,UAGEC,EAAiBA,CAAChB,EAAeiB,KACnCpC,CAAOC,EAAUkC,eAAe7B,KAAKa,EAAOiB,IAE1CC,EAAgBlB,GACA,iBAAVA,IAAuBV,EAAOU,IAAWZ,EAAWY,GAE1DmB,EAAan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ACpF,MAAO,CACHK,cAAc,EACdjE,YAAY,EACZmE,GAA2D,GAAhDL,eAAQK,IAAIP,EAAc1C,EAAU0C,KAIvD,IAAMmB,EAAajB,QAAQe,yBAAyBjB,EAAc1C,GAClE,OAAO6D,EAAUC,EAAA,CAAA,EAAQD,EAAU,CAAEd,cAAc,SAAS5D,CAChE,EACA4E,eAAcA,IACHnG,OAAOmG,eAAerB,IAvDrC,CAyDE,EAwE8CD,CAA2BT,EAAMjB,GACrDyB,IACAJ,EAAY,CAAC/B,EAAKmC,GAE1B,CACJ,CAER,CAAE,MAAAwB,GACE5B,EAAYH,CAChB,CAEA,OAAOF,EAAckC,MAAMC,KAAM9B,EACrC,IAwDJ+B,UApDaC,CACbxD,EACAC,EACAC,IAEOxC,EAEHY,EAAQM,eAAe3B,UACvB,QAGCwG,GACU,SACHC,EACAjE,EACAkE,EACAC,EACAC,QAFK,IAALF,IAAAA,GAAQ,GAOR,IAAMG,EAAMR,KAENnD,EAAU,IAAIwB,QACdF,EAAajC,EAAcC,GAC7BgC,GACA1B,EAAkBC,EAAWC,EAAYC,EAAgBuB,EAAYtB,GAGzE,IAAM4D,EAASN,EAAanG,KAAKwG,EAAKJ,EAAQjE,EAAKkE,EAAOC,EAAUC,GAapE,OAXA5E,EAAgB0D,SAASqB,IACrB,IAAM7F,EAAQgC,EAAQkC,IAAI2B,GAC1B,GAAI7F,EACA,IACI2F,EAAIG,iBAAiBD,EAAQ7F,EACjC,CAAE,MAAA+F,GACE,CAER,IAGGH,CACX,KAUZlF,EAAiBkC,sBAAsBoD,uBAAyBnD,EAOhEnC,EAAiBuF,8BAAgCpD"} |
+1
-1
| { | ||
| "name": "posthog-js", | ||
| "version": "1.396.5", | ||
| "version": "1.396.6", | ||
| "bugs": { | ||
@@ -5,0 +5,0 @@ "url": "https://github.com/PostHog/posthog-js/issues" |
@@ -96,2 +96,4 @@ export declare const PEOPLE_DISTINCT_ID_KEY = "$people_distinct_id"; | ||
| export declare const SURVEYS_REQUEST_TIMEOUT_MS = 10000; | ||
| export declare const SURVEYS_CACHE_TTL_MS: number; | ||
| export declare const SURVEYS_REFRESH_BACKOFF_MS: number; | ||
| export declare const LOAD_EXT_NOT_FOUND = "PostHog loadExternalDependency extension not found."; | ||
@@ -98,0 +100,0 @@ export declare const COOKIELESS_ON_REJECT: "on_reject"; |
+10
-2
@@ -7,4 +7,4 @@ "use strict"; | ||
| exports.SURVEYS = exports.STORED_GROUP_PROPERTIES_KEY = exports.STORED_PERSON_PROPERTIES_KEY = exports.PERSISTENCE_OVERRIDE_FEATURE_FLAG_PAYLOADS = exports.PERSISTENCE_OVERRIDE_FEATURE_FLAGS = exports.PERSISTENCE_FEATURE_FLAG_REQUEST_ID = exports.PERSISTENCE_FEATURE_FLAG_PAYLOADS = exports.PERSISTENCE_FEATURE_FLAG_DETAILS = exports.PERSISTENCE_EARLY_ACCESS_FEATURES = exports.PERSISTENCE_ACTIVE_FEATURE_FLAGS = exports.ENABLED_FEATURE_FLAGS = exports.SESSION_RECORDING_FLUSHED_SIZE = exports.SESSION_RECORDING_FIRST_FULL_SNAPSHOT_TIMESTAMP = exports.SESSION_RECORDING_TRIGGER_V2_GROUP_SAMPLING_PREFIX = exports.SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX = exports.SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX = exports.SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION = exports.SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION = exports.SESSION_RECORDING_PAST_MINIMUM_DURATION = exports.SESSION_RECORDING_IS_SAMPLED = exports.SESSION_ID = exports.SESSION_RECORDING_OVERRIDE_EVENT_TRIGGER = exports.SESSION_RECORDING_OVERRIDE_URL_TRIGGER = exports.SESSION_RECORDING_OVERRIDE_LINKED_FLAG = exports.SESSION_RECORDING_OVERRIDE_SAMPLING = exports.SESSION_RECORDING_SCRIPT_CONFIG = exports.SESSION_RECORDING_MINIMUM_DURATION = exports.SESSION_RECORDING_SAMPLE_RATE = exports.SESSION_RECORDING_CANVAS_RECORDING = exports.SESSION_RECORDING_MASKING = exports.SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE = exports.CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE = exports.SESSION_RECORDING_ENABLED_SERVER_SIDE = exports.SESSION_RECORDING_REMOTE_CONFIG = exports.WEB_VITALS_ALLOWED_METRICS = exports.PRODUCT_TOURS_ENABLED_SERVER_SIDE = exports.DEAD_CLICKS_ENABLED_SERVER_SIDE = exports.WEB_VITALS_ENABLED_SERVER_SIDE = exports.ERROR_TRACKING_CAPTURE_EXTENSION_EXCEPTIONS = exports.ERROR_TRACKING_SUPPRESSION_RULES = exports.EXCEPTION_CAPTURE_ENABLED_SERVER_SIDE = exports.HEATMAPS_ENABLED_SERVER_SIDE = exports.AUTOCAPTURE_DISABLED_SERVER_SIDE = exports.EVENT_TIMERS_KEY = exports.CAMPAIGN_IDS_KEY = exports.ALIAS_ID_KEY = exports.DEVICE_MODEL = exports.DEVICE_ID = exports.DISTINCT_ID = exports.PEOPLE_DISTINCT_ID_KEY = void 0; | ||
| exports.EVENT_IDENTIFY = exports.EVENT_PAGELEAVE = exports.EVENT_PAGEVIEW = exports.DOM_EVENT_BEFOREUNLOAD = exports.DOM_EVENT_VISIBILITYCHANGE = exports.PERSON_PROFILES_IDENTIFIED_ONLY = exports.USER_STATE_IDENTIFIED = exports.USER_STATE_ANONYMOUS = exports.COOKIELESS_ALWAYS = exports.COOKIELESS_ON_REJECT = exports.LOAD_EXT_NOT_FOUND = exports.SURVEYS_REQUEST_TIMEOUT_MS = exports.SESSION_RECORDING_START_REASON = exports.SDK_DEBUG_REPLAY_RRWEB_START_ATTEMPTED = exports.SDK_DEBUG_REPLAY_RRWEB_ATTACHED = exports.SDK_DEBUG_REPLAY_URL_TRIGGER_STATUS = exports.SDK_DEBUG_REPLAY_TRIGGER_GROUPS_COUNT = exports.SDK_DEBUG_REPLAY_REMOTE_TRIGGER_MATCHING_CONFIG = exports.SDK_DEBUG_REPLAY_MATCHED_RECORDING_TRIGGER_GROUPS = exports.SDK_DEBUG_REPLAY_LINKED_FLAG_TRIGGER_STATUS = exports.SDK_DEBUG_REPLAY_EVENT_TRIGGER_STATUS = exports.SDK_DEBUG_RECORDING_SCRIPT_NOT_LOADED = exports.SDK_DEBUG_EXTENSIONS_INIT_TIME_MS = exports.SDK_DEBUG_EXTENSIONS_INIT_METHOD = exports.SDK_DIST_CHANNEL = exports.WEB_EXPERIMENTS = exports.COOKIELESS_MODE_FLAG_PROPERTY = exports.COOKIELESS_SENTINEL_VALUE = exports.TOOLBAR_CONTAINER_CLASS = exports.TOOLBAR_ID = exports.ENABLE_PERSON_PROCESSING = exports.INITIAL_PERSON_INFO = exports.INITIAL_REFERRER_INFO = exports.INITIAL_CAMPAIGN_PARAMS = exports.CAPTURE_RATE_LIMIT = exports.CLIENT_SESSION_PROPS = exports.USER_STATE = exports.PERSISTENCE_FEATURE_FLAG_EVALUATED_AT = exports.PERSISTENCE_FEATURE_FLAG_ERRORS = exports.FLAG_CALL_REPORTED_SESSION_ID = exports.FLAG_CALL_REPORTED = exports.CONVERSATIONS_LEGACY_USER_TRAITS = exports.CONVERSATIONS_LEGACY_WIDGET_STATE = exports.CONVERSATIONS_LEGACY_TICKET_ID = exports.CONVERSATIONS_LEGACY_WIDGET_SESSION_ID = exports.CONVERSATIONS = exports.PRODUCT_TOURS_ACTIVATED = exports.PRODUCT_TOURS = exports.SURVEYS_ACTIVATED = exports.SURVEYS_LOADED_AT = void 0; | ||
| exports.Z_INDEX_CONVERSATIONS = exports.Z_INDEX_SURVEYS = exports.Z_INDEX_TOURS = exports.EVENT_GROUPIDENTIFY = void 0; | ||
| exports.EVENT_PAGEVIEW = exports.DOM_EVENT_BEFOREUNLOAD = exports.DOM_EVENT_VISIBILITYCHANGE = exports.PERSON_PROFILES_IDENTIFIED_ONLY = exports.USER_STATE_IDENTIFIED = exports.USER_STATE_ANONYMOUS = exports.COOKIELESS_ALWAYS = exports.COOKIELESS_ON_REJECT = exports.LOAD_EXT_NOT_FOUND = exports.SURVEYS_REFRESH_BACKOFF_MS = exports.SURVEYS_CACHE_TTL_MS = exports.SURVEYS_REQUEST_TIMEOUT_MS = exports.SESSION_RECORDING_START_REASON = exports.SDK_DEBUG_REPLAY_RRWEB_START_ATTEMPTED = exports.SDK_DEBUG_REPLAY_RRWEB_ATTACHED = exports.SDK_DEBUG_REPLAY_URL_TRIGGER_STATUS = exports.SDK_DEBUG_REPLAY_TRIGGER_GROUPS_COUNT = exports.SDK_DEBUG_REPLAY_REMOTE_TRIGGER_MATCHING_CONFIG = exports.SDK_DEBUG_REPLAY_MATCHED_RECORDING_TRIGGER_GROUPS = exports.SDK_DEBUG_REPLAY_LINKED_FLAG_TRIGGER_STATUS = exports.SDK_DEBUG_REPLAY_EVENT_TRIGGER_STATUS = exports.SDK_DEBUG_RECORDING_SCRIPT_NOT_LOADED = exports.SDK_DEBUG_EXTENSIONS_INIT_TIME_MS = exports.SDK_DEBUG_EXTENSIONS_INIT_METHOD = exports.SDK_DIST_CHANNEL = exports.WEB_EXPERIMENTS = exports.COOKIELESS_MODE_FLAG_PROPERTY = exports.COOKIELESS_SENTINEL_VALUE = exports.TOOLBAR_CONTAINER_CLASS = exports.TOOLBAR_ID = exports.ENABLE_PERSON_PROCESSING = exports.INITIAL_PERSON_INFO = exports.INITIAL_REFERRER_INFO = exports.INITIAL_CAMPAIGN_PARAMS = exports.CAPTURE_RATE_LIMIT = exports.CLIENT_SESSION_PROPS = exports.USER_STATE = exports.PERSISTENCE_FEATURE_FLAG_EVALUATED_AT = exports.PERSISTENCE_FEATURE_FLAG_ERRORS = exports.FLAG_CALL_REPORTED_SESSION_ID = exports.FLAG_CALL_REPORTED = exports.CONVERSATIONS_LEGACY_USER_TRAITS = exports.CONVERSATIONS_LEGACY_WIDGET_STATE = exports.CONVERSATIONS_LEGACY_TICKET_ID = exports.CONVERSATIONS_LEGACY_WIDGET_SESSION_ID = exports.CONVERSATIONS = exports.PRODUCT_TOURS_ACTIVATED = exports.PRODUCT_TOURS = exports.SURVEYS_ACTIVATED = exports.SURVEYS_LOADED_AT = void 0; | ||
| exports.Z_INDEX_CONVERSATIONS = exports.Z_INDEX_SURVEYS = exports.Z_INDEX_TOURS = exports.EVENT_GROUPIDENTIFY = exports.EVENT_IDENTIFY = exports.EVENT_PAGELEAVE = void 0; | ||
| /* PROPERTY KEYS */ | ||
@@ -116,2 +116,10 @@ // This key is deprecated, but we want to check for it to see whether aliasing is allowed. | ||
| exports.SURVEYS_REQUEST_TIMEOUT_MS = 10000; | ||
| // How long the cached `$surveys` definitions are considered fresh. After this, the next | ||
| // `getSurveys` call serves the cache immediately but kicks off a background refresh so | ||
| // server-side changes (e.g. a survey switched from popover to API) propagate to a | ||
| // long-lived tab without needing a page reload. | ||
| exports.SURVEYS_CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes | ||
| // After a failed background refresh we back off for the same window as the cache TTL before | ||
| // trying again. Aliased to make the shared duration intentional rather than coincidental. | ||
| exports.SURVEYS_REFRESH_BACKOFF_MS = exports.SURVEYS_CACHE_TTL_MS; | ||
| exports.LOAD_EXT_NOT_FOUND = 'PostHog loadExternalDependency extension not found.'; | ||
@@ -118,0 +126,0 @@ /* EVENT NAMES - interned to reduce bundle size */ |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":";AAAA;;GAEG;;;;;AAEH,mBAAmB;AAEnB,0FAA0F;AAC7E,QAAA,sBAAsB,GAAG,qBAAqB,CAAA;AAC9C,QAAA,WAAW,GAAG,aAAa,CAAA;AAC3B,QAAA,SAAS,GAAG,YAAY,CAAA;AACxB,QAAA,YAAY,GAAG,eAAe,CAAA;AAC9B,QAAA,YAAY,GAAG,SAAS,CAAA;AACxB,QAAA,gBAAgB,GAAG,SAAS,CAAA;AAC5B,QAAA,gBAAgB,GAAG,UAAU,CAAA;AA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D,uBAAuB;AACV,QAAA,oBAAoB,GAAG,WAAW,CAAA;AAClC,QAAA,qBAAqB,GAAG,YAAY,CAAA;AAEjD,0BAA0B;AACb,QAAA,+BAA+B,GAAG,iBAA0B,CAAA;AAEzE,sDAAsD;AACzC,QAAA,0BAA0B,GAAG,kBAAkB,CAAA;AAC/C,QAAA,sBAAsB,GAAG,cAAc,CAAA;AAEvC,QAAA,cAAc,GAAG,WAAW,CAAA;AAC5B,QAAA,eAAe,GAAG,YAAY,CAAA;AAC9B,QAAA,cAAc,GAAG,WAAW,CAAA;AAC5B,QAAA,mBAAmB,GAAG,gBAAgB,CAAA;AAEnD,kDAAkD;AACrC,QAAA,aAAa,GAAG,UAAU,CAAA;AAC1B,QAAA,eAAe,GAAG,UAAU,CAAA;AAC5B,QAAA,qBAAqB,GAAG,UAAU,CAAA","sourcesContent":["/*\n * Constants\n */\n\n/* PROPERTY KEYS */\n\n// This key is deprecated, but we want to check for it to see whether aliasing is allowed.\nexport const PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id'\nexport const DISTINCT_ID = 'distinct_id'\nexport const DEVICE_ID = '$device_id'\nexport const DEVICE_MODEL = '$device_model'\nexport const ALIAS_ID_KEY = '__alias'\nexport const CAMPAIGN_IDS_KEY = '__cmpns'\nexport const EVENT_TIMERS_KEY = '__timers'\nexport const AUTOCAPTURE_DISABLED_SERVER_SIDE = '$autocapture_disabled_server_side'\nexport const HEATMAPS_ENABLED_SERVER_SIDE = '$heatmaps_enabled_server_side'\nexport const EXCEPTION_CAPTURE_ENABLED_SERVER_SIDE = '$exception_capture_enabled_server_side'\nexport const ERROR_TRACKING_SUPPRESSION_RULES = '$error_tracking_suppression_rules'\nexport const ERROR_TRACKING_CAPTURE_EXTENSION_EXCEPTIONS = '$error_tracking_capture_extension_exceptions'\nexport const WEB_VITALS_ENABLED_SERVER_SIDE = '$web_vitals_enabled_server_side'\nexport const DEAD_CLICKS_ENABLED_SERVER_SIDE = '$dead_clicks_enabled_server_side'\nexport const PRODUCT_TOURS_ENABLED_SERVER_SIDE = '$product_tours_enabled_server_side'\nexport const WEB_VITALS_ALLOWED_METRICS = '$web_vitals_allowed_metrics'\nexport const SESSION_RECORDING_REMOTE_CONFIG = '$session_recording_remote_config'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_ENABLED_SERVER_SIDE = '$session_recording_enabled_server_side'\n// @deprecated can be removed along with eager loaded replay\nexport const CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE = '$console_log_recording_enabled_server_side'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE = '$session_recording_network_payload_capture'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_MASKING = '$session_recording_masking'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_CANVAS_RECORDING = '$session_recording_canvas_recording'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_SAMPLE_RATE = '$replay_sample_rate'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_MINIMUM_DURATION = '$replay_minimum_duration'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_SCRIPT_CONFIG = '$replay_script_config'\nexport const SESSION_RECORDING_OVERRIDE_SAMPLING = '$replay_override_sampling'\nexport const SESSION_RECORDING_OVERRIDE_LINKED_FLAG = '$replay_override_linked_flag'\nexport const SESSION_RECORDING_OVERRIDE_URL_TRIGGER = '$replay_override_url_trigger'\nexport const SESSION_RECORDING_OVERRIDE_EVENT_TRIGGER = '$replay_override_event_trigger'\nexport const SESSION_ID = '$sesid'\nexport const SESSION_RECORDING_IS_SAMPLED = '$session_is_sampled'\nexport const SESSION_RECORDING_PAST_MINIMUM_DURATION = '$session_past_minimum_duration'\nexport const SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION = '$session_recording_url_trigger_activated_session'\nexport const SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION = '$session_recording_event_trigger_activated_session'\n// V2 Trigger Groups: Per-group persistence key prefixes (suffix with group ID)\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX = '$posthog_sr_group_event_trigger_'\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX = '$posthog_sr_group_url_trigger_'\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_SAMPLING_PREFIX = '$posthog_sr_group_sampling_'\nexport const SESSION_RECORDING_FIRST_FULL_SNAPSHOT_TIMESTAMP = '$debug_first_full_snapshot_timestamp'\nexport const SESSION_RECORDING_FLUSHED_SIZE = '$sess_rec_flush_size'\nexport const ENABLED_FEATURE_FLAGS = '$enabled_feature_flags'\nexport const PERSISTENCE_ACTIVE_FEATURE_FLAGS = '$active_feature_flags'\nexport const PERSISTENCE_EARLY_ACCESS_FEATURES = '$early_access_features'\nexport const PERSISTENCE_FEATURE_FLAG_DETAILS = '$feature_flag_details'\nexport const PERSISTENCE_FEATURE_FLAG_PAYLOADS = '$feature_flag_payloads'\nexport const PERSISTENCE_FEATURE_FLAG_REQUEST_ID = '$feature_flag_request_id'\nexport const PERSISTENCE_OVERRIDE_FEATURE_FLAGS = '$override_feature_flags'\nexport const PERSISTENCE_OVERRIDE_FEATURE_FLAG_PAYLOADS = '$override_feature_flag_payloads'\nexport const STORED_PERSON_PROPERTIES_KEY = '$stored_person_properties'\nexport const STORED_GROUP_PROPERTIES_KEY = '$stored_group_properties'\nexport const SURVEYS = '$surveys'\nexport const SURVEYS_LOADED_AT = '$surveys_loaded_at'\nexport const SURVEYS_ACTIVATED = '$surveys_activated'\nexport const PRODUCT_TOURS = 'ph_product_tours'\nexport const PRODUCT_TOURS_ACTIVATED = '$product_tours_activated'\nexport const CONVERSATIONS = '$conversations'\nexport const CONVERSATIONS_LEGACY_WIDGET_SESSION_ID = '$conversations_widget_session_id'\nexport const CONVERSATIONS_LEGACY_TICKET_ID = '$conversations_ticket_id'\nexport const CONVERSATIONS_LEGACY_WIDGET_STATE = '$conversations_widget_state'\nexport const CONVERSATIONS_LEGACY_USER_TRAITS = '$conversations_user_traits'\nexport const FLAG_CALL_REPORTED = '$flag_call_reported'\nexport const FLAG_CALL_REPORTED_SESSION_ID = '$flag_call_reported_session_id'\nexport const PERSISTENCE_FEATURE_FLAG_ERRORS = '$feature_flag_errors'\nexport const PERSISTENCE_FEATURE_FLAG_EVALUATED_AT = '$feature_flag_evaluated_at'\nexport const USER_STATE = '$user_state'\nexport const CLIENT_SESSION_PROPS = '$client_session_props'\nexport const CAPTURE_RATE_LIMIT = '$capture_rate_limit'\n\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_CAMPAIGN_PARAMS = '$initial_campaign_params'\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_REFERRER_INFO = '$initial_referrer_info'\nexport const INITIAL_PERSON_INFO = '$initial_person_info'\nexport const ENABLE_PERSON_PROCESSING = '$epp'\nexport const TOOLBAR_ID = '__POSTHOG_TOOLBAR__'\nexport const TOOLBAR_CONTAINER_CLASS = 'toolbar-global-fade-container'\n\n/**\n * PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION\n * Sentinel value for distinct id, device id, session id. Signals that the server should generate the value\n * */\nexport const COOKIELESS_SENTINEL_VALUE = '$posthog_cookieless'\nexport const COOKIELESS_MODE_FLAG_PROPERTY = '$cookieless_mode'\n\nexport const WEB_EXPERIMENTS = '$web_experiments'\n\nexport const SDK_DIST_CHANNEL = '$sdk_dist_channel'\nexport const SDK_DEBUG_EXTENSIONS_INIT_METHOD = '$sdk_debug_extensions_init_method'\nexport const SDK_DEBUG_EXTENSIONS_INIT_TIME_MS = '$sdk_debug_extensions_init_time_ms'\nexport const SDK_DEBUG_RECORDING_SCRIPT_NOT_LOADED = '$sdk_debug_recording_script_not_loaded'\nexport const SDK_DEBUG_REPLAY_EVENT_TRIGGER_STATUS = '$sdk_debug_replay_event_trigger_status'\nexport const SDK_DEBUG_REPLAY_LINKED_FLAG_TRIGGER_STATUS = '$sdk_debug_replay_linked_flag_trigger_status'\nexport const SDK_DEBUG_REPLAY_MATCHED_RECORDING_TRIGGER_GROUPS = '$sdk_debug_replay_matched_recording_trigger_groups'\nexport const SDK_DEBUG_REPLAY_REMOTE_TRIGGER_MATCHING_CONFIG = '$sdk_debug_replay_remote_trigger_matching_config'\nexport const SDK_DEBUG_REPLAY_TRIGGER_GROUPS_COUNT = '$sdk_debug_replay_trigger_groups_count'\nexport const SDK_DEBUG_REPLAY_URL_TRIGGER_STATUS = '$sdk_debug_replay_url_trigger_status'\nexport const SDK_DEBUG_REPLAY_RRWEB_ATTACHED = '$sdk_debug_rrweb_attached'\nexport const SDK_DEBUG_REPLAY_RRWEB_START_ATTEMPTED = '$sdk_debug_rrweb_start_attempted'\nexport const SESSION_RECORDING_START_REASON = '$session_recording_start_reason'\n\nexport const SURVEYS_REQUEST_TIMEOUT_MS = 10000\nexport const LOAD_EXT_NOT_FOUND = 'PostHog loadExternalDependency extension not found.'\n\n/* EVENT NAMES - interned to reduce bundle size */\n/* COOKIELESS MODE VALUES */\nexport const COOKIELESS_ON_REJECT = 'on_reject' as const\nexport const COOKIELESS_ALWAYS = 'always' as const\n\n/* USER STATE VALUES */\nexport const USER_STATE_ANONYMOUS = 'anonymous'\nexport const USER_STATE_IDENTIFIED = 'identified'\n\n/* PERSON PROFILE MODES */\nexport const PERSON_PROFILES_IDENTIFIED_ONLY = 'identified_only' as const\n\n/* DOM EVENT NAMES - interned to reduce bundle size */\nexport const DOM_EVENT_VISIBILITYCHANGE = 'visibilitychange'\nexport const DOM_EVENT_BEFOREUNLOAD = 'beforeunload'\n\nexport const EVENT_PAGEVIEW = '$pageview'\nexport const EVENT_PAGELEAVE = '$pageleave'\nexport const EVENT_IDENTIFY = '$identify'\nexport const EVENT_GROUPIDENTIFY = '$groupidentify'\n\n/* Z-INDEX HIERARCHY: tours > surveys > support */\nexport const Z_INDEX_TOURS = 2147483646\nexport const Z_INDEX_SURVEYS = 2147483645\nexport const Z_INDEX_CONVERSATIONS = 2147483644\n"]} | ||
| {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":";AAAA;;GAEG;;;;;AAEH,mBAAmB;AAEnB,0FAA0F;AAC7E,QAAA,sBAAsB,GAAG,qBAAqB,CAAA;AAC9C,QAAA,WAAW,GAAG,aAAa,CAAA;AAC3B,QAAA,SAAS,GAAG,YAAY,CAAA;AACxB,QAAA,YAAY,GAAG,eAAe,CAAA;AAC9B,QAAA,YAAY,GAAG,SAAS,CAAA;AACxB,QAAA,gBAAgB,GAAG,SAAS,CAAA;AAC5B,QAAA,gBAAgB,GAAG,UAAU,CAAA;AAC7B,QAAA,gCAAgC,GAAG,mCAAmC,CAAA;AACtE,QAAA,4BAA4B,GAAG,+BAA+B,CAAA;AAC9D,QAAA,qCAAqC,GAAG,wCAAwC,CAAA;AAChF,QAAA,gCAAgC,GAAG,mCAAmC,CAAA;AACtE,QAAA,2CAA2C,GAAG,8CAA8C,CAAA;AAC5F,QAAA,8BAA8B,GAAG,iCAAiC,CAAA;AAClE,QAAA,+BAA+B,GAAG,kCAAkC,CAAA;AACpE,QAAA,iCAAiC,GAAG,oCAAoC,CAAA;AACxE,QAAA,0BAA0B,GAAG,6BAA6B,CAAA;AAC1D,QAAA,+BAA+B,GAAG,kCAAkC,CAAA;AACjF,4DAA4D;AAC/C,QAAA,qCAAqC,GAAG,wCAAwC,CAAA;AAC7F,4DAA4D;AAC/C,QAAA,yCAAyC,GAAG,4CAA4C,CAAA;AACrG,4DAA4D;AAC/C,QAAA,yCAAyC,GAAG,4CAA4C,CAAA;AACrG,4DAA4D;AAC/C,QAAA,yBAAyB,GAAG,4BAA4B,CAAA;AACrE,4DAA4D;AAC/C,QAAA,kCAAkC,GAAG,qCAAqC,CAAA;AACvF,4DAA4D;AAC/C,QAAA,6BAA6B,GAAG,qBAAqB,C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\n */\n\n/* PROPERTY KEYS */\n\n// This key is deprecated, but we want to check for it to see whether aliasing is allowed.\nexport const PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id'\nexport const DISTINCT_ID = 'distinct_id'\nexport const DEVICE_ID = '$device_id'\nexport const DEVICE_MODEL = '$device_model'\nexport const ALIAS_ID_KEY = '__alias'\nexport const CAMPAIGN_IDS_KEY = '__cmpns'\nexport const EVENT_TIMERS_KEY = '__timers'\nexport const AUTOCAPTURE_DISABLED_SERVER_SIDE = '$autocapture_disabled_server_side'\nexport const HEATMAPS_ENABLED_SERVER_SIDE = '$heatmaps_enabled_server_side'\nexport const EXCEPTION_CAPTURE_ENABLED_SERVER_SIDE = '$exception_capture_enabled_server_side'\nexport const ERROR_TRACKING_SUPPRESSION_RULES = '$error_tracking_suppression_rules'\nexport const ERROR_TRACKING_CAPTURE_EXTENSION_EXCEPTIONS = '$error_tracking_capture_extension_exceptions'\nexport const WEB_VITALS_ENABLED_SERVER_SIDE = '$web_vitals_enabled_server_side'\nexport const DEAD_CLICKS_ENABLED_SERVER_SIDE = '$dead_clicks_enabled_server_side'\nexport const PRODUCT_TOURS_ENABLED_SERVER_SIDE = '$product_tours_enabled_server_side'\nexport const WEB_VITALS_ALLOWED_METRICS = '$web_vitals_allowed_metrics'\nexport const SESSION_RECORDING_REMOTE_CONFIG = '$session_recording_remote_config'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_ENABLED_SERVER_SIDE = '$session_recording_enabled_server_side'\n// @deprecated can be removed along with eager loaded replay\nexport const CONSOLE_LOG_RECORDING_ENABLED_SERVER_SIDE = '$console_log_recording_enabled_server_side'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_NETWORK_PAYLOAD_CAPTURE = '$session_recording_network_payload_capture'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_MASKING = '$session_recording_masking'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_CANVAS_RECORDING = '$session_recording_canvas_recording'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_SAMPLE_RATE = '$replay_sample_rate'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_MINIMUM_DURATION = '$replay_minimum_duration'\n// @deprecated can be removed along with eager loaded replay\nexport const SESSION_RECORDING_SCRIPT_CONFIG = '$replay_script_config'\nexport const SESSION_RECORDING_OVERRIDE_SAMPLING = '$replay_override_sampling'\nexport const SESSION_RECORDING_OVERRIDE_LINKED_FLAG = '$replay_override_linked_flag'\nexport const SESSION_RECORDING_OVERRIDE_URL_TRIGGER = '$replay_override_url_trigger'\nexport const SESSION_RECORDING_OVERRIDE_EVENT_TRIGGER = '$replay_override_event_trigger'\nexport const SESSION_ID = '$sesid'\nexport const SESSION_RECORDING_IS_SAMPLED = '$session_is_sampled'\nexport const SESSION_RECORDING_PAST_MINIMUM_DURATION = '$session_past_minimum_duration'\nexport const SESSION_RECORDING_URL_TRIGGER_ACTIVATED_SESSION = '$session_recording_url_trigger_activated_session'\nexport const SESSION_RECORDING_EVENT_TRIGGER_ACTIVATED_SESSION = '$session_recording_event_trigger_activated_session'\n// V2 Trigger Groups: Per-group persistence key prefixes (suffix with group ID)\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_EVENT_PREFIX = '$posthog_sr_group_event_trigger_'\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_URL_PREFIX = '$posthog_sr_group_url_trigger_'\nexport const SESSION_RECORDING_TRIGGER_V2_GROUP_SAMPLING_PREFIX = '$posthog_sr_group_sampling_'\nexport const SESSION_RECORDING_FIRST_FULL_SNAPSHOT_TIMESTAMP = '$debug_first_full_snapshot_timestamp'\nexport const SESSION_RECORDING_FLUSHED_SIZE = '$sess_rec_flush_size'\nexport const ENABLED_FEATURE_FLAGS = '$enabled_feature_flags'\nexport const PERSISTENCE_ACTIVE_FEATURE_FLAGS = '$active_feature_flags'\nexport const PERSISTENCE_EARLY_ACCESS_FEATURES = '$early_access_features'\nexport const PERSISTENCE_FEATURE_FLAG_DETAILS = '$feature_flag_details'\nexport const PERSISTENCE_FEATURE_FLAG_PAYLOADS = '$feature_flag_payloads'\nexport const PERSISTENCE_FEATURE_FLAG_REQUEST_ID = '$feature_flag_request_id'\nexport const PERSISTENCE_OVERRIDE_FEATURE_FLAGS = '$override_feature_flags'\nexport const PERSISTENCE_OVERRIDE_FEATURE_FLAG_PAYLOADS = '$override_feature_flag_payloads'\nexport const STORED_PERSON_PROPERTIES_KEY = '$stored_person_properties'\nexport const STORED_GROUP_PROPERTIES_KEY = '$stored_group_properties'\nexport const SURVEYS = '$surveys'\nexport const SURVEYS_LOADED_AT = '$surveys_loaded_at'\nexport const SURVEYS_ACTIVATED = '$surveys_activated'\nexport const PRODUCT_TOURS = 'ph_product_tours'\nexport const PRODUCT_TOURS_ACTIVATED = '$product_tours_activated'\nexport const CONVERSATIONS = '$conversations'\nexport const CONVERSATIONS_LEGACY_WIDGET_SESSION_ID = '$conversations_widget_session_id'\nexport const CONVERSATIONS_LEGACY_TICKET_ID = '$conversations_ticket_id'\nexport const CONVERSATIONS_LEGACY_WIDGET_STATE = '$conversations_widget_state'\nexport const CONVERSATIONS_LEGACY_USER_TRAITS = '$conversations_user_traits'\nexport const FLAG_CALL_REPORTED = '$flag_call_reported'\nexport const FLAG_CALL_REPORTED_SESSION_ID = '$flag_call_reported_session_id'\nexport const PERSISTENCE_FEATURE_FLAG_ERRORS = '$feature_flag_errors'\nexport const PERSISTENCE_FEATURE_FLAG_EVALUATED_AT = '$feature_flag_evaluated_at'\nexport const USER_STATE = '$user_state'\nexport const CLIENT_SESSION_PROPS = '$client_session_props'\nexport const CAPTURE_RATE_LIMIT = '$capture_rate_limit'\n\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_CAMPAIGN_PARAMS = '$initial_campaign_params'\n/** @deprecated Delete this when INITIAL_PERSON_INFO has been around for long enough to ignore backwards compat */\nexport const INITIAL_REFERRER_INFO = '$initial_referrer_info'\nexport const INITIAL_PERSON_INFO = '$initial_person_info'\nexport const ENABLE_PERSON_PROCESSING = '$epp'\nexport const TOOLBAR_ID = '__POSTHOG_TOOLBAR__'\nexport const TOOLBAR_CONTAINER_CLASS = 'toolbar-global-fade-container'\n\n/**\n * PREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION\n * Sentinel value for distinct id, device id, session id. Signals that the server should generate the value\n * */\nexport const COOKIELESS_SENTINEL_VALUE = '$posthog_cookieless'\nexport const COOKIELESS_MODE_FLAG_PROPERTY = '$cookieless_mode'\n\nexport const WEB_EXPERIMENTS = '$web_experiments'\n\nexport const SDK_DIST_CHANNEL = '$sdk_dist_channel'\nexport const SDK_DEBUG_EXTENSIONS_INIT_METHOD = '$sdk_debug_extensions_init_method'\nexport const SDK_DEBUG_EXTENSIONS_INIT_TIME_MS = '$sdk_debug_extensions_init_time_ms'\nexport const SDK_DEBUG_RECORDING_SCRIPT_NOT_LOADED = '$sdk_debug_recording_script_not_loaded'\nexport const SDK_DEBUG_REPLAY_EVENT_TRIGGER_STATUS = '$sdk_debug_replay_event_trigger_status'\nexport const SDK_DEBUG_REPLAY_LINKED_FLAG_TRIGGER_STATUS = '$sdk_debug_replay_linked_flag_trigger_status'\nexport const SDK_DEBUG_REPLAY_MATCHED_RECORDING_TRIGGER_GROUPS = '$sdk_debug_replay_matched_recording_trigger_groups'\nexport const SDK_DEBUG_REPLAY_REMOTE_TRIGGER_MATCHING_CONFIG = '$sdk_debug_replay_remote_trigger_matching_config'\nexport const SDK_DEBUG_REPLAY_TRIGGER_GROUPS_COUNT = '$sdk_debug_replay_trigger_groups_count'\nexport const SDK_DEBUG_REPLAY_URL_TRIGGER_STATUS = '$sdk_debug_replay_url_trigger_status'\nexport const SDK_DEBUG_REPLAY_RRWEB_ATTACHED = '$sdk_debug_rrweb_attached'\nexport const SDK_DEBUG_REPLAY_RRWEB_START_ATTEMPTED = '$sdk_debug_rrweb_start_attempted'\nexport const SESSION_RECORDING_START_REASON = '$session_recording_start_reason'\n\nexport const SURVEYS_REQUEST_TIMEOUT_MS = 10000\n// How long the cached `$surveys` definitions are considered fresh. After this, the next\n// `getSurveys` call serves the cache immediately but kicks off a background refresh so\n// server-side changes (e.g. a survey switched from popover to API) propagate to a\n// long-lived tab without needing a page reload.\nexport const SURVEYS_CACHE_TTL_MS = 5 * 60 * 1000 // 5 minutes\n// After a failed background refresh we back off for the same window as the cache TTL before\n// trying again. Aliased to make the shared duration intentional rather than coincidental.\nexport const SURVEYS_REFRESH_BACKOFF_MS = SURVEYS_CACHE_TTL_MS\nexport const LOAD_EXT_NOT_FOUND = 'PostHog loadExternalDependency extension not found.'\n\n/* EVENT NAMES - interned to reduce bundle size */\n/* COOKIELESS MODE VALUES */\nexport const COOKIELESS_ON_REJECT = 'on_reject' as const\nexport const COOKIELESS_ALWAYS = 'always' as const\n\n/* USER STATE VALUES */\nexport const USER_STATE_ANONYMOUS = 'anonymous'\nexport const USER_STATE_IDENTIFIED = 'identified'\n\n/* PERSON PROFILE MODES */\nexport const PERSON_PROFILES_IDENTIFIED_ONLY = 'identified_only' as const\n\n/* DOM EVENT NAMES - interned to reduce bundle size */\nexport const DOM_EVENT_VISIBILITYCHANGE = 'visibilitychange'\nexport const DOM_EVENT_BEFOREUNLOAD = 'beforeunload'\n\nexport const EVENT_PAGEVIEW = '$pageview'\nexport const EVENT_PAGELEAVE = '$pageleave'\nexport const EVENT_IDENTIFY = '$identify'\nexport const EVENT_GROUPIDENTIFY = '$groupidentify'\n\n/* Z-INDEX HIERARCHY: tours > surveys > support */\nexport const Z_INDEX_TOURS = 2147483646\nexport const Z_INDEX_SURVEYS = 2147483645\nexport const Z_INDEX_CONVERSATIONS = 2147483644\n"]} |
@@ -14,2 +14,3 @@ import type { Extension } from './extensions/types'; | ||
| private _getSurveysInFlightPromise; | ||
| private _lastSurveyRefreshFailedAt; | ||
| private get _config(); | ||
@@ -47,2 +48,30 @@ constructor(_instance: PostHog); | ||
| getSurveys(callback: SurveyCallback, forceReload?: boolean): void; | ||
| /** | ||
| * Whether to kick off a background refresh of the cached definitions: the cache is stale, no | ||
| * fetch is already in flight, and we're not backing off after a recent failure. | ||
| */ | ||
| private _shouldBackgroundRefreshSurveys; | ||
| /** | ||
| * Whether the cached `$surveys` definitions have aged past their TTL. Returns false when no | ||
| * timestamp is recorded (e.g. surveys injected directly in tests) so the cache stays valid. | ||
| */ | ||
| private _isSurveyCacheStale; | ||
| private _isSurveyRefreshBackingOff; | ||
| /** | ||
| * Marks a survey as seen for the current device, mirroring the local state the SDK records | ||
| * when it shows or sends a survey itself. | ||
| * | ||
| * Use this when you display surveys through your own backend/integration (so the SDK never | ||
| * captures the `survey shown`/`sent`/`dismissed` events) and still want PostHog's display | ||
| * logic to honour the "already seen" and wait-period checks on subsequent page loads. | ||
| * | ||
| * Note: surveys configured to repeat (`schedule: 'always'` or event `repeatedActivation`) | ||
| * intentionally bypass the seen check, so marking them as seen will not stop them showing. | ||
| * | ||
| * @param surveyId The ID of the survey to mark as seen. | ||
| * @param options Optional settings. `iteration` is the survey's current iteration number, if any. | ||
| */ | ||
| markSurveyAsSeen(surveyId: string, options?: { | ||
| iteration?: number | null; | ||
| }): void; | ||
| /** Helper method to notify all registered callbacks */ | ||
@@ -49,0 +78,0 @@ private _notifySurveyCallbacks; |
@@ -47,2 +47,5 @@ "use strict"; | ||
| this._getSurveysInFlightPromise = null; | ||
| // Backs off the stale-cache refresh for one TTL after a failure, so a surveys-API outage can't | ||
| // turn the ~1s display poll into a per-poll request storm. | ||
| this._lastSurveyRefreshFailedAt = null; | ||
| // we set this to undefined here because we need the persistence storage for this type | ||
@@ -217,5 +220,14 @@ // but that's not initialized until loadIfEnabled is called. | ||
| if (existingSurveys && !forceReload) { | ||
| return callback(existingSurveys, { | ||
| // Serve the cached definitions synchronously so callers that rely on a synchronous | ||
| // callback (e.g. _getSurveyById) keep working. | ||
| callback(existingSurveys, { | ||
| isLoaded: true, | ||
| }); | ||
| // If the cache has aged past its TTL, kick off a background refresh so server-side | ||
| // changes (e.g. a survey switched from popover to API) reach a long-lived tab. The | ||
| // next poll then evaluates the refreshed definitions. | ||
| if (this._shouldBackgroundRefreshSurveys()) { | ||
| this.getSurveys(function () { }, true); | ||
| } | ||
| return; | ||
| } | ||
@@ -252,2 +264,3 @@ // If a fetch is already in progress and Promise is available, reuse that promise | ||
| survey_utils_1.SURVEY_LOGGER.error(error); | ||
| _this._lastSurveyRefreshFailedAt = Date.now(); | ||
| var context_1 = { isLoaded: false, error: error }; | ||
@@ -258,2 +271,3 @@ callback([], context_1); | ||
| } | ||
| _this._lastSurveyRefreshFailedAt = null; | ||
| var surveys = response.json.surveys || []; | ||
@@ -277,2 +291,46 @@ var eventOrActionBasedSurveys = surveys.filter(function (survey) { | ||
| }; | ||
| /** | ||
| * Whether to kick off a background refresh of the cached definitions: the cache is stale, no | ||
| * fetch is already in flight, and we're not backing off after a recent failure. | ||
| */ | ||
| PostHogSurveys.prototype._shouldBackgroundRefreshSurveys = function () { | ||
| return this._isSurveyCacheStale() && !this._getSurveysInFlightPromise && !this._isSurveyRefreshBackingOff(); | ||
| }; | ||
| /** | ||
| * Whether the cached `$surveys` definitions have aged past their TTL. Returns false when no | ||
| * timestamp is recorded (e.g. surveys injected directly in tests) so the cache stays valid. | ||
| */ | ||
| PostHogSurveys.prototype._isSurveyCacheStale = function () { | ||
| var surveysLoadedAt = this._instance.get_property(constants_1.SURVEYS_LOADED_AT); | ||
| return (0, core_1.isNumber)(surveysLoadedAt) && Date.now() - surveysLoadedAt > constants_1.SURVEYS_CACHE_TTL_MS; | ||
| }; | ||
| PostHogSurveys.prototype._isSurveyRefreshBackingOff = function () { | ||
| return ((0, core_1.isNumber)(this._lastSurveyRefreshFailedAt) && | ||
| Date.now() - this._lastSurveyRefreshFailedAt < constants_1.SURVEYS_REFRESH_BACKOFF_MS); | ||
| }; | ||
| /** | ||
| * Marks a survey as seen for the current device, mirroring the local state the SDK records | ||
| * when it shows or sends a survey itself. | ||
| * | ||
| * Use this when you display surveys through your own backend/integration (so the SDK never | ||
| * captures the `survey shown`/`sent`/`dismissed` events) and still want PostHog's display | ||
| * logic to honour the "already seen" and wait-period checks on subsequent page loads. | ||
| * | ||
| * Note: surveys configured to repeat (`schedule: 'always'` or event `repeatedActivation`) | ||
| * intentionally bypass the seen check, so marking them as seen will not stop them showing. | ||
| * | ||
| * @param surveyId The ID of the survey to mark as seen. | ||
| * @param options Optional settings. `iteration` is the survey's current iteration number, if any. | ||
| */ | ||
| PostHogSurveys.prototype.markSurveyAsSeen = function (surveyId, options) { | ||
| var _a; | ||
| var survey = { id: surveyId, current_iteration: (_a = options === null || options === void 0 ? void 0 : options.iteration) !== null && _a !== void 0 ? _a : null }; | ||
| (0, survey_utils_1.setSurveySeenOnLocalStorage)(survey); | ||
| try { | ||
| localStorage.setItem('lastSeenSurveyDate', new Date().toISOString()); | ||
| } | ||
| catch (_b) { | ||
| // localStorage is not always available (e.g. in cross-origin iframes); best-effort only. | ||
| } | ||
| }; | ||
| /** Helper method to notify all registered callbacks */ | ||
@@ -279,0 +337,0 @@ PostHogSurveys.prototype._notifySurveyCallbacks = function (context) { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"posthog-surveys.js","sourceRoot":"","sources":["../../src/posthog-surveys.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yCAA4E;AAE5E,IAAM,iBAAiB,GAAG,8DAA8D,CAAA;AACxF,IAAM,eAAe,GAAG,gCAAgC,CAAA;AAIxD,iEAMgC;AAEhC,2CAA4D;AAC5D,uEAAmE;AACnE,qDAQ6B;AAC7B,sCAA+D;AAE/D;IAoBI,wBAA6B,SAAkB;QAAlB,cAAS,GAAT,SAAS,CAAS;QAnB/C,6DAA6D;QAC7D,qDAAqD;QACrD,2CAA2C;QAC3C,sEAAsE;QAC9D,sBAAiB,GAAa,SAAS,CAAA;QAEvC,mBAAc,GAAyB,IAAI,CAAA;QAC3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AU,CAAC,CAAA;YACxE,OAAM;QACV,CAAC;QACD,IAAI,CAAC,cAAc,CAAC,mBAAmB,CAAC,eAAe,EAAE,OAAO,CAAC,CAAA;IACrE,CAAC;IAED,4CAAmB,GAAnB,UAAoB,QAAgB;QAChC,IAAI,IAAA,gBAAS,EAAC,IAAI,CAAC,cAAc,CAAC,EAAE,CAAC;YACjC,4BAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAA;YAClC,OAAM;QACV,CAAC;QACD,IAAI,CAAC,cAAc,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAA;IAC9C,CAAC;IAED,yCAAgB,GAAhB;;QACI,MAAA,IAAI,CAAC,cAAc,0CAAE,gBAAgB,EAAE,CAAA;IAC3C,CAAC;IACL,qBAAC;AAAD,CAAC,AAhaD,IAgaC;AAhaY,wCAAc","sourcesContent":["import { LOAD_EXT_NOT_FOUND, SURVEYS, SURVEYS_LOADED_AT } from './constants'\n\nconst SURVEY_NOT_LOADED = 'SDK is not enabled or survey functionality is not yet loaded'\nconst SURVEY_DISABLED = 'Disabled. Not loading surveys.'\nimport { SurveyManager } from './extensions/surveys'\nimport type { Extension } from './extensions/types'\nimport { PostHog } from './posthog-core'\nimport {\n DisplaySurveyOptions,\n DisplaySurveyType,\n Survey,\n SurveyCallback,\n SurveyRenderReason,\n} from './posthog-surveys-types'\nimport { Properties, RemoteConfig } from './types'\nimport { assignableWindow, document } from './utils/globals'\nimport { SurveyEventReceiver } from './utils/survey-event-receiver'\nimport {\n doesSurveyActivateByAction,\n doesSurveyActivateByEvent,\n IN_APP_SURVEY_TYPES,\n isSurveyRunning,\n SURVEY_LOGGER as logger,\n SURVEY_IN_PROGRESS_PREFIX,\n SURVEY_SEEN_PREFIX,\n} from './utils/survey-utils'\nimport { isNullish, isUndefined, isArray } from '@posthog/core'\n\nexport class PostHogSurveys implements Extension {\n // this is set to undefined until the remote config is loaded\n // then it's set to true if there are surveys to load\n // or false if there are no surveys to load\n // or false if the surveys feature is disabled in the project settings\n private _isSurveysEnabled?: boolean = undefined\n public _surveyEventReceiver: SurveyEventReceiver | null\n private _surveyManager: SurveyManager | null = null\n private _isInitializingSurveys: boolean = false\n private _surveyCallbacks: SurveyCallback[] = []\n // Promise for in-flight survey fetch - allows multiple callers to await the same request\n private _getSurveysInFlightPromise: Promise<{\n surveys: Survey[]\n context: { isLoaded: boolean; error?: string }\n }> | null = null\n\n private get _config() {\n return this._instance.config\n }\n\n constructor(private readonly _instance: PostHog) {\n // we set this to undefined here because we need the persistence storage for this type\n // but that's not initialized until loadIfEnabled is called.\n this._surveyEventReceiver = null\n }\n\n initialize() {\n this.loadIfEnabled()\n }\n\n onRemoteConfig(response: RemoteConfig) {\n // only load surveys if they are enabled and there are surveys to load\n if (this._config.disable_surveys) {\n return\n }\n\n const surveys = response['surveys']\n if (isNullish(surveys)) {\n return logger.warn('Flags not loaded yet. Not loading surveys.')\n }\n const isArrayResponse = isArray(surveys)\n this._isSurveysEnabled = isArrayResponse ? surveys.length > 0 : surveys\n logger.info(`flags response received, isSurveysEnabled: ${this._isSurveysEnabled}`)\n this.loadIfEnabled()\n }\n\n reset(): void {\n try {\n // Drop in-memory event/action activations too; they aren't in persistence (which\n // reset() has already cleared), so without this an armed-but-unshown survey would\n // survive a logout/account switch that doesn't reload the page.\n this._surveyEventReceiver?.reset()\n localStorage.removeItem('lastSeenSurveyDate')\n const surveyKeys = []\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i)\n if (key?.startsWith(SURVEY_SEEN_PREFIX) || key?.startsWith(SURVEY_IN_PROGRESS_PREFIX)) {\n surveyKeys.push(key)\n }\n }\n\n surveyKeys.forEach((key) => localStorage.removeItem(key))\n } catch {\n // localStorage is not always available (e.g. in cross-origin iframes); resetting survey state is best-effort.\n }\n }\n\n loadIfEnabled() {\n // Initial guard clauses\n if (this._surveyManager) {\n return\n } // Already loaded\n if (this._isInitializingSurveys) {\n logger.info('Already initializing surveys, skipping...')\n return\n }\n if (this._config.disable_surveys) {\n logger.info(SURVEY_DISABLED)\n return\n }\n if (this._config.cookieless_mode && this._instance.consent.isOptedOut()) {\n logger.info('Not loading surveys in cookieless mode without consent.')\n return\n }\n\n const phExtensions = assignableWindow?.__PosthogExtensions__\n if (!phExtensions) {\n logger.error('PostHog Extensions not found.')\n return\n }\n\n // waiting for remote config to load\n // if surveys is forced enable (like external surveys), ignore the remote config and load surveys\n if (isUndefined(this._isSurveysEnabled) && !this._config.advanced_enable_surveys) {\n return\n }\n\n const isSurveysEnabled = this._isSurveysEnabled || this._config.advanced_enable_surveys\n\n this._isInitializingSurveys = true\n\n try {\n const generateSurveys = phExtensions.generateSurveys\n if (generateSurveys) {\n // Surveys code is already loaded\n this._completeSurveyInitialization(generateSurveys, isSurveysEnabled)\n return\n }\n\n // If we reach here, surveys code is not loaded yet\n const loadExternalDependency = phExtensions.loadExternalDependency\n if (!loadExternalDependency) {\n // Cannot load surveys code\n this._handleSurveyLoadError(LOAD_EXT_NOT_FOUND)\n return\n }\n\n // If we reach here, we need to load the dependency\n loadExternalDependency(this._instance, 'surveys', (err) => {\n if (err || !phExtensions.generateSurveys) {\n this._handleSurveyLoadError('Could not load surveys script', err)\n } else {\n // Need to get the function reference again inside the callback\n this._completeSurveyInitialization(phExtensions.generateSurveys, isSurveysEnabled)\n }\n })\n } catch (e) {\n this._handleSurveyLoadError('Error initializing surveys', e)\n throw e\n } finally {\n // Ensure the flag is always reset\n this._isInitializingSurveys = false\n }\n }\n\n /** Helper to finalize survey initialization */\n private _completeSurveyInitialization(\n generateSurveysFn: (instance: PostHog, isSurveysEnabled: boolean) => any,\n isSurveysEnabled: boolean\n ): void {\n this._surveyManager = generateSurveysFn(this._instance, isSurveysEnabled)\n this._surveyEventReceiver = new SurveyEventReceiver(this._instance)\n logger.info('Surveys loaded successfully')\n this._notifySurveyCallbacks({ isLoaded: true })\n }\n\n /** Helper to handle errors during survey loading */\n private _handleSurveyLoadError(message: string, error?: any): void {\n logger.error(message, error)\n this._notifySurveyCallbacks({ isLoaded: false, error: message })\n }\n\n /**\n * Register a callback that runs when surveys are initialized.\n * ### Usage:\n *\n * posthog.onSurveysLoaded((surveys) => {\n * // You can work with all surveys\n * console.log('All available surveys:', surveys)\n *\n * // Or get active matching surveys\n * posthog.getActiveMatchingSurveys((activeMatchingSurveys) => {\n * if (activeMatchingSurveys.length > 0) {\n * posthog.renderSurvey(activeMatchingSurveys[0].id, '#survey-container')\n * }\n * })\n * })\n *\n * @param {Function} callback The callback function will be called when surveys are loaded or updated.\n * It receives the array of all surveys and a context object with error status.\n * @returns {Function} A function that can be called to unsubscribe the listener.\n */\n onSurveysLoaded(callback: SurveyCallback): () => void {\n this._surveyCallbacks.push(callback)\n\n if (this._surveyManager) {\n this._notifySurveyCallbacks({\n isLoaded: true,\n })\n }\n // Return unsubscribe function\n return () => {\n this._surveyCallbacks = this._surveyCallbacks.filter((cb: SurveyCallback) => cb !== callback)\n }\n }\n\n getSurveys(callback: SurveyCallback, forceReload = false) {\n // In case we manage to load the surveys script, but config says not to load surveys\n // then we shouldn't return survey data\n if (this._config.disable_surveys) {\n logger.info(SURVEY_DISABLED)\n return callback([])\n }\n\n const existingSurveys = this._instance.get_property(SURVEYS)\n if (existingSurveys && !forceReload) {\n return callback(existingSurveys, {\n isLoaded: true,\n })\n }\n\n // If a fetch is already in progress and Promise is available, reuse that promise\n // In browsers without Promise (IE11), we skip this optimization and just make concurrent requests\n if (typeof Promise !== 'undefined' && this._getSurveysInFlightPromise) {\n this._getSurveysInFlightPromise.then(({ surveys, context }) => callback(surveys, context))\n return\n }\n\n // Create a new promise for this fetch that other callers can reuse\n // We need to assign the promise before starting the request, because\n // in tests (and potentially in some edge cases) the callback may fire synchronously\n let resolvePromise: (value: { surveys: Survey[]; context: { isLoaded: boolean; error?: string } }) => void\n if (typeof Promise !== 'undefined') {\n this._getSurveysInFlightPromise = new Promise((resolve) => {\n resolvePromise = resolve\n })\n }\n\n this._instance._send_request({\n url: this._instance.requestRouter.endpointFor('api', `/api/surveys/?token=${this._config.token}`),\n method: 'GET',\n timeout: this._config.surveys_request_timeout_ms,\n callback: (response) => {\n this._getSurveysInFlightPromise = null\n\n const statusCode = response.statusCode\n if (statusCode !== 200 || !response.json) {\n const error = `Surveys API could not be loaded, status: ${statusCode}`\n logger.error(error)\n const context = { isLoaded: false, error }\n callback([], context)\n resolvePromise?.({ surveys: [], context })\n return\n }\n const surveys = response.json.surveys || []\n\n const eventOrActionBasedSurveys = surveys.filter(\n (survey: Survey) =>\n isSurveyRunning(survey) &&\n (doesSurveyActivateByEvent(survey) || doesSurveyActivateByAction(survey))\n )\n\n if (eventOrActionBasedSurveys.length > 0) {\n this._surveyEventReceiver?.register(eventOrActionBasedSurveys)\n }\n\n // Stamp when these definitions were fetched so the split-storage\n // loader can tell a fresher main-blob write-back from a stale\n // `__surveys` entry (the survey analogue of $feature_flag_evaluated_at).\n this._instance.persistence?.register({ [SURVEYS]: surveys, [SURVEYS_LOADED_AT]: Date.now() })\n const context = { isLoaded: true }\n callback(surveys, context)\n resolvePromise?.({ surveys, context })\n },\n })\n }\n\n /** Helper method to notify all registered callbacks */\n private _notifySurveyCallbacks(context: { isLoaded: boolean; error?: string }): void {\n for (const callback of this._surveyCallbacks) {\n try {\n if (!context.isLoaded) {\n return callback([], context)\n }\n this.getSurveys(callback)\n } catch (error) {\n logger.error('Error in survey callback', error)\n }\n }\n }\n\n getActiveMatchingSurveys(callback: SurveyCallback, forceReload = false) {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return\n }\n return this._surveyManager.getActiveMatchingSurveys(callback, forceReload)\n }\n\n private _getSurveyById(surveyId: string): Survey | null {\n let survey: Survey | null = null\n this.getSurveys((surveys) => {\n survey = surveys.find((x) => x.id === surveyId) ?? null\n })\n return survey\n }\n\n private _checkSurveyEligibility(surveyId: string | Survey): { eligible: boolean; reason?: string } {\n if (isNullish(this._surveyManager)) {\n return { eligible: false, reason: SURVEY_NOT_LOADED }\n }\n const survey = typeof surveyId === 'string' ? this._getSurveyById(surveyId) : surveyId\n if (!survey) {\n return { eligible: false, reason: 'Survey not found' }\n }\n return this._surveyManager.checkSurveyEligibility(survey)\n }\n\n canRenderSurvey(surveyId: string | Survey): SurveyRenderReason {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return { visible: false, disabledReason: SURVEY_NOT_LOADED }\n }\n const eligibility = this._checkSurveyEligibility(surveyId)\n\n return { visible: eligibility.eligible, disabledReason: eligibility.reason }\n }\n\n canRenderSurveyAsync(surveyId: string, forceReload: boolean): Promise<SurveyRenderReason> {\n // Ensure surveys are loaded before checking\n // Using Promise to wrap the callback-based getSurveys method\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return Promise.resolve({\n visible: false,\n disabledReason: SURVEY_NOT_LOADED,\n })\n }\n\n // eslint-disable-next-line compat/compat\n return new Promise<SurveyRenderReason>((resolve) => {\n this.getSurveys((surveys) => {\n const survey = surveys.find((x) => x.id === surveyId) ?? null\n if (!survey) {\n resolve({ visible: false, disabledReason: 'Survey not found' })\n } else {\n const eligibility = this._checkSurveyEligibility(survey)\n resolve({ visible: eligibility.eligible, disabledReason: eligibility.reason })\n }\n }, forceReload)\n })\n }\n\n renderSurvey(surveyId: string | Survey, selector: string, properties?: Properties) {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return\n }\n const survey = typeof surveyId === 'string' ? this._getSurveyById(surveyId) : surveyId\n if (!survey?.id) {\n logger.warn('Survey not found')\n return\n }\n if (!IN_APP_SURVEY_TYPES.includes(survey.type)) {\n logger.warn(`Surveys of type ${survey.type} cannot be rendered in the app`)\n return\n }\n const elem = document?.querySelector(selector)\n if (!elem) {\n logger.warn('Survey element not found')\n return\n }\n if (survey.appearance?.surveyPopupDelaySeconds) {\n logger.info(\n `Rendering survey ${survey.id} with delay of ${survey.appearance.surveyPopupDelaySeconds} seconds`\n )\n setTimeout(() => {\n logger.info(\n `Rendering survey ${survey.id} with delay of ${survey.appearance?.surveyPopupDelaySeconds} seconds`\n )\n this._surveyManager?.renderSurvey(survey, elem, properties)\n logger.info(`Survey ${survey.id} rendered`)\n }, survey.appearance.surveyPopupDelaySeconds * 1000)\n return\n }\n this._surveyManager.renderSurvey(survey, elem, properties)\n }\n\n displaySurvey(surveyId: string, options: DisplaySurveyOptions) {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return\n }\n const survey = this._getSurveyById(surveyId)\n if (!survey) {\n logger.warn('Survey not found')\n return\n }\n let surveyToDisplay = survey\n if (survey.appearance?.surveyPopupDelaySeconds && options.ignoreDelay) {\n surveyToDisplay = {\n ...survey,\n appearance: {\n ...survey.appearance,\n surveyPopupDelaySeconds: 0,\n },\n }\n }\n if (options.displayType !== DisplaySurveyType.Popover && options.initialResponses) {\n logger.warn('initialResponses is only supported for popover surveys. prefill will not be applied.')\n }\n if (options.ignoreConditions === false) {\n const canRender = this.canRenderSurvey(survey)\n if (!canRender.visible) {\n logger.warn('Survey is not eligible to be displayed: ', canRender.disabledReason)\n return\n }\n }\n if (options.displayType === DisplaySurveyType.Inline) {\n this.renderSurvey(surveyToDisplay, options.selector, options.properties)\n return\n }\n this._surveyManager.handlePopoverSurvey(surveyToDisplay, options)\n }\n\n cancelPendingSurvey(surveyId: string): void {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return\n }\n this._surveyManager.cancelSurvey(surveyId)\n }\n\n handlePageUnload(): void {\n this._surveyManager?.handlePageUnload()\n }\n}\n"]} | ||
| {"version":3,"file":"posthog-surveys.js","sourceRoot":"","sources":["../../src/posthog-surveys.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yCAMoB;AAEpB,IAAM,iBAAiB,GAAG,8DAA8D,CAAA;AACxF,IAAM,eAAe,GAAG,gCAAgC,CAAA;AAIxD,iEAMgC;AAEhC,2CAA4D;AAC5D,uEAAmE;AACnE,qDAS6B;AAC7B,sCAAyE;AAEzE;IAuBI,wBAA6B,SAAkB;QAAlB,cAAS,GAAT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YAC9C,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC;gBACrB,4BAAM,CAAC,IAAI,CAAC,0CAA0C,EAAE,SAAS,CAAC,cAAc,CAAC,CAAA;gBACjF,OAAM;YACV,CAAC;QACL,CAAC;QACD,IAAI,OAAO,CAAC,WAAW,KAAK,yCAAiB,CAAC,MAAM,EAAE,CAAC;YACnD,IAAI,CAAC,YAAY,CAAC,eAAe,EAAE,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,UAAU,CAAC,CAAA;YACxE,OAAM;QACV,CAAC;QACD,IAAI,CAAC,cAAc,CAAC,mBAAmB,CAAC,eAAe,EAAE,OAAO,CAAC,CAAA;IACrE,CAAC;IAED,4CAAmB,GAAnB,UAAoB,QAAgB;QAChC,IAAI,IAAA,gBAAS,EAAC,IAAI,CAAC,cAAc,CAAC,EAAE,CAAC;YACjC,4BAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAA;YAClC,OAAM;QACV,CAAC;QACD,IAAI,CAAC,cAAc,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAA;IAC9C,CAAC;IAED,yCAAgB,GAAhB;;QACI,MAAA,IAAI,CAAC,cAAc,0CAAE,gBAAgB,EAAE,CAAA;IAC3C,CAAC;IACL,qBAAC;AAAD,CAAC,AA9dD,IA8dC;AA9dY,wCAAc","sourcesContent":["import {\n LOAD_EXT_NOT_FOUND,\n SURVEYS,\n SURVEYS_CACHE_TTL_MS,\n SURVEYS_LOADED_AT,\n SURVEYS_REFRESH_BACKOFF_MS,\n} from './constants'\n\nconst SURVEY_NOT_LOADED = 'SDK is not enabled or survey functionality is not yet loaded'\nconst SURVEY_DISABLED = 'Disabled. Not loading surveys.'\nimport { SurveyManager } from './extensions/surveys'\nimport type { Extension } from './extensions/types'\nimport { PostHog } from './posthog-core'\nimport {\n DisplaySurveyOptions,\n DisplaySurveyType,\n Survey,\n SurveyCallback,\n SurveyRenderReason,\n} from './posthog-surveys-types'\nimport { Properties, RemoteConfig } from './types'\nimport { assignableWindow, document } from './utils/globals'\nimport { SurveyEventReceiver } from './utils/survey-event-receiver'\nimport {\n doesSurveyActivateByAction,\n doesSurveyActivateByEvent,\n IN_APP_SURVEY_TYPES,\n isSurveyRunning,\n setSurveySeenOnLocalStorage,\n SURVEY_LOGGER as logger,\n SURVEY_IN_PROGRESS_PREFIX,\n SURVEY_SEEN_PREFIX,\n} from './utils/survey-utils'\nimport { isNullish, isUndefined, isArray, isNumber } from '@posthog/core'\n\nexport class PostHogSurveys implements Extension {\n // this is set to undefined until the remote config is loaded\n // then it's set to true if there are surveys to load\n // or false if there are no surveys to load\n // or false if the surveys feature is disabled in the project settings\n private _isSurveysEnabled?: boolean = undefined\n public _surveyEventReceiver: SurveyEventReceiver | null\n private _surveyManager: SurveyManager | null = null\n private _isInitializingSurveys: boolean = false\n private _surveyCallbacks: SurveyCallback[] = []\n // Promise for in-flight survey fetch - allows multiple callers to await the same request\n private _getSurveysInFlightPromise: Promise<{\n surveys: Survey[]\n context: { isLoaded: boolean; error?: string }\n }> | null = null\n // Backs off the stale-cache refresh for one TTL after a failure, so a surveys-API outage can't\n // turn the ~1s display poll into a per-poll request storm.\n private _lastSurveyRefreshFailedAt: number | null = null\n\n private get _config() {\n return this._instance.config\n }\n\n constructor(private readonly _instance: PostHog) {\n // we set this to undefined here because we need the persistence storage for this type\n // but that's not initialized until loadIfEnabled is called.\n this._surveyEventReceiver = null\n }\n\n initialize() {\n this.loadIfEnabled()\n }\n\n onRemoteConfig(response: RemoteConfig) {\n // only load surveys if they are enabled and there are surveys to load\n if (this._config.disable_surveys) {\n return\n }\n\n const surveys = response['surveys']\n if (isNullish(surveys)) {\n return logger.warn('Flags not loaded yet. Not loading surveys.')\n }\n const isArrayResponse = isArray(surveys)\n this._isSurveysEnabled = isArrayResponse ? surveys.length > 0 : surveys\n logger.info(`flags response received, isSurveysEnabled: ${this._isSurveysEnabled}`)\n this.loadIfEnabled()\n }\n\n reset(): void {\n try {\n // Drop in-memory event/action activations too; they aren't in persistence (which\n // reset() has already cleared), so without this an armed-but-unshown survey would\n // survive a logout/account switch that doesn't reload the page.\n this._surveyEventReceiver?.reset()\n localStorage.removeItem('lastSeenSurveyDate')\n const surveyKeys = []\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i)\n if (key?.startsWith(SURVEY_SEEN_PREFIX) || key?.startsWith(SURVEY_IN_PROGRESS_PREFIX)) {\n surveyKeys.push(key)\n }\n }\n\n surveyKeys.forEach((key) => localStorage.removeItem(key))\n } catch {\n // localStorage is not always available (e.g. in cross-origin iframes); resetting survey state is best-effort.\n }\n }\n\n loadIfEnabled() {\n // Initial guard clauses\n if (this._surveyManager) {\n return\n } // Already loaded\n if (this._isInitializingSurveys) {\n logger.info('Already initializing surveys, skipping...')\n return\n }\n if (this._config.disable_surveys) {\n logger.info(SURVEY_DISABLED)\n return\n }\n if (this._config.cookieless_mode && this._instance.consent.isOptedOut()) {\n logger.info('Not loading surveys in cookieless mode without consent.')\n return\n }\n\n const phExtensions = assignableWindow?.__PosthogExtensions__\n if (!phExtensions) {\n logger.error('PostHog Extensions not found.')\n return\n }\n\n // waiting for remote config to load\n // if surveys is forced enable (like external surveys), ignore the remote config and load surveys\n if (isUndefined(this._isSurveysEnabled) && !this._config.advanced_enable_surveys) {\n return\n }\n\n const isSurveysEnabled = this._isSurveysEnabled || this._config.advanced_enable_surveys\n\n this._isInitializingSurveys = true\n\n try {\n const generateSurveys = phExtensions.generateSurveys\n if (generateSurveys) {\n // Surveys code is already loaded\n this._completeSurveyInitialization(generateSurveys, isSurveysEnabled)\n return\n }\n\n // If we reach here, surveys code is not loaded yet\n const loadExternalDependency = phExtensions.loadExternalDependency\n if (!loadExternalDependency) {\n // Cannot load surveys code\n this._handleSurveyLoadError(LOAD_EXT_NOT_FOUND)\n return\n }\n\n // If we reach here, we need to load the dependency\n loadExternalDependency(this._instance, 'surveys', (err) => {\n if (err || !phExtensions.generateSurveys) {\n this._handleSurveyLoadError('Could not load surveys script', err)\n } else {\n // Need to get the function reference again inside the callback\n this._completeSurveyInitialization(phExtensions.generateSurveys, isSurveysEnabled)\n }\n })\n } catch (e) {\n this._handleSurveyLoadError('Error initializing surveys', e)\n throw e\n } finally {\n // Ensure the flag is always reset\n this._isInitializingSurveys = false\n }\n }\n\n /** Helper to finalize survey initialization */\n private _completeSurveyInitialization(\n generateSurveysFn: (instance: PostHog, isSurveysEnabled: boolean) => any,\n isSurveysEnabled: boolean\n ): void {\n this._surveyManager = generateSurveysFn(this._instance, isSurveysEnabled)\n this._surveyEventReceiver = new SurveyEventReceiver(this._instance)\n logger.info('Surveys loaded successfully')\n this._notifySurveyCallbacks({ isLoaded: true })\n }\n\n /** Helper to handle errors during survey loading */\n private _handleSurveyLoadError(message: string, error?: any): void {\n logger.error(message, error)\n this._notifySurveyCallbacks({ isLoaded: false, error: message })\n }\n\n /**\n * Register a callback that runs when surveys are initialized.\n * ### Usage:\n *\n * posthog.onSurveysLoaded((surveys) => {\n * // You can work with all surveys\n * console.log('All available surveys:', surveys)\n *\n * // Or get active matching surveys\n * posthog.getActiveMatchingSurveys((activeMatchingSurveys) => {\n * if (activeMatchingSurveys.length > 0) {\n * posthog.renderSurvey(activeMatchingSurveys[0].id, '#survey-container')\n * }\n * })\n * })\n *\n * @param {Function} callback The callback function will be called when surveys are loaded or updated.\n * It receives the array of all surveys and a context object with error status.\n * @returns {Function} A function that can be called to unsubscribe the listener.\n */\n onSurveysLoaded(callback: SurveyCallback): () => void {\n this._surveyCallbacks.push(callback)\n\n if (this._surveyManager) {\n this._notifySurveyCallbacks({\n isLoaded: true,\n })\n }\n // Return unsubscribe function\n return () => {\n this._surveyCallbacks = this._surveyCallbacks.filter((cb: SurveyCallback) => cb !== callback)\n }\n }\n\n getSurveys(callback: SurveyCallback, forceReload = false) {\n // In case we manage to load the surveys script, but config says not to load surveys\n // then we shouldn't return survey data\n if (this._config.disable_surveys) {\n logger.info(SURVEY_DISABLED)\n return callback([])\n }\n\n const existingSurveys = this._instance.get_property(SURVEYS)\n if (existingSurveys && !forceReload) {\n // Serve the cached definitions synchronously so callers that rely on a synchronous\n // callback (e.g. _getSurveyById) keep working.\n callback(existingSurveys, {\n isLoaded: true,\n })\n // If the cache has aged past its TTL, kick off a background refresh so server-side\n // changes (e.g. a survey switched from popover to API) reach a long-lived tab. The\n // next poll then evaluates the refreshed definitions.\n if (this._shouldBackgroundRefreshSurveys()) {\n this.getSurveys(() => {}, true)\n }\n return\n }\n\n // If a fetch is already in progress and Promise is available, reuse that promise\n // In browsers without Promise (IE11), we skip this optimization and just make concurrent requests\n if (typeof Promise !== 'undefined' && this._getSurveysInFlightPromise) {\n this._getSurveysInFlightPromise.then(({ surveys, context }) => callback(surveys, context))\n return\n }\n\n // Create a new promise for this fetch that other callers can reuse\n // We need to assign the promise before starting the request, because\n // in tests (and potentially in some edge cases) the callback may fire synchronously\n let resolvePromise: (value: { surveys: Survey[]; context: { isLoaded: boolean; error?: string } }) => void\n if (typeof Promise !== 'undefined') {\n this._getSurveysInFlightPromise = new Promise((resolve) => {\n resolvePromise = resolve\n })\n }\n\n this._instance._send_request({\n url: this._instance.requestRouter.endpointFor('api', `/api/surveys/?token=${this._config.token}`),\n method: 'GET',\n timeout: this._config.surveys_request_timeout_ms,\n callback: (response) => {\n this._getSurveysInFlightPromise = null\n\n const statusCode = response.statusCode\n if (statusCode !== 200 || !response.json) {\n const error = `Surveys API could not be loaded, status: ${statusCode}`\n logger.error(error)\n this._lastSurveyRefreshFailedAt = Date.now()\n const context = { isLoaded: false, error }\n callback([], context)\n resolvePromise?.({ surveys: [], context })\n return\n }\n this._lastSurveyRefreshFailedAt = null\n const surveys = response.json.surveys || []\n\n const eventOrActionBasedSurveys = surveys.filter(\n (survey: Survey) =>\n isSurveyRunning(survey) &&\n (doesSurveyActivateByEvent(survey) || doesSurveyActivateByAction(survey))\n )\n\n if (eventOrActionBasedSurveys.length > 0) {\n this._surveyEventReceiver?.register(eventOrActionBasedSurveys)\n }\n\n // Stamp when these definitions were fetched so the split-storage\n // loader can tell a fresher main-blob write-back from a stale\n // `__surveys` entry (the survey analogue of $feature_flag_evaluated_at).\n this._instance.persistence?.register({ [SURVEYS]: surveys, [SURVEYS_LOADED_AT]: Date.now() })\n const context = { isLoaded: true }\n callback(surveys, context)\n resolvePromise?.({ surveys, context })\n },\n })\n }\n\n /**\n * Whether to kick off a background refresh of the cached definitions: the cache is stale, no\n * fetch is already in flight, and we're not backing off after a recent failure.\n */\n private _shouldBackgroundRefreshSurveys(): boolean {\n return this._isSurveyCacheStale() && !this._getSurveysInFlightPromise && !this._isSurveyRefreshBackingOff()\n }\n\n /**\n * Whether the cached `$surveys` definitions have aged past their TTL. Returns false when no\n * timestamp is recorded (e.g. surveys injected directly in tests) so the cache stays valid.\n */\n private _isSurveyCacheStale(): boolean {\n const surveysLoadedAt = this._instance.get_property(SURVEYS_LOADED_AT)\n return isNumber(surveysLoadedAt) && Date.now() - surveysLoadedAt > SURVEYS_CACHE_TTL_MS\n }\n\n private _isSurveyRefreshBackingOff(): boolean {\n return (\n isNumber(this._lastSurveyRefreshFailedAt) &&\n Date.now() - this._lastSurveyRefreshFailedAt < SURVEYS_REFRESH_BACKOFF_MS\n )\n }\n\n /**\n * Marks a survey as seen for the current device, mirroring the local state the SDK records\n * when it shows or sends a survey itself.\n *\n * Use this when you display surveys through your own backend/integration (so the SDK never\n * captures the `survey shown`/`sent`/`dismissed` events) and still want PostHog's display\n * logic to honour the \"already seen\" and wait-period checks on subsequent page loads.\n *\n * Note: surveys configured to repeat (`schedule: 'always'` or event `repeatedActivation`)\n * intentionally bypass the seen check, so marking them as seen will not stop them showing.\n *\n * @param surveyId The ID of the survey to mark as seen.\n * @param options Optional settings. `iteration` is the survey's current iteration number, if any.\n */\n markSurveyAsSeen(surveyId: string, options?: { iteration?: number | null }): void {\n const survey = { id: surveyId, current_iteration: options?.iteration ?? null }\n setSurveySeenOnLocalStorage(survey)\n try {\n localStorage.setItem('lastSeenSurveyDate', new Date().toISOString())\n } catch {\n // localStorage is not always available (e.g. in cross-origin iframes); best-effort only.\n }\n }\n\n /** Helper method to notify all registered callbacks */\n private _notifySurveyCallbacks(context: { isLoaded: boolean; error?: string }): void {\n for (const callback of this._surveyCallbacks) {\n try {\n if (!context.isLoaded) {\n return callback([], context)\n }\n this.getSurveys(callback)\n } catch (error) {\n logger.error('Error in survey callback', error)\n }\n }\n }\n\n getActiveMatchingSurveys(callback: SurveyCallback, forceReload = false) {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return\n }\n return this._surveyManager.getActiveMatchingSurveys(callback, forceReload)\n }\n\n private _getSurveyById(surveyId: string): Survey | null {\n let survey: Survey | null = null\n this.getSurveys((surveys) => {\n survey = surveys.find((x) => x.id === surveyId) ?? null\n })\n return survey\n }\n\n private _checkSurveyEligibility(surveyId: string | Survey): { eligible: boolean; reason?: string } {\n if (isNullish(this._surveyManager)) {\n return { eligible: false, reason: SURVEY_NOT_LOADED }\n }\n const survey = typeof surveyId === 'string' ? this._getSurveyById(surveyId) : surveyId\n if (!survey) {\n return { eligible: false, reason: 'Survey not found' }\n }\n return this._surveyManager.checkSurveyEligibility(survey)\n }\n\n canRenderSurvey(surveyId: string | Survey): SurveyRenderReason {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return { visible: false, disabledReason: SURVEY_NOT_LOADED }\n }\n const eligibility = this._checkSurveyEligibility(surveyId)\n\n return { visible: eligibility.eligible, disabledReason: eligibility.reason }\n }\n\n canRenderSurveyAsync(surveyId: string, forceReload: boolean): Promise<SurveyRenderReason> {\n // Ensure surveys are loaded before checking\n // Using Promise to wrap the callback-based getSurveys method\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return Promise.resolve({\n visible: false,\n disabledReason: SURVEY_NOT_LOADED,\n })\n }\n\n // eslint-disable-next-line compat/compat\n return new Promise<SurveyRenderReason>((resolve) => {\n this.getSurveys((surveys) => {\n const survey = surveys.find((x) => x.id === surveyId) ?? null\n if (!survey) {\n resolve({ visible: false, disabledReason: 'Survey not found' })\n } else {\n const eligibility = this._checkSurveyEligibility(survey)\n resolve({ visible: eligibility.eligible, disabledReason: eligibility.reason })\n }\n }, forceReload)\n })\n }\n\n renderSurvey(surveyId: string | Survey, selector: string, properties?: Properties) {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return\n }\n const survey = typeof surveyId === 'string' ? this._getSurveyById(surveyId) : surveyId\n if (!survey?.id) {\n logger.warn('Survey not found')\n return\n }\n if (!IN_APP_SURVEY_TYPES.includes(survey.type)) {\n logger.warn(`Surveys of type ${survey.type} cannot be rendered in the app`)\n return\n }\n const elem = document?.querySelector(selector)\n if (!elem) {\n logger.warn('Survey element not found')\n return\n }\n if (survey.appearance?.surveyPopupDelaySeconds) {\n logger.info(\n `Rendering survey ${survey.id} with delay of ${survey.appearance.surveyPopupDelaySeconds} seconds`\n )\n setTimeout(() => {\n logger.info(\n `Rendering survey ${survey.id} with delay of ${survey.appearance?.surveyPopupDelaySeconds} seconds`\n )\n this._surveyManager?.renderSurvey(survey, elem, properties)\n logger.info(`Survey ${survey.id} rendered`)\n }, survey.appearance.surveyPopupDelaySeconds * 1000)\n return\n }\n this._surveyManager.renderSurvey(survey, elem, properties)\n }\n\n displaySurvey(surveyId: string, options: DisplaySurveyOptions) {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return\n }\n const survey = this._getSurveyById(surveyId)\n if (!survey) {\n logger.warn('Survey not found')\n return\n }\n let surveyToDisplay = survey\n if (survey.appearance?.surveyPopupDelaySeconds && options.ignoreDelay) {\n surveyToDisplay = {\n ...survey,\n appearance: {\n ...survey.appearance,\n surveyPopupDelaySeconds: 0,\n },\n }\n }\n if (options.displayType !== DisplaySurveyType.Popover && options.initialResponses) {\n logger.warn('initialResponses is only supported for popover surveys. prefill will not be applied.')\n }\n if (options.ignoreConditions === false) {\n const canRender = this.canRenderSurvey(survey)\n if (!canRender.visible) {\n logger.warn('Survey is not eligible to be displayed: ', canRender.disabledReason)\n return\n }\n }\n if (options.displayType === DisplaySurveyType.Inline) {\n this.renderSurvey(surveyToDisplay, options.selector, options.properties)\n return\n }\n this._surveyManager.handlePopoverSurvey(surveyToDisplay, options)\n }\n\n cancelPendingSurvey(surveyId: string): void {\n if (isNullish(this._surveyManager)) {\n logger.warn('init was not called')\n return\n }\n this._surveyManager.cancelSurvey(surveyId)\n }\n\n handlePageUnload(): void {\n this._surveyManager?.handlePageUnload()\n }\n}\n"]} |
+17
-7
@@ -309,3 +309,6 @@ "use strict"; | ||
| var aborter = null; | ||
| var timeoutReason = null; | ||
| // Set the instant our own timeout fires, before the abort propagates. This is the source of | ||
| // truth for "we timed out ourselves" - see the `.catch` below for why we can't rely on the | ||
| // abort reason. | ||
| var timedOut = false; | ||
| if (globals_1.AbortController) { | ||
@@ -316,2 +319,3 @@ var controller_1 = new globals_1.AbortController(); | ||
| timeout: setTimeout(function () { | ||
| timedOut = true; | ||
| // Abort with an explicit reason. Without one, the browser rejects the fetch with a | ||
@@ -323,4 +327,3 @@ // reason-less `DOMException: AbortError: signal is aborted without reason`, which is | ||
| // timeout handling (e.g. feature flag timeout detection) keeps working. | ||
| timeoutReason = timeoutAbortReason(options.timeout); | ||
| controller_1.abort(timeoutReason); | ||
| controller_1.abort(timeoutAbortReason(options.timeout)); | ||
| }, options.timeout), | ||
@@ -358,7 +361,14 @@ }; | ||
| var _a; | ||
| // Identity comparison against the exact reason we created, so a genuine network error | ||
| // that happens to settle in the same turn as the timeout is never misclassified. | ||
| if (error === timeoutReason) { | ||
| // Detect our own timeout via the `timedOut` flag rather than by comparing `error` | ||
| // against the reason we passed to `controller.abort(...)`. Not every browser propagates | ||
| // the abort reason to the fetch rejection - some reject with a generic native | ||
| // `DOMException: AbortError: The operation was aborted.` instead - so a reference (or | ||
| // message) comparison misses those and misclassifies our own timeout as a real error. | ||
| // The flag is set synchronously the instant our timeout fires, and we additionally | ||
| // require `name === 'AbortError'` so a genuine network error that happens to settle | ||
| // just after the timeout is never mislabelled. | ||
| if (timedOut && (error === null || error === void 0 ? void 0 : error.name) === 'AbortError') { | ||
| // Our own request timeout is an expected, intentional abort (the request queue | ||
| // retries), not a genuine failure - so log it at `warn` rather than `error`. | ||
| // retries), not a genuine failure - so log it at `warn` rather than `error`. This | ||
| // also keeps it out of error tracking's console-error capture as an exception. | ||
| logger_1.logger.warn(error); | ||
@@ -365,0 +375,0 @@ } |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"request.js","sourceRoot":"","sources":["../../src/request.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iCAAoC;AACpC,oDAA6B;AAC7B,iCAA0E;AAC1E,uDAAsE;AAEtE,yCAAuC;AACvC,2CAAsG;AACtG,iCAA0C;AAE1C,qDAAoD;AACpD,sCAMsB;AAMtB,yCAAyC;AAC5B,QAAA,gBAAgB,GAAG,CAAC,CAAC,wBAAc,IAAI,CAAC,CAAC,eAAK,CAAA;AAE3D,IAAM,kBAAkB,GAAG,YAAY,CAAA;AACvC,IAAM,iBAAiB,GAAG,kBAAkB,CAAA;AAC5C,IAAM,iBAAiB,GAAG,mCAAmC,CAAA;AAC7D,IAAM,oBAAoB,GAAG,EAAE,GAAG,IAAI,CAAA;AACtC;;;;EAIE;AACF,IAAM,oBAAoB,GAAG,oBAAoB,GAAG,GAAG,CAAA;AACvD,IAAI,uBAAuB,GAAG,KAAK,CAAA;AAEnC,IAAM,cAAc,GAAG,UAAC,GAAW,EAAE,KAAa;IACxC,IAAA,KAAA,OAAyB,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,IAAA,EAAtC,cAAc,QAAA,EAAE,IAAI,QAAkB,CAAA;IACvC,IAAA,KAAA,OAAoB,cAAc,CAAC,KAAK,CAAC,GAAG,CAAC,IAAA,EAA5C,OAAO,QAAA,EAAE,MAAM,QAA6B,CAAA;IAEnD,IAAI,CAAC,MAAM,EAAE,C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AAC,CAAC,2BAAiB;QACnB,OAAO,OAAO,KAAK,WAAW;QAC9B,CAAC,uBAAuB,EAC1B,CAAC;QACC,cAAc,CAAC,OAAO,CAAC;aAClB,IAAI,CAAC,UAAC,cAAc;YACjB,eAAe,CAAC,cAAc,CAAC,CAAA;QACnC,CAAC,CAAC;aACD,KAAK,CAAC,UAAC,KAAK;YACT,IAAI,IAAA,iCAA0B,EAAC,KAAK,CAAC,EAAE,CAAC;gBACpC,uBAAuB,GAAG,IAAI,CAAA;gBAC9B,eAAe,uBACR,OAAO,KACV,WAAW,EAAE,SAAS,EACtB,GAAG,EAAE,eAAe,CAAC,QAAQ,CAAC,GAAG,EAAE,SAAS,CAAC,IAC/C,CAAA;gBACF,OAAM;YACV,CAAC;YAED,IAAI,IAAA,6BAAsB,EAAC,KAAK,CAAC,EAAE,CAAC;gBAChC,uBAAuB,GAAG,IAAI,CAAA;YAClC,CAAC;YAED,0FAA0F;YAC1F,eAAe,CAAC,OAAO,CAAC,CAAA;QAC5B,CAAC,CAAC,CAAA;IACV,CAAC;SAAM,CAAC;QACJ,eAAe,CAAC,OAAO,CAAC,CAAA;IAC5B,CAAC;AACL,CAAC,CAAA;AAxDY,QAAA,OAAO,WAwDnB","sourcesContent":["import { each, find } from './utils'\nimport Config from './config'\nimport { Compression, RequestWithOptions, RequestResponse } from './types'\nimport { formDataToQuery, getQueryParam } from './utils/request-utils'\n\nimport { logger } from './utils/logger'\nimport { AbortController, CompressionStream, fetch, navigator, XMLHttpRequest } from './utils/globals'\nimport { gzipSync, strToU8 } from 'fflate'\n\nimport { _base64Encode } from './utils/encode-utils'\nimport {\n gzipCompress,\n isGzipData,\n isGzipRequest,\n isNativeAsyncGzipError,\n isNativeAsyncGzipReadError,\n} from '@posthog/core'\n\ninterface RequestWithEncodedBody extends RequestWithOptions {\n _encodedBody?: EncodedBody\n}\n\n// eslint-disable-next-line compat/compat\nexport const SUPPORTS_REQUEST = !!XMLHttpRequest || !!fetch\n\nconst CONTENT_TYPE_PLAIN = 'text/plain'\nconst CONTENT_TYPE_JSON = 'application/json'\nconst CONTENT_TYPE_FORM = 'application/x-www-form-urlencoded'\nconst SIXTY_FOUR_KILOBYTES = 64 * 1024\n/*\n fetch will fail if we request keepalive with a body greater than 64kb\n sets the threshold lower than that so that\n any overhead doesn't push over the threshold after checking here\n*/\nconst KEEP_ALIVE_THRESHOLD = SIXTY_FOUR_KILOBYTES * 0.8\nlet nativeAsyncGzipDisabled = false\n\nconst removeURLParam = (url: string, param: string): string => {\n const [urlWithoutHash, hash] = url.split('#')\n const [baseUrl, search] = urlWithoutHash.split('?')\n\n if (!search) {\n return url\n }\n\n const updatedSearch = search\n .split('&')\n .filter((pair) => pair.split('=')[0] !== param)\n .join('&')\n\n return `${baseUrl}${updatedSearch ? `?${updatedSearch}` : ''}${hash ? `#${hash}` : ''}`\n}\n\ntype EncodedBody = {\n contentType: string\n body: string | BlobPart | ArrayBuffer\n estimatedSize: number\n}\n\ntype EncodedRequest = {\n url: string\n encodedBody?: EncodedBody\n}\n\n/**\n * Extends a URL with additional query parameters\n * @param url - The URL to extend\n * @param params - The parameters to add\n * @param replace - When true (default), new params overwrite existing ones with same key. When false, existing params are preserved.\n * @returns The URL with extended parameters\n */\nexport const extendURLParams = (url: string, params: Record<string, any>, replace: boolean = true): string => {\n const [baseUrl, search] = url.split('?')\n const newParams = { ...params }\n\n const updatedSearch =\n search?.split('&').map((pair) => {\n const [key, origValue] = pair.split('=')\n const value = replace ? (newParams[key] ?? origValue) : origValue\n delete newParams[key]\n return `${key}=${value}`\n }) ?? []\n\n const remaining = formDataToQuery(newParams)\n if (remaining) {\n updatedSearch.push(remaining)\n }\n\n return `${baseUrl}?${updatedSearch.join('&')}`\n}\n\nexport const jsonStringify = (data: any, space?: string | number): string => {\n // With plain JSON.stringify, we get an exception when a property is a BigInt. This has caused problems for some users,\n // see https://github.com/PostHog/posthog-js/issues/1440\n // To work around this, we convert BigInts to strings before stringifying the data. This is not ideal, as we lose\n // information that this was originally a number, but given ClickHouse doesn't support BigInts, the customer\n // would not be able to operate on these numerically anyway.\n return JSON.stringify(data, (_, value) => (typeof value === 'bigint' ? value.toString() : value), space)\n}\n\nconst encodeToDataString = (data: string | Record<string, any>): string => {\n return 'data=' + encodeURIComponent(typeof data === 'string' ? data : jsonStringify(data))\n}\n\nconst encodePostData = (options: RequestWithEncodedBody): EncodedBody | undefined => {\n // Use pre-encoded body if available (set by async compression in the request entrypoint)\n if (options._encodedBody) {\n return options._encodedBody\n }\n\n const { data, compression } = options\n if (!data) {\n return\n }\n\n if (compression === Compression.GZipJS) {\n const gzipData = gzipSync(strToU8(jsonStringify(data)), { mtime: 0 })\n return {\n contentType: CONTENT_TYPE_PLAIN,\n body: gzipData.buffer.slice(gzipData.byteOffset, gzipData.byteOffset + gzipData.byteLength) as ArrayBuffer,\n estimatedSize: gzipData.byteLength,\n }\n }\n\n if (compression === Compression.Base64) {\n const b64data = _base64Encode(jsonStringify(data))\n const encodedBody = encodeToDataString(b64data)\n\n return {\n contentType: CONTENT_TYPE_FORM,\n body: encodedBody,\n estimatedSize: new Blob([encodedBody]).size,\n }\n }\n\n const jsonBody = jsonStringify(data)\n return {\n contentType: CONTENT_TYPE_JSON,\n body: jsonBody,\n estimatedSize: new Blob([jsonBody]).size,\n }\n}\n\nconst encodePostDataSafely = (options: RequestWithEncodedBody): EncodedRequest => {\n const fallbackToUncompressed = (): EncodedRequest => {\n return {\n url: removeURLParam(options.url, 'compression'),\n encodedBody: encodePostData({\n ...options,\n compression: undefined,\n _encodedBody: undefined,\n }),\n }\n }\n\n let encodedBody: EncodedBody | undefined\n try {\n encodedBody = encodePostData(options)\n } catch (error) {\n if (isGzipRequest(options.compression, getQueryParam(options.url, 'compression'))) {\n logger.error('Failed to gzip request body, sending uncompressed payload', error)\n return fallbackToUncompressed()\n }\n\n throw error\n }\n\n if (\n !encodedBody ||\n !isGzipRequest(options.compression, getQueryParam(options.url, 'compression')) ||\n isGzipData(encodedBody.body)\n ) {\n return { url: options.url, encodedBody }\n }\n\n nativeAsyncGzipDisabled = true\n return fallbackToUncompressed()\n}\n\nconst encodeRequest = (options: RequestWithEncodedBody): EncodedRequest | undefined => {\n try {\n return encodePostDataSafely(options)\n } catch (error) {\n logger.error(error)\n options.callback?.({ statusCode: 0, error })\n return undefined\n }\n}\n\n/**\n * Pre-encode the request body using async native CompressionStream.\n * This avoids blocking the main thread with fflate's synchronous gzip,\n * which can take 300ms+ on constrained devices.\n *\n * Callers must check preconditions (data exists, gzip compression, CompressionStream available)\n * before calling this function.\n */\nconst preEncodeAsync = async (options: RequestWithEncodedBody): Promise<RequestWithEncodedBody> => {\n const jsonData = jsonStringify(options.data)\n const compressed = await gzipCompress(jsonData, Config.DEBUG, { rethrow: true })\n if (!compressed) {\n return options\n }\n const body = await compressed.arrayBuffer()\n\n return {\n ...options,\n _encodedBody: {\n contentType: CONTENT_TYPE_PLAIN,\n body,\n estimatedSize: body.byteLength,\n },\n }\n}\n\n/**\n * Builds the reason used when aborting a fetch because our own request timeout elapsed.\n * It keeps `name === 'AbortError'` (so callers that detect timeouts by error name keep working)\n * but carries a descriptive message, so it is never a reason-less\n * `signal is aborted without reason` exception.\n */\nconst timeoutAbortReason = (timeout?: number): Error => {\n const reason = new Error(`PostHog request timed out${timeout ? ` after ${timeout}ms` : ''}`)\n reason.name = 'AbortError'\n return reason\n}\n\nconst xhr = (options: RequestWithOptions) => {\n const encodedRequest = encodeRequest(options)\n if (!encodedRequest) {\n return\n }\n\n const req = new XMLHttpRequest!()\n const { url, encodedBody } = encodedRequest\n req.open(options.method || 'GET', url, true)\n const { contentType, body } = encodedBody ?? {}\n\n each(options.headers, function (headerValue, headerName) {\n req.setRequestHeader(headerName, headerValue)\n })\n\n if (contentType) {\n req.setRequestHeader('Content-Type', contentType)\n }\n\n if (options.timeout) {\n req.timeout = options.timeout\n }\n req.onreadystatechange = () => {\n // XMLHttpRequest.DONE == 4, except in safari 4\n if (req.readyState === 4) {\n const response: RequestResponse = {\n statusCode: req.status,\n text: req.responseText,\n }\n if (req.status === 200) {\n try {\n response.json = JSON.parse(req.responseText)\n } catch {\n // logger.error(e)\n }\n }\n\n options.callback?.(response)\n }\n }\n req.send(body)\n}\n\nconst _fetch = (options: RequestWithOptions) => {\n const encodedRequest = encodeRequest(options)\n if (!encodedRequest) {\n return\n }\n\n const { url, encodedBody } = encodedRequest\n const { contentType, body, estimatedSize } = encodedBody ?? {}\n\n // eslint-disable-next-line compat/compat\n const headers = new Headers()\n each(options.headers, function (headerValue, headerName) {\n headers.append(headerName, headerValue)\n })\n\n if (contentType) {\n headers.append('Content-Type', contentType)\n }\n\n let aborter: { signal: any; timeout: ReturnType<typeof setTimeout> } | null = null\n let timeoutReason: Error | null = null\n\n if (AbortController) {\n const controller = new AbortController()\n aborter = {\n signal: controller.signal,\n timeout: setTimeout(() => {\n // Abort with an explicit reason. Without one, the browser rejects the fetch with a\n // reason-less `DOMException: AbortError: signal is aborted without reason`, which is\n // indistinguishable from a host app's own aborted fetches wherever it surfaces (the\n // `{ statusCode: 0, error }` callback, logs, stack traces). An explicit reason makes\n // our own request timeouts identifiable. We keep `name === 'AbortError'` so existing\n // timeout handling (e.g. feature flag timeout detection) keeps working.\n timeoutReason = timeoutAbortReason(options.timeout)\n controller.abort(timeoutReason)\n }, options.timeout),\n }\n }\n\n fetch!(url, {\n method: options?.method || 'GET',\n headers,\n // if body is greater than 64kb, then fetch with keepalive will error\n // see 8:10:5 at https://fetch.spec.whatwg.org/#http-network-or-cache-fetch,\n // but we do want to set keepalive sometimes as it can help with success\n // when e.g. a page is being closed\n // so let's get the best of both worlds and only set keepalive for POST requests\n // where the body is less than 64kb\n // NB this is fetch keepalive and not http keepalive\n keepalive: options.method === 'POST' && (estimatedSize || 0) < KEEP_ALIVE_THRESHOLD,\n body,\n signal: aborter?.signal,\n ...options.fetchOptions,\n })\n .then((response) => {\n return response.text().then((responseText) => {\n const res: RequestResponse = {\n statusCode: response.status,\n text: responseText,\n }\n\n if (response.status === 200) {\n try {\n res.json = JSON.parse(responseText)\n } catch (e) {\n logger.error(e)\n }\n }\n\n options.callback?.(res)\n })\n })\n .catch((error) => {\n // Identity comparison against the exact reason we created, so a genuine network error\n // that happens to settle in the same turn as the timeout is never misclassified.\n if (error === timeoutReason) {\n // Our own request timeout is an expected, intentional abort (the request queue\n // retries), not a genuine failure - so log it at `warn` rather than `error`.\n logger.warn(error)\n } else {\n logger.error(error)\n }\n options.callback?.({ statusCode: 0, error })\n })\n .finally(() => (aborter ? clearTimeout(aborter.timeout) : null))\n\n return\n}\n\nconst _sendBeacon = (options: RequestWithOptions) => {\n // beacon documentation https://w3c.github.io/beacon/\n // beacons format the message and use the type property\n\n try {\n const { url, encodedBody } = encodePostDataSafely(options)\n const { contentType, body } = encodedBody ?? {}\n if (!body) {\n return\n }\n // sendBeacon requires a Blob to set the Content-Type header correctly.\n // Without wrapping, ArrayBuffer bodies are sent with no Content-Type,\n // which can cause issues with proxies/WAFs that require it.\n const sendBeaconBody = body instanceof Blob ? body : new Blob([body], { type: contentType })\n navigator!.sendBeacon!(url, sendBeaconBody)\n } catch {\n // send beacon is a best-effort, fire-and-forget mechanism on page unload,\n // we don't want to throw errors here\n }\n}\n\nconst buildRequestURL = (url: string, compression?: RequestWithOptions['compression']): string => {\n return extendURLParams(url, {\n _: new Date().getTime().toString(),\n ver: Config.JS_SDK_VERSION,\n compression,\n })\n}\n\nconst AVAILABLE_TRANSPORTS: {\n transport: RequestWithOptions['transport']\n method: (options: RequestWithOptions) => void\n}[] = []\n\n// We add the transports in order of preference\nif (fetch) {\n AVAILABLE_TRANSPORTS.push({\n transport: 'fetch',\n method: _fetch,\n })\n}\n\nif (XMLHttpRequest) {\n AVAILABLE_TRANSPORTS.push({\n transport: 'XHR',\n method: xhr,\n })\n}\n\nif (navigator?.sendBeacon) {\n AVAILABLE_TRANSPORTS.push({\n transport: 'sendBeacon',\n method: _sendBeacon,\n })\n}\n\n// This is the entrypoint. It takes care of sanitizing the options and then calls the appropriate request method.\nexport const request = (_options: RequestWithOptions) => {\n // Clone the options so we don't modify the original object\n const options: RequestWithEncodedBody = { ..._options }\n options.timeout = options.timeout || 60000\n\n options.url = buildRequestURL(options.url, options.compression)\n\n const transport = options.transport ?? 'fetch'\n\n const availableTransports = AVAILABLE_TRANSPORTS.filter(\n (t) => !options.disableTransport || !t.transport || !options.disableTransport.includes(t.transport)\n )\n\n const transportMethod =\n find(availableTransports, (t) => t.transport === transport)?.method ?? availableTransports[0].method\n\n if (!transportMethod) {\n throw new Error('No available transport method')\n }\n\n // For non-sendBeacon transports, use async native CompressionStream when available\n // to avoid blocking the main thread with fflate's synchronous gzip (which can take 300ms+).\n // sendBeacon must remain synchronous as it's used during page unload.\n if (\n transport !== 'sendBeacon' &&\n options.data &&\n options.compression === Compression.GZipJS &&\n !!CompressionStream &&\n typeof Promise !== 'undefined' &&\n !nativeAsyncGzipDisabled\n ) {\n preEncodeAsync(options)\n .then((encodedOptions) => {\n transportMethod(encodedOptions)\n })\n .catch((error) => {\n if (isNativeAsyncGzipReadError(error)) {\n nativeAsyncGzipDisabled = true\n transportMethod({\n ...options,\n compression: undefined,\n url: buildRequestURL(_options.url, undefined),\n })\n return\n }\n\n if (isNativeAsyncGzipError(error)) {\n nativeAsyncGzipDisabled = true\n }\n\n // If async compression fails for another reason, fall back to the synchronous fflate path\n transportMethod(options)\n })\n } else {\n transportMethod(options)\n }\n}\n"]} | ||
| {"version":3,"file":"request.js","sourceRoot":"","sources":["../../src/request.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iCAAoC;AACpC,oDAA6B;AAC7B,iCAA0E;AAC1E,uDAAsE;AAEtE,yCAAuC;AACvC,2CAAsG;AACtG,iCAA0C;AAE1C,qDAAoD;AACpD,sCAMsB;AAMtB,yCAAyC;AAC5B,QAAA,gBAAgB,GAAG,CAAC,CAAC,wBAAc,IAAI,CAAC,CA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CAAC,IAC/C,CAAA;gBACF,OAAM;YACV,CAAC;YAED,IAAI,IAAA,6BAAsB,EAAC,KAAK,CAAC,EAAE,CAAC;gBAChC,uBAAuB,GAAG,IAAI,CAAA;YAClC,CAAC;YAED,0FAA0F;YAC1F,eAAe,CAAC,OAAO,CAAC,CAAA;QAC5B,CAAC,CAAC,CAAA;IACV,CAAC;SAAM,CAAC;QACJ,eAAe,CAAC,OAAO,CAAC,CAAA;IAC5B,CAAC;AACL,CAAC,CAAA;AAxDY,QAAA,OAAO,WAwDnB","sourcesContent":["import { each, find } from './utils'\nimport Config from './config'\nimport { Compression, RequestWithOptions, RequestResponse } from './types'\nimport { formDataToQuery, getQueryParam } from './utils/request-utils'\n\nimport { logger } from './utils/logger'\nimport { AbortController, CompressionStream, fetch, navigator, XMLHttpRequest } from './utils/globals'\nimport { gzipSync, strToU8 } from 'fflate'\n\nimport { _base64Encode } from './utils/encode-utils'\nimport {\n gzipCompress,\n isGzipData,\n isGzipRequest,\n isNativeAsyncGzipError,\n isNativeAsyncGzipReadError,\n} from '@posthog/core'\n\ninterface RequestWithEncodedBody extends RequestWithOptions {\n _encodedBody?: EncodedBody\n}\n\n// eslint-disable-next-line compat/compat\nexport const SUPPORTS_REQUEST = !!XMLHttpRequest || !!fetch\n\nconst CONTENT_TYPE_PLAIN = 'text/plain'\nconst CONTENT_TYPE_JSON = 'application/json'\nconst CONTENT_TYPE_FORM = 'application/x-www-form-urlencoded'\nconst SIXTY_FOUR_KILOBYTES = 64 * 1024\n/*\n fetch will fail if we request keepalive with a body greater than 64kb\n sets the threshold lower than that so that\n any overhead doesn't push over the threshold after checking here\n*/\nconst KEEP_ALIVE_THRESHOLD = SIXTY_FOUR_KILOBYTES * 0.8\nlet nativeAsyncGzipDisabled = false\n\nconst removeURLParam = (url: string, param: string): string => {\n const [urlWithoutHash, hash] = url.split('#')\n const [baseUrl, search] = urlWithoutHash.split('?')\n\n if (!search) {\n return url\n }\n\n const updatedSearch = search\n .split('&')\n .filter((pair) => pair.split('=')[0] !== param)\n .join('&')\n\n return `${baseUrl}${updatedSearch ? `?${updatedSearch}` : ''}${hash ? `#${hash}` : ''}`\n}\n\ntype EncodedBody = {\n contentType: string\n body: string | BlobPart | ArrayBuffer\n estimatedSize: number\n}\n\ntype EncodedRequest = {\n url: string\n encodedBody?: EncodedBody\n}\n\n/**\n * Extends a URL with additional query parameters\n * @param url - The URL to extend\n * @param params - The parameters to add\n * @param replace - When true (default), new params overwrite existing ones with same key. When false, existing params are preserved.\n * @returns The URL with extended parameters\n */\nexport const extendURLParams = (url: string, params: Record<string, any>, replace: boolean = true): string => {\n const [baseUrl, search] = url.split('?')\n const newParams = { ...params }\n\n const updatedSearch =\n search?.split('&').map((pair) => {\n const [key, origValue] = pair.split('=')\n const value = replace ? (newParams[key] ?? origValue) : origValue\n delete newParams[key]\n return `${key}=${value}`\n }) ?? []\n\n const remaining = formDataToQuery(newParams)\n if (remaining) {\n updatedSearch.push(remaining)\n }\n\n return `${baseUrl}?${updatedSearch.join('&')}`\n}\n\nexport const jsonStringify = (data: any, space?: string | number): string => {\n // With plain JSON.stringify, we get an exception when a property is a BigInt. This has caused problems for some users,\n // see https://github.com/PostHog/posthog-js/issues/1440\n // To work around this, we convert BigInts to strings before stringifying the data. This is not ideal, as we lose\n // information that this was originally a number, but given ClickHouse doesn't support BigInts, the customer\n // would not be able to operate on these numerically anyway.\n return JSON.stringify(data, (_, value) => (typeof value === 'bigint' ? value.toString() : value), space)\n}\n\nconst encodeToDataString = (data: string | Record<string, any>): string => {\n return 'data=' + encodeURIComponent(typeof data === 'string' ? data : jsonStringify(data))\n}\n\nconst encodePostData = (options: RequestWithEncodedBody): EncodedBody | undefined => {\n // Use pre-encoded body if available (set by async compression in the request entrypoint)\n if (options._encodedBody) {\n return options._encodedBody\n }\n\n const { data, compression } = options\n if (!data) {\n return\n }\n\n if (compression === Compression.GZipJS) {\n const gzipData = gzipSync(strToU8(jsonStringify(data)), { mtime: 0 })\n return {\n contentType: CONTENT_TYPE_PLAIN,\n body: gzipData.buffer.slice(gzipData.byteOffset, gzipData.byteOffset + gzipData.byteLength) as ArrayBuffer,\n estimatedSize: gzipData.byteLength,\n }\n }\n\n if (compression === Compression.Base64) {\n const b64data = _base64Encode(jsonStringify(data))\n const encodedBody = encodeToDataString(b64data)\n\n return {\n contentType: CONTENT_TYPE_FORM,\n body: encodedBody,\n estimatedSize: new Blob([encodedBody]).size,\n }\n }\n\n const jsonBody = jsonStringify(data)\n return {\n contentType: CONTENT_TYPE_JSON,\n body: jsonBody,\n estimatedSize: new Blob([jsonBody]).size,\n }\n}\n\nconst encodePostDataSafely = (options: RequestWithEncodedBody): EncodedRequest => {\n const fallbackToUncompressed = (): EncodedRequest => {\n return {\n url: removeURLParam(options.url, 'compression'),\n encodedBody: encodePostData({\n ...options,\n compression: undefined,\n _encodedBody: undefined,\n }),\n }\n }\n\n let encodedBody: EncodedBody | undefined\n try {\n encodedBody = encodePostData(options)\n } catch (error) {\n if (isGzipRequest(options.compression, getQueryParam(options.url, 'compression'))) {\n logger.error('Failed to gzip request body, sending uncompressed payload', error)\n return fallbackToUncompressed()\n }\n\n throw error\n }\n\n if (\n !encodedBody ||\n !isGzipRequest(options.compression, getQueryParam(options.url, 'compression')) ||\n isGzipData(encodedBody.body)\n ) {\n return { url: options.url, encodedBody }\n }\n\n nativeAsyncGzipDisabled = true\n return fallbackToUncompressed()\n}\n\nconst encodeRequest = (options: RequestWithEncodedBody): EncodedRequest | undefined => {\n try {\n return encodePostDataSafely(options)\n } catch (error) {\n logger.error(error)\n options.callback?.({ statusCode: 0, error })\n return undefined\n }\n}\n\n/**\n * Pre-encode the request body using async native CompressionStream.\n * This avoids blocking the main thread with fflate's synchronous gzip,\n * which can take 300ms+ on constrained devices.\n *\n * Callers must check preconditions (data exists, gzip compression, CompressionStream available)\n * before calling this function.\n */\nconst preEncodeAsync = async (options: RequestWithEncodedBody): Promise<RequestWithEncodedBody> => {\n const jsonData = jsonStringify(options.data)\n const compressed = await gzipCompress(jsonData, Config.DEBUG, { rethrow: true })\n if (!compressed) {\n return options\n }\n const body = await compressed.arrayBuffer()\n\n return {\n ...options,\n _encodedBody: {\n contentType: CONTENT_TYPE_PLAIN,\n body,\n estimatedSize: body.byteLength,\n },\n }\n}\n\n/**\n * Builds the reason used when aborting a fetch because our own request timeout elapsed.\n * It keeps `name === 'AbortError'` (so callers that detect timeouts by error name keep working)\n * but carries a descriptive message, so it is never a reason-less\n * `signal is aborted without reason` exception.\n */\nconst timeoutAbortReason = (timeout?: number): Error => {\n const reason = new Error(`PostHog request timed out${timeout ? ` after ${timeout}ms` : ''}`)\n reason.name = 'AbortError'\n return reason\n}\n\nconst xhr = (options: RequestWithOptions) => {\n const encodedRequest = encodeRequest(options)\n if (!encodedRequest) {\n return\n }\n\n const req = new XMLHttpRequest!()\n const { url, encodedBody } = encodedRequest\n req.open(options.method || 'GET', url, true)\n const { contentType, body } = encodedBody ?? {}\n\n each(options.headers, function (headerValue, headerName) {\n req.setRequestHeader(headerName, headerValue)\n })\n\n if (contentType) {\n req.setRequestHeader('Content-Type', contentType)\n }\n\n if (options.timeout) {\n req.timeout = options.timeout\n }\n req.onreadystatechange = () => {\n // XMLHttpRequest.DONE == 4, except in safari 4\n if (req.readyState === 4) {\n const response: RequestResponse = {\n statusCode: req.status,\n text: req.responseText,\n }\n if (req.status === 200) {\n try {\n response.json = JSON.parse(req.responseText)\n } catch {\n // logger.error(e)\n }\n }\n\n options.callback?.(response)\n }\n }\n req.send(body)\n}\n\nconst _fetch = (options: RequestWithOptions) => {\n const encodedRequest = encodeRequest(options)\n if (!encodedRequest) {\n return\n }\n\n const { url, encodedBody } = encodedRequest\n const { contentType, body, estimatedSize } = encodedBody ?? {}\n\n // eslint-disable-next-line compat/compat\n const headers = new Headers()\n each(options.headers, function (headerValue, headerName) {\n headers.append(headerName, headerValue)\n })\n\n if (contentType) {\n headers.append('Content-Type', contentType)\n }\n\n let aborter: { signal: any; timeout: ReturnType<typeof setTimeout> } | null = null\n // Set the instant our own timeout fires, before the abort propagates. This is the source of\n // truth for \"we timed out ourselves\" - see the `.catch` below for why we can't rely on the\n // abort reason.\n let timedOut = false\n\n if (AbortController) {\n const controller = new AbortController()\n aborter = {\n signal: controller.signal,\n timeout: setTimeout(() => {\n timedOut = true\n // Abort with an explicit reason. Without one, the browser rejects the fetch with a\n // reason-less `DOMException: AbortError: signal is aborted without reason`, which is\n // indistinguishable from a host app's own aborted fetches wherever it surfaces (the\n // `{ statusCode: 0, error }` callback, logs, stack traces). An explicit reason makes\n // our own request timeouts identifiable. We keep `name === 'AbortError'` so existing\n // timeout handling (e.g. feature flag timeout detection) keeps working.\n controller.abort(timeoutAbortReason(options.timeout))\n }, options.timeout),\n }\n }\n\n fetch!(url, {\n method: options?.method || 'GET',\n headers,\n // if body is greater than 64kb, then fetch with keepalive will error\n // see 8:10:5 at https://fetch.spec.whatwg.org/#http-network-or-cache-fetch,\n // but we do want to set keepalive sometimes as it can help with success\n // when e.g. a page is being closed\n // so let's get the best of both worlds and only set keepalive for POST requests\n // where the body is less than 64kb\n // NB this is fetch keepalive and not http keepalive\n keepalive: options.method === 'POST' && (estimatedSize || 0) < KEEP_ALIVE_THRESHOLD,\n body,\n signal: aborter?.signal,\n ...options.fetchOptions,\n })\n .then((response) => {\n return response.text().then((responseText) => {\n const res: RequestResponse = {\n statusCode: response.status,\n text: responseText,\n }\n\n if (response.status === 200) {\n try {\n res.json = JSON.parse(responseText)\n } catch (e) {\n logger.error(e)\n }\n }\n\n options.callback?.(res)\n })\n })\n .catch((error) => {\n // Detect our own timeout via the `timedOut` flag rather than by comparing `error`\n // against the reason we passed to `controller.abort(...)`. Not every browser propagates\n // the abort reason to the fetch rejection - some reject with a generic native\n // `DOMException: AbortError: The operation was aborted.` instead - so a reference (or\n // message) comparison misses those and misclassifies our own timeout as a real error.\n // The flag is set synchronously the instant our timeout fires, and we additionally\n // require `name === 'AbortError'` so a genuine network error that happens to settle\n // just after the timeout is never mislabelled.\n if (timedOut && (error as Error)?.name === 'AbortError') {\n // Our own request timeout is an expected, intentional abort (the request queue\n // retries), not a genuine failure - so log it at `warn` rather than `error`. This\n // also keeps it out of error tracking's console-error capture as an exception.\n logger.warn(error)\n } else {\n logger.error(error)\n }\n options.callback?.({ statusCode: 0, error })\n })\n .finally(() => (aborter ? clearTimeout(aborter.timeout) : null))\n\n return\n}\n\nconst _sendBeacon = (options: RequestWithOptions) => {\n // beacon documentation https://w3c.github.io/beacon/\n // beacons format the message and use the type property\n\n try {\n const { url, encodedBody } = encodePostDataSafely(options)\n const { contentType, body } = encodedBody ?? {}\n if (!body) {\n return\n }\n // sendBeacon requires a Blob to set the Content-Type header correctly.\n // Without wrapping, ArrayBuffer bodies are sent with no Content-Type,\n // which can cause issues with proxies/WAFs that require it.\n const sendBeaconBody = body instanceof Blob ? body : new Blob([body], { type: contentType })\n navigator!.sendBeacon!(url, sendBeaconBody)\n } catch {\n // send beacon is a best-effort, fire-and-forget mechanism on page unload,\n // we don't want to throw errors here\n }\n}\n\nconst buildRequestURL = (url: string, compression?: RequestWithOptions['compression']): string => {\n return extendURLParams(url, {\n _: new Date().getTime().toString(),\n ver: Config.JS_SDK_VERSION,\n compression,\n })\n}\n\nconst AVAILABLE_TRANSPORTS: {\n transport: RequestWithOptions['transport']\n method: (options: RequestWithOptions) => void\n}[] = []\n\n// We add the transports in order of preference\nif (fetch) {\n AVAILABLE_TRANSPORTS.push({\n transport: 'fetch',\n method: _fetch,\n })\n}\n\nif (XMLHttpRequest) {\n AVAILABLE_TRANSPORTS.push({\n transport: 'XHR',\n method: xhr,\n })\n}\n\nif (navigator?.sendBeacon) {\n AVAILABLE_TRANSPORTS.push({\n transport: 'sendBeacon',\n method: _sendBeacon,\n })\n}\n\n// This is the entrypoint. It takes care of sanitizing the options and then calls the appropriate request method.\nexport const request = (_options: RequestWithOptions) => {\n // Clone the options so we don't modify the original object\n const options: RequestWithEncodedBody = { ..._options }\n options.timeout = options.timeout || 60000\n\n options.url = buildRequestURL(options.url, options.compression)\n\n const transport = options.transport ?? 'fetch'\n\n const availableTransports = AVAILABLE_TRANSPORTS.filter(\n (t) => !options.disableTransport || !t.transport || !options.disableTransport.includes(t.transport)\n )\n\n const transportMethod =\n find(availableTransports, (t) => t.transport === transport)?.method ?? availableTransports[0].method\n\n if (!transportMethod) {\n throw new Error('No available transport method')\n }\n\n // For non-sendBeacon transports, use async native CompressionStream when available\n // to avoid blocking the main thread with fflate's synchronous gzip (which can take 300ms+).\n // sendBeacon must remain synchronous as it's used during page unload.\n if (\n transport !== 'sendBeacon' &&\n options.data &&\n options.compression === Compression.GZipJS &&\n !!CompressionStream &&\n typeof Promise !== 'undefined' &&\n !nativeAsyncGzipDisabled\n ) {\n preEncodeAsync(options)\n .then((encodedOptions) => {\n transportMethod(encodedOptions)\n })\n .catch((error) => {\n if (isNativeAsyncGzipReadError(error)) {\n nativeAsyncGzipDisabled = true\n transportMethod({\n ...options,\n compression: undefined,\n url: buildRequestURL(_options.url, undefined),\n })\n return\n }\n\n if (isNativeAsyncGzipError(error)) {\n nativeAsyncGzipDisabled = true\n }\n\n // If async compression fails for another reason, fall back to the synchronous fflate path\n transportMethod(options)\n })\n } else {\n transportMethod(options)\n }\n}\n"]} |
+5
-5
| { | ||
| "name": "posthog-js", | ||
| "version": "1.396.5", | ||
| "version": "1.396.6", | ||
| "bugs": { | ||
@@ -36,4 +36,4 @@ "url": "https://github.com/PostHog/posthog-js/issues" | ||
| "web-vitals": "^5.3.0", | ||
| "@posthog/types": "^1.392.0", | ||
| "@posthog/core": "^1.39.5" | ||
| "@posthog/core": "^1.39.6", | ||
| "@posthog/types": "^1.392.1" | ||
| }, | ||
@@ -102,7 +102,7 @@ "devDependencies": { | ||
| "yargs": "^17.7.2", | ||
| "@posthog-tooling/rollup-utils": "1.1.1", | ||
| "@posthog/rrweb": "0.0.75", | ||
| "@posthog/rrweb-plugin-console-record": "0.0.75", | ||
| "@posthog/rrweb-record": "0.0.75", | ||
| "@posthog/rrweb-types": "0.0.62" | ||
| "@posthog/rrweb-types": "0.0.62", | ||
| "@posthog-tooling/rollup-utils": "1.1.1" | ||
| }, | ||
@@ -109,0 +109,0 @@ "browserslist": [ |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Telemetry
Supply chain riskThis package contains telemetry which tracks how it is used.
Found 3 instances
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Found 2 instances
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Telemetry
Supply chain riskThis package contains telemetry which tracks how it is used.
Found 7 instances
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Found 3 instances
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
38795928
0.42%116100
0.66%3
-57.14%59
-1.67%Updated
Updated