@payment-kit-js/vanilla 0.5.13 → 0.5.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/{airwallex-apple-pay-adapter-BFsoDoSf.mjs → airwallex-apple-pay-adapter-Bs8AdQKY.mjs} +8 -2
  2. package/dist/airwallex-apple-pay-adapter-Bs8AdQKY.mjs.map +1 -0
  3. package/dist/{airwallex-apple-pay-adapter-BCYt7Jzc.d.mts → airwallex-apple-pay-adapter-D8enI9Vq.d.mts} +3 -1
  4. package/dist/airwallex-apple-pay-adapter-D8enI9Vq.d.mts.map +1 -0
  5. package/dist/{airwallex-google-pay-adapter-B5xmg7b8.mjs → airwallex-google-pay-adapter-C8JTp01q.mjs} +1 -1
  6. package/dist/{airwallex-google-pay-adapter-B5xmg7b8.mjs.map → airwallex-google-pay-adapter-C8JTp01q.mjs.map} +1 -1
  7. package/dist/{airwallex-google-pay-adapter-DvEB6t5i.d.mts → airwallex-google-pay-adapter-adaDktQM.d.mts} +1 -1
  8. package/dist/{airwallex-google-pay-adapter-DvEB6t5i.d.mts.map → airwallex-google-pay-adapter-adaDktQM.d.mts.map} +1 -1
  9. package/dist/bnpl-shared-B-en2sPr.d.mts +64 -0
  10. package/dist/bnpl-shared-B-en2sPr.d.mts.map +1 -0
  11. package/dist/bnpl-shared-CEAXTL3Q.mjs +107 -0
  12. package/dist/bnpl-shared-CEAXTL3Q.mjs.map +1 -0
  13. package/dist/cdn/paymentkit.js +362 -20
  14. package/dist/cdn/paymentkit.js.map +4 -4
  15. package/dist/cdn/paymentkit.min.js +6 -6
  16. package/dist/cdn/paymentkit.min.js.map +4 -4
  17. package/dist/{connect-card-Cxy51W6t.d.mts → connect-card-Cra_F1cC.d.mts} +1 -1
  18. package/dist/{connect-card-Cxy51W6t.d.mts.map → connect-card-Cra_F1cC.d.mts.map} +1 -1
  19. package/dist/{connect-card-CMZkeppE.mjs → connect-card-D3Je4V7p.mjs} +1 -1
  20. package/dist/{connect-card-CMZkeppE.mjs.map → connect-card-D3Je4V7p.mjs.map} +1 -1
  21. package/dist/{connect-tunnel-x-lv6Wtdme.d.mts → connect-tunnel-x-Wh-JG1O5.d.mts} +1 -1
  22. package/dist/{connect-tunnel-x-lv6Wtdme.d.mts.map → connect-tunnel-x-Wh-JG1O5.d.mts.map} +1 -1
  23. package/dist/index.d.mts +3 -3
  24. package/dist/index.mjs +1 -1
  25. package/dist/index.mjs.map +1 -1
  26. package/dist/{next-action-handlers-CTx8tRt0.mjs → next-action-handlers-BZs04hYb.mjs} +1 -1
  27. package/dist/{next-action-handlers-CTx8tRt0.mjs.map → next-action-handlers-BZs04hYb.mjs.map} +1 -1
  28. package/dist/payment-methods/affirm.d.mts +13 -0
  29. package/dist/payment-methods/affirm.d.mts.map +1 -0
  30. package/dist/payment-methods/affirm.mjs +14 -0
  31. package/dist/payment-methods/affirm.mjs.map +1 -0
  32. package/dist/payment-methods/afterpay.d.mts +13 -0
  33. package/dist/payment-methods/afterpay.d.mts.map +1 -0
  34. package/dist/payment-methods/afterpay.mjs +14 -0
  35. package/dist/payment-methods/afterpay.mjs.map +1 -0
  36. package/dist/payment-methods/airwallex-apple-pay-adapter.d.mts +1 -1
  37. package/dist/payment-methods/airwallex-apple-pay-adapter.mjs +1 -1
  38. package/dist/payment-methods/airwallex-google-pay-adapter.d.mts +1 -1
  39. package/dist/payment-methods/airwallex-google-pay-adapter.mjs +1 -1
  40. package/dist/payment-methods/apple-pay.d.mts +38 -7
  41. package/dist/payment-methods/apple-pay.d.mts.map +1 -1
  42. package/dist/payment-methods/apple-pay.mjs +159 -14
  43. package/dist/payment-methods/apple-pay.mjs.map +1 -1
  44. package/dist/payment-methods/bnpl-shared.d.mts +5 -0
  45. package/dist/payment-methods/bnpl-shared.mjs +4 -0
  46. package/dist/payment-methods/card.d.mts +3 -3
  47. package/dist/payment-methods/card.mjs +3 -3
  48. package/dist/payment-methods/google-pay.d.mts +5 -5
  49. package/dist/payment-methods/google-pay.mjs +3 -3
  50. package/dist/payment-methods/klarna.d.mts +13 -0
  51. package/dist/payment-methods/klarna.d.mts.map +1 -0
  52. package/dist/payment-methods/klarna.mjs +14 -0
  53. package/dist/payment-methods/klarna.mjs.map +1 -0
  54. package/dist/payment-methods/next-action-handlers.mjs +1 -1
  55. package/dist/payment-methods/paypal.d.mts +9 -3
  56. package/dist/payment-methods/paypal.d.mts.map +1 -1
  57. package/dist/payment-methods/paypal.mjs.map +1 -1
  58. package/dist/payment-methods/stripe-apple-pay-adapter.d.mts +1 -1
  59. package/dist/payment-methods/stripe-apple-pay-adapter.mjs +1 -1
  60. package/dist/payment-methods/stripe-google-pay-adapter.d.mts +1 -1
  61. package/dist/payment-methods/stripe-google-pay-adapter.mjs +1 -1
  62. package/dist/payment-methods/vgs-collect-loader.mjs +1 -1
  63. package/dist/penpal/connect-card.d.mts +1 -1
  64. package/dist/penpal/connect-card.mjs +1 -1
  65. package/dist/penpal/connect-tunnel-x.d.mts +1 -1
  66. package/dist/{stripe-apple-pay-adapter-Cd9LVNnp.mjs → stripe-apple-pay-adapter-BLRjqgDf.mjs} +1 -1
  67. package/dist/{stripe-apple-pay-adapter-Cd9LVNnp.mjs.map → stripe-apple-pay-adapter-BLRjqgDf.mjs.map} +1 -1
  68. package/dist/{stripe-apple-pay-adapter-DhpGclW9.d.mts → stripe-apple-pay-adapter-DcuGlQqQ.d.mts} +1 -1
  69. package/dist/{stripe-apple-pay-adapter-DhpGclW9.d.mts.map → stripe-apple-pay-adapter-DcuGlQqQ.d.mts.map} +1 -1
  70. package/dist/{stripe-google-pay-adapter-Bdox4xBq.d.mts → stripe-google-pay-adapter-BlQ2jVpE.d.mts} +1 -1
  71. package/dist/{stripe-google-pay-adapter-Bdox4xBq.d.mts.map → stripe-google-pay-adapter-BlQ2jVpE.d.mts.map} +1 -1
  72. package/dist/{stripe-google-pay-adapter-3cx0KNjK.mjs → stripe-google-pay-adapter-CIkgjhw8.mjs} +1 -1
  73. package/dist/{stripe-google-pay-adapter-3cx0KNjK.mjs.map → stripe-google-pay-adapter-CIkgjhw8.mjs.map} +1 -1
  74. package/dist/{types-D88-nhWu.d.mts → types-CQ8xbgoh.d.mts} +3 -3
  75. package/dist/{types-D88-nhWu.d.mts.map → types-CQ8xbgoh.d.mts.map} +1 -1
  76. package/dist/{vgs-collect-loader-BZj36d8r.mjs → vgs-collect-loader-l5_Pnmhz.mjs} +1 -1
  77. package/dist/{vgs-collect-loader-BZj36d8r.mjs.map → vgs-collect-loader-l5_Pnmhz.mjs.map} +1 -1
  78. package/package.json +6 -2
  79. package/dist/airwallex-apple-pay-adapter-BCYt7Jzc.d.mts.map +0 -1
  80. package/dist/airwallex-apple-pay-adapter-BFsoDoSf.mjs.map +0 -1
@@ -1,14 +1,14 @@
1
1
  /**
2
- * PaymentKit.js v0.5.13
2
+ * PaymentKit.js v0.5.15
3
3
  * https://paymentkit.com
4
4
  *
5
5
  * @license MIT
6
6
  */
7
7
 
8
- "use strict";var PaymentKit=(()=>{var gr=Object.defineProperty;var wl=Object.getOwnPropertyDescriptor;var kl=Object.getOwnPropertyNames;var Pl=Object.prototype.hasOwnProperty;var bs=r=>{throw TypeError(r)};var xl=(r,e,t)=>e in r?gr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var El=(r,e)=>{for(var t in e)gr(r,t,{get:e[t],enumerable:!0})},Sl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of kl(e))!Pl.call(r,i)&&i!==t&&gr(r,i,{get:()=>e[i],enumerable:!(n=wl(e,i))||n.enumerable});return r};var Cl=r=>Sl(gr({},"__esModule",{value:!0}),r);var R=(r,e,t)=>xl(r,typeof e!="symbol"?e+"":e,t),ws=(r,e,t)=>e.has(r)||bs("Cannot "+t);var T=(r,e,t)=>(ws(r,e,"read from private field"),t?t.call(r):e.get(r)),Z=(r,e,t)=>e.has(r)?bs("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),_e=(r,e,t,n)=>(ws(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t);var Op={};El(Op,{PaymentMethods:()=>Fp,default:()=>Tp});var ks="0.5.13";var Tt=class{constructor(){R(this,"events",[]);R(this,"distinctId",null)}identify(e){this.distinctId=e}capture(e,t){this.events.push({event:e,distinct_id:this.distinctId,properties:t,timestamp:Date.now()})}isInitialized(){return!0}getEvents(){return[...this.events]}getEventsByName(e){return this.events.filter(t=>t.event===e)}clear(){this.events=[]}};var y=typeof window<"u"?window:void 0,X=typeof globalThis<"u"?globalThis:y;typeof self>"u"&&(X.self=X),typeof File>"u"&&(X.File=function(){});var _o=Array.prototype,Ps=_o.forEach,xs=_o.indexOf,le=X?.navigator,P=X?.document,W=X?.location,An=X?.fetch,In=X!=null&&X.XMLHttpRequest&&"withCredentials"in new X.XMLHttpRequest?X.XMLHttpRequest:void 0,Es=X?.AbortController,se=le?.userAgent,A=y??{},Ie={DEBUG:!1,LIB_VERSION:"1.341.0"};function Ss(r,e,t,n,i,s,o){try{var a=r[s](o),l=a.value}catch(u){return void t(u)}a.done?e(l):Promise.resolve(l).then(n,i)}function ft(r){return function(){var e=this,t=arguments;return new Promise(function(n,i){var s=r.apply(e,t);function o(l){Ss(s,n,i,o,a,"next",l)}function a(l){Ss(s,n,i,o,a,"throw",l)}o(void 0)})}}function S(){return S=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)({}).hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r},S.apply(null,arguments)}function bo(r,e){if(r==null)return{};var t={};for(var n in r)if({}.hasOwnProperty.call(r,n)){if(e.indexOf(n)!==-1)continue;t[n]=r[n]}return t}var Il=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Cs=function(r,e){if(e===void 0&&(e=[]),!r)return!1;var t=r.toLowerCase();return Il.concat(e).some(n=>{var i=n.toLowerCase();return t.indexOf(i)!==-1})},Ml=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"];function F(r,e){return r.indexOf(e)!==-1}var Hr=function(r){return r.trim()},Mn=function(r){return r.replace(/^\$/,"")},Rl=Array.isArray,wo=Object.prototype,ko=wo.hasOwnProperty,Kr=wo.toString,$=Rl||function(r){return Kr.call(r)==="[object Array]"},ze=r=>typeof r=="function",H=r=>r===Object(r)&&!$(r),gt=r=>{if(H(r)){for(var e in r)if(ko.call(r,e))return!1;return!0}return!1},x=r=>r===void 0,K=r=>Kr.call(r)=="[object String]",Rn=r=>K(r)&&r.trim().length===0,me=r=>r===null,O=r=>x(r)||me(r),$e=r=>Kr.call(r)=="[object Number]"&&r==r,dt=r=>$e(r)&&r>0,Oe=r=>Kr.call(r)==="[object Boolean]",Tl=r=>r instanceof FormData,Fl=r=>F(Ml,r);function Tn(r){return r===null||typeof r!="object"}function Pr(r,e){return Object.prototype.toString.call(r)==="[object "+e+"]"}function Po(r){return!x(Event)&&function(e,t){try{return e instanceof t}catch{return!1}}(r,Event)}var Ol=[!0,"true",1,"1","yes"],pn=r=>F(Ol,r),$l=[!1,"false",0,"0","no"];function we(r,e,t,n,i){return e>t&&(n.warn("min cannot be greater than max."),e=t),$e(r)?r>t?(n.warn(" cannot be greater than max: "+t+". Using max value instead."),t):r<e?(n.warn(" cannot be less than min: "+e+". Using min value instead."),e):r:(n.warn(" must be a number. using max or fallback. max: "+t+", fallback: "+i),we(i||t,e,t,n))}var Fn=class{constructor(e){this.t={},this.i=e.i,this.o=we(e.bucketSize,0,100,e.h),this.m=we(e.refillRate,0,this.o,e.h),this.$=we(e.refillInterval,0,864e5,e.h)}S(e,t){var n=t-e.lastAccess,i=Math.floor(n/this.$);if(i>0){var s=i*this.m;e.tokens=Math.min(e.tokens+s,this.o),e.lastAccess=e.lastAccess+i*this.$}}consumeRateLimit(e){var t,n=Date.now(),i=String(e),s=this.t[i];return s?this.S(s,n):(s={tokens:this.o,lastAccess:n},this.t[i]=s),s.tokens===0||(s.tokens--,s.tokens===0&&((t=this.i)==null||t.call(this,e)),s.tokens===0)}stop(){this.t={}}},fe="Mobile",xr="iOS",Fe="Android",Qt="Tablet",xo=Fe+" "+Qt,Eo="iPad",So="Apple",Co=So+" Watch",er="Safari",_t="BlackBerry",Ao="Samsung",Io=Ao+"Browser",Mo=Ao+" Internet",tt="Chrome",Nl=tt+" OS",Ro=tt+" "+xr,Li="Internet Explorer",To=Li+" "+fe,Ui="Opera",Dl=Ui+" Mini",Vi="Edge",Fo="Microsoft "+Vi,mt="Firefox",Oo=mt+" "+xr,tr="Nintendo",rr="PlayStation",vt="Xbox",$o=Fe+" "+fe,No=fe+" "+er,Ut="Windows",On=Ut+" Phone",As="Nokia",$n="Ouya",Do="Generic",ql=Do+" "+fe.toLowerCase(),qo=Do+" "+Qt.toLowerCase(),Nn="Konqueror",re="(\\d+(\\.\\d+)?)",dn=new RegExp("Version/"+re),jl=new RegExp(vt,"i"),Gl=new RegExp(rr+" \\w+","i"),Ll=new RegExp(tr+" \\w+","i"),zi=new RegExp(_t+"|PlayBook|BB10","i"),Ul={"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"},yr,Is,hn,Vl=(r,e)=>e&&F(e,So)||function(t){return F(t,er)&&!F(t,tt)&&!F(t,Fe)}(r),jo=function(r,e){return e=e||"",F(r," OPR/")&&F(r,"Mini")?Dl:F(r," OPR/")?Ui:zi.test(r)?_t:F(r,"IE"+fe)||F(r,"WPDesktop")?To:F(r,Io)?Mo:F(r,Vi)||F(r,"Edg/")?Fo:F(r,"FBIOS")?"Facebook "+fe:F(r,"UCWEB")||F(r,"UCBrowser")?"UC Browser":F(r,"CriOS")?Ro:F(r,"CrMo")||F(r,tt)?tt:F(r,Fe)&&F(r,er)?$o:F(r,"FxiOS")?Oo:F(r.toLowerCase(),Nn.toLowerCase())?Nn:Vl(r,e)?F(r,fe)?No:er:F(r,mt)?mt:F(r,"MSIE")||F(r,"Trident/")?Li:F(r,"Gecko")?mt:""},zl={[To]:[new RegExp("rv:"+re)],[Fo]:[new RegExp(Vi+"?\\/"+re)],[tt]:[new RegExp("("+tt+"|CrMo)\\/"+re)],[Ro]:[new RegExp("CriOS\\/"+re)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+re)],[er]:[dn],[No]:[dn],[Ui]:[new RegExp("(Opera|OPR)\\/"+re)],[mt]:[new RegExp(mt+"\\/"+re)],[Oo]:[new RegExp("FxiOS\\/"+re)],[Nn]:[new RegExp("Konqueror[:/]?"+re,"i")],[_t]:[new RegExp(_t+" "+re),dn],[$o]:[new RegExp("android\\s"+re,"i")],[Mo]:[new RegExp(Io+"\\/"+re)],[Li]:[new RegExp("(rv:|MSIE )"+re)],Mozilla:[new RegExp("rv:"+re)]},Hl=function(r,e){var t=jo(r,e),n=zl[t];if(x(n))return null;for(var i=0;i<n.length;i++){var s=n[i],o=r.match(s);if(o)return parseFloat(o[o.length-2])}return null},Ms=[[new RegExp(vt+"; "+vt+" (.*?)[);]","i"),r=>[vt,r&&r[1]||""]],[new RegExp(tr,"i"),[tr,""]],[new RegExp(rr,"i"),[rr,""]],[zi,[_t,""]],[new RegExp(Ut,"i"),(r,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[On,""];if(new RegExp(fe).test(e)&&!/IEMobile\b/.test(e))return[Ut+" "+fe,""];var t=/Windows NT ([0-9.]+)/i.exec(e);if(t&&t[1]){var n=t[1],i=Ul[n]||"";return/arm/i.test(e)&&(i="RT"),[Ut,i]}return[Ut,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,r=>{if(r&&r[3]){var e=[r[3],r[4],r[5]||"0"];return[xr,e.join(".")]}return[xr,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,r=>{var e="";return r&&r.length>=3&&(e=x(r[2])?r[3]:r[2]),["watchOS",e]}],[new RegExp("("+Fe+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Fe+")","i"),r=>{if(r&&r[2]){var e=[r[2],r[3],r[4]||"0"];return[Fe,e.join(".")]}return[Fe,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,r=>{var e=["Mac OS X",""];if(r&&r[1]){var t=[r[1],r[2],r[3]||"0"];e[1]=t.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Nl,""]],[/Linux|debian/i,["Linux",""]]],Rs=function(r){return Ll.test(r)?tr:Gl.test(r)?rr:jl.test(r)?vt:new RegExp($n,"i").test(r)?$n:new RegExp("("+On+"|WPDesktop)","i").test(r)?On:/iPad/.test(r)?Eo:/iPod/.test(r)?"iPod Touch":/iPhone/.test(r)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(r)?Co:zi.test(r)?_t:/(kobo)\s(ereader|touch)/i.test(r)?"Kobo":new RegExp(As,"i").test(r)?As:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(r)||/(kf[a-z]+)( bui|\)).+silk\//i.test(r)?"Kindle Fire":/(Android|ZTE)/i.test(r)?new RegExp(fe).test(r)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(r)||/pixel[\daxl ]{1,6}/i.test(r)&&!/pixel c/i.test(r)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(r)||/lmy47v/i.test(r)&&!/QTAQZ3/i.test(r)?Fe:xo:new RegExp("(pda|"+fe+")","i").test(r)?ql:new RegExp(Qt,"i").test(r)&&!new RegExp(Qt+" pc","i").test(r)?qo:""},Kl=r=>r instanceof Error;function Bl(r){var e=globalThis._posthogChunkIds;if(e){var t=Object.keys(e);return hn&&t.length===Is||(Is=t.length,hn=t.reduce((n,i)=>{yr||(yr={});var s=yr[i];if(s)n[s[0]]=s[1];else for(var o=r(i),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[i];if(u&&c){n[u]=c,yr[i]=[u,c];break}}return n},{})),hn}}var Dn=class{constructor(e,t,n){n===void 0&&(n=[]),this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t){t===void 0&&(t={});var n=t&&t.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(n,t,0).apply(e),s=this.buildParsingContext(),o=this.parseStacktrace(i,s);return{$exception_list:this.convertToExceptionList(o,n),$exception_level:"error"}}modifyFrames(e){var t=this;return ft(function*(){for(var n of e)n.stacktrace&&n.stacktrace.frames&&$(n.stacktrace.frames)&&(n.stacktrace.frames=yield t.applyModifiers(n.stacktrace.frames));return e})()}coerceFallback(e){var t;return{type:"Error",value:"Unknown error",stack:(t=e.syntheticException)==null?void 0:t.stack,synthetic:!0}}parseStacktrace(e,t){var n,i;return e.cause!=null&&(n=this.parseStacktrace(e.cause,t)),e.stack!=""&&e.stack!=null&&(i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?1:0),t.chunkIdMap)),S({},e,{cause:n,stack:i})}applyChunkIds(e,t){return e.map(n=>(n.filename&&t&&(n.chunk_id=t[n.filename]),n))}applyCoercers(e,t){for(var n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}applyModifiers(e){var t=this;return ft(function*(){var n=e;for(var i of t.modifiers)n=yield i(n);return n})()}convertToExceptionList(e,t){var n,i,s,o={type:e.type,value:e.value,mechanism:{type:(n=t.type)!==null&&n!==void 0?n:"generic",handled:(i=t.handled)===null||i===void 0||i,synthetic:(s=e.synthetic)!==null&&s!==void 0&&s}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,S({},t,{handled:!0}))),a}buildParsingContext(){return{chunkIdMap:Bl(this.stackParser)}}buildCoercingContext(e,t,n){n===void 0&&(n=0);var i=(s,o)=>{if(o<=4){var a=this.buildCoercingContext(e,t,o);return this.applyCoercers(s,a)}};return S({},t,{syntheticException:n==0?t.syntheticException:void 0,mechanism:e,apply:s=>i(s,n),next:s=>i(s,n+1)})}},bt="?";function qn(r,e,t,n,i){var s={platform:r,filename:e,function:t==="<anonymous>"?bt:t,in_app:!0};return x(n)||(s.lineno=n),x(i)||(s.colno=i),s}var Go=(r,e)=>{var t=r.indexOf("safari-extension")!==-1,n=r.indexOf("safari-web-extension")!==-1;return t||n?[r.indexOf("@")!==-1?r.split("@")[0]:bt,t?"safari-extension:"+e:"safari-web-extension:"+e]:[r,e]},Wl=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Xl=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Yl=/\((\S*)(?::(\d+))(?::(\d+))\)/,Jl=(r,e)=>{var t=Wl.exec(r);if(t){var[,n,i,s]=t;return qn(e,n,bt,+i,+s)}var o=Xl.exec(r);if(o){if(o[2]&&o[2].indexOf("eval")===0){var a=Yl.exec(o[2]);a&&(o[2]=a[1],o[3]=a[2],o[4]=a[3])}var[l,u]=Go(o[1]||bt,o[2]);return qn(e,u,l,o[3]?+o[3]:void 0,o[4]?+o[4]:void 0)}},Zl=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Ql=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ec=(r,e)=>{var t=Zl.exec(r);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){var n=Ql.exec(t[3]);n&&(t[1]=t[1]||"eval",t[3]=n[1],t[4]=n[2],t[5]="")}var i=t[3],s=t[1]||bt;return[s,i]=Go(s,i),qn(e,i,s,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}},Ts=/\(error: (.*)\)/,Fs=50;function tc(){return function(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),n=1;n<e;n++)t[n-1]=arguments[n];return function(i,s){s===void 0&&(s=0);for(var o=[],a=i.split(`
9
- `),l=s;l<a.length;l++){var u=a[l];if(!(u.length>1024)){var c=Ts.test(u)?u.replace(Ts,"$1"):u;if(!c.match(/\S*Error: /)){for(var p of t){var d=p(c,r);if(d){o.push(d);break}}if(o.length>=Fs)break}}}return function(h){if(!h.length)return[];var g=Array.from(h);return g.reverse(),g.slice(0,Fs).map(f=>{return S({},f,{filename:f.filename||(m=g,m[m.length-1]||{}).filename,function:f.function||bt});var m})}(o)}}("web:javascript",Jl,ec)}var jn=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){var n=K(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:n?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?t+": "+e.message:t}isDOMException(e){return Pr(e,"DOMException")}isDOMError(e){return Pr(e,"DOMError")}},Gn=class{match(e){return(t=>t instanceof Error)(e)}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){var n=e.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(e){return e.stacktrace||e.stack||void 0}},Ln=class{constructor(){}match(e){return Pr(e,"ErrorEvent")&&e.error!=null}coerce(e,t){var n,i=t.apply(e.error);return i||{type:"ErrorEvent",value:e.message,stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}},rc=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,Un=class{match(e){return typeof e=="string"}coerce(e,t){var n,[i,s]=this.getInfos(e);return{type:i??"Error",value:s??e,stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}getInfos(e){var t="Error",n=e,i=e.match(rc);return i&&(t=i[1],n=i[2]),[t,n]}},nc=["fatal","error","warning","log","info","debug"];function Lo(r,e){e===void 0&&(e=40);var t=Object.keys(r);if(t.sort(),!t.length)return"[object has no keys]";for(var n=t.length;n>0;n--){var i=t.slice(0,n).join(", ");if(!(i.length>e))return n===t.length||i.length<=e?i:i.slice(0,e)+"..."}return""}var Vn=class{match(e){return typeof e=="object"&&e!==null}coerce(e,t){var n,i=this.getErrorPropertyFromObject(e);return i?t.apply(i):{type:this.getType(e),value:this.getValue(e),stack:(n=t.syntheticException)==null?void 0:n.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Po(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var t="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(t+=" with message: '"+e.message+"'"),t}if("message"in e&&typeof e.message=="string")return e.message;var n=this.getObjectClassName(e);return(n&&n!=="Object"?"'"+n+"'":"Object")+" captured as exception with keys: "+Lo(e)}isSeverityLevel(e){return K(e)&&!Rn(e)&&nc.indexOf(e)>=0}getErrorPropertyFromObject(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t)){var n=e[t];if(Kl(n))return n}}getObjectClassName(e){try{var t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}},zn=class{match(e){return Po(e)}coerce(e,t){var n,i=e.constructor.name;return{type:i,value:i+" captured as exception with keys: "+Lo(e),stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}},Hn=class{match(e){return Tn(e)}coerce(e,t){var n;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}},Kn=class{match(e){return Pr(e,"PromiseRejectionEvent")}coerce(e,t){var n,i=this.getUnhandledRejectionReason(e);return Tn(i)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(i),stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}:t.apply(i)}getUnhandledRejectionReason(e){if(Tn(e))return e;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch{}return e}},Uo=function(r,e){var{debugEnabled:t}=e===void 0?{}:e,n={k:function(i){if(y&&(Ie.DEBUG||A.POSTHOG_DEBUG||t)&&!x(y.console)&&y.console){for(var s=("__rrweb_original__"in y.console[i])?y.console[i].__rrweb_original__:y.console[i],o=arguments.length,a=new Array(o>1?o-1:0),l=1;l<o;l++)a[l-1]=arguments[l];s(r,...a)}},info:function(){for(var i=arguments.length,s=new Array(i),o=0;o<i;o++)s[o]=arguments[o];n.k("log",...s)},warn:function(){for(var i=arguments.length,s=new Array(i),o=0;o<i;o++)s[o]=arguments[o];n.k("warn",...s)},error:function(){for(var i=arguments.length,s=new Array(i),o=0;o<i;o++)s[o]=arguments[o];n.k("error",...s)},critical:function(){for(var i=arguments.length,s=new Array(i),o=0;o<i;o++)s[o]=arguments[o];console.error(r,...s)},uninitializedWarning:i=>{n.error("You must initialize PostHog before calling "+i)},createLogger:(i,s)=>Uo(r+" "+i,s)};return n},E=Uo("[PostHog.js]"),L=E.createLogger,ic=L("[ExternalScriptsLoader]"),Os=(r,e,t)=>{if(r.config.disable_external_dependency_loading)return ic.warn(e+" was requested but loading of external scripts is disabled."),t("Loading of external scripts is disabled");var n=P?.querySelectorAll("script");if(n){for(var i,s=function(){if(n[o].src===e){var l=n[o];return l.__posthog_loading_callback_fired?{v:t()}:(l.addEventListener("load",u=>{l.__posthog_loading_callback_fired=!0,t(void 0,u)}),l.onerror=u=>t(u),{v:void 0})}},o=0;o<n.length;o++)if(i=s())return i.v}var a=()=>{if(!P)return t("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=p=>{l.__posthog_loading_callback_fired=!0,t(void 0,p)},l.onerror=p=>t(p),r.config.prepare_external_dependency_script&&(l=r.config.prepare_external_dependency_script(l)),!l)return t("prepare_external_dependency_script returned null");if(r.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};A.__PosthogExtensions__=A.__PosthogExtensions__||{},A.__PosthogExtensions__.loadExternalDependency=(r,e,t)=>{var n="/static/"+e+".js?v="+r.version;if(e==="remote-config"&&(n="/array/"+r.config.token+"/config.js"),e==="toolbar"){var i=3e5;n=n+"&t="+Math.floor(Date.now()/i)*i}var s=r.requestRouter.endpointFor("assets",n);Os(r,s,t)},A.__PosthogExtensions__.loadSiteApp=(r,e,t)=>{var n=r.requestRouter.endpointFor("api",e);Os(r,n,t)};var Er={};function He(r,e,t){if($(r)){if(Ps&&r.forEach===Ps)r.forEach(e,t);else if("length"in r&&r.length===+r.length){for(var n=0,i=r.length;n<i;n++)if(n in r&&e.call(t,r[n],n)===Er)return}}}function D(r,e,t){if(!O(r)){if($(r))return He(r,e,t);if(Tl(r)){for(var n of r.entries())if(e.call(t,n[1],n[0])===Er)return}else for(var i in r)if(ko.call(r,i)&&e.call(t,r[i],i)===Er)return}}var U=function(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),n=1;n<e;n++)t[n-1]=arguments[n];return He(t,function(i){for(var s in i)i[s]!==void 0&&(r[s]=i[s])}),r},kt=function(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),n=1;n<e;n++)t[n-1]=arguments[n];return He(t,function(i){He(i,function(s){r.push(s)})}),r};function wr(r){for(var e=Object.keys(r),t=e.length,n=new Array(t);t--;)n[t]=[e[t],r[e[t]]];return n}var $s=function(r){try{return r()}catch{return}},sc=function(r){return function(){try{for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return r.apply(this,t)}catch(i){E.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),E.critical(i)}}},Hi=function(r){var e={};return D(r,function(t,n){(K(t)&&t.length>0||$e(t))&&(e[n]=t)}),e};function oc(r,e){return t=r,n=s=>K(s)&&!me(e)?s.slice(0,e):s,i=new Set,function s(o,a){return o!==Object(o)?n?n(o,a):o:i.has(o)?void 0:(i.add(o),$(o)?(l=[],He(o,u=>{l.push(s(u))})):(l={},D(o,(u,c)=>{i.has(u)||(l[c]=s(u,c))})),l);var l}(t);var t,n,i}var ac=["herokuapp.com","vercel.app","netlify.app"];function lc(r){var e=r?.hostname;if(!K(e))return!1;var t=e.split(".").slice(-2).join(".");for(var n of ac)if(t===n)return!1;return!0}function Vo(r,e){for(var t=0;t<r.length;t++)if(e(r[t]))return r[t]}function z(r,e,t,n){var{capture:i=!1,passive:s=!0}=n??{};r?.addEventListener(e,t,{capture:i,passive:s})}var zo="$people_distinct_id",Vt="__alias",zt="__timers",Ns="$autocapture_disabled_server_side",Bn="$heatmaps_enabled_server_side",Ds="$exception_capture_enabled_server_side",Wn="$error_tracking_suppression_rules",qs="$error_tracking_capture_extension_exceptions",js="$web_vitals_enabled_server_side",Ho="$dead_clicks_enabled_server_side",Gs="$product_tours_enabled_server_side",Ls="$web_vitals_allowed_metrics",fn="$session_recording_remote_config",Sr="$sesid",Ko="$session_is_sampled",yt="$enabled_feature_flags",Ht="$early_access_features",Xn="$feature_flag_details",Kt="$stored_person_properties",et="$stored_group_properties",Yn="$surveys",Cr="$flag_call_reported",Me="$user_state",Jn="$client_session_props",Zn="$capture_rate_limit",Qn="$initial_campaign_params",ei="$initial_referrer_info",Ar="$initial_person_info",Ir="$epp",Bo="__POSTHOG_TOOLBAR__",Ft="$posthog_cookieless",cc=[zo,Vt,"__cmpns",zt,"$session_recording_enabled_server_side",Bn,Sr,yt,Wn,Me,Ht,Xn,et,Kt,Yn,Cr,Jn,Zn,Qn,ei,Ir,Ar,"$conversations_widget_session_id","$conversations_ticket_id","$conversations_widget_state","$conversations_user_traits"];function Us(r){return r instanceof Element&&(r.id===Bo||!(r.closest==null||!r.closest(".toolbar-global-fade-container")))}function Br(r){return!!r&&r.nodeType===1}function Ke(r,e){return!!r&&!!r.tagName&&r.tagName.toLowerCase()===e.toLowerCase()}function Wo(r){return!!r&&r.nodeType===3}function Xo(r){return!!r&&r.nodeType===11}function Ki(r){return r?Hr(r).split(/\s+/):[]}function Vs(r){var e=y?.location.href;return!!(e&&r&&r.some(t=>e.match(t)))}function Mr(r){var e="";switch(typeof r.className){case"string":e=r.className;break;case"object":e=(r.className&&"baseVal"in r.className?r.className.baseVal:null)||r.getAttribute("class")||"";break;default:e=""}return Ki(e)}function Yo(r){return O(r)?null:Hr(r).split(/(\s+)/).filter(e=>nr(e)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function sr(r){var e="";return ti(r)&&!ta(r)&&r.childNodes&&r.childNodes.length&&D(r.childNodes,function(t){var n;Wo(t)&&t.textContent&&(e+=(n=Yo(t.textContent))!==null&&n!==void 0?n:"")}),Hr(e)}function Jo(r){return x(r.target)?r.srcElement||null:(e=r.target)!=null&&e.shadowRoot?r.composedPath()[0]||null:r.target||null;var e}var Bi=["a","button","form","input","select","textarea","label"];function Zo(r,e){if(x(e))return!0;var t,n=function(s){if(e.some(o=>s.matches(o)))return{v:!0}};for(var i of r)if(t=n(i))return t.v;return!1}function Qo(r){var e=r.parentNode;return!(!e||!Br(e))&&e}var uc=["next","previous","prev",">","<"],zs=10,Hs=[".ph-no-rageclick",".ph-no-capture"];function pc(r,e){if(!y||Wi(r))return!1;var t,n,i;if(Oe(e)?(t=!!e&&Hs,n=void 0):(t=(i=e?.css_selector_ignorelist)!==null&&i!==void 0?i:Hs,n=e?.content_ignorelist),t===!1)return!1;var{targetElementList:s}=ea(r,!1);return!function(o,a){if(o===!1||x(o))return!1;var l;if(o===!0)l=uc;else{if(!$(o))return!1;if(o.length>zs)return E.error("[PostHog] content_ignorelist array cannot exceed "+zs+" items. Use css_selector_ignorelist for more complex matching."),!1;l=o.map(u=>u.toLowerCase())}return a.some(u=>{var{safeText:c,ariaLabel:p}=u;return l.some(d=>c.includes(d)||p.includes(d))})}(n,s.map(o=>{var a;return{safeText:sr(o).toLowerCase(),ariaLabel:((a=o.getAttribute("aria-label"))==null?void 0:a.toLowerCase().trim())||""}}))&&!Zo(s,t)}var Wi=r=>!r||Ke(r,"html")||!Br(r),ea=(r,e)=>{if(!y||Wi(r))return{parentIsUsefulElement:!1,targetElementList:[]};for(var t=!1,n=[r],i=r;i.parentNode&&!Ke(i,"body");)if(Xo(i.parentNode))n.push(i.parentNode.host),i=i.parentNode.host;else{var s=Qo(i);if(!s)break;if(e||Bi.indexOf(s.tagName.toLowerCase())>-1)t=!0;else{var o=y.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(t=!0)}n.push(s),i=s}return{parentIsUsefulElement:t,targetElementList:n}};function dc(r,e,t,n,i){var s,o,a,l;if(t===void 0&&(t=void 0),!y||Wi(r)||(s=t)!=null&&s.url_allowlist&&!Vs(t.url_allowlist)||(o=t)!=null&&o.url_ignorelist&&Vs(t.url_ignorelist))return!1;if((a=t)!=null&&a.dom_event_allowlist){var u=t.dom_event_allowlist;if(u&&!u.some(g=>e.type===g))return!1}var{parentIsUsefulElement:c,targetElementList:p}=ea(r,n);if(!function(g,f){var m=f?.element_allowlist;if(x(m))return!0;var w,b=function(_){if(m.some(k=>_.tagName.toLowerCase()===k))return{v:!0}};for(var v of g)if(w=b(v))return w.v;return!1}(p,t)||!Zo(p,(l=t)==null?void 0:l.css_selector_allowlist))return!1;var d=y.getComputedStyle(r);if(d&&d.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;var h=r.tagName.toLowerCase();switch(h){case"html":return!1;case"form":return(i||["submit"]).indexOf(e.type)>=0;case"input":case"select":case"textarea":return(i||["change","click"]).indexOf(e.type)>=0;default:return c?(i||["click"]).indexOf(e.type)>=0:(i||["click"]).indexOf(e.type)>=0&&(Bi.indexOf(h)>-1||r.getAttribute("contenteditable")==="true")}}function ti(r){for(var e=r;e.parentNode&&!Ke(e,"body");e=e.parentNode){var t=Mr(e);if(F(t,"ph-sensitive")||F(t,"ph-no-capture"))return!1}if(F(Mr(r),"ph-include"))return!0;var n=r.type||"";if(K(n))switch(n.toLowerCase()){case"hidden":case"password":return!1}var i=r.name||r.id||"";return!(K(i)&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g,"")))}function ta(r){return!!(Ke(r,"input")&&!["button","checkbox","submit","reset"].includes(r.type)||Ke(r,"select")||Ke(r,"textarea")||r.getAttribute("contenteditable")==="true")}var ra="(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})",hc=new RegExp("^(?:"+ra+")$"),fc=new RegExp(ra),na="\\d{3}-?\\d{2}-?\\d{4}",gc=new RegExp("^("+na+")$"),yc=new RegExp("("+na+")");function nr(r,e){return e===void 0&&(e=!0),!(O(r)||K(r)&&(r=Hr(r),(e?hc:fc).test((r||"").replace(/[- ]/g,""))||(e?gc:yc).test(r)))}function ia(r){var e=sr(r);return nr(e=(e+" "+sa(r)).trim())?e:""}function sa(r){var e="";return r&&r.childNodes&&r.childNodes.length&&D(r.childNodes,function(t){var n;if(t&&((n=t.tagName)==null?void 0:n.toLowerCase())==="span")try{var i=sr(t);e=(e+" "+i).trim(),t.childNodes&&t.childNodes.length&&(e=(e+" "+sa(t)).trim())}catch(s){E.error("[AutoCapture]",s)}}),e}function mc(r){return function(e){var t=e.map(n=>{var i,s,o="";if(n.tag_name&&(o+=n.tag_name),n.attr_class)for(var a of(n.attr_class.sort(),n.attr_class))o+="."+a.replace(/"/g,"");var l=S({},n.text?{text:n.text}:{},{"nth-child":(i=n.nth_child)!==null&&i!==void 0?i:0,"nth-of-type":(s=n.nth_of_type)!==null&&s!==void 0?s:0},n.href?{href:n.href}:{},n.attr_id?{attr_id:n.attr_id}:{},n.attributes),u={};return wr(l).sort((c,p)=>{var[d]=c,[h]=p;return d.localeCompare(h)}).forEach(c=>{var[p,d]=c;return u[Ks(p.toString())]=Ks(d.toString())}),o+=":",o+=wr(u).map(c=>{var[p,d]=c;return p+'="'+d+'"'}).join("")});return t.join(";")}(function(e){return e.map(t=>{var n,i,s={text:(n=t.$el_text)==null?void 0:n.slice(0,400),tag_name:t.tag_name,href:(i=t.attr__href)==null?void 0:i.slice(0,2048),attr_class:vc(t),attr_id:t.attr__id,nth_child:t.nth_child,nth_of_type:t.nth_of_type,attributes:{}};return wr(t).filter(o=>{var[a]=o;return a.indexOf("attr__")===0}).forEach(o=>{var[a,l]=o;return s.attributes[a]=l}),s})}(r))}function Ks(r){return r.replace(/"|\\"/g,'\\"')}function vc(r){var e=r.attr__class;return e?$(e)?e:Ki(e):void 0}var Rr=class{constructor(e){this.disabled=e===!1;var t=H(e)?e:{};this.thresholdPx=t.threshold_px||30,this.timeoutMs=t.timeout_ms||1e3,this.clickCount=t.click_count||3,this.clicks=[]}isRageClick(e,t,n){if(this.disabled)return!1;var i=this.clicks[this.clicks.length-1];if(i&&Math.abs(e-i.x)+Math.abs(t-i.y)<this.thresholdPx&&n-i.timestamp<this.timeoutMs){if(this.clicks.push({x:e,y:t,timestamp:n}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:t,timestamp:n}];return!1}},Tr=r=>{var e=P?.createElement("a");return x(e)?null:(e.href=r,e)},_c=function(r,e){var t,n;e===void 0&&(e="&");var i=[];return D(r,function(s,o){x(s)||x(o)||o==="undefined"||(t=encodeURIComponent((a=>a instanceof File)(s)?s.name:s.toString()),n=encodeURIComponent(o),i[i.length]=n+"="+t)}),i.join(e)},Fr=function(r,e){for(var t,n=((r.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),i=0;i<n.length;i++){var s=n[i].split("=");if(s[0]===e){t=s;break}}if(!$(t)||t.length<2)return"";var o=t[1];try{o=decodeURIComponent(o)}catch{E.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},or=function(r,e,t){if(!r||!e||!e.length)return r;for(var n=r.split("#"),i=n[0]||"",s=n[1],o=i.split("?"),a=o[1],l=o[0],u=(a||"").split("&"),c=[],p=0;p<u.length;p++){var d=u[p].split("=");$(d)&&(e.includes(d[0])?c.push(d[0]+"="+t):c.push(u[p]))}var h=l;return a!=null&&(h+="?"+c.join("&")),s!=null&&(h+="#"+s),h},Or=function(r,e){var t=r.match(new RegExp(e+"=([^&]*)"));return t?t[1]:null},gn="$copy_autocapture",Bs=L("[AutoCapture]");function yn(r,e){return e.length>r?e.slice(0,r)+"...":e}function bc(r){if(r.previousElementSibling)return r.previousElementSibling;var e=r;do e=e.previousSibling;while(e&&!Br(e));return e}function wc(r,e,t,n){var i=r.tagName.toLowerCase(),s={tag_name:i};Bi.indexOf(i)>-1&&!t&&(i.toLowerCase()==="a"||i.toLowerCase()==="button"?s.$el_text=yn(1024,ia(r)):s.$el_text=yn(1024,sr(r)));var o=Mr(r);o.length>0&&(s.classes=o.filter(function(c){return c!==""})),D(r.attributes,function(c){var p;if((!ta(r)||["name","id","class","aria-label"].indexOf(c.name)!==-1)&&(n==null||!n.includes(c.name))&&!e&&nr(c.value)&&(p=c.name,!K(p)||p.substring(0,10)!=="_ngcontent"&&p.substring(0,7)!=="_nghost")){var d=c.value;c.name==="class"&&(d=Ki(d).join(" ")),s["attr__"+c.name]=yn(1024,d)}});for(var a=1,l=1,u=r;u=bc(u);)a++,u.tagName===r.tagName&&l++;return s.nth_child=a,s.nth_of_type=l,s}function kc(r,e){for(var t,n,{e:i,maskAllElementAttributes:s,maskAllText:o,elementAttributeIgnoreList:a,elementsChainAsString:l}=e,u=[r],c=r;c.parentNode&&!Ke(c,"body");)Xo(c.parentNode)?(u.push(c.parentNode.host),c=c.parentNode.host):(u.push(c.parentNode),c=c.parentNode);var p,d=[],h={},g=!1,f=!1;if(D(u,_=>{var k=ti(_);_.tagName.toLowerCase()==="a"&&(g=_.getAttribute("href"),g=k&&g&&nr(g)&&g),F(Mr(_),"ph-no-capture")&&(f=!0),d.push(wc(_,s,o,a));var I=function(M){if(!ti(M))return{};var C={};return D(M.attributes,function(j){if(j.name&&j.name.indexOf("data-ph-capture-attribute")===0){var V=j.name.replace("data-ph-capture-attribute-",""),Q=j.value;V&&Q&&nr(Q)&&(C[V]=Q)}}),C}(_);U(h,I)}),f)return{props:{},explicitNoCapture:f};if(o||(r.tagName.toLowerCase()==="a"||r.tagName.toLowerCase()==="button"?d[0].$el_text=ia(r):d[0].$el_text=sr(r)),g){var m,w;d[0].attr__href=g;var b=(m=Tr(g))==null?void 0:m.host,v=y==null||(w=y.location)==null?void 0:w.host;b&&v&&b!==v&&(p=g)}return{props:U({$event_type:i.type,$ce_version:1},l?{}:{$elements:d},{$elements_chain:mc(d)},(t=d[0])!=null&&t.$el_text?{$el_text:(n=d[0])==null?void 0:n.$el_text}:{},p&&i.type==="click"?{$external_click_url:p}:{},h)}}var ri=class{constructor(e){this.P=!1,this.T=null,this.I=!1,this.instance=e,this.rageclicks=new Rr(e.config.rageclick),this.C=null}get R(){var e,t,n=H(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(e=n.url_allowlist)==null?void 0:e.map(i=>new RegExp(i)),n.url_ignorelist=(t=n.url_ignorelist)==null?void 0:t.map(i=>new RegExp(i)),n}F(){if(this.isBrowserSupported()){if(y&&P){var e=n=>{n=n||y?.event;try{this.O(n)}catch(i){Bs.error("Failed to capture event",i)}};if(z(P,"submit",e,{capture:!0}),z(P,"change",e,{capture:!0}),z(P,"click",e,{capture:!0}),this.R.capture_copied_text){var t=n=>{n=n||y?.event,this.O(n,gn)};z(P,"copy",t,{capture:!0}),z(P,"cut",t,{capture:!0})}}}else Bs.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.P&&(this.F(),this.P=!0)}onRemoteConfig(e){e.elementsChainAsString&&(this.I=e.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[Ns]:!!e.autocapture_opt_out}),this.T=!!e.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(e){this.C=e}getElementSelectors(e){var t,n=[];return(t=this.C)==null||t.forEach(i=>{var s=P?.querySelectorAll(i);s?.forEach(o=>{e===o&&n.push(i)})}),n}get isEnabled(){var e,t,n=(e=this.instance.persistence)==null?void 0:e.props[Ns],i=this.T;if(me(i)&&!Oe(n)&&!this.instance.M())return!1;var s=(t=this.T)!==null&&t!==void 0?t:!!n;return!!this.instance.config.autocapture&&!s}O(e,t){if(t===void 0&&(t="$autocapture"),this.isEnabled){var n,i=Jo(e);Wo(i)&&(i=i.parentNode||null),t==="$autocapture"&&e.type==="click"&&e instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(e.clientX,e.clientY,e.timeStamp||new Date().getTime())&&pc(i,this.instance.config.rageclick)&&this.O(e,"$rageclick");var s=t===gn;if(i&&dc(i,e,this.R,s,s?["copy","cut"]:void 0)){var{props:o,explicitNoCapture:a}=kc(i,{e,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.R.element_attribute_ignorelist,elementsChainAsString:this.I});if(a)return!1;var l=this.getElementSelectors(i);if(l&&l.length>0&&(o.$element_selectors=l),t===gn){var u,c=Yo(y==null||(u=y.getSelection())==null?void 0:u.toString()),p=e.type||"clipboard";if(!c)return!1;o.$selected_content=c,o.$copy_type=p}return this.instance.capture(t,o),!0}}}isBrowserSupported(){return ze(P?.querySelectorAll)}};Math.trunc||(Math.trunc=function(r){return r<0?Math.ceil(r):Math.floor(r)}),Number.isInteger||(Number.isInteger=function(r){return $e(r)&&isFinite(r)&&Math.floor(r)===r});var Ws="0123456789abcdef",ni=class r{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,n,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(i)||e<0||t<0||n<0||i<0||e>0xffffffffffff||t>4095||n>1073741823||i>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/Math.pow(2,8),s[5]=e,s[6]=112|t>>>8,s[7]=t,s[8]=128|n>>>24,s[9]=n>>>16,s[10]=n>>>8,s[11]=n,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new r(s)}toString(){for(var e="",t=0;t<this.bytes.length;t++)e=e+Ws.charAt(this.bytes[t]>>>4)+Ws.charAt(15&this.bytes[t]),t!==3&&t!==5&&t!==7&&t!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new r(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var t=0;t<16;t++){var n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}},ii=class{constructor(){this.A=0,this.j=0,this.D=new si}generate(){var e=this.generateOrAbort();if(x(e)){this.A=0;var t=this.generateOrAbort();if(x(t))throw new Error("Could not generate UUID after timestamp reset");return t}return e}generateOrAbort(){var e=Date.now();if(e>this.A)this.A=e,this.L();else{if(!(e+1e4>this.A))return;this.j++,this.j>4398046511103&&(this.A++,this.L())}return ni.fromFieldsV7(this.A,Math.trunc(this.j/Math.pow(2,30)),this.j&Math.pow(2,30)-1,this.D.nextUint32())}L(){this.j=1024*this.D.nextUint32()+(1023&this.D.nextUint32())}},Xs,oa=r=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;e<r.length;e++)r[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return r};y&&!x(y.crypto)&&crypto.getRandomValues&&(oa=r=>crypto.getRandomValues(r));var si=class{constructor(){this.N=new Uint32Array(8),this.U=1/0}nextUint32(){return this.U>=this.N.length&&(oa(this.N),this.U=0),this.N[this.U++]}},Ve=()=>Pc().toString(),Pc=()=>(Xs||(Xs=new ii)).generate(),Ot="",xc=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function Ec(r,e){if(e){var t=function(i,s){if(s===void 0&&(s=P),Ot)return Ot;if(!s||["localhost","127.0.0.1"].includes(i))return"";for(var o=i.split("."),a=Math.min(o.length,8),l="dmn_chk_"+Ve();!Ot&&a--;){var u=o.slice(a).join("."),c=l+"=1;domain=."+u+";path=/";s.cookie=c+";max-age=3",s.cookie.includes(l)&&(s.cookie=c+";max-age=0",Ot=u)}return Ot}(r);if(!t){var n=(i=>{var s=i.match(xc);return s?s[0]:""})(r);n!==t&&E.info("Warning: cookie subdomain discovery mismatch",n,t),t=n}return t?"; domain=."+t:""}return""}var be={H:()=>!!P,B:function(r){E.error("cookieStore error: "+r)},q:function(r){if(P){try{for(var e=r+"=",t=P.cookie.split(";").filter(s=>s.length),n=0;n<t.length;n++){for(var i=t[n];i.charAt(0)==" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return decodeURIComponent(i.substring(e.length,i.length))}}catch{}return null}},W:function(r){var e;try{e=JSON.parse(be.q(r))||{}}catch{}return e},G:function(r,e,t,n,i){if(P)try{var s="",o="",a=Ec(P.location.hostname,n);if(t){var l=new Date;l.setTime(l.getTime()+24*t*60*60*1e3),s="; expires="+l.toUTCString()}i&&(o="; secure");var u=r+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&E.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,u}catch{return}},V:function(r,e){if(P!=null&&P.cookie)try{be.G(r,"",-1,e)}catch{return}}},mn=null,G={H:function(){if(!me(mn))return mn;var r=!0;if(x(y))r=!1;else try{var e="__mplssupport__";G.G(e,"xyz"),G.q(e)!=='"xyz"'&&(r=!1),G.V(e)}catch{r=!1}return r||E.error("localStorage unsupported; falling back to cookie store"),mn=r,r},B:function(r){E.error("localStorage error: "+r)},q:function(r){try{return y?.localStorage.getItem(r)}catch(e){G.B(e)}return null},W:function(r){try{return JSON.parse(G.q(r))||{}}catch{}return null},G:function(r,e){try{y?.localStorage.setItem(r,JSON.stringify(e))}catch(t){G.B(t)}},V:function(r){try{y?.localStorage.removeItem(r)}catch(e){G.B(e)}}},Sc=["$device_id","distinct_id",Sr,Ko,Ir,Ar],mr={},Cc={H:function(){return!0},B:function(r){E.error("memoryStorage error: "+r)},q:function(r){return mr[r]||null},W:function(r){return mr[r]||null},G:function(r,e){mr[r]=e},V:function(r){delete mr[r]}},Ze=null,B={H:function(){if(!me(Ze))return Ze;if(Ze=!0,x(y))Ze=!1;else try{var r="__support__";B.G(r,"xyz"),B.q(r)!=='"xyz"'&&(Ze=!1),B.V(r)}catch{Ze=!1}return Ze},B:function(r){E.error("sessionStorage error: ",r)},q:function(r){try{return y?.sessionStorage.getItem(r)}catch(e){B.B(e)}return null},W:function(r){try{return JSON.parse(B.q(r))||null}catch{}return null},G:function(r,e){try{y?.sessionStorage.setItem(r,JSON.stringify(e))}catch(t){B.B(t)}},V:function(r){try{y?.sessionStorage.removeItem(r)}catch(e){B.B(e)}}},Re=function(r){return r[r.PENDING=-1]="PENDING",r[r.DENIED=0]="DENIED",r[r.GRANTED=1]="GRANTED",r}({}),oi=class{constructor(e){this._instance=e}get R(){return this._instance.config}get consent(){return this.J()?Re.DENIED:this.K}isOptedOut(){return this.R.cookieless_mode==="always"||this.consent===Re.DENIED||this.consent===Re.PENDING&&(this.R.opt_out_capturing_by_default||this.R.cookieless_mode==="on_reject")}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===Re.DENIED}optInOut(e){this.Y.G(this.X,e?1:0,this.R.cookie_expiration,this.R.cross_subdomain_cookie,this.R.secure_cookie)}reset(){this.Y.V(this.X,this.R.cross_subdomain_cookie)}get X(){var{token:e,opt_out_capturing_cookie_prefix:t,consent_persistence_name:n}=this._instance.config;return n||(t?t+e:"__ph_opt_in_out_"+e)}get K(){var e=this.Y.q(this.X);return pn(e)?Re.GRANTED:F($l,e)?Re.DENIED:Re.PENDING}get Y(){if(!this.Z){var e=this.R.opt_out_capturing_persistence_type;this.Z=e==="localStorage"?G:be;var t=e==="localStorage"?be:G;t.q(this.X)&&(this.Z.q(this.X)||this.optInOut(pn(t.q(this.X))),t.V(this.X,this.R.cross_subdomain_cookie))}return this.Z}J(){return!!this.R.respect_dnt&&!!Vo([le?.doNotTrack,le?.msDoNotTrack,A.doNotTrack],e=>pn(e))}},vr=L("[Dead Clicks]"),Ac=()=>!0,Ic=r=>{var e,t=!((e=r.instance.persistence)==null||!e.get_property(Ho)),n=r.instance.config.capture_dead_clicks;return Oe(n)?n:!!H(n)||t},$r=class{get lazyLoadedDeadClicksAutocapture(){return this.tt}constructor(e,t,n){this.instance=e,this.isEnabled=t,this.onCapture=n,this.startIfEnabled()}onRemoteConfig(e){this.instance.persistence&&this.instance.persistence.register({[Ho]:e?.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.it(()=>{this.et()})}it(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.initDeadClicksAutocapture&&e(),(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this.instance,"dead-clicks-autocapture",i=>{i?vr.error("failed to load script",i):e()})}et(){var e;if(P){if(!this.tt&&(e=A.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var t=H(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};t.__onCapture=this.onCapture,this.tt=A.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,t),this.tt.start(P),vr.info("starting...")}}else vr.error("`document` not found. Cannot start.")}stop(){this.tt&&(this.tt.stop(),this.tt=void 0,vr.info("stopping..."))}},$t=L("[ExceptionAutocapture]"),ai=class{constructor(e){var t,n,i;this.rt=()=>{var s;if(y&&this.isEnabled&&(s=A.__PosthogExtensions__)!=null&&s.errorWrappingFunctions){var o=A.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,a=A.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,l=A.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.st&&this.R.capture_unhandled_errors&&(this.st=o(this.captureException.bind(this))),!this.nt&&this.R.capture_unhandled_rejections&&(this.nt=a(this.captureException.bind(this))),!this.ot&&this.R.capture_console_errors&&(this.ot=l(this.captureException.bind(this)))}catch(u){$t.error("failed to start",u),this.ut()}}},this._instance=e,this.ht=!((t=this._instance.persistence)==null||!t.props[Ds]),this.dt=new Fn({refillRate:(n=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:1,bucketSize:(i=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&i!==void 0?i:10,refillInterval:1e4,h:$t}),this.R=this.vt(),this.startIfEnabledOrStop()}vt(){var e=this._instance.config.capture_exceptions,t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return H(e)?t=S({},t,e):(x(e)?this.ht:e)&&(t=S({},t,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),t}get isEnabled(){return this.R.capture_console_errors||this.R.capture_unhandled_errors||this.R.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?($t.info("enabled"),this.ut(),this.it(this.rt)):this.ut()}it(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.errorWrappingFunctions&&e(),(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",i=>{if(i)return $t.error("failed to load script",i);e()})}ut(){var e,t,n;(e=this.st)==null||e.call(this),this.st=void 0,(t=this.nt)==null||t.call(this),this.nt=void 0,(n=this.ot)==null||n.call(this),this.ot=void 0}onRemoteConfig(e){var t=e.autocaptureExceptions;this.ht=!!t||!1,this._instance.persistence&&this._instance.persistence.register({[Ds]:this.ht}),this.R=this.vt(),this.startIfEnabledOrStop()}onConfigChange(){this.R=this.vt()}captureException(e){var t,n,i=(t=e==null||(n=e.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&t!==void 0?t:"Exception";this.dt.consumeRateLimit(i)?$t.info("Skipping exception capture because of client rate limiting.",{exception:i}):this._instance.exceptions.sendExceptionEvent(e)}};function Ys(r,e,t){try{if(!(e in r))return()=>{};var n=r[e],i=t(n);return ze(i)&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__posthog_wrapped__:{enumerable:!1,value:!0}})),r[e]=i,()=>{r[e]=n}}catch{return()=>{}}}var li=class{constructor(e){var t;this._instance=e,this.ct=(y==null||(t=y.location)==null?void 0:t.pathname)||""}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(E.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.ft&&this.ft(),this.ft=void 0,E.info("History API monitoring stopped")}monitorHistoryChanges(){var e,t;if(y&&y.history){var n=this;(e=y.history.pushState)!=null&&e.__posthog_wrapped__||Ys(y.history,"pushState",i=>function(s,o,a){i.call(this,s,o,a),n._t("pushState")}),(t=y.history.replaceState)!=null&&t.__posthog_wrapped__||Ys(y.history,"replaceState",i=>function(s,o,a){i.call(this,s,o,a),n._t("replaceState")}),this.bt()}}_t(e){try{var t,n=y==null||(t=y.location)==null?void 0:t.pathname;if(!n)return;n!==this.ct&&this.isEnabled&&this._instance.capture("$pageview",{navigation_type:e}),this.ct=n}catch(i){E.error("Error capturing "+e+" pageview",i)}}bt(){if(!this.ft){var e=()=>{this._t("popstate")};z(y,"popstate",e),this.ft=()=>{y&&y.removeEventListener("popstate",e)}}}},vn=L("[SegmentIntegration]");function Mc(r,e){var t=r.config.segment;if(!t)return e();(function(n,i){var s=n.config.segment;if(!s)return i();var o=l=>{var u=()=>l.anonymousId()||Ve();n.config.get_device_id=u,l.id()&&(n.register({distinct_id:l.id(),$device_id:u()}),n.persistence.set_property(Me,"identified")),i()},a=s.user();"then"in a&&ze(a.then)?a.then(o):o(a)})(r,()=>{t.register((n=>{Promise&&Promise.resolve||vn.warn("This browser does not have Promise support, and can not use the segment integration");var i=(s,o)=>{if(!o)return s;s.event.userId||s.event.anonymousId===n.get_distinct_id()||(vn.info("No userId set, resetting PostHog"),n.reset()),s.event.userId&&s.event.userId!==n.get_distinct_id()&&(vn.info("UserId set, identifying with PostHog"),n.identify(s.event.userId));var a=n.calculateEventProperties(o,s.event.properties);return s.event.properties=Object.assign({},a,s.event.properties),s};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:s=>i(s,s.event.event),page:s=>i(s,"$pageview"),identify:s=>i(s,"$identify"),screen:s=>i(s,"$screen")}})(r)).then(()=>{e()})})}var aa="posthog-js";function la(r,e){var{organization:t,projectId:n,prefix:i,severityAllowList:s=["error"],sendExceptionsToPostHog:o=!0}=e===void 0?{}:e;return a=>{var l,u,c,p,d;if(!(s==="*"||s.includes(a.level))||!r.__loaded)return a;a.tags||(a.tags={});var h=r.requestRouter.endpointFor("ui","/project/"+r.config.token+"/person/"+r.get_distinct_id());a.tags["PostHog Person URL"]=h,r.sessionRecordingStarted()&&(a.tags["PostHog Recording URL"]=r.get_session_replay_url({withTimestamp:!0}));var g=((l=a.exception)==null?void 0:l.values)||[],f=g.map(w=>S({},w,{stacktrace:w.stacktrace?S({},w.stacktrace,{type:"raw",frames:(w.stacktrace.frames||[]).map(b=>S({},b,{platform:"web:javascript"}))}):void 0})),m={$exception_message:((u=g[0])==null?void 0:u.value)||a.message,$exception_type:(c=g[0])==null?void 0:c.type,$exception_level:a.level,$exception_list:f,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:((p=g[0])==null?void 0:p.value)||a.message,$sentry_exception_type:(d=g[0])==null?void 0:d.type,$sentry_tags:a.tags};return t&&n&&(m.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+n+"&query="+a.event_id),o&&r.exceptions.sendExceptionEvent(m),a}}var ci=class{constructor(e,t,n,i,s,o){this.name=aa,this.setupOnce=function(a){a(la(e,{organization:t,projectId:n,prefix:i,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}},Rc=y!=null&&y.location?Or(y.location.hash,"__posthog")||Or(location.hash,"state"):null,Js="_postHogToolbarParams",Zs=L("[Toolbar]"),Ue=function(r){return r[r.UNINITIALIZED=0]="UNINITIALIZED",r[r.LOADING=1]="LOADING",r[r.LOADED=2]="LOADED",r}(Ue||{}),ui=class{constructor(e){this.instance=e}yt(e){A.ph_toolbar_state=e}wt(){var e;return(e=A.ph_toolbar_state)!==null&&e!==void 0?e:Ue.UNINITIALIZED}maybeLoadToolbar(e,t,n){if(e===void 0&&(e=void 0),t===void 0&&(t=void 0),n===void 0&&(n=void 0),!y||!P)return!1;e=e??y.location,n=n??y.history;try{if(!t){try{y.localStorage.setItem("test","test"),y.localStorage.removeItem("test")}catch{return!1}t=y?.localStorage}var i,s=Rc||Or(e.hash,"__posthog")||Or(e.hash,"state"),o=s?$s(()=>JSON.parse(atob(decodeURIComponent(s))))||$s(()=>JSON.parse(decodeURIComponent(s))):null;return o&&o.action==="ph_authorize"?((i=o).source="url",i&&Object.keys(i).length>0&&(o.desiredHash?e.hash=o.desiredHash:n?n.replaceState(n.state,"",e.pathname+e.search):e.hash="")):((i=JSON.parse(t.getItem(Js)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token)&&(this.loadToolbar(i),!0)}catch{return!1}}xt(e){var t=A.ph_load_toolbar||A.ph_load_editor;!O(t)&&ze(t)?t(e,this.instance):Zs.warn("No toolbar load function found")}loadToolbar(e){var t=!(P==null||!P.getElementById(Bo));if(!y||t)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=S({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(y.localStorage.setItem(Js,JSON.stringify(S({},i,{source:void 0}))),this.wt()===Ue.LOADED)this.xt(i);else if(this.wt()===Ue.UNINITIALIZED){var s;this.yt(Ue.LOADING),(s=A.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this.instance,"toolbar",o=>{if(o)return Zs.error("[Toolbar] Failed to load",o),void this.yt(Ue.UNINITIALIZED);this.yt(Ue.LOADED),this.xt(i)}),z(y,"turbolinks:load",()=>{this.yt(Ue.UNINITIALIZED),this.loadToolbar(i)})}return!0}Et(e){return this.loadToolbar(e)}maybeLoadEditor(e,t,n){return e===void 0&&(e=void 0),t===void 0&&(t=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(e,t,n)}},Tc=L("[TracingHeaders]"),pi=class{constructor(e){this.$t=void 0,this.St=void 0,this.rt=()=>{var t,n;x(this.$t)&&((t=A.__PosthogExtensions__)==null||(t=t.tracingHeadersPatchFns)==null||t._patchXHR(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager)),x(this.St)&&((n=A.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null||n._patchFetch(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=e}it(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.tracingHeadersPatchFns&&e(),(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",i=>{if(i)return Tc.error("failed to load script",i);e()})}startIfEnabledOrStop(){var e,t;this._instance.config.__add_tracing_headers?this.it(this.rt):((e=this.$t)==null||e.call(this),(t=this.St)==null||t.call(this),this.$t=void 0,this.St=void 0)}},_r="https?://(.*)",Pt=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Fc=kt(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],Pt),ar="<masked>",Oc=["li_fat_id"];function ca(r,e,t){if(!P)return{};var n,i=e?kt([],Pt,t||[]):[],s=ua(or(P.URL,i,ar),r),o=(n={},D(Oc,function(a){var l=be.q(a);n[a]=l||null}),n);return U(o,s)}function ua(r,e){var t=Fc.concat(e||[]),n={};return D(t,function(i){var s=Fr(r,i);n[i]=s||null}),n}function pa(r){var e=function(s){return s?s.search(_r+"google.([^/?]*)")===0?"google":s.search(_r+"bing.com")===0?"bing":s.search(_r+"yahoo.com")===0?"yahoo":s.search(_r+"duckduckgo.com")===0?"duckduckgo":null:null}(r),t=e!="yahoo"?"q":"p",n={};if(!me(e)){n.$search_engine=e;var i=P?Fr(P.referrer,t):"";i.length&&(n.ph_keyword=i)}return n}function Qs(){return navigator.language||navigator.userLanguage}function da(){return P?.referrer||"$direct"}function ha(r,e){var t=r?kt([],Pt,e||[]):[],n=W?.href.substring(0,1e3);return{r:da().substring(0,1e3),u:n?or(n,t,ar):void 0}}function fa(r){var e,{r:t,u:n}=r,i={$referrer:t,$referring_domain:t==null?void 0:t=="$direct"?"$direct":(e=Tr(t))==null?void 0:e.host};if(n){i.$current_url=n;var s=Tr(n);i.$host=s?.host,i.$pathname=s?.pathname;var o=ua(n);U(i,o)}if(t){var a=pa(t);U(i,a)}return i}function ga(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function $c(){try{return new Date().getTimezoneOffset()}catch{return}}function Nc(r,e){if(!se)return{};var t,n,i,s=r?kt([],Pt,e||[]):[],[o,a]=function(l){for(var u=0;u<Ms.length;u++){var[c,p]=Ms[u],d=c.exec(l),h=d&&(ze(p)?p(d,l):p);if(h)return h}return["",""]}(se);return U(Hi({$os:o,$os_version:a,$browser:jo(se,navigator.vendor),$device:Rs(se),$device_type:(n=se,i=Rs(n),i===Eo||i===xo||i==="Kobo"||i==="Kindle Fire"||i===qo?Qt:i===tr||i===vt||i===rr||i===$n?"Console":i===Co?"Wearable":i?fe:"Desktop"),$timezone:ga(),$timezone_offset:$c()}),{$current_url:or(W?.href,s,ar),$host:W?.host,$pathname:W?.pathname,$raw_user_agent:se.length>1e3?se.substring(0,997)+"...":se,$browser_version:Hl(se,navigator.vendor),$browser_language:Qs(),$browser_language_prefix:(t=Qs(),typeof t=="string"?t.split("-")[0]:void 0),$screen_height:y?.screen.height,$screen_width:y?.screen.width,$viewport_height:y?.innerHeight,$viewport_width:y?.innerWidth,$lib:"web",$lib_version:Ie.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})}var je=L("[Web Vitals]"),eo=9e5,di=class{constructor(e){var t;this.kt=!1,this.P=!1,this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.Pt=()=>{clearTimeout(this.Tt),this.N.metrics.length!==0&&(this._instance.capture("$web_vitals",this.N.metrics.reduce((n,i)=>S({},n,{["$web_vitals_"+i.name+"_event"]:S({},i),["$web_vitals_"+i.name+"_value"]:i.value}),{})),this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.It=n=>{var i,s=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0);if(x(s))je.error("Could not read session ID. Dropping metrics!");else{this.N=this.N||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var o=this.Ct();x(o)||(O(n?.name)||O(n?.value)?je.error("Invalid metric received",n):this.Rt&&n.value>=this.Rt?je.error("Ignoring metric with value >= "+this.Rt,n):(this.N.url!==o&&(this.Pt(),this.Tt=setTimeout(this.Pt,this.flushToCaptureTimeoutMs)),x(this.N.url)&&(this.N.url=o),this.N.firstMetricTimestamp=x(this.N.firstMetricTimestamp)?Date.now():this.N.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0),this.N.metrics.push(S({},n,{$current_url:o,$session_id:s.sessionId,$window_id:s.windowId,timestamp:Date.now()})),this.N.metrics.length===this.allowedMetrics.length&&this.Pt()))}},this.rt=()=>{if(!this.P){var n,i,s,o,a=A.__PosthogExtensions__;x(a)||x(a.postHogWebVitalsCallbacks)||({onLCP:n,onCLS:i,onFCP:s,onINP:o}=a.postHogWebVitalsCallbacks),n&&i&&s&&o?(this.allowedMetrics.indexOf("LCP")>-1&&n(this.It.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&i(this.It.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&s(this.It.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&o(this.It.bind(this)),this.P=!0):je.error("web vitals callbacks not loaded - not starting")}},this._instance=e,this.kt=!((t=this._instance.persistence)==null||!t.props[js]),this.startIfEnabled()}get allowedMetrics(){var e,t,n=H(this._instance.config.capture_performance)?(e=this._instance.config.capture_performance)==null?void 0:e.web_vitals_allowed_metrics:void 0;return O(n)?((t=this._instance.persistence)==null?void 0:t.props[Ls])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(H(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var e=H(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_attribution:void 0;return e!=null&&e}get Rt(){var e=H(this._instance.config.capture_performance)&&$e(this._instance.config.capture_performance.__web_vitals_max_value)?this._instance.config.capture_performance.__web_vitals_max_value:eo;return 0<e&&e<=6e4?eo:e}get isEnabled(){var e=W?.protocol;if(e!=="http:"&&e!=="https:")return je.info("Web Vitals are disabled on non-http/https protocols"),!1;var t=H(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals:Oe(this._instance.config.capture_performance)?this._instance.config.capture_performance:void 0;return Oe(t)?t:this.kt}startIfEnabled(){this.isEnabled&&!this.P&&(je.info("enabled, starting..."),this.it(this.rt))}onRemoteConfig(e){var t=H(e.capturePerformance)&&!!e.capturePerformance.web_vitals,n=H(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[js]:t}),this._instance.persistence.register({[Ls]:n})),this.kt=t,this.startIfEnabled()}it(e){var t,n;if((t=A.__PosthogExtensions__)!=null&&t.postHogWebVitalsCallbacks)e();else{var i=this.useAttribution?"web-vitals-with-attribution":"web-vitals";(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,i,s=>{s?je.error("failed to load script",s):e()})}}Ct(){var e=y?y.location.href:void 0;if(e){var t=this._instance.config.mask_personal_data_properties,n=this._instance.config.custom_personal_data_properties,i=t?kt([],Pt,n||[]):[];return or(e,i,ar)}je.error("Could not determine current URL")}},Dc=L("[Heatmaps]");function to(r){return H(r)&&"clientX"in r&&"clientY"in r&&$e(r.clientX)&&$e(r.clientY)}var hi=class{constructor(e){var t;this.kt=!1,this.P=!1,this.Ft=null,this.instance=e,this.kt=!((t=this.instance.persistence)==null||!t.props[Bn]),this.rageclicks=new Rr(e.config.rageclick)}get flushIntervalMilliseconds(){var e=5e3;return H(this.instance.config.capture_heatmaps)&&this.instance.config.capture_heatmaps.flush_interval_milliseconds&&(e=this.instance.config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return O(this.instance.config.capture_heatmaps)?O(this.instance.config.enable_heatmaps)?this.kt:this.instance.config.enable_heatmaps:this.instance.config.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.P)return;Dc.info("starting..."),this.Ot(),this.Mt()}else{var e;clearInterval((e=this.Ft)!==null&&e!==void 0?e:void 0),this.At(),this.getAndClearBuffer()}}onRemoteConfig(e){var t=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Bn]:t}),this.kt=t,this.startIfEnabled()}getAndClearBuffer(){var e=this.N;return this.N=void 0,e}jt(e){this.Dt(e.originalEvent,"deadclick")}Mt(){this.Ft&&clearInterval(this.Ft),this.Ft=function(e){return e?.visibilityState==="visible"}(P)?setInterval(this.Lt.bind(this),this.flushIntervalMilliseconds):null}Ot(){y&&P&&(this.Nt=this.Lt.bind(this),z(y,"beforeunload",this.Nt),this.Ut=e=>this.Dt(e||y?.event),z(P,"click",this.Ut,{capture:!0}),this.zt=e=>this.Ht(e||y?.event),z(P,"mousemove",this.zt,{capture:!0}),this.Bt=new $r(this.instance,Ac,this.jt.bind(this)),this.Bt.startIfEnabled(),this.qt=this.Mt.bind(this),z(P,"visibilitychange",this.qt),this.P=!0)}At(){var e;y&&P&&(this.Nt&&y.removeEventListener("beforeunload",this.Nt),this.Ut&&P.removeEventListener("click",this.Ut,{capture:!0}),this.zt&&P.removeEventListener("mousemove",this.zt,{capture:!0}),this.qt&&P.removeEventListener("visibilitychange",this.qt),clearTimeout(this.Wt),(e=this.Bt)==null||e.stop(),this.P=!1)}Gt(e,t){var n=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),s=this.instance.scrollManager.scrollElement(),o=function(a,l,u){for(var c=a;c&&Br(c)&&!Ke(c,"body");){if(c===u)return!1;if(F(l,y?.getComputedStyle(c).position))return!0;c=Qo(c)}return!1}(Jo(e),["fixed","sticky"],s);return{x:e.clientX+(o?0:i),y:e.clientY+(o?0:n),target_fixed:o,type:t}}Dt(e,t){var n;if(t===void 0&&(t="click"),!Us(e.target)&&to(e)){var i=this.Gt(e,t);(n=this.rageclicks)!=null&&n.isRageClick(e.clientX,e.clientY,new Date().getTime())&&this.Vt(S({},i,{type:"rageclick"})),this.Vt(i)}}Ht(e){!Us(e.target)&&to(e)&&(clearTimeout(this.Wt),this.Wt=setTimeout(()=>{this.Vt(this.Gt(e,"mousemove"))},500))}Vt(e){if(y){var t=y.location.href,n=this.instance.config.mask_personal_data_properties,i=this.instance.config.custom_personal_data_properties,s=n?kt([],Pt,i||[]):[],o=or(t,s,ar);this.N=this.N||{},this.N[o]||(this.N[o]=[]),this.N[o].push(e)}}Lt(){this.N&&!gt(this.N)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},Nr=class{constructor(e){this.Jt=(t,n,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength)&&(E.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:t,changeReason:i}),this.Kt=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.Yt()}Yt(){var e;this.Xt=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.Jt)}destroy(){var e;(e=this.Xt)==null||e.call(this),this.Xt=void 0}doPageView(e,t){var n,i=this.Qt(e,t);return this.Kt={pathname:(n=y?.location.pathname)!==null&&n!==void 0?n:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),i}doPageLeave(e){var t;return this.Qt(e,(t=this.Kt)==null?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.Kt)==null?void 0:e.pageViewId}}Qt(e,t){var n=this.Kt;if(!n)return{$pageview_id:t};var i={$pageview_id:t,$prev_pageview_id:n.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:o,lastScrollY:a,maxScrollY:l,maxContentHeight:u,lastContentY:c,maxContentY:p}=s;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(p))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),p=Math.ceil(p);var d=o<=1?1:we(a/o,0,1,E),h=o<=1?1:we(l/o,0,1,E),g=u<=1?1:we(c/u,0,1,E),f=u<=1?1:we(p/u,0,1,E);i=U(i,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:d,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:g,$prev_pageview_max_content:p,$prev_pageview_max_content_percentage:f})}}return n.pathname&&(i.$prev_pageview_pathname=n.pathname),n.timestamp&&(i.$prev_pageview_duration=(e.getTime()-n.timestamp.getTime())/1e3),i}};var Te=function(r){return r.GZipJS="gzip-js",r.Base64="base64",r}({}),ge=Uint8Array,ne=Uint16Array,wt=Uint32Array,Xi=new ge([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Yi=new ge([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),ro=new ge([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ya=function(r,e){for(var t=new ne(31),n=0;n<31;++n)t[n]=e+=1<<r[n-1];var i=new wt(t[30]);for(n=1;n<30;++n)for(var s=t[n];s<t[n+1];++s)i[s]=s-t[n]<<5|n;return[t,i]},ma=ya(Xi,2),qc=ma[0],fi=ma[1];qc[28]=258,fi[258]=28;for(gi=ya(Yi,0)[1],Dr=new ne(32768),q=0;q<32768;++q)Ge=(43690&q)>>>1|(21845&q)<<1,Ge=(61680&(Ge=(52428&Ge)>>>2|(13107&Ge)<<2))>>>4|(3855&Ge)<<4,Dr[q]=((65280&Ge)>>>8|(255&Ge)<<8)>>>1;var Ge,gi,Dr,q,Yt=function(r,e,t){for(var n=r.length,i=0,s=new ne(e);i<n;++i)++s[r[i]-1];var o,a=new ne(e);for(i=0;i<e;++i)a[i]=a[i-1]+s[i-1]<<1;if(t){o=new ne(1<<e);var l=15-e;for(i=0;i<n;++i)if(r[i])for(var u=i<<4|r[i],c=e-r[i],p=a[r[i]-1]++<<c,d=p|(1<<c)-1;p<=d;++p)o[Dr[p]>>>l]=u}else for(o=new ne(n),i=0;i<n;++i)o[i]=Dr[a[r[i]-1]++]>>>15-r[i];return o},rt=new ge(288);for(q=0;q<144;++q)rt[q]=8;for(q=144;q<256;++q)rt[q]=9;for(q=256;q<280;++q)rt[q]=7;for(q=280;q<288;++q)rt[q]=8;var qr=new ge(32);for(q=0;q<32;++q)qr[q]=5;var jc=Yt(rt,9,0),Gc=Yt(qr,5,0),va=function(r){return(r/8>>0)+(7&r&&1)},_a=function(r,e,t){(t==null||t>r.length)&&(t=r.length);var n=new(r instanceof ne?ne:r instanceof wt?wt:ge)(t-e);return n.set(r.subarray(e,t)),n},Ce=function(r,e,t){t<<=7&e;var n=e/8>>0;r[n]|=t,r[n+1]|=t>>>8},Nt=function(r,e,t){t<<=7&e;var n=e/8>>0;r[n]|=t,r[n+1]|=t>>>8,r[n+2]|=t>>>16},_n=function(r,e){for(var t=[],n=0;n<r.length;++n)r[n]&&t.push({s:n,f:r[n]});var i=t.length,s=t.slice();if(!i)return[new ge(0),0];if(i==1){var o=new ge(t[0].s+1);return o[t[0].s]=1,[o,1]}t.sort(function(k,I){return k.f-I.f}),t.push({s:-1,f:25001});var a=t[0],l=t[1],u=0,c=1,p=2;for(t[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=i-1;)a=t[t[u].f<t[p].f?u++:p++],l=t[u!=c&&t[u].f<t[p].f?u++:p++],t[c++]={s:-1,f:a.f+l.f,l:a,r:l};var d=s[0].s;for(n=1;n<i;++n)s[n].s>d&&(d=s[n].s);var h=new ne(d+1),g=yi(t[c-1],h,0);if(g>e){n=0;var f=0,m=g-e,w=1<<m;for(s.sort(function(k,I){return h[I.s]-h[k.s]||k.f-I.f});n<i;++n){var b=s[n].s;if(!(h[b]>e))break;f+=w-(1<<g-h[b]),h[b]=e}for(f>>>=m;f>0;){var v=s[n].s;h[v]<e?f-=1<<e-h[v]++-1:++n}for(;n>=0&&f;--n){var _=s[n].s;h[_]==e&&(--h[_],++f)}g=e}return[new ge(h),g]},yi=function(r,e,t){return r.s==-1?Math.max(yi(r.l,e,t+1),yi(r.r,e,t+1)):e[r.s]=t},no=function(r){for(var e=r.length;e&&!r[--e];);for(var t=new ne(++e),n=0,i=r[0],s=1,o=function(l){t[n++]=l},a=1;a<=e;++a)if(r[a]==i&&a!=e)++s;else{if(!i&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(i),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(i);s=1,i=r[a]}return[t.subarray(0,n),e]},Dt=function(r,e){for(var t=0,n=0;n<e.length;++n)t+=r[n]*e[n];return t},mi=function(r,e,t){var n=t.length,i=va(e+2);r[i]=255&n,r[i+1]=n>>>8,r[i+2]=255^r[i],r[i+3]=255^r[i+1];for(var s=0;s<n;++s)r[i+s+4]=t[s];return 8*(i+4+n)},io=function(r,e,t,n,i,s,o,a,l,u,c){Ce(e,c++,t),++i[256];for(var p=_n(i,15),d=p[0],h=p[1],g=_n(s,15),f=g[0],m=g[1],w=no(d),b=w[0],v=w[1],_=no(f),k=_[0],I=_[1],M=new ne(19),C=0;C<b.length;++C)M[31&b[C]]++;for(C=0;C<k.length;++C)M[31&k[C]]++;for(var j=_n(M,7),V=j[0],Q=j[1],ee=19;ee>4&&!V[ro[ee-1]];--ee);var Y,ie,J,de,ye=u+5<<3,Se=Dt(i,rt)+Dt(s,qr)+o,ve=Dt(i,d)+Dt(s,f)+o+14+3*ee+Dt(M,V)+(2*M[16]+3*M[17]+7*M[18]);if(ye<=Se&&ye<=ve)return mi(e,c,r.subarray(l,l+u));if(Ce(e,c,1+(ve<Se)),c+=2,ve<Se){Y=Yt(d,h,0),ie=d,J=Yt(f,m,0),de=f;var Ne=Yt(V,Q,0);for(Ce(e,c,v-257),Ce(e,c+5,I-1),Ce(e,c+10,ee-4),c+=14,C=0;C<ee;++C)Ce(e,c+3*C,V[ro[C]]);c+=3*ee;for(var lt=[b,k],te=0;te<2;++te){var he=lt[te];for(C=0;C<he.length;++C){var oe=31&he[C];Ce(e,c,Ne[oe]),c+=V[oe],oe>15&&(Ce(e,c,he[C]>>>5&127),c+=he[C]>>>12)}}}else Y=jc,ie=rt,J=Gc,de=qr;for(C=0;C<a;++C)if(n[C]>255){oe=n[C]>>>18&31,Nt(e,c,Y[oe+257]),c+=ie[oe+257],oe>7&&(Ce(e,c,n[C]>>>23&31),c+=Xi[oe]);var ct=31&n[C];Nt(e,c,J[ct]),c+=de[ct],ct>3&&(Nt(e,c,n[C]>>>5&8191),c+=Yi[ct])}else Nt(e,c,Y[n[C]]),c+=ie[n[C]];return Nt(e,c,Y[256]),c+ie[256]},Lc=new wt([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Uc=function(){for(var r=new wt(256),e=0;e<256;++e){for(var t=e,n=9;--n;)t=(1&t&&3988292384)^t>>>1;r[e]=t}return r}(),Vc=function(r,e,t,n,i){return function(s,o,a,l,u,c){var p=s.length,d=new ge(l+p+5*(1+Math.floor(p/7e3))+u),h=d.subarray(l,d.length-u),g=0;if(!o||p<8)for(var f=0;f<=p;f+=65535){var m=f+65535;m<p?g=mi(h,g,s.subarray(f,m)):(h[f]=c,g=mi(h,g,s.subarray(f,p)))}else{for(var w=Lc[o-1],b=w>>>13,v=8191&w,_=(1<<a)-1,k=new ne(32768),I=new ne(_+1),M=Math.ceil(a/3),C=2*M,j=function(un){return(s[un]^s[un+1]<<M^s[un+2]<<C)&_},V=new wt(25e3),Q=new ne(288),ee=new ne(32),Y=0,ie=0,J=(f=0,0),de=0,ye=0;f<p;++f){var Se=j(f),ve=32767&f,Ne=I[Se];if(k[ve]=Ne,I[Se]=ve,de<=f){var lt=p-f;if((Y>7e3||J>24576)&&lt>423){g=io(s,h,0,V,Q,ee,ie,J,ye,f-ye,g),J=Y=ie=0,ye=f;for(var te=0;te<286;++te)Q[te]=0;for(te=0;te<30;++te)ee[te]=0}var he=2,oe=0,ct=v,De=ve-Ne&32767;if(lt>2&&Se==j(f-De))for(var ml=Math.min(b,lt)-1,vl=Math.min(32767,f),_l=Math.min(258,lt);De<=vl&&--ct&&ve!=Ne;){if(s[f+he]==s[f+he-De]){for(var qe=0;qe<_l&&s[f+qe]==s[f+qe-De];++qe);if(qe>he){if(he=qe,oe=De,qe>ml)break;var bl=Math.min(De,qe-2),ys=0;for(te=0;te<bl;++te){var cn=f-De+te+32768&32767,ms=cn-k[cn]+32768&32767;ms>ys&&(ys=ms,Ne=cn)}}}De+=(ve=Ne)-(Ne=k[ve])+32768&32767}if(oe){V[J++]=268435456|fi[he]<<18|gi[oe];var vs=31&fi[he],_s=31&gi[oe];ie+=Xi[vs]+Yi[_s],++Q[257+vs],++ee[_s],de=f+he,++Y}else V[J++]=s[f],++Q[s[f]]}}g=io(s,h,c,V,Q,ee,ie,J,ye,f-ye,g)}return _a(d,0,l+va(g)+u)}(r,e.level==null?6:e.level,e.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+e.mem,t,n,!0)},bn=function(r,e,t){for(;t;++e)r[e]=t,t>>>=8};function zc(r,e){e===void 0&&(e={});var t=function(){var a=4294967295;return{p:function(l){for(var u=a,c=0;c<l.length;++c)u=Uc[255&u^l[c]]^u>>>8;a=u},d:function(){return 4294967295^a}}}(),n=r.length;t.p(r);var i,s=Vc(r,e,10+((i=e).filename&&i.filename.length+1||0),8),o=s.length;return function(a,l){var u=l.filename;if(a[0]=31,a[1]=139,a[2]=8,a[8]=l.level<2?4:l.level==9?2:0,a[9]=3,l.mtime!=0&&bn(a,4,Math.floor(new Date(l.mtime||Date.now())/1e3)),u){a[3]=8;for(var c=0;c<=u.length;++c)a[c+10]=u.charCodeAt(c)}}(s,e),bn(s,o-8,t.d()),bn(s,o-4,n),s}var Hc=function(r){var e,t,n,i,s="";for(e=t=0,n=(r=(r+"").replace(/\r\n/g,`
8
+ "use strict";var PaymentKit=(()=>{var yr=Object.defineProperty;var Cl=Object.getOwnPropertyDescriptor;var Al=Object.getOwnPropertyNames;var Il=Object.prototype.hasOwnProperty;var wi=r=>{throw TypeError(r)};var Ml=(r,e,t)=>e in r?yr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Rl=(r,e)=>{for(var t in e)yr(r,t,{get:e[t],enumerable:!0})},Tl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Al(e))!Il.call(r,s)&&s!==t&&yr(r,s,{get:()=>e[s],enumerable:!(n=Cl(e,s))||n.enumerable});return r};var Fl=r=>Tl(yr({},"__esModule",{value:!0}),r);var R=(r,e,t)=>Ml(r,typeof e!="symbol"?e+"":e,t),Pi=(r,e,t)=>e.has(r)||wi("Cannot "+t);var T=(r,e,t)=>(Pi(r,e,"read from private field"),t?t.call(r):e.get(r)),ee=(r,e,t)=>e.has(r)?wi("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),ke=(r,e,t,n)=>(Pi(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t);var zp={};Rl(zp,{PaymentMethods:()=>Vp,default:()=>Up});var xi="0.5.15";var Ft=class{constructor(){R(this,"events",[]);R(this,"distinctId",null)}identify(e){this.distinctId=e}capture(e,t){this.events.push({event:e,distinct_id:this.distinctId,properties:t,timestamp:Date.now()})}isInitialized(){return!0}getEvents(){return[...this.events]}getEventsByName(e){return this.events.filter(t=>t.event===e)}clear(){this.events=[]}};var y=typeof window<"u"?window:void 0,Z=typeof globalThis<"u"?globalThis:y;typeof self>"u"&&(Z.self=Z),typeof File>"u"&&(Z.File=function(){});var ko=Array.prototype,Ei=ko.forEach,Si=ko.indexOf,le=Z?.navigator,P=Z?.document,J=Z?.location,Mn=Z?.fetch,Rn=Z!=null&&Z.XMLHttpRequest&&"withCredentials"in new Z.XMLHttpRequest?Z.XMLHttpRequest:void 0,Ci=Z?.AbortController,ie=le?.userAgent,A=y??{},Me={DEBUG:!1,LIB_VERSION:"1.341.0"};function Ai(r,e,t,n,s,i,o){try{var a=r[i](o),l=a.value}catch(u){return void t(u)}a.done?e(l):Promise.resolve(l).then(n,s)}function gt(r){return function(){var e=this,t=arguments;return new Promise(function(n,s){var i=r.apply(e,t);function o(l){Ai(i,n,s,o,a,"next",l)}function a(l){Ai(i,n,s,o,a,"throw",l)}o(void 0)})}}function C(){return C=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)({}).hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r},C.apply(null,arguments)}function wo(r,e){if(r==null)return{};var t={};for(var n in r)if({}.hasOwnProperty.call(r,n)){if(e.indexOf(n)!==-1)continue;t[n]=r[n]}return t}var $l=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Ii=function(r,e){if(e===void 0&&(e=[]),!r)return!1;var t=r.toLowerCase();return $l.concat(e).some(n=>{var s=n.toLowerCase();return t.indexOf(s)!==-1})},Nl=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"];function F(r,e){return r.indexOf(e)!==-1}var Hr=function(r){return r.trim()},Tn=function(r){return r.replace(/^\$/,"")},Dl=Array.isArray,Po=Object.prototype,xo=Po.hasOwnProperty,Br=Po.toString,N=Dl||function(r){return Br.call(r)==="[object Array]"},Ke=r=>typeof r=="function",H=r=>r===Object(r)&&!N(r),yt=r=>{if(H(r)){for(var e in r)if(xo.call(r,e))return!1;return!0}return!1},x=r=>r===void 0,B=r=>Br.call(r)=="[object String]",Fn=r=>B(r)&&r.trim().length===0,_e=r=>r===null,$=r=>x(r)||_e(r),Ne=r=>Br.call(r)=="[object Number]"&&r==r,ht=r=>Ne(r)&&r>0,$e=r=>Br.call(r)==="[object Boolean]",ql=r=>r instanceof FormData,jl=r=>F(Nl,r);function On(r){return r===null||typeof r!="object"}function xr(r,e){return Object.prototype.toString.call(r)==="[object "+e+"]"}function Eo(r){return!x(Event)&&function(e,t){try{return e instanceof t}catch{return!1}}(r,Event)}var Gl=[!0,"true",1,"1","yes"],hn=r=>F(Gl,r),Ll=[!1,"false",0,"0","no"];function Pe(r,e,t,n,s){return e>t&&(n.warn("min cannot be greater than max."),e=t),Ne(r)?r>t?(n.warn(" cannot be greater than max: "+t+". Using max value instead."),t):r<e?(n.warn(" cannot be less than min: "+e+". Using min value instead."),e):r:(n.warn(" must be a number. using max or fallback. max: "+t+", fallback: "+s),Pe(s||t,e,t,n))}var $n=class{constructor(e){this.t={},this.i=e.i,this.o=Pe(e.bucketSize,0,100,e.h),this.m=Pe(e.refillRate,0,this.o,e.h),this.$=Pe(e.refillInterval,0,864e5,e.h)}S(e,t){var n=t-e.lastAccess,s=Math.floor(n/this.$);if(s>0){var i=s*this.m;e.tokens=Math.min(e.tokens+i,this.o),e.lastAccess=e.lastAccess+s*this.$}}consumeRateLimit(e){var t,n=Date.now(),s=String(e),i=this.t[s];return i?this.S(i,n):(i={tokens:this.o,lastAccess:n},this.t[s]=i),i.tokens===0||(i.tokens--,i.tokens===0&&((t=this.i)==null||t.call(this,e)),i.tokens===0)}stop(){this.t={}}},fe="Mobile",Er="iOS",Oe="Android",er="Tablet",So=Oe+" "+er,Co="iPad",Ao="Apple",Io=Ao+" Watch",tr="Safari",bt="BlackBerry",Mo="Samsung",Ro=Mo+"Browser",To=Mo+" Internet",tt="Chrome",Ul=tt+" OS",Fo=tt+" "+Er,Vs="Internet Explorer",Oo=Vs+" "+fe,zs="Opera",Vl=zs+" Mini",Ks="Edge",$o="Microsoft "+Ks,vt="Firefox",No=vt+" "+Er,rr="Nintendo",nr="PlayStation",_t="Xbox",Do=Oe+" "+fe,qo=fe+" "+tr,Vt="Windows",Nn=Vt+" Phone",Mi="Nokia",Dn="Ouya",jo="Generic",zl=jo+" "+fe.toLowerCase(),Go=jo+" "+er.toLowerCase(),qn="Konqueror",ne="(\\d+(\\.\\d+)?)",fn=new RegExp("Version/"+ne),Kl=new RegExp(_t,"i"),Hl=new RegExp(nr+" \\w+","i"),Bl=new RegExp(rr+" \\w+","i"),Hs=new RegExp(bt+"|PlayBook|BB10","i"),Wl={"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"},mr,Ri,gn,Xl=(r,e)=>e&&F(e,Ao)||function(t){return F(t,tr)&&!F(t,tt)&&!F(t,Oe)}(r),Lo=function(r,e){return e=e||"",F(r," OPR/")&&F(r,"Mini")?Vl:F(r," OPR/")?zs:Hs.test(r)?bt:F(r,"IE"+fe)||F(r,"WPDesktop")?Oo:F(r,Ro)?To:F(r,Ks)||F(r,"Edg/")?$o:F(r,"FBIOS")?"Facebook "+fe:F(r,"UCWEB")||F(r,"UCBrowser")?"UC Browser":F(r,"CriOS")?Fo:F(r,"CrMo")||F(r,tt)?tt:F(r,Oe)&&F(r,tr)?Do:F(r,"FxiOS")?No:F(r.toLowerCase(),qn.toLowerCase())?qn:Xl(r,e)?F(r,fe)?qo:tr:F(r,vt)?vt:F(r,"MSIE")||F(r,"Trident/")?Vs:F(r,"Gecko")?vt:""},Yl={[Oo]:[new RegExp("rv:"+ne)],[$o]:[new RegExp(Ks+"?\\/"+ne)],[tt]:[new RegExp("("+tt+"|CrMo)\\/"+ne)],[Fo]:[new RegExp("CriOS\\/"+ne)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+ne)],[tr]:[fn],[qo]:[fn],[zs]:[new RegExp("(Opera|OPR)\\/"+ne)],[vt]:[new RegExp(vt+"\\/"+ne)],[No]:[new RegExp("FxiOS\\/"+ne)],[qn]:[new RegExp("Konqueror[:/]?"+ne,"i")],[bt]:[new RegExp(bt+" "+ne),fn],[Do]:[new RegExp("android\\s"+ne,"i")],[To]:[new RegExp(Ro+"\\/"+ne)],[Vs]:[new RegExp("(rv:|MSIE )"+ne)],Mozilla:[new RegExp("rv:"+ne)]},Jl=function(r,e){var t=Lo(r,e),n=Yl[t];if(x(n))return null;for(var s=0;s<n.length;s++){var i=n[s],o=r.match(i);if(o)return parseFloat(o[o.length-2])}return null},Ti=[[new RegExp(_t+"; "+_t+" (.*?)[);]","i"),r=>[_t,r&&r[1]||""]],[new RegExp(rr,"i"),[rr,""]],[new RegExp(nr,"i"),[nr,""]],[Hs,[bt,""]],[new RegExp(Vt,"i"),(r,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Nn,""];if(new RegExp(fe).test(e)&&!/IEMobile\b/.test(e))return[Vt+" "+fe,""];var t=/Windows NT ([0-9.]+)/i.exec(e);if(t&&t[1]){var n=t[1],s=Wl[n]||"";return/arm/i.test(e)&&(s="RT"),[Vt,s]}return[Vt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,r=>{if(r&&r[3]){var e=[r[3],r[4],r[5]||"0"];return[Er,e.join(".")]}return[Er,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,r=>{var e="";return r&&r.length>=3&&(e=x(r[2])?r[3]:r[2]),["watchOS",e]}],[new RegExp("("+Oe+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Oe+")","i"),r=>{if(r&&r[2]){var e=[r[2],r[3],r[4]||"0"];return[Oe,e.join(".")]}return[Oe,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,r=>{var e=["Mac OS X",""];if(r&&r[1]){var t=[r[1],r[2],r[3]||"0"];e[1]=t.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Ul,""]],[/Linux|debian/i,["Linux",""]]],Fi=function(r){return Bl.test(r)?rr:Hl.test(r)?nr:Kl.test(r)?_t:new RegExp(Dn,"i").test(r)?Dn:new RegExp("("+Nn+"|WPDesktop)","i").test(r)?Nn:/iPad/.test(r)?Co:/iPod/.test(r)?"iPod Touch":/iPhone/.test(r)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(r)?Io:Hs.test(r)?bt:/(kobo)\s(ereader|touch)/i.test(r)?"Kobo":new RegExp(Mi,"i").test(r)?Mi:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(r)||/(kf[a-z]+)( bui|\)).+silk\//i.test(r)?"Kindle Fire":/(Android|ZTE)/i.test(r)?new RegExp(fe).test(r)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(r)||/pixel[\daxl ]{1,6}/i.test(r)&&!/pixel c/i.test(r)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(r)||/lmy47v/i.test(r)&&!/QTAQZ3/i.test(r)?Oe:So:new RegExp("(pda|"+fe+")","i").test(r)?zl:new RegExp(er,"i").test(r)&&!new RegExp(er+" pc","i").test(r)?Go:""},Zl=r=>r instanceof Error;function Ql(r){var e=globalThis._posthogChunkIds;if(e){var t=Object.keys(e);return gn&&t.length===Ri||(Ri=t.length,gn=t.reduce((n,s)=>{mr||(mr={});var i=mr[s];if(i)n[i[0]]=i[1];else for(var o=r(s),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[s];if(u&&c){n[u]=c,mr[s]=[u,c];break}}return n},{})),gn}}var jn=class{constructor(e,t,n){n===void 0&&(n=[]),this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t){t===void 0&&(t={});var n=t&&t.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(n,t,0).apply(e),i=this.buildParsingContext(),o=this.parseStacktrace(s,i);return{$exception_list:this.convertToExceptionList(o,n),$exception_level:"error"}}modifyFrames(e){var t=this;return gt(function*(){for(var n of e)n.stacktrace&&n.stacktrace.frames&&N(n.stacktrace.frames)&&(n.stacktrace.frames=yield t.applyModifiers(n.stacktrace.frames));return e})()}coerceFallback(e){var t;return{type:"Error",value:"Unknown error",stack:(t=e.syntheticException)==null?void 0:t.stack,synthetic:!0}}parseStacktrace(e,t){var n,s;return e.cause!=null&&(n=this.parseStacktrace(e.cause,t)),e.stack!=""&&e.stack!=null&&(s=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?1:0),t.chunkIdMap)),C({},e,{cause:n,stack:s})}applyChunkIds(e,t){return e.map(n=>(n.filename&&t&&(n.chunk_id=t[n.filename]),n))}applyCoercers(e,t){for(var n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}applyModifiers(e){var t=this;return gt(function*(){var n=e;for(var s of t.modifiers)n=yield s(n);return n})()}convertToExceptionList(e,t){var n,s,i,o={type:e.type,value:e.value,mechanism:{type:(n=t.type)!==null&&n!==void 0?n:"generic",handled:(s=t.handled)===null||s===void 0||s,synthetic:(i=e.synthetic)!==null&&i!==void 0&&i}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,C({},t,{handled:!0}))),a}buildParsingContext(){return{chunkIdMap:Ql(this.stackParser)}}buildCoercingContext(e,t,n){n===void 0&&(n=0);var s=(i,o)=>{if(o<=4){var a=this.buildCoercingContext(e,t,o);return this.applyCoercers(i,a)}};return C({},t,{syntheticException:n==0?t.syntheticException:void 0,mechanism:e,apply:i=>s(i,n),next:i=>s(i,n+1)})}},kt="?";function Gn(r,e,t,n,s){var i={platform:r,filename:e,function:t==="<anonymous>"?kt:t,in_app:!0};return x(n)||(i.lineno=n),x(s)||(i.colno=s),i}var Uo=(r,e)=>{var t=r.indexOf("safari-extension")!==-1,n=r.indexOf("safari-web-extension")!==-1;return t||n?[r.indexOf("@")!==-1?r.split("@")[0]:kt,t?"safari-extension:"+e:"safari-web-extension:"+e]:[r,e]},ec=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,tc=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,rc=/\((\S*)(?::(\d+))(?::(\d+))\)/,nc=(r,e)=>{var t=ec.exec(r);if(t){var[,n,s,i]=t;return Gn(e,n,kt,+s,+i)}var o=tc.exec(r);if(o){if(o[2]&&o[2].indexOf("eval")===0){var a=rc.exec(o[2]);a&&(o[2]=a[1],o[3]=a[2],o[4]=a[3])}var[l,u]=Uo(o[1]||kt,o[2]);return Gn(e,u,l,o[3]?+o[3]:void 0,o[4]?+o[4]:void 0)}},sc=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ic=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,oc=(r,e)=>{var t=sc.exec(r);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){var n=ic.exec(t[3]);n&&(t[1]=t[1]||"eval",t[3]=n[1],t[4]=n[2],t[5]="")}var s=t[3],i=t[1]||kt;return[i,s]=Uo(i,s),Gn(e,s,i,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}},Oi=/\(error: (.*)\)/,$i=50;function ac(){return function(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),n=1;n<e;n++)t[n-1]=arguments[n];return function(s,i){i===void 0&&(i=0);for(var o=[],a=s.split(`
9
+ `),l=i;l<a.length;l++){var u=a[l];if(!(u.length>1024)){var c=Oi.test(u)?u.replace(Oi,"$1"):u;if(!c.match(/\S*Error: /)){for(var p of t){var d=p(c,r);if(d){o.push(d);break}}if(o.length>=$i)break}}}return function(h){if(!h.length)return[];var g=Array.from(h);return g.reverse(),g.slice(0,$i).map(f=>{return C({},f,{filename:f.filename||(m=g,m[m.length-1]||{}).filename,function:f.function||kt});var m})}(o)}}("web:javascript",nc,oc)}var Ln=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){var n=B(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:n?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?t+": "+e.message:t}isDOMException(e){return xr(e,"DOMException")}isDOMError(e){return xr(e,"DOMError")}},Un=class{match(e){return(t=>t instanceof Error)(e)}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){var n=e.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(e){return e.stacktrace||e.stack||void 0}},Vn=class{constructor(){}match(e){return xr(e,"ErrorEvent")&&e.error!=null}coerce(e,t){var n,s=t.apply(e.error);return s||{type:"ErrorEvent",value:e.message,stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}},lc=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,zn=class{match(e){return typeof e=="string"}coerce(e,t){var n,[s,i]=this.getInfos(e);return{type:s??"Error",value:i??e,stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}getInfos(e){var t="Error",n=e,s=e.match(lc);return s&&(t=s[1],n=s[2]),[t,n]}},cc=["fatal","error","warning","log","info","debug"];function Vo(r,e){e===void 0&&(e=40);var t=Object.keys(r);if(t.sort(),!t.length)return"[object has no keys]";for(var n=t.length;n>0;n--){var s=t.slice(0,n).join(", ");if(!(s.length>e))return n===t.length||s.length<=e?s:s.slice(0,e)+"..."}return""}var Kn=class{match(e){return typeof e=="object"&&e!==null}coerce(e,t){var n,s=this.getErrorPropertyFromObject(e);return s?t.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(n=t.syntheticException)==null?void 0:n.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Eo(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var t="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(t+=" with message: '"+e.message+"'"),t}if("message"in e&&typeof e.message=="string")return e.message;var n=this.getObjectClassName(e);return(n&&n!=="Object"?"'"+n+"'":"Object")+" captured as exception with keys: "+Vo(e)}isSeverityLevel(e){return B(e)&&!Fn(e)&&cc.indexOf(e)>=0}getErrorPropertyFromObject(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t)){var n=e[t];if(Zl(n))return n}}getObjectClassName(e){try{var t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}},Hn=class{match(e){return Eo(e)}coerce(e,t){var n,s=e.constructor.name;return{type:s,value:s+" captured as exception with keys: "+Vo(e),stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}},Bn=class{match(e){return On(e)}coerce(e,t){var n;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}},Wn=class{match(e){return xr(e,"PromiseRejectionEvent")}coerce(e,t){var n,s=this.getUnhandledRejectionReason(e);return On(s)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(s),stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}:t.apply(s)}getUnhandledRejectionReason(e){if(On(e))return e;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch{}return e}},zo=function(r,e){var{debugEnabled:t}=e===void 0?{}:e,n={k:function(s){if(y&&(Me.DEBUG||A.POSTHOG_DEBUG||t)&&!x(y.console)&&y.console){for(var i=("__rrweb_original__"in y.console[s])?y.console[s].__rrweb_original__:y.console[s],o=arguments.length,a=new Array(o>1?o-1:0),l=1;l<o;l++)a[l-1]=arguments[l];i(r,...a)}},info:function(){for(var s=arguments.length,i=new Array(s),o=0;o<s;o++)i[o]=arguments[o];n.k("log",...i)},warn:function(){for(var s=arguments.length,i=new Array(s),o=0;o<s;o++)i[o]=arguments[o];n.k("warn",...i)},error:function(){for(var s=arguments.length,i=new Array(s),o=0;o<s;o++)i[o]=arguments[o];n.k("error",...i)},critical:function(){for(var s=arguments.length,i=new Array(s),o=0;o<s;o++)i[o]=arguments[o];console.error(r,...i)},uninitializedWarning:s=>{n.error("You must initialize PostHog before calling "+s)},createLogger:(s,i)=>zo(r+" "+s,i)};return n},E=zo("[PostHog.js]"),L=E.createLogger,uc=L("[ExternalScriptsLoader]"),Ni=(r,e,t)=>{if(r.config.disable_external_dependency_loading)return uc.warn(e+" was requested but loading of external scripts is disabled."),t("Loading of external scripts is disabled");var n=P?.querySelectorAll("script");if(n){for(var s,i=function(){if(n[o].src===e){var l=n[o];return l.__posthog_loading_callback_fired?{v:t()}:(l.addEventListener("load",u=>{l.__posthog_loading_callback_fired=!0,t(void 0,u)}),l.onerror=u=>t(u),{v:void 0})}},o=0;o<n.length;o++)if(s=i())return s.v}var a=()=>{if(!P)return t("document not found");var l=P.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=p=>{l.__posthog_loading_callback_fired=!0,t(void 0,p)},l.onerror=p=>t(p),r.config.prepare_external_dependency_script&&(l=r.config.prepare_external_dependency_script(l)),!l)return t("prepare_external_dependency_script returned null");if(r.config.external_scripts_inject_target==="head")P.head.appendChild(l);else{var u,c=P.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):P.body.appendChild(l)}};P!=null&&P.body?a():P?.addEventListener("DOMContentLoaded",a)};A.__PosthogExtensions__=A.__PosthogExtensions__||{},A.__PosthogExtensions__.loadExternalDependency=(r,e,t)=>{var n="/static/"+e+".js?v="+r.version;if(e==="remote-config"&&(n="/array/"+r.config.token+"/config.js"),e==="toolbar"){var s=3e5;n=n+"&t="+Math.floor(Date.now()/s)*s}var i=r.requestRouter.endpointFor("assets",n);Ni(r,i,t)},A.__PosthogExtensions__.loadSiteApp=(r,e,t)=>{var n=r.requestRouter.endpointFor("api",e);Ni(r,n,t)};var Sr={};function He(r,e,t){if(N(r)){if(Ei&&r.forEach===Ei)r.forEach(e,t);else if("length"in r&&r.length===+r.length){for(var n=0,s=r.length;n<s;n++)if(n in r&&e.call(t,r[n],n)===Sr)return}}}function q(r,e,t){if(!$(r)){if(N(r))return He(r,e,t);if(ql(r)){for(var n of r.entries())if(e.call(t,n[1],n[0])===Sr)return}else for(var s in r)if(xo.call(r,s)&&e.call(t,r[s],s)===Sr)return}}var U=function(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),n=1;n<e;n++)t[n-1]=arguments[n];return He(t,function(s){for(var i in s)s[i]!==void 0&&(r[i]=s[i])}),r},Pt=function(r){for(var e=arguments.length,t=new Array(e>1?e-1:0),n=1;n<e;n++)t[n-1]=arguments[n];return He(t,function(s){He(s,function(i){r.push(i)})}),r};function wr(r){for(var e=Object.keys(r),t=e.length,n=new Array(t);t--;)n[t]=[e[t],r[e[t]]];return n}var Di=function(r){try{return r()}catch{return}},pc=function(r){return function(){try{for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return r.apply(this,t)}catch(s){E.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),E.critical(s)}}},Bs=function(r){var e={};return q(r,function(t,n){(B(t)&&t.length>0||Ne(t))&&(e[n]=t)}),e};function dc(r,e){return t=r,n=i=>B(i)&&!_e(e)?i.slice(0,e):i,s=new Set,function i(o,a){return o!==Object(o)?n?n(o,a):o:s.has(o)?void 0:(s.add(o),N(o)?(l=[],He(o,u=>{l.push(i(u))})):(l={},q(o,(u,c)=>{s.has(u)||(l[c]=i(u,c))})),l);var l}(t);var t,n,s}var hc=["herokuapp.com","vercel.app","netlify.app"];function fc(r){var e=r?.hostname;if(!B(e))return!1;var t=e.split(".").slice(-2).join(".");for(var n of hc)if(t===n)return!1;return!0}function Ko(r,e){for(var t=0;t<r.length;t++)if(e(r[t]))return r[t]}function K(r,e,t,n){var{capture:s=!1,passive:i=!0}=n??{};r?.addEventListener(e,t,{capture:s,passive:i})}var Ho="$people_distinct_id",zt="__alias",Kt="__timers",qi="$autocapture_disabled_server_side",Xn="$heatmaps_enabled_server_side",ji="$exception_capture_enabled_server_side",Yn="$error_tracking_suppression_rules",Gi="$error_tracking_capture_extension_exceptions",Li="$web_vitals_enabled_server_side",Bo="$dead_clicks_enabled_server_side",Ui="$product_tours_enabled_server_side",Vi="$web_vitals_allowed_metrics",yn="$session_recording_remote_config",Cr="$sesid",Wo="$session_is_sampled",mt="$enabled_feature_flags",Ht="$early_access_features",Jn="$feature_flag_details",Bt="$stored_person_properties",et="$stored_group_properties",Zn="$surveys",Ar="$flag_call_reported",Re="$user_state",Qn="$client_session_props",es="$capture_rate_limit",ts="$initial_campaign_params",rs="$initial_referrer_info",Ir="$initial_person_info",Mr="$epp",Xo="__POSTHOG_TOOLBAR__",Ot="$posthog_cookieless",gc=[Ho,zt,"__cmpns",Kt,"$session_recording_enabled_server_side",Xn,Cr,mt,Yn,Re,Ht,Jn,et,Bt,Zn,Ar,Qn,es,ts,rs,Mr,Ir,"$conversations_widget_session_id","$conversations_ticket_id","$conversations_widget_state","$conversations_user_traits"];function zi(r){return r instanceof Element&&(r.id===Xo||!(r.closest==null||!r.closest(".toolbar-global-fade-container")))}function Wr(r){return!!r&&r.nodeType===1}function Be(r,e){return!!r&&!!r.tagName&&r.tagName.toLowerCase()===e.toLowerCase()}function Yo(r){return!!r&&r.nodeType===3}function Jo(r){return!!r&&r.nodeType===11}function Ws(r){return r?Hr(r).split(/\s+/):[]}function Ki(r){var e=y?.location.href;return!!(e&&r&&r.some(t=>e.match(t)))}function Rr(r){var e="";switch(typeof r.className){case"string":e=r.className;break;case"object":e=(r.className&&"baseVal"in r.className?r.className.baseVal:null)||r.getAttribute("class")||"";break;default:e=""}return Ws(e)}function Zo(r){return $(r)?null:Hr(r).split(/(\s+)/).filter(e=>sr(e)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function or(r){var e="";return ns(r)&&!na(r)&&r.childNodes&&r.childNodes.length&&q(r.childNodes,function(t){var n;Yo(t)&&t.textContent&&(e+=(n=Zo(t.textContent))!==null&&n!==void 0?n:"")}),Hr(e)}function Qo(r){return x(r.target)?r.srcElement||null:(e=r.target)!=null&&e.shadowRoot?r.composedPath()[0]||null:r.target||null;var e}var Xs=["a","button","form","input","select","textarea","label"];function ea(r,e){if(x(e))return!0;var t,n=function(i){if(e.some(o=>i.matches(o)))return{v:!0}};for(var s of r)if(t=n(s))return t.v;return!1}function ta(r){var e=r.parentNode;return!(!e||!Wr(e))&&e}var yc=["next","previous","prev",">","<"],Hi=10,Bi=[".ph-no-rageclick",".ph-no-capture"];function mc(r,e){if(!y||Ys(r))return!1;var t,n,s;if($e(e)?(t=!!e&&Bi,n=void 0):(t=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:Bi,n=e?.content_ignorelist),t===!1)return!1;var{targetElementList:i}=ra(r,!1);return!function(o,a){if(o===!1||x(o))return!1;var l;if(o===!0)l=yc;else{if(!N(o))return!1;if(o.length>Hi)return E.error("[PostHog] content_ignorelist array cannot exceed "+Hi+" items. Use css_selector_ignorelist for more complex matching."),!1;l=o.map(u=>u.toLowerCase())}return a.some(u=>{var{safeText:c,ariaLabel:p}=u;return l.some(d=>c.includes(d)||p.includes(d))})}(n,i.map(o=>{var a;return{safeText:or(o).toLowerCase(),ariaLabel:((a=o.getAttribute("aria-label"))==null?void 0:a.toLowerCase().trim())||""}}))&&!ea(i,t)}var Ys=r=>!r||Be(r,"html")||!Wr(r),ra=(r,e)=>{if(!y||Ys(r))return{parentIsUsefulElement:!1,targetElementList:[]};for(var t=!1,n=[r],s=r;s.parentNode&&!Be(s,"body");)if(Jo(s.parentNode))n.push(s.parentNode.host),s=s.parentNode.host;else{var i=ta(s);if(!i)break;if(e||Xs.indexOf(i.tagName.toLowerCase())>-1)t=!0;else{var o=y.getComputedStyle(i);o&&o.getPropertyValue("cursor")==="pointer"&&(t=!0)}n.push(i),s=i}return{parentIsUsefulElement:t,targetElementList:n}};function vc(r,e,t,n,s){var i,o,a,l;if(t===void 0&&(t=void 0),!y||Ys(r)||(i=t)!=null&&i.url_allowlist&&!Ki(t.url_allowlist)||(o=t)!=null&&o.url_ignorelist&&Ki(t.url_ignorelist))return!1;if((a=t)!=null&&a.dom_event_allowlist){var u=t.dom_event_allowlist;if(u&&!u.some(g=>e.type===g))return!1}var{parentIsUsefulElement:c,targetElementList:p}=ra(r,n);if(!function(g,f){var m=f?.element_allowlist;if(x(m))return!0;var w,b=function(_){if(m.some(k=>_.tagName.toLowerCase()===k))return{v:!0}};for(var v of g)if(w=b(v))return w.v;return!1}(p,t)||!ea(p,(l=t)==null?void 0:l.css_selector_allowlist))return!1;var d=y.getComputedStyle(r);if(d&&d.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;var h=r.tagName.toLowerCase();switch(h){case"html":return!1;case"form":return(s||["submit"]).indexOf(e.type)>=0;case"input":case"select":case"textarea":return(s||["change","click"]).indexOf(e.type)>=0;default:return c?(s||["click"]).indexOf(e.type)>=0:(s||["click"]).indexOf(e.type)>=0&&(Xs.indexOf(h)>-1||r.getAttribute("contenteditable")==="true")}}function ns(r){for(var e=r;e.parentNode&&!Be(e,"body");e=e.parentNode){var t=Rr(e);if(F(t,"ph-sensitive")||F(t,"ph-no-capture"))return!1}if(F(Rr(r),"ph-include"))return!0;var n=r.type||"";if(B(n))switch(n.toLowerCase()){case"hidden":case"password":return!1}var s=r.name||r.id||"";return!(B(s)&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(s.replace(/[^a-zA-Z0-9]/g,"")))}function na(r){return!!(Be(r,"input")&&!["button","checkbox","submit","reset"].includes(r.type)||Be(r,"select")||Be(r,"textarea")||r.getAttribute("contenteditable")==="true")}var sa="(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})",_c=new RegExp("^(?:"+sa+")$"),bc=new RegExp(sa),ia="\\d{3}-?\\d{2}-?\\d{4}",kc=new RegExp("^("+ia+")$"),wc=new RegExp("("+ia+")");function sr(r,e){return e===void 0&&(e=!0),!($(r)||B(r)&&(r=Hr(r),(e?_c:bc).test((r||"").replace(/[- ]/g,""))||(e?kc:wc).test(r)))}function oa(r){var e=or(r);return sr(e=(e+" "+aa(r)).trim())?e:""}function aa(r){var e="";return r&&r.childNodes&&r.childNodes.length&&q(r.childNodes,function(t){var n;if(t&&((n=t.tagName)==null?void 0:n.toLowerCase())==="span")try{var s=or(t);e=(e+" "+s).trim(),t.childNodes&&t.childNodes.length&&(e=(e+" "+aa(t)).trim())}catch(i){E.error("[AutoCapture]",i)}}),e}function Pc(r){return function(e){var t=e.map(n=>{var s,i,o="";if(n.tag_name&&(o+=n.tag_name),n.attr_class)for(var a of(n.attr_class.sort(),n.attr_class))o+="."+a.replace(/"/g,"");var l=C({},n.text?{text:n.text}:{},{"nth-child":(s=n.nth_child)!==null&&s!==void 0?s:0,"nth-of-type":(i=n.nth_of_type)!==null&&i!==void 0?i:0},n.href?{href:n.href}:{},n.attr_id?{attr_id:n.attr_id}:{},n.attributes),u={};return wr(l).sort((c,p)=>{var[d]=c,[h]=p;return d.localeCompare(h)}).forEach(c=>{var[p,d]=c;return u[Wi(p.toString())]=Wi(d.toString())}),o+=":",o+=wr(u).map(c=>{var[p,d]=c;return p+'="'+d+'"'}).join("")});return t.join(";")}(function(e){return e.map(t=>{var n,s,i={text:(n=t.$el_text)==null?void 0:n.slice(0,400),tag_name:t.tag_name,href:(s=t.attr__href)==null?void 0:s.slice(0,2048),attr_class:xc(t),attr_id:t.attr__id,nth_child:t.nth_child,nth_of_type:t.nth_of_type,attributes:{}};return wr(t).filter(o=>{var[a]=o;return a.indexOf("attr__")===0}).forEach(o=>{var[a,l]=o;return i.attributes[a]=l}),i})}(r))}function Wi(r){return r.replace(/"|\\"/g,'\\"')}function xc(r){var e=r.attr__class;return e?N(e)?e:Ws(e):void 0}var Tr=class{constructor(e){this.disabled=e===!1;var t=H(e)?e:{};this.thresholdPx=t.threshold_px||30,this.timeoutMs=t.timeout_ms||1e3,this.clickCount=t.click_count||3,this.clicks=[]}isRageClick(e,t,n){if(this.disabled)return!1;var s=this.clicks[this.clicks.length-1];if(s&&Math.abs(e-s.x)+Math.abs(t-s.y)<this.thresholdPx&&n-s.timestamp<this.timeoutMs){if(this.clicks.push({x:e,y:t,timestamp:n}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:t,timestamp:n}];return!1}},Fr=r=>{var e=P?.createElement("a");return x(e)?null:(e.href=r,e)},Ec=function(r,e){var t,n;e===void 0&&(e="&");var s=[];return q(r,function(i,o){x(i)||x(o)||o==="undefined"||(t=encodeURIComponent((a=>a instanceof File)(i)?i.name:i.toString()),n=encodeURIComponent(o),s[s.length]=n+"="+t)}),s.join(e)},Or=function(r,e){for(var t,n=((r.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),s=0;s<n.length;s++){var i=n[s].split("=");if(i[0]===e){t=i;break}}if(!N(t)||t.length<2)return"";var o=t[1];try{o=decodeURIComponent(o)}catch{E.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},ar=function(r,e,t){if(!r||!e||!e.length)return r;for(var n=r.split("#"),s=n[0]||"",i=n[1],o=s.split("?"),a=o[1],l=o[0],u=(a||"").split("&"),c=[],p=0;p<u.length;p++){var d=u[p].split("=");N(d)&&(e.includes(d[0])?c.push(d[0]+"="+t):c.push(u[p]))}var h=l;return a!=null&&(h+="?"+c.join("&")),i!=null&&(h+="#"+i),h},$r=function(r,e){var t=r.match(new RegExp(e+"=([^&]*)"));return t?t[1]:null},mn="$copy_autocapture",Xi=L("[AutoCapture]");function vn(r,e){return e.length>r?e.slice(0,r)+"...":e}function Sc(r){if(r.previousElementSibling)return r.previousElementSibling;var e=r;do e=e.previousSibling;while(e&&!Wr(e));return e}function Cc(r,e,t,n){var s=r.tagName.toLowerCase(),i={tag_name:s};Xs.indexOf(s)>-1&&!t&&(s.toLowerCase()==="a"||s.toLowerCase()==="button"?i.$el_text=vn(1024,oa(r)):i.$el_text=vn(1024,or(r)));var o=Rr(r);o.length>0&&(i.classes=o.filter(function(c){return c!==""})),q(r.attributes,function(c){var p;if((!na(r)||["name","id","class","aria-label"].indexOf(c.name)!==-1)&&(n==null||!n.includes(c.name))&&!e&&sr(c.value)&&(p=c.name,!B(p)||p.substring(0,10)!=="_ngcontent"&&p.substring(0,7)!=="_nghost")){var d=c.value;c.name==="class"&&(d=Ws(d).join(" ")),i["attr__"+c.name]=vn(1024,d)}});for(var a=1,l=1,u=r;u=Sc(u);)a++,u.tagName===r.tagName&&l++;return i.nth_child=a,i.nth_of_type=l,i}function Ac(r,e){for(var t,n,{e:s,maskAllElementAttributes:i,maskAllText:o,elementAttributeIgnoreList:a,elementsChainAsString:l}=e,u=[r],c=r;c.parentNode&&!Be(c,"body");)Jo(c.parentNode)?(u.push(c.parentNode.host),c=c.parentNode.host):(u.push(c.parentNode),c=c.parentNode);var p,d=[],h={},g=!1,f=!1;if(q(u,_=>{var k=ns(_);_.tagName.toLowerCase()==="a"&&(g=_.getAttribute("href"),g=k&&g&&sr(g)&&g),F(Rr(_),"ph-no-capture")&&(f=!0),d.push(Cc(_,i,o,a));var M=function(I){if(!ns(I))return{};var S={};return q(I.attributes,function(O){if(O.name&&O.name.indexOf("data-ph-capture-attribute")===0){var V=O.name.replace("data-ph-capture-attribute-",""),W=O.value;V&&W&&sr(W)&&(S[V]=W)}}),S}(_);U(h,M)}),f)return{props:{},explicitNoCapture:f};if(o||(r.tagName.toLowerCase()==="a"||r.tagName.toLowerCase()==="button"?d[0].$el_text=oa(r):d[0].$el_text=or(r)),g){var m,w;d[0].attr__href=g;var b=(m=Fr(g))==null?void 0:m.host,v=y==null||(w=y.location)==null?void 0:w.host;b&&v&&b!==v&&(p=g)}return{props:U({$event_type:s.type,$ce_version:1},l?{}:{$elements:d},{$elements_chain:Pc(d)},(t=d[0])!=null&&t.$el_text?{$el_text:(n=d[0])==null?void 0:n.$el_text}:{},p&&s.type==="click"?{$external_click_url:p}:{},h)}}var ss=class{constructor(e){this.P=!1,this.T=null,this.I=!1,this.instance=e,this.rageclicks=new Tr(e.config.rageclick),this.C=null}get R(){var e,t,n=H(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(e=n.url_allowlist)==null?void 0:e.map(s=>new RegExp(s)),n.url_ignorelist=(t=n.url_ignorelist)==null?void 0:t.map(s=>new RegExp(s)),n}F(){if(this.isBrowserSupported()){if(y&&P){var e=n=>{n=n||y?.event;try{this.O(n)}catch(s){Xi.error("Failed to capture event",s)}};if(K(P,"submit",e,{capture:!0}),K(P,"change",e,{capture:!0}),K(P,"click",e,{capture:!0}),this.R.capture_copied_text){var t=n=>{n=n||y?.event,this.O(n,mn)};K(P,"copy",t,{capture:!0}),K(P,"cut",t,{capture:!0})}}}else Xi.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.P&&(this.F(),this.P=!0)}onRemoteConfig(e){e.elementsChainAsString&&(this.I=e.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[qi]:!!e.autocapture_opt_out}),this.T=!!e.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(e){this.C=e}getElementSelectors(e){var t,n=[];return(t=this.C)==null||t.forEach(s=>{var i=P?.querySelectorAll(s);i?.forEach(o=>{e===o&&n.push(s)})}),n}get isEnabled(){var e,t,n=(e=this.instance.persistence)==null?void 0:e.props[qi],s=this.T;if(_e(s)&&!$e(n)&&!this.instance.M())return!1;var i=(t=this.T)!==null&&t!==void 0?t:!!n;return!!this.instance.config.autocapture&&!i}O(e,t){if(t===void 0&&(t="$autocapture"),this.isEnabled){var n,s=Qo(e);Yo(s)&&(s=s.parentNode||null),t==="$autocapture"&&e.type==="click"&&e instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(e.clientX,e.clientY,e.timeStamp||new Date().getTime())&&mc(s,this.instance.config.rageclick)&&this.O(e,"$rageclick");var i=t===mn;if(s&&vc(s,e,this.R,i,i?["copy","cut"]:void 0)){var{props:o,explicitNoCapture:a}=Ac(s,{e,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.R.element_attribute_ignorelist,elementsChainAsString:this.I});if(a)return!1;var l=this.getElementSelectors(s);if(l&&l.length>0&&(o.$element_selectors=l),t===mn){var u,c=Zo(y==null||(u=y.getSelection())==null?void 0:u.toString()),p=e.type||"clipboard";if(!c)return!1;o.$selected_content=c,o.$copy_type=p}return this.instance.capture(t,o),!0}}}isBrowserSupported(){return Ke(P?.querySelectorAll)}};Math.trunc||(Math.trunc=function(r){return r<0?Math.ceil(r):Math.floor(r)}),Number.isInteger||(Number.isInteger=function(r){return Ne(r)&&isFinite(r)&&Math.floor(r)===r});var Yi="0123456789abcdef",is=class r{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,n,s){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(s)||e<0||t<0||n<0||s<0||e>0xffffffffffff||t>4095||n>1073741823||s>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|t>>>8,i[7]=t,i[8]=128|n>>>24,i[9]=n>>>16,i[10]=n>>>8,i[11]=n,i[12]=s>>>24,i[13]=s>>>16,i[14]=s>>>8,i[15]=s,new r(i)}toString(){for(var e="",t=0;t<this.bytes.length;t++)e=e+Yi.charAt(this.bytes[t]>>>4)+Yi.charAt(15&this.bytes[t]),t!==3&&t!==5&&t!==7&&t!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new r(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var t=0;t<16;t++){var n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}},os=class{constructor(){this.A=0,this.j=0,this.D=new as}generate(){var e=this.generateOrAbort();if(x(e)){this.A=0;var t=this.generateOrAbort();if(x(t))throw new Error("Could not generate UUID after timestamp reset");return t}return e}generateOrAbort(){var e=Date.now();if(e>this.A)this.A=e,this.L();else{if(!(e+1e4>this.A))return;this.j++,this.j>4398046511103&&(this.A++,this.L())}return is.fromFieldsV7(this.A,Math.trunc(this.j/Math.pow(2,30)),this.j&Math.pow(2,30)-1,this.D.nextUint32())}L(){this.j=1024*this.D.nextUint32()+(1023&this.D.nextUint32())}},Ji,la=r=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;e<r.length;e++)r[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return r};y&&!x(y.crypto)&&crypto.getRandomValues&&(la=r=>crypto.getRandomValues(r));var as=class{constructor(){this.N=new Uint32Array(8),this.U=1/0}nextUint32(){return this.U>=this.N.length&&(la(this.N),this.U=0),this.N[this.U++]}},ze=()=>Ic().toString(),Ic=()=>(Ji||(Ji=new os)).generate(),$t="",Mc=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function Rc(r,e){if(e){var t=function(s,i){if(i===void 0&&(i=P),$t)return $t;if(!i||["localhost","127.0.0.1"].includes(s))return"";for(var o=s.split("."),a=Math.min(o.length,8),l="dmn_chk_"+ze();!$t&&a--;){var u=o.slice(a).join("."),c=l+"=1;domain=."+u+";path=/";i.cookie=c+";max-age=3",i.cookie.includes(l)&&(i.cookie=c+";max-age=0",$t=u)}return $t}(r);if(!t){var n=(s=>{var i=s.match(Mc);return i?i[0]:""})(r);n!==t&&E.info("Warning: cookie subdomain discovery mismatch",n,t),t=n}return t?"; domain=."+t:""}return""}var we={H:()=>!!P,B:function(r){E.error("cookieStore error: "+r)},q:function(r){if(P){try{for(var e=r+"=",t=P.cookie.split(";").filter(i=>i.length),n=0;n<t.length;n++){for(var s=t[n];s.charAt(0)==" ";)s=s.substring(1,s.length);if(s.indexOf(e)===0)return decodeURIComponent(s.substring(e.length,s.length))}}catch{}return null}},W:function(r){var e;try{e=JSON.parse(we.q(r))||{}}catch{}return e},G:function(r,e,t,n,s){if(P)try{var i="",o="",a=Rc(P.location.hostname,n);if(t){var l=new Date;l.setTime(l.getTime()+24*t*60*60*1e3),i="; expires="+l.toUTCString()}s&&(o="; secure");var u=r+"="+encodeURIComponent(JSON.stringify(e))+i+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&E.warn("cookieStore warning: large cookie, len="+u.length),P.cookie=u,u}catch{return}},V:function(r,e){if(P!=null&&P.cookie)try{we.G(r,"",-1,e)}catch{return}}},_n=null,G={H:function(){if(!_e(_n))return _n;var r=!0;if(x(y))r=!1;else try{var e="__mplssupport__";G.G(e,"xyz"),G.q(e)!=='"xyz"'&&(r=!1),G.V(e)}catch{r=!1}return r||E.error("localStorage unsupported; falling back to cookie store"),_n=r,r},B:function(r){E.error("localStorage error: "+r)},q:function(r){try{return y?.localStorage.getItem(r)}catch(e){G.B(e)}return null},W:function(r){try{return JSON.parse(G.q(r))||{}}catch{}return null},G:function(r,e){try{y?.localStorage.setItem(r,JSON.stringify(e))}catch(t){G.B(t)}},V:function(r){try{y?.localStorage.removeItem(r)}catch(e){G.B(e)}}},Tc=["$device_id","distinct_id",Cr,Wo,Mr,Ir],vr={},Fc={H:function(){return!0},B:function(r){E.error("memoryStorage error: "+r)},q:function(r){return vr[r]||null},W:function(r){return vr[r]||null},G:function(r,e){vr[r]=e},V:function(r){delete vr[r]}},Ze=null,Y={H:function(){if(!_e(Ze))return Ze;if(Ze=!0,x(y))Ze=!1;else try{var r="__support__";Y.G(r,"xyz"),Y.q(r)!=='"xyz"'&&(Ze=!1),Y.V(r)}catch{Ze=!1}return Ze},B:function(r){E.error("sessionStorage error: ",r)},q:function(r){try{return y?.sessionStorage.getItem(r)}catch(e){Y.B(e)}return null},W:function(r){try{return JSON.parse(Y.q(r))||null}catch{}return null},G:function(r,e){try{y?.sessionStorage.setItem(r,JSON.stringify(e))}catch(t){Y.B(t)}},V:function(r){try{y?.sessionStorage.removeItem(r)}catch(e){Y.B(e)}}},Te=function(r){return r[r.PENDING=-1]="PENDING",r[r.DENIED=0]="DENIED",r[r.GRANTED=1]="GRANTED",r}({}),ls=class{constructor(e){this._instance=e}get R(){return this._instance.config}get consent(){return this.J()?Te.DENIED:this.K}isOptedOut(){return this.R.cookieless_mode==="always"||this.consent===Te.DENIED||this.consent===Te.PENDING&&(this.R.opt_out_capturing_by_default||this.R.cookieless_mode==="on_reject")}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===Te.DENIED}optInOut(e){this.Y.G(this.X,e?1:0,this.R.cookie_expiration,this.R.cross_subdomain_cookie,this.R.secure_cookie)}reset(){this.Y.V(this.X,this.R.cross_subdomain_cookie)}get X(){var{token:e,opt_out_capturing_cookie_prefix:t,consent_persistence_name:n}=this._instance.config;return n||(t?t+e:"__ph_opt_in_out_"+e)}get K(){var e=this.Y.q(this.X);return hn(e)?Te.GRANTED:F(Ll,e)?Te.DENIED:Te.PENDING}get Y(){if(!this.Z){var e=this.R.opt_out_capturing_persistence_type;this.Z=e==="localStorage"?G:we;var t=e==="localStorage"?we:G;t.q(this.X)&&(this.Z.q(this.X)||this.optInOut(hn(t.q(this.X))),t.V(this.X,this.R.cross_subdomain_cookie))}return this.Z}J(){return!!this.R.respect_dnt&&!!Ko([le?.doNotTrack,le?.msDoNotTrack,A.doNotTrack],e=>hn(e))}},_r=L("[Dead Clicks]"),Oc=()=>!0,$c=r=>{var e,t=!((e=r.instance.persistence)==null||!e.get_property(Bo)),n=r.instance.config.capture_dead_clicks;return $e(n)?n:!!H(n)||t},Nr=class{get lazyLoadedDeadClicksAutocapture(){return this.tt}constructor(e,t,n){this.instance=e,this.isEnabled=t,this.onCapture=n,this.startIfEnabled()}onRemoteConfig(e){this.instance.persistence&&this.instance.persistence.register({[Bo]:e?.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.it(()=>{this.et()})}it(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.initDeadClicksAutocapture&&e(),(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this.instance,"dead-clicks-autocapture",s=>{s?_r.error("failed to load script",s):e()})}et(){var e;if(P){if(!this.tt&&(e=A.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var t=H(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};t.__onCapture=this.onCapture,this.tt=A.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,t),this.tt.start(P),_r.info("starting...")}}else _r.error("`document` not found. Cannot start.")}stop(){this.tt&&(this.tt.stop(),this.tt=void 0,_r.info("stopping..."))}},Nt=L("[ExceptionAutocapture]"),cs=class{constructor(e){var t,n,s;this.rt=()=>{var i;if(y&&this.isEnabled&&(i=A.__PosthogExtensions__)!=null&&i.errorWrappingFunctions){var o=A.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,a=A.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,l=A.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.st&&this.R.capture_unhandled_errors&&(this.st=o(this.captureException.bind(this))),!this.nt&&this.R.capture_unhandled_rejections&&(this.nt=a(this.captureException.bind(this))),!this.ot&&this.R.capture_console_errors&&(this.ot=l(this.captureException.bind(this)))}catch(u){Nt.error("failed to start",u),this.ut()}}},this._instance=e,this.ht=!((t=this._instance.persistence)==null||!t.props[ji]),this.dt=new $n({refillRate:(n=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:1,bucketSize:(s=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10,refillInterval:1e4,h:Nt}),this.R=this.vt(),this.startIfEnabledOrStop()}vt(){var e=this._instance.config.capture_exceptions,t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return H(e)?t=C({},t,e):(x(e)?this.ht:e)&&(t=C({},t,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),t}get isEnabled(){return this.R.capture_console_errors||this.R.capture_unhandled_errors||this.R.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Nt.info("enabled"),this.ut(),this.it(this.rt)):this.ut()}it(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.errorWrappingFunctions&&e(),(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",s=>{if(s)return Nt.error("failed to load script",s);e()})}ut(){var e,t,n;(e=this.st)==null||e.call(this),this.st=void 0,(t=this.nt)==null||t.call(this),this.nt=void 0,(n=this.ot)==null||n.call(this),this.ot=void 0}onRemoteConfig(e){var t=e.autocaptureExceptions;this.ht=!!t||!1,this._instance.persistence&&this._instance.persistence.register({[ji]:this.ht}),this.R=this.vt(),this.startIfEnabledOrStop()}onConfigChange(){this.R=this.vt()}captureException(e){var t,n,s=(t=e==null||(n=e.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&t!==void 0?t:"Exception";this.dt.consumeRateLimit(s)?Nt.info("Skipping exception capture because of client rate limiting.",{exception:s}):this._instance.exceptions.sendExceptionEvent(e)}};function Zi(r,e,t){try{if(!(e in r))return()=>{};var n=r[e],s=t(n);return Ke(s)&&(s.prototype=s.prototype||{},Object.defineProperties(s,{__posthog_wrapped__:{enumerable:!1,value:!0}})),r[e]=s,()=>{r[e]=n}}catch{return()=>{}}}var us=class{constructor(e){var t;this._instance=e,this.ct=(y==null||(t=y.location)==null?void 0:t.pathname)||""}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(E.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.ft&&this.ft(),this.ft=void 0,E.info("History API monitoring stopped")}monitorHistoryChanges(){var e,t;if(y&&y.history){var n=this;(e=y.history.pushState)!=null&&e.__posthog_wrapped__||Zi(y.history,"pushState",s=>function(i,o,a){s.call(this,i,o,a),n._t("pushState")}),(t=y.history.replaceState)!=null&&t.__posthog_wrapped__||Zi(y.history,"replaceState",s=>function(i,o,a){s.call(this,i,o,a),n._t("replaceState")}),this.bt()}}_t(e){try{var t,n=y==null||(t=y.location)==null?void 0:t.pathname;if(!n)return;n!==this.ct&&this.isEnabled&&this._instance.capture("$pageview",{navigation_type:e}),this.ct=n}catch(s){E.error("Error capturing "+e+" pageview",s)}}bt(){if(!this.ft){var e=()=>{this._t("popstate")};K(y,"popstate",e),this.ft=()=>{y&&y.removeEventListener("popstate",e)}}}},bn=L("[SegmentIntegration]");function Nc(r,e){var t=r.config.segment;if(!t)return e();(function(n,s){var i=n.config.segment;if(!i)return s();var o=l=>{var u=()=>l.anonymousId()||ze();n.config.get_device_id=u,l.id()&&(n.register({distinct_id:l.id(),$device_id:u()}),n.persistence.set_property(Re,"identified")),s()},a=i.user();"then"in a&&Ke(a.then)?a.then(o):o(a)})(r,()=>{t.register((n=>{Promise&&Promise.resolve||bn.warn("This browser does not have Promise support, and can not use the segment integration");var s=(i,o)=>{if(!o)return i;i.event.userId||i.event.anonymousId===n.get_distinct_id()||(bn.info("No userId set, resetting PostHog"),n.reset()),i.event.userId&&i.event.userId!==n.get_distinct_id()&&(bn.info("UserId set, identifying with PostHog"),n.identify(i.event.userId));var a=n.calculateEventProperties(o,i.event.properties);return i.event.properties=Object.assign({},a,i.event.properties),i};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:i=>s(i,i.event.event),page:i=>s(i,"$pageview"),identify:i=>s(i,"$identify"),screen:i=>s(i,"$screen")}})(r)).then(()=>{e()})})}var ca="posthog-js";function ua(r,e){var{organization:t,projectId:n,prefix:s,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}=e===void 0?{}:e;return a=>{var l,u,c,p,d;if(!(i==="*"||i.includes(a.level))||!r.__loaded)return a;a.tags||(a.tags={});var h=r.requestRouter.endpointFor("ui","/project/"+r.config.token+"/person/"+r.get_distinct_id());a.tags["PostHog Person URL"]=h,r.sessionRecordingStarted()&&(a.tags["PostHog Recording URL"]=r.get_session_replay_url({withTimestamp:!0}));var g=((l=a.exception)==null?void 0:l.values)||[],f=g.map(w=>C({},w,{stacktrace:w.stacktrace?C({},w.stacktrace,{type:"raw",frames:(w.stacktrace.frames||[]).map(b=>C({},b,{platform:"web:javascript"}))}):void 0})),m={$exception_message:((u=g[0])==null?void 0:u.value)||a.message,$exception_type:(c=g[0])==null?void 0:c.type,$exception_level:a.level,$exception_list:f,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:((p=g[0])==null?void 0:p.value)||a.message,$sentry_exception_type:(d=g[0])==null?void 0:d.type,$sentry_tags:a.tags};return t&&n&&(m.$sentry_url=(s||"https://sentry.io/organizations/")+t+"/issues/?project="+n+"&query="+a.event_id),o&&r.exceptions.sendExceptionEvent(m),a}}var ps=class{constructor(e,t,n,s,i,o){this.name=ca,this.setupOnce=function(a){a(ua(e,{organization:t,projectId:n,prefix:s,severityAllowList:i,sendExceptionsToPostHog:o==null||o}))}}},Dc=y!=null&&y.location?$r(y.location.hash,"__posthog")||$r(location.hash,"state"):null,Qi="_postHogToolbarParams",eo=L("[Toolbar]"),Ve=function(r){return r[r.UNINITIALIZED=0]="UNINITIALIZED",r[r.LOADING=1]="LOADING",r[r.LOADED=2]="LOADED",r}(Ve||{}),ds=class{constructor(e){this.instance=e}yt(e){A.ph_toolbar_state=e}wt(){var e;return(e=A.ph_toolbar_state)!==null&&e!==void 0?e:Ve.UNINITIALIZED}maybeLoadToolbar(e,t,n){if(e===void 0&&(e=void 0),t===void 0&&(t=void 0),n===void 0&&(n=void 0),!y||!P)return!1;e=e??y.location,n=n??y.history;try{if(!t){try{y.localStorage.setItem("test","test"),y.localStorage.removeItem("test")}catch{return!1}t=y?.localStorage}var s,i=Dc||$r(e.hash,"__posthog")||$r(e.hash,"state"),o=i?Di(()=>JSON.parse(atob(decodeURIComponent(i))))||Di(()=>JSON.parse(decodeURIComponent(i))):null;return o&&o.action==="ph_authorize"?((s=o).source="url",s&&Object.keys(s).length>0&&(o.desiredHash?e.hash=o.desiredHash:n?n.replaceState(n.state,"",e.pathname+e.search):e.hash="")):((s=JSON.parse(t.getItem(Qi)||"{}")).source="localstorage",delete s.userIntent),!(!s.token||this.instance.config.token!==s.token)&&(this.loadToolbar(s),!0)}catch{return!1}}xt(e){var t=A.ph_load_toolbar||A.ph_load_editor;!$(t)&&Ke(t)?t(e,this.instance):eo.warn("No toolbar load function found")}loadToolbar(e){var t=!(P==null||!P.getElementById(Xo));if(!y||t)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,s=C({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(y.localStorage.setItem(Qi,JSON.stringify(C({},s,{source:void 0}))),this.wt()===Ve.LOADED)this.xt(s);else if(this.wt()===Ve.UNINITIALIZED){var i;this.yt(Ve.LOADING),(i=A.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"toolbar",o=>{if(o)return eo.error("[Toolbar] Failed to load",o),void this.yt(Ve.UNINITIALIZED);this.yt(Ve.LOADED),this.xt(s)}),K(y,"turbolinks:load",()=>{this.yt(Ve.UNINITIALIZED),this.loadToolbar(s)})}return!0}Et(e){return this.loadToolbar(e)}maybeLoadEditor(e,t,n){return e===void 0&&(e=void 0),t===void 0&&(t=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(e,t,n)}},qc=L("[TracingHeaders]"),hs=class{constructor(e){this.$t=void 0,this.St=void 0,this.rt=()=>{var t,n;x(this.$t)&&((t=A.__PosthogExtensions__)==null||(t=t.tracingHeadersPatchFns)==null||t._patchXHR(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager)),x(this.St)&&((n=A.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null||n._patchFetch(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=e}it(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.tracingHeadersPatchFns&&e(),(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",s=>{if(s)return qc.error("failed to load script",s);e()})}startIfEnabledOrStop(){var e,t;this._instance.config.__add_tracing_headers?this.it(this.rt):((e=this.$t)==null||e.call(this),(t=this.St)==null||t.call(this),this.$t=void 0,this.St=void 0)}},br="https?://(.*)",xt=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],jc=Pt(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],xt),lr="<masked>",Gc=["li_fat_id"];function pa(r,e,t){if(!P)return{};var n,s=e?Pt([],xt,t||[]):[],i=da(ar(P.URL,s,lr),r),o=(n={},q(Gc,function(a){var l=we.q(a);n[a]=l||null}),n);return U(o,i)}function da(r,e){var t=jc.concat(e||[]),n={};return q(t,function(s){var i=Or(r,s);n[s]=i||null}),n}function ha(r){var e=function(i){return i?i.search(br+"google.([^/?]*)")===0?"google":i.search(br+"bing.com")===0?"bing":i.search(br+"yahoo.com")===0?"yahoo":i.search(br+"duckduckgo.com")===0?"duckduckgo":null:null}(r),t=e!="yahoo"?"q":"p",n={};if(!_e(e)){n.$search_engine=e;var s=P?Or(P.referrer,t):"";s.length&&(n.ph_keyword=s)}return n}function to(){return navigator.language||navigator.userLanguage}function fa(){return P?.referrer||"$direct"}function ga(r,e){var t=r?Pt([],xt,e||[]):[],n=J?.href.substring(0,1e3);return{r:fa().substring(0,1e3),u:n?ar(n,t,lr):void 0}}function ya(r){var e,{r:t,u:n}=r,s={$referrer:t,$referring_domain:t==null?void 0:t=="$direct"?"$direct":(e=Fr(t))==null?void 0:e.host};if(n){s.$current_url=n;var i=Fr(n);s.$host=i?.host,s.$pathname=i?.pathname;var o=da(n);U(s,o)}if(t){var a=ha(t);U(s,a)}return s}function ma(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Lc(){try{return new Date().getTimezoneOffset()}catch{return}}function Uc(r,e){if(!ie)return{};var t,n,s,i=r?Pt([],xt,e||[]):[],[o,a]=function(l){for(var u=0;u<Ti.length;u++){var[c,p]=Ti[u],d=c.exec(l),h=d&&(Ke(p)?p(d,l):p);if(h)return h}return["",""]}(ie);return U(Bs({$os:o,$os_version:a,$browser:Lo(ie,navigator.vendor),$device:Fi(ie),$device_type:(n=ie,s=Fi(n),s===Co||s===So||s==="Kobo"||s==="Kindle Fire"||s===Go?er:s===rr||s===_t||s===nr||s===Dn?"Console":s===Io?"Wearable":s?fe:"Desktop"),$timezone:ma(),$timezone_offset:Lc()}),{$current_url:ar(J?.href,i,lr),$host:J?.host,$pathname:J?.pathname,$raw_user_agent:ie.length>1e3?ie.substring(0,997)+"...":ie,$browser_version:Jl(ie,navigator.vendor),$browser_language:to(),$browser_language_prefix:(t=to(),typeof t=="string"?t.split("-")[0]:void 0),$screen_height:y?.screen.height,$screen_width:y?.screen.width,$viewport_height:y?.innerHeight,$viewport_width:y?.innerWidth,$lib:"web",$lib_version:Me.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})}var Ge=L("[Web Vitals]"),ro=9e5,fs=class{constructor(e){var t;this.kt=!1,this.P=!1,this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.Pt=()=>{clearTimeout(this.Tt),this.N.metrics.length!==0&&(this._instance.capture("$web_vitals",this.N.metrics.reduce((n,s)=>C({},n,{["$web_vitals_"+s.name+"_event"]:C({},s),["$web_vitals_"+s.name+"_value"]:s.value}),{})),this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.It=n=>{var s,i=(s=this._instance.sessionManager)==null?void 0:s.checkAndGetSessionAndWindowId(!0);if(x(i))Ge.error("Could not read session ID. Dropping metrics!");else{this.N=this.N||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var o=this.Ct();x(o)||($(n?.name)||$(n?.value)?Ge.error("Invalid metric received",n):this.Rt&&n.value>=this.Rt?Ge.error("Ignoring metric with value >= "+this.Rt,n):(this.N.url!==o&&(this.Pt(),this.Tt=setTimeout(this.Pt,this.flushToCaptureTimeoutMs)),x(this.N.url)&&(this.N.url=o),this.N.firstMetricTimestamp=x(this.N.firstMetricTimestamp)?Date.now():this.N.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0),this.N.metrics.push(C({},n,{$current_url:o,$session_id:i.sessionId,$window_id:i.windowId,timestamp:Date.now()})),this.N.metrics.length===this.allowedMetrics.length&&this.Pt()))}},this.rt=()=>{if(!this.P){var n,s,i,o,a=A.__PosthogExtensions__;x(a)||x(a.postHogWebVitalsCallbacks)||({onLCP:n,onCLS:s,onFCP:i,onINP:o}=a.postHogWebVitalsCallbacks),n&&s&&i&&o?(this.allowedMetrics.indexOf("LCP")>-1&&n(this.It.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&s(this.It.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&i(this.It.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&o(this.It.bind(this)),this.P=!0):Ge.error("web vitals callbacks not loaded - not starting")}},this._instance=e,this.kt=!((t=this._instance.persistence)==null||!t.props[Li]),this.startIfEnabled()}get allowedMetrics(){var e,t,n=H(this._instance.config.capture_performance)?(e=this._instance.config.capture_performance)==null?void 0:e.web_vitals_allowed_metrics:void 0;return $(n)?((t=this._instance.persistence)==null?void 0:t.props[Vi])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(H(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var e=H(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_attribution:void 0;return e!=null&&e}get Rt(){var e=H(this._instance.config.capture_performance)&&Ne(this._instance.config.capture_performance.__web_vitals_max_value)?this._instance.config.capture_performance.__web_vitals_max_value:ro;return 0<e&&e<=6e4?ro:e}get isEnabled(){var e=J?.protocol;if(e!=="http:"&&e!=="https:")return Ge.info("Web Vitals are disabled on non-http/https protocols"),!1;var t=H(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals:$e(this._instance.config.capture_performance)?this._instance.config.capture_performance:void 0;return $e(t)?t:this.kt}startIfEnabled(){this.isEnabled&&!this.P&&(Ge.info("enabled, starting..."),this.it(this.rt))}onRemoteConfig(e){var t=H(e.capturePerformance)&&!!e.capturePerformance.web_vitals,n=H(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Li]:t}),this._instance.persistence.register({[Vi]:n})),this.kt=t,this.startIfEnabled()}it(e){var t,n;if((t=A.__PosthogExtensions__)!=null&&t.postHogWebVitalsCallbacks)e();else{var s=this.useAttribution?"web-vitals-with-attribution":"web-vitals";(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,s,i=>{i?Ge.error("failed to load script",i):e()})}}Ct(){var e=y?y.location.href:void 0;if(e){var t=this._instance.config.mask_personal_data_properties,n=this._instance.config.custom_personal_data_properties,s=t?Pt([],xt,n||[]):[];return ar(e,s,lr)}Ge.error("Could not determine current URL")}},Vc=L("[Heatmaps]");function no(r){return H(r)&&"clientX"in r&&"clientY"in r&&Ne(r.clientX)&&Ne(r.clientY)}var gs=class{constructor(e){var t;this.kt=!1,this.P=!1,this.Ft=null,this.instance=e,this.kt=!((t=this.instance.persistence)==null||!t.props[Xn]),this.rageclicks=new Tr(e.config.rageclick)}get flushIntervalMilliseconds(){var e=5e3;return H(this.instance.config.capture_heatmaps)&&this.instance.config.capture_heatmaps.flush_interval_milliseconds&&(e=this.instance.config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return $(this.instance.config.capture_heatmaps)?$(this.instance.config.enable_heatmaps)?this.kt:this.instance.config.enable_heatmaps:this.instance.config.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.P)return;Vc.info("starting..."),this.Ot(),this.Mt()}else{var e;clearInterval((e=this.Ft)!==null&&e!==void 0?e:void 0),this.At(),this.getAndClearBuffer()}}onRemoteConfig(e){var t=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Xn]:t}),this.kt=t,this.startIfEnabled()}getAndClearBuffer(){var e=this.N;return this.N=void 0,e}jt(e){this.Dt(e.originalEvent,"deadclick")}Mt(){this.Ft&&clearInterval(this.Ft),this.Ft=function(e){return e?.visibilityState==="visible"}(P)?setInterval(this.Lt.bind(this),this.flushIntervalMilliseconds):null}Ot(){y&&P&&(this.Nt=this.Lt.bind(this),K(y,"beforeunload",this.Nt),this.Ut=e=>this.Dt(e||y?.event),K(P,"click",this.Ut,{capture:!0}),this.zt=e=>this.Ht(e||y?.event),K(P,"mousemove",this.zt,{capture:!0}),this.Bt=new Nr(this.instance,Oc,this.jt.bind(this)),this.Bt.startIfEnabled(),this.qt=this.Mt.bind(this),K(P,"visibilitychange",this.qt),this.P=!0)}At(){var e;y&&P&&(this.Nt&&y.removeEventListener("beforeunload",this.Nt),this.Ut&&P.removeEventListener("click",this.Ut,{capture:!0}),this.zt&&P.removeEventListener("mousemove",this.zt,{capture:!0}),this.qt&&P.removeEventListener("visibilitychange",this.qt),clearTimeout(this.Wt),(e=this.Bt)==null||e.stop(),this.P=!1)}Gt(e,t){var n=this.instance.scrollManager.scrollY(),s=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),o=function(a,l,u){for(var c=a;c&&Wr(c)&&!Be(c,"body");){if(c===u)return!1;if(F(l,y?.getComputedStyle(c).position))return!0;c=ta(c)}return!1}(Qo(e),["fixed","sticky"],i);return{x:e.clientX+(o?0:s),y:e.clientY+(o?0:n),target_fixed:o,type:t}}Dt(e,t){var n;if(t===void 0&&(t="click"),!zi(e.target)&&no(e)){var s=this.Gt(e,t);(n=this.rageclicks)!=null&&n.isRageClick(e.clientX,e.clientY,new Date().getTime())&&this.Vt(C({},s,{type:"rageclick"})),this.Vt(s)}}Ht(e){!zi(e.target)&&no(e)&&(clearTimeout(this.Wt),this.Wt=setTimeout(()=>{this.Vt(this.Gt(e,"mousemove"))},500))}Vt(e){if(y){var t=y.location.href,n=this.instance.config.mask_personal_data_properties,s=this.instance.config.custom_personal_data_properties,i=n?Pt([],xt,s||[]):[],o=ar(t,i,lr);this.N=this.N||{},this.N[o]||(this.N[o]=[]),this.N[o].push(e)}}Lt(){this.N&&!yt(this.N)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},Dr=class{constructor(e){this.Jt=(t,n,s)=>{s&&(s.noSessionId||s.activityTimeout||s.sessionPastMaximumLength)&&(E.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:t,changeReason:s}),this.Kt=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.Yt()}Yt(){var e;this.Xt=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.Jt)}destroy(){var e;(e=this.Xt)==null||e.call(this),this.Xt=void 0}doPageView(e,t){var n,s=this.Qt(e,t);return this.Kt={pathname:(n=y?.location.pathname)!==null&&n!==void 0?n:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),s}doPageLeave(e){var t;return this.Qt(e,(t=this.Kt)==null?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.Kt)==null?void 0:e.pageViewId}}Qt(e,t){var n=this.Kt;if(!n)return{$pageview_id:t};var s={$pageview_id:t,$prev_pageview_id:n.pageViewId},i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:o,lastScrollY:a,maxScrollY:l,maxContentHeight:u,lastContentY:c,maxContentY:p}=i;if(!(x(o)||x(a)||x(l)||x(u)||x(c)||x(p))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),p=Math.ceil(p);var d=o<=1?1:Pe(a/o,0,1,E),h=o<=1?1:Pe(l/o,0,1,E),g=u<=1?1:Pe(c/u,0,1,E),f=u<=1?1:Pe(p/u,0,1,E);s=U(s,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:d,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:g,$prev_pageview_max_content:p,$prev_pageview_max_content_percentage:f})}}return n.pathname&&(s.$prev_pageview_pathname=n.pathname),n.timestamp&&(s.$prev_pageview_duration=(e.getTime()-n.timestamp.getTime())/1e3),s}};var Fe=function(r){return r.GZipJS="gzip-js",r.Base64="base64",r}({}),ge=Uint8Array,se=Uint16Array,wt=Uint32Array,Js=new ge([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Zs=new ge([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),so=new ge([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),va=function(r,e){for(var t=new se(31),n=0;n<31;++n)t[n]=e+=1<<r[n-1];var s=new wt(t[30]);for(n=1;n<30;++n)for(var i=t[n];i<t[n+1];++i)s[i]=i-t[n]<<5|n;return[t,s]},_a=va(Js,2),zc=_a[0],ys=_a[1];zc[28]=258,ys[258]=28;for(ms=va(Zs,0)[1],qr=new se(32768),j=0;j<32768;++j)Le=(43690&j)>>>1|(21845&j)<<1,Le=(61680&(Le=(52428&Le)>>>2|(13107&Le)<<2))>>>4|(3855&Le)<<4,qr[j]=((65280&Le)>>>8|(255&Le)<<8)>>>1;var Le,ms,qr,j,Jt=function(r,e,t){for(var n=r.length,s=0,i=new se(e);s<n;++s)++i[r[s]-1];var o,a=new se(e);for(s=0;s<e;++s)a[s]=a[s-1]+i[s-1]<<1;if(t){o=new se(1<<e);var l=15-e;for(s=0;s<n;++s)if(r[s])for(var u=s<<4|r[s],c=e-r[s],p=a[r[s]-1]++<<c,d=p|(1<<c)-1;p<=d;++p)o[qr[p]>>>l]=u}else for(o=new se(n),s=0;s<n;++s)o[s]=qr[a[r[s]-1]++]>>>15-r[s];return o},rt=new ge(288);for(j=0;j<144;++j)rt[j]=8;for(j=144;j<256;++j)rt[j]=9;for(j=256;j<280;++j)rt[j]=7;for(j=280;j<288;++j)rt[j]=8;var jr=new ge(32);for(j=0;j<32;++j)jr[j]=5;var Kc=Jt(rt,9,0),Hc=Jt(jr,5,0),ba=function(r){return(r/8>>0)+(7&r&&1)},ka=function(r,e,t){(t==null||t>r.length)&&(t=r.length);var n=new(r instanceof se?se:r instanceof wt?wt:ge)(t-e);return n.set(r.subarray(e,t)),n},Ae=function(r,e,t){t<<=7&e;var n=e/8>>0;r[n]|=t,r[n+1]|=t>>>8},Dt=function(r,e,t){t<<=7&e;var n=e/8>>0;r[n]|=t,r[n+1]|=t>>>8,r[n+2]|=t>>>16},kn=function(r,e){for(var t=[],n=0;n<r.length;++n)r[n]&&t.push({s:n,f:r[n]});var s=t.length,i=t.slice();if(!s)return[new ge(0),0];if(s==1){var o=new ge(t[0].s+1);return o[t[0].s]=1,[o,1]}t.sort(function(k,M){return k.f-M.f}),t.push({s:-1,f:25001});var a=t[0],l=t[1],u=0,c=1,p=2;for(t[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=s-1;)a=t[t[u].f<t[p].f?u++:p++],l=t[u!=c&&t[u].f<t[p].f?u++:p++],t[c++]={s:-1,f:a.f+l.f,l:a,r:l};var d=i[0].s;for(n=1;n<s;++n)i[n].s>d&&(d=i[n].s);var h=new se(d+1),g=vs(t[c-1],h,0);if(g>e){n=0;var f=0,m=g-e,w=1<<m;for(i.sort(function(k,M){return h[M.s]-h[k.s]||k.f-M.f});n<s;++n){var b=i[n].s;if(!(h[b]>e))break;f+=w-(1<<g-h[b]),h[b]=e}for(f>>>=m;f>0;){var v=i[n].s;h[v]<e?f-=1<<e-h[v]++-1:++n}for(;n>=0&&f;--n){var _=i[n].s;h[_]==e&&(--h[_],++f)}g=e}return[new ge(h),g]},vs=function(r,e,t){return r.s==-1?Math.max(vs(r.l,e,t+1),vs(r.r,e,t+1)):e[r.s]=t},io=function(r){for(var e=r.length;e&&!r[--e];);for(var t=new se(++e),n=0,s=r[0],i=1,o=function(l){t[n++]=l},a=1;a<=e;++a)if(r[a]==s&&a!=e)++i;else{if(!s&&i>2){for(;i>138;i-=138)o(32754);i>2&&(o(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(o(s),--i;i>6;i-=6)o(8304);i>2&&(o(i-3<<5|8208),i=0)}for(;i--;)o(s);i=1,s=r[a]}return[t.subarray(0,n),e]},qt=function(r,e){for(var t=0,n=0;n<e.length;++n)t+=r[n]*e[n];return t},_s=function(r,e,t){var n=t.length,s=ba(e+2);r[s]=255&n,r[s+1]=n>>>8,r[s+2]=255^r[s],r[s+3]=255^r[s+1];for(var i=0;i<n;++i)r[s+i+4]=t[i];return 8*(s+4+n)},oo=function(r,e,t,n,s,i,o,a,l,u,c){Ae(e,c++,t),++s[256];for(var p=kn(s,15),d=p[0],h=p[1],g=kn(i,15),f=g[0],m=g[1],w=io(d),b=w[0],v=w[1],_=io(f),k=_[0],M=_[1],I=new se(19),S=0;S<b.length;++S)I[31&b[S]]++;for(S=0;S<k.length;++S)I[31&k[S]]++;for(var O=kn(I,7),V=O[0],W=O[1],X=19;X>4&&!V[so[X-1]];--X);var z,te,Q,de,ve=u+5<<3,Ce=qt(s,rt)+qt(i,jr)+o,be=qt(s,d)+qt(i,f)+o+14+3*X+qt(I,V)+(2*I[16]+3*I[17]+7*I[18]);if(ve<=Ce&&ve<=be)return _s(e,c,r.subarray(l,l+u));if(Ae(e,c,1+(be<Ce)),c+=2,be<Ce){z=Jt(d,h,0),te=d,Q=Jt(f,m,0),de=f;var De=Jt(V,W,0);for(Ae(e,c,v-257),Ae(e,c+5,M-1),Ae(e,c+10,X-4),c+=14,S=0;S<X;++S)Ae(e,c+3*S,V[so[S]]);c+=3*X;for(var ct=[b,k],re=0;re<2;++re){var he=ct[re];for(S=0;S<he.length;++S){var oe=31&he[S];Ae(e,c,De[oe]),c+=V[oe],oe>15&&(Ae(e,c,he[S]>>>5&127),c+=he[S]>>>12)}}}else z=Kc,te=rt,Q=Hc,de=jr;for(S=0;S<a;++S)if(n[S]>255){oe=n[S]>>>18&31,Dt(e,c,z[oe+257]),c+=te[oe+257],oe>7&&(Ae(e,c,n[S]>>>23&31),c+=Js[oe]);var ut=31&n[S];Dt(e,c,Q[ut]),c+=de[ut],ut>3&&(Dt(e,c,n[S]>>>5&8191),c+=Zs[ut])}else Dt(e,c,z[n[S]]),c+=te[n[S]];return Dt(e,c,z[256]),c+te[256]},Bc=new wt([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Wc=function(){for(var r=new wt(256),e=0;e<256;++e){for(var t=e,n=9;--n;)t=(1&t&&3988292384)^t>>>1;r[e]=t}return r}(),Xc=function(r,e,t,n,s){return function(i,o,a,l,u,c){var p=i.length,d=new ge(l+p+5*(1+Math.floor(p/7e3))+u),h=d.subarray(l,d.length-u),g=0;if(!o||p<8)for(var f=0;f<=p;f+=65535){var m=f+65535;m<p?g=_s(h,g,i.subarray(f,m)):(h[f]=c,g=_s(h,g,i.subarray(f,p)))}else{for(var w=Bc[o-1],b=w>>>13,v=8191&w,_=(1<<a)-1,k=new se(32768),M=new se(_+1),I=Math.ceil(a/3),S=2*I,O=function(dn){return(i[dn]^i[dn+1]<<I^i[dn+2]<<S)&_},V=new wt(25e3),W=new se(288),X=new se(32),z=0,te=0,Q=(f=0,0),de=0,ve=0;f<p;++f){var Ce=O(f),be=32767&f,De=M[Ce];if(k[be]=De,M[Ce]=be,de<=f){var ct=p-f;if((z>7e3||Q>24576)&&ct>423){g=oo(i,h,0,V,W,X,te,Q,ve,f-ve,g),Q=z=te=0,ve=f;for(var re=0;re<286;++re)W[re]=0;for(re=0;re<30;++re)X[re]=0}var he=2,oe=0,ut=v,qe=be-De&32767;if(ct>2&&Ce==O(f-qe))for(var Pl=Math.min(b,ct)-1,xl=Math.min(32767,f),El=Math.min(258,ct);qe<=xl&&--ut&&be!=De;){if(i[f+he]==i[f+he-qe]){for(var je=0;je<El&&i[f+je]==i[f+je-qe];++je);if(je>he){if(he=je,oe=qe,je>Pl)break;var Sl=Math.min(qe,je-2),vi=0;for(re=0;re<Sl;++re){var pn=f-qe+re+32768&32767,_i=pn-k[pn]+32768&32767;_i>vi&&(vi=_i,De=pn)}}}qe+=(be=De)-(De=k[be])+32768&32767}if(oe){V[Q++]=268435456|ys[he]<<18|ms[oe];var bi=31&ys[he],ki=31&ms[oe];te+=Js[bi]+Zs[ki],++W[257+bi],++X[ki],de=f+he,++z}else V[Q++]=i[f],++W[i[f]]}}g=oo(i,h,c,V,W,X,te,Q,ve,f-ve,g)}return ka(d,0,l+ba(g)+u)}(r,e.level==null?6:e.level,e.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+e.mem,t,n,!0)},wn=function(r,e,t){for(;t;++e)r[e]=t,t>>>=8};function Yc(r,e){e===void 0&&(e={});var t=function(){var a=4294967295;return{p:function(l){for(var u=a,c=0;c<l.length;++c)u=Wc[255&u^l[c]]^u>>>8;a=u},d:function(){return 4294967295^a}}}(),n=r.length;t.p(r);var s,i=Xc(r,e,10+((s=e).filename&&s.filename.length+1||0),8),o=i.length;return function(a,l){var u=l.filename;if(a[0]=31,a[1]=139,a[2]=8,a[8]=l.level<2?4:l.level==9?2:0,a[9]=3,l.mtime!=0&&wn(a,4,Math.floor(new Date(l.mtime||Date.now())/1e3)),u){a[3]=8;for(var c=0;c<=u.length;++c)a[c+10]=u.charCodeAt(c)}}(i,e),wn(i,o-8,t.d()),wn(i,o-4,n),i}var Jc=function(r){var e,t,n,s,i="";for(e=t=0,n=(r=(r+"").replace(/\r\n/g,`
10
10
  `).replace(/\r/g,`
11
- `)).length,i=0;i<n;i++){var o=r.charCodeAt(i),a=null;o<128?t++:a=o>127&&o<2048?String.fromCharCode(o>>6|192,63&o|128):String.fromCharCode(o>>12|224,o>>6&63|128,63&o|128),me(a)||(t>e&&(s+=r.substring(e,t)),s+=a,e=t=i+1)}return t>e&&(s+=r.substring(e,r.length)),s},Kc=!!In||!!An,so="text/plain",jr=function(r,e,t){var n;t===void 0&&(t=!0);var[i,s]=r.split("?"),o=S({},e),a=(n=s?.split("&").map(u=>{var c,[p,d]=u.split("="),h=t&&(c=o[p])!==null&&c!==void 0?c:d;return delete o[p],p+"="+h}))!==null&&n!==void 0?n:[],l=_c(o);return l&&a.push(l),i+"?"+a.join("&")},Bt=(r,e)=>JSON.stringify(r,(t,n)=>typeof n=="bigint"?n.toString():n,e),wn=r=>{var{data:e,compression:t}=r;if(e){if(t===Te.GZipJS){var n=zc(function(l,u){var c=l.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(l);for(var p=new ge(l.length+(l.length>>>1)),d=0,h=function(w){p[d++]=w},g=0;g<c;++g){if(d+5>p.length){var f=new ge(d+8+(c-g<<1));f.set(p),p=f}var m=l.charCodeAt(g);m<128||u?h(m):m<2048?(h(192|m>>>6),h(128|63&m)):m>55295&&m<57344?(h(240|(m=65536+(1047552&m)|1023&l.charCodeAt(++g))>>>18),h(128|m>>>12&63),h(128|m>>>6&63),h(128|63&m)):(h(224|m>>>12),h(128|m>>>6&63),h(128|63&m))}return _a(p,0,d)}(Bt(e)),{mtime:0}),i=new Blob([n],{type:so});return{contentType:so,body:i,estimatedSize:i.size}}if(t===Te.Base64){var s=function(l){var u,c,p,d,h,g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",f=0,m=0,w="",b=[];if(!l)return l;l=Hc(l);do u=(h=l.charCodeAt(f++)<<16|l.charCodeAt(f++)<<8|l.charCodeAt(f++))>>18&63,c=h>>12&63,p=h>>6&63,d=63&h,b[m++]=g.charAt(u)+g.charAt(c)+g.charAt(p)+g.charAt(d);while(f<l.length);switch(w=b.join(""),l.length%3){case 1:w=w.slice(0,-2)+"==";break;case 2:w=w.slice(0,-1)+"="}return w}(Bt(e)),o=(l=>"data="+encodeURIComponent(typeof l=="string"?l:Bt(l)))(s);return{contentType:"application/x-www-form-urlencoded",body:o,estimatedSize:new Blob([o]).size}}var a=Bt(e);return{contentType:"application/json",body:a,estimatedSize:new Blob([a]).size}}},kr=[];An&&kr.push({transport:"fetch",method:r=>{var e,t,{contentType:n,body:i,estimatedSize:s}=(e=wn(r))!==null&&e!==void 0?e:{},o=new Headers;D(r.headers,function(c,p){o.append(p,c)}),n&&o.append("Content-Type",n);var a=r.url,l=null;if(Es){var u=new Es;l={signal:u.signal,timeout:setTimeout(()=>u.abort(),r.timeout)}}An(a,S({method:r?.method||"GET",headers:o,keepalive:r.method==="POST"&&(s||0)<52428.8,body:i,signal:(t=l)==null?void 0:t.signal},r.fetchOptions)).then(c=>c.text().then(p=>{var d={statusCode:c.status,text:p};if(c.status===200)try{d.json=JSON.parse(p)}catch(h){E.error(h)}r.callback==null||r.callback(d)})).catch(c=>{E.error(c),r.callback==null||r.callback({statusCode:0,text:c})}).finally(()=>l?clearTimeout(l.timeout):null)}}),In&&kr.push({transport:"XHR",method:r=>{var e,t=new In;t.open(r.method||"GET",r.url,!0);var{contentType:n,body:i}=(e=wn(r))!==null&&e!==void 0?e:{};D(r.headers,function(s,o){t.setRequestHeader(o,s)}),n&&t.setRequestHeader("Content-Type",n),r.timeout&&(t.timeout=r.timeout),r.disableXHRCredentials||(t.withCredentials=!0),t.onreadystatechange=()=>{if(t.readyState===4){var s={statusCode:t.status,text:t.responseText};if(t.status===200)try{s.json=JSON.parse(t.responseText)}catch{}r.callback==null||r.callback(s)}},t.send(i)}}),le!=null&&le.sendBeacon&&kr.push({transport:"sendBeacon",method:r=>{var e=jr(r.url,{beacon:"1"});try{var t,{contentType:n,body:i}=(t=wn(r))!==null&&t!==void 0?t:{},s=typeof i=="string"?new Blob([i],{type:n}):i;le.sendBeacon(e,s)}catch{}}});var Gr=function(r,e){if(!function(t){try{new RegExp(t)}catch{return!1}return!0}(e))return!1;try{return new RegExp(e).test(r)}catch{return!1}};function oo(r,e,t){return Bt({distinct_id:r,userPropertiesToSet:e,userPropertiesToSetOnce:t})}var ba={exact:(r,e)=>e.some(t=>r.some(n=>t===n)),is_not:(r,e)=>e.every(t=>r.every(n=>t!==n)),regex:(r,e)=>e.some(t=>r.some(n=>Gr(t,n))),not_regex:(r,e)=>e.every(t=>r.every(n=>!Gr(t,n))),icontains:(r,e)=>e.map(br).some(t=>r.map(br).some(n=>t.includes(n))),not_icontains:(r,e)=>e.map(br).every(t=>r.map(br).every(n=>!t.includes(n))),gt:(r,e)=>e.some(t=>{var n=parseFloat(t);return!isNaN(n)&&r.some(i=>n>parseFloat(i))}),lt:(r,e)=>e.some(t=>{var n=parseFloat(t);return!isNaN(n)&&r.some(i=>n<parseFloat(i))})},br=r=>r.toLowerCase();function wa(r,e){return!r||Object.entries(r).every(t=>{var[n,i]=t,s=e?.[n];if(x(s)||me(s))return!1;var o=[String(s)],a=ba[i.operator];return!!a&&a(i.values,o)})}var kn=L("[Error tracking]"),vi=class{constructor(e){var t,n;this.Zt=[],this.ti=new Dn([new jn,new Kn,new Ln,new Gn,new zn,new Vn,new Un,new Hn],tc()),this._instance=e,this.Zt=(t=(n=this._instance.persistence)==null?void 0:n.get_property(Wn))!==null&&t!==void 0?t:[]}onRemoteConfig(e){var t,n,i,s=(t=(n=e.errorTracking)==null?void 0:n.suppressionRules)!==null&&t!==void 0?t:[],o=(i=e.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Zt=s,this._instance.persistence&&this._instance.persistence.register({[Wn]:this.Zt,[qs]:o})}get ii(){var e,t=!!this._instance.get_property(qs),n=this._instance.config.error_tracking.captureExtensionExceptions;return(e=n??t)!==null&&e!==void 0&&e}buildProperties(e,t){return this.ti.buildFromUnknown(e,{syntheticException:t?.syntheticException,mechanism:{handled:t?.handled}})}sendExceptionEvent(e){var t=e.$exception_list;if(this.ei(t)){if(this.ri(t))return void kn.info("Skipping exception capture because a suppression rule matched");if(!this.ii&&this.si(t))return void kn.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ni(t))return void kn.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent"})}ri(e){if(e.length===0)return!1;var t=e.reduce((n,i)=>{var{type:s,value:o}=i;return K(s)&&s.length>0&&n.$exception_types.push(s),K(o)&&o.length>0&&n.$exception_values.push(o),n},{$exception_types:[],$exception_values:[]});return this.Zt.some(n=>{var i=n.values.map(s=>{var o,a=ba[s.operator],l=$(s.value)?s.value:[s.value],u=(o=t[s.key])!==null&&o!==void 0?o:[];return l.length>0&&a(l,u)});return n.type==="OR"?i.some(Boolean):i.every(Boolean)})}si(e){return e.flatMap(t=>{var n,i;return(n=(i=t.stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[]}).some(t=>t.filename&&t.filename.startsWith("chrome-extension://"))}ni(e){if(e.length>0){var t,n,i,s,o=(t=(n=e[0].stacktrace)==null?void 0:n.frames)!==null&&t!==void 0?t:[],a=o[o.length-1];return(i=a==null||(s=a.filename)==null?void 0:s.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}ei(e){return!O(e)&&$(e)}},ae=L("[FeatureFlags]"),qt=L("[FeatureFlags]",{debugEnabled:!0}),Pn="$active_feature_flags",ut="$override_feature_flags",ao="$feature_flag_payloads",jt="$override_feature_flag_payloads",lo="$feature_flag_request_id",co="$feature_flag_evaluated_at",uo=r=>{var e={};for(var[t,n]of wr(r||{}))n&&(e[t]=n);return e},Bc=r=>{var e=r.flags;return e?(r.featureFlags=Object.fromEntries(Object.keys(e).map(t=>{var n;return[t,(n=e[t].variant)!==null&&n!==void 0?n:e[t].enabled]})),r.featureFlagPayloads=Object.fromEntries(Object.keys(e).filter(t=>e[t].enabled).filter(t=>{var n;return(n=e[t].metadata)==null?void 0:n.payload}).map(t=>{var n;return[t,(n=e[t].metadata)==null?void 0:n.payload]}))):ae.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),r},Wc=function(r){return r.FeatureFlags="feature_flags",r.Recordings="recordings",r}({}),_i=class{constructor(e){this.oi=!1,this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.ci=!1,this._instance=e,this.featureFlagEventHandlers=[]}fi(){var e,t=(e=this._instance.config.evaluation_contexts)!==null&&e!==void 0?e:this._instance.config.evaluation_environments;return!this._instance.config.evaluation_environments||this._instance.config.evaluation_contexts||this.ci||(ae.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.ci=!0),t!=null&&t.length?t.filter(n=>{var i=n&&typeof n=="string"&&n.trim().length>0;return i||ae.error("Invalid evaluation context found:",n,"Expected non-empty string"),i}):[]}pi(){return this.fi().length>0}flags(){if(this._instance.config.__preview_remote_config)this.di=!0;else{var e=!this.gi&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.mi({disableFlags:e})}}get hasLoadedFlags(){return this.ai}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._instance.get_property(Xn),t=this._instance.get_property(ut),n=this._instance.get_property(jt);if(!n&&!t)return e||{};var i=U({},e||{}),s=[...new Set([...Object.keys(n||{}),...Object.keys(t||{})])];for(var o of s){var a,l,u=i[o],c=t?.[o],p=x(c)?(a=u?.enabled)!==null&&a!==void 0&&a:!!c,d=x(c)?u.variant:typeof c=="string"?c:void 0,h=n?.[o],g=S({},u,{enabled:p,variant:p?d??u?.variant:void 0});p!==u?.enabled&&(g.original_enabled=u?.enabled),d!==u?.variant&&(g.original_variant=u?.variant),h&&(g.metadata=S({},u?.metadata,{payload:h,original_payload:u==null||(l=u.metadata)==null?void 0:l.payload})),i[o]=g}return this.oi||(ae.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:n,finalDetails:i}),this.oi=!0),i}getFlagVariants(){var e=this._instance.get_property(yt),t=this._instance.get_property(ut);if(!t)return e||{};for(var n=U({},e),i=Object.keys(t),s=0;s<i.length;s++)n[i[s]]=t[i[s]];return this.oi||(ae.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:t,finalFlags:n}),this.oi=!0),n}getFlagPayloads(){var e=this._instance.get_property(ao),t=this._instance.get_property(jt);if(!t)return e||{};for(var n=U({},e||{}),i=Object.keys(t),s=0;s<i.length;s++)n[i[s]]=t[i[s]];return this.oi||(ae.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:t,finalPayloads:n}),this.oi=!0),n}reloadFeatureFlags(){this.ui||this._instance.config.advanced_disable_feature_flags||this.gi||(this.gi=setTimeout(()=>{this.mi()},5))}bi(){clearTimeout(this.gi),this.gi=void 0}ensureFlagsLoaded(){this.ai||this.li||this.gi||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.ui=e}mi(e){var t;if(this.bi(),!this._instance.M())if(this.li)this.hi=!0;else{var n=this._instance.config.token,i=this._instance.get_property("$device_id"),s={token:n,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:S({},((t=this._instance.persistence)==null?void 0:t.get_initial_props())||{},this._instance.get_property(Kt)||{}),group_properties:this._instance.get_property(et)};me(i)||x(i)||(s.$device_id=i),(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(s.disable_flags=!0),this.pi()&&(s.evaluation_contexts=this.fi());var o=this._instance.config.__preview_remote_config,a=o?"/flags/?v=2":"/flags/?v=2&config=true",l=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",u=this._instance.requestRouter.endpointFor("flags",a+l);o&&(s.timezone=ga()),this.li=!0,this._instance._send_request({method:"POST",url:u,data:s,compression:this._instance.config.disable_compression?void 0:Te.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:c=>{var p,d,h=!0;if(c.statusCode===200&&(this.hi||(this.$anon_distinct_id=void 0),h=!1),this.li=!1,this.di||(this.di=!0,this._instance.yi((d=c.json)!==null&&d!==void 0?d:{})),!s.disable_flags||this.hi)if(this.vi=!h,c.json&&(p=c.json.quotaLimited)!=null&&p.includes(Wc.FeatureFlags))ae.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more.");else{var g;s.disable_flags||this.receivedFeatureFlags((g=c.json)!==null&&g!==void 0?g:{},h),this.hi&&(this.hi=!1,this.mi())}}})}}getFeatureFlag(e,t){var n;if(t===void 0&&(t={}),this.ai||this.getFlags()&&this.getFlags().length>0){var i=this.getFeatureFlagResult(e,t);return(n=i?.variant)!==null&&n!==void 0?n:i?.enabled}ae.warn('getFeatureFlag for key "'+e+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){var t=this.getFeatureFlagResult(e,{send_event:!1});return t?.payload}getFeatureFlagResult(e,t){if(t===void 0&&(t={}),this.ai||this.getFlags()&&this.getFlags().length>0){var n=this.getFlagVariants(),i=e in n,s=n[e],o=this.getFlagPayloads()[e],a=String(s),l=this._instance.get_property(lo)||void 0,u=this._instance.get_property(co)||void 0,c=this._instance.get_property(Cr)||{};if((t.send_event||!("send_event"in t))&&(!(e in c)||!c[e].includes(a))){var p,d,h,g,f,m,w,b,v;$(c[e])?c[e].push(a):c[e]=[a],(p=this._instance.persistence)==null||p.register({[Cr]:c});var _=this.getFeatureFlagDetails(e),k={$feature_flag:e,$feature_flag_response:s,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((d=this._instance.config.bootstrap)==null||(d=d.featureFlags)==null?void 0:d[e])||null,$feature_flag_bootstrapped_payload:((h=this._instance.config.bootstrap)==null||(h=h.featureFlagPayloads)==null?void 0:h[e])||null,$used_bootstrap_value:!this.vi};x(_==null||(g=_.metadata)==null?void 0:g.version)||(k.$feature_flag_version=_.metadata.version);var I,M=(f=_==null||(m=_.reason)==null?void 0:m.description)!==null&&f!==void 0?f:_==null||(w=_.reason)==null?void 0:w.code;M&&(k.$feature_flag_reason=M),_!=null&&(b=_.metadata)!=null&&b.id&&(k.$feature_flag_id=_.metadata.id),x(_?.original_variant)&&x(_?.original_enabled)||(k.$feature_flag_original_response=x(_.original_variant)?_.original_enabled:_.original_variant),_!=null&&(v=_.metadata)!=null&&v.original_payload&&(k.$feature_flag_original_payload=_==null||(I=_.metadata)==null?void 0:I.original_payload),this._instance.capture("$feature_flag_called",k)}if(i){var C=o;if(!x(o))try{C=JSON.parse(o)}catch{}return{key:e,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:C}}}else ae.warn('getFeatureFlagResult for key "'+e+`" failed. Feature flags didn't load in time.`)}getRemoteConfigPayload(e,t){var n=this._instance.config.token,i={distinct_id:this._instance.get_distinct_id(),token:n};this.pi()&&(i.evaluation_contexts=this.fi()),this._instance._send_request({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2&config=true"),data:i,compression:this._instance.config.disable_compression?void 0:Te.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:s=>{var o,a=(o=s.json)==null?void 0:o.featureFlagPayloads;t(a?.[e]||void 0)}})}isFeatureEnabled(e,t){if(t===void 0&&(t={}),this.ai||this.getFlags()&&this.getFlags().length>0){var n=this.getFeatureFlag(e,t);return x(n)?void 0:!!n}ae.warn('isFeatureEnabled for key "'+e+`" failed. Feature flags didn't load in time.`)}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(t=>t!==e)}receivedFeatureFlags(e,t){if(this._instance.persistence){this.ai=!0;var n=this.getFlagVariants(),i=this.getFlagPayloads(),s=this.getFlagsWithDetails();(function(o,a,l,u,c){l===void 0&&(l={}),u===void 0&&(u={}),c===void 0&&(c={});var p=Bc(o),d=p.flags,h=p.featureFlags,g=p.featureFlagPayloads;if(h){var f=o.requestId,m=o.evaluatedAt;if($(h)){ae.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var w={};if(h)for(var b=0;b<h.length;b++)w[h[b]]=!0;a&&a.register({[Pn]:h,[yt]:w})}else{var v=h,_=g,k=d;if(o.errorsWhileComputingFlags)if(d){var I=new Set(Object.keys(d).filter(M=>{var C;return!((C=d[M])!=null&&C.failed)}));v=S({},l,Object.fromEntries(Object.entries(v).filter(M=>{var[C]=M;return I.has(C)}))),_=S({},u,Object.fromEntries(Object.entries(_||{}).filter(M=>{var[C]=M;return I.has(C)}))),k=S({},c,Object.fromEntries(Object.entries(k||{}).filter(M=>{var[C]=M;return I.has(C)})))}else v=S({},l,v),_=S({},u,_),k=S({},c,k);a&&a.register(S({[Pn]:Object.keys(uo(v)),[yt]:v||{},[ao]:_||{},[Xn]:k||{}},f?{[lo]:f}:{},m?{[co]:m}:{}))}}})(e,this._instance.persistence,n,i,s),this.wi(t)}}override(e,t){t===void 0&&(t=!1),ae.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:t})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return ae.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this._instance.persistence.unregister(ut),this._instance.persistence.unregister(jt),this.wi(),qt.info("All overrides cleared");if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var t,n=e;if(this.oi=!!((t=n.suppressWarning)!==null&&t!==void 0&&t),"flags"in n){if(n.flags===!1)this._instance.persistence.unregister(ut),qt.info("Flag overrides cleared");else if(n.flags){if($(n.flags)){for(var i={},s=0;s<n.flags.length;s++)i[n.flags[s]]=!0;this._instance.persistence.register({[ut]:i})}else this._instance.persistence.register({[ut]:n.flags});qt.info("Flag overrides set",{flags:n.flags})}}return"payloads"in n&&(n.payloads===!1?(this._instance.persistence.unregister(jt),qt.info("Payload overrides cleared")):n.payloads&&(this._instance.persistence.register({[jt]:n.payloads}),qt.info("Payload overrides set",{payloads:n.payloads}))),void this.wi()}this.wi()}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.ai){var{flags:t,flagVariants:n}=this.xi();e(t,n)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,n){var i,s=(this._instance.get_property(Ht)||[]).find(u=>u.flagKey===e),o={["$feature_enrollment/"+e]:t},a={$feature_flag:e,$feature_enrollment:t,$set:o};s&&(a.$early_access_feature_name=s.name),n&&(a.$feature_enrollment_stage=n),this._instance.capture("$feature_enrollment_update",a),this.setPersonPropertiesForFlags(o,!1);var l=S({},this.getFlagVariants(),{[e]:t});(i=this._instance.persistence)==null||i.register({[Pn]:Object.keys(uo(l)),[yt]:l}),this.wi()}getEarlyAccessFeatures(e,t,n){t===void 0&&(t=!1);var i=this._instance.get_property(Ht),s=n?"&"+n.map(o=>"stage="+o).join("&"):"";if(i&&!t)return e(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+s),method:"GET",callback:o=>{var a,l;if(o.json){var u=o.json.earlyAccessFeatures;return(a=this._instance.persistence)==null||a.unregister(Ht),(l=this._instance.persistence)==null||l.register({[Ht]:u}),e(u)}}})}xi(){var e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter(n=>t[n]),flagVariants:Object.keys(t).filter(n=>t[n]).reduce((n,i)=>(n[i]=t[i],n),{})}}wi(e){var{flags:t,flagVariants:n}=this.xi();this.featureFlagEventHandlers.forEach(i=>i(t,n,{errorsLoading:e}))}setPersonPropertiesForFlags(e,t){t===void 0&&(t=!0);var n=this._instance.get_property(Kt)||{};this._instance.register({[Kt]:S({},n,e)}),t&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(Kt)}setGroupPropertiesForFlags(e,t){t===void 0&&(t=!0);var n=this._instance.get_property(et)||{};Object.keys(n).length!==0&&Object.keys(n).forEach(i=>{n[i]=S({},n[i],e[i]),delete e[i]}),this._instance.register({[et]:S({},n,e)}),t&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var t=this._instance.get_property(et)||{};this._instance.register({[et]:S({},t,{[e]:{}})})}else this._instance.unregister(et)}reset(){this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.$anon_distinct_id=void 0,this.bi(),this.oi=!1}},Xc=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Jt=class{constructor(e,t){this.R=e,this.props={},this.Ei=!1,this.$i=(n=>{var i="";return n.token&&(i=n.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),n.persistence_name?"ph_"+n.persistence_name:"ph_"+i+"_posthog"})(e),this.Y=this.Si(e),this.load(),e.debug&&E.info("Persistence loaded",e.persistence,S({},this.props)),this.update_config(e,e,t),this.save()}isDisabled(){return!!this.ki}Si(e){Xc.indexOf(e.persistence.toLowerCase())===-1&&(E.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var t=function(i){i===void 0&&(i=[]);var s=[...Sc,...i];return S({},G,{W:function(o){try{var a={};try{a=be.W(o)||{}}catch{}var l=U(a,JSON.parse(G.q(o)||"{}"));return G.G(o,l),l}catch{}return null},G:function(o,a,l,u,c,p){try{G.G(o,a,void 0,void 0,p);var d={};s.forEach(h=>{a[h]&&(d[h]=a[h])}),Object.keys(d).length&&be.G(o,d,l,u,c,p)}catch(h){G.B(h)}},V:function(o,a){try{y?.localStorage.removeItem(o),be.V(o,a)}catch(l){G.B(l)}}})}(e.cookie_persisted_properties||[]),n=e.persistence.toLowerCase();return n==="localstorage"&&G.H()?G:n==="localstorage+cookie"&&t.H()?t:n==="sessionstorage"&&B.H()?B:n==="memory"?Cc:n==="cookie"?be:t.H()?t:be}properties(){var e={};return D(this.props,function(t,n){if(n===yt&&H(t))for(var i=Object.keys(t),s=0;s<i.length;s++)e["$feature/"+i[s]]=t[i[s]];else a=n,l=!1,(me(o=cc)?l:xs&&o.indexOf===xs?o.indexOf(a)!=-1:(D(o,function(u){if(l||(l=u===a))return Er}),l))||(e[n]=t);var o,a,l}),e}load(){if(!this.ki){var e=this.Y.W(this.$i);e&&(this.props=U({},e))}}save(){this.ki||this.Y.G(this.$i,this.props,this.Pi,this.Ti,this.Ii,this.R.debug)}remove(){this.Y.V(this.$i,!1),this.Y.V(this.$i,!0)}clear(){this.remove(),this.props={}}register_once(e,t,n){if(H(e)){x(t)&&(t="None"),this.Pi=x(n)?this.Ci:n;var i=!1;if(D(e,(s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==t||(this.props[o]=s,i=!0)}),i)return this.save(),!0}return!1}register(e,t){if(H(e)){this.Pi=x(t)?this.Ci:t;var n=!1;if(D(e,(i,s)=>{e.hasOwnProperty(s)&&this.props[s]!==i&&(this.props[s]=i,n=!0)}),n)return this.save(),!0}return!1}unregister(e){e in this.props&&(delete this.props[e],this.save())}update_campaign_params(){if(!this.Ei){var e=ca(this.R.custom_campaign_params,this.R.mask_personal_data_properties,this.R.custom_personal_data_properties);gt(Hi(e))||this.register(e),this.Ei=!0}}update_search_keyword(){var e;this.register((e=P?.referrer)?pa(e):{})}update_referrer_info(){var e;this.register_once({$referrer:da(),$referring_domain:P!=null&&P.referrer&&((e=Tr(P.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[Qn]||this.props[ei]||this.register_once({[Ar]:ha(this.R.mask_personal_data_properties,this.R.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};D([ei,Qn],o=>{var a=this.props[o];a&&D(a,function(l,u){e["$initial_"+Mn(u)]=l})});var t,n,i=this.props[Ar];if(i){var s=(t=fa(i),n={},D(t,function(o,a){n["$initial_"+Mn(a)]=o}),n);U(e,s)}return e}safe_merge(e){return D(this.props,function(t,n){n in e||(e[n]=t)}),e}update_config(e,t,n){if(this.Ci=this.Pi=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!n),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==t.persistence||!((o,a)=>{if(o.length!==a.length)return!1;var l=[...o].sort(),u=[...a].sort();return l.every((c,p)=>c===u[p])})(e.cookie_persisted_properties||[],t.cookie_persisted_properties||[])){var i=this.Si(e),s=this.props;this.clear(),this.Y=i,this.props=s,this.save()}}set_disabled(e){this.ki=e,this.ki?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ti&&(this.Ti=e,this.remove(),this.save())}set_secure(e){e!==this.Ii&&(this.Ii=e,this.remove(),this.save())}set_event_timer(e,t){var n=this.props[zt]||{};n[e]=t,this.props[zt]=n,this.save()}remove_event_timer(e){var t=(this.props[zt]||{})[e];return x(t)||(delete this.props[zt][e],this.save()),t}get_property(e){return this.props[e]}set_property(e,t){this.props[e]=t,this.save()}},po=L("[Product Tours]"),xn="ph_product_tours",bi=class{constructor(e){this.Ri=null,this.Fi=null,this._instance=e}onRemoteConfig(e){this._instance.persistence&&this._instance.persistence.register({[Gs]:!(e==null||!e.productTours)}),this.loadIfEnabled()}loadIfEnabled(){var e,t;this.Ri||(e=this._instance).config.disable_product_tours||(t=e.persistence)==null||!t.get_property(Gs)||this.it(()=>this.Oi())}it(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.generateProductTours?e():(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",i=>{i?po.error("Could not load product tours script",i):e()})}Oi(){var e;!this.Ri&&(e=A.__PosthogExtensions__)!=null&&e.generateProductTours&&(this.Ri=A.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t){if(t===void 0&&(t=!1),!$(this.Fi)||t){var n=this._instance.persistence;if(n){var i=n.props[xn];if($(i)&&!t)return this.Fi=i,void e(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",callback:s=>{var o=s.statusCode;if(o!==200||!s.json){var a="Product Tours API could not be loaded, status: "+o;return po.error(a),void e([],{isLoaded:!1,error:a})}var l=$(s.json.product_tours)?s.json.product_tours:[];this.Fi=l,n&&n.register({[xn]:l}),e(l,{isLoaded:!0})}})}else e(this.Fi,{isLoaded:!0})}getActiveProductTours(e){O(this.Ri)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this.Ri.getActiveProductTours(e)}showProductTour(e){var t;(t=this.Ri)==null||t.showTourById(e)}previewTour(e){this.Ri?this.Ri.previewTour(e):this.it(()=>{var t;this.Oi(),(t=this.Ri)==null||t.previewTour(e)})}dismissProductTour(){var e;(e=this.Ri)==null||e.dismissTour("user_clicked_skip")}nextStep(){var e;(e=this.Ri)==null||e.nextStep()}previousStep(){var e;(e=this.Ri)==null||e.previousStep()}clearCache(){var e;this.Fi=null,(e=this._instance.persistence)==null||e.unregister(xn)}resetTour(e){var t;(t=this.Ri)==null||t.resetTour(e)}resetAllTours(){var e;(e=this.Ri)==null||e.resetAllTours()}cancelPendingTour(e){var t;(t=this.Ri)==null||t.cancelPendingTour(e)}},Gt=function(r){return r.Activation="events",r.Cancellation="cancelEvents",r}({}),jp=function(r){return r.Button="button",r.Tab="tab",r.Selector="selector",r}({}),Gp=function(r){return r.TopLeft="top_left",r.TopRight="top_right",r.TopCenter="top_center",r.MiddleLeft="middle_left",r.MiddleRight="middle_right",r.MiddleCenter="middle_center",r.Left="left",r.Center="center",r.Right="right",r.NextToTrigger="next_to_trigger",r}({}),Lp=function(r){return r.Top="top",r.Left="left",r.Right="right",r.Bottom="bottom",r}({}),En=function(r){return r.Popover="popover",r.API="api",r.Widget="widget",r.ExternalSurvey="external_survey",r}({}),Up=function(r){return r.Open="open",r.MultipleChoice="multiple_choice",r.SingleChoice="single_choice",r.Rating="rating",r.Link="link",r}({}),Vp=function(r){return r.NextQuestion="next_question",r.End="end",r.ResponseBased="response_based",r.SpecificQuestion="specific_question",r}({}),zp=function(r){return r.Once="once",r.Recurring="recurring",r.Always="always",r}({}),Wt=function(r){return r.SHOWN="survey shown",r.DISMISSED="survey dismissed",r.SENT="survey sent",r.ABANDONED="survey abandoned",r}({}),Sn=function(r){return r.SURVEY_ID="$survey_id",r.SURVEY_NAME="$survey_name",r.SURVEY_RESPONSE="$survey_response",r.SURVEY_ITERATION="$survey_iteration",r.SURVEY_ITERATION_START_DATE="$survey_iteration_start_date",r.SURVEY_PARTIALLY_COMPLETED="$survey_partially_completed",r.SURVEY_SUBMISSION_ID="$survey_submission_id",r.SURVEY_QUESTIONS="$survey_questions",r.SURVEY_COMPLETED="$survey_completed",r.PRODUCT_TOUR_ID="$product_tour_id",r.SURVEY_LAST_SEEN_DATE="$survey_last_seen_date",r}({}),wi=function(r){return r.Popover="popover",r.Inline="inline",r}({}),N=L("[Surveys]"),ka="seenSurvey_",Yc=(r,e)=>{var t="$survey_"+e+"/"+r.id;return r.current_iteration&&r.current_iteration>0&&(t="$survey_"+e+"/"+r.id+"/"+r.current_iteration),t},ho=r=>((e,t)=>{var n=""+e+t.id;return t.current_iteration&&t.current_iteration>0&&(n=""+e+t.id+"_"+t.current_iteration),n})(ka,r),Jc=[En.Popover,En.Widget,En.API],Zc={ignoreConditions:!1,ignoreDelay:!1,displayType:wi.Popover},ir=class{constructor(){this.Mi={},this.Mi={}}on(e,t){return this.Mi[e]||(this.Mi[e]=[]),this.Mi[e].push(t),()=>{this.Mi[e]=this.Mi[e].filter(n=>n!==t)}}emit(e,t){for(var n of this.Mi[e]||[])n(t);for(var i of this.Mi["*"]||[])i(e,t)}};function pt(r,e,t){if(O(r))return!1;switch(t){case"exact":return r===e;case"contains":var n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(n,"i").test(r);case"regex":try{return new RegExp(e).test(r)}catch{return!1}default:return!1}}var ki=class{constructor(e){this.Ai=new ir,this.ji=(t,n)=>this.Di(t,n)&&this.Li(t,n)&&this.Ni(t,n)&&this.Ui(t,n),this.Di=(t,n)=>n==null||!n.event||t?.event===n?.event,this._instance=e,this.zi=new Set,this.Hi=new Set}init(){var e;if(!x((e=this._instance)==null?void 0:e._addCaptureHook)){var t;(t=this._instance)==null||t._addCaptureHook((n,i)=>{this.on(n,i)})}}register(e){var t,n;if(!x((t=this._instance)==null?void 0:t._addCaptureHook)&&(e.forEach(o=>{var a,l;(a=this.Hi)==null||a.add(o),(l=o.steps)==null||l.forEach(u=>{var c;(c=this.zi)==null||c.add(u?.event||"")})}),(n=this._instance)!=null&&n.autocapture)){var i,s=new Set;e.forEach(o=>{var a;(a=o.steps)==null||a.forEach(l=>{l!=null&&l.selector&&s.add(l?.selector)})}),(i=this._instance)==null||i.autocapture.setElementSelectors(s)}}on(e,t){var n;t!=null&&e.length!=0&&(this.zi.has(e)||this.zi.has(t?.event))&&this.Hi&&((n=this.Hi)==null?void 0:n.size)>0&&this.Hi.forEach(i=>{this.Bi(t,i)&&this.Ai.emit("actionCaptured",i.name)})}qi(e){this.onAction("actionCaptured",t=>e(t))}Bi(e,t){if(t?.steps==null)return!1;for(var n of t.steps)if(this.ji(e,n))return!0;return!1}onAction(e,t){return this.Ai.on(e,t)}Li(e,t){if(t!=null&&t.url){var n,i=e==null||(n=e.properties)==null?void 0:n.$current_url;if(!i||typeof i!="string"||!pt(i,t.url,t.url_matching||"contains"))return!1}return!0}Ni(e,t){return!!this.Wi(e,t)&&!!this.Gi(e,t)&&!!this.Vi(e,t)}Wi(e,t){var n;if(t==null||!t.href)return!0;var i=this.Ji(e);if(i.length>0)return i.some(a=>pt(a.href,t.href,t.href_matching||"exact"));var s,o=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";return!!o&&pt((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",t.href,t.href_matching||"exact")}Gi(e,t){var n;if(t==null||!t.text)return!0;var i=this.Ji(e);if(i.length>0)return i.some(u=>pt(u.text,t.text,t.text_matching||"exact")||pt(u.$el_text,t.text,t.text_matching||"exact"));var s,o,a,l=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";return!!l&&(s=function(u){for(var c,p=[],d=/(?::|")text="(.*?)"/g;!O(c=d.exec(u));)p.includes(c[1])||p.push(c[1]);return p}(l),o=t.text,a=t.text_matching||"exact",s.some(u=>pt(u,o,a)))}Vi(e,t){var n,i;if(t==null||!t.selector)return!0;var s=e==null||(n=e.properties)==null?void 0:n.$element_selectors;if(s!=null&&s.includes(t.selector))return!0;var o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";if(t.selector_regex&&o)try{return new RegExp(t.selector_regex).test(o)}catch{return!1}return!1}Ji(e){var t;return(e==null||(t=e.properties)==null?void 0:t.$elements)==null?[]:e?.properties.$elements}Ui(e,t){return t==null||!t.properties||t.properties.length===0||wa(t.properties.reduce((n,i)=>{var s=$(i.value)?i.value.map(String):i.value!=null?[String(i.value)]:[];return n[i.key]={values:s,operator:i.operator||"exact"},n},{}),e?.properties)}},Pi=class{constructor(e){this._instance=e,this.Ki=new Map,this.Yi=new Map,this.Xi=new Map}Qi(e,t){return!!e&&wa(e.propertyFilters,t?.properties)}Zi(e,t){var n=new Map;return e.forEach(i=>{var s;(s=i.conditions)==null||(s=s[t])==null||(s=s.values)==null||s.forEach(o=>{if(o!=null&&o.name){var a=n.get(o.name)||[];a.push(i.id),n.set(o.name,a)}})}),n}te(e,t,n){var i=(n===Gt.Activation?this.Ki:this.Yi).get(e),s=[];return this.ie(o=>{s=o.filter(a=>i?.includes(a.id))}),s.filter(o=>{var a,l=(a=o.conditions)==null||(a=a[n])==null||(a=a.values)==null?void 0:a.find(u=>u.name===e);return this.Qi(l,t)})}register(e){var t;x((t=this._instance)==null?void 0:t._addCaptureHook)||(this.ee(e),this.re(e))}re(e){var t=e.filter(n=>{var i,s;return((i=n.conditions)==null?void 0:i.actions)&&((s=n.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0});t.length!==0&&(this.se==null&&(this.se=new ki(this._instance),this.se.init(),this.se.qi(n=>{this.onAction(n)})),t.forEach(n=>{var i,s,o,a,l;n.conditions&&(i=n.conditions)!=null&&i.actions&&(s=n.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=n.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.se)==null||a.register(n.conditions.actions.values),(l=n.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach(u=>{if(u&&u.name){var c=this.Xi.get(u.name);c&&c.push(n.id),this.Xi.set(u.name,c||[n.id])}}))}))}ee(e){var t,n=e.filter(s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0}),i=e.filter(s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0});(n.length!==0||i.length!==0)&&((t=this._instance)==null||t._addCaptureHook((s,o)=>{this.onEvent(s,o)}),this.Ki=this.Zi(e,Gt.Activation),this.Yi=this.Zi(e,Gt.Cancellation))}onEvent(e,t){var n,i=this.ne(),s=this.oe(),o=this.ae(),a=((n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[s])||[];if(o===e&&t&&a.length>0){var l,u;i.info("event matched, removing item from activated items",{event:e,eventPayload:t,existingActivatedItems:a});var c=(t==null||(l=t.properties)==null?void 0:l.$survey_id)||(t==null||(u=t.properties)==null?void 0:u.$product_tour_id);if(c){var p=a.indexOf(c);p>=0&&(a.splice(p,1),this.le(a))}}else{if(this.Yi.has(e)){var d=this.te(e,t,Gt.Cancellation);d.length>0&&(i.info("cancel event matched, cancelling items",{event:e,itemsToCancel:d.map(g=>g.id)}),d.forEach(g=>{var f=a.indexOf(g.id);f>=0&&a.splice(f,1),this.ue(g.id)}),this.le(a))}if(this.Ki.has(e)){i.info("event name matched",{event:e,eventPayload:t,items:this.Ki.get(e)});var h=this.te(e,t,Gt.Activation);this.le(a.concat(h.map(g=>g.id)||[]))}}}onAction(e){var t,n=this.oe(),i=((t=this._instance)==null||(t=t.persistence)==null?void 0:t.props[n])||[];this.Xi.has(e)&&this.le(i.concat(this.Xi.get(e)||[]))}le(e){var t,n=this.ne(),i=this.oe(),s=[...new Set(e)].filter(o=>!this.he(o));n.info("updating activated items",{activatedItems:s}),(t=this._instance)==null||(t=t.persistence)==null||t.register({[i]:s})}getActivatedIds(){var e,t=this.oe(),n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[t];return n||[]}getEventToItemsMap(){return this.Ki}de(){return this.se}},xi=class extends Pi{constructor(e){super(e)}oe(){return"$surveys_activated"}ae(){return Wt.SHOWN}ie(e){var t;(t=this._instance)==null||t.getSurveys(e)}ue(e){var t;(t=this._instance)==null||t.cancelPendingSurvey(e)}ne(){return N}he(){return!1}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}},Ei=class{constructor(e){this.ve=void 0,this._surveyManager=null,this.ce=!1,this.fe=[],this.pe=null,this._instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){if(!this._instance.config.disable_surveys){var t=e.surveys;if(O(t))return N.warn("Flags not loaded yet. Not loading surveys.");var n=$(t);this.ve=n?t.length>0:t,N.info("flags response received, isSurveysEnabled: "+this.ve),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],t=0;t<localStorage.length;t++){var n=localStorage.key(t);(n!=null&&n.startsWith(ka)||n!=null&&n.startsWith("inProgressSurvey_"))&&e.push(n)}e.forEach(i=>localStorage.removeItem(i))}loadIfEnabled(){if(!this._surveyManager)if(this.ce)N.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)N.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())N.info("Not loading surveys in cookieless mode without consent.");else{var e=A?.__PosthogExtensions__;if(e){if(!x(this.ve)||this._instance.config.advanced_enable_surveys){var t=this.ve||this._instance.config.advanced_enable_surveys;this.ce=!0;try{var n=e.generateSurveys;if(n)return void this.ge(n,t);var i=e.loadExternalDependency;if(!i)return void this._e("PostHog loadExternalDependency extension not found.");i(this._instance,"surveys",s=>{s||!e.generateSurveys?this._e("Could not load surveys script",s):this.ge(e.generateSurveys,t)})}catch(s){throw this._e("Error initializing surveys",s),s}finally{this.ce=!1}}}else N.error("PostHog Extensions not found.")}}ge(e,t){this._surveyManager=e(this._instance,t),this._surveyEventReceiver=new xi(this._instance),N.info("Surveys loaded successfully"),this.me({isLoaded:!0})}_e(e,t){N.error(e,t),this.me({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.fe.push(e),this._surveyManager&&this.me({isLoaded:!0}),()=>{this.fe=this.fe.filter(t=>t!==e)}}getSurveys(e,t){if(t===void 0&&(t=!1),this._instance.config.disable_surveys)return N.info("Disabled. Not loading surveys."),e([]);var n,i=this._instance.get_property(Yn);if(i&&!t)return e(i,{isLoaded:!0});typeof Promise<"u"&&this.pe?this.pe.then(s=>{var{surveys:o,context:a}=s;return e(o,a)}):(typeof Promise<"u"&&(this.pe=new Promise(s=>{n=s})),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:s=>{var o;this.pe=null;var a=s.statusCode;if(a!==200||!s.json){var l="Surveys API could not be loaded, status: "+a;N.error(l);var u={isLoaded:!1,error:l};return e([],u),void(n==null||n({surveys:[],context:u}))}var c,p=s.json.surveys||[],d=p.filter(g=>function(f){return!(!f.start_date||f.end_date)}(g)&&(function(f){var m;return!((m=f.conditions)==null||(m=m.events)==null||(m=m.values)==null||!m.length)}(g)||function(f){var m;return!((m=f.conditions)==null||(m=m.actions)==null||(m=m.values)==null||!m.length)}(g)));d.length>0&&((c=this._surveyEventReceiver)==null||c.register(d)),(o=this._instance.persistence)==null||o.register({[Yn]:p});var h={isLoaded:!0};e(p,h),n?.({surveys:p,context:h})}}))}me(e){for(var t of this.fe)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(n){N.error("Error in survey callback",n)}}getActiveMatchingSurveys(e,t){if(t===void 0&&(t=!1),!O(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);N.warn("init was not called")}be(e){var t=null;return this.getSurveys(n=>{var i;t=(i=n.find(s=>s.id===e))!==null&&i!==void 0?i:null}),t}ye(e){if(O(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var t=typeof e=="string"?this.be(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(O(this._surveyManager))return N.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var t=this.ye(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return O(this._surveyManager)?(N.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise(n=>{this.getSurveys(i=>{var s,o=(s=i.find(l=>l.id===e))!==null&&s!==void 0?s:null;if(o){var a=this.ye(o);n({visible:a.eligible,disabledReason:a.reason})}else n({visible:!1,disabledReason:"Survey not found"})},t)})}renderSurvey(e,t,n){var i;if(O(this._surveyManager))N.warn("init was not called");else{var s=typeof e=="string"?this.be(e):e;if(s!=null&&s.id)if(Jc.includes(s.type)){var o=P?.querySelector(t);if(o)return(i=s.appearance)!=null&&i.surveyPopupDelaySeconds?(N.info("Rendering survey "+s.id+" with delay of "+s.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout(()=>{var a,l;N.info("Rendering survey "+s.id+" with delay of "+((a=s.appearance)==null?void 0:a.surveyPopupDelaySeconds)+" seconds"),(l=this._surveyManager)==null||l.renderSurvey(s,o,n),N.info("Survey "+s.id+" rendered")},1e3*s.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(s,o,n);N.warn("Survey element not found")}else N.warn("Surveys of type "+s.type+" cannot be rendered in the app");else N.warn("Survey not found")}}displaySurvey(e,t){var n;if(O(this._surveyManager))N.warn("init was not called");else{var i=this.be(e);if(i){var s=i;if((n=i.appearance)!=null&&n.surveyPopupDelaySeconds&&t.ignoreDelay&&(s=S({},i,{appearance:S({},i.appearance,{surveyPopupDelaySeconds:0})})),t.displayType!==wi.Popover&&t.initialResponses&&N.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),t.ignoreConditions===!1){var o=this.canRenderSurvey(i);if(!o.visible)return void N.warn("Survey is not eligible to be displayed: ",o.disabledReason)}t.displayType!==wi.Inline?this._surveyManager.handlePopoverSurvey(s,t):this.renderSurvey(s,t.selector,t.properties)}else N.warn("Survey not found")}}cancelPendingSurvey(e){O(this._surveyManager)?N.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e;(e=this._surveyManager)==null||e.handlePageUnload()}},Ae=L("[Conversations]"),Si=class{constructor(e){this.we=void 0,this._conversationsManager=null,this.xe=!1,this.Ee=null,this._instance=e}onRemoteConfig(e){if(!this._instance.config.disable_conversations){var t=e.conversations;O(t)||(Oe(t)?this.we=t:(this.we=t.enabled,this.Ee=t),this.loadIfEnabled())}}reset(){var e;(e=this._conversationsManager)==null||e.reset(),this._conversationsManager=null,this.we=void 0,this.Ee=null}loadIfEnabled(){if(!this._conversationsManager&&!this.xe&&!(this._instance.config.disable_conversations||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var e=A?.__PosthogExtensions__;if(e&&!x(this.we)&&this.we)if(this.Ee&&this.Ee.token){this.xe=!0;try{var t=e.initConversations;if(t)return this.$e(t),void(this.xe=!1);var n=e.loadExternalDependency;if(!n)return void this.Se("PostHog loadExternalDependency extension not found.");n(this._instance,"conversations",i=>{i||!e.initConversations?this.Se("Could not load conversations script",i):this.$e(e.initConversations),this.xe=!1})}catch(i){this.Se("Error initializing conversations",i),this.xe=!1}}else Ae.error("Conversations enabled but missing token in remote config.")}}$e(e){if(this.Ee)try{this._conversationsManager=e(this.Ee,this._instance),Ae.info("Conversations loaded successfully")}catch(t){this.Se("Error completing conversations initialization",t)}else Ae.error("Cannot complete initialization: remote config is null")}Se(e,t){Ae.error(e,t),this._conversationsManager=null,this.xe=!1}show(){this._conversationsManager?this._conversationsManager.show():Ae.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.we===!0&&!me(this._conversationsManager)}isVisible(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.isVisible())!==null&&e!==void 0&&e}sendMessage(e,t,n){var i=this;return ft(function*(){return i._conversationsManager?i._conversationsManager.sendMessage(e,t,n):(Ae.warn("Conversations not available yet."),null)})()}getMessages(e,t){var n=this;return ft(function*(){return n._conversationsManager?n._conversationsManager.getMessages(e,t):(Ae.warn("Conversations not available yet."),null)})()}markAsRead(e){var t=this;return ft(function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(Ae.warn("Conversations not available yet."),null)})()}getTickets(e){var t=this;return ft(function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(Ae.warn("Conversations not available yet."),null)})()}getCurrentTicketId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getCurrentTicketId())!==null&&e!==void 0?e:null}getWidgetSessionId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getWidgetSessionId())!==null&&e!==void 0?e:null}},Ci=class{constructor(e){var t;this.ke=!1,this.Pe=!1,this._instance=e,this._instance&&(t=this._instance.config.logs)!=null&&t.captureConsoleLogs&&(this.ke=!0)}onRemoteConfig(e){var t,n=(t=e.logs)==null?void 0:t.captureConsoleLogs;!O(n)&&n&&(this.ke=!0,this.loadIfEnabled())}reset(){}loadIfEnabled(){if(this.ke&&!this.Pe){var e=L("[logs]"),t=A?.__PosthogExtensions__;if(t){var n=t.loadExternalDependency;n?n(this._instance,"logs",i=>{var s;i||(s=t.logs)==null||!s.initializeLogs?e.error("Could not load logs script",i):(t.logs.initializeLogs(this._instance),this.Pe=!0)}):e.error("PostHog loadExternalDependency extension not found.")}else e.error("PostHog Extensions not found.")}}},fo=L("[RateLimiter]"),Ai=class{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=t=>{var n=t.text;if(n&&n.length)try{(JSON.parse(n).quota_limited||[]).forEach(i=>{fo.info((i||"events")+" is quota limited."),this.serverLimits[i]=new Date().getTime()+6e4})}catch(i){return void fo.warn('could not rate limit - continuing. Error: "'+i?.message+'"',{text:n})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var t,n,i;e===void 0&&(e=!1);var{captureEventsBurstLimit:s,captureEventsPerSecond:o}=this,a=new Date().getTime(),l=(t=(n=this.instance.persistence)==null?void 0:n.get_property(Zn))!==null&&t!==void 0?t:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=l.tokens<1;return u||e||(l.tokens=Math.max(0,l.tokens-1)),!u||this.lastEventRateLimited||e||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+o+" events per second and "+s+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=u,(i=this.instance.persistence)==null||i.set_property(Zn,l),{isRateLimited:u,remainingTokens:l.tokens}}isServerRateLimited(e){var t=this.serverLimits[e||"events"]||!1;return t!==!1&&new Date().getTime()<t}},Qe=L("[RemoteConfig]"),Ii=class{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=A._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.config}Te(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.loadExternalDependency?(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"remote-config",()=>e(this.remoteConfig)):(Qe.error("PostHog Extensions not found. Cannot load remote config."),e())}Ie(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:t=>{e(t.json)}})}load(){try{if(this.remoteConfig)return Qe.info("Using preloaded remote config",this.remoteConfig),void this.yi(this.remoteConfig);if(this._instance.M())return void Qe.warn("Remote config is disabled. Falling back to local config.");this.Te(e=>{if(!e)return Qe.info("No config found after loading remote JS config. Falling back to JSON."),void this.Ie(t=>{this.yi(t)});this.yi(e)})}catch(e){Qe.error("Error loading remote config",e)}}yi(e){e?this._instance.config.__preview_remote_config?(this._instance.yi(e),e.hasFeatureFlags!==!1&&this._instance.featureFlags.ensureFlagsLoaded()):Qe.info("__preview_remote_config is disabled. Logging config instead",e):Qe.error("Failed to fetch remote config from PostHog.")}},Mi=3e3,Ri=class{constructor(e,t){this.Ce=!0,this.Re=[],this.Fe=we(t?.flush_interval_ms||Mi,250,5e3,E.createLogger("flush interval"),Mi),this.Oe=e}enqueue(e){this.Re.push(e),this.Me||this.Ae()}unload(){this.je();var e=this.Re.length>0?this.De():{},t=Object.values(e);[...t.filter(n=>n.url.indexOf("/e")===0),...t.filter(n=>n.url.indexOf("/e")!==0)].map(n=>{this.Oe(S({},n,{transport:"sendBeacon"}))})}enable(){this.Ce=!1,this.Ae()}Ae(){var e=this;this.Ce||(this.Me=setTimeout(()=>{if(this.je(),this.Re.length>0){var t=this.De(),n=function(){var s=t[i],o=new Date().getTime();s.data&&$(s.data)&&D(s.data,a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp}),e.Oe(s)};for(var i in t)n()}},this.Fe))}je(){clearTimeout(this.Me),this.Me=void 0}De(){var e={};return D(this.Re,t=>{var n,i=t,s=(i?i.batchKey:null)||i.url;x(e[s])&&(e[s]=S({},i,{data:[]})),(n=e[s].data)==null||n.push(i.data)}),this.Re=[],e}},Qc=["retriesPerformedSoFar"],Ti=class{constructor(e){this.Le=!1,this.Ne=3e3,this.Re=[],this._instance=e,this.Re=[],this.Ue=!0,!x(y)&&"onLine"in y.navigator&&(this.Ue=y.navigator.onLine,this.ze=()=>{this.Ue=!0,this.Lt()},this.He=()=>{this.Ue=!1},z(y,"online",this.ze),z(y,"offline",this.He))}get length(){return this.Re.length}retriableRequest(e){var{retriesPerformedSoFar:t}=e,n=bo(e,Qc);dt(t)&&(n.url=jr(n.url,{retry_count:t})),this._instance._send_request(S({},n,{callback:i=>{i.statusCode!==200&&(i.statusCode<400||i.statusCode>=500)&&(t??0)<10?this.Be(S({retriesPerformedSoFar:t},n)):n.callback==null||n.callback(i)}}))}Be(e){var t=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=t+1;var n=function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=(Math.random()-.5)*(u-l);return Math.ceil(u+c)}(t),i=Date.now()+n;this.Re.push({retryAt:i,requestOptions:e});var s="Enqueued failed request for retry in "+n;navigator.onLine||(s+=" (Browser is offline)"),E.warn(s),this.Le||(this.Le=!0,this.qe())}qe(){if(this.We&&clearTimeout(this.We),this.Re.length===0)return this.Le=!1,void(this.We=void 0);this.We=setTimeout(()=>{this.Ue&&this.Re.length>0&&this.Lt(),this.qe()},this.Ne)}Lt(){var e=Date.now(),t=[],n=this.Re.filter(s=>s.retryAt<e||(t.push(s),!1));if(this.Re=t,n.length>0)for(var{requestOptions:i}of n)this.retriableRequest(i)}unload(){for(var{requestOptions:e}of(this.We&&(clearTimeout(this.We),this.We=void 0),this.Le=!1,x(y)||(this.ze&&(y.removeEventListener("online",this.ze),this.ze=void 0),this.He&&(y.removeEventListener("offline",this.He),this.He=void 0)),this.Re))try{this._instance._send_request(S({},e,{transport:"sendBeacon"}))}catch(t){E.error(t)}this.Re=[]}},Fi=class{constructor(e){this.Ge=()=>{var t,n,i,s;this.Ve||(this.Ve={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.Ve.lastScrollY=Math.ceil(a),this.Ve.maxScrollY=Math.max(a,(t=this.Ve.maxScrollY)!==null&&t!==void 0?t:0),this.Ve.maxScrollHeight=Math.max(l,(n=this.Ve.maxScrollHeight)!==null&&n!==void 0?n:0),this.Ve.lastContentY=u,this.Ve.maxContentY=Math.max(u,(i=this.Ve.maxContentY)!==null&&i!==void 0?i:0),this.Ve.maxContentHeight=Math.max(c,(s=this.Ve.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=e}getContext(){return this.Ve}resetContext(){var e=this.Ve;return setTimeout(this.Ge,0),e}startMeasuringScrollPosition(){z(y,"scroll",this.Ge,{capture:!0}),z(y,"scrollend",this.Ge,{capture:!0}),z(y,"resize",this.Ge)}scrollElement(){if(!this._instance.config.scroll_root_selector)return y?.document.documentElement;var e=$(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var t of e){var n=y?.document.querySelector(t);if(n)return n}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return y&&(y.scrollY||y.pageYOffset||y.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return y&&(y.scrollX||y.pageXOffset||y.document.documentElement.scrollLeft)||0}},eu=r=>ha(r?.config.mask_personal_data_properties,r?.config.custom_personal_data_properties),Lr=class{constructor(e,t,n,i){this.Je=s=>{var o=this.Ke();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Ye(this._instance)};this.Xe.register({[Jn]:a})}},this._instance=e,this.Qe=t,this.Xe=n,this.Ye=i||eu,this.Qe.onSessionId(this.Je)}Ke(){return this.Xe.props[Jn]}getSetOnceProps(){var e,t=(e=this.Ke())==null?void 0:e.props;return t?"r"in t?fa(t):{$referring_domain:t.referringDomain,$pathname:t.initialPathName,utm_source:t.utm_source,utm_campaign:t.utm_campaign,utm_medium:t.utm_medium,utm_content:t.utm_content,utm_term:t.utm_term}:{}}getSessionProps(){var e={};return D(Hi(this.getSetOnceProps()),(t,n)=>{n==="$current_url"&&(n="url"),e["$session_entry_"+Mn(n)]=t}),e}},Cn=L("[SessionId]"),Ur=class{on(e,t){return this.Ze.on(e,t)}constructor(e,t,n){var i;if(this.tr=[],this.ir=void 0,this.Ze=new ir,this.er=(c,p)=>!(!dt(c)||!dt(p))&&Math.abs(c-p)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.R=e.config,this.Xe=e.persistence,this.rr=void 0,this.sr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.nr=t||Ve,this.ar=n||Ve;var s=this.R.persistence_name||this.R.token,o=this.R.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*we(o,60,36e3,Cn.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.lr(),this.ur="ph_"+s+"_window_id",this.hr="ph_"+s+"_primary_window_exists",this.dr()){var a=B.W(this.ur),l=B.W(this.hr);a&&!l?this.rr=a:B.V(this.ur),B.G(this.hr,!0)}if((i=this.R.bootstrap)!=null&&i.sessionID)try{var u=(c=>{var p=c.replace(/-/g,"");if(p.length!==32)throw new Error("Not a valid UUID");if(p[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(p.substring(0,12),16)})(this.R.bootstrap.sessionID);this.vr(this.R.bootstrap.sessionID,new Date().getTime(),u)}catch(c){Cn.error("Invalid sessionID in bootstrap",c)}this.cr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.tr)&&(this.tr=[]),this.tr.push(e),this.sr&&e(this.sr,this.rr),()=>{this.tr=this.tr.filter(t=>t!==e)}}dr(){return this.R.persistence!=="memory"&&!this.Xe.ki&&B.H()}pr(e){e!==this.rr&&(this.rr=e,this.dr()&&B.G(this.ur,e))}gr(){return this.rr?this.rr:this.dr()?B.W(this.ur):null}vr(e,t,n){e===this.sr&&t===this._sessionActivityTimestamp&&n===this._sessionStartTimestamp||(this._sessionStartTimestamp=n,this._sessionActivityTimestamp=t,this.sr=e,this.Xe.register({[Sr]:[t,e,n]}))}_r(){var e=this.Xe.props[Sr];return $(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.vr(null,null,null)}destroy(){clearTimeout(this.mr),this.mr=void 0,this.ir&&y&&(y.removeEventListener("beforeunload",this.ir,{capture:!1}),this.ir=void 0),this.tr=[]}cr(){this.ir=()=>{this.dr()&&B.V(this.hr)},z(y,"beforeunload",this.ir,{capture:!1})}checkAndGetSessionAndWindowId(e,t){if(e===void 0&&(e=!1),t===void 0&&(t=null),this.R.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var n=t||new Date().getTime(),[i,s,o]=this._r(),a=this.gr(),l=dt(o)&&Math.abs(n-o)>864e5,u=!1,c=!s,p=!c&&!e&&this.er(n,i);c||p||l?(s=this.nr(),a=this.ar(),Cn.info("new session ID generated",{sessionId:s,windowId:a,changeReason:{noSessionId:c,activityTimeout:p,sessionPastMaximumLength:l}}),o=n,u=!0):a||(a=this.ar(),u=!0);var d=dt(i)&&e&&!l?i:n,h=dt(o)?o:new Date().getTime();return this.pr(a),this.vr(s,d,h),e||this.lr(),u&&this.tr.forEach(g=>g(s,a,u?{noSessionId:c,activityTimeout:p,sessionPastMaximumLength:l}:void 0)),{sessionId:s,windowId:a,sessionStartTimestamp:h,changeReason:u?{noSessionId:c,activityTimeout:p,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:i}}lr(){clearTimeout(this.mr),this.mr=setTimeout(()=>{var[e]=this._r();if(this.er(new Date().getTime(),e)){var t=this.sr;this.resetSessionId(),this.Ze.emit("forcedIdleReset",{idleSessionId:t})}},1.1*this.sessionTimeoutMs)}},tu=["$set_once","$set"],Le=L("[SiteApps]"),Oi=class{constructor(e){this._instance=e,this.br=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}yr(e,t){if(t){var n=this.globalsForEvent(t);this.br.push(n),this.br.length>1e3&&(this.br=this.br.slice(10))}}get siteAppLoaders(){var e;return(e=A._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}init(){if(this.isEnabled){var e=this._instance._addCaptureHook(this.yr.bind(this));this.wr=()=>{e(),this.br=[],this.wr=void 0}}}globalsForEvent(e){var t,n,i,s,o,a,l;if(!e)throw new Error("Event payload is required");var u={},c=this._instance.get_property("$groups")||[],p=this._instance.get_property("$stored_group_properties")||{};for(var[d,h]of Object.entries(p))u[d]={id:c[d],type:d,properties:h};var{$set_once:g,$set:f}=e;return{event:S({},bo(e,tu),{properties:S({},e.properties,f?{$set:S({},(t=(n=e.properties)==null?void 0:n.$set)!==null&&t!==void 0?t:{},f)}:{},g?{$set_once:S({},(i=(s=e.properties)==null?void 0:s.$set_once)!==null&&i!==void 0?i:{},g)}:{}),elements_chain:(o=(a=e.properties)==null?void 0:a.$elements_chain)!==null&&o!==void 0?o:"",distinct_id:(l=e.properties)==null?void 0:l.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:u}}setupSiteApp(e){var t=this.apps[e.id],n=()=>{var a;!t.errored&&this.br.length&&(Le.info("Processing "+this.br.length+" events for site app with id "+e.id),this.br.forEach(l=>t.processEvent==null?void 0:t.processEvent(l)),t.processedBuffer=!0),Object.values(this.apps).every(l=>l.processedBuffer||l.errored)&&((a=this.wr)==null||a.call(this))},i=!1,s=a=>{t.errored=!a,t.loaded=!0,Le.info("Site app with id "+e.id+" "+(a?"loaded":"errored")),i&&n()};try{var{processEvent:o}=e.init({posthog:this._instance,callback:a=>{s(a)}});o&&(t.processEvent=o),i=!0}catch(a){Le.error("Error while initializing PostHog app with config id "+e.id,a),s(!1)}if(i&&t.loaded)try{n()}catch(a){Le.error("Error while processing buffered events PostHog app with config id "+e.id,a),t.errored=!0}}Er(){var e=this.siteAppLoaders||[];for(var t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of e)this.setupSiteApp(n)}$r(e){if(Object.keys(this.apps).length!==0){var t=this.globalsForEvent(e);for(var n of Object.values(this.apps))try{n.processEvent==null||n.processEvent(t)}catch(i){Le.error("Error while processing event "+e.event+" for site app "+n.id,i)}}}onRemoteConfig(e){var t,n,i,s=this;if((t=this.siteAppLoaders)!=null&&t.length)return this.isEnabled?(this.Er(),void this._instance.on("eventCaptured",u=>this.$r(u))):void Le.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.wr)==null||n.call(this),(i=e.siteApps)!=null&&i.length)if(this.isEnabled){var o=function(u){var c;A["__$$ph_site_app_"+u]=s._instance,(c=A.__PosthogExtensions__)==null||c.loadSiteApp==null||c.loadSiteApp(s._instance,l,p=>{if(p)return Le.error("Error while initializing PostHog app with config id "+u,p)})};for(var{id:a,url:l}of e.siteApps)o(a)}else Le.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}},Pa=function(r,e){if(!r)return!1;var t=r.userAgent;if(t&&Cs(t,e))return!0;try{var n=r?.userAgentData;if(n!=null&&n.brands&&n.brands.some(i=>Cs(i?.brand,e)))return!0}catch{}return!!r.webdriver},Xt=function(r){return r.US="us",r.EU="eu",r.CUSTOM="custom",r}({}),go="i.posthog.com",$i=class{constructor(e){this.Sr={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,t=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return t||(t=this.apiHost.replace("."+go,".posthog.com")),t==="https://app.posthog.com"?"https://us.posthog.com":t}get region(){return this.Sr[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Sr[this.apiHost]=Xt.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Sr[this.apiHost]=Xt.EU:this.Sr[this.apiHost]=Xt.CUSTOM),this.Sr[this.apiHost]}endpointFor(e,t){if(t===void 0&&(t=""),t&&(t=t[0]==="/"?t:"/"+t),e==="ui")return this.uiHost+t;if(e==="flags")return this.flagsApiHost+t;if(this.region===Xt.CUSTOM)return this.apiHost+t;var n=go+t;switch(e){case"assets":return"https://"+this.region+"-assets."+n;case"api":return"https://"+this.region+"."+n}}},ru={icontains:(r,e)=>!!y&&e.href.toLowerCase().indexOf(r.toLowerCase())>-1,not_icontains:(r,e)=>!!y&&e.href.toLowerCase().indexOf(r.toLowerCase())===-1,regex:(r,e)=>!!y&&Gr(e.href,r),not_regex:(r,e)=>!!y&&!Gr(e.href,r),exact:(r,e)=>e.href===r,is_not:(r,e)=>e.href!==r},Ni=class r{constructor(e){var t=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(n){n===void 0&&(n=!1),t.getWebExperiments(i=>{r.kr("retrieved web experiments from the server"),t.Pr=new Map,i.forEach(s=>{if(s.feature_flag_key){var o;t.Pr&&(r.kr("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=t.Pr)==null||o.set(s.feature_flag_key,s));var a=t._instance.getFeatureFlag(s.feature_flag_key);K(a)&&s.variants[a]&&t.Tr(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];r.Ir(u)&&t.Tr(s.name,l,u.transforms)}})},n)},this._instance=e,this._instance.onFeatureFlags(n=>{this.onFeatureFlags(n)})}onFeatureFlags(e){if(this._is_bot())r.kr("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if(O(this.Pr))return this.Pr=new Map,this.loadIfEnabled(),void this.previewWebExperiment();r.kr("applying feature flags",e),e.forEach(t=>{var n;if(this.Pr&&(n=this.Pr)!=null&&n.has(t)){var i,s=this._instance.getFeatureFlag(t),o=(i=this.Pr)==null?void 0:i.get(t);s&&o!=null&&o.variants[s]&&this.Tr(o.name,s,o.variants[s].transforms)}})}}previewWebExperiment(){var e=r.getWindowLocation();if(e!=null&&e.search){var t=Fr(e?.search,"__experiment_id"),n=Fr(e?.search,"__experiment_variant");t&&n&&(r.kr("previewing web experiments "+t+" && "+n),this.getWebExperiments(i=>{this.Cr(parseInt(t),n,i)},!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,t,n){if(this._instance.config.disable_web_experiments&&!n)return e([]);var i=this._instance.get_property("$web_experiments");if(i&&!t)return e(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:s=>{if(s.statusCode!==200||!s.json)return e([]);var o=s.json.experiments||[];return e(o)}})}Cr(e,t,n){var i=n.filter(s=>s.id===e);i&&i.length>0&&(r.kr("Previewing web experiment ["+i[0].name+"] with variant ["+t+"]"),this.Tr(i[0].name,t,i[0].variants[t].transforms))}static Ir(e){return!O(e.conditions)&&r.Rr(e)&&r.Fr(e)}static Rr(e){var t;if(O(e.conditions)||O((t=e.conditions)==null?void 0:t.url))return!0;var n,i,s,o=r.getWindowLocation();return!!o&&((n=e.conditions)==null||!n.url||ru[(i=(s=e.conditions)==null?void 0:s.urlMatchType)!==null&&i!==void 0?i:"icontains"](e.conditions.url,o))}static getWindowLocation(){return y?.location}static Fr(e){var t;if(O(e.conditions)||O((t=e.conditions)==null?void 0:t.utm))return!0;var n=ca();if(n.utm_source){var i,s,o,a,l,u,c,p,d=(i=e.conditions)==null||(i=i.utm)==null||!i.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==n.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==n.utm_source,g=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==n.utm_medium,f=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((p=e.conditions)==null||(p=p.utm)==null?void 0:p.utm_term)==n.utm_term;return d&&g&&f&&h}return!1}static kr(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];E.info("[WebExperiments] "+e,n)}Tr(e,t,n){this._is_bot()?r.kr("Refusing to render web experiment since the viewer is a likely bot"):t!=="control"?n.forEach(i=>{if(i.selector){var s;r.kr("applying transform of variant "+t+" for experiment "+e+" ",i);var o=(s=document)==null?void 0:s.querySelectorAll(i.selector);o?.forEach(a=>{var l=a;i.html&&(l.innerHTML=i.html),i.css&&l.setAttribute("style",i.css)})}}):r.kr("Control variants leave the page unmodified.")}_is_bot(){return le&&this._instance?Pa(le,this._instance.config.custom_blocked_useragents):void 0}},nu=L("[PostHog ExternalIntegrations]"),iu={intercom:"intercom-integration",crispChat:"crisp-chat-integration"},Di=class{constructor(e){this._instance=e}it(e,t){var n;(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,e,i=>{if(i)return nu.error("failed to load script",i);t()})}startIfEnabledOrStop(){var e=this,t=function(o){var a,l,u;!i||(a=A.__PosthogExtensions__)!=null&&(a=a.integrations)!=null&&a[o]||e.it(iu[o],()=>{var c;(c=A.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[o])==null||c.start(e._instance)}),!i&&(l=A.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[o]&&((u=A.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[o])==null||u.stop())};for(var[n,i]of Object.entries((s=this._instance.config.integrations)!==null&&s!==void 0?s:{})){var s;t(n)}}},qi="[SessionRecording]",Lt=L(qi),Vr=class{get started(){var e;return!((e=this.Or)==null||!e.isStarted)}get status(){return this.Or?this.Or.status:this.Mr&&!this.Ar?"disabled":"lazy_loading"}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.Mr=!1,this.jr=void 0,this._instance=e,!this._instance.sessionManager)throw Lt.error("started without valid sessionManager"),new Error(qi+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(qi+' cannot be used with cookieless_mode="always"')}get Ar(){var e,t=!((e=this._instance.get_property(fn))==null||!e.enabled),n=!this._instance.config.disable_session_recording,i=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return y&&t&&n&&!i}startIfEnabledOrStop(e){var t;if(!this.Ar||(t=this.Or)==null||!t.isStarted){var n=!x(Object.assign)&&!x(Array.from);this.Ar&&n?(this.Dr(e),Lt.info("starting")):this.stopRecording()}}Dr(e){var t,n,i;this.Ar&&(A!=null&&(t=A.__PosthogExtensions__)!=null&&(t=t.rrweb)!=null&&t.record&&(n=A.__PosthogExtensions__)!=null&&n.initSessionRecording?this.Lr(e):(i=A.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.Nr,s=>{if(s)return Lt.error("could not load recorder",s);this.Lr(e)}))}stopRecording(){var e,t;(e=this.jr)==null||e.call(this),this.jr=void 0,(t=this.Or)==null||t.stop()}Ur(){var e;(e=this._instance.persistence)==null||e.unregister(Ko)}zr(e){if(this._instance.persistence){var t,n,i=this._instance.persistence,s=()=>{var o=e.sessionRecording===!1?void 0:e.sessionRecording,a=o?.sampleRate,l=O(a)?null:parseFloat(a);O(l)&&this.Ur();var u=o?.minimumDurationMilliseconds;i.register({[fn]:S({enabled:!!o},o,{networkPayloadCapture:S({capturePerformance:e.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:l,minimumDurationMilliseconds:x(u)?null:u,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers})})};s(),(t=this.jr)==null||t.call(this),this.jr=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(s)}}onRemoteConfig(e){"sessionRecording"in e?e.sessionRecording!==!1?(this.zr(e),this.Mr=!0,this.startIfEnabledOrStop()):this.Mr=!0:Lt.info("skipping remote config with no sessionRecording",e)}log(e,t){var n;t===void 0&&(t="log"),(n=this.Or)!=null&&n.log?this.Or.log(e,t):Lt.warn("log called before recorder was ready")}get Nr(){var e,t,n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(fn);return(n==null||(t=n.scriptConfig)==null?void 0:t.script)||"lazy-recorder"}Lr(e){var t,n;if((t=A.__PosthogExtensions__)==null||!t.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.Or||(this.Or=(n=A.__PosthogExtensions__)==null?void 0:n.initSessionRecording(this._instance),this.Or._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.Or.start(e)}onRRwebEmit(e){var t;(t=this.Or)==null||t.onRRwebEmit==null||t.onRRwebEmit(e)}overrideLinkedFlag(){var e,t;this.Or||(t=this._instance.persistence)==null||t.register({$replay_override_linked_flag:!0}),(e=this.Or)==null||e.overrideLinkedFlag()}overrideSampling(){var e,t;this.Or||(t=this._instance.persistence)==null||t.register({$replay_override_sampling:!0}),(e=this.Or)==null||e.overrideSampling()}overrideTrigger(e){var t,n;this.Or||(n=this._instance.persistence)==null||n.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(t=this.Or)==null||t.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.Or)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,t){var n;return!((n=this.Or)==null||!n.tryAddCustomEvent(e,t))}},Zt={},ji=()=>{},ht="posthog",xa=!Kc&&se?.indexOf("MSIE")===-1&&se?.indexOf("Mozilla")===-1,yo=r=>{var e;return S({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:lc(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:ji,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:r??"unset",__preview_deferred_init_extensions:!1,debug:W&&K(W?.search)&&W.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!0,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(y==null||(e=y.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:t=>{var n="Bad HTTP status: "+t.statusCode+" "+t.text;E.error(n)},get_device_id:t=>t,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:Mi},error_tracking:{},_onCapture:ji,__preview_eager_load_replay:!1},(t=>({rageclick:!(t&&t>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(t&&t>="2025-05-24")||"history_change",session_recording:t&&t>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:t&&t>="2026-01-30"?"head":"body",internal_or_test_user_hostname:t&&t>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0}))(r))},mo=r=>{var e={};x(r.process_person)||(e.person_profiles=r.process_person),x(r.xhr_headers)||(e.request_headers=r.xhr_headers),x(r.cookie_name)||(e.persistence_name=r.cookie_name),x(r.disable_cookie)||(e.disable_persistence=r.disable_cookie),x(r.store_google)||(e.save_campaign_params=r.store_google),x(r.verbose)||(e.debug=r.verbose);var t=U({},e,r);return $(r.property_blacklist)&&(x(r.property_denylist)?t.property_denylist=r.property_blacklist:$(r.property_denylist)?t.property_denylist=[...r.property_blacklist,...r.property_denylist]:E.error("Invalid value for property_denylist config: "+r.property_denylist)),t},Gi=class{constructor(){this.__forceAllowLocalhost=!1}get Hr(){return this.__forceAllowLocalhost}set Hr(e){E.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},zr=class r{get decideEndpointWasHit(){var e,t;return(e=(t=this.featureFlags)==null?void 0:t.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,t;return(e=(t=this.featureFlags)==null?void 0:t.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){this.webPerformance=new Gi,this.Br=!1,this.version=Ie.LIB_VERSION,this.qr=new ir,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=yo(),this.SentryIntegration=ci,this.sentryIntegration=e=>function(t,n){var i=la(t,n);return{name:aa,processEvent:s=>i(s)}}(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Wr=!1,this.Gr=null,this.Vr=null,this.Jr=null,this.featureFlags=new _i(this),this.toolbar=new ui(this),this.scrollManager=new Fi(this),this.pageViewManager=new Nr(this),this.surveys=new Ei(this),this.conversations=new Si(this),this.logs=new Ci(this),this.experiments=new Ni(this),this.exceptions=new vi(this),this.rateLimiter=new Ai(this),this.requestRouter=new $i(this),this.consent=new oi(this),this.externalIntegrations=new Di(this),this.people={set:(e,t,n)=>{var i=K(e)?{[e]:t}:e;this.setPersonProperties(i),n?.({})},set_once:(e,t,n)=>{var i=K(e)?{[e]:t}:e;this.setPersonProperties(void 0,i),n?.({})}},this.on("eventCaptured",e=>E.info('send "'+e?.event+'"',e))}init(e,t,n){if(n&&n!==ht){var i,s=(i=Zt[n])!==null&&i!==void 0?i:new r;return s._init(e,t,n),Zt[n]=s,Zt[ht][n]=s,s}return this._init(e,t,n)}_init(e,t,n){var i;if(t===void 0&&(t={}),x(e)||Rn(e))return E.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},t.debug=this.Kr(t.debug),this.Yr=t,this.Xr=[],t.person_profiles&&(this.Vr=t.person_profiles),this.set_config(U({},yo(t.defaults),mo(t),{name:n,token:e})),this.config.on_xhr_error&&E.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=t.disable_compression?void 0:Te.GZipJS;var s=this.Qr();this.persistence=new Jt(this.config,s),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Jt(S({},this.config,{persistence:"sessionStorage"}),s);var o=S({},this.persistence.props),a=S({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Zr=new Ri(b=>this.ts(b),this.config.request_queue_config),this.es=new Ti(this),this.__request_queue=[];var l=this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut();if(l||(this.sessionManager=new Ur(this),this.sessionPropsManager=new Lr(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?(E.info("Deferring extension initialization to improve startup performance"),setTimeout(()=>{this.rs(l)},0)):(E.info("Initializing extensions synchronously"),this.rs(l)),Ie.DEBUG=Ie.DEBUG||this.config.debug,Ie.DEBUG&&E.info("Starting in debug mode",{this:this,config:t,thisC:S({},this.config),p:o,s:a}),((i=t.bootstrap)==null?void 0:i.distinctID)!==void 0){var u,c,p=this.config.get_device_id(Ve()),d=(u=t.bootstrap)!=null&&u.isIdentifiedID?p:t.bootstrap.distinctID;this.persistence.set_property(Me,(c=t.bootstrap)!=null&&c.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:t.bootstrap.distinctID,$device_id:d})}if(this.ss()){var h,g,f=Object.keys(((h=t.bootstrap)==null?void 0:h.featureFlags)||{}).filter(b=>{var v;return!((v=t.bootstrap)==null||(v=v.featureFlags)==null||!v[b])}).reduce((b,v)=>{var _;return b[v]=((_=t.bootstrap)==null||(_=_.featureFlags)==null?void 0:_[v])||!1,b},{}),m=Object.keys(((g=t.bootstrap)==null?void 0:g.featureFlagPayloads)||{}).filter(b=>f[b]).reduce((b,v)=>{var _,k;return(_=t.bootstrap)!=null&&(_=_.featureFlagPayloads)!=null&&_[v]&&(b[v]=(k=t.bootstrap)==null||(k=k.featureFlagPayloads)==null?void 0:k[v]),b},{});this.featureFlags.receivedFeatureFlags({featureFlags:f,featureFlagPayloads:m})}if(l)this.register_once({distinct_id:Ft,$device_id:null},"");else if(!this.get_distinct_id()){var w=this.config.get_device_id(Ve());this.register_once({distinct_id:w,$device_id:w},""),this.persistence.set_property(Me,"anonymous")}return z(y,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),t.segment?Mc(this,()=>this.ns()):this.ns(),ze(this.config._onCapture)&&this.config._onCapture!==ji&&(E.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",b=>this.config._onCapture(b.event,b))),this.config.ip&&E.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this}rs(e){var t=performance.now();this.historyAutocapture=new li(this),this.historyAutocapture.startIfEnabled();var n=[];n.push(()=>{new pi(this).startIfEnabledOrStop()}),n.push(()=>{var i;this.siteApps=new Oi(this),(i=this.siteApps)==null||i.init()}),e||n.push(()=>{this.sessionRecording=new Vr(this),this.sessionRecording.startIfEnabledOrStop()}),this.config.disable_scroll_properties||n.push(()=>{this.scrollManager.startMeasuringScrollPosition()}),n.push(()=>{this.autocapture=new ri(this),this.autocapture.startIfEnabled()}),n.push(()=>{this.surveys.loadIfEnabled()}),n.push(()=>{this.logs.loadIfEnabled()}),n.push(()=>{this.conversations.loadIfEnabled()}),n.push(()=>{this.productTours=new bi(this),this.productTours.loadIfEnabled()}),n.push(()=>{this.heatmaps=new hi(this),this.heatmaps.startIfEnabled()}),n.push(()=>{this.webVitalsAutocapture=new di(this)}),n.push(()=>{this.exceptionObserver=new ai(this),this.exceptionObserver.startIfEnabledOrStop()}),n.push(()=>{this.deadClicksAutocapture=new $r(this,Ic),this.deadClicksAutocapture.startIfEnabled()}),n.push(()=>{if(this.os){var i=this.os;this.os=void 0,this.yi(i)}}),this.ls(n,t)}ls(e,t){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-t>=30&&e.length>0)return void setTimeout(()=>{this.ls(e,t)},0);var n=e.shift();if(n)try{n()}catch(s){E.error("Error initializing extension:",s)}}var i=Math.round(performance.now()-t);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:i}),this.config.__preview_deferred_init_extensions&&E.info("PostHog extensions initialized ("+i+"ms)")}yi(e){var t,n,i,s,o,a,l,u,c;if(!P||!P.body)return E.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this.yi(e)},500);this.config.__preview_deferred_init_extensions&&(this.os=e),this.compression=void 0,e.supportedCompression&&!this.config.disable_compression&&(this.compression=F(e.supportedCompression,Te.GZipJS)?Te.GZipJS:F(e.supportedCompression,Te.Base64)?Te.Base64:void 0),(t=e.analytics)!=null&&t.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Vr?this.Vr:"identified_only"}),(n=this.siteApps)==null||n.onRemoteConfig(e),(i=this.sessionRecording)==null||i.onRemoteConfig(e),(s=this.autocapture)==null||s.onRemoteConfig(e),(o=this.heatmaps)==null||o.onRemoteConfig(e),this.surveys.onRemoteConfig(e),this.logs.onRemoteConfig(e),this.conversations.onRemoteConfig(e),(a=this.productTours)==null||a.onRemoteConfig(e),(l=this.webVitalsAutocapture)==null||l.onRemoteConfig(e),(u=this.exceptionObserver)==null||u.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(c=this.deadClicksAutocapture)==null||c.onRemoteConfig(e)}ns(){try{this.config.loaded(this)}catch(n){E.critical("`loaded` function failed",n)}if(this.us(),this.config.internal_or_test_user_hostname&&W!=null&&W.hostname){var e=W.hostname,t=this.config.internal_or_test_user_hostname;(typeof t=="string"?e===t:t.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.hs()},1),new Ii(this).load(),this.featureFlags.flags()}us(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.Zr)==null||e.enable())}_dom_loaded(){this.is_capturing()&&He(this.__request_queue,e=>this.ts(e)),this.__request_queue=[],this.us()}_handle_unload(){var e,t;this.surveys.handlePageUnload(),this.config.request_batching?(this.ds()&&this.capture("$pageleave"),(e=this.Zr)==null||e.unload(),(t=this.es)==null||t.unload()):this.ds()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}_send_request(e){this.__loaded&&(xa?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=jr(e.url,{ip:this.config.ip?1:0}),e.headers=S({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,e.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(t=>{var n,i,s,o=S({},t);o.timeout=o.timeout||6e4,o.url=jr(o.url,{_:new Date().getTime().toString(),ver:Ie.LIB_VERSION,compression:o.compression});var a=(n=o.transport)!==null&&n!==void 0?n:"fetch",l=kr.filter(c=>!o.disableTransport||!c.transport||!o.disableTransport.includes(c.transport)),u=(i=(s=Vo(l,c=>c.transport===a))==null?void 0:s.method)!==null&&i!==void 0?i:l[0].method;if(!u)throw new Error("No available transport method");u(o)})(S({},e,{callback:t=>{var n,i;this.rateLimiter.checkForLimiting(t),t.statusCode>=400&&((n=(i=this.config).on_request_error)==null||n.call(i,t)),e.callback==null||e.callback(t)}}))))}ts(e){this.es?this.es.retriableRequest(e):this._send_request(e)}_execute_array(e){var t,n=[],i=[],s=[];He(e,a=>{a&&(t=a[0],$(t)?s.push(a):ze(a)?a.call(this):$(a)&&t==="alias"?n.push(a):$(a)&&t.indexOf("capture")!==-1&&ze(this[t])?s.push(a):i.push(a))});var o=function(a,l){He(a,function(u){if($(u[0])){var c=l;D(u,function(p){c=c[p[0]].apply(c,p.slice(1))})}else this[u[0]].apply(this,u.slice(1))},l)};o(n,this),o(i,this),o(s,this)}ss(){var e,t;return((e=this.config.bootstrap)==null?void 0:e.featureFlags)&&Object.keys((t=this.config.bootstrap)==null?void 0:t.featureFlags).length>0||!1}push(e){this._execute_array([e])}capture(e,t,n){var i;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Zr){if(this.is_capturing())if(!x(e)&&K(e)){var s=!this.config.opt_out_useragent_filter&&this._is_bot();if(!(s&&!this.config.__preview_capture_bot_pageviews)){var o=n!=null&&n.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(o==null||!o.isRateLimited){t!=null&&t.$current_url&&!K(t?.$current_url)&&(E.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),t==null||delete t.$current_url),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var a=new Date,l=n?.timestamp||a,u=Ve(),c={uuid:u,event:e,properties:this.calculateEventProperties(e,t||{},l,u)};e==="$pageview"&&this.config.__preview_capture_bot_pageviews&&s&&(c.event="$bot_pageview",c.properties.$browser_type="bot"),o&&(c.properties.$lib_rate_limit_remaining_tokens=o.remainingTokens),n?.$set&&(c.$set=n?.$set);var p,d=e!=="$groupidentify",h=this.vs(n?.$set_once,d);if(h&&(c.$set_once=h),(c=oc(c,n!=null&&n._noTruncate?null:this.config.properties_string_max_length)).timestamp=l,x(n?.timestamp)||(c.properties.$event_time_override_provided=!0,c.properties.$event_time_override_system_time=a),e===Wt.DISMISSED||e===Wt.SENT){var g=t?.[Sn.SURVEY_ID],f=t?.[Sn.SURVEY_ITERATION];p={id:g,current_iteration:f},localStorage.getItem(ho(p))||localStorage.setItem(ho(p),"true"),c.$set=S({},c.$set,{[Yc({id:g,current_iteration:f},e===Wt.SENT?"responded":"dismissed")]:!0})}else e===Wt.SHOWN&&(c.$set=S({},c.$set,{[Sn.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));var m=S({},c.properties.$set,c.$set);if(gt(m)||this.setPersonPropertiesForFlags(m),!O(this.config.before_send)){var w=this.cs(c);if(!w)return;c=w}this.qr.emit("eventCaptured",c);var b={method:"POST",url:(i=n?._url)!==null&&i!==void 0?i:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:c,compression:"best-available",batchKey:n?._batchKey};return!this.config.request_batching||n&&(n==null||!n._batchKey)||n!=null&&n.send_instantly?this.ts(b):this.Zr.enqueue(b),c}E.critical("This capture call is ignored due to client rate limiting.")}}else E.error("No event name provided to posthog.capture")}else E.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",t=>e(t.event,t))}calculateEventProperties(e,t,n,i,s){if(n=n||new Date,!this.persistence||!this.sessionPersistence)return t;var o=s?void 0:this.persistence.remove_event_timer(e),a=S({},t);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(a.$cookieless_mode=!0),e==="$snapshot"){var l=S({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!K(a.distinct_id)&&!$e(a.distinct_id)||Rn(a.distinct_id))&&E.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=Nc(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:p,windowId:d}=this.sessionManager.checkAndGetSessionAndWindowId(s,n.getTime());a.$session_id=p,a.$window_id=d}this.sessionPropsManager&&U(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&U(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.es)==null?void 0:h.length}catch(w){a.$sdk_debug_error_capturing_properties=String(w)}if(this.requestRouter.region===Xt.CUSTOM&&(a.$lib_custom_api_host=this.config.api_host),u=e!=="$pageview"||s?e!=="$pageleave"||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(n):this.pageViewManager.doPageView(n,i),a=U(a,u),e==="$pageview"&&P&&(a.title=P.title),!x(o)){var g=n.getTime()-o;a.$duration=parseFloat((g/1e3).toFixed(3))}se&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser"),(a=U({},c,this.persistence.properties(),this.sessionPersistence.properties(),a)).$is_identified=this._isIdentified(),$(this.config.property_denylist)?D(this.config.property_denylist,function(w){delete a[w]}):E.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var f=this.config.sanitize_properties;f&&(E.error("sanitize_properties is deprecated. Use before_send instead"),a=f(a,e));var m=this.fs();return a.$process_person_profile=m,m&&!s&&this.ps("_calculate_event_properties"),a}vs(e,t){var n;if(t===void 0&&(t=!0),!this.persistence||!this.fs()||this.Br)return e;var i=this.persistence.get_initial_props(),s=(n=this.sessionPropsManager)==null?void 0:n.getSetOnceProps(),o=U({},i,s||{},e||{}),a=this.config.sanitize_properties;return a&&(E.error("sanitize_properties is deprecated. Use before_send instead"),o=a(o,"$set_once")),t&&(this.Br=!0),gt(o)?void 0:o}register(e,t){var n;(n=this.persistence)==null||n.register(e,t)}register_once(e,t,n){var i;(i=this.persistence)==null||i.register_once(e,t,n)}register_for_session(e){var t;(t=this.sessionPersistence)==null||t.register(e)}unregister(e){var t;(t=this.persistence)==null||t.unregister(e)}unregister_for_session(e){var t;(t=this.sessionPersistence)==null||t.unregister(e)}gs(e,t){this.register({[e]:t})}getFeatureFlag(e,t){return this.featureFlags.getFeatureFlag(e,t)}getFeatureFlagPayload(e){return this.featureFlags.getFeatureFlagPayload(e)}getFeatureFlagResult(e,t){return this.featureFlags.getFeatureFlagResult(e,t)}isFeatureEnabled(e,t){return this.featureFlags.isFeatureEnabled(e,t)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateFlags(e,t,n){var i=n!=null&&n.merge?this.featureFlags.getFlagVariants():{},s=n!=null&&n.merge?this.featureFlags.getFlagPayloads():{},o=S({},i,e),a=S({},s,t),l={};for(var[u,c]of Object.entries(o)){var p=typeof c=="string";l[u]={key:u,enabled:!!p||!!c,variant:p?c:void 0,reason:void 0,metadata:x(a?.[u])?void 0:{id:0,version:void 0,description:void 0,payload:a[u]}}}this.featureFlags.receivedFeatureFlags({flags:l})}updateEarlyAccessFeatureEnrollment(e,t,n){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,t,n)}getEarlyAccessFeatures(e,t,n){return t===void 0&&(t=!1),this.featureFlags.getEarlyAccessFeatures(e,t,n)}on(e,t){return this.qr.on(e,t)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var t,n;return(t=(n=this.sessionManager)==null?void 0:n.onSessionId(e))!==null&&t!==void 0?t:()=>{}}getSurveys(e,t){t===void 0&&(t=!1),this.surveys.getSurveys(e,t)}getActiveMatchingSurveys(e,t){t===void 0&&(t=!1),this.surveys.getActiveMatchingSurveys(e,t)}renderSurvey(e,t){this.surveys.renderSurvey(e,t)}displaySurvey(e,t){t===void 0&&(t=Zc),this.surveys.displaySurvey(e,t)}cancelPendingSurvey(e){this.surveys.cancelPendingSurvey(e)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,t){return t===void 0&&(t=!1),this.surveys.canRenderSurveyAsync(e,t)}identify(e,t,n){if(!this.__loaded||!this.persistence)return E.uninitializedWarning("posthog.identify");if($e(e)&&(e=e.toString(),E.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),e)if(["distinct_id","distinctid"].includes(e.toLowerCase()))E.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(e!==Ft){if(this.ps("posthog.identify")){var i=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var s=i;this.register_once({$had_persisted_distinct_id:!0,$device_id:s},"")}e!==i&&e!==this.get_property(Vt)&&(this.unregister(Vt),this.register({distinct_id:e}));var o=(this.persistence.get_property(Me)||"anonymous")==="anonymous";e!==i&&o?(this.persistence.set_property(Me,"identified"),this.setPersonPropertiesForFlags(S({},n||{},t||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:i},{$set:t||{},$set_once:n||{}}),this.Jr=oo(e,t,n),this.featureFlags.setAnonymousDistinctId(i)):(t||n)&&this.setPersonProperties(t,n),e!==i&&(this.reloadFeatureFlags(),this.unregister(Cr))}}else E.critical('The string "'+Ft+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else E.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,t){if((e||t)&&this.ps("posthog.setPersonProperties")){var n=oo(this.get_distinct_id(),e,t);this.Jr!==n?(this.setPersonPropertiesForFlags(S({},t||{},e||{})),this.capture("$set",{$set:e||{},$set_once:t||{}}),this.Jr=n):E.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,t,n){if(e&&t){var i=this.getGroups();i[e]!==t&&this.resetGroupPropertiesForFlags(e),this.register({$groups:S({},i,{[e]:t})}),n&&(this.capture("$groupidentify",{$group_type:e,$group_key:t,$group_set:n}),this.setGroupPropertiesForFlags({[e]:n})),i[e]===t||n||this.reloadFeatureFlags()}else E.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,t){t===void 0&&(t=!0),this.featureFlags.setPersonPropertiesForFlags(e,t)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,t){t===void 0&&(t=!0),this.ps("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,t)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var t,n,i,s;if(E.info("reset"),!this.__loaded)return E.uninitializedWarning("posthog.reset");var o=this.get_property("$device_id");if(this.consent.reset(),(t=this.persistence)==null||t.clear(),(n=this.sessionPersistence)==null||n.clear(),this.surveys.reset(),this.featureFlags.reset(),(i=this.persistence)==null||i.set_property(Me,"anonymous"),(s=this.sessionManager)==null||s.resetSessionId(),this.Jr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:Ft,$device_id:null},"");else{var a=this.config.get_device_id(Ve());this.register_once({distinct_id:a,$device_id:e?a:o},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,t;return(e=(t=this.sessionManager)==null?void 0:t.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:t,sessionStartTimestamp:n}=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+t);if(e!=null&&e.withTimestamp&&n){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!n)return i;i+="?t="+Math.max(Math.floor((new Date().getTime()-n)/1e3)-o,0)}return i}alias(e,t){return e===this.get_property(zo)?(E.critical("Attempting to create alias for existing People user - aborting."),-2):this.ps("posthog.alias")?(x(t)&&(t=this.get_distinct_id()),e!==t?(this.gs(Vt,e),this.capture("$create_alias",{alias:e,distinct_id:t})):(E.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var t=S({},this.config);if(H(e)){var n,i,s,o,a,l,u;U(this.config,mo(e));var c=this.Qr();(n=this.persistence)==null||n.update_config(this.config,t,c),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Jt(S({},this.config,{persistence:"sessionStorage"}),c);var p=this.Kr(this.config.debug);Oe(p)&&(this.config.debug=p),Oe(this.config.debug)&&(this.config.debug?(Ie.DEBUG=!0,G.H()&&G.G("ph_debug","true"),E.info("set_config",{config:e,oldConfig:t,newConfig:S({},this.config)})):(Ie.DEBUG=!1,G.H()&&G.V("ph_debug"))),(i=this.exceptionObserver)==null||i.onConfigChange(),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),(o=this.autocapture)==null||o.startIfEnabled(),(a=this.heatmaps)==null||a.startIfEnabled(),(l=this.exceptionObserver)==null||l.startIfEnabledOrStop(),this.surveys.loadIfEnabled(),this._s(),(u=this.externalIntegrations)==null||u.startIfEnabledOrStop()}}startSessionRecording(e){var t=e===!0,n={sampling:t||!(e==null||!e.sampling),linked_flag:t||!(e==null||!e.linked_flag),url_trigger:t||!(e==null||!e.url_trigger),event_trigger:t||!(e==null||!e.event_trigger)};if(Object.values(n).some(Boolean)){var i,s,o,a,l;(i=this.sessionManager)==null||i.checkAndGetSessionAndWindowId(),n.sampling&&((s=this.sessionRecording)==null||s.overrideSampling()),n.linked_flag&&((o=this.sessionRecording)==null||o.overrideLinkedFlag()),n.url_trigger&&((a=this.sessionRecording)==null||a.overrideTrigger("url")),n.event_trigger&&((l=this.sessionRecording)==null||l.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,t){var n=new Error("PostHog syntheticException"),i=this.exceptions.buildProperties(e,{handled:!0,syntheticException:n});return this.exceptions.sendExceptionEvent(S({},i,t))}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var t;return(t=this.persistence)==null?void 0:t.props[e]}getSessionProperty(e){var t;return(t=this.sessionPersistence)==null?void 0:t.props[e]}toString(){var e,t=(e=this.config.name)!==null&&e!==void 0?e:ht;return t!==ht&&(t=ht+"."+t),t}_isIdentified(){var e,t;return((e=this.persistence)==null?void 0:e.get_property(Me))==="identified"||((t=this.sessionPersistence)==null?void 0:t.get_property(Me))==="identified"}fs(){var e,t;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&gt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Vt])&&((t=this.persistence)==null||(t=t.props)==null||!t[Ir]))}ds(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.fs()||this.ps("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.ps("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}ps(e){return this.config.person_profiles==="never"?(E.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.gs(Ir,!0),!0)}Qr(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut(),t=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||e&&!!t}_s(){var e,t,n,i,s=this.Qr();return((e=this.persistence)==null?void 0:e.ki)!==s&&((n=this.persistence)==null||n.set_disabled(s)),((t=this.sessionPersistence)==null?void 0:t.ki)!==s&&((i=this.sessionPersistence)==null||i.set_disabled(s)),s}opt_in_capturing(e){var t;if(this.config.cookieless_mode!=="always"){var n,i,s;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=new Ur(this),this.pageViewManager=new Nr(this),this.persistence&&(this.sessionPropsManager=new Lr(this,this.sessionManager,this.persistence)),this.sessionRecording=new Vr(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this._s(),this.us(),(t=this.sessionRecording)==null||t.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((s=e?.captureEventName)!==null&&s!==void 0?s:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.hs()}else E.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e,t,n;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this._s(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:Ft,$device_id:null}),(e=this.sessionManager)==null||e.destroy(),(t=this.pageViewManager)==null||t.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(n=this.sessionRecording)==null||n.stopRecording(),this.sessionRecording=void 0,this.hs())):E.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===Re.GRANTED?"granted":e===Re.DENIED?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isExplicitlyOptedOut()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this._s()}_is_bot(){return le?Pa(le,this.config.custom_blocked_useragents):void 0}hs(){P&&(P.visibilityState==="visible"?this.Wr||(this.Wr=!0,this.capture("$pageview",{title:P.title},{send_instantly:!0}),this.Gr&&(P.removeEventListener("visibilitychange",this.Gr),this.Gr=null)):this.Gr||(this.Gr=this.hs.bind(this),z(P,"visibilitychange",this.Gr)))}debug(e){e===!1?(y?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(y?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}M(){var e,t,n,i,s,o,a,l=this.Yr||{};return"advanced_disable_flags"in l?!!l.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(E.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(n="advanced_disable_decide",i=!1,s=E,o=(t="advanced_disable_flags")in(e=l)&&!O(e[t]),a=n in e&&!O(e[n]),o?e[t]:a?(s&&s.warn("Config field '"+n+"' is deprecated. Please use '"+t+"' instead. The old field will be removed in a future major version."),e[n]):i)}cs(e){if(O(this.config.before_send))return e;var t=$(this.config.before_send)?this.config.before_send:[this.config.before_send],n=e;for(var i of t){if(n=i(n),O(n)){var s="Event '"+e.event+"' was rejected in beforeSend function";return Fl(e.event)?E.warn(s+". This can cause unexpected behavior."):E.info(s),null}n.properties&&!gt(n.properties)||E.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return n}getPageViewId(){var e;return(e=this.pageViewManager.Kt)==null?void 0:e.pageViewId}captureTraceFeedback(e,t){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:t})}captureTraceMetric(e,t,n){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:t,$ai_metric_value:String(n)})}Kr(e){var t=Oe(e)&&!e,n=G.H()&&G.q("ph_debug")==="true";return!t&&(!!n||e)}};(function(r,e){for(var t=0;t<e.length;t++)r.prototype[e[t]]=sc(r.prototype[e[t]])})(zr,["identify"]);var vo;var Wr=(vo=Zt[ht]=new zr,function(){function r(){r.done||(r.done=!0,xa=!1,D(Zt,function(e){e._dom_loaded()}))}P!=null&&P.addEventListener?P.readyState==="complete"?r():z(P,"DOMContentLoaded",r,{capture:!1}):y&&E.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}(),vo);var su="phc_u9YDYUeUxo3CYn16XGrrwpVb8ycXgcjz5DarvIKRAAG",lr=class r{constructor(e){R(this,"initialized",!1);this.initPostHog(e)}static getInstance(e){if(typeof window>"u")throw new Error("[PaymentKit Analytics] PostHog requires a browser environment");let t=window.__paymentKitPostHog__;if(t){if(t.apiBaseUrl!==e)throw new Error(`[PaymentKit Analytics] PostHog already initialized with apiBaseUrl "${t.apiBaseUrl}", cannot re-initialize with different apiBaseUrl "${e}"`);return t.instance}let n=new r(e);return window.__paymentKitPostHog__={instance:n,apiBaseUrl:e},n}initPostHog(e){try{Wr.init(su,{api_host:`${e}/ingest`,ui_host:"https://us.posthog.com",persistence:"memory",disable_session_recording:!0,autocapture:!1,capture_pageview:!1,request_batching:!1,opt_out_useragent_filter:!0,loaded:()=>{this.initialized=!0}})}catch(t){console.warn("[PaymentKit Analytics] Failed to initialize PostHog:",t)}}identify(e){try{Wr.identify(e)}catch(t){console.warn("[PaymentKit Analytics] Failed to identify:",t)}}capture(e,t){try{Wr.capture(e,t)}catch(n){console.warn("[PaymentKit Analytics] Failed to capture event:",n)}}isInitialized(){return this.initialized}};var Ji=class{constructor(){R(this,"adapters",[]);R(this,"testMock",null)}init(e,t){try{this.addAdapter(lr.getInstance(e)),t&&this.enableTestMode()}catch(n){console.warn("[PaymentKit Analytics] Init failed:",n)}}enableTestMode(){this.testMock||(this.testMock=new Tt,this.addAdapter(this.testMock),typeof window<"u"&&(window.__paymentKitAnalytics__=this.testMock))}getTestMock(){return this.testMock}addAdapter(e){this.adapters.includes(e)||this.adapters.push(e)}clearAdapters(){this.adapters=[],this.testMock=null,typeof window<"u"&&delete window.__paymentKitAnalytics__}identify(e){for(let t of this.adapters)try{t.identify(e)}catch{}}capture(e,t){for(let n of this.adapters)try{n.capture(e,t)}catch{}}isInitialized(){return this.adapters.some(e=>e.isInitialized())}},ke=new Ji;var cr=class cr{constructor(e,t){R(this,"startTime");R(this,"checkoutSessionId");R(this,"requestId");R(this,"inputReadyTracked",!1);this.startTime=performance.now(),this.checkoutSessionId=e,this.requestId=t}trackPageReady(){cr.pageReadyTracked||(cr.pageReadyTracked=!0,ke.capture("checkout_page_ready",{checkout_session_id:this.checkoutSessionId,request_id:this.requestId,elapsed_ms:this.getElapsedMs()}))}trackInputReady(){this.inputReadyTracked||(this.inputReadyTracked=!0,ke.capture("checkout_input_ready",{checkout_session_id:this.checkoutSessionId,request_id:this.requestId,elapsed_ms:this.getElapsedMs()}))}trackSubmit(){ke.capture("checkout_submit",{checkout_session_id:this.checkoutSessionId,request_id:this.requestId,elapsed_ms:this.getElapsedMs()})}trackSuccess(e){ke.capture("checkout_success",{checkout_session_id:this.checkoutSessionId,checkout_attempt_id:e,request_id:this.requestId,total_elapsed_ms:this.getElapsedMs()})}trackFail(e,t,n){ke.capture("checkout_fail",{checkout_session_id:this.checkoutSessionId,checkout_attempt_id:e,request_id:this.requestId,error_code:t,error_message:n,total_elapsed_ms:this.getElapsedMs()})}getElapsedMs(){return Math.round(performance.now()-this.startTime)}};R(cr,"pageReadyTracked",!1);var ur=cr;var ou=class extends Error{constructor(e,t){super(t);R(this,"code");this.name="PenpalError",this.code=e}},pe=ou,au=r=>({name:r.name,message:r.message,stack:r.stack,penpalCode:r instanceof pe?r.code:void 0}),lu=({name:r,message:e,stack:t,penpalCode:n})=>{let i=n?new pe(n,e):new Error(e);return i.name=r,i.stack=t,i},cu=Symbol("Reply"),es,Ia,uu=(Ia=class{constructor(r,e){R(this,"value");R(this,"transferables");Z(this,es,cu);this.value=r,this.transferables=e?.transferables}},es=new WeakMap,Ia),pu=uu,ue="penpal",Zr=r=>typeof r=="object"&&r!==null,Ta=r=>typeof r=="function",du=r=>Zr(r)&&r.namespace===ue,Xr=r=>r.type==="SYN",rs=r=>r.type==="ACK1",Zi=r=>r.type==="ACK2",Fa=r=>r.type==="CALL",Oa=r=>r.type==="REPLY",hu=r=>r.type==="DESTROY",$a=(r,e=[])=>{let t=[];for(let n of Object.keys(r)){let i=r[n];Ta(i)?t.push([...e,n]):Zr(i)&&t.push(...$a(i,[...e,n]))}return t},fu=(r,e)=>{let t=r.reduce((n,i)=>Zr(n)?n[i]:void 0,e);return Ta(t)?t:void 0},Xe=r=>r.join("."),Ea=(r,e,t)=>({namespace:ue,channel:r,type:"REPLY",callId:e,isError:!0,...t instanceof Error?{value:au(t),isSerializedErrorInstance:!0}:{value:t}}),gu=(r,e,t,n)=>{let i=!1,s=async o=>{if(i||!Fa(o))return;n?.(`Received ${Xe(o.methodPath)}() call`,o);let{methodPath:a,args:l,id:u}=o,c,p;try{let d=fu(a,e);if(!d)throw new pe("METHOD_NOT_FOUND",`Method \`${Xe(a)}\` is not found.`);let h=await d(...l);h instanceof pu&&(p=h.transferables,h=await h.value),c={namespace:ue,channel:t,type:"REPLY",callId:u,value:h}}catch(d){c=Ea(t,u,d)}if(!i)try{n?.(`Sending ${Xe(a)}() reply`,c),r.sendMessage(c,p)}catch(d){throw d.name==="DataCloneError"&&(c=Ea(t,u,d),n?.(`Sending ${Xe(a)}() reply`,c),r.sendMessage(c)),d}};return r.addMessageHandler(s),()=>{i=!0,r.removeMessageHandler(s)}},yu=gu,Na=crypto.randomUUID?.bind(crypto)??(()=>new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")),mu=Symbol("CallOptions"),ts,Ma,vu=(Ma=class{constructor(r){R(this,"transferables");R(this,"timeout");Z(this,ts,mu);this.transferables=r?.transferables,this.timeout=r?.timeout}},ts=new WeakMap,Ma),_u=vu,bu=new Set(["apply","call","bind"]),Da=(r,e,t=[])=>new Proxy(t.length?()=>{}:Object.create(null),{get(n,i){if(i!=="then")return t.length&&bu.has(i)?Reflect.get(n,i):Da(r,e,[...t,i])},apply(n,i,s){return r(t,s)}}),Sa=r=>new pe("CONNECTION_DESTROYED",`Method call ${Xe(r)}() failed due to destroyed connection`),wu=(r,e,t)=>{let n=!1,i=new Map,s=l=>{if(!Oa(l))return;let{callId:u,value:c,isError:p,isSerializedErrorInstance:d}=l,h=i.get(u);h&&(i.delete(u),t?.(`Received ${Xe(h.methodPath)}() call`,l),p?h.reject(d?lu(c):c):h.resolve(c))};return r.addMessageHandler(s),{remoteProxy:Da((l,u)=>{if(n)throw Sa(l);let c=Na(),p=u[u.length-1],d=p instanceof _u,{timeout:h,transferables:g}=d?p:{},f=d?u.slice(0,-1):u;return new Promise((m,w)=>{let b=h!==void 0?window.setTimeout(()=>{i.delete(c),w(new pe("METHOD_CALL_TIMEOUT",`Method call ${Xe(l)}() timed out after ${h}ms`))},h):void 0;i.set(c,{methodPath:l,resolve:m,reject:w,timeoutId:b});try{let v={namespace:ue,channel:e,type:"CALL",id:c,methodPath:l,args:f};t?.(`Sending ${Xe(l)}() call`,v),r.sendMessage(v,g)}catch(v){w(new pe("TRANSMISSION_FAILED",v.message))}})},t),destroy:()=>{n=!0,r.removeMessageHandler(s);for(let{methodPath:l,reject:u,timeoutId:c}of i.values())clearTimeout(c),u(Sa(l));i.clear()}}},ku=wu,Pu=()=>{let r,e;return{promise:new Promise((n,i)=>{r=n,e=i}),resolve:r,reject:e}},xu=Pu,Eu=class extends Error{constructor(r){super(`You've hit a bug in Penpal. Please file an issue with the following information: ${r}`)}},Yr=Eu,Qi="deprecated-penpal",Su=r=>Zr(r)&&"penpal"in r,Cu=r=>r.split("."),Ca=r=>r.join("."),qa=r=>new Yr(`Unexpected message to translate: ${JSON.stringify(r)}`),Au=r=>{if(r.penpal==="syn")return{namespace:ue,channel:void 0,type:"SYN",participantId:Qi};if(r.penpal==="ack")return{namespace:ue,channel:void 0,type:"ACK2"};if(r.penpal==="call")return{namespace:ue,channel:void 0,type:"CALL",id:r.id,methodPath:Cu(r.methodName),args:r.args};if(r.penpal==="reply")return r.resolution==="fulfilled"?{namespace:ue,channel:void 0,type:"REPLY",callId:r.id,value:r.returnValue}:{namespace:ue,channel:void 0,type:"REPLY",callId:r.id,isError:!0,...r.returnValueIsError?{value:r.returnValue,isSerializedErrorInstance:!0}:{value:r.returnValue}};throw qa(r)},Iu=r=>{if(rs(r))return{penpal:"synAck",methodNames:r.methodPaths.map(Ca)};if(Fa(r))return{penpal:"call",id:r.id,methodName:Ca(r.methodPath),args:r.args};if(Oa(r))return r.isError?{penpal:"reply",id:r.callId,resolution:"rejected",...r.isSerializedErrorInstance?{returnValue:r.value,returnValueIsError:!0}:{returnValue:r.value}}:{penpal:"reply",id:r.callId,resolution:"fulfilled",returnValue:r.value};throw qa(r)},Mu=({messenger:r,methods:e,timeout:t,channel:n,log:i})=>{let s=Na(),o,a=[],l=!1,u=$a(e),{promise:c,resolve:p,reject:d}=xu(),h=t!==void 0?setTimeout(()=>{d(new pe("CONNECTION_TIMEOUT",`Connection timed out after ${t}ms`))},t):void 0,g=()=>{for(let k of a)k()},f=()=>{if(l)return;a.push(yu(r,e,n,i));let{remoteProxy:k,destroy:I}=ku(r,n,i);a.push(I),clearTimeout(h),l=!0,p({remoteProxy:k,destroy:g})},m=()=>{let k={namespace:ue,type:"SYN",channel:n,participantId:s};i?.("Sending handshake SYN",k);try{r.sendMessage(k)}catch(I){d(new pe("TRANSMISSION_FAILED",I.message))}},w=k=>{if(i?.("Received handshake SYN",k),k.participantId===o&&o!==Qi||(o=k.participantId,m(),!(s>o||o===Qi)))return;let M={namespace:ue,channel:n,type:"ACK1",methodPaths:u};i?.("Sending handshake ACK1",M);try{r.sendMessage(M)}catch(C){d(new pe("TRANSMISSION_FAILED",C.message));return}},b=k=>{i?.("Received handshake ACK1",k);let I={namespace:ue,channel:n,type:"ACK2"};i?.("Sending handshake ACK2",I);try{r.sendMessage(I)}catch(M){d(new pe("TRANSMISSION_FAILED",M.message));return}f()},v=k=>{i?.("Received handshake ACK2",k),f()},_=k=>{Xr(k)&&w(k),rs(k)&&b(k),Zi(k)&&v(k)};return r.addMessageHandler(_),a.push(()=>r.removeMessageHandler(_)),m(),c},Ru=Mu,Tu=r=>{let e=!1,t;return(...n)=>(e||(e=!0,t=r(...n)),t)},Fu=Tu,Aa=new WeakSet,Ou=({messenger:r,methods:e={},timeout:t,channel:n,log:i})=>{if(!r)throw new pe("INVALID_ARGUMENT","messenger must be defined");if(Aa.has(r))throw new pe("INVALID_ARGUMENT","A messenger can only be used for a single connection");Aa.add(r);let s=[r.destroy],o=Fu(u=>{if(u){let c={namespace:ue,channel:n,type:"DESTROY"};try{r.sendMessage(c)}catch{}}for(let c of s)c();i?.("Connection destroyed")}),a=u=>du(u)&&u.channel===n;return{promise:(async()=>{try{r.initialize({log:i,validateReceivedMessage:a}),r.addMessageHandler(p=>{hu(p)&&o(!1)});let{remoteProxy:u,destroy:c}=await Ru({messenger:r,methods:e,timeout:t,channel:n,log:i});return s.push(c),u}catch(u){throw o(!0),u}})(),destroy:()=>{o(!0)}}},ja=Ou,Be,nt,xt,Et,it,We,ce,st,Jr,St,pr,dr,Ct,Ra,$u=(Ra=class{constructor({remoteWindow:r,allowedOrigins:e}){Z(this,Be);Z(this,nt);Z(this,xt);Z(this,Et);Z(this,it);Z(this,We,new Set);Z(this,ce);Z(this,st,!1);R(this,"initialize",({log:r,validateReceivedMessage:e})=>{_e(this,xt,r),_e(this,Et,e),window.addEventListener("message",T(this,dr))});R(this,"sendMessage",(r,e)=>{if(Xr(r)){let t=T(this,St).call(this,r);T(this,Be).postMessage(r,{targetOrigin:t,transfer:e});return}if(rs(r)||T(this,st)){let t=T(this,st)?Iu(r):r,n=T(this,St).call(this,r);T(this,Be).postMessage(t,{targetOrigin:n,transfer:e});return}if(Zi(r)){let{port1:t,port2:n}=new MessageChannel;_e(this,ce,t),t.addEventListener("message",T(this,Ct)),t.start();let i=[n,...e||[]],s=T(this,St).call(this,r);T(this,Be).postMessage(r,{targetOrigin:s,transfer:i});return}if(T(this,ce)){T(this,ce).postMessage(r,{transfer:e});return}throw new Yr("Port is undefined")});R(this,"addMessageHandler",r=>{T(this,We).add(r)});R(this,"removeMessageHandler",r=>{T(this,We).delete(r)});R(this,"destroy",()=>{window.removeEventListener("message",T(this,dr)),T(this,pr).call(this),T(this,We).clear()});Z(this,Jr,r=>T(this,nt).some(e=>e instanceof RegExp?e.test(r):e===r||e==="*"));Z(this,St,r=>{if(Xr(r))return"*";if(!T(this,it))throw new Yr("Concrete remote origin not set");return T(this,it)==="null"&&T(this,nt).includes("*")?"*":T(this,it)});Z(this,pr,()=>{T(this,ce)?.removeEventListener("message",T(this,Ct)),T(this,ce)?.close(),_e(this,ce,void 0)});Z(this,dr,({source:r,origin:e,ports:t,data:n})=>{var i,s,o;if(r===T(this,Be)&&(Su(n)&&((i=T(this,xt))==null||i.call(this,"Please upgrade the child window to the latest version of Penpal."),_e(this,st,!0),n=Au(n)),!!((s=T(this,Et))!=null&&s.call(this,n)))){if(!T(this,Jr).call(this,e)){(o=T(this,xt))==null||o.call(this,`Received a message from origin \`${e}\` which did not match allowed origins \`[${T(this,nt).join(", ")}]\``);return}if(Xr(n)&&(T(this,pr).call(this),_e(this,it,e)),Zi(n)&&!T(this,st)){if(_e(this,ce,t[0]),!T(this,ce))throw new Yr("No port received on ACK2");T(this,ce).addEventListener("message",T(this,Ct)),T(this,ce).start()}for(let a of T(this,We))a(n)}});Z(this,Ct,({data:r})=>{var e;if((e=T(this,Et))!=null&&e.call(this,r))for(let t of T(this,We))t(r)});if(!r)throw new pe("INVALID_ARGUMENT","remoteWindow must be defined");_e(this,Be,r),_e(this,nt,e?.length?e:[window.origin])}},Be=new WeakMap,nt=new WeakMap,xt=new WeakMap,Et=new WeakMap,it=new WeakMap,We=new WeakMap,ce=new WeakMap,st=new WeakMap,Jr=new WeakMap,St=new WeakMap,pr=new WeakMap,dr=new WeakMap,Ct=new WeakMap,Ra),Ga=$u;var Qr=({window:r,methods:e})=>{let t=new Ga({remoteWindow:r,allowedOrigins:["*"]});return ja({methods:e,messenger:t})};var La=(r,e)=>Qr({window:r.contentWindow,methods:e});var tn=class tn{constructor(e,t){R(this,"penpalConn");R(this,"_methods");this.penpalConn=e,this._methods=t}get publicEndpoints(){let e={get:(t,n)=>async(...i)=>await this._methods.queryPublicEndpoint(n,i[0],i[1])};return new Proxy({},e)}destroy(){this.penpalConn.destroy()}};R(tn,"createFromPenpalConnection",async e=>{let t=await e.promise;return new tn(e,t)});var en=tn;var Ua={local:{baseUrl:"http://localhost:9101",apiBaseUrl:"http://localhost:9000"},sandbox:{baseUrl:"https://staging.paymentkit.com/customer",apiBaseUrl:"https://staging.paymentkit.com"},production:{baseUrl:"https://app.paymentkit.com/customer",apiBaseUrl:"https://app.paymentkit.com"}};function Nu(){if(typeof window<"u"){let e=new URLSearchParams(window.location.search).get("api_base_url");if(e)return{baseUrl:window.location.origin,apiBaseUrl:e};let t=window.location.hostname;if(t.includes("loclx.io")){let n=t.replace(/cportal|playground/,"api");return{baseUrl:`https://${t}`,apiBaseUrl:`https://${n}`}}}return Ua.local}function Va(r){if(r==="tunnel")return Nu();let t=Ua[r];if(!t)throw new Error(`Invalid environment: ${r}. Must be one of: local, tunnel, sandbox, production`);return t}var za="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Ha=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=za[t[r]&63];return e};var Du={local:"dev",tunnel:"dev",sandbox:"stg",production:"prod"},ns="__paymentKitRequestId__";function Ka(r){let e=Du[r]||"dev",t=Ha(12);return`pk_${e}_${t}`}function Pe(r){if(typeof window<"u"&&window[ns])return window[ns];let e=Ka(r);return typeof window<"u"&&(window[ns]=e),e}function is(r){return{headers:{"x-request-id":r}}}var ss;function Ba(r){return{lang:r?.lang??ss?.lang,message:r?.message,abortEarly:r?.abortEarly??ss?.abortEarly,abortPipeEarly:r?.abortPipeEarly??ss?.abortPipeEarly}}var qu;function ju(r){return qu?.get(r)}var Gu;function Lu(r){return Gu?.get(r)}var Uu;function Vu(r,e){return Uu?.get(r)?.get(e)}function zu(r){let e=typeof r;return e==="string"?`"${r}"`:e==="number"||e==="bigint"||e==="boolean"?`${r}`:e==="object"||e==="function"?(r&&Object.getPrototypeOf(r)?.constructor?.name)??"null":e}function ot(r,e,t,n,i){let s=i&&"input"in i?i.input:t.value,o=i?.expected??r.expects??null,a=i?.received??zu(s),l={kind:r.kind,type:r.type,input:s,expected:o,received:a,message:`Invalid ${e}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:r.requirement,path:i?.path,issues:i?.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},u=r.kind==="schema",c=i?.message??r.message??Vu(r.reference,l.lang)??(u?Lu(l.lang):null)??n.message??ju(l.lang);c!==void 0&&(l.message=typeof c=="function"?c(l):c),u&&(t.typed=!1),t.issues?t.issues.push(l):t.issues=[l]}function os(r){return{version:1,vendor:"valibot",validate(e){return r["~run"]({value:e},Ba())}}}function Wa(r){if(r.path){let e="";for(let t of r.path)if(typeof t.key=="string"||typeof t.key=="number")e?e+=`.${t.key}`:e+=t.key;else return null;return e}return null}var Hu=/^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu;function as(r){return{kind:"validation",type:"email",reference:as,expects:null,async:!1,requirement:Hu,message:r,"~run"(e,t){return e.typed&&!this.requirement.test(e.value)&&ot(this,"email",e,t),e}}}function ls(r,e){return{kind:"validation",type:"max_length",reference:ls,async:!1,expects:`<=${r}`,requirement:r,message:e,"~run"(t,n){return t.typed&&t.value.length>this.requirement&&ot(this,"length",t,n,{received:`${t.value.length}`}),t}}}function cs(r,e){return{kind:"validation",type:"min_length",reference:cs,async:!1,expects:`>=${r}`,requirement:r,message:e,"~run"(t,n){return t.typed&&t.value.length<this.requirement&&ot(this,"length",t,n,{received:`${t.value.length}`}),t}}}function At(r){return{kind:"validation",type:"non_empty",reference:At,async:!1,expects:"!0",message:r,"~run"(e,t){return e.typed&&e.value.length===0&&ot(this,"length",e,t,{received:"0"}),e}}}function Ku(r,e,t){return typeof r.fallback=="function"?r.fallback(e,t):r.fallback}function Bu(r,e,t){return typeof r.default=="function"?r.default(e,t):r.default}function us(r,e){return{kind:"schema",type:"object",reference:us,expects:"Object",async:!1,entries:r,message:e,get"~standard"(){return os(this)},"~run"(t,n){let i=t.value;if(i&&typeof i=="object"){t.typed=!0,t.value={};for(let s in this.entries){let o=this.entries[s];if(s in i||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){let a=s in i?i[s]:Bu(o),l=o["~run"]({value:a},n);if(l.issues){let u={type:"object",origin:"value",input:i,key:s,value:a};for(let c of l.issues)c.path?c.path.unshift(u):c.path=[u],t.issues?.push(c);if(t.issues||(t.issues=l.issues),n.abortEarly){t.typed=!1;break}}l.typed||(t.typed=!1),t.value[s]=l.value}else if(o.fallback!==void 0)t.value[s]=Ku(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(ot(this,"key",t,n,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:i,key:s,value:i[s]}]}),n.abortEarly))break}}else ot(this,"type",t,n);return t}}}function at(r){return{kind:"schema",type:"string",reference:at,expects:"string",async:!1,message:r,get"~standard"(){return os(this)},"~run"(e,t){return typeof e.value=="string"?e.typed=!0:ot(this,"type",e,t),e}}}function It(...r){return{...r[0],pipe:r,get"~standard"(){return os(this)},"~run"(e,t){for(let n of r)if(n.kind!=="metadata"){if(e.issues&&(n.kind==="schema"||n.kind==="transformation")){e.typed=!1;break}(!e.issues||!t.abortEarly&&!t.abortPipeEarly)&&(e=n["~run"](e,t))}return e}}}function Xa(r,e,t){let n=r["~run"]({value:e},Ba(t));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}var ps=async(r,e={})=>{let t=us({customer_name:It(at("required"),At("required"),cs(4,"invalid"),ls(40,"invalid")),customer_email:It(at("required"),At("required"),as("invalid")),customer_country:It(at("required"),At("required")),customer_zip_code:e.optionalZipCode?It(at("required")):It(at("required"),At("required"))}),n=Xa(t,r);return n.issues?{isSuccess:!1,errors:n.issues.reduce((s,o)=>{let a=Wa(o);return s[a]=o.kind==="schema"?"required":o.message,s},{})}:{isSuccess:!0}};var Ya=r=>{let e=document.querySelector(r);if(!e)throw new Error(`Cannot find element with selector: ${r}`);return e},Ye=r=>r,rn=(r,e,t)=>{let n=document.createElement("iframe"),s=new URLSearchParams(t).toString();return n.src=`${e}/embeds/v1/${r}${s?`?${s}`:""}`,Object.assign(n.style,{width:"100%",height:"100%",border:"none"}),n};function xe(){return{ipAddress:void 0,browserInfo:{userAgent:navigator.userAgent,language:navigator.language,screenHeight:window.screen.height,screenWidth:window.screen.width,colorDepth:window.screen.colorDepth,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone},processorFraudInfo:void 0}}var Xu=(r,e,t)=>{let n=rn("tunnel-x",r,{checkout_token:t,api_base_url:e});Object.assign(n.style,{width:"0",height:"0",position:"absolute",visibility:"hidden"}),document.body.appendChild(n);let i=La(n,{});return{unmount:()=>{i.destroy(),document.body.removeChild(n)},connection:i}},Yu=({environment:r,secureToken:e,paymentMethods:t,cardTokenizationMode:n,vgsVaultId:i,vgsEnvironment:s,__enableAnalyticsTestMode:o})=>{let{baseUrl:a,apiBaseUrl:l}=Va(r);console.log(`[PaymentKit] v${ks} initialized (env: ${r})`);let u=Pe(r);console.log(`[PaymentKit] checkout_request_id: ${u}`),ke.init(l,o),ke.identify(e);let c=new ur(e,u);c.trackPageReady();let{connection:p,unmount:d}=Xu(a,l,e),h={baseUrl:a,apiBaseUrl:l,secureToken:e,environment:r,tunnelXConnection:p,timingTracker:c,checkoutRequestId:u,cardTokenizationMode:n,vgsVaultId:i,vgsEnvironment:s,_sessionConfigReady:void 0};if(n===void 0){let b=`${l}/api/checkout-sessions/token/${e}`;console.log(`[PaymentKit] cardTokenizationMode not provided \u2014 auto-detecting from session API: ${b}`),h._sessionConfigReady=fetch(b).then(v=>v.ok?v.json():(console.warn(`[PaymentKit] Session config fetch failed with status ${v.status}`),null)).then(v=>{if(v&&typeof v=="object"&&typeof v.card_tokenization_mode=="string"){h.cardTokenizationMode=v.card_tokenization_mode||"direct",console.log(`[PaymentKit] Session config detected \u2014 cardTokenizationMode: ${h.cardTokenizationMode}`);let _=v.vgs_vault_id,k=v.vgs_environment;_&&/^tnt[a-z0-9]+$/.test(_)&&(k==="sandbox"||k==="live")?(h.vgsVaultId=_,h.vgsEnvironment=k,console.log(`[PaymentKit] VGS config valid \u2014 vaultId: ${_}, environment: ${k}`)):h.cardTokenizationMode==="vgs"&&(console.warn(`[PaymentKit] Invalid VGS config from session API (vaultId: ${_}, env: ${k}), falling back to direct mode`),h.cardTokenizationMode="direct")}else console.log("[PaymentKit] Session response missing card_tokenization_mode \u2014 defaulting to direct mode"),h.cardTokenizationMode="direct"}).catch(v=>{console.error("[PaymentKit] Session config fetch error \u2014 falling back to direct mode:",v),h.cardTokenizationMode="direct"})}else console.log(`[PaymentKit] cardTokenizationMode explicitly set: ${n}`);let g=t.map(b=>b(h)),f=g.reduce((b,{name:v,externalFuncs:_})=>(b[v]=_,b),{});return{submit:({paymentMethod:b,fields:v,options:_,onSuccess:k,onError:I})=>{let M=g.find(({name:C})=>C===b);if(!M){I({root:"payment_method_not_found"});return}M.internalFuncs.submitPayment(v,_).then(({data:C,errors:j})=>{j?I(j):k(C)}).catch(C=>{console.error("PaymentKit:submit:catch",C),C?.response?.data?I(C.response.data):C?.message?I({root:C.message}):I({root:"unknown_error"})})},cleanup:()=>{for(let b of g)b.internalFuncs.cleanup&&b.internalFuncs.cleanup();d()},...f}},Ja=Yu;var nn=class{constructor(e){R(this,"config",null);R(this,"mockScenario");this.mockScenario=e??"none"}initialize(e){return this.mockScenario!=="none"?(console.log("[MockApplePay:Airwallex] initialize called (mock mode)"),this.config=e,!0):typeof window>"u"||!window.ApplePaySession?(console.error("[ApplePay:Airwallex] ApplePaySession not available (not Safari or unsupported device)"),!1):(this.config=e,!0)}async canMakePayment(){if(this.mockScenario!=="none")return console.log("[MockApplePay:Airwallex] canMakePayment: true (mock mode)"),!0;if(!window.ApplePaySession)return!1;try{let e=window.ApplePaySession.canMakePayments();return console.log("[ApplePay:Airwallex] canMakePayments:",e),e}catch(e){return console.error("[ApplePay:Airwallex] canMakePayment error:",e),!1}}formatAmount(e,t){return["BIF","CLP","DJF","GNF","ISK","JPY","KMF","KRW","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"].includes(t.toUpperCase())?e.toString():(e/100).toFixed(2)}async showPaymentSheet(e){if(this.mockScenario==="success")return console.log("[MockApplePay:Airwallex] showPaymentSheet: returning mock success token"),{success:!0,token:{paymentData:{version:"EC_v1",data:"MOCK_ENCRYPTED_DATA",signature:"MOCK_SIGNATURE",header:{ephemeralPublicKey:"MOCK_PUBLIC_KEY",publicKeyHash:"MOCK_HASH",transactionId:"mock_txn_123"}},paymentMethod:{displayName:"Visa 4242",network:"Visa",type:"debit"},transactionIdentifier:"MOCK_TXN_ID"},payerEmail:"mock@example.com",complete:o=>console.log(`[MockApplePay:Airwallex] complete: ${o}`)};if(this.mockScenario==="cancelled")return console.log("[MockApplePay:Airwallex] showPaymentSheet: returning mock cancelled"),{success:!1,cancelled:!0};if(!this.config)return{success:!1,error:"Apple Pay not initialized"};if(!window.ApplePaySession)return{success:!1,error:"ApplePaySession not available"};let t=this.config,n=this.formatAmount(t.amount,t.currency),i={countryCode:t.country.toUpperCase(),currencyCode:t.currency.toUpperCase(),supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS"],total:{label:t.merchantName||"Total",amount:n,type:"final"},requiredBillingContactFields:["email"]};return new Promise(s=>{try{let o=new window.ApplePaySession(3,i),a=window.ApplePaySession.STATUS_SUCCESS,l=window.ApplePaySession.STATUS_FAILURE;o.onvalidatemerchant=async u=>{console.log("[ApplePay:Airwallex] onvalidatemerchant called",u.validationURL);try{let c=await e(u.validationURL);if(c.error||!c.merchantSession){console.error("[ApplePay:Airwallex] Merchant validation failed:",c.error),o.abort(),s({success:!1,error:c.error||"Merchant validation failed"});return}o.completeMerchantValidation(c.merchantSession),console.log("[ApplePay:Airwallex] Merchant validation completed")}catch(c){console.error("[ApplePay:Airwallex] Merchant validation error:",c),o.abort(),s({success:!1,error:`Merchant validation error: ${c}`})}},o.onpaymentauthorized=u=>{console.log("[ApplePay:Airwallex] onpaymentauthorized called");let c=u.payment,p={paymentData:c.token.paymentData,paymentMethod:{displayName:c.token.paymentMethod.displayName,network:c.token.paymentMethod.network,type:c.token.paymentMethod.type},transactionIdentifier:c.token.transactionIdentifier},d=c.billingContact?.emailAddress??c.shippingContact?.emailAddress??void 0;s({success:!0,token:p,payerEmail:d,complete:g=>{console.log("[ApplePay:Airwallex] completing session with status:",g);let f=g==="success"?a:l;o.completePayment({status:f})}})},o.oncancel=()=>{console.log("[ApplePay:Airwallex] oncancel - user cancelled"),s({success:!1,cancelled:!0})},console.log("[ApplePay:Airwallex] Starting Apple Pay session"),o.begin()}catch(o){console.error("[ApplePay:Airwallex] Session creation error:",o),s({success:!1,error:`Failed to create Apple Pay session: ${o}`})}})}};function ds(r){let{url:e,size:t,radius:n=6,onMessage:i}=r;return new Promise(s=>{let o=!1,a=document.createElement("div");a.id="pk-iframe-modal-overlay",a.setAttribute("role","dialog"),a.setAttribute("aria-modal","true"),a.setAttribute("aria-label","3D Secure Verification"),a.style.cssText=`
11
+ `)).length,s=0;s<n;s++){var o=r.charCodeAt(s),a=null;o<128?t++:a=o>127&&o<2048?String.fromCharCode(o>>6|192,63&o|128):String.fromCharCode(o>>12|224,o>>6&63|128,63&o|128),_e(a)||(t>e&&(i+=r.substring(e,t)),i+=a,e=t=s+1)}return t>e&&(i+=r.substring(e,r.length)),i},Zc=!!Rn||!!Mn,ao="text/plain",Gr=function(r,e,t){var n;t===void 0&&(t=!0);var[s,i]=r.split("?"),o=C({},e),a=(n=i?.split("&").map(u=>{var c,[p,d]=u.split("="),h=t&&(c=o[p])!==null&&c!==void 0?c:d;return delete o[p],p+"="+h}))!==null&&n!==void 0?n:[],l=Ec(o);return l&&a.push(l),s+"?"+a.join("&")},Wt=(r,e)=>JSON.stringify(r,(t,n)=>typeof n=="bigint"?n.toString():n,e),Pn=r=>{var{data:e,compression:t}=r;if(e){if(t===Fe.GZipJS){var n=Yc(function(l,u){var c=l.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(l);for(var p=new ge(l.length+(l.length>>>1)),d=0,h=function(w){p[d++]=w},g=0;g<c;++g){if(d+5>p.length){var f=new ge(d+8+(c-g<<1));f.set(p),p=f}var m=l.charCodeAt(g);m<128||u?h(m):m<2048?(h(192|m>>>6),h(128|63&m)):m>55295&&m<57344?(h(240|(m=65536+(1047552&m)|1023&l.charCodeAt(++g))>>>18),h(128|m>>>12&63),h(128|m>>>6&63),h(128|63&m)):(h(224|m>>>12),h(128|m>>>6&63),h(128|63&m))}return ka(p,0,d)}(Wt(e)),{mtime:0}),s=new Blob([n],{type:ao});return{contentType:ao,body:s,estimatedSize:s.size}}if(t===Fe.Base64){var i=function(l){var u,c,p,d,h,g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",f=0,m=0,w="",b=[];if(!l)return l;l=Jc(l);do u=(h=l.charCodeAt(f++)<<16|l.charCodeAt(f++)<<8|l.charCodeAt(f++))>>18&63,c=h>>12&63,p=h>>6&63,d=63&h,b[m++]=g.charAt(u)+g.charAt(c)+g.charAt(p)+g.charAt(d);while(f<l.length);switch(w=b.join(""),l.length%3){case 1:w=w.slice(0,-2)+"==";break;case 2:w=w.slice(0,-1)+"="}return w}(Wt(e)),o=(l=>"data="+encodeURIComponent(typeof l=="string"?l:Wt(l)))(i);return{contentType:"application/x-www-form-urlencoded",body:o,estimatedSize:new Blob([o]).size}}var a=Wt(e);return{contentType:"application/json",body:a,estimatedSize:new Blob([a]).size}}},Pr=[];Mn&&Pr.push({transport:"fetch",method:r=>{var e,t,{contentType:n,body:s,estimatedSize:i}=(e=Pn(r))!==null&&e!==void 0?e:{},o=new Headers;q(r.headers,function(c,p){o.append(p,c)}),n&&o.append("Content-Type",n);var a=r.url,l=null;if(Ci){var u=new Ci;l={signal:u.signal,timeout:setTimeout(()=>u.abort(),r.timeout)}}Mn(a,C({method:r?.method||"GET",headers:o,keepalive:r.method==="POST"&&(i||0)<52428.8,body:s,signal:(t=l)==null?void 0:t.signal},r.fetchOptions)).then(c=>c.text().then(p=>{var d={statusCode:c.status,text:p};if(c.status===200)try{d.json=JSON.parse(p)}catch(h){E.error(h)}r.callback==null||r.callback(d)})).catch(c=>{E.error(c),r.callback==null||r.callback({statusCode:0,text:c})}).finally(()=>l?clearTimeout(l.timeout):null)}}),Rn&&Pr.push({transport:"XHR",method:r=>{var e,t=new Rn;t.open(r.method||"GET",r.url,!0);var{contentType:n,body:s}=(e=Pn(r))!==null&&e!==void 0?e:{};q(r.headers,function(i,o){t.setRequestHeader(o,i)}),n&&t.setRequestHeader("Content-Type",n),r.timeout&&(t.timeout=r.timeout),r.disableXHRCredentials||(t.withCredentials=!0),t.onreadystatechange=()=>{if(t.readyState===4){var i={statusCode:t.status,text:t.responseText};if(t.status===200)try{i.json=JSON.parse(t.responseText)}catch{}r.callback==null||r.callback(i)}},t.send(s)}}),le!=null&&le.sendBeacon&&Pr.push({transport:"sendBeacon",method:r=>{var e=Gr(r.url,{beacon:"1"});try{var t,{contentType:n,body:s}=(t=Pn(r))!==null&&t!==void 0?t:{},i=typeof s=="string"?new Blob([s],{type:n}):s;le.sendBeacon(e,i)}catch{}}});var Lr=function(r,e){if(!function(t){try{new RegExp(t)}catch{return!1}return!0}(e))return!1;try{return new RegExp(e).test(r)}catch{return!1}};function lo(r,e,t){return Wt({distinct_id:r,userPropertiesToSet:e,userPropertiesToSetOnce:t})}var wa={exact:(r,e)=>e.some(t=>r.some(n=>t===n)),is_not:(r,e)=>e.every(t=>r.every(n=>t!==n)),regex:(r,e)=>e.some(t=>r.some(n=>Lr(t,n))),not_regex:(r,e)=>e.every(t=>r.every(n=>!Lr(t,n))),icontains:(r,e)=>e.map(kr).some(t=>r.map(kr).some(n=>t.includes(n))),not_icontains:(r,e)=>e.map(kr).every(t=>r.map(kr).every(n=>!t.includes(n))),gt:(r,e)=>e.some(t=>{var n=parseFloat(t);return!isNaN(n)&&r.some(s=>n>parseFloat(s))}),lt:(r,e)=>e.some(t=>{var n=parseFloat(t);return!isNaN(n)&&r.some(s=>n<parseFloat(s))})},kr=r=>r.toLowerCase();function Pa(r,e){return!r||Object.entries(r).every(t=>{var[n,s]=t,i=e?.[n];if(x(i)||_e(i))return!1;var o=[String(i)],a=wa[s.operator];return!!a&&a(s.values,o)})}var xn=L("[Error tracking]"),bs=class{constructor(e){var t,n;this.Zt=[],this.ti=new jn([new Ln,new Wn,new Vn,new Un,new Hn,new Kn,new zn,new Bn],ac()),this._instance=e,this.Zt=(t=(n=this._instance.persistence)==null?void 0:n.get_property(Yn))!==null&&t!==void 0?t:[]}onRemoteConfig(e){var t,n,s,i=(t=(n=e.errorTracking)==null?void 0:n.suppressionRules)!==null&&t!==void 0?t:[],o=(s=e.errorTracking)==null?void 0:s.captureExtensionExceptions;this.Zt=i,this._instance.persistence&&this._instance.persistence.register({[Yn]:this.Zt,[Gi]:o})}get ii(){var e,t=!!this._instance.get_property(Gi),n=this._instance.config.error_tracking.captureExtensionExceptions;return(e=n??t)!==null&&e!==void 0&&e}buildProperties(e,t){return this.ti.buildFromUnknown(e,{syntheticException:t?.syntheticException,mechanism:{handled:t?.handled}})}sendExceptionEvent(e){var t=e.$exception_list;if(this.ei(t)){if(this.ri(t))return void xn.info("Skipping exception capture because a suppression rule matched");if(!this.ii&&this.si(t))return void xn.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ni(t))return void xn.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent"})}ri(e){if(e.length===0)return!1;var t=e.reduce((n,s)=>{var{type:i,value:o}=s;return B(i)&&i.length>0&&n.$exception_types.push(i),B(o)&&o.length>0&&n.$exception_values.push(o),n},{$exception_types:[],$exception_values:[]});return this.Zt.some(n=>{var s=n.values.map(i=>{var o,a=wa[i.operator],l=N(i.value)?i.value:[i.value],u=(o=t[i.key])!==null&&o!==void 0?o:[];return l.length>0&&a(l,u)});return n.type==="OR"?s.some(Boolean):s.every(Boolean)})}si(e){return e.flatMap(t=>{var n,s;return(n=(s=t.stacktrace)==null?void 0:s.frames)!==null&&n!==void 0?n:[]}).some(t=>t.filename&&t.filename.startsWith("chrome-extension://"))}ni(e){if(e.length>0){var t,n,s,i,o=(t=(n=e[0].stacktrace)==null?void 0:n.frames)!==null&&t!==void 0?t:[],a=o[o.length-1];return(s=a==null||(i=a.filename)==null?void 0:i.includes("posthog.com/static"))!==null&&s!==void 0&&s}return!1}ei(e){return!$(e)&&N(e)}},ae=L("[FeatureFlags]"),jt=L("[FeatureFlags]",{debugEnabled:!0}),En="$active_feature_flags",pt="$override_feature_flags",co="$feature_flag_payloads",Gt="$override_feature_flag_payloads",uo="$feature_flag_request_id",po="$feature_flag_evaluated_at",ho=r=>{var e={};for(var[t,n]of wr(r||{}))n&&(e[t]=n);return e},Qc=r=>{var e=r.flags;return e?(r.featureFlags=Object.fromEntries(Object.keys(e).map(t=>{var n;return[t,(n=e[t].variant)!==null&&n!==void 0?n:e[t].enabled]})),r.featureFlagPayloads=Object.fromEntries(Object.keys(e).filter(t=>e[t].enabled).filter(t=>{var n;return(n=e[t].metadata)==null?void 0:n.payload}).map(t=>{var n;return[t,(n=e[t].metadata)==null?void 0:n.payload]}))):ae.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),r},eu=function(r){return r.FeatureFlags="feature_flags",r.Recordings="recordings",r}({}),ks=class{constructor(e){this.oi=!1,this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.ci=!1,this._instance=e,this.featureFlagEventHandlers=[]}fi(){var e,t=(e=this._instance.config.evaluation_contexts)!==null&&e!==void 0?e:this._instance.config.evaluation_environments;return!this._instance.config.evaluation_environments||this._instance.config.evaluation_contexts||this.ci||(ae.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.ci=!0),t!=null&&t.length?t.filter(n=>{var s=n&&typeof n=="string"&&n.trim().length>0;return s||ae.error("Invalid evaluation context found:",n,"Expected non-empty string"),s}):[]}pi(){return this.fi().length>0}flags(){if(this._instance.config.__preview_remote_config)this.di=!0;else{var e=!this.gi&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.mi({disableFlags:e})}}get hasLoadedFlags(){return this.ai}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._instance.get_property(Jn),t=this._instance.get_property(pt),n=this._instance.get_property(Gt);if(!n&&!t)return e||{};var s=U({},e||{}),i=[...new Set([...Object.keys(n||{}),...Object.keys(t||{})])];for(var o of i){var a,l,u=s[o],c=t?.[o],p=x(c)?(a=u?.enabled)!==null&&a!==void 0&&a:!!c,d=x(c)?u.variant:typeof c=="string"?c:void 0,h=n?.[o],g=C({},u,{enabled:p,variant:p?d??u?.variant:void 0});p!==u?.enabled&&(g.original_enabled=u?.enabled),d!==u?.variant&&(g.original_variant=u?.variant),h&&(g.metadata=C({},u?.metadata,{payload:h,original_payload:u==null||(l=u.metadata)==null?void 0:l.payload})),s[o]=g}return this.oi||(ae.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:n,finalDetails:s}),this.oi=!0),s}getFlagVariants(){var e=this._instance.get_property(mt),t=this._instance.get_property(pt);if(!t)return e||{};for(var n=U({},e),s=Object.keys(t),i=0;i<s.length;i++)n[s[i]]=t[s[i]];return this.oi||(ae.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:t,finalFlags:n}),this.oi=!0),n}getFlagPayloads(){var e=this._instance.get_property(co),t=this._instance.get_property(Gt);if(!t)return e||{};for(var n=U({},e||{}),s=Object.keys(t),i=0;i<s.length;i++)n[s[i]]=t[s[i]];return this.oi||(ae.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:t,finalPayloads:n}),this.oi=!0),n}reloadFeatureFlags(){this.ui||this._instance.config.advanced_disable_feature_flags||this.gi||(this.gi=setTimeout(()=>{this.mi()},5))}bi(){clearTimeout(this.gi),this.gi=void 0}ensureFlagsLoaded(){this.ai||this.li||this.gi||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.ui=e}mi(e){var t;if(this.bi(),!this._instance.M())if(this.li)this.hi=!0;else{var n=this._instance.config.token,s=this._instance.get_property("$device_id"),i={token:n,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:C({},((t=this._instance.persistence)==null?void 0:t.get_initial_props())||{},this._instance.get_property(Bt)||{}),group_properties:this._instance.get_property(et)};_e(s)||x(s)||(i.$device_id=s),(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(i.disable_flags=!0),this.pi()&&(i.evaluation_contexts=this.fi());var o=this._instance.config.__preview_remote_config,a=o?"/flags/?v=2":"/flags/?v=2&config=true",l=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",u=this._instance.requestRouter.endpointFor("flags",a+l);o&&(i.timezone=ma()),this.li=!0,this._instance._send_request({method:"POST",url:u,data:i,compression:this._instance.config.disable_compression?void 0:Fe.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:c=>{var p,d,h=!0;if(c.statusCode===200&&(this.hi||(this.$anon_distinct_id=void 0),h=!1),this.li=!1,this.di||(this.di=!0,this._instance.yi((d=c.json)!==null&&d!==void 0?d:{})),!i.disable_flags||this.hi)if(this.vi=!h,c.json&&(p=c.json.quotaLimited)!=null&&p.includes(eu.FeatureFlags))ae.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more.");else{var g;i.disable_flags||this.receivedFeatureFlags((g=c.json)!==null&&g!==void 0?g:{},h),this.hi&&(this.hi=!1,this.mi())}}})}}getFeatureFlag(e,t){var n;if(t===void 0&&(t={}),this.ai||this.getFlags()&&this.getFlags().length>0){var s=this.getFeatureFlagResult(e,t);return(n=s?.variant)!==null&&n!==void 0?n:s?.enabled}ae.warn('getFeatureFlag for key "'+e+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){var t=this.getFeatureFlagResult(e,{send_event:!1});return t?.payload}getFeatureFlagResult(e,t){if(t===void 0&&(t={}),this.ai||this.getFlags()&&this.getFlags().length>0){var n=this.getFlagVariants(),s=e in n,i=n[e],o=this.getFlagPayloads()[e],a=String(i),l=this._instance.get_property(uo)||void 0,u=this._instance.get_property(po)||void 0,c=this._instance.get_property(Ar)||{};if((t.send_event||!("send_event"in t))&&(!(e in c)||!c[e].includes(a))){var p,d,h,g,f,m,w,b,v;N(c[e])?c[e].push(a):c[e]=[a],(p=this._instance.persistence)==null||p.register({[Ar]:c});var _=this.getFeatureFlagDetails(e),k={$feature_flag:e,$feature_flag_response:i,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((d=this._instance.config.bootstrap)==null||(d=d.featureFlags)==null?void 0:d[e])||null,$feature_flag_bootstrapped_payload:((h=this._instance.config.bootstrap)==null||(h=h.featureFlagPayloads)==null?void 0:h[e])||null,$used_bootstrap_value:!this.vi};x(_==null||(g=_.metadata)==null?void 0:g.version)||(k.$feature_flag_version=_.metadata.version);var M,I=(f=_==null||(m=_.reason)==null?void 0:m.description)!==null&&f!==void 0?f:_==null||(w=_.reason)==null?void 0:w.code;I&&(k.$feature_flag_reason=I),_!=null&&(b=_.metadata)!=null&&b.id&&(k.$feature_flag_id=_.metadata.id),x(_?.original_variant)&&x(_?.original_enabled)||(k.$feature_flag_original_response=x(_.original_variant)?_.original_enabled:_.original_variant),_!=null&&(v=_.metadata)!=null&&v.original_payload&&(k.$feature_flag_original_payload=_==null||(M=_.metadata)==null?void 0:M.original_payload),this._instance.capture("$feature_flag_called",k)}if(s){var S=o;if(!x(o))try{S=JSON.parse(o)}catch{}return{key:e,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:S}}}else ae.warn('getFeatureFlagResult for key "'+e+`" failed. Feature flags didn't load in time.`)}getRemoteConfigPayload(e,t){var n=this._instance.config.token,s={distinct_id:this._instance.get_distinct_id(),token:n};this.pi()&&(s.evaluation_contexts=this.fi()),this._instance._send_request({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2&config=true"),data:s,compression:this._instance.config.disable_compression?void 0:Fe.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:i=>{var o,a=(o=i.json)==null?void 0:o.featureFlagPayloads;t(a?.[e]||void 0)}})}isFeatureEnabled(e,t){if(t===void 0&&(t={}),this.ai||this.getFlags()&&this.getFlags().length>0){var n=this.getFeatureFlag(e,t);return x(n)?void 0:!!n}ae.warn('isFeatureEnabled for key "'+e+`" failed. Feature flags didn't load in time.`)}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(t=>t!==e)}receivedFeatureFlags(e,t){if(this._instance.persistence){this.ai=!0;var n=this.getFlagVariants(),s=this.getFlagPayloads(),i=this.getFlagsWithDetails();(function(o,a,l,u,c){l===void 0&&(l={}),u===void 0&&(u={}),c===void 0&&(c={});var p=Qc(o),d=p.flags,h=p.featureFlags,g=p.featureFlagPayloads;if(h){var f=o.requestId,m=o.evaluatedAt;if(N(h)){ae.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var w={};if(h)for(var b=0;b<h.length;b++)w[h[b]]=!0;a&&a.register({[En]:h,[mt]:w})}else{var v=h,_=g,k=d;if(o.errorsWhileComputingFlags)if(d){var M=new Set(Object.keys(d).filter(I=>{var S;return!((S=d[I])!=null&&S.failed)}));v=C({},l,Object.fromEntries(Object.entries(v).filter(I=>{var[S]=I;return M.has(S)}))),_=C({},u,Object.fromEntries(Object.entries(_||{}).filter(I=>{var[S]=I;return M.has(S)}))),k=C({},c,Object.fromEntries(Object.entries(k||{}).filter(I=>{var[S]=I;return M.has(S)})))}else v=C({},l,v),_=C({},u,_),k=C({},c,k);a&&a.register(C({[En]:Object.keys(ho(v)),[mt]:v||{},[co]:_||{},[Jn]:k||{}},f?{[uo]:f}:{},m?{[po]:m}:{}))}}})(e,this._instance.persistence,n,s,i),this.wi(t)}}override(e,t){t===void 0&&(t=!1),ae.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:t})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return ae.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this._instance.persistence.unregister(pt),this._instance.persistence.unregister(Gt),this.wi(),jt.info("All overrides cleared");if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var t,n=e;if(this.oi=!!((t=n.suppressWarning)!==null&&t!==void 0&&t),"flags"in n){if(n.flags===!1)this._instance.persistence.unregister(pt),jt.info("Flag overrides cleared");else if(n.flags){if(N(n.flags)){for(var s={},i=0;i<n.flags.length;i++)s[n.flags[i]]=!0;this._instance.persistence.register({[pt]:s})}else this._instance.persistence.register({[pt]:n.flags});jt.info("Flag overrides set",{flags:n.flags})}}return"payloads"in n&&(n.payloads===!1?(this._instance.persistence.unregister(Gt),jt.info("Payload overrides cleared")):n.payloads&&(this._instance.persistence.register({[Gt]:n.payloads}),jt.info("Payload overrides set",{payloads:n.payloads}))),void this.wi()}this.wi()}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.ai){var{flags:t,flagVariants:n}=this.xi();e(t,n)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,n){var s,i=(this._instance.get_property(Ht)||[]).find(u=>u.flagKey===e),o={["$feature_enrollment/"+e]:t},a={$feature_flag:e,$feature_enrollment:t,$set:o};i&&(a.$early_access_feature_name=i.name),n&&(a.$feature_enrollment_stage=n),this._instance.capture("$feature_enrollment_update",a),this.setPersonPropertiesForFlags(o,!1);var l=C({},this.getFlagVariants(),{[e]:t});(s=this._instance.persistence)==null||s.register({[En]:Object.keys(ho(l)),[mt]:l}),this.wi()}getEarlyAccessFeatures(e,t,n){t===void 0&&(t=!1);var s=this._instance.get_property(Ht),i=n?"&"+n.map(o=>"stage="+o).join("&"):"";if(s&&!t)return e(s);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+i),method:"GET",callback:o=>{var a,l;if(o.json){var u=o.json.earlyAccessFeatures;return(a=this._instance.persistence)==null||a.unregister(Ht),(l=this._instance.persistence)==null||l.register({[Ht]:u}),e(u)}}})}xi(){var e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter(n=>t[n]),flagVariants:Object.keys(t).filter(n=>t[n]).reduce((n,s)=>(n[s]=t[s],n),{})}}wi(e){var{flags:t,flagVariants:n}=this.xi();this.featureFlagEventHandlers.forEach(s=>s(t,n,{errorsLoading:e}))}setPersonPropertiesForFlags(e,t){t===void 0&&(t=!0);var n=this._instance.get_property(Bt)||{};this._instance.register({[Bt]:C({},n,e)}),t&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(Bt)}setGroupPropertiesForFlags(e,t){t===void 0&&(t=!0);var n=this._instance.get_property(et)||{};Object.keys(n).length!==0&&Object.keys(n).forEach(s=>{n[s]=C({},n[s],e[s]),delete e[s]}),this._instance.register({[et]:C({},n,e)}),t&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var t=this._instance.get_property(et)||{};this._instance.register({[et]:C({},t,{[e]:{}})})}else this._instance.unregister(et)}reset(){this.ai=!1,this.li=!1,this.ui=!1,this.hi=!1,this.di=!1,this.vi=!1,this.$anon_distinct_id=void 0,this.bi(),this.oi=!1}},tu=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Zt=class{constructor(e,t){this.R=e,this.props={},this.Ei=!1,this.$i=(n=>{var s="";return n.token&&(s=n.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),n.persistence_name?"ph_"+n.persistence_name:"ph_"+s+"_posthog"})(e),this.Y=this.Si(e),this.load(),e.debug&&E.info("Persistence loaded",e.persistence,C({},this.props)),this.update_config(e,e,t),this.save()}isDisabled(){return!!this.ki}Si(e){tu.indexOf(e.persistence.toLowerCase())===-1&&(E.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var t=function(s){s===void 0&&(s=[]);var i=[...Tc,...s];return C({},G,{W:function(o){try{var a={};try{a=we.W(o)||{}}catch{}var l=U(a,JSON.parse(G.q(o)||"{}"));return G.G(o,l),l}catch{}return null},G:function(o,a,l,u,c,p){try{G.G(o,a,void 0,void 0,p);var d={};i.forEach(h=>{a[h]&&(d[h]=a[h])}),Object.keys(d).length&&we.G(o,d,l,u,c,p)}catch(h){G.B(h)}},V:function(o,a){try{y?.localStorage.removeItem(o),we.V(o,a)}catch(l){G.B(l)}}})}(e.cookie_persisted_properties||[]),n=e.persistence.toLowerCase();return n==="localstorage"&&G.H()?G:n==="localstorage+cookie"&&t.H()?t:n==="sessionstorage"&&Y.H()?Y:n==="memory"?Fc:n==="cookie"?we:t.H()?t:we}properties(){var e={};return q(this.props,function(t,n){if(n===mt&&H(t))for(var s=Object.keys(t),i=0;i<s.length;i++)e["$feature/"+s[i]]=t[s[i]];else a=n,l=!1,(_e(o=gc)?l:Si&&o.indexOf===Si?o.indexOf(a)!=-1:(q(o,function(u){if(l||(l=u===a))return Sr}),l))||(e[n]=t);var o,a,l}),e}load(){if(!this.ki){var e=this.Y.W(this.$i);e&&(this.props=U({},e))}}save(){this.ki||this.Y.G(this.$i,this.props,this.Pi,this.Ti,this.Ii,this.R.debug)}remove(){this.Y.V(this.$i,!1),this.Y.V(this.$i,!0)}clear(){this.remove(),this.props={}}register_once(e,t,n){if(H(e)){x(t)&&(t="None"),this.Pi=x(n)?this.Ci:n;var s=!1;if(q(e,(i,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==t||(this.props[o]=i,s=!0)}),s)return this.save(),!0}return!1}register(e,t){if(H(e)){this.Pi=x(t)?this.Ci:t;var n=!1;if(q(e,(s,i)=>{e.hasOwnProperty(i)&&this.props[i]!==s&&(this.props[i]=s,n=!0)}),n)return this.save(),!0}return!1}unregister(e){e in this.props&&(delete this.props[e],this.save())}update_campaign_params(){if(!this.Ei){var e=pa(this.R.custom_campaign_params,this.R.mask_personal_data_properties,this.R.custom_personal_data_properties);yt(Bs(e))||this.register(e),this.Ei=!0}}update_search_keyword(){var e;this.register((e=P?.referrer)?ha(e):{})}update_referrer_info(){var e;this.register_once({$referrer:fa(),$referring_domain:P!=null&&P.referrer&&((e=Fr(P.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[ts]||this.props[rs]||this.register_once({[Ir]:ga(this.R.mask_personal_data_properties,this.R.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};q([rs,ts],o=>{var a=this.props[o];a&&q(a,function(l,u){e["$initial_"+Tn(u)]=l})});var t,n,s=this.props[Ir];if(s){var i=(t=ya(s),n={},q(t,function(o,a){n["$initial_"+Tn(a)]=o}),n);U(e,i)}return e}safe_merge(e){return q(this.props,function(t,n){n in e||(e[n]=t)}),e}update_config(e,t,n){if(this.Ci=this.Pi=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!n),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==t.persistence||!((o,a)=>{if(o.length!==a.length)return!1;var l=[...o].sort(),u=[...a].sort();return l.every((c,p)=>c===u[p])})(e.cookie_persisted_properties||[],t.cookie_persisted_properties||[])){var s=this.Si(e),i=this.props;this.clear(),this.Y=s,this.props=i,this.save()}}set_disabled(e){this.ki=e,this.ki?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ti&&(this.Ti=e,this.remove(),this.save())}set_secure(e){e!==this.Ii&&(this.Ii=e,this.remove(),this.save())}set_event_timer(e,t){var n=this.props[Kt]||{};n[e]=t,this.props[Kt]=n,this.save()}remove_event_timer(e){var t=(this.props[Kt]||{})[e];return x(t)||(delete this.props[Kt][e],this.save()),t}get_property(e){return this.props[e]}set_property(e,t){this.props[e]=t,this.save()}},fo=L("[Product Tours]"),Sn="ph_product_tours",ws=class{constructor(e){this.Ri=null,this.Fi=null,this._instance=e}onRemoteConfig(e){this._instance.persistence&&this._instance.persistence.register({[Ui]:!(e==null||!e.productTours)}),this.loadIfEnabled()}loadIfEnabled(){var e,t;this.Ri||(e=this._instance).config.disable_product_tours||(t=e.persistence)==null||!t.get_property(Ui)||this.it(()=>this.Oi())}it(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.generateProductTours?e():(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",s=>{s?fo.error("Could not load product tours script",s):e()})}Oi(){var e;!this.Ri&&(e=A.__PosthogExtensions__)!=null&&e.generateProductTours&&(this.Ri=A.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t){if(t===void 0&&(t=!1),!N(this.Fi)||t){var n=this._instance.persistence;if(n){var s=n.props[Sn];if(N(s)&&!t)return this.Fi=s,void e(s,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",callback:i=>{var o=i.statusCode;if(o!==200||!i.json){var a="Product Tours API could not be loaded, status: "+o;return fo.error(a),void e([],{isLoaded:!1,error:a})}var l=N(i.json.product_tours)?i.json.product_tours:[];this.Fi=l,n&&n.register({[Sn]:l}),e(l,{isLoaded:!0})}})}else e(this.Fi,{isLoaded:!0})}getActiveProductTours(e){$(this.Ri)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this.Ri.getActiveProductTours(e)}showProductTour(e){var t;(t=this.Ri)==null||t.showTourById(e)}previewTour(e){this.Ri?this.Ri.previewTour(e):this.it(()=>{var t;this.Oi(),(t=this.Ri)==null||t.previewTour(e)})}dismissProductTour(){var e;(e=this.Ri)==null||e.dismissTour("user_clicked_skip")}nextStep(){var e;(e=this.Ri)==null||e.nextStep()}previousStep(){var e;(e=this.Ri)==null||e.previousStep()}clearCache(){var e;this.Fi=null,(e=this._instance.persistence)==null||e.unregister(Sn)}resetTour(e){var t;(t=this.Ri)==null||t.resetTour(e)}resetAllTours(){var e;(e=this.Ri)==null||e.resetAllTours()}cancelPendingTour(e){var t;(t=this.Ri)==null||t.cancelPendingTour(e)}},Lt=function(r){return r.Activation="events",r.Cancellation="cancelEvents",r}({}),Xp=function(r){return r.Button="button",r.Tab="tab",r.Selector="selector",r}({}),Yp=function(r){return r.TopLeft="top_left",r.TopRight="top_right",r.TopCenter="top_center",r.MiddleLeft="middle_left",r.MiddleRight="middle_right",r.MiddleCenter="middle_center",r.Left="left",r.Center="center",r.Right="right",r.NextToTrigger="next_to_trigger",r}({}),Jp=function(r){return r.Top="top",r.Left="left",r.Right="right",r.Bottom="bottom",r}({}),Cn=function(r){return r.Popover="popover",r.API="api",r.Widget="widget",r.ExternalSurvey="external_survey",r}({}),Zp=function(r){return r.Open="open",r.MultipleChoice="multiple_choice",r.SingleChoice="single_choice",r.Rating="rating",r.Link="link",r}({}),Qp=function(r){return r.NextQuestion="next_question",r.End="end",r.ResponseBased="response_based",r.SpecificQuestion="specific_question",r}({}),ed=function(r){return r.Once="once",r.Recurring="recurring",r.Always="always",r}({}),Xt=function(r){return r.SHOWN="survey shown",r.DISMISSED="survey dismissed",r.SENT="survey sent",r.ABANDONED="survey abandoned",r}({}),An=function(r){return r.SURVEY_ID="$survey_id",r.SURVEY_NAME="$survey_name",r.SURVEY_RESPONSE="$survey_response",r.SURVEY_ITERATION="$survey_iteration",r.SURVEY_ITERATION_START_DATE="$survey_iteration_start_date",r.SURVEY_PARTIALLY_COMPLETED="$survey_partially_completed",r.SURVEY_SUBMISSION_ID="$survey_submission_id",r.SURVEY_QUESTIONS="$survey_questions",r.SURVEY_COMPLETED="$survey_completed",r.PRODUCT_TOUR_ID="$product_tour_id",r.SURVEY_LAST_SEEN_DATE="$survey_last_seen_date",r}({}),Ps=function(r){return r.Popover="popover",r.Inline="inline",r}({}),D=L("[Surveys]"),xa="seenSurvey_",ru=(r,e)=>{var t="$survey_"+e+"/"+r.id;return r.current_iteration&&r.current_iteration>0&&(t="$survey_"+e+"/"+r.id+"/"+r.current_iteration),t},go=r=>((e,t)=>{var n=""+e+t.id;return t.current_iteration&&t.current_iteration>0&&(n=""+e+t.id+"_"+t.current_iteration),n})(xa,r),nu=[Cn.Popover,Cn.Widget,Cn.API],su={ignoreConditions:!1,ignoreDelay:!1,displayType:Ps.Popover},ir=class{constructor(){this.Mi={},this.Mi={}}on(e,t){return this.Mi[e]||(this.Mi[e]=[]),this.Mi[e].push(t),()=>{this.Mi[e]=this.Mi[e].filter(n=>n!==t)}}emit(e,t){for(var n of this.Mi[e]||[])n(t);for(var s of this.Mi["*"]||[])s(e,t)}};function dt(r,e,t){if($(r))return!1;switch(t){case"exact":return r===e;case"contains":var n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(n,"i").test(r);case"regex":try{return new RegExp(e).test(r)}catch{return!1}default:return!1}}var xs=class{constructor(e){this.Ai=new ir,this.ji=(t,n)=>this.Di(t,n)&&this.Li(t,n)&&this.Ni(t,n)&&this.Ui(t,n),this.Di=(t,n)=>n==null||!n.event||t?.event===n?.event,this._instance=e,this.zi=new Set,this.Hi=new Set}init(){var e;if(!x((e=this._instance)==null?void 0:e._addCaptureHook)){var t;(t=this._instance)==null||t._addCaptureHook((n,s)=>{this.on(n,s)})}}register(e){var t,n;if(!x((t=this._instance)==null?void 0:t._addCaptureHook)&&(e.forEach(o=>{var a,l;(a=this.Hi)==null||a.add(o),(l=o.steps)==null||l.forEach(u=>{var c;(c=this.zi)==null||c.add(u?.event||"")})}),(n=this._instance)!=null&&n.autocapture)){var s,i=new Set;e.forEach(o=>{var a;(a=o.steps)==null||a.forEach(l=>{l!=null&&l.selector&&i.add(l?.selector)})}),(s=this._instance)==null||s.autocapture.setElementSelectors(i)}}on(e,t){var n;t!=null&&e.length!=0&&(this.zi.has(e)||this.zi.has(t?.event))&&this.Hi&&((n=this.Hi)==null?void 0:n.size)>0&&this.Hi.forEach(s=>{this.Bi(t,s)&&this.Ai.emit("actionCaptured",s.name)})}qi(e){this.onAction("actionCaptured",t=>e(t))}Bi(e,t){if(t?.steps==null)return!1;for(var n of t.steps)if(this.ji(e,n))return!0;return!1}onAction(e,t){return this.Ai.on(e,t)}Li(e,t){if(t!=null&&t.url){var n,s=e==null||(n=e.properties)==null?void 0:n.$current_url;if(!s||typeof s!="string"||!dt(s,t.url,t.url_matching||"contains"))return!1}return!0}Ni(e,t){return!!this.Wi(e,t)&&!!this.Gi(e,t)&&!!this.Vi(e,t)}Wi(e,t){var n;if(t==null||!t.href)return!0;var s=this.Ji(e);if(s.length>0)return s.some(a=>dt(a.href,t.href,t.href_matching||"exact"));var i,o=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";return!!o&&dt((i=o.match(/(?::|")href="(.*?)"/))?i[1]:"",t.href,t.href_matching||"exact")}Gi(e,t){var n;if(t==null||!t.text)return!0;var s=this.Ji(e);if(s.length>0)return s.some(u=>dt(u.text,t.text,t.text_matching||"exact")||dt(u.$el_text,t.text,t.text_matching||"exact"));var i,o,a,l=(e==null||(n=e.properties)==null?void 0:n.$elements_chain)||"";return!!l&&(i=function(u){for(var c,p=[],d=/(?::|")text="(.*?)"/g;!$(c=d.exec(u));)p.includes(c[1])||p.push(c[1]);return p}(l),o=t.text,a=t.text_matching||"exact",i.some(u=>dt(u,o,a)))}Vi(e,t){var n,s;if(t==null||!t.selector)return!0;var i=e==null||(n=e.properties)==null?void 0:n.$element_selectors;if(i!=null&&i.includes(t.selector))return!0;var o=(e==null||(s=e.properties)==null?void 0:s.$elements_chain)||"";if(t.selector_regex&&o)try{return new RegExp(t.selector_regex).test(o)}catch{return!1}return!1}Ji(e){var t;return(e==null||(t=e.properties)==null?void 0:t.$elements)==null?[]:e?.properties.$elements}Ui(e,t){return t==null||!t.properties||t.properties.length===0||Pa(t.properties.reduce((n,s)=>{var i=N(s.value)?s.value.map(String):s.value!=null?[String(s.value)]:[];return n[s.key]={values:i,operator:s.operator||"exact"},n},{}),e?.properties)}},Es=class{constructor(e){this._instance=e,this.Ki=new Map,this.Yi=new Map,this.Xi=new Map}Qi(e,t){return!!e&&Pa(e.propertyFilters,t?.properties)}Zi(e,t){var n=new Map;return e.forEach(s=>{var i;(i=s.conditions)==null||(i=i[t])==null||(i=i.values)==null||i.forEach(o=>{if(o!=null&&o.name){var a=n.get(o.name)||[];a.push(s.id),n.set(o.name,a)}})}),n}te(e,t,n){var s=(n===Lt.Activation?this.Ki:this.Yi).get(e),i=[];return this.ie(o=>{i=o.filter(a=>s?.includes(a.id))}),i.filter(o=>{var a,l=(a=o.conditions)==null||(a=a[n])==null||(a=a.values)==null?void 0:a.find(u=>u.name===e);return this.Qi(l,t)})}register(e){var t;x((t=this._instance)==null?void 0:t._addCaptureHook)||(this.ee(e),this.re(e))}re(e){var t=e.filter(n=>{var s,i;return((s=n.conditions)==null?void 0:s.actions)&&((i=n.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0});t.length!==0&&(this.se==null&&(this.se=new xs(this._instance),this.se.init(),this.se.qi(n=>{this.onAction(n)})),t.forEach(n=>{var s,i,o,a,l;n.conditions&&(s=n.conditions)!=null&&s.actions&&(i=n.conditions)!=null&&(i=i.actions)!=null&&i.values&&((o=n.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.se)==null||a.register(n.conditions.actions.values),(l=n.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach(u=>{if(u&&u.name){var c=this.Xi.get(u.name);c&&c.push(n.id),this.Xi.set(u.name,c||[n.id])}}))}))}ee(e){var t,n=e.filter(i=>{var o,a;return((o=i.conditions)==null?void 0:o.events)&&((a=i.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0}),s=e.filter(i=>{var o,a;return((o=i.conditions)==null?void 0:o.cancelEvents)&&((a=i.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0});(n.length!==0||s.length!==0)&&((t=this._instance)==null||t._addCaptureHook((i,o)=>{this.onEvent(i,o)}),this.Ki=this.Zi(e,Lt.Activation),this.Yi=this.Zi(e,Lt.Cancellation))}onEvent(e,t){var n,s=this.ne(),i=this.oe(),o=this.ae(),a=((n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[i])||[];if(o===e&&t&&a.length>0){var l,u;s.info("event matched, removing item from activated items",{event:e,eventPayload:t,existingActivatedItems:a});var c=(t==null||(l=t.properties)==null?void 0:l.$survey_id)||(t==null||(u=t.properties)==null?void 0:u.$product_tour_id);if(c){var p=a.indexOf(c);p>=0&&(a.splice(p,1),this.le(a))}}else{if(this.Yi.has(e)){var d=this.te(e,t,Lt.Cancellation);d.length>0&&(s.info("cancel event matched, cancelling items",{event:e,itemsToCancel:d.map(g=>g.id)}),d.forEach(g=>{var f=a.indexOf(g.id);f>=0&&a.splice(f,1),this.ue(g.id)}),this.le(a))}if(this.Ki.has(e)){s.info("event name matched",{event:e,eventPayload:t,items:this.Ki.get(e)});var h=this.te(e,t,Lt.Activation);this.le(a.concat(h.map(g=>g.id)||[]))}}}onAction(e){var t,n=this.oe(),s=((t=this._instance)==null||(t=t.persistence)==null?void 0:t.props[n])||[];this.Xi.has(e)&&this.le(s.concat(this.Xi.get(e)||[]))}le(e){var t,n=this.ne(),s=this.oe(),i=[...new Set(e)].filter(o=>!this.he(o));n.info("updating activated items",{activatedItems:i}),(t=this._instance)==null||(t=t.persistence)==null||t.register({[s]:i})}getActivatedIds(){var e,t=this.oe(),n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[t];return n||[]}getEventToItemsMap(){return this.Ki}de(){return this.se}},Ss=class extends Es{constructor(e){super(e)}oe(){return"$surveys_activated"}ae(){return Xt.SHOWN}ie(e){var t;(t=this._instance)==null||t.getSurveys(e)}ue(e){var t;(t=this._instance)==null||t.cancelPendingSurvey(e)}ne(){return D}he(){return!1}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}},Cs=class{constructor(e){this.ve=void 0,this._surveyManager=null,this.ce=!1,this.fe=[],this.pe=null,this._instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){if(!this._instance.config.disable_surveys){var t=e.surveys;if($(t))return D.warn("Flags not loaded yet. Not loading surveys.");var n=N(t);this.ve=n?t.length>0:t,D.info("flags response received, isSurveysEnabled: "+this.ve),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],t=0;t<localStorage.length;t++){var n=localStorage.key(t);(n!=null&&n.startsWith(xa)||n!=null&&n.startsWith("inProgressSurvey_"))&&e.push(n)}e.forEach(s=>localStorage.removeItem(s))}loadIfEnabled(){if(!this._surveyManager)if(this.ce)D.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)D.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())D.info("Not loading surveys in cookieless mode without consent.");else{var e=A?.__PosthogExtensions__;if(e){if(!x(this.ve)||this._instance.config.advanced_enable_surveys){var t=this.ve||this._instance.config.advanced_enable_surveys;this.ce=!0;try{var n=e.generateSurveys;if(n)return void this.ge(n,t);var s=e.loadExternalDependency;if(!s)return void this._e("PostHog loadExternalDependency extension not found.");s(this._instance,"surveys",i=>{i||!e.generateSurveys?this._e("Could not load surveys script",i):this.ge(e.generateSurveys,t)})}catch(i){throw this._e("Error initializing surveys",i),i}finally{this.ce=!1}}}else D.error("PostHog Extensions not found.")}}ge(e,t){this._surveyManager=e(this._instance,t),this._surveyEventReceiver=new Ss(this._instance),D.info("Surveys loaded successfully"),this.me({isLoaded:!0})}_e(e,t){D.error(e,t),this.me({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.fe.push(e),this._surveyManager&&this.me({isLoaded:!0}),()=>{this.fe=this.fe.filter(t=>t!==e)}}getSurveys(e,t){if(t===void 0&&(t=!1),this._instance.config.disable_surveys)return D.info("Disabled. Not loading surveys."),e([]);var n,s=this._instance.get_property(Zn);if(s&&!t)return e(s,{isLoaded:!0});typeof Promise<"u"&&this.pe?this.pe.then(i=>{var{surveys:o,context:a}=i;return e(o,a)}):(typeof Promise<"u"&&(this.pe=new Promise(i=>{n=i})),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:i=>{var o;this.pe=null;var a=i.statusCode;if(a!==200||!i.json){var l="Surveys API could not be loaded, status: "+a;D.error(l);var u={isLoaded:!1,error:l};return e([],u),void(n==null||n({surveys:[],context:u}))}var c,p=i.json.surveys||[],d=p.filter(g=>function(f){return!(!f.start_date||f.end_date)}(g)&&(function(f){var m;return!((m=f.conditions)==null||(m=m.events)==null||(m=m.values)==null||!m.length)}(g)||function(f){var m;return!((m=f.conditions)==null||(m=m.actions)==null||(m=m.values)==null||!m.length)}(g)));d.length>0&&((c=this._surveyEventReceiver)==null||c.register(d)),(o=this._instance.persistence)==null||o.register({[Zn]:p});var h={isLoaded:!0};e(p,h),n?.({surveys:p,context:h})}}))}me(e){for(var t of this.fe)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(n){D.error("Error in survey callback",n)}}getActiveMatchingSurveys(e,t){if(t===void 0&&(t=!1),!$(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);D.warn("init was not called")}be(e){var t=null;return this.getSurveys(n=>{var s;t=(s=n.find(i=>i.id===e))!==null&&s!==void 0?s:null}),t}ye(e){if($(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var t=typeof e=="string"?this.be(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if($(this._surveyManager))return D.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var t=this.ye(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return $(this._surveyManager)?(D.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise(n=>{this.getSurveys(s=>{var i,o=(i=s.find(l=>l.id===e))!==null&&i!==void 0?i:null;if(o){var a=this.ye(o);n({visible:a.eligible,disabledReason:a.reason})}else n({visible:!1,disabledReason:"Survey not found"})},t)})}renderSurvey(e,t,n){var s;if($(this._surveyManager))D.warn("init was not called");else{var i=typeof e=="string"?this.be(e):e;if(i!=null&&i.id)if(nu.includes(i.type)){var o=P?.querySelector(t);if(o)return(s=i.appearance)!=null&&s.surveyPopupDelaySeconds?(D.info("Rendering survey "+i.id+" with delay of "+i.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout(()=>{var a,l;D.info("Rendering survey "+i.id+" with delay of "+((a=i.appearance)==null?void 0:a.surveyPopupDelaySeconds)+" seconds"),(l=this._surveyManager)==null||l.renderSurvey(i,o,n),D.info("Survey "+i.id+" rendered")},1e3*i.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(i,o,n);D.warn("Survey element not found")}else D.warn("Surveys of type "+i.type+" cannot be rendered in the app");else D.warn("Survey not found")}}displaySurvey(e,t){var n;if($(this._surveyManager))D.warn("init was not called");else{var s=this.be(e);if(s){var i=s;if((n=s.appearance)!=null&&n.surveyPopupDelaySeconds&&t.ignoreDelay&&(i=C({},s,{appearance:C({},s.appearance,{surveyPopupDelaySeconds:0})})),t.displayType!==Ps.Popover&&t.initialResponses&&D.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),t.ignoreConditions===!1){var o=this.canRenderSurvey(s);if(!o.visible)return void D.warn("Survey is not eligible to be displayed: ",o.disabledReason)}t.displayType!==Ps.Inline?this._surveyManager.handlePopoverSurvey(i,t):this.renderSurvey(i,t.selector,t.properties)}else D.warn("Survey not found")}}cancelPendingSurvey(e){$(this._surveyManager)?D.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e;(e=this._surveyManager)==null||e.handlePageUnload()}},Ie=L("[Conversations]"),As=class{constructor(e){this.we=void 0,this._conversationsManager=null,this.xe=!1,this.Ee=null,this._instance=e}onRemoteConfig(e){if(!this._instance.config.disable_conversations){var t=e.conversations;$(t)||($e(t)?this.we=t:(this.we=t.enabled,this.Ee=t),this.loadIfEnabled())}}reset(){var e;(e=this._conversationsManager)==null||e.reset(),this._conversationsManager=null,this.we=void 0,this.Ee=null}loadIfEnabled(){if(!this._conversationsManager&&!this.xe&&!(this._instance.config.disable_conversations||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var e=A?.__PosthogExtensions__;if(e&&!x(this.we)&&this.we)if(this.Ee&&this.Ee.token){this.xe=!0;try{var t=e.initConversations;if(t)return this.$e(t),void(this.xe=!1);var n=e.loadExternalDependency;if(!n)return void this.Se("PostHog loadExternalDependency extension not found.");n(this._instance,"conversations",s=>{s||!e.initConversations?this.Se("Could not load conversations script",s):this.$e(e.initConversations),this.xe=!1})}catch(s){this.Se("Error initializing conversations",s),this.xe=!1}}else Ie.error("Conversations enabled but missing token in remote config.")}}$e(e){if(this.Ee)try{this._conversationsManager=e(this.Ee,this._instance),Ie.info("Conversations loaded successfully")}catch(t){this.Se("Error completing conversations initialization",t)}else Ie.error("Cannot complete initialization: remote config is null")}Se(e,t){Ie.error(e,t),this._conversationsManager=null,this.xe=!1}show(){this._conversationsManager?this._conversationsManager.show():Ie.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.we===!0&&!_e(this._conversationsManager)}isVisible(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.isVisible())!==null&&e!==void 0&&e}sendMessage(e,t,n){var s=this;return gt(function*(){return s._conversationsManager?s._conversationsManager.sendMessage(e,t,n):(Ie.warn("Conversations not available yet."),null)})()}getMessages(e,t){var n=this;return gt(function*(){return n._conversationsManager?n._conversationsManager.getMessages(e,t):(Ie.warn("Conversations not available yet."),null)})()}markAsRead(e){var t=this;return gt(function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(Ie.warn("Conversations not available yet."),null)})()}getTickets(e){var t=this;return gt(function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(Ie.warn("Conversations not available yet."),null)})()}getCurrentTicketId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getCurrentTicketId())!==null&&e!==void 0?e:null}getWidgetSessionId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getWidgetSessionId())!==null&&e!==void 0?e:null}},Is=class{constructor(e){var t;this.ke=!1,this.Pe=!1,this._instance=e,this._instance&&(t=this._instance.config.logs)!=null&&t.captureConsoleLogs&&(this.ke=!0)}onRemoteConfig(e){var t,n=(t=e.logs)==null?void 0:t.captureConsoleLogs;!$(n)&&n&&(this.ke=!0,this.loadIfEnabled())}reset(){}loadIfEnabled(){if(this.ke&&!this.Pe){var e=L("[logs]"),t=A?.__PosthogExtensions__;if(t){var n=t.loadExternalDependency;n?n(this._instance,"logs",s=>{var i;s||(i=t.logs)==null||!i.initializeLogs?e.error("Could not load logs script",s):(t.logs.initializeLogs(this._instance),this.Pe=!0)}):e.error("PostHog loadExternalDependency extension not found.")}else e.error("PostHog Extensions not found.")}}},yo=L("[RateLimiter]"),Ms=class{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=t=>{var n=t.text;if(n&&n.length)try{(JSON.parse(n).quota_limited||[]).forEach(s=>{yo.info((s||"events")+" is quota limited."),this.serverLimits[s]=new Date().getTime()+6e4})}catch(s){return void yo.warn('could not rate limit - continuing. Error: "'+s?.message+'"',{text:n})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var t,n,s;e===void 0&&(e=!1);var{captureEventsBurstLimit:i,captureEventsPerSecond:o}=this,a=new Date().getTime(),l=(t=(n=this.instance.persistence)==null?void 0:n.get_property(es))!==null&&t!==void 0?t:{tokens:i,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>i&&(l.tokens=i);var u=l.tokens<1;return u||e||(l.tokens=Math.max(0,l.tokens-1)),!u||this.lastEventRateLimited||e||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+o+" events per second and "+i+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=u,(s=this.instance.persistence)==null||s.set_property(es,l),{isRateLimited:u,remainingTokens:l.tokens}}isServerRateLimited(e){var t=this.serverLimits[e||"events"]||!1;return t!==!1&&new Date().getTime()<t}},Qe=L("[RemoteConfig]"),Rs=class{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=A._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.config}Te(e){var t,n;(t=A.__PosthogExtensions__)!=null&&t.loadExternalDependency?(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"remote-config",()=>e(this.remoteConfig)):(Qe.error("PostHog Extensions not found. Cannot load remote config."),e())}Ie(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:t=>{e(t.json)}})}load(){try{if(this.remoteConfig)return Qe.info("Using preloaded remote config",this.remoteConfig),void this.yi(this.remoteConfig);if(this._instance.M())return void Qe.warn("Remote config is disabled. Falling back to local config.");this.Te(e=>{if(!e)return Qe.info("No config found after loading remote JS config. Falling back to JSON."),void this.Ie(t=>{this.yi(t)});this.yi(e)})}catch(e){Qe.error("Error loading remote config",e)}}yi(e){e?this._instance.config.__preview_remote_config?(this._instance.yi(e),e.hasFeatureFlags!==!1&&this._instance.featureFlags.ensureFlagsLoaded()):Qe.info("__preview_remote_config is disabled. Logging config instead",e):Qe.error("Failed to fetch remote config from PostHog.")}},Ts=3e3,Fs=class{constructor(e,t){this.Ce=!0,this.Re=[],this.Fe=Pe(t?.flush_interval_ms||Ts,250,5e3,E.createLogger("flush interval"),Ts),this.Oe=e}enqueue(e){this.Re.push(e),this.Me||this.Ae()}unload(){this.je();var e=this.Re.length>0?this.De():{},t=Object.values(e);[...t.filter(n=>n.url.indexOf("/e")===0),...t.filter(n=>n.url.indexOf("/e")!==0)].map(n=>{this.Oe(C({},n,{transport:"sendBeacon"}))})}enable(){this.Ce=!1,this.Ae()}Ae(){var e=this;this.Ce||(this.Me=setTimeout(()=>{if(this.je(),this.Re.length>0){var t=this.De(),n=function(){var i=t[s],o=new Date().getTime();i.data&&N(i.data)&&q(i.data,a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp}),e.Oe(i)};for(var s in t)n()}},this.Fe))}je(){clearTimeout(this.Me),this.Me=void 0}De(){var e={};return q(this.Re,t=>{var n,s=t,i=(s?s.batchKey:null)||s.url;x(e[i])&&(e[i]=C({},s,{data:[]})),(n=e[i].data)==null||n.push(s.data)}),this.Re=[],e}},iu=["retriesPerformedSoFar"],Os=class{constructor(e){this.Le=!1,this.Ne=3e3,this.Re=[],this._instance=e,this.Re=[],this.Ue=!0,!x(y)&&"onLine"in y.navigator&&(this.Ue=y.navigator.onLine,this.ze=()=>{this.Ue=!0,this.Lt()},this.He=()=>{this.Ue=!1},K(y,"online",this.ze),K(y,"offline",this.He))}get length(){return this.Re.length}retriableRequest(e){var{retriesPerformedSoFar:t}=e,n=wo(e,iu);ht(t)&&(n.url=Gr(n.url,{retry_count:t})),this._instance._send_request(C({},n,{callback:s=>{s.statusCode!==200&&(s.statusCode<400||s.statusCode>=500)&&(t??0)<10?this.Be(C({retriesPerformedSoFar:t},n)):n.callback==null||n.callback(s)}}))}Be(e){var t=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=t+1;var n=function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=(Math.random()-.5)*(u-l);return Math.ceil(u+c)}(t),s=Date.now()+n;this.Re.push({retryAt:s,requestOptions:e});var i="Enqueued failed request for retry in "+n;navigator.onLine||(i+=" (Browser is offline)"),E.warn(i),this.Le||(this.Le=!0,this.qe())}qe(){if(this.We&&clearTimeout(this.We),this.Re.length===0)return this.Le=!1,void(this.We=void 0);this.We=setTimeout(()=>{this.Ue&&this.Re.length>0&&this.Lt(),this.qe()},this.Ne)}Lt(){var e=Date.now(),t=[],n=this.Re.filter(i=>i.retryAt<e||(t.push(i),!1));if(this.Re=t,n.length>0)for(var{requestOptions:s}of n)this.retriableRequest(s)}unload(){for(var{requestOptions:e}of(this.We&&(clearTimeout(this.We),this.We=void 0),this.Le=!1,x(y)||(this.ze&&(y.removeEventListener("online",this.ze),this.ze=void 0),this.He&&(y.removeEventListener("offline",this.He),this.He=void 0)),this.Re))try{this._instance._send_request(C({},e,{transport:"sendBeacon"}))}catch(t){E.error(t)}this.Re=[]}},$s=class{constructor(e){this.Ge=()=>{var t,n,s,i;this.Ve||(this.Ve={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+(o?.clientHeight||0),c=o?.scrollHeight||0;this.Ve.lastScrollY=Math.ceil(a),this.Ve.maxScrollY=Math.max(a,(t=this.Ve.maxScrollY)!==null&&t!==void 0?t:0),this.Ve.maxScrollHeight=Math.max(l,(n=this.Ve.maxScrollHeight)!==null&&n!==void 0?n:0),this.Ve.lastContentY=u,this.Ve.maxContentY=Math.max(u,(s=this.Ve.maxContentY)!==null&&s!==void 0?s:0),this.Ve.maxContentHeight=Math.max(c,(i=this.Ve.maxContentHeight)!==null&&i!==void 0?i:0)},this._instance=e}getContext(){return this.Ve}resetContext(){var e=this.Ve;return setTimeout(this.Ge,0),e}startMeasuringScrollPosition(){K(y,"scroll",this.Ge,{capture:!0}),K(y,"scrollend",this.Ge,{capture:!0}),K(y,"resize",this.Ge)}scrollElement(){if(!this._instance.config.scroll_root_selector)return y?.document.documentElement;var e=N(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var t of e){var n=y?.document.querySelector(t);if(n)return n}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return y&&(y.scrollY||y.pageYOffset||y.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return y&&(y.scrollX||y.pageXOffset||y.document.documentElement.scrollLeft)||0}},ou=r=>ga(r?.config.mask_personal_data_properties,r?.config.custom_personal_data_properties),Ur=class{constructor(e,t,n,s){this.Je=i=>{var o=this.Ke();if(!o||o.sessionId!==i){var a={sessionId:i,props:this.Ye(this._instance)};this.Xe.register({[Qn]:a})}},this._instance=e,this.Qe=t,this.Xe=n,this.Ye=s||ou,this.Qe.onSessionId(this.Je)}Ke(){return this.Xe.props[Qn]}getSetOnceProps(){var e,t=(e=this.Ke())==null?void 0:e.props;return t?"r"in t?ya(t):{$referring_domain:t.referringDomain,$pathname:t.initialPathName,utm_source:t.utm_source,utm_campaign:t.utm_campaign,utm_medium:t.utm_medium,utm_content:t.utm_content,utm_term:t.utm_term}:{}}getSessionProps(){var e={};return q(Bs(this.getSetOnceProps()),(t,n)=>{n==="$current_url"&&(n="url"),e["$session_entry_"+Tn(n)]=t}),e}},In=L("[SessionId]"),Vr=class{on(e,t){return this.Ze.on(e,t)}constructor(e,t,n){var s;if(this.tr=[],this.ir=void 0,this.Ze=new ir,this.er=(c,p)=>!(!ht(c)||!ht(p))&&Math.abs(c-p)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.R=e.config,this.Xe=e.persistence,this.rr=void 0,this.sr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.nr=t||ze,this.ar=n||ze;var i=this.R.persistence_name||this.R.token,o=this.R.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*Pe(o,60,36e3,In.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.lr(),this.ur="ph_"+i+"_window_id",this.hr="ph_"+i+"_primary_window_exists",this.dr()){var a=Y.W(this.ur),l=Y.W(this.hr);a&&!l?this.rr=a:Y.V(this.ur),Y.G(this.hr,!0)}if((s=this.R.bootstrap)!=null&&s.sessionID)try{var u=(c=>{var p=c.replace(/-/g,"");if(p.length!==32)throw new Error("Not a valid UUID");if(p[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(p.substring(0,12),16)})(this.R.bootstrap.sessionID);this.vr(this.R.bootstrap.sessionID,new Date().getTime(),u)}catch(c){In.error("Invalid sessionID in bootstrap",c)}this.cr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return x(this.tr)&&(this.tr=[]),this.tr.push(e),this.sr&&e(this.sr,this.rr),()=>{this.tr=this.tr.filter(t=>t!==e)}}dr(){return this.R.persistence!=="memory"&&!this.Xe.ki&&Y.H()}pr(e){e!==this.rr&&(this.rr=e,this.dr()&&Y.G(this.ur,e))}gr(){return this.rr?this.rr:this.dr()?Y.W(this.ur):null}vr(e,t,n){e===this.sr&&t===this._sessionActivityTimestamp&&n===this._sessionStartTimestamp||(this._sessionStartTimestamp=n,this._sessionActivityTimestamp=t,this.sr=e,this.Xe.register({[Cr]:[t,e,n]}))}_r(){var e=this.Xe.props[Cr];return N(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.vr(null,null,null)}destroy(){clearTimeout(this.mr),this.mr=void 0,this.ir&&y&&(y.removeEventListener("beforeunload",this.ir,{capture:!1}),this.ir=void 0),this.tr=[]}cr(){this.ir=()=>{this.dr()&&Y.V(this.hr)},K(y,"beforeunload",this.ir,{capture:!1})}checkAndGetSessionAndWindowId(e,t){if(e===void 0&&(e=!1),t===void 0&&(t=null),this.R.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var n=t||new Date().getTime(),[s,i,o]=this._r(),a=this.gr(),l=ht(o)&&Math.abs(n-o)>864e5,u=!1,c=!i,p=!c&&!e&&this.er(n,s);c||p||l?(i=this.nr(),a=this.ar(),In.info("new session ID generated",{sessionId:i,windowId:a,changeReason:{noSessionId:c,activityTimeout:p,sessionPastMaximumLength:l}}),o=n,u=!0):a||(a=this.ar(),u=!0);var d=ht(s)&&e&&!l?s:n,h=ht(o)?o:new Date().getTime();return this.pr(a),this.vr(i,d,h),e||this.lr(),u&&this.tr.forEach(g=>g(i,a,u?{noSessionId:c,activityTimeout:p,sessionPastMaximumLength:l}:void 0)),{sessionId:i,windowId:a,sessionStartTimestamp:h,changeReason:u?{noSessionId:c,activityTimeout:p,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:s}}lr(){clearTimeout(this.mr),this.mr=setTimeout(()=>{var[e]=this._r();if(this.er(new Date().getTime(),e)){var t=this.sr;this.resetSessionId(),this.Ze.emit("forcedIdleReset",{idleSessionId:t})}},1.1*this.sessionTimeoutMs)}},au=["$set_once","$set"],Ue=L("[SiteApps]"),Ns=class{constructor(e){this._instance=e,this.br=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}yr(e,t){if(t){var n=this.globalsForEvent(t);this.br.push(n),this.br.length>1e3&&(this.br=this.br.slice(10))}}get siteAppLoaders(){var e;return(e=A._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}init(){if(this.isEnabled){var e=this._instance._addCaptureHook(this.yr.bind(this));this.wr=()=>{e(),this.br=[],this.wr=void 0}}}globalsForEvent(e){var t,n,s,i,o,a,l;if(!e)throw new Error("Event payload is required");var u={},c=this._instance.get_property("$groups")||[],p=this._instance.get_property("$stored_group_properties")||{};for(var[d,h]of Object.entries(p))u[d]={id:c[d],type:d,properties:h};var{$set_once:g,$set:f}=e;return{event:C({},wo(e,au),{properties:C({},e.properties,f?{$set:C({},(t=(n=e.properties)==null?void 0:n.$set)!==null&&t!==void 0?t:{},f)}:{},g?{$set_once:C({},(s=(i=e.properties)==null?void 0:i.$set_once)!==null&&s!==void 0?s:{},g)}:{}),elements_chain:(o=(a=e.properties)==null?void 0:a.$elements_chain)!==null&&o!==void 0?o:"",distinct_id:(l=e.properties)==null?void 0:l.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:u}}setupSiteApp(e){var t=this.apps[e.id],n=()=>{var a;!t.errored&&this.br.length&&(Ue.info("Processing "+this.br.length+" events for site app with id "+e.id),this.br.forEach(l=>t.processEvent==null?void 0:t.processEvent(l)),t.processedBuffer=!0),Object.values(this.apps).every(l=>l.processedBuffer||l.errored)&&((a=this.wr)==null||a.call(this))},s=!1,i=a=>{t.errored=!a,t.loaded=!0,Ue.info("Site app with id "+e.id+" "+(a?"loaded":"errored")),s&&n()};try{var{processEvent:o}=e.init({posthog:this._instance,callback:a=>{i(a)}});o&&(t.processEvent=o),s=!0}catch(a){Ue.error("Error while initializing PostHog app with config id "+e.id,a),i(!1)}if(s&&t.loaded)try{n()}catch(a){Ue.error("Error while processing buffered events PostHog app with config id "+e.id,a),t.errored=!0}}Er(){var e=this.siteAppLoaders||[];for(var t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of e)this.setupSiteApp(n)}$r(e){if(Object.keys(this.apps).length!==0){var t=this.globalsForEvent(e);for(var n of Object.values(this.apps))try{n.processEvent==null||n.processEvent(t)}catch(s){Ue.error("Error while processing event "+e.event+" for site app "+n.id,s)}}}onRemoteConfig(e){var t,n,s,i=this;if((t=this.siteAppLoaders)!=null&&t.length)return this.isEnabled?(this.Er(),void this._instance.on("eventCaptured",u=>this.$r(u))):void Ue.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.wr)==null||n.call(this),(s=e.siteApps)!=null&&s.length)if(this.isEnabled){var o=function(u){var c;A["__$$ph_site_app_"+u]=i._instance,(c=A.__PosthogExtensions__)==null||c.loadSiteApp==null||c.loadSiteApp(i._instance,l,p=>{if(p)return Ue.error("Error while initializing PostHog app with config id "+u,p)})};for(var{id:a,url:l}of e.siteApps)o(a)}else Ue.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}},Ea=function(r,e){if(!r)return!1;var t=r.userAgent;if(t&&Ii(t,e))return!0;try{var n=r?.userAgentData;if(n!=null&&n.brands&&n.brands.some(s=>Ii(s?.brand,e)))return!0}catch{}return!!r.webdriver},Yt=function(r){return r.US="us",r.EU="eu",r.CUSTOM="custom",r}({}),mo="i.posthog.com",Ds=class{constructor(e){this.Sr={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,t=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return t||(t=this.apiHost.replace("."+mo,".posthog.com")),t==="https://app.posthog.com"?"https://us.posthog.com":t}get region(){return this.Sr[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Sr[this.apiHost]=Yt.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Sr[this.apiHost]=Yt.EU:this.Sr[this.apiHost]=Yt.CUSTOM),this.Sr[this.apiHost]}endpointFor(e,t){if(t===void 0&&(t=""),t&&(t=t[0]==="/"?t:"/"+t),e==="ui")return this.uiHost+t;if(e==="flags")return this.flagsApiHost+t;if(this.region===Yt.CUSTOM)return this.apiHost+t;var n=mo+t;switch(e){case"assets":return"https://"+this.region+"-assets."+n;case"api":return"https://"+this.region+"."+n}}},lu={icontains:(r,e)=>!!y&&e.href.toLowerCase().indexOf(r.toLowerCase())>-1,not_icontains:(r,e)=>!!y&&e.href.toLowerCase().indexOf(r.toLowerCase())===-1,regex:(r,e)=>!!y&&Lr(e.href,r),not_regex:(r,e)=>!!y&&!Lr(e.href,r),exact:(r,e)=>e.href===r,is_not:(r,e)=>e.href!==r},qs=class r{constructor(e){var t=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(n){n===void 0&&(n=!1),t.getWebExperiments(s=>{r.kr("retrieved web experiments from the server"),t.Pr=new Map,s.forEach(i=>{if(i.feature_flag_key){var o;t.Pr&&(r.kr("setting flag key ",i.feature_flag_key," to web experiment ",i),(o=t.Pr)==null||o.set(i.feature_flag_key,i));var a=t._instance.getFeatureFlag(i.feature_flag_key);B(a)&&i.variants[a]&&t.Tr(i.name,a,i.variants[a].transforms)}else if(i.variants)for(var l in i.variants){var u=i.variants[l];r.Ir(u)&&t.Tr(i.name,l,u.transforms)}})},n)},this._instance=e,this._instance.onFeatureFlags(n=>{this.onFeatureFlags(n)})}onFeatureFlags(e){if(this._is_bot())r.kr("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if($(this.Pr))return this.Pr=new Map,this.loadIfEnabled(),void this.previewWebExperiment();r.kr("applying feature flags",e),e.forEach(t=>{var n;if(this.Pr&&(n=this.Pr)!=null&&n.has(t)){var s,i=this._instance.getFeatureFlag(t),o=(s=this.Pr)==null?void 0:s.get(t);i&&o!=null&&o.variants[i]&&this.Tr(o.name,i,o.variants[i].transforms)}})}}previewWebExperiment(){var e=r.getWindowLocation();if(e!=null&&e.search){var t=Or(e?.search,"__experiment_id"),n=Or(e?.search,"__experiment_variant");t&&n&&(r.kr("previewing web experiments "+t+" && "+n),this.getWebExperiments(s=>{this.Cr(parseInt(t),n,s)},!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,t,n){if(this._instance.config.disable_web_experiments&&!n)return e([]);var s=this._instance.get_property("$web_experiments");if(s&&!t)return e(s);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:i=>{if(i.statusCode!==200||!i.json)return e([]);var o=i.json.experiments||[];return e(o)}})}Cr(e,t,n){var s=n.filter(i=>i.id===e);s&&s.length>0&&(r.kr("Previewing web experiment ["+s[0].name+"] with variant ["+t+"]"),this.Tr(s[0].name,t,s[0].variants[t].transforms))}static Ir(e){return!$(e.conditions)&&r.Rr(e)&&r.Fr(e)}static Rr(e){var t;if($(e.conditions)||$((t=e.conditions)==null?void 0:t.url))return!0;var n,s,i,o=r.getWindowLocation();return!!o&&((n=e.conditions)==null||!n.url||lu[(s=(i=e.conditions)==null?void 0:i.urlMatchType)!==null&&s!==void 0?s:"icontains"](e.conditions.url,o))}static getWindowLocation(){return y?.location}static Fr(e){var t;if($(e.conditions)||$((t=e.conditions)==null?void 0:t.utm))return!0;var n=pa();if(n.utm_source){var s,i,o,a,l,u,c,p,d=(s=e.conditions)==null||(s=s.utm)==null||!s.utm_campaign||((i=e.conditions)==null||(i=i.utm)==null?void 0:i.utm_campaign)==n.utm_campaign,h=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==n.utm_source,g=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==n.utm_medium,f=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((p=e.conditions)==null||(p=p.utm)==null?void 0:p.utm_term)==n.utm_term;return d&&g&&f&&h}return!1}static kr(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];E.info("[WebExperiments] "+e,n)}Tr(e,t,n){this._is_bot()?r.kr("Refusing to render web experiment since the viewer is a likely bot"):t!=="control"?n.forEach(s=>{if(s.selector){var i;r.kr("applying transform of variant "+t+" for experiment "+e+" ",s);var o=(i=document)==null?void 0:i.querySelectorAll(s.selector);o?.forEach(a=>{var l=a;s.html&&(l.innerHTML=s.html),s.css&&l.setAttribute("style",s.css)})}}):r.kr("Control variants leave the page unmodified.")}_is_bot(){return le&&this._instance?Ea(le,this._instance.config.custom_blocked_useragents):void 0}},cu=L("[PostHog ExternalIntegrations]"),uu={intercom:"intercom-integration",crispChat:"crisp-chat-integration"},js=class{constructor(e){this._instance=e}it(e,t){var n;(n=A.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,e,s=>{if(s)return cu.error("failed to load script",s);t()})}startIfEnabledOrStop(){var e=this,t=function(o){var a,l,u;!s||(a=A.__PosthogExtensions__)!=null&&(a=a.integrations)!=null&&a[o]||e.it(uu[o],()=>{var c;(c=A.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[o])==null||c.start(e._instance)}),!s&&(l=A.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[o]&&((u=A.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[o])==null||u.stop())};for(var[n,s]of Object.entries((i=this._instance.config.integrations)!==null&&i!==void 0?i:{})){var i;t(n)}}},Gs="[SessionRecording]",Ut=L(Gs),zr=class{get started(){var e;return!((e=this.Or)==null||!e.isStarted)}get status(){return this.Or?this.Or.status:this.Mr&&!this.Ar?"disabled":"lazy_loading"}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.Mr=!1,this.jr=void 0,this._instance=e,!this._instance.sessionManager)throw Ut.error("started without valid sessionManager"),new Error(Gs+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(Gs+' cannot be used with cookieless_mode="always"')}get Ar(){var e,t=!((e=this._instance.get_property(yn))==null||!e.enabled),n=!this._instance.config.disable_session_recording,s=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return y&&t&&n&&!s}startIfEnabledOrStop(e){var t;if(!this.Ar||(t=this.Or)==null||!t.isStarted){var n=!x(Object.assign)&&!x(Array.from);this.Ar&&n?(this.Dr(e),Ut.info("starting")):this.stopRecording()}}Dr(e){var t,n,s;this.Ar&&(A!=null&&(t=A.__PosthogExtensions__)!=null&&(t=t.rrweb)!=null&&t.record&&(n=A.__PosthogExtensions__)!=null&&n.initSessionRecording?this.Lr(e):(s=A.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,this.Nr,i=>{if(i)return Ut.error("could not load recorder",i);this.Lr(e)}))}stopRecording(){var e,t;(e=this.jr)==null||e.call(this),this.jr=void 0,(t=this.Or)==null||t.stop()}Ur(){var e;(e=this._instance.persistence)==null||e.unregister(Wo)}zr(e){if(this._instance.persistence){var t,n,s=this._instance.persistence,i=()=>{var o=e.sessionRecording===!1?void 0:e.sessionRecording,a=o?.sampleRate,l=$(a)?null:parseFloat(a);$(l)&&this.Ur();var u=o?.minimumDurationMilliseconds;s.register({[yn]:C({enabled:!!o},o,{networkPayloadCapture:C({capturePerformance:e.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:l,minimumDurationMilliseconds:x(u)?null:u,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers})})};i(),(t=this.jr)==null||t.call(this),this.jr=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(i)}}onRemoteConfig(e){"sessionRecording"in e?e.sessionRecording!==!1?(this.zr(e),this.Mr=!0,this.startIfEnabledOrStop()):this.Mr=!0:Ut.info("skipping remote config with no sessionRecording",e)}log(e,t){var n;t===void 0&&(t="log"),(n=this.Or)!=null&&n.log?this.Or.log(e,t):Ut.warn("log called before recorder was ready")}get Nr(){var e,t,n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(yn);return(n==null||(t=n.scriptConfig)==null?void 0:t.script)||"lazy-recorder"}Lr(e){var t,n;if((t=A.__PosthogExtensions__)==null||!t.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.Or||(this.Or=(n=A.__PosthogExtensions__)==null?void 0:n.initSessionRecording(this._instance),this.Or._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.Or.start(e)}onRRwebEmit(e){var t;(t=this.Or)==null||t.onRRwebEmit==null||t.onRRwebEmit(e)}overrideLinkedFlag(){var e,t;this.Or||(t=this._instance.persistence)==null||t.register({$replay_override_linked_flag:!0}),(e=this.Or)==null||e.overrideLinkedFlag()}overrideSampling(){var e,t;this.Or||(t=this._instance.persistence)==null||t.register({$replay_override_sampling:!0}),(e=this.Or)==null||e.overrideSampling()}overrideTrigger(e){var t,n;this.Or||(n=this._instance.persistence)==null||n.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(t=this.Or)==null||t.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.Or)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,t){var n;return!((n=this.Or)==null||!n.tryAddCustomEvent(e,t))}},Qt={},Ls=()=>{},ft="posthog",Sa=!Zc&&ie?.indexOf("MSIE")===-1&&ie?.indexOf("Mozilla")===-1,vo=r=>{var e;return C({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:fc(P?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Ls,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:r??"unset",__preview_deferred_init_extensions:!1,debug:J&&B(J?.search)&&J.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!0,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(y==null||(e=y.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:t=>{var n="Bad HTTP status: "+t.statusCode+" "+t.text;E.error(n)},get_device_id:t=>t,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:Ts},error_tracking:{},_onCapture:Ls,__preview_eager_load_replay:!1},(t=>({rageclick:!(t&&t>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(t&&t>="2025-05-24")||"history_change",session_recording:t&&t>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:t&&t>="2026-01-30"?"head":"body",internal_or_test_user_hostname:t&&t>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0}))(r))},_o=r=>{var e={};x(r.process_person)||(e.person_profiles=r.process_person),x(r.xhr_headers)||(e.request_headers=r.xhr_headers),x(r.cookie_name)||(e.persistence_name=r.cookie_name),x(r.disable_cookie)||(e.disable_persistence=r.disable_cookie),x(r.store_google)||(e.save_campaign_params=r.store_google),x(r.verbose)||(e.debug=r.verbose);var t=U({},e,r);return N(r.property_blacklist)&&(x(r.property_denylist)?t.property_denylist=r.property_blacklist:N(r.property_denylist)?t.property_denylist=[...r.property_blacklist,...r.property_denylist]:E.error("Invalid value for property_denylist config: "+r.property_denylist)),t},Us=class{constructor(){this.__forceAllowLocalhost=!1}get Hr(){return this.__forceAllowLocalhost}set Hr(e){E.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},Kr=class r{get decideEndpointWasHit(){var e,t;return(e=(t=this.featureFlags)==null?void 0:t.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,t;return(e=(t=this.featureFlags)==null?void 0:t.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){this.webPerformance=new Us,this.Br=!1,this.version=Me.LIB_VERSION,this.qr=new ir,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=vo(),this.SentryIntegration=ps,this.sentryIntegration=e=>function(t,n){var s=ua(t,n);return{name:ca,processEvent:i=>s(i)}}(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Wr=!1,this.Gr=null,this.Vr=null,this.Jr=null,this.featureFlags=new ks(this),this.toolbar=new ds(this),this.scrollManager=new $s(this),this.pageViewManager=new Dr(this),this.surveys=new Cs(this),this.conversations=new As(this),this.logs=new Is(this),this.experiments=new qs(this),this.exceptions=new bs(this),this.rateLimiter=new Ms(this),this.requestRouter=new Ds(this),this.consent=new ls(this),this.externalIntegrations=new js(this),this.people={set:(e,t,n)=>{var s=B(e)?{[e]:t}:e;this.setPersonProperties(s),n?.({})},set_once:(e,t,n)=>{var s=B(e)?{[e]:t}:e;this.setPersonProperties(void 0,s),n?.({})}},this.on("eventCaptured",e=>E.info('send "'+e?.event+'"',e))}init(e,t,n){if(n&&n!==ft){var s,i=(s=Qt[n])!==null&&s!==void 0?s:new r;return i._init(e,t,n),Qt[n]=i,Qt[ft][n]=i,i}return this._init(e,t,n)}_init(e,t,n){var s;if(t===void 0&&(t={}),x(e)||Fn(e))return E.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},t.debug=this.Kr(t.debug),this.Yr=t,this.Xr=[],t.person_profiles&&(this.Vr=t.person_profiles),this.set_config(U({},vo(t.defaults),_o(t),{name:n,token:e})),this.config.on_xhr_error&&E.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=t.disable_compression?void 0:Fe.GZipJS;var i=this.Qr();this.persistence=new Zt(this.config,i),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Zt(C({},this.config,{persistence:"sessionStorage"}),i);var o=C({},this.persistence.props),a=C({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Zr=new Fs(b=>this.ts(b),this.config.request_queue_config),this.es=new Os(this),this.__request_queue=[];var l=this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut();if(l||(this.sessionManager=new Vr(this),this.sessionPropsManager=new Ur(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?(E.info("Deferring extension initialization to improve startup performance"),setTimeout(()=>{this.rs(l)},0)):(E.info("Initializing extensions synchronously"),this.rs(l)),Me.DEBUG=Me.DEBUG||this.config.debug,Me.DEBUG&&E.info("Starting in debug mode",{this:this,config:t,thisC:C({},this.config),p:o,s:a}),((s=t.bootstrap)==null?void 0:s.distinctID)!==void 0){var u,c,p=this.config.get_device_id(ze()),d=(u=t.bootstrap)!=null&&u.isIdentifiedID?p:t.bootstrap.distinctID;this.persistence.set_property(Re,(c=t.bootstrap)!=null&&c.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:t.bootstrap.distinctID,$device_id:d})}if(this.ss()){var h,g,f=Object.keys(((h=t.bootstrap)==null?void 0:h.featureFlags)||{}).filter(b=>{var v;return!((v=t.bootstrap)==null||(v=v.featureFlags)==null||!v[b])}).reduce((b,v)=>{var _;return b[v]=((_=t.bootstrap)==null||(_=_.featureFlags)==null?void 0:_[v])||!1,b},{}),m=Object.keys(((g=t.bootstrap)==null?void 0:g.featureFlagPayloads)||{}).filter(b=>f[b]).reduce((b,v)=>{var _,k;return(_=t.bootstrap)!=null&&(_=_.featureFlagPayloads)!=null&&_[v]&&(b[v]=(k=t.bootstrap)==null||(k=k.featureFlagPayloads)==null?void 0:k[v]),b},{});this.featureFlags.receivedFeatureFlags({featureFlags:f,featureFlagPayloads:m})}if(l)this.register_once({distinct_id:Ot,$device_id:null},"");else if(!this.get_distinct_id()){var w=this.config.get_device_id(ze());this.register_once({distinct_id:w,$device_id:w},""),this.persistence.set_property(Re,"anonymous")}return K(y,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),t.segment?Nc(this,()=>this.ns()):this.ns(),Ke(this.config._onCapture)&&this.config._onCapture!==Ls&&(E.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",b=>this.config._onCapture(b.event,b))),this.config.ip&&E.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this}rs(e){var t=performance.now();this.historyAutocapture=new us(this),this.historyAutocapture.startIfEnabled();var n=[];n.push(()=>{new hs(this).startIfEnabledOrStop()}),n.push(()=>{var s;this.siteApps=new Ns(this),(s=this.siteApps)==null||s.init()}),e||n.push(()=>{this.sessionRecording=new zr(this),this.sessionRecording.startIfEnabledOrStop()}),this.config.disable_scroll_properties||n.push(()=>{this.scrollManager.startMeasuringScrollPosition()}),n.push(()=>{this.autocapture=new ss(this),this.autocapture.startIfEnabled()}),n.push(()=>{this.surveys.loadIfEnabled()}),n.push(()=>{this.logs.loadIfEnabled()}),n.push(()=>{this.conversations.loadIfEnabled()}),n.push(()=>{this.productTours=new ws(this),this.productTours.loadIfEnabled()}),n.push(()=>{this.heatmaps=new gs(this),this.heatmaps.startIfEnabled()}),n.push(()=>{this.webVitalsAutocapture=new fs(this)}),n.push(()=>{this.exceptionObserver=new cs(this),this.exceptionObserver.startIfEnabledOrStop()}),n.push(()=>{this.deadClicksAutocapture=new Nr(this,$c),this.deadClicksAutocapture.startIfEnabled()}),n.push(()=>{if(this.os){var s=this.os;this.os=void 0,this.yi(s)}}),this.ls(n,t)}ls(e,t){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-t>=30&&e.length>0)return void setTimeout(()=>{this.ls(e,t)},0);var n=e.shift();if(n)try{n()}catch(i){E.error("Error initializing extension:",i)}}var s=Math.round(performance.now()-t);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:s}),this.config.__preview_deferred_init_extensions&&E.info("PostHog extensions initialized ("+s+"ms)")}yi(e){var t,n,s,i,o,a,l,u,c;if(!P||!P.body)return E.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this.yi(e)},500);this.config.__preview_deferred_init_extensions&&(this.os=e),this.compression=void 0,e.supportedCompression&&!this.config.disable_compression&&(this.compression=F(e.supportedCompression,Fe.GZipJS)?Fe.GZipJS:F(e.supportedCompression,Fe.Base64)?Fe.Base64:void 0),(t=e.analytics)!=null&&t.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Vr?this.Vr:"identified_only"}),(n=this.siteApps)==null||n.onRemoteConfig(e),(s=this.sessionRecording)==null||s.onRemoteConfig(e),(i=this.autocapture)==null||i.onRemoteConfig(e),(o=this.heatmaps)==null||o.onRemoteConfig(e),this.surveys.onRemoteConfig(e),this.logs.onRemoteConfig(e),this.conversations.onRemoteConfig(e),(a=this.productTours)==null||a.onRemoteConfig(e),(l=this.webVitalsAutocapture)==null||l.onRemoteConfig(e),(u=this.exceptionObserver)==null||u.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(c=this.deadClicksAutocapture)==null||c.onRemoteConfig(e)}ns(){try{this.config.loaded(this)}catch(n){E.critical("`loaded` function failed",n)}if(this.us(),this.config.internal_or_test_user_hostname&&J!=null&&J.hostname){var e=J.hostname,t=this.config.internal_or_test_user_hostname;(typeof t=="string"?e===t:t.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.hs()},1),new Rs(this).load(),this.featureFlags.flags()}us(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.Zr)==null||e.enable())}_dom_loaded(){this.is_capturing()&&He(this.__request_queue,e=>this.ts(e)),this.__request_queue=[],this.us()}_handle_unload(){var e,t;this.surveys.handlePageUnload(),this.config.request_batching?(this.ds()&&this.capture("$pageleave"),(e=this.Zr)==null||e.unload(),(t=this.es)==null||t.unload()):this.ds()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}_send_request(e){this.__loaded&&(Sa?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=Gr(e.url,{ip:this.config.ip?1:0}),e.headers=C({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,e.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(t=>{var n,s,i,o=C({},t);o.timeout=o.timeout||6e4,o.url=Gr(o.url,{_:new Date().getTime().toString(),ver:Me.LIB_VERSION,compression:o.compression});var a=(n=o.transport)!==null&&n!==void 0?n:"fetch",l=Pr.filter(c=>!o.disableTransport||!c.transport||!o.disableTransport.includes(c.transport)),u=(s=(i=Ko(l,c=>c.transport===a))==null?void 0:i.method)!==null&&s!==void 0?s:l[0].method;if(!u)throw new Error("No available transport method");u(o)})(C({},e,{callback:t=>{var n,s;this.rateLimiter.checkForLimiting(t),t.statusCode>=400&&((n=(s=this.config).on_request_error)==null||n.call(s,t)),e.callback==null||e.callback(t)}}))))}ts(e){this.es?this.es.retriableRequest(e):this._send_request(e)}_execute_array(e){var t,n=[],s=[],i=[];He(e,a=>{a&&(t=a[0],N(t)?i.push(a):Ke(a)?a.call(this):N(a)&&t==="alias"?n.push(a):N(a)&&t.indexOf("capture")!==-1&&Ke(this[t])?i.push(a):s.push(a))});var o=function(a,l){He(a,function(u){if(N(u[0])){var c=l;q(u,function(p){c=c[p[0]].apply(c,p.slice(1))})}else this[u[0]].apply(this,u.slice(1))},l)};o(n,this),o(s,this),o(i,this)}ss(){var e,t;return((e=this.config.bootstrap)==null?void 0:e.featureFlags)&&Object.keys((t=this.config.bootstrap)==null?void 0:t.featureFlags).length>0||!1}push(e){this._execute_array([e])}capture(e,t,n){var s;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Zr){if(this.is_capturing())if(!x(e)&&B(e)){var i=!this.config.opt_out_useragent_filter&&this._is_bot();if(!(i&&!this.config.__preview_capture_bot_pageviews)){var o=n!=null&&n.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(o==null||!o.isRateLimited){t!=null&&t.$current_url&&!B(t?.$current_url)&&(E.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),t==null||delete t.$current_url),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var a=new Date,l=n?.timestamp||a,u=ze(),c={uuid:u,event:e,properties:this.calculateEventProperties(e,t||{},l,u)};e==="$pageview"&&this.config.__preview_capture_bot_pageviews&&i&&(c.event="$bot_pageview",c.properties.$browser_type="bot"),o&&(c.properties.$lib_rate_limit_remaining_tokens=o.remainingTokens),n?.$set&&(c.$set=n?.$set);var p,d=e!=="$groupidentify",h=this.vs(n?.$set_once,d);if(h&&(c.$set_once=h),(c=dc(c,n!=null&&n._noTruncate?null:this.config.properties_string_max_length)).timestamp=l,x(n?.timestamp)||(c.properties.$event_time_override_provided=!0,c.properties.$event_time_override_system_time=a),e===Xt.DISMISSED||e===Xt.SENT){var g=t?.[An.SURVEY_ID],f=t?.[An.SURVEY_ITERATION];p={id:g,current_iteration:f},localStorage.getItem(go(p))||localStorage.setItem(go(p),"true"),c.$set=C({},c.$set,{[ru({id:g,current_iteration:f},e===Xt.SENT?"responded":"dismissed")]:!0})}else e===Xt.SHOWN&&(c.$set=C({},c.$set,{[An.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));var m=C({},c.properties.$set,c.$set);if(yt(m)||this.setPersonPropertiesForFlags(m),!$(this.config.before_send)){var w=this.cs(c);if(!w)return;c=w}this.qr.emit("eventCaptured",c);var b={method:"POST",url:(s=n?._url)!==null&&s!==void 0?s:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:c,compression:"best-available",batchKey:n?._batchKey};return!this.config.request_batching||n&&(n==null||!n._batchKey)||n!=null&&n.send_instantly?this.ts(b):this.Zr.enqueue(b),c}E.critical("This capture call is ignored due to client rate limiting.")}}else E.error("No event name provided to posthog.capture")}else E.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",t=>e(t.event,t))}calculateEventProperties(e,t,n,s,i){if(n=n||new Date,!this.persistence||!this.sessionPersistence)return t;var o=i?void 0:this.persistence.remove_event_timer(e),a=C({},t);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(a.$cookieless_mode=!0),e==="$snapshot"){var l=C({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!B(a.distinct_id)&&!Ne(a.distinct_id)||Fn(a.distinct_id))&&E.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=Uc(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:p,windowId:d}=this.sessionManager.checkAndGetSessionAndWindowId(i,n.getTime());a.$session_id=p,a.$window_id=d}this.sessionPropsManager&&U(a,this.sessionPropsManager.getSessionProps());try{var h;this.sessionRecording&&U(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(h=this.es)==null?void 0:h.length}catch(w){a.$sdk_debug_error_capturing_properties=String(w)}if(this.requestRouter.region===Yt.CUSTOM&&(a.$lib_custom_api_host=this.config.api_host),u=e!=="$pageview"||i?e!=="$pageleave"||i?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(n):this.pageViewManager.doPageView(n,s),a=U(a,u),e==="$pageview"&&P&&(a.title=P.title),!x(o)){var g=n.getTime()-o;a.$duration=parseFloat((g/1e3).toFixed(3))}ie&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser"),(a=U({},c,this.persistence.properties(),this.sessionPersistence.properties(),a)).$is_identified=this._isIdentified(),N(this.config.property_denylist)?q(this.config.property_denylist,function(w){delete a[w]}):E.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var f=this.config.sanitize_properties;f&&(E.error("sanitize_properties is deprecated. Use before_send instead"),a=f(a,e));var m=this.fs();return a.$process_person_profile=m,m&&!i&&this.ps("_calculate_event_properties"),a}vs(e,t){var n;if(t===void 0&&(t=!0),!this.persistence||!this.fs()||this.Br)return e;var s=this.persistence.get_initial_props(),i=(n=this.sessionPropsManager)==null?void 0:n.getSetOnceProps(),o=U({},s,i||{},e||{}),a=this.config.sanitize_properties;return a&&(E.error("sanitize_properties is deprecated. Use before_send instead"),o=a(o,"$set_once")),t&&(this.Br=!0),yt(o)?void 0:o}register(e,t){var n;(n=this.persistence)==null||n.register(e,t)}register_once(e,t,n){var s;(s=this.persistence)==null||s.register_once(e,t,n)}register_for_session(e){var t;(t=this.sessionPersistence)==null||t.register(e)}unregister(e){var t;(t=this.persistence)==null||t.unregister(e)}unregister_for_session(e){var t;(t=this.sessionPersistence)==null||t.unregister(e)}gs(e,t){this.register({[e]:t})}getFeatureFlag(e,t){return this.featureFlags.getFeatureFlag(e,t)}getFeatureFlagPayload(e){return this.featureFlags.getFeatureFlagPayload(e)}getFeatureFlagResult(e,t){return this.featureFlags.getFeatureFlagResult(e,t)}isFeatureEnabled(e,t){return this.featureFlags.isFeatureEnabled(e,t)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateFlags(e,t,n){var s=n!=null&&n.merge?this.featureFlags.getFlagVariants():{},i=n!=null&&n.merge?this.featureFlags.getFlagPayloads():{},o=C({},s,e),a=C({},i,t),l={};for(var[u,c]of Object.entries(o)){var p=typeof c=="string";l[u]={key:u,enabled:!!p||!!c,variant:p?c:void 0,reason:void 0,metadata:x(a?.[u])?void 0:{id:0,version:void 0,description:void 0,payload:a[u]}}}this.featureFlags.receivedFeatureFlags({flags:l})}updateEarlyAccessFeatureEnrollment(e,t,n){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,t,n)}getEarlyAccessFeatures(e,t,n){return t===void 0&&(t=!1),this.featureFlags.getEarlyAccessFeatures(e,t,n)}on(e,t){return this.qr.on(e,t)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var t,n;return(t=(n=this.sessionManager)==null?void 0:n.onSessionId(e))!==null&&t!==void 0?t:()=>{}}getSurveys(e,t){t===void 0&&(t=!1),this.surveys.getSurveys(e,t)}getActiveMatchingSurveys(e,t){t===void 0&&(t=!1),this.surveys.getActiveMatchingSurveys(e,t)}renderSurvey(e,t){this.surveys.renderSurvey(e,t)}displaySurvey(e,t){t===void 0&&(t=su),this.surveys.displaySurvey(e,t)}cancelPendingSurvey(e){this.surveys.cancelPendingSurvey(e)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,t){return t===void 0&&(t=!1),this.surveys.canRenderSurveyAsync(e,t)}identify(e,t,n){if(!this.__loaded||!this.persistence)return E.uninitializedWarning("posthog.identify");if(Ne(e)&&(e=e.toString(),E.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),e)if(["distinct_id","distinctid"].includes(e.toLowerCase()))E.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(e!==Ot){if(this.ps("posthog.identify")){var s=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var i=s;this.register_once({$had_persisted_distinct_id:!0,$device_id:i},"")}e!==s&&e!==this.get_property(zt)&&(this.unregister(zt),this.register({distinct_id:e}));var o=(this.persistence.get_property(Re)||"anonymous")==="anonymous";e!==s&&o?(this.persistence.set_property(Re,"identified"),this.setPersonPropertiesForFlags(C({},n||{},t||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:s},{$set:t||{},$set_once:n||{}}),this.Jr=lo(e,t,n),this.featureFlags.setAnonymousDistinctId(s)):(t||n)&&this.setPersonProperties(t,n),e!==s&&(this.reloadFeatureFlags(),this.unregister(Ar))}}else E.critical('The string "'+Ot+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else E.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,t){if((e||t)&&this.ps("posthog.setPersonProperties")){var n=lo(this.get_distinct_id(),e,t);this.Jr!==n?(this.setPersonPropertiesForFlags(C({},t||{},e||{})),this.capture("$set",{$set:e||{},$set_once:t||{}}),this.Jr=n):E.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,t,n){if(e&&t){var s=this.getGroups();s[e]!==t&&this.resetGroupPropertiesForFlags(e),this.register({$groups:C({},s,{[e]:t})}),n&&(this.capture("$groupidentify",{$group_type:e,$group_key:t,$group_set:n}),this.setGroupPropertiesForFlags({[e]:n})),s[e]===t||n||this.reloadFeatureFlags()}else E.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,t){t===void 0&&(t=!0),this.featureFlags.setPersonPropertiesForFlags(e,t)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,t){t===void 0&&(t=!0),this.ps("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,t)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var t,n,s,i;if(E.info("reset"),!this.__loaded)return E.uninitializedWarning("posthog.reset");var o=this.get_property("$device_id");if(this.consent.reset(),(t=this.persistence)==null||t.clear(),(n=this.sessionPersistence)==null||n.clear(),this.surveys.reset(),this.featureFlags.reset(),(s=this.persistence)==null||s.set_property(Re,"anonymous"),(i=this.sessionManager)==null||i.resetSessionId(),this.Jr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:Ot,$device_id:null},"");else{var a=this.config.get_device_id(ze());this.register_once({distinct_id:a,$device_id:e?a:o},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,t;return(e=(t=this.sessionManager)==null?void 0:t.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:t,sessionStartTimestamp:n}=this.sessionManager.checkAndGetSessionAndWindowId(!0),s=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+t);if(e!=null&&e.withTimestamp&&n){var i,o=(i=e.timestampLookBack)!==null&&i!==void 0?i:10;if(!n)return s;s+="?t="+Math.max(Math.floor((new Date().getTime()-n)/1e3)-o,0)}return s}alias(e,t){return e===this.get_property(Ho)?(E.critical("Attempting to create alias for existing People user - aborting."),-2):this.ps("posthog.alias")?(x(t)&&(t=this.get_distinct_id()),e!==t?(this.gs(zt,e),this.capture("$create_alias",{alias:e,distinct_id:t})):(E.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var t=C({},this.config);if(H(e)){var n,s,i,o,a,l,u;U(this.config,_o(e));var c=this.Qr();(n=this.persistence)==null||n.update_config(this.config,t,c),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Zt(C({},this.config,{persistence:"sessionStorage"}),c);var p=this.Kr(this.config.debug);$e(p)&&(this.config.debug=p),$e(this.config.debug)&&(this.config.debug?(Me.DEBUG=!0,G.H()&&G.G("ph_debug","true"),E.info("set_config",{config:e,oldConfig:t,newConfig:C({},this.config)})):(Me.DEBUG=!1,G.H()&&G.V("ph_debug"))),(s=this.exceptionObserver)==null||s.onConfigChange(),(i=this.sessionRecording)==null||i.startIfEnabledOrStop(),(o=this.autocapture)==null||o.startIfEnabled(),(a=this.heatmaps)==null||a.startIfEnabled(),(l=this.exceptionObserver)==null||l.startIfEnabledOrStop(),this.surveys.loadIfEnabled(),this._s(),(u=this.externalIntegrations)==null||u.startIfEnabledOrStop()}}startSessionRecording(e){var t=e===!0,n={sampling:t||!(e==null||!e.sampling),linked_flag:t||!(e==null||!e.linked_flag),url_trigger:t||!(e==null||!e.url_trigger),event_trigger:t||!(e==null||!e.event_trigger)};if(Object.values(n).some(Boolean)){var s,i,o,a,l;(s=this.sessionManager)==null||s.checkAndGetSessionAndWindowId(),n.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),n.linked_flag&&((o=this.sessionRecording)==null||o.overrideLinkedFlag()),n.url_trigger&&((a=this.sessionRecording)==null||a.overrideTrigger("url")),n.event_trigger&&((l=this.sessionRecording)==null||l.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,t){var n=new Error("PostHog syntheticException"),s=this.exceptions.buildProperties(e,{handled:!0,syntheticException:n});return this.exceptions.sendExceptionEvent(C({},s,t))}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var t;return(t=this.persistence)==null?void 0:t.props[e]}getSessionProperty(e){var t;return(t=this.sessionPersistence)==null?void 0:t.props[e]}toString(){var e,t=(e=this.config.name)!==null&&e!==void 0?e:ft;return t!==ft&&(t=ft+"."+t),t}_isIdentified(){var e,t;return((e=this.persistence)==null?void 0:e.get_property(Re))==="identified"||((t=this.sessionPersistence)==null?void 0:t.get_property(Re))==="identified"}fs(){var e,t;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&yt(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[zt])&&((t=this.persistence)==null||(t=t.props)==null||!t[Mr]))}ds(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.fs()||this.ps("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.ps("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}ps(e){return this.config.person_profiles==="never"?(E.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.gs(Mr,!0),!0)}Qr(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut(),t=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||e&&!!t}_s(){var e,t,n,s,i=this.Qr();return((e=this.persistence)==null?void 0:e.ki)!==i&&((n=this.persistence)==null||n.set_disabled(i)),((t=this.sessionPersistence)==null?void 0:t.ki)!==i&&((s=this.sessionPersistence)==null||s.set_disabled(i)),i}opt_in_capturing(e){var t;if(this.config.cookieless_mode!=="always"){var n,s,i;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(n=this.sessionManager)==null||n.destroy(),(s=this.pageViewManager)==null||s.destroy(),this.sessionManager=new Vr(this),this.pageViewManager=new Dr(this),this.persistence&&(this.sessionPropsManager=new Ur(this,this.sessionManager,this.persistence)),this.sessionRecording=new zr(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this._s(),this.us(),(t=this.sessionRecording)==null||t.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(x(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((i=e?.captureEventName)!==null&&i!==void 0?i:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.hs()}else E.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e,t,n;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this._s(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:Ot,$device_id:null}),(e=this.sessionManager)==null||e.destroy(),(t=this.pageViewManager)==null||t.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(n=this.sessionRecording)==null||n.stopRecording(),this.sessionRecording=void 0,this.hs())):E.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===Te.GRANTED?"granted":e===Te.DENIED?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isExplicitlyOptedOut()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this._s()}_is_bot(){return le?Ea(le,this.config.custom_blocked_useragents):void 0}hs(){P&&(P.visibilityState==="visible"?this.Wr||(this.Wr=!0,this.capture("$pageview",{title:P.title},{send_instantly:!0}),this.Gr&&(P.removeEventListener("visibilitychange",this.Gr),this.Gr=null)):this.Gr||(this.Gr=this.hs.bind(this),K(P,"visibilitychange",this.Gr)))}debug(e){e===!1?(y?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(y?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}M(){var e,t,n,s,i,o,a,l=this.Yr||{};return"advanced_disable_flags"in l?!!l.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(E.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(n="advanced_disable_decide",s=!1,i=E,o=(t="advanced_disable_flags")in(e=l)&&!$(e[t]),a=n in e&&!$(e[n]),o?e[t]:a?(i&&i.warn("Config field '"+n+"' is deprecated. Please use '"+t+"' instead. The old field will be removed in a future major version."),e[n]):s)}cs(e){if($(this.config.before_send))return e;var t=N(this.config.before_send)?this.config.before_send:[this.config.before_send],n=e;for(var s of t){if(n=s(n),$(n)){var i="Event '"+e.event+"' was rejected in beforeSend function";return jl(e.event)?E.warn(i+". This can cause unexpected behavior."):E.info(i),null}n.properties&&!yt(n.properties)||E.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return n}getPageViewId(){var e;return(e=this.pageViewManager.Kt)==null?void 0:e.pageViewId}captureTraceFeedback(e,t){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:t})}captureTraceMetric(e,t,n){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:t,$ai_metric_value:String(n)})}Kr(e){var t=$e(e)&&!e,n=G.H()&&G.q("ph_debug")==="true";return!t&&(!!n||e)}};(function(r,e){for(var t=0;t<e.length;t++)r.prototype[e[t]]=pc(r.prototype[e[t]])})(Kr,["identify"]);var bo;var Xr=(bo=Qt[ft]=new Kr,function(){function r(){r.done||(r.done=!0,Sa=!1,q(Qt,function(e){e._dom_loaded()}))}P!=null&&P.addEventListener?P.readyState==="complete"?r():K(P,"DOMContentLoaded",r,{capture:!1}):y&&E.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}(),bo);var pu="phc_u9YDYUeUxo3CYn16XGrrwpVb8ycXgcjz5DarvIKRAAG",cr=class r{constructor(e){R(this,"initialized",!1);this.initPostHog(e)}static getInstance(e){if(typeof window>"u")throw new Error("[PaymentKit Analytics] PostHog requires a browser environment");let t=window.__paymentKitPostHog__;if(t){if(t.apiBaseUrl!==e)throw new Error(`[PaymentKit Analytics] PostHog already initialized with apiBaseUrl "${t.apiBaseUrl}", cannot re-initialize with different apiBaseUrl "${e}"`);return t.instance}let n=new r(e);return window.__paymentKitPostHog__={instance:n,apiBaseUrl:e},n}initPostHog(e){try{Xr.init(pu,{api_host:`${e}/ingest`,ui_host:"https://us.posthog.com",persistence:"memory",disable_session_recording:!0,autocapture:!1,capture_pageview:!1,request_batching:!1,opt_out_useragent_filter:!0,loaded:()=>{this.initialized=!0}})}catch(t){console.warn("[PaymentKit Analytics] Failed to initialize PostHog:",t)}}identify(e){try{Xr.identify(e)}catch(t){console.warn("[PaymentKit Analytics] Failed to identify:",t)}}capture(e,t){try{Xr.capture(e,t)}catch(n){console.warn("[PaymentKit Analytics] Failed to capture event:",n)}}isInitialized(){return this.initialized}};var Qs=class{constructor(){R(this,"adapters",[]);R(this,"testMock",null)}init(e,t){try{this.addAdapter(cr.getInstance(e)),t&&this.enableTestMode()}catch(n){console.warn("[PaymentKit Analytics] Init failed:",n)}}enableTestMode(){this.testMock||(this.testMock=new Ft,this.addAdapter(this.testMock),typeof window<"u"&&(window.__paymentKitAnalytics__=this.testMock))}getTestMock(){return this.testMock}addAdapter(e){this.adapters.includes(e)||this.adapters.push(e)}clearAdapters(){this.adapters=[],this.testMock=null,typeof window<"u"&&delete window.__paymentKitAnalytics__}identify(e){for(let t of this.adapters)try{t.identify(e)}catch{}}capture(e,t){for(let n of this.adapters)try{n.capture(e,t)}catch{}}isInitialized(){return this.adapters.some(e=>e.isInitialized())}},xe=new Qs;var ur=class ur{constructor(e,t){R(this,"startTime");R(this,"checkoutSessionId");R(this,"requestId");R(this,"inputReadyTracked",!1);this.startTime=performance.now(),this.checkoutSessionId=e,this.requestId=t}trackPageReady(){ur.pageReadyTracked||(ur.pageReadyTracked=!0,xe.capture("checkout_page_ready",{checkout_session_id:this.checkoutSessionId,request_id:this.requestId,elapsed_ms:this.getElapsedMs()}))}trackInputReady(){this.inputReadyTracked||(this.inputReadyTracked=!0,xe.capture("checkout_input_ready",{checkout_session_id:this.checkoutSessionId,request_id:this.requestId,elapsed_ms:this.getElapsedMs()}))}trackSubmit(){xe.capture("checkout_submit",{checkout_session_id:this.checkoutSessionId,request_id:this.requestId,elapsed_ms:this.getElapsedMs()})}trackSuccess(e){xe.capture("checkout_success",{checkout_session_id:this.checkoutSessionId,checkout_attempt_id:e,request_id:this.requestId,total_elapsed_ms:this.getElapsedMs()})}trackFail(e,t,n){xe.capture("checkout_fail",{checkout_session_id:this.checkoutSessionId,checkout_attempt_id:e,request_id:this.requestId,error_code:t,error_message:n,total_elapsed_ms:this.getElapsedMs()})}getElapsedMs(){return Math.round(performance.now()-this.startTime)}};R(ur,"pageReadyTracked",!1);var pr=ur;var du=class extends Error{constructor(e,t){super(t);R(this,"code");this.name="PenpalError",this.code=e}},pe=du,hu=r=>({name:r.name,message:r.message,stack:r.stack,penpalCode:r instanceof pe?r.code:void 0}),fu=({name:r,message:e,stack:t,penpalCode:n})=>{let s=n?new pe(n,e):new Error(e);return s.name=r,s.stack=t,s},gu=Symbol("Reply"),ri,Ra,yu=(Ra=class{constructor(r,e){R(this,"value");R(this,"transferables");ee(this,ri,gu);this.value=r,this.transferables=e?.transferables}},ri=new WeakMap,Ra),mu=yu,ue="penpal",Qr=r=>typeof r=="object"&&r!==null,Oa=r=>typeof r=="function",vu=r=>Qr(r)&&r.namespace===ue,Yr=r=>r.type==="SYN",si=r=>r.type==="ACK1",ei=r=>r.type==="ACK2",$a=r=>r.type==="CALL",Na=r=>r.type==="REPLY",_u=r=>r.type==="DESTROY",Da=(r,e=[])=>{let t=[];for(let n of Object.keys(r)){let s=r[n];Oa(s)?t.push([...e,n]):Qr(s)&&t.push(...Da(s,[...e,n]))}return t},bu=(r,e)=>{let t=r.reduce((n,s)=>Qr(n)?n[s]:void 0,e);return Oa(t)?t:void 0},Ye=r=>r.join("."),Ca=(r,e,t)=>({namespace:ue,channel:r,type:"REPLY",callId:e,isError:!0,...t instanceof Error?{value:hu(t),isSerializedErrorInstance:!0}:{value:t}}),ku=(r,e,t,n)=>{let s=!1,i=async o=>{if(s||!$a(o))return;n?.(`Received ${Ye(o.methodPath)}() call`,o);let{methodPath:a,args:l,id:u}=o,c,p;try{let d=bu(a,e);if(!d)throw new pe("METHOD_NOT_FOUND",`Method \`${Ye(a)}\` is not found.`);let h=await d(...l);h instanceof mu&&(p=h.transferables,h=await h.value),c={namespace:ue,channel:t,type:"REPLY",callId:u,value:h}}catch(d){c=Ca(t,u,d)}if(!s)try{n?.(`Sending ${Ye(a)}() reply`,c),r.sendMessage(c,p)}catch(d){throw d.name==="DataCloneError"&&(c=Ca(t,u,d),n?.(`Sending ${Ye(a)}() reply`,c),r.sendMessage(c)),d}};return r.addMessageHandler(i),()=>{s=!0,r.removeMessageHandler(i)}},wu=ku,qa=crypto.randomUUID?.bind(crypto)??(()=>new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")),Pu=Symbol("CallOptions"),ni,Ta,xu=(Ta=class{constructor(r){R(this,"transferables");R(this,"timeout");ee(this,ni,Pu);this.transferables=r?.transferables,this.timeout=r?.timeout}},ni=new WeakMap,Ta),Eu=xu,Su=new Set(["apply","call","bind"]),ja=(r,e,t=[])=>new Proxy(t.length?()=>{}:Object.create(null),{get(n,s){if(s!=="then")return t.length&&Su.has(s)?Reflect.get(n,s):ja(r,e,[...t,s])},apply(n,s,i){return r(t,i)}}),Aa=r=>new pe("CONNECTION_DESTROYED",`Method call ${Ye(r)}() failed due to destroyed connection`),Cu=(r,e,t)=>{let n=!1,s=new Map,i=l=>{if(!Na(l))return;let{callId:u,value:c,isError:p,isSerializedErrorInstance:d}=l,h=s.get(u);h&&(s.delete(u),t?.(`Received ${Ye(h.methodPath)}() call`,l),p?h.reject(d?fu(c):c):h.resolve(c))};return r.addMessageHandler(i),{remoteProxy:ja((l,u)=>{if(n)throw Aa(l);let c=qa(),p=u[u.length-1],d=p instanceof Eu,{timeout:h,transferables:g}=d?p:{},f=d?u.slice(0,-1):u;return new Promise((m,w)=>{let b=h!==void 0?window.setTimeout(()=>{s.delete(c),w(new pe("METHOD_CALL_TIMEOUT",`Method call ${Ye(l)}() timed out after ${h}ms`))},h):void 0;s.set(c,{methodPath:l,resolve:m,reject:w,timeoutId:b});try{let v={namespace:ue,channel:e,type:"CALL",id:c,methodPath:l,args:f};t?.(`Sending ${Ye(l)}() call`,v),r.sendMessage(v,g)}catch(v){w(new pe("TRANSMISSION_FAILED",v.message))}})},t),destroy:()=>{n=!0,r.removeMessageHandler(i);for(let{methodPath:l,reject:u,timeoutId:c}of s.values())clearTimeout(c),u(Aa(l));s.clear()}}},Au=Cu,Iu=()=>{let r,e;return{promise:new Promise((n,s)=>{r=n,e=s}),resolve:r,reject:e}},Mu=Iu,Ru=class extends Error{constructor(r){super(`You've hit a bug in Penpal. Please file an issue with the following information: ${r}`)}},Jr=Ru,ti="deprecated-penpal",Tu=r=>Qr(r)&&"penpal"in r,Fu=r=>r.split("."),Ia=r=>r.join("."),Ga=r=>new Jr(`Unexpected message to translate: ${JSON.stringify(r)}`),Ou=r=>{if(r.penpal==="syn")return{namespace:ue,channel:void 0,type:"SYN",participantId:ti};if(r.penpal==="ack")return{namespace:ue,channel:void 0,type:"ACK2"};if(r.penpal==="call")return{namespace:ue,channel:void 0,type:"CALL",id:r.id,methodPath:Fu(r.methodName),args:r.args};if(r.penpal==="reply")return r.resolution==="fulfilled"?{namespace:ue,channel:void 0,type:"REPLY",callId:r.id,value:r.returnValue}:{namespace:ue,channel:void 0,type:"REPLY",callId:r.id,isError:!0,...r.returnValueIsError?{value:r.returnValue,isSerializedErrorInstance:!0}:{value:r.returnValue}};throw Ga(r)},$u=r=>{if(si(r))return{penpal:"synAck",methodNames:r.methodPaths.map(Ia)};if($a(r))return{penpal:"call",id:r.id,methodName:Ia(r.methodPath),args:r.args};if(Na(r))return r.isError?{penpal:"reply",id:r.callId,resolution:"rejected",...r.isSerializedErrorInstance?{returnValue:r.value,returnValueIsError:!0}:{returnValue:r.value}}:{penpal:"reply",id:r.callId,resolution:"fulfilled",returnValue:r.value};throw Ga(r)},Nu=({messenger:r,methods:e,timeout:t,channel:n,log:s})=>{let i=qa(),o,a=[],l=!1,u=Da(e),{promise:c,resolve:p,reject:d}=Mu(),h=t!==void 0?setTimeout(()=>{d(new pe("CONNECTION_TIMEOUT",`Connection timed out after ${t}ms`))},t):void 0,g=()=>{for(let k of a)k()},f=()=>{if(l)return;a.push(wu(r,e,n,s));let{remoteProxy:k,destroy:M}=Au(r,n,s);a.push(M),clearTimeout(h),l=!0,p({remoteProxy:k,destroy:g})},m=()=>{let k={namespace:ue,type:"SYN",channel:n,participantId:i};s?.("Sending handshake SYN",k);try{r.sendMessage(k)}catch(M){d(new pe("TRANSMISSION_FAILED",M.message))}},w=k=>{if(s?.("Received handshake SYN",k),k.participantId===o&&o!==ti||(o=k.participantId,m(),!(i>o||o===ti)))return;let I={namespace:ue,channel:n,type:"ACK1",methodPaths:u};s?.("Sending handshake ACK1",I);try{r.sendMessage(I)}catch(S){d(new pe("TRANSMISSION_FAILED",S.message));return}},b=k=>{s?.("Received handshake ACK1",k);let M={namespace:ue,channel:n,type:"ACK2"};s?.("Sending handshake ACK2",M);try{r.sendMessage(M)}catch(I){d(new pe("TRANSMISSION_FAILED",I.message));return}f()},v=k=>{s?.("Received handshake ACK2",k),f()},_=k=>{Yr(k)&&w(k),si(k)&&b(k),ei(k)&&v(k)};return r.addMessageHandler(_),a.push(()=>r.removeMessageHandler(_)),m(),c},Du=Nu,qu=r=>{let e=!1,t;return(...n)=>(e||(e=!0,t=r(...n)),t)},ju=qu,Ma=new WeakSet,Gu=({messenger:r,methods:e={},timeout:t,channel:n,log:s})=>{if(!r)throw new pe("INVALID_ARGUMENT","messenger must be defined");if(Ma.has(r))throw new pe("INVALID_ARGUMENT","A messenger can only be used for a single connection");Ma.add(r);let i=[r.destroy],o=ju(u=>{if(u){let c={namespace:ue,channel:n,type:"DESTROY"};try{r.sendMessage(c)}catch{}}for(let c of i)c();s?.("Connection destroyed")}),a=u=>vu(u)&&u.channel===n;return{promise:(async()=>{try{r.initialize({log:s,validateReceivedMessage:a}),r.addMessageHandler(p=>{_u(p)&&o(!1)});let{remoteProxy:u,destroy:c}=await Du({messenger:r,methods:e,timeout:t,channel:n,log:s});return i.push(c),u}catch(u){throw o(!0),u}})(),destroy:()=>{o(!0)}}},La=Gu,We,nt,Et,St,st,Xe,ce,it,Zr,Ct,dr,hr,At,Fa,Lu=(Fa=class{constructor({remoteWindow:r,allowedOrigins:e}){ee(this,We);ee(this,nt);ee(this,Et);ee(this,St);ee(this,st);ee(this,Xe,new Set);ee(this,ce);ee(this,it,!1);R(this,"initialize",({log:r,validateReceivedMessage:e})=>{ke(this,Et,r),ke(this,St,e),window.addEventListener("message",T(this,hr))});R(this,"sendMessage",(r,e)=>{if(Yr(r)){let t=T(this,Ct).call(this,r);T(this,We).postMessage(r,{targetOrigin:t,transfer:e});return}if(si(r)||T(this,it)){let t=T(this,it)?$u(r):r,n=T(this,Ct).call(this,r);T(this,We).postMessage(t,{targetOrigin:n,transfer:e});return}if(ei(r)){let{port1:t,port2:n}=new MessageChannel;ke(this,ce,t),t.addEventListener("message",T(this,At)),t.start();let s=[n,...e||[]],i=T(this,Ct).call(this,r);T(this,We).postMessage(r,{targetOrigin:i,transfer:s});return}if(T(this,ce)){T(this,ce).postMessage(r,{transfer:e});return}throw new Jr("Port is undefined")});R(this,"addMessageHandler",r=>{T(this,Xe).add(r)});R(this,"removeMessageHandler",r=>{T(this,Xe).delete(r)});R(this,"destroy",()=>{window.removeEventListener("message",T(this,hr)),T(this,dr).call(this),T(this,Xe).clear()});ee(this,Zr,r=>T(this,nt).some(e=>e instanceof RegExp?e.test(r):e===r||e==="*"));ee(this,Ct,r=>{if(Yr(r))return"*";if(!T(this,st))throw new Jr("Concrete remote origin not set");return T(this,st)==="null"&&T(this,nt).includes("*")?"*":T(this,st)});ee(this,dr,()=>{T(this,ce)?.removeEventListener("message",T(this,At)),T(this,ce)?.close(),ke(this,ce,void 0)});ee(this,hr,({source:r,origin:e,ports:t,data:n})=>{var s,i,o;if(r===T(this,We)&&(Tu(n)&&((s=T(this,Et))==null||s.call(this,"Please upgrade the child window to the latest version of Penpal."),ke(this,it,!0),n=Ou(n)),!!((i=T(this,St))!=null&&i.call(this,n)))){if(!T(this,Zr).call(this,e)){(o=T(this,Et))==null||o.call(this,`Received a message from origin \`${e}\` which did not match allowed origins \`[${T(this,nt).join(", ")}]\``);return}if(Yr(n)&&(T(this,dr).call(this),ke(this,st,e)),ei(n)&&!T(this,it)){if(ke(this,ce,t[0]),!T(this,ce))throw new Jr("No port received on ACK2");T(this,ce).addEventListener("message",T(this,At)),T(this,ce).start()}for(let a of T(this,Xe))a(n)}});ee(this,At,({data:r})=>{var e;if((e=T(this,St))!=null&&e.call(this,r))for(let t of T(this,Xe))t(r)});if(!r)throw new pe("INVALID_ARGUMENT","remoteWindow must be defined");ke(this,We,r),ke(this,nt,e?.length?e:[window.origin])}},We=new WeakMap,nt=new WeakMap,Et=new WeakMap,St=new WeakMap,st=new WeakMap,Xe=new WeakMap,ce=new WeakMap,it=new WeakMap,Zr=new WeakMap,Ct=new WeakMap,dr=new WeakMap,hr=new WeakMap,At=new WeakMap,Fa),Ua=Lu;var en=({window:r,methods:e})=>{let t=new Ua({remoteWindow:r,allowedOrigins:["*"]});return La({methods:e,messenger:t})};var Va=(r,e)=>en({window:r.contentWindow,methods:e});var rn=class rn{constructor(e,t){R(this,"penpalConn");R(this,"_methods");this.penpalConn=e,this._methods=t}get publicEndpoints(){let e={get:(t,n)=>async(...s)=>await this._methods.queryPublicEndpoint(n,s[0],s[1])};return new Proxy({},e)}destroy(){this.penpalConn.destroy()}};R(rn,"createFromPenpalConnection",async e=>{let t=await e.promise;return new rn(e,t)});var tn=rn;var za={local:{baseUrl:"http://localhost:9101",apiBaseUrl:"http://localhost:9000"},sandbox:{baseUrl:"https://staging.paymentkit.com/customer",apiBaseUrl:"https://staging.paymentkit.com"},production:{baseUrl:"https://app.paymentkit.com/customer",apiBaseUrl:"https://app.paymentkit.com"}};function Uu(){if(typeof window<"u"){let e=new URLSearchParams(window.location.search).get("api_base_url");if(e)return{baseUrl:window.location.origin,apiBaseUrl:e};let t=window.location.hostname;if(t.includes("loclx.io")){let n=t.replace(/cportal|playground/,"api");return{baseUrl:`https://${t}`,apiBaseUrl:`https://${n}`}}}return za.local}function Ka(r){if(r==="tunnel")return Uu();let t=za[r];if(!t)throw new Error(`Invalid environment: ${r}. Must be one of: local, tunnel, sandbox, production`);return t}var Ha="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Ba=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=Ha[t[r]&63];return e};var Vu={local:"dev",tunnel:"dev",sandbox:"stg",production:"prod"},ii="__paymentKitRequestId__";function Wa(r){let e=Vu[r]||"dev",t=Ba(12);return`pk_${e}_${t}`}function ye(r){if(typeof window<"u"&&window[ii])return window[ii];let e=Wa(r);return typeof window<"u"&&(window[ii]=e),e}function oi(r){return{headers:{"x-request-id":r}}}var ai;function Xa(r){return{lang:r?.lang??ai?.lang,message:r?.message,abortEarly:r?.abortEarly??ai?.abortEarly,abortPipeEarly:r?.abortPipeEarly??ai?.abortPipeEarly}}var zu;function Ku(r){return zu?.get(r)}var Hu;function Bu(r){return Hu?.get(r)}var Wu;function Xu(r,e){return Wu?.get(r)?.get(e)}function Yu(r){let e=typeof r;return e==="string"?`"${r}"`:e==="number"||e==="bigint"||e==="boolean"?`${r}`:e==="object"||e==="function"?(r&&Object.getPrototypeOf(r)?.constructor?.name)??"null":e}function ot(r,e,t,n,s){let i=s&&"input"in s?s.input:t.value,o=s?.expected??r.expects??null,a=s?.received??Yu(i),l={kind:r.kind,type:r.type,input:i,expected:o,received:a,message:`Invalid ${e}: ${o?`Expected ${o} but r`:"R"}eceived ${a}`,requirement:r.requirement,path:s?.path,issues:s?.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},u=r.kind==="schema",c=s?.message??r.message??Xu(r.reference,l.lang)??(u?Bu(l.lang):null)??n.message??Ku(l.lang);c!==void 0&&(l.message=typeof c=="function"?c(l):c),u&&(t.typed=!1),t.issues?t.issues.push(l):t.issues=[l]}function li(r){return{version:1,vendor:"valibot",validate(e){return r["~run"]({value:e},Xa())}}}function Ya(r){if(r.path){let e="";for(let t of r.path)if(typeof t.key=="string"||typeof t.key=="number")e?e+=`.${t.key}`:e+=t.key;else return null;return e}return null}var Ju=/^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu;function ci(r){return{kind:"validation",type:"email",reference:ci,expects:null,async:!1,requirement:Ju,message:r,"~run"(e,t){return e.typed&&!this.requirement.test(e.value)&&ot(this,"email",e,t),e}}}function ui(r,e){return{kind:"validation",type:"max_length",reference:ui,async:!1,expects:`<=${r}`,requirement:r,message:e,"~run"(t,n){return t.typed&&t.value.length>this.requirement&&ot(this,"length",t,n,{received:`${t.value.length}`}),t}}}function pi(r,e){return{kind:"validation",type:"min_length",reference:pi,async:!1,expects:`>=${r}`,requirement:r,message:e,"~run"(t,n){return t.typed&&t.value.length<this.requirement&&ot(this,"length",t,n,{received:`${t.value.length}`}),t}}}function It(r){return{kind:"validation",type:"non_empty",reference:It,async:!1,expects:"!0",message:r,"~run"(e,t){return e.typed&&e.value.length===0&&ot(this,"length",e,t,{received:"0"}),e}}}function Zu(r,e,t){return typeof r.fallback=="function"?r.fallback(e,t):r.fallback}function Qu(r,e,t){return typeof r.default=="function"?r.default(e,t):r.default}function di(r,e){return{kind:"schema",type:"object",reference:di,expects:"Object",async:!1,entries:r,message:e,get"~standard"(){return li(this)},"~run"(t,n){let s=t.value;if(s&&typeof s=="object"){t.typed=!0,t.value={};for(let i in this.entries){let o=this.entries[i];if(i in s||(o.type==="exact_optional"||o.type==="optional"||o.type==="nullish")&&o.default!==void 0){let a=i in s?s[i]:Qu(o),l=o["~run"]({value:a},n);if(l.issues){let u={type:"object",origin:"value",input:s,key:i,value:a};for(let c of l.issues)c.path?c.path.unshift(u):c.path=[u],t.issues?.push(c);if(t.issues||(t.issues=l.issues),n.abortEarly){t.typed=!1;break}}l.typed||(t.typed=!1),t.value[i]=l.value}else if(o.fallback!==void 0)t.value[i]=Zu(o);else if(o.type!=="exact_optional"&&o.type!=="optional"&&o.type!=="nullish"&&(ot(this,"key",t,n,{input:void 0,expected:`"${i}"`,path:[{type:"object",origin:"key",input:s,key:i,value:s[i]}]}),n.abortEarly))break}}else ot(this,"type",t,n);return t}}}function at(r){return{kind:"schema",type:"string",reference:at,expects:"string",async:!1,message:r,get"~standard"(){return li(this)},"~run"(e,t){return typeof e.value=="string"?e.typed=!0:ot(this,"type",e,t),e}}}function Mt(...r){return{...r[0],pipe:r,get"~standard"(){return li(this)},"~run"(e,t){for(let n of r)if(n.kind!=="metadata"){if(e.issues&&(n.kind==="schema"||n.kind==="transformation")){e.typed=!1;break}(!e.issues||!t.abortEarly&&!t.abortPipeEarly)&&(e=n["~run"](e,t))}return e}}}function Ja(r,e,t){let n=r["~run"]({value:e},Xa(t));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}var hi=async(r,e={})=>{let t=di({customer_name:Mt(at("required"),It("required"),pi(4,"invalid"),ui(40,"invalid")),customer_email:Mt(at("required"),It("required"),ci("invalid")),customer_country:Mt(at("required"),It("required")),customer_zip_code:e.optionalZipCode?Mt(at("required")):Mt(at("required"),It("required"))}),n=Ja(t,r);return n.issues?{isSuccess:!1,errors:n.issues.reduce((i,o)=>{let a=Ya(o);return i[a]=o.kind==="schema"?"required":o.message,i},{})}:{isSuccess:!0}};var Za=r=>{let e=document.querySelector(r);if(!e)throw new Error(`Cannot find element with selector: ${r}`);return e},Ee=r=>r,nn=(r,e,t)=>{let n=document.createElement("iframe"),i=new URLSearchParams(t).toString();return n.src=`${e}/embeds/v1/${r}${i?`?${i}`:""}`,Object.assign(n.style,{width:"100%",height:"100%",border:"none"}),n};function me(){return{ipAddress:void 0,browserInfo:{userAgent:navigator.userAgent,language:navigator.language,screenHeight:window.screen.height,screenWidth:window.screen.width,colorDepth:window.screen.colorDepth,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone},processorFraudInfo:void 0}}var tp=(r,e,t)=>{let n=nn("tunnel-x",r,{checkout_token:t,api_base_url:e});Object.assign(n.style,{width:"0",height:"0",position:"absolute",visibility:"hidden"}),document.body.appendChild(n);let s=Va(n,{});return{unmount:()=>{s.destroy(),document.body.removeChild(n)},connection:s}},rp=({environment:r,secureToken:e,paymentMethods:t,cardTokenizationMode:n,vgsVaultId:s,vgsEnvironment:i,__enableAnalyticsTestMode:o})=>{let{baseUrl:a,apiBaseUrl:l}=Ka(r);console.log(`[PaymentKit] v${xi} initialized (env: ${r})`);let u=ye(r);console.log(`[PaymentKit] checkout_request_id: ${u}`),xe.init(l,o),xe.identify(e);let c=new pr(e,u);c.trackPageReady();let{connection:p,unmount:d}=tp(a,l,e),h={baseUrl:a,apiBaseUrl:l,secureToken:e,environment:r,tunnelXConnection:p,timingTracker:c,checkoutRequestId:u,cardTokenizationMode:n,vgsVaultId:s,vgsEnvironment:i,_sessionConfigReady:void 0};if(n===void 0){let b=`${l}/api/checkout-sessions/token/${e}`;console.log(`[PaymentKit] cardTokenizationMode not provided \u2014 auto-detecting from session API: ${b}`),h._sessionConfigReady=fetch(b).then(v=>v.ok?v.json():(console.warn(`[PaymentKit] Session config fetch failed with status ${v.status}`),null)).then(v=>{if(v&&typeof v=="object"&&typeof v.card_tokenization_mode=="string"){h.cardTokenizationMode=v.card_tokenization_mode||"direct",console.log(`[PaymentKit] Session config detected \u2014 cardTokenizationMode: ${h.cardTokenizationMode}`);let _=v.vgs_vault_id,k=v.vgs_environment;_&&/^tnt[a-z0-9]+$/.test(_)&&(k==="sandbox"||k==="live")?(h.vgsVaultId=_,h.vgsEnvironment=k,console.log(`[PaymentKit] VGS config valid \u2014 vaultId: ${_}, environment: ${k}`)):h.cardTokenizationMode==="vgs"&&(console.warn(`[PaymentKit] Invalid VGS config from session API (vaultId: ${_}, env: ${k}), falling back to direct mode`),h.cardTokenizationMode="direct")}else console.log("[PaymentKit] Session response missing card_tokenization_mode \u2014 defaulting to direct mode"),h.cardTokenizationMode="direct"}).catch(v=>{console.error("[PaymentKit] Session config fetch error \u2014 falling back to direct mode:",v),h.cardTokenizationMode="direct"})}else console.log(`[PaymentKit] cardTokenizationMode explicitly set: ${n}`);let g=t.map(b=>b(h)),f=g.reduce((b,{name:v,externalFuncs:_})=>(b[v]=_,b),{});return{submit:({paymentMethod:b,fields:v,options:_,onSuccess:k,onError:M})=>{let I=g.find(({name:S})=>S===b);if(!I){M({root:"payment_method_not_found"});return}I.internalFuncs.submitPayment(v,_).then(({data:S,errors:O})=>{O?M(O):k(S)}).catch(S=>{console.error("PaymentKit:submit:catch",S),S?.response?.data?M(S.response.data):S?.message?M({root:S.message}):M({root:"unknown_error"})})},cleanup:()=>{for(let b of g)b.internalFuncs.cleanup&&b.internalFuncs.cleanup();d()},...f}},Qa=rp;var np=(r,e)=>{let{name:t,endpointPath:n,supportsSetupFutureUsage:s}=e,i=t.charAt(0).toUpperCase()+t.slice(1);return async(a,l)=>{let{apiBaseUrl:u,secureToken:c,environment:p}=r,d=l;if(!d?.processorId)return{errors:{processor_id:"Processor ID is required"}};if(!d?.customerInfo?.first_name||!d?.customerInfo?.last_name)return{errors:{customer_name:"Customer first and last name are required"}};try{let h=ye(p),g={processor_id:d.processorId,customer_info:d.customerInfo,fraud_metadata:me()};s&&d.setupFutureUsage!==void 0&&(g.setup_future_usage=d.setupFutureUsage);let f=await fetch(`${u}/api/checkout/${c}/stripe/${n}/start`,{method:"POST",headers:{"Content-Type":"application/json","x-request-id":h},body:JSON.stringify(g)});if(!f.ok){let _=`Failed to start ${i} checkout (${f.status})`;try{_=(await f.json()).detail||_}catch{_=f.statusText||_}return{errors:{[t]:_}}}let{approval_url:m,popup_token:w,checkout_attempt_id:b}=await f.json(),v=window.open(m,i,"width=600,height=700");return v?(r.popup=v,new Promise(_=>{let k=0,M=5,I=setInterval(async()=>{try{let S=await fetch(`${u}/api/checkout/${c}/popup/status?popup_token=${w}`);if(!S.ok){clearInterval(I),v.close(),_({errors:{[t]:`Failed to check ${i} status`}});return}let O=await S.json();if(O.completed){if(clearInterval(I),v.close(),O.status==="success"){let V=O.result||{id:b,checkoutAttemptId:b,checkoutSessionId:c,state:"checkout_succeeded"};_({data:V})}else _({errors:{[t]:O.error||`${i} checkout ${O.status}`}});return}if(v.closed){k++,k>=M&&(clearInterval(I),_({errors:{[t]:`${i} popup closed by user`}}));return}}catch(S){clearInterval(I),v.close(),_({errors:{[t]:`Polling error: ${S}`}})}},2e3);r.pollInterval=I})):{errors:{[t]:`Failed to open ${i} popup. Please allow popups for this site.`}}}catch(h){return{errors:{[t]:`${i} checkout error: ${h}`}}}}};function Rt(r){return Ee(e=>{let t={...e};return{name:r.name,externalFuncs:{},internalFuncs:{submitPayment:np(t,r),cleanup:()=>{t.pollInterval&&clearInterval(t.pollInterval),t.popup&&!t.popup.closed&&t.popup.close()}}}})}var sp=Rt({name:"affirm",endpointPath:"affirm",supportsSetupFutureUsage:!1}),el=sp;var ip=Rt({name:"afterpay",endpointPath:"afterpay",supportsSetupFutureUsage:!1}),tl=ip;var sn=class{constructor(e){R(this,"config",null);R(this,"mockScenario");this.mockScenario=e??"none"}initialize(e){return this.mockScenario!=="none"?(console.log("[MockApplePay:Airwallex] initialize called (mock mode)"),this.config=e,!0):typeof window>"u"||!window.ApplePaySession?(console.error("[ApplePay:Airwallex] ApplePaySession not available (not Safari or unsupported device)"),!1):(this.config=e,!0)}async canMakePayment(){if(this.mockScenario!=="none")return console.log("[MockApplePay:Airwallex] canMakePayment: true (mock mode)"),!0;if(!window.ApplePaySession)return!1;try{let e=window.ApplePaySession.canMakePayments();return console.log("[ApplePay:Airwallex] canMakePayments:",e),e}catch(e){return console.error("[ApplePay:Airwallex] canMakePayment error:",e),!1}}formatAmount(e,t){return["BIF","CLP","DJF","GNF","ISK","JPY","KMF","KRW","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"].includes(t.toUpperCase())?e.toString():(e/100).toFixed(2)}async showPaymentSheet(e){if(this.mockScenario==="success")return console.log("[MockApplePay:Airwallex] showPaymentSheet: returning mock success token"),{success:!0,token:{paymentData:{version:"EC_v1",data:"MOCK_ENCRYPTED_DATA",signature:"MOCK_SIGNATURE",header:{ephemeralPublicKey:"MOCK_PUBLIC_KEY",publicKeyHash:"MOCK_HASH",transactionId:"mock_txn_123"}},paymentMethod:{displayName:"Visa 4242",network:"Visa",type:"debit"},transactionIdentifier:"MOCK_TXN_ID"},payerEmail:"mock@example.com",payerFirstName:"Mock",payerLastName:"User",complete:o=>console.log(`[MockApplePay:Airwallex] complete: ${o}`)};if(this.mockScenario==="cancelled")return console.log("[MockApplePay:Airwallex] showPaymentSheet: returning mock cancelled"),{success:!1,cancelled:!0};if(!this.config)return{success:!1,error:"Apple Pay not initialized"};if(!window.ApplePaySession)return{success:!1,error:"ApplePaySession not available"};let t=this.config,n=this.formatAmount(t.amount,t.currency),s={countryCode:t.country.toUpperCase(),currencyCode:t.currency.toUpperCase(),supportedNetworks:["visa","masterCard","amex","discover"],merchantCapabilities:["supports3DS"],total:{label:t.merchantName||"Total",amount:n,type:"final"},requiredBillingContactFields:["email","name"]};return new Promise(i=>{try{let o=new window.ApplePaySession(3,s),a=window.ApplePaySession.STATUS_SUCCESS,l=window.ApplePaySession.STATUS_FAILURE;o.onvalidatemerchant=async u=>{console.log("[ApplePay:Airwallex] onvalidatemerchant called",u.validationURL);try{let c=await e(u.validationURL);if(c.error||!c.merchantSession){console.error("[ApplePay:Airwallex] Merchant validation failed:",c.error),o.abort(),i({success:!1,error:c.error||"Merchant validation failed"});return}o.completeMerchantValidation(c.merchantSession),console.log("[ApplePay:Airwallex] Merchant validation completed")}catch(c){console.error("[ApplePay:Airwallex] Merchant validation error:",c),o.abort(),i({success:!1,error:`Merchant validation error: ${c}`})}},o.onpaymentauthorized=u=>{console.log("[ApplePay:Airwallex] onpaymentauthorized called");let c=u.payment,p={paymentData:c.token.paymentData,paymentMethod:{displayName:c.token.paymentMethod.displayName,network:c.token.paymentMethod.network,type:c.token.paymentMethod.type},transactionIdentifier:c.token.transactionIdentifier},d=c.billingContact?.emailAddress??c.shippingContact?.emailAddress??void 0,h=c.billingContact?.givenName??c.shippingContact?.givenName??void 0,g=c.billingContact?.familyName??c.shippingContact?.familyName??void 0;i({success:!0,token:p,payerEmail:d,payerFirstName:h,payerLastName:g,complete:m=>{console.log("[ApplePay:Airwallex] completing session with status:",m);let w=m==="success"?a:l;o.completePayment({status:w})}})},o.oncancel=()=>{console.log("[ApplePay:Airwallex] oncancel - user cancelled"),i({success:!1,cancelled:!0})},console.log("[ApplePay:Airwallex] Starting Apple Pay session"),o.begin()}catch(o){console.error("[ApplePay:Airwallex] Session creation error:",o),i({success:!1,error:`Failed to create Apple Pay session: ${o}`})}})}};function fi(r){let{url:e,size:t,radius:n=6,onMessage:s}=r;return new Promise(i=>{let o=!1,a=document.createElement("div");a.id="pk-iframe-modal-overlay",a.setAttribute("role","dialog"),a.setAttribute("aria-modal","true"),a.setAttribute("aria-label","3D Secure Verification"),a.style.cssText=`
12
12
  position: fixed;
13
13
  top: 0;
14
14
  left: 0;
@@ -60,6 +60,6 @@
60
60
  transition: opacity 0.2s ease;
61
61
  position: relative;
62
62
  z-index: 1;
63
- `,c.onload=()=>{c.style.opacity="1"},c.onerror=()=>{o||(console.error("[IframeModal] Failed to load iframe"),p(),s({success:!1,error:"Failed to load verification page. Please try again."}))},l.appendChild(u),l.appendChild(c),a.appendChild(l),document.body.appendChild(a),requestAnimationFrame(()=>{a.style.background="rgba(0, 0, 0, 0.5)",l.style.opacity="1",l.style.transform="scale(1) translateY(0)"});let p=()=>{o||(o=!0,window.removeEventListener("message",g),window.removeEventListener("keydown",h),requestAnimationFrame(()=>{a.style.background="rgba(0, 0, 0, 0)",l.style.opacity="0",l.style.transform="scale(0.95) translateY(10px)",setTimeout(()=>{a.parentNode&&a.parentNode.removeChild(a)},250)}))},d=()=>{o||(console.log("[IframeModal] User cancelled"),p(),s({success:!1,error:"Verification cancelled"}))};u.onclick=d;let h=f=>{f.key==="Escape"&&d(),f.key==="Tab"&&(f.preventDefault(),document.activeElement===u?c.focus():u.focus())};window.addEventListener("keydown",h),u.focus();let g=f=>{let m=i(f);m.handled&&(p(),s(m.result))};window.addEventListener("message",g)})}var Ju=r=>new Promise(e=>setTimeout(e,r)),Za=()=>"Stripe"in window,Zu=async r=>{for(let t=0;t<10&&!Za();t++)await Ju(500);if(!Za())throw new Error(`Stripe.js not loaded. Add this script tag to your HTML <head>:
64
- <script src="https://js.stripe.com/v3/"><\/script>`);return new window.Stripe(r)},Qu=async r=>{let{clientSecret:e,stripePk:t}=r,n=await Zu(t),{error:i}=await n.confirmCardPayment(e);return i?(console.error("[3DS:Stripe] Authentication failed:",i.message),{success:!1,error:i.message||"3DS authentication failed"}):{success:!0}},ep=async r=>ds({url:r.url,size:{width:605,height:550},onMessage:e=>{if(e.data.type!=="3ds_complete")return{handled:!1};let{isSuccess:t,error:n}=e.data;return t?{handled:!0,result:{success:!0,data:{}}}:(console.error("[3DS:Airwallex] Authentication failed:",n),{handled:!0,result:{success:!1,error:n||"3DS authentication failed"}})}}),Mt=async r=>{switch(r.type){case"stripe_3ds":return Qu(r);case"airwallex_3ds":return ep(r);default:return{success:!1,error:`Unknown next action type: ${r.type}`}}};var sn=class{constructor(e){R(this,"stripe",null);R(this,"mockScenario");R(this,"preparedPaymentRequest",null);this.mockScenario=e??"none"}initialize(e){switch(this.mockScenario){case"none":{if(console.log("[ApplePay] initialize called"),!window.Stripe)return console.log("[ApplePay] Stripe.js not loaded"),!1;this.stripe=window.Stripe(e);let t=this.stripe!==null;return console.log("[ApplePay] initialize result:",t),t}case"success":case"cancelled":return console.log("[MockApplePay] initialize called"),console.log("[MockApplePay] initialize result:",!0),!0}}static isAvailable(){if(typeof window>"u"||!window.ApplePaySession)return console.log("[ApplePay] ApplePaySession not available"),!1;let e=window.ApplePaySession.canMakePayments();return console.log("[ApplePay] canMakePayments:",e),e}async canMakePayment(){if(!this.stripe)return console.log("[ApplePay] Stripe not initialized"),null;let t=await this.stripe.paymentRequest({country:"US",currency:"usd",total:{label:"Check",amount:100}}).canMakePayment();return console.log("[ApplePay] canMakePayment result:",t),t?{applePay:t.applePay??!1,googlePay:t.googlePay??!1}:null}async preparePaymentRequest(e){if(this.mockScenario!=="none")return console.log("[MockApplePay] preparePaymentRequest called"),this.preparedConfig=e,{success:!0,applePay:!0,googlePay:!1};if(console.log("[ApplePay] preparePaymentRequest called",e),!this.stripe)return{success:!1,error:"Stripe not initialized"};let t=this.stripe.paymentRequest({country:e.country,currency:e.currency.toLowerCase(),total:{label:e.total.label,amount:e.total.amount},requestPayerName:!0,requestPayerEmail:!0}),n=await t.canMakePayment();return console.log("[ApplePay] preparePaymentRequest canMakePayment:",n),n?(this.preparedPaymentRequest=t,this.preparedConfig=e,{success:!0,applePay:n.applePay??!1,googlePay:n.googlePay??!1}):{success:!1,error:"Payment methods not available on this device/browser",applePay:!1,googlePay:!1}}isPrepared(){return this.preparedPaymentRequest!==null||this.mockScenario!=="none"}clearPrepared(){this.preparedPaymentRequest=null,this.preparedConfig=null}showPreparedPaymentSheet(){switch(this.mockScenario){case"none":{if(console.log("[ApplePay] showPreparedPaymentSheet called"),!this.preparedPaymentRequest)return console.error("[ApplePay] No prepared PaymentRequest! Call preparePaymentRequest() first."),Promise.resolve({success:!1,error:"PaymentRequest not prepared. Call preparePaymentRequest() before showing the sheet."});let e=this.preparedPaymentRequest;return new Promise(t=>{e.on("paymentmethod",n=>{console.log("[ApplePay] paymentmethod event received",{paymentMethodId:n.paymentMethod.id,payerEmail:n.payerEmail,payerName:n.payerName}),this.preparedPaymentRequest=null,t({success:!0,paymentMethodId:n.paymentMethod.id,paymentMethodEvent:n,billingDetails:{email:n.payerEmail??void 0,name:n.payerName??void 0,address:n.paymentMethod.billing_details?.address??void 0}})}),e.on("cancel",()=>{console.log("[ApplePay] cancel event - user cancelled"),this.preparedPaymentRequest=null,t({success:!1,cancelled:!0})}),console.log("[ApplePay] showing payment sheet"),e.show()})}case"success":return console.log("[MockApplePay] showPreparedPaymentSheet: success"),new Promise(e=>{setTimeout(()=>{e({success:!0,paymentMethodId:"pm_mock_apple_pay_test",paymentMethodEvent:{complete:t=>console.log(`[MockApplePay] complete: ${t}`),paymentMethod:{id:"pm_mock_apple_pay_test",object:"payment_method",type:"card",card:{brand:"visa",last4:"4242",exp_month:12,exp_year:2030},billing_details:{email:"test@example.com",name:"Test User"}},payerEmail:"test@example.com",payerName:"Test User"},billingDetails:{email:"test@example.com",name:"Test User"}})},500)});case"cancelled":return console.log("[MockApplePay] showPreparedPaymentSheet: cancelled"),new Promise(e=>{setTimeout(()=>{e({success:!1,cancelled:!0})},500)})}}async showPaymentSheet(e){console.warn("[ApplePay] showPaymentSheet is deprecated. Use preparePaymentRequest() + showPreparedPaymentSheet() instead.");let t=await this.preparePaymentRequest(e);return t.success?this.showPreparedPaymentSheet():{success:!1,error:t.error??"Failed to prepare payment request"}}completePayment(e,t){console.log("[ApplePay] completePayment:",t),e.complete(t)}async confirmPaymentIntent(e,t){switch(this.mockScenario){case"none":{if(console.log("[ApplePay] confirmPaymentIntent called",{clientSecret:`${e.slice(0,20)}...`,paymentMethodId:t}),!this.stripe)return console.log("[ApplePay] confirmPaymentIntent: Stripe not initialized"),{success:!1,error:"Stripe not initialized"};let{error:n}=await this.stripe.confirmCardPayment(e,{payment_method:t});return n?(console.log("[ApplePay] confirmPaymentIntent error:",n),{success:!1,error:n.message??"Payment failed"}):(console.log("[ApplePay] confirmPaymentIntent success"),{success:!0})}case"success":return console.log("[MockApplePay] confirmPaymentIntent called",{clientSecret:e,paymentMethodId:t}),{success:!0};case"cancelled":throw new Error("confirmPaymentIntent should not be called when scenario is Cancelled")}}};var Je=null,Ee=null;async function Rt(r,e,t){let n=new Headers(e.headers);t&&n.set("x-request-id",t);let i=await fetch(r,{...e,headers:n});if(!i.ok){let s=`Request failed (${i.status})`;try{s=(await i.json()).detail||s}catch{s=i.statusText||s}return{error:s}}return{data:await i.json()}}function tp(r){return r?.processorId?r.processorType==="airwallex"&&!r.country&&!Ee?.country?{country:"Country is required for Airwallex Apple Pay"}:null:{processor_id:"Processor ID is required"}}function nl(r){return r&&r!=="none"?r:void 0}async function il(r,e,t,n,i){return Rt(`${r}/api/checkout/${e}/apple-pay/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({processor_id:t.processorId,customer_info:t.customerInfo,fraud_metadata:xe(),mock_scenario:n})},i)}function sl(r,e){let t=new sn(e);return t.initialize(r)?{adapter:t}:{error:'Stripe.js not loaded. Add <script src="https://js.stripe.com/v3/"><\/script> to your page.'}}async function Qa(r,e,t,n,i,s){let o=await Rt(`${r}/api/checkout/${e}/apple-pay/confirm`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payment_method_id:t,payer_email:s,mock_scenario:n})},i);if(o.error||!o.data)return{errors:{apple_pay:o.error||"Failed to confirm payment"}};let a=o.data;return a.charge_status==="success"?{data:{id:a.transaction_id,checkoutAttemptId:a.checkout_attempt_id,checkoutSessionId:a.checkout_session_id??e,state:"checkout_succeeded",paymentIntentId:a.payment_intent_id,customerId:a.customer_id,paymentMethodId:a.payment_method_id,processorUsed:a.processor_used,subscriptionId:a.subscription_id,invoiceId:a.invoice_id,invoiceNumber:a.invoice_number,cardBrand:a.card_brand,cardLast4:a.card_last4,cardExpMonth:a.card_exp_month,cardExpYear:a.card_exp_year,errorCode:a.error_code,errorMessageForCustomer:a.error_message_for_customer,errorMessageForDebug:a.error_message_for_debug,nextAction:a.next_action}}:{errors:{apple_pay:a.error_message_for_customer||a.error_message_for_debug||"Payment failed"}}}async function rp(r,e,t,n){console.log("[ApplePay] prepareApplePay called"),Je=null;let i=nl(t.mockScenario),s=Pe(n);if(console.log(`[ApplePay] Using checkout_request_id: ${s}`),t.processorType==="airwallex"){console.log("[ApplePay] Airwallex processor - fetching session info for amount");let p=await ol(r,e,s);if(p.error||!p.data)return console.error("[ApplePay] Failed to fetch session info:",p.error),{success:!1,error:p.error||"Failed to fetch Apple Pay session info"};console.log("[ApplePay] Got session info:",p.data);let d=p.data.amount,h=p.data.currency;return Ee={country:t.country||p.data.country,currency:h,amount:d,merchantName:t.merchantName},console.log("[ApplePay] Airwallex prepared state:",Ee),{success:!0,applePay:!0}}let o=await il(r,e,t,i,s);if(o.error||!o.data)return{success:!1,error:o.error||"Failed to start Apple Pay"};let a=o.data;if(!a.stripe_pk)return{success:!1,error:"Stripe publishable key not provided"};let{adapter:l,error:u}=sl(a.stripe_pk,t.mockScenario);if(!l)return{success:!1,error:u};let c=await l.preparePaymentRequest({country:a.country,currency:a.currency.toLowerCase(),total:{label:"Total",amount:a.amount}});return c.success?c.applePay?(Je={processor:"stripe",adapter:l,startData:a,mockScenarioStr:i,checkoutRequestId:s},console.log("[ApplePay] prepareApplePay success (Stripe), ready for click"),{success:!0,applePay:!0}):{success:!1,error:"Apple Pay is not available on this device or Stripe account",applePay:!1}:{success:!1,error:c.error||"Failed to prepare payment request",applePay:c.applePay}}function hr(){Je&&Je.adapter.clearPrepared(),Je=null,Ee=null}async function ol(r,e,t){return Rt(`${r}/api/checkout/${e}/airwallex/apple-pay/session-info`,{method:"GET",headers:{"Content-Type":"application/json"}},t)}async function el(r,e,t,n,i,s,o){return Rt(`${r}/api/checkout/${e}/airwallex/apple-pay/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({processor_id:t.processorId,customer_info:t.customerInfo,fraud_metadata:xe(),validation_url:n,initiative_context:i,mock_scenario:s})},o)}async function np(r,e,t,n,i,s){let o=await Rt(`${r}/api/checkout/${e}/airwallex/apple-pay/confirm`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apple_pay_token:t,payer_email:s,mock_scenario:n})},i);return o.error||!o.data?{charge_status:"fail",error_message_for_debug:o.error||"Failed to confirm payment",checkout_attempt_id:""}:o.data}async function ip(r,e,t){let n=await Rt(`${r}/api/checkout/${e}/airwallex/apple-pay/verify`,{method:"POST",headers:{"Content-Type":"application/json"}},t);return n.error||!n.data?{charge_status:"fail",error_message_for_debug:n.error||"Failed to verify payment",checkout_attempt_id:""}:n.data}function tl(r,e){return r.charge_status==="success"?{data:{id:r.transaction_id,checkoutAttemptId:r.checkout_attempt_id,checkoutSessionId:r.checkout_session_id??e,state:"checkout_succeeded",paymentIntentId:r.payment_intent_id,customerId:r.customer_id,paymentMethodId:r.payment_method_id,processorUsed:r.processor_used,subscriptionId:r.subscription_id,invoiceId:r.invoice_id,invoiceNumber:r.invoice_number,cardBrand:r.card_brand,cardLast4:r.card_last4,cardExpMonth:r.card_exp_month,cardExpYear:r.card_exp_year,errorCode:r.error_code,errorMessageForCustomer:r.error_message_for_customer,errorMessageForDebug:r.error_message_for_debug,nextAction:r.next_action}}:{errors:{apple_pay:r.error_message_for_customer||r.error_message_for_debug||"Payment failed"}}}var rl=5;async function sp(r,e,t,n,i){let s="none";if(t.mockScenario==="success"?s="success":t.mockScenario==="cancelled"&&(s="cancelled"),!t.country)return{errors:{apple_pay:"Country is required for Airwallex Apple Pay"}};if(!t.amount){let m=await ol(r,e,i);m.data&&(t.amount=m.data.amount,t.currency=t.currency||m.data.currency,t.country=t.country||m.data.country)}let o=new nn(s),a={amount:t.amount||0,currency:(t.currency||"USD").toUpperCase(),country:t.country.toUpperCase(),merchantName:t.merchantName||"Total"};if(!o.initialize(a))return{errors:{apple_pay:"Apple Pay not available on this device (requires Safari)"}};if(!await o.canMakePayment())return{errors:{apple_pay:"Apple Pay not available on this device"}};let u=typeof window<"u"?window.location.hostname:"";if(s!=="none"){let m=await el(r,e,t,"https://mock-apple-pay-gateway.example.com/paymentservices/startSession",u,n,i);if(m.error||!m.data)return{errors:{apple_pay:m.error||"Failed to start mock checkout"}}}let c=await o.showPaymentSheet(async m=>{let w=await el(r,e,t,m,u,n,i);return w.error||!w.data?{error:w.error||"Merchant validation failed"}:w.data.merchant_session?{merchantSession:w.data.merchant_session}:{error:"No merchant session returned from server"}});if(!c.success)return"cancelled"in c&&c.cancelled?{errors:{apple_pay:"Apple Pay cancelled by user"}}:{errors:{apple_pay:c.error||"Apple Pay failed"}};let{token:p,complete:d,payerEmail:h}=c,g=await np(r,e,p,n,i,h),f=0;for(;g.charge_status==="pending"&&g.next_action&&f<rl;){f++;let m=g.next_action,w=await Mt({type:m.type,url:m.url}),b=await ip(r,e,i);if(b.charge_status==="pending"&&b.next_action){w.success||console.log("[ApplePay:Airwallex] 3DS failed but retry available, continuing loop..."),g=b;continue}return w.success?(d(b.charge_status==="success"?"success":"fail"),tl(b,e)):(d("fail"),{errors:{apple_pay:b.error_message_for_customer||b.error_message_for_debug||w.error||"3DS authentication failed"}})}return f>=rl?(d("fail"),{errors:{apple_pay:"Too many authentication attempts. Please try again."}}):(d(g.charge_status==="success"?"success":"fail"),tl(g,e))}var op=r=>async(t,n)=>{let{apiBaseUrl:i,secureToken:s,environment:o}=r,a=n,l=tp(a);if(l)return{errors:l};try{let u=nl(a.mockScenario),c=Pe(o);if(console.log(`[ApplePay] Using checkout_request_id: ${c}`),Je?.adapter.isPrepared()){console.log("[ApplePay] Using prepared Stripe state for immediate sheet display");let I=await Je.adapter.showPreparedPaymentSheet();if(!I.success)return hr(),"cancelled"in I&&I.cancelled?{errors:{apple_pay:"Apple Pay cancelled by user"}}:{errors:{apple_pay:"error"in I?I.error:"Unknown error"}};let{paymentMethodId:M,paymentMethodEvent:C,billingDetails:j}=I,V=await Qa(i,s,M,u,Je.checkoutRequestId,j?.email);return V.data?(C.complete("success"),hr(),V):(C.complete("fail"),hr(),V)}if(a.processorType==="airwallex"){console.log("[ApplePay] Running Airwallex flow (processorType=airwallex)"),Ee&&(a.country==null&&(a.country=Ee.country),a.currency==null&&(a.currency=Ee.currency),a.amount==null&&(a.amount=Ee.amount),a.merchantName==null&&(a.merchantName=Ee.merchantName));try{return await sp(i,s,a,u,c)}finally{Ee=null}}let p=await il(i,s,a,u,c);if(p.error||!p.data)return{errors:{apple_pay:p.error||"Failed to start Apple Pay"}};let d=p.data;if(console.warn("[ApplePay] Stripe flow without prepared state - may fail due to user gesture requirements"),!d.stripe_pk)return{errors:{apple_pay:"Stripe publishable key not provided"}};let{adapter:h,error:g}=sl(d.stripe_pk,a.mockScenario);if(!h)return{errors:{apple_pay:g||"Failed to initialize Stripe adapter"}};let f=await h.preparePaymentRequest({country:d.country,currency:d.currency.toLowerCase(),total:{label:"Total",amount:d.amount}});if(!f.success||!f.applePay)return{errors:{apple_pay:f.error||"Apple Pay not available"}};let m=await h.showPreparedPaymentSheet();if(!m.success)return"cancelled"in m&&m.cancelled?{errors:{apple_pay:"Apple Pay cancelled by user"}}:{errors:{apple_pay:"error"in m?m.error:"Unknown error"}};let{paymentMethodId:w,paymentMethodEvent:b,billingDetails:v}=m,_=await Qa(i,s,w,u,c,v?.email);return _.data?(b.complete("success"),_):(b.complete("fail"),_)}catch(u){return hr(),{errors:{apple_pay:`Apple Pay error: ${u}`}}}},ap=Ye(r=>({name:"apple_pay",externalFuncs:{prepareApplePay:e=>rp(r.apiBaseUrl,r.secureToken,e,r.environment)},internalFuncs:{submitPayment:op(r),cleanup:()=>{hr()}}}));var al=ap;var ll=(r,e)=>Qr({window:r.contentWindow,methods:e});var hs="https://js.verygoodvault.com/vgs-collect/3.2.1/vgs-collect.js",fr=null;function cl(){return fr?(console.log("[PaymentKit] VGS Collect CDN load already in progress \u2014 reusing promise"),fr):(fr=new Promise((r,e)=>{if(typeof window<"u"&&window.VGSCollect){console.log("[PaymentKit] VGS Collect JS already available on window"),r();return}console.log(`[PaymentKit] Loading VGS Collect JS from CDN: ${hs}`);let t=document.createElement("script");t.src=hs,t.async=!0,t.onload=()=>{console.log("[PaymentKit] VGS Collect JS loaded successfully from CDN"),r()},t.onerror=()=>{console.error(`[PaymentKit] Failed to load VGS Collect JS from CDN: ${hs}`),fr=null,e(new Error("Failed to load VGS Collect JS"))},document.head.appendChild(t)}),fr)}function ul(r,e){if(!window.VGSCollect)throw new Error("VGS Collect JS not loaded. Call loadVgsCollectScript() first.");return window.VGSCollect.create(r,e,()=>{})}function pl(r,e,t,n,i){let s=document.querySelector(e.pan),o=s?getComputedStyle(s).padding:void 0,l={...t??{"font-size":"1rem",color:"#18181b","font-family":"ui-sans-serif, system-ui, sans-serif"},height:"100%","box-sizing":"border-box",...o&&o!=="0px"?{padding:o}:{}};for(let g of[e.pan,e.exp,e.cvc]){let f=document.querySelector(g);if(!f)continue;let m=f.querySelectorAll("iframe");for(let w of m)w.remove()}let u=r.cardNumberField(e.pan,{placeholder:i?.card_pan??"Card number",validations:["required","validCardNumber"],css:l}),c=r.field(e.exp,{type:"card-expiration-date",name:"exp-date",placeholder:i?.card_exp??"MM / YY",yearLength:2,serializers:[{name:"separate",options:{monthName:"month",yearName:"year"}}],validations:["required","validCardExpirationDate"],css:l}),p=r.cardCVCField(e.cvc,{placeholder:i?.card_cvc??"123",validations:["required","validCardSecurityCode"],css:l}),d=[],h=[];for(let g of[e.pan,e.exp,e.cvc]){let f=document.querySelector(g);if(!f)continue;h.push(f);let m=v=>{let _=f;getComputedStyle(_).position==="static"&&(_.style.position="relative"),v.style.position="absolute",v.style.inset="0",v.style.width="100%",v.style.height="100%",v.style.border="none"},w=new MutationObserver(()=>{let v=f.querySelector("iframe");v&&v.style.position!=="absolute"&&m(v)});w.observe(f,{childList:!0,subtree:!0}),d.push(w);let b=f.querySelector("iframe");b&&b.style.position!=="absolute"&&m(b)}if(n){let g=[[u,"card_pan"],[c,"card_exp"],[p,"card_cvc"]];for(let[f,m]of g){let w=n[m];w&&(f.on("focus",()=>w(!0)),f.on("blur",()=>w(!1)))}}return()=>{for(let g of d)g.disconnect();for(let g of h){let f=g.querySelectorAll("iframe");for(let m of f)m.remove()}}}var lp=r=>{let e=r.trim(),t=e.indexOf(" ");return t===-1?{firstName:e}:{firstName:e.substring(0,t),lastName:e.substring(t+1).trim()||void 0}},cp=r=>{let{firstName:e,lastName:t}=lp(r.customer_name),n=r.customer_country||r.customer_zip_code||r.customer_address_line1||r.customer_address_line2||r.customer_city||r.customer_state,i=r.shipping_address_line1||r.shipping_address_line2||r.shipping_city||r.shipping_state||r.shipping_zip_code||r.shipping_country,s;if(r.customer_tax_ids)try{s=JSON.parse(r.customer_tax_ids)}catch{s=void 0}return{email:r.customer_email||void 0,firstName:e,lastName:t,businessName:r.customer_business_name||void 0,taxIds:s?.length?s:void 0,billingAddress:n?{country:r.customer_country||void 0,zipCode:r.customer_zip_code||void 0,line1:r.customer_address_line1||void 0,line2:r.customer_address_line2||void 0,city:r.customer_city||void 0,state:r.customer_state||void 0}:void 0,shippingAddress:i?{line1:r.shipping_address_line1||void 0,line2:r.shipping_address_line2||void 0,city:r.shipping_city||void 0,state:r.shipping_state||void 0,zipCode:r.shipping_zip_code||void 0,country:r.shipping_country||void 0}:void 0}},up=r=>{let{baseUrl:e,apiBaseUrl:t,cardInputConnections:n,secureToken:i,timingTracker:s}=r;return(o,a)=>{let{style:l,onLoaded:u,onFocusChange:c,placeholder:p}=a;return{mount:h=>{let g,f,m=!1;r.vgsMountSelectors||(r.vgsMountSelectors={}),r.vgsMountSelectors[o]=h;let w=()=>{if(m)return;let b=r.cardTokenizationMode==="vgs";if(console.log(`[PaymentKit] card.doMount(${o}) \u2014 mode: ${r.cardTokenizationMode}, vgsVaultId: ${r.vgsVaultId??"unset"}, vgsEnvironment: ${r.vgsEnvironment??"unset"}`),b&&r.vgsVaultId&&r.vgsEnvironment){if(c&&(r.vgsFocusCallbacks||(r.vgsFocusCallbacks={}),r.vgsFocusCallbacks[o]=c),p&&(r.vgsPlaceholders||(r.vgsPlaceholders={}),r.vgsPlaceholders[o]=p),o==="card_pan"){let j=r.vgsVaultId,V=r.vgsEnvironment;console.log(`[PaymentKit] VGS mode active \u2014 loading VGS Collect CDN for vault ${j} (${V})...`);let Q=15e3,ee;Promise.race([cl(),new Promise((Y,ie)=>{ee=setTimeout(()=>{console.warn(`[PaymentKit] VGS Collect CDN load timed out after ${Q/1e3}s`),ie(new Error("VGS Collect CDN load timed out"))},Q)})]).finally(()=>clearTimeout(ee)).then(()=>{if(m)return;console.log("[PaymentKit] VGS Collect CDN loaded \u2014 initializing form...");let Y=ul(j,V);if(m){Y.unmount();return}r.vgsForm=Y;let ie=l?Object.fromEntries(Object.entries(l).map(([ye,Se])=>[ye.replace(/([A-Z])/g,"-$1").toLowerCase(),Se])):void 0,J=r.vgsMountSelectors?.card_exp,de=r.vgsMountSelectors?.card_cvc;if(!J||!de){console.error(`[PaymentKit] VGS mode requires all three card fields to be mounted. Missing: ${J?"":"card_exp"}${!J&&!de?", ":""}${de?"":"card_cvc"}`),u?.();return}console.log(`[PaymentKit] Creating VGS card fields \u2014 pan: ${h}, exp: ${J}, cvc: ${de}`),r.vgsFieldsCleanup=pl(Y,{pan:h,exp:J,cvc:de},ie,r.vgsFocusCallbacks,r.vgsPlaceholders),console.log("[PaymentKit] VGS card fields created successfully"),s.trackInputReady(),u?.()}).catch(Y=>{console.error("[PaymentKit] Failed to load VGS Collect script. Card input will not be available:",Y),u?.()})}o!=="card_pan"&&u?.(),g=()=>{if(o==="card_pan"&&r.vgsForm){try{r.vgsFieldsCleanup?.()}catch{}r.vgsFieldsCleanup=void 0;try{r.vgsForm.unmount()}catch{}r.vgsForm=void 0}};return}b&&console.warn(`[PaymentKit] VGS mode requested but config incomplete (vgsVaultId: ${r.vgsVaultId??"unset"}, vgsEnvironment: ${r.vgsEnvironment??"unset"}) \u2014 using direct mode`);let v=Ya(h),_=getComputedStyle(v),k=_.padding!=="0px"?_.padding:void 0,I={...l??{},height:"100%",boxSizing:"border-box",...k?{padding:k}:{}},M={checkout_token:i,api_base_url:t,style:JSON.stringify(I)},C=rn(o.replace("_","-"),e,M);_.position==="static"&&(v.style.position="relative"),C.style.position="absolute",C.style.inset="0",f=()=>{n[o]?.destroy();try{v.removeChild(C)}catch{}r.cardInputConnections[o]=void 0},v.appendChild(C),C.onload=()=>{o==="card_pan"&&s.trackInputReady();let j=ll(C,{onLoaded:u||(()=>{}),onFocusChange:c||(()=>{})});r.cardInputConnections[o]=j}};return r._sessionConfigReady?r._sessionConfigReady.then(w):w(),{unmount:()=>{m=!0,g?.(),f?.()}}}}}},pp=r=>async(t,n)=>{r._sessionConfigReady&&await r._sessionConfigReady;let i=r.cardTokenizationMode==="vgs",{timingTracker:s,checkoutRequestId:o}=r;s.trackSubmit();let a=is(o),l=await en.createFromPenpalConnection(r.tunnelXConnection),c=n?.skipCustomerValidation===!0?{isSuccess:!0}:await ps(t);if(i){if(!c.isSuccess)return s.trackFail(null,"validation_error","Form validation failed"),{errors:c.errors}}else{let f=await yp(r);if(!(f.isSuccess&&c.isSuccess))return s.trackFail(null,"validation_error","Form validation failed"),{errors:{...f.errors,...c.errors}}}if(!r.cardSetupIntentId){let f=await l.publicEndpoints.createCardSetupIntent({checkoutToken:r.secureToken});r.cardSetupIntentId=f.cardSetupIntentId}if(i){console.log("[PaymentKit] Submitting card via VGS CMP...");let f=await fp(r,l);if(!f.isSuccess){let m=Object.entries(f.errors).map(([w,b])=>`${w}: ${b}`).join(", ");return s.trackFail(null,"card_submit_error",m||"VGS card submission failed"),{errors:f.errors}}}else{let f=await gp(r);if(!f.isSuccess)return s.trackFail(null,"card_submit_error","Card submission failed"),{errors:f.errors}}let p=await l.publicEndpoints.getCardSetupIntent({cardSetupIntentId:r.cardSetupIntentId,checkoutToken:r.secureToken});if(!p.isCardAllSet){let f={};return p.isCardPanSet||(f.card_pan="required"),p.isCardExpSet||(f.card_exp="required"),p.isCardCvcSet||(f.card_cvc="required"),s.trackFail(null,"card_setup_incomplete","Card details incomplete"),{errors:f}}console.log("Card setup intent is set \u2705",p),console.log("Fields",t);let d=await l.publicEndpoints.cardCheckout({checkoutToken:r.secureToken,publicCardCheckoutRequest:{cardSetupIntentId:r.cardSetupIntentId,customerInfo:cp(t),fraudMetadata:xe()}},a);console.log("Card checkout result:",d);let h=5,g=0;for(;d.nextAction&&g<h;){g++,console.log(`Handling user action ${g}/${h}...`);let f=await Mt(d.nextAction);console.log("User action completed, verifying checkout...");let m=await l.publicEndpoints.cardCheckoutVerify({checkoutToken:r.secureToken},a);if(m.nextAction){f.success?console.log("Another user action required, continuing loop..."):console.log("3DS failed but cascade triggered new action, continuing loop..."),d=m;continue}return f.success?(console.log("Card checkout verified \u2705",m),s.trackSuccess(m.checkoutAttemptId||"unknown"),{data:m}):(console.log("3DS authentication failed, checkout concluded:",m),s.trackFail(m.checkoutAttemptId||null,m.errorCode||"3ds_failed",m.errorMessageForCustomer||f.error),{errors:{root:m.errorMessageForCustomer||f.error,checkout_response:m}})}return g>=h?(console.error("Max user actions exceeded"),s.trackFail(null,"max_actions_exceeded","Too many authentication attempts"),{errors:{root:"Too many authentication attempts. Please try again."}}):d.state==="payment_failed"||d.state==="checkout_failed"?(console.log("Card checkout failed:",d),s.trackFail(d.checkoutAttemptId||null,d.errorCode||"payment_failed",d.errorMessageForCustomer||"Payment failed"),{errors:{root:d.errorMessageForCustomer||"Payment failed",checkout_response:d}}):(console.log("Card checkout completed \u2705",d),s.trackSuccess(d.checkoutAttemptId||"unknown"),{data:d})},dp=async(r,e)=>{let t=await fetch(`${r}/api/card-setup-intents/${e}/collect-token`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to get collect token: ${t.status}`);return(await t.json()).access_token},hp={pan:"card_pan",cvc:"card_cvc","exp-date":"card_exp","card-number":"card_pan","card-security-code":"card_cvc","card-expiration-date":"card_exp"},on=r=>{if(r instanceof Error)return r.message;try{return JSON.stringify(r)}catch{return String(r)}},fp=async(r,e)=>{let{vgsForm:t,cardSetupIntentId:n,secureToken:i,apiBaseUrl:s,checkoutRequestId:o}=r,a=`[PaymentKit] [${o}]`,l={};if(!t)return l.card_pan="required",{errors:l,isSuccess:!1};if(!n)return l.root="Card setup intent not created",{errors:l,isSuccess:!1};let u;try{u=await dp(s,i)}catch(v){return console.error(`${a} VGS auth token fetch failed:`,on(v)),l.root="Card authentication failed \u2014 please try again",{errors:l,isSuccess:!1}}let c,p=3e4;try{let v;c=await Promise.race([new Promise((_,k)=>{t.createCard({auth:u,data:{cardholder:{}}},(I,M)=>_(M),I=>k(I))}),new Promise((_,k)=>{v=setTimeout(()=>k(new Error("VGS_TIMEOUT")),p)})]).finally(()=>clearTimeout(v))}catch(v){let _=on(v);if(console.error(`${a} VGS createCard failed:`,_),v instanceof Error&&v.message==="VGS_TIMEOUT")return l.root="Card processing timed out \u2014 please try again",{errors:l,isSuccess:!1};if(v&&typeof v=="object"&&!(v instanceof Error)){let k=v;for(let[I,M]of Object.entries(hp))if(I in k){let j=k[I]?.errorMessages;l[M]=Array.isArray(j)?j[0]:"invalid"}if(Object.keys(l).length>0)return{errors:l,isSuccess:!1}}return l.root="Card validation failed \u2014 please check your card details and try again",{errors:l,isSuccess:!1}}if(!c?.data?.attributes)return console.error(`${a} VGS createCard returned invalid response:`,on(c)),l.root="Card processing returned an invalid response \u2014 please try again",{errors:l,isSuccess:!1};let{pan_alias:d,cvc_alias:h,exp_month:g,exp_year:f}=c.data.attributes,m=f<100?2e3+f:f,w=`${String(g).padStart(2,"0")}/${m}`,b=c.data.id;try{let v=e.publicEndpoints.updateCardSetupIntent({checkoutToken:i,cardSetupIntentId:n,updateCardSetupIntentReq:{cardPan:d,cardExp:w,cardCvc:h,cmpCardId:b,fraudMetadata:xe()}}),_=new Promise((k,I)=>{if(!t.submit){I(new Error("VGS form.submit not available"));return}t.submit(`/api/card-setup-intents/${i}/${n}`,{method:"post",headers:{"Content-Type":"application/json"},data:M=>({card_cvc:M.cvc})},M=>k(),M=>I(M))});await Promise.all([v,_])}catch(v){return console.error(`${a} updateCardSetupIntent failed:`,on(v)),l.root="Failed to save card details \u2014 please try again",{errors:l,isSuccess:!1}}return{errors:{},isSuccess:!0}},gp=async r=>{let e={},{cardSetupIntentId:t,cardInputConnections:n}=r,i=Object.entries(n).map(async([s,o])=>{let a=s,u=await(await o.promise).onSubmit(t||"");"error"in u&&(e[a]=u.error)});return await Promise.allSettled(i),{errors:e,isSuccess:Object.keys(e).length===0}},yp=async r=>{let e={},{cardInputConnections:t}=r,n=Object.entries(t).map(async([i,s])=>{let o=i;if(!s){e[o]="penpal_not_connected";return}let l=await(await s.promise).onValidate();l&&(e[o]=l)});return await Promise.allSettled(n),{errors:e,isSuccess:Object.keys(e).length===0}},mp=Ye(r=>{let e=Object.create(r);return e.cardInputConnections={},{name:"card",externalFuncs:{createElement:up(e)},internalFuncs:{submitPayment:pp(e),cleanup:()=>{e.vgsForm&&(e.vgsFieldsCleanup?.(),e.vgsFieldsCleanup=void 0,e.vgsForm.unmount(),e.vgsForm=void 0);for(let t of Object.values(e.cardInputConnections))t?.destroy();e.cardInputConnections={}}}}}),dl=mp;var an=class{constructor(e){R(this,"client",null);R(this,"config",null);R(this,"mockScenario");this.mockScenario=e??"none"}initialize(e){return this.mockScenario!=="none"?(console.log("[MockGooglePay:Airwallex] initialize called (mock mode)"),this.config=e,!0):window.google?.payments?.api?.PaymentsClient?(this.config=e,this.client=new window.google.payments.api.PaymentsClient({environment:e.isProduction?"PRODUCTION":"TEST"}),this.client!==null):(console.error("[GooglePay:Airwallex] Google Pay API not loaded"),!1)}getAllowedPaymentMethods(e){if(!this.config)throw new Error("Config not set. Call initialize() first.");let t={type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["VISA","MASTERCARD","AMEX","DISCOVER","JCB"]}};return e&&(t.tokenizationSpecification={type:"PAYMENT_GATEWAY",parameters:{gateway:"airwallex",gatewayMerchantId:this.config.gatewayMerchantId}}),[t]}async canMakePayment(){if(this.mockScenario!=="none")return console.log("[MockGooglePay:Airwallex] canMakePayment: true (mock mode)"),!0;if(!this.client)return!1;try{let e={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:this.getAllowedPaymentMethods(!1)};return(await this.client.isReadyToPay(e)).result}catch(e){return console.error("[GooglePay:Airwallex] canMakePayment error:",e),!1}}async showPaymentSheet(){if(this.mockScenario==="success")return console.log("[MockGooglePay:Airwallex] showPaymentSheet: returning mock success token"),{success:!0,token:{protocolVersion:"ECv2",signature:"MOCK_SIGNATURE",intermediateSigningKey:{signedKey:"MOCK_SIGNED_KEY",signatures:["MOCK_SIGNATURE"]},signedMessage:"MOCK_SIGNED_MESSAGE"},payerEmail:"mock@example.com"};if(this.mockScenario==="cancelled")return console.log("[MockGooglePay:Airwallex] showPaymentSheet: returning mock cancelled"),{success:!1,cancelled:!0};if(!this.client||!this.config)return{success:!1,error:"Google Pay not initialized"};try{let e=this.config.amountDisplay,t={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:this.getAllowedPaymentMethods(!0),merchantInfo:{merchantName:this.config.merchantId,...this.config.isProduction&&this.config.googleMerchantId?{merchantId:this.config.googleMerchantId}:{}},transactionInfo:{totalPriceStatus:"FINAL",totalPrice:e,currencyCode:this.config.currency.toUpperCase(),countryCode:this.config.country.toUpperCase()},emailRequired:!0},n=await this.client.loadPaymentData(t),i=n.paymentMethodData.tokenizationData.token;return{success:!0,token:JSON.parse(i),payerEmail:n.email}}catch(e){return e instanceof Error&&e.message?.includes("CANCELED")?{success:!1,cancelled:!0}:e.statusCode==="CANCELED"?{success:!1,cancelled:!0}:(console.error("[GooglePay:Airwallex] Payment sheet error:",e),{success:!1,error:e instanceof Error?e.message:"Unknown error"})}}};var ln=class{constructor(e){R(this,"stripe",null);R(this,"paymentRequest",null);R(this,"mockScenario");this.mockScenario=e??"none"}initialize(e){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] initialize called"),!window.Stripe)return console.log("[GooglePay] Stripe.js not loaded"),!1;this.stripe=window.Stripe(e);let t=this.stripe!==null;return console.log("[GooglePay] initialize result:",t),t}case"success":case"cancelled":return console.log("[MockGooglePay] initialize called"),console.log("[MockGooglePay] initialize result:",!0),!0}}createPaymentRequest(e){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] createPaymentRequest called",e),!this.stripe)throw new Error("Stripe not initialized");this.paymentRequest=this.stripe.paymentRequest(e),console.log("[GooglePay] paymentRequest created");return}case"success":case"cancelled":{console.log("[MockGooglePay] createPaymentRequest called",e);return}}}async canMakePayment(){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] canMakePayment called"),!this.paymentRequest)return console.log("[GooglePay] canMakePayment: no paymentRequest"),!1;let e=await this.paymentRequest.canMakePayment(),t=e?.googlePay??!1;return console.log("[GooglePay] canMakePayment result:",{result:e,isAvailable:t}),t}case"success":case"cancelled":return console.log("[MockGooglePay] canMakePayment called"),console.log("[MockGooglePay] canMakePayment result:",{result:{googlePay:!0},isAvailable:!0}),!0}}async showPaymentSheet(){switch(this.mockScenario){case"none":return console.log("[GooglePay] showPaymentSheet called"),this.paymentRequest?new Promise(e=>{this.paymentRequest.on("paymentmethod",t=>{console.log("[GooglePay] showPaymentSheet: paymentmethod event",{paymentMethodId:t.paymentMethod.id,payerEmail:t.payerEmail}),e({success:!0,paymentMethodId:t.paymentMethod.id,payerEmail:t.payerEmail??void 0,complete:n=>{console.log("[GooglePay] complete called:",n),t.complete(n)}})}),this.paymentRequest.on("cancel",()=>{console.log("[GooglePay] showPaymentSheet: cancelled by user"),e({success:!1,cancelled:!0})}),console.log("[GooglePay] showing payment sheet..."),this.paymentRequest.show()}):(console.log("[GooglePay] showPaymentSheet: no paymentRequest"),{success:!1,error:"Payment request not created"});case"success":return console.log("[MockGooglePay] showPaymentSheet: success"),await new Promise(e=>setTimeout(e,500)),{success:!0,paymentMethodId:"pm_mock_123456789",payerEmail:"mock@example.com",complete:e=>console.log(`[MockGooglePay] complete: ${e}`)};case"cancelled":return console.log("[MockGooglePay] showPaymentSheet: cancelled"),await new Promise(e=>setTimeout(e,500)),{success:!1,cancelled:!0}}}async confirmCardSetup(e,t){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] confirmCardSetup called",{clientSecret:`${e.slice(0,20)}...`,paymentMethodId:t}),!this.stripe)return console.log("[GooglePay] confirmCardSetup: Stripe not initialized"),{success:!1,error:"Stripe not initialized"};let{error:n}=await this.stripe.confirmCardSetup(e,{payment_method:t});return n?(console.log("[GooglePay] confirmCardSetup error:",n),{success:!1,error:n.message??"Card setup failed"}):(console.log("[GooglePay] confirmCardSetup success"),{success:!0})}case"success":return console.log("[MockGooglePay] confirmCardSetup called",{clientSecret:e,paymentMethodId:t}),{success:!0};case"cancelled":throw new Error("confirmCardSetup should not be called when scenario is Cancelled")}}};async function gs(r,e,t){let n=new Headers(e.headers);t&&n.set("x-request-id",t);let i=await fetch(r,{...e,headers:n});if(!i.ok){let s=`Request failed (${i.status})`;try{s=(await i.json()).detail||s}catch{s=i.statusText||s}return{error:s}}return{data:await i.json()}}function vp(r){return r?.processorId?null:{processor_id:"Processor ID is required"}}function _p(r){return r&&r!=="none"?r:void 0}async function bp(r,e,t,n,i){return gs(`${r}/api/checkout/${e}/google-pay/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({processor_id:t.processorId,customer_info:t.customerInfo,fraud_metadata:xe(),mock_scenario:n})},i)}function wp(r,e,t){let n=new ln(t);if(!n.initialize(r))return{error:'Stripe.js not loaded. Add <script src="https://js.stripe.com/v3/"><\/script> to your page.'};let i={country:e.country,currency:e.currency.toLowerCase(),total:{label:"Total",amount:e.amount},requestPayerName:!0,requestPayerEmail:!0};return n.createPaymentRequest(i),{adapter:n}}async function kp(r,e){if(!r.stripe_pk||!r.client_secret)return{success:!1,error:"Stripe credentials not provided"};let{adapter:t,error:n}=wp(r.stripe_pk,r,e);if(!t)return{success:!1,error:n};if(!await t.canMakePayment())return{success:!1,error:"Google Pay not available on this device"};let s=await t.showPaymentSheet();if(!s.success)return"cancelled"in s&&s.cancelled?{success:!1,error:"Google Pay cancelled by user"}:{success:!1,error:"error"in s?s.error:"Unknown error"};let o=await t.confirmCardSetup(r.client_secret,s.paymentMethodId);return o.success?(s.complete("success"),{success:!0,payerEmail:s.payerEmail}):(s.complete("fail"),{success:!1,error:"error"in o?o.error:"Card setup failed"})}function Pp(r,e){if(!r.merchant_name||!r.airwallex_account_id)return{error:"Airwallex Google Pay credentials not provided"};let t="none";e==="success"?t="success":e==="cancelled"&&(t="cancelled");let n=new an(t),i={merchantId:r.merchant_name,gatewayMerchantId:r.airwallex_account_id,amountDisplay:r.amount_display,currency:r.currency,country:r.country,isProduction:r.is_sandbox===!1,googleMerchantId:r.google_merchant_id};return n.initialize(i)?{adapter:n}:{error:'Google Pay API not loaded. Add <script src="https://pay.google.com/gp/p/js/pay.js"><\/script> to your page.'}}async function xp(r,e){let{adapter:t,error:n}=Pp(r,e);if(!t)return{success:!1,error:n};if(!await t.canMakePayment())return{success:!1,error:"Google Pay not available on this device"};let s=await t.showPaymentSheet();return s.success?{success:!0,token:s.token,payerEmail:s.payerEmail}:"cancelled"in s&&s.cancelled?{success:!1,error:"Google Pay cancelled by user"}:{success:!1,error:"error"in s?s.error:"Unknown error"}}async function fl(r,e,t,n,i,s){let o={mock_scenario:n};t&&(o.google_pay_token=t),s&&(o.payer_email=s);let a=await gs(`${r}/api/checkout/${e}/google-pay/confirm`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},i);return a.error||!a.data?{charge_status:"fail",error_message:a.error||"Failed to confirm payment",checkout_attempt_id:""}:a.data}async function Ep(r,e,t){let n=await gs(`${r}/api/checkout/${e}/google-pay/verify`,{method:"POST",headers:{"Content-Type":"application/json"}},t);return n.error||!n.data?{charge_status:"fail",error_message:n.error||"Failed to verify payment",checkout_attempt_id:""}:n.data}function fs(r,e){return r.charge_status==="success"?{data:{id:r.transaction_id,checkoutAttemptId:r.checkout_attempt_id,checkoutSessionId:r.checkout_session_id??e,state:"checkout_succeeded",paymentIntentId:r.payment_intent_id,customerId:r.customer_id,paymentMethodId:r.payment_method_id,processorUsed:r.processor_used,subscriptionId:r.subscription_id,invoiceId:r.invoice_id,invoiceNumber:r.invoice_number,cardBrand:r.card_brand,cardLast4:r.card_last4,cardExpMonth:r.card_exp_month,cardExpYear:r.card_exp_year,errorCode:r.error_code,errorMessageForCustomer:r.error_message_for_customer,errorMessageForDebug:r.error_message_for_debug,nextAction:r.next_action}}:{errors:{google_pay:r.error_message_for_customer||r.error_message_for_debug||r.error_message||"Payment failed"}}}async function Sp(r,e,t,n,i){let s=await fl(r,e,void 0,t,n,i);return fs(s,e)}var hl=5;async function Cp(r,e,t,n,i,s){let o=0,a=await fl(r,e,t,n,i,s);for(;a.charge_status==="pending"&&a.next_action&&o<hl;){o++;let l=await Mt(a.next_action),u=await Ep(r,e,i);if(u.charge_status==="pending"&&u.next_action){l.success||console.log("[GooglePay:Airwallex] 3DS failed but retry available, continuing loop..."),a=u;continue}return l.success?fs(u,e):{errors:{google_pay:u.error_message||l.error||"3DS authentication failed"}}}return o>=hl?{errors:{google_pay:"Too many authentication attempts. Please try again."}}:fs(a,e)}var Ap=r=>async(t,n)=>{let{apiBaseUrl:i,secureToken:s,environment:o}=r,a=n,l=vp(a);if(l)return{errors:l};try{let u=_p(a.mockScenario),c=Pe(o);console.log(`[GooglePay] Using checkout_request_id: ${c}`);let p=await bp(i,s,a,u,c);if(p.error||!p.data)return{errors:{google_pay:p.error||"Failed to start Google Pay"}};let d=p.data;if(d.processor==="stripe"){let h=await kp(d,a.mockScenario);return h.success?await Sp(i,s,u,c,h.payerEmail):{errors:{google_pay:h.error}}}if(d.processor==="airwallex"){let h=await xp(d,a.mockScenario);return h.success?h.token?await Cp(i,s,h.token,u,c,h.payerEmail):{errors:{google_pay:"Google Pay token not received"}}:{errors:{google_pay:h.error}}}return{errors:{google_pay:`Unsupported processor: ${d.processor}`}}}catch(u){return{errors:{google_pay:`Google Pay error: ${u}`}}}},Ip=Ye(r=>({name:"google_pay",externalFuncs:{},internalFuncs:{submitPayment:Ap(r),cleanup:()=>{}}}));var gl=Ip;var Mp=r=>async(t,n)=>{let{apiBaseUrl:i,secureToken:s,environment:o}=r,a=n;if(!a?.processorId)return{errors:{processor_id:"Processor ID is required"}};if(!a?.customerInfo?.first_name||!a?.customerInfo?.last_name)return{errors:{customer_name:"Customer first and last name are required"}};try{let l=Pe(o);console.log(`[PayPal] Using checkout_request_id: ${l}`);let u=await fetch(`${i}/api/checkout/${s}/paypal/start`,{method:"POST",headers:{"Content-Type":"application/json","x-request-id":l},body:JSON.stringify({processor_id:a.processorId,customer_info:a.customerInfo,fraud_metadata:xe()})});if(!u.ok){let g=`Failed to start PayPal checkout (${u.status})`;try{g=(await u.json()).detail||g}catch{g=u.statusText||g}return{errors:{paypal:g}}}let{approval_url:c,popup_token:p,checkout_attempt_id:d}=await u.json(),h=window.open(c,"PayPal","width=600,height=700");return h?(r.popup=h,new Promise(g=>{let f=setInterval(async()=>{try{let m=await fetch(`${i}/api/checkout/${s}/popup/status?popup_token=${p}`);if(!m.ok){clearInterval(f),h.close(),g({errors:{paypal:"Failed to check PayPal status"}});return}let w=await m.json();if(w.completed){if(clearInterval(f),h.close(),w.status==="success"){let b=w.result||{id:d,checkoutAttemptId:d,checkoutSessionId:s,state:"checkout_succeeded"};g({data:b})}else g({errors:{paypal:w.error||`PayPal checkout ${w.status}`}});return}if(h.closed){clearInterval(f),g({errors:{paypal:"PayPal popup closed by user"}});return}}catch(m){clearInterval(f),h.close(),g({errors:{paypal:`Polling error: ${m}`}})}},2e3);r.pollInterval=f})):{errors:{paypal:"Failed to open PayPal popup. Please allow popups for this site."}}}catch(l){return{errors:{paypal:`PayPal checkout error: ${l}`}}}},Rp=Ye(r=>{let e={...r};return{name:"paypal",externalFuncs:{},internalFuncs:{submitPayment:Mp(e),cleanup:()=>{e.pollInterval&&clearInterval(e.pollInterval),e.popup&&!e.popup.closed&&e.popup.close()}}}}),yl=Rp;var Tp=Ja,Fp={applePay:al,card:dl,googlePay:gl,paypal:yl};return Cl(Op);})();
63
+ `,c.onload=()=>{c.style.opacity="1"},c.onerror=()=>{o||(console.error("[IframeModal] Failed to load iframe"),p(),i({success:!1,error:"Failed to load verification page. Please try again."}))},l.appendChild(u),l.appendChild(c),a.appendChild(l),document.body.appendChild(a),requestAnimationFrame(()=>{a.style.background="rgba(0, 0, 0, 0.5)",l.style.opacity="1",l.style.transform="scale(1) translateY(0)"});let p=()=>{o||(o=!0,window.removeEventListener("message",g),window.removeEventListener("keydown",h),requestAnimationFrame(()=>{a.style.background="rgba(0, 0, 0, 0)",l.style.opacity="0",l.style.transform="scale(0.95) translateY(10px)",setTimeout(()=>{a.parentNode&&a.parentNode.removeChild(a)},250)}))},d=()=>{o||(console.log("[IframeModal] User cancelled"),p(),i({success:!1,error:"Verification cancelled"}))};u.onclick=d;let h=f=>{f.key==="Escape"&&d(),f.key==="Tab"&&(f.preventDefault(),document.activeElement===u?c.focus():u.focus())};window.addEventListener("keydown",h),u.focus();let g=f=>{let m=s(f);m.handled&&(p(),i(m.result))};window.addEventListener("message",g)})}var op=r=>new Promise(e=>setTimeout(e,r)),rl=()=>"Stripe"in window,ap=async r=>{for(let t=0;t<10&&!rl();t++)await op(500);if(!rl())throw new Error(`Stripe.js not loaded. Add this script tag to your HTML <head>:
64
+ <script src="https://js.stripe.com/v3/"><\/script>`);return new window.Stripe(r)},lp=async r=>{let{clientSecret:e,stripePk:t}=r,n=await ap(t),{error:s}=await n.confirmCardPayment(e);return s?(console.error("[3DS:Stripe] Authentication failed:",s.message),{success:!1,error:s.message||"3DS authentication failed"}):{success:!0}},cp=async r=>fi({url:r.url,size:{width:605,height:550},onMessage:e=>{if(e.data.type!=="3ds_complete")return{handled:!1};let{isSuccess:t,error:n}=e.data;return t?{handled:!0,result:{success:!0,data:{}}}:(console.error("[3DS:Airwallex] Authentication failed:",n),{handled:!0,result:{success:!1,error:n||"3DS authentication failed"}})}}),Tt=async r=>{switch(r.type){case"stripe_3ds":return lp(r);case"airwallex_3ds":return cp(r);default:return{success:!1,error:`Unknown next action type: ${r.type}`}}};var on=class{constructor(e){R(this,"stripe",null);R(this,"mockScenario");R(this,"preparedPaymentRequest",null);this.mockScenario=e??"none"}initialize(e){switch(this.mockScenario){case"none":{if(console.log("[ApplePay] initialize called"),!window.Stripe)return console.log("[ApplePay] Stripe.js not loaded"),!1;this.stripe=window.Stripe(e);let t=this.stripe!==null;return console.log("[ApplePay] initialize result:",t),t}case"success":case"cancelled":return console.log("[MockApplePay] initialize called"),console.log("[MockApplePay] initialize result:",!0),!0}}static isAvailable(){if(typeof window>"u"||!window.ApplePaySession)return console.log("[ApplePay] ApplePaySession not available"),!1;let e=window.ApplePaySession.canMakePayments();return console.log("[ApplePay] canMakePayments:",e),e}async canMakePayment(){if(!this.stripe)return console.log("[ApplePay] Stripe not initialized"),null;let t=await this.stripe.paymentRequest({country:"US",currency:"usd",total:{label:"Check",amount:100}}).canMakePayment();return console.log("[ApplePay] canMakePayment result:",t),t?{applePay:t.applePay??!1,googlePay:t.googlePay??!1}:null}async preparePaymentRequest(e){if(this.mockScenario!=="none")return console.log("[MockApplePay] preparePaymentRequest called"),this.preparedConfig=e,{success:!0,applePay:!0,googlePay:!1};if(console.log("[ApplePay] preparePaymentRequest called",e),!this.stripe)return{success:!1,error:"Stripe not initialized"};let t=this.stripe.paymentRequest({country:e.country,currency:e.currency.toLowerCase(),total:{label:e.total.label,amount:e.total.amount},requestPayerName:!0,requestPayerEmail:!0}),n=await t.canMakePayment();return console.log("[ApplePay] preparePaymentRequest canMakePayment:",n),n?(this.preparedPaymentRequest=t,this.preparedConfig=e,{success:!0,applePay:n.applePay??!1,googlePay:n.googlePay??!1}):{success:!1,error:"Payment methods not available on this device/browser",applePay:!1,googlePay:!1}}isPrepared(){return this.preparedPaymentRequest!==null||this.mockScenario!=="none"}clearPrepared(){this.preparedPaymentRequest=null,this.preparedConfig=null}showPreparedPaymentSheet(){switch(this.mockScenario){case"none":{if(console.log("[ApplePay] showPreparedPaymentSheet called"),!this.preparedPaymentRequest)return console.error("[ApplePay] No prepared PaymentRequest! Call preparePaymentRequest() first."),Promise.resolve({success:!1,error:"PaymentRequest not prepared. Call preparePaymentRequest() before showing the sheet."});let e=this.preparedPaymentRequest;return new Promise(t=>{e.on("paymentmethod",n=>{console.log("[ApplePay] paymentmethod event received",{paymentMethodId:n.paymentMethod.id,payerEmail:n.payerEmail,payerName:n.payerName}),this.preparedPaymentRequest=null,t({success:!0,paymentMethodId:n.paymentMethod.id,paymentMethodEvent:n,billingDetails:{email:n.payerEmail??void 0,name:n.payerName??void 0,address:n.paymentMethod.billing_details?.address??void 0}})}),e.on("cancel",()=>{console.log("[ApplePay] cancel event - user cancelled"),this.preparedPaymentRequest=null,t({success:!1,cancelled:!0})}),console.log("[ApplePay] showing payment sheet"),e.show()})}case"success":return console.log("[MockApplePay] showPreparedPaymentSheet: success"),new Promise(e=>{setTimeout(()=>{e({success:!0,paymentMethodId:"pm_mock_apple_pay_test",paymentMethodEvent:{complete:t=>console.log(`[MockApplePay] complete: ${t}`),paymentMethod:{id:"pm_mock_apple_pay_test",object:"payment_method",type:"card",card:{brand:"visa",last4:"4242",exp_month:12,exp_year:2030},billing_details:{email:"test@example.com",name:"Test User"}},payerEmail:"test@example.com",payerName:"Test User"},billingDetails:{email:"test@example.com",name:"Test User"}})},500)});case"cancelled":return console.log("[MockApplePay] showPreparedPaymentSheet: cancelled"),new Promise(e=>{setTimeout(()=>{e({success:!1,cancelled:!0})},500)})}}async showPaymentSheet(e){console.warn("[ApplePay] showPaymentSheet is deprecated. Use preparePaymentRequest() + showPreparedPaymentSheet() instead.");let t=await this.preparePaymentRequest(e);return t.success?this.showPreparedPaymentSheet():{success:!1,error:t.error??"Failed to prepare payment request"}}completePayment(e,t){console.log("[ApplePay] completePayment:",t),e.complete(t)}async confirmPaymentIntent(e,t){switch(this.mockScenario){case"none":{if(console.log("[ApplePay] confirmPaymentIntent called",{clientSecret:`${e.slice(0,20)}...`,paymentMethodId:t}),!this.stripe)return console.log("[ApplePay] confirmPaymentIntent: Stripe not initialized"),{success:!1,error:"Stripe not initialized"};let{error:n}=await this.stripe.confirmCardPayment(e,{payment_method:t});return n?(console.log("[ApplePay] confirmPaymentIntent error:",n),{success:!1,error:n.message??"Payment failed"}):(console.log("[ApplePay] confirmPaymentIntent success"),{success:!0})}case"success":return console.log("[MockApplePay] confirmPaymentIntent called",{clientSecret:e,paymentMethodId:t}),{success:!0};case"cancelled":throw new Error("confirmPaymentIntent should not be called when scenario is Cancelled")}}};var Je=null,Se=null,an=null;async function up(){if(!(typeof window>"u")&&!window.ApplePaySession)return document.getElementById("__pk_apple_pay_sdk")?an??Promise.resolve():(an=new Promise((r,e)=>{let t=document.createElement("script");t.id="__pk_apple_pay_sdk",t.src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js",t.crossOrigin="anonymous",t.onload=()=>r(),t.onerror=()=>{an=null,document.getElementById("__pk_apple_pay_sdk")?.remove(),e(new Error("Failed to load Apple Pay SDK"))},document.head.appendChild(t)}),an)}async function lt(r,e,t){let n=new Headers(e.headers);t&&n.set("x-request-id",t);let s=await fetch(r,{...e,headers:n});if(!s.ok){let i=`Request failed (${s.status})`;try{i=(await s.json()).detail||i}catch{i=s.statusText||i}return{error:i}}return{data:await s.json()}}function pp(r){return r?.processorId?r.processorType==="airwallex"&&!r.country&&!Se?.country?{country:"Country is required for Airwallex Apple Pay"}:null:{processor_id:"Processor ID is required"}}function ll(r){return r&&r!=="none"?r:void 0}async function cl(r,e,t,n,s){return lt(`${r}/api/checkout/${e}/apple-pay/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({processor_id:t.processorId,customer_info:t.customerInfo,fraud_metadata:me(),mock_scenario:n})},s)}function ul(r,e){let t=new on(e);return t.initialize(r)?{adapter:t}:{error:'Stripe.js not loaded. Add <script src="https://js.stripe.com/v3/"><\/script> to your page.'}}async function nl(r,e,t,n,s,i){let o=await lt(`${r}/api/checkout/${e}/apple-pay/confirm`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payment_method_id:t,payer_email:i,mock_scenario:n})},s);if(o.error||!o.data)return{errors:{apple_pay:o.error||"Failed to confirm payment"}};let a=o.data;return a.charge_status==="success"?{data:{id:a.transaction_id,checkoutAttemptId:a.checkout_attempt_id,checkoutSessionId:a.checkout_session_id??e,state:"checkout_succeeded",paymentIntentId:a.payment_intent_id,customerId:a.customer_id,paymentMethodId:a.payment_method_id,processorUsed:a.processor_used,subscriptionId:a.subscription_id,invoiceId:a.invoice_id,invoiceNumber:a.invoice_number,cardBrand:a.card_brand,cardLast4:a.card_last4,cardExpMonth:a.card_exp_month,cardExpYear:a.card_exp_year,errorCode:a.error_code,errorMessageForCustomer:a.error_message_for_customer,errorMessageForDebug:a.error_message_for_debug,nextAction:a.next_action}}:{errors:{apple_pay:a.error_message_for_customer||a.error_message_for_debug||"Payment failed"}}}async function sl(r,e,t,n){console.log("[ApplePay] prepareApplePay called"),Je=null;let s=ll(t.mockScenario),i=ye(n);if(console.log(`[ApplePay] Using checkout_request_id: ${i}`),t.processorType==="airwallex"){if(console.log("[ApplePay] Airwallex processor - loading Apple Pay SDK, fetching session info for amount"),!s){try{await up()}catch(m){return console.error("[ApplePay] Failed to load Apple Pay SDK:",m),{success:!1,error:"Failed to load Apple Pay"}}let f=!1;try{f=!!window.ApplePaySession?.canMakePayments()}catch{f=!1}if(!f)return console.log("[ApplePay] Apple Pay not available on this device/browser"),{success:!1,error:"Apple Pay not available on this device"}}let p=await pl(r,e,i);if(p.error||!p.data)return console.error("[ApplePay] Failed to fetch session info:",p.error),{success:!1,error:p.error||"Failed to fetch Apple Pay session info"};console.log("[ApplePay] Got session info:",p.data);let d=p.data.amount,h=p.data.currency;return Se={country:p.data.country||t.country,currency:h,amount:d,merchantName:t.merchantName},console.log("[ApplePay] Airwallex prepared state:",Se),{success:!0,applePay:!0}}let o=await cl(r,e,t,s,i);if(o.error||!o.data)return{success:!1,error:o.error||"Failed to start Apple Pay"};let a=o.data;if(!a.stripe_pk)return{success:!1,error:"Stripe publishable key not provided"};let{adapter:l,error:u}=ul(a.stripe_pk,t.mockScenario);if(!l)return{success:!1,error:u};let c=await l.preparePaymentRequest({country:a.country,currency:a.currency.toLowerCase(),total:{label:"Total",amount:a.amount}});return c.success?c.applePay?(Je={processor:"stripe",adapter:l,startData:a,mockScenarioStr:s,checkoutRequestId:i},console.log("[ApplePay] prepareApplePay success (Stripe), ready for click"),{success:!0,applePay:!0}):{success:!1,error:"Apple Pay is not available on this device or Stripe account",applePay:!1}:{success:!1,error:c.error||"Failed to prepare payment request",applePay:c.applePay}}function fr(){Je&&Je.adapter.clearPrepared(),Je=null,Se=null}async function pl(r,e,t){return lt(`${r}/api/checkout/${e}/airwallex/apple-pay/session-info`,{method:"GET",headers:{"Content-Type":"application/json"}},t)}async function il(r,e,t,n,s,i,o){return lt(`${r}/api/checkout/${e}/airwallex/apple-pay/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({processor_id:t.processorId,customer_info:t.customerInfo,fraud_metadata:me(),validation_url:n,initiative_context:s,mock_scenario:i})},o)}async function dp(r,e,t,n,s,i,o,a){let l=await lt(`${r}/api/checkout/${e}/airwallex/apple-pay/confirm`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apple_pay_token:t,payer_email:i,payer_first_name:o,payer_last_name:a,mock_scenario:n})},s);return l.error||!l.data?{charge_status:"fail",error_message_for_debug:l.error||"Failed to confirm payment",checkout_attempt_id:""}:l.data}async function hp(r,e,t){let n=await lt(`${r}/api/checkout/${e}/airwallex/apple-pay/verify`,{method:"POST",headers:{"Content-Type":"application/json"}},t);return n.error||!n.data?{charge_status:"fail",error_message_for_debug:n.error||"Failed to verify payment",checkout_attempt_id:""}:n.data}function ol(r,e){return r.charge_status==="success"?{data:{id:r.transaction_id,checkoutAttemptId:r.checkout_attempt_id,checkoutSessionId:r.checkout_session_id??e,state:"checkout_succeeded",paymentIntentId:r.payment_intent_id,customerId:r.customer_id,paymentMethodId:r.payment_method_id,processorUsed:r.processor_used,subscriptionId:r.subscription_id,invoiceId:r.invoice_id,invoiceNumber:r.invoice_number,cardBrand:r.card_brand,cardLast4:r.card_last4,cardExpMonth:r.card_exp_month,cardExpYear:r.card_exp_year,errorCode:r.error_code,errorMessageForCustomer:r.error_message_for_customer,errorMessageForDebug:r.error_message_for_debug,nextAction:r.next_action}}:{errors:{apple_pay:r.error_message_for_customer||r.error_message_for_debug||"Payment failed"}}}var al=5;async function fp(r,e,t,n,s){let i="none";if(t.mockScenario==="success"?i="success":t.mockScenario==="cancelled"&&(i="cancelled"),!t.country)return{errors:{apple_pay:"Country is required for Airwallex Apple Pay"}};if(!t.amount){let b=await pl(r,e,s);b.data&&(t.amount=b.data.amount,t.currency=t.currency||b.data.currency,t.country=t.country||b.data.country)}let o=new sn(i),a={amount:t.amount||0,currency:(t.currency||"USD").toUpperCase(),country:t.country.toUpperCase(),merchantName:t.merchantName||"Total"};if(!o.initialize(a))return{errors:{apple_pay:"Apple Pay not available on this device"}};if(!await o.canMakePayment())return{errors:{apple_pay:"Apple Pay not available on this device"}};let u=typeof window<"u"?window.location.hostname:"";if(i!=="none"){let b=await il(r,e,t,"https://mock-apple-pay-gateway.example.com/paymentservices/startSession",u,n,s);if(b.error||!b.data)return{errors:{apple_pay:b.error||"Failed to start mock checkout"}}}let c=await o.showPaymentSheet(async b=>{let v=await il(r,e,t,b,u,n,s);return v.error||!v.data?{error:v.error||"Merchant validation failed"}:v.data.merchant_session?{merchantSession:v.data.merchant_session}:{error:"No merchant session returned from server"}});if(!c.success)return"cancelled"in c&&c.cancelled?{errors:{apple_pay:"Apple Pay cancelled by user"}}:{errors:{apple_pay:c.error||"Apple Pay failed"}};let{token:p,complete:d,payerEmail:h,payerFirstName:g,payerLastName:f}=c,m=await dp(r,e,p,n,s,h,g,f),w=0;for(;m.charge_status==="pending"&&m.next_action&&w<al;){w++;let b=m.next_action,v=await Tt({type:b.type,url:b.url}),_=await hp(r,e,s);if(_.charge_status==="pending"&&_.next_action){v.success||console.log("[ApplePay:Airwallex] 3DS failed but retry available, continuing loop..."),m=_;continue}return v.success?(d(_.charge_status==="success"?"success":"fail"),ol(_,e)):(d("fail"),{errors:{apple_pay:_.error_message_for_customer||_.error_message_for_debug||v.error||"3DS authentication failed"}})}return w>=al?(d("fail"),{errors:{apple_pay:"Too many authentication attempts. Please try again."}}):(d(m.charge_status==="success"?"success":"fail"),ol(m,e))}var gp=(r,e,t)=>async(s,i)=>{let{apiBaseUrl:o,secureToken:a,environment:l}=r,u=i,c=e();!u.processorId&&c?.processorId&&(u.processorId=c.processorId),!u.processorType&&c?.processorType&&(u.processorType=c.processorType);let p=pp(u);if(p)return{errors:p};try{let d=ll(u.mockScenario),h=ye(l);if(console.log(`[ApplePay] Using checkout_request_id: ${h}`),Je?.adapter.isPrepared()){console.log("[ApplePay] Using prepared Stripe state for immediate sheet display");let O=await Je.adapter.showPreparedPaymentSheet();if(!O.success)return fr(),"cancelled"in O&&O.cancelled?{errors:{apple_pay:"Apple Pay cancelled by user"}}:{errors:{apple_pay:"error"in O?O.error:"Unknown error"}};let{paymentMethodId:V,paymentMethodEvent:W,billingDetails:X}=O,z=await nl(o,a,V,d,Je.checkoutRequestId,X?.email);return z.data?(W.complete("success"),fr(),z):(W.complete("fail"),fr(),z)}if(u.processorType==="airwallex"){console.log("[ApplePay] Running Airwallex flow (processorType=airwallex)"),Se&&(u.country==null&&(u.country=Se.country),u.currency==null&&(u.currency=Se.currency),u.amount==null&&(u.amount=Se.amount),u.merchantName==null&&(u.merchantName=Se.merchantName));try{return await fp(o,a,u,d,h)}finally{Se=null}}let g=await cl(o,a,u,d,h);if(g.error||!g.data)return{errors:{apple_pay:g.error||"Failed to start Apple Pay"}};let f=g.data;if(console.warn("[ApplePay] Stripe flow without prepared state - may fail due to user gesture requirements"),!f.stripe_pk)return{errors:{apple_pay:"Stripe publishable key not provided"}};let{adapter:m,error:w}=ul(f.stripe_pk,u.mockScenario);if(!m)return{errors:{apple_pay:w||"Failed to initialize Stripe adapter"}};let b=await m.preparePaymentRequest({country:f.country,currency:f.currency.toLowerCase(),total:{label:"Total",amount:f.amount}});if(!b.success||!b.applePay)return{errors:{apple_pay:b.error||"Apple Pay not available"}};let v=await m.showPreparedPaymentSheet();if(!v.success)return"cancelled"in v&&v.cancelled?{errors:{apple_pay:"Apple Pay cancelled by user"}}:{errors:{apple_pay:"error"in v?v.error:"Unknown error"}};let{paymentMethodId:_,paymentMethodEvent:k,billingDetails:M}=v,I=await nl(o,a,_,d,h,M?.email);return I.data?(k.complete("success"),I):(k.complete("fail"),I)}catch(d){return t(),{errors:{apple_pay:`Apple Pay error: ${d}`}}}},yp=Ee(r=>{let{apiBaseUrl:e,secureToken:t,environment:n}=r,s=null,i=[],o=!1,a=!1,l=0,u=null,c=[];function p(g){o=g;for(let f of i)f(g)}function d(){fr(),p(!1)}async function h(g,f,m){if(a)return u={apiBaseUrl:g,secureToken:f,environment:m},new Promise(b=>c.push(b));a=!0;let w=l;p(!1);try{let b=await lt(`${g}/api/checkout-sessions/token/${f}`,{method:"GET"});if(l!==w)return;if(b.error||!b.data){console.warn("[ApplePay] Auto-prepare: failed to fetch session config:",b.error);return}let v=b.data.express_checkout_processor_id;if(!v){console.log("[ApplePay] Auto-prepare: no express checkout processor configured");return}let _=b.data.express_checkout_processor_type,k=_==="airwallex"||_==="stripe"?_:void 0;s={processorId:v,processorType:k};let M=await sl(g,f,{processorId:v,processorType:k,customerInfo:{first_name:"",last_name:""}},m);if(l!==w)return;p(M.success&&M.applePay===!0)}catch(b){l===w&&console.error("[ApplePay] Auto-prepare failed:",b)}finally{a=!1;let b=l!==w,v=u,_=c.splice(0);if(!b&&v)u=null,h(v.apiBaseUrl,v.secureToken,v.environment).then(()=>{for(let k of _)k()});else{u=null;for(let k of _)k()}}}return h(e,t,n).catch(g=>console.error("[ApplePay] Unhandled init error:",g)),{name:"apple_pay",externalFuncs:{prepareApplePay:g=>sl(e,t,g,n),onApplePayReady:g=>{i.push(g),g(o)},notifyAmountChanged:()=>(d(),s=null,h(e,t,n))},internalFuncs:{submitPayment:gp(r,()=>s,d),cleanup:()=>{l++,i=[],o=!1,s=null,u=null,c=[],a=!1,fr()}}}});var dl=yp;var hl=(r,e)=>en({window:r.contentWindow,methods:e});var gi="https://js.verygoodvault.com/vgs-collect/3.2.1/vgs-collect.js",gr=null;function fl(){return gr?(console.log("[PaymentKit] VGS Collect CDN load already in progress \u2014 reusing promise"),gr):(gr=new Promise((r,e)=>{if(typeof window<"u"&&window.VGSCollect){console.log("[PaymentKit] VGS Collect JS already available on window"),r();return}console.log(`[PaymentKit] Loading VGS Collect JS from CDN: ${gi}`);let t=document.createElement("script");t.src=gi,t.async=!0,t.onload=()=>{console.log("[PaymentKit] VGS Collect JS loaded successfully from CDN"),r()},t.onerror=()=>{console.error(`[PaymentKit] Failed to load VGS Collect JS from CDN: ${gi}`),gr=null,e(new Error("Failed to load VGS Collect JS"))},document.head.appendChild(t)}),gr)}function gl(r,e){if(!window.VGSCollect)throw new Error("VGS Collect JS not loaded. Call loadVgsCollectScript() first.");return window.VGSCollect.create(r,e,()=>{})}function yl(r,e,t,n,s){let i=document.querySelector(e.pan),o=i?getComputedStyle(i).padding:void 0,l={...t??{"font-size":"1rem",color:"#18181b","font-family":"ui-sans-serif, system-ui, sans-serif"},height:"100%","box-sizing":"border-box",...o&&o!=="0px"?{padding:o}:{}};for(let g of[e.pan,e.exp,e.cvc]){let f=document.querySelector(g);if(!f)continue;let m=f.querySelectorAll("iframe");for(let w of m)w.remove()}let u=r.cardNumberField(e.pan,{placeholder:s?.card_pan??"Card number",validations:["required","validCardNumber"],css:l}),c=r.field(e.exp,{type:"card-expiration-date",name:"exp-date",placeholder:s?.card_exp??"MM / YY",yearLength:2,serializers:[{name:"separate",options:{monthName:"month",yearName:"year"}}],validations:["required","validCardExpirationDate"],css:l}),p=r.cardCVCField(e.cvc,{placeholder:s?.card_cvc??"123",validations:["required","validCardSecurityCode"],css:l}),d=[],h=[];for(let g of[e.pan,e.exp,e.cvc]){let f=document.querySelector(g);if(!f)continue;h.push(f);let m=v=>{let _=f;getComputedStyle(_).position==="static"&&(_.style.position="relative"),v.style.position="absolute",v.style.inset="0",v.style.width="100%",v.style.height="100%",v.style.border="none"},w=new MutationObserver(()=>{let v=f.querySelector("iframe");v&&v.style.position!=="absolute"&&m(v)});w.observe(f,{childList:!0,subtree:!0}),d.push(w);let b=f.querySelector("iframe");b&&b.style.position!=="absolute"&&m(b)}if(n){let g=[[u,"card_pan"],[c,"card_exp"],[p,"card_cvc"]];for(let[f,m]of g){let w=n[m];w&&(f.on("focus",()=>w(!0)),f.on("blur",()=>w(!1)))}}return()=>{for(let g of d)g.disconnect();for(let g of h){let f=g.querySelectorAll("iframe");for(let m of f)m.remove()}}}var mp=r=>{let e=r.trim(),t=e.indexOf(" ");return t===-1?{firstName:e}:{firstName:e.substring(0,t),lastName:e.substring(t+1).trim()||void 0}},vp=r=>{let{firstName:e,lastName:t}=mp(r.customer_name),n=r.customer_country||r.customer_zip_code||r.customer_address_line1||r.customer_address_line2||r.customer_city||r.customer_state,s=r.shipping_address_line1||r.shipping_address_line2||r.shipping_city||r.shipping_state||r.shipping_zip_code||r.shipping_country,i;if(r.customer_tax_ids)try{i=JSON.parse(r.customer_tax_ids)}catch{i=void 0}return{email:r.customer_email||void 0,firstName:e,lastName:t,businessName:r.customer_business_name||void 0,taxIds:i?.length?i:void 0,billingAddress:n?{country:r.customer_country||void 0,zipCode:r.customer_zip_code||void 0,line1:r.customer_address_line1||void 0,line2:r.customer_address_line2||void 0,city:r.customer_city||void 0,state:r.customer_state||void 0}:void 0,shippingAddress:s?{line1:r.shipping_address_line1||void 0,line2:r.shipping_address_line2||void 0,city:r.shipping_city||void 0,state:r.shipping_state||void 0,zipCode:r.shipping_zip_code||void 0,country:r.shipping_country||void 0}:void 0}},_p=r=>{let{baseUrl:e,apiBaseUrl:t,cardInputConnections:n,secureToken:s,timingTracker:i}=r;return(o,a)=>{let{style:l,onLoaded:u,onFocusChange:c,placeholder:p}=a;return{mount:h=>{let g,f,m=!1;r.vgsMountSelectors||(r.vgsMountSelectors={}),r.vgsMountSelectors[o]=h;let w=()=>{if(m)return;let b=r.cardTokenizationMode==="vgs";if(console.log(`[PaymentKit] card.doMount(${o}) \u2014 mode: ${r.cardTokenizationMode}, vgsVaultId: ${r.vgsVaultId??"unset"}, vgsEnvironment: ${r.vgsEnvironment??"unset"}`),b&&r.vgsVaultId&&r.vgsEnvironment){if(c&&(r.vgsFocusCallbacks||(r.vgsFocusCallbacks={}),r.vgsFocusCallbacks[o]=c),p&&(r.vgsPlaceholders||(r.vgsPlaceholders={}),r.vgsPlaceholders[o]=p),o==="card_pan"){let O=r.vgsVaultId,V=r.vgsEnvironment;console.log(`[PaymentKit] VGS mode active \u2014 loading VGS Collect CDN for vault ${O} (${V})...`);let W=15e3,X;Promise.race([fl(),new Promise((z,te)=>{X=setTimeout(()=>{console.warn(`[PaymentKit] VGS Collect CDN load timed out after ${W/1e3}s`),te(new Error("VGS Collect CDN load timed out"))},W)})]).finally(()=>clearTimeout(X)).then(()=>{if(m)return;console.log("[PaymentKit] VGS Collect CDN loaded \u2014 initializing form...");let z=gl(O,V);if(m){z.unmount();return}r.vgsForm=z;let te=l?Object.fromEntries(Object.entries(l).map(([ve,Ce])=>[ve.replace(/([A-Z])/g,"-$1").toLowerCase(),Ce])):void 0,Q=r.vgsMountSelectors?.card_exp,de=r.vgsMountSelectors?.card_cvc;if(!Q||!de){console.error(`[PaymentKit] VGS mode requires all three card fields to be mounted. Missing: ${Q?"":"card_exp"}${!Q&&!de?", ":""}${de?"":"card_cvc"}`),u?.();return}console.log(`[PaymentKit] Creating VGS card fields \u2014 pan: ${h}, exp: ${Q}, cvc: ${de}`),r.vgsFieldsCleanup=yl(z,{pan:h,exp:Q,cvc:de},te,r.vgsFocusCallbacks,r.vgsPlaceholders),console.log("[PaymentKit] VGS card fields created successfully"),i.trackInputReady(),u?.()}).catch(z=>{console.error("[PaymentKit] Failed to load VGS Collect script. Card input will not be available:",z),u?.()})}o!=="card_pan"&&u?.(),g=()=>{if(o==="card_pan"&&r.vgsForm){try{r.vgsFieldsCleanup?.()}catch{}r.vgsFieldsCleanup=void 0;try{r.vgsForm.unmount()}catch{}r.vgsForm=void 0}};return}b&&console.warn(`[PaymentKit] VGS mode requested but config incomplete (vgsVaultId: ${r.vgsVaultId??"unset"}, vgsEnvironment: ${r.vgsEnvironment??"unset"}) \u2014 using direct mode`);let v=Za(h),_=getComputedStyle(v),k=_.padding!=="0px"?_.padding:void 0,M={...l??{},height:"100%",boxSizing:"border-box",...k?{padding:k}:{}},I={checkout_token:s,api_base_url:t,style:JSON.stringify(M)},S=nn(o.replace("_","-"),e,I);_.position==="static"&&(v.style.position="relative"),S.style.position="absolute",S.style.inset="0",f=()=>{n[o]?.destroy();try{v.removeChild(S)}catch{}r.cardInputConnections[o]=void 0},v.appendChild(S),S.onload=()=>{o==="card_pan"&&i.trackInputReady();let O=hl(S,{onLoaded:u||(()=>{}),onFocusChange:c||(()=>{})});r.cardInputConnections[o]=O}};return r._sessionConfigReady?r._sessionConfigReady.then(w):w(),{unmount:()=>{m=!0,g?.(),f?.()}}}}}},bp=r=>async(t,n)=>{r._sessionConfigReady&&await r._sessionConfigReady;let s=r.cardTokenizationMode==="vgs",{timingTracker:i,checkoutRequestId:o}=r;i.trackSubmit();let a=oi(o),l=await tn.createFromPenpalConnection(r.tunnelXConnection),c=n?.skipCustomerValidation===!0?{isSuccess:!0}:await hi(t);if(s){if(!c.isSuccess)return i.trackFail(null,"validation_error","Form validation failed"),{errors:c.errors}}else{let f=await Ep(r);if(!(f.isSuccess&&c.isSuccess))return i.trackFail(null,"validation_error","Form validation failed"),{errors:{...f.errors,...c.errors}}}if(!r.cardSetupIntentId){let f=await l.publicEndpoints.createCardSetupIntent({checkoutToken:r.secureToken});r.cardSetupIntentId=f.cardSetupIntentId}if(s){console.log("[PaymentKit] Submitting card via VGS CMP...");let f=await Pp(r,l);if(!f.isSuccess){let m=Object.entries(f.errors).map(([w,b])=>`${w}: ${b}`).join(", ");return i.trackFail(null,"card_submit_error",m||"VGS card submission failed"),{errors:f.errors}}}else{let f=await xp(r);if(!f.isSuccess)return i.trackFail(null,"card_submit_error","Card submission failed"),{errors:f.errors}}let p=await l.publicEndpoints.getCardSetupIntent({cardSetupIntentId:r.cardSetupIntentId,checkoutToken:r.secureToken});if(!p.isCardAllSet){let f={};return p.isCardPanSet||(f.card_pan="required"),p.isCardExpSet||(f.card_exp="required"),p.isCardCvcSet||(f.card_cvc="required"),i.trackFail(null,"card_setup_incomplete","Card details incomplete"),{errors:f}}console.log("Card setup intent is set \u2705",p),console.log("Fields",t);let d=await l.publicEndpoints.cardCheckout({checkoutToken:r.secureToken,publicCardCheckoutRequest:{cardSetupIntentId:r.cardSetupIntentId,customerInfo:vp(t),fraudMetadata:me()}},a);console.log("Card checkout result:",d);let h=5,g=0;for(;d.nextAction&&g<h;){g++,console.log(`Handling user action ${g}/${h}...`);let f=await Tt(d.nextAction);console.log("User action completed, verifying checkout...");let m=await l.publicEndpoints.cardCheckoutVerify({checkoutToken:r.secureToken},a);if(m.nextAction){f.success?console.log("Another user action required, continuing loop..."):console.log("3DS failed but cascade triggered new action, continuing loop..."),d=m;continue}return f.success?(console.log("Card checkout verified \u2705",m),i.trackSuccess(m.checkoutAttemptId||"unknown"),{data:m}):(console.log("3DS authentication failed, checkout concluded:",m),i.trackFail(m.checkoutAttemptId||null,m.errorCode||"3ds_failed",m.errorMessageForCustomer||f.error),{errors:{root:m.errorMessageForCustomer||f.error,checkout_response:m}})}return g>=h?(console.error("Max user actions exceeded"),i.trackFail(null,"max_actions_exceeded","Too many authentication attempts"),{errors:{root:"Too many authentication attempts. Please try again."}}):d.state==="payment_failed"||d.state==="checkout_failed"?(console.log("Card checkout failed:",d),i.trackFail(d.checkoutAttemptId||null,d.errorCode||"payment_failed",d.errorMessageForCustomer||"Payment failed"),{errors:{root:d.errorMessageForCustomer||"Payment failed",checkout_response:d}}):(console.log("Card checkout completed \u2705",d),i.trackSuccess(d.checkoutAttemptId||"unknown"),{data:d})},kp=async(r,e)=>{let t=await fetch(`${r}/api/card-setup-intents/${e}/collect-token`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok)throw new Error(`Failed to get collect token: ${t.status}`);return(await t.json()).access_token},wp={pan:"card_pan",cvc:"card_cvc","exp-date":"card_exp","card-number":"card_pan","card-security-code":"card_cvc","card-expiration-date":"card_exp"},ln=r=>{if(r instanceof Error)return r.message;try{return JSON.stringify(r)}catch{return String(r)}},Pp=async(r,e)=>{let{vgsForm:t,cardSetupIntentId:n,secureToken:s,apiBaseUrl:i,checkoutRequestId:o}=r,a=`[PaymentKit] [${o}]`,l={};if(!t)return l.card_pan="required",{errors:l,isSuccess:!1};if(!n)return l.root="Card setup intent not created",{errors:l,isSuccess:!1};let u;try{u=await kp(i,s)}catch(v){return console.error(`${a} VGS auth token fetch failed:`,ln(v)),l.root="Card authentication failed \u2014 please try again",{errors:l,isSuccess:!1}}let c,p=3e4;try{let v;c=await Promise.race([new Promise((_,k)=>{t.createCard({auth:u,data:{cardholder:{}}},(M,I)=>_(I),M=>k(M))}),new Promise((_,k)=>{v=setTimeout(()=>k(new Error("VGS_TIMEOUT")),p)})]).finally(()=>clearTimeout(v))}catch(v){let _=ln(v);if(console.error(`${a} VGS createCard failed:`,_),v instanceof Error&&v.message==="VGS_TIMEOUT")return l.root="Card processing timed out \u2014 please try again",{errors:l,isSuccess:!1};if(v&&typeof v=="object"&&!(v instanceof Error)){let k=v;for(let[M,I]of Object.entries(wp))if(M in k){let O=k[M]?.errorMessages;l[I]=Array.isArray(O)?O[0]:"invalid"}if(Object.keys(l).length>0)return{errors:l,isSuccess:!1}}return l.root="Card validation failed \u2014 please check your card details and try again",{errors:l,isSuccess:!1}}if(!c?.data?.attributes)return console.error(`${a} VGS createCard returned invalid response:`,ln(c)),l.root="Card processing returned an invalid response \u2014 please try again",{errors:l,isSuccess:!1};let{pan_alias:d,cvc_alias:h,exp_month:g,exp_year:f}=c.data.attributes,m=f<100?2e3+f:f,w=`${String(g).padStart(2,"0")}/${m}`,b=c.data.id;try{let v=e.publicEndpoints.updateCardSetupIntent({checkoutToken:s,cardSetupIntentId:n,updateCardSetupIntentReq:{cardPan:d,cardExp:w,cardCvc:h,cmpCardId:b,fraudMetadata:me()}}),_=new Promise((k,M)=>{if(!t.submit){M(new Error("VGS form.submit not available"));return}t.submit(`/api/card-setup-intents/${s}/${n}`,{method:"post",headers:{"Content-Type":"application/json"},data:I=>({card_cvc:I.cvc})},I=>k(),I=>M(I))});await Promise.all([v,_])}catch(v){return console.error(`${a} updateCardSetupIntent failed:`,ln(v)),l.root="Failed to save card details \u2014 please try again",{errors:l,isSuccess:!1}}return{errors:{},isSuccess:!0}},xp=async r=>{let e={},{cardSetupIntentId:t,cardInputConnections:n}=r,s=Object.entries(n).map(async([i,o])=>{let a=i,u=await(await o.promise).onSubmit(t||"");"error"in u&&(e[a]=u.error)});return await Promise.allSettled(s),{errors:e,isSuccess:Object.keys(e).length===0}},Ep=async r=>{let e={},{cardInputConnections:t}=r,n=Object.entries(t).map(async([s,i])=>{let o=s;if(!i){e[o]="penpal_not_connected";return}let l=await(await i.promise).onValidate();l&&(e[o]=l)});return await Promise.allSettled(n),{errors:e,isSuccess:Object.keys(e).length===0}},Sp=Ee(r=>{let e=Object.create(r);return e.cardInputConnections={},{name:"card",externalFuncs:{createElement:_p(e)},internalFuncs:{submitPayment:bp(e),cleanup:()=>{e.vgsForm&&(e.vgsFieldsCleanup?.(),e.vgsFieldsCleanup=void 0,e.vgsForm.unmount(),e.vgsForm=void 0);for(let t of Object.values(e.cardInputConnections))t?.destroy();e.cardInputConnections={}}}}}),ml=Sp;var cn=class{constructor(e){R(this,"client",null);R(this,"config",null);R(this,"mockScenario");this.mockScenario=e??"none"}initialize(e){return this.mockScenario!=="none"?(console.log("[MockGooglePay:Airwallex] initialize called (mock mode)"),this.config=e,!0):window.google?.payments?.api?.PaymentsClient?(this.config=e,this.client=new window.google.payments.api.PaymentsClient({environment:e.isProduction?"PRODUCTION":"TEST"}),this.client!==null):(console.error("[GooglePay:Airwallex] Google Pay API not loaded"),!1)}getAllowedPaymentMethods(e){if(!this.config)throw new Error("Config not set. Call initialize() first.");let t={type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["VISA","MASTERCARD","AMEX","DISCOVER","JCB"]}};return e&&(t.tokenizationSpecification={type:"PAYMENT_GATEWAY",parameters:{gateway:"airwallex",gatewayMerchantId:this.config.gatewayMerchantId}}),[t]}async canMakePayment(){if(this.mockScenario!=="none")return console.log("[MockGooglePay:Airwallex] canMakePayment: true (mock mode)"),!0;if(!this.client)return!1;try{let e={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:this.getAllowedPaymentMethods(!1)};return(await this.client.isReadyToPay(e)).result}catch(e){return console.error("[GooglePay:Airwallex] canMakePayment error:",e),!1}}async showPaymentSheet(){if(this.mockScenario==="success")return console.log("[MockGooglePay:Airwallex] showPaymentSheet: returning mock success token"),{success:!0,token:{protocolVersion:"ECv2",signature:"MOCK_SIGNATURE",intermediateSigningKey:{signedKey:"MOCK_SIGNED_KEY",signatures:["MOCK_SIGNATURE"]},signedMessage:"MOCK_SIGNED_MESSAGE"},payerEmail:"mock@example.com"};if(this.mockScenario==="cancelled")return console.log("[MockGooglePay:Airwallex] showPaymentSheet: returning mock cancelled"),{success:!1,cancelled:!0};if(!this.client||!this.config)return{success:!1,error:"Google Pay not initialized"};try{let e=this.config.amountDisplay,t={apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:this.getAllowedPaymentMethods(!0),merchantInfo:{merchantName:this.config.merchantId,...this.config.isProduction&&this.config.googleMerchantId?{merchantId:this.config.googleMerchantId}:{}},transactionInfo:{totalPriceStatus:"FINAL",totalPrice:e,currencyCode:this.config.currency.toUpperCase(),countryCode:this.config.country.toUpperCase()},emailRequired:!0},n=await this.client.loadPaymentData(t),s=n.paymentMethodData.tokenizationData.token;return{success:!0,token:JSON.parse(s),payerEmail:n.email}}catch(e){return e instanceof Error&&e.message?.includes("CANCELED")?{success:!1,cancelled:!0}:e.statusCode==="CANCELED"?{success:!1,cancelled:!0}:(console.error("[GooglePay:Airwallex] Payment sheet error:",e),{success:!1,error:e instanceof Error?e.message:"Unknown error"})}}};var un=class{constructor(e){R(this,"stripe",null);R(this,"paymentRequest",null);R(this,"mockScenario");this.mockScenario=e??"none"}initialize(e){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] initialize called"),!window.Stripe)return console.log("[GooglePay] Stripe.js not loaded"),!1;this.stripe=window.Stripe(e);let t=this.stripe!==null;return console.log("[GooglePay] initialize result:",t),t}case"success":case"cancelled":return console.log("[MockGooglePay] initialize called"),console.log("[MockGooglePay] initialize result:",!0),!0}}createPaymentRequest(e){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] createPaymentRequest called",e),!this.stripe)throw new Error("Stripe not initialized");this.paymentRequest=this.stripe.paymentRequest(e),console.log("[GooglePay] paymentRequest created");return}case"success":case"cancelled":{console.log("[MockGooglePay] createPaymentRequest called",e);return}}}async canMakePayment(){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] canMakePayment called"),!this.paymentRequest)return console.log("[GooglePay] canMakePayment: no paymentRequest"),!1;let e=await this.paymentRequest.canMakePayment(),t=e?.googlePay??!1;return console.log("[GooglePay] canMakePayment result:",{result:e,isAvailable:t}),t}case"success":case"cancelled":return console.log("[MockGooglePay] canMakePayment called"),console.log("[MockGooglePay] canMakePayment result:",{result:{googlePay:!0},isAvailable:!0}),!0}}async showPaymentSheet(){switch(this.mockScenario){case"none":return console.log("[GooglePay] showPaymentSheet called"),this.paymentRequest?new Promise(e=>{this.paymentRequest.on("paymentmethod",t=>{console.log("[GooglePay] showPaymentSheet: paymentmethod event",{paymentMethodId:t.paymentMethod.id,payerEmail:t.payerEmail}),e({success:!0,paymentMethodId:t.paymentMethod.id,payerEmail:t.payerEmail??void 0,complete:n=>{console.log("[GooglePay] complete called:",n),t.complete(n)}})}),this.paymentRequest.on("cancel",()=>{console.log("[GooglePay] showPaymentSheet: cancelled by user"),e({success:!1,cancelled:!0})}),console.log("[GooglePay] showing payment sheet..."),this.paymentRequest.show()}):(console.log("[GooglePay] showPaymentSheet: no paymentRequest"),{success:!1,error:"Payment request not created"});case"success":return console.log("[MockGooglePay] showPaymentSheet: success"),await new Promise(e=>setTimeout(e,500)),{success:!0,paymentMethodId:"pm_mock_123456789",payerEmail:"mock@example.com",complete:e=>console.log(`[MockGooglePay] complete: ${e}`)};case"cancelled":return console.log("[MockGooglePay] showPaymentSheet: cancelled"),await new Promise(e=>setTimeout(e,500)),{success:!1,cancelled:!0}}}async confirmCardSetup(e,t){switch(this.mockScenario){case"none":{if(console.log("[GooglePay] confirmCardSetup called",{clientSecret:`${e.slice(0,20)}...`,paymentMethodId:t}),!this.stripe)return console.log("[GooglePay] confirmCardSetup: Stripe not initialized"),{success:!1,error:"Stripe not initialized"};let{error:n}=await this.stripe.confirmCardSetup(e,{payment_method:t});return n?(console.log("[GooglePay] confirmCardSetup error:",n),{success:!1,error:n.message??"Card setup failed"}):(console.log("[GooglePay] confirmCardSetup success"),{success:!0})}case"success":return console.log("[MockGooglePay] confirmCardSetup called",{clientSecret:e,paymentMethodId:t}),{success:!0};case"cancelled":throw new Error("confirmCardSetup should not be called when scenario is Cancelled")}}};async function mi(r,e,t){let n=new Headers(e.headers);t&&n.set("x-request-id",t);let s=await fetch(r,{...e,headers:n});if(!s.ok){let i=`Request failed (${s.status})`;try{i=(await s.json()).detail||i}catch{i=s.statusText||i}return{error:i}}return{data:await s.json()}}function Cp(r){return r?.processorId?null:{processor_id:"Processor ID is required"}}function Ap(r){return r&&r!=="none"?r:void 0}async function Ip(r,e,t,n,s){return mi(`${r}/api/checkout/${e}/google-pay/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({processor_id:t.processorId,customer_info:t.customerInfo,fraud_metadata:me(),mock_scenario:n})},s)}function Mp(r,e,t){let n=new un(t);if(!n.initialize(r))return{error:'Stripe.js not loaded. Add <script src="https://js.stripe.com/v3/"><\/script> to your page.'};let s={country:e.country,currency:e.currency.toLowerCase(),total:{label:"Total",amount:e.amount},requestPayerName:!0,requestPayerEmail:!0};return n.createPaymentRequest(s),{adapter:n}}async function Rp(r,e){if(!r.stripe_pk||!r.client_secret)return{success:!1,error:"Stripe credentials not provided"};let{adapter:t,error:n}=Mp(r.stripe_pk,r,e);if(!t)return{success:!1,error:n};if(!await t.canMakePayment())return{success:!1,error:"Google Pay not available on this device"};let i=await t.showPaymentSheet();if(!i.success)return"cancelled"in i&&i.cancelled?{success:!1,error:"Google Pay cancelled by user"}:{success:!1,error:"error"in i?i.error:"Unknown error"};let o=await t.confirmCardSetup(r.client_secret,i.paymentMethodId);return o.success?(i.complete("success"),{success:!0,payerEmail:i.payerEmail}):(i.complete("fail"),{success:!1,error:"error"in o?o.error:"Card setup failed"})}function Tp(r,e){if(!r.merchant_name||!r.airwallex_account_id)return{error:"Airwallex Google Pay credentials not provided"};let t="none";e==="success"?t="success":e==="cancelled"&&(t="cancelled");let n=new cn(t),s={merchantId:r.merchant_name,gatewayMerchantId:r.airwallex_account_id,amountDisplay:r.amount_display,currency:r.currency,country:r.country,isProduction:r.is_sandbox===!1,googleMerchantId:r.google_merchant_id};return n.initialize(s)?{adapter:n}:{error:'Google Pay API not loaded. Add <script src="https://pay.google.com/gp/p/js/pay.js"><\/script> to your page.'}}async function Fp(r,e){let{adapter:t,error:n}=Tp(r,e);if(!t)return{success:!1,error:n};if(!await t.canMakePayment())return{success:!1,error:"Google Pay not available on this device"};let i=await t.showPaymentSheet();return i.success?{success:!0,token:i.token,payerEmail:i.payerEmail}:"cancelled"in i&&i.cancelled?{success:!1,error:"Google Pay cancelled by user"}:{success:!1,error:"error"in i?i.error:"Unknown error"}}async function _l(r,e,t,n,s,i){let o={mock_scenario:n};t&&(o.google_pay_token=t),i&&(o.payer_email=i);let a=await mi(`${r}/api/checkout/${e}/google-pay/confirm`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},s);return a.error||!a.data?{charge_status:"fail",error_message:a.error||"Failed to confirm payment",checkout_attempt_id:""}:a.data}async function Op(r,e,t){let n=await mi(`${r}/api/checkout/${e}/google-pay/verify`,{method:"POST",headers:{"Content-Type":"application/json"}},t);return n.error||!n.data?{charge_status:"fail",error_message:n.error||"Failed to verify payment",checkout_attempt_id:""}:n.data}function yi(r,e){return r.charge_status==="success"?{data:{id:r.transaction_id,checkoutAttemptId:r.checkout_attempt_id,checkoutSessionId:r.checkout_session_id??e,state:"checkout_succeeded",paymentIntentId:r.payment_intent_id,customerId:r.customer_id,paymentMethodId:r.payment_method_id,processorUsed:r.processor_used,subscriptionId:r.subscription_id,invoiceId:r.invoice_id,invoiceNumber:r.invoice_number,cardBrand:r.card_brand,cardLast4:r.card_last4,cardExpMonth:r.card_exp_month,cardExpYear:r.card_exp_year,errorCode:r.error_code,errorMessageForCustomer:r.error_message_for_customer,errorMessageForDebug:r.error_message_for_debug,nextAction:r.next_action}}:{errors:{google_pay:r.error_message_for_customer||r.error_message_for_debug||r.error_message||"Payment failed"}}}async function $p(r,e,t,n,s){let i=await _l(r,e,void 0,t,n,s);return yi(i,e)}var vl=5;async function Np(r,e,t,n,s,i){let o=0,a=await _l(r,e,t,n,s,i);for(;a.charge_status==="pending"&&a.next_action&&o<vl;){o++;let l=await Tt(a.next_action),u=await Op(r,e,s);if(u.charge_status==="pending"&&u.next_action){l.success||console.log("[GooglePay:Airwallex] 3DS failed but retry available, continuing loop..."),a=u;continue}return l.success?yi(u,e):{errors:{google_pay:u.error_message||l.error||"3DS authentication failed"}}}return o>=vl?{errors:{google_pay:"Too many authentication attempts. Please try again."}}:yi(a,e)}var Dp=r=>async(t,n)=>{let{apiBaseUrl:s,secureToken:i,environment:o}=r,a=n,l=Cp(a);if(l)return{errors:l};try{let u=Ap(a.mockScenario),c=ye(o);console.log(`[GooglePay] Using checkout_request_id: ${c}`);let p=await Ip(s,i,a,u,c);if(p.error||!p.data)return{errors:{google_pay:p.error||"Failed to start Google Pay"}};let d=p.data;if(d.processor==="stripe"){let h=await Rp(d,a.mockScenario);return h.success?await $p(s,i,u,c,h.payerEmail):{errors:{google_pay:h.error}}}if(d.processor==="airwallex"){let h=await Fp(d,a.mockScenario);return h.success?h.token?await Np(s,i,h.token,u,c,h.payerEmail):{errors:{google_pay:"Google Pay token not received"}}:{errors:{google_pay:h.error}}}return{errors:{google_pay:`Unsupported processor: ${d.processor}`}}}catch(u){return{errors:{google_pay:`Google Pay error: ${u}`}}}},qp=Ee(r=>({name:"google_pay",externalFuncs:{},internalFuncs:{submitPayment:Dp(r),cleanup:()=>{}}}));var bl=qp;var jp=Rt({name:"klarna",endpointPath:"klarna",supportsSetupFutureUsage:!0}),kl=jp;var Gp=r=>async(t,n)=>{let{apiBaseUrl:s,secureToken:i,environment:o}=r,a=n;if(!a?.processorId)return{errors:{processor_id:"Processor ID is required"}};if(!a?.customerInfo?.first_name||!a?.customerInfo?.last_name)return{errors:{customer_name:"Customer first and last name are required"}};try{let l=ye(o);console.log(`[PayPal] Using checkout_request_id: ${l}`);let u=await fetch(`${s}/api/checkout/${i}/paypal/start`,{method:"POST",headers:{"Content-Type":"application/json","x-request-id":l},body:JSON.stringify({processor_id:a.processorId,customer_info:a.customerInfo,fraud_metadata:me()})});if(!u.ok){let g=`Failed to start PayPal checkout (${u.status})`;try{g=(await u.json()).detail||g}catch{g=u.statusText||g}return{errors:{paypal:g}}}let{approval_url:c,popup_token:p,checkout_attempt_id:d}=await u.json(),h=window.open(c,"PayPal","width=600,height=700");return h?(r.popup=h,new Promise(g=>{let f=setInterval(async()=>{try{let m=await fetch(`${s}/api/checkout/${i}/popup/status?popup_token=${p}`);if(!m.ok){clearInterval(f),h.close(),g({errors:{paypal:"Failed to check PayPal status"}});return}let w=await m.json();if(w.completed){if(clearInterval(f),h.close(),w.status==="success"){let b=w.result||{id:d,checkoutAttemptId:d,checkoutSessionId:i,state:"checkout_succeeded"};g({data:b})}else g({errors:{paypal:w.error||`PayPal checkout ${w.status}`}});return}if(h.closed){clearInterval(f),g({errors:{paypal:"PayPal popup closed by user"}});return}}catch(m){clearInterval(f),h.close(),g({errors:{paypal:`Polling error: ${m}`}})}},2e3);r.pollInterval=f})):{errors:{paypal:"Failed to open PayPal popup. Please allow popups for this site."}}}catch(l){return{errors:{paypal:`PayPal checkout error: ${l}`}}}},Lp=Ee(r=>{let e={...r};return{name:"paypal",externalFuncs:{},internalFuncs:{submitPayment:Gp(e),cleanup:()=>{e.pollInterval&&clearInterval(e.pollInterval),e.popup&&!e.popup.closed&&e.popup.close()}}}}),wl=Lp;var Up=Qa,Vp={applePay:dl,card:ml,googlePay:bl,paypal:wl,klarna:kl,afterpay:tl,affirm:el};return Fl(zp);})();
65
65
  //# sourceMappingURL=paymentkit.min.js.map