@heycatch/sdk 0.8.4-dev.2561 → 0.8.5-dev.2546
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.
- package/README.md +51 -2
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +12 -2
- package/dist/index.d.ts +12 -2
- package/dist/index.js +2 -2
- package/dist/react-native.cjs +1 -1
- package/dist/react-native.d.cts +18 -0
- package/dist/server.cjs +2 -2
- package/dist/server.d.cts +10 -2
- package/dist/server.d.ts +10 -2
- package/dist/server.js +2 -2
- package/dist/{shared-jAHOZrzL.d.cts → shared-nNQmChFP.d.cts} +9 -0
- package/dist/{shared-jAHOZrzL.d.ts → shared-nNQmChFP.d.ts} +9 -0
- package/package.json +1 -1
package/dist/server.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var Ht=Object.defineProperty;var Bi=Object.getOwnPropertyDescriptor;var Hi=Object.getOwnPropertyNames;var Ki=Object.prototype.hasOwnProperty;var Kt=(r,e)=>{for(var t in e)Ht(r,t,{get:e[t],enumerable:!0})},Gi=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Hi(e))!Ki.call(r,o)&&o!==t&&Ht(r,o,{get:()=>e[o],enumerable:!(n=Bi(e,o))||n.enumerable});return r};var Wi=r=>Gi(Ht({},"__esModule",{value:!0}),r);var Au={};Kt(Au,{KNOWN_FRAMEWORKS:()=>so,KNOWN_INSTALL_AGENTS:()=>ao,SDK_VERSION:()=>Oe,STAGE:()=>ze,TRACING_HEADERS:()=>lt,UNKNOWN_INSTALL_VALUE:()=>oe,analytics:()=>Iu});module.exports=Wi(Au);function Vr(){}function Xr(){}var et="project",qi="[a-z0-9]",Ru=new RegExp(`^${qi}$`);var V={};Kt(V,{BIGINT_FORMAT_RANGES:()=>hs,CONSTANT_CATCH:()=>_n,Class:()=>qt,NUMBER_FORMAT_RANGES:()=>ds,aborted:()=>q,allowsEval:()=>nn,assert:()=>es,assertEqual:()=>Vi,assertIs:()=>Qi,assertNever:()=>Yi,assertNotEqual:()=>Xi,assignProp:()=>Se,attachSchema:()=>Ce,base64ToUint8Array:()=>gn,base64urlToUint8Array:()=>xs,cached:()=>rt,captureStackTrace:()=>nt,cleanEnum:()=>bs,cleanRegex:()=>Xt,clone:()=>L,cloneDef:()=>ss,codePointLength:()=>_s,constantCatch:()=>yn,createTransparentProxy:()=>ps,defineLazy:()=>Qr,defineLazyInternal:()=>D,derived:()=>$s,esc:()=>tn,escapeRegex:()=>Ae,explicitlyAborted:()=>er,extend:()=>un,finalizeIssue:()=>re,floatSafeRemainder:()=>ns,getElementAtPath:()=>as,getEnumValues:()=>tt,getLengthableOrigin:()=>ys,getParsedType:()=>fs,getSizableOrigin:()=>gs,hexToUint8Array:()=>Ps,hide:()=>rr,installLazyProp:()=>nr,isObject:()=>Fe,isPlainObject:()=>Ie,issue:()=>ct,joinValues:()=>ts,jsonStringifyReplacer:()=>Vt,members:()=>tr,merge:()=>pn,mergeDefs:()=>B,normalizeParams:()=>N,nullish:()=>rs,numKeys:()=>ls,objectClone:()=>os,omit:()=>cn,optionalKeys:()=>Yt,own:()=>U,parsedType:()=>vs,partial:()=>dn,pick:()=>an,prefixIssues:()=>st,primitiveTypes:()=>on,promiseAllObject:()=>cs,propertyKeyTypes:()=>Qt,randomString:()=>us,rawShape:()=>Jt,required:()=>hn,safeExtend:()=>fn,shallowClone:()=>ot,sizeCaps:()=>at,slugify:()=>rn,stringifyPrimitive:()=>sn,toZod:()=>Ji,uint8ArrayToBase64:()=>mn,uint8ArrayToBase64url:()=>ws,uint8ArrayToHex:()=>Es,unwrapMessage:()=>he});function Vi(r){return r}function Xi(r){return r}function Ji(){return r=>r}function Qi(r){}function Yi(r){throw new Error("Unexpected value in exhaustive check")}function es(r){}function tt(r){let e=Object.values(r).filter(n=>typeof n=="number");return Object.entries(r).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function ts(r,e="|"){return r.map(t=>sn(t)).join(e)}function Vt(r,e){return typeof e=="bigint"?e.toString():e}var Wt=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function rt(r){return new Wt(r)}function rs(r){return r==null}function Xt(r){let e=r.startsWith("^")?1:0,t=r.endsWith("$")?r.length-1:r.length;return r.slice(e,t)}function ns(r,e){let t=r/e,n=Math.round(t),o=4*Number.EPSILON*Math.max(Math.abs(t),1);return Math.abs(t-n)<o?0:t-n}var Jr=Symbol("evaluating");function Qr(r,e,t){let n;Object.defineProperty(r,e,{get(){if(n!==Jr)return n===void 0&&(n=Jr,n=t()),n},set(o){Object.defineProperty(r,e,{value:o})},configurable:!0})}function os(r){return Object.create(Object.getPrototypeOf(r),Object.getOwnPropertyDescriptors(r))}function Se(r,e,t){Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}function Jt(r){let e=Object.getOwnPropertyDescriptor(r,"shape");return e?.get?e.get.raw:e?.value}function W(r){return Jt(r._zod.def)??r._zod.def.shape}function Yr(r,e,t){Object.defineProperty(r,e,{get(){let n=t();return Se(this,e,n),n},enumerable:!0,configurable:!0})}function en(r,e,t){e in r?Se(r,e,t):r[e]=t}function se(r,e,t,n){let o=W(e);for(let i of t){let s=Object.getOwnPropertyDescriptor(o,i);s.enumerable&&(s.get?Yr(r,i,()=>{let a=e._zod.def.shape[i];return n?n(a,i):a}):en(r,i,n?n(s.value,i):s.value))}}function is(r,e){for(let t of Reflect.ownKeys(e)){let n=Object.getOwnPropertyDescriptor(e,t);n.enumerable&&(n.get?Yr(r,t,()=>e[t]):en(r,t,n.value))}}function B(...r){let e={};for(let t of r){let n=Object.getOwnPropertyDescriptors(t);Object.assign(e,n)}return Object.defineProperties({},e)}function ss(r){return B(r._zod.def)}function as(r,e){return e?e.reduce((t,n)=>t?.[n],r):r}function cs(r){let e=Object.keys(r),t=e.map(n=>r[n]);return Promise.all(t).then(n=>{let o={};for(let i=0;i<e.length;i++)o[e[i]]=n[i];return o})}function us(r=10){let e="abcdefghijklmnopqrstuvwxyz",t="";for(let n=0;n<r;n++)t+=e[Math.floor(Math.random()*e.length)];return t}function tn(r){return JSON.stringify(r)}function rn(r){return r.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var nt="captureStackTrace"in Error?Error.captureStackTrace:(...r)=>{};function Fe(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}var nn=rt(()=>{if(ae.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let r=Function;return new r(""),!0}catch{return!1}});function Ie(r){if(Fe(r)===!1)return!1;let e=r.constructor;if(e===void 0||typeof e!="function")return!0;let t=e.prototype;return!(Fe(t)===!1||Object.prototype.hasOwnProperty.call(t,"isPrototypeOf")===!1)}function ot(r){return Ie(r)?{...r}:Array.isArray(r)?[...r]:r instanceof Map?new Map(r):r instanceof Set?new Set(r):r}function ls(r){let e=0;for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&e++;return e}var fs=r=>{let e=typeof r;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(r)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(r)?"array":r===null?"null":r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?"promise":typeof Map<"u"&&r instanceof Map?"map":typeof Set<"u"&&r instanceof Set?"set":typeof Date<"u"&&r instanceof Date?"date":typeof File<"u"&&r instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Qt=new Set(["string","number","symbol"]),on=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ae(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function L(r,e,t){let n=new r._zod.constr(e??r._zod.def);return(!e||t?.parent)&&(n._zod.parent=r),n}function N(r){let e=r;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function ps(r){let e;return new Proxy({},{get(t,n,o){return e??(e=r()),Reflect.get(e,n,o)},set(t,n,o,i){return e??(e=r()),Reflect.set(e,n,o,i)},has(t,n){return e??(e=r()),Reflect.has(e,n)},deleteProperty(t,n){return e??(e=r()),Reflect.deleteProperty(e,n)},ownKeys(t){return e??(e=r()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(t,n){return e??(e=r()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(t,n,o){return e??(e=r()),Reflect.defineProperty(e,n,o)}})}function sn(r){return typeof r=="bigint"?r.toString()+"n":typeof r=="string"?`"${r}"`:`${r}`}function Yt(r){return Object.keys(r).filter(e=>r[e]._zod.optin!==void 0&&r[e]._zod.optout==="optional")}var ds={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},hs={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function an(r,e){let t=r._zod.def,n=t.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i={};return se(i,r,it(r,e)),L(r,B(t,{shape:i,checks:[]}))}function it(r,e){let t=W(r),n=[];for(let o of Reflect.ownKeys(e)){if(!Object.getOwnPropertyDescriptor(t,o)?.enumerable)throw new Error(`Unrecognized key: "${String(o)}"`);e[o]&&n.push(o)}return n}function cn(r,e){let t=r._zod.def,n=t.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=new Set(it(r,e)),s={};return se(s,r,Reflect.ownKeys(W(r)).filter(a=>!i.has(a))),L(r,B(t,{shape:s,checks:[]}))}function un(r,e){if(!Ie(e))throw new Error("Invalid input to extend: expected a plain object");let t=r._zod.def.checks;if(t&&t.length>0){let o=W(r);for(let i of Reflect.ownKeys(e))if(Object.getOwnPropertyDescriptor(o,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return L(r,B(r._zod.def,{shape:ln(r,e)}))}function ln(r,e){let t={};return se(t,r,Reflect.ownKeys(W(r))),is(t,e),t}function fn(r,e){if(!Ie(e))throw new Error("Invalid input to safeExtend: expected a plain object");return L(r,B(r._zod.def,{shape:ln(r,e)}))}function pn(r,e){if(!e?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(r._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let t={};se(t,r,Reflect.ownKeys(W(r))),se(t,e,Reflect.ownKeys(W(e)));let n=B(r._zod.def,{shape:t,get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return L(r,n)}function dn(r,e,t,n="partial"){let i=e._zod.def.checks;if(i&&i.length>0)throw new Error(`.${n}() cannot be used on object schemas containing refinements`);let a=t?new Set(it(e,t)):void 0,u={};return se(u,e,Reflect.ownKeys(W(e)),r&&((c,l)=>a&&!a.has(l)?c:new r({type:"optional",innerType:c}))),L(e,B(e._zod.def,{shape:u,checks:[]}))}function hn(r,e,t){let n=t?new Set(it(e,t)):void 0,o={};return se(o,e,Reflect.ownKeys(W(e)),(i,s)=>n&&!n.has(s)?i:new r({type:"nonoptional",innerType:i})),L(e,B(e._zod.def,{shape:o}))}function q(r,e=0){if(r.aborted===!0)return!0;for(let t=e;t<r.issues.length;t++)if(r.issues[t]?.continue!==!0)return!0;return!1}function er(r,e=0){if(r.aborted===!0)return!0;for(let t=e;t<r.issues.length;t++)if(r.issues[t]?.continue===!1)return!0;return!1}function st(r,e){return e.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(r),t})}function he(r){return typeof r=="string"?r:r?.message}function at(r){let e=[];for(let t of r??[]){let n=t._zod.def;if(!/_(length|size)$|_equals$/.test(n.check))break;let o=n.maximum??n.length??n.size;o>=0&&e.push([o,t])}return e}function Ce(r,e,t){var n;for(let o=e;o<r.length;o++)(n=r[o]).schema??(n.schema=t)}function re(r,e,t){var n;let o=r.inst?._zod?.traits;o?.has("$ZodType")&&(o.has("$ZodCheck")?(n=r).schema??(n.schema=r.inst):r.schema=r.inst);let i=r.schema!==r.inst?r.schema?._zod.def?.error:void 0,s=r.message?r.message:he(r.inst?._zod.def?.error?.(r))??he(i?.(r))??he(e?.error?.(r))??he(t.customError?.(r))??he(t.localeError?.(r))??"Invalid input",a={};for(let u of Object.keys(r))u==="inst"||u==="schema"||u==="continue"||u==="input"||u==="__proto__"||(a[u]=r[u]);return a.path??(a.path=[]),a.message=s,e?.reportInput&&(a.input=r.input),a}function gs(r){return r instanceof Set?"set":r instanceof Map?"map":r instanceof File?"file":"unknown"}var ms=/[\uD800-\uDBFF]/;function _s(r){let e=r.length;if(!ms.test(r))return e;let t=e;for(let n=0;n<e-1;n++)(r.charCodeAt(n)&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320&&(t--,n++);return t}function ys(r){return Array.isArray(r)?"array":typeof r=="string"?"string":"unknown"}function vs(r){let e=typeof r;switch(e){case"number":return Number.isNaN(r)?"nan":"number";case"object":{if(r===null)return"null";if(Array.isArray(r))return"array";let t=r;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&"constructor"in t&&t.constructor)return t.constructor.name}}return e}function ct(...r){let[e,t,n]=r;return typeof e=="string"?{message:e,code:"custom",input:t,inst:n}:{...e}}function bs(r){return Object.entries(r).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function gn(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function mn(r){let e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e)}function xs(r){let e=r.replace(/-/g,"+").replace(/_/g,"/"),t="=".repeat((4-e.length%4)%4);return gn(e+t)}function ws(r){return mn(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ps(r){let e=r.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=Number.parseInt(e.slice(n,n+2),16);return t}function Es(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}var qt=class{constructor(...e){}};function tr(r,e){for(let t in e){let n=Object.getOwnPropertyDescriptor(e,t);n.get?Object.defineProperty(r,t,{...n,enumerable:!1}):Fs(r,t,n.value)}}function U(r,e,t,n=!0){return Object.defineProperty(r,e,{configurable:!0,writable:!0,enumerable:n,value:t}),t}function rr(r,e,t){return U(r,e,t,!1)}function $s(r,e){for(let t in r){let n=r[t];Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){return U(this,t,n(this))},set(o){U(this,t,o)}})}return e}function Fs(r,e,t){Object.defineProperty(r,e,{configurable:!0,get(){return this==null?t:U(this,e,t.bind(this))},set(n){U(this,e,n)}})}function Ss(r,e){let t=Object.getPrototypeOf(r);return e in t?void 0:t}var Gt,te=!1,Is={configurable:!0,get(){te=!0}};function D(r,e,t){let n=Object.getPrototypeOf(r._zod);if(e in n&&Gt!==r._zod){Gt=void 0;return}Gt=r._zod,Object.defineProperty(n,e,{configurable:!0,get(){Object.defineProperty(this,e,Is);let o=te;te=!1;try{let i=t(this);return te?delete this[e]:Object.defineProperty(this,e,{configurable:!0,writable:!0,value:i}),te=te||o,i}catch(i){throw delete this[e],te=te||o,i}},set(o){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:o})}})}function nr(r,e,t,n){let o=Ss(r,e);o&&Object.defineProperty(o,e,{configurable:!0,get(){let i={configurable:!0,writable:!0,enumerable:n,value:void 0};return Object.defineProperty(this,e,i),i.value=t(this),Object.defineProperty(this,e,i),i.value},set(i){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:n,value:i})}})}var _n="~constantCatch";function yn(r){let e=()=>r;return e[_n]=!0,e}var vn;var or={value:void 0,enumerable:!1},bn="captureStackTrace"in Error?Error:null;function As(r){let e=bn;if(e){let t=e.stackTraceLimit;if(typeof t=="number"){try{e.stackTraceLimit=0}catch{return bn=null,new r}try{return new r}finally{e.stackTraceLimit=t}}}return new r}function b(r,e,t,n){let o={};function i(p){this.def=p,this.constr=f,this.traits=new Set}i.prototype=o;let s=t,a=s&&new WeakSet;function u(p,d){if(p._zod){if(p._zod.traits.has(r))return}else{or.value=new i(d);try{Object.defineProperty(p,"_zod",or)}finally{or.value=void 0}}if(p._zod.traits.add(r),e(p,d),a){let g=Object.getPrototypeOf(p),w=p._zod.constr.prototype,_=g;for(;_&&_!==w;)_=Object.getPrototypeOf(_);let v=_??g;a.has(v)||(a.add(v),tr(v,s))}let h=f.prototype;for(let g in h)Object.prototype.hasOwnProperty.call(h,g)&&(g in p||(p[g]=h[g].bind(p)))}let c=n?.Parent??Object;class l extends c{}Object.defineProperty(l,"name",{value:r});function f(p){let d=n?.Parent?As(l):this;u(d,p);let h=d._zod.deferred;if(h){for(let w of h)w();d._zod.deferred=void 0}let g=globalThis.__zod_globalConfig?.postProcessor;return g&&g(d),d}return Object.defineProperty(f,"init",{value:u}),Object.defineProperty(f,Symbol.hasInstance,{value:p=>n?.Parent&&p instanceof n.Parent?!0:p?._zod?.traits?.has(r)}),Object.defineProperty(f,"name",{value:r}),f}var X=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};(vn=globalThis).__zod_globalConfig??(vn.__zod_globalConfig={});var ae=globalThis.__zod_globalConfig;function ce(r){return r&&Object.assign(ae,r),ae}function Cs(){let r=this._zod;return r.message??(r.message=JSON.stringify(r.def,Vt,2)),r.message}function ks(r){this._zod.message=r}var Rs={get:Cs,set:ks,enumerable:!0,configurable:!0},sr={value:void 0,enumerable:!1},xn=new WeakSet([Object.prototype,Error.prototype]),wn=(r,e)=>{r.name="$ZodError",sr.value=e,Object.defineProperty(r,"issues",sr),sr.value=void 0,Object.defineProperty(r,"message",Rs);let t=Object.getPrototypeOf(r);xn.has(t)||(xn.add(t),Object.defineProperty(t,"toString",{configurable:!0,enumerable:!1,get(){let n=()=>this.message;return Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0})}}))},Lu=b("$ZodError",wn),ke=b("$ZodError",wn,void 0,{Parent:Error});var Os=r=>{let e=(t,n,o,i)=>{let s=o?{...o,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new X;if(a.issues.length){let u=new(i?.Err??r)(a.issues.map(c=>re(c,s,ce())));throw nt(u,i?.callee??e),u}return a.value};return e},ar=Os(ke),Ts=r=>{let e=async(t,n,o,i)=>{let s=o?{...o,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){let u=new(i?.Err??r)(a.issues.map(c=>re(c,s,ce())));throw nt(u,i?.callee??e),u}return a.value};return e},cr=Ts(ke),Ms=r=>(e,t,n)=>{let o=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:t,issues:[]},o);if(i instanceof Promise)throw new X;return i.issues.length?Pn(r,i.issues,o):{success:!0,data:i.value}},ur=Ms(ke);function Pn(r,e,t){let n;return{success:!1,get error(){return n||(n=new r(e.map(o=>re(o,t,ce()))),e=void 0,t=void 0),n},set error(o){n=o,e=void 0,t=void 0}}}var Ls=r=>async(e,t,n)=>{let o=n?{...n,async:!0}:{async:!0},i=e._zod.run({value:t,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?Pn(r,i.issues,o):{success:!0,data:i.value}},lr=Ls(ke);var En=/^[\s\S]{0,}$/;var $n=/^-?\d+(?:\.\d+)?$/,Fn=/^(?:true|false)$/i;var Re=b("$ZodCheck",(r,e)=>{var t;r._zod??(r._zod={}),r._zod.def=e,(t=r._zod).onattach??(t.onattach=[])});var Sn=b("$ZodCheckStringFormat",(r,e)=>{var t,n;Re.init(r,e),e.pattern?(t=r._zod).check??(t.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:r,continue:!e.abort})}):(n=r._zod).check??(n.check=()=>{})}),In=b("$ZodCheckRegex",(r,e)=>{Sn.init(r,e),r._zod.check=t=>{e.pattern.lastIndex=0,!e.pattern.test(t.value)&&t.issues.push({origin:"string",code:"invalid_format",format:"regex",input:t.value,pattern:e.pattern.toString(),inst:r,continue:!e.abort})}});var Cn={major:4,minor:6,patch:6};var O=b("$ZodType",(r,e)=>{var t;r??(r={}),r._zod.def=e,r._zod.bag=r._zod.bag||{},r._zod.version=Cn;let n=r._zod.def.checks,o=r._zod.traits.has("$ZodCheck")?[r,...n??[]]:n?.length?[...n]:[];for(let i of o)for(let s of i._zod.onattach)s(r);if(o.length===0)(t=r._zod).deferred??(t.deferred=[]),r._zod.deferred?.push(()=>{r._zod.run=r._zod.parse});else{let i=(a,u,c)=>{if(a.memo)return a;let l=q(a),f;for(let p of u){if(p._zod.def.when){if(er(a)||!p._zod.def.when(a))continue}else if(l)continue;let d=a.issues.length,h=p._zod.check(a);if(h instanceof Promise&&c?.async===!1)throw new X;if(f||h instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await h,a.issues.length!==d&&(Ce(a.issues,d,r),l||(l=q(a,d)))});else{if(a.issues.length===d)continue;Ce(a.issues,d,r),l||(l=q(a,d))}}return f?f.then(()=>a):a},s=(a,u,c)=>{if(q(a))return a.aborted=!0,a;let l=i(u,o,c);if(l instanceof Promise){if(c.async===!1)throw new X;return l.then(f=>r._zod.parse(f,c))}return r._zod.parse(l,c)};r._zod.run=(a,u)=>{if(u.skipChecks)return r._zod.parse(a,u);if(u.direction==="backward"){let l=r._zod.parse({value:a.value,issues:[]},{...u,skipChecks:!0});return l instanceof Promise?l.then(f=>s(f,a,u)):s(l,a,u)}let c=r._zod.parse(a,u);if(c instanceof Promise){if(u.async===!1)throw new X;return c.then(l=>i(l,o,u))}return i(c,o,u)}}},{get"~standard"(){return rr(this,"~standard",Ds(this))},set"~standard"(r){U(this,"~standard",r)}}),Mn=(r,e)=>r.issues.length?{issues:r.issues.map(t=>re(t,e,ce()))}:{value:r.value};async function Ns(r,e){let t={async:!0};return Mn(await r._zod.run({value:e,issues:[]},t),t)}function Ds(r){return{validate:e=>{let t={async:!1};try{let n=r._zod.run({value:e,issues:[]},t);if(!(n instanceof Promise))return Mn(n,t)}catch{}return Ns(r,e)},vendor:"zod",version:1}}var Ln=b("$ZodString",(r,e)=>{O.init(r,e),r._zod.pattern=e.pattern??En,r._zod.parse=(t,n)=>{if(e.coerce)try{t.value=String(t.value)}catch{}return typeof t.value=="string"||t.issues.push({expected:"string",code:"invalid_type",input:t.value,inst:r}),t}});var Nn=b("$ZodNumber",(r,e)=>{O.init(r,e),r._zod.pattern=$n,r._zod.parse=(t,n)=>{if(e.coerce)try{t.value=Number(t.value)}catch{}let o=t.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return t;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:String(o):void 0;return t.issues.push({expected:"number",code:"invalid_type",input:o,inst:r,...i?{received:i}:{}}),t}});var Dn=b("$ZodBoolean",(r,e)=>{O.init(r,e),r._zod.pattern=Fn,r._zod.parse=(t,n)=>{if(e.coerce)try{t.value=!!t.value}catch{}let o=t.value;return typeof o=="boolean"||t.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:r}),t}});function Zs(r,e){let t=at(r._zod.def.checks);if(!t.length)return;let n=Math.min(...t.map(i=>i[0])),o=r._zod.parse;r._zod.parse=(i,s)=>{let a=e(i.value);if(a>n&&!s?.skipChecks&&s?.direction!=="backward"){for(let[u,c]of at(r._zod.def.checks))if(a>u&&c._zod.def.when(i)){let l=i.issues.length;return c._zod.check(i),i.issues[l].continue=!1,Ce(i.issues,l,r),i}}return o(i,s)}}var js=r=>Array.isArray(r)?r.length:-1;function kn(r,e,t){r.issues.length&&e.issues.push(...st(t,r.issues)),e.value[t]=r.value}var Zn=b("$ZodArray",(r,e)=>{O.init(r,e);let t=ae.memoizer;t?.attach(r),r._zod.parse=(n,o)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:r}),n;n.value=t?t.alloc(r,n,Array(i.length),o):Array(i.length);let s=[],a=o?.abortEarly;for(let u=0;u<i.length;u++){let c=i[u],l=e.element._zod.run({value:c,issues:[]},o);if(l instanceof Promise)s.push(l.then(f=>kn(f,n,u)));else if(kn(l,n,u),a&&l.issues.length!==0&&q(l))break}return s.length?Promise.all(s).then(()=>n):n},Zs(r,js)});function ut(r,e,t,n,o,i){let s=t in n,a=i==="optional";if(!(!s&&a&&o==="optional")){if(r.issues.length){if(o!==void 0&&a&&!s)return;e.issues.push(...st(t,r.issues))}if(!s&&o===void 0){r.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[t]});return}r.value===void 0?(s||o==="defaulted"&&!a)&&(e.value[t]=void 0):e.value[t]=r.value}}var Us=[];function Bs(r){let e=Object.keys(r.shape),t=Object.getOwnPropertySymbols(r.shape),n=t.length?t:Us,o=n.length?[...e,...n]:e;for(let s of o)if(!r.shape?.[s]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(s)}": expected a Zod schema`);let i=Yt(r.shape);return{...r,allKeys:o,symbolKeys:n,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(i)}}function Hs(r,e,t,n,o,i,s){let a=[],u=o.keySet,c=o.catchall._zod,l=c.def.type,f=c.optin,p=c.optout,d=0;for(let h in e){if(s&&t.issues.length!==d){if(q(t,d))break;d=t.issues.length}if(u.has(h))continue;if(h==="__proto__"){l==="never"&&a.push(h);continue}if(l==="never"){a.push(h);continue}let g=c.run({value:e[h],issues:[]},n);g instanceof Promise?r.push(g.then(w=>ut(w,t,h,e,f,p))):ut(g,t,h,e,f,p)}return a.length&&t.issues.push({code:"unrecognized_keys",keys:a,input:e,inst:i,continue:!0}),r.length?Promise.all(r).then(()=>t):t}var jn=b("$ZodObject",(r,e)=>{O.init(r,e);let t=Object.getOwnPropertyDescriptor(e,"shape"),n=t?.get?t.get.raw:e.shape??{};if(n){let c=()=>{let l={...n};return Object.defineProperty(e,"shape",{value:l}),c.raw=l,l};c.raw=n,Object.defineProperty(e,"shape",{get:c})}let o=rt(()=>Bs(e));D(r,"propValues",c=>{let l=c.def.shape,f={};for(let p in l){let d=l[p]._zod;if(d.values){Object.prototype.hasOwnProperty.call(f,p)||Se(f,p,new Set);for(let h of d.values)f[p].add(h);d.optin!==void 0&&f[p].add(void 0)}}return f});let i=Fe,s=e.catchall,a,u=ae.memoizer;u?.attach(r),r._zod.parse=(c,l)=>{a??(a=o.value);let f=c.value;if(!i(f))return c.issues.push({expected:"object",code:"invalid_type",input:f,inst:r}),c;c.value=u?u.alloc(r,c,{},l):{};let p=[],d=a.shape,h=l?.abortEarly,g=c.issues.length;for(let w of a.allKeys){if(h&&c.issues.length!==g){if(q(c,g))break;g=c.issues.length}if(w==="__proto__")continue;let _=d[w],v=_._zod.optin,R=_._zod.optout,I=_._zod.run({value:f[w],issues:[]},l);I instanceof Promise?p.push(I.then(x=>ut(x,c,w,f,v,R))):ut(I,c,w,f,v,R)}return s?Hs(p,f,c,l,o.value,r,h===!0):p.length?Promise.all(p).then(()=>c):c}});var Un=b("$ZodEnum",(r,e)=>{O.init(r,e);let t=tt(e.entries),n=new Set(t);r._zod.values=n,D(r,"pattern",o=>{let i=tt(o.def.entries).filter(s=>Qt.has(typeof s));return new RegExp(i.length?`^(${i.map(s=>Ae(s.toString())).join("|")})$`:"^[^\\s\\S]$")}),r._zod.parse=(o,i)=>{let s=o.value;return n.has(s)||o.issues.push({code:"invalid_value",values:t,input:s,inst:r}),o}}),Bn=b("$ZodLiteral",(r,e)=>{O.init(r,e);let t=new Set(e.values);r._zod.values=t,D(r,"pattern",n=>{let o=n.def.values;return new RegExp(o.length?`^(${o.map(i=>typeof i=="string"?Ae(i):i?Ae(i.toString()):String(i)).join("|")})$`:"^[^\\s\\S]$")}),r._zod.parse=(n,o)=>{let i=n.value;return t.has(i)||n.issues.push({code:"invalid_value",values:e.values,input:i,inst:r}),n}});function Rn(r,e){return r.value=e.issues.length?void 0:e.value,r}var Hn=b("$ZodOptional",(r,e)=>{O.init(r,e),D(r,"optin",t=>t.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),r._zod.optout="optional",D(r,"values",t=>{let n=t.def.innerType._zod.values;return n?new Set([...n,void 0]):void 0}),D(r,"pattern",t=>{let n=t.def.innerType._zod.pattern;return n?new RegExp(`^(${Xt(n.source)})?$`):void 0}),r._zod.parse=(t,n)=>{if(t.value===void 0){if(e.innerType._zod.optin!=="defaulted")return t;let o=e.innerType._zod.run({value:t.value,issues:[]},n);return o instanceof Promise?o.then(i=>Rn(t,i)):Rn(t,o)}return e.innerType._zod.run(t,n)}});var Kn=b("$ZodDefault",(r,e)=>{O.init(r,e),r._zod.optin="defaulted",D(r,"values",t=>t.def.innerType._zod.values),r._zod.parse=(t,n)=>{if(n.direction==="backward")return e.innerType._zod.run(t,n);if(t.value===void 0)return t.value=e.defaultValue,t;let o=e.innerType._zod.run(t,n);return o instanceof Promise?o.then(i=>zn(i,e)):zn(o,e)}});function zn(r,e){return r.value===void 0&&(r.value=e.defaultValue),r}function On(r,e,t,n){return e.issues.length?(r.value=t.catchValue({...e,value:r.value,error:{issues:e.issues.map(o=>re(o,n,ce()))},input:r.value}),r):(r.value=e.value,e.memo&&(r.memo=!0),r)}var Gn=b("$ZodCatch",(r,e)=>{O.init(r,e),D(r,"optin",t=>t.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),D(r,"optout",t=>t.def.innerType._zod.optout),D(r,"values",t=>t.def.innerType._zod.values),r._zod.parse=(t,n)=>{if(n.direction==="backward")return e.innerType._zod.run(t,n);let o=e.innerType._zod.run({value:t.value,issues:[]},n);return o instanceof Promise?o.then(i=>On(t,i,e,n)):On(t,o,e,n)}});var Wn=b("$ZodCustom",(r,e)=>{Re.init(r,e),O.init(r,e),r._zod.parse=(t,n)=>t,r._zod.check=t=>{let n=t.value,o=e.fn(n);if(o instanceof Promise)return o.then(i=>Tn(i,t,n,r));Tn(o,t,n,r)}});function Tn(r,e,t,n){if(!r){let o={code:"custom",input:t,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(ct(o))}}function qn(r){return r.checks&&(r.checks=[...r.checks]),r}function Vn(r,e){return new r(qn({type:"string",...N(e)}))}function Xn(r,e){return new r(qn({type:"number",checks:[],...N(e)}))}function Jn(r,e){return new r({type:"boolean",...N(e)})}function pr(r,e){return new In({check:"string_format",format:"regex",...N(e),pattern:r})}function Qn(r,e,t){let n=N(t);return n.abort??(n.abort=!0),new r({type:"custom",check:"custom",fn:e,...n})}var j=b("ZodMiniType",(r,e)=>{if(!r._zod)throw new Error("Uninitialized schema in ZodMiniType.");O.init(r,e),r.def=e,r.type=e.type},{get with(){return this.check},set with(r){U(this,"with",r)},parse(r,e){return ar(this,r,e,{callee:this.parse})},parseAsync(r,e){return cr(this,r,e,{callee:this.parseAsync})},safeParse(r,e){return ur(this,r,e)},safeParseAsync(r,e){return lr(this,r,e)},check(...r){let e=this.def;return this.clone({...e,checks:[...e.checks??[],...r.map(t=>typeof t=="function"?{_zod:{check:t,def:{check:"custom"},onattach:[]}}:t)]},{parent:!0})},clone(r,e){return L(this,r,e)},brand(){return this},register(r,e){return r.add(this,e),this},apply(r,...e){return e.length===0?r(this):r(this,...e)}}),Ws=b("ZodMiniString",(r,e)=>{Ln.init(r,e),j.init(r,e)});function ue(r){return Vn(Ws,r)}var qs=b("ZodMiniNumber",(r,e)=>{Nn.init(r,e),j.init(r,e)});function dr(r){return Xn(qs,r)}var Vs=b("ZodMiniBoolean",(r,e)=>{Dn.init(r,e),j.init(r,e)});function ne(r){return Jn(Vs,r)}var Xs=b("ZodMiniArray",(r,e)=>{Zn.init(r,e),j.init(r,e)});function hr(r,e){return new Xs({type:"array",element:r,...N(e)})}var Js=b("ZodMiniObject",(r,e)=>{jn.init(r,e),j.init(r,e),nr(r,"shape",t=>t._zod.def.shape,!1)});function gr(r,e){let t={type:"object",shape:r??{},...N(e)};return new Js(t)}var Qs=b("ZodMiniEnum",(r,e)=>{Un.init(r,e),j.init(r,e),r.options=[...r._zod.values]});function Yn(r,e){let t=Array.isArray(r)?Object.fromEntries(r.map(n=>[n,n])):r;return new Qs({type:"enum",entries:t,...N(e)})}var Ys=b("ZodMiniLiteral",(r,e)=>{Bn.init(r,e),j.init(r,e)});function eo(r,e){return new Ys({type:"literal",values:Array.isArray(r)?r:[r],...N(e)})}var ea=b("ZodMiniOptional",(r,e)=>{Hn.init(r,e),j.init(r,e)});function k(r){return new ea({type:"optional",innerType:r})}var ta=b("ZodMiniDefault",(r,e)=>{Kn.init(r,e),j.init(r,e)});function ge(r,e){return new ta({type:"default",innerType:r,get defaultValue(){return typeof e=="function"?e():ot(e)}})}var ra=b("ZodMiniCatch",(r,e)=>{Gn.init(r,e),j.init(r,e)});function to(r,e){return new ra({type:"catch",innerType:r,catchValue:typeof e=="function"?e:V.constantCatch(e)})}var na=b("ZodMiniCustom",(r,e)=>{Wn.init(r,e),j.init(r,e)});function mr(r,e){return Qn(na,r??(()=>!0),e)}var ro="https://in.dev.heycatch.ai",ze="dev",Oe="0.8.4-dev.2561",no="phc_CqKdgm7xbFBs3mSdtqzrHNTfzTRKrwRmCrEB9aftENY9";function me(){return typeof globalThis.window<"u"}function oo(r=ze){return r!=="dev"?null:`[HeyCatch] WARNING: this is an internal development build (v${Oe}). Events are being sent to the HeyCatch development environment and will NEVER appear in your dashboard. Reinstall the latest stable version - resolve it with \`npm view @heycatch/sdk version\` - or re-run the install guide: https://heycatch.ai/agents.md`}var lt=["X-HeyCatch-Session-Id","X-HeyCatch-Window-Id","X-HeyCatch-Distinct-Id"],oe="unknown",aa=["localStorage","cookie","memory","localStorage+cookie","sessionStorage"];var io=gr({projectKey:ue({error:'config.projectKey is missing or malformed \u2014 expected a string starting with "hck_pk_". Copy it from your project page in the HeyCatch dashboard.'}).check(pr(/^hck_pk_/,{error:'config.projectKey is missing or malformed \u2014 expected a string starting with "hck_pk_". Copy it from your project page in the HeyCatch dashboard.'})),tracingHosts:ge(hr(ue()),[]),install:ge(gr({framework:ge(ue(),oe),frameworkVersion:ge(ue(),oe),agent:ge(ue(),oe)}),{framework:oe,frameworkVersion:oe,agent:oe}),autocapture:k(ne()),maskAllText:k(ne()),maskAllElementAttributes:k(ne()),propertyDenylist:k(hr(ue())),sanitizeProperties:k(mr(r=>typeof r=="function")),beforeSend:k(mr(r=>typeof r=="function"||Array.isArray(r)&&r.every(e=>typeof e=="function"))),persistence:k(Yn(aa)),disablePersistence:k(ne()),cookieExpirationDays:k(dr()),optOutCapturingByDefault:k(ne()),respectDnt:k(ne()),requestBatching:k(ne()),flushIntervalMs:k(dr()),site:to(k(eo("landing")),r=>{let e=typeof r.value=="string"?JSON.stringify(r.value):`a ${typeof r.value}`;console.error(`[HeyCatch] config.site must be 'landing' or omitted - got ${e}. Ignoring it; this project is reported as untagged.`)})}),so=["nextjs","vite-react","react","vue","svelte","astro","angular","react-native","web"],ao=["lovable","bolt","v0","replit","cursor","claude-code","codex","windsurf","other"];var _e=require("path");function uo(){let r=ca();return async e=>{for(let t of e)t.module=r(t.filename);return e}}function ca(r=process.argv[1]?(0,_e.dirname)(process.argv[1]):process.cwd(),e=_e.sep==="\\"){let t=e?co(r):r;return n=>{if(!n)return;let o=e?co(n):n,{dir:i,base:s,ext:a}=_e.posix.parse(o);(a===".js"||a===".mjs"||a===".cjs")&&(s=s.slice(0,-1*a.length));let u=decodeURIComponent(s);i||(i=".");let c=i.lastIndexOf("/node_modules");if(c>-1)return`${i.slice(c+14).replace(/\//g,".")}:${u}`;if(i.startsWith(t)){let l=i.slice(t.length+1).replace(/\//g,".");return l?`${l}:${u}`:u}return u}}function co(r){return r.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var _r=r=>{if("flags"in r){let e=lo(r.flags),t=fo(r.flags);return{...r,featureFlags:e,featureFlagPayloads:t}}{let e=r.featureFlags??{},t=Object.fromEntries(Object.entries(r.featureFlagPayloads||{}).map(([o,i])=>[o,ft(i)])),n=Object.fromEntries(Object.entries(e).map(([o,i])=>[o,ua(o,i,t[o])]));return{...r,featureFlags:e,featureFlagPayloads:t,flags:n}}};function ua(r,e,t){return{key:r,enabled:typeof e=="string"?!0:e,variant:typeof e=="string"?e:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:t?JSON.stringify(t):void 0,description:void 0}}}var lo=r=>Object.fromEntries(Object.entries(r??{}).map(([e,t])=>[e,Te(t)]).filter(([,e])=>e!==void 0)),fo=r=>{let e=r??{};return Object.fromEntries(Object.keys(e).filter(t=>{let n=e[t];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(t=>{let n=e[t].metadata?.payload;return[t,n?ft(n):void 0]}))},Te=r=>r===void 0?void 0:r.variant??r.enabled,ft=r=>{if(typeof r!="string")return r;try{return JSON.parse(r)}catch{return r}};var la=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Me=(r,e=[])=>{let t={},n=o=>{r[o]!==void 0&&(t[o]=r[o])};return la.forEach(n),e.forEach(n),t};var T=(function(r){return r.AnonymousId="anonymous_id",r.DistinctId="distinct_id",r.Props="props",r.EnablePersonProcessing="enable_person_processing",r.PersonMode="person_mode",r.FeatureFlagDetails="feature_flag_details",r.FeatureFlags="feature_flags",r.FeatureFlagPayloads="feature_flag_payloads",r.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",r.BootstrapFeatureFlags="bootstrap_feature_flags",r.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",r.OverrideFeatureFlags="override_feature_flags",r.Queue="queue",r.AiQueue="ai_queue",r.LogsQueue="logs_queue",r.OptedOut="opted_out",r.SessionId="session_id",r.SessionStartTimestamp="session_start_timestamp",r.SessionLastTimestamp="session_timestamp",r.PersonProperties="person_properties",r.GroupProperties="group_properties",r.InstalledAppBuild="installed_app_build",r.InstalledAppVersion="installed_app_version",r.SessionReplay="session_replay",r.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",r.SurveyLastSeenDate="survey_last_seen_date",r.SurveysSeen="surveys_seen",r.Surveys="surveys",r.RemoteConfig="remote_config",r.FlagsEndpointWasHit="flags_endpoint_was_hit",r.DeviceId="device_id",r})({});function yr(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var pa="NativeGzipValidationError",da=31,ha=139,ga=8,ma=r=>r.length>=2&&r[0]===da&&r[1]===ha;var Le,_a=()=>{if(Le)return Le;Le=[];for(let r=0;r<256;r++){let e=r;for(let t=0;t<8;t++)e=1&e?3988292384^e>>>1:e>>>1;Le[r]=e>>>0}return Le},ya=r=>{let e=_a(),t=4294967295;for(let n=0;n<r.length;n++)t=e[(t^r[n])&255]^t>>>8;return(4294967295^t)>>>0},pt=r=>{let e=new Error(`Native gzip produced invalid output: ${r}`);throw e.name=pa,e},va=async(r,e)=>{r.size<18&&pt("too-short");let t=new Uint8Array(await r.slice(0,10).arrayBuffer());(!ma(t)||t[2]!==ga)&&pt("invalid-header");let n=new DataView(await r.slice(r.size-8).arrayBuffer());n.getUint32(0,!0)!==ya(e)&&pt("invalid-crc");let o=e.length>>>0;n.getUint32(4,!0)!==o&&pt("invalid-size")};async function le(r,e=!0,t){try{let n=new TextEncoder().encode(r),o=new globalThis.CompressionStream("gzip"),i=o.writable.getWriter(),s=i.write(n).then(()=>i.close()).catch(async c=>{try{await i.abort(c)}catch{}throw c}),a=new Response(o.readable).blob(),[u]=await Promise.all([a,s]);return await va(u,n),u}catch(n){if(t?.rethrow)throw n;return e&&console.error("Failed to gzip compress data",n),null}}var ba=["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"],po=function(r,e=[]){if(!r)return!1;let t=r.toLowerCase();return ba.concat(e).some(n=>{let o=n.toLowerCase();return t.indexOf(o)!==-1})};function ye(r){let e=[];return JSON.stringify(r,function(t,n){if(typeof n=="bigint")return n.toString();if(!(typeof n=="function"||typeof n=="symbol")){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;e.length>0&&e[e.length-1]!==this;)e.pop();if(e.includes(n))return"[Circular]";e.push(n)}return n}})??"null"}var wa=Array.isArray,ho=Object.prototype,th=ho.hasOwnProperty,dt=ho.toString,H=wa||function(r){return dt.call(r)==="[object Array]"};var Ne=r=>r===Object(r)&&!H(r);var fe=r=>r===void 0,J=r=>dt.call(r)=="[object String]",go=r=>J(r)&&r.trim().length===0,mo=r=>r===null;var De=r=>dt.call(r)=="[object Number]"&&r===r;var _o=r=>dt.call(r)==="[object Boolean]";var yo=r=>r instanceof Error;function ht(r){return r===null||typeof r!="object"}function pe(r,e){return Object.prototype.toString.call(r)===`[object ${e}]`}function vo(r){return pe(r,"ErrorEvent")}function ve(r){return typeof Event<"u"&&Pa(r,Event)}function bo(r){return pe(r,"Object")}function Pa(r,e){try{return r instanceof e}catch{return!1}}function Ze(r,e,t,n,o){return e>t&&(n.warn("min cannot be greater than max."),e=t),De(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: "+o),Ze(o||t,e,t,n))}var Ea=864e5,$a=1,Fa=10;function xo(r={}){return{refillRate:r.exceptionRateLimiterRefillRate??r.__exceptionRateLimiterRefillRate??$a,bucketSize:r.exceptionRateLimiterBucketSize??r.__exceptionRateLimiterBucketSize??Fa}}var gt=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Ze(e.bucketSize,0,100,e._logger),this._refillRate=Ze(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Ze(e.refillInterval,0,Ea,e._logger)}_applyRefill(e,t){let n=t-e.lastAccess,o=Math.floor(n/this._refillInterval);if(o>0){let i=o*this._refillRate;e.tokens=Math.min(e.tokens+i,this._bucketSize),e.lastAccess=e.lastAccess+o*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),n=String(e),o=this._buckets[n];return o?this._applyRefill(o,t):(o={tokens:this._bucketSize,lastAccess:t},this._buckets[n]=o),o.tokens===0?!0:(o.tokens--,o.tokens===0&&this._onBucketRateLimited?.(e),o.tokens===0)}stop(){this._buckets={}}};var mt="0123456789abcdef",_t=class r{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new r(e);throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,n,o){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(o)||e<0||t<0||n<0||o<0||e>0xffffffffffff||t>4095||n>1073741823||o>4294967295)throw new RangeError("invalid field value");let i=new Uint8Array(16);return i[0]=e/2**40,i[1]=e/2**32,i[2]=e/2**24,i[3]=e/2**16,i[4]=e/256,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]=o>>>24,i[13]=o>>>16,i[14]=o>>>8,i[15]=o,new r(i)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;default:break}if(t){let n=new Uint8Array(16);for(let o=0;o<16;o+=4){let i=parseInt(t.substring(2*o,2*o+8),16);n[o+0]=i>>>24,n[o+1]=i>>>16,n[o+2]=i>>>8,n[o+3]=i}return new r(n)}throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=mt.charAt(this.bytes[t]>>>4),e+=mt.charAt(15&this.bytes[t]),(t===3||t===5||t===7||t===9)&&(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=mt.charAt(this.bytes[t]>>>4),e+=mt.charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw new Error("unreachable");if(e<=7)return this.bytes.every(t=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(t=>t===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new r(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}},vr=class{constructor(e){this.timestamp=0,this.counter=0,this.random=e??Sa()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let n=this.generateOrAbortCore(e,t);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(e,t)),n}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return _t.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,_t.ofInner(e)}},Sa=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),wo,M=()=>Ia().toString(),Ia=()=>(wo||(wo=new vr)).generate();var yt=class{add(e){let t=M(),n=++this.nextId;return this.promiseByIds[t]={id:n,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map(n=>n.promise),t=e.length;for(;t>0;)await Promise.all(e),e=Object.values(this.promiseByIds).map(n=>n.promise),t=e.length}getPromises(e=[],t=this.nextId){let n=new Set(e);return Object.values(this.promiseByIds).filter(o=>o.id<=t&&!n.has(o.promise)).map(o=>o.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}};function Aa(r=console){return{log:r.log.bind(r),warn:r.warn.bind(r),error:r.error.bind(r),debug:r.debug.bind(r)}}var Po=(r,e,t)=>{function n(i,...s){e(()=>{let a=t[i];a(r,...s)})}return{debug:(...i)=>{n("debug",...i)},info:(...i)=>{n("log",...i)},warn:(...i)=>{n("warn",...i)},error:(...i)=>{n("error",...i)},critical:(...i)=>{t.error(r,...i)},createLogger:i=>Po(`${r} ${i}`,e,t)}},Ca=r=>r();function Eo(r,e=Ca){return Po(r,e,Aa())}var xe="Mobile",bt="iOS",be="Android",Ao="Tablet",dh=be+" "+Ao;var Ra="Apple",hh=Ra+" Watch",Co="Safari",xt="BlackBerry",ko="Samsung",za=ko+"Browser",Oa=ko+" Internet",wt="Chrome",Ta=wt+" OS",Ma=wt+" "+bt,Ro="Internet Explorer",La=Ro+" "+xe,xr="Opera",gh=xr+" Mini",zo="Edge",Na="Microsoft "+zo,wr="Firefox",Da=wr+" "+bt,Pr="Nintendo",Er="PlayStation",vt="Xbox",Za=be+" "+xe,ja=xe+" "+Co,je="Windows",Ua=je+" Phone";var Oo="Generic",mh=Oo+" "+xe.toLowerCase(),_h=Oo+" "+Ao.toLowerCase(),Ba="Konqueror",Ha="Oculus Browser",$o="Vivaldi",Ka="Yandex",Fo="Whale",Ga="DuckDuckGo",Wa="Pale Moon",So="Waterfox",Io="Brave",qa="Google Search App",E="(\\d+(\\.\\d+)?)",br=new RegExp("Version/"+E);var yh=new RegExp(vt,"i"),vh=new RegExp(Er+" \\w+","i"),bh=new RegExp(Pr+" \\w+","i"),Va=new RegExp(xt+"|PlayBook|BB10","i"),Xa={"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"};var xh={[La]:[new RegExp("rv:"+E)],[Na]:[new RegExp(zo+"?\\/"+E)],[wt]:[new RegExp("("+wt+"|CrMo)\\/"+E)],[Ma]:[new RegExp("CriOS\\/"+E)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+E)],[Co]:[br],[ja]:[br],[xr]:[new RegExp("("+xr+"|OPR)\\/"+E)],[wr]:[new RegExp(wr+"\\/"+E)],[Da]:[new RegExp("FxiOS\\/"+E)],[Ba]:[new RegExp("Konqueror[:/]?"+E,"i")],[xt]:[new RegExp(xt+" "+E),br],[Za]:[new RegExp("android\\s"+E,"i")],[Oa]:[new RegExp(za+"\\/"+E)],[Ha]:[new RegExp("OculusBrowser\\/"+E)],[$o]:[new RegExp($o+"\\/"+E)],[Ka]:[new RegExp("YaBrowser\\/"+E)],[Fo]:[new RegExp(Fo+"\\/"+E)],[Io]:[new RegExp(Io+"\\/"+E)],[Ga]:[new RegExp("(DuckDuckGo|Ddg)\\/"+E)],[Wa]:[new RegExp("PaleMoon\\/"+E)],[So]:[new RegExp(So+"\\/"+E)],[qa]:[new RegExp("GSA\\/"+E)],[Ro]:[new RegExp("(rv:|MSIE )"+E)],Mozilla:[new RegExp("rv:"+E)]};var wh=[[new RegExp(vt+"; "+vt+" (.*?)[);]","i"),r=>[vt,r&&r[1]||""]],[new RegExp(Pr,"i"),[Pr,""]],[new RegExp(Er,"i"),[Er,""]],[Va,[xt,""]],[new RegExp(je,"i"),(r,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Ua,""];if(new RegExp(xe).test(e)&&!/IEMobile\b/.test(e))return[je+" "+xe,""];let t=/Windows NT ([0-9.]+)/i.exec(e);if(t&&t[1]){let n=t[1],o=Xa[n]||"";return/arm/i.test(e)&&(o="RT"),[je,o]}return[je,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,r=>{if(r&&r[3]){let e=[r[3],r[4],r[5]||"0"];return[bt,e.join(".")]}return[bt,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,r=>{let e="";return r&&r.length>=3&&(e=fe(r[2])?r[3]:r[2]),["watchOS",e]}],[new RegExp("("+be+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+be+")","i"),r=>{if(r&&r[2]){let e=[r[2],r[3],r[4]||"0"];return[be,e.join(".")]}return[be,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,r=>{let e=["Mac OS X",""];if(r&&r[1]){let t=[r[1],r[2],r[3]||"0"];e[1]=t.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Ta,""]],[/Linux|debian/i,["Linux",""]]];var To="utf8",Ja=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Qa(r){return typeof r=="string"&&Ja.test(r)}function Pt(r,e){return Qa(r)?r:e()}function Mo(r){return r?.replace(/\/+$/,"")}async function Lo(r,e){let t=null;for(let n=0;n<e.retryCount+1;n++){n>0&&await new Promise(o=>setTimeout(o,e.retryDelay));try{return await r()}catch(o){if(t=o,!e.retryCheck(o))throw o}}throw t}function $r(){return new Date().toISOString()}function A(r,e){let t=setTimeout(r,e);return t?.unref&&t?.unref(),t}var No=r=>r instanceof Error;function Fr(r){return Promise.all(r.map(e=>(e??Promise.resolve()).then(t=>({status:"fulfilled",value:t}),t=>({status:"rejected",reason:t}))))}var ec={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},Oh=ec.info;function Sr(r){if(_o(r))return{boolValue:r};if(typeof r=="number")return Number.isFinite(r)?Number.isInteger(r)?{intValue:r}:{doubleValue:r}:{stringValue:String(r)};if(typeof r=="string")return{stringValue:r};if(H(r))return{arrayValue:{values:r.map(e=>Sr(e))}};try{return{stringValue:JSON.stringify(r)}}catch{return{stringValue:String(r)}}}function Ue(r){let e=[];for(let t in r){let n=r[t];mo(n)||fe(n)||e.push({key:t,value:Sr(n)})}return e}var Be=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ir(r){return String(r)+"000000"}function Ar(r,e,t,n){let o="";return n&&(o=Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(n[s])}`).join(",")),`${r}\0${e}\0${t??""}\0${o}`}function Do(r,e){for(let t=0;t<e.length;t++)if(r<=e[t])return t;return e.length}function Cr(r,e,t){return{...r.resourceAttributes,"service.name":r.serviceName||"unknown_service",...r.environment&&{"deployment.environment":r.environment},...r.serviceVersion&&{"service.version":r.serviceVersion},"telemetry.sdk.name":e,"telemetry.sdk.version":t}}function kr(r,e,t,n){return{resourceMetrics:[{resource:{attributes:Ue(e)},scopeMetrics:[{scope:{name:t,version:n},metrics:r}]}]}}function Et(r){let e=r?.resourceAttributes;return{serviceName:e?.["service.name"]??r?.serviceName,serviceVersion:e?.["service.version"]??r?.serviceVersion,environment:e?.["deployment.environment"]??r?.environment,resourceAttributes:e,beforeSend:r?.beforeSend,flushIntervalMs:r?.flushIntervalMs??1e4,maxSeriesPerFlush:r?.maxSeriesPerFlush??1e3}}var Zo=1,He=class{constructor(e,t,n){this._instance=e,this._config=t,this._logger=n,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._generation=0}count(e,t=1,n){this._capture({name:e,type:"count",value:t,unit:n?.unit,attributes:n?.attributes})}gauge(e,t,n){this._capture({name:e,type:"gauge",value:t,unit:n?.unit,attributes:n?.attributes})}histogram(e,t,n){this._capture({name:e,type:"histogram",value:t,unit:n?.unit,attributes:n?.attributes})}flush(){let e=this._flushPromise,n=(async()=>{e&&await e.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===n&&(this._flushPromise=null)});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._clearFlushTimer(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(this._instance.isDisabled||this._instance.optedOut)return;let t=this._runBeforeSend(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this._logger.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&t.value<0)return void this._logger.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let n,o;try{n=t.attributes?{...t.attributes}:void 0,o=Ar(t.type,t.name,t.unit,n)}catch(a){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,a);return}let i=this._series.get(o);if(!i){if(!this._admitNewSeries())return;i={name:t.name,type:t.type,unit:t.unit,attributes:n,windowStartMs:Date.now()},this._series.set(o,i)}let s=this._typeByName.get(t.name);s===void 0?this._typeByName.set(t.name,t.type):s!==t.type&&!this._typeCollisionWarned.has(t.name)&&(this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${s}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`)),this._fold(i,t.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush?!0:(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:new Array(Be.length+1).fill(0)});let n=e.hist;n.count+=1,n.sum+=t,n.min=Math.min(n.min,t),n.max=Math.max(n.max,t),n.bucketCounts[Do(t,Be)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let n=H(t)?t:[t],o=e;for(let i of n)try{let s=i(o);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;o=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return o}_armFlushTimer(){this._flushTimer||(this._flushTimer=A(()=>{this._flushTimer=void 0,this.flush().catch(e=>{this._logger.error("Metrics flush failed:",e)})},this._config.flushIntervalMs))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}async _doFlush(){if(this._series.size===0)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._armFlushTimer();return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(e){return kr(this._buildMetrics(e),Cr(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=Ir(Date.now()),n=new Map;for(let o of e.values()){let i=Ar(o.type,o.name,o.unit,void 0),s=n.get(i);s||(s={name:o.name,...o.unit&&{unit:o.unit}},o.type==="count"?s.sum={aggregationTemporality:Zo,isMonotonic:!0,dataPoints:[]}:o.type==="gauge"?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:Zo,dataPoints:[]},n.set(i,s));let a=Ue(o.attributes??{}),u=Ir(o.windowStartMs);if(o.type==="count"){let c={attributes:a,startTimeUnixNano:u,timeUnixNano:t,asDouble:o.total??0};s.sum.dataPoints.push(c)}else if(o.type==="gauge"){let c={attributes:a,timeUnixNano:t,asDouble:o.last??0};s.gauge.dataPoints.push(c)}else if(o.hist){let c={attributes:a,startTimeUnixNano:u,timeUnixNano:t,count:o.hist.count,sum:o.hist.sum,min:o.hist.min,max:o.hist.max,bucketCounts:o.hist.bucketCounts,explicitBounds:Be};s.histogram.dataPoints.push(c)}}return Array.from(n.values())}_mergeWindowBack(e){for(let[t,n]of e){let o=this._series.get(t);if(!o){this._admitNewSeries()&&this._series.set(t,n);continue}switch(o.windowStartMs=Math.min(o.windowStartMs,n.windowStartMs),o.type){case"count":o.total=(o.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(o.hist){o.hist.count+=n.hist.count,o.hist.sum+=n.hist.sum,o.hist.min=Math.min(o.hist.min,n.hist.min),o.hist.max=Math.max(o.hist.max,n.hist.max);for(let i=0;i<o.hist.bucketCounts.length;i++)o.hist.bucketCounts[i]+=n.hist.bucketCounts[i]}else o.hist=n.hist;break}}}};var $t=class{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(n=>n!==t)}}emit(e,t){for(let n of this.events[e]||[])n(t);for(let n of this.events["*"]||[])n(e,t)}};var z={};Kt(z,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>Ct,DOMExceptionCoercer:()=>Tr,EXCEPTION_STEP_INTERNAL_FIELDS:()=>Xe,ErrorCoercer:()=>Ge,ErrorEventCoercer:()=>Mr,ErrorPropertiesBuilder:()=>Ke,EventCoercer:()=>Lr,ExceptionStepsBuffer:()=>jr,ObjectCoercer:()=>qe,PrimitiveCoercer:()=>Ve,PromiseRejectionEventCoercer:()=>Nr,ReduceableCache:()=>Dr,StringCoercer:()=>We,chromeStackLineParser:()=>Rr,createDefaultStackParser:()=>Or,createStackParser:()=>Jo,geckoStackLineParser:()=>zr,getUtf8ByteLength:()=>Yo,nodeStackLineParser:()=>Wo,opera10StackLineParser:()=>Ho,opera11StackLineParser:()=>Ko,resolveExceptionStepsConfig:()=>Zr,reverseAndStripFrames:()=>Xo,stripReservedExceptionStepFields:()=>wc,winjsStackLineParser:()=>Bo});var Ft,jo,St;function Uo(r){let e=globalThis._posthogChunkIds;if(!e)return;let t=Object.keys(e);return St&&t.length===jo||(jo=t.length,St=t.reduce((n,o)=>{Ft||(Ft={});let i=Ft[o];if(i)n[i[0]]=i[1];else{let s=r(o);for(let a=s.length-1;a>=0;a--){let c=s[a]?.filename,l=e[o];if(c&&l){n[c]=l,Ft[o]=[c,l];break}}}return n},{})),St}var oc=4,Ke=class{constructor(e,t,n=[]){this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t={}){let o=t&&t.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(o,t,0).apply(e),a=this.buildParsingContext(t),u=this.parseStacktrace(s,a);return{$exception_list:this.convertToExceptionList(u,o),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&H(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let n;e.cause!=null&&(n=this.parseStacktrace(e.cause,t));let o;return e.stack!=""&&e.stack!=null&&(o=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),{...e,cause:n,stack:o}}applyChunkIds(e,t){return e.map(n=>(n.filename&&t&&(n.chunk_id=t[n.filename]),n))}applyCoercers(e,t){for(let n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let n of this.modifiers)t=await n(t);return t}convertToExceptionList(e,t){let n={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};e.stack&&(n.stacktrace={type:"raw",frames:e.stack});let o=[n];return e.cause!=null&&o.push(...this.convertToExceptionList(e.cause,{...t,handled:!0})),o}buildParsingContext(e){return{chunkIdMap:Uo(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,n=0){let o=(s,a)=>{if(a<=oc){let u=this.buildCoercingContext(e,t,a);return this.applyCoercers(s,u)}};return{...t,syntheticException:n==0?t.syntheticException:void 0,mechanism:e,apply:s=>o(s,n),next:s=>o(s,n+1)}}};var F="?";function K(r,e,t,n,o){let i={platform:r,filename:e,function:t==="<anonymous>"?F:t,in_app:!0};return fe(n)||(i.lineno=n),fe(o)||(i.colno=o),i}var It=(r,e)=>{let t=r.indexOf("safari-extension")!==-1,n=r.indexOf("safari-web-extension")!==-1;return t||n?[r.indexOf("@")!==-1?r.split("@")[0]:F,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[r,e]};var ic=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,sc=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ac=/\((\S*)(?::(\d+))(?::(\d+))\)/,Rr=(r,e)=>{let t=ic.exec(r);if(t){let[,o,i,s]=t;return K(e,o,F,+i,+s)}let n=sc.exec(r);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=ac.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[i,s]=It(n[1]||F,n[2]);return K(e,s,i,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var cc=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,uc=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,zr=(r,e)=>{let t=cc.exec(r);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){let s=uc.exec(t[3]);s&&(t[1]=t[1]||"eval",t[3]=s[1],t[4]=s[2],t[5]="")}let o=t[3],i=t[1]||F;return[i,o]=It(i,o),K(e,o,i,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}};var lc=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,Bo=(r,e)=>{let t=lc.exec(r);return t?K(e,t[2],t[1]||F,+t[3],t[4]?+t[4]:void 0):void 0};var fc=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Ho=(r,e)=>{let t=fc.exec(r);return t?K(e,t[2],t[3]||F,+t[1]):void 0},pc=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Ko=(r,e)=>{let t=pc.exec(r);return t?K(e,t[5],t[3]||t[4]||F,+t[1],+t[2]):void 0};var dc=/^\s*[-]{4,}$/,hc=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,gc=/^Promise\.(?:all|any)$/,mc=/^index \d+$/,_c="node:internal/promise",Wo=(r,e)=>{let t=r.match(hc);if(t){let n,o,i,s,a;if(t[1]){i=t[1];let l=i.lastIndexOf(".");if(i[l-1]==="."&&l--,l>0){n=i.slice(0,l),o=i.slice(l+1);let f=n.indexOf(".Module");f>0&&(i=i.slice(f+1),n=n.slice(0,f))}s=void 0}o&&(s=n,a=o),o==="<anonymous>"&&(a=void 0,i=void 0),i===void 0&&(a=a||F,i=s?`${s}.${a}`:a);let u=t[2]?.startsWith("file://")?t[2].slice(7):t[2],c=t[5]==="native";return u?.match(/\/[A-Z]:/)&&(u=u.slice(1)),!u&&t[5]&&!c&&(u=t[5]),gc.test(i)&&mc.test(u||"")&&(u=_c),{filename:u?decodeURI(u):void 0,module:void 0,function:i,lineno:Go(t[3]),colno:Go(t[4]),in_app:yc(u||"",c),platform:e}}if(r.match(dc))return{filename:r,platform:e}};function yc(r,e=!1){return!(e||r&&!r.startsWith("/")&&!r.match(/^[A-Z]:/)&&!r.startsWith(".")&&!r.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&r!==void 0&&!r.includes("node_modules/")}function Go(r){return parseInt(r||"",10)||void 0}var qo=/\(error: (.*)\)/,Vo=50;function Xo(r){if(!r.length)return[];let e=Array.from(r);return e.reverse(),e.slice(0,Vo).map(t=>({...t,filename:t.filename||vc(e).filename,function:t.function||F}))}function vc(r){return r[r.length-1]||{}}function Or(){return Jo("web:javascript",Rr,zr)}function Jo(r,...e){return(t,n=0)=>{let o=[],i=t.split(`
|
|
2
|
-
`);for(let s=n;s<i.length;s++){let a=i[s];if(a.length>1024)continue;let u=qo.test(a)?a.replace(qo,"$1"):a;if(!u.match(/\S*Error: /)){for(let c of e){let l=c(u,r);if(l){o.push(l);break}}if(o.length>=Vo)break}}return Xo(o)}}var Tr=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let n=J(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){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return pe(e,"DOMException")}isDOMError(e){return pe(e,"DOMError")}};var Ge=class{match(e){return yo(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){let 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}};var Mr=class{constructor(){}match(e){return vo(e)&&e.error!=null}coerce(e,t){let n=t.apply(e.error);return n||{type:"ErrorEvent",value:e.message,stack:t.syntheticException?.stack,synthetic:!0}}};var bc=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,We=class{match(e){return typeof e=="string"}coerce(e,t){let[n,o]=this.getInfos(e);return{type:n??"Error",value:o??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",n=e,o=e.match(bc);return o&&(t=o[1],n=o[2]),[t,n]}};var Qo=["fatal","error","warning","log","info","debug"];function At(r,e=40){let t=Object.keys(r);if(t.sort(),!t.length)return"[object has no keys]";for(let n=t.length;n>0;n--){let o=t.slice(0,n).join(", ");if(!(o.length>e))return n===t.length||o.length<=e?o:`${o.slice(0,e)}...`}return""}var qe=class{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let n=this.getErrorPropertyFromObject(e);return n?t.apply(n):{type:this.getType(e),value:this.getValue(e),stack:t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return ve(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let o=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(o+=` with message: '${e.message}'`),o}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),n=At(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(e){return J(e)&&!go(e)&&Qo.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];if(No(n))return n}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}};var Lr=class{match(e){return ve(e)}coerce(e,t){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${At(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}};var Ve=class{match(e){return ht(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}};var Nr=class{match(e){return pe(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!ve(e))return!1;try{let t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){let n=this.getUnhandledRejectionReason(e);return ht(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.apply(n)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}};var Dr=class{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(t!==void 0)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}};var Xe={MESSAGE:"$message",TIMESTAMP:"$timestamp"},xc=new Set([Xe.MESSAGE,Xe.TIMESTAMP]),Ct={enabled:!0,max_bytes:32768};function Zr(r){return r?{enabled:r.enabled??Ct.enabled,max_bytes:Pc(r.max_bytes,Ct.max_bytes)}:{...Ct}}function wc(r){if(!r)return{sanitizedProperties:{},droppedKeys:[]};let e=[];return{sanitizedProperties:Object.keys(r).reduce((n,o)=>xc.has(o)?(e.push(o),n):(n[o]=r[o],n),{}),droppedKeys:e}}var jr=class{constructor(e){this._entries=[],this._totalBytes=0,this._config=Zr(e)}setConfig(e){this._config=Zr(e),this._trimToMaxBytes()}add(e){let t=Ec(e);if(!t)return;let n=Yo(t.json);n>this._config.max_bytes||(this._entries.push({step:t.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(e=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}};function Pc(r,e){if(!De(r)||r===1/0||r===-1/0)return e;let t=Math.floor(r);return t<0?e:t}function Ec(r){let e;try{e=ye(r)}catch{return}try{let t=JSON.parse(e);if(!Ne(t))return;let n=t,o=n[Xe.MESSAGE],i=n[Xe.TIMESTAMP];return!J(o)||o.trim().length===0||!J(i)&&!De(i)?void 0:{step:n,json:e}}catch{return}}function Yo(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;let e=encodeURIComponent(r),t=0;for(let n=0;n<e.length;n++)e[n]==="%"?(t+=1,n+=2):t+=1;return t}var Q=class extends Error{constructor(e,t){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}},ie=class extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}};var ri=(r,e)=>{for(let t of Object.keys(e))(t.startsWith("$feature/")||t==="$active_feature_flags")&&(r[t]=e[t])};async function ei(r){if(r instanceof Q){let e="";try{e=await r.text}catch{}console.error(`Error while flushing PostHog: message=${r.message}, response body=${e}`,r)}else console.error("Error while flushing PostHog",r);return Promise.resolve()}function $c(r){return typeof r=="object"&&(r instanceof Q||ni(r))}function ni(r){return r instanceof ie}function Fc(r){if(r instanceof Q)return r.status===502||r.status===504;if(!(r instanceof ie))return!1;let e=r.error;return(e?.code??e?.cause?.code)!=="ECONNREFUSED"}function we(r){return typeof r=="object"&&r instanceof Q&&r.status===413}function Je(r){return r instanceof Q?r.status===408||r.status===429||r.status>=500:ni(r)}function ti(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var Ur="default",Qe=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new Ke([new Ge,new qe,new We,new Ve],Or())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new yt,this._events=new $t,this._isInitialized=!1;let n=typeof e=="string"?e.trim():"",o=typeof t.host=="string"?t.host.trim():"",i=!n;this._logger=Eo("[PostHog]",this.logMsgIfDebug.bind(this)),i&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=Mo(o||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:Je},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||i,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!yr()||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return e();this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(T.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(T.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(T.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(n,o)=>this._logger.info(n,o));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},n={...t,...this.getCommonEventProperties()};return ri(n,t),e.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=Me(n)),{distinct_id:e.distinct_id,event:e.event,properties:n}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,n){this.wrap(()=>{let o={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",o,n)})}async identifyStatelessImmediate(e,t,n){let o={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",o,n)}captureStateless(e,t,n,o){this.wrap(()=>{let i=this.buildPayload({distinct_id:e,event:t,properties:n});this.enqueue("capture",i,o)})}async captureStatelessImmediate(e,t,n,o){let i=this.buildPayload({distinct_id:e,event:t,properties:n});await this.sendImmediate("capture",i,o)}aliasStateless(e,t,n,o){this.wrap(()=>{let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});this.enqueue("alias",i,o)})}async aliasStatelessImmediate(e,t,n,o){let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",i,o)}groupIdentifyStateless(e,t,n,o,i,s){this.wrap(()=>{let a=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{},...s||{}}});this.enqueue("capture",a,o)})}async groupIdentifyStatelessImmediate(e,t,n,o,i,s){let a=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{},...s||{}}});await this.sendImmediate("capture",a,o)}async getRemoteConfig(){await this._initPromise;let e=this.host;e==="https://us.i.posthog.com"?e="https://us-assets.i.posthog.com":e==="https://eu.i.posthog.com"&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,n,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(o=>o.json()).catch(o=>{this._logger.error("Remote config could not be loaded",o),this._events.emit("error",o)})}async getFlags(e,t={},n={},o={},i={},s=!1){await this._initPromise;let a=s?"&config=true":"",u=`${this.host}/flags/?v=2${a}`,c={token:this.apiKey,distinct_id:e,groups:t,person_properties:n,group_properties:o,...i};n.$device_id&&(c.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(c.evaluation_contexts=this.evaluationContexts);let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(c)};return this._logger.info("Flags URL",u),this.fetchWithRetry(u,l,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:Fc},this.featureFlagsRequestTimeoutMs).then(f=>f.json()).then(f=>({success:!0,response:_r(f)})).catch(f=>(this._events.emit("error",f),{success:!1,error:this.categorizeRequestError(f)}))}categorizeRequestError(e){if(e instanceof Q)return{type:"api_error",statusCode:e.status};if(e instanceof ie){let t=e.error;return t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,n={},o={},i={},s){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(e,t,n,o,i,s);if(a===void 0)return{response:void 0,requestId:void 0};let u=Te(a.response);return u===void 0&&(u=!1),{response:u,requestId:a.requestId}}async getFeatureFlagDetailStateless(e,t,n={},o={},i={},s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,n,o,i,s,[e]);return a===void 0?void 0:{response:a.flags[e],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,n={},o={},i={},s){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(t,n,o,i,s,[e]);if(!a)return;let u=a[e];return u===void 0?null:u}async getFeatureFlagPayloadsStateless(e,t={},n={},o={},i,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,n,o,i,s)).payloads}async getFeatureFlagsStateless(e,t={},n={},o={},i,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,n,o,i,s)}async getFeatureFlagsAndPayloadsStateless(e,t={},n={},o={},i,s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(e,t,n,o,i,s);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},n={},o={},i,s){await this._initPromise;let a={geoip_disable:i??this.disableGeoip};s&&(a.flag_keys_to_evaluate=s);let u=await this.getFlags(e,t,n,o,a);if(!u.success)return;let c=u.response;return c.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),c.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:c?.requestId,quotaLimited:c.quotaLimited}):c}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},o=(await this.fetchWithRetry(e,t).then(i=>{if(i.status!==200||!i.json){let s=`Surveys API could not be loaded: ${i.status}`,a=new Error(s);this._logger.error(a),this._events.emit("error",new Error(s));return}return i.json()}).catch(i=>{this._logger.error("Surveys API could not be loaded",i),this._events.emit("error",i)}))?.surveys;return o&&this._logger.info("Surveys fetched from API: ",JSON.stringify(o)),o??[]}get props(){return this._props||(this._props=this.getPersistedProperty(T.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(T.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(T.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return Ur}persistedQueueKeyForRoute(e){return T.Queue}getActiveQueueRoutes(){return[Ur]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,n){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(t,n);if(o=this.processBeforeEnqueue(o),o===null)return;o=this.normalizeMessage(o);let i=this.persistedQueueKeyForRoute(this.getQueueRouteKey(o)),s=this.getPersistedProperty(i)||[];s.length>=this.maxQueueSize&&(s.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),s.push({message:o}),this.setPersistedProperty(i,s),this._events.emit(e,o),s.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=A(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,n){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(t,n);if(o=this.processBeforeEnqueue(o),o!==null){o=this.normalizeMessage(o);try{await this.sendBatch([o],void 0,this.getQueueRouteKey(o))}catch(i){this._events.emit("error",i)}}}normalizeMessage(e){let{type:t,library:n,library_version:o,...i}=e,s=ti(i.properties)?i.properties:void 0;return n!==void 0&&s?.$lib===void 0&&(s={...s||{},$lib:n}),o!==void 0&&s?.$lib_version===void 0&&(s={...s||{},$lib_version:o}),s&&(i.properties=s),i.uuid=Pt(i.uuid,M),i}prepareMessage(e,t){let n={...e,timestamp:t?.timestamp?t?.timestamp:$r(),uuid:Pt(t?.uuid,M)};return(t?.disableGeoip??this.disableGeoip)&&(ti(n.properties)||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flush().catch(async e=>{await ei(e)})}async waitForPendingPromises(e,t=[]){let n=t.filter(i=>!!i),o=0;for(;;){let i=this.promiseQueue.getPromises([...n,...this.flushPromises],e);if(i.length===0)return;o>0&&this._logger.debug(`flush() re-checking ${i.length} pending promise(s) before flushing`),await Promise.all(i.map(s=>s.catch(()=>{}))),o++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,n=this.promiseQueue.maxId,o=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(n,[t,o])}).then(()=>Fr([t])).then(()=>(this.pendingFlushPromise===o&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=o,this.flushPromise=o,this.flushPromises.add(o),this.addPendingPromise(o),Fr([o]).then(()=>{this.flushPromises.delete(o),this.pendingFlushPromise===o&&(this.pendingFlushPromise=null),this.flushPromise===o&&(this.flushPromise=null)}),o}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&e!==""&&(t["User-Agent"]=e),t}async sendBatch(e,t,n=Ur){let o={api_key:this.apiKey,batch:e,sent_at:$r()};this.historicalMigration&&(o.historical_migration=!0);let i=ye(o),s=`${this.host}/batch/`,a=this.disableCompression?null:await le(i,this.isDebug),u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||i};await(await this.fetchWithRetry(s,u,t)).body?.cancel()?.catch(()=>{})}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some(o=>this.getRouteQueue(o).length>0))return;let t=[],n;for(let o of e)try{await this._flushRoute(o,t)}catch(i){n===void 0&&(n=i)}if(n!==void 0)throw n;this._events.emit("flush",t)}async _flushRoute(e,t){let n=this.persistedQueueKeyForRoute(e),o=this.getPersistedProperty(n)||[];if(!o.length)return;let i=o.length,s=0;for(;o.length>0&&s<i;){let a=o.slice(0,this.maxBatchSize),u=a.map(f=>f.message===void 0?f.message:this.normalizeMessage(f.message)),c=async()=>{let p=(this.getPersistedProperty(n)||[]).slice(a.length);this.setPersistedProperty(n,p),o=p,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},l={retryCheck:f=>we(f)?!1:Je(f)};try{await this.sendBatch(u,l,e)}catch(f){if(we(f)&&u.length>1){this.maxBatchSize=Math.max(1,Math.floor(u.length/2)),this._logger.warn(`Received 413 when sending batch of size ${u.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw f instanceof ie||await c(),this._events.emit("error",f),f}await c(),t.push(...u),s+=u.length}}async _sendLogsBatch(e){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let t=JSON.stringify(e),n=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,o=this.disableCompression?null:await le(t,this.isDebug),i={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...o!==null&&{"Content-Encoding":"gzip"}},body:o||t};try{return await this.fetchWithRetry(n,i,{retryCheck:s=>we(s)?!1:Je(s)}),{kind:"ok"}}catch(s){return we(s)?{kind:"too-large"}:s instanceof ie?{kind:"retry-later",error:s}:{kind:"fatal",error:s}}}async _sendMetricsBatch(e){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let t=JSON.stringify(e),n=`${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`,o=this.disableCompression?null:await le(t,this.isDebug),i={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...o!==null&&{"Content-Encoding":"gzip"}},body:o||t};try{return await this.fetchWithRetry(n,i,{retryCheck:s=>we(s)?!1:Je(s)}),{kind:"ok"}}catch(s){return we(s)?{kind:"too-large"}:Je(s)?{kind:"retry-later",error:s}:{kind:"fatal",error:s}}}async fetchWithRetry(e,t,n,o){let i=t.body?t.body:"",s=-1;try{s=i instanceof Blob?i.size:Buffer.byteLength(i,To)}catch{i instanceof Blob?s=i.size:s=new TextEncoder().encode(i).length}return await Lo(async()=>{let a=new AbortController,u=o??this.requestTimeout,c=A(()=>a.abort(),u),l=null;try{l=await this.fetch(e,{signal:a.signal,...t})}catch(p){throw new ie(p)}finally{clearTimeout(c)}if(!(t.mode==="no-cors")&&(l.status<200||l.status>=400))throw new Q(l,s);return l},{...this._retryOptions,...n})}async _shutdown(e=3e4){await this._initPromise;let t=!1;if(this.clearFlushTimer(),this.disabled)return;let n=async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(a=>this.getRouteQueue(a).length>0);){let s=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===s){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(i){if(!$c(i))throw i;await ei(i)}},o;try{return await Promise.race([new Promise((i,s)=>{o=A(()=>{this._logger.error("Timed out while shutting down PostHog"),t=!0,s("Timeout while shutting down PostHog. Some events may not have been sent.")},e)}),n()])}finally{clearTimeout(o)}}async shutdown(e=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var si=require("fs"),ai=require("readline"),kt=new z.ReduceableCache(25),ci=new z.ReduceableCache(20),Br=7,kc=1e3,Rc=1e4;async function ui(r){let e={};for(let o=r.length-1;o>=0;o--){let i=r[o],s=i?.filename;if(!i||typeof s!="string"||typeof i.lineno!="number"||Mc(s)||Lc(i))continue;e[s]||(e[s]=[]),e[s].push(i.lineno)}let t=Object.keys(e);if(t.length==0)return r;let n=[];for(let o of t){if(ci.get(o))continue;let i=e[o];if(!i)continue;i.sort((u,c)=>u-c);let s=Dc(i);if(s.every(u=>Nc(o,u)))continue;let a=Zc(kt,o,{});n.push(zc(o,s,a))}return await Promise.all(n).catch(()=>{}),r&&r.length>0&&Oc(r,kt),kt.reduce(),r}function zc(r,e,t){return new Promise(n=>{let o=(0,si.createReadStream)(r),i=(0,ai.createInterface)({input:o});function s(){o.destroy(),n()}let a=0,u=0,c=e[u];if(c===void 0)return void s();let l=c[0],f=c[1];function p(){ci.set(r,1),i.close(),i.removeAllListeners(),s()}o.on("error",p),i.on("error",p),i.on("close",s),i.on("line",d=>{if(a++,!(a<l)&&(t[a]=jc(d,0),a>=f)){if(u===e.length-1){i.close(),i.removeAllListeners();return}u++;let h=e[u];if(h===void 0){i.close(),i.removeAllListeners();return}l=h[0],f=h[1]}})})}function Oc(r,e){for(let t of r)if(t.filename&&t.context_line===void 0&&typeof t.lineno=="number"){let n=e.get(t.filename);if(n===void 0)continue;Tc(t.lineno,t,n)}}function Tc(r,e,t){if(e.lineno===void 0||t===void 0)return;e.pre_context=[];for(let o=li(r);o<r;o++){let i=t[o];if(i===void 0)return void oi(e);e.pre_context.push(i)}if(t[r]===void 0)return void oi(e);e.context_line=t[r];let n=fi(r);e.post_context=[];for(let o=r+1;o<=n;o++){let i=t[o];if(i===void 0)break;e.post_context.push(i)}}function oi(r){delete r.pre_context,delete r.context_line,delete r.post_context}function Mc(r){return r.startsWith("node:")||r.endsWith(".min.js")||r.endsWith(".min.cjs")||r.endsWith(".min.mjs")||r.startsWith("data:")}function Lc(r){return r.lineno!==void 0&&r.lineno>Rc||r.colno!==void 0&&r.colno>kc}function Nc(r,e){let t=kt.get(r);if(t===void 0)return!1;for(let n=e[0];n<=e[1];n++)if(t[n]===void 0)return!1;return!0}function Dc(r){if(!r.length)return[];let e=0,t=r[0];if(typeof t!="number")return[];let n=ii(t),o=[];for(;;){if(e===r.length-1){o.push(n);break}let i=r[e+1];if(typeof i!="number")break;i<=n[1]?n[1]=i+Br:(o.push(n),n=ii(i)),e++}return o}function ii(r){return[li(r),fi(r)]}function li(r){return Math.max(1,r-Br)}function fi(r){return r+Br}function Zc(r,e,t){let n=r.get(e);return n===void 0?(r.set(e,t),t):n}function jc(r,e){let t=r,n=t.length;if(n<=150)return t;e>n&&(e=n);let o=Math.max(e-60,0);o<5&&(o=0);let i=Math.min(o+140,n);return i>n-5&&(i=n),i===n&&(o=Math.max(i-140,0)),t=t.slice(o,i),o>0&&(t=`...${t}`),i<n&&(t+="..."),t}var Pe=require("path");function pi(r=process.cwd()){let e=Pe.sep==="\\",t=o=>e?o.replace(/\\/g,"/"):o,n=t(r);return async o=>{for(let i of o)!i.filename||i.filename.startsWith("node:")||i.filename.startsWith("data:")||(0,Pe.isAbsolute)(i.filename)&&(i.filename=t((0,Pe.relative)(n,t(i.filename))));return o}}var di="5.46.1";var Y={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var de=class r{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e){let t=this._flags[e];return this._recordAccess(e),t?.enabled??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),!!t)return t.enabled?t.variant??!0:!1}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let n=this._flags[t];n&&(e[t]=n)}return this._cloneWith(e)}only(e){let t={},n=[];for(let o of e){let i=this._flags[o];i?t[o]=i:n.push(o)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[n,o]of Object.entries(this._flags)){let i=o.enabled===!1?!1:o.variant??!0;e[`$feature/${n}`]=i,o.enabled&&t.push(n)}return t.length>0&&(t.sort(),e.$active_feature_flags=t),e}_cloneWith(e){return new r({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),this._distinctId===""||this._isSlice&&!(e in this._flags))return;let t=this._flags[e],n=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,o={$feature_flag:e,$feature_flag_response:n,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};t?.hasExperiment!==void 0&&(o.$feature_flag_has_experiment=t.hasExperiment),t?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(o.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let i=[];this._errorsWhileComputing&&i.push(Y.ERRORS_WHILE_COMPUTING),this._quotaLimited&&i.push(Y.QUOTA_LIMITED),t===void 0&&i.push(Y.FLAG_MISSING),i.length>0&&(o.$feature_flag_error=i.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:o})}};async function hi(r){let e=globalThis.crypto?.subtle;if(!e)throw new Error("SubtleCrypto API not available");let t=await e.digest("SHA-1",new TextEncoder().encode(r));return Array.from(new Uint8Array(t)).map(o=>o.toString(16).padStart(2,"0")).join("")}var Uc=6e4,Bc=1152921504606847e3,Hc=["is_not","is_set"],Ee=class r extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,r.prototype)}};function yi(r,e){r.name=e.name,Error.captureStackTrace(r,e),Object.setPrototypeOf(r,e.prototype)}var y=class r extends Error{constructor(e){super(e),yi(this,r)}},G=class r extends Error{constructor(e){super(e),yi(this,r)}},Rt=class{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:n,timeout:o,host:i,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=o,this.projectApiKey=n,this.host=i,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}createEvaluationContext(e,t={},n={},o={},i={}){return{distinctId:e,groups:t,personProperties:n,groupProperties:o,evaluationCache:i}}async getFeatureFlag(e,t,n={},o={},i={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[e],a!==void 0){let u=this.createEvaluationContext(t,n,o,i);try{s=(await this.computeFlagAndPayloadLocally(a,u)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${s}`))}catch(c){c instanceof G||c instanceof y?this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${e}: ${c.message}`)):c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${e}: ${c}`))}}return s}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let n={},o={},i=this.featureFlags.length==0,s=t?t.map(u=>this.featureFlagsByKey[u]).filter(Boolean):this.featureFlags,a={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(s.map(async u=>{try{let{value:c,payload:l}=await this.computeFlagAndPayloadLocally(u,a);n[u.key]=c,l&&(o[u.key]=l)}catch(c){c instanceof G||c instanceof y?this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${u.key}: ${c.message}`)):c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${u.key}: ${c}`)),i=!0}})),{response:n,payloads:o,fallbackToFlags:i}}async computeFlagAndPayloadLocally(e,t,n={}){let{matchValue:o,skipLoadCheck:i=!1}=n;if(i||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=o!==void 0?o:await this.computeFlagValueLocally(e,t);let a=this.getFeatureFlagPayload(e.key,s);return{value:s,payload:a}}async computeFlagValueLocally(e,t){let{distinctId:n,groups:o,personProperties:i,groupProperties:s}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new y("Flag has experience continuity enabled");let u=(e.filters||{}).aggregation_group_type_index;if(u!=null){let c=this.groupTypeMapping[String(u)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${u} for feature flag ${e.key}`)),new y("Flag has unknown group type index");if(!(c in o))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;e.bucketing_identifier==="device_id"&&(i?.$device_id===void 0||i?.$device_id===null||i?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let l=s[c];return await this.matchFeatureFlagProperties(e,o[c],l,t)}{let c=this.getBucketingValueForFlag(e,n,i);if(c===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new y(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,c,i,t)}}getBucketingValueForFlag(e,t,n){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let o=n?.$device_id;return o==null||o===""?void 0:o}return t}getFeatureFlagPayload(e,t){let n=null;if(t!==!1&&t!=null&&(typeof t=="boolean"?n=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null:typeof t=="string"&&(n=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(e,t,n){let{evaluationCache:o}=n,i=e.key;if(!this.featureFlagsByKey)throw new y("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new y(`Flag dependency property for '${i}' is missing required 'dependency_chain' field`);let s=e.dependency_chain;if(!Array.isArray(s))throw new y(`Flag dependency property for '${i}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new y(`Circular dependency detected for flag '${i}' (empty dependency chain)`);for(let u of s){if(!(u in o)){let l=this.featureFlagsByKey[u];if(l)if(l.active)try{let f=await this.computeFlagValueLocally(l,n);o[u]=f}catch(f){throw new y(`Error evaluating flag dependency '${u}' for flag '${i}': ${f}`)}else o[u]=!1;else throw new y(`Missing flag dependency '${u}' for flag '${i}'`)}if(o[u]==null)throw new y(`Dependency '${u}' could not be evaluated`)}let a=o[i];return this.flagEvaluatesToExpectedValue(e.value,a)}flagEvaluatesToExpectedValue(e,t){return typeof e=="boolean"?e===t||typeof t=="string"&&t!==""&&e===!0:typeof e=="string"?t===e:!1}async matchFeatureFlagProperties(e,t,n,o){let i=e.filters||{},s=i.groups||[],a=i.aggregation_group_type_index,u=i.early_exit??!1,{groups:c,groupProperties:l}=o,f=!1,p;for(let d of s)try{let h=d.aggregation_group_type_index!==void 0?d.aggregation_group_type_index:a,g=n,w=t;if(h!==a&&h!=null){let v=this.groupTypeMapping[String(h)];if(!v||!(v in c)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${h} not available`));continue}if(!(v in l)){f=!0;continue}g=l[v],w=c[v]}let _=await this.isConditionMatch(e,w,d,g,o);if(_==="match"){let v=d.variant,R=i.multivariate?.variants||[];p=v&&R.some(I=>I.key===v)?v:await this.getMatchingVariant(e,w)||!0;break}if(u&&_==="out_of_rollout_bound")return!1}catch(h){if(h instanceof G)throw h;if(h instanceof y)f=!0;else throw h}if(p!==void 0)return p;if(f)throw new y("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,n,o,i){let s=n.rollout_percentage,a=u=>{this.logMsgIfDebug(()=>console.warn(u))};if((n.properties||[]).length>0){for(let u of n.properties){let c=u.type,l=!1;if(c==="cohort"){let f=await bi(u,o,this.cohorts,this.debugMode,p=>this.evaluateFlagDependency(p,o,i));l=u.operator==="not_in"?!f:f}else l=c==="flag"?await this.evaluateFlagDependency(u,o,i):vi(u,o,a);if(!l)return"no_match"}if(s==null)return"match"}return s!=null&&await gi(e.key,t)>s/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){let n=await gi(e.key,t,"variant"),o=this.variantLookupTable(e).find(i=>n>=i.valueMin&&n<i.valueMax);if(o)return o.key}variantLookupTable(e){let t=[],n=0,o=0;return((e.filters||{}).multivariate?.variants||[]).forEach(a=>{o=n+a.rollout_percentage/100,t.push({valueMin:n,valueMax:o,key:a.key}),n=o}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((t,n)=>(t[n.key]=n,t),{}),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(e.minimalFlagCalledEvents===!0)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter(n=>n.ensure_experience_continuity);t.length>0&&console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();return t?(this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(t.flags),!0):!1}catch(t){return this.onError?.(new Error(`Failed to load from cache: ${t}`)),!1}}async loadFeatureFlags(e=!1){if(!(this.loadedSuccessfullyOnce&&!e))return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(t=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${t}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(Uc,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!e&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new Ee(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new Ee(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Ee(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await t.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let o={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{},minimalFlagCalledEvents:n.minimal_flag_called_events===!0};if(this.updateFlagState(o),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(o)}catch(i){this.onError?.(new Error(`Failed to store in cache: ${i}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(o.flags);break}default:return}}catch(e){e instanceof Ee&&this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET",t){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(n["If-None-Match"]=t),{method:e,headers:n}}_requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let o=new AbortController;n=A(()=>{o.abort()},this.timeout),t.signal=o.signal}try{let o=this.fetch;return o(e,t)}finally{clearTimeout(n)}}async stopPoller(e=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await Promise.race([t,new Promise((n,o)=>setTimeout(()=>o(new Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(t){this.onError?.(new Error(`Error during cache shutdown: ${t}`))}}};async function gi(r,e,t=""){let n=await hi(`${r}.${e}${t}`);return parseInt(n.slice(0,15),16)/Bc}function vi(r,e,t){let n=r.key,o=r.value,i=r.operator||"exact";if(n in e){if(i==="is_not_set")return!1}else{if(i==="is_not_set")return!0;throw new y(`Property ${n} not found in propertyValues`)}let s=e[n];if(s==null&&!Hc.includes(i))return t&&t(`Property ${n} cannot have a value of null/undefined with the ${i} operator`),!1;function a(c,l){return Array.isArray(c)?c.map(f=>String(f).toLowerCase()).includes(String(l).toLowerCase()):String(c).toLowerCase()===String(l).toLowerCase()}function u(c,l,f){if(f==="gt")return c>l;if(f==="gte")return c>=l;if(f==="lt")return c<l;if(f==="lte")return c<=l;throw new Error(`Invalid operator: ${f}`)}switch(i){case"exact":return a(o,s);case"is_not":return!a(o,s);case"is_set":return n in e;case"icontains":return String(s).toLowerCase().includes(String(o).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(o).toLowerCase());case"regex":return mi(String(o))&&String(s).match(String(o))!==null;case"not_regex":return mi(String(o))&&String(s).match(String(o))===null;case"gt":case"gte":case"lt":case"lte":{let c=typeof o=="number"?o:parseFloat(String(o)),l;return l=typeof s=="number"?s:s!=null?parseFloat(String(s)):NaN,Number.isFinite(c)&&Number.isFinite(l)?u(l,c,i):u(String(s),String(o),i)}case"is_date_after":case"is_date_before":{if(typeof o=="boolean")throw new y("Date operations cannot be performed on boolean values");let c=Vc(String(o));if(c==null&&(c=_i(o)),c==null)throw new y(`Invalid date: ${o}`);let l=_i(s);return["is_date_before"].includes(i)?l<c:l>c}case"semver_eq":return Z(S(String(s)),S(String(o)))===0;case"semver_neq":return Z(S(String(s)),S(String(o)))!==0;case"semver_gt":return Z(S(String(s)),S(String(o)))>0;case"semver_gte":return Z(S(String(s)),S(String(o)))>=0;case"semver_lt":return Z(S(String(s)),S(String(o)))<0;case"semver_lte":return Z(S(String(s)),S(String(o)))<=0;case"semver_tilde":{let c=S(String(s)),{lower:l,upper:f}=Gc(String(o));return Z(c,l)>=0&&Z(c,f)<0}case"semver_caret":{let c=S(String(s)),{lower:l,upper:f}=Wc(String(o));return Z(c,l)>=0&&Z(c,f)<0}case"semver_wildcard":{let c=S(String(s)),{lower:l,upper:f}=qc(String(o));return Z(c,l)>=0&&Z(c,f)<0}default:throw new y(`Unknown operator: ${i}`)}}function Kc(r,e){if(!(r in e))throw new G(`cohort ${r} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function bi(r,e,t,n=!1,o){let i=String(r.value);Kc(i,t);let s=t[i];return xi(s,e,t,n,o)}async function xi(r,e,t,n=!1,o){if(!r)return!0;let i=r.type,s=r.values;if(!s||s.length===0)return!0;let a=!1;if("values"in s[0]){for(let u of s)try{let c=await xi(u,e,t,n,o);if(i==="AND"){if(!c)return!1}else if(c)return!0}catch(c){if(c instanceof G)throw c;if(c instanceof y)n&&console.debug(`Failed to compute property ${u} locally: ${c}`),a=!0;else throw c}if(a)throw new y("Can't match cohort without a given cohort property value");return i==="AND"}for(let u of s)try{let c;if(u.type==="cohort")c=await bi(u,e,t,n,o);else if(u.type==="flag"){if(!o)throw new y(`Flag dependency '${u.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);c=await o(u)}else c=vi(u,e);let l=u.negation||!1;if(i==="AND"){if(!c&&!l||c&&l)return!1}else if(c&&!l||!c&&l)return!0}catch(c){if(c instanceof G)throw c;if(c instanceof y)n&&console.debug(`Failed to compute property ${u} locally: ${c}`),a=!0;else throw c}if(a)throw new y("can't match cohort without a given cohort property value");return i==="AND"}function mi(r){try{return new RegExp(r),!0}catch{return!1}}function wi(r,e){if(!/^\d+$/.test(r))throw new y(`Invalid semver: ${e}`);if(r.length>1&&r[0]==="0")throw new y(`Invalid semver: ${e}`);return parseInt(r,10)}function S(r){let t=String(r).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!t||t.startsWith("."))throw new y(`Invalid semver: ${r}`);let n=t.split("."),o=u=>u===void 0||u===""?0:wi(u,r),i=o(n[0]),s=o(n[1]),a=o(n[2]);return[i,s,a]}function Z(r,e){for(let t=0;t<3;t++){if(r[t]<e[t])return-1;if(r[t]>e[t])return 1}return 0}function Gc(r){let e=S(r),t=[e[0],e[1],e[2]],n=[e[0],e[1]+1,0];return{lower:t,upper:n}}function Wc(r){let e=S(r),[t,n,o]=e,i=[t,n,o],s;return s=t>0?[t+1,0,0]:n>0?[0,n+1,0]:[0,0,o+1],{lower:i,upper:s}}function qc(r){let t=String(r).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!t)throw new y(`Invalid wildcard semver: ${r}`);let n=t.split("."),o=u=>{try{return wi(u,r)}catch{throw new y(`Invalid wildcard semver: ${r}`)}},i=o(n[0]),s,a;if(n.length===1)s=[i,0,0],a=[i+1,0,0];else{let u=o(n[1]);s=[i,u,0],a=[i,u+1,0]}return{lower:s,upper:a}}function _i(r){if(r instanceof Date)return r;if(typeof r=="string"||typeof r=="number"){let e=new Date(r);if(!isNaN(e.valueOf()))return e;throw new y(`${r} is in an invalid date format`)}throw new y(`The date provided ${r} must be a string, number, or date object`)}function Vc(r){let e=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,t=r.match(e),n=new Date(new Date().toISOString());if(!t)return null;{if(!t.groups)return null;let o=parseInt(t.groups.number);if(o>=1e4)return null;let i=t.groups.interval;if(i=="h")n.setUTCHours(n.getUTCHours()-o);else if(i=="d")n.setUTCDate(n.getUTCDate()-o);else if(i=="w")n.setUTCDate(n.getUTCDate()-7*o);else if(i=="m")n.setUTCMonth(n.getUTCMonth()-o);else{if(i!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-o)}return n}}function Xc(r,e){let t=!1;return Object.assign(n=>{let i=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;r(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!t&&i&&(t=!0,e(n))},{_posthogErrorHandler:!0})}function Pi(r,e){globalThis.process?.on("uncaughtException",Xc(r,e))}function Ei(r){globalThis.process?.on("unhandledRejection",e=>r(e,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var Jc=2e3,ee=class r{constructor(e,t,n){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new gt({...xo(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return Ne(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,n,o,i){let s={...i},a=e.buildFromUnknown(t,n);return a.$exception_list=await e.modifyFrames(a.$exception_list),{event:"$exception",distinctId:o,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(Pi(this.onException.bind(this),this.onFatalError.bind(this)),Ei(this.onException.bind(this)))}onException(e,t){this.client.addPendingPromise((async()=>{if(!r.isPreviouslyCapturedError(e)){let n=await r.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),i=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(i)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:i}):this.client._capturePreparedEvent(n,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(Jc),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var zt=class{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}};function Qc(r){return r==="v0"||r==="v1"}function $i(){let r=typeof process<"u"?process.env?.POSTHOG_CAPTURE_MODE:void 0;return Qc(r)?r:"v0"}var Yc="$ai_",Ye="analytics";function Fi(r){return typeof r.event=="string"&&r.event.startsWith(Yc)}var $e=class r extends Error{constructor({requestId:e,drops:t,retryExhausted:n,cause:o}){super(r.buildMessage(e,t,n,o)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=n,this.cause=o}static buildMessage(e,t,n,o){let i=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${n.length} undelivered`;return o instanceof Error&&(i+=` (${o.message})`),i}};function Hr(r){if(typeof r=="boolean")return r;if(typeof r=="number")return r!==0;if(typeof r=="string"){let e=r.trim().toLowerCase();if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1}}function eu(r){return typeof r=="string"?r:void 0}var tu=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Hr},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Hr},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Hr},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:eu}],ru=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function nu(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function ou(r){if(typeof r=="string"){let t=new Date(r);return Number.isNaN(t.getTime())?new Date().toISOString():r}if(r instanceof Date)return Number.isNaN(r.getTime())?new Date().toISOString():r.toISOString();let e=r==null?new Date:new Date(r);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()}function Si(r,e,t){t!==void 0&&!(e in r)&&(r[e]=t)}function iu(r){let t={...nu(r.properties)?r.properties:{}},n={};for(let{property:i,optionKey:s,coerce:a}of tu)if(i in t){let u=a(t[i]);u!==void 0&&(n[s]=u),delete t[i]}let o={};for(let{property:i,field:s}of ru)if(i in t){let a=t[i];typeof a=="string"&&(o[s]=a),delete t[i]}return delete t.$lib,delete t.$lib_version,Si(t,"$set",r.$set),Si(t,"$set_once",r.$set_once),{event:String(r.event??""),uuid:String(r.uuid??""),distinct_id:String(r.distinct_id??""),timestamp:ou(r.timestamp),...o,options:n,properties:t}}function Ii(r,{createdAt:e,historicalMigration:t}){let n={created_at:e,batch:r.map(iu)};return t&&(n.historical_migration=!0),n}var su="/i/v1/analytics/events",au=3e4,cu=new Set([408,500,502,503,504]),Ot=class{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??au,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??(n=>new Promise(o=>A(o,n))),this.generateRequestId=t.generateRequestId??M,this.compress=t.compress??le}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:o}=Ii(e,{createdAt:n,historicalMigration:this.config.historicalMigration}),i=`${this.config.host}${su}`,s=[],a=o,u=Math.max(1,this.config.maxAttempts);for(let c=1;c<=u;c++){let l=c===u,f=ye({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),p;try{p=await this.sendOnce(i,f,c,t)}catch(_){if(l)return this.surfaceBatchFailure(t,s,a,_);await this.sleep(this.backoffDelay(c));continue}let{status:d}=p;if(d<200||d>=300){if(!l&&cu.has(d)){let v=this.parseRetryAfter(p);await this.cancelBody(p),await this.sleep(this.backoffDelay(c,v));continue}let _=await this.buildHttpError(p,d);return this.surfaceBatchFailure(t,s,a,_)}let h;try{h=await this.parseResponse(p)}catch{return this.surfaceBatchFailure(t,s,a,new Error(`Capture V1 returned an unparseable ${d} response body`))}let g=this.classify(a,h,s);if(g.length===0)return this.surfacePartialDrops(t,s);if(l)return void this.onError(new $e({requestId:t,drops:s,retryExhausted:g.map(_=>_.uuid)}));a=g;let w=this.parseRetryAfter(p);await this.sleep(this.backoffDelay(c,w))}}async sendOnce(e,t,n,o){let i=this.buildHeaders(n,o),s=t;if(this.config.compressionEnabled){let c=await this.compress(t,this.config.isDebug);c!==null&&(s=c,i["Content-Encoding"]="gzip")}let a=new AbortController,u=A(()=>a.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(e,{method:"POST",headers:i,body:s,signal:a.signal})}finally{clearTimeout(u)}}buildHeaders(e,t){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,o={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(o["User-Agent"]=this.config.userAgent),o}classify(e,t,n){let o=t.results??{},i=[];for(let s of e){let a=o[s.uuid];a&&(a.result==="drop"?n.push({uuid:s.uuid,details:a.details??void 0}):a.result==="retry"&&i.push(s))}return i}backoffDelay(e,t){let n=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return t===void 0?n:Math.max(n,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let n=t.trim();if(/^\d+$/.test(n)){let s=parseInt(n,10);return Number.isFinite(s)&&s>0?1e3*s:void 0}let o=Date.parse(n);if(Number.isNaN(o))return;let i=o-this.now();return i>0?i:void 0}async parseResponse(e){let t=await e.text(),n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("unexpected response shape");let o=n.results;if(o!==void 0&&(typeof o!="object"||o===null||Array.isArray(o)))throw new Error("unexpected results shape");return{results:o??{}}}async buildHttpError(e,t){let n="";try{n=(await e.text()).slice(0,512)}catch{}let o=n?`: ${n}`:"";return new Error(`Capture V1 request failed with HTTP ${t}${o}`)}surfaceBatchFailure(e,t,n,o){this.onError(new $e({requestId:e,drops:t,retryExhausted:n.map(i=>i.uuid),cause:o}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new $e({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}};var uu=100,Ai=3e4,lu=5e4,fu=50,pu=500,du="https://us.i.posthog.com",Ci=new Set;function Mt(r,e){Ci.has(r)||(Ci.add(r),console.warn(`[PostHog] ${e}`))}function hu(r){return typeof r=="string"?r.trim():""}function gu(r){return(typeof r=="string"?r.trim():"")||void 0}function mu(r){return(typeof r=="string"?r.trim():"")||du}function _u(r){return(Array.isArray(r)?r:[r]).filter(t=>typeof t=="string"&&t.trim().length>0)}function yu(r){if(!r)return{};let e={};for(let[n,o]of Object.entries(r))e[`$feature/${n}`]=o;let t=Object.keys(r).filter(n=>r[n]!==!1).sort();return t.length>0&&(e.$active_feature_flags=t),e}var Lt=class extends Qe{constructor(e,t={}){let n=hu(e),o={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:mu(t.host),personalApiKey:gu(t.secretKey??t.personalApiKey)};if(super(n,o),this._memoryStorage=new zt,this._minimalFlagCalledEvents=!1,this.options=o,this.captureMode=$i(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof o.featureFlagsPollingInterval=="number"?Math.max(o.featureFlagsPollingInterval,uu):Ai,typeof o.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(o.waitUntilDebounceMs,0)),typeof o.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(o.waitUntilMaxWaitMs,0)),!this.disabled&&o.personalApiKey){if(o.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');o.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new Rt({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:o.personalApiKey,projectApiKey:n,timeout:o.requestTimeout??1e4,host:this.host,fetch:o.fetch,onError:s=>{this._events.emit("error",s)},onLoad:s=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:s=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:o.flagDefinitionCacheProvider,strictLocalEvaluation:o.strictLocalEvaluation}))}this.errorTracking=new ee(this,o,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=o.maxCacheSize||lu}enqueue(e,t,n){super.enqueue(e,t,n),this.scheduleDebouncedFlush()}async flush(){let e=this.flushWithPendingPromises(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,a=new Promise(u=>{s=u});try{e(a)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??pu,o=t>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),o)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??fu;this._waitUntilCycle.timer=A(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this.flushWithPendingPromises()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){return this.captureMode==="v1"&&Fi(e)?"ai":Ye}persistedQueueKeyForRoute(e){return e==="ai"?T.AiQueue:T.Queue}getActiveQueueRoutes(){return this.captureMode==="v1"?[Ye,"ai"]:[Ye]}async sendBatch(e,t,n=Ye){if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(e,t,n);let o=e.filter(i=>i!==void 0);await this.getV1Sender().sendV1Batch(o)}getV1Sender(){return this._v1Sender||(this._v1Sender=new Ot({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:e=>this._events.emit("error",e)})),this._v1Sender}getLibraryVersion(){return di}get metrics(){return this._metrics||(this._metrics=new He(this,Et(this.options.metrics),this._logger)),this._metrics}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,n){typeof e=="string"&&this._logger.warn(t),e.event==="$exception"&&!e._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(e,t,n,o){return this.addPendingPromise(this._prepareEventMessage(t,o).then(({distinctId:i,event:s,properties:a,options:u})=>{let c={timestamp:u.timestamp,disableGeoip:u.disableGeoip,uuid:u.uuid},l={distinctId:i,event:s,properties:{...a,...this.getCommonEventProperties()}};return n?this.sendImmediate(e,l,c):this.enqueue(e,l,c)}).catch(i=>{i&&console.error(i)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}identify({distinctId:e,properties:t={},disableGeoip:n}){let{$set:o,$set_once:i,$anon_distinct_id:s,...a}=t,l={$set:o||a,$set_once:i||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:n}){let{$set:o,$set_once:i,$anon_distinct_id:s,...a}=t,l={$set:o||a,$set_once:i||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:n={}}){if(Object.keys(t).length===0&&Object.keys(n).length===0)return;let o={};Object.keys(t).length>0&&(o.$set=t),Object.keys(n).length>0&&(o.$set_once=n),this.capture({distinctId:e,event:"$set",properties:o})}unsetPersonProperties({distinctId:e,properties:t}){let n=_u(t);n.length!==0&&this.capture({distinctId:e,event:"$set",properties:{$unset:n}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=Ai){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(t=>{let n=setTimeout(()=>{o(),t(!1)},e),o=this._events.on("localEvaluationFlagsLoaded",i=>{clearTimeout(n),o(),t(i>0)})})}_resolveDistinctId(e,t){return typeof e=="string"?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,n={},o){if(this.disabled)return void this._logger.warn("The client is disabled");let i=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let m=this._flagOverrides[e];if(m===void 0)return;let P=this._payloadOverrides?.[e];return{key:e,enabled:m!==!1,variant:typeof m=="string"?m:void 0,payload:P}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=n,f=this.addLocalPersonAndGroupProperties(t,s,c,l);c=f.allPersonProperties,l=f.allGroupProperties;let p=this.createFeatureFlagEvaluationContext(t,s,this.personPropertiesForLocalEvaluation(t,c),l);u==null&&(u=this.options.strictLocalEvaluation??!1);let d,h=!1,g,w,_,v,R,I,x;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let m=this.featureFlagsPoller?.featureFlagsByKey[e];if(m)try{let P=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(m,p,{matchValue:o});if(P){h=!0;let $=P.value;v=m.id,I="Evaluated locally",x=m.has_experiment,d={key:e,enabled:$!==!1,variant:typeof $=="string"?$:void 0,payload:P.payload??void 0}}}catch(P){if(P instanceof G||P instanceof y)this._logger?.info(`${P.name} when computing flag locally: ${e}: ${P.message}`);else throw P}}if(!h&&!u){let m=await super.getFeatureFlagDetailsStateless(p.distinctId,p.groups,c,l,a,[e]);if(m===void 0)_=Y.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=m.minimalFlagCalledEvents===!0,g=m.requestId,w=m.evaluatedAt;let P=[];m.errorsWhileComputingFlags&&P.push(Y.ERRORS_WHILE_COMPUTING),m.quotaLimited?.includes("feature_flags")&&P.push(Y.QUOTA_LIMITED);let $=m.flags[e];if($===void 0)P.push(Y.FLAG_MISSING);else{v=$.metadata?.id,R=$.metadata?.version,I=$.reason?.description??$.reason?.code,x=$.metadata?.has_experiment;let Bt;if($.metadata?.payload!==void 0)try{Bt=JSON.parse($.metadata.payload)}catch{Bt=$.metadata.payload}d={key:e,enabled:$.enabled,variant:$.variant,payload:Bt}}P.length>0&&(_=P.join(","))}}if(i){let m=d===void 0?void 0:d.enabled===!1?!1:d.variant??!0,P={$feature_flag:e,$feature_flag_response:m,$feature_flag_id:v,$feature_flag_version:R,$feature_flag_reason:I,locally_evaluated:h,[`$feature/${e}`]:m,$feature_flag_request_id:g,$feature_flag_evaluated_at:h?Date.now():w};if(x!==void 0&&(P.$feature_flag_has_experiment=x),h&&this.featureFlagsPoller){let $=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();$!==void 0&&(P.$feature_flag_definitions_loaded_at=$)}_&&(P.$feature_flag_error=_),this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:m,groups:s,disableGeoip:a,properties:P})}return d!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides&&(d={...d,payload:this._payloadOverrides[e]}),d}async getFeatureFlag(e,t,n){Mt("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let o=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(o!==void 0)return o.enabled===!1?!1:o.variant??!0}async getFeatureFlagPayload(e,t,n,o){if(Mt("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let i=await this._getFeatureFlagResult(e,t,{...o,sendFeatureFlagEvents:!1},n);if(i!==void 0)return i.payload??null}async getFeatureFlagResult(e,t,n){let{distinctId:o,options:i}=this._resolveDistinctId(t,n);return o?this._getFeatureFlagResult(e,o,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let n=await t.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(e,t,n){Mt("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let o=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return o===void 0?void 0:o.enabled===!1?!1:!!(o.variant??!0)||!1}async getAllFlags(e,t){let{distinctId:n,options:o}=this._resolveDistinctId(e,t);return n?(await this.getAllFlagsAndPayloads(n,o)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:n,options:o}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:i,disableGeoip:s,flagKeys:a}=o||{},{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=o||{},f=this.addLocalPersonAndGroupProperties(n,i,c,l);c=f.allPersonProperties,l=f.allGroupProperties;let p=this.createFeatureFlagEvaluationContext(n,i,this.personPropertiesForLocalEvaluation(n,c),l);u==null&&(u=this.options.strictLocalEvaluation??!1);let d=await this.featureFlagsPoller?.getAllFlagsAndPayloads(p,a),h={},g={},w=!0;if(d&&(h=d.response,g=d.payloads,w=d.fallbackToFlags),w&&!u){let _=await super.getFeatureFlagsAndPayloadsStateless(p.distinctId,p.groups,c,l,s,a);h={...h,..._.flags||{}},g={...g,..._.payloads||{}}}return this._flagOverrides!==void 0&&(h={...h,...this._flagOverrides}),this._payloadOverrides!==void 0&&(g={...g,...this._payloadOverrides}),{featureFlags:h,featureFlagPayloads:g}}async evaluateFlags(e,t){let{distinctId:n,options:o}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new de({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new de({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:i,disableGeoip:s,flagKeys:a}=o||{},{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=o||{},f=this.addLocalPersonAndGroupProperties(n,i,c,l);c=f.allPersonProperties,l=f.allGroupProperties;let p=this.createFeatureFlagEvaluationContext(n,i,this.personPropertiesForLocalEvaluation(n,c),l);u==null&&(u=this.options.strictLocalEvaluation??!1);let d={},h,g,w=!1,_=!1,v=await this.featureFlagsPoller?.getAllFlagsAndPayloads(p,a),R=new Set;if(v)for(let[x,C]of Object.entries(v.response)){let m=this.featureFlagsPoller?.featureFlagsByKey[x];d[x]={key:x,enabled:C!==!1,variant:typeof C=="string"?C:void 0,payload:v.payloads[x],id:m?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:m?.has_experiment},R.add(x)}if((v?v.fallbackToFlags:!0)&&!u){let x=await super.getFeatureFlagDetailsStateless(p.distinctId,p.groups,c,l,s,a);if(x){this._minimalFlagCalledEvents=x.minimalFlagCalledEvents===!0,h=x.requestId,g=x.evaluatedAt,w=!!x.errorsWhileComputingFlags,_=Array.isArray(x.quotaLimited)&&x.quotaLimited.includes("feature_flags");for(let[C,m]of Object.entries(x.flags)){if(R.has(C))continue;let P;if(m.metadata?.payload!==void 0)try{P=JSON.parse(m.metadata.payload)}catch{P=m.metadata.payload}d[C]={key:C,enabled:m.enabled,variant:m.variant,payload:P,id:m.metadata?.id,version:m.metadata?.version,reason:m.reason?.description??m.reason?.code,locallyEvaluated:!1,hasExperiment:m.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[x,C]of Object.entries(this._flagOverrides)){if(C===void 0){delete d[x];continue}let m=d[x];d[x]={key:x,enabled:C!==!1,variant:typeof C=="string"?C:void 0,payload:m?.payload,id:m?.id,version:m?.version,reason:m?.reason,locallyEvaluated:m?.locallyEvaluated??!1,hasExperiment:m?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[x,C]of Object.entries(this._payloadOverrides)){let m=d[x];m&&(d[x]={...m,payload:C})}return new de({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:i,disableGeoip:s,flags:d,requestId:h,evaluatedAt:g,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:w,quotaLimited:_})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:n,response:o,groups:i,disableGeoip:s,properties:a}=e,u=i&&Object.keys(i).length>0?`_${JSON.stringify(Object.entries(i).sort(([l],[f])=>l<f?-1:l>f?1:0))}`:"",c=`${n}_${o}${u}`;t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(c)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[t]instanceof Set?this.distinctIdHasSentFlagCalls[t].add(c):this.distinctIdHasSentFlagCalls[t]=new Set([c]),this.capture({distinctId:t,event:"$feature_flag_called",properties:a,groups:i,disableGeoip:s}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),logWarning:e=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:n,distinctId:o,disableGeoip:i}){this._sendPreparedEvent("capture",{distinctId:o||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{}},disableGeoip:i},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:n,distinctId:o,disableGeoip:i}){await this._sendPreparedEvent("capture",{distinctId:o||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{}},disableGeoip:i},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=n=>Object.fromEntries(n.map(o=>[o,!0]));if(e===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(e.flags===!1?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):e.flags!==void 0&&(this._flagOverrides={...e.flags})),"payloads"in e&&(e.payloads===!1?this._payloadOverrides=void 0:e.payloads!==void 0&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if("flags"in t){let n=t.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in t){let n=t.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(e,t,n){return this.context?this.context.run(e,t,n):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await Promise.race([this._metrics.flush().catch(()=>{}),new Promise(o=>A(o,Math.max(0,t-Date.now())))]),this._metrics.reset());try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},n?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},o=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let i=new AbortController;o=A(()=>{i.abort()},this.options.requestTimeout),n.signal=i.signal}try{return await this.fetch(t,n)}catch(i){this._events.emit("error",i);return}finally{o&&clearTimeout(o)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let n={},o={};for(let[i,s]of Object.entries(e))if(bo(s)&&t&&i in t){let a={};for(let[u,c]of Object.entries(s))a[String(u)]=String(c);o[String(i)]=a}else n[String(i)]=String(s);return{personProperties:n,groupProperties:o}}async getFeatureFlagsForEvent(e,t,n,o){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let i=o?.personProperties||{},s=o?.groupProperties||{},a=o?.flagKeys;if(o?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[l,f]of Object.entries(t||{}))c[l]=String(f);return await this.getAllFlags(e,{groups:c,personProperties:i,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[l,f]of Object.entries(t||{}))c[l]=String(f);return await this.getAllFlags(e,{groups:c,personProperties:i,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(e,t,i,s,n)).flags}addLocalPersonAndGroupProperties(e,t,n,o){let i={...n||{}},s={};if(t)for(let a of Object.keys(t))s[a]={$group_key:t[a],...o?.[a]||{}};return{allPersonProperties:i,allGroupProperties:s}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,n,o){return{distinctId:e,groups:t||{},personProperties:n||{},groupProperties:o||{},evaluationCache:{}}}captureException(e,t,n,o,i){if(!ee.isPreviouslyCapturedError(e)){let s=new Error("PostHog syntheticException");this.addPendingPromise(ee.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,n).then(a=>this._capturePreparedEvent({...a,uuid:o,flags:i},!1)))}}async captureExceptionImmediate(e,t,n,o){if(!ee.isPreviouslyCapturedError(e)){let i=new Error("PostHog syntheticException");return this.addPendingPromise(ee.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:i},t,n).then(s=>this.captureImmediate({...s,flags:o})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:n,event:o,properties:i,groups:s,flags:a,sendFeatureFlags:u,timestamp:c,disableGeoip:l,uuid:f}=e,p=this.context?.get(),d=t.includeContextProperties??!0,h=n||p?.distinctId,g=d?{...this.props,...p?.properties||{},...i||{}}:{...i||{}};h||(h=M(),g.$process_person_profile=!1),d&&p?.sessionId&&!g.$session_id&&(g.$session_id=p.sessionId);let w=this._shouldSendMinimalFlagCalledEvent(o,g)?Me(g):g,_=this._runBeforeSend({distinctId:h,event:o,properties:w,groups:s,flags:a,sendFeatureFlags:u,timestamp:c,disableGeoip:l,uuid:f});if(!_)return Promise.reject(null);let v=await Promise.resolve().then(async()=>{if(a)return u&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(u){Mt("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let R=typeof u=="object"?u:void 0,I=await this.getFeatureFlagsForEvent(_.distinctId,s,l,R);return yu(I)}return{}}).catch(()=>({})).then(R=>{let I=_.groups||s;return{...R,..._.properties||{},...I!==void 0&&Object.keys(I).length>0?{$groups:I}:{}}});return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof v.$raw_user_agent=="string"&&po(v.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",v.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:v,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let n=Array.isArray(t)?t:[t],o=e;for(let i of n){if(o=i(o),!o)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!o.properties||Object.keys(o.properties).length===0){let s=`Event '${o.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}return o}};var ki=require("async_hooks"),Nt=class{constructor(){this.storage=new ki.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,n){return this.storage.run(this.resolve(e,n),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let n=this.get()||{};return{distinctId:e.distinctId??n.distinctId,sessionId:e.sessionId??n.sessionId,properties:{...n.properties||{},...e.properties||{}}}}};var Ri="posthog-node";function vu(r,{organization:e,projectId:t,prefix:n,severityAllowList:o=["error"],sendExceptionsToPostHog:i=!0}={}){return s=>{if(!(o==="*"||o.includes(s.level)))return s;s.tags||(s.tags={});let u=s.tags[Kr.POSTHOG_ID_TAG];if(u===void 0)return s;let c=r.options.host??"https://us.i.posthog.com",l=new URL(`/project/${r.apiKey}/person/${u}`,c).toString();s.tags["PostHog Person URL"]=l;let f=s.exception?.values||[],p=f.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(g=>({...g,platform:"node:javascript"}))}:void 0})),d={$exception_message:f[0]?.value||s.message,$exception_type:f[0]?.type,$exception_level:s.level,$exception_list:p,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:f[0]?.value||s.message,$sentry_exception_type:f[0]?.type,$sentry_tags:s.tags};return e&&t&&(d.$sentry_url=(n||"https://sentry.io/organizations/")+e+"/issues/?project="+t+"&query="+s.event_id),i&&r.capture({event:"$exception",distinctId:u,properties:d}),s}}var Kr=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,n,o,i){this.name=Ri,this.name=Ri,this.setupOnce=function(s,a){let u=a()?.getClient()?.getDsn()?.projectId;s(vu(e,{organization:t,projectId:u,prefix:n,severityAllowList:o,sendExceptionsToPostHog:i??!0}))}}};var Dt=class extends Lt{getLibraryId(){return"posthog-node"}initializeContext(){return new Nt}createErrorPropertiesBuilder(){return new z.ErrorPropertiesBuilder([new z.EventCoercer,new z.ErrorCoercer,new z.ObjectCoercer,new z.StringCoercer,new z.PrimitiveCoercer],z.createStackParser("node:javascript",z.nodeStackLineParser),[uo(),ui,pi()])}};var zi="[redacted]",bu=/(^|[#&?])(access_token|refresh_token|token_hash|token)=[^\s#&"'<>]+/gi,xu=/(^|[^\w-])eyJ[\w-]+\.[\w-]+\.[\w-]+/g;function Oi(r){return r.replaceAll(bu,`$1$2=${zi}`).replaceAll(xu,`$1${zi}`)}var wu=new Set(["$anon_distinct_id","distinct_id"]),Pu=["$set","$set_once"];function Gr(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Wr(r){return typeof r=="string"?Oi(r):Array.isArray(r)?Eu(r):Gr(r)?Ti(r,()=>!0):r}function Eu(r){let e=r.map(t=>Wr(t));return e.some((t,n)=>t!==r[n])?e:r}function Ti(r,e){let t=!1,n=[];for(let[o,i]of Object.entries(r)){let s=e(o)?Wr(i):i;s!==i&&(t=!0),n.push([o,s])}return t?Object.fromEntries(n):r}function Mi(r){if(!Gr(r))return r;try{let e=!1,t={...r},{properties:n}=r;if(Gr(n)){let o=Ti(n,i=>!wu.has(i));o!==n&&(e=!0,t.properties=o)}for(let o of Pu){let i=r[o],s=Wr(i);s!==i&&(e=!0,t[o]=s)}return e?t:r}catch{return r}}var Zt=null,qr=null;function jt(){return Zt===null||qr===null?null:{client:Zt,projectKey:qr}}function Li(r){if(Zt!==null)return;if(me()){console.error("[HeyCatch] the server entry was bundled into a browser build - import '@heycatch/sdk' with your bundler's browser condition enabled. Server calls are no-ops here.");return}let e=io.safeParse(r);if(!e.success){let o=e.error.issues[0]?.message??"init() requires a config object with { projectKey }.";console.error(`[HeyCatch] ${o}`);return}let t=new Dt(no,{host:ro,flushAt:1,flushInterval:0,fetchRetryCount:1,fetchRetryDelay:250,requestTimeout:5e3,before_send:Mi});t.on("error",o=>{console.error("[HeyCatch] server send failed:",o)}),Zt=t,qr=e.data.projectKey;let n=oo();n!==null&&console.warn(n)}function Ut(r){return{heycatch_project_key:r,heycatch_sdk_version:Oe,heycatch_sdk_stage:ze}}async function Ni(r,e,t){if(me())return;let n=jt();if(n===null){console.error("[HeyCatch] setIdentity() called before init() - call init({ projectKey }) once at module scope.");return}if(typeof r!="string"||r.length===0){console.error("[HeyCatch] setIdentity() requires a non-empty string user id. Pass a stable internal user id from your auth provider \u2014 not an email or session token.");return}try{await n.client.captureImmediate({distinctId:r,event:"$identify",properties:{...e?{$set:e}:{},...t?{$set_once:t}:{},...Ut(n.projectKey)},groups:{[et]:n.projectKey}})}catch(o){console.error("[HeyCatch] setIdentity() failed to reach ingest:",o)}}function Di(r,e){console.error("[HeyCatch] setPersonProperties() has no ambient person on the server - use setIdentity(userId, properties) or trackEvent(..., { userId, set }).")}function Zi(){}var[$u]=lt,Fu="X-POSTHOG-SESSION-ID";function ji(r,e){try{if("get"in r&&typeof r.get=="function"){let n=r.get(e);return n===""?null:n}let t=e.toLowerCase();for(let[n,o]of Object.entries(r)){if(n.toLowerCase()!==t)continue;let i=o,s=Array.isArray(i)?i[0]:i;return typeof s=="string"&&s!==""?s:null}return null}catch{return null}}function Su(r){let e=r?.headers;return e?ji(e,$u)??ji(e,Fu):null}async function Ui(r,e,t){if(me())return;let n=jt();if(n===null){console.error("[HeyCatch] trackEvent() called before init() - call init({ projectKey }) once at module scope.");return}if(typeof r!="string"||r.length===0||r.startsWith("$")){console.error('[HeyCatch] trackEvent() requires a non-empty event name that does not start with "$" (reserved for built-ins).');return}let o=t??{},i=o.userId;if(typeof i!="string"||i.length===0){console.error("[HeyCatch] trackEvent() on the server requires options.userId - there is no ambient person in a server process. Pass the same stable internal user id the client uses.");return}let s=Su(o.request);try{await n.client.captureImmediate({distinctId:i,event:r,properties:{...e,...s?{$session_id:s}:{},...o.set?{$set:o.set}:{},...o.setOnce?{$set_once:o.setOnce}:{},...Ut(n.projectKey),heycatch_custom_user_event:!0},groups:{[et]:n.projectKey}})}catch(a){console.error("[HeyCatch] trackEvent() failed to reach ingest:",a)}}var Iu={init:Li,optInCapturing:Vr,optOutCapturing:Xr,resetIdentity:Zi,setIdentity:Ni,setPersonProperties:Di,trackEvent:Ui};0&&(module.exports={KNOWN_FRAMEWORKS,KNOWN_INSTALL_AGENTS,SDK_VERSION,STAGE,TRACING_HEADERS,UNKNOWN_INSTALL_VALUE,analytics});
|
|
1
|
+
"use strict";var Ht=Object.defineProperty;var Hi=Object.getOwnPropertyDescriptor;var Ki=Object.getOwnPropertyNames;var Gi=Object.prototype.hasOwnProperty;var Kt=(r,e)=>{for(var t in e)Ht(r,t,{get:e[t],enumerable:!0})},Wi=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ki(e))!Gi.call(r,o)&&o!==t&&Ht(r,o,{get:()=>e[o],enumerable:!(n=Hi(e,o))||n.enumerable});return r};var qi=r=>Wi(Ht({},"__esModule",{value:!0}),r);var Cu={};Kt(Cu,{KNOWN_FRAMEWORKS:()=>ao,KNOWN_INSTALL_AGENTS:()=>co,SDK_VERSION:()=>Oe,STAGE:()=>ze,TRACING_HEADERS:()=>lt,UNKNOWN_INSTALL_VALUE:()=>oe,analytics:()=>Au});module.exports=qi(Cu);function Vr(){}function Xr(){}function Jr(r){}var et="project",Vi="[a-z0-9]",zu=new RegExp(`^${Vi}$`);var V={};Kt(V,{BIGINT_FORMAT_RANGES:()=>gs,CONSTANT_CATCH:()=>yn,Class:()=>qt,NUMBER_FORMAT_RANGES:()=>hs,aborted:()=>q,allowsEval:()=>on,assert:()=>ts,assertEqual:()=>Xi,assertIs:()=>Yi,assertNever:()=>es,assertNotEqual:()=>Ji,assignProp:()=>Se,attachSchema:()=>Ce,base64ToUint8Array:()=>mn,base64urlToUint8Array:()=>ws,cached:()=>rt,captureStackTrace:()=>nt,cleanEnum:()=>xs,cleanRegex:()=>Xt,clone:()=>L,cloneDef:()=>as,codePointLength:()=>ys,constantCatch:()=>vn,createTransparentProxy:()=>ds,defineLazy:()=>Yr,defineLazyInternal:()=>D,derived:()=>Fs,esc:()=>rn,escapeRegex:()=>Ae,explicitlyAborted:()=>er,extend:()=>ln,finalizeIssue:()=>ne,floatSafeRemainder:()=>os,getElementAtPath:()=>cs,getEnumValues:()=>tt,getLengthableOrigin:()=>vs,getParsedType:()=>ps,getSizableOrigin:()=>ms,hexToUint8Array:()=>Es,hide:()=>rr,installLazyProp:()=>nr,isObject:()=>Fe,isPlainObject:()=>Ie,issue:()=>ct,joinValues:()=>rs,jsonStringifyReplacer:()=>Vt,members:()=>tr,merge:()=>dn,mergeDefs:()=>B,normalizeParams:()=>N,nullish:()=>ns,numKeys:()=>fs,objectClone:()=>is,omit:()=>un,optionalKeys:()=>Yt,own:()=>U,parsedType:()=>bs,partial:()=>hn,pick:()=>cn,prefixIssues:()=>st,primitiveTypes:()=>sn,promiseAllObject:()=>us,propertyKeyTypes:()=>Qt,randomString:()=>ls,rawShape:()=>Jt,required:()=>gn,safeExtend:()=>pn,shallowClone:()=>ot,sizeCaps:()=>at,slugify:()=>nn,stringifyPrimitive:()=>an,toZod:()=>Qi,uint8ArrayToBase64:()=>_n,uint8ArrayToBase64url:()=>Ps,uint8ArrayToHex:()=>$s,unwrapMessage:()=>he});function Xi(r){return r}function Ji(r){return r}function Qi(){return r=>r}function Yi(r){}function es(r){throw new Error("Unexpected value in exhaustive check")}function ts(r){}function tt(r){let e=Object.values(r).filter(n=>typeof n=="number");return Object.entries(r).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function rs(r,e="|"){return r.map(t=>an(t)).join(e)}function Vt(r,e){return typeof e=="bigint"?e.toString():e}var Wt=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function rt(r){return new Wt(r)}function ns(r){return r==null}function Xt(r){let e=r.startsWith("^")?1:0,t=r.endsWith("$")?r.length-1:r.length;return r.slice(e,t)}function os(r,e){let t=r/e,n=Math.round(t),o=4*Number.EPSILON*Math.max(Math.abs(t),1);return Math.abs(t-n)<o?0:t-n}var Qr=Symbol("evaluating");function Yr(r,e,t){let n;Object.defineProperty(r,e,{get(){if(n!==Qr)return n===void 0&&(n=Qr,n=t()),n},set(o){Object.defineProperty(r,e,{value:o})},configurable:!0})}function is(r){return Object.create(Object.getPrototypeOf(r),Object.getOwnPropertyDescriptors(r))}function Se(r,e,t){Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}function Jt(r){let e=Object.getOwnPropertyDescriptor(r,"shape");return e?.get?e.get.raw:e?.value}function W(r){return Jt(r._zod.def)??r._zod.def.shape}function en(r,e,t){Object.defineProperty(r,e,{get(){let n=t();return Se(this,e,n),n},enumerable:!0,configurable:!0})}function tn(r,e,t){e in r?Se(r,e,t):r[e]=t}function se(r,e,t,n){let o=W(e);for(let i of t){let s=Object.getOwnPropertyDescriptor(o,i);s.enumerable&&(s.get?en(r,i,()=>{let a=e._zod.def.shape[i];return n?n(a,i):a}):tn(r,i,n?n(s.value,i):s.value))}}function ss(r,e){for(let t of Reflect.ownKeys(e)){let n=Object.getOwnPropertyDescriptor(e,t);n.enumerable&&(n.get?en(r,t,()=>e[t]):tn(r,t,n.value))}}function B(...r){let e={};for(let t of r){let n=Object.getOwnPropertyDescriptors(t);Object.assign(e,n)}return Object.defineProperties({},e)}function as(r){return B(r._zod.def)}function cs(r,e){return e?e.reduce((t,n)=>t?.[n],r):r}function us(r){let e=Object.keys(r),t=e.map(n=>r[n]);return Promise.all(t).then(n=>{let o={};for(let i=0;i<e.length;i++)o[e[i]]=n[i];return o})}function ls(r=10){let e="abcdefghijklmnopqrstuvwxyz",t="";for(let n=0;n<r;n++)t+=e[Math.floor(Math.random()*e.length)];return t}function rn(r){return JSON.stringify(r)}function nn(r){return r.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var nt="captureStackTrace"in Error?Error.captureStackTrace:(...r)=>{};function Fe(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}var on=rt(()=>{if(ae.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let r=Function;return new r(""),!0}catch{return!1}});function Ie(r){if(Fe(r)===!1)return!1;let e=r.constructor;if(e===void 0||typeof e!="function")return!0;let t=e.prototype;return!(Fe(t)===!1||Object.prototype.hasOwnProperty.call(t,"isPrototypeOf")===!1)}function ot(r){return Ie(r)?{...r}:Array.isArray(r)?[...r]:r instanceof Map?new Map(r):r instanceof Set?new Set(r):r}function fs(r){let e=0;for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&e++;return e}var ps=r=>{let e=typeof r;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(r)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(r)?"array":r===null?"null":r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?"promise":typeof Map<"u"&&r instanceof Map?"map":typeof Set<"u"&&r instanceof Set?"set":typeof Date<"u"&&r instanceof Date?"date":typeof File<"u"&&r instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Qt=new Set(["string","number","symbol"]),sn=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ae(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function L(r,e,t){let n=new r._zod.constr(e??r._zod.def);return(!e||t?.parent)&&(n._zod.parent=r),n}function N(r){let e=r;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function ds(r){let e;return new Proxy({},{get(t,n,o){return e??(e=r()),Reflect.get(e,n,o)},set(t,n,o,i){return e??(e=r()),Reflect.set(e,n,o,i)},has(t,n){return e??(e=r()),Reflect.has(e,n)},deleteProperty(t,n){return e??(e=r()),Reflect.deleteProperty(e,n)},ownKeys(t){return e??(e=r()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(t,n){return e??(e=r()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(t,n,o){return e??(e=r()),Reflect.defineProperty(e,n,o)}})}function an(r){return typeof r=="bigint"?r.toString()+"n":typeof r=="string"?`"${r}"`:`${r}`}function Yt(r){return Object.keys(r).filter(e=>r[e]._zod.optin!==void 0&&r[e]._zod.optout==="optional")}var hs={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},gs={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function cn(r,e){let t=r._zod.def,n=t.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i={};return se(i,r,it(r,e)),L(r,B(t,{shape:i,checks:[]}))}function it(r,e){let t=W(r),n=[];for(let o of Reflect.ownKeys(e)){if(!Object.getOwnPropertyDescriptor(t,o)?.enumerable)throw new Error(`Unrecognized key: "${String(o)}"`);e[o]&&n.push(o)}return n}function un(r,e){let t=r._zod.def,n=t.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=new Set(it(r,e)),s={};return se(s,r,Reflect.ownKeys(W(r)).filter(a=>!i.has(a))),L(r,B(t,{shape:s,checks:[]}))}function ln(r,e){if(!Ie(e))throw new Error("Invalid input to extend: expected a plain object");let t=r._zod.def.checks;if(t&&t.length>0){let o=W(r);for(let i of Reflect.ownKeys(e))if(Object.getOwnPropertyDescriptor(o,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return L(r,B(r._zod.def,{shape:fn(r,e)}))}function fn(r,e){let t={};return se(t,r,Reflect.ownKeys(W(r))),ss(t,e),t}function pn(r,e){if(!Ie(e))throw new Error("Invalid input to safeExtend: expected a plain object");return L(r,B(r._zod.def,{shape:fn(r,e)}))}function dn(r,e){if(!e?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(r._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let t={};se(t,r,Reflect.ownKeys(W(r))),se(t,e,Reflect.ownKeys(W(e)));let n=B(r._zod.def,{shape:t,get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return L(r,n)}function hn(r,e,t,n="partial"){let i=e._zod.def.checks;if(i&&i.length>0)throw new Error(`.${n}() cannot be used on object schemas containing refinements`);let a=t?new Set(it(e,t)):void 0,u={};return se(u,e,Reflect.ownKeys(W(e)),r&&((c,l)=>a&&!a.has(l)?c:new r({type:"optional",innerType:c}))),L(e,B(e._zod.def,{shape:u,checks:[]}))}function gn(r,e,t){let n=t?new Set(it(e,t)):void 0,o={};return se(o,e,Reflect.ownKeys(W(e)),(i,s)=>n&&!n.has(s)?i:new r({type:"nonoptional",innerType:i})),L(e,B(e._zod.def,{shape:o}))}function q(r,e=0){if(r.aborted===!0)return!0;for(let t=e;t<r.issues.length;t++)if(r.issues[t]?.continue!==!0)return!0;return!1}function er(r,e=0){if(r.aborted===!0)return!0;for(let t=e;t<r.issues.length;t++)if(r.issues[t]?.continue===!1)return!0;return!1}function st(r,e){return e.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(r),t})}function he(r){return typeof r=="string"?r:r?.message}function at(r){let e=[];for(let t of r??[]){let n=t._zod.def;if(!/_(length|size)$|_equals$/.test(n.check))break;let o=n.maximum??n.length??n.size;o>=0&&e.push([o,t])}return e}function Ce(r,e,t){var n;for(let o=e;o<r.length;o++)(n=r[o]).schema??(n.schema=t)}function ne(r,e,t){var n;let o=r.inst?._zod?.traits;o?.has("$ZodType")&&(o.has("$ZodCheck")?(n=r).schema??(n.schema=r.inst):r.schema=r.inst);let i=r.schema!==r.inst?r.schema?._zod.def?.error:void 0,s=r.message?r.message:he(r.inst?._zod.def?.error?.(r))??he(i?.(r))??he(e?.error?.(r))??he(t.customError?.(r))??he(t.localeError?.(r))??"Invalid input",a={};for(let u of Object.keys(r))u==="inst"||u==="schema"||u==="continue"||u==="input"||u==="__proto__"||(a[u]=r[u]);return a.path??(a.path=[]),a.message=s,e?.reportInput&&(a.input=r.input),a}function ms(r){return r instanceof Set?"set":r instanceof Map?"map":r instanceof File?"file":"unknown"}var _s=/[\uD800-\uDBFF]/;function ys(r){let e=r.length;if(!_s.test(r))return e;let t=e;for(let n=0;n<e-1;n++)(r.charCodeAt(n)&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320&&(t--,n++);return t}function vs(r){return Array.isArray(r)?"array":typeof r=="string"?"string":"unknown"}function bs(r){let e=typeof r;switch(e){case"number":return Number.isNaN(r)?"nan":"number";case"object":{if(r===null)return"null";if(Array.isArray(r))return"array";let t=r;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&"constructor"in t&&t.constructor)return t.constructor.name}}return e}function ct(...r){let[e,t,n]=r;return typeof e=="string"?{message:e,code:"custom",input:t,inst:n}:{...e}}function xs(r){return Object.entries(r).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function mn(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function _n(r){let e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e)}function ws(r){let e=r.replace(/-/g,"+").replace(/_/g,"/"),t="=".repeat((4-e.length%4)%4);return mn(e+t)}function Ps(r){return _n(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Es(r){let e=r.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=Number.parseInt(e.slice(n,n+2),16);return t}function $s(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}var qt=class{constructor(...e){}};function tr(r,e){for(let t in e){let n=Object.getOwnPropertyDescriptor(e,t);n.get?Object.defineProperty(r,t,{...n,enumerable:!1}):Ss(r,t,n.value)}}function U(r,e,t,n=!0){return Object.defineProperty(r,e,{configurable:!0,writable:!0,enumerable:n,value:t}),t}function rr(r,e,t){return U(r,e,t,!1)}function Fs(r,e){for(let t in r){let n=r[t];Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){return U(this,t,n(this))},set(o){U(this,t,o)}})}return e}function Ss(r,e,t){Object.defineProperty(r,e,{configurable:!0,get(){return this==null?t:U(this,e,t.bind(this))},set(n){U(this,e,n)}})}function Is(r,e){let t=Object.getPrototypeOf(r);return e in t?void 0:t}var Gt,re=!1,As={configurable:!0,get(){re=!0}};function D(r,e,t){let n=Object.getPrototypeOf(r._zod);if(e in n&&Gt!==r._zod){Gt=void 0;return}Gt=r._zod,Object.defineProperty(n,e,{configurable:!0,get(){Object.defineProperty(this,e,As);let o=re;re=!1;try{let i=t(this);return re?delete this[e]:Object.defineProperty(this,e,{configurable:!0,writable:!0,value:i}),re=re||o,i}catch(i){throw delete this[e],re=re||o,i}},set(o){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:o})}})}function nr(r,e,t,n){let o=Is(r,e);o&&Object.defineProperty(o,e,{configurable:!0,get(){let i={configurable:!0,writable:!0,enumerable:n,value:void 0};return Object.defineProperty(this,e,i),i.value=t(this),Object.defineProperty(this,e,i),i.value},set(i){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:n,value:i})}})}var yn="~constantCatch";function vn(r){let e=()=>r;return e[yn]=!0,e}var bn;var or={value:void 0,enumerable:!1},xn="captureStackTrace"in Error?Error:null;function Cs(r){let e=xn;if(e){let t=e.stackTraceLimit;if(typeof t=="number"){try{e.stackTraceLimit=0}catch{return xn=null,new r}try{return new r}finally{e.stackTraceLimit=t}}}return new r}function b(r,e,t,n){let o={};function i(p){this.def=p,this.constr=f,this.traits=new Set}i.prototype=o;let s=t,a=s&&new WeakSet;function u(p,d){if(p._zod){if(p._zod.traits.has(r))return}else{or.value=new i(d);try{Object.defineProperty(p,"_zod",or)}finally{or.value=void 0}}if(p._zod.traits.add(r),e(p,d),a){let g=Object.getPrototypeOf(p),w=p._zod.constr.prototype,_=g;for(;_&&_!==w;)_=Object.getPrototypeOf(_);let v=_??g;a.has(v)||(a.add(v),tr(v,s))}let h=f.prototype;for(let g in h)Object.prototype.hasOwnProperty.call(h,g)&&(g in p||(p[g]=h[g].bind(p)))}let c=n?.Parent??Object;class l extends c{}Object.defineProperty(l,"name",{value:r});function f(p){let d=n?.Parent?Cs(l):this;u(d,p);let h=d._zod.deferred;if(h){for(let w of h)w();d._zod.deferred=void 0}let g=globalThis.__zod_globalConfig?.postProcessor;return g&&g(d),d}return Object.defineProperty(f,"init",{value:u}),Object.defineProperty(f,Symbol.hasInstance,{value:p=>n?.Parent&&p instanceof n.Parent?!0:p?._zod?.traits?.has(r)}),Object.defineProperty(f,"name",{value:r}),f}var X=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};(bn=globalThis).__zod_globalConfig??(bn.__zod_globalConfig={});var ae=globalThis.__zod_globalConfig;function ce(r){return r&&Object.assign(ae,r),ae}function ks(){let r=this._zod;return r.message??(r.message=JSON.stringify(r.def,Vt,2)),r.message}function Rs(r){this._zod.message=r}var zs={get:ks,set:Rs,enumerable:!0,configurable:!0},sr={value:void 0,enumerable:!1},wn=new WeakSet([Object.prototype,Error.prototype]),Pn=(r,e)=>{r.name="$ZodError",sr.value=e,Object.defineProperty(r,"issues",sr),sr.value=void 0,Object.defineProperty(r,"message",zs);let t=Object.getPrototypeOf(r);wn.has(t)||(wn.add(t),Object.defineProperty(t,"toString",{configurable:!0,enumerable:!1,get(){let n=()=>this.message;return Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0})}}))},Nu=b("$ZodError",Pn),ke=b("$ZodError",Pn,void 0,{Parent:Error});var Ts=r=>{let e=(t,n,o,i)=>{let s=o?{...o,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new X;if(a.issues.length){let u=new(i?.Err??r)(a.issues.map(c=>ne(c,s,ce())));throw nt(u,i?.callee??e),u}return a.value};return e},ar=Ts(ke),Ms=r=>{let e=async(t,n,o,i)=>{let s=o?{...o,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){let u=new(i?.Err??r)(a.issues.map(c=>ne(c,s,ce())));throw nt(u,i?.callee??e),u}return a.value};return e},cr=Ms(ke),Ls=r=>(e,t,n)=>{let o=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:t,issues:[]},o);if(i instanceof Promise)throw new X;return i.issues.length?En(r,i.issues,o):{success:!0,data:i.value}},ur=Ls(ke);function En(r,e,t){let n;return{success:!1,get error(){return n||(n=new r(e.map(o=>ne(o,t,ce()))),e=void 0,t=void 0),n},set error(o){n=o,e=void 0,t=void 0}}}var Ns=r=>async(e,t,n)=>{let o=n?{...n,async:!0}:{async:!0},i=e._zod.run({value:t,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?En(r,i.issues,o):{success:!0,data:i.value}},lr=Ns(ke);var $n=/^[\s\S]{0,}$/;var Fn=/^-?\d+(?:\.\d+)?$/,Sn=/^(?:true|false)$/i;var Re=b("$ZodCheck",(r,e)=>{var t;r._zod??(r._zod={}),r._zod.def=e,(t=r._zod).onattach??(t.onattach=[])});var In=b("$ZodCheckStringFormat",(r,e)=>{var t,n;Re.init(r,e),e.pattern?(t=r._zod).check??(t.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:r,continue:!e.abort})}):(n=r._zod).check??(n.check=()=>{})}),An=b("$ZodCheckRegex",(r,e)=>{In.init(r,e),r._zod.check=t=>{e.pattern.lastIndex=0,!e.pattern.test(t.value)&&t.issues.push({origin:"string",code:"invalid_format",format:"regex",input:t.value,pattern:e.pattern.toString(),inst:r,continue:!e.abort})}});var kn={major:4,minor:6,patch:6};var O=b("$ZodType",(r,e)=>{var t;r??(r={}),r._zod.def=e,r._zod.bag=r._zod.bag||{},r._zod.version=kn;let n=r._zod.def.checks,o=r._zod.traits.has("$ZodCheck")?[r,...n??[]]:n?.length?[...n]:[];for(let i of o)for(let s of i._zod.onattach)s(r);if(o.length===0)(t=r._zod).deferred??(t.deferred=[]),r._zod.deferred?.push(()=>{r._zod.run=r._zod.parse});else{let i=(a,u,c)=>{if(a.memo)return a;let l=q(a),f;for(let p of u){if(p._zod.def.when){if(er(a)||!p._zod.def.when(a))continue}else if(l)continue;let d=a.issues.length,h=p._zod.check(a);if(h instanceof Promise&&c?.async===!1)throw new X;if(f||h instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await h,a.issues.length!==d&&(Ce(a.issues,d,r),l||(l=q(a,d)))});else{if(a.issues.length===d)continue;Ce(a.issues,d,r),l||(l=q(a,d))}}return f?f.then(()=>a):a},s=(a,u,c)=>{if(q(a))return a.aborted=!0,a;let l=i(u,o,c);if(l instanceof Promise){if(c.async===!1)throw new X;return l.then(f=>r._zod.parse(f,c))}return r._zod.parse(l,c)};r._zod.run=(a,u)=>{if(u.skipChecks)return r._zod.parse(a,u);if(u.direction==="backward"){let l=r._zod.parse({value:a.value,issues:[]},{...u,skipChecks:!0});return l instanceof Promise?l.then(f=>s(f,a,u)):s(l,a,u)}let c=r._zod.parse(a,u);if(c instanceof Promise){if(u.async===!1)throw new X;return c.then(l=>i(l,o,u))}return i(c,o,u)}}},{get"~standard"(){return rr(this,"~standard",Zs(this))},set"~standard"(r){U(this,"~standard",r)}}),Ln=(r,e)=>r.issues.length?{issues:r.issues.map(t=>ne(t,e,ce()))}:{value:r.value};async function Ds(r,e){let t={async:!0};return Ln(await r._zod.run({value:e,issues:[]},t),t)}function Zs(r){return{validate:e=>{let t={async:!1};try{let n=r._zod.run({value:e,issues:[]},t);if(!(n instanceof Promise))return Ln(n,t)}catch{}return Ds(r,e)},vendor:"zod",version:1}}var Nn=b("$ZodString",(r,e)=>{O.init(r,e),r._zod.pattern=e.pattern??$n,r._zod.parse=(t,n)=>{if(e.coerce)try{t.value=String(t.value)}catch{}return typeof t.value=="string"||t.issues.push({expected:"string",code:"invalid_type",input:t.value,inst:r}),t}});var Dn=b("$ZodNumber",(r,e)=>{O.init(r,e),r._zod.pattern=Fn,r._zod.parse=(t,n)=>{if(e.coerce)try{t.value=Number(t.value)}catch{}let o=t.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return t;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:String(o):void 0;return t.issues.push({expected:"number",code:"invalid_type",input:o,inst:r,...i?{received:i}:{}}),t}});var Zn=b("$ZodBoolean",(r,e)=>{O.init(r,e),r._zod.pattern=Sn,r._zod.parse=(t,n)=>{if(e.coerce)try{t.value=!!t.value}catch{}let o=t.value;return typeof o=="boolean"||t.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:r}),t}});function js(r,e){let t=at(r._zod.def.checks);if(!t.length)return;let n=Math.min(...t.map(i=>i[0])),o=r._zod.parse;r._zod.parse=(i,s)=>{let a=e(i.value);if(a>n&&!s?.skipChecks&&s?.direction!=="backward"){for(let[u,c]of at(r._zod.def.checks))if(a>u&&c._zod.def.when(i)){let l=i.issues.length;return c._zod.check(i),i.issues[l].continue=!1,Ce(i.issues,l,r),i}}return o(i,s)}}var Us=r=>Array.isArray(r)?r.length:-1;function Rn(r,e,t){r.issues.length&&e.issues.push(...st(t,r.issues)),e.value[t]=r.value}var jn=b("$ZodArray",(r,e)=>{O.init(r,e);let t=ae.memoizer;t?.attach(r),r._zod.parse=(n,o)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:r}),n;n.value=t?t.alloc(r,n,Array(i.length),o):Array(i.length);let s=[],a=o?.abortEarly;for(let u=0;u<i.length;u++){let c=i[u],l=e.element._zod.run({value:c,issues:[]},o);if(l instanceof Promise)s.push(l.then(f=>Rn(f,n,u)));else if(Rn(l,n,u),a&&l.issues.length!==0&&q(l))break}return s.length?Promise.all(s).then(()=>n):n},js(r,Us)});function ut(r,e,t,n,o,i){let s=t in n,a=i==="optional";if(!(!s&&a&&o==="optional")){if(r.issues.length){if(o!==void 0&&a&&!s)return;e.issues.push(...st(t,r.issues))}if(!s&&o===void 0){r.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[t]});return}r.value===void 0?(s||o==="defaulted"&&!a)&&(e.value[t]=void 0):e.value[t]=r.value}}var Bs=[];function Hs(r){let e=Object.keys(r.shape),t=Object.getOwnPropertySymbols(r.shape),n=t.length?t:Bs,o=n.length?[...e,...n]:e;for(let s of o)if(!r.shape?.[s]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(s)}": expected a Zod schema`);let i=Yt(r.shape);return{...r,allKeys:o,symbolKeys:n,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(i)}}function Ks(r,e,t,n,o,i,s){let a=[],u=o.keySet,c=o.catchall._zod,l=c.def.type,f=c.optin,p=c.optout,d=0;for(let h in e){if(s&&t.issues.length!==d){if(q(t,d))break;d=t.issues.length}if(u.has(h))continue;if(h==="__proto__"){l==="never"&&a.push(h);continue}if(l==="never"){a.push(h);continue}let g=c.run({value:e[h],issues:[]},n);g instanceof Promise?r.push(g.then(w=>ut(w,t,h,e,f,p))):ut(g,t,h,e,f,p)}return a.length&&t.issues.push({code:"unrecognized_keys",keys:a,input:e,inst:i,continue:!0}),r.length?Promise.all(r).then(()=>t):t}var Un=b("$ZodObject",(r,e)=>{O.init(r,e);let t=Object.getOwnPropertyDescriptor(e,"shape"),n=t?.get?t.get.raw:e.shape??{};if(n){let c=()=>{let l={...n};return Object.defineProperty(e,"shape",{value:l}),c.raw=l,l};c.raw=n,Object.defineProperty(e,"shape",{get:c})}let o=rt(()=>Hs(e));D(r,"propValues",c=>{let l=c.def.shape,f={};for(let p in l){let d=l[p]._zod;if(d.values){Object.prototype.hasOwnProperty.call(f,p)||Se(f,p,new Set);for(let h of d.values)f[p].add(h);d.optin!==void 0&&f[p].add(void 0)}}return f});let i=Fe,s=e.catchall,a,u=ae.memoizer;u?.attach(r),r._zod.parse=(c,l)=>{a??(a=o.value);let f=c.value;if(!i(f))return c.issues.push({expected:"object",code:"invalid_type",input:f,inst:r}),c;c.value=u?u.alloc(r,c,{},l):{};let p=[],d=a.shape,h=l?.abortEarly,g=c.issues.length;for(let w of a.allKeys){if(h&&c.issues.length!==g){if(q(c,g))break;g=c.issues.length}if(w==="__proto__")continue;let _=d[w],v=_._zod.optin,R=_._zod.optout,I=_._zod.run({value:f[w],issues:[]},l);I instanceof Promise?p.push(I.then(x=>ut(x,c,w,f,v,R))):ut(I,c,w,f,v,R)}return s?Ks(p,f,c,l,o.value,r,h===!0):p.length?Promise.all(p).then(()=>c):c}});var Bn=b("$ZodEnum",(r,e)=>{O.init(r,e);let t=tt(e.entries),n=new Set(t);r._zod.values=n,D(r,"pattern",o=>{let i=tt(o.def.entries).filter(s=>Qt.has(typeof s));return new RegExp(i.length?`^(${i.map(s=>Ae(s.toString())).join("|")})$`:"^[^\\s\\S]$")}),r._zod.parse=(o,i)=>{let s=o.value;return n.has(s)||o.issues.push({code:"invalid_value",values:t,input:s,inst:r}),o}}),Hn=b("$ZodLiteral",(r,e)=>{O.init(r,e);let t=new Set(e.values);r._zod.values=t,D(r,"pattern",n=>{let o=n.def.values;return new RegExp(o.length?`^(${o.map(i=>typeof i=="string"?Ae(i):i?Ae(i.toString()):String(i)).join("|")})$`:"^[^\\s\\S]$")}),r._zod.parse=(n,o)=>{let i=n.value;return t.has(i)||n.issues.push({code:"invalid_value",values:e.values,input:i,inst:r}),n}});function zn(r,e){return r.value=e.issues.length?void 0:e.value,r}var Kn=b("$ZodOptional",(r,e)=>{O.init(r,e),D(r,"optin",t=>t.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),r._zod.optout="optional",D(r,"values",t=>{let n=t.def.innerType._zod.values;return n?new Set([...n,void 0]):void 0}),D(r,"pattern",t=>{let n=t.def.innerType._zod.pattern;return n?new RegExp(`^(${Xt(n.source)})?$`):void 0}),r._zod.parse=(t,n)=>{if(t.value===void 0){if(e.innerType._zod.optin!=="defaulted")return t;let o=e.innerType._zod.run({value:t.value,issues:[]},n);return o instanceof Promise?o.then(i=>zn(t,i)):zn(t,o)}return e.innerType._zod.run(t,n)}});var Gn=b("$ZodDefault",(r,e)=>{O.init(r,e),r._zod.optin="defaulted",D(r,"values",t=>t.def.innerType._zod.values),r._zod.parse=(t,n)=>{if(n.direction==="backward")return e.innerType._zod.run(t,n);if(t.value===void 0)return t.value=e.defaultValue,t;let o=e.innerType._zod.run(t,n);return o instanceof Promise?o.then(i=>On(i,e)):On(o,e)}});function On(r,e){return r.value===void 0&&(r.value=e.defaultValue),r}function Tn(r,e,t,n){return e.issues.length?(r.value=t.catchValue({...e,value:r.value,error:{issues:e.issues.map(o=>ne(o,n,ce()))},input:r.value}),r):(r.value=e.value,e.memo&&(r.memo=!0),r)}var Wn=b("$ZodCatch",(r,e)=>{O.init(r,e),D(r,"optin",t=>t.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),D(r,"optout",t=>t.def.innerType._zod.optout),D(r,"values",t=>t.def.innerType._zod.values),r._zod.parse=(t,n)=>{if(n.direction==="backward")return e.innerType._zod.run(t,n);let o=e.innerType._zod.run({value:t.value,issues:[]},n);return o instanceof Promise?o.then(i=>Tn(t,i,e,n)):Tn(t,o,e,n)}});var qn=b("$ZodCustom",(r,e)=>{Re.init(r,e),O.init(r,e),r._zod.parse=(t,n)=>t,r._zod.check=t=>{let n=t.value,o=e.fn(n);if(o instanceof Promise)return o.then(i=>Mn(i,t,n,r));Mn(o,t,n,r)}});function Mn(r,e,t,n){if(!r){let o={code:"custom",input:t,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(ct(o))}}function Vn(r){return r.checks&&(r.checks=[...r.checks]),r}function Xn(r,e){return new r(Vn({type:"string",...N(e)}))}function Jn(r,e){return new r(Vn({type:"number",checks:[],...N(e)}))}function Qn(r,e){return new r({type:"boolean",...N(e)})}function pr(r,e){return new An({check:"string_format",format:"regex",...N(e),pattern:r})}function Yn(r,e,t){let n=N(t);return n.abort??(n.abort=!0),new r({type:"custom",check:"custom",fn:e,...n})}var j=b("ZodMiniType",(r,e)=>{if(!r._zod)throw new Error("Uninitialized schema in ZodMiniType.");O.init(r,e),r.def=e,r.type=e.type},{get with(){return this.check},set with(r){U(this,"with",r)},parse(r,e){return ar(this,r,e,{callee:this.parse})},parseAsync(r,e){return cr(this,r,e,{callee:this.parseAsync})},safeParse(r,e){return ur(this,r,e)},safeParseAsync(r,e){return lr(this,r,e)},check(...r){let e=this.def;return this.clone({...e,checks:[...e.checks??[],...r.map(t=>typeof t=="function"?{_zod:{check:t,def:{check:"custom"},onattach:[]}}:t)]},{parent:!0})},clone(r,e){return L(this,r,e)},brand(){return this},register(r,e){return r.add(this,e),this},apply(r,...e){return e.length===0?r(this):r(this,...e)}}),qs=b("ZodMiniString",(r,e)=>{Nn.init(r,e),j.init(r,e)});function ue(r){return Xn(qs,r)}var Vs=b("ZodMiniNumber",(r,e)=>{Dn.init(r,e),j.init(r,e)});function dr(r){return Jn(Vs,r)}var Xs=b("ZodMiniBoolean",(r,e)=>{Zn.init(r,e),j.init(r,e)});function J(r){return Qn(Xs,r)}var Js=b("ZodMiniArray",(r,e)=>{jn.init(r,e),j.init(r,e)});function hr(r,e){return new Js({type:"array",element:r,...N(e)})}var Qs=b("ZodMiniObject",(r,e)=>{Un.init(r,e),j.init(r,e),nr(r,"shape",t=>t._zod.def.shape,!1)});function gr(r,e){let t={type:"object",shape:r??{},...N(e)};return new Qs(t)}var Ys=b("ZodMiniEnum",(r,e)=>{Bn.init(r,e),j.init(r,e),r.options=[...r._zod.values]});function eo(r,e){let t=Array.isArray(r)?Object.fromEntries(r.map(n=>[n,n])):r;return new Ys({type:"enum",entries:t,...N(e)})}var ea=b("ZodMiniLiteral",(r,e)=>{Hn.init(r,e),j.init(r,e)});function to(r,e){return new ea({type:"literal",values:Array.isArray(r)?r:[r],...N(e)})}var ta=b("ZodMiniOptional",(r,e)=>{Kn.init(r,e),j.init(r,e)});function A(r){return new ta({type:"optional",innerType:r})}var ra=b("ZodMiniDefault",(r,e)=>{Gn.init(r,e),j.init(r,e)});function ge(r,e){return new ra({type:"default",innerType:r,get defaultValue(){return typeof e=="function"?e():ot(e)}})}var na=b("ZodMiniCatch",(r,e)=>{Wn.init(r,e),j.init(r,e)});function ro(r,e){return new na({type:"catch",innerType:r,catchValue:typeof e=="function"?e:V.constantCatch(e)})}var oa=b("ZodMiniCustom",(r,e)=>{qn.init(r,e),j.init(r,e)});function mr(r,e){return Yn(oa,r??(()=>!0),e)}var no="https://in.dev.heycatch.ai",ze="dev",Oe="0.8.5-dev.2546",oo="phc_CqKdgm7xbFBs3mSdtqzrHNTfzTRKrwRmCrEB9aftENY9";function me(){return typeof globalThis.window<"u"}function io(r=ze){return r!=="dev"?null:`[HeyCatch] WARNING: this is an internal development build (v${Oe}). Events are being sent to the HeyCatch development environment and will NEVER appear in your dashboard. Reinstall the latest stable version - resolve it with \`npm view @heycatch/sdk version\` - or re-run the install guide: https://heycatch.ai/agents.md`}var lt=["X-HeyCatch-Session-Id","X-HeyCatch-Window-Id","X-HeyCatch-Distinct-Id"],oe="unknown",ca=["localStorage","cookie","memory","localStorage+cookie","sessionStorage"];var so=gr({projectKey:ue({error:'config.projectKey is missing or malformed \u2014 expected a string starting with "hck_pk_". Copy it from your project page in the HeyCatch dashboard.'}).check(pr(/^hck_pk_/,{error:'config.projectKey is missing or malformed \u2014 expected a string starting with "hck_pk_". Copy it from your project page in the HeyCatch dashboard.'})),tracingHosts:ge(hr(ue()),[]),install:ge(gr({framework:ge(ue(),oe),frameworkVersion:ge(ue(),oe),agent:ge(ue(),oe)}),{framework:oe,frameworkVersion:oe,agent:oe}),autocapture:A(J()),maskAllText:A(J()),maskAllElementAttributes:A(J()),propertyDenylist:A(hr(ue())),sanitizeProperties:A(mr(r=>typeof r=="function")),beforeSend:A(mr(r=>typeof r=="function"||Array.isArray(r)&&r.every(e=>typeof e=="function"))),persistence:A(eo(ca)),disablePersistence:A(J()),cookieExpirationDays:A(dr()),optOutCapturingByDefault:A(J()),respectDnt:A(J()),collectIp:A(J()),requestBatching:A(J()),flushIntervalMs:A(dr()),site:ro(A(to("landing")),r=>{let e=typeof r.value=="string"?JSON.stringify(r.value):`a ${typeof r.value}`;console.error(`[HeyCatch] config.site must be 'landing' or omitted - got ${e}. Ignoring it; this project is reported as untagged.`)})}),ao=["nextjs","vite-react","react","vue","svelte","astro","angular","react-native","web"],co=["lovable","bolt","v0","replit","cursor","claude-code","codex","windsurf","other"];var _e=require("path");function lo(){let r=ua();return async e=>{for(let t of e)t.module=r(t.filename);return e}}function ua(r=process.argv[1]?(0,_e.dirname)(process.argv[1]):process.cwd(),e=_e.sep==="\\"){let t=e?uo(r):r;return n=>{if(!n)return;let o=e?uo(n):n,{dir:i,base:s,ext:a}=_e.posix.parse(o);(a===".js"||a===".mjs"||a===".cjs")&&(s=s.slice(0,-1*a.length));let u=decodeURIComponent(s);i||(i=".");let c=i.lastIndexOf("/node_modules");if(c>-1)return`${i.slice(c+14).replace(/\//g,".")}:${u}`;if(i.startsWith(t)){let l=i.slice(t.length+1).replace(/\//g,".");return l?`${l}:${u}`:u}return u}}function uo(r){return r.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var _r=r=>{if("flags"in r){let e=fo(r.flags),t=po(r.flags);return{...r,featureFlags:e,featureFlagPayloads:t}}{let e=r.featureFlags??{},t=Object.fromEntries(Object.entries(r.featureFlagPayloads||{}).map(([o,i])=>[o,ft(i)])),n=Object.fromEntries(Object.entries(e).map(([o,i])=>[o,la(o,i,t[o])]));return{...r,featureFlags:e,featureFlagPayloads:t,flags:n}}};function la(r,e,t){return{key:r,enabled:typeof e=="string"?!0:e,variant:typeof e=="string"?e:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:t?JSON.stringify(t):void 0,description:void 0}}}var fo=r=>Object.fromEntries(Object.entries(r??{}).map(([e,t])=>[e,Te(t)]).filter(([,e])=>e!==void 0)),po=r=>{let e=r??{};return Object.fromEntries(Object.keys(e).filter(t=>{let n=e[t];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(t=>{let n=e[t].metadata?.payload;return[t,n?ft(n):void 0]}))},Te=r=>r===void 0?void 0:r.variant??r.enabled,ft=r=>{if(typeof r!="string")return r;try{return JSON.parse(r)}catch{return r}};var fa=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Me=(r,e=[])=>{let t={},n=o=>{r[o]!==void 0&&(t[o]=r[o])};return fa.forEach(n),e.forEach(n),t};var T=(function(r){return r.AnonymousId="anonymous_id",r.DistinctId="distinct_id",r.Props="props",r.EnablePersonProcessing="enable_person_processing",r.PersonMode="person_mode",r.FeatureFlagDetails="feature_flag_details",r.FeatureFlags="feature_flags",r.FeatureFlagPayloads="feature_flag_payloads",r.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",r.BootstrapFeatureFlags="bootstrap_feature_flags",r.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",r.OverrideFeatureFlags="override_feature_flags",r.Queue="queue",r.AiQueue="ai_queue",r.LogsQueue="logs_queue",r.OptedOut="opted_out",r.SessionId="session_id",r.SessionStartTimestamp="session_start_timestamp",r.SessionLastTimestamp="session_timestamp",r.PersonProperties="person_properties",r.GroupProperties="group_properties",r.InstalledAppBuild="installed_app_build",r.InstalledAppVersion="installed_app_version",r.SessionReplay="session_replay",r.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",r.SurveyLastSeenDate="survey_last_seen_date",r.SurveysSeen="surveys_seen",r.Surveys="surveys",r.RemoteConfig="remote_config",r.FlagsEndpointWasHit="flags_endpoint_was_hit",r.DeviceId="device_id",r})({});function yr(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var da="NativeGzipValidationError",ha=31,ga=139,ma=8,_a=r=>r.length>=2&&r[0]===ha&&r[1]===ga;var Le,ya=()=>{if(Le)return Le;Le=[];for(let r=0;r<256;r++){let e=r;for(let t=0;t<8;t++)e=1&e?3988292384^e>>>1:e>>>1;Le[r]=e>>>0}return Le},va=r=>{let e=ya(),t=4294967295;for(let n=0;n<r.length;n++)t=e[(t^r[n])&255]^t>>>8;return(4294967295^t)>>>0},pt=r=>{let e=new Error(`Native gzip produced invalid output: ${r}`);throw e.name=da,e},ba=async(r,e)=>{r.size<18&&pt("too-short");let t=new Uint8Array(await r.slice(0,10).arrayBuffer());(!_a(t)||t[2]!==ma)&&pt("invalid-header");let n=new DataView(await r.slice(r.size-8).arrayBuffer());n.getUint32(0,!0)!==va(e)&&pt("invalid-crc");let o=e.length>>>0;n.getUint32(4,!0)!==o&&pt("invalid-size")};async function le(r,e=!0,t){try{let n=new TextEncoder().encode(r),o=new globalThis.CompressionStream("gzip"),i=o.writable.getWriter(),s=i.write(n).then(()=>i.close()).catch(async c=>{try{await i.abort(c)}catch{}throw c}),a=new Response(o.readable).blob(),[u]=await Promise.all([a,s]);return await ba(u,n),u}catch(n){if(t?.rethrow)throw n;return e&&console.error("Failed to gzip compress data",n),null}}var xa=["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"],ho=function(r,e=[]){if(!r)return!1;let t=r.toLowerCase();return xa.concat(e).some(n=>{let o=n.toLowerCase();return t.indexOf(o)!==-1})};function ye(r){let e=[];return JSON.stringify(r,function(t,n){if(typeof n=="bigint")return n.toString();if(!(typeof n=="function"||typeof n=="symbol")){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;e.length>0&&e[e.length-1]!==this;)e.pop();if(e.includes(n))return"[Circular]";e.push(n)}return n}})??"null"}var Pa=Array.isArray,go=Object.prototype,rh=go.hasOwnProperty,dt=go.toString,H=Pa||function(r){return dt.call(r)==="[object Array]"};var Ne=r=>r===Object(r)&&!H(r);var fe=r=>r===void 0,Q=r=>dt.call(r)=="[object String]",mo=r=>Q(r)&&r.trim().length===0,_o=r=>r===null;var De=r=>dt.call(r)=="[object Number]"&&r===r;var yo=r=>dt.call(r)==="[object Boolean]";var vo=r=>r instanceof Error;function ht(r){return r===null||typeof r!="object"}function pe(r,e){return Object.prototype.toString.call(r)===`[object ${e}]`}function bo(r){return pe(r,"ErrorEvent")}function ve(r){return typeof Event<"u"&&Ea(r,Event)}function xo(r){return pe(r,"Object")}function Ea(r,e){try{return r instanceof e}catch{return!1}}function Ze(r,e,t,n,o){return e>t&&(n.warn("min cannot be greater than max."),e=t),De(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: "+o),Ze(o||t,e,t,n))}var $a=864e5,Fa=1,Sa=10;function wo(r={}){return{refillRate:r.exceptionRateLimiterRefillRate??r.__exceptionRateLimiterRefillRate??Fa,bucketSize:r.exceptionRateLimiterBucketSize??r.__exceptionRateLimiterBucketSize??Sa}}var gt=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=Ze(e.bucketSize,0,100,e._logger),this._refillRate=Ze(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=Ze(e.refillInterval,0,$a,e._logger)}_applyRefill(e,t){let n=t-e.lastAccess,o=Math.floor(n/this._refillInterval);if(o>0){let i=o*this._refillRate;e.tokens=Math.min(e.tokens+i,this._bucketSize),e.lastAccess=e.lastAccess+o*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),n=String(e),o=this._buckets[n];return o?this._applyRefill(o,t):(o={tokens:this._bucketSize,lastAccess:t},this._buckets[n]=o),o.tokens===0?!0:(o.tokens--,o.tokens===0&&this._onBucketRateLimited?.(e),o.tokens===0)}stop(){this._buckets={}}};var mt="0123456789abcdef",_t=class r{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new r(e);throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,n,o){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(o)||e<0||t<0||n<0||o<0||e>0xffffffffffff||t>4095||n>1073741823||o>4294967295)throw new RangeError("invalid field value");let i=new Uint8Array(16);return i[0]=e/2**40,i[1]=e/2**32,i[2]=e/2**24,i[3]=e/2**16,i[4]=e/256,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]=o>>>24,i[13]=o>>>16,i[14]=o>>>8,i[15]=o,new r(i)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;default:break}if(t){let n=new Uint8Array(16);for(let o=0;o<16;o+=4){let i=parseInt(t.substring(2*o,2*o+8),16);n[o+0]=i>>>24,n[o+1]=i>>>16,n[o+2]=i>>>8,n[o+3]=i}return new r(n)}throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=mt.charAt(this.bytes[t]>>>4),e+=mt.charAt(15&this.bytes[t]),(t===3||t===5||t===7||t===9)&&(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=mt.charAt(this.bytes[t]>>>4),e+=mt.charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw new Error("unreachable");if(e<=7)return this.bytes.every(t=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(t=>t===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new r(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}},vr=class{constructor(e){this.timestamp=0,this.counter=0,this.random=e??Ia()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let n=this.generateOrAbortCore(e,t);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(e,t)),n}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return _t.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,_t.ofInner(e)}},Ia=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),Po,M=()=>Aa().toString(),Aa=()=>(Po||(Po=new vr)).generate();var yt=class{add(e){let t=M(),n=++this.nextId;return this.promiseByIds[t]={id:n,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map(n=>n.promise),t=e.length;for(;t>0;)await Promise.all(e),e=Object.values(this.promiseByIds).map(n=>n.promise),t=e.length}getPromises(e=[],t=this.nextId){let n=new Set(e);return Object.values(this.promiseByIds).filter(o=>o.id<=t&&!n.has(o.promise)).map(o=>o.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}};function Ca(r=console){return{log:r.log.bind(r),warn:r.warn.bind(r),error:r.error.bind(r),debug:r.debug.bind(r)}}var Eo=(r,e,t)=>{function n(i,...s){e(()=>{let a=t[i];a(r,...s)})}return{debug:(...i)=>{n("debug",...i)},info:(...i)=>{n("log",...i)},warn:(...i)=>{n("warn",...i)},error:(...i)=>{n("error",...i)},critical:(...i)=>{t.error(r,...i)},createLogger:i=>Eo(`${r} ${i}`,e,t)}},ka=r=>r();function $o(r,e=ka){return Eo(r,e,Ca())}var xe="Mobile",bt="iOS",be="Android",Co="Tablet",hh=be+" "+Co;var za="Apple",gh=za+" Watch",ko="Safari",xt="BlackBerry",Ro="Samsung",Oa=Ro+"Browser",Ta=Ro+" Internet",wt="Chrome",Ma=wt+" OS",La=wt+" "+bt,zo="Internet Explorer",Na=zo+" "+xe,xr="Opera",mh=xr+" Mini",Oo="Edge",Da="Microsoft "+Oo,wr="Firefox",Za=wr+" "+bt,Pr="Nintendo",Er="PlayStation",vt="Xbox",ja=be+" "+xe,Ua=xe+" "+ko,je="Windows",Ba=je+" Phone";var To="Generic",_h=To+" "+xe.toLowerCase(),yh=To+" "+Co.toLowerCase(),Ha="Konqueror",Ka="Oculus Browser",Fo="Vivaldi",Ga="Yandex",So="Whale",Wa="DuckDuckGo",qa="Pale Moon",Io="Waterfox",Ao="Brave",Va="Google Search App",E="(\\d+(\\.\\d+)?)",br=new RegExp("Version/"+E);var vh=new RegExp(vt,"i"),bh=new RegExp(Er+" \\w+","i"),xh=new RegExp(Pr+" \\w+","i"),Xa=new RegExp(xt+"|PlayBook|BB10","i"),Ja={"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"};var wh={[Na]:[new RegExp("rv:"+E)],[Da]:[new RegExp(Oo+"?\\/"+E)],[wt]:[new RegExp("("+wt+"|CrMo)\\/"+E)],[La]:[new RegExp("CriOS\\/"+E)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+E)],[ko]:[br],[Ua]:[br],[xr]:[new RegExp("("+xr+"|OPR)\\/"+E)],[wr]:[new RegExp(wr+"\\/"+E)],[Za]:[new RegExp("FxiOS\\/"+E)],[Ha]:[new RegExp("Konqueror[:/]?"+E,"i")],[xt]:[new RegExp(xt+" "+E),br],[ja]:[new RegExp("android\\s"+E,"i")],[Ta]:[new RegExp(Oa+"\\/"+E)],[Ka]:[new RegExp("OculusBrowser\\/"+E)],[Fo]:[new RegExp(Fo+"\\/"+E)],[Ga]:[new RegExp("YaBrowser\\/"+E)],[So]:[new RegExp(So+"\\/"+E)],[Ao]:[new RegExp(Ao+"\\/"+E)],[Wa]:[new RegExp("(DuckDuckGo|Ddg)\\/"+E)],[qa]:[new RegExp("PaleMoon\\/"+E)],[Io]:[new RegExp(Io+"\\/"+E)],[Va]:[new RegExp("GSA\\/"+E)],[zo]:[new RegExp("(rv:|MSIE )"+E)],Mozilla:[new RegExp("rv:"+E)]};var Ph=[[new RegExp(vt+"; "+vt+" (.*?)[);]","i"),r=>[vt,r&&r[1]||""]],[new RegExp(Pr,"i"),[Pr,""]],[new RegExp(Er,"i"),[Er,""]],[Xa,[xt,""]],[new RegExp(je,"i"),(r,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Ba,""];if(new RegExp(xe).test(e)&&!/IEMobile\b/.test(e))return[je+" "+xe,""];let t=/Windows NT ([0-9.]+)/i.exec(e);if(t&&t[1]){let n=t[1],o=Ja[n]||"";return/arm/i.test(e)&&(o="RT"),[je,o]}return[je,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,r=>{if(r&&r[3]){let e=[r[3],r[4],r[5]||"0"];return[bt,e.join(".")]}return[bt,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,r=>{let e="";return r&&r.length>=3&&(e=fe(r[2])?r[3]:r[2]),["watchOS",e]}],[new RegExp("("+be+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+be+")","i"),r=>{if(r&&r[2]){let e=[r[2],r[3],r[4]||"0"];return[be,e.join(".")]}return[be,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,r=>{let e=["Mac OS X",""];if(r&&r[1]){let t=[r[1],r[2],r[3]||"0"];e[1]=t.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Ma,""]],[/Linux|debian/i,["Linux",""]]];var Mo="utf8",Qa=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ya(r){return typeof r=="string"&&Qa.test(r)}function Pt(r,e){return Ya(r)?r:e()}function Lo(r){return r?.replace(/\/+$/,"")}async function No(r,e){let t=null;for(let n=0;n<e.retryCount+1;n++){n>0&&await new Promise(o=>setTimeout(o,e.retryDelay));try{return await r()}catch(o){if(t=o,!e.retryCheck(o))throw o}}throw t}function $r(){return new Date().toISOString()}function C(r,e){let t=setTimeout(r,e);return t?.unref&&t?.unref(),t}var Do=r=>r instanceof Error;function Fr(r){return Promise.all(r.map(e=>(e??Promise.resolve()).then(t=>({status:"fulfilled",value:t}),t=>({status:"rejected",reason:t}))))}var tc={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},Th=tc.info;function Sr(r){if(yo(r))return{boolValue:r};if(typeof r=="number")return Number.isFinite(r)?Number.isInteger(r)?{intValue:r}:{doubleValue:r}:{stringValue:String(r)};if(typeof r=="string")return{stringValue:r};if(H(r))return{arrayValue:{values:r.map(e=>Sr(e))}};try{return{stringValue:JSON.stringify(r)}}catch{return{stringValue:String(r)}}}function Ue(r){let e=[];for(let t in r){let n=r[t];_o(n)||fe(n)||e.push({key:t,value:Sr(n)})}return e}var Be=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ir(r){return String(r)+"000000"}function Ar(r,e,t,n){let o="";return n&&(o=Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(n[s])}`).join(",")),`${r}\0${e}\0${t??""}\0${o}`}function Zo(r,e){for(let t=0;t<e.length;t++)if(r<=e[t])return t;return e.length}function Cr(r,e,t){return{...r.resourceAttributes,"service.name":r.serviceName||"unknown_service",...r.environment&&{"deployment.environment":r.environment},...r.serviceVersion&&{"service.version":r.serviceVersion},"telemetry.sdk.name":e,"telemetry.sdk.version":t}}function kr(r,e,t,n){return{resourceMetrics:[{resource:{attributes:Ue(e)},scopeMetrics:[{scope:{name:t,version:n},metrics:r}]}]}}function Et(r){let e=r?.resourceAttributes;return{serviceName:e?.["service.name"]??r?.serviceName,serviceVersion:e?.["service.version"]??r?.serviceVersion,environment:e?.["deployment.environment"]??r?.environment,resourceAttributes:e,beforeSend:r?.beforeSend,flushIntervalMs:r?.flushIntervalMs??1e4,maxSeriesPerFlush:r?.maxSeriesPerFlush??1e3}}var jo=1,He=class{constructor(e,t,n){this._instance=e,this._config=t,this._logger=n,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._generation=0}count(e,t=1,n){this._capture({name:e,type:"count",value:t,unit:n?.unit,attributes:n?.attributes})}gauge(e,t,n){this._capture({name:e,type:"gauge",value:t,unit:n?.unit,attributes:n?.attributes})}histogram(e,t,n){this._capture({name:e,type:"histogram",value:t,unit:n?.unit,attributes:n?.attributes})}flush(){let e=this._flushPromise,n=(async()=>{e&&await e.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===n&&(this._flushPromise=null)});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._clearFlushTimer(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(this._instance.isDisabled||this._instance.optedOut)return;let t=this._runBeforeSend(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this._logger.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&t.value<0)return void this._logger.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let n,o;try{n=t.attributes?{...t.attributes}:void 0,o=Ar(t.type,t.name,t.unit,n)}catch(a){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,a);return}let i=this._series.get(o);if(!i){if(!this._admitNewSeries())return;i={name:t.name,type:t.type,unit:t.unit,attributes:n,windowStartMs:Date.now()},this._series.set(o,i)}let s=this._typeByName.get(t.name);s===void 0?this._typeByName.set(t.name,t.type):s!==t.type&&!this._typeCollisionWarned.has(t.name)&&(this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${s}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`)),this._fold(i,t.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush?!0:(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:new Array(Be.length+1).fill(0)});let n=e.hist;n.count+=1,n.sum+=t,n.min=Math.min(n.min,t),n.max=Math.max(n.max,t),n.bucketCounts[Zo(t,Be)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let n=H(t)?t:[t],o=e;for(let i of n)try{let s=i(o);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;o=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return o}_armFlushTimer(){this._flushTimer||(this._flushTimer=C(()=>{this._flushTimer=void 0,this.flush().catch(e=>{this._logger.error("Metrics flush failed:",e)})},this._config.flushIntervalMs))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}async _doFlush(){if(this._series.size===0)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._armFlushTimer();return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(e){return kr(this._buildMetrics(e),Cr(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=Ir(Date.now()),n=new Map;for(let o of e.values()){let i=Ar(o.type,o.name,o.unit,void 0),s=n.get(i);s||(s={name:o.name,...o.unit&&{unit:o.unit}},o.type==="count"?s.sum={aggregationTemporality:jo,isMonotonic:!0,dataPoints:[]}:o.type==="gauge"?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:jo,dataPoints:[]},n.set(i,s));let a=Ue(o.attributes??{}),u=Ir(o.windowStartMs);if(o.type==="count"){let c={attributes:a,startTimeUnixNano:u,timeUnixNano:t,asDouble:o.total??0};s.sum.dataPoints.push(c)}else if(o.type==="gauge"){let c={attributes:a,timeUnixNano:t,asDouble:o.last??0};s.gauge.dataPoints.push(c)}else if(o.hist){let c={attributes:a,startTimeUnixNano:u,timeUnixNano:t,count:o.hist.count,sum:o.hist.sum,min:o.hist.min,max:o.hist.max,bucketCounts:o.hist.bucketCounts,explicitBounds:Be};s.histogram.dataPoints.push(c)}}return Array.from(n.values())}_mergeWindowBack(e){for(let[t,n]of e){let o=this._series.get(t);if(!o){this._admitNewSeries()&&this._series.set(t,n);continue}switch(o.windowStartMs=Math.min(o.windowStartMs,n.windowStartMs),o.type){case"count":o.total=(o.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(o.hist){o.hist.count+=n.hist.count,o.hist.sum+=n.hist.sum,o.hist.min=Math.min(o.hist.min,n.hist.min),o.hist.max=Math.max(o.hist.max,n.hist.max);for(let i=0;i<o.hist.bucketCounts.length;i++)o.hist.bucketCounts[i]+=n.hist.bucketCounts[i]}else o.hist=n.hist;break}}}};var $t=class{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(n=>n!==t)}}emit(e,t){for(let n of this.events[e]||[])n(t);for(let n of this.events["*"]||[])n(e,t)}};var z={};Kt(z,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>Ct,DOMExceptionCoercer:()=>Tr,EXCEPTION_STEP_INTERNAL_FIELDS:()=>Xe,ErrorCoercer:()=>Ge,ErrorEventCoercer:()=>Mr,ErrorPropertiesBuilder:()=>Ke,EventCoercer:()=>Lr,ExceptionStepsBuffer:()=>jr,ObjectCoercer:()=>qe,PrimitiveCoercer:()=>Ve,PromiseRejectionEventCoercer:()=>Nr,ReduceableCache:()=>Dr,StringCoercer:()=>We,chromeStackLineParser:()=>Rr,createDefaultStackParser:()=>Or,createStackParser:()=>Qo,geckoStackLineParser:()=>zr,getUtf8ByteLength:()=>ei,nodeStackLineParser:()=>qo,opera10StackLineParser:()=>Ko,opera11StackLineParser:()=>Go,resolveExceptionStepsConfig:()=>Zr,reverseAndStripFrames:()=>Jo,stripReservedExceptionStepFields:()=>Pc,winjsStackLineParser:()=>Ho});var Ft,Uo,St;function Bo(r){let e=globalThis._posthogChunkIds;if(!e)return;let t=Object.keys(e);return St&&t.length===Uo||(Uo=t.length,St=t.reduce((n,o)=>{Ft||(Ft={});let i=Ft[o];if(i)n[i[0]]=i[1];else{let s=r(o);for(let a=s.length-1;a>=0;a--){let c=s[a]?.filename,l=e[o];if(c&&l){n[c]=l,Ft[o]=[c,l];break}}}return n},{})),St}var ic=4,Ke=class{constructor(e,t,n=[]){this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t={}){let o=t&&t.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(o,t,0).apply(e),a=this.buildParsingContext(t),u=this.parseStacktrace(s,a);return{$exception_list:this.convertToExceptionList(u,o),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&H(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let n;e.cause!=null&&(n=this.parseStacktrace(e.cause,t));let o;return e.stack!=""&&e.stack!=null&&(o=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),{...e,cause:n,stack:o}}applyChunkIds(e,t){return e.map(n=>(n.filename&&t&&(n.chunk_id=t[n.filename]),n))}applyCoercers(e,t){for(let n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let n of this.modifiers)t=await n(t);return t}convertToExceptionList(e,t){let n={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};e.stack&&(n.stacktrace={type:"raw",frames:e.stack});let o=[n];return e.cause!=null&&o.push(...this.convertToExceptionList(e.cause,{...t,handled:!0})),o}buildParsingContext(e){return{chunkIdMap:Bo(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,n=0){let o=(s,a)=>{if(a<=ic){let u=this.buildCoercingContext(e,t,a);return this.applyCoercers(s,u)}};return{...t,syntheticException:n==0?t.syntheticException:void 0,mechanism:e,apply:s=>o(s,n),next:s=>o(s,n+1)}}};var F="?";function K(r,e,t,n,o){let i={platform:r,filename:e,function:t==="<anonymous>"?F:t,in_app:!0};return fe(n)||(i.lineno=n),fe(o)||(i.colno=o),i}var It=(r,e)=>{let t=r.indexOf("safari-extension")!==-1,n=r.indexOf("safari-web-extension")!==-1;return t||n?[r.indexOf("@")!==-1?r.split("@")[0]:F,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[r,e]};var sc=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ac=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,cc=/\((\S*)(?::(\d+))(?::(\d+))\)/,Rr=(r,e)=>{let t=sc.exec(r);if(t){let[,o,i,s]=t;return K(e,o,F,+i,+s)}let n=ac.exec(r);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=cc.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[i,s]=It(n[1]||F,n[2]);return K(e,s,i,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var uc=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,lc=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,zr=(r,e)=>{let t=uc.exec(r);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){let s=lc.exec(t[3]);s&&(t[1]=t[1]||"eval",t[3]=s[1],t[4]=s[2],t[5]="")}let o=t[3],i=t[1]||F;return[i,o]=It(i,o),K(e,o,i,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}};var fc=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,Ho=(r,e)=>{let t=fc.exec(r);return t?K(e,t[2],t[1]||F,+t[3],t[4]?+t[4]:void 0):void 0};var pc=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,Ko=(r,e)=>{let t=pc.exec(r);return t?K(e,t[2],t[3]||F,+t[1]):void 0},dc=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Go=(r,e)=>{let t=dc.exec(r);return t?K(e,t[5],t[3]||t[4]||F,+t[1],+t[2]):void 0};var hc=/^\s*[-]{4,}$/,gc=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,mc=/^Promise\.(?:all|any)$/,_c=/^index \d+$/,yc="node:internal/promise",qo=(r,e)=>{let t=r.match(gc);if(t){let n,o,i,s,a;if(t[1]){i=t[1];let l=i.lastIndexOf(".");if(i[l-1]==="."&&l--,l>0){n=i.slice(0,l),o=i.slice(l+1);let f=n.indexOf(".Module");f>0&&(i=i.slice(f+1),n=n.slice(0,f))}s=void 0}o&&(s=n,a=o),o==="<anonymous>"&&(a=void 0,i=void 0),i===void 0&&(a=a||F,i=s?`${s}.${a}`:a);let u=t[2]?.startsWith("file://")?t[2].slice(7):t[2],c=t[5]==="native";return u?.match(/\/[A-Z]:/)&&(u=u.slice(1)),!u&&t[5]&&!c&&(u=t[5]),mc.test(i)&&_c.test(u||"")&&(u=yc),{filename:u?decodeURI(u):void 0,module:void 0,function:i,lineno:Wo(t[3]),colno:Wo(t[4]),in_app:vc(u||"",c),platform:e}}if(r.match(hc))return{filename:r,platform:e}};function vc(r,e=!1){return!(e||r&&!r.startsWith("/")&&!r.match(/^[A-Z]:/)&&!r.startsWith(".")&&!r.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&r!==void 0&&!r.includes("node_modules/")}function Wo(r){return parseInt(r||"",10)||void 0}var Vo=/\(error: (.*)\)/,Xo=50;function Jo(r){if(!r.length)return[];let e=Array.from(r);return e.reverse(),e.slice(0,Xo).map(t=>({...t,filename:t.filename||bc(e).filename,function:t.function||F}))}function bc(r){return r[r.length-1]||{}}function Or(){return Qo("web:javascript",Rr,zr)}function Qo(r,...e){return(t,n=0)=>{let o=[],i=t.split(`
|
|
2
|
+
`);for(let s=n;s<i.length;s++){let a=i[s];if(a.length>1024)continue;let u=Vo.test(a)?a.replace(Vo,"$1"):a;if(!u.match(/\S*Error: /)){for(let c of e){let l=c(u,r);if(l){o.push(l);break}}if(o.length>=Xo)break}}return Jo(o)}}var Tr=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let n=Q(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){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return pe(e,"DOMException")}isDOMError(e){return pe(e,"DOMError")}};var Ge=class{match(e){return vo(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){let 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}};var Mr=class{constructor(){}match(e){return bo(e)&&e.error!=null}coerce(e,t){let n=t.apply(e.error);return n||{type:"ErrorEvent",value:e.message,stack:t.syntheticException?.stack,synthetic:!0}}};var xc=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,We=class{match(e){return typeof e=="string"}coerce(e,t){let[n,o]=this.getInfos(e);return{type:n??"Error",value:o??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",n=e,o=e.match(xc);return o&&(t=o[1],n=o[2]),[t,n]}};var Yo=["fatal","error","warning","log","info","debug"];function At(r,e=40){let t=Object.keys(r);if(t.sort(),!t.length)return"[object has no keys]";for(let n=t.length;n>0;n--){let o=t.slice(0,n).join(", ");if(!(o.length>e))return n===t.length||o.length<=e?o:`${o.slice(0,e)}...`}return""}var qe=class{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let n=this.getErrorPropertyFromObject(e);return n?t.apply(n):{type:this.getType(e),value:this.getValue(e),stack:t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return ve(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let o=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(o+=` with message: '${e.message}'`),o}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),n=At(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(e){return Q(e)&&!mo(e)&&Yo.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];if(Do(n))return n}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}};var Lr=class{match(e){return ve(e)}coerce(e,t){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${At(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}};var Ve=class{match(e){return ht(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}};var Nr=class{match(e){return pe(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!ve(e))return!1;try{let t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){let n=this.getUnhandledRejectionReason(e);return ht(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.apply(n)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}};var Dr=class{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(t!==void 0)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}};var Xe={MESSAGE:"$message",TIMESTAMP:"$timestamp"},wc=new Set([Xe.MESSAGE,Xe.TIMESTAMP]),Ct={enabled:!0,max_bytes:32768};function Zr(r){return r?{enabled:r.enabled??Ct.enabled,max_bytes:Ec(r.max_bytes,Ct.max_bytes)}:{...Ct}}function Pc(r){if(!r)return{sanitizedProperties:{},droppedKeys:[]};let e=[];return{sanitizedProperties:Object.keys(r).reduce((n,o)=>wc.has(o)?(e.push(o),n):(n[o]=r[o],n),{}),droppedKeys:e}}var jr=class{constructor(e){this._entries=[],this._totalBytes=0,this._config=Zr(e)}setConfig(e){this._config=Zr(e),this._trimToMaxBytes()}add(e){let t=$c(e);if(!t)return;let n=ei(t.json);n>this._config.max_bytes||(this._entries.push({step:t.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(e=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}};function Ec(r,e){if(!De(r)||r===1/0||r===-1/0)return e;let t=Math.floor(r);return t<0?e:t}function $c(r){let e;try{e=ye(r)}catch{return}try{let t=JSON.parse(e);if(!Ne(t))return;let n=t,o=n[Xe.MESSAGE],i=n[Xe.TIMESTAMP];return!Q(o)||o.trim().length===0||!Q(i)&&!De(i)?void 0:{step:n,json:e}}catch{return}}function ei(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;let e=encodeURIComponent(r),t=0;for(let n=0;n<e.length;n++)e[n]==="%"?(t+=1,n+=2):t+=1;return t}var Y=class extends Error{constructor(e,t){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}},ie=class extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}};var ni=(r,e)=>{for(let t of Object.keys(e))(t.startsWith("$feature/")||t==="$active_feature_flags")&&(r[t]=e[t])};async function ti(r){if(r instanceof Y){let e="";try{e=await r.text}catch{}console.error(`Error while flushing PostHog: message=${r.message}, response body=${e}`,r)}else console.error("Error while flushing PostHog",r);return Promise.resolve()}function Fc(r){return typeof r=="object"&&(r instanceof Y||oi(r))}function oi(r){return r instanceof ie}function Sc(r){if(r instanceof Y)return r.status===502||r.status===504;if(!(r instanceof ie))return!1;let e=r.error;return(e?.code??e?.cause?.code)!=="ECONNREFUSED"}function we(r){return typeof r=="object"&&r instanceof Y&&r.status===413}function Je(r){return r instanceof Y?r.status===408||r.status===429||r.status>=500:oi(r)}function ri(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var Ur="default",Qe=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new Ke([new Ge,new qe,new We,new Ve],Or())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new yt,this._events=new $t,this._isInitialized=!1;let n=typeof e=="string"?e.trim():"",o=typeof t.host=="string"?t.host.trim():"",i=!n;this._logger=$o("[PostHog]",this.logMsgIfDebug.bind(this)),i&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=Lo(o||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:Je},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||i,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!yr()||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return e();this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(T.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(T.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(T.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(n,o)=>this._logger.info(n,o));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},n={...t,...this.getCommonEventProperties()};return ni(n,t),e.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=Me(n)),{distinct_id:e.distinct_id,event:e.event,properties:n}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,n){this.wrap(()=>{let o={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",o,n)})}async identifyStatelessImmediate(e,t,n){let o={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",o,n)}captureStateless(e,t,n,o){this.wrap(()=>{let i=this.buildPayload({distinct_id:e,event:t,properties:n});this.enqueue("capture",i,o)})}async captureStatelessImmediate(e,t,n,o){let i=this.buildPayload({distinct_id:e,event:t,properties:n});await this.sendImmediate("capture",i,o)}aliasStateless(e,t,n,o){this.wrap(()=>{let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});this.enqueue("alias",i,o)})}async aliasStatelessImmediate(e,t,n,o){let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",i,o)}groupIdentifyStateless(e,t,n,o,i,s){this.wrap(()=>{let a=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{},...s||{}}});this.enqueue("capture",a,o)})}async groupIdentifyStatelessImmediate(e,t,n,o,i,s){let a=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{},...s||{}}});await this.sendImmediate("capture",a,o)}async getRemoteConfig(){await this._initPromise;let e=this.host;e==="https://us.i.posthog.com"?e="https://us-assets.i.posthog.com":e==="https://eu.i.posthog.com"&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,n,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(o=>o.json()).catch(o=>{this._logger.error("Remote config could not be loaded",o),this._events.emit("error",o)})}async getFlags(e,t={},n={},o={},i={},s=!1){await this._initPromise;let a=s?"&config=true":"",u=`${this.host}/flags/?v=2${a}`,c={token:this.apiKey,distinct_id:e,groups:t,person_properties:n,group_properties:o,...i};n.$device_id&&(c.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(c.evaluation_contexts=this.evaluationContexts);let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(c)};return this._logger.info("Flags URL",u),this.fetchWithRetry(u,l,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:Sc},this.featureFlagsRequestTimeoutMs).then(f=>f.json()).then(f=>({success:!0,response:_r(f)})).catch(f=>(this._events.emit("error",f),{success:!1,error:this.categorizeRequestError(f)}))}categorizeRequestError(e){if(e instanceof Y)return{type:"api_error",statusCode:e.status};if(e instanceof ie){let t=e.error;return t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,n={},o={},i={},s){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(e,t,n,o,i,s);if(a===void 0)return{response:void 0,requestId:void 0};let u=Te(a.response);return u===void 0&&(u=!1),{response:u,requestId:a.requestId}}async getFeatureFlagDetailStateless(e,t,n={},o={},i={},s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,n,o,i,s,[e]);return a===void 0?void 0:{response:a.flags[e],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,n={},o={},i={},s){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(t,n,o,i,s,[e]);if(!a)return;let u=a[e];return u===void 0?null:u}async getFeatureFlagPayloadsStateless(e,t={},n={},o={},i,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,n,o,i,s)).payloads}async getFeatureFlagsStateless(e,t={},n={},o={},i,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,n,o,i,s)}async getFeatureFlagsAndPayloadsStateless(e,t={},n={},o={},i,s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(e,t,n,o,i,s);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},n={},o={},i,s){await this._initPromise;let a={geoip_disable:i??this.disableGeoip};s&&(a.flag_keys_to_evaluate=s);let u=await this.getFlags(e,t,n,o,a);if(!u.success)return;let c=u.response;return c.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),c.quotaLimited?.includes("feature_flags")?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:c?.requestId,quotaLimited:c.quotaLimited}):c}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},o=(await this.fetchWithRetry(e,t).then(i=>{if(i.status!==200||!i.json){let s=`Surveys API could not be loaded: ${i.status}`,a=new Error(s);this._logger.error(a),this._events.emit("error",new Error(s));return}return i.json()}).catch(i=>{this._logger.error("Surveys API could not be loaded",i),this._events.emit("error",i)}))?.surveys;return o&&this._logger.info("Surveys fetched from API: ",JSON.stringify(o)),o??[]}get props(){return this._props||(this._props=this.getPersistedProperty(T.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(T.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(T.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return Ur}persistedQueueKeyForRoute(e){return T.Queue}getActiveQueueRoutes(){return[Ur]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,n){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(t,n);if(o=this.processBeforeEnqueue(o),o===null)return;o=this.normalizeMessage(o);let i=this.persistedQueueKeyForRoute(this.getQueueRouteKey(o)),s=this.getPersistedProperty(i)||[];s.length>=this.maxQueueSize&&(s.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),s.push({message:o}),this.setPersistedProperty(i,s),this._events.emit(e,o),s.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=C(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,n){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(t,n);if(o=this.processBeforeEnqueue(o),o!==null){o=this.normalizeMessage(o);try{await this.sendBatch([o],void 0,this.getQueueRouteKey(o))}catch(i){this._events.emit("error",i)}}}normalizeMessage(e){let{type:t,library:n,library_version:o,...i}=e,s=ri(i.properties)?i.properties:void 0;return n!==void 0&&s?.$lib===void 0&&(s={...s||{},$lib:n}),o!==void 0&&s?.$lib_version===void 0&&(s={...s||{},$lib_version:o}),s&&(i.properties=s),i.uuid=Pt(i.uuid,M),i}prepareMessage(e,t){let n={...e,timestamp:t?.timestamp?t?.timestamp:$r(),uuid:Pt(t?.uuid,M)};return(t?.disableGeoip??this.disableGeoip)&&(ri(n.properties)||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flush().catch(async e=>{await ti(e)})}async waitForPendingPromises(e,t=[]){let n=t.filter(i=>!!i),o=0;for(;;){let i=this.promiseQueue.getPromises([...n,...this.flushPromises],e);if(i.length===0)return;o>0&&this._logger.debug(`flush() re-checking ${i.length} pending promise(s) before flushing`),await Promise.all(i.map(s=>s.catch(()=>{}))),o++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,n=this.promiseQueue.maxId,o=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(n,[t,o])}).then(()=>Fr([t])).then(()=>(this.pendingFlushPromise===o&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=o,this.flushPromise=o,this.flushPromises.add(o),this.addPendingPromise(o),Fr([o]).then(()=>{this.flushPromises.delete(o),this.pendingFlushPromise===o&&(this.pendingFlushPromise=null),this.flushPromise===o&&(this.flushPromise=null)}),o}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&e!==""&&(t["User-Agent"]=e),t}async sendBatch(e,t,n=Ur){let o={api_key:this.apiKey,batch:e,sent_at:$r()};this.historicalMigration&&(o.historical_migration=!0);let i=ye(o),s=`${this.host}/batch/`,a=this.disableCompression?null:await le(i,this.isDebug),u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||i};await(await this.fetchWithRetry(s,u,t)).body?.cancel()?.catch(()=>{})}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some(o=>this.getRouteQueue(o).length>0))return;let t=[],n;for(let o of e)try{await this._flushRoute(o,t)}catch(i){n===void 0&&(n=i)}if(n!==void 0)throw n;this._events.emit("flush",t)}async _flushRoute(e,t){let n=this.persistedQueueKeyForRoute(e),o=this.getPersistedProperty(n)||[];if(!o.length)return;let i=o.length,s=0;for(;o.length>0&&s<i;){let a=o.slice(0,this.maxBatchSize),u=a.map(f=>f.message===void 0?f.message:this.normalizeMessage(f.message)),c=async()=>{let p=(this.getPersistedProperty(n)||[]).slice(a.length);this.setPersistedProperty(n,p),o=p,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},l={retryCheck:f=>we(f)?!1:Je(f)};try{await this.sendBatch(u,l,e)}catch(f){if(we(f)&&u.length>1){this.maxBatchSize=Math.max(1,Math.floor(u.length/2)),this._logger.warn(`Received 413 when sending batch of size ${u.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw f instanceof ie||await c(),this._events.emit("error",f),f}await c(),t.push(...u),s+=u.length}}async _sendLogsBatch(e){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let t=JSON.stringify(e),n=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,o=this.disableCompression?null:await le(t,this.isDebug),i={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...o!==null&&{"Content-Encoding":"gzip"}},body:o||t};try{return await this.fetchWithRetry(n,i,{retryCheck:s=>we(s)?!1:Je(s)}),{kind:"ok"}}catch(s){return we(s)?{kind:"too-large"}:s instanceof ie?{kind:"retry-later",error:s}:{kind:"fatal",error:s}}}async _sendMetricsBatch(e){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let t=JSON.stringify(e),n=`${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`,o=this.disableCompression?null:await le(t,this.isDebug),i={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...o!==null&&{"Content-Encoding":"gzip"}},body:o||t};try{return await this.fetchWithRetry(n,i,{retryCheck:s=>we(s)?!1:Je(s)}),{kind:"ok"}}catch(s){return we(s)?{kind:"too-large"}:Je(s)?{kind:"retry-later",error:s}:{kind:"fatal",error:s}}}async fetchWithRetry(e,t,n,o){let i=t.body?t.body:"",s=-1;try{s=i instanceof Blob?i.size:Buffer.byteLength(i,Mo)}catch{i instanceof Blob?s=i.size:s=new TextEncoder().encode(i).length}return await No(async()=>{let a=new AbortController,u=o??this.requestTimeout,c=C(()=>a.abort(),u),l=null;try{l=await this.fetch(e,{signal:a.signal,...t})}catch(p){throw new ie(p)}finally{clearTimeout(c)}if(!(t.mode==="no-cors")&&(l.status<200||l.status>=400))throw new Y(l,s);return l},{...this._retryOptions,...n})}async _shutdown(e=3e4){await this._initPromise;let t=!1;if(this.clearFlushTimer(),this.disabled)return;let n=async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(a=>this.getRouteQueue(a).length>0);){let s=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===s){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(i){if(!Fc(i))throw i;await ti(i)}},o;try{return await Promise.race([new Promise((i,s)=>{o=C(()=>{this._logger.error("Timed out while shutting down PostHog"),t=!0,s("Timeout while shutting down PostHog. Some events may not have been sent.")},e)}),n()])}finally{clearTimeout(o)}}async shutdown(e=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var ai=require("fs"),ci=require("readline"),kt=new z.ReduceableCache(25),ui=new z.ReduceableCache(20),Br=7,Rc=1e3,zc=1e4;async function li(r){let e={};for(let o=r.length-1;o>=0;o--){let i=r[o],s=i?.filename;if(!i||typeof s!="string"||typeof i.lineno!="number"||Lc(s)||Nc(i))continue;e[s]||(e[s]=[]),e[s].push(i.lineno)}let t=Object.keys(e);if(t.length==0)return r;let n=[];for(let o of t){if(ui.get(o))continue;let i=e[o];if(!i)continue;i.sort((u,c)=>u-c);let s=Zc(i);if(s.every(u=>Dc(o,u)))continue;let a=jc(kt,o,{});n.push(Oc(o,s,a))}return await Promise.all(n).catch(()=>{}),r&&r.length>0&&Tc(r,kt),kt.reduce(),r}function Oc(r,e,t){return new Promise(n=>{let o=(0,ai.createReadStream)(r),i=(0,ci.createInterface)({input:o});function s(){o.destroy(),n()}let a=0,u=0,c=e[u];if(c===void 0)return void s();let l=c[0],f=c[1];function p(){ui.set(r,1),i.close(),i.removeAllListeners(),s()}o.on("error",p),i.on("error",p),i.on("close",s),i.on("line",d=>{if(a++,!(a<l)&&(t[a]=Uc(d,0),a>=f)){if(u===e.length-1){i.close(),i.removeAllListeners();return}u++;let h=e[u];if(h===void 0){i.close(),i.removeAllListeners();return}l=h[0],f=h[1]}})})}function Tc(r,e){for(let t of r)if(t.filename&&t.context_line===void 0&&typeof t.lineno=="number"){let n=e.get(t.filename);if(n===void 0)continue;Mc(t.lineno,t,n)}}function Mc(r,e,t){if(e.lineno===void 0||t===void 0)return;e.pre_context=[];for(let o=fi(r);o<r;o++){let i=t[o];if(i===void 0)return void ii(e);e.pre_context.push(i)}if(t[r]===void 0)return void ii(e);e.context_line=t[r];let n=pi(r);e.post_context=[];for(let o=r+1;o<=n;o++){let i=t[o];if(i===void 0)break;e.post_context.push(i)}}function ii(r){delete r.pre_context,delete r.context_line,delete r.post_context}function Lc(r){return r.startsWith("node:")||r.endsWith(".min.js")||r.endsWith(".min.cjs")||r.endsWith(".min.mjs")||r.startsWith("data:")}function Nc(r){return r.lineno!==void 0&&r.lineno>zc||r.colno!==void 0&&r.colno>Rc}function Dc(r,e){let t=kt.get(r);if(t===void 0)return!1;for(let n=e[0];n<=e[1];n++)if(t[n]===void 0)return!1;return!0}function Zc(r){if(!r.length)return[];let e=0,t=r[0];if(typeof t!="number")return[];let n=si(t),o=[];for(;;){if(e===r.length-1){o.push(n);break}let i=r[e+1];if(typeof i!="number")break;i<=n[1]?n[1]=i+Br:(o.push(n),n=si(i)),e++}return o}function si(r){return[fi(r),pi(r)]}function fi(r){return Math.max(1,r-Br)}function pi(r){return r+Br}function jc(r,e,t){let n=r.get(e);return n===void 0?(r.set(e,t),t):n}function Uc(r,e){let t=r,n=t.length;if(n<=150)return t;e>n&&(e=n);let o=Math.max(e-60,0);o<5&&(o=0);let i=Math.min(o+140,n);return i>n-5&&(i=n),i===n&&(o=Math.max(i-140,0)),t=t.slice(o,i),o>0&&(t=`...${t}`),i<n&&(t+="..."),t}var Pe=require("path");function di(r=process.cwd()){let e=Pe.sep==="\\",t=o=>e?o.replace(/\\/g,"/"):o,n=t(r);return async o=>{for(let i of o)!i.filename||i.filename.startsWith("node:")||i.filename.startsWith("data:")||(0,Pe.isAbsolute)(i.filename)&&(i.filename=t((0,Pe.relative)(n,t(i.filename))));return o}}var hi="5.46.1";var ee={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var de=class r{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e){let t=this._flags[e];return this._recordAccess(e),t?.enabled??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),!!t)return t.enabled?t.variant??!0:!1}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let n=this._flags[t];n&&(e[t]=n)}return this._cloneWith(e)}only(e){let t={},n=[];for(let o of e){let i=this._flags[o];i?t[o]=i:n.push(o)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[n,o]of Object.entries(this._flags)){let i=o.enabled===!1?!1:o.variant??!0;e[`$feature/${n}`]=i,o.enabled&&t.push(n)}return t.length>0&&(t.sort(),e.$active_feature_flags=t),e}_cloneWith(e){return new r({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),this._distinctId===""||this._isSlice&&!(e in this._flags))return;let t=this._flags[e],n=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,o={$feature_flag:e,$feature_flag_response:n,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};t?.hasExperiment!==void 0&&(o.$feature_flag_has_experiment=t.hasExperiment),t?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(o.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let i=[];this._errorsWhileComputing&&i.push(ee.ERRORS_WHILE_COMPUTING),this._quotaLimited&&i.push(ee.QUOTA_LIMITED),t===void 0&&i.push(ee.FLAG_MISSING),i.length>0&&(o.$feature_flag_error=i.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:o})}};async function gi(r){let e=globalThis.crypto?.subtle;if(!e)throw new Error("SubtleCrypto API not available");let t=await e.digest("SHA-1",new TextEncoder().encode(r));return Array.from(new Uint8Array(t)).map(o=>o.toString(16).padStart(2,"0")).join("")}var Bc=6e4,Hc=1152921504606847e3,Kc=["is_not","is_set"],Ee=class r extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,r.prototype)}};function vi(r,e){r.name=e.name,Error.captureStackTrace(r,e),Object.setPrototypeOf(r,e.prototype)}var y=class r extends Error{constructor(e){super(e),vi(this,r)}},G=class r extends Error{constructor(e){super(e),vi(this,r)}},Rt=class{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:n,timeout:o,host:i,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=o,this.projectApiKey=n,this.host=i,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}createEvaluationContext(e,t={},n={},o={},i={}){return{distinctId:e,groups:t,personProperties:n,groupProperties:o,evaluationCache:i}}async getFeatureFlag(e,t,n={},o={},i={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[e],a!==void 0){let u=this.createEvaluationContext(t,n,o,i);try{s=(await this.computeFlagAndPayloadLocally(a,u)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${s}`))}catch(c){c instanceof G||c instanceof y?this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${e}: ${c.message}`)):c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${e}: ${c}`))}}return s}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let n={},o={},i=this.featureFlags.length==0,s=t?t.map(u=>this.featureFlagsByKey[u]).filter(Boolean):this.featureFlags,a={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(s.map(async u=>{try{let{value:c,payload:l}=await this.computeFlagAndPayloadLocally(u,a);n[u.key]=c,l&&(o[u.key]=l)}catch(c){c instanceof G||c instanceof y?this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${u.key}: ${c.message}`)):c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${u.key}: ${c}`)),i=!0}})),{response:n,payloads:o,fallbackToFlags:i}}async computeFlagAndPayloadLocally(e,t,n={}){let{matchValue:o,skipLoadCheck:i=!1}=n;if(i||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=o!==void 0?o:await this.computeFlagValueLocally(e,t);let a=this.getFeatureFlagPayload(e.key,s);return{value:s,payload:a}}async computeFlagValueLocally(e,t){let{distinctId:n,groups:o,personProperties:i,groupProperties:s}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new y("Flag has experience continuity enabled");let u=(e.filters||{}).aggregation_group_type_index;if(u!=null){let c=this.groupTypeMapping[String(u)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${u} for feature flag ${e.key}`)),new y("Flag has unknown group type index");if(!(c in o))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;e.bucketing_identifier==="device_id"&&(i?.$device_id===void 0||i?.$device_id===null||i?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let l=s[c];return await this.matchFeatureFlagProperties(e,o[c],l,t)}{let c=this.getBucketingValueForFlag(e,n,i);if(c===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new y(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,c,i,t)}}getBucketingValueForFlag(e,t,n){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let o=n?.$device_id;return o==null||o===""?void 0:o}return t}getFeatureFlagPayload(e,t){let n=null;if(t!==!1&&t!=null&&(typeof t=="boolean"?n=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null:typeof t=="string"&&(n=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(e,t,n){let{evaluationCache:o}=n,i=e.key;if(!this.featureFlagsByKey)throw new y("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new y(`Flag dependency property for '${i}' is missing required 'dependency_chain' field`);let s=e.dependency_chain;if(!Array.isArray(s))throw new y(`Flag dependency property for '${i}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new y(`Circular dependency detected for flag '${i}' (empty dependency chain)`);for(let u of s){if(!(u in o)){let l=this.featureFlagsByKey[u];if(l)if(l.active)try{let f=await this.computeFlagValueLocally(l,n);o[u]=f}catch(f){throw new y(`Error evaluating flag dependency '${u}' for flag '${i}': ${f}`)}else o[u]=!1;else throw new y(`Missing flag dependency '${u}' for flag '${i}'`)}if(o[u]==null)throw new y(`Dependency '${u}' could not be evaluated`)}let a=o[i];return this.flagEvaluatesToExpectedValue(e.value,a)}flagEvaluatesToExpectedValue(e,t){return typeof e=="boolean"?e===t||typeof t=="string"&&t!==""&&e===!0:typeof e=="string"?t===e:!1}async matchFeatureFlagProperties(e,t,n,o){let i=e.filters||{},s=i.groups||[],a=i.aggregation_group_type_index,u=i.early_exit??!1,{groups:c,groupProperties:l}=o,f=!1,p;for(let d of s)try{let h=d.aggregation_group_type_index!==void 0?d.aggregation_group_type_index:a,g=n,w=t;if(h!==a&&h!=null){let v=this.groupTypeMapping[String(h)];if(!v||!(v in c)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${h} not available`));continue}if(!(v in l)){f=!0;continue}g=l[v],w=c[v]}let _=await this.isConditionMatch(e,w,d,g,o);if(_==="match"){let v=d.variant,R=i.multivariate?.variants||[];p=v&&R.some(I=>I.key===v)?v:await this.getMatchingVariant(e,w)||!0;break}if(u&&_==="out_of_rollout_bound")return!1}catch(h){if(h instanceof G)throw h;if(h instanceof y)f=!0;else throw h}if(p!==void 0)return p;if(f)throw new y("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,n,o,i){let s=n.rollout_percentage,a=u=>{this.logMsgIfDebug(()=>console.warn(u))};if((n.properties||[]).length>0){for(let u of n.properties){let c=u.type,l=!1;if(c==="cohort"){let f=await xi(u,o,this.cohorts,this.debugMode,p=>this.evaluateFlagDependency(p,o,i));l=u.operator==="not_in"?!f:f}else l=c==="flag"?await this.evaluateFlagDependency(u,o,i):bi(u,o,a);if(!l)return"no_match"}if(s==null)return"match"}return s!=null&&await mi(e.key,t)>s/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){let n=await mi(e.key,t,"variant"),o=this.variantLookupTable(e).find(i=>n>=i.valueMin&&n<i.valueMax);if(o)return o.key}variantLookupTable(e){let t=[],n=0,o=0;return((e.filters||{}).multivariate?.variants||[]).forEach(a=>{o=n+a.rollout_percentage/100,t.push({valueMin:n,valueMax:o,key:a.key}),n=o}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((t,n)=>(t[n.key]=n,t),{}),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(e.minimalFlagCalledEvents===!0)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter(n=>n.ensure_experience_continuity);t.length>0&&console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map(n=>n.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();return t?(this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(t.flags),!0):!1}catch(t){return this.onError?.(new Error(`Failed to load from cache: ${t}`)),!1}}async loadFeatureFlags(e=!1){if(!(this.loadedSuccessfullyOnce&&!e))return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(t=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${t}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(Bc,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!e&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new Ee(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new Ee(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Ee(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await t.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let o={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{},minimalFlagCalledEvents:n.minimal_flag_called_events===!0};if(this.updateFlagState(o),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(o)}catch(i){this.onError?.(new Error(`Failed to store in cache: ${i}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(o.flags);break}default:return}}catch(e){e instanceof Ee&&this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET",t){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(n["If-None-Match"]=t),{method:e,headers:n}}_requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let o=new AbortController;n=C(()=>{o.abort()},this.timeout),t.signal=o.signal}try{let o=this.fetch;return o(e,t)}finally{clearTimeout(n)}}async stopPoller(e=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await Promise.race([t,new Promise((n,o)=>setTimeout(()=>o(new Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(t){this.onError?.(new Error(`Error during cache shutdown: ${t}`))}}};async function mi(r,e,t=""){let n=await gi(`${r}.${e}${t}`);return parseInt(n.slice(0,15),16)/Hc}function bi(r,e,t){let n=r.key,o=r.value,i=r.operator||"exact";if(n in e){if(i==="is_not_set")return!1}else{if(i==="is_not_set")return!0;throw new y(`Property ${n} not found in propertyValues`)}let s=e[n];if(s==null&&!Kc.includes(i))return t&&t(`Property ${n} cannot have a value of null/undefined with the ${i} operator`),!1;function a(c,l){return Array.isArray(c)?c.map(f=>String(f).toLowerCase()).includes(String(l).toLowerCase()):String(c).toLowerCase()===String(l).toLowerCase()}function u(c,l,f){if(f==="gt")return c>l;if(f==="gte")return c>=l;if(f==="lt")return c<l;if(f==="lte")return c<=l;throw new Error(`Invalid operator: ${f}`)}switch(i){case"exact":return a(o,s);case"is_not":return!a(o,s);case"is_set":return n in e;case"icontains":return String(s).toLowerCase().includes(String(o).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(o).toLowerCase());case"regex":return _i(String(o))&&String(s).match(String(o))!==null;case"not_regex":return _i(String(o))&&String(s).match(String(o))===null;case"gt":case"gte":case"lt":case"lte":{let c=typeof o=="number"?o:parseFloat(String(o)),l;return l=typeof s=="number"?s:s!=null?parseFloat(String(s)):NaN,Number.isFinite(c)&&Number.isFinite(l)?u(l,c,i):u(String(s),String(o),i)}case"is_date_after":case"is_date_before":{if(typeof o=="boolean")throw new y("Date operations cannot be performed on boolean values");let c=Xc(String(o));if(c==null&&(c=yi(o)),c==null)throw new y(`Invalid date: ${o}`);let l=yi(s);return["is_date_before"].includes(i)?l<c:l>c}case"semver_eq":return Z(S(String(s)),S(String(o)))===0;case"semver_neq":return Z(S(String(s)),S(String(o)))!==0;case"semver_gt":return Z(S(String(s)),S(String(o)))>0;case"semver_gte":return Z(S(String(s)),S(String(o)))>=0;case"semver_lt":return Z(S(String(s)),S(String(o)))<0;case"semver_lte":return Z(S(String(s)),S(String(o)))<=0;case"semver_tilde":{let c=S(String(s)),{lower:l,upper:f}=Wc(String(o));return Z(c,l)>=0&&Z(c,f)<0}case"semver_caret":{let c=S(String(s)),{lower:l,upper:f}=qc(String(o));return Z(c,l)>=0&&Z(c,f)<0}case"semver_wildcard":{let c=S(String(s)),{lower:l,upper:f}=Vc(String(o));return Z(c,l)>=0&&Z(c,f)<0}default:throw new y(`Unknown operator: ${i}`)}}function Gc(r,e){if(!(r in e))throw new G(`cohort ${r} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function xi(r,e,t,n=!1,o){let i=String(r.value);Gc(i,t);let s=t[i];return wi(s,e,t,n,o)}async function wi(r,e,t,n=!1,o){if(!r)return!0;let i=r.type,s=r.values;if(!s||s.length===0)return!0;let a=!1;if("values"in s[0]){for(let u of s)try{let c=await wi(u,e,t,n,o);if(i==="AND"){if(!c)return!1}else if(c)return!0}catch(c){if(c instanceof G)throw c;if(c instanceof y)n&&console.debug(`Failed to compute property ${u} locally: ${c}`),a=!0;else throw c}if(a)throw new y("Can't match cohort without a given cohort property value");return i==="AND"}for(let u of s)try{let c;if(u.type==="cohort")c=await xi(u,e,t,n,o);else if(u.type==="flag"){if(!o)throw new y(`Flag dependency '${u.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);c=await o(u)}else c=bi(u,e);let l=u.negation||!1;if(i==="AND"){if(!c&&!l||c&&l)return!1}else if(c&&!l||!c&&l)return!0}catch(c){if(c instanceof G)throw c;if(c instanceof y)n&&console.debug(`Failed to compute property ${u} locally: ${c}`),a=!0;else throw c}if(a)throw new y("can't match cohort without a given cohort property value");return i==="AND"}function _i(r){try{return new RegExp(r),!0}catch{return!1}}function Pi(r,e){if(!/^\d+$/.test(r))throw new y(`Invalid semver: ${e}`);if(r.length>1&&r[0]==="0")throw new y(`Invalid semver: ${e}`);return parseInt(r,10)}function S(r){let t=String(r).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!t||t.startsWith("."))throw new y(`Invalid semver: ${r}`);let n=t.split("."),o=u=>u===void 0||u===""?0:Pi(u,r),i=o(n[0]),s=o(n[1]),a=o(n[2]);return[i,s,a]}function Z(r,e){for(let t=0;t<3;t++){if(r[t]<e[t])return-1;if(r[t]>e[t])return 1}return 0}function Wc(r){let e=S(r),t=[e[0],e[1],e[2]],n=[e[0],e[1]+1,0];return{lower:t,upper:n}}function qc(r){let e=S(r),[t,n,o]=e,i=[t,n,o],s;return s=t>0?[t+1,0,0]:n>0?[0,n+1,0]:[0,0,o+1],{lower:i,upper:s}}function Vc(r){let t=String(r).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!t)throw new y(`Invalid wildcard semver: ${r}`);let n=t.split("."),o=u=>{try{return Pi(u,r)}catch{throw new y(`Invalid wildcard semver: ${r}`)}},i=o(n[0]),s,a;if(n.length===1)s=[i,0,0],a=[i+1,0,0];else{let u=o(n[1]);s=[i,u,0],a=[i,u+1,0]}return{lower:s,upper:a}}function yi(r){if(r instanceof Date)return r;if(typeof r=="string"||typeof r=="number"){let e=new Date(r);if(!isNaN(e.valueOf()))return e;throw new y(`${r} is in an invalid date format`)}throw new y(`The date provided ${r} must be a string, number, or date object`)}function Xc(r){let e=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,t=r.match(e),n=new Date(new Date().toISOString());if(!t)return null;{if(!t.groups)return null;let o=parseInt(t.groups.number);if(o>=1e4)return null;let i=t.groups.interval;if(i=="h")n.setUTCHours(n.getUTCHours()-o);else if(i=="d")n.setUTCDate(n.getUTCDate()-o);else if(i=="w")n.setUTCDate(n.getUTCDate()-7*o);else if(i=="m")n.setUTCMonth(n.getUTCMonth()-o);else{if(i!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-o)}return n}}function Jc(r,e){let t=!1;return Object.assign(n=>{let i=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;r(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!t&&i&&(t=!0,e(n))},{_posthogErrorHandler:!0})}function Ei(r,e){globalThis.process?.on("uncaughtException",Jc(r,e))}function $i(r){globalThis.process?.on("unhandledRejection",e=>r(e,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var Qc=2e3,te=class r{constructor(e,t,n){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new gt({...wo(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return Ne(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,n,o,i){let s={...i},a=e.buildFromUnknown(t,n);return a.$exception_list=await e.modifyFrames(a.$exception_list),{event:"$exception",distinctId:o,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(Ei(this.onException.bind(this),this.onFatalError.bind(this)),$i(this.onException.bind(this)))}onException(e,t){this.client.addPendingPromise((async()=>{if(!r.isPreviouslyCapturedError(e)){let n=await r.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),i=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(i)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:i}):this.client._capturePreparedEvent(n,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(Qc),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var zt=class{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}};function Yc(r){return r==="v0"||r==="v1"}function Fi(){let r=typeof process<"u"?process.env?.POSTHOG_CAPTURE_MODE:void 0;return Yc(r)?r:"v0"}var eu="$ai_",Ye="analytics";function Si(r){return typeof r.event=="string"&&r.event.startsWith(eu)}var $e=class r extends Error{constructor({requestId:e,drops:t,retryExhausted:n,cause:o}){super(r.buildMessage(e,t,n,o)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=n,this.cause=o}static buildMessage(e,t,n,o){let i=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${n.length} undelivered`;return o instanceof Error&&(i+=` (${o.message})`),i}};function Hr(r){if(typeof r=="boolean")return r;if(typeof r=="number")return r!==0;if(typeof r=="string"){let e=r.trim().toLowerCase();if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1}}function tu(r){return typeof r=="string"?r:void 0}var ru=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:Hr},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:Hr},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:Hr},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:tu}],nu=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function ou(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function iu(r){if(typeof r=="string"){let t=new Date(r);return Number.isNaN(t.getTime())?new Date().toISOString():r}if(r instanceof Date)return Number.isNaN(r.getTime())?new Date().toISOString():r.toISOString();let e=r==null?new Date:new Date(r);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()}function Ii(r,e,t){t!==void 0&&!(e in r)&&(r[e]=t)}function su(r){let t={...ou(r.properties)?r.properties:{}},n={};for(let{property:i,optionKey:s,coerce:a}of ru)if(i in t){let u=a(t[i]);u!==void 0&&(n[s]=u),delete t[i]}let o={};for(let{property:i,field:s}of nu)if(i in t){let a=t[i];typeof a=="string"&&(o[s]=a),delete t[i]}return delete t.$lib,delete t.$lib_version,Ii(t,"$set",r.$set),Ii(t,"$set_once",r.$set_once),{event:String(r.event??""),uuid:String(r.uuid??""),distinct_id:String(r.distinct_id??""),timestamp:iu(r.timestamp),...o,options:n,properties:t}}function Ai(r,{createdAt:e,historicalMigration:t}){let n={created_at:e,batch:r.map(su)};return t&&(n.historical_migration=!0),n}var au="/i/v1/analytics/events",cu=3e4,uu=new Set([408,500,502,503,504]),Ot=class{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??cu,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??(n=>new Promise(o=>C(o,n))),this.generateRequestId=t.generateRequestId??M,this.compress=t.compress??le}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:o}=Ai(e,{createdAt:n,historicalMigration:this.config.historicalMigration}),i=`${this.config.host}${au}`,s=[],a=o,u=Math.max(1,this.config.maxAttempts);for(let c=1;c<=u;c++){let l=c===u,f=ye({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),p;try{p=await this.sendOnce(i,f,c,t)}catch(_){if(l)return this.surfaceBatchFailure(t,s,a,_);await this.sleep(this.backoffDelay(c));continue}let{status:d}=p;if(d<200||d>=300){if(!l&&uu.has(d)){let v=this.parseRetryAfter(p);await this.cancelBody(p),await this.sleep(this.backoffDelay(c,v));continue}let _=await this.buildHttpError(p,d);return this.surfaceBatchFailure(t,s,a,_)}let h;try{h=await this.parseResponse(p)}catch{return this.surfaceBatchFailure(t,s,a,new Error(`Capture V1 returned an unparseable ${d} response body`))}let g=this.classify(a,h,s);if(g.length===0)return this.surfacePartialDrops(t,s);if(l)return void this.onError(new $e({requestId:t,drops:s,retryExhausted:g.map(_=>_.uuid)}));a=g;let w=this.parseRetryAfter(p);await this.sleep(this.backoffDelay(c,w))}}async sendOnce(e,t,n,o){let i=this.buildHeaders(n,o),s=t;if(this.config.compressionEnabled){let c=await this.compress(t,this.config.isDebug);c!==null&&(s=c,i["Content-Encoding"]="gzip")}let a=new AbortController,u=C(()=>a.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(e,{method:"POST",headers:i,body:s,signal:a.signal})}finally{clearTimeout(u)}}buildHeaders(e,t){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,o={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(o["User-Agent"]=this.config.userAgent),o}classify(e,t,n){let o=t.results??{},i=[];for(let s of e){let a=o[s.uuid];a&&(a.result==="drop"?n.push({uuid:s.uuid,details:a.details??void 0}):a.result==="retry"&&i.push(s))}return i}backoffDelay(e,t){let n=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return t===void 0?n:Math.max(n,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let n=t.trim();if(/^\d+$/.test(n)){let s=parseInt(n,10);return Number.isFinite(s)&&s>0?1e3*s:void 0}let o=Date.parse(n);if(Number.isNaN(o))return;let i=o-this.now();return i>0?i:void 0}async parseResponse(e){let t=await e.text(),n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("unexpected response shape");let o=n.results;if(o!==void 0&&(typeof o!="object"||o===null||Array.isArray(o)))throw new Error("unexpected results shape");return{results:o??{}}}async buildHttpError(e,t){let n="";try{n=(await e.text()).slice(0,512)}catch{}let o=n?`: ${n}`:"";return new Error(`Capture V1 request failed with HTTP ${t}${o}`)}surfaceBatchFailure(e,t,n,o){this.onError(new $e({requestId:e,drops:t,retryExhausted:n.map(i=>i.uuid),cause:o}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new $e({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}};var lu=100,Ci=3e4,fu=5e4,pu=50,du=500,hu="https://us.i.posthog.com",ki=new Set;function Mt(r,e){ki.has(r)||(ki.add(r),console.warn(`[PostHog] ${e}`))}function gu(r){return typeof r=="string"?r.trim():""}function mu(r){return(typeof r=="string"?r.trim():"")||void 0}function _u(r){return(typeof r=="string"?r.trim():"")||hu}function yu(r){return(Array.isArray(r)?r:[r]).filter(t=>typeof t=="string"&&t.trim().length>0)}function vu(r){if(!r)return{};let e={};for(let[n,o]of Object.entries(r))e[`$feature/${n}`]=o;let t=Object.keys(r).filter(n=>r[n]!==!1).sort();return t.length>0&&(e.$active_feature_flags=t),e}var Lt=class extends Qe{constructor(e,t={}){let n=gu(e),o={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:_u(t.host),personalApiKey:mu(t.secretKey??t.personalApiKey)};if(super(n,o),this._memoryStorage=new zt,this._minimalFlagCalledEvents=!1,this.options=o,this.captureMode=Fi(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof o.featureFlagsPollingInterval=="number"?Math.max(o.featureFlagsPollingInterval,lu):Ci,typeof o.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(o.waitUntilDebounceMs,0)),typeof o.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(o.waitUntilMaxWaitMs,0)),!this.disabled&&o.personalApiKey){if(o.personalApiKey.includes("phc_"))throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');o.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new Rt({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:o.personalApiKey,projectApiKey:n,timeout:o.requestTimeout??1e4,host:this.host,fetch:o.fetch,onError:s=>{this._events.emit("error",s)},onLoad:s=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:s=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:o.flagDefinitionCacheProvider,strictLocalEvaluation:o.strictLocalEvaluation}))}this.errorTracking=new te(this,o,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=o.maxCacheSize||fu}enqueue(e,t,n){super.enqueue(e,t,n),this.scheduleDebouncedFlush()}async flush(){let e=this.flushWithPendingPromises(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,a=new Promise(u=>{s=u});try{e(a)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??du,o=t>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),o)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??pu;this._waitUntilCycle.timer=C(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this.flushWithPendingPromises()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){return this.captureMode==="v1"&&Si(e)?"ai":Ye}persistedQueueKeyForRoute(e){return e==="ai"?T.AiQueue:T.Queue}getActiveQueueRoutes(){return this.captureMode==="v1"?[Ye,"ai"]:[Ye]}async sendBatch(e,t,n=Ye){if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(e,t,n);let o=e.filter(i=>i!==void 0);await this.getV1Sender().sendV1Batch(o)}getV1Sender(){return this._v1Sender||(this._v1Sender=new Ot({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:e=>this._events.emit("error",e)})),this._v1Sender}getLibraryVersion(){return hi}get metrics(){return this._metrics||(this._metrics=new He(this,Et(this.options.metrics),this._logger)),this._metrics}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,n){typeof e=="string"&&this._logger.warn(t),e.event==="$exception"&&!e._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(e,t,n,o){return this.addPendingPromise(this._prepareEventMessage(t,o).then(({distinctId:i,event:s,properties:a,options:u})=>{let c={timestamp:u.timestamp,disableGeoip:u.disableGeoip,uuid:u.uuid},l={distinctId:i,event:s,properties:{...a,...this.getCommonEventProperties()}};return n?this.sendImmediate(e,l,c):this.enqueue(e,l,c)}).catch(i=>{i&&console.error(i)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}identify({distinctId:e,properties:t={},disableGeoip:n}){let{$set:o,$set_once:i,$anon_distinct_id:s,...a}=t,l={$set:o||a,$set_once:i||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:n}){let{$set:o,$set_once:i,$anon_distinct_id:s,...a}=t,l={$set:o||a,$set_once:i||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:n={}}){if(Object.keys(t).length===0&&Object.keys(n).length===0)return;let o={};Object.keys(t).length>0&&(o.$set=t),Object.keys(n).length>0&&(o.$set_once=n),this.capture({distinctId:e,event:"$set",properties:o})}unsetPersonProperties({distinctId:e,properties:t}){let n=yu(t);n.length!==0&&this.capture({distinctId:e,event:"$set",properties:{$unset:n}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=Ci){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(t=>{let n=setTimeout(()=>{o(),t(!1)},e),o=this._events.on("localEvaluationFlagsLoaded",i=>{clearTimeout(n),o(),t(i>0)})})}_resolveDistinctId(e,t){return typeof e=="string"?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,n={},o){if(this.disabled)return void this._logger.warn("The client is disabled");let i=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let m=this._flagOverrides[e];if(m===void 0)return;let P=this._payloadOverrides?.[e];return{key:e,enabled:m!==!1,variant:typeof m=="string"?m:void 0,payload:P}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=n,f=this.addLocalPersonAndGroupProperties(t,s,c,l);c=f.allPersonProperties,l=f.allGroupProperties;let p=this.createFeatureFlagEvaluationContext(t,s,this.personPropertiesForLocalEvaluation(t,c),l);u==null&&(u=this.options.strictLocalEvaluation??!1);let d,h=!1,g,w,_,v,R,I,x;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let m=this.featureFlagsPoller?.featureFlagsByKey[e];if(m)try{let P=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(m,p,{matchValue:o});if(P){h=!0;let $=P.value;v=m.id,I="Evaluated locally",x=m.has_experiment,d={key:e,enabled:$!==!1,variant:typeof $=="string"?$:void 0,payload:P.payload??void 0}}}catch(P){if(P instanceof G||P instanceof y)this._logger?.info(`${P.name} when computing flag locally: ${e}: ${P.message}`);else throw P}}if(!h&&!u){let m=await super.getFeatureFlagDetailsStateless(p.distinctId,p.groups,c,l,a,[e]);if(m===void 0)_=ee.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=m.minimalFlagCalledEvents===!0,g=m.requestId,w=m.evaluatedAt;let P=[];m.errorsWhileComputingFlags&&P.push(ee.ERRORS_WHILE_COMPUTING),m.quotaLimited?.includes("feature_flags")&&P.push(ee.QUOTA_LIMITED);let $=m.flags[e];if($===void 0)P.push(ee.FLAG_MISSING);else{v=$.metadata?.id,R=$.metadata?.version,I=$.reason?.description??$.reason?.code,x=$.metadata?.has_experiment;let Bt;if($.metadata?.payload!==void 0)try{Bt=JSON.parse($.metadata.payload)}catch{Bt=$.metadata.payload}d={key:e,enabled:$.enabled,variant:$.variant,payload:Bt}}P.length>0&&(_=P.join(","))}}if(i){let m=d===void 0?void 0:d.enabled===!1?!1:d.variant??!0,P={$feature_flag:e,$feature_flag_response:m,$feature_flag_id:v,$feature_flag_version:R,$feature_flag_reason:I,locally_evaluated:h,[`$feature/${e}`]:m,$feature_flag_request_id:g,$feature_flag_evaluated_at:h?Date.now():w};if(x!==void 0&&(P.$feature_flag_has_experiment=x),h&&this.featureFlagsPoller){let $=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();$!==void 0&&(P.$feature_flag_definitions_loaded_at=$)}_&&(P.$feature_flag_error=_),this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:m,groups:s,disableGeoip:a,properties:P})}return d!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides&&(d={...d,payload:this._payloadOverrides[e]}),d}async getFeatureFlag(e,t,n){Mt("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let o=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(o!==void 0)return o.enabled===!1?!1:o.variant??!0}async getFeatureFlagPayload(e,t,n,o){if(Mt("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let i=await this._getFeatureFlagResult(e,t,{...o,sendFeatureFlagEvents:!1},n);if(i!==void 0)return i.payload??null}async getFeatureFlagResult(e,t,n){let{distinctId:o,options:i}=this._resolveDistinctId(t,n);return o?this._getFeatureFlagResult(e,o,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let n=await t.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(e,t,n){Mt("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let o=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return o===void 0?void 0:o.enabled===!1?!1:!!(o.variant??!0)||!1}async getAllFlags(e,t){let{distinctId:n,options:o}=this._resolveDistinctId(e,t);return n?(await this.getAllFlagsAndPayloads(n,o)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:n,options:o}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:i,disableGeoip:s,flagKeys:a}=o||{},{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=o||{},f=this.addLocalPersonAndGroupProperties(n,i,c,l);c=f.allPersonProperties,l=f.allGroupProperties;let p=this.createFeatureFlagEvaluationContext(n,i,this.personPropertiesForLocalEvaluation(n,c),l);u==null&&(u=this.options.strictLocalEvaluation??!1);let d=await this.featureFlagsPoller?.getAllFlagsAndPayloads(p,a),h={},g={},w=!0;if(d&&(h=d.response,g=d.payloads,w=d.fallbackToFlags),w&&!u){let _=await super.getFeatureFlagsAndPayloadsStateless(p.distinctId,p.groups,c,l,s,a);h={...h,..._.flags||{}},g={...g,..._.payloads||{}}}return this._flagOverrides!==void 0&&(h={...h,...this._flagOverrides}),this._payloadOverrides!==void 0&&(g={...g,...this._payloadOverrides}),{featureFlags:h,featureFlagPayloads:g}}async evaluateFlags(e,t){let{distinctId:n,options:o}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new de({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new de({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:i,disableGeoip:s,flagKeys:a}=o||{},{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=o||{},f=this.addLocalPersonAndGroupProperties(n,i,c,l);c=f.allPersonProperties,l=f.allGroupProperties;let p=this.createFeatureFlagEvaluationContext(n,i,this.personPropertiesForLocalEvaluation(n,c),l);u==null&&(u=this.options.strictLocalEvaluation??!1);let d={},h,g,w=!1,_=!1,v=await this.featureFlagsPoller?.getAllFlagsAndPayloads(p,a),R=new Set;if(v)for(let[x,k]of Object.entries(v.response)){let m=this.featureFlagsPoller?.featureFlagsByKey[x];d[x]={key:x,enabled:k!==!1,variant:typeof k=="string"?k:void 0,payload:v.payloads[x],id:m?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:m?.has_experiment},R.add(x)}if((v?v.fallbackToFlags:!0)&&!u){let x=await super.getFeatureFlagDetailsStateless(p.distinctId,p.groups,c,l,s,a);if(x){this._minimalFlagCalledEvents=x.minimalFlagCalledEvents===!0,h=x.requestId,g=x.evaluatedAt,w=!!x.errorsWhileComputingFlags,_=Array.isArray(x.quotaLimited)&&x.quotaLimited.includes("feature_flags");for(let[k,m]of Object.entries(x.flags)){if(R.has(k))continue;let P;if(m.metadata?.payload!==void 0)try{P=JSON.parse(m.metadata.payload)}catch{P=m.metadata.payload}d[k]={key:k,enabled:m.enabled,variant:m.variant,payload:P,id:m.metadata?.id,version:m.metadata?.version,reason:m.reason?.description??m.reason?.code,locallyEvaluated:!1,hasExperiment:m.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[x,k]of Object.entries(this._flagOverrides)){if(k===void 0){delete d[x];continue}let m=d[x];d[x]={key:x,enabled:k!==!1,variant:typeof k=="string"?k:void 0,payload:m?.payload,id:m?.id,version:m?.version,reason:m?.reason,locallyEvaluated:m?.locallyEvaluated??!1,hasExperiment:m?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[x,k]of Object.entries(this._payloadOverrides)){let m=d[x];m&&(d[x]={...m,payload:k})}return new de({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:i,disableGeoip:s,flags:d,requestId:h,evaluatedAt:g,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:w,quotaLimited:_})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:n,response:o,groups:i,disableGeoip:s,properties:a}=e,u=i&&Object.keys(i).length>0?`_${JSON.stringify(Object.entries(i).sort(([l],[f])=>l<f?-1:l>f?1:0))}`:"",c=`${n}_${o}${u}`;t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(c)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[t]instanceof Set?this.distinctIdHasSentFlagCalls[t].add(c):this.distinctIdHasSentFlagCalls[t]=new Set([c]),this.capture({distinctId:t,event:"$feature_flag_called",properties:a,groups:i,disableGeoip:s}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),logWarning:e=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:n,distinctId:o,disableGeoip:i}){this._sendPreparedEvent("capture",{distinctId:o||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{}},disableGeoip:i},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:n,distinctId:o,disableGeoip:i}){await this._sendPreparedEvent("capture",{distinctId:o||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{}},disableGeoip:i},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=n=>Object.fromEntries(n.map(o=>[o,!0]));if(e===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(e.flags===!1?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):e.flags!==void 0&&(this._flagOverrides={...e.flags})),"payloads"in e&&(e.payloads===!1?this._payloadOverrides=void 0:e.payloads!==void 0&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if("flags"in t){let n=t.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in t){let n=t.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(e,t,n){return this.context?this.context.run(e,t,n):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await Promise.race([this._metrics.flush().catch(()=>{}),new Promise(o=>C(o,Math.max(0,t-Date.now())))]),this._metrics.reset());try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},n?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},o=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let i=new AbortController;o=C(()=>{i.abort()},this.options.requestTimeout),n.signal=i.signal}try{return await this.fetch(t,n)}catch(i){this._events.emit("error",i);return}finally{o&&clearTimeout(o)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let n={},o={};for(let[i,s]of Object.entries(e))if(xo(s)&&t&&i in t){let a={};for(let[u,c]of Object.entries(s))a[String(u)]=String(c);o[String(i)]=a}else n[String(i)]=String(s);return{personProperties:n,groupProperties:o}}async getFeatureFlagsForEvent(e,t,n,o){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let i=o?.personProperties||{},s=o?.groupProperties||{},a=o?.flagKeys;if(o?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[l,f]of Object.entries(t||{}))c[l]=String(f);return await this.getAllFlags(e,{groups:c,personProperties:i,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[l,f]of Object.entries(t||{}))c[l]=String(f);return await this.getAllFlags(e,{groups:c,personProperties:i,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(e,t,i,s,n)).flags}addLocalPersonAndGroupProperties(e,t,n,o){let i={...n||{}},s={};if(t)for(let a of Object.keys(t))s[a]={$group_key:t[a],...o?.[a]||{}};return{allPersonProperties:i,allGroupProperties:s}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,n,o){return{distinctId:e,groups:t||{},personProperties:n||{},groupProperties:o||{},evaluationCache:{}}}captureException(e,t,n,o,i){if(!te.isPreviouslyCapturedError(e)){let s=new Error("PostHog syntheticException");this.addPendingPromise(te.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,n).then(a=>this._capturePreparedEvent({...a,uuid:o,flags:i},!1)))}}async captureExceptionImmediate(e,t,n,o){if(!te.isPreviouslyCapturedError(e)){let i=new Error("PostHog syntheticException");return this.addPendingPromise(te.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:i},t,n).then(s=>this.captureImmediate({...s,flags:o})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:n,event:o,properties:i,groups:s,flags:a,sendFeatureFlags:u,timestamp:c,disableGeoip:l,uuid:f}=e,p=this.context?.get(),d=t.includeContextProperties??!0,h=n||p?.distinctId,g=d?{...this.props,...p?.properties||{},...i||{}}:{...i||{}};h||(h=M(),g.$process_person_profile=!1),d&&p?.sessionId&&!g.$session_id&&(g.$session_id=p.sessionId);let w=this._shouldSendMinimalFlagCalledEvent(o,g)?Me(g):g,_=this._runBeforeSend({distinctId:h,event:o,properties:w,groups:s,flags:a,sendFeatureFlags:u,timestamp:c,disableGeoip:l,uuid:f});if(!_)return Promise.reject(null);let v=await Promise.resolve().then(async()=>{if(a)return u&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(u){Mt("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let R=typeof u=="object"?u:void 0,I=await this.getFeatureFlagsForEvent(_.distinctId,s,l,R);return vu(I)}return{}}).catch(()=>({})).then(R=>{let I=_.groups||s;return{...R,..._.properties||{},...I!==void 0&&Object.keys(I).length>0?{$groups:I}:{}}});return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof v.$raw_user_agent=="string"&&ho(v.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",v.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:v,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let n=Array.isArray(t)?t:[t],o=e;for(let i of n){if(o=i(o),!o)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!o.properties||Object.keys(o.properties).length===0){let s=`Event '${o.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}return o}};var Ri=require("async_hooks"),Nt=class{constructor(){this.storage=new Ri.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,n){return this.storage.run(this.resolve(e,n),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let n=this.get()||{};return{distinctId:e.distinctId??n.distinctId,sessionId:e.sessionId??n.sessionId,properties:{...n.properties||{},...e.properties||{}}}}};var zi="posthog-node";function bu(r,{organization:e,projectId:t,prefix:n,severityAllowList:o=["error"],sendExceptionsToPostHog:i=!0}={}){return s=>{if(!(o==="*"||o.includes(s.level)))return s;s.tags||(s.tags={});let u=s.tags[Kr.POSTHOG_ID_TAG];if(u===void 0)return s;let c=r.options.host??"https://us.i.posthog.com",l=new URL(`/project/${r.apiKey}/person/${u}`,c).toString();s.tags["PostHog Person URL"]=l;let f=s.exception?.values||[],p=f.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(g=>({...g,platform:"node:javascript"}))}:void 0})),d={$exception_message:f[0]?.value||s.message,$exception_type:f[0]?.type,$exception_level:s.level,$exception_list:p,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:f[0]?.value||s.message,$sentry_exception_type:f[0]?.type,$sentry_tags:s.tags};return e&&t&&(d.$sentry_url=(n||"https://sentry.io/organizations/")+e+"/issues/?project="+t+"&query="+s.event_id),i&&r.capture({event:"$exception",distinctId:u,properties:d}),s}}var Kr=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,n,o,i){this.name=zi,this.name=zi,this.setupOnce=function(s,a){let u=a()?.getClient()?.getDsn()?.projectId;s(bu(e,{organization:t,projectId:u,prefix:n,severityAllowList:o,sendExceptionsToPostHog:i??!0}))}}};var Dt=class extends Lt{getLibraryId(){return"posthog-node"}initializeContext(){return new Nt}createErrorPropertiesBuilder(){return new z.ErrorPropertiesBuilder([new z.EventCoercer,new z.ErrorCoercer,new z.ObjectCoercer,new z.StringCoercer,new z.PrimitiveCoercer],z.createStackParser("node:javascript",z.nodeStackLineParser),[lo(),li,di()])}};var Oi="[redacted]",xu=/(^|[#&?])(access_token|refresh_token|token_hash|token)=[^\s#&"'<>]+/gi,wu=/(^|[^\w-])eyJ[\w-]+\.[\w-]+\.[\w-]+/g;function Ti(r){return r.replaceAll(xu,`$1$2=${Oi}`).replaceAll(wu,`$1${Oi}`)}var Pu=new Set(["$anon_distinct_id","distinct_id"]),Eu=["$set","$set_once"];function Gr(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Wr(r){return typeof r=="string"?Ti(r):Array.isArray(r)?$u(r):Gr(r)?Mi(r,()=>!0):r}function $u(r){let e=r.map(t=>Wr(t));return e.some((t,n)=>t!==r[n])?e:r}function Mi(r,e){let t=!1,n=[];for(let[o,i]of Object.entries(r)){let s=e(o)?Wr(i):i;s!==i&&(t=!0),n.push([o,s])}return t?Object.fromEntries(n):r}function Li(r){if(!Gr(r))return r;try{let e=!1,t={...r},{properties:n}=r;if(Gr(n)){let o=Mi(n,i=>!Pu.has(i));o!==n&&(e=!0,t.properties=o)}for(let o of Eu){let i=r[o],s=Wr(i);s!==i&&(e=!0,t[o]=s)}return e?t:r}catch{return r}}var Zt=null,qr=null;function jt(){return Zt===null||qr===null?null:{client:Zt,projectKey:qr}}function Ni(r){if(Zt!==null)return;if(me()){console.error("[HeyCatch] the server entry was bundled into a browser build - import '@heycatch/sdk' with your bundler's browser condition enabled. Server calls are no-ops here.");return}let e=so.safeParse(r);if(!e.success){let o=e.error.issues[0]?.message??"init() requires a config object with { projectKey }.";console.error(`[HeyCatch] ${o}`);return}let t=new Dt(oo,{host:no,flushAt:1,flushInterval:0,fetchRetryCount:1,fetchRetryDelay:250,requestTimeout:5e3,before_send:Li});t.on("error",o=>{console.error("[HeyCatch] server send failed:",o)}),Zt=t,qr=e.data.projectKey;let n=io();n!==null&&console.warn(n)}function Ut(r){return{heycatch_project_key:r,heycatch_sdk_version:Oe,heycatch_sdk_stage:ze}}async function Di(r,e,t){if(me())return;let n=jt();if(n===null){console.error("[HeyCatch] setIdentity() called before init() - call init({ projectKey }) once at module scope.");return}if(typeof r!="string"||r.length===0){console.error("[HeyCatch] setIdentity() requires a non-empty string user id. Pass a stable internal user id from your auth provider \u2014 not an email or session token.");return}try{await n.client.captureImmediate({distinctId:r,event:"$identify",properties:{...e?{$set:e}:{},...t?{$set_once:t}:{},...Ut(n.projectKey)},groups:{[et]:n.projectKey}})}catch(o){console.error("[HeyCatch] setIdentity() failed to reach ingest:",o)}}function Zi(r,e){console.error("[HeyCatch] setPersonProperties() has no ambient person on the server - use setIdentity(userId, properties) or trackEvent(..., { userId, set }).")}function ji(){}var[Fu]=lt,Su="X-POSTHOG-SESSION-ID";function Ui(r,e){try{if("get"in r&&typeof r.get=="function"){let n=r.get(e);return n===""?null:n}let t=e.toLowerCase();for(let[n,o]of Object.entries(r)){if(n.toLowerCase()!==t)continue;let i=o,s=Array.isArray(i)?i[0]:i;return typeof s=="string"&&s!==""?s:null}return null}catch{return null}}function Iu(r){let e=r?.headers;return e?Ui(e,Fu)??Ui(e,Su):null}async function Bi(r,e,t){if(me())return;let n=jt();if(n===null){console.error("[HeyCatch] trackEvent() called before init() - call init({ projectKey }) once at module scope.");return}if(typeof r!="string"||r.length===0||r.startsWith("$")){console.error('[HeyCatch] trackEvent() requires a non-empty event name that does not start with "$" (reserved for built-ins).');return}let o=t??{},i=o.userId;if(typeof i!="string"||i.length===0){console.error("[HeyCatch] trackEvent() on the server requires options.userId - there is no ambient person in a server process. Pass the same stable internal user id the client uses.");return}let s=Iu(o.request);try{await n.client.captureImmediate({distinctId:i,event:r,properties:{...e,...s?{$session_id:s}:{},...o.set?{$set:o.set}:{},...o.setOnce?{$set_once:o.setOnce}:{},...Ut(n.projectKey),heycatch_custom_user_event:!0},groups:{[et]:n.projectKey}})}catch(a){console.error("[HeyCatch] trackEvent() failed to reach ingest:",a)}}var Au={init:Ni,optInCapturing:Vr,optOutCapturing:Xr,resetIdentity:ji,setIdentity:Di,setIpCollection:Jr,setPersonProperties:Zi,trackEvent:Bi};0&&(module.exports={KNOWN_FRAMEWORKS,KNOWN_INSTALL_AGENTS,SDK_VERSION,STAGE,TRACING_HEADERS,UNKNOWN_INSTALL_VALUE,analytics});
|
|
3
3
|
//# sourceMappingURL=server.cjs.map
|